@pezkuwi/keyring 14.0.22 → 14.0.23

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.
Files changed (178) hide show
  1. package/build/LICENSE +201 -0
  2. package/build/README.md +17 -0
  3. package/build/bundle.d.ts +7 -0
  4. package/build/bundle.js +7 -0
  5. package/build/cjs/bundle.d.ts +7 -0
  6. package/build/cjs/bundle.js +19 -0
  7. package/build/cjs/defaults.d.ts +2 -0
  8. package/build/cjs/defaults.js +5 -0
  9. package/build/cjs/index.d.ts +4 -0
  10. package/build/cjs/index.js +7 -0
  11. package/build/cjs/keyring.d.ts +145 -0
  12. package/build/cjs/keyring.js +261 -0
  13. package/build/cjs/package.json +3 -0
  14. package/build/cjs/packageDetect.d.ts +1 -0
  15. package/build/cjs/packageDetect.js +7 -0
  16. package/build/cjs/packageInfo.d.ts +6 -0
  17. package/build/cjs/packageInfo.js +4 -0
  18. package/build/cjs/pair/decode.d.ts +12 -0
  19. package/build/cjs/pair/decode.js +45 -0
  20. package/build/cjs/pair/defaults.d.ts +12 -0
  21. package/build/cjs/pair/defaults.js +15 -0
  22. package/build/cjs/pair/encode.d.ts +5 -0
  23. package/build/cjs/pair/encode.js +22 -0
  24. package/build/cjs/pair/index.d.ts +40 -0
  25. package/build/cjs/pair/index.js +183 -0
  26. package/build/cjs/pair/nobody.d.ts +2 -0
  27. package/build/cjs/pair/nobody.js +43 -0
  28. package/build/cjs/pair/toJson.d.ts +8 -0
  29. package/build/cjs/pair/toJson.js +11 -0
  30. package/build/cjs/pair/types.d.ts +5 -0
  31. package/build/cjs/pair/types.js +2 -0
  32. package/build/cjs/pairs.d.ts +8 -0
  33. package/build/cjs/pairs.js +28 -0
  34. package/build/cjs/testing.d.ts +20 -0
  35. package/build/cjs/testing.js +126 -0
  36. package/build/cjs/testingPairs.d.ts +25 -0
  37. package/build/cjs/testingPairs.js +16 -0
  38. package/build/cjs/types.d.ts +111 -0
  39. package/build/cjs/types.js +2 -0
  40. package/build/defaults.d.ts +2 -0
  41. package/build/defaults.js +2 -0
  42. package/build/index.d.ts +4 -0
  43. package/build/index.js +4 -0
  44. package/build/keyring.d.ts +145 -0
  45. package/build/keyring.js +257 -0
  46. package/build/package.json +294 -0
  47. package/build/packageDetect.d.ts +1 -0
  48. package/build/packageDetect.js +5 -0
  49. package/build/packageInfo.d.ts +6 -0
  50. package/build/packageInfo.js +1 -0
  51. package/build/pair/decode.d.ts +12 -0
  52. package/build/pair/decode.js +42 -0
  53. package/build/pair/defaults.d.ts +12 -0
  54. package/build/pair/defaults.js +12 -0
  55. package/build/pair/encode.d.ts +5 -0
  56. package/build/pair/encode.js +19 -0
  57. package/build/pair/index.d.ts +40 -0
  58. package/build/pair/index.js +180 -0
  59. package/build/pair/nobody.d.ts +2 -0
  60. package/build/pair/nobody.js +40 -0
  61. package/build/pair/toJson.d.ts +8 -0
  62. package/build/pair/toJson.js +8 -0
  63. package/build/pair/types.d.ts +5 -0
  64. package/build/pair/types.js +1 -0
  65. package/build/pairs.d.ts +8 -0
  66. package/build/pairs.js +24 -0
  67. package/build/testing.d.ts +20 -0
  68. package/build/testing.js +122 -0
  69. package/build/testingPairs.d.ts +25 -0
  70. package/build/testingPairs.js +13 -0
  71. package/build/types.d.ts +111 -0
  72. package/build/types.js +1 -0
  73. package/build-deno/README.md +17 -0
  74. package/build-deno/bundle.ts +10 -0
  75. package/build-deno/defaults.ts +4 -0
  76. package/build-deno/index.ts +8 -0
  77. package/build-deno/keyring.ts +305 -0
  78. package/build-deno/mod.ts +2 -0
  79. package/build-deno/packageDetect.ts +9 -0
  80. package/build-deno/packageInfo.ts +3 -0
  81. package/build-deno/pair/decode.ts +54 -0
  82. package/build-deno/pair/defaults.ts +18 -0
  83. package/build-deno/pair/encode.ts +28 -0
  84. package/build-deno/pair/index.ts +218 -0
  85. package/build-deno/pair/nobody.ts +58 -0
  86. package/build-deno/pair/toJson.ts +18 -0
  87. package/build-deno/pair/types.ts +6 -0
  88. package/build-deno/pairs.ts +39 -0
  89. package/build-deno/testing.ts +150 -0
  90. package/build-deno/testingPairs.ts +54 -0
  91. package/build-deno/types.ts +129 -0
  92. package/build-tsc/bundle.d.ts +7 -0
  93. package/build-tsc/defaults.d.ts +2 -0
  94. package/build-tsc/index.d.ts +4 -0
  95. package/build-tsc/keyring.d.ts +145 -0
  96. package/build-tsc/packageDetect.d.ts +1 -0
  97. package/build-tsc/packageInfo.d.ts +6 -0
  98. package/build-tsc/pair/decode.d.ts +12 -0
  99. package/build-tsc/pair/defaults.d.ts +12 -0
  100. package/build-tsc/pair/encode.d.ts +5 -0
  101. package/build-tsc/pair/index.d.ts +40 -0
  102. package/build-tsc/pair/nobody.d.ts +2 -0
  103. package/build-tsc/pair/toJson.d.ts +8 -0
  104. package/build-tsc/pair/types.d.ts +5 -0
  105. package/build-tsc/pairs.d.ts +8 -0
  106. package/build-tsc/testing.d.ts +20 -0
  107. package/build-tsc/testingPairs.d.ts +25 -0
  108. package/build-tsc/types.d.ts +111 -0
  109. package/build-tsc-cjs/bundle.js +19 -0
  110. package/build-tsc-cjs/defaults.js +5 -0
  111. package/build-tsc-cjs/index.js +7 -0
  112. package/build-tsc-cjs/keyring.js +261 -0
  113. package/build-tsc-cjs/packageDetect.js +7 -0
  114. package/build-tsc-cjs/packageInfo.js +4 -0
  115. package/build-tsc-cjs/pair/decode.js +45 -0
  116. package/build-tsc-cjs/pair/defaults.js +15 -0
  117. package/build-tsc-cjs/pair/encode.js +22 -0
  118. package/build-tsc-cjs/pair/index.js +183 -0
  119. package/build-tsc-cjs/pair/nobody.js +43 -0
  120. package/build-tsc-cjs/pair/toJson.js +11 -0
  121. package/build-tsc-cjs/pair/types.js +2 -0
  122. package/build-tsc-cjs/pairs.js +28 -0
  123. package/build-tsc-cjs/testing.js +126 -0
  124. package/build-tsc-cjs/testingPairs.js +16 -0
  125. package/build-tsc-cjs/types.js +2 -0
  126. package/build-tsc-esm/bundle.js +7 -0
  127. package/build-tsc-esm/defaults.js +2 -0
  128. package/build-tsc-esm/index.js +4 -0
  129. package/build-tsc-esm/keyring.js +257 -0
  130. package/build-tsc-esm/packageDetect.js +5 -0
  131. package/build-tsc-esm/packageInfo.js +1 -0
  132. package/build-tsc-esm/pair/decode.js +42 -0
  133. package/build-tsc-esm/pair/defaults.js +12 -0
  134. package/build-tsc-esm/pair/encode.js +19 -0
  135. package/build-tsc-esm/pair/index.js +180 -0
  136. package/build-tsc-esm/pair/nobody.js +40 -0
  137. package/build-tsc-esm/pair/toJson.js +8 -0
  138. package/build-tsc-esm/pair/types.js +1 -0
  139. package/build-tsc-esm/pairs.js +24 -0
  140. package/build-tsc-esm/testing.js +122 -0
  141. package/build-tsc-esm/testingPairs.js +13 -0
  142. package/build-tsc-esm/types.js +1 -0
  143. package/bundle-pezkuwi-keyring.js +1 -1
  144. package/cjs/packageInfo.js +1 -1
  145. package/cjs/pair/defaults.d.ts +2 -2
  146. package/package.json +11 -11
  147. package/packageInfo.js +1 -1
  148. package/pair/defaults.d.ts +2 -2
  149. package/src/bundle.ts +16 -0
  150. package/src/defaults.ts +8 -0
  151. package/src/index.spec.ts +609 -0
  152. package/src/index.ts +10 -0
  153. package/src/keyring.ts +307 -0
  154. package/src/mod.ts +4 -0
  155. package/src/packageDetect.ts +13 -0
  156. package/src/packageInfo.ts +6 -0
  157. package/src/pair/decode.spec.ts +26 -0
  158. package/src/pair/decode.ts +56 -0
  159. package/src/pair/defaults.ts +20 -0
  160. package/src/pair/encode.spec.ts +28 -0
  161. package/src/pair/encode.ts +30 -0
  162. package/src/pair/index.spec.ts +189 -0
  163. package/src/pair/index.ts +220 -0
  164. package/src/pair/nobody.ts +62 -0
  165. package/src/pair/toJson.spec.ts +42 -0
  166. package/src/pair/toJson.ts +20 -0
  167. package/src/pair/types.ts +8 -0
  168. package/src/pair/vrf.spec.ts +47 -0
  169. package/src/pairs.ts +41 -0
  170. package/src/suri.spec.ts +109 -0
  171. package/src/testing.ts +156 -0
  172. package/src/testingPairs.spec.ts +79 -0
  173. package/src/testingPairs.ts +56 -0
  174. package/src/types.ts +131 -0
  175. package/tsconfig.build.json +16 -0
  176. package/tsconfig.build.tsbuildinfo +1 -0
  177. package/tsconfig.spec.json +18 -0
  178. package/tsconfig.spec.tsbuildinfo +1 -0
@@ -0,0 +1,10 @@
1
+
2
+ export { decodeAddress, encodeAddress, setSS58Format } from 'https://deno.land/x/pezkuwi/util-crypto/mod.ts';
3
+
4
+ export { Keyring } from './keyring.ts';
5
+ export { packageInfo } from './packageInfo.ts';
6
+ export { createPair } from './pair/index.ts';
7
+ export { createTestKeyring } from './testing.ts';
8
+ export { createTestPairs } from './testingPairs.ts';
9
+
10
+ export * from './defaults.ts';
@@ -0,0 +1,4 @@
1
+
2
+ export const DEV_PHRASE = 'bottom drive obey lake curtain smoke basket hold race lonely fit walk';
3
+
4
+ export const DEV_SEED = '0xfac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e';
@@ -0,0 +1,8 @@
1
+
2
+ import './packageDetect.ts';
3
+
4
+ import { Keyring } from './bundle.ts';
5
+
6
+ export * from './bundle.ts';
7
+
8
+ export default Keyring;
@@ -0,0 +1,305 @@
1
+
2
+ import type { EncryptedJsonEncoding, Keypair, KeypairType } from 'https://deno.land/x/pezkuwi/util-crypto/types.ts';
3
+ import type { KeyringInstance, KeyringOptions, KeyringPair, KeyringPair$Json, KeyringPair$Meta } from './types.ts';
4
+
5
+ import { hexToU8a, isHex, stringToU8a } from 'https://deno.land/x/pezkuwi/util/mod.ts';
6
+ import { base64Decode, decodeAddress, ed25519PairFromSeed as ed25519FromSeed, encodeAddress, ethereumEncode, hdEthereum, keyExtractSuri, keyFromPath, mnemonicToLegacySeed, mnemonicToMiniSecret, secp256k1PairFromSeed as secp256k1FromSeed, sr25519PairFromSeed as sr25519FromSeed } from 'https://deno.land/x/pezkuwi/util-crypto/mod.ts';
7
+
8
+ import { createPair } from './pair/index.ts';
9
+ import { DEV_PHRASE } from './defaults.ts';
10
+ import { Pairs } from './pairs.ts';
11
+
12
+ const PairFromSeed = {
13
+ ecdsa: (seed: Uint8Array): Keypair => secp256k1FromSeed(seed),
14
+ ed25519: (seed: Uint8Array): Keypair => ed25519FromSeed(seed),
15
+ ethereum: (seed: Uint8Array): Keypair => secp256k1FromSeed(seed),
16
+ sr25519: (seed: Uint8Array): Keypair => sr25519FromSeed(seed)
17
+ };
18
+
19
+ function pairToPublic ({ publicKey }: KeyringPair): Uint8Array {
20
+ return publicKey;
21
+ }
22
+
23
+ /**
24
+ * # @pezkuwi/keyring
25
+ *
26
+ * ## Overview
27
+ *
28
+ * @name Keyring
29
+ * @summary Keyring management of user accounts
30
+ * @description Allows generation of keyring pairs from a variety of input combinations, such as
31
+ * json object containing account address or public key, account metadata, and account encoded using
32
+ * `addFromJson`, or by providing those values as arguments separately to `addFromAddress`,
33
+ * or by providing the mnemonic (seed phrase) and account metadata as arguments to `addFromMnemonic`.
34
+ * Stores the keyring pairs in a keyring pair dictionary. Removal of the keyring pairs from the keyring pair
35
+ * dictionary is achieved using `removePair`. Retrieval of all the stored pairs via `getPairs` or perform
36
+ * lookup of a pair for a given account address or public key using `getPair`. JSON metadata associated with
37
+ * an account may be obtained using `toJson` accompanied by the account passphrase.
38
+ */
39
+ export class Keyring implements KeyringInstance {
40
+ readonly #pairs: Pairs;
41
+
42
+ readonly #type: KeypairType;
43
+
44
+ #ss58?: number | undefined;
45
+
46
+ public decodeAddress = decodeAddress;
47
+
48
+ constructor (options: KeyringOptions = {}) {
49
+ options.type = options.type || 'ed25519';
50
+
51
+ if (!['ecdsa', 'ethereum', 'ed25519', 'sr25519'].includes(options.type || 'undefined')) {
52
+ throw new Error(`Expected a keyring type of either 'ed25519', 'sr25519', 'ethereum' or 'ecdsa', found '${options.type || 'unknown'}`);
53
+ }
54
+
55
+ this.#pairs = new Pairs();
56
+ this.#ss58 = options.ss58Format;
57
+ this.#type = options.type;
58
+ }
59
+
60
+ /**
61
+ * @description retrieve the pairs (alias for getPairs)
62
+ */
63
+ public get pairs (): KeyringPair[] {
64
+ return this.getPairs();
65
+ }
66
+
67
+ /**
68
+ * @description retrieve the publicKeys (alias for getPublicKeys)
69
+ */
70
+ public get publicKeys (): Uint8Array[] {
71
+ return this.getPublicKeys();
72
+ }
73
+
74
+ /**
75
+ * @description Returns the type of the keyring, ed25519, sr25519 or ecdsa
76
+ */
77
+ public get type (): KeypairType {
78
+ return this.#type;
79
+ }
80
+
81
+ /**
82
+ * @name addPair
83
+ * @summary Stores an account, given a keyring pair, as a Key/Value (public key, pair) in Keyring Pair Dictionary
84
+ */
85
+ public addPair (pair: KeyringPair): KeyringPair {
86
+ return this.#pairs.add(pair);
87
+ }
88
+
89
+ /**
90
+ * @name addFromAddress
91
+ * @summary Stores an account, given an account address, as a Key/Value (public key, pair) in Keyring Pair Dictionary
92
+ * @description Allows user to explicitly provide separate inputs including account address or public key, and optionally
93
+ * the associated account metadata, and the default encoded value as arguments (that may be obtained from the json file
94
+ * of an account backup), and then generates a keyring pair from them that it passes to
95
+ * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
96
+ */
97
+ public addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, type: KeypairType = this.type, ignoreChecksum?: boolean, encType?: EncryptedJsonEncoding[]): KeyringPair {
98
+ const publicKey = this.decodeAddress(address, ignoreChecksum);
99
+
100
+ return this.addPair(createPair({ toSS58: this.encodeAddress, type }, { publicKey, secretKey: new Uint8Array() }, meta, encoded, encType));
101
+ }
102
+
103
+ /**
104
+ * @name addFromJson
105
+ * @summary Stores an account, given JSON data, as a Key/Value (public key, pair) in Keyring Pair Dictionary
106
+ * @description Allows user to provide a json object argument that contains account information (that may be obtained from the json file
107
+ * of an account backup), and then generates a keyring pair from it that it passes to
108
+ * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
109
+ */
110
+ public addFromJson (json: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair {
111
+ return this.addPair(this.createFromJson(json, ignoreChecksum));
112
+ }
113
+
114
+ /**
115
+ * @name addFromMnemonic
116
+ * @summary Stores an account, given a mnemonic, as a Key/Value (public key, pair) in Keyring Pair Dictionary
117
+ * @description Allows user to provide a mnemonic (seed phrase that is provided when account is originally created)
118
+ * argument and a metadata argument that contains account information (that may be obtained from the json file
119
+ * of an account backup), and then generates a keyring pair from it that it passes to
120
+ * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
121
+ */
122
+ public addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type, wordlist?: string[]): KeyringPair {
123
+ return this.addFromUri(mnemonic, meta, type, wordlist);
124
+ }
125
+
126
+ /**
127
+ * @name addFromPair
128
+ * @summary Stores an account created from an explicit publicKey/secreteKey combination
129
+ */
130
+ public addFromPair (pair: Keypair, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
131
+ return this.addPair(
132
+ this.createFromPair(pair, meta, type)
133
+ );
134
+ }
135
+
136
+ /**
137
+ * @name addFromSeed
138
+ * @summary Stores an account, given seed data, as a Key/Value (public key, pair) in Keyring Pair Dictionary
139
+ * @description Stores in a keyring pair dictionary the public key of the pair as a key and the pair as the associated value.
140
+ * Allows user to provide the account seed as an argument, and then generates a keyring pair from it that it passes to
141
+ * `addPair` to store in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value.
142
+ */
143
+ public addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
144
+ return this.addPair(
145
+ createPair({ toSS58: this.encodeAddress, type }, PairFromSeed[type](seed), meta, null)
146
+ );
147
+ }
148
+
149
+ /**
150
+ * @name addFromUri
151
+ * @summary Creates an account via an suri
152
+ * @description Extracts the phrase, path and password from a SURI format for specifying secret keys `<secret>/<soft-key>//<hard-key>///<password>` (the `///password` may be omitted, and `/<soft-key>` and `//<hard-key>` maybe repeated and mixed). The secret can be a hex string, mnemonic phrase or a string (to be padded)
153
+ */
154
+ public addFromUri (suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type, wordlist?: string[]): KeyringPair {
155
+ return this.addPair(
156
+ this.createFromUri(suri, meta, type, wordlist)
157
+ );
158
+ }
159
+
160
+ /**
161
+ * @name createFromJson
162
+ * @description Creates a pair from a JSON keyfile
163
+ */
164
+ public createFromJson ({ address, encoded, encoding: { content, type, version }, meta }: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair {
165
+ if (version === '3' && content[0] !== 'pkcs8') {
166
+ throw new Error(`Unable to decode non-pkcs8 type, [${content.join(',')}] found}`);
167
+ }
168
+
169
+ const cryptoType = version === '0' || !Array.isArray(content)
170
+ ? this.type
171
+ : content[1];
172
+ const encType = !Array.isArray(type)
173
+ ? [type]
174
+ : type;
175
+
176
+ if (!['ed25519', 'sr25519', 'ecdsa', 'ethereum'].includes(cryptoType)) {
177
+ throw new Error(`Unknown crypto type ${cryptoType}`);
178
+ }
179
+
180
+ // Here the address and publicKey are 32 bytes and isomorphic. This is why the address field needs to be the public key for ethereum type pairs
181
+ const publicKey = isHex(address)
182
+ ? hexToU8a(address)
183
+ : this.decodeAddress(address, ignoreChecksum);
184
+ const decoded = isHex(encoded)
185
+ ? hexToU8a(encoded)
186
+ : base64Decode(encoded);
187
+
188
+ return createPair({ toSS58: this.encodeAddress, type: cryptoType as KeypairType }, { publicKey, secretKey: new Uint8Array() }, meta, decoded, encType);
189
+ }
190
+
191
+ /**
192
+ * @name createFromPair
193
+ * @summary Creates a pair from an explicit publicKey/secreteKey combination
194
+ */
195
+ public createFromPair (pair: Keypair, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
196
+ return createPair({ toSS58: this.encodeAddress, type }, pair, meta, null);
197
+ }
198
+
199
+ /**
200
+ * @name createFromUri
201
+ * @summary Creates a Keypair from an suri
202
+ * @description This creates a pair from the suri, but does not add it to the keyring
203
+ */
204
+ public createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type, wordlist?: string[]): KeyringPair {
205
+ // here we only aut-add the dev phrase if we have a hard-derived path
206
+ const suri = _suri.startsWith('//')
207
+ ? `${DEV_PHRASE}${_suri}`
208
+ : _suri;
209
+ const { derivePath, password, path, phrase } = keyExtractSuri(suri);
210
+ let seed: Uint8Array;
211
+ const isPhraseHex = isHex(phrase, 256);
212
+
213
+ if (isPhraseHex) {
214
+ seed = hexToU8a(phrase);
215
+ } else {
216
+ const parts = phrase.split(' ');
217
+
218
+ if ([12, 15, 18, 21, 24].includes(parts.length)) {
219
+ seed = type === 'ethereum'
220
+ ? mnemonicToLegacySeed(phrase, '', false, 64)
221
+ : mnemonicToMiniSecret(phrase, password, wordlist);
222
+ } else {
223
+ if (phrase.length > 32) {
224
+ throw new Error('specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
225
+ }
226
+
227
+ seed = stringToU8a(phrase.padEnd(32));
228
+ }
229
+ }
230
+
231
+ const derived = type === 'ethereum'
232
+ ? isPhraseHex
233
+ ? PairFromSeed[type](seed) // for eth, if the private key is provided as suri, it must be derived only once
234
+ : hdEthereum(seed, derivePath.substring(1))
235
+ : keyFromPath(PairFromSeed[type](seed), path, type);
236
+
237
+ return createPair({ toSS58: this.encodeAddress, type }, derived, meta, null);
238
+ }
239
+
240
+ /**
241
+ * @name encodeAddress
242
+ * @description Encodes the input into an ss58 representation
243
+ */
244
+ public encodeAddress = (address: Uint8Array | string, ss58Format?: number): string => {
245
+ return this.type === 'ethereum'
246
+ ? ethereumEncode(address)
247
+ : encodeAddress(address, ss58Format ?? this.#ss58);
248
+ };
249
+
250
+ /**
251
+ * @name getPair
252
+ * @summary Retrieves an account keyring pair from the Keyring Pair Dictionary, given an account address
253
+ * @description Returns a keyring pair value from the keyring pair dictionary by performing
254
+ * a key lookup using the provided account address or public key (after decoding it).
255
+ */
256
+ public getPair (address: string | Uint8Array): KeyringPair {
257
+ return this.#pairs.get(address);
258
+ }
259
+
260
+ /**
261
+ * @name getPairs
262
+ * @summary Retrieves all account keyring pairs from the Keyring Pair Dictionary
263
+ * @description Returns an array list of all the keyring pair values that are stored in the keyring pair dictionary.
264
+ */
265
+ public getPairs (): KeyringPair[] {
266
+ return this.#pairs.all();
267
+ }
268
+
269
+ /**
270
+ * @name getPublicKeys
271
+ * @summary Retrieves Public Keys of all Keyring Pairs stored in the Keyring Pair Dictionary
272
+ * @description Returns an array list of all the public keys associated with each of the keyring pair values that are stored in the keyring pair dictionary.
273
+ */
274
+ public getPublicKeys (): Uint8Array[] {
275
+ return this.#pairs.all().map(pairToPublic);
276
+ }
277
+
278
+ /**
279
+ * @name removePair
280
+ * @description Deletes the provided input address or public key from the stored Keyring Pair Dictionary.
281
+ */
282
+ public removePair (address: string | Uint8Array): void {
283
+ this.#pairs.remove(address);
284
+ }
285
+
286
+ /**
287
+ * @name setSS58Format;
288
+ * @description Sets the ss58 format for the keyring
289
+ */
290
+ public setSS58Format (ss58: number): void {
291
+ this.#ss58 = ss58;
292
+ }
293
+
294
+ /**
295
+ * @name toJson
296
+ * @summary Returns a JSON object associated with the input argument that contains metadata assocated with an account
297
+ * @description Returns a JSON object containing the metadata associated with an account
298
+ * when valid address or public key and when the account passphrase is provided if the account secret
299
+ * is not already unlocked and available in memory. Note that in [Polkadot-JS Apps](https://github.com/polkadot-js/apps) the user
300
+ * may backup their account to a JSON file that contains this information.
301
+ */
302
+ public toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json {
303
+ return this.#pairs.get(address).toJson(passphrase);
304
+ }
305
+ }
@@ -0,0 +1,2 @@
1
+
2
+ export * from './index.ts';
@@ -0,0 +1,9 @@
1
+
2
+
3
+ import { detectPackage } from 'https://deno.land/x/pezkuwi/util/mod.ts';
4
+ import { packageInfo as utilInfo } from 'https://deno.land/x/pezkuwi/util/packageInfo.ts';
5
+ import { packageInfo as cryptoInfo } from 'https://deno.land/x/pezkuwi/util-crypto/packageInfo.ts';
6
+
7
+ import { packageInfo } from './packageInfo.ts';
8
+
9
+ detectPackage(packageInfo, null, [cryptoInfo, utilInfo]);
@@ -0,0 +1,3 @@
1
+
2
+
3
+ export const packageInfo = { name: '@pezkuwi/keyring', path: new URL(import.meta.url).pathname, type: 'deno', version: '14.0.23' };
@@ -0,0 +1,54 @@
1
+
2
+ import type { EncryptedJsonEncoding } from 'https://deno.land/x/pezkuwi/util-crypto/types.ts';
3
+
4
+ import { u8aEq } from 'https://deno.land/x/pezkuwi/util/mod.ts';
5
+ import { jsonDecryptData } from 'https://deno.land/x/pezkuwi/util-crypto/mod.ts';
6
+
7
+ import { PAIR_DIV, PAIR_HDR, PUB_LENGTH, SEC_LENGTH, SEED_LENGTH } from './defaults.ts';
8
+
9
+ const SEED_OFFSET = PAIR_HDR.length;
10
+
11
+ /**
12
+ * Decode a pair, taking into account the generation-specific formats and headers
13
+ *
14
+ * For divisor/headers, don't rely on the magic being static. These will
15
+ * change between generations, aka with the long-awaited 4th generation
16
+ * of the format. The external decode interface is the only way to use and decode these.
17
+ **/
18
+ export function decodePair (passphrase?: string, encrypted?: Uint8Array | null, _encType?: EncryptedJsonEncoding | EncryptedJsonEncoding[]): { publicKey: Uint8Array; secretKey: Uint8Array } {
19
+ const encType = Array.isArray(_encType) || _encType === undefined
20
+ ? _encType
21
+ : [_encType];
22
+ const decrypted = jsonDecryptData(encrypted, passphrase, encType);
23
+ const header = decrypted.subarray(0, PAIR_HDR.length);
24
+
25
+ // check the start header (generations 1-3)
26
+ if (!u8aEq(header, PAIR_HDR)) {
27
+ throw new Error('Invalid encoding header found in body');
28
+ }
29
+
30
+ // setup for generation 3 format
31
+ let secretKey = decrypted.subarray(SEED_OFFSET, SEED_OFFSET + SEC_LENGTH);
32
+ let divOffset = SEED_OFFSET + SEC_LENGTH;
33
+ let divider = decrypted.subarray(divOffset, divOffset + PAIR_DIV.length);
34
+
35
+ // old-style (generation 1 & 2), we have the seed here
36
+ if (!u8aEq(divider, PAIR_DIV)) {
37
+ divOffset = SEED_OFFSET + SEED_LENGTH;
38
+ secretKey = decrypted.subarray(SEED_OFFSET, divOffset);
39
+ divider = decrypted.subarray(divOffset, divOffset + PAIR_DIV.length);
40
+
41
+ // check the divisior at this point (already checked for generation 3)
42
+ if (!u8aEq(divider, PAIR_DIV)) {
43
+ throw new Error('Invalid encoding divider found in body');
44
+ }
45
+ }
46
+
47
+ const pubOffset = divOffset + PAIR_DIV.length;
48
+ const publicKey = decrypted.subarray(pubOffset, pubOffset + PUB_LENGTH);
49
+
50
+ return {
51
+ publicKey,
52
+ secretKey
53
+ };
54
+ }
@@ -0,0 +1,18 @@
1
+
2
+ /** public/secret section divider (generation 1-3, will change in 4, don't rely on value) */
3
+ export const PAIR_DIV = new Uint8Array([161, 35, 3, 33, 0]);
4
+
5
+ /** public/secret start block (generation 1-3, will change in 4, don't rely on value) */
6
+ export const PAIR_HDR = new Uint8Array([48, 83, 2, 1, 1, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32]);
7
+
8
+ /** length of a public key */
9
+ export const PUB_LENGTH = 32;
10
+
11
+ /** length of a salt */
12
+ export const SALT_LENGTH = 32;
13
+
14
+ /** length of a secret key */
15
+ export const SEC_LENGTH = 64;
16
+
17
+ /** length of a user-input seed */
18
+ export const SEED_LENGTH = 32;
@@ -0,0 +1,28 @@
1
+
2
+ import type { PairInfo } from './types.ts';
3
+
4
+ import { u8aConcat } from 'https://deno.land/x/pezkuwi/util/mod.ts';
5
+ import { naclEncrypt, scryptEncode, scryptToU8a } from 'https://deno.land/x/pezkuwi/util-crypto/mod.ts';
6
+
7
+ import { PAIR_DIV, PAIR_HDR } from './defaults.ts';
8
+
9
+ /**
10
+ * Encode a pair with the latest generation format (generation 3)
11
+ **/
12
+ export function encodePair ({ publicKey, secretKey }: PairInfo, passphrase?: string): Uint8Array {
13
+ if (!secretKey) {
14
+ throw new Error('Expected a valid secretKey to be passed to encode');
15
+ }
16
+
17
+ const encoded = u8aConcat(PAIR_HDR, secretKey, PAIR_DIV, publicKey);
18
+
19
+ if (!passphrase) {
20
+ return encoded;
21
+ }
22
+
23
+ // this is only for generation 3 (previous generations are only handled in decoding)
24
+ const { params, password, salt } = scryptEncode(passphrase);
25
+ const { encrypted, nonce } = naclEncrypt(encoded, password.subarray(0, 32));
26
+
27
+ return u8aConcat(scryptToU8a(salt, params), nonce, encrypted);
28
+ }
@@ -0,0 +1,218 @@
1
+
2
+ import type { EncryptedJsonEncoding, Keypair, KeypairType } from 'https://deno.land/x/pezkuwi/util-crypto/types.ts';
3
+ import type { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types.ts';
4
+ import type { PairInfo } from './types.ts';
5
+
6
+ import { objectSpread, u8aConcat, u8aEmpty, u8aEq, u8aToHex, u8aToU8a } from 'https://deno.land/x/pezkuwi/util/mod.ts';
7
+ import { blake2AsU8a, ed25519PairFromSeed as ed25519FromSeed, ed25519Sign, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, secp256k1Compress, secp256k1Expand, secp256k1PairFromSeed as secp256k1FromSeed, secp256k1Sign, signatureVerify, sr25519PairFromSeed as sr25519FromSeed, sr25519Sign, sr25519VrfSign, sr25519VrfVerify } from 'https://deno.land/x/pezkuwi/util-crypto/mod.ts';
8
+
9
+ import { decodePair } from './decode.ts';
10
+ import { encodePair } from './encode.ts';
11
+ import { pairToJson } from './toJson.ts';
12
+
13
+ interface Setup {
14
+ toSS58: (publicKey: Uint8Array) => string;
15
+ type: KeypairType;
16
+ }
17
+
18
+ const SIG_TYPE_NONE = new Uint8Array();
19
+
20
+ const TYPE_FROM_SEED = {
21
+ ecdsa: secp256k1FromSeed,
22
+ ed25519: ed25519FromSeed,
23
+ ethereum: secp256k1FromSeed,
24
+ sr25519: sr25519FromSeed
25
+ };
26
+
27
+ const TYPE_PREFIX = {
28
+ ecdsa: new Uint8Array([2]),
29
+ ed25519: new Uint8Array([0]),
30
+ ethereum: new Uint8Array([2]),
31
+ sr25519: new Uint8Array([1])
32
+ };
33
+
34
+ const TYPE_SIGNATURE = {
35
+ ecdsa: (m: Uint8Array, p: Partial<Keypair>) => secp256k1Sign(m, p, 'blake2'),
36
+ ed25519: ed25519Sign,
37
+ ethereum: (m: Uint8Array, p: Partial<Keypair>) => secp256k1Sign(m, p, 'keccak'),
38
+ sr25519: sr25519Sign
39
+ };
40
+
41
+ const TYPE_ADDRESS = {
42
+ ecdsa: (p: Uint8Array) => p.length > 32 ? blake2AsU8a(p) : p,
43
+ ed25519: (p: Uint8Array) => p,
44
+ ethereum: (p: Uint8Array) => p.length === 20 ? p : keccakAsU8a(secp256k1Expand(p)),
45
+ sr25519: (p: Uint8Array) => p
46
+ };
47
+
48
+ function isLocked (secretKey?: Uint8Array): secretKey is undefined {
49
+ return !secretKey || u8aEmpty(secretKey);
50
+ }
51
+
52
+ function vrfHash (proof: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array {
53
+ return blake2AsU8a(u8aConcat(context || '', extra || '', proof));
54
+ }
55
+
56
+ /**
57
+ * @name createPair
58
+ * @summary Creates a keyring pair object
59
+ * @description Creates a keyring pair object with provided account public key, metadata, and encoded arguments.
60
+ * The keyring pair stores the account state including the encoded address and associated metadata.
61
+ *
62
+ * It has properties whose values are functions that may be called to perform account actions:
63
+ *
64
+ * - `address` function retrieves the address associated with the account.
65
+ * - `decodedPkcs8` function is called with the account passphrase and account encoded public key.
66
+ * It decodes the encoded public key using the passphrase provided to obtain the decoded account public key
67
+ * and associated secret key that are then available in memory, and changes the account address stored in the
68
+ * state of the pair to correspond to the address of the decoded public key.
69
+ * - `encodePkcs8` function when provided with the correct passphrase associated with the account pair
70
+ * and when the secret key is in memory (when the account pair is not locked) it returns an encoded
71
+ * public key of the account.
72
+ * - `meta` is the metadata that is stored in the state of the pair, either when it was originally
73
+ * created or set via `setMeta`.
74
+ * - `publicKey` returns the public key stored in memory for the pair.
75
+ * - `sign` may be used to return a signature by signing a provided message with the secret
76
+ * key (if it is in memory) using Nacl.
77
+ * - `toJson` calls another `toJson` function and provides the state of the pair,
78
+ * it generates arguments to be passed to the other `toJson` function including an encoded public key of the account
79
+ * that it generates using the secret key from memory (if it has been made available in memory)
80
+ * and the optionally provided passphrase argument. It passes a third boolean argument to `toJson`
81
+ * indicating whether the public key has been encoded or not (if a passphrase argument was provided then it is encoded).
82
+ * The `toJson` function that it calls returns a JSON object with properties including the `address`
83
+ * and `meta` that are assigned with the values stored in the corresponding state variables of the account pair,
84
+ * an `encoded` property that is assigned with the encoded public key in hex format, and an `encoding`
85
+ * property that indicates whether the public key value of the `encoded` property is encoded or not.
86
+ */
87
+ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, encTypes?: EncryptedJsonEncoding[]): KeyringPair {
88
+ const decodePkcs8 = (passphrase?: string, userEncoded?: Uint8Array | null): void => {
89
+ const decoded = decodePair(passphrase, userEncoded || encoded, encTypes);
90
+
91
+ if (decoded.secretKey.length === 64) {
92
+ publicKey = decoded.publicKey;
93
+ secretKey = decoded.secretKey;
94
+ } else {
95
+ const pair = TYPE_FROM_SEED[type](decoded.secretKey);
96
+
97
+ publicKey = pair.publicKey;
98
+ secretKey = pair.secretKey;
99
+ }
100
+ };
101
+
102
+ const recode = (passphrase?: string): Uint8Array => {
103
+ isLocked(secretKey) && encoded && decodePkcs8(passphrase, encoded);
104
+
105
+ encoded = encodePair({ publicKey, secretKey }, passphrase); // re-encode, latest version
106
+ encTypes = undefined; // swap to defaults, latest version follows
107
+
108
+ return encoded;
109
+ };
110
+
111
+ const encodeAddress = (): string => {
112
+ const raw = TYPE_ADDRESS[type](publicKey);
113
+
114
+ return type === 'ethereum'
115
+ ? ethereumEncode(raw)
116
+ : toSS58(raw);
117
+ };
118
+
119
+ return {
120
+ get address (): string {
121
+ return encodeAddress();
122
+ },
123
+ get addressRaw (): Uint8Array {
124
+ const raw = TYPE_ADDRESS[type](publicKey);
125
+
126
+ return type === 'ethereum'
127
+ ? raw.slice(-20)
128
+ : raw;
129
+ },
130
+ get isLocked (): boolean {
131
+ return isLocked(secretKey);
132
+ },
133
+ get meta (): KeyringPair$Meta {
134
+ return meta;
135
+ },
136
+ get publicKey (): Uint8Array {
137
+ return publicKey;
138
+ },
139
+ get type (): KeypairType {
140
+ return type;
141
+ },
142
+ // eslint-disable-next-line sort-keys
143
+ decodePkcs8,
144
+ derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair => {
145
+ if (type === 'ethereum') {
146
+ throw new Error('Unable to derive on this keypair');
147
+ } else if (isLocked(secretKey)) {
148
+ throw new Error('Cannot derive on a locked keypair');
149
+ }
150
+
151
+ const { path } = keyExtractPath(suri);
152
+ const derived = keyFromPath({ publicKey, secretKey }, path, type);
153
+
154
+ return createPair({ toSS58, type }, derived, meta, null);
155
+ },
156
+ encodePkcs8: (passphrase?: string): Uint8Array => {
157
+ return recode(passphrase);
158
+ },
159
+ lock: (): void => {
160
+ secretKey = new Uint8Array();
161
+ },
162
+ setMeta: (additional: KeyringPair$Meta): void => {
163
+ meta = objectSpread({}, meta, additional);
164
+ },
165
+ sign: (message: string | Uint8Array, options: SignOptions = {}): Uint8Array => {
166
+ if (isLocked(secretKey)) {
167
+ throw new Error('Cannot sign with a locked key pair');
168
+ }
169
+
170
+ return u8aConcat(
171
+ options.withType
172
+ ? TYPE_PREFIX[type]
173
+ : SIG_TYPE_NONE,
174
+ TYPE_SIGNATURE[type](u8aToU8a(message), { publicKey, secretKey })
175
+ );
176
+ },
177
+ toJson: (passphrase?: string): KeyringPair$Json => {
178
+ // NOTE: For ecdsa and ethereum, the publicKey cannot be extracted from the address. For these
179
+ // pass the hex-encoded publicKey through to the address portion of the JSON (before decoding)
180
+ // unless the publicKey is already an address
181
+ const address = ['ecdsa', 'ethereum'].includes(type)
182
+ ? publicKey.length === 20
183
+ ? u8aToHex(publicKey)
184
+ : u8aToHex(secp256k1Compress(publicKey))
185
+ : encodeAddress();
186
+
187
+ return pairToJson(type, { address, meta }, recode(passphrase), !!passphrase);
188
+ },
189
+ unlock: (passphrase?: string): void => {
190
+ return decodePkcs8(passphrase);
191
+ },
192
+ verify: (message: string | Uint8Array, signature: string | Uint8Array, signerPublic: string | Uint8Array): boolean => {
193
+ return signatureVerify(message, signature, TYPE_ADDRESS[type](u8aToU8a(signerPublic))).isValid;
194
+ },
195
+ vrfSign: (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
196
+ if (isLocked(secretKey)) {
197
+ throw new Error('Cannot sign with a locked key pair');
198
+ }
199
+
200
+ if (type === 'sr25519') {
201
+ return sr25519VrfSign(message, { secretKey }, context, extra);
202
+ }
203
+
204
+ const proof = TYPE_SIGNATURE[type](u8aToU8a(message), { publicKey, secretKey });
205
+
206
+ return u8aConcat(vrfHash(proof, context, extra), proof);
207
+ },
208
+ vrfVerify: (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: Uint8Array | string, context?: string | Uint8Array, extra?: string | Uint8Array): boolean => {
209
+ if (type === 'sr25519') {
210
+ return sr25519VrfVerify(message, vrfResult, publicKey, context, extra);
211
+ }
212
+
213
+ const result = signatureVerify(message, u8aConcat(TYPE_PREFIX[type], vrfResult.subarray(32)), TYPE_ADDRESS[type](u8aToU8a(signerPublic)));
214
+
215
+ return result.isValid && u8aEq(vrfResult.subarray(0, 32), vrfHash(vrfResult.subarray(32), context, extra));
216
+ }
217
+ };
218
+ }