Skip to content

Commit

Permalink
fix: chain w computation to main loop in hashBlocks()
Browse files Browse the repository at this point in the history
  • Loading branch information
twoeths committed Feb 28, 2024
1 parent 45e2027 commit 8a6bb40
Show file tree
Hide file tree
Showing 8 changed files with 4,485 additions and 2,620 deletions.
25 changes: 9 additions & 16 deletions packages/as-sha256/assembly/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ function SIG1(x: u32): u32 {
return rotr(x, 17) ^ rotr(x, 19) ^ (x >>> 10);
}

var tmpW: u32;
/**
* Expand message blocks (16 32bit blocks), into extended message blocks (64 32bit blocks),
* Apply SHA256 compression function on extended message blocks
Expand All @@ -158,25 +159,17 @@ function hashBlocks(wPtr: usize, mPtr: usize): void {
g = H6;
h = H7;

// Load message blocks into first 16 expanded message blocks
for (i = 0; i < 16; i++) {
store32(wPtr, i,
load32be(mPtr, i)
);
}
// Expand message blocks 17-64
for (i = 16; i < 64; i++) {
store32(wPtr, i,
SIG1(load32(wPtr, i - 2)) +
load32(wPtr, i - 7) +
SIG0(load32(wPtr, i - 15)) +
load32(wPtr, i - 16)
);
}
// 16 first u32 of expanded message block are same as message block
// rest of the 48 u32 are computed from the first 16 u32
// instead of computing expanded messsage blocks in a separate for loop,
// chain it to the below for loop to improve performance

// Apply SHA256 compression function on expanded message blocks
for (i = 0; i < 64; i++) {
t1 = h + EP1(e) + CH(e, f, g) + load32(kPtr, i) + load32(wPtr, i);
tmpW = i < 16 ? load32be(mPtr, i) : SIG1(load32(wPtr, i - 2)) + load32(wPtr, i - 7) +
SIG0(load32(wPtr, i - 15)) + load32(wPtr, i - 16);
store32(wPtr, i, tmpW);
t1 = h + EP1(e) + CH(e, f, g) + load32(kPtr, i) + tmpW;
t2 = EP0(a) + MAJ(a, b, c);
h = g;
g = f;
Expand Down
Binary file modified packages/as-sha256/build/optimized.wasm
Binary file not shown.
Loading

0 comments on commit 8a6bb40

Please sign in to comment.