feat(phase1): implement RNG, SampleCBD, SampleNTT modules + xsim TBs

Phase 1 complete — all 4 leaf modules verified:
- rng_sync.v: 256-bit Galois LFSR PRNG (10/10 PASS)
- sample_cbd_sync.v: CBD sampler with keccak_core PRF (2560/2560 PASS)
- sample_ntt_sync.v: SHAKE-128 rejection sampling for A matrix (1536/1536 PASS)
- xsim Verilog TBs for sha3 module (tb_sha3_xsim.v, tb_sha3_xsim_simple.v, tb_keccak_core_xsim.v)
This commit is contained in:
2026-06-24 21:32:53 +08:00
parent 453bc899fc
commit 5941fee980
16 changed files with 2398 additions and 0 deletions

View File

@@ -0,0 +1,206 @@
// tb_sample_cbd.cpp - Verilator C++ testbench for sample_cbd_sync
//
// Reads test vectors from +VECTOR_FILE= plusarg.
// Format: "SEED_HEX NONCE_HEX ETA"
// SEED_HEX: 64 hex chars (256-bit seed, MSB-first)
// NONCE_HEX: 2 hex chars (8-bit nonce)
// ETA: "2" or "3" (decimal)
//
// Drives DUT with seed, nonce, eta. Waits for valid_o, collects 256
// coefficients. Prints "RESULT: COEFF_HEX\n" for each coefficient.
//
// Clock: 10ns period. Reset: 2 cycles.
// Timeout: 500000 cycles.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include "Vsample_cbd_sync.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;
}
// Toggle clock: both edges + eval (one full cycle)
static void posedge(Vsample_cbd_sync* 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 hex string (MSB-first) into 8 x 32-bit words for 256-bit seed.
// Word 0 = bits[31:0], word 7 = bits[255:224].
// Hex string: leftmost char = most significant nibble (bits 255:252).
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 len = (int)hex.length();
int nibble_idx = 0;
for (int i = len - 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++;
}
}
// Parse 2-char hex string into an 8-bit value.
// "FF" → 0xFF, "0A" → 0x0A.
static uint8_t hex_to_8(const std::string& hex) {
int val = 0;
for (size_t i = 0; i < hex.length(); i++) {
val = (val << 4) | hex_char_to_nibble(hex[i]);
}
return (uint8_t)(val & 0xFF);
}
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
Vsample_cbd_sync* dut = new Vsample_cbd_sync;
// Initialize
dut->clk = 0;
dut->rst_n = 0;
for (int w = 0; w < 8; w++) dut->seed_i[w] = 0;
dut->nonce_i = 0;
dut->eta_i = 0;
dut->valid_i = 0;
dut->ready_i = 0;
// Reset: 2 full cycles
for (int i = 0; i < 2; i++) posedge(dut);
dut->rst_n = 1;
// Consumer always ready
dut->ready_i = 1;
std::string line;
vluint64_t cycle = 0;
int vec_count = 0;
int total_coeff_count = 0;
while (std::getline(infile, line)) {
if (line.empty() || line[0] == '#') continue;
// Parse: SEED_HEX NONCE_HEX ETA
std::istringstream iss(line);
std::string seed_hex, nonce_hex;
int eta_val;
if (!(iss >> seed_hex >> nonce_hex >> eta_val)) continue;
if (seed_hex.length() < 64) continue;
// Set seed_i (256 bits)
uint32_t seed_words[8];
hex_to_256(seed_hex, seed_words);
for (int w = 0; w < 8; w++) dut->seed_i[w] = seed_words[w];
// Set nonce_i (8 bits)
dut->nonce_i = hex_to_8(nonce_hex);
// Set eta_i (2'd2 or 2'd3)
dut->eta_i = (eta_val == 3) ? 3 : 2;
// Assert valid_i for one cycle
dut->valid_i = 1;
posedge(dut);
cycle++;
dut->valid_i = 0;
// Wait for 256 coefficients
int coeffs_collected = 0;
bool timed_out = false;
while (coeffs_collected < 256) {
posedge(dut);
cycle++;
if (cycle > TIMEOUT_CYCLES) {
std::cerr << "ERROR: Timeout waiting for coeffs (vec "
<< vec_count << ", got " << coeffs_collected
<< "/256)" << std::endl;
timed_out = true;
break;
}
if (dut->valid_o && dut->ready_i) {
// Read 12-bit coefficient and print
uint32_t coeff = dut->coeff_o & 0xFFF;
printf("RESULT: %03X\n", coeff);
coeffs_collected++;
total_coeff_count++;
}
}
if (timed_out) {
goto done;
}
// Wait for DUT to return to IDLE before next vector
int wait_cycles = 0;
while (!dut->ready_o && wait_cycles < 100) {
posedge(dut);
cycle++;
wait_cycles++;
}
vec_count++;
}
done:
infile.close();
delete dut;
if (vec_count == 0) {
std::cerr << "ERROR: No vectors processed" << std::endl;
return 1;
}
return 0;
}

View File

@@ -0,0 +1,305 @@
// sample_cbd_sync.v - Centered Binomial Distribution sampling via SHAKE-256 PRF
//
// Generates 256 polynomial coefficients from a 256-bit seed and 8-bit nonce
// using SHAKE-256 PRF followed by Centered Binomial Distribution (CBD).
//
// Algorithm (FIPS 203 / ML-KEM):
// PRF(sigma, N) = SHAKE-256(sigma || N) squeeze eta*64 bytes
// For each of 256 coefficients:
// eta=2: read 4 bits, coeff = (b0+b1) - (b2+b3)
// eta=3: read 6 bits, coeff = (b0+b1+b2) - (b3+b4+b5)
// Each coefficient in range [-eta, eta], stored as 12-bit signed.
//
// SHAKE-256 parameters:
// rate = 1088 bits, capacity = 512 bits
// suffix = 4'b1111
// pad10*1 padding
//
// Multi-squeeze (eta=3):
// SHAKE-256 squeezes 1088-bit blocks. For eta=3 we need 1536 bits.
// First squeeze provides bits [0:1087], second provides [1088:1535].
// The 1536-bit squeeze_buf accumulates both blocks contiguously:
// After 1st: buf[1087:0] = squeeze1, buf[1535:1088] = 0
// After 2nd: buf[1535:1088] = squeeze2[447:0] (remapped)
// Bit ordering matches Python reference PRF output.
//
// Interface:
// clk, rst_n - clock, active-low reset
// seed_i [255:0] - sigma (256-bit seed)
// nonce_i [7:0] - N counter byte
// eta_i [1:0] - 2'd2 or 2'd3
// valid_i - input valid (start sampling)
// ready_o - module can accept new input
// coeff_o [11:0] - one coefficient per cycle, 12-bit signed
// valid_o - output valid
// ready_i - downstream accepts output
// last_o - high when last coefficient (255th, 0-indexed)
module sample_cbd_sync (
input clk,
input rst_n,
input [255:0] seed_i,
input [7:0] nonce_i,
input [1:0] eta_i, // 2'd2 or 2'd3
input valid_i,
output ready_o,
output [11:0] coeff_o, // 12-bit signed
output valid_o,
input ready_i,
output last_o
);
// ================================================================
// FSM state encoding
// ================================================================
localparam ST_IDLE = 2'd0;
localparam ST_PERMUTE = 2'd1;
localparam ST_SQUEEZE = 2'd2;
reg [1:0] state_r, state_next;
// ================================================================
// SHAKE-256 pad10*1 construction (combinational)
//
// Message: {nonce_i, seed_i} = 264 bits
// In FIPS 202 bit ordering: message[0] = seed_i[0], message[263] = nonce_i[7]
// Padded block (1088 rate bits):
// {1'b1, 818'b0, 1'b1, 4'b1111, nonce_i, seed_i}
//
// Matches Python: PRF(sigma, N) = shake256(sigma||N, d)
// where sigma bits come first (LSB), then N bits, then suffix+padding.
// ================================================================
wire [263:0] message_264;
wire [1087:0] padded_block;
assign message_264 = {nonce_i, seed_i};
assign padded_block = {1'b1, {818{1'b0}}, 1'b1, 4'b1111, message_264};
// Absorb state: capacity (512 bits of zero) || padded rate block
wire [1599:0] absorb_state;
assign absorb_state = {{(1600-1088){1'b0}}, padded_block};
// ================================================================
// Registered inputs (captured on valid_i && ready_o)
// ================================================================
reg [2:0] eta_r; // 2 or 3
reg [7:0] coeff_cnt; // 0..255, number of coeffs output so far
reg [1599:0] keccak_state_r; // current 1600-bit keccak state (for re-permutation)
reg perm_done; // 1 after first keccak permutation completes
// Combinational mux select: absorb_state BEFORE first perm finishes,
// keccak_state_r AFTER. Must be combinational to avoid NBA race
// with kc_valid_i on the IDLEPERMUTE transition edge.
wire first_perm_sel;
assign first_perm_sel = !perm_done;
// ================================================================
// Squeeze buffer (accumulated across multiple squeezes)
// ================================================================
reg [1535:0] squeeze_buf; // accumulated squeeze data
reg [10:0] buf_fill; // valid bits in squeeze_buf (0, 1088, or 1536)
reg [10:0] buf_ptr; // read position within squeeze_buf
reg kc_done_d1; // kc_valid_o delayed by 1 cycle (gate for valid_o)
// ================================================================
// keccak_core instantiation
// ================================================================
wire kc_valid_i;
/* verilator lint_off UNUSEDSIGNAL */
wire kc_ready_o;
/* verilator lint_on UNUSEDSIGNAL */
wire [1599:0] kc_state_o;
wire kc_valid_o;
// Mux: absorb_state for first perm, keccak_state_r for re-permutation
wire [1599:0] kc_state_i;
assign kc_state_i = first_perm_sel ? absorb_state : keccak_state_r;
keccak_core #(.ROUNDS(24)) u_keccak (
.clk (clk),
.rst_n (rst_n),
.state_i (kc_state_i),
.valid_i (kc_valid_i),
.ready_o (kc_ready_o),
.state_o (kc_state_o),
.valid_o (kc_valid_o),
.ready_i (1'b1) // always accept keccak output
);
// ================================================================
// Bits per coefficient
// ================================================================
wire [3:0] bits_per_coeff;
assign bits_per_coeff = (eta_r == 3'd2) ? 4'd4 : 4'd6;
// ================================================================
// CBD computation (combinational)
//
// Extract bits_per_coeff bits from squeeze_buf starting at buf_ptr.
// For eta=2: b0,b1,b2,b3 coeff = (b0+b1) - (b2+b3)
// For eta=3: b0,b1,b2,b3,b4,b5 coeff = (b0+b1+b2) - (b3+b4+b5)
// ================================================================
wire [5:0] cbd_bits;
assign cbd_bits = squeeze_buf[buf_ptr +: 6];
wire [2:0] sum_pos, sum_neg;
// eta=2: sum_pos = b0+b1, sum_neg = b2+b3
wire [2:0] sp2, sn2;
assign sp2 = {2'b00, cbd_bits[0]} + {2'b00, cbd_bits[1]};
assign sn2 = {2'b00, cbd_bits[2]} + {2'b00, cbd_bits[3]};
// eta=3: sum_pos = b0+b1+b2, sum_neg = b3+b4+b5
wire [2:0] sp3, sn3;
assign sp3 = {2'b00, cbd_bits[0]} + {2'b00, cbd_bits[1]} + {2'b00, cbd_bits[2]};
assign sn3 = {2'b00, cbd_bits[3]} + {2'b00, cbd_bits[4]} + {2'b00, cbd_bits[5]};
assign sum_pos = (eta_r == 3'd2) ? sp2 : sp3;
assign sum_neg = (eta_r == 3'd2) ? sn2 : sn3;
wire signed [3:0] coeff_raw;
assign coeff_raw = $signed({1'b0, sum_pos}) - $signed({1'b0, sum_neg});
wire [11:0] coeff_signed;
assign coeff_signed = {{8{coeff_raw[3]}}, coeff_raw[3:0]}; // sign-extend to 12 bits
assign coeff_o = coeff_signed;
// valid_o: suppress for 1 cycle after keccak finishes to avoid
// buf_ptr race between squeeze capture and SQUEEZE advancement.
assign valid_o = (state_r == ST_SQUEEZE) && (buf_fill >= {7'b0, bits_per_coeff}) && !kc_done_d1;
assign last_o = valid_o && (coeff_cnt == 8'd255);
// ================================================================
// FSM: ready_o
// ================================================================
assign ready_o = (state_r == ST_IDLE);
// ================================================================
// kc_valid_i: start keccak_core when transitioning to PERMUTE
// ================================================================
assign kc_valid_i = (state_next == ST_PERMUTE) && (state_r != ST_PERMUTE);
// ================================================================
// Buffer exhaustion detection
// ================================================================
wire [11:0] next_buf_ptr;
assign next_buf_ptr = {1'b0, buf_ptr} + {8'b0, bits_per_coeff};
// buffer will be exhausted after outputting NEXT coefficient
wire buffer_exhaust_next;
assign buffer_exhaust_next = (next_buf_ptr + {8'b0, bits_per_coeff}) > {1'b0, buf_fill};
// Coefficients remaining AFTER the current one
wire [8:0] coeffs_remaining;
assign coeffs_remaining = 9'd256 - {1'b0, coeff_cnt} - 9'd1;
// ================================================================
// FSM combinational next-state logic
// ================================================================
always @(*) begin
state_next = state_r;
case (state_r)
ST_IDLE: begin
if (valid_i && ready_o)
state_next = ST_PERMUTE;
end
ST_PERMUTE: begin
// Wait for keccak_core to finish
if (kc_valid_o)
state_next = ST_SQUEEZE;
end
ST_SQUEEZE: begin
// Output one coeff per cycle when ready
if (valid_o && ready_i) begin
if (coeff_cnt == 8'd255) begin
// Last coefficient was output
state_next = ST_IDLE;
end else if (buffer_exhaust_next && (coeffs_remaining > 9'd0)) begin
// Need more squeeze data: start another keccak permutation
state_next = ST_PERMUTE;
end
// else: stay in SQUEEZE for next coefficient
end
end
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;
eta_r <= 3'd0;
coeff_cnt <= 8'd0;
keccak_state_r <= 1600'd0;
perm_done <= 1'b0;
squeeze_buf <= 1536'd0;
buf_fill <= 11'd0;
buf_ptr <= 11'd0;
kc_done_d1 <= 1'b0;
end else begin
state_r <= state_next;
// Delay kc_valid_o by 1 cycle to gate valid_o
kc_done_d1 <= kc_valid_o;
// ---- Capture inputs on IDLE → PERMUTE transition ----
if (state_r == ST_IDLE && valid_i && ready_o) begin
// Determine eta: 2 or 3
if (eta_i == 2'd2)
eta_r <= 3'd2;
else if (eta_i == 2'd3)
eta_r <= 3'd3;
else
eta_r <= 3'd2; // default
coeff_cnt <= 8'd0;
buf_fill <= 11'd0;
buf_ptr <= 11'd0;
end
// ---- On keccak_core valid_o: latch squeeze data ----
if (kc_valid_o) begin
// Save full 1600-bit state for potential re-permutation
keccak_state_r <= kc_state_o;
if (!perm_done) begin
// First squeeze: fill lower 1088 bits of squeeze_buf
// buf[1087:0] = squeeze data, buf[1535:1088] = 0
squeeze_buf <= {{(1536 - 1088){1'b0}}, kc_state_o[1087:0]};
buf_fill <= 11'd1088;
buf_ptr <= 11'd0;
perm_done <= 1'b1;
end else begin
// Second squeeze: fill upper 448 bits of squeeze_buf
// buf[1535:1088] = squeeze2[447:0], buf[1087:0] preserved
// This remaps: squeeze2[0] → buf[1088], matching Python's contiguous output
squeeze_buf <= {kc_state_o[447:0], squeeze_buf[1087:0]};
buf_fill <= 11'd1536;
// buf_ptr stays at current position (kept from SQUEEZE)
end
end
// ---- SQUEEZE: advance on output ----
if (state_r == ST_SQUEEZE && valid_o && ready_i) begin
buf_ptr <= buf_ptr + {7'b0, bits_per_coeff};
coeff_cnt <= coeff_cnt + 8'd1;
// Clear state on last coeff
if (coeff_cnt == 8'd255) begin
buf_fill <= 11'd0;
buf_ptr <= 11'd0;
// Reset perm_done here (before next IDLE→PERMUTE)
// so the mux selects absorb_state for the next vector.
perm_done <= 1'b0;
end
end
end
end
endmodule