hdwallet.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /**
  2. * Explain HD Wallets..
  3. *
  4. * @_subsection: api/wallet:HD Wallets [hd-wallets]
  5. */
  6. import { computeHmac, randomBytes, ripemd160, SigningKey, sha256 } from "../crypto/index.js";
  7. import { VoidSigner } from "../providers/index.js";
  8. import { computeAddress } from "../transaction/index.js";
  9. import {
  10. concat, dataSlice, decodeBase58, defineProperties, encodeBase58,
  11. getBytes, hexlify, isBytesLike,
  12. getNumber, toBeArray, toBigInt, toBeHex,
  13. assertPrivate, assert, assertArgument
  14. } from "../utils/index.js";
  15. import { LangEn } from "../wordlists/lang-en.js";
  16. import { BaseWallet } from "./base-wallet.js";
  17. import { Mnemonic } from "./mnemonic.js";
  18. import {
  19. encryptKeystoreJson, encryptKeystoreJsonSync,
  20. } from "./json-keystore.js";
  21. import type { ProgressCallback } from "../crypto/index.js";
  22. import type { Provider } from "../providers/index.js";
  23. import type { BytesLike, Numeric } from "../utils/index.js";
  24. import type { Wordlist } from "../wordlists/index.js";
  25. import type { KeystoreAccount } from "./json-keystore.js";
  26. /**
  27. * The default derivation path for Ethereum HD Nodes. (i.e. ``"m/44'/60'/0'/0/0"``)
  28. */
  29. export const defaultPath: string = "m/44'/60'/0'/0/0";
  30. // "Bitcoin seed"
  31. const MasterSecret = new Uint8Array([ 66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100 ]);
  32. const HardenedBit = 0x80000000;
  33. const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
  34. const Nibbles = "0123456789abcdef";
  35. function zpad(value: number, length: number): string {
  36. let result = "";
  37. while (value) {
  38. result = Nibbles[value % 16] + result;
  39. value = Math.trunc(value / 16);
  40. }
  41. while (result.length < length * 2) { result = "0" + result; }
  42. return "0x" + result;
  43. }
  44. function encodeBase58Check(_value: BytesLike): string {
  45. const value = getBytes(_value);
  46. const check = dataSlice(sha256(sha256(value)), 0, 4);
  47. const bytes = concat([ value, check ]);
  48. return encodeBase58(bytes);
  49. }
  50. const _guard = { };
  51. function ser_I(index: number, chainCode: string, publicKey: string, privateKey: null | string): { IL: Uint8Array, IR: Uint8Array } {
  52. const data = new Uint8Array(37);
  53. if (index & HardenedBit) {
  54. assert(privateKey != null, "cannot derive child of neutered node", "UNSUPPORTED_OPERATION", {
  55. operation: "deriveChild"
  56. });
  57. // Data = 0x00 || ser_256(k_par)
  58. data.set(getBytes(privateKey), 1);
  59. } else {
  60. // Data = ser_p(point(k_par))
  61. data.set(getBytes(publicKey));
  62. }
  63. // Data += ser_32(i)
  64. for (let i = 24; i >= 0; i -= 8) { data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff); }
  65. const I = getBytes(computeHmac("sha512", chainCode, data));
  66. return { IL: I.slice(0, 32), IR: I.slice(32) };
  67. }
  68. type HDNodeLike<T> = { depth: number, deriveChild: (i: number) => T };
  69. function derivePath<T extends HDNodeLike<T>>(node: T, path: string): T {
  70. const components = path.split("/");
  71. assertArgument(components.length > 0, "invalid path", "path", path);
  72. if (components[0] === "m") {
  73. assertArgument(node.depth === 0, `cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${ node.depth }`, "path", path);
  74. components.shift();
  75. }
  76. let result: T = node;
  77. for (let i = 0; i < components.length; i++) {
  78. const component = components[i];
  79. if (component.match(/^[0-9]+'$/)) {
  80. const index = parseInt(component.substring(0, component.length - 1));
  81. assertArgument(index < HardenedBit, "invalid path index", `path[${ i }]`, component);
  82. result = result.deriveChild(HardenedBit + index);
  83. } else if (component.match(/^[0-9]+$/)) {
  84. const index = parseInt(component);
  85. assertArgument(index < HardenedBit, "invalid path index", `path[${ i }]`, component);
  86. result = result.deriveChild(index);
  87. } else {
  88. assertArgument(false, "invalid path component", `path[${ i }]`, component);
  89. }
  90. }
  91. return result;
  92. }
  93. /**
  94. * An **HDNodeWallet** is a [[Signer]] backed by the private key derived
  95. * from an HD Node using the [[link-bip-32]] stantard.
  96. *
  97. * An HD Node forms a hierarchal structure with each HD Node having a
  98. * private key and the ability to derive child HD Nodes, defined by
  99. * a path indicating the index of each child.
  100. */
  101. export class HDNodeWallet extends BaseWallet {
  102. /**
  103. * The compressed public key.
  104. */
  105. readonly publicKey!: string;
  106. /**
  107. * The fingerprint.
  108. *
  109. * A fingerprint allows quick qay to detect parent and child nodes,
  110. * but developers should be prepared to deal with collisions as it
  111. * is only 4 bytes.
  112. */
  113. readonly fingerprint!: string;
  114. /**
  115. * The parent fingerprint.
  116. */
  117. readonly parentFingerprint!: string;
  118. /**
  119. * The mnemonic used to create this HD Node, if available.
  120. *
  121. * Sources such as extended keys do not encode the mnemonic, in
  122. * which case this will be ``null``.
  123. */
  124. readonly mnemonic!: null | Mnemonic;
  125. /**
  126. * The chaincode, which is effectively a public key used
  127. * to derive children.
  128. */
  129. readonly chainCode!: string;
  130. /**
  131. * The derivation path of this wallet.
  132. *
  133. * Since extended keys do not provide full path details, this
  134. * may be ``null``, if instantiated from a source that does not
  135. * encode it.
  136. */
  137. readonly path!: null | string;
  138. /**
  139. * The child index of this wallet. Values over ``2 *\* 31`` indicate
  140. * the node is hardened.
  141. */
  142. readonly index!: number;
  143. /**
  144. * The depth of this wallet, which is the number of components
  145. * in its path.
  146. */
  147. readonly depth!: number;
  148. /**
  149. * @private
  150. */
  151. constructor(guard: any, signingKey: SigningKey, parentFingerprint: string, chainCode: string, path: null | string, index: number, depth: number, mnemonic: null | Mnemonic, provider: null | Provider) {
  152. super(signingKey, provider);
  153. assertPrivate(guard, _guard, "HDNodeWallet");
  154. defineProperties<HDNodeWallet>(this, { publicKey: signingKey.compressedPublicKey });
  155. const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4);
  156. defineProperties<HDNodeWallet>(this, {
  157. parentFingerprint, fingerprint,
  158. chainCode, path, index, depth
  159. });
  160. defineProperties<HDNodeWallet>(this, { mnemonic });
  161. }
  162. connect(provider: null | Provider): HDNodeWallet {
  163. return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint,
  164. this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider);
  165. }
  166. #account(): KeystoreAccount {
  167. const account: KeystoreAccount = { address: this.address, privateKey: this.privateKey };
  168. const m = this.mnemonic;
  169. if (this.path && m && m.wordlist.locale === "en" && m.password === "") {
  170. account.mnemonic = {
  171. path: this.path,
  172. locale: "en",
  173. entropy: m.entropy
  174. };
  175. }
  176. return account;
  177. }
  178. /**
  179. * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with
  180. * %%password%%.
  181. *
  182. * If %%progressCallback%% is specified, it will receive periodic
  183. * updates as the encryption process progreses.
  184. */
  185. async encrypt(password: Uint8Array | string, progressCallback?: ProgressCallback): Promise<string> {
  186. return await encryptKeystoreJson(this.#account(), password, { progressCallback });
  187. }
  188. /**
  189. * Returns a [JSON Keystore Wallet](json-wallets) encryped with
  190. * %%password%%.
  191. *
  192. * It is preferred to use the [async version](encrypt) instead,
  193. * which allows a [[ProgressCallback]] to keep the user informed.
  194. *
  195. * This method will block the event loop (freezing all UI) until
  196. * it is complete, which may be a non-trivial duration.
  197. */
  198. encryptSync(password: Uint8Array | string): string {
  199. return encryptKeystoreJsonSync(this.#account(), password);
  200. }
  201. /**
  202. * The extended key.
  203. *
  204. * This key will begin with the prefix ``xpriv`` and can be used to
  205. * reconstruct this HD Node to derive its children.
  206. */
  207. get extendedKey(): string {
  208. // We only support the mainnet values for now, but if anyone needs
  209. // testnet values, let me know. I believe current sentiment is that
  210. // we should always use mainnet, and use BIP-44 to derive the network
  211. // - Mainnet: public=0x0488B21E, private=0x0488ADE4
  212. // - Testnet: public=0x043587CF, private=0x04358394
  213. assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" });
  214. return encodeBase58Check(concat([
  215. "0x0488ADE4", zpad(this.depth, 1), this.parentFingerprint,
  216. zpad(this.index, 4), this.chainCode,
  217. concat([ "0x00", this.privateKey ])
  218. ]));
  219. }
  220. /**
  221. * Returns true if this wallet has a path, providing a Type Guard
  222. * that the path is non-null.
  223. */
  224. hasPath(): this is { path: string } { return (this.path != null); }
  225. /**
  226. * Returns a neutered HD Node, which removes the private details
  227. * of an HD Node.
  228. *
  229. * A neutered node has no private key, but can be used to derive
  230. * child addresses and other public data about the HD Node.
  231. */
  232. neuter(): HDNodeVoidWallet {
  233. return new HDNodeVoidWallet(_guard, this.address, this.publicKey,
  234. this.parentFingerprint, this.chainCode, this.path, this.index,
  235. this.depth, this.provider);
  236. }
  237. /**
  238. * Return the child for %%index%%.
  239. */
  240. deriveChild(_index: Numeric): HDNodeWallet {
  241. const index = getNumber(_index, "index");
  242. assertArgument(index <= 0xffffffff, "invalid index", "index", index);
  243. // Base path
  244. let path = this.path;
  245. if (path) {
  246. path += "/" + (index & ~HardenedBit);
  247. if (index & HardenedBit) { path += "'"; }
  248. }
  249. const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey);
  250. const ki = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32));
  251. return new HDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR),
  252. path, index, this.depth + 1, this.mnemonic, this.provider);
  253. }
  254. /**
  255. * Return the HDNode for %%path%% from this node.
  256. */
  257. derivePath(path: string): HDNodeWallet {
  258. return derivePath<HDNodeWallet>(this, path);
  259. }
  260. static #fromSeed(_seed: BytesLike, mnemonic: null | Mnemonic): HDNodeWallet {
  261. assertArgument(isBytesLike(_seed), "invalid seed", "seed", "[REDACTED]");
  262. const seed = getBytes(_seed, "seed");
  263. assertArgument(seed.length >= 16 && seed.length <= 64 , "invalid seed", "seed", "[REDACTED]");
  264. const I = getBytes(computeHmac("sha512", MasterSecret, seed));
  265. const signingKey = new SigningKey(hexlify(I.slice(0, 32)));
  266. return new HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I.slice(32)),
  267. "m", 0, 0, mnemonic, null);
  268. }
  269. /**
  270. * Creates a new HD Node from %%extendedKey%%.
  271. *
  272. * If the %%extendedKey%% will either have a prefix or ``xpub`` or
  273. * ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]])
  274. * or full HD Node ([[HDNodeWallet) respectively.
  275. */
  276. static fromExtendedKey(extendedKey: string): HDNodeWallet | HDNodeVoidWallet {
  277. const bytes = toBeArray(decodeBase58(extendedKey)); // @TODO: redact
  278. assertArgument(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey,
  279. "invalid extended key", "extendedKey", "[ REDACTED ]");
  280. const depth = bytes[4];
  281. const parentFingerprint = hexlify(bytes.slice(5, 9));
  282. const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16);
  283. const chainCode = hexlify(bytes.slice(13, 45));
  284. const key = bytes.slice(45, 78);
  285. switch (hexlify(bytes.slice(0, 4))) {
  286. // Public Key
  287. case "0x0488b21e": case "0x043587cf": {
  288. const publicKey = hexlify(key);
  289. return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey,
  290. parentFingerprint, chainCode, null, index, depth, null);
  291. }
  292. // Private Key
  293. case "0x0488ade4": case "0x04358394 ":
  294. if (key[0] !== 0) { break; }
  295. return new HDNodeWallet(_guard, new SigningKey(key.slice(1)),
  296. parentFingerprint, chainCode, null, index, depth, null, null);
  297. }
  298. assertArgument(false, "invalid extended key prefix", "extendedKey", "[ REDACTED ]");
  299. }
  300. /**
  301. * Creates a new random HDNode.
  302. */
  303. static createRandom(password?: string, path?: string, wordlist?: Wordlist): HDNodeWallet {
  304. if (password == null) { password = ""; }
  305. if (path == null) { path = defaultPath; }
  306. if (wordlist == null) { wordlist = LangEn.wordlist(); }
  307. const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist)
  308. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  309. }
  310. /**
  311. * Create an HD Node from %%mnemonic%%.
  312. */
  313. static fromMnemonic(mnemonic: Mnemonic, path?: string): HDNodeWallet {
  314. if (!path) { path = defaultPath; }
  315. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  316. }
  317. /**
  318. * Creates an HD Node from a mnemonic %%phrase%%.
  319. */
  320. static fromPhrase(phrase: string, password?: string, path?: string, wordlist?: Wordlist): HDNodeWallet {
  321. if (password == null) { password = ""; }
  322. if (path == null) { path = defaultPath; }
  323. if (wordlist == null) { wordlist = LangEn.wordlist(); }
  324. const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist)
  325. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  326. }
  327. /**
  328. * Creates an HD Node from a %%seed%%.
  329. */
  330. static fromSeed(seed: BytesLike): HDNodeWallet {
  331. return HDNodeWallet.#fromSeed(seed, null);
  332. }
  333. }
  334. /**
  335. * A **HDNodeVoidWallet** cannot sign, but provides access to
  336. * the children nodes of a [[link-bip-32]] HD wallet addresses.
  337. *
  338. * The can be created by using an extended ``xpub`` key to
  339. * [[HDNodeWallet_fromExtendedKey]] or by
  340. * [nuetering](HDNodeWallet-neuter) a [[HDNodeWallet]].
  341. */
  342. export class HDNodeVoidWallet extends VoidSigner {
  343. /**
  344. * The compressed public key.
  345. */
  346. readonly publicKey!: string;
  347. /**
  348. * The fingerprint.
  349. *
  350. * A fingerprint allows quick qay to detect parent and child nodes,
  351. * but developers should be prepared to deal with collisions as it
  352. * is only 4 bytes.
  353. */
  354. readonly fingerprint!: string;
  355. /**
  356. * The parent node fingerprint.
  357. */
  358. readonly parentFingerprint!: string;
  359. /**
  360. * The chaincode, which is effectively a public key used
  361. * to derive children.
  362. */
  363. readonly chainCode!: string;
  364. /**
  365. * The derivation path of this wallet.
  366. *
  367. * Since extended keys do not provider full path details, this
  368. * may be ``null``, if instantiated from a source that does not
  369. * enocde it.
  370. */
  371. readonly path!: null | string;
  372. /**
  373. * The child index of this wallet. Values over ``2 *\* 31`` indicate
  374. * the node is hardened.
  375. */
  376. readonly index!: number;
  377. /**
  378. * The depth of this wallet, which is the number of components
  379. * in its path.
  380. */
  381. readonly depth!: number;
  382. /**
  383. * @private
  384. */
  385. constructor(guard: any, address: string, publicKey: string, parentFingerprint: string, chainCode: string, path: null | string, index: number, depth: number, provider: null | Provider) {
  386. super(address, provider);
  387. assertPrivate(guard, _guard, "HDNodeVoidWallet");
  388. defineProperties<HDNodeVoidWallet>(this, { publicKey });
  389. const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4);
  390. defineProperties<HDNodeVoidWallet>(this, {
  391. publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth
  392. });
  393. }
  394. connect(provider: null | Provider): HDNodeVoidWallet {
  395. return new HDNodeVoidWallet(_guard, this.address, this.publicKey,
  396. this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider);
  397. }
  398. /**
  399. * The extended key.
  400. *
  401. * This key will begin with the prefix ``xpub`` and can be used to
  402. * reconstruct this neutered key to derive its children addresses.
  403. */
  404. get extendedKey(): string {
  405. // We only support the mainnet values for now, but if anyone needs
  406. // testnet values, let me know. I believe current sentiment is that
  407. // we should always use mainnet, and use BIP-44 to derive the network
  408. // - Mainnet: public=0x0488B21E, private=0x0488ADE4
  409. // - Testnet: public=0x043587CF, private=0x04358394
  410. assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" });
  411. return encodeBase58Check(concat([
  412. "0x0488B21E",
  413. zpad(this.depth, 1),
  414. this.parentFingerprint,
  415. zpad(this.index, 4),
  416. this.chainCode,
  417. this.publicKey,
  418. ]));
  419. }
  420. /**
  421. * Returns true if this wallet has a path, providing a Type Guard
  422. * that the path is non-null.
  423. */
  424. hasPath(): this is { path: string } { return (this.path != null); }
  425. /**
  426. * Return the child for %%index%%.
  427. */
  428. deriveChild(_index: Numeric): HDNodeVoidWallet {
  429. const index = getNumber(_index, "index");
  430. assertArgument(index <= 0xffffffff, "invalid index", "index", index);
  431. // Base path
  432. let path = this.path;
  433. if (path) {
  434. path += "/" + (index & ~HardenedBit);
  435. if (index & HardenedBit) { path += "'"; }
  436. }
  437. const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null);
  438. const Ki = SigningKey.addPoints(IL, this.publicKey, true);
  439. const address = computeAddress(Ki);
  440. return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, hexlify(IR),
  441. path, index, this.depth + 1, this.provider);
  442. }
  443. /**
  444. * Return the signer for %%path%% from this node.
  445. */
  446. derivePath(path: string): HDNodeVoidWallet {
  447. return derivePath<HDNodeVoidWallet>(this, path);
  448. }
  449. }
  450. /*
  451. export class HDNodeWalletManager {
  452. #root: HDNodeWallet;
  453. constructor(phrase: string, password?: null | string, path?: null | string, locale?: null | Wordlist) {
  454. if (password == null) { password = ""; }
  455. if (path == null) { path = "m/44'/60'/0'/0"; }
  456. if (locale == null) { locale = LangEn.wordlist(); }
  457. this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale);
  458. }
  459. getSigner(index?: number): HDNodeWallet {
  460. return this.#root.deriveChild((index == null) ? 0: index);
  461. }
  462. }
  463. */
  464. /**
  465. * Returns the [[link-bip-32]] path for the account at %%index%%.
  466. *
  467. * This is the pattern used by wallets like Ledger.
  468. *
  469. * There is also an [alternate pattern](getIndexedAccountPath) used by
  470. * some software.
  471. */
  472. export function getAccountPath(_index: Numeric): string {
  473. const index = getNumber(_index, "index");
  474. assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index);
  475. return `m/44'/60'/${ index }'/0/0`;
  476. }
  477. /**
  478. * Returns the path using an alternative pattern for deriving accounts,
  479. * at %%index%%.
  480. *
  481. * This derivation path uses the //index// component rather than the
  482. * //account// component to derive sequential accounts.
  483. *
  484. * This is the pattern used by wallets like MetaMask.
  485. */
  486. export function getIndexedAccountPath(_index: Numeric): string {
  487. const index = getNumber(_index, "index");
  488. assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index);
  489. return `m/44'/60'/0'/0/${ index}`;
  490. }