use sha2::{Digest, Sha256};
use crate::payload::{GateError, GateVariant, WritePayload, WriteReceipt};
pub trait WriteGate: Send + Sync {
fn admit(&mut self, payload: &WritePayload) -> Result<WriteReceipt, GateError>;
fn verify_receipt(&self, receipt: &WriteReceipt) -> bool;
fn chain_root(&self) -> [u8; 32];
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn variant(&self) -> GateVariant;
}
pub struct NullGate {
seq: u64,
}
impl NullGate {
pub fn new() -> Self {
Self { seq: 0 }
}
}
impl Default for NullGate {
fn default() -> Self {
Self::new()
}
}
impl WriteGate for NullGate {
fn admit(&mut self, _payload: &WritePayload) -> Result<WriteReceipt, GateError> {
let seq = self.seq;
self.seq += 1;
Ok(WriteReceipt {
sequence: seq,
payload_hash: [0u8; 32],
chain_commitment: [0u8; 32],
gate_variant: GateVariant::Null,
})
}
fn verify_receipt(&self, _receipt: &WriteReceipt) -> bool {
true
}
fn chain_root(&self) -> [u8; 32] {
[0u8; 32]
}
fn len(&self) -> usize {
self.seq as usize
}
fn variant(&self) -> GateVariant {
GateVariant::Null
}
}
pub struct HashChainGate {
seq: u64,
prev_commitment: [u8; 32],
chain: Vec<[u8; 32]>,
payload_hashes: Vec<[u8; 32]>,
}
const GENESIS: [u8; 32] = *b"\xb7\x4c\x9b\x41\x3e\x27\x0e\x56\
\xd3\x8a\x12\x9f\x6c\x3b\x4d\x8a\
\x2f\x1e\x0c\x5a\x9d\x7b\xe4\xf2\
\x6a\x8c\x3d\x0b\x5e\x9f\x2c\x47";
impl HashChainGate {
pub fn new() -> Self {
Self {
seq: 0,
prev_commitment: GENESIS,
chain: Vec::new(),
payload_hashes: Vec::new(),
}
}
fn compute_commitment(prev: &[u8; 32], payload_hash: &[u8; 32], seq: u64) -> [u8; 32] {
let mut h = Sha256::new();
h.update(b"ruvector:chain:");
h.update(prev);
h.update(payload_hash);
h.update(&seq.to_le_bytes());
h.finalize().into()
}
pub fn verify_integrity(&self) -> bool {
if self.chain.len() != self.payload_hashes.len() {
return false;
}
let mut prev = GENESIS;
for (i, (commitment, payload_hash)) in
self.chain.iter().zip(self.payload_hashes.iter()).enumerate()
{
let expected = Self::compute_commitment(&prev, payload_hash, i as u64);
if &expected != commitment {
return false;
}
prev = *commitment;
}
self.prev_commitment == prev
}
}
impl Default for HashChainGate {
fn default() -> Self {
Self::new()
}
}
impl WriteGate for HashChainGate {
fn admit(&mut self, payload: &WritePayload) -> Result<WriteReceipt, GateError> {
let payload_hash: [u8; 32] = payload.payload_hash();
let commitment = Self::compute_commitment(&self.prev_commitment, &payload_hash, self.seq);
self.prev_commitment = commitment;
self.chain.push(commitment);
self.payload_hashes.push(payload_hash);
let seq = self.seq;
self.seq += 1;
Ok(WriteReceipt {
sequence: seq,
payload_hash,
chain_commitment: commitment,
gate_variant: GateVariant::HashChain,
})
}
fn verify_receipt(&self, receipt: &WriteReceipt) -> bool {
let idx = receipt.sequence as usize;
idx < self.chain.len() && self.chain[idx] == receipt.chain_commitment
}
fn chain_root(&self) -> [u8; 32] {
self.prev_commitment
}
fn len(&self) -> usize {
self.seq as usize
}
fn variant(&self) -> GateVariant {
GateVariant::HashChain
}
}
pub struct MerkleGate {
seq: u64,
peaks: Vec<[u8; 32]>,
leaf_count: u64,
leaves: Vec<[u8; 32]>,
}
impl MerkleGate {
pub fn new() -> Self {
Self {
seq: 0,
peaks: Vec::new(),
leaf_count: 0,
leaves: Vec::new(),
}
}
fn hash_pair(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
let mut h = Sha256::new();
h.update(b"ruvector:mmr:");
h.update(left);
h.update(right);
h.finalize().into()
}
fn leaf_commit(payload_hash: &[u8; 32], seq: u64) -> [u8; 32] {
let mut h = Sha256::new();
h.update(b"ruvector:leaf:");
h.update(payload_hash);
h.update(&seq.to_le_bytes());
h.finalize().into()
}
fn append(&mut self, leaf: [u8; 32]) {
let mut node = leaf;
let mut n = self.leaf_count;
while n & 1 == 1 {
let peak = self.peaks.pop().expect("peak must exist when bit is set");
node = Self::hash_pair(&peak, &node);
n >>= 1;
}
self.peaks.push(node);
self.leaf_count += 1;
}
fn bagged_root(&self) -> [u8; 32] {
if self.peaks.is_empty() {
return [0u8; 32];
}
let mut acc = self.peaks[0];
for peak in &self.peaks[1..] {
acc = Self::hash_pair(&acc, peak);
}
acc
}
pub fn verify_leaf(&self, sequence: u64, payload_hash: &[u8; 32]) -> bool {
let idx = sequence as usize;
if idx >= self.leaves.len() {
return false;
}
let expected = Self::leaf_commit(payload_hash, sequence);
self.leaves[idx] == expected
}
}
impl Default for MerkleGate {
fn default() -> Self {
Self::new()
}
}
impl WriteGate for MerkleGate {
fn admit(&mut self, payload: &WritePayload) -> Result<WriteReceipt, GateError> {
let payload_hash: [u8; 32] = payload.payload_hash();
let leaf = Self::leaf_commit(&payload_hash, self.seq);
self.leaves.push(leaf);
self.append(leaf);
let root = self.bagged_root();
let seq = self.seq;
self.seq += 1;
Ok(WriteReceipt {
sequence: seq,
payload_hash,
chain_commitment: root,
gate_variant: GateVariant::Merkle,
})
}
fn verify_receipt(&self, receipt: &WriteReceipt) -> bool {
self.verify_leaf(receipt.sequence, &receipt.payload_hash)
}
fn chain_root(&self) -> [u8; 32] {
self.bagged_root()
}
fn len(&self) -> usize {
self.seq as usize
}
fn variant(&self) -> GateVariant {
GateVariant::Merkle
}
}
#[cfg(test)]
mod rederivation_tests {
use super::*;
use crate::WritePayload;
fn gate_with(n: u64) -> HashChainGate {
let mut g = HashChainGate::new();
for i in 0..n {
g.admit(&WritePayload::new(i, vec![i as f32, 1.0, -(i as f32)])).unwrap();
}
g
}
#[test]
fn clean_chain_reverifies() {
assert!(gate_with(8).verify_integrity());
assert!(HashChainGate::new().verify_integrity(), "empty chain is valid");
}
#[test]
fn tampered_commitment_detected() {
let mut g = gate_with(8);
g.chain[3][0] ^= 0xFF; assert!(!g.verify_integrity(), "mutated commitment must fail re-derivation");
}
#[test]
fn tampered_payload_hash_detected() {
let mut g = gate_with(8);
g.payload_hashes[2][0] ^= 0xFF; assert!(!g.verify_integrity(), "mutated payload hash must fail re-derivation");
}
#[test]
fn reordered_entries_detected() {
let mut g = gate_with(8);
g.chain.swap(2, 5);
g.payload_hashes.swap(2, 5);
assert!(!g.verify_integrity(), "reordering entries must fail re-derivation");
}
#[test]
fn length_mismatch_detected() {
let mut g = gate_with(8);
g.payload_hashes.pop();
assert!(!g.verify_integrity());
}
}