@solana/keys 2.0.0-experimental.fc4e943 → 2.0.0-experimental.fcff844

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
@@ -18,7 +18,11 @@ This package contains utilities for validating, generating, and manipulating add
18
18
 
19
19
  ## Types
20
20
 
21
- ### `Ed25519Signature`
21
+ ### `Signature`
22
+
23
+ This type represents a 64-byte Ed25519 signature of some data with a private key, as a base58-encoded string.
24
+
25
+ ### `SignatureBytes`
22
26
 
23
27
  This type represents a 64-byte Ed25519 signature of some data with a private key.
24
28
 
@@ -26,6 +30,31 @@ Whenever you need to verify that a particular signature is, in fact, the one tha
26
30
 
27
31
  ## Functions
28
32
 
33
+ ### `assertIsSignature()`
34
+
35
+ From time to time you might acquire a string that you expect to be a base58-encoded signature (eg. of a transaction) from an untrusted network API or user input. To assert that such an arbitrary string is in fact an Ed25519 signature, use the `assertIsSignature` function.
36
+
37
+ ```ts
38
+ import { assertIsSignature } from '@solana/keys';
39
+
40
+ // Imagine a function that asserts whether a user-supplied signature is valid or not.
41
+ function handleSubmit() {
42
+ // We know only that what the user typed conforms to the `string` type.
43
+ const signature: string = signatureInput.value;
44
+ try {
45
+ // If this type assertion function doesn't throw, then
46
+ // Typescript will upcast `signature` to `Signature`.
47
+ assertIsSignature(signature);
48
+ // At this point, `signature` is a `Signature` that can be used with the RPC.
49
+ const {
50
+ value: [status],
51
+ } = await rpc.getSignatureStatuses([signature]).send();
52
+ } catch (e) {
53
+ // `signature` turned out not to be a base58-encoded signature
54
+ }
55
+ }
56
+ ```
57
+
29
58
  ### `generateKeyPair()`
30
59
 
31
60
  Generates an Ed25519 public/private key pair for use with other methods in this package that accept `CryptoKey` objects.
@@ -36,6 +65,25 @@ import { generateKeyPair } from '@solana/keys';
36
65
  const { privateKey, publicKey } = await generateKeyPair();
37
66
  ```
38
67
 
68
+ ### `isSignature()`
69
+
70
+ 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.
71
+
72
+ ```ts
73
+ import { isSignature } from '@solana/keys';
74
+
75
+ if (isSignature(signature)) {
76
+ // At this point, `signature` has been refined to a
77
+ // `Signature` that can be used with the RPC.
78
+ const {
79
+ value: [status],
80
+ } = await rpc.getSignatureStatuses([signature]).send();
81
+ setSignatureStatus(status);
82
+ } else {
83
+ setError(`${signature} is not a transaction signature`);
84
+ }
85
+ ```
86
+
39
87
  ### `signBytes()`
40
88
 
41
89
  Given a private `CryptoKey` and a `Uint8Array` of bytes, this method will return the 64-byte Ed25519 signature of that data as a `Uint8Array`.
@@ -47,9 +95,22 @@ const data = new Uint8Array([1, 2, 3]);
47
95
  const signature = await signBytes(privateKey, data);
48
96
  ```
49
97
 
98
+ ### `signature()`
99
+
100
+ This helper combines _asserting_ that a string is an Ed25519 signature with _coercing_ it to the `Signature` type. It's best used with untrusted input.
101
+
102
+ ```ts
103
+ import { signature } from '@solana/keys';
104
+
105
+ const signature = signature(userSuppliedSignature);
106
+ const {
107
+ value: [status],
108
+ } = await rpc.getSignatureStatuses([signature]).send();
109
+ ```
110
+
50
111
  ### `verifySignature()`
51
112
 
52
- Given a public `CryptoKey`, an `Ed25519Signature`, and a `Uint8Array` of bytes, this method will return `true` if the signature was produced by signing the bytes using the private key associated with the public key, and `false` otherwise.
113
+ Given a public `CryptoKey`, some `SignatureBytes`, and a `Uint8Array` of data, this method will return `true` if the signature was produced by signing the data using the private key associated with the public key, and `false` otherwise.
53
114
 
54
115
  ```ts
55
116
  import { verifySignature } from '@solana/keys';
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var assertions = require('@solana/assertions');
4
+ var codecsStrings = require('@solana/codecs-strings');
4
5
 
5
6
  // src/key-pair.ts
6
7
  async function generateKeyPair() {
@@ -17,18 +18,119 @@ async function generateKeyPair() {
17
18
  );
18
19
  return keyPair;
19
20
  }
21
+
22
+ // src/private-key.ts
23
+ function addPkcs8Header(bytes) {
24
+ return new Uint8Array([
25
+ /**
26
+ * PKCS#8 header
27
+ */
28
+ 48,
29
+ // ASN.1 sequence tag
30
+ 46,
31
+ // Length of sequence (46 more bytes)
32
+ 2,
33
+ // ASN.1 integer tag
34
+ 1,
35
+ // Length of integer
36
+ 0,
37
+ // Version number
38
+ 48,
39
+ // ASN.1 sequence tag
40
+ 5,
41
+ // Length of sequence
42
+ 6,
43
+ // ASN.1 object identifier tag
44
+ 3,
45
+ // Length of object identifier
46
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
47
+ 43,
48
+ // 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)
49
+ 101,
50
+ // thawte(101)
51
+ // Ed25519 identifier
52
+ 112,
53
+ // id-Ed25519(112)
54
+ /**
55
+ * Private key payload
56
+ */
57
+ 4,
58
+ // ASN.1 octet string tag
59
+ 34,
60
+ // String length (34 more bytes)
61
+ // Private key bytes as octet string
62
+ 4,
63
+ // ASN.1 octet string tag
64
+ 32,
65
+ // String length (32 bytes)
66
+ ...bytes
67
+ ]);
68
+ }
69
+ async function createPrivateKeyFromBytes(bytes, extractable) {
70
+ if (bytes.byteLength !== 32) {
71
+ throw new Error("Private key bytes must be of length 32");
72
+ }
73
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
74
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable ?? false, ["sign"]);
75
+ }
76
+ var base58Encoder;
77
+ function assertIsSignature(putativeSignature) {
78
+ if (!base58Encoder)
79
+ base58Encoder = codecsStrings.getBase58Encoder();
80
+ try {
81
+ if (
82
+ // Lowest value (64 bytes of zeroes)
83
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
84
+ putativeSignature.length > 88
85
+ ) {
86
+ throw new Error("Expected input string to decode to a byte array of length 64.");
87
+ }
88
+ const bytes = base58Encoder.encode(putativeSignature);
89
+ const numBytes = bytes.byteLength;
90
+ if (numBytes !== 64) {
91
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
92
+ }
93
+ } catch (e) {
94
+ throw new Error(`\`${putativeSignature}\` is not a signature`, {
95
+ cause: e
96
+ });
97
+ }
98
+ }
99
+ function isSignature(putativeSignature) {
100
+ if (!base58Encoder)
101
+ base58Encoder = codecsStrings.getBase58Encoder();
102
+ if (
103
+ // Lowest value (64 bytes of zeroes)
104
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
105
+ putativeSignature.length > 88
106
+ ) {
107
+ return false;
108
+ }
109
+ const bytes = base58Encoder.encode(putativeSignature);
110
+ const numBytes = bytes.byteLength;
111
+ if (numBytes !== 64) {
112
+ return false;
113
+ }
114
+ return true;
115
+ }
20
116
  async function signBytes(key, data) {
21
117
  await assertions.assertSigningCapabilityIsAvailable();
22
118
  const signedData = await crypto.subtle.sign("Ed25519", key, data);
23
119
  return new Uint8Array(signedData);
24
120
  }
25
- async function verifySignature(key, signature, data) {
121
+ function signature(putativeSignature) {
122
+ assertIsSignature(putativeSignature);
123
+ return putativeSignature;
124
+ }
125
+ async function verifySignature(key, signature2, data) {
26
126
  await assertions.assertVerificationCapabilityIsAvailable();
27
- return await crypto.subtle.verify("Ed25519", key, signature, data);
127
+ return await crypto.subtle.verify("Ed25519", key, signature2, data);
28
128
  }
29
129
 
130
+ exports.assertIsSignature = assertIsSignature;
131
+ exports.createPrivateKeyFromBytes = createPrivateKeyFromBytes;
30
132
  exports.generateKeyPair = generateKeyPair;
133
+ exports.isSignature = isSignature;
31
134
  exports.signBytes = signBytes;
135
+ exports.signature = signature;
32
136
  exports.verifySignature = verifySignature;
33
- //# sourceMappingURL=out.js.map
34
- //# sourceMappingURL=index.browser.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":[],"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;AAI5F,eAAsB,UAAU,KAAgB,MAA6C;AACzF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["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';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/private-key.ts","../src/signatures.ts"],"names":["signature"],"mappings":";AAAA,SAAS,sCAAsC;AAE/C,eAAsB,kBAA0C;AAC5D,QAAM,+BAA+B;AACrC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AAA,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","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,4 +1,5 @@
1
1
  import { assertKeyGenerationIsAvailable, assertSigningCapabilityIsAvailable, assertVerificationCapabilityIsAvailable } from '@solana/assertions';
2
+ import { getBase58Encoder } from '@solana/codecs-strings';
2
3
 
3
4
  // src/key-pair.ts
4
5
  async function generateKeyPair() {
@@ -15,16 +16,115 @@ async function generateKeyPair() {
15
16
  );
16
17
  return keyPair;
17
18
  }
19
+
20
+ // src/private-key.ts
21
+ function addPkcs8Header(bytes) {
22
+ return new Uint8Array([
23
+ /**
24
+ * PKCS#8 header
25
+ */
26
+ 48,
27
+ // ASN.1 sequence tag
28
+ 46,
29
+ // Length of sequence (46 more bytes)
30
+ 2,
31
+ // ASN.1 integer tag
32
+ 1,
33
+ // Length of integer
34
+ 0,
35
+ // Version number
36
+ 48,
37
+ // ASN.1 sequence tag
38
+ 5,
39
+ // Length of sequence
40
+ 6,
41
+ // ASN.1 object identifier tag
42
+ 3,
43
+ // Length of object identifier
44
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
45
+ 43,
46
+ // 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)
47
+ 101,
48
+ // thawte(101)
49
+ // Ed25519 identifier
50
+ 112,
51
+ // id-Ed25519(112)
52
+ /**
53
+ * Private key payload
54
+ */
55
+ 4,
56
+ // ASN.1 octet string tag
57
+ 34,
58
+ // String length (34 more bytes)
59
+ // Private key bytes as octet string
60
+ 4,
61
+ // ASN.1 octet string tag
62
+ 32,
63
+ // String length (32 bytes)
64
+ ...bytes
65
+ ]);
66
+ }
67
+ async function createPrivateKeyFromBytes(bytes, extractable) {
68
+ if (bytes.byteLength !== 32) {
69
+ throw new Error("Private key bytes must be of length 32");
70
+ }
71
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
72
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable ?? false, ["sign"]);
73
+ }
74
+ var base58Encoder;
75
+ function assertIsSignature(putativeSignature) {
76
+ if (!base58Encoder)
77
+ base58Encoder = getBase58Encoder();
78
+ try {
79
+ if (
80
+ // Lowest value (64 bytes of zeroes)
81
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
82
+ putativeSignature.length > 88
83
+ ) {
84
+ throw new Error("Expected input string to decode to a byte array of length 64.");
85
+ }
86
+ const bytes = base58Encoder.encode(putativeSignature);
87
+ const numBytes = bytes.byteLength;
88
+ if (numBytes !== 64) {
89
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
90
+ }
91
+ } catch (e) {
92
+ throw new Error(`\`${putativeSignature}\` is not a signature`, {
93
+ cause: e
94
+ });
95
+ }
96
+ }
97
+ function isSignature(putativeSignature) {
98
+ if (!base58Encoder)
99
+ base58Encoder = getBase58Encoder();
100
+ if (
101
+ // Lowest value (64 bytes of zeroes)
102
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
103
+ putativeSignature.length > 88
104
+ ) {
105
+ return false;
106
+ }
107
+ const bytes = base58Encoder.encode(putativeSignature);
108
+ const numBytes = bytes.byteLength;
109
+ if (numBytes !== 64) {
110
+ return false;
111
+ }
112
+ return true;
113
+ }
18
114
  async function signBytes(key, data) {
19
115
  await assertSigningCapabilityIsAvailable();
20
116
  const signedData = await crypto.subtle.sign("Ed25519", key, data);
21
117
  return new Uint8Array(signedData);
22
118
  }
23
- async function verifySignature(key, signature, data) {
119
+ function signature(putativeSignature) {
120
+ assertIsSignature(putativeSignature);
121
+ return putativeSignature;
122
+ }
123
+ async function verifySignature(key, signature2, data) {
24
124
  await assertVerificationCapabilityIsAvailable();
25
- return await crypto.subtle.verify("Ed25519", key, signature, data);
125
+ return await crypto.subtle.verify("Ed25519", key, signature2, data);
26
126
  }
27
127
 
28
- export { generateKeyPair, signBytes, verifySignature };
128
+ export { assertIsSignature, createPrivateKeyFromBytes, generateKeyPair, isSignature, signBytes, signature, verifySignature };
29
129
  //# sourceMappingURL=out.js.map
30
130
  //# sourceMappingURL=index.browser.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key-pair.ts","../src/signatures.ts"],"names":[],"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;AAI5F,eAAsB,UAAU,KAAgB,MAA6C;AACzF,QAAM,mCAAmC;AACzC,QAAM,aAAa,MAAM,OAAO,OAAO,KAAK,WAAW,KAAK,IAAI;AAChE,SAAO,IAAI,WAAW,UAAU;AACpC;AAEA,eAAsB,gBAAgB,KAAgB,WAA6B,MAAoC;AACnH,QAAM,wCAAwC;AAC9C,SAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,WAAW,IAAI;AACrE","sourcesContent":["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';\n\nexport type Ed25519Signature = Uint8Array & { readonly __brand: unique symbol };\n\nexport async function signBytes(key: CryptoKey, data: Uint8Array): Promise<Ed25519Signature> {\n await assertSigningCapabilityIsAvailable();\n const signedData = await crypto.subtle.sign('Ed25519', key, data);\n return new Uint8Array(signedData) as Ed25519Signature;\n}\n\nexport async function verifySignature(key: CryptoKey, signature: Ed25519Signature, data: Uint8Array): Promise<boolean> {\n await assertVerificationCapabilityIsAvailable();\n return await crypto.subtle.verify('Ed25519', key, signature, data);\n}\n"]}
1
+ {"version":3,"sources":["../src/key-pair.ts","../src/private-key.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,eAAe,OAA+B;AAEnD,SAAO,IAAI,WAAW;AAAA;AAAA;AAAA;AAAA,IAIlB;AAAA;AAAA,IACA;AAAA;AAAA,IAEI;AAAA;AAAA,IACA;AAAA;AAAA,IAC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EA,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","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"]}
@@ -33,8 +33,9 @@ this.globalThis.solanaWeb3 = (function (exports) {
33
33
  }
34
34
  }
35
35
  async function assertKeyGenerationIsAvailable() {
36
+ var _a;
36
37
  assertIsSecureContext();
37
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
38
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.generateKey) !== "function") {
38
39
  throw new Error("No key generation implementation could be found");
39
40
  }
40
41
  if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
@@ -44,14 +45,16 @@ this.globalThis.solanaWeb3 = (function (exports) {
44
45
  }
45
46
  }
46
47
  async function assertSigningCapabilityIsAvailable() {
48
+ var _a;
47
49
  assertIsSecureContext();
48
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
50
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.sign) !== "function") {
49
51
  throw new Error("No signing implementation could be found");
50
52
  }
51
53
  }
52
54
  async function assertVerificationCapabilityIsAvailable() {
55
+ var _a;
53
56
  assertIsSecureContext();
54
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
57
+ if (typeof globalThis.crypto === "undefined" || typeof ((_a = globalThis.crypto.subtle) == null ? void 0 : _a.verify) !== "function") {
55
58
  throw new Error("No signature verification implementation could be found");
56
59
  }
57
60
  }
@@ -72,19 +75,184 @@ this.globalThis.solanaWeb3 = (function (exports) {
72
75
  return keyPair;
73
76
  }
74
77
 
78
+ // src/private-key.ts
79
+ function addPkcs8Header(bytes) {
80
+ return new Uint8Array([
81
+ /**
82
+ * PKCS#8 header
83
+ */
84
+ 48,
85
+ // ASN.1 sequence tag
86
+ 46,
87
+ // Length of sequence (46 more bytes)
88
+ 2,
89
+ // ASN.1 integer tag
90
+ 1,
91
+ // Length of integer
92
+ 0,
93
+ // Version number
94
+ 48,
95
+ // ASN.1 sequence tag
96
+ 5,
97
+ // Length of sequence
98
+ 6,
99
+ // ASN.1 object identifier tag
100
+ 3,
101
+ // Length of object identifier
102
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
103
+ 43,
104
+ // 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)
105
+ 101,
106
+ // thawte(101)
107
+ // Ed25519 identifier
108
+ 112,
109
+ // id-Ed25519(112)
110
+ /**
111
+ * Private key payload
112
+ */
113
+ 4,
114
+ // ASN.1 octet string tag
115
+ 34,
116
+ // String length (34 more bytes)
117
+ // Private key bytes as octet string
118
+ 4,
119
+ // ASN.1 octet string tag
120
+ 32,
121
+ // String length (32 bytes)
122
+ ...bytes
123
+ ]);
124
+ }
125
+ async function createPrivateKeyFromBytes(bytes, extractable) {
126
+ if (bytes.byteLength !== 32) {
127
+ throw new Error("Private key bytes must be of length 32");
128
+ }
129
+ const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
130
+ return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, "Ed25519", extractable != null ? extractable : false, ["sign"]);
131
+ }
132
+
133
+ // ../codecs-core/dist/index.browser.js
134
+ function getEncodedSize(value, encoder) {
135
+ return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
136
+ }
137
+ function createEncoder(encoder) {
138
+ return Object.freeze({
139
+ ...encoder,
140
+ encode: (value) => {
141
+ const bytes = new Uint8Array(getEncodedSize(value, encoder));
142
+ encoder.write(value, bytes, 0);
143
+ return bytes;
144
+ }
145
+ });
146
+ }
147
+
148
+ // ../codecs-strings/dist/index.browser.js
149
+ function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
150
+ if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
151
+ throw new Error(`Expected a string of base ${alphabet4.length}, got [${givenValue}].`);
152
+ }
153
+ }
154
+ var getBaseXEncoder = (alphabet4) => {
155
+ return createEncoder({
156
+ getSizeFromValue: (value) => {
157
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
158
+ if (tailChars === "")
159
+ return value.length;
160
+ const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
161
+ return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
162
+ },
163
+ write(value, bytes, offset) {
164
+ assertValidBaseString(alphabet4, value);
165
+ if (value === "")
166
+ return offset;
167
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
168
+ if (tailChars === "") {
169
+ bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
170
+ return offset + leadingZeroes.length;
171
+ }
172
+ let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
173
+ const tailBytes = [];
174
+ while (base10Number > 0n) {
175
+ tailBytes.unshift(Number(base10Number % 256n));
176
+ base10Number /= 256n;
177
+ }
178
+ const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
179
+ bytes.set(bytesToAdd, offset);
180
+ return offset + bytesToAdd.length;
181
+ }
182
+ });
183
+ };
184
+ function partitionLeadingZeroes(value, zeroCharacter) {
185
+ const leadingZeroIndex = [...value].findIndex((c) => c !== zeroCharacter);
186
+ return leadingZeroIndex === -1 ? [value, ""] : [value.slice(0, leadingZeroIndex), value.slice(leadingZeroIndex)];
187
+ }
188
+ function getBigIntFromBaseX(value, alphabet4) {
189
+ const base = BigInt(alphabet4.length);
190
+ return [...value].reduce((sum, char) => sum * base + BigInt(alphabet4.indexOf(char)), 0n);
191
+ }
192
+ var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
193
+ var getBase58Encoder = () => getBaseXEncoder(alphabet2);
194
+
75
195
  // src/signatures.ts
196
+ var base58Encoder;
197
+ function assertIsSignature(putativeSignature) {
198
+ if (!base58Encoder)
199
+ base58Encoder = getBase58Encoder();
200
+ try {
201
+ if (
202
+ // Lowest value (64 bytes of zeroes)
203
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
204
+ putativeSignature.length > 88
205
+ ) {
206
+ throw new Error("Expected input string to decode to a byte array of length 64.");
207
+ }
208
+ const bytes = base58Encoder.encode(putativeSignature);
209
+ const numBytes = bytes.byteLength;
210
+ if (numBytes !== 64) {
211
+ throw new Error(`Expected input string to decode to a byte array of length 64. Actual length: ${numBytes}`);
212
+ }
213
+ } catch (e2) {
214
+ throw new Error(`\`${putativeSignature}\` is not a signature`, {
215
+ cause: e2
216
+ });
217
+ }
218
+ }
219
+ function isSignature(putativeSignature) {
220
+ if (!base58Encoder)
221
+ base58Encoder = getBase58Encoder();
222
+ if (
223
+ // Lowest value (64 bytes of zeroes)
224
+ putativeSignature.length < 64 || // Highest value (64 bytes of 255)
225
+ putativeSignature.length > 88
226
+ ) {
227
+ return false;
228
+ }
229
+ const bytes = base58Encoder.encode(putativeSignature);
230
+ const numBytes = bytes.byteLength;
231
+ if (numBytes !== 64) {
232
+ return false;
233
+ }
234
+ return true;
235
+ }
76
236
  async function signBytes(key, data) {
77
237
  await assertSigningCapabilityIsAvailable();
78
238
  const signedData = await crypto.subtle.sign("Ed25519", key, data);
79
239
  return new Uint8Array(signedData);
80
240
  }
81
- async function verifySignature(key, signature, data) {
241
+ function signature(putativeSignature) {
242
+ assertIsSignature(putativeSignature);
243
+ return putativeSignature;
244
+ }
245
+ async function verifySignature(key, signature2, data) {
82
246
  await assertVerificationCapabilityIsAvailable();
83
- return await crypto.subtle.verify("Ed25519", key, signature, data);
247
+ return await crypto.subtle.verify("Ed25519", key, signature2, data);
84
248
  }
85
249
 
250
+ exports.assertIsSignature = assertIsSignature;
251
+ exports.createPrivateKeyFromBytes = createPrivateKeyFromBytes;
86
252
  exports.generateKeyPair = generateKeyPair;
253
+ exports.isSignature = isSignature;
87
254
  exports.signBytes = signBytes;
255
+ exports.signature = signature;
88
256
  exports.verifySignature = verifySignature;
89
257
 
90
258
  return exports;