block.rs

cdk-rsx/crates/cdk-rsx-rechain/src/block.rs

block.rs298 lines← SDK documentation
1//! V3 records separate original-body commitment from the public header chain.2use crate::settings::{CommitmentMode, MAX_READ_POLICY_BYTES, RecordContract};3use blake3::Hasher;4pub type Hash = [u8; 32];5#[cfg(not(feature = "tripwire-workload"))]6pub const HASH_FORMAT: &str = "blake3-header-body-v3";7#[cfg(feature = "tripwire-workload")]8pub const HASH_FORMAT: &str = "blake3-tripwire-header-body-v3";9pub const RECORD_FORMAT: u16 = 3;10#[cfg(feature = "tripwire-workload")]11mod tripwire;12#[cfg(all(feature = "tripwire-workload", not(target_family = "wasm")))]13pub use tripwire::header_layout;14#[cfg(feature = "tripwire-workload")]15pub use tripwire::{decode_header, encode_header};16#[cfg(not(feature = "tripwire-workload"))]17pub fn encode_header(value: &RecordHeader) -> Result<Vec<u8>, String> {18    encode(value)19}20#[cfg(not(feature = "tripwire-workload"))]21pub fn decode_header(bytes: &[u8]) -> Result<RecordHeader, String> {22    decode(bytes)23}24#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Serialize, serde::Deserialize)]25pub struct RecordContext {26    pub source: cdk_rsx::Principal,27    pub genesis: Hash,28    pub chain: u8,29    pub index: u64,30    pub phash: Option<Hash>,31    pub committed_at_ns: u64,32    pub contract: RecordContract,33    pub blinding_epoch: u64,34}35#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Serialize, serde::Deserialize)]36pub struct RecordHeader {37    pub format: u16,38    pub context: RecordContext,39    #[serde(with = "cdk_rsx::wire::bytes")]40    pub read_policy: Vec<u8>,41}42pub struct RecordedPayload {43    pub bytes: Vec<u8>,44    pub read_policy: Vec<u8>,45}46impl RecordedPayload {47    pub fn new(bytes: Vec<u8>) -> Self {48        Self {49            bytes,50            read_policy: Vec::new(),51        }52    }53}54/// Trusted host context, never decoded from a user's method arguments.55#[derive(Clone, Copy, Debug)]56pub struct ReadContext {57    pub caller: cdk_rsx::Principal,58    pub now_ns: u64,59}60impl ReadContext {61    pub fn from_system() -> Self {62        Self {63            caller: cdk_rsx::api::msg_caller(),64            now_ns: cdk_rsx::api::time(),65        }66    }67}68#[derive(Clone, Debug, PartialEq, Eq)]69pub enum ReadDecision {70    Original,71    Redacted(Vec<u8>),72    Restricted,73}74#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Serialize, serde::Deserialize)]75pub enum Disclosure {76    Original {77        #[serde(with = "cdk_rsx::wire::bytes")]78        payload: Vec<u8>,79        opening: Hash,80    },81    Redacted {82        #[serde(with = "cdk_rsx::wire::bytes")]83        payload: Vec<u8>,84    },85    Restricted,86}87#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Serialize, serde::Deserialize)]88pub struct Block {89    pub header: RecordHeader,90    #[serde(with = "cdk_rsx::wire::bytes")]91    pub payload: Vec<u8>,92    pub opening: Hash,93}94#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Serialize, serde::Deserialize)]95pub struct ReadBlock {96    pub header: RecordHeader,97    pub payload_commitment: Hash,98    pub disclosure: Disclosure,99}100#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Serialize, serde::Deserialize)]101pub struct ServiceBlock {102    pub id: u64,103    pub block: ReadBlock,104}105#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Serialize, serde::Deserialize)]106pub struct OriginalServiceBlock {107    pub id: u64,108    pub block: Block,109}110pub fn validate_parts(header: &RecordHeader, payload: &[u8], opening: &Hash) -> Result<(), String> {111    let c = &header.context;112    if header.format != RECORD_FORMAT113        || header.read_policy.len() > MAX_READ_POLICY_BYTES114        || payload.len() > 1_000_000115        || (c.index == 0) != c.phash.is_none()116    {117        return Err("invalid record framing".into());118    }119    match c.contract.commitment {120        CommitmentMode::Public if c.blinding_epoch != 0 || *opening != [0; 32] => {121            Err("invalid public record opening".into())122        }123        CommitmentMode::Blinded if c.blinding_epoch == 0 => {124            Err("missing record blinding epoch".into())125        }126        _ => Ok(()),127    }128}129pub fn payload_commitment(payload: &[u8], opening: &Hash) -> Hash {130    let mut hash = Hasher::new();131    hash.update(b"rechain/body-commitment/v3\0");132    hash.update(opening);133    hash.update(&(payload.len() as u64).to_le_bytes());134    hash.update(payload);135    *hash.finalize().as_bytes()136}137pub fn header_hash(header: &RecordHeader, commitment: &Hash) -> Hash {138    let mut hash = Hasher::new();139    hash.update(b"rechain/header-chain/v3\0");140    #[cfg(feature = "tripwire-workload")]141    tripwire::with_header(header, |bytes| {142        hash.update(bytes);143    });144    #[cfg(not(feature = "tripwire-workload"))]145    cdk_rsx_wire::with_encoded(146        header,147        cdk_rsx_reactor::wire::PAYLOAD_LIMITS,148        &mut [0; 128],149        |bytes| {150            // The V3 commitment owns the fixed header bytes. The Wire helper151            // writes an empty message extension block after that exact core.152            let header = bytes.strip_suffix(&[0]).expect("empty header extensions");153            hash.update(header);154        },155    )156    .expect("validated bounded record header");157    hash.update(commitment);158    *hash.finalize().as_bytes()159}160pub fn read_parts(161    header: &RecordHeader,162    payload: &[u8],163    opening: &Hash,164    decision: ReadDecision,165) -> ReadBlock {166    let disclosure = match decision {167        ReadDecision::Original => Disclosure::Original {168            payload: payload.to_vec(),169            opening: *opening,170        },171        ReadDecision::Redacted(payload) => Disclosure::Redacted { payload },172        ReadDecision::Restricted => Disclosure::Restricted,173    };174    ReadBlock {175        header: header.clone(),176        payload_commitment: payload_commitment(payload, opening),177        disclosure,178    }179}180impl Block {181    pub fn validate(&self) -> Result<(), String> {182        validate_parts(&self.header, &self.payload, &self.opening)183    }184    pub fn payload_commitment(&self) -> Hash {185        payload_commitment(&self.payload, &self.opening)186    }187    pub fn hash(&self) -> Hash {188        header_hash(&self.header, &self.payload_commitment())189    }190    pub fn read_view(&self, decision: ReadDecision) -> ReadBlock {191        read_parts(&self.header, &self.payload, &self.opening, decision)192    }193}194impl ReadBlock {195    pub fn hash(&self) -> Hash {196        header_hash(&self.header, &self.payload_commitment)197    }198    pub fn into_original(self) -> Result<Block, String> {199        let Disclosure::Original { payload, opening } = self.disclosure else {200            return Err("record is not disclosed for replay".into());201        };202        let block = Block {203            header: self.header,204            payload,205            opening,206        };207        block.validate()?;208        if block.payload_commitment() != self.payload_commitment {209            return Err("record opening does not match commitment".into());210        }211        Ok(block)212    }213}214pub fn encode<T: serde::Serialize>(action: &T) -> Result<Vec<u8>, String> {215    cdk_rsx_wire::encode(action, cdk_rsx_reactor::wire::PAYLOAD_LIMITS).map_err(|e| e.to_string())216}217pub fn decode<T: serde::de::DeserializeOwned>(payload: &[u8]) -> Result<T, String> {218    cdk_rsx_wire::decode(payload, cdk_rsx_reactor::wire::PAYLOAD_LIMITS).map_err(|e| e.to_string())219}220#[cfg(test)]221mod tests {222    use super::*;223    fn block() -> Block {224        Block {225            header: RecordHeader {226                format: RECORD_FORMAT,227                context: RecordContext {228                    source: cdk_rsx::Principal::anonymous(),229                    genesis: [7; 32],230                    chain: 0,231                    index: 0,232                    phash: None,233                    committed_at_ns: 10,234                    contract: RecordContract::IDENTITY,235                    blinding_epoch: 0,236                },237                read_policy: Vec::new(),238            },239            payload: vec![1, 2, 3],240            opening: [0; 32],241        }242    }243    #[test]244    fn restricted_and_redacted_views_keep_verifiable_original_header_hash() {245        let original = block();246        for decision in [247            ReadDecision::Original,248            ReadDecision::Redacted(vec![9]),249            ReadDecision::Restricted,250        ] {251            let view = original.read_view(decision.clone());252            assert_eq!(view.hash(), original.hash());253            if decision == ReadDecision::Original {254                assert_eq!(view.into_original().unwrap(), original);255            } else {256                assert!(view.into_original().is_err());257            }258        }259    }260    #[test]261    fn body_opening_and_header_context_are_bound() {262        let original = block();263        let mut view = original.read_view(ReadDecision::Original);264        if let Disclosure::Original { payload, .. } = &mut view.disclosure {265            payload[0] ^= 1;266        }267        assert!(view.into_original().is_err());268        let mut other = original.clone();269        other.header.context.committed_at_ns += 1;270        assert_ne!(other.hash(), original.hash());271        other = original.clone();272        other.header.read_policy.push(1);273        assert_ne!(other.hash(), original.hash());274        other = original.clone();275        other.header.context.genesis[0] ^= 1;276        assert_ne!(other.hash(), original.hash());277    }278    #[test]279    fn v3_hash_framing_is_explicit_and_restricted_tail_is_verifiable() {280        let original = block();281        let mut body = Vec::from(b"rechain/body-commitment/v3\0".as_slice());282        body.extend_from_slice(&original.opening);283        body.extend_from_slice(&(original.payload.len() as u64).to_le_bytes());284        body.extend_from_slice(&original.payload);285        let expected_commitment = *blake3::hash(&body).as_bytes();286        let mut public = Vec::from(b"rechain/header-chain/v3\0".as_slice());287        let header = encode_header(&original.header).unwrap();288        #[cfg(not(feature = "tripwire-workload"))]289        let header = header.strip_suffix(&[0]).unwrap();290        public.extend_from_slice(&header);291        public.extend_from_slice(&expected_commitment);292        let expected_hash = *blake3::hash(&public).as_bytes();293        let restricted = original.read_view(ReadDecision::Restricted);294        assert_eq!(restricted.payload_commitment, expected_commitment);295        assert_eq!(restricted.hash(), expected_hash);296        assert_eq!(original.hash(), expected_hash);297    }298}