From 164d29e4d1960d16fdeafe2cc8ea8144a769f7b2 Mon Sep 17 00:00:00 2001 From: Tom French <15848336+TomAFrench@users.noreply.github.com> Date: Tue, 24 Sep 2024 20:23:08 +0100 Subject: [PATCH] feat: optimize constraints in sha256 (#6145) # Description ## Problem\* Resolves ## Summary\* We can optimize the sha256 implementation rolling the if-statement condition into the values being constrained manually. This allows us to have a single constraint rather than 2 with opposite predicates. ## Additional Context ## Documentation\* Check one: - [x] No documentation needed. - [ ] Documentation included in this PR. - [ ] **[For Experimental Features]** Documentation to be submitted in a separate PR. # PR Checklist\* - [x] I have tested the changes locally. - [x] I have formatted the changes with [Prettier](https://prettier.io/) and/or `cargo fmt` on default settings. --- noir_stdlib/src/hash/sha256.nr | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/noir_stdlib/src/hash/sha256.nr b/noir_stdlib/src/hash/sha256.nr index 7f255fe5586..e03f2b586ed 100644 --- a/noir_stdlib/src/hash/sha256.nr +++ b/noir_stdlib/src/hash/sha256.nr @@ -186,18 +186,18 @@ pub fn sha256_var(msg: [u8; N], message_size: u64) -> [u8; 32] { if !crate::runtime::is_unconstrained() { for i in 0..56 { - if i < msg_byte_ptr { - assert_eq(msg_block[i], last_block[i]); - } else { - assert_eq(msg_block[i], zero); - } + let predicate = (i < msg_byte_ptr) as u8; + let expected_byte = predicate * last_block[i]; + assert_eq(msg_block[i], expected_byte); } + // We verify the message length was inserted correctly by reversing the byte decomposition. let len = 8 * message_size; - let len_bytes: [u8; 8] = (len as Field).to_be_bytes(); + let mut reconstructed_len: Field = 0; for i in 56..64 { - assert_eq(msg_block[i], len_bytes[i - 56]); + reconstructed_len = 256 * reconstructed_len + msg_block[i] as Field; } + assert_eq(reconstructed_len, len as Field); } hash_final_block(msg_block, h) @@ -254,4 +254,3 @@ fn hash_final_block(msg_block: [u8; 64], mut state: [u32; 8]) -> [u8; 32] { out_h } -