implementedProfilenative C and wasmQualifiedcpu, wasm

7. SHA-512

Bitcoin uses SHA-512 in two places, both in wallets rather than in consensus:

  • A BIP-39 seed is PBKDF2-HMAC-SHA512 of the phrase, 2,048 rounds (chapter 31).
  • A BIP-32 child key and chain code are the two halves of one HMAC-SHA512 output (chapter 32).

Nostr's NIP-06 keys come from the same two steps. This chapter builds SHA-512 from FIPS 180-4. SHA-512 has the same shape as SHA-256 (chapter 4): padding, a message schedule, rounds over eight working variables and a streaming interface over state that you own. The chapter works through what changes when the words are 64 bits wide, works out the first steps for abc by hand and checks the code against all 257 NIST vectors.

What this chapter teaches

  • How SHA-512 differs from SHA-256: 64-bit words, 128-byte blocks, 80 rounds, a 128-bit length field and different rotation distances.
  • Why 111 and 112 bytes are the padding boundary, and how a 64-bit byte count fills a 128-bit length field.
  • How to wrap 64-bit additions when no wider type exists.
  • What round 0 does for abc, worked by hand.
  • How a streaming hash keeps its state in bytes you own and refuses bad state, bad output and misuse without changing anything.

Where the code is

SHA-512 is in three files:

  • coax/lib/crypto/sha512-kernel.coax has the constants, the word arithmetic, the compression function S512_compress, the padding and a one-shot hash S512_hash over a byte view.
  • coax/lib/crypto/sha512.coax has the streaming interface (sha512_init, sha512_update_checked, sha512_final_checked, sha512_hash_checked) and the one-shot calls that BIP-39 and BIP-32 use: sha512, sha512_two, hmac_sha512 and pbkdf2_hmac_sha512.
  • coax/lib/crypto/sha512-memory.coax has the wrappers sha512_update, sha512_final and sha512_hash, which compute the overlap fact from the addresses of the views.

Before this chapter, sha512.coax was one file written for the BIP-39 and BIP-32 code (bip39.coax, bip32.coax): a one-shot hash with a bool result and no streaming state. The chapter splits out the kernel, adds the streaming interface with the status codes of chapter 4, and makes the one-shot calls refuse negative counts. PBKDF2 now erases its salt buffer, and its blocks on refusal as well as on success. The BIP-39, BIP-32 and NIP-06 vectors give the same results as before.

How SHA-512 differs from SHA-256

PropertySHA-256SHA-512
Word32 bits64 bits
Block64 bytes, 16 words128 bytes, 16 words
Schedule64 words80 words
Rounds6480
Length field64 bits128 bits
Longest input that fits in one block55 bytes111 bytes
Digest32 bytes64 bytes
σ0(x)rotr 7 ^ rotr 18 ^ shr 3rotr 1 ^ rotr 8 ^ shr 7
σ1(x)rotr 17 ^ rotr 19 ^ shr 10rotr 19 ^ rotr 61 ^ shr 6
Σ0(a)rotr 2 ^ rotr 13 ^ rotr 22rotr 28 ^ rotr 34 ^ rotr 39
Σ1(e)rotr 6 ^ rotr 11 ^ rotr 25rotr 14 ^ rotr 18 ^ rotr 41

Ch and Maj are the same bitwise functions. The constants come from the same primes, with 64 bits instead of 32:

  • K[i] is the first 64 bits of the fractional part of the cube root of the i-th prime, for 80 primes. For i below 64, its top 32 bits are SHA-256's K[i]: SHA-512's K[0] is 0x428a2f98d728ae22, and SHA-256's is 0x428a2f98.
  • The initial hash words are the first 64 bits of the fractional parts of the square roots of the first eight primes. Their top halves are SHA-256's initial words.

The kernel keeps them in S512_K and S512_IV.

Word arithmetic

FIPS 180-4 takes every SHA-512 addition modulo 2^64. SHA-256's kernel widened its 32-bit sums to u64 and kept the low half. Coax has no wider integer than u64, so the SHA-512 kernel uses add_wrap, which says the wrap is intended. A checked build refuses any other u64 addition that overflows, so a sum that should wrap and doesn't say so stops the program instead of giving a wrong digest:

jai
// Word arithmetic on u64. A checked build refuses an addition that// overflows, so every sum that FIPS 180-4 takes modulo 2^64 says so with// add_wrap.S512_rotr :: (x: u64, n: int) -> u64 #effects(all) {  if n == 0 { return x; }  return (x >> n) | (x << (64 - n));}S512_sum2 :: (a: u64, b: u64) -> u64 #effects(all) { return add_wrap(a, b); }S512_sum4 :: (a: u64, b: u64, c: u64, d: u64) -> u64 #effects(all) { return add_wrap(add_wrap(a, b), add_wrap(c, d)); }S512_sum5 :: (a: u64, b: u64, c: u64, d: u64, e: u64) -> u64 #effects(all) { return add_wrap(S512_sum4(a, b, c, d), e); }

Padding

SHA-512 works on 128-byte blocks. The padded message is:

  1. The input bytes.
  2. One 0x80 byte.
  3. Zero bytes until the length is 16 bytes short of a multiple of 128.
  4. The input's length in bits, as a big-endian 128-bit number.

The 0x80 byte and the length take 17 bytes. An input of 111 bytes leaves exactly 17 bytes free in its block, so it needs one block. An input of 112 bytes leaves 16, so its length goes in a second block.

The streaming state counts bytes in a u64, so the largest input is 2^64 − 1 bytes. Its bit length is 2^67 − 8, which needs 67 bits. The high word of the length field gets the top 3 bits of the byte count (n >> 61), and the low word gets the byte count shifted left by 3 (n << 3, which drops those 3 bits).

The kernel pads the last partial block in place. S512_pad writes the 0x80 byte and the zeros and says whether the length still fits. S512_finish compresses an extra block when it doesn't, writes the length, compresses the last block and erases it:

jai
// The padded message is the input, one 0x80 byte, zero bytes, and the input's// bit length as a big-endian 128-bit number in the last 16 bytes. It needs// one block per 128 input bytes plus one, and one more when the last block// has fewer than 17 bytes free (the remainder is 112 to 127).S512_blocks :: (n: u64) -> u64 #effects(all) {  blocks := n / 128 + 1;  if n % 128 >= 112 { blocks += 1; }  return blocks;}// Write the 0x80 byte and zeros after the `used` input bytes of the last// block. Return whether the 16-byte length still fits in this block.S512_pad :: (block: [] u8, used: int) -> bool #effects(all) {  block[used] = 0x80;  for i: used + 1..<128 { block[i] = 0; }  return used < 112;}// The bit length of n bytes is 8n, which needs up to 67 bits. The high word// is the top 3 bits of n, at most 7; the low word is n shifted left by 3.S512_length :: (block: [] u8, n: u64) #effects(all) {  block[119] = cast(u8) (n >> 61);  for i: 112..<119 { block[i] = 0; }  low := n << 3;  for i: 0..<8 { block[120 + i] = cast,trunc(u8) (low >> ((7 - i) * 8)); }}// The last one or two blocks. block holds the `used` bytes (0 to 127) that// didn't fill a block, and n is the whole input's byte count. The block is// erased afterwards.S512_finish :: (h: [] u64, block: [] u8, used: int, n: u64, w: [] u64) #effects(all) {  if !S512_pad(block, used) {    S512_compress(h, block, 0, w);    for i: 0..<128 { block[i] = 0; }  }  S512_length(block, n);  S512_compress(h, block, 0, w);  for i: 0..<128 { block[i] = 0; }}

Worked example: padding abc

abc is the bytes 61 62 63, so it is 3 bytes, or 24 bits.

  1. 3 is less than 112, so the padded message is one block of 128 bytes.
  2. Bytes 0–2 are 61 62 63.
  3. Byte 3 is 80.
  4. Bytes 4–111 are 00.
  5. Bytes 112–127 hold 24 as a big-endian 128-bit number: fifteen 00 bytes, then 18.

Worked example: the largest length field

For 2^64 − 1 bytes, every bit of the byte count is 1:

  1. The high word is n >> 61, which is 0b111, or 7.
  2. The low word is n << 3. The three top bits fall off and three zero bits enter at the bottom, so it is 0xfffffffffffffff8.
  3. The 16 bytes are 00 00 00 00 00 00 00 07 ff ff ff ff ff ff ff f8.

That is 7 × 2^64 + 2^64 − 8 = 2^67 − 8 bits.

The message schedule

The compression function reads the block as 16 big-endian 64-bit words and extends them to 80. For i from 16 to 79:

jai
w[i] = w[i - 16] + σ0(w[i - 15]) + w[i - 7] + σ1(w[i - 2])   (mod 2^64)σ0(x) = rotr(x, 1) ^ rotr(x, 8) ^ (x >> 7)σ1(x) = rotr(x, 19) ^ rotr(x, 61) ^ (x >> 6)

Worked example: the first schedule words for abc

From the padded block:

  • w[0] is bytes 0–7, 61 62 63 80 00 00 00 00, which is 0x6162638000000000.
  • w[1] to w[14] are 0.
  • w[15] is bytes 120–127, which is 0x0000000000000018.

Then:

  1. w[16] = w[0] + σ0(w[1]) + w[9] + σ1(w[14]). Every term but w[0] is 0, so w[16] is 0x6162638000000000.
  2. w[17] = w[1] + σ0(w[2]) + w[10] + σ1(w[15]), which is σ1(0x18). 0x18 has bits 3 and 4 set.
  3. Rotating right by 19 moves bit 3 to bit 3 − 19 + 64 = 48 and bit 4 to bit 49. The result is 0x0003000000000000.
  4. Rotating right by 61 moves them to bits 6 and 7: 0x00000000000000c0.
  5. Shifting right by 6 drops both bits: 0.
  6. The XOR of the three is 0x00030000000000c0.

So w[17] is 0x00030000000000c0.

The compression function

Each of the 80 rounds computes two temporary words and shifts the eight working variables down by one, as in SHA-256:

jai
T1 = h + Σ1(e) + Ch(e, f, g) + K[i] + w[i]T2 = Σ0(a) + Maj(a, b, c)h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2

After the 80 rounds, each working variable is added to its hash word. The caller passes the 80-word schedule w in, and the kernel erases it before it returns, because HMAC and PBKDF2 pass key bytes through it. A check can then see that the schedule was erased:

jai
// The 128-byte block at data[at..<at + 128] into the eight hash words h. The// caller owns the 80-word message schedule w, and it is erased before// return, because HMAC and PBKDF2 pass key bytes through it.S512_compress :: (h: [] u64, data: [] u8, at: int, w: [] u64) #effects(all) {  // The message schedule: 16 big-endian words from the block, then 64 more.  for i: 0..<16 {    x: u64 = 0;    for j: 0..<8 { x = x | (cast(u64) data[at + i * 8 + j] << ((7 - j) * 8)); }    w[i] = x;  }  for i: 16..<80 {    x := w[i - 15]; y := w[i - 2];    s0 := S512_rotr(x, 1) ^ S512_rotr(x, 8) ^ (x >> 7);    s1 := S512_rotr(y, 19) ^ S512_rotr(y, 61) ^ (y >> 6);    w[i] = S512_sum4(w[i - 16], s0, w[i - 7], s1);  }  // 80 rounds over the eight working variables. FIPS 180-4 calls the last  // one h; here it is z, because h is the hash.  k := S512_K;  a := h[0]; b := h[1]; c := h[2]; d := h[3]; e := h[4]; f := h[5]; g := h[6]; z := h[7];  for i: 0..<80 {    s1 := S512_rotr(e, 14) ^ S512_rotr(e, 18) ^ S512_rotr(e, 41);    choose := (e & f) ^ ((e ^ 0xffffffffffffffff) & g);    t1 := S512_sum5(z, s1, choose, k[i], w[i]);    s0 := S512_rotr(a, 28) ^ S512_rotr(a, 34) ^ S512_rotr(a, 39);    majority := (a & b) ^ (a & c) ^ (b & c);    t2 := S512_sum2(s0, majority);    z = g; g = f; f = e; e = S512_sum2(d, t1); d = c; c = b; b = a; a = S512_sum2(t1, t2);  }  h[0] = S512_sum2(h[0], a); h[1] = S512_sum2(h[1], b); h[2] = S512_sum2(h[2], c); h[3] = S512_sum2(h[3], d);  h[4] = S512_sum2(h[4], e); h[5] = S512_sum2(h[5], f); h[6] = S512_sum2(h[6], g); h[7] = S512_sum2(h[7], z);  for i: 0..<80 { w[i] = 0; }}

Worked example: round 0 for abc

At round 0 the working variables are the initial hash words. a is 0x6a09e667f3bcc908, d is 0xa54ff53a5f1d36f1, e is 0x510e527fade682d1 and h is 0x5be0cd19137e2179. The bitwise functions give:

  • Σ1(e) = 0x9427e33bb5c9dbca
  • Ch(e, f, g) = 0x1f85c98c7b273d3b
  • Σ0(a) = 0x08c4db56aac80c2a
  • Maj(a, b, c) = 0x3a6fe667f69ce92b

The top halves of Ch and Maj are SHA-256's round 0 values, 0x1f85c98c and 0x3a6fe667 (chapter 4). They work bit by bit, and the top halves of the initial words are SHA-256's. Σ0 and Σ1 differ, because 64-bit rotations move bits between the halves.

  1. T1 adds five words: `0x5be0cd19137e2179 + 0x9427e33bb5c9dbca + 0x1f85c98c7b273d3b + 0x428a2f98d728ae22 + 0x6162638000000000 is 0x1b37b0cfa1b97e8a0`. The carry out of bit 63 is dropped, so T1 is 0xb37b0cfa1b97e8a0.
  2. T2 = 0x08c4db56aac80c2a + 0x3a6fe667f69ce92b is 0x4334c1bea164f555, with no carry.
  3. The new a is T1 + T2 = 0xf6afceb8bcfcddf5.
  4. The new e is d + T1 = 0xa54ff53a5f1d36f1 + 0xb37b0cfa1b97e8a0, which is 0x158cb02347ab51f91. Dropping the carry gives 0x58cb02347ab51f91.

FIPS 180-2 Appendix C.1 lists the same a and e for round 0 of abc. After all 80 rounds and the final additions, the digest is:

text
ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f

A one-shot hash

S512_hash hashes a whole byte view. It compresses the full blocks where they are, then copies the rest into one local block, which S512_finish pads and erases:

jai
// The digest of a whole byte view. Full blocks are compressed where they are;// the rest is copied into one local block, which S512_finish pads and erases.S512_hash :: (input: [] u8) -> S512_Digest #export_c #effects(all) {  if input.count < 0 { return S512_Digest.{error = 1}; } // mutant: equivalent (every reader tests error != 0)  h := S512_IV; w: [80] u64;  full := input.count / 128;  for i: 0..<full { S512_compress(h[..], input, i * 128, w[..]); }  last: [128] u8;  used := input.count - full * 128;  for i: 0..<used { last[i] = input[full * 128 + i]; }  S512_finish(h[..], last[..], used, cast(u64) input.count, w[..]);  return S512_Digest.{words = h};}

A negative count, which a C caller can pass, returns an error digest. The // mutant: equivalent note tells coax mutate that changing the error value from 1 to 2 can't be seen: every reader tests whether it is 0.

Streaming over your state

sha512.coax keeps a stream in a 208-byte state that you own:

BytesField
0–3The magic bytes S512
4The version, 1
5The phase: 1 active, 2 final
6Zero
7The number of buffered bytes, 0–127
8–15The total byte count, big-endian
16–79The eight hash words, big-endian
80–207The partial block

Every call reads the header first and refuses a state whose magic bytes, version, phase or zero byte are wrong, or whose buffered count isn't the total modulo 128:

jai
SHA512_OK :: cast(u32) 0;SHA512_BAD_STATE :: cast(u32) 1;SHA512_BAD_INPUT :: cast(u32) 2;SHA512_BAD_OUTPUT :: cast(u32) 3;SHA512_PHASE :: cast(u32) 4;SHA512_ALIAS :: cast(u32) 5;SHA512_LENGTH :: cast(u32) 6;SHA512_STATE_BYTES :: 208;// The state counts bytes in a u64, so one stream hashes at most 2^64 - 1// bytes. Their bit length still fits the 128-bit length field.SHA512_MAX_TOTAL :: cast(u64) 18446744073709551615;SHA512_MAX :: 1048576;     // bytes one call takesSHA512_ACTIVE :: cast(u32) 1;SHA512_FINAL :: cast(u32) 2;Sha512Info :: struct { error: u32; phase: u32; total: u64; buffered: u32; }// The state is: "S512", version 1, the phase (1 active, 2 final), 0, the// number of buffered bytes (0 to 127), the total byte count (big-endian u64),// the eight hash words (big-endian) and the 128-byte partial block.sha512_header :: (state: [] u8) -> Sha512Info #effects(all) {  bad := Sha512Info.{error = SHA512_BAD_STATE};  if state.count != SHA512_STATE_BYTES { return bad; }  if state[0] != 'S' || state[1] != '5' || state[2] != '1' || state[3] != '2' || state[4] != 1 || state[6] != 0 { return bad; }  phase := cast(u32) state[5]; used := cast(u32) state[7]; total := sha512_get64(state, 8);  if phase != SHA512_ACTIVE && phase != SHA512_FINAL { return bad; }  // An active state buffers exactly total mod 128 bytes; a final one none.  if phase == SHA512_ACTIVE && cast(u64) used != total % 128 { return bad; }  if phase == SHA512_FINAL && used != 0 { return bad; }  return Sha512Info.{phase = phase, total = total, buffered = used};}

The statuses are chapter 4's, without the tag status:

StatusNameMeaning
0SHA512_OKSuccess
1SHA512_BAD_STATEThe state has the wrong size or isn't a valid state
2SHA512_BAD_INPUTThe input is negative or larger than 1 MiB
3SHA512_BAD_OUTPUTThe output has fewer than 64 bytes
4SHA512_PHASEAn update after the hash was finalized
5SHA512_ALIASThe state, input or output overlap
6SHA512_LENGTHThe total would pass 2^64 − 1 bytes

The update and final calls do all their checks before they write anything, so a refusal leaves the state and the output unchanged:

jai
// Append input to the stream. Every check comes first, so a refusal leaves// the state unchanged.sha512_update_checked :: (state: [] u8, input: [] u8, overlap: bool) -> u32 #effects(all) {  info := sha512_header(state);  if info.error != SHA512_OK { return info.error; }  if info.phase != SHA512_ACTIVE { return SHA512_PHASE; }  status := sha512_update_limit(info.total, input.count);  if status != SHA512_OK { return status; }  if input.count > 0 && overlap { return SHA512_ALIAS; }  used := cast(int) info.buffered;  for byte: input {    state[80 + used] = byte; used += 1;    if used == 128 { sha512_absorb(state); used = 0; }  }  state[7] = cast(u8) used;  sha512_put64(state, 8, info.total + cast(u64) input.count);  return SHA512_OK;}// Pad, compress the last one or two blocks and write the 64-byte digest.// The final state keeps the hash words and erases the partial block, so a// second call writes the same digest.sha512_final_checked :: (state: [] u8, out: [] u8, overlap: bool) -> u32 #effects(all) {  info := sha512_header(state);  if info.error != SHA512_OK { return info.error; }  if !cb_span(out.count, 0, 64) { return SHA512_BAD_OUTPUT; }  if overlap { return SHA512_ALIAS; }  h: [8] u64; w: [80] u64;  for i: 0..<8 { h[i] = sha512_get64(state, 16 + i * 8); }  if info.phase == SHA512_ACTIVE {    S512_finish(h[..], state[80..<208], cast(int) info.buffered, info.total, w[..]);    for i: 0..<8 { sha512_put64(state, 16 + i * 8, h[i]); }    state[5] = cast(u8) SHA512_FINAL; state[7] = 0;  }  for i: 0..<8 { sha512_put64(out, i * 8, h[i]); }  for i: 0..<8 { h[i] = 0; } // mutant: equivalent (erases a dead local; no result reads it)  return SHA512_OK;}

Unlike chapter 4's state, the final state erases its partial block: S512_finish zeros it after the last compression. The block held the last input bytes, and nothing needs them after the digest. The state still holds the hash words, so a second final call writes the same digest. When you hash a key, erase the whole state afterwards (chapter 3).

The calls BIP-39 and BIP-32 use

The wallet code calls four one-shot procedures, each returning bool:

  • sha512(input, out) writes the digest of up to 1 MiB.
  • sha512_two(a, b, out) writes the digest of a followed by b, without copying them together. HMAC uses it for the key pad and the message.
  • hmac_sha512(key, msg, out) hashes a key longer than 128 bytes first, as RFC 2104 says.
  • pbkdf2_hmac_sha512(password, salt, rounds, out) computes one 64-byte PBKDF2 block, which is what BIP-39 asks for.

These calls run the kernel on local words rather than on a serialized state, because PBKDF2's 2,048 rounds make 8,192 compressions per seed. Each reads every input byte before it writes its output, so PBKDF2 can pass the same 64 bytes as message and output. Their bounds are separate procedures on counts (sha512_two_ok, hmac_sha512_ok, pbkdf2_hmac_sha512_ok), so the checks test the 1 MiB limits without building 1 MiB inputs. Chapters 31 and 32 teach the wallet code that uses them.

The example

The example is bitcoin/examples/sha-512.coax. It prints the padding and the schedule words worked out above, runs round 0, hashes abc, streams the 112-byte FIPS message one byte at a time, hashes one million a bytes in 1,000 updates, checks every split of a 1,000-byte message, prints the largest length field and shows six refusals.

jai
#load "../../coax/lib/crypto/sha512.coax";#load "../../coax/lib/nostr/hex.coax";#import "Basic";// Print a label and bytes as lowercase hex.show :: (label: string, bytes: [] u8) {  text: [256] u8;  r := hex_encode_checked(cast(string) bytes, text[..], false);  print("%: %\n", label, cast(string) text[0..<r.written]);}// Print a label and one 64-bit word as 16 hex digits.show_word :: (label: string, x: u64) {  b: [8] u8;  sha512_put64(b[..], 0, x);  show(label, b[..]);}// Every call below this point must succeed; say so if one doesn't.must :: (status: u32) { if status != SHA512_OK { print("unexpected status %\n", status); } }STATUS :: [7] string.["ok", "bad state", "bad input", "bad output",  "already final", "overlap", "too long"];main :: () {  abc := [3] u8.[97, 98, 99];  // Padding: "abc" is 3 bytes, so it fits in one 128-byte block.  print("blocks for 0, 111, 112 and 128 bytes: % % % %\n", S512_blocks(0), S512_blocks(111), S512_blocks(112), S512_blocks(128));  block: [128] u8;  for i: 0..<3 { block[i] = abc[i]; }  fits := S512_pad(block[..], 3);  S512_length(block[..], 3);  print("length fits in the block: %\n", fits);  show("padded block bytes 0-7", block[0..<8]);  show("padded block bytes 112-127", block[112..<128]);  // The first schedule words, as the compression function builds them.  w: [18] u64;  for i: 0..<16 { w[i] = sha512_get64(block[..], i * 8); }  for i: 16..<18 {    x := w[i - 15]; y := w[i - 2];    s0 := S512_rotr(x, 1) ^ S512_rotr(x, 8) ^ (x >> 7);    s1 := S512_rotr(y, 19) ^ S512_rotr(y, 61) ^ (y >> 6);    w[i] = S512_sum4(w[i - 16], s0, w[i - 7], s1);  }  show_word("w[0]", w[0]); show_word("w[15]", w[15]);  show_word("w[16]", w[16]); show_word("w[17]", w[17]);  // Round 0 of the compression function, from the initial hash words.  iv := S512_IV;  a := iv[0]; e := iv[4];  s1 := S512_rotr(e, 14) ^ S512_rotr(e, 18) ^ S512_rotr(e, 41);  choose := (e & iv[5]) ^ ((e ^ 0xffffffffffffffff) & iv[6]);  t1 := S512_sum5(iv[7], s1, choose, S512_K[0], w[0]);  s0 := S512_rotr(a, 28) ^ S512_rotr(a, 34) ^ S512_rotr(a, 39);  majority := (a & iv[1]) ^ (a & iv[2]) ^ (iv[1] & iv[2]);  t2 := S512_sum2(s0, majority);  show_word("round 0 T1", t1); show_word("round 0 T2", t2);  show_word("round 0 new a", S512_sum2(t1, t2)); show_word("round 0 new e", S512_sum2(iv[3], t1));  // The digest of "abc", in one call.  out: [64] u8;  print("hash \"abc\": %\n", STATUS[sha512_hash_checked(abc[..], out[..], false)]);  show("SHA-512(\"abc\")", out[..]);  // The two-block FIPS 180-4 message, streamed one byte at a time.  text := "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";  long: [112] u8;  for i: 0..<112 { long[i] = text[i]; }  state: [208] u8;  must(sha512_init(state[..]));  for i: 0..<112 { must(sha512_update_checked(state[..], long[i..<i + 1], false)); }  print("% bytes in 112 updates, % buffered\n", sha512_info(state[..]).total, sha512_info(state[..]).buffered);  must(sha512_final_checked(state[..], out[..], false));  show("SHA-512(112-byte message)", out[..]);  // One million "a" bytes, in 1,000 updates of 1,000 bytes.  thousand: [1000] u8;  for i: 0..<1000 { thousand[i] = 97; }  must(sha512_init(state[..]));  for i: 0..<1000 { must(sha512_update_checked(state[..], thousand[..], false)); }  must(sha512_final_checked(state[..], out[..], false));  show("SHA-512(1,000,000 x \"a\")", out[..]);  // Every split of a 1,000-byte message into two updates gives the digest  // of one update.  message: [1000] u8;  for i: 0..<1000 { message[i] = cast(u8) ((i * 7 + 3) % 256); }  whole: [64] u8;  must(sha512_hash_checked(message[..], whole[..], false));  agree := 0;  for cut: 0..<1001 {    split: [64] u8;    must(sha512_init(state[..]));    must(sha512_update_checked(state[..], message[0..<cut], false));    must(sha512_update_checked(state[..], message[cut..<1000], false));    must(sha512_final_checked(state[..], split[..], false));    same := true;    for i: 0..<64 { if split[i] != whole[i] { same = false; } }    if same { agree += 1; }  }  print("splits of 1,000 bytes that match one update: % of 1001\n", agree);  show("SHA-512(1,000-byte message)", whole[..]);  // The 128-bit length field for the largest stream, 2^64 - 1 bytes.  S512_length(block[..], SHA512_MAX_TOTAL);  show("length field for 2^64 - 1 bytes", block[112..<128]);  // Refusals. Each one returns a status and leaves the state and output unchanged.  must(sha512_init(state[..]));  must(sha512_final_checked(state[..], out[..], false));  print("update after final: %\n", STATUS[sha512_update_checked(state[..], abc[..], false)]);  small: [63] u8;  print("63-byte output: %\n", STATUS[sha512_hash_checked(abc[..], small[..], false)]);  print("1 MiB + 1 byte in one call: %\n", STATUS[sha512_request(1048577, 64, false)]);  short: [207] u8;  print("207-byte state: %\n", STATUS[sha512_init(short[..])]);  must(sha512_init(state[..]));  state[7] = 1;  print("state that buffers 1 byte of 0: %\n", STATUS[sha512_update_checked(state[..], abc[..], false)]);  print("legacy call, 63-byte output: %\n", sha512(abc[..], small[..]));}

Run it from the repository root:

shell
coax/bin/coax run bitcoin/examples/sha-512.coax

The output matches the values worked out by hand above:

text
blocks for 0, 111, 112 and 128 bytes: 1 1 2 2
length fits in the block: true
padded block bytes 0-7: 6162638000000000
padded block bytes 112-127: 00000000000000000000000000000018
w[0]: 6162638000000000
w[15]: 0000000000000018
w[16]: 6162638000000000
w[17]: 00030000000000c0
round 0 T1: b37b0cfa1b97e8a0
round 0 T2: 4334c1bea164f555
round 0 new a: f6afceb8bcfcddf5
round 0 new e: 58cb02347ab51f91
hash "abc": ok
SHA-512("abc"): ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f
112 bytes in 112 updates, 112 buffered
SHA-512(112-byte message): 8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909
SHA-512(1,000,000 x "a"): e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b
splits of 1,000 bytes that match one update: 1001 of 1001
SHA-512(1,000-byte message): 00e36fccf193e59697a92b5ab24666ce6326d7fa16bf10832d0991ddc591112e9dfa6a636950ed9c4d67344a760654c2ff7785e1d60094d651038735b5dccabd
length field for 2^64 - 1 bytes: 0000000000000007fffffffffffffff8
update after final: already final
63-byte output: bad output
1 MiB + 1 byte in one call: bad input
207-byte state: bad state
state that buffers 1 byte of 0: bad state
legacy call, 63-byte output: false

The three message digests are the FIPS 180-2 Appendix C examples:

  • abc: ddaf35a1…a54ca49f.
  • The 112-byte message: 8e959b75…874be909.
  • One million a bytes: e718483d…ad8cc09b.

The 112-byte message buffers all 112 bytes and finalizes into two blocks, because 112 bytes leave no room for the 16-byte length.

The book's checks run this program in debug and release builds and compare the output with bitcoin/fixtures/sha-512.out.

A broken case and its refusal

The last six lines of the output are refusals. Each returns its status before it writes anything:

  • An update after the final call returns already final. A finalized state has absorbed its padding, so more input would give a digest of no message.
  • A 63-byte output returns bad output. A digest is 64 bytes, and the call doesn't truncate it for you.
  • One update of 1 MiB + 1 byte returns bad input. Split larger inputs across updates.
  • A 207-byte state returns bad state.
  • A state whose buffered count says 1 while its total is 0 returns bad state. Such a state can't come from these calls, so it was damaged or forged. Hashing it would give a digest of bytes nobody wrote.
  • The legacy sha512 call returns false for a 63-byte output and leaves it unwritten.

How the code is checked

Published vectors

coax/tests/bitcoin/sha512.py compiles sha512-memory.coax to C in checked and release builds and runs all 257 rows of the NIST CAVS 11.0 SHA512ShortMsg.rsp (129 rows, 0 to 128 bytes) and SHA512LongMsg.rsp (128 rows, up to 12,800 bytes), pinned in coax/tests/vectors/upstream/nist/. Each row goes through the one-shot call, the legacy sha512 call and the stream in 113-byte updates, and each digest is compared with the published value and with Python's hashlib. Then it compiles the same C to wasm32 and runs the rows the same three ways in Node. It also streams 15 lengths around the block boundaries at eight chunk sizes, and checks that each refusal leaves the state and the output unchanged:

shell
python3 coax/tests/bitcoin/sha512.py

The two response files come from the same NIST archive as chapter 4's, whose SHA-256 digest the provenance manifest already pins. The manifest records each file's archive member, byte count and SHA-256.

Checks in Coax

  • sha512-kernel.coax checks the three FIPS examples, digests of 111, 112, 127, 128, 129, 239, 240 and 256 bytes against hashlib, the block counts, the padding, the length field at 3 and at 2^64 − 1 bytes, that the schedule and the last block are erased, and every rotate distance.
  • sha512.coax keeps its RFC 4231 HMAC-SHA512 cases 1, 2, 6 and 7 and its PBKDF2 vectors at 1 and 2 rounds. It adds HMAC with 128- and 129-byte keys and PBKDF2 at 3 rounds against Python's hmac and hashlib, the stream against S512_hash for 14 lengths and three chunk sizes, every header byte, the counter limit, the count bounds of the one-shot calls, and that every refusal leaves the state and the output unchanged.

The example adds a check of every split of a 260-byte message against a digest computed by Python's hashlib. 260 bytes cross two block boundaries:

jai
// Every split of a 260-byte message into two updates gives the same digest// as one update. 260 bytes cross two block boundaries, so the cuts cover an// empty first chunk, a full first block, a chunk that ends inside the length// field's range and an empty second chunk.#forall "every split of a 260-byte message gives the same digest" cut: 0..<261 #steps 200000000 {  message: [260] u8;  for i: 0..<260 { message[i] = cast(u8) ((i * 7 + 3) % 256); }  state: [208] u8; split: [64] u8;  #assert sha512_init(state[..]) == SHA512_OK;  #assert sha512_update_checked(state[..], message[0..<cut], false) == SHA512_OK;  #assert sha512_update_checked(state[..], message[cut..<260], false) == SHA512_OK;  #assert sha512_final_checked(state[..], split[..], false) == SHA512_OK;  // The digest computed outside Coax, with Python's hashlib.  expected := "e0e77840e82d30fc7dd9ea91990fe54b802a2664c08444a099a21dfdb9c1cd2d417ab22cf8f644256d9ce3cc4ebf819f4adc1c576c822f7ae88c46f40c3df627";  text: [128] u8;  #assert hex_encode_checked(cast(string) split[..], text[..], false).written == 128;  #assert cast(string) text[..] == expected;}

To run all the checks:

shell
coax/bin/coax test bitcoin/examples/sha-512.coaxcoax/bin/coax test coax/lib/crypto/sha512.coaxcoax/bin/coax mutate coax/lib/crypto/sha512-kernel.coaxcoax/bin/coax mutate coax/lib/crypto/sha512.coax --root-only

coax mutate leaves zero survivors. The kernel has 212 mutants: 211 are killed and 1 is the marked error value. sha512.coax has 395 mutants of its own procedures: 363 are killed and 32 are marked equivalent. Ten of the twelve marked lines erase a local that nothing reads afterwards, such as HMAC's key block. Erasure is a rule from chapter 3, not a result, so no check can see it. The other two are the key hash that hmac_sha512_ok keeps from failing and the shorter-of-two-counts choice in sha512_bytes, where equal counts give the same answer either way.

The users' checks pass unchanged: coax test on bip32.coax, bip39.coax, nostr/examples/checks/seed-phrase.coax and coax/lib/nostr/nipkeys.coax.

Summary

  • SHA-512 is SHA-256 with 64-bit words, 128-byte blocks, 80 rounds, a 128-bit length field and its own rotation distances.
  • 111 bytes fit in one block; 112 need two.
  • Every 64-bit sum wraps with add_wrap, because no wider type exists.
  • The stream keeps a 208-byte state, refuses bad state and misuse without changing anything, and erases its partial block when it finalizes.

Dependencies

Sources

  • FIPS 180-4, sections 4.1.3, 4.2.3, 5.1.2, 5.3.5 and 6.4.
  • FIPS 180-2, Appendix C, for the abc, 112-byte and one-million-a examples and the round 0 values.
  • The NIST CAVS 11.0 SHA-512 vectors, pinned in coax/tests/vectors/SOURCES.md.