@solana/keys 2.0.0-experimental.eefafdf → 2.0.0-experimental.f07dced

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,12 @@ This type represents a string that validates as a Solana address or public key.
24
24
 
25
25
  Whenever you need to validate an arbitrary string as a base58-encoded address, use the `assertIsBase58EncodedAddress()` function in this package.
26
26
 
27
+ ### `Ed25519Signature`
28
+
29
+ This type represents a 64-byte Ed25519 signature of some data with a private key.
30
+
31
+ Whenever you need to verify that a particular signature is, in fact, the one that would have been produced by signing some known bytes using the private key associated with some known public key, use the `verifySignature()` function in this package.
32
+
27
33
  ## Functions
28
34
 
29
35
  ### `assertIsBase58EncodedAddress()`
@@ -33,7 +39,7 @@ Client applications primarily deal with addresses and public keys in the form of
33
39
  From time to time you might acquire a string, that you expect to validate as an address, from an untrusted network API or user input. To assert that such an arbitrary string is a base58-encoded address, use the `assertIsBase58EncodedAddress` function.
34
40
 
35
41
  ```ts
36
- import { assertIsBase58EncodedAddress } from '@solana/web3.js`;
42
+ import { assertIsBase58EncodedAddress } from '@solana/keys';
37
43
 
38
44
  // Imagine a function that fetches an account's balance when a user submits a form.
39
45
  function handleSubmit() {
@@ -50,3 +56,47 @@ function handleSubmit() {
50
56
  }
51
57
  }
52
58
  ```
59
+
60
+ ### `generateKeyPair()`
61
+
62
+ Generates an Ed25519 public/private key pair for use with other methods in this package that accept `CryptoKey` objects.
63
+
64
+ ```ts
65
+ import { generateKeyPair } from '@solana/keys';
66
+
67
+ const { privateKey, publicKey } = await generateKeyPair();
68
+ ```
69
+
70
+ ### `getBase58EncodedAddressFromPublicKey()`
71
+
72
+ Given a public `CryptoKey`, this method will return its associated `Base58EncodedAddress`.
73
+
74
+ ```ts
75
+ import { getBase58EncodedAddressFromPublicKey } from '@solana/keys';
76
+
77
+ const address = await getBase58EncodedAddressFromPublicKey(publicKey);
78
+ ```
79
+
80
+ ### `signBytes()`
81
+
82
+ Given a private `CryptoKey` and a `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a `Uint8Array`.
83
+
84
+ ```ts
85
+ import { signBytes } from '@solana/keys';
86
+
87
+ const data = new Uint8Array([1, 2, 3]);
88
+ const signature = await signBytes(privateKey, data);
89
+ ```
90
+
91
+ ### `verifySignature()`
92
+
93
+ Given a public `CryptoKey`, an `Ed25519Signature`, and a `Uint8Array` of bytes, this method will return `true` if the signature was produced by signing the bytes using the private key associated with the public key, and `false` otherwise.
94
+
95
+ ```ts
96
+ import { verifySignature } from '@solana/keys';
97
+
98
+ const data = new Uint8Array([1, 2, 3]);
99
+ if (!(await verifySignature(publicKey, signature, data))) {
100
+ throw new Error('The data were *not* signed by the private key associated with `publicKey`');
101
+ }
102
+ ```
@@ -1,12 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var bs58 = require('bs58');
3
+ var umiSerializers = require('@metaplex-foundation/umi-serializers');
4
4
 
5
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
-
7
- var bs58__default = /*#__PURE__*/_interopDefault(bs58);
8
-
9
- // src/base58.ts
5
+ // ../build-scripts/env-shim.ts
6
+ var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
10
7
  function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
11
8
  try {
12
9
  if (
@@ -16,7 +13,7 @@ function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
16
13
  ) {
17
14
  throw new Error("Expected input string to decode to a byte array of length 32.");
18
15
  }
19
- const bytes = bs58__default.default.decode(putativeBase58EncodedAddress);
16
+ const bytes = umiSerializers.base58.serialize(putativeBase58EncodedAddress);
20
17
  const numBytes = bytes.byteLength;
21
18
  if (numBytes !== 32) {
22
19
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
@@ -27,6 +24,13 @@ function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
27
24
  });
28
25
  }
29
26
  }
27
+ function getBase58EncodedAddressCodec(config) {
28
+ return umiSerializers.string({
29
+ description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
30
+ encoding: umiSerializers.base58,
31
+ size: 32
32
+ });
33
+ }
30
34
  function getBase58EncodedAddressComparator() {
31
35
  return new Intl.Collator("en", {
32
36
  caseFirst: "lower",
@@ -38,7 +42,110 @@ function getBase58EncodedAddressComparator() {
38
42
  }).compare;
39
43
  }
40
44
 
45
+ // src/guard.ts
46
+ function assertIsSecureContext() {
47
+ if (!globalThis.isSecureContext) {
48
+ throw new Error(
49
+ "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
50
+ );
51
+ }
52
+ }
53
+ var cachedEd25519Decision;
54
+ async function isEd25519CurveSupported(subtle) {
55
+ if (cachedEd25519Decision === void 0) {
56
+ cachedEd25519Decision = new Promise((resolve) => {
57
+ subtle.generateKey(
58
+ "Ed25519",
59
+ /* extractable */
60
+ false,
61
+ ["sign", "verify"]
62
+ ).catch(() => {
63
+ resolve(cachedEd25519Decision = false);
64
+ }).then(() => {
65
+ resolve(cachedEd25519Decision = true);
66
+ });
67
+ });
68
+ }
69
+ if (typeof cachedEd25519Decision === "boolean") {
70
+ return cachedEd25519Decision;
71
+ } else {
72
+ return await cachedEd25519Decision;
73
+ }
74
+ }
75
+ async function assertKeyGenerationIsAvailable() {
76
+ assertIsSecureContext();
77
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
78
+ throw new Error("No key generation implementation could be found");
79
+ }
80
+ if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
81
+ throw new Error(
82
+ "This runtime does not support the generation of Ed25519 key pairs.\n\nInstall and import `@solana/webcrypto-ed25519-polyfill` before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20"
83
+ );
84
+ }
85
+ }
86
+ async function assertKeyExporterIsAvailable() {
87
+ assertIsSecureContext();
88
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") {
89
+ throw new Error("No key export implementation could be found");
90
+ }
91
+ }
92
+ async function assertSigningCapabilityIsAvailable() {
93
+ assertIsSecureContext();
94
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
95
+ throw new Error("No signing implementation could be found");
96
+ }
97
+ }
98
+ async function assertVerificationCapabilityIsAvailable() {
99
+ assertIsSecureContext();
100
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
101
+ throw new Error("No signature verification implementation could be found");
102
+ }
103
+ }
104
+
105
+ // src/key-pair.ts
106
+ async function generateKeyPair() {
107
+ await assertKeyGenerationIsAvailable();
108
+ const keyPair = await crypto.subtle.generateKey(
109
+ /* algorithm */
110
+ "Ed25519",
111
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
112
+ /* extractable */
113
+ false,
114
+ // Prevents the bytes of the private key from being visible to JS.
115
+ /* allowed uses */
116
+ ["sign", "verify"]
117
+ );
118
+ return keyPair;
119
+ }
120
+
121
+ // src/pubkey.ts
122
+ async function getBase58EncodedAddressFromPublicKey(publicKey) {
123
+ await assertKeyExporterIsAvailable();
124
+ if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
125
+ throw new Error("The `CryptoKey` must be an `Ed25519` public key");
126
+ }
127
+ const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
128
+ const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
129
+ return base58EncodedAddress;
130
+ }
131
+
132
+ // src/signatures.ts
133
+ async function signBytes(key, data) {
134
+ await assertSigningCapabilityIsAvailable();
135
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
136
+ return new Uint8Array(signedData);
137
+ }
138
+ async function verifySignature(key, signature, data) {
139
+ await assertVerificationCapabilityIsAvailable();
140
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
141
+ }
142
+
41
143
  exports.assertIsBase58EncodedAddress = assertIsBase58EncodedAddress;
144
+ exports.generateKeyPair = generateKeyPair;
145
+ exports.getBase58EncodedAddressCodec = getBase58EncodedAddressCodec;
42
146
  exports.getBase58EncodedAddressComparator = getBase58EncodedAddressComparator;
147
+ exports.getBase58EncodedAddressFromPublicKey = getBase58EncodedAddressFromPublicKey;
148
+ exports.signBytes = signBytes;
149
+ exports.verifySignature = verifySignature;
43
150
  //# sourceMappingURL=out.js.map
44
151
  //# sourceMappingURL=index.browser.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/base58.ts"],"names":[],"mappings":";AAAA,OAAO,UAAU;AAMV,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,KAAK,OAAO,4BAA4B;AACtD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["import bs58 from 'bs58';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = bs58.decode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n"]}
1
+ {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts","../src/guard.ts","../src/key-pair.ts","../src/pubkey.ts","../src/signatures.ts"],"names":[],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B;AAC3D,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,6BACZ,QAGgC;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nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { assertKeyGenerationIsAvailable } from './guard';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { Base58EncodedAddress, getBase58EncodedAddressCodec } from './base58';\nimport { assertKeyExporterIsAvailable } from './guard';\n\nexport async function getBase58EncodedAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from './guard';\n\nexport type Ed25519Signature = Uint8Array & { readonly __ed25519Signature: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,6 +1,7 @@
1
- import bs58 from 'bs58';
1
+ import { base58, string } from '@metaplex-foundation/umi-serializers';
2
2
 
3
- // src/base58.ts
3
+ // ../build-scripts/env-shim.ts
4
+ var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
4
5
  function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
5
6
  try {
6
7
  if (
@@ -10,7 +11,7 @@ function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
10
11
  ) {
11
12
  throw new Error("Expected input string to decode to a byte array of length 32.");
12
13
  }
13
- const bytes = bs58.decode(putativeBase58EncodedAddress);
14
+ const bytes = base58.serialize(putativeBase58EncodedAddress);
14
15
  const numBytes = bytes.byteLength;
15
16
  if (numBytes !== 32) {
16
17
  throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);
@@ -21,6 +22,13 @@ function assertIsBase58EncodedAddress(putativeBase58EncodedAddress) {
21
22
  });
22
23
  }
23
24
  }
25
+ function getBase58EncodedAddressCodec(config) {
26
+ return string({
27
+ description: config?.description ?? (__DEV__ ? "A 32-byte account address" : ""),
28
+ encoding: base58,
29
+ size: 32
30
+ });
31
+ }
24
32
  function getBase58EncodedAddressComparator() {
25
33
  return new Intl.Collator("en", {
26
34
  caseFirst: "lower",
@@ -32,6 +40,104 @@ function getBase58EncodedAddressComparator() {
32
40
  }).compare;
33
41
  }
34
42
 
35
- export { assertIsBase58EncodedAddress, getBase58EncodedAddressComparator };
43
+ // src/guard.ts
44
+ function assertIsSecureContext() {
45
+ if (!globalThis.isSecureContext) {
46
+ throw new Error(
47
+ "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
48
+ );
49
+ }
50
+ }
51
+ var cachedEd25519Decision;
52
+ async function isEd25519CurveSupported(subtle) {
53
+ if (cachedEd25519Decision === void 0) {
54
+ cachedEd25519Decision = new Promise((resolve) => {
55
+ subtle.generateKey(
56
+ "Ed25519",
57
+ /* extractable */
58
+ false,
59
+ ["sign", "verify"]
60
+ ).catch(() => {
61
+ resolve(cachedEd25519Decision = false);
62
+ }).then(() => {
63
+ resolve(cachedEd25519Decision = true);
64
+ });
65
+ });
66
+ }
67
+ if (typeof cachedEd25519Decision === "boolean") {
68
+ return cachedEd25519Decision;
69
+ } else {
70
+ return await cachedEd25519Decision;
71
+ }
72
+ }
73
+ async function assertKeyGenerationIsAvailable() {
74
+ assertIsSecureContext();
75
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
76
+ throw new Error("No key generation implementation could be found");
77
+ }
78
+ if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
79
+ throw new Error(
80
+ "This runtime does not support the generation of Ed25519 key pairs.\n\nInstall and import `@solana/webcrypto-ed25519-polyfill` before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20"
81
+ );
82
+ }
83
+ }
84
+ async function assertKeyExporterIsAvailable() {
85
+ assertIsSecureContext();
86
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") {
87
+ throw new Error("No key export implementation could be found");
88
+ }
89
+ }
90
+ async function assertSigningCapabilityIsAvailable() {
91
+ assertIsSecureContext();
92
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
93
+ throw new Error("No signing implementation could be found");
94
+ }
95
+ }
96
+ async function assertVerificationCapabilityIsAvailable() {
97
+ assertIsSecureContext();
98
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
99
+ throw new Error("No signature verification implementation could be found");
100
+ }
101
+ }
102
+
103
+ // src/key-pair.ts
104
+ async function generateKeyPair() {
105
+ await assertKeyGenerationIsAvailable();
106
+ const keyPair = await crypto.subtle.generateKey(
107
+ /* algorithm */
108
+ "Ed25519",
109
+ // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
110
+ /* extractable */
111
+ false,
112
+ // Prevents the bytes of the private key from being visible to JS.
113
+ /* allowed uses */
114
+ ["sign", "verify"]
115
+ );
116
+ return keyPair;
117
+ }
118
+
119
+ // src/pubkey.ts
120
+ async function getBase58EncodedAddressFromPublicKey(publicKey) {
121
+ await assertKeyExporterIsAvailable();
122
+ if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
123
+ throw new Error("The `CryptoKey` must be an `Ed25519` public key");
124
+ }
125
+ const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
126
+ const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));
127
+ return base58EncodedAddress;
128
+ }
129
+
130
+ // src/signatures.ts
131
+ async function signBytes(key, data) {
132
+ await assertSigningCapabilityIsAvailable();
133
+ const signedData = await crypto.subtle.sign("Ed25519", key, data);
134
+ return new Uint8Array(signedData);
135
+ }
136
+ async function verifySignature(key, signature, data) {
137
+ await assertVerificationCapabilityIsAvailable();
138
+ return await crypto.subtle.verify("Ed25519", key, signature, data);
139
+ }
140
+
141
+ export { assertIsBase58EncodedAddress, generateKeyPair, getBase58EncodedAddressCodec, getBase58EncodedAddressComparator, getBase58EncodedAddressFromPublicKey, signBytes, verifySignature };
36
142
  //# sourceMappingURL=out.js.map
37
143
  //# sourceMappingURL=index.browser.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/base58.ts"],"names":[],"mappings":";AAAA,OAAO,UAAU;AAMV,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,KAAK,OAAO,4BAA4B;AACtD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,UAAU;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAP;AACE,UAAM,IAAI,MAAM,KAAK,mEAAmE;AAAA,MACpF,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,oCAAsE;AAClF,SAAO,IAAI,KAAK,SAAS,MAAM;AAAA,IAC3B,WAAW;AAAA,IACX,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,aAAa;AAAA,IACb,OAAO;AAAA,EACX,CAAC,EAAE;AACP","sourcesContent":["import bs58 from 'bs58';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = bs58.decode(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n"]}
1
+ {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/base58.ts","../src/guard.ts","../src/key-pair.ts","../src/pubkey.ts","../src/signatures.ts"],"names":[],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACDvG,SAAS,QAAoB,cAAc;AAMpC,SAAS,6BACZ,8BACiG;AACjG,MAAI;AAEA;AAAA;AAAA,MAEI,6BAA6B,SAAS;AAAA,MAEtC,6BAA6B,SAAS;AAAA,MACxC;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,OAAO,UAAU,4BAA4B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,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\n","import { base58, Serializer, string } from '@metaplex-foundation/umi-serializers';\n\nexport type Base58EncodedAddress<TAddress extends string = string> = TAddress & {\n readonly __base58EncodedAddress: unique symbol;\n};\n\nexport function assertIsBase58EncodedAddress(\n putativeBase58EncodedAddress: string\n): asserts putativeBase58EncodedAddress is Base58EncodedAddress<typeof putativeBase58EncodedAddress> {\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest address (32 bytes of zeroes)\n putativeBase58EncodedAddress.length < 32 ||\n // Highest address (32 bytes of 255)\n putativeBase58EncodedAddress.length > 44\n ) {\n throw new Error('Expected input string to decode to a byte array of length 32.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58.serialize(putativeBase58EncodedAddress);\n const numBytes = bytes.byteLength;\n if (numBytes !== 32) {\n throw new Error(`Expected input string to decode to a byte array of length 32. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeBase58EncodedAddress}\\` is not a base-58 encoded address`, {\n cause: e,\n });\n }\n}\n\nexport function getBase58EncodedAddressCodec(\n config?: Readonly<{\n description: string;\n }>\n): Serializer<Base58EncodedAddress> {\n return string({\n description: config?.description ?? (__DEV__ ? 'A 32-byte account address' : ''),\n encoding: base58,\n size: 32,\n }) as unknown as Serializer<Base58EncodedAddress>;\n}\n\nexport function getBase58EncodedAddressComparator(): (x: string, y: string) => number {\n return new Intl.Collator('en', {\n caseFirst: 'lower',\n ignorePunctuation: false,\n localeMatcher: 'best fit',\n numeric: false,\n sensitivity: 'variant',\n usage: 'sort',\n }).compare;\n}\n","function assertIsSecureContext() {\n if (__BROWSER__ && !globalThis.isSecureContext) {\n // TODO: Coded error.\n throw new Error(\n 'Cryptographic operations are only allowed in secure browser contexts. Read more ' +\n 'here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts'\n );\n }\n}\n\nlet cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined;\nasync function isEd25519CurveSupported(subtle: SubtleCrypto): Promise<boolean> {\n if (cachedEd25519Decision === undefined) {\n cachedEd25519Decision = new Promise(resolve => {\n subtle\n .generateKey('Ed25519', /* extractable */ false, ['sign', 'verify'])\n .catch(() => {\n resolve((cachedEd25519Decision = false));\n })\n .then(() => {\n resolve((cachedEd25519Decision = true));\n });\n });\n }\n if (typeof cachedEd25519Decision === 'boolean') {\n return cachedEd25519Decision;\n } else {\n return await cachedEd25519Decision;\n }\n}\n\nexport async function assertKeyGenerationIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.generateKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key generation implementation could be found');\n }\n if (!(await isEd25519CurveSupported(globalThis.crypto.subtle))) {\n // TODO: Coded error.\n throw new Error(\n 'This runtime does not support the generation of Ed25519 key pairs.\\n\\nInstall and ' +\n 'import `@solana/webcrypto-ed25519-polyfill` before generating keys in ' +\n 'environments that do not support Ed25519.\\n\\nFor a list of runtimes that ' +\n 'currently support Ed25519 operations, visit ' +\n 'https://github.com/WICG/webcrypto-secure-curves/issues/20'\n );\n }\n}\n\nexport async function assertKeyExporterIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.exportKey !== 'function') {\n // TODO: Coded error.\n throw new Error('No key export implementation could be found');\n }\n}\n\nexport async function assertSigningCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.sign !== 'function') {\n // TODO: Coded error.\n throw new Error('No signing implementation could be found');\n }\n}\n\nexport async function assertVerificationCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.verify !== 'function') {\n // TODO: Coded error.\n throw new Error('No signature verification implementation could be found');\n }\n}\n","import { assertKeyGenerationIsAvailable } from './guard';\n\nexport async function generateKeyPair(): Promise<CryptoKeyPair> {\n await assertKeyGenerationIsAvailable();\n const keyPair = await crypto.subtle.generateKey(\n /* algorithm */ 'Ed25519', // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20\n /* extractable */ false, // Prevents the bytes of the private key from being visible to JS.\n /* allowed uses */ ['sign', 'verify']\n );\n return keyPair as CryptoKeyPair;\n}\n","import { Base58EncodedAddress, getBase58EncodedAddressCodec } from './base58';\nimport { assertKeyExporterIsAvailable } from './guard';\n\nexport async function getBase58EncodedAddressFromPublicKey(publicKey: CryptoKey): Promise<Base58EncodedAddress> {\n await assertKeyExporterIsAvailable();\n if (publicKey.type !== 'public' || publicKey.algorithm.name !== 'Ed25519') {\n // TODO: Coded error.\n throw new Error('The `CryptoKey` must be an `Ed25519` public key');\n }\n const publicKeyBytes = await crypto.subtle.exportKey('raw', publicKey);\n const [base58EncodedAddress] = getBase58EncodedAddressCodec().deserialize(new Uint8Array(publicKeyBytes));\n return base58EncodedAddress;\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from './guard';\n\nexport type Ed25519Signature = Uint8Array & { readonly __ed25519Signature: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}