-
Notifications
You must be signed in to change notification settings - Fork 15
/
keyExpressions.ts
327 lines (313 loc) · 11.4 KB
/
keyExpressions.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
// Copyright (c) 2023 Jose-Luis Landabaso - https://bitcoinerlab.com
// Distributed under the MIT software license
import { networks, Network } from 'bitcoinjs-lib';
import type { ECPairAPI, ECPairInterface } from 'ecpair';
import type { BIP32API, BIP32Interface } from 'bip32';
import type { KeyInfo } from './types';
import {
LedgerState,
LedgerManager,
getLedgerMasterFingerPrint,
getLedgerXpub
} from './ledger';
import * as RE from './re';
const derivePath = (node: BIP32Interface, path: string) => {
if (typeof path !== 'string') {
throw new Error(`Error: invalid derivation path ${path}`);
}
const parsedPath = path.replaceAll('H', "'").replaceAll('h', "'").slice(1);
const splitPath = parsedPath.split('/');
for (const element of splitPath) {
const unhardened = element.endsWith("'") ? element.slice(0, -1) : element;
if (
!Number.isInteger(Number(unhardened)) ||
Number(unhardened) >= 0x80000000
)
throw new Error(`Error: BIP 32 path element overflow`);
}
return node.derivePath(parsedPath);
};
/**
* Parses a key expression (xpub, xprv, pubkey or wif) into {@link KeyInfo | `KeyInfo`}.
*
* For example, given this `keyExpression`: `"[d34db33f/49'/0'/0']tpubDCdxmvzJ5QBjTN8oCjjyT2V58AyZvA1fkmCeZRC75QMoaHcVP2m45Bv3hmnR7ttAwkb2UNYyoXdHVt4gwBqRrJqLUU2JrM43HippxiWpHra/1/2/3/4/*"`, this is its parsed result:
*
* ```javascript
* {
* keyExpression:
* "[d34db33f/49'/0'/0']tpubDCdxmvzJ5QBjTN8oCjjyT2V58AyZvA1fkmCeZRC75QMoaHcVP2m45Bv3hmnR7ttAwkb2UNYyoXdHVt4gwBqRrJqLUU2JrM43HippxiWpHra/1/2/3/4/*",
* keyPath: '/1/2/3/4/*',
* originPath: "/49'/0'/0'",
* path: "m/49'/0'/0'/1/2/3/4/*",
* // Other relevant properties of the type `KeyInfo`: `pubkey`, `ecpair` & `bip32` interfaces, `masterFingerprint`, etc.
* }
* ```
*/
export function parseKeyExpression({
keyExpression,
isSegwit,
ECPair,
BIP32,
network = networks.bitcoin
}: {
keyExpression: string;
/** @default networks.bitcoin */
network?: Network;
/**
* Indicates if this key expression belongs to a a SegWit output. When set,
* further checks are done to ensure the public key (if present in the
* expression) is compressed (33 bytes).
*/
isSegwit?: boolean;
ECPair: ECPairAPI;
BIP32: BIP32API;
}): KeyInfo {
let pubkey: Buffer | undefined; //won't be computed for ranged keyExpressions
let ecpair: ECPairInterface | undefined;
let bip32: BIP32Interface | undefined;
let masterFingerprint: Buffer | undefined;
let originPath: string | undefined;
let keyPath: string | undefined;
let path: string | undefined;
const isRanged = keyExpression.indexOf('*') !== -1;
//Validate the keyExpression:
const keyExpressions = keyExpression.match(RE.reKeyExp);
if (keyExpressions === null || keyExpressions[0] !== keyExpression) {
throw new Error(`Error: expected a keyExpression but got ${keyExpression}`);
}
const reOriginAnchoredStart = RegExp(String.raw`^(${RE.reOrigin})?`); //starts with ^origin
const mOrigin = keyExpression.match(reOriginAnchoredStart);
if (mOrigin) {
const bareOrigin = mOrigin[0].replace(/[[\]]/g, ''); //strip the "[" and "]" in [origin]
const reMasterFingerprintAnchoredStart = String.raw`^(${RE.reMasterFingerprint})`;
const mMasterFingerprint = bareOrigin.match(
reMasterFingerprintAnchoredStart
);
const masterFingerprintHex = mMasterFingerprint
? mMasterFingerprint[0]
: '';
originPath = bareOrigin.replace(masterFingerprintHex, '');
if (masterFingerprintHex.length > 0) {
if (masterFingerprintHex.length !== 8)
throw new Error(
`Error: masterFingerprint ${masterFingerprintHex} invalid for keyExpression: ${keyExpression}`
);
masterFingerprint = Buffer.from(masterFingerprintHex, 'hex');
}
}
//Remove the origin (if it exists) and store result in actualKey
const actualKey = keyExpression.replace(reOriginAnchoredStart, '');
let mPubKey, mWIF, mXpubKey, mXprvKey;
//match pubkey:
if ((mPubKey = actualKey.match(RE.anchorStartAndEnd(RE.rePubKey))) !== null) {
pubkey = Buffer.from(mPubKey[0], 'hex');
ecpair = ECPair.fromPublicKey(pubkey, { network });
//Validate the pubkey (compressed or uncompressed)
if (
!ECPair.isPoint(pubkey) ||
!(pubkey.length === 33 || pubkey.length === 65)
) {
throw new Error(`Error: invalid pubkey`);
}
//Do an extra check in case we know this pubkey refers to a segwit input
if (
typeof isSegwit === 'boolean' &&
isSegwit &&
pubkey.length !== 33 //Inside wpkh and wsh, only compressed public keys are permitted.
) {
throw new Error(`Error: invalid pubkey`);
}
//match WIF:
} else if (
(mWIF = actualKey.match(RE.anchorStartAndEnd(RE.reWIF))) !== null
) {
ecpair = ECPair.fromWIF(mWIF[0], network);
//fromWIF will throw if the wif is not valid
pubkey = ecpair.publicKey;
//match xpub:
} else if (
(mXpubKey = actualKey.match(RE.anchorStartAndEnd(RE.reXpubKey))) !== null
) {
const xPubKey = mXpubKey[0];
const xPub = xPubKey.match(RE.reXpub)?.[0];
if (!xPub) throw new Error(`Error: xpub could not be matched`);
bip32 = BIP32.fromBase58(xPub, network);
const mPath = xPubKey.match(RE.rePath);
if (mPath !== null) {
keyPath = xPubKey.match(RE.rePath)?.[0];
if (!keyPath) throw new Error(`Error: could not extract a path`);
//fromBase58 and derivePath will throw if xPub or path are not valid
if (!isRanged) pubkey = derivePath(bip32, keyPath).publicKey;
} else {
pubkey = bip32.publicKey;
}
//match xprv:
} else if (
(mXprvKey = actualKey.match(RE.anchorStartAndEnd(RE.reXprvKey))) !== null
) {
const xPrvKey = mXprvKey[0];
const xPrv = xPrvKey.match(RE.reXprv)?.[0];
if (!xPrv) throw new Error(`Error: xprv could not be matched`);
bip32 = BIP32.fromBase58(xPrv, network);
const mPath = xPrvKey.match(RE.rePath);
if (mPath !== null) {
keyPath = xPrvKey.match(RE.rePath)?.[0];
if (!keyPath) throw new Error(`Error: could not extract a path`);
//fromBase58 and derivePath will throw if xPrv or path are not valid
if (!isRanged) pubkey = derivePath(bip32, keyPath).publicKey;
} else {
pubkey = bip32.publicKey;
}
} else {
throw new Error(
`Error: could not get pubkey for keyExpression ${keyExpression}`
);
}
if (originPath || keyPath) {
path = `m${originPath ?? ''}${keyPath ?? ''}`;
}
return {
keyExpression,
...(pubkey !== undefined ? { pubkey } : {}),
...(ecpair !== undefined ? { ecpair } : {}),
...(bip32 !== undefined ? { bip32 } : {}),
...(masterFingerprint !== undefined ? { masterFingerprint } : {}),
...(originPath !== undefined && originPath !== '' ? { originPath } : {}),
...(keyPath !== undefined && keyPath !== '' ? { keyPath } : {}),
...(path !== undefined ? { path } : {})
};
}
function assertChangeIndexKeyPath({
change,
index,
keyPath
}: {
change?: number | undefined; //0 -> external (reveive), 1 -> internal (change)
index?: number | undefined | '*';
keyPath?: string | undefined; //In the case of the Ledger, keyPath must be /<1;0>/number
}) {
if (
!(
(change === undefined && index === undefined) ||
(change !== undefined && index !== undefined)
)
)
throw new Error(`Error: Pass change and index or neither`);
if ((change !== undefined) === (keyPath !== undefined))
throw new Error(`Error: Pass either change and index or a keyPath`);
}
/**
* Constructs a key expression string for a Ledger device from the provided
* components.
*
* This function assists in crafting key expressions tailored for Ledger
* hardware wallets. It fetches the master fingerprint and xpub for a
* specified origin path and then combines them with the input parameters.
*
* For detailed understanding and examples of terms like `originPath`,
* `change`, and `keyPath`, refer to the documentation of
* {@link _Internal_.ParseKeyExpression | ParseKeyExpression}, which consists
* of the reverse procedure.
*
* @returns {string} - The formed key expression for the Ledger device.
*/
export async function keyExpressionLedger({
ledgerManager,
originPath,
keyPath,
change,
index
}: {
ledgerManager: LedgerManager;
originPath: string;
change?: number | undefined; //0 -> external (reveive), 1 -> internal (change)
index?: number | undefined | '*';
keyPath?: string | undefined; //In the case of the Ledger, keyPath must be /<1;0>/number
}): Promise<string>;
/** @deprecated @hidden */
export async function keyExpressionLedger({
ledgerClient,
ledgerState,
originPath,
keyPath,
change,
index
}: {
ledgerClient: unknown;
ledgerState: LedgerState;
originPath: string;
change?: number | undefined; //0 -> external (reveive), 1 -> internal (change)
index?: number | undefined | '*';
keyPath?: string | undefined; //In the case of the Ledger, keyPath must be /<1;0>/number
}): Promise<string>;
/** @hidden */
export async function keyExpressionLedger({
ledgerClient,
ledgerState,
ledgerManager,
originPath,
keyPath,
change,
index
}: {
ledgerClient?: unknown;
ledgerState?: LedgerState;
ledgerManager?: LedgerManager;
originPath: string;
change?: number | undefined; //0 -> external (reveive), 1 -> internal (change)
index?: number | undefined | '*';
keyPath?: string | undefined; //In the case of the Ledger, keyPath must be /<1;0>/number
}) {
if (ledgerManager && (ledgerClient || ledgerState))
throw new Error(`ledgerClient and ledgerState have been deprecated`);
if (ledgerManager) ({ ledgerClient, ledgerState } = ledgerManager);
if (!ledgerClient || !ledgerState)
throw new Error(`Could not retrieve ledgerClient or ledgerState`);
assertChangeIndexKeyPath({ change, index, keyPath });
const masterFingerprint = await getLedgerMasterFingerPrint({
ledgerClient,
ledgerState
});
const origin = `[${masterFingerprint.toString('hex')}${originPath}]`;
const xpub = await getLedgerXpub({ originPath, ledgerClient, ledgerState });
const keyRoot = `${origin}${xpub}`;
if (keyPath !== undefined) return `${keyRoot}${keyPath}`;
else return `${keyRoot}/${change}/${index}`;
}
/**
* Constructs a key expression string from its constituent components.
*
* This function essentially performs the reverse operation of
* {@link _Internal_.ParseKeyExpression | ParseKeyExpression}. For detailed
* explanations and examples of the terms used here, refer to
* {@link _Internal_.ParseKeyExpression | ParseKeyExpression}.
*/
export function keyExpressionBIP32({
masterNode,
originPath,
keyPath,
change,
index,
isPublic = true
}: {
masterNode: BIP32Interface;
originPath: string;
change?: number | undefined; //0 -> external (reveive), 1 -> internal (change)
index?: number | undefined | '*';
keyPath?: string | undefined; //In the case of the Ledger, keyPath must be /<1;0>/number
/**
* Compute an xpub or xprv
* @default true
*/
isPublic?: boolean;
}) {
assertChangeIndexKeyPath({ change, index, keyPath });
const masterFingerprint = masterNode.fingerprint;
const origin = `[${masterFingerprint.toString('hex')}${originPath}]`;
const xpub = isPublic
? masterNode.derivePath(`m${originPath}`).neutered().toBase58().toString()
: masterNode.derivePath(`m${originPath}`).toBase58().toString();
const keyRoot = `${origin}${xpub}`;
if (keyPath !== undefined) return `${keyRoot}${keyPath}`;
else return `${keyRoot}/${change}/${index}`;
}