Skip to content

Commit

Permalink
Validate CIP-3 master node entropy size (#171)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mrtenz authored May 15, 2024
1 parent c94ade2 commit 809410e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
36 changes: 28 additions & 8 deletions src/derivers/bip39.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,29 +83,49 @@ describe('createBip39KeyFromSeed', () => {
});

describe('Cip3', () => {
fixtures.cip3.forEach((fixture) => {
describe('entropyToCip3MasterNode', () => {
it('derives the correct bip39 key for ed25519Bip32 curve', async () => {
describe('entropyToCip3MasterNode', () => {
it.each(fixtures.cip3)(
'derives the correct bip39 key for ed25519Bip32 curve',
async (fixture) => {
const result = await entropyToCip3MasterNode(
hexToBytes(fixture.entropyHex),
ed25519Bip32,
);
const { bip39Node } = fixture.nodes;
expect(result.privateKey).toBe(bip39Node.privateKey);
expect(result.chainCode).toBe(bip39Node.chainCode);
});
},
);

it('throws if the entropy is less than 16 bytes', async () => {
await expect(
entropyToCip3MasterNode(new Uint8Array(15), ed25519Bip32),
).rejects.toThrow(
'Invalid entropy: The entropy must be between 16 and 64 bytes long.',
);
});

describe('deriveChildKey', () => {
it('derives the correct child key for ed25519Bip32 curve from mnemonic', async () => {
it('throws if the entropy is greater than 64 bytes', async () => {
await expect(
entropyToCip3MasterNode(new Uint8Array(65), ed25519Bip32),
).rejects.toThrow(
'Invalid entropy: The entropy must be between 16 and 64 bytes long.',
);
});
});

describe('deriveChildKey', () => {
it.each(fixtures.cip3)(
'derives the correct child key for ed25519Bip32 curve from mnemonic',
async (fixture) => {
const result = await deriveChildKey({
path: fixture.mnemonic,
curve: ed25519Bip32,
});
const { bip39Node } = fixture.nodes;
expect(result.privateKey).toBe(bip39Node.privateKey);
expect(result.chainCode).toBe(bip39Node.chainCode);
});
});
},
);
});
});
5 changes: 5 additions & 0 deletions src/derivers/bip39.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ export async function entropyToCip3MasterNode(
entropy: Uint8Array,
curve: Extract<Curve, { masterNodeGenerationSpec: 'cip3' }>,
): Promise<SLIP10Node> {
assert(
entropy.length >= 16 && entropy.length <= 64,
'Invalid entropy: The entropy must be between 16 and 64 bytes long.',
);

const rootNode = pbkdf2(sha512, curve.secret, entropy, {
c: 4096,
dkLen: 96,
Expand Down

0 comments on commit 809410e

Please sign in to comment.