Skip to content
This repository was archived by the owner on Sep 16, 2025. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions src/mnemonic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class Mnemonic {

static fromString(text: string) {
text = text.trim();

Mnemonic.assertTextIsValid(text);
return new Mnemonic(text);
}
Expand All @@ -34,13 +34,42 @@ export class Mnemonic {
}

deriveKey(addressIndex: number = 0, password: string = ""): UserSecretKey {
let seed = mnemonicToSeedSync(this.text, password);
let derivationPath = `${BIP44_DERIVATION_PREFIX}/${addressIndex}'`;
let derivationResult = derivePath(derivationPath, seed.toString("hex"));
let key = derivationResult.key;
const seed = mnemonicToSeedSync(this.text, password);
return this.deriveKeyWithIndex(seed, addressIndex);
}

private deriveKeyWithIndex(seed: Buffer, addressIndex: number): UserSecretKey {
const derivationPath = `${BIP44_DERIVATION_PREFIX}/${addressIndex}'`;
const derivationResult = derivePath(derivationPath, seed.toString("hex"));
const key = derivationResult.key;
return new UserSecretKey(key);
}

deriveKeysWithPredicate(options: {
startAddressIndex: number,
stopAddressIndex: number,
numStop: number;
password?: string,
predicate: (index: number, userKey: UserSecretKey) => boolean
}): { index: number, userKey: UserSecretKey }[] {
const userKeys: { index: number, userKey: UserSecretKey }[] = [];
const seed = mnemonicToSeedSync(this.text, options.password || "");

for (let index = options.startAddressIndex; index < options.stopAddressIndex; index++) {
const userKey = this.deriveKeyWithIndex(seed, index);

if (options.predicate(index, userKey)) {
userKeys.push({ index: index, userKey: userKey });
}

if (userKeys.length == options.numStop) {
break;
}
}

return userKeys;
}

getWords(): string[] {
return this.text.split(" ");
}
Expand Down
17 changes: 17 additions & 0 deletions src/users.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,23 @@ describe("test user wallets", () => {
assert.equal(mnemonic.deriveKey(2).hex(), carol.secretKeyHex);
});

it("should derive keys with predicate", async function() {
this.timeout(20000);

const mnemonic = Mnemonic.fromString(DummyMnemonic);
const keys = mnemonic.deriveKeysWithPredicate({
startAddressIndex: 0,
stopAddressIndex: 10000,
numStop: 4,
predicate: (_index: number, userKey: UserSecretKey) => {
const pk = userKey.generatePublicKey().hex();
return pk.endsWith("2a");
}
});

assert.lengthOf(keys, 4);
});

it("should create secret key", () => {
let keyHex = alice.secretKeyHex;
let fromBuffer = new UserSecretKey(Buffer.from(keyHex, "hex"));
Expand Down