Skip to content

Commit 6653985

Browse files
committed
chore: more optimizations
1 parent fcbb118 commit 6653985

File tree

1 file changed

+9
-3
lines changed
  • packages/state-transition/src/util

1 file changed

+9
-3
lines changed

packages/state-transition/src/util/seed.ts

+9-3
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ export function computeProposerIndex(
120120
const shuffledResult = new Map<number, number>();
121121

122122
let i = 0;
123+
const cachedHashInput = Buffer.allocUnsafe(32 + 8);
124+
cachedHashInput.set(seed, 0);
123125
let cachedHash: Uint8Array | null = null;
124126
while (true) {
125127
// an optimized version of the below naive code
@@ -134,7 +136,8 @@ export function computeProposerIndex(
134136

135137
// compute a new hash every 16 iterations
136138
if (i % 16 === 0) {
137-
cachedHash = digest(Buffer.concat([seed, intToBytes(Math.floor(i / 16), 8, "le")]));
139+
cachedHashInput.writeUint32LE(Math.floor(i / 16), 32);
140+
cachedHash = digest(cachedHashInput);
138141
}
139142

140143
if (cachedHash == null) {
@@ -270,6 +273,8 @@ export function getNextSyncCommitteeIndices(
270273

271274
let i = 0;
272275
let cachedHash: Uint8Array | null = null;
276+
const cachedHashInput = Buffer.allocUnsafe(32 + 8);
277+
cachedHashInput.set(seed, 0);
273278
// this simple cache makes sure we don't have to recompute the shuffled index for the next round of activeValidatorCount
274279
const shuffledResult = new Map<number, number>();
275280
while (syncCommitteeIndices.length < SYNC_COMMITTEE_SIZE) {
@@ -285,7 +290,8 @@ export function getNextSyncCommitteeIndices(
285290

286291
// compute a new hash every 16 iterations
287292
if (i % 16 === 0) {
288-
cachedHash = digest(Buffer.concat([seed, intToBytes(Math.floor(i / 16), 8, "le")]));
293+
cachedHashInput.writeUint32LE(Math.floor(i / 16), 32);
294+
cachedHash = digest(cachedHashInput);
289295
}
290296

291297
if (cachedHash == null) {
@@ -402,7 +408,7 @@ export function getComputeShuffledIndexFn(indexCount: number, seed: Bytes32): Co
402408
// bytesToBigInt(digest(Buffer.concat([_seed, intToBytes(i, 1)])).slice(0, 8)) % BigInt(indexCount)
403409
// );
404410
pivotBuffer[32] = i % 256;
405-
pivot = Number(bytesToBigInt(digest(pivotBuffer).slice(0, 8)) % BigInt(indexCount));
411+
pivot = Number(bytesToBigInt(digest(pivotBuffer).subarray(0, 8)) % BigInt(indexCount));
406412
pivotByIndex.set(i, pivot);
407413
}
408414

0 commit comments

Comments
 (0)