Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
sha256.fuzzer.cpp
Go to the documentation of this file.
1#include "sha256.hpp"
5#include <array>
6#include <cassert>
7#include <cstdint>
8
9using namespace bb;
10using namespace bb::stdlib;
11
27// Convert 4 bytes to uint32_t (big-endian, as per SHA-256 spec)
28static uint32_t bytes_to_uint32(const uint8_t* bytes)
29{
30 return (static_cast<uint32_t>(bytes[0]) << 24) | (static_cast<uint32_t>(bytes[1]) << 16) |
31 (static_cast<uint32_t>(bytes[2]) << 8) | static_cast<uint32_t>(bytes[3]);
32}
33
34extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size)
35{
36 // SHA-256 compression input: 32 bytes h_init (8 x uint32) + 64 bytes block (16 x uint32)
37 constexpr size_t SHA256_BLOCK_INPUT_SIZE = 96;
38 if (Size < SHA256_BLOCK_INPUT_SIZE) {
39 return 0;
40 }
41
42 // Parse h_init (8 x 32-bit words) from first 32 bytes
43 std::array<uint32_t, 8> h_init_native;
44 for (size_t i = 0; i < 8; i++) {
45 h_init_native[i] = bytes_to_uint32(Data + i * 4);
46 }
47
48 // Parse block (16 x 32-bit words) from next 64 bytes
49 std::array<uint32_t, 16> block_native;
50 for (size_t i = 0; i < 16; i++) {
51 block_native[i] = bytes_to_uint32(Data + 32 + i * 4);
52 }
53
54 // Compute native result
55 auto expected_output = crypto::sha256_block(h_init_native, block_native);
56
57 // Build circuit with compression
59
60 // Convert state to circuit field elements
62 for (size_t i = 0; i < 8; i++) {
63 h_init[i] = witness_t<UltraCircuitBuilder>(&builder, h_init_native[i]);
64 }
65
67 for (size_t i = 0; i < 16; i++) {
68 block[i] = witness_t<UltraCircuitBuilder>(&builder, block_native[i]);
69 }
70
71 // Run circuit compression
72 auto circuit_output = SHA256<UltraCircuitBuilder>::sha256_block(h_init, block);
73
74 // Verify circuit correctness
76
77 // Compare outputs
78 for (size_t i = 0; i < 8; i++) {
79 uint32_t circuit_val = static_cast<uint32_t>(uint256_t(circuit_output[i].get_value()));
80 assert(circuit_val == expected_output[i]);
81 }
82
83 return 0;
84}
static bool check(const Builder &circuit)
Check the witness satisifies the circuit.
static std::array< field_ct, 8 > sha256_block(const std::array< field_ct, 8 > &h_init, const std::array< field_ct, 16 > &input)
Apply the SHA-256 compression function to a single 512-bit message block.
Definition sha256.cpp:248
AluTraceBuilder builder
Definition alu.test.cpp:124
std::array< uint32_t, 8 > sha256_block(const std::array< uint32_t, 8 > &h_init, const std::array< uint32_t, 16 > &input)
SHA-256 compression function (FIPS 180-4 Section 6.2.2)
Definition sha256.cpp:73
Entry point for Barretenberg command-line interface.
Definition api.hpp:5
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)