@solana/keys 2.0.0-experimental.a48ebd2 → 2.0.0-experimental.a64df70

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
@@ -65,6 +65,22 @@ import { generateKeyPair } from '@solana/keys';
65
65
  const { privateKey, publicKey } = await generateKeyPair();
66
66
  ```
67
67
 
68
+ ### `createKeyPairFromBytes()`
69
+
70
+ Given a 64-bytes `Uint8Array` secret key, creates an Ed25519 public/private key pair for use with other methods in this package that accept `CryptoKey` objects.
71
+
72
+ ```ts
73
+ import fs from 'fs';
74
+ import { createKeyPairFromBytes } from '@solana/keys';
75
+
76
+ // Get bytes from local keypair file.
77
+ const keypairFile = fs.readFileSync('~/.config/solana/id.json');
78
+ const keypairBytes = new Uint8Array(JSON.parse(keypairFile.toString()));
79
+
80
+ // Create a CryptoKeyPair from the bytes.
81
+ const { privateKey, publicKey } = await createKeyPairFromBytes(keypairBytes);
82
+ ```
83
+
68
84
  ### `isSignature()`
69
85
 
70
86
  This is a type guard that accepts a string as input. It will both return `true` if the string conforms to the `Signature` type and will refine the type for use in your program.
@@ -1,8 +1,66 @@
1
1
  'use strict';
2
2
 
3
3
  var assertions = require('@solana/assertions');
4
+ var errors = require('@solana/errors');
4
5
  var codecsStrings = require('@solana/codecs-strings');
5
6
 
7
+ // src/key-pair.ts
8
+
9
+ // src/private-key.ts
10
+ function addPkcs8Header(bytes) {
11
+ return new Uint8Array([
12
+ /**
13
+ * PKCS#8 header
14
+ */
15
+ 48,
16
+ // ASN.1 sequence tag
17
+ 46,
18
+ // Length of sequence (46 more bytes)
19
+ 2,
20
+ // ASN.1 integer tag
21
+ 1,
22
+ // Length of integer
23
+ 0,
24
+ // Version number
25
+ 48,
26
+ // ASN.1 sequence tag
27
+ 5,
28
+ // Length of sequence
29
+ 6,
30
+ // ASN.1 object identifier tag
31
+ 3,
32
+ // Length of object identifier
33
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
34
+ 43,
35
+ // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
36
+ 101,
37
+ // thawte(101)
38
+ // Ed25519 identifier
39
+ 112,
40
+ // id-Ed25519(112)
41
+ /**
42
+ * Private key payload
43
+ */
44
+ 4,
45
+ // ASN.1 octet string tag
46
+ 34,
47
+ // String length (34 more bytes)
48
+ // Private key bytes as octet string
49
+ 4,
50
+ // ASN.1 octet string tag
51
+ 32,
52
+ // String length (32 bytes)
53
+ ...bytes
54
+ ]);
55
+ }
56
+ async function createPrivateKeyFromBytes(bytes, extractable) {
57
+ if (bytes.byteLength !== 32) {
58
+ throw new Error("Private key bytes must be of length 32");
59
+ }
60
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
61
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable ?? false, ["sign"]);
62
+ }
63
+
6
64
  // src/key-pair.ts
7
65
  async function generateKeyPair() {
8
66
  await assertions.assertKeyGenerationIsAvailable();
@@ -18,6 +76,23 @@ async function generateKeyPair() {
18
76
  );
19
77
  return keyPair;
20
78
  }
79
+ async function createKeyPairFromBytes(bytes, extractable) {
80
+ if (bytes.byteLength !== 64) {
81
+ throw new errors.SolanaError(errors.SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });
82
+ }
83
+ const [publicKey, privateKey] = await Promise.all([
84
+ crypto.subtle.importKey(
85
+ "raw",
86
+ bytes.slice(32),
87
+ "Ed25519",
88
+ /* extractable */
89
+ true,
90
+ ["verify"]
91
+ ),
92
+ createPrivateKeyFromBytes(bytes.slice(0, 32), extractable)
93
+ ]);
94
+ return { privateKey, publicKey };
95
+ }
21
96
  var base58Encoder;
22
97
  function assertIsSignature(putativeSignature) {
23
98
  if (!base58Encoder)
@@ -73,6 +148,8 @@ async function verifySignature(key, signature2, data) {
73
148
  }
74
149
 
75
150
  exports.assertIsSignature = assertIsSignature;
151
+ exports.createKeyPairFromBytes = createKeyPairFromBytes;
152
+ exports.createPrivateKeyFromBytes = createPrivateKeyFromBytes;
76
153
  exports.generateKeyPair = generateKeyPair;
77
154
  exports.isSignature = isSignature;
78
155
  exports.signBytes = signBytes;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAE5F,SAAS,wBAAwB;AAKjC,IAAI;AAEG,SAAS,kBAAkB,mBAAmE;AACjG,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAErD,MAAI;AAEA;AAAA;AAAA,MAEI,kBAAkB,SAAS;AAAA,MAE3B,kBAAkB,SAAS;AAAA,MAC7B;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,QAAQ,EAAE;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAG;AACR,UAAM,IAAI,MAAM,KAAK,iBAAiB,yBAAyB;AAAA,MAC3D,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,YAAY,mBAA2D;AACnF,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAGrD;AAAA;AAAA,IAEI,kBAAkB,SAAS;AAAA,IAE3B,kBAAkB,SAAS;AAAA,IAC7B;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBA,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\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 { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/private-key.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAC/C,SAAS,qCAAqC,mBAAmB;;;ACDjE,SAAS,eAAe,OAA+B;AAEnD,SAAO,IAAI,WAAW;AAAA;AAAA;AAAA;AAAA,IAIlB;AAAA;AAAA,IACA;AAAA;AAAA,IAEI;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IAEJ;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEQ;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhB;AAAA;AAA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AAAA,IACnF;AAEA,UAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,QAAQ,EAAE;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAG;AACR,UAAM,IAAI,MAAM,KAAK,iBAAiB,yBAAyB;AAAA,MAC3D,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,YAAY,mBAA2D;AACnF,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAGrD;AAAA;AAAA,IAEI,kBAAkB,SAAS;AAAA,IAE3B,kBAAkB,SAAS;AAAA,IAC7B;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBA,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__INVALID_KEYPAIR_BYTES, SolanaError } from '@solana/errors';\n\nimport { createPrivateKeyFromBytes } from './private-key';\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\nexport async function createKeyPairFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKeyPair> {\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), 'Ed25519', /* extractable */ true, ['verify']),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n","function addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\nexport async function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey> {\n if (bytes.byteLength !== 32) {\n // TODO: Coded error.\n throw new Error('Private key bytes must be of length 32');\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, 'Ed25519', extractable ?? false, ['sign']);\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,6 +1,64 @@
1
1
  import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
2
+ import { SolanaError, SOLANA_ERROR__INVALID_KEYPAIR_BYTES } from '@solana/errors';
2
3
  import { getBase58Encoder } from '@solana/codecs-strings';
3
4
 
5
+ // src/key-pair.ts
6
+
7
+ // src/private-key.ts
8
+ function addPkcs8Header(bytes) {
9
+ return new Uint8Array([
10
+ /**
11
+ * PKCS#8 header
12
+ */
13
+ 48,
14
+ // ASN.1 sequence tag
15
+ 46,
16
+ // Length of sequence (46 more bytes)
17
+ 2,
18
+ // ASN.1 integer tag
19
+ 1,
20
+ // Length of integer
21
+ 0,
22
+ // Version number
23
+ 48,
24
+ // ASN.1 sequence tag
25
+ 5,
26
+ // Length of sequence
27
+ 6,
28
+ // ASN.1 object identifier tag
29
+ 3,
30
+ // Length of object identifier
31
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
32
+ 43,
33
+ // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
34
+ 101,
35
+ // thawte(101)
36
+ // Ed25519 identifier
37
+ 112,
38
+ // id-Ed25519(112)
39
+ /**
40
+ * Private key payload
41
+ */
42
+ 4,
43
+ // ASN.1 octet string tag
44
+ 34,
45
+ // String length (34 more bytes)
46
+ // Private key bytes as octet string
47
+ 4,
48
+ // ASN.1 octet string tag
49
+ 32,
50
+ // String length (32 bytes)
51
+ ...bytes
52
+ ]);
53
+ }
54
+ async function createPrivateKeyFromBytes(bytes, extractable) {
55
+ if (bytes.byteLength !== 32) {
56
+ throw new Error("Private key bytes must be of length 32");
57
+ }
58
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
59
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable ?? false, ["sign"]);
60
+ }
61
+
4
62
  // src/key-pair.ts
5
63
  async function generateKeyPair() {
6
64
  await assertKeyGenerationIsAvailable();
@@ -16,6 +74,23 @@ async function generateKeyPair() {
16
74
  );
17
75
  return keyPair;
18
76
  }
77
+ async function createKeyPairFromBytes(bytes, extractable) {
78
+ if (bytes.byteLength !== 64) {
79
+ throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });
80
+ }
81
+ const [publicKey, privateKey] = await Promise.all([
82
+ crypto.subtle.importKey(
83
+ "raw",
84
+ bytes.slice(32),
85
+ "Ed25519",
86
+ /* extractable */
87
+ true,
88
+ ["verify"]
89
+ ),
90
+ createPrivateKeyFromBytes(bytes.slice(0, 32), extractable)
91
+ ]);
92
+ return { privateKey, publicKey };
93
+ }
19
94
  var base58Encoder;
20
95
  function assertIsSignature(putativeSignature) {
21
96
  if (!base58Encoder)
@@ -70,6 +145,6 @@ async function verifySignature(key, signature2, data) {
70
145
  return await crypto.subtle.verify("Ed25519", key, signature2, data);
71
146
  }
72
147
 
73
- export { assertIsSignature, generateKeyPair, isSignature, signBytes, signature, verifySignature };
148
+ export { assertIsSignature, createKeyPairFromBytes, createPrivateKeyFromBytes, generateKeyPair, isSignature, signBytes, signature, verifySignature };
74
149
  //# sourceMappingURL=out.js.map
75
150
  //# sourceMappingURL=index.browser.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAE5F,SAAS,wBAAwB;AAKjC,IAAI;AAEG,SAAS,kBAAkB,mBAAmE;AACjG,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAErD,MAAI;AAEA;AAAA;AAAA,MAEI,kBAAkB,SAAS;AAAA,MAE3B,kBAAkB,SAAS;AAAA,MAC7B;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,QAAQ,EAAE;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAG;AACR,UAAM,IAAI,MAAM,KAAK,iBAAiB,yBAAyB;AAAA,MAC3D,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,YAAY,mBAA2D;AACnF,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAGrD;AAAA;AAAA,IAEI,kBAAkB,SAAS;AAAA,IAE3B,kBAAkB,SAAS;AAAA,IAC7B;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBA,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\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 { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/private-key.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAC/C,SAAS,qCAAqC,mBAAmB;;;ACDjE,SAAS,eAAe,OAA+B;AAEnD,SAAO,IAAI,WAAW;AAAA;AAAA;AAAA;AAAA,IAIlB;AAAA;AAAA,IACA;AAAA;AAAA,IAEI;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IAEJ;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEQ;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhB;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAGI;AAAA;AAAA,IACA;AAAA;AAAA,IAEJ,GAAG;AAAA,EACP,CAAC;AACL;AAEA,eAAsB,0BAA0B,OAAmB,aAA2C;AAC1G,MAAI,MAAM,eAAe,IAAI;AAEzB,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC5D;AACA,QAAM,uBAAuB,eAAe,KAAK;AACjD,SAAO,MAAM,OAAO,OAAO,UAAU,SAAS,sBAAsB,WAAW,eAAe,OAAO,CAAC,MAAM,CAAC;AACjH;;;ADvCA,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC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AM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBA,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__INVALID_KEYPAIR_BYTES, SolanaError } from '@solana/errors';\n\nimport { createPrivateKeyFromBytes } from './private-key';\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\nexport async function createKeyPairFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKeyPair> {\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), 'Ed25519', /* extractable */ true, ['verify']),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n","function addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\nexport async function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey> {\n if (bytes.byteLength !== 32) {\n // TODO: Coded error.\n throw new Error('Private key bytes must be of length 32');\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, 'Ed25519', extractable ?? false, ['sign']);\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,6 +1,64 @@
1
1
  import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
2
+ import { SolanaError, SOLANA_ERROR__INVALID_KEYPAIR_BYTES } from '@solana/errors';
2
3
  import { getBase58Encoder } from '@solana/codecs-strings';
3
4
 
5
+ // src/key-pair.ts
6
+
7
+ // src/private-key.ts
8
+ function addPkcs8Header(bytes) {
9
+ return new Uint8Array([
10
+ /**
11
+ * PKCS#8 header
12
+ */
13
+ 48,
14
+ // ASN.1 sequence tag
15
+ 46,
16
+ // Length of sequence (46 more bytes)
17
+ 2,
18
+ // ASN.1 integer tag
19
+ 1,
20
+ // Length of integer
21
+ 0,
22
+ // Version number
23
+ 48,
24
+ // ASN.1 sequence tag
25
+ 5,
26
+ // Length of sequence
27
+ 6,
28
+ // ASN.1 object identifier tag
29
+ 3,
30
+ // Length of object identifier
31
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
32
+ 43,
33
+ // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
34
+ 101,
35
+ // thawte(101)
36
+ // Ed25519 identifier
37
+ 112,
38
+ // id-Ed25519(112)
39
+ /**
40
+ * Private key payload
41
+ */
42
+ 4,
43
+ // ASN.1 octet string tag
44
+ 34,
45
+ // String length (34 more bytes)
46
+ // Private key bytes as octet string
47
+ 4,
48
+ // ASN.1 octet string tag
49
+ 32,
50
+ // String length (32 bytes)
51
+ ...bytes
52
+ ]);
53
+ }
54
+ async function createPrivateKeyFromBytes(bytes, extractable) {
55
+ if (bytes.byteLength !== 32) {
56
+ throw new Error("Private key bytes must be of length 32");
57
+ }
58
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
59
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable ?? false, ["sign"]);
60
+ }
61
+
4
62
  // src/key-pair.ts
5
63
  async function generateKeyPair() {
6
64
  await assertKeyGenerationIsAvailable();
@@ -16,6 +74,23 @@ async function generateKeyPair() {
16
74
  );
17
75
  return keyPair;
18
76
  }
77
+ async function createKeyPairFromBytes(bytes, extractable) {
78
+ if (bytes.byteLength !== 64) {
79
+ throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });
80
+ }
81
+ const [publicKey, privateKey] = await Promise.all([
82
+ crypto.subtle.importKey(
83
+ "raw",
84
+ bytes.slice(32),
85
+ "Ed25519",
86
+ /* extractable */
87
+ true,
88
+ ["verify"]
89
+ ),
90
+ createPrivateKeyFromBytes(bytes.slice(0, 32), extractable)
91
+ ]);
92
+ return { privateKey, publicKey };
93
+ }
19
94
  var base58Encoder;
20
95
  function assertIsSignature(putativeSignature) {
21
96
  if (!base58Encoder)
@@ -70,6 +145,6 @@ async function verifySignature(key, signature2, data) {
70
145
  return await crypto.subtle.verify("Ed25519", key, signature2, data);
71
146
  }
72
147
 
73
- export { assertIsSignature, generateKeyPair, isSignature, signBytes, signature, verifySignature };
148
+ export { assertIsSignature, createKeyPairFromBytes, createPrivateKeyFromBytes, generateKeyPair, isSignature, signBytes, signature, verifySignature };
74
149
  //# sourceMappingURL=out.js.map
75
150
  //# sourceMappingURL=index.native.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAE5F,SAAS,wBAAwB;AAKjC,IAAI;AAEG,SAAS,kBAAkB,mBAAmE;AACjG,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAErD,MAAI;AAEA;AAAA;AAAA,MAEI,kBAAkB,SAAS;AAAA,MAE3B,kBAAkB,SAAS;AAAA,MAC7B;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,QAAQ,EAAE;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAG;AACR,UAAM,IAAI,MAAM,KAAK,iBAAiB,yBAAyB;AAAA,MAC3D,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,YAAY,mBAA2D;AACnF,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAGrD;AAAA;AAAA,IAEI,kBAAkB,SAAS;AAAA,IAE3B,kBAAkB,SAAS;AAAA,IAC7B;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBA,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\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 { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/private-key.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAC/C,SAAS,qCAAqC,mBAAmB;;;ACDjE,SAAS,eAAe,OAA+B;AAEnD,SAAO,IAAI,WAAW;AAAA;AAAA;AAAA;AAAA,IAIlB;AAAA;AAAA,IACA;AAAA;AAAA,IAEI;AAAA;AA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solana/errors';\n\nimport { createPrivateKeyFromBytes } from './private-key';\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\nexport async function createKeyPairFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKeyPair> {\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), 'Ed25519', /* extractable */ true, ['verify']),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n","function addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\nexport async function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey> {\n if (bytes.byteLength !== 32) {\n // TODO: Coded error.\n throw new Error('Private key bytes must be of length 32');\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, 'Ed25519', extractable ?? false, ['sign']);\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,8 +1,66 @@
1
1
  'use strict';
2
2
 
3
3
  var assertions = require('@solana/assertions');
4
+ var errors = require('@solana/errors');
4
5
  var codecsStrings = require('@solana/codecs-strings');
5
6
 
7
+ // src/key-pair.ts
8
+
9
+ // src/private-key.ts
10
+ function addPkcs8Header(bytes) {
11
+ return new Uint8Array([
12
+ /**
13
+ * PKCS#8 header
14
+ */
15
+ 48,
16
+ // ASN.1 sequence tag
17
+ 46,
18
+ // Length of sequence (46 more bytes)
19
+ 2,
20
+ // ASN.1 integer tag
21
+ 1,
22
+ // Length of integer
23
+ 0,
24
+ // Version number
25
+ 48,
26
+ // ASN.1 sequence tag
27
+ 5,
28
+ // Length of sequence
29
+ 6,
30
+ // ASN.1 object identifier tag
31
+ 3,
32
+ // Length of object identifier
33
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
34
+ 43,
35
+ // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
36
+ 101,
37
+ // thawte(101)
38
+ // Ed25519 identifier
39
+ 112,
40
+ // id-Ed25519(112)
41
+ /**
42
+ * Private key payload
43
+ */
44
+ 4,
45
+ // ASN.1 octet string tag
46
+ 34,
47
+ // String length (34 more bytes)
48
+ // Private key bytes as octet string
49
+ 4,
50
+ // ASN.1 octet string tag
51
+ 32,
52
+ // String length (32 bytes)
53
+ ...bytes
54
+ ]);
55
+ }
56
+ async function createPrivateKeyFromBytes(bytes, extractable) {
57
+ if (bytes.byteLength !== 32) {
58
+ throw new Error("Private key bytes must be of length 32");
59
+ }
60
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
61
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable ?? false, ["sign"]);
62
+ }
63
+
6
64
  // src/key-pair.ts
7
65
  async function generateKeyPair() {
8
66
  await assertions.assertKeyGenerationIsAvailable();
@@ -18,6 +76,23 @@ async function generateKeyPair() {
18
76
  );
19
77
  return keyPair;
20
78
  }
79
+ async function createKeyPairFromBytes(bytes, extractable) {
80
+ if (bytes.byteLength !== 64) {
81
+ throw new errors.SolanaError(errors.SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });
82
+ }
83
+ const [publicKey, privateKey] = await Promise.all([
84
+ crypto.subtle.importKey(
85
+ "raw",
86
+ bytes.slice(32),
87
+ "Ed25519",
88
+ /* extractable */
89
+ true,
90
+ ["verify"]
91
+ ),
92
+ createPrivateKeyFromBytes(bytes.slice(0, 32), extractable)
93
+ ]);
94
+ return { privateKey, publicKey };
95
+ }
21
96
  var base58Encoder;
22
97
  function assertIsSignature(putativeSignature) {
23
98
  if (!base58Encoder)
@@ -73,6 +148,8 @@ async function verifySignature(key, signature2, data) {
73
148
  }
74
149
 
75
150
  exports.assertIsSignature = assertIsSignature;
151
+ exports.createKeyPairFromBytes = createKeyPairFromBytes;
152
+ exports.createPrivateKeyFromBytes = createPrivateKeyFromBytes;
76
153
  exports.generateKeyPair = generateKeyPair;
77
154
  exports.isSignature = isSignature;
78
155
  exports.signBytes = signBytes;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,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IsAvailable } from '@solana/assertions';\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 { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/private-key.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAC/C,SAAS,qCAAqC,mBAAmB;;;ACDjE,SAAS,eAAe,OAA+B;AAEnD,SAAO,IAAI,WAAW;AAAA;AAAA;AAAA;AAAA,IAIlB;AAAA;AAAA,IACA;AAAA;AAAA,IAEI;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IAEJ;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEQ;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhB;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAGI;AAAA;AAAA,IACA;AAAA;AAAA,IAEJ,GAAG;AAAA,EACP,CAAC;AACL;AAEA,eAAsB,0BAA0B,OAAmB,aAA2C;AAC1G,MAAI,MAAM,eAAe,IAAI;AAEzB,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC5D;AACA,QAAM,uBAAuB,eAAe,KAAK;AACjD,SAAO,MAAM,OAAO,OAAO,UAAU,SAAS,sBAAsB,WAAW,eAAe,OAAO,CAAC,MAAM,CAAC;AACjH;;;ADvCA,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,O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AAS;AAAA,IAC7B;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBA,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__INVALID_KEYPAIR_BYTES, SolanaError } from '@solana/errors';\n\nimport { createPrivateKeyFromBytes } from './private-key';\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\nexport async function createKeyPairFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKeyPair> {\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), 'Ed25519', /* extractable */ true, ['verify']),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n","function addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\nexport async function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey> {\n if (bytes.byteLength !== 32) {\n // TODO: Coded error.\n throw new Error('Private key bytes must be of length 32');\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, 'Ed25519', extractable ?? false, ['sign']);\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,6 +1,64 @@
1
1
  import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
2
+ import { SolanaError, SOLANA_ERROR__INVALID_KEYPAIR_BYTES } from '@solana/errors';
2
3
  import { getBase58Encoder } from '@solana/codecs-strings';
3
4
 
5
+ // src/key-pair.ts
6
+
7
+ // src/private-key.ts
8
+ function addPkcs8Header(bytes) {
9
+ return new Uint8Array([
10
+ /**
11
+ * PKCS#8 header
12
+ */
13
+ 48,
14
+ // ASN.1 sequence tag
15
+ 46,
16
+ // Length of sequence (46 more bytes)
17
+ 2,
18
+ // ASN.1 integer tag
19
+ 1,
20
+ // Length of integer
21
+ 0,
22
+ // Version number
23
+ 48,
24
+ // ASN.1 sequence tag
25
+ 5,
26
+ // Length of sequence
27
+ 6,
28
+ // ASN.1 object identifier tag
29
+ 3,
30
+ // Length of object identifier
31
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
32
+ 43,
33
+ // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
34
+ 101,
35
+ // thawte(101)
36
+ // Ed25519 identifier
37
+ 112,
38
+ // id-Ed25519(112)
39
+ /**
40
+ * Private key payload
41
+ */
42
+ 4,
43
+ // ASN.1 octet string tag
44
+ 34,
45
+ // String length (34 more bytes)
46
+ // Private key bytes as octet string
47
+ 4,
48
+ // ASN.1 octet string tag
49
+ 32,
50
+ // String length (32 bytes)
51
+ ...bytes
52
+ ]);
53
+ }
54
+ async function createPrivateKeyFromBytes(bytes, extractable) {
55
+ if (bytes.byteLength !== 32) {
56
+ throw new Error("Private key bytes must be of length 32");
57
+ }
58
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
59
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable ?? false, ["sign"]);
60
+ }
61
+
4
62
  // src/key-pair.ts
5
63
  async function generateKeyPair() {
6
64
  await assertKeyGenerationIsAvailable();
@@ -16,6 +74,23 @@ async function generateKeyPair() {
16
74
  );
17
75
  return keyPair;
18
76
  }
77
+ async function createKeyPairFromBytes(bytes, extractable) {
78
+ if (bytes.byteLength !== 64) {
79
+ throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });
80
+ }
81
+ const [publicKey, privateKey] = await Promise.all([
82
+ crypto.subtle.importKey(
83
+ "raw",
84
+ bytes.slice(32),
85
+ "Ed25519",
86
+ /* extractable */
87
+ true,
88
+ ["verify"]
89
+ ),
90
+ createPrivateKeyFromBytes(bytes.slice(0, 32), extractable)
91
+ ]);
92
+ return { privateKey, publicKey };
93
+ }
19
94
  var base58Encoder;
20
95
  function assertIsSignature(putativeSignature) {
21
96
  if (!base58Encoder)
@@ -70,6 +145,6 @@ async function verifySignature(key, signature2, data) {
70
145
  return await crypto.subtle.verify("Ed25519", key, signature2, data);
71
146
  }
72
147
 
73
- export { assertIsSignature, generateKeyPair, isSignature, signBytes, signature, verifySignature };
148
+ export { assertIsSignature, createKeyPairFromBytes, createPrivateKeyFromBytes, generateKeyPair, isSignature, signBytes, signature, verifySignature };
74
149
  //# sourceMappingURL=out.js.map
75
150
  //# sourceMappingURL=index.node.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC,QAAM,UAAU,MAAM,OAAO,OAAO;AAAA;AAAA,IAChB;AAAA;AAAA;AAAA,IACE;AAAA;AAAA;AAAA,IACC,CAAC,QAAQ,QAAQ;AAAA,EACxC;AACA,SAAO;AACX;;;ACVA,SAAS,oCAAoC,+CAA+C;AAE5F,SAAS,wBAAwB;AAKjC,IAAI;AAEG,SAAS,kBAAkB,mBAAmE;AACjG,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAErD,MAAI;AAEA;AAAA;AAAA,MAEI,kBAAkB,SAAS;AAAA,MAE3B,kBAAkB,SAAS;AAAA,MAC7B;AACE,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACnF;AAEA,UAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,UAAM,WAAW,MAAM;AACvB,QAAI,aAAa,IAAI;AACjB,YAAM,IAAI,MAAM,gFAAgF,QAAQ,EAAE;AAAA,IAC9G;AAAA,EACJ,SAAS,GAAG;AACR,UAAM,IAAI,MAAM,KAAK,iBAAiB,yBAAyB;AAAA,MAC3D,OAAO;AAAA,IACX,CAAC;AAAA,EACL;AACJ;AAEO,SAAS,YAAY,mBAA2D;AACnF,MAAI,CAAC;AAAe,oBAAgB,iBAAiB;AAGrD;AAAA;AAAA,IAEI,kBAAkB,SAAS;AAAA,IAE3B,kBAAkB,SAAS;AAAA,IAC7B;AACE,WAAO;AAAA,EACX;AAEA,QAAM,QAAQ,cAAc,OAAO,iBAAiB;AACpD,QAAM,WAAW,MAAM;AACvB,MAAI,aAAa,IAAI;AACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBA,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\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 { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/private-key.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAC/C,SAAS,qCAAqC,mBAAmB;;;ACDjE,SAAS,eAAe,OAA+B;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ACrE","sourcesContent":["import { assertKeyGenerationIsAvailable } from '@solana/assertions';\nimport { SOLANA_ERROR__INVALID_KEYPAIR_BYTES, SolanaError } from '@solana/errors';\n\nimport { createPrivateKeyFromBytes } from './private-key';\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\nexport async function createKeyPairFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKeyPair> {\n if (bytes.byteLength !== 64) {\n throw new SolanaError(SOLANA_ERROR__INVALID_KEYPAIR_BYTES, { byteLength: bytes.byteLength });\n }\n const [publicKey, privateKey] = await Promise.all([\n crypto.subtle.importKey('raw', bytes.slice(32), 'Ed25519', /* extractable */ true, ['verify']),\n createPrivateKeyFromBytes(bytes.slice(0, 32), extractable),\n ]);\n return { privateKey, publicKey } as CryptoKeyPair;\n}\n","function addPkcs8Header(bytes: Uint8Array): Uint8Array {\n // prettier-ignore\n return new Uint8Array([\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n\n ...bytes\n ]);\n}\n\nexport async function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey> {\n if (bytes.byteLength !== 32) {\n // TODO: Coded error.\n throw new Error('Private key bytes must be of length 32');\n }\n const privateKeyBytesPkcs8 = addPkcs8Header(bytes);\n return await crypto.subtle.importKey('pkcs8', privateKeyBytesPkcs8, 'Ed25519', extractable ?? false, ['sign']);\n}\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,3 +1,4 @@
1
- export * from './key-pair';
2
- export * from './signatures';
1
+ export * from './key-pair.js';
2
+ export * from './private-key.js';
3
+ export * from './signatures.js';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,cAAc,CAAC"}
@@ -1,2 +1,3 @@
1
1
  export declare function generateKeyPair(): Promise<CryptoKeyPair>;
2
+ export declare function createKeyPairFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKeyPair>;
2
3
  //# sourceMappingURL=key-pair.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"key-pair.d.ts","sourceRoot":"","sources":["../../src/key-pair.ts"],"names":[],"mappings":"AAEA,wBAAsB,eAAe,IAAI,OAAO,CAAC,aAAa,CAAC,CAQ9D"}
1
+ {"version":3,"file":"key-pair.d.ts","sourceRoot":"","sources":["../../src/key-pair.ts"],"names":[],"mappings":"AAKA,wBAAsB,eAAe,IAAI,OAAO,CAAC,aAAa,CAAC,CAQ9D;AAED,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,aAAa,CAAC,CAS7G"}
@@ -0,0 +1,2 @@
1
+ export declare function createPrivateKeyFromBytes(bytes: Uint8Array, extractable?: boolean): Promise<CryptoKey>;
2
+ //# sourceMappingURL=private-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"private-key.d.ts","sourceRoot":"","sources":["../../src/private-key.ts"],"names":[],"mappings":"AAqCA,wBAAsB,yBAAyB,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAO5G"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/keys",
3
- "version": "2.0.0-experimental.a48ebd2",
3
+ "version": "2.0.0-experimental.a64df70",
4
4
  "description": "Helpers for generating and transforming key material",
5
5
  "exports": {
6
6
  "browser": {
@@ -49,31 +49,10 @@
49
49
  "node": ">=17.4"
50
50
  },
51
51
  "dependencies": {
52
- "@solana/assertions": "2.0.0-experimental.a48ebd2",
53
- "@solana/codecs-core": "2.0.0-experimental.a48ebd2",
54
- "@solana/codecs-strings": "2.0.0-experimental.a48ebd2"
55
- },
56
- "devDependencies": {
57
- "@solana/eslint-config-solana": "^1.0.2",
58
- "@swc/jest": "^0.2.29",
59
- "@types/jest": "^29.5.6",
60
- "@typescript-eslint/eslint-plugin": "^6.7.0",
61
- "@typescript-eslint/parser": "^6.3.0",
62
- "agadoo": "^3.0.0",
63
- "eslint": "^8.45.0",
64
- "eslint-plugin-jest": "^27.4.2",
65
- "eslint-plugin-sort-keys-fix": "^1.1.2",
66
- "jest": "^29.7.0",
67
- "jest-environment-jsdom": "^29.7.0",
68
- "jest-runner-eslint": "^2.1.2",
69
- "jest-runner-prettier": "^1.0.0",
70
- "prettier": "^2.8",
71
- "tsup": "^8.0.1",
72
- "typescript": "^5.2.2",
73
- "version-from-git": "^1.1.1",
74
- "build-scripts": "0.0.0",
75
- "test-config": "0.0.0",
76
- "tsconfig": "0.0.0"
52
+ "@solana/assertions": "2.0.0-experimental.a64df70",
53
+ "@solana/codecs-core": "2.0.0-experimental.a64df70",
54
+ "@solana/codecs-strings": "2.0.0-experimental.a64df70",
55
+ "@solana/errors": "2.0.0-experimental.a64df70"
77
56
  },
78
57
  "bundlewatch": {
79
58
  "defaultCompression": "gzip",
@@ -84,18 +63,19 @@
84
63
  ]
85
64
  },
86
65
  "scripts": {
87
- "compile:js": "tsup --config build-scripts/tsup.config.library.ts",
88
- "compile:typedefs": "tsc -p ./tsconfig.declarations.json",
89
- "dev": "jest -c node_modules/test-config/jest-dev.config.ts --rootDir . --watch",
90
- "publish-packages": "pnpm publish --tag experimental --access public --no-git-checks",
66
+ "compile:js": "tsup --config build-scripts/tsup.config.package.ts",
67
+ "compile:typedefs": "tsc -p ./tsconfig.declarations.json && node node_modules/@solana/build-scripts/add-js-extension-to-types.mjs",
68
+ "dev": "jest -c node_modules/@solana/test-config/jest-dev.config.ts --rootDir . --watch",
69
+ "publish-impl": "npm view $npm_package_name@$npm_package_version > /dev/null 2>&1 || pnpm publish --tag experimental --access public --no-git-checks",
70
+ "publish-packages": "pnpm prepublishOnly && pnpm publish-impl",
91
71
  "style:fix": "pnpm eslint --fix src/* && pnpm prettier -w src/* package.json",
92
- "test:lint": "jest -c node_modules/test-config/jest-lint.config.ts --rootDir . --silent",
93
- "test:prettier": "jest -c node_modules/test-config/jest-prettier.config.ts --rootDir . --silent",
72
+ "test:lint": "jest -c node_modules/@solana/test-config/jest-lint.config.ts --rootDir . --silent",
73
+ "test:prettier": "jest -c node_modules/@solana/test-config/jest-prettier.config.ts --rootDir . --silent",
94
74
  "test:treeshakability:browser": "agadoo dist/index.browser.js",
95
75
  "test:treeshakability:native": "agadoo dist/index.native.js",
96
76
  "test:treeshakability:node": "agadoo dist/index.node.js",
97
77
  "test:typecheck": "tsc --noEmit",
98
- "test:unit:browser": "jest -c node_modules/test-config/jest-unit.config.browser.ts --rootDir . --silent",
99
- "test:unit:node": "jest -c node_modules/test-config/jest-unit.config.node.ts --rootDir . --silent"
78
+ "test:unit:browser": "jest -c node_modules/@solana/test-config/jest-unit.config.browser.ts --rootDir . --silent",
79
+ "test:unit:node": "jest -c node_modules/@solana/test-config/jest-unit.config.node.ts --rootDir . --silent"
100
80
  }
101
81
  }
@@ -1,186 +0,0 @@
1
- this.globalThis = this.globalThis || {};
2
- this.globalThis.solanaWeb3 = (function (exports) {
3
- 'use strict';
4
-
5
- // ../assertions/dist/index.browser.js
6
- function assertIsSecureContext() {
7
- if (!globalThis.isSecureContext) {
8
- throw new Error(
9
- "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
10
- );
11
- }
12
- }
13
- var cachedEd25519Decision;
14
- async function isEd25519CurveSupported(subtle) {
15
- if (cachedEd25519Decision === void 0) {
16
- cachedEd25519Decision = new Promise((resolve) => {
17
- subtle.generateKey(
18
- "Ed25519",
19
- /* extractable */
20
- false,
21
- ["sign", "verify"]
22
- ).catch(() => {
23
- resolve(cachedEd25519Decision = false);
24
- }).then(() => {
25
- resolve(cachedEd25519Decision = true);
26
- });
27
- });
28
- }
29
- if (typeof cachedEd25519Decision === "boolean") {
30
- return cachedEd25519Decision;
31
- } else {
32
- return await cachedEd25519Decision;
33
- }
34
- }
35
- async function assertKeyGenerationIsAvailable() {
36
- var _a;
37
- assertIsSecureContext();
38
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.generateKey) !== "function") {
39
- throw new Error("No key generation implementation could be found");
40
- }
41
- if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
42
- throw new Error(
43
- "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"
44
- );
45
- }
46
- }
47
- async function assertSigningCapabilityIsAvailable() {
48
- var _a;
49
- assertIsSecureContext();
50
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.sign) !== "function") {
51
- throw new Error("No signing implementation could be found");
52
- }
53
- }
54
- async function assertVerificationCapabilityIsAvailable() {
55
- var _a;
56
- assertIsSecureContext();
57
- if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.verify) !== "function") {
58
- throw new Error("No signature verification implementation could be found");
59
- }
60
- }
61
-
62
- // src/key-pair.ts
63
- async function generateKeyPair() {
64
- await assertKeyGenerationIsAvailable();
65
- const keyPair = await crypto.subtle.generateKey(
66
- /* algorithm */
67
- "Ed25519",
68
- // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
69
- /* extractable */
70
- false,
71
- // Prevents the bytes of the private key from being visible to JS.
72
- /* allowed uses */
73
- ["sign", "verify"]
74
- );
75
- return keyPair;
76
- }
77
-
78
- // ../codecs-strings/dist/index.browser.js
79
- function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
80
- if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
81
- throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
82
- }
83
- }
84
- var getBaseXEncoder = (alphabet4) => {
85
- const base = alphabet4.length;
86
- const baseBigInt = BigInt(base);
87
- return {
88
- description: `base${base}`,
89
- encode(value) {
90
- assertValidBaseString(alphabet4, value);
91
- if (value === "")
92
- return new Uint8Array();
93
- const chars = [...value];
94
- let trailIndex = chars.findIndex((c) => c !== alphabet4[0]);
95
- trailIndex = trailIndex === -1 ? chars.length : trailIndex;
96
- const leadingZeroes = Array(trailIndex).fill(0);
97
- if (trailIndex === chars.length)
98
- return Uint8Array.from(leadingZeroes);
99
- const tailChars = chars.slice(trailIndex);
100
- let base10Number = 0n;
101
- let baseXPower = 1n;
102
- for (let i = tailChars.length - 1; i >= 0; i -= 1) {
103
- base10Number += baseXPower * BigInt(alphabet4.indexOf(tailChars[i]));
104
- baseXPower *= baseBigInt;
105
- }
106
- const tailBytes = [];
107
- while (base10Number > 0n) {
108
- tailBytes.unshift(Number(base10Number % 256n));
109
- base10Number /= 256n;
110
- }
111
- return Uint8Array.from(leadingZeroes.concat(tailBytes));
112
- },
113
- fixedSize: null,
114
- maxSize: null
115
- };
116
- };
117
- var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
118
- var getBase58Encoder = () => getBaseXEncoder(alphabet2);
119
-
120
- // src/signatures.ts
121
- var base58Encoder;
122
- function assertIsSignature(putativeSignature) {
123
- if (!base58Encoder)
124
- base58Encoder = getBase58Encoder();
125
- try {
126
- if (
127
- // Lowest value (64 bytes of zeroes)
128
- putativeSignature.length < 64 || // Highest value (64 bytes of 255)
129
- putativeSignature.length > 88
130
- ) {
131
- throw new Error("Expected input string to decode to a byte array of length 64.");
132
- }
133
- const bytes = base58Encoder.encode(putativeSignature);
134
- const numBytes = bytes.byteLength;
135
- if (numBytes !== 64) {
136
- throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
137
- }
138
- } catch (e2) {
139
- throw new Error(`\`${putativeSignature}\` is not a signature`, {
140
- cause: e2
141
- });
142
- }
143
- }
144
- function isSignature(putativeSignature) {
145
- if (!base58Encoder)
146
- base58Encoder = getBase58Encoder();
147
- if (
148
- // Lowest value (64 bytes of zeroes)
149
- putativeSignature.length < 64 || // Highest value (64 bytes of 255)
150
- putativeSignature.length > 88
151
- ) {
152
- return false;
153
- }
154
- const bytes = base58Encoder.encode(putativeSignature);
155
- const numBytes = bytes.byteLength;
156
- if (numBytes !== 64) {
157
- return false;
158
- }
159
- return true;
160
- }
161
- async function signBytes(key, data) {
162
- await assertSigningCapabilityIsAvailable();
163
- const signedData = await crypto.subtle.sign("Ed25519", key, data);
164
- return new Uint8Array(signedData);
165
- }
166
- function signature(putativeSignature) {
167
- assertIsSignature(putativeSignature);
168
- return putativeSignature;
169
- }
170
- async function verifySignature(key, signature2, data) {
171
- await assertVerificationCapabilityIsAvailable();
172
- return await crypto.subtle.verify("Ed25519", key, signature2, data);
173
- }
174
-
175
- exports.assertIsSignature = assertIsSignature;
176
- exports.generateKeyPair = generateKeyPair;
177
- exports.isSignature = isSignature;
178
- exports.signBytes = signBytes;
179
- exports.signature = signature;
180
- exports.verifySignature = verifySignature;
181
-
182
- return exports;
183
-
184
- })({});
185
- //# sourceMappingURL=out.js.map
186
- //# sourceMappingURL=index.development.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../assertions/src/subtle-crypto.ts","../src/key-pair.ts","../../codecs-strings/src/assertions.ts","../../codecs-strings/src/baseX.ts","../../codecs-strings/src/base16.ts","../../codecs-strings/src/base64.ts","../src/signatures.ts"],"names":["alphabet","e","signature"],"mappings":";AAAA,SAAS,wBAAwB;AAC7B,MAAmB,CAAC,WAAW,iBAAiB;AAE5C,UAAM,IAAI;MACN;IAEJ;EACJ;AACJ;AAEA,IAAI;AACJ,eAAe,wBAAwB,QAAwC;AAC3E,MAAI,0BAA0B,QAAW;AACrC,4BAAwB,IAAI,QAAQ,CAAA,YAAW;AAC3C,aACK;QAAY;;QAA6B;QAAO,CAAC,QAAQ,QAAQ;MAAC,EAClE,MAAM,MAAM;AACT,gBAAS,wBAAwB,KAAM;MAC3C,CAAC,EACA,KAAK,MAAM;AACR,gBAAS,wBAAwB,IAAK;MAC1C,CAAC;IACT,CAAC;EACL;AACA,MAAI,OAAO,0BAA0B,WAAW;AAC5C,WAAO;EACX,OAAO;AACH,WAAO,MAAM;EACjB;AACJ;AAUA,eAAsB,iCAAiC;;AACnD,wBAAsB;AACtB,MAAI,OAAO,WAAW,WAAW,eAAe,SAAO,gBAAW,OAAO,WAAlB,mBAA0B,iBAAgB,YAAY;AAEzG,UAAM,IAAI,MAAM,iDAAiD;E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ACjB,WAAO;AAAA,EACX;AACA,SAAO;AACX;AAEA,eAAsB,UAAU,KAAgB,MAA2C;AACvF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,UAAU,mBAAsC;AAC5D,oBAAkB,iBAAiB;AACnC,SAAO;AACX;AAEA,eAAsB,gBAAgB,KAAgBC,YAA2B,MAAoC;AACjH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAKA,YAAW,IAAI;AACrE","sourcesContent":["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 assertDigestCapabilityIsAvailable() {\n assertIsSecureContext();\n if (typeof globalThis.crypto === 'undefined' || typeof globalThis.crypto.subtle?.digest !== 'function') {\n // TODO: Coded error.\n throw new Error('No digest implementation could be found');\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 '@solana/assertions';\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","/**\n * Asserts that a given string matches a given alphabet.\n */\nexport function assertValidBaseString(alphabet: string, testValue: string, givenValue = testValue) {\n if (!testValue.match(new RegExp(`^[${alphabet}]*$`))) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base ${alphabet.length}, got [${givenValue}].`);\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/**\n * Encodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXEncoder = (alphabet: string): Encoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n description: `base${base}`,\n encode(value: string): Uint8Array {\n // Check if the value is valid.\n assertValidBaseString(alphabet, value);\n if (value === '') return new Uint8Array();\n\n // Handle leading zeroes.\n const chars = [...value];\n let trailIndex = chars.findIndex(c => c !== alphabet[0]);\n trailIndex = trailIndex === -1 ? chars.length : trailIndex;\n const leadingZeroes = Array(trailIndex).fill(0);\n if (trailIndex === chars.length) return Uint8Array.from(leadingZeroes);\n\n // From baseX to base10.\n const tailChars = chars.slice(trailIndex);\n let base10Number = 0n;\n let baseXPower = 1n;\n for (let i = tailChars.length - 1; i >= 0; i -= 1) {\n base10Number += baseXPower * BigInt(alphabet.indexOf(tailChars[i]));\n baseXPower *= baseBigInt;\n }\n\n // From base10 to bytes.\n const tailBytes = [];\n while (base10Number > 0n) {\n tailBytes.unshift(Number(base10Number % 256n));\n base10Number /= 256n;\n }\n return Uint8Array.from(leadingZeroes.concat(tailBytes));\n },\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * Decodes a string using a custom alphabet by dividing\n * by the base and handling leading zeroes.\n * @see {@link getBaseXCodec} for a more detailed description.\n */\nexport const getBaseXDecoder = (alphabet: string): Decoder<string> => {\n const base = alphabet.length;\n const baseBigInt = BigInt(base);\n return {\n decode(rawBytes, offset = 0): [string, number] {\n const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);\n if (bytes.length === 0) return ['', 0];\n\n // Handle leading zeroes.\n let trailIndex = bytes.findIndex(n => n !== 0);\n trailIndex = trailIndex === -1 ? bytes.length : trailIndex;\n const leadingZeroes = alphabet[0].repeat(trailIndex);\n if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];\n\n // From bytes to base10.\n let base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);\n\n // From base10 to baseX.\n const tailChars = [];\n while (base10Number > 0n) {\n tailChars.unshift(alphabet[Number(base10Number % baseBigInt)]);\n base10Number /= baseBigInt;\n }\n\n return [leadingZeroes + tailChars.join(''), rawBytes.length];\n },\n description: `base${base}`,\n fixedSize: null,\n maxSize: null,\n };\n};\n\n/**\n * A string codec that requires a custom alphabet and uses\n * the length of that alphabet as the base. It then divides\n * the input by the base as many times as necessary to get\n * the output. It also supports leading zeroes by using the\n * first character of the alphabet as the zero character.\n *\n * This can be used to create codecs such as base10 or base58.\n */\nexport const getBaseXCodec = (alphabet: string): Codec<string> =>\n combineCodec(getBaseXEncoder(alphabet), getBaseXDecoder(alphabet));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\n\n/** Encodes strings in base16. */\nexport const getBase16Encoder = (): Encoder<string> => ({\n description: 'base16',\n encode(value: string) {\n const lowercaseValue = value.toLowerCase();\n assertValidBaseString('0123456789abcdef', lowercaseValue, value);\n const matches = lowercaseValue.match(/.{1,2}/g);\n return Uint8Array.from(matches ? matches.map((byte: string) => parseInt(byte, 16)) : []);\n },\n fixedSize: null,\n maxSize: null,\n});\n\n/** Decodes strings in base16. */\nexport const getBase16Decoder = (): Decoder<string> => ({\n decode(bytes, offset = 0) {\n const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n return [value, bytes.length];\n },\n description: 'base16',\n fixedSize: null,\n maxSize: null,\n});\n\n/** Encodes and decodes strings in base16. */\nexport const getBase16Codec = (): Codec<string> => combineCodec(getBase16Encoder(), getBase16Decoder());\n","import { combineCodec, Decoder, Encoder, mapDecoder, mapEncoder } from '@solana/codecs-core';\n\nimport { assertValidBaseString } from './assertions';\nimport { getBaseXResliceDecoder, getBaseXResliceEncoder } from './baseX-reslice';\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Encodes strings in base64. */\nexport const getBase64Encoder = (): Encoder<string> => {\n if (__BROWSER__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n try {\n const bytes = (atob as Window['atob'])(value)\n .split('')\n .map(c => c.charCodeAt(0));\n return new Uint8Array(bytes);\n } catch (e) {\n // TODO: Coded error.\n throw new Error(`Expected a string of base 64, got [${value}].`);\n }\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n description: `base64`,\n encode(value: string): Uint8Array {\n assertValidBaseString(alphabet, value.replace(/=/g, ''));\n return new Uint8Array(Buffer.from(value, 'base64'));\n },\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapEncoder(getBaseXResliceEncoder(alphabet, 6), (value: string): string => value.replace(/=/g, ''));\n};\n\n/** Decodes strings in base64. */\nexport const getBase64Decoder = (): Decoder<string> => {\n if (__BROWSER__) {\n return {\n decode(bytes, offset = 0) {\n const slice = bytes.slice(offset);\n const value = (btoa as Window['btoa'])(String.fromCharCode(...slice));\n return [value, bytes.length];\n },\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n if (__NODEJS__) {\n return {\n decode: (bytes, offset = 0) => [Buffer.from(bytes, offset).toString('base64'), bytes.length],\n description: `base64`,\n fixedSize: null,\n maxSize: null,\n };\n }\n\n return mapDecoder(getBaseXResliceDecoder(alphabet, 6), (value: string): string =>\n value.padEnd(Math.ceil(value.length / 4) * 4, '=')\n );\n};\n\n/** Encodes and decodes strings in base64. */\nexport const getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());\n","import { assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';\nimport { Encoder } from '@solana/codecs-core';\nimport { getBase58Encoder } from '@solana/codecs-strings';\n\nexport type Signature = string & { readonly __brand: unique symbol };\nexport type SignatureBytes = Uint8Array & { readonly __brand: unique symbol };\n\nlet base58Encoder: Encoder<string> | undefined;\n\nexport function assertIsSignature(putativeSignature: string): asserts putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n try {\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n throw new Error('Expected input string to decode to a byte array of length 64.');\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);\n }\n } catch (e) {\n throw new Error(`\\`${putativeSignature}\\` is not a signature`, {\n cause: e,\n });\n }\n}\n\nexport function isSignature(putativeSignature: string): putativeSignature is Signature {\n if (!base58Encoder) base58Encoder = getBase58Encoder();\n\n // Fast-path; see if the input string is of an acceptable length.\n if (\n // Lowest value (64 bytes of zeroes)\n putativeSignature.length < 64 ||\n // Highest value (64 bytes of 255)\n putativeSignature.length > 88\n ) {\n return false;\n }\n // Slow-path; actually attempt to decode the input string.\n const bytes = base58Encoder.encode(putativeSignature);\n const numBytes = bytes.byteLength;\n if (numBytes !== 64) {\n return false;\n }\n return true;\n}\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<SignatureBytes> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as SignatureBytes;\n}\n\nexport function signature(putativeSignature: string): Signature {\n assertIsSignature(putativeSignature);\n return putativeSignature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: SignatureBytes, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
@@ -1,20 +0,0 @@
1
- this.globalThis = this.globalThis || {};
2
- this.globalThis.solanaWeb3 = (function (exports) {
3
- 'use strict';
4
-
5
- function u(){if(!globalThis.isSecureContext)throw new Error("Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts")}var r;async function v(e){return r===void 0&&(r=new Promise(t=>{e.generateKey("Ed25519",!1,["sign","verify"]).catch(()=>{t(r=!1);}).then(()=>{t(r=!0);});})),typeof r=="boolean"?r:await r}async function b(){var e;if(u(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.generateKey)!="function")throw new Error("No key generation implementation could be found");if(!await v(globalThis.crypto.subtle))throw new Error(`This runtime does not support the generation of Ed25519 key pairs.
6
-
7
- Install and import \`@solana/webcrypto-ed25519-polyfill\` before generating keys in environments that do not support Ed25519.
8
-
9
- For a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20`)}async function m(){var e;if(u(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.sign)!="function")throw new Error("No signing implementation could be found")}async function x(){var e;if(u(),typeof globalThis.crypto>"u"||typeof((e=globalThis.crypto.subtle)==null?void 0:e.verify)!="function")throw new Error("No signature verification implementation could be found")}async function D(){return await b(),await crypto.subtle.generateKey("Ed25519",!1,["sign","verify"])}function E(e,t,n=t){if(!t.match(new RegExp(`^[${e}]*$`)))throw new Error(`Expected a string of base ${e.length}, got [${n}].`)}var S=e=>{let t=e.length,n=BigInt(t);return {description:`base${t}`,encode(d){if(E(e,d),d==="")return new Uint8Array;let a=[...d],o=a.findIndex(s=>s!==e[0]);o=o===-1?a.length:o;let f=Array(o).fill(0);if(o===a.length)return Uint8Array.from(f);let y=a.slice(o),c=0n,p=1n;for(let s=y.length-1;s>=0;s-=1)c+=p*BigInt(e.indexOf(y[s])),p*=n;let h=[];for(;c>0n;)h.unshift(Number(c%256n)),c/=256n;return Uint8Array.from(f.concat(h))},fixedSize:null,maxSize:null}};var w="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",g=()=>S(w);var i;function C(e){i||(i=g());try{if(e.length<64||e.length>88)throw new Error("Expected input string to decode to a byte array of length 64.");let n=i.encode(e).byteLength;if(n!==64)throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${n}`)}catch(t){throw new Error(`\`${e}\` is not a signature`,{cause:t})}}function X(e){return i||(i=g()),!(e.length<64||e.length>88||i.encode(e).byteLength!==64)}async function R(e,t){await m();let n=await crypto.subtle.sign("Ed25519",e,t);return new Uint8Array(n)}function V(e){return C(e),e}async function O(e,t,n){return await x(),await crypto.subtle.verify("Ed25519",e,t,n)}
10
-
11
- exports.assertIsSignature = C;
12
- exports.generateKeyPair = D;
13
- exports.isSignature = X;
14
- exports.signBytes = R;
15
- exports.signature = V;
16
- exports.verifySignature = O;
17
-
18
- return exports;
19
-
20
- })({});