Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
sha256.cpp
Go to the documentation of this file.
2
3#include <algorithm>
4#include <array>
5#include <vector>
6
7#include "barretenberg/aztec/aztec_constants.hpp"
9
10namespace bb::avm2::simulation {
11
12namespace {
13
14// constants come from barretenberg/cpp/src/barretenberg/crypto/sha256/sha256.cpp
15constexpr std::array<uint32_t, 64> ROUND_CONSTANTS{
16 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
17 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
18 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
19 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
20 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
21 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
22 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
23 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
24};
25
26} // namespace
27
43MemoryValue Sha256::ror(const MemoryValue& x, uint8_t shift)
44{
45 auto val = x.as<uint32_t>();
46 // In a rotation, we decompose into a lhs and rhs (or hi and lo) part.
47 uint32_t lo = val & ((static_cast<uint32_t>(1) << shift) - 1);
48 uint32_t hi = val >> shift;
49 uint32_t result = (lo << (32U - shift)) | hi;
50
51 range_check.assert_range(lo, shift);
52 return MemoryValue::from<uint32_t>(result);
53}
54
68MemoryValue Sha256::shr(const MemoryValue& x, uint8_t shift)
69{
70 uint32_t input = x.as<uint32_t>();
71 // Get the lower shift bits
72 uint32_t lo = input & ((static_cast<uint32_t>(1) << shift) - 1);
73 uint32_t hi = input >> shift;
74
75 range_check.assert_range(lo, shift);
76
77 return MemoryValue::from<uint32_t>(hi);
78}
79
90{
91 uint64_t sum = 0;
92 for (const auto& value : values) {
93 // This is safe, since we've already checked that the values are of tag U32
94 sum += value.as<uint32_t>();
95 }
96 uint32_t lo = static_cast<uint32_t>(sum);
97 uint32_t hi = static_cast<uint32_t>(sum >> 32);
98
99 // lo matches PIL RANGE_COMP_*_RHS lookups (range_check.sel_sha256 at 32 bits).
100 range_check.assert_range(lo, 32);
101 // hi is range-checked in PIL via boolean constraint (output) or precomputed.sel_range_8 lookup
102 // (computed_w / next_a / next_e); both bounds fit in 8 bits, so this sim-time assert is sufficient.
103 BB_ASSERT(hi < 256, "High value in MODULO_SUM out of range");
104 return MemoryValue::from<uint32_t>(lo);
105}
106
130 MemoryAddress state_addr,
131 MemoryAddress input_addr,
132 MemoryAddress output_addr)
133{
134 uint32_t execution_clk = execution_id_manager.get_execution_id();
135 uint16_t space_id = memory.get_space_id();
136
137 // Default values are FF(0) as that is what the circuit would expect
139 state.fill(MemoryValue::from<FF>(0));
140
142 input.reserve(16);
143
144 // Check that the maximum addresss for the state, input, and output addresses are within the valid range.
145 // (1) Read the 8 element hash state from { state_addr, state_addr + 1, ..., state_addr + 7 }
146 // (2) Read the 16 element input from { input_addr, input_addr + 1, ..., input_addr + 15 }
147 // (3) Write the 8 element output to { output_addr, output_addr + 1, ..., output_addr + 7 }
148 bool state_addr_out_of_range = gt.gt(static_cast<uint64_t>(state_addr) + 7, AVM_HIGHEST_MEM_ADDRESS);
149 bool input_addr_out_of_range = gt.gt(static_cast<uint64_t>(input_addr) + 15, AVM_HIGHEST_MEM_ADDRESS);
150 bool output_addr_out_of_range = gt.gt(static_cast<uint64_t>(output_addr) + 7, AVM_HIGHEST_MEM_ADDRESS);
151
152 try {
153 if (state_addr_out_of_range || input_addr_out_of_range || output_addr_out_of_range) {
154 throw Sha256CompressionException("Memory address out of range for sha256 compression.");
155 }
156
157 // Read the hash state from memory. The state needs to be loaded atomically from memory (i.e. all 8 elements are
158 // read regardless of errors)
159 for (uint32_t i = 0; i < 8; ++i) {
160 state[i] = memory.get(state_addr + i);
161 }
162
163 // If any of the state values are not of tag U32, we throw an error.
164 if (std::ranges::any_of(state, [](const MemoryValue& val) { return val.get_tag() != MemoryTag::U32; })) {
165 throw Sha256CompressionException("Invalid tag for sha256 state values.");
166 }
167
168 // Load 16 elements representing the hash input from memory.
169 // Since the circuit loads this per row, we throw on the first error we find.
170 for (uint32_t i = 0; i < 16; ++i) {
171 input.emplace_back(memory.get(input_addr + i));
172 if (input[i].get_tag() != MemoryTag::U32) {
173 throw Sha256CompressionException("Invalid tag for sha256 input values.");
174 }
175 }
176
177 // Perform sha256 compression. Taken from `vm2/simulation/lib/sha256_compression.cpp` but using
178 // the bitwise operations and MemoryValues
180
181 // Fill first 16 words with the inputs
182 for (size_t i = 0; i < 16; ++i) {
183 w[i] = input[i];
184 }
185
186 // Extend the input data into the remaining 48 words
187 for (size_t i = 16; i < 64; ++i) {
188 MemoryValue s0 =
189 bitwise.xor_op(bitwise.xor_op(ror(w[i - 15], 7U), ror(w[i - 15], 18U)), shr(w[i - 15], 3U));
190 MemoryValue s1 = bitwise.xor_op(bitwise.xor_op(ror(w[i - 2], 17U), ror(w[i - 2], 19U)), shr(w[i - 2], 10U));
191 // Could be explicit with an std::initializer_list<uint32_t> here, the array overload is more readable imo.
192 // std::spans are annoying to construct from literals
193 // (https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2447r2.html)
194 w[i] = modulo_sum({ { w[i - 16], w[i - 7], s0, s1 } });
195 }
196
197 // Initialize round variables with previous block output
198 MemoryValue a = state[0];
199 MemoryValue b = state[1];
200 MemoryValue c = state[2];
201 MemoryValue d = state[3];
202 MemoryValue e = state[4];
203 MemoryValue f = state[5];
204 MemoryValue g = state[6];
205 MemoryValue h = state[7];
206
207 // Apply SHA-256 compression function to the message schedule
208 for (size_t i = 0; i < 64; ++i) {
209 MemoryValue S1 = bitwise.xor_op(bitwise.xor_op(ror(e, 6U), ror(e, 11U)), ror(e, 25U));
210 MemoryValue ch = bitwise.xor_op(bitwise.and_op(e, f), bitwise.and_op(~e, g));
211 MemoryValue S0 = bitwise.xor_op(bitwise.xor_op(ror(a, 2U), ror(a, 13U)), ror(a, 22U));
212 MemoryValue maj =
213 bitwise.xor_op(bitwise.xor_op(bitwise.and_op(a, b), bitwise.and_op(a, c)), bitwise.and_op(b, c));
214
215 auto prev_h = h; // Need to store the previous h value before updating it so we can use it in the modulo sum
216 h = g;
217 g = f;
218 f = e;
219 // e = d + temp1;
220 e = modulo_sum({ { d, prev_h, S1, ch, MemoryValue::from<uint32_t>(ROUND_CONSTANTS[i]), w[i] } });
221 d = c;
222 c = b;
223 b = a;
224 // a = temp1 + temp2;
225 a = modulo_sum({ { prev_h, S1, ch, MemoryValue::from<uint32_t>(ROUND_CONSTANTS[i]), w[i], S0, maj } });
226 }
227
228 // Add into previous block output and return
230 modulo_sum({ { a, state[0] } }), modulo_sum({ { b, state[1] } }), modulo_sum({ { c, state[2] } }),
231 modulo_sum({ { d, state[3] } }), modulo_sum({ { e, state[4] } }), modulo_sum({ { f, state[5] } }),
232 modulo_sum({ { g, state[6] } }), modulo_sum({ { h, state[7] } }),
233 };
234
235 // Write the output back to memory.
236 for (uint32_t i = 0; i < 8; ++i) {
237 memory.set(output_addr + i, output[i]);
238 }
239
240 events.emit({ .execution_clk = execution_clk,
241 .space_id = space_id,
242 .state_addr = state_addr,
243 .input_addr = input_addr,
244 .output_addr = output_addr,
245 .state = state,
246 .input = input,
247 .output = output });
248 } catch (const Sha256CompressionException& e) {
249 // If any error occurs, we emit an event with the error message.
251 output.fill(MemoryValue::from<FF>(0)); // Default output in case of error
252 events.emit({ .execution_clk = execution_clk,
253 .space_id = space_id,
254 .state_addr = state_addr,
255 .input_addr = input_addr,
256 .output_addr = output_addr,
257 .state = state,
258 .input = input,
259 .output = output });
260
261 // Rethrow the exception after emitting the event
262 throw;
263 }
264}
265
266} // namespace bb::avm2::simulation
#define BB_ASSERT(expression,...)
Definition assert.hpp:70
ValueTag get_tag() const
virtual uint32_t get_execution_id() const =0
MemoryValue modulo_sum(std::span< const MemoryValue > values)
Sum a span of U32 MemoryValues and return the result modulo 2^32.
Definition sha256.cpp:89
EventEmitterInterface< Sha256CompressionEvent > & events
Definition sha256.hpp:47
void compression(MemoryInterface &memory, MemoryAddress state_addr, MemoryAddress input_addr, MemoryAddress output_addr) override
Execute the SHA-256 compression function: read state and input from memory, compress,...
Definition sha256.cpp:129
MemoryValue shr(const MemoryValue &x, uint8_t shift)
Perform a 32-bit right shift on a MemoryValue.
Definition sha256.cpp:68
ExecutionIdGetterInterface & execution_id_manager
Definition sha256.hpp:43
MemoryValue ror(const MemoryValue &x, uint8_t shift)
Perform a 32-bit right rotation on a MemoryValue.
Definition sha256.cpp:43
FF a
FF b
AVM range check gadget for witness generation.
uint32_t MemoryAddress
Inner sum(Cont< Inner, Args... > const &in)
Definition container.hpp:70
constexpr ScalarIndex shift(ScalarIndex ctx, size_t d)
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
VectorField result