reference_impl.rs
cdk-rsx/crates/crypto/vendor/blake3/reference_impl/reference_impl.rs
1//! This is the reference implementation of BLAKE3. It is used for testing and2//! as a readable example of the algorithms involved. Section 5.1 of [the BLAKE33//! spec](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf)4//! discusses this implementation. You can render docs for this implementation5//! by running `cargo doc --open` in this directory.6//!7//! # Example8//!9//! ```10//! let mut hasher = reference_impl::Hasher::new();11//! hasher.update(b"abc");12//! hasher.update(b"def");13//! let mut hash = [0; 32];14//! hasher.finalize(&mut hash);15//! let mut extended_hash = [0; 500];16//! hasher.finalize(&mut extended_hash);17//! assert_eq!(hash, extended_hash[..32]);18//! ```1920use core::cmp::min;2122const OUT_LEN: usize = 32;23const KEY_LEN: usize = 32;24const BLOCK_LEN: usize = 64;25const CHUNK_LEN: usize = 1024;2627const CHUNK_START: u32 = 1 << 0;28const CHUNK_END: u32 = 1 << 1;29const PARENT: u32 = 1 << 2;30const ROOT: u32 = 1 << 3;31const KEYED_HASH: u32 = 1 << 4;32const DERIVE_KEY_CONTEXT: u32 = 1 << 5;33const DERIVE_KEY_MATERIAL: u32 = 1 << 6;3435const IV: [u32; 8] = [36 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,37];3839const MSG_PERMUTATION: [usize; 16] = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8];4041// The mixing function, G, which mixes either a column or a diagonal.42fn g(state: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize, mx: u32, my: u32) {43 state[a] = state[a].wrapping_add(state[b]).wrapping_add(mx);44 state[d] = (state[d] ^ state[a]).rotate_right(16);45 state[c] = state[c].wrapping_add(state[d]);46 state[b] = (state[b] ^ state[c]).rotate_right(12);47 state[a] = state[a].wrapping_add(state[b]).wrapping_add(my);48 state[d] = (state[d] ^ state[a]).rotate_right(8);49 state[c] = state[c].wrapping_add(state[d]);50 state[b] = (state[b] ^ state[c]).rotate_right(7);51}5253fn round(state: &mut [u32; 16], m: &[u32; 16]) {54 // Mix the columns.55 g(state, 0, 4, 8, 12, m[0], m[1]);56 g(state, 1, 5, 9, 13, m[2], m[3]);57 g(state, 2, 6, 10, 14, m[4], m[5]);58 g(state, 3, 7, 11, 15, m[6], m[7]);59 // Mix the diagonals.60 g(state, 0, 5, 10, 15, m[8], m[9]);61 g(state, 1, 6, 11, 12, m[10], m[11]);62 g(state, 2, 7, 8, 13, m[12], m[13]);63 g(state, 3, 4, 9, 14, m[14], m[15]);64}6566fn permute(m: &mut [u32; 16]) {67 let mut permuted = [0; 16];68 for i in 0..16 {69 permuted[i] = m[MSG_PERMUTATION[i]];70 }71 *m = permuted;72}7374fn compress(75 chaining_value: &[u32; 8],76 block_words: &[u32; 16],77 counter: u64,78 block_len: u32,79 flags: u32,80) -> [u32; 16] {81 let counter_low = counter as u32;82 let counter_high = (counter >> 32) as u32;83 #[rustfmt::skip]84 let mut state = [85 chaining_value[0], chaining_value[1], chaining_value[2], chaining_value[3],86 chaining_value[4], chaining_value[5], chaining_value[6], chaining_value[7],87 IV[0], IV[1], IV[2], IV[3],88 counter_low, counter_high, block_len, flags,89 ];90 let mut block = *block_words;9192 round(&mut state, &block); // round 193 permute(&mut block);94 round(&mut state, &block); // round 295 permute(&mut block);96 round(&mut state, &block); // round 397 permute(&mut block);98 round(&mut state, &block); // round 499 permute(&mut block);100 round(&mut state, &block); // round 5101 permute(&mut block);102 round(&mut state, &block); // round 6103 permute(&mut block);104 round(&mut state, &block); // round 7105106 for i in 0..8 {107 state[i] ^= state[i + 8];108 state[i + 8] ^= chaining_value[i];109 }110 state111}112113fn first_8_words(compression_output: [u32; 16]) -> [u32; 8] {114 compression_output[0..8].try_into().unwrap()115}116117fn words_from_little_endian_bytes(bytes: &[u8], words: &mut [u32]) {118 debug_assert_eq!(bytes.len(), 4 * words.len());119 for (four_bytes, word) in bytes.chunks_exact(4).zip(words) {120 *word = u32::from_le_bytes(four_bytes.try_into().unwrap());121 }122}123124// Each chunk or parent node can produce either an 8-word chaining value or, by125// setting the ROOT flag, any number of final output bytes. The Output struct126// captures the state just prior to choosing between those two possibilities.127struct Output {128 input_chaining_value: [u32; 8],129 block_words: [u32; 16],130 counter: u64,131 block_len: u32,132 flags: u32,133}134135impl Output {136 fn chaining_value(&self) -> [u32; 8] {137 first_8_words(compress(138 &self.input_chaining_value,139 &self.block_words,140 self.counter,141 self.block_len,142 self.flags,143 ))144 }145146 fn root_output_bytes(&self, out_slice: &mut [u8]) {147 let mut output_block_counter = 0;148 for out_block in out_slice.chunks_mut(2 * OUT_LEN) {149 let words = compress(150 &self.input_chaining_value,151 &self.block_words,152 output_block_counter,153 self.block_len,154 self.flags | ROOT,155 );156 // The output length might not be a multiple of 4.157 for (word, out_word) in words.iter().zip(out_block.chunks_mut(4)) {158 out_word.copy_from_slice(&word.to_le_bytes()[..out_word.len()]);159 }160 output_block_counter += 1;161 }162 }163}164165struct ChunkState {166 chaining_value: [u32; 8],167 chunk_counter: u64,168 block: [u8; BLOCK_LEN],169 block_len: u8,170 blocks_compressed: u8,171 flags: u32,172}173174impl ChunkState {175 fn new(key_words: [u32; 8], chunk_counter: u64, flags: u32) -> Self {176 Self {177 chaining_value: key_words,178 chunk_counter,179 block: [0; BLOCK_LEN],180 block_len: 0,181 blocks_compressed: 0,182 flags,183 }184 }185186 fn len(&self) -> usize {187 BLOCK_LEN * self.blocks_compressed as usize + self.block_len as usize188 }189190 fn start_flag(&self) -> u32 {191 if self.blocks_compressed == 0 {192 CHUNK_START193 } else {194 0195 }196 }197198 fn update(&mut self, mut input: &[u8]) {199 while !input.is_empty() {200 // If the block buffer is full, compress it and clear it. More201 // input is coming, so this compression is not CHUNK_END.202 if self.block_len as usize == BLOCK_LEN {203 let mut block_words = [0; 16];204 words_from_little_endian_bytes(&self.block, &mut block_words);205 self.chaining_value = first_8_words(compress(206 &self.chaining_value,207 &block_words,208 self.chunk_counter,209 BLOCK_LEN as u32,210 self.flags | self.start_flag(),211 ));212 self.blocks_compressed += 1;213 self.block = [0; BLOCK_LEN];214 self.block_len = 0;215 }216217 // Copy input bytes into the block buffer.218 let want = BLOCK_LEN - self.block_len as usize;219 let take = min(want, input.len());220 self.block[self.block_len as usize..][..take].copy_from_slice(&input[..take]);221 self.block_len += take as u8;222 input = &input[take..];223 }224 }225226 fn output(&self) -> Output {227 let mut block_words = [0; 16];228 words_from_little_endian_bytes(&self.block, &mut block_words);229 Output {230 input_chaining_value: self.chaining_value,231 block_words,232 counter: self.chunk_counter,233 block_len: self.block_len as u32,234 flags: self.flags | self.start_flag() | CHUNK_END,235 }236 }237}238239fn parent_output(240 left_child_cv: [u32; 8],241 right_child_cv: [u32; 8],242 key_words: [u32; 8],243 flags: u32,244) -> Output {245 let mut block_words = [0; 16];246 block_words[..8].copy_from_slice(&left_child_cv);247 block_words[8..].copy_from_slice(&right_child_cv);248 Output {249 input_chaining_value: key_words,250 block_words,251 counter: 0, // Always 0 for parent nodes.252 block_len: BLOCK_LEN as u32, // Always BLOCK_LEN (64) for parent nodes.253 flags: PARENT | flags,254 }255}256257fn parent_cv(258 left_child_cv: [u32; 8],259 right_child_cv: [u32; 8],260 key_words: [u32; 8],261 flags: u32,262) -> [u32; 8] {263 parent_output(left_child_cv, right_child_cv, key_words, flags).chaining_value()264}265266/// An incremental hasher that can accept any number of writes.267pub struct Hasher {268 chunk_state: ChunkState,269 key_words: [u32; 8],270 cv_stack: [[u32; 8]; 54], // Space for 54 subtree chaining values:271 cv_stack_len: u8, // 2^54 * CHUNK_LEN = 2^64272 flags: u32,273}274275impl Hasher {276 fn new_internal(key_words: [u32; 8], flags: u32) -> Self {277 Self {278 chunk_state: ChunkState::new(key_words, 0, flags),279 key_words,280 cv_stack: [[0; 8]; 54],281 cv_stack_len: 0,282 flags,283 }284 }285286 /// Construct a new `Hasher` for the regular hash function.287 pub fn new() -> Self {288 Self::new_internal(IV, 0)289 }290291 /// Construct a new `Hasher` for the keyed hash function.292 pub fn new_keyed(key: &[u8; KEY_LEN]) -> Self {293 let mut key_words = [0; 8];294 words_from_little_endian_bytes(key, &mut key_words);295 Self::new_internal(key_words, KEYED_HASH)296 }297298 /// Construct a new `Hasher` for the key derivation function. The context299 /// string should be hardcoded, globally unique, and application-specific.300 pub fn new_derive_key(context: &str) -> Self {301 let mut context_hasher = Self::new_internal(IV, DERIVE_KEY_CONTEXT);302 context_hasher.update(context.as_bytes());303 let mut context_key = [0; KEY_LEN];304 context_hasher.finalize(&mut context_key);305 let mut context_key_words = [0; 8];306 words_from_little_endian_bytes(&context_key, &mut context_key_words);307 Self::new_internal(context_key_words, DERIVE_KEY_MATERIAL)308 }309310 fn push_stack(&mut self, cv: [u32; 8]) {311 self.cv_stack[self.cv_stack_len as usize] = cv;312 self.cv_stack_len += 1;313 }314315 fn pop_stack(&mut self) -> [u32; 8] {316 self.cv_stack_len -= 1;317 self.cv_stack[self.cv_stack_len as usize]318 }319320 // Section 5.1.2 of the BLAKE3 spec explains this algorithm in more detail.321 fn add_chunk_chaining_value(&mut self, mut new_cv: [u32; 8], mut total_chunks: u64) {322 // This chunk might complete some subtrees. For each completed subtree,323 // its left child will be the current top entry in the CV stack, and324 // its right child will be the current value of `new_cv`. Pop each left325 // child off the stack, merge it with `new_cv`, and overwrite `new_cv`326 // with the result. After all these merges, push the final value of327 // `new_cv` onto the stack. The number of completed subtrees is given328 // by the number of trailing 0-bits in the new total number of chunks.329 while total_chunks & 1 == 0 {330 new_cv = parent_cv(self.pop_stack(), new_cv, self.key_words, self.flags);331 total_chunks >>= 1;332 }333 self.push_stack(new_cv);334 }335336 /// Add input to the hash state. This can be called any number of times.337 pub fn update(&mut self, mut input: &[u8]) {338 while !input.is_empty() {339 // If the current chunk is complete, finalize it and reset the340 // chunk state. More input is coming, so this chunk is not ROOT.341 if self.chunk_state.len() == CHUNK_LEN {342 let chunk_cv = self.chunk_state.output().chaining_value();343 let total_chunks = self.chunk_state.chunk_counter + 1;344 self.add_chunk_chaining_value(chunk_cv, total_chunks);345 self.chunk_state = ChunkState::new(self.key_words, total_chunks, self.flags);346 }347348 // Compress input bytes into the current chunk state.349 let want = CHUNK_LEN - self.chunk_state.len();350 let take = min(want, input.len());351 self.chunk_state.update(&input[..take]);352 input = &input[take..];353 }354 }355356 /// Finalize the hash and write any number of output bytes.357 pub fn finalize(&self, out_slice: &mut [u8]) {358 // Starting with the Output from the current chunk, compute all the359 // parent chaining values along the right edge of the tree, until we360 // have the root Output.361 let mut output = self.chunk_state.output();362 let mut parent_nodes_remaining = self.cv_stack_len as usize;363 while parent_nodes_remaining > 0 {364 parent_nodes_remaining -= 1;365 output = parent_output(366 self.cv_stack[parent_nodes_remaining],367 output.chaining_value(),368 self.key_words,369 self.flags,370 );371 }372 output.root_output_bytes(out_slice);373 }374}