Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
refactor: replace seedCounter w/ an instance prng (#795)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmurdoch authored Feb 22, 2021
1 parent 3d1129e commit fa3ef5f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 12 deletions.
4 changes: 1 addition & 3 deletions src/chains/ethereum/ethereum/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1927,9 +1927,7 @@ export default class EthereumApi implements types.Api {
}

const wallet = this.#wallet;
const newAccount = wallet.createRandomAccount(
this.#options.wallet.mnemonic
);
const newAccount = wallet.createRandomAccount();
const address = newAccount.address;
const strAddress = address.toString();
const encryptedKeyFile = await wallet.encrypt(
Expand Down
16 changes: 7 additions & 9 deletions src/chains/ethereum/ethereum/src/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ export default class Wallet {

constructor(opts: EthereumInternalOptions["wallet"]) {
this.#hdKey = HDKey.fromMasterSeed(mnemonicToSeedSync(opts.mnemonic, null));
// create a RNG from our initial starting conditions (opts.mnemonic)
this.#randomRng = rng("ganache " + opts.mnemonic);

const initialAccounts = (this.initialAccounts = this.#initializeAccounts(
opts
Expand Down Expand Up @@ -188,14 +190,13 @@ export default class Wallet {
//#endregion
}

#seedCounter = 0n;
#randomRng: seedrandom.prng;

#randomBytes = (length: number) => {
// Since this is a mock RPC library, the rng doesn't need to be
// cryptographically secure, and determinism is desired.
const buf = Buffer.allocUnsafe(length);
const seed = (this.#seedCounter += 1n);
const rand = rng(seed.toString());
const rand = this.#randomRng;
for (let i = 0; i < length; i++) {
buf[i] = (rand() * 256) | 0; // generates a random number from 0 to 255
}
Expand Down Expand Up @@ -371,13 +372,10 @@ export default class Wallet {
return account;
}

public createRandomAccount(startingSeed: string) {
public createRandomAccount() {
// create some seeded deterministic psuedo-randomness based on the chain's
// initial starting conditions (`startingSeed`)
const seed = Buffer.concat([
Buffer.from(startingSeed),
this.#randomBytes(64)
]);
// initial starting conditions
const seed = this.#randomBytes(128);
const acct = HDKey.fromMasterSeed(seed);
const address = uncompressedPublicKeyToAddress(acct.publicKey);
const privateKey = Data.from(acct.privateKey);
Expand Down

0 comments on commit fa3ef5f

Please sign in to comment.