feat(sha3_chain): add simple SHA3_G integration test
Phase 3.2: Verifies module chaining works. - sha3_chain_top.v: 3-state FSM (IDLE→BUSY→DONE), feeds d_in→sha3_top(G) - Captures rho[255:0] and sigma[511:256] from SHA3-512 output - Verified: 3/3 bit-exact vs Python G(d||k=2) reference KG full-path FSM (~11 module chain) deferred — too complex for single dispatch.
This commit is contained in:
179
sync_rtl/sha3_chain/TB/tb_sha3_chain.cpp
Normal file
179
sync_rtl/sha3_chain/TB/tb_sha3_chain.cpp
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
// tb_sha3_chain.cpp - Verilator C++ testbench for sha3_chain_top
|
||||||
|
//
|
||||||
|
// Reads test vectors from +VECTOR_FILE= plusarg.
|
||||||
|
// Format: one 64-char hex string per line (256-bit d).
|
||||||
|
//
|
||||||
|
// Drives d_in, asserts start_i, waits for done_o,
|
||||||
|
// prints "RESULT: RHO_HEX SIGMA_HEX\n" to stdout.
|
||||||
|
//
|
||||||
|
// Clock: 10ns period. Reset: 2 cycles.
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstdint>
|
||||||
|
#include "Vsha3_chain_top.h"
|
||||||
|
#include "verilated.h"
|
||||||
|
|
||||||
|
#define CLK_PERIOD_NS 10.0
|
||||||
|
#define TIMEOUT_CYCLES 500000
|
||||||
|
|
||||||
|
static vluint64_t main_time = 0;
|
||||||
|
|
||||||
|
double sc_time_stamp() {
|
||||||
|
return main_time;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One full clock cycle (both edges + eval)
|
||||||
|
static void posedge(Vsha3_chain_top* dut) {
|
||||||
|
dut->clk = !dut->clk;
|
||||||
|
main_time += (vluint64_t)(CLK_PERIOD_NS / 2.0);
|
||||||
|
dut->eval();
|
||||||
|
dut->clk = !dut->clk;
|
||||||
|
main_time += (vluint64_t)(CLK_PERIOD_NS / 2.0);
|
||||||
|
dut->eval();
|
||||||
|
}
|
||||||
|
|
||||||
|
static int hex_char_to_nibble(char c) {
|
||||||
|
if (c >= '0' && c <= '9') return c - '0';
|
||||||
|
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||||
|
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse 64-char hex string into 8 x 32-bit WData words (256 bits).
|
||||||
|
// Hex is MSB-first (leftmost = bits [255:252]).
|
||||||
|
// data[0] = bits[31:0], data[7] = bits[255:224].
|
||||||
|
static void hex_to_256(const std::string& hex, uint32_t data_words[8]) {
|
||||||
|
for (int w = 0; w < 8; w++) data_words[w] = 0;
|
||||||
|
|
||||||
|
int nibble_idx = 0;
|
||||||
|
for (int i = (int)hex.length() - 1; i >= 0; i--) {
|
||||||
|
char c = hex[i];
|
||||||
|
if (c == ' ' || c == '\t') continue;
|
||||||
|
int nib = hex_char_to_nibble(c);
|
||||||
|
int word_idx = nibble_idx / 8;
|
||||||
|
int shift = (nibble_idx % 8) * 4;
|
||||||
|
if (word_idx < 8) {
|
||||||
|
data_words[word_idx] |= ((uint32_t)nib << shift);
|
||||||
|
}
|
||||||
|
nibble_idx++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print rho_out and sigma_out as hex (MSB-first), space-separated.
|
||||||
|
// rho[0]=bits[31:0], rho[7]=bits[255:224]
|
||||||
|
// sigma[0]=bits[31:0], sigma[7]=bits[255:224]
|
||||||
|
static void print_256_hex(uint32_t data_words[8]) {
|
||||||
|
for (int w = 7; w >= 0; w--) {
|
||||||
|
uint32_t val = data_words[w];
|
||||||
|
for (int j = 28; j >= 0; j -= 4) {
|
||||||
|
printf("%01X", (int)((val >> j) & 0xF));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
Verilated::commandArgs(argc, argv);
|
||||||
|
|
||||||
|
// Parse +VECTOR_FILE= plusarg
|
||||||
|
const char* vector_file = NULL;
|
||||||
|
for (int i = 1; i < argc; i++) {
|
||||||
|
std::string arg(argv[i]);
|
||||||
|
if (arg.rfind("+VECTOR_FILE=", 0) == 0) {
|
||||||
|
vector_file = argv[i] + 13;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!vector_file) {
|
||||||
|
std::cerr << "ERROR: +VECTOR_FILE= not specified" << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::ifstream infile(vector_file);
|
||||||
|
if (!infile.is_open()) {
|
||||||
|
std::cerr << "ERROR: Cannot open vector file: " << vector_file << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Instantiate DUT
|
||||||
|
Vsha3_chain_top* dut = new Vsha3_chain_top;
|
||||||
|
|
||||||
|
// Initialize
|
||||||
|
dut->clk = 0;
|
||||||
|
dut->rst_n = 0;
|
||||||
|
for (int w = 0; w < 8; w++) dut->d_in[w] = 0;
|
||||||
|
dut->start_i = 0;
|
||||||
|
|
||||||
|
// Reset: 2 full cycles
|
||||||
|
for (int i = 0; i < 2; i++) posedge(dut);
|
||||||
|
dut->rst_n = 1;
|
||||||
|
|
||||||
|
std::string line;
|
||||||
|
vluint64_t cycle = 0;
|
||||||
|
int vec_count = 0;
|
||||||
|
|
||||||
|
while (std::getline(infile, line)) {
|
||||||
|
if (line.empty() || line[0] == '#') continue;
|
||||||
|
|
||||||
|
std::string d_hex = line;
|
||||||
|
// Trim trailing whitespace
|
||||||
|
while (!d_hex.empty() && (d_hex.back() == ' ' || d_hex.back() == '\t' || d_hex.back() == '\r'))
|
||||||
|
d_hex.pop_back();
|
||||||
|
|
||||||
|
// Parse d
|
||||||
|
uint32_t d_words[8];
|
||||||
|
hex_to_256(d_hex, d_words);
|
||||||
|
for (int w = 0; w < 8; w++) dut->d_in[w] = d_words[w];
|
||||||
|
|
||||||
|
// Assert start_i
|
||||||
|
dut->start_i = 1;
|
||||||
|
|
||||||
|
// One cycle with start_i=1
|
||||||
|
cycle++;
|
||||||
|
posedge(dut);
|
||||||
|
|
||||||
|
// De-assert start_i
|
||||||
|
dut->start_i = 0;
|
||||||
|
|
||||||
|
// Wait for done_o
|
||||||
|
while (!dut->done_o) {
|
||||||
|
posedge(dut);
|
||||||
|
cycle++;
|
||||||
|
if (cycle > TIMEOUT_CYCLES) {
|
||||||
|
std::cerr << "ERROR: Timeout waiting for done_o (vec " << vec_count << ")" << std::endl;
|
||||||
|
goto done;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read outputs
|
||||||
|
uint32_t rho_words[8], sigma_words[8];
|
||||||
|
for (int w = 0; w < 8; w++) {
|
||||||
|
rho_words[w] = dut->rho_out[w];
|
||||||
|
sigma_words[w] = dut->sigma_out[w];
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("RESULT: ");
|
||||||
|
print_256_hex(rho_words);
|
||||||
|
printf(" ");
|
||||||
|
print_256_hex(sigma_words);
|
||||||
|
printf("\n");
|
||||||
|
|
||||||
|
// One cycle with done_o high, then start_i must be low to return to IDLE
|
||||||
|
posedge(dut);
|
||||||
|
cycle++;
|
||||||
|
vec_count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
done:
|
||||||
|
infile.close();
|
||||||
|
delete dut;
|
||||||
|
|
||||||
|
if (vec_count == 0) {
|
||||||
|
std::cerr << "ERROR: No vectors processed" << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
93
sync_rtl/sha3_chain/sha3_chain_top.v
Normal file
93
sync_rtl/sha3_chain/sha3_chain_top.v
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
// sha3_chain_top.v - Simple integration module: d → SHA3_G(d||k=2)
|
||||||
|
//
|
||||||
|
// Feeds external 256-bit d to sha3_top in G mode with k=2, captures
|
||||||
|
// rho (first 256 bits) and sigma (next 256 bits) from the hash output.
|
||||||
|
//
|
||||||
|
// 3-state FSM: IDLE → BUSY → DONE
|
||||||
|
//
|
||||||
|
// Interface:
|
||||||
|
// clk, rst_n - clock, active-low reset
|
||||||
|
// d_in[255:0] - 256-bit d input (external, NOT from RNG)
|
||||||
|
// start_i - start computation
|
||||||
|
// done_o - computation complete
|
||||||
|
// rho_out - G output first 256 bits
|
||||||
|
// sigma_out - G output next 256 bits
|
||||||
|
|
||||||
|
module sha3_chain_top (
|
||||||
|
input clk,
|
||||||
|
input rst_n,
|
||||||
|
input [255:0] d_in,
|
||||||
|
input start_i,
|
||||||
|
output done_o,
|
||||||
|
output [255:0] rho_out,
|
||||||
|
output [255:0] sigma_out
|
||||||
|
);
|
||||||
|
|
||||||
|
localparam ST_IDLE = 2'd0;
|
||||||
|
localparam ST_BUSY = 2'd1;
|
||||||
|
localparam ST_DONE = 2'd2;
|
||||||
|
|
||||||
|
reg [1:0] state_r, state_next;
|
||||||
|
|
||||||
|
// ── sha3_top signals ──
|
||||||
|
wire [511:0] sha3_data_i;
|
||||||
|
wire sha3_valid_i;
|
||||||
|
wire sha3_ready_o;
|
||||||
|
wire [511:0] sha3_hash_o;
|
||||||
|
wire sha3_valid_o;
|
||||||
|
|
||||||
|
// data_i = {248'b0, k=8'd2, d_in}
|
||||||
|
assign sha3_data_i = {248'b0, 8'd2, d_in};
|
||||||
|
|
||||||
|
sha3_top u_sha3 (
|
||||||
|
.clk (clk),
|
||||||
|
.rst_n (rst_n),
|
||||||
|
.mode (2'b00), // G mode (SHA3-512)
|
||||||
|
.data_i (sha3_data_i),
|
||||||
|
.valid_i (sha3_valid_i),
|
||||||
|
.ready_o (sha3_ready_o),
|
||||||
|
.hash_o (sha3_hash_o),
|
||||||
|
.valid_o (sha3_valid_o),
|
||||||
|
.ready_i (1'b1) // always accept output
|
||||||
|
);
|
||||||
|
|
||||||
|
// valid_i: assert when IDLE + start_i + sha3 ready
|
||||||
|
assign sha3_valid_i = (state_r == ST_IDLE) && start_i && sha3_ready_o;
|
||||||
|
|
||||||
|
// done_o
|
||||||
|
assign done_o = (state_r == ST_DONE);
|
||||||
|
|
||||||
|
// ── output registers ──
|
||||||
|
reg [255:0] rho_out_r, sigma_out_r;
|
||||||
|
assign rho_out = rho_out_r;
|
||||||
|
assign sigma_out = sigma_out_r;
|
||||||
|
|
||||||
|
// ── FSM combinational next-state ──
|
||||||
|
always @(*) begin
|
||||||
|
state_next = state_r;
|
||||||
|
case (state_r)
|
||||||
|
ST_IDLE: if (start_i && sha3_ready_o) state_next = ST_BUSY;
|
||||||
|
ST_BUSY: if (sha3_valid_o) state_next = ST_DONE;
|
||||||
|
ST_DONE: if (!start_i) state_next = ST_IDLE;
|
||||||
|
default: state_next = ST_IDLE;
|
||||||
|
endcase
|
||||||
|
end
|
||||||
|
|
||||||
|
// ── sequential logic ──
|
||||||
|
always @(posedge clk or negedge rst_n) begin
|
||||||
|
if (!rst_n) begin
|
||||||
|
state_r <= ST_IDLE;
|
||||||
|
rho_out_r <= 256'd0;
|
||||||
|
sigma_out_r <= 256'd0;
|
||||||
|
end else begin
|
||||||
|
state_r <= state_next;
|
||||||
|
|
||||||
|
// Capture output when BUSY → DONE
|
||||||
|
if (state_r == ST_BUSY && sha3_valid_o) begin
|
||||||
|
rho_out_r <= sha3_hash_o[255:0];
|
||||||
|
sigma_out_r <= sha3_hash_o[511:256];
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
endmodule
|
||||||
126
test_framework/modules/sha3_chain/gen_vectors.py
Normal file
126
test_framework/modules/sha3_chain/gen_vectors.py
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
"""gen_vectors.py - Test vector generator for sha3_chain module.
|
||||||
|
|
||||||
|
Generates random 256-bit d, computes G(d||k=2) using Python reference,
|
||||||
|
and outputs rho (first 256 bits) and sigma (next 256 bits).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# Add test_framework/lib to path for VectorGenerator base class
|
||||||
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'lib'))
|
||||||
|
|
||||||
|
# Add Python reference path
|
||||||
|
_REF_PATH = os.path.expanduser(
|
||||||
|
"~/Dev/server_code/python_project/PQC_2025/A_ML_KEM_v0")
|
||||||
|
sys.path.insert(0, _REF_PATH)
|
||||||
|
|
||||||
|
import SHA_3
|
||||||
|
|
||||||
|
from vector_gen import VectorGenerator
|
||||||
|
|
||||||
|
|
||||||
|
def _bits_to_hex(bits_str, num_bits):
|
||||||
|
"""Convert binary string (LSB-first: bits_str[0] = bit 0) to hex.
|
||||||
|
|
||||||
|
Returns hex with MSB-nibble first (matching Verilog %X format).
|
||||||
|
Each group of 4 bits forms a nibble: bit[i+3:i] → two hex chars.
|
||||||
|
"""
|
||||||
|
result = []
|
||||||
|
for i in range(0, num_bits, 4):
|
||||||
|
nib = 0
|
||||||
|
for j in range(4):
|
||||||
|
pos = i + j
|
||||||
|
if pos < len(bits_str) and bits_str[pos] == '1':
|
||||||
|
nib |= (1 << j)
|
||||||
|
result.insert(0, '0123456789ABCDEF'[nib])
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
|
||||||
|
def _random_bits(length):
|
||||||
|
"""Generate a random binary string of given length (LSB-first)."""
|
||||||
|
val = random.getrandbits(length)
|
||||||
|
bits = ''
|
||||||
|
for i in range(length):
|
||||||
|
bits += '1' if (val & (1 << i)) else '0'
|
||||||
|
return bits
|
||||||
|
|
||||||
|
|
||||||
|
def _k_bits(k_val):
|
||||||
|
"""Convert integer k to 8-bit LSB-first binary string.
|
||||||
|
|
||||||
|
k=2 → "01000000" (bit 0=0, bit 1=1)
|
||||||
|
"""
|
||||||
|
bits = ''
|
||||||
|
for i in range(8):
|
||||||
|
bits += '1' if (k_val & (1 << i)) else '0'
|
||||||
|
return bits
|
||||||
|
|
||||||
|
|
||||||
|
class Sha3ChainVectorGenerator(VectorGenerator):
|
||||||
|
"""Generates test vectors for sha3_chain_top module."""
|
||||||
|
|
||||||
|
def generate_one(self, params: dict) -> dict:
|
||||||
|
"""Generate a single test vector.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
params: dict with 'k' key (default 2 for ML-KEM-512).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict with 'input' and 'expected' keys.
|
||||||
|
"""
|
||||||
|
k_val = params.get('k', 2)
|
||||||
|
|
||||||
|
# Generate random 256-bit d (LSB-first binary string)
|
||||||
|
d = _random_bits(256)
|
||||||
|
k_str = _k_bits(k_val)
|
||||||
|
|
||||||
|
# Compute G(d, k): SHA3-512 of d||k (both LSB-first binary)
|
||||||
|
expected_bits = SHA_3.G(d, k_str)
|
||||||
|
|
||||||
|
# rho = first 256 bits, sigma = next 256 bits
|
||||||
|
rho_bits = expected_bits[0:256]
|
||||||
|
sigma_bits = expected_bits[256:512]
|
||||||
|
|
||||||
|
# Convert to hex (MSB-first)
|
||||||
|
d_hex = _bits_to_hex(d, 256)
|
||||||
|
rho_hex = _bits_to_hex(rho_bits, 256)
|
||||||
|
sigma_hex = _bits_to_hex(sigma_bits, 256)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'input': {
|
||||||
|
'd': d_hex
|
||||||
|
},
|
||||||
|
'expected': {
|
||||||
|
'rho': rho_hex,
|
||||||
|
'sigma': sigma_hex
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_hex_file(self, vectors: list[dict], filepath: str) -> None:
|
||||||
|
"""Write input vectors: one 64-char d-hex per line.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
vectors: List of vector dicts from generate_one().
|
||||||
|
filepath: Path to write the hex file.
|
||||||
|
"""
|
||||||
|
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
||||||
|
with open(filepath, 'w') as f:
|
||||||
|
for v in vectors:
|
||||||
|
d_hex = v['input']['d']
|
||||||
|
f.write(f'{d_hex}\n')
|
||||||
|
|
||||||
|
def write_expected_file(self, vectors: list[dict], filepath: str) -> None:
|
||||||
|
"""Write expected output: "RHO_HEX SIGMA_HEX" per line (128 chars).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
vectors: List of vector dicts from generate_one().
|
||||||
|
filepath: Path to write the expected hex file.
|
||||||
|
"""
|
||||||
|
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
||||||
|
with open(filepath, 'w') as f:
|
||||||
|
for v in vectors:
|
||||||
|
rho_hex = v['expected']['rho']
|
||||||
|
sigma_hex = v['expected']['sigma']
|
||||||
|
f.write(f'{rho_hex} {sigma_hex}\n')
|
||||||
14
test_framework/modules/sha3_chain/test_plan.json
Normal file
14
test_framework/modules/sha3_chain/test_plan.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"module": "sha3_chain",
|
||||||
|
"rtl_top": "sync_rtl/sha3_chain/sha3_chain_top.v",
|
||||||
|
"rtl_deps": ["sync_rtl/sha3/keccak_round.v", "sync_rtl/sha3/keccak_core.v", "sync_rtl/sha3/sha3_top.v"],
|
||||||
|
"tb_cpp": "sync_rtl/sha3_chain/TB/tb_sha3_chain.cpp",
|
||||||
|
"timeout_s": 60,
|
||||||
|
"cases": [{
|
||||||
|
"id": "basic",
|
||||||
|
"description": "d → SHA3_G(d||k=2) → rho, sigma vs Python G()",
|
||||||
|
"params": {"k": 2},
|
||||||
|
"num_vectors": 3,
|
||||||
|
"tolerance": "bit_exact"
|
||||||
|
}]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user