# 4. SHA-256

Bitcoin and Nostr hash everything with SHA-256:

- A txid and a block hash are SHA-256 applied twice (chapter 5).
- An event ID is the SHA-256 of the event's serialization (Nostr chapter 21).
- BIP-340 signatures hash the nonce, the key and the message with tagged
  SHA-256 hashes (chapters 23 and 24).
- HMAC, HKDF and NIP-44 are built on SHA-256 (chapters 8 and 9, and Nostr chapter 20).

This chapter builds SHA-256 from FIPS 180-4: the padding, the message
schedule, the 64 rounds of the compression function and a streaming
interface over state that you own. It works out the first steps for the
message `abc` by hand, then checks the code against the NIST vectors.

## What this chapter teaches

- How the padding adds a `0x80` byte, zero bytes and a 64-bit length, and
  why 55 and 56 bytes are the boundary.
- How the message schedule turns 16 words into 64.
- What one round does to the eight working variables.
- How a streaming hash buffers partial blocks, so any split of the input
  gives the same digest.
- How BIP-340 tagged hashes are built from plain SHA-256.

## Where the code is

SHA-256 is in two files:

- [coax/lib/crypto/sha256-kernel.coax](../../coax/lib/crypto/sha256-kernel.coax)
  has the padding, the word arithmetic, the compression function
  `S_compress`, the initial hash words and a one-shot hash `S_hash` over a
  whole string.
- [coax/lib/crypto/sha256.coax](../../coax/lib/crypto/sha256.coax) has the
  streaming interface: `sha256_init`, `sha256_update_checked`,
  `sha256_final_checked`, the one-shot `sha256_hash_checked` and the tagged
  hashes.

The Coax compiler also uses SHA-256: the provenance line of every generated
protobuf module records hashes of its inputs. Until this chapter, the
compression function lived in the compiler's
[coax/lib/proto/fingerprint.coax](../../coax/lib/proto/fingerprint.coax), and
`sha256.coax` loaded that file. The kernel now has its own file, and both the
compiler and `sha256.coax` load it. Every digest is unchanged.

A third file,
[coax/lib/crypto/sha256_workspace.coax](../../coax/lib/crypto/sha256_workspace.coax),
is an experimental streaming path for scrypt (Nostr chapter 47). It keeps the
message schedule in storage that you own, so it can be erased, and it has its
own copy of the rounds. The [migration
section](#moving-the-kernel-out-of-the-compiler) says what that move changed
in the compiler's build.

## Padding

SHA-256 works on 64-byte blocks. The padded message is:

1. The input bytes.
2. One `0x80` byte: a `1` bit followed by seven `0` bits.
3. Zero bytes until the length is 8 bytes short of a multiple of 64.
4. The input's length in bits, as a big-endian 64-bit number.

The `0x80` byte and the length take 9 bytes. An input of 55 bytes leaves
exactly 9 bytes free in its block, so it needs one block. An input of 56
bytes leaves 8, so its length goes in a second block. In general, an input of
`n` bytes needs `n / 64 + 1` blocks, plus one more when `n % 64` is 56 or
more.

The kernel never builds the padded message. `S_padded` returns the byte at
any position of it, from the input or from `S_padding`:

<!-- source: coax/lib/crypto/sha256-kernel.coax padding -->
```jai
// The padded message is the input, one 0x80 byte, zero bytes, and the input's
// bit length as a big-endian u64 in the last 8 bytes. It needs one block per
// 64 input bytes plus one, and one more when the last block has fewer than 9
// bytes free (the remainder is 56 to 63).
S_length :: (n: int) -> bool #effects(all) { return n >= 0 && n <= 2305843009213693951; }
S_blocks :: (n: int) -> int #effects(all) {
  blocks := n / 64 + 1;
  if n % 64 >= 56 { blocks += 1; }
  return blocks;
}
S_padding :: (count: int, at: int, total: int) -> u8 #effects(all) {
  if at == count { return 128; }
  if at >= total - 8 { return cast,trunc(u8) ((cast(u64) count * 8) >> ((total - 1 - at) * 8)); }
  return 0;
}
S_padded :: (input: string, at: int, total: int) -> u8 #effects(all) {
  if at < input.count { return input[at]; }
  return S_padding(input.count, at, total);
}
```

### Worked example: padding `abc`

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

1. 3 is less than 56, so the padded message is one block of 64 bytes.
2. Bytes 0–2 are `61 62 63`.
3. Byte 3 is `80`.
4. Bytes 4–55 are `00`.
5. Bytes 56–63 hold 24 as a big-endian 64-bit number:
   `00 00 00 00 00 00 00 18`.

## The message schedule

The compression function reads the block as 16 big-endian 32-bit words,
`w[0]` to `w[15]`, and extends them to 64 words. For `i` from 16 to 63:

```jai
w[i] = w[i - 16] + σ0(w[i - 15]) + w[i - 7] + σ1(w[i - 2])   (mod 2^32)
σ0(x) = rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3)
σ1(x) = rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10)
```

`rotr(x, n)` rotates `x` right by `n` bits. Every addition is modulo 2^32.
The kernel's sums widen to `u64` and keep the low 32 bits, so checked builds,
which refuse an overflowing `u32` addition, compute the same result as
native builds:

<!-- source: coax/lib/crypto/sha256-kernel.coax words -->
```jai
// Word arithmetic. Sums widen to u64 and keep the low 32 bits, so they wrap
// the same way in checked and native builds.
S_rotr :: (x: u32, n: int) -> u32 #effects(all) {
  if n == 0 { return x; }
  return (x >> n) | (x << (32 - n));
}
S_sum2 :: (a: u32, b: u32) -> u32 #effects(all) { return cast,trunc(u32) (cast(u64) a + cast(u64) b); }
S_sum4 :: (a: u32, b: u32, c: u32, d: u32) -> u32 #effects(all) { return cast,trunc(u32) (cast(u64) a + cast(u64) b + cast(u64) c + cast(u64) d); }
S_sum5 :: (a: u32, b: u32, c: u32, d: u32, e: u32) -> u32 #effects(all) { return cast,trunc(u32) (cast(u64) a + cast(u64) b + cast(u64) c + cast(u64) d + cast(u64) e); }
```

### Worked example: the first schedule words for `abc`

From the padded block:

- `w[0]` is bytes 0–3, `61 62 63 80`, which is `0x61626380`.
- `w[1]` to `w[14]` are 0.
- `w[15]` is bytes 60–63, `00 00 00 18`, which is `0x00000018`.

Then:

1. `w[16] = w[0] + σ0(w[1]) + w[9] + σ1(w[14])`. Every term but `w[0]` is 0,
   because `σ0(0)` and `σ1(0)` are 0. So `w[16]` is `0x61626380`.
2. `w[17] = w[1] + σ0(w[2]) + w[10] + σ1(w[15])`, which is `σ1(0x18)`.
   `0x18` has bits 3 and 4 set.
   - Rotating right by 17 moves bit 3 to bit 3 − 17 + 32 = 18 and bit 4 to
     bit 19. The result is `0x000c0000`.
   - Rotating right by 19 moves them to bits 16 and 17: `0x00030000`.
   - Shifting right by 10 drops both bits: `0`.
   - `0x000c0000 ^ 0x00030000 ^ 0` is `0x000f0000`.

So `w[17]` is `0x000f0000`.

## The compression function

The compression function starts from the current hash words `h[0]` to
`h[7]` and copies them into eight working variables, `a` to `h`. The code
names the last one `z`, because `h` is the hash. Each of the 64 rounds
computes two temporary words and shifts the variables down by one:

```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
```

- `Σ1(e)` is `rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)`.
- `Σ0(a)` is `rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)`.
- `Ch(e, f, g)` takes each bit from `f` where `e` has a 1 and from `g` where
  `e` has a 0.
- `Maj(a, b, c)` takes each bit from the majority of `a`, `b` and `c`.
- `K[i]` is the first 32 bits of the fractional part of the cube root of the
  `i`-th prime.

After the 64 rounds, each working variable is added to its hash word:

<!-- source: coax/lib/crypto/sha256-kernel.coax compress -->
```jai
S_K :: [64] u32.[
  0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
  0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
  0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
  0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
  0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
  0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
  0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
  0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2];

// One 64-byte block starting at `at` in `input` into the eight hash words `h`,
// using caller-provided schedule scratch `w` (wiped once by caller).
S_compress_block :: (h: [] u32, input: string, at: int, w: [] u32) #effects(all) {
  for i: 0..<16 {
    p := at + i * 4;
    w[i] = (cast(u32) input[p] << 24) | (cast(u32) input[p + 1] << 16) | (cast(u32) input[p + 2] << 8) | cast(u32) input[p + 3];
  }
  for i: 16..<64 {
    x := w[i - 15]; y := w[i - 2];
    s0 := ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3);
    s1 := ((y >> 17) | (y << 15)) ^ ((y >> 19) | (y << 13)) ^ (y >> 10);
    w[i] = S_sum4(w[i - 16], s0, w[i - 7], s1);
  }
  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..<64 {
    s1 := ((e >> 6) | (e << 26)) ^ ((e >> 11) | (e << 21)) ^ ((e >> 25) | (e << 7));
    choose := (e & f) ^ ((e ^ 4294967295) & g);
    t1 := S_sum5(z, s1, choose, S_K[i], w[i]);
    s0 := ((a >> 2) | (a << 30)) ^ ((a >> 13) | (a << 19)) ^ ((a >> 22) | (a << 10));
    majority := (a & b) ^ (a & c) ^ (b & c);
    t2 := S_sum2(s0, majority);
    z = g; g = f; f = e; e = S_sum2(d, t1); d = c; c = b; b = a; a = S_sum2(t1, t2);
  }
  h[0] = S_sum2(h[0], a); h[1] = S_sum2(h[1], b); h[2] = S_sum2(h[2], c); h[3] = S_sum2(h[3], d);
  h[4] = S_sum2(h[4], e); h[5] = S_sum2(h[5], f); h[6] = S_sum2(h[6], g); h[7] = S_sum2(h[7], z);
}
S_compress :: (h: [] u32, input: string, at: int, total: int) #effects(all) {
  w: [64] u32; defer {secure_zero(w[..]);for wiped:w[..] {#assert wiped==0;}}
  block: [64] u8; defer {secure_zero(block[..]);for wiped:block[..] {#assert wiped==0;}}
  for i: 0..<64 { block[i] = S_padded(input, at + i, total); }
  S_compress_block(h, cast(string) block[..], 0, w[..]);
}
```

FIPS 180-4 writes `Ch` as `(e & f) ^ (~e & g)`. The code writes `~e` as
`e ^ 4294967295`, which flips every bit of `e`.

### Worked example: round 0 for `abc`

The initial hash words are the first 32 bits of the fractional parts of the
square roots of the first eight primes. So at round 0, `a` is `0x6a09e667`,
`d` is `0xa54ff53a`, `e` is `0x510e527f` and `h` is `0x5be0cd19`. The
bitwise functions give `Σ1(e) = 0x3587272b`, `Ch(e, f, g) = 0x1f85c98c`,
`Σ0(a) = 0xce20b47e` and `Maj(a, b, c) = 0x3a6fe667`.

1. `T1` adds five words: `0x5be0cd19 + 0x3587272b + 0x1f85c98c +
   0x428a2f98 + 0x61626380` is `0x154da50e8`. The carry out of bit 31 is
   dropped, so `T1` is `0x54da50e8`.
2. `T2 = 0xce20b47e + 0x3a6fe667` is `0x108909ae5`, so `T2` is
   `0x08909ae5`.
3. The new `a` is `T1 + T2 = 0x54da50e8 + 0x08909ae5 = 0x5d6aebcd`.
4. The new `e` is `d + T1 = 0xa54ff53a + 0x54da50e8 = 0xfa2a4622`.

FIPS 180-2 Appendix B.1 lists the same two values for round 0 of `abc`. After
all 64 rounds and the final additions, the digest is:

```text
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
```

## A one-shot hash

`S_hash` hashes a whole string. It starts from the initial hash words and
runs the compression function once for each block of the padded message:

<!-- source: coax/lib/crypto/sha256-kernel.coax hash -->
```jai
// The initial hash words: the first 32 bits of the fractional parts of the
// square roots of the first eight primes.
S_seed :: (count: int) -> S_Digest #effects(all) {
  if !S_length(count) { return S_Digest.{error = 1}; }
  h := [8] u32.[0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
  return S_Digest.{words = h};
}
S_hash :: (input: string) -> S_Digest #export_c #effects(all) {
  seed := S_seed(input.count);
  if seed.error != 0 { return seed; }
  defer {secure_zero(seed.words[..]);for wiped:seed.words[..] {#assert wiped==0;}}
  h := seed.words; defer {secure_zero(h[..]);for wiped:h[..] {#assert wiped==0;}}
  w: [64] u32; defer {secure_zero(w[..]);for wiped:w[..] {#assert wiped==0;}}
  full := input.count / 64;
  for i: 0..<full { S_compress_block(h[..], input, i * 64, w[..]); }
  tail: [128] u8; defer {secure_zero(tail[..]);for wiped:tail[..] {#assert wiped==0;}}
  rem := input.count % 64;
  base := full * 64;
  for i: 0..<rem { tail[i] = input[base + i]; }
  blocks := S_blocks(input.count); total := blocks * 64;
  tail_blocks := blocks - full;
  for i: rem..<tail_blocks * 64 { tail[i] = S_padding(input.count, base + i, total); }
  for i: 0..<tail_blocks { S_compress_block(h[..], cast(string) tail[..], i * 64, w[..]); }
  return S_Digest.{words = h};
}
```

`S_seed` refuses a length over 2^61 − 1 bytes, because the bit length must
fit in 64 bits. `S_hash` needs the whole input at once. The compiler uses it
for its fingerprints, and `#run` uses it to compute the BIP-340 tag hashes at
compile time.

## Streaming over your state

Most callers don't have the whole message at once: a relay reads an event in
pieces, and HMAC hashes a key block and then a message. `sha256.coax` keeps
the hash in a 112-byte state that you own:

| Bytes | Field |
| --- | --- |
| 0–3 | The magic bytes `S256` |
| 4 | The version, 1 |
| 5 | The phase: 1 active, 2 final |
| 6 | Zero |
| 7 | The number of buffered bytes, 0–63 |
| 8–15 | The total byte count, big-endian |
| 16–47 | The eight hash words, big-endian |
| 48–111 | The partial block |

The calls are:

1. `sha256_init(state)` writes a fresh state.
2. `sha256_update_checked(state, input, overlap)` appends the input to the
   partial block and compresses each block as it fills.
3. `sha256_final_checked(state, out, overlap)` pads the partial block,
   compresses the last one or two blocks and writes 32 bytes to `out`.
   Calling it again returns the same digest.

Every call checks the state before it uses it: the magic bytes, the version,
the phase, and that the buffered count equals the total modulo 64. Each call
returns a status:

| Status | Name | Meaning |
| --- | --- | --- |
| 0 | `SHA_OK` | Success |
| 1 | `SHA_BAD_STATE` | The state has the wrong size or isn't a valid state |
| 2 | `SHA_BAD_INPUT` | The input is negative or larger than 1 MiB |
| 3 | `SHA_BAD_OUTPUT` | The output has fewer than 32 bytes |
| 4 | `SHA_PHASE` | An update after the hash was finalized |
| 5 | `SHA_ALIAS` | The state, input or output overlap |
| 6 | `SHA_LENGTH` | The total would pass 2^61 − 1 bytes |
| 7 | `SHA_BAD_TAG` | An unknown BIP-340 tag or a tag over 1,024 bytes |

A refusal leaves the state and the output unchanged.

The `_checked` procedures take the overlap fact as a `bool`. The wrappers in
[coax/lib/crypto/sha256-memory.coax](../../coax/lib/crypto/sha256-memory.coax),
`sha256_update`, `sha256_final` and `sha256_hash`, compute it from the
addresses of the views.

The state isn't secret by itself, but it holds input bytes. When you hash a
key, erase the state afterwards (chapter 3). `sha256_init` overwrites the
state; it is not an erasure.

## Tagged hashes

BIP-340 hashes each kind of value under its own tag, so a hash computed for
one purpose can't be reused for another:

```jai
tagged(tag, msg) = SHA256(SHA256(tag) || SHA256(tag) || msg)
```

The two copies of `SHA256(tag)` fill exactly one 64-byte block, so an
implementation can start from the state after that block.
`sha256_tagged_checked` takes any tag up to 1,024 bytes, and
`sha256_bip340_checked` takes a tag ID: 0 for `BIP0340/aux`, 1 for
`BIP0340/nonce` and 2 for `BIP0340/challenge`.

## The example

The example is [bitcoin/examples/sha-256.coax](../examples/sha-256.coax). It
prints the padding and the schedule words worked out above, runs round 0,
hashes `abc`, streams the two-block 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, computes a tagged hash and shows five refusals.

<!-- source: bitcoin/examples/sha-256.coax example -->
```jai
#load "../../coax/lib/crypto/sha256.coax";
#load "../../coax/lib/nostr/hex.coax";
#import "Basic";

// Print a label and bytes as lowercase hex.
show :: (label: string, bytes: [] u8) {
  text: [128] u8;
  r := hex_encode_checked(cast(string) bytes, text[..], false);
  print("%: %\n", label, cast(string) text[0..<r.written]);
}
// Print a label and one 32-bit word as 8 hex digits.
show_word :: (label: string, x: u32) {
  b: [4] u8;
  if cb_store_be32(b[..], 0, x) { show(label, b[..]); }
}
// Every call below this point must succeed; say so if one doesn't.
must :: (status: u32) { if status != SHA_OK { print("unexpected status %\n", status); } }

STATUS :: [8] string.["ok", "bad state", "bad input", "bad output",
  "already final", "overlap", "too long", "bad tag"];

main :: () {
  abc := [3] u8.[97, 98, 99];

  // Padding: "abc" is 3 bytes, so it fits in one 64-byte block.
  print("blocks for 0, 55, 56 and 64 bytes: % % % %\n", S_blocks(0), S_blocks(55), S_blocks(56), S_blocks(64));
  block: [64] u8;
  for i: 0..<64 { block[i] = S_padded("abc", i, 64); }
  show("padded block bytes 0-3", block[0..<4]);
  show("padded block bytes 56-63", block[56..<64]);

  // The first schedule words, as the compression function builds them.
  w: [18] u32;
  for i: 0..<16 { w[i] = cb_load_be32(block[..], i * 4).value; }
  for i: 16..<18 {
    x := w[i - 15]; y := w[i - 2];
    s0 := S_rotr(x, 7) ^ S_rotr(x, 18) ^ (x >> 3);
    s1 := S_rotr(y, 17) ^ S_rotr(y, 19) ^ (y >> 10);
    w[i] = S_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 := S_seed(3).words;
  a := iv[0]; e := iv[4];
  s1 := S_rotr(e, 6) ^ S_rotr(e, 11) ^ S_rotr(e, 25);
  choose := (e & iv[5]) ^ ((e ^ 4294967295) & iv[6]);
  t1 := S_sum5(iv[7], s1, choose, 0x428a2f98, w[0]);
  s0 := S_rotr(a, 2) ^ S_rotr(a, 13) ^ S_rotr(a, 22);
  majority := (a & iv[1]) ^ (a & iv[2]) ^ (iv[1] & iv[2]);
  t2 := S_sum2(s0, majority);
  show_word("round 0 T1", t1); show_word("round 0 T2", t2);
  show_word("round 0 new a", S_sum2(t1, t2)); show_word("round 0 new e", S_sum2(iv[3], t1));

  // The digest of "abc", in one call.
  out: [32] u8;
  print("hash \"abc\": %\n", STATUS[sha256_hash_checked(abc[..], out[..], false)]);
  show("SHA-256(\"abc\")", out[..]);

  // The two-block FIPS 180-2 message, streamed one byte at a time.
  text := "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
  long: [56] u8;
  for i: 0..<56 { long[i] = text[i]; }
  state: [112] u8;
  must(sha256_init(state[..]));
  for i: 0..<56 { must(sha256_update_checked(state[..], long[i..<i + 1], false)); }
  print("% bytes in 56 updates, % buffered\n", sha256_info(state[..]).total, sha256_info(state[..]).buffered);
  must(sha256_final_checked(state[..], out[..], false));
  show("SHA-256(56-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(sha256_init(state[..]));
  for i: 0..<1000 { must(sha256_update_checked(state[..], thousand[..], false)); }
  must(sha256_final_checked(state[..], out[..], false));
  show("SHA-256(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: [32] u8;
  must(sha256_hash_checked(message[..], whole[..], false));
  agree := 0;
  for cut: 0..<1001 {
    split: [32] u8;
    must(sha256_init(state[..]));
    must(sha256_update_checked(state[..], message[0..<cut], false));
    must(sha256_update_checked(state[..], message[cut..<1000], false));
    must(sha256_final_checked(state[..], split[..], false));
    same := true;
    for i: 0..<32 { 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-256(1,000-byte message)", whole[..]);

  // A BIP-340 tagged hash: SHA-256(SHA-256(tag) || SHA-256(tag) || "abc").
  tag := S_hash("BIP0340/challenge");
  tag_bytes: [32] u8;
  must(sha256_emit(tag.words[..], tag_bytes[..]));
  show("SHA-256(\"BIP0340/challenge\")", tag_bytes[..]);
  must(sha256_bip340_checked(2, abc[..], out[..], false));
  show("tagged challenge of \"abc\"", out[..]);

  // Refusals. Each one returns a status and leaves the output unchanged.
  must(sha256_init(state[..]));
  must(sha256_final_checked(state[..], out[..], false));
  print("update after final: %\n", STATUS[sha256_update_checked(state[..], abc[..], false)]);
  small: [31] u8;
  print("31-byte output: %\n", STATUS[sha256_hash_checked(abc[..], small[..], false)]);
  print("tag id 3: %\n", STATUS[sha256_bip340_checked(3, abc[..], out[..], false)]);
  print("1 MiB + 1 byte in one call: %\n", STATUS[sha256_request(1048577, 32, false)]);
  short: [111] u8;
  print("111-byte state: %\n", STATUS[sha256_init(short[..])]);
}
```

Run it from the repository root:

```shell
coax/bin/coax run bitcoin/examples/sha-256.coax
```

The output matches the values worked out by hand above:

```text
blocks for 0, 55, 56 and 64 bytes: 1 1 2 2
padded block bytes 0-3: 61626380
padded block bytes 56-63: 0000000000000018
w[0]: 61626380
w[15]: 00000018
w[16]: 61626380
w[17]: 000f0000
round 0 T1: 54da50e8
round 0 T2: 08909ae5
round 0 new a: 5d6aebcd
round 0 new e: fa2a4622
hash "abc": ok
SHA-256("abc"): ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
56 bytes in 56 updates, 56 buffered
SHA-256(56-byte message): 248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1
SHA-256(1,000,000 x "a"): cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0
splits of 1,000 bytes that match one update: 1001 of 1001
SHA-256(1,000-byte message): 1e9bc38cbf860b9ec31918b065f9b52476c549a782e0e7990bed8ce3868d2371
SHA-256("BIP0340/challenge"): 7bb52d7a9fef58323eb1bf7a407db382d2f3f2d81bb1224f49fe518f6d48d37c
tagged challenge of "abc": 770a5b7e7c304bbcc3ea107343ff951dd404312ef418db0c3b94e2ebfbb50087
update after final: already final
31-byte output: bad output
tag id 3: bad tag
1 MiB + 1 byte in one call: bad input
111-byte state: bad state
```

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

- `abc`: `ba7816bf…f20015ad`.
- The 56-byte message: `248d6a61…19db06c1`.
- One million `a` bytes: `cdc76e5c…c7112cd0`.

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

The five refusals are an update after the final call, an output of 31 bytes,
tag ID 3, one update of 1 MiB + 1 byte and a 111-byte state. Each returns its
status before it writes anything.

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

## How the code is checked

### Published vectors

[coax/tests/nostr/sha256.py](../../coax/tests/nostr/sha256.py) compiles
`sha256.coax` to C and to wasm32 and runs all 129 rows of the NIST CAVS 11.0
`SHA256ShortMsg.rsp` and `SHA256LongMsg.rsp` files, pinned in
`coax/tests/vectors/upstream/nist/`. It compares each digest with the
published value and with Python's `hashlib`. It also hashes a 1 MiB payload
split at every chunk size from 1 to 129 bytes, natively and in wasm:

```shell
python3 coax/tests/nostr/sha256.py
```

### Checks in Coax

- `sha256-kernel.coax` checks the empty string, `abc` and binary messages of
  1, 3, 55, 56, 57, 63, 64, 65, 119, 120, 128, 256 and 1,000 bytes, every
  rotate distance, and the padding at the largest length.
- `sha256.coax` checks the streaming path against `S_hash` for 12 lengths
  around the block boundaries and three chunk sizes, the three BIP-340 tags
  of `abc` against frozen values, and that every refusal leaves the state and
  the output unchanged.

The example adds a check of every split of a 130-byte message against a
digest computed by Python's `hashlib`. 130 bytes cross two block boundaries,
so the cuts include an empty first update, a full first block and an empty
second update:

<!-- source: bitcoin/examples/sha-256.coax splits -->
```jai
// Every split of a 130-byte message into two updates gives the same digest
// as one update. 130 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 and an empty second chunk.
#forall "every split of a 130-byte message gives the same digest" cut: 0..<131 {
  message: [130] u8;
  for i: 0..<130 { message[i] = cast(u8) ((i * 7 + 3) % 256); }
  state: [112] u8; split: [32] u8;
  #assert sha256_init(state[..]) == SHA_OK;
  #assert sha256_update_checked(state[..], message[0..<cut], false) == SHA_OK;
  #assert sha256_update_checked(state[..], message[cut..<130], false) == SHA_OK;
  #assert sha256_final_checked(state[..], split[..], false) == SHA_OK;
  // The digest computed outside Coax, with Python's hashlib.
  expected := "4d5e47a2e8510a314576c238f6ff19d389d3ef3aaaca8b2e530263a5d15741da";
  text: [64] u8;
  #assert hex_encode_checked(cast(string) split[..], text[..], false).written == 64;
  #assert cast(string) text[..] == expected;
}
```

To run all the checks:

```shell
coax/bin/coax test bitcoin/examples/sha-256.coax
coax/bin/coax mutate coax/lib/crypto/sha256-kernel.coax
coax/bin/coax mutate coax/lib/crypto/sha256.coax
```

`coax mutate` leaves zero survivors: 281 mutants in the kernel, 693 in the
streaming file with the kernel and `bytes.coax`, and 785 in the example with
the files it loads.

## Moving the kernel out of the compiler

`fingerprint.coax` is a compiler input, so moving code out of it changes the
compiler's build. The move changed these things:

- The compiler build records a fingerprint of every compiler input in
  `coax/provenance.sh`. That list now includes
  `coax/lib/crypto/sha256-kernel.coax`, and `coax/build.sh` copies the file
  into its private build snapshot.
- The bootstrap (`coax/bootstrap-build.sh`) runs `coax test` and
  `coax mutate` on the kernel before it builds the compiler.
- A generated protobuf module's provenance line has a `fingerprint_sha256`
  field. It is now the SHA-256 of the kernel followed by `fingerprint.coax`,
  the two files that compute the fingerprint. Before, it was the SHA-256 of
  `fingerprint.coax` alone.

No digest changed. The kernel's code is the same arithmetic, and its checks
compare the same published vectors before and after.

## Summary

- Padding adds `0x80`, zeros and the 64-bit bit length. 55 bytes fit in one
  block; 56 need two.
- The schedule extends 16 words to 64 with `σ0` and `σ1`.
- Each of the 64 rounds computes `T1` and `T2` and shifts the eight working
  variables. Every addition is modulo 2^32.
- The streaming state buffers a partial block, so any split of the input
  gives the same digest.
- A tagged hash is SHA-256 over two copies of the tag's hash and the
  message.

## Dependencies

- [1. Bytes, hex and base64](ch001-bytes-hex-and-base64.md)

## Sources

- [FIPS 180-4](https://csrc.nist.gov/pubs/fips/180-4/upd1/final), sections
  4.1.2, 4.2.2, 5.1.1, 5.3.3 and 6.2.
- FIPS 180-2, Appendix B, for the `abc`, 56-byte and one-million-`a`
  examples and the round 0 values.
- The NIST CAVS 11.0 SHA-256 vectors and
  [BIP-340](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki),
  pinned in [coax/tests/vectors/SOURCES.md](../../coax/tests/vectors/SOURCES.md).
