UNPKG

1.22 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { assert } from '@polkadot/util';
4import { ed25519PairFromSeed } from "../../ed25519/index.js";
5import { mnemonicValidate } from "../../mnemonic/index.js";
6import { HARDENED, hdValidatePath } from "../validatePath.js";
7import { ledgerDerivePrivate } from "./derivePrivate.js";
8import { ledgerMaster } from "./master.js";
9export function hdLedger(_mnemonic, path) {
10 const words = _mnemonic.split(' ').map(s => s.trim()).filter(s => s);
11
12 assert([12, 24, 25].includes(words.length), 'Expected a mnemonic with 24 words (or 25 including a password)');
13 const [mnemonic, password] = words.length === 25 ? [words.slice(0, 24).join(' '), words[24]] : [words.join(' '), ''];
14 assert(mnemonicValidate(mnemonic), 'Invalid mnemonic passed to ledger derivation');
15 assert(hdValidatePath(path), 'Invalid derivation path');
16 const parts = path.split('/').slice(1);
17 let seed = ledgerMaster(mnemonic, password);
18
19 for (const p of parts) {
20 const n = parseInt(p.replace(/'$/, ''), 10);
21 seed = ledgerDerivePrivate(seed, n < HARDENED ? n + HARDENED : n);
22 }
23
24 return ed25519PairFromSeed(seed.slice(0, 32));
25}
\No newline at end of file