-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
BIP44Node.ts
448 lines (387 loc) · 11.9 KB
/
BIP44Node.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import { assert } from '@metamask/utils';
import type {
BIP44Depth,
PartialHDPathTuple,
RootedSLIP10PathTuple,
SLIP10Path,
} from './constants';
import {
BIP44PurposeNodeToken,
BIP_32_PATH_REGEX,
BIP_39_PATH_REGEX,
MAX_BIP_44_DEPTH,
MIN_BIP_44_DEPTH,
} from './constants';
import type { SupportedCurve } from './curves';
import { decodeExtendedKey, PRIVATE_KEY_VERSION } from './extended-keys';
import { SLIP10Node, validateBIP32Depth } from './SLIP10Node';
import { isHardened } from './utils';
export type BIP44ExtendedKeyOptions = {
readonly depth: number;
readonly parentFingerprint: number;
readonly index: number;
readonly chainCode: Uint8Array | string;
readonly privateKey?: Uint8Array | string | undefined;
readonly publicKey?: Uint8Array | string | undefined;
};
export type BIP44DerivationPathOptions = {
readonly derivationPath: RootedSLIP10PathTuple;
};
/**
* A wrapper for BIP-44 Hierarchical Deterministic (HD) tree nodes, i.e.
* cryptographic keys used to generate keypairs and addresses for cryptocurrency
* protocols.
*/
export type JsonBIP44Node = {
/**
* The 0-indexed BIP-44 path depth of this node.
*
* A BIP-44 path is of the form:
*
* `m / 44' / coin_type' / account' / change / address_index`
*
* With the following depths:
*
* `0 / 1 / 2 / 3 / 4 / 5`
*/
readonly depth: BIP44Depth;
/**
* The fingerprint of the master node, i.e., the node at depth 0. May be
* undefined if this node was created from an extended key.
*/
readonly masterFingerprint?: number | undefined;
/**
* The fingerprint of the parent key, or 0 if this is a master node.
*/
readonly parentFingerprint: number;
/**
* The index of the node, or 0 if this is a master node.
*/
readonly index: number;
/**
* The hexadecimal string representation of the private key for this node.
* May be `undefined` if the node is a public node.
*/
readonly privateKey?: string | undefined;
/**
* The hexadecimal string representation of the public key for this node.
*/
readonly publicKey: string;
/**
* The hexadecimal string representation of the chain code for this node.
*/
readonly chainCode: string;
};
export type BIP44NodeInterface = JsonBIP44Node & {
/**
* @returns A JSON-compatible representation of this node's data fields.
*/
toJSON(): JsonBIP44Node;
};
/**
* A wrapper for BIP-44 Hierarchical Deterministic (HD) tree nodes, i.e.
* cryptographic keys used to generate keypairs and addresses for cryptocurrency
* protocols.
*
* This class contains methods and fields that may not serialize well. Use
* {@link BIP44Node.toJSON} to get a JSON-compatible representation.
*/
export class BIP44Node implements BIP44NodeInterface {
/**
* Wrapper of the {@link fromExtendedKey} function. Refer to that function
* for documentation.
*
* @param json - The JSON representation of a SLIP-10 node.
*/
static async fromJSON(json: JsonBIP44Node): Promise<BIP44Node> {
return BIP44Node.fromExtendedKey(json);
}
/**
* Create a new BIP-44 node from a key and chain code. You must specify
* either a private key or a public key. When specifying a private key,
* the public key will be derived from the private key.
*
* All parameters are stringently validated, and an error is thrown if
* validation fails.
*
* @param options - An object containing the extended key, or an extended
* public (xpub) or private (xprv) key.
* @param options.depth - The depth of the node.
* @param options.privateKey - The private key for the node.
* @param options.publicKey - The public key for the node. If a private key is
* specified, this parameter is ignored.
* @param options.chainCode - The chain code for the node.
*/
static async fromExtendedKey(
options: BIP44ExtendedKeyOptions | string,
): Promise<BIP44Node> {
if (typeof options === 'string') {
const extendedKey = decodeExtendedKey(options);
const { chainCode, depth, parentFingerprint, index } = extendedKey;
if (extendedKey.version === PRIVATE_KEY_VERSION) {
const { privateKey } = extendedKey;
return BIP44Node.fromExtendedKey({
depth,
parentFingerprint,
index,
privateKey,
chainCode,
});
}
const { publicKey } = extendedKey;
return BIP44Node.fromExtendedKey({
depth,
parentFingerprint,
index,
publicKey,
chainCode,
});
}
const {
privateKey,
publicKey,
chainCode,
depth,
parentFingerprint,
index,
} = options;
validateBIP44Depth(depth);
const node = await SLIP10Node.fromExtendedKey({
privateKey,
publicKey,
chainCode,
depth,
parentFingerprint,
index,
curve: 'secp256k1',
});
return new BIP44Node(node);
}
/**
* Create a new BIP-44 node from a derivation path. The derivation path
* must be rooted, i.e. it must begin with a BIP-39 node, given as a string of
* the form `bip39:MNEMONIC`, where `MNEMONIC` is a space-separated list of
* BIP-39 seed phrase words.
*
* All parameters are stringently validated, and an error is thrown if
* validation fails.
*
* Recall that a BIP-44 HD tree path consists of the following nodes:
*
* `m / 44' / coin_type' / account' / change / address_index`
*
* With the following depths:
*
* `0 / 1 / 2 / 3 / 4 / 5`
*
* @param options - An object containing the derivation path.
* @param options.derivationPath - The rooted HD tree path that will be used
* to derive the key of this node.
*/
static async fromDerivationPath({
derivationPath,
}: BIP44DerivationPathOptions): Promise<BIP44Node> {
validateBIP44Depth(derivationPath.length - 1);
validateBIP44DerivationPath(derivationPath, MIN_BIP_44_DEPTH);
const node = await SLIP10Node.fromDerivationPath({
derivationPath,
curve: 'secp256k1',
});
return new BIP44Node(node);
}
#node: SLIP10Node;
public get depth(): BIP44Depth {
return this.#node.depth as BIP44Depth;
}
public get privateKeyBytes(): Uint8Array | undefined {
return this.#node.privateKeyBytes;
}
public get publicKeyBytes(): Uint8Array {
return this.#node.publicKeyBytes;
}
public get chainCodeBytes(): Uint8Array {
return this.#node.chainCodeBytes;
}
public get privateKey(): string | undefined {
return this.#node.privateKey;
}
public get publicKey(): string {
return this.#node.publicKey;
}
public get compressedPublicKey(): string {
return this.#node.compressedPublicKey;
}
public get compressedPublicKeyBytes(): Uint8Array {
return this.#node.compressedPublicKeyBytes;
}
public get chainCode(): string {
return this.#node.chainCode;
}
public get address(): string {
return this.#node.address;
}
public get masterFingerprint(): number | undefined {
return this.#node.masterFingerprint;
}
public get parentFingerprint(): number {
return this.#node.parentFingerprint;
}
public get fingerprint(): number {
return this.#node.fingerprint;
}
public get index(): number {
return this.#node.index;
}
public get extendedKey(): string {
return this.#node.extendedKey;
}
public get curve(): SupportedCurve {
return this.#node.curve;
}
constructor(node: SLIP10Node) {
this.#node = node;
Object.freeze(this);
}
/**
* Get a neutered version of this node, i.e. a node without a private key.
*
* @returns A neutered version of this node.
*/
public neuter(): BIP44Node {
const node = this.#node.neuter();
return new BIP44Node(node);
}
/**
* Derives a child of the key contains be this node and returns a new
* {@link BIP44Node} containing the child key.
*
* The specified path must be a valid HD path from this node, per BIP-44.
* At present, this means that the path must consist of no more than 5 BIP-32
* nodes, depending on the depth of this node.
*
* Recall that a BIP-44 HD tree path consists of the following nodes:
*
* `m / 44' / coin_type' / account' / change / address_index`
*
* With the following depths:
*
* `0 / 1 / 2 / 3 / 4 / 5`
*
* @param path - The partial (non-rooted) BIP-44 HD tree path will be used
* to derive a child key from the parent key contained within this node.
* @returns The {@link BIP44Node} corresponding to the derived child key.
*/
public async derive(path: PartialHDPathTuple): Promise<BIP44Node> {
if (this.depth === MAX_BIP_44_DEPTH) {
throw new Error(
'Illegal operation: This HD tree node is already a leaf node.',
);
}
const newDepth = this.depth + path.length;
validateBIP44Depth(newDepth);
validateBIP44DerivationPath(path, (this.depth + 1) as BIP44Depth);
const node = await this.#node.derive(path);
return new BIP44Node(node);
}
// This is documented in the interface of this class.
public toJSON(): JsonBIP44Node {
return {
depth: this.depth,
masterFingerprint: this.masterFingerprint,
parentFingerprint: this.parentFingerprint,
index: this.index,
privateKey: this.privateKey,
publicKey: this.publicKey,
chainCode: this.chainCode,
};
}
}
/**
* Validates a BIP-44 path depth. Effectively, asserts that the depth is an
* integer `number` N such that 0 <= N <= 5. Throws an error if validation
* fails.
*
* @param depth - The depth to validate.
*/
export function validateBIP44Depth(
depth: unknown,
): asserts depth is BIP44Depth {
validateBIP32Depth(depth);
if (depth < MIN_BIP_44_DEPTH || depth > MAX_BIP_44_DEPTH) {
throw new Error(
`Invalid HD tree path depth: The depth must be a positive integer N such that 0 <= N <= 5. Received: "${depth}"`,
);
}
}
/**
* Ensures that the given derivation is valid by BIP-44.
*
* Recall that a BIP-44 HD tree path consists of the following nodes:
*
* `m / 44' / coin_type' / account' / change / address_index`
*
* With the following depths:
*
* `0 / 1 / 2 / 3 / 4 / 5`
*
* @param path - The path to validate.
* @param startingDepth - The depth of the first node of the derivation path.
*/
function validateBIP44DerivationPath(
path: SLIP10Path,
startingDepth: BIP44Depth,
) {
path.forEach((nodeToken, index) => {
const currentDepth = startingDepth + index;
if (currentDepth === MIN_BIP_44_DEPTH) {
if (
!(nodeToken instanceof Uint8Array) &&
!BIP_39_PATH_REGEX.test(nodeToken)
) {
throw new Error(
'Invalid derivation path: The "m" / seed node (depth 0) must be a BIP-39 node.',
);
}
return;
}
assert(typeof nodeToken === 'string');
// eslint-disable-next-line default-case
switch (currentDepth) {
case 1:
if (nodeToken !== BIP44PurposeNodeToken) {
throw new Error(
`Invalid derivation path: The "purpose" node (depth 1) must be the string "${BIP44PurposeNodeToken}".`,
);
}
break;
case 2:
if (!BIP_32_PATH_REGEX.test(nodeToken) || !isHardened(nodeToken)) {
throw new Error(
'Invalid derivation path: The "coin_type" node (depth 2) must be a hardened BIP-32 node.',
);
}
break;
case 3:
if (!BIP_32_PATH_REGEX.test(nodeToken) || !isHardened(nodeToken)) {
throw new Error(
'Invalid derivation path: The "account" node (depth 3) must be a hardened BIP-32 node.',
);
}
break;
case 4:
if (!BIP_32_PATH_REGEX.test(nodeToken)) {
throw new Error(
'Invalid derivation path: The "change" node (depth 4) must be a BIP-32 node.',
);
}
break;
case MAX_BIP_44_DEPTH: // 5
if (!BIP_32_PATH_REGEX.test(nodeToken)) {
throw new Error(
'Invalid derivation path: The "address_index" node (depth 5) must be a BIP-32 node.',
);
}
break;
}
});
}