certification.rs

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

certification.rs364 lines← SDK documentation
1//! Transient adaptive publication cache reconstructed from durable chain tips.2//! The host publishes returned digests with certified_data_set and registers3//! `deadline`/`publish_due` on the one shared Reactor scheduler.4use crate::{Stats, block::Hash};56use ic_certification::{AsHashTree, HashTree, NestedTree, fork, pruned};7use std::collections::{BTreeMap, BTreeSet};8const SECOND: u64 = 1_000_000_000;9const CREDIT: u64 = 250_000_000;10const ENTER: u64 = 750_000_000;11const RESUME: u64 = 250_000_000;12#[derive(13    Clone, Copy, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Deserialize, serde::Serialize,14)]15pub enum Tip {16    Empty,17    Unrecorded,18    Tip { index: u64, hash: Hash },19}20impl From<&Stats> for Tip {21    fn from(s: &Stats) -> Self {22        if !s.recorded {23            Self::Unrecorded24        } else {25            match s.phash {26                Some(hash) => Self::Tip {27                    index: s.next_index - 1,28                    hash,29                },30                None => Self::Empty,31            }32        }33    }34}35#[derive(Default)]36pub struct Publisher {37    tree: NestedTree<Vec<u8>, Vec<u8>>,38    application_root: Option<Hash>,39    published: BTreeMap<u8, Tip>,40    latest: BTreeMap<u8, Tip>,41    dirty: BTreeSet<u8>,42    until: u64,43    hot: bool,44    deadline: Option<u64>,45}46#[derive(Clone, Debug, PartialEq, Eq)]47pub struct Proof {48    pub hash_tree: Vec<u8>,49    pub tips: Vec<(u8, Tip)>,50    pub digest: Hash,51}52/// An application witness must reveal the exact branch most recently registered53/// with this publisher. It cannot replace the certified-root owner.54#[derive(Clone, Copy, Debug, PartialEq, Eq)]55pub enum ApplicationWitnessError {56    NotRegistered,57    RootMismatch,58}59fn path(id: u8, name: &[u8]) -> Vec<Vec<u8>> {60    vec![61        b"rechain".to_vec(),62        b"chains".to_vec(),63        vec![id],64        name.to_vec(),65    ]66}67fn uleb(mut n: u64) -> Vec<u8> {68    let mut out = Vec::new();69    loop {70        let byte = (n & 127) as u8;71        n >>= 7;72        out.push(byte | if n > 0 { 128 } else { 0 });73        if n == 0 {74            return out;75        }76    }77}78impl Publisher {79    /// Startup needs at most one small tip per registered chain, not log replay.80    pub fn restore(tips: impl IntoIterator<Item = (u8, Tip)>) -> Self {81        let mut p = Self::default();82        for (id, tip) in tips {83            p.register(id, tip);84        }85        p86    }87    fn put(&mut self, id: u8, tip: Tip) {88        let state = match tip {89            Tip::Empty => 0,90            Tip::Unrecorded => 1,91            Tip::Tip { .. } => 2,92        };93        self.tree.insert(&path(id, b"state"), vec![state]);94        match tip {95            Tip::Tip { index, hash } => {96                self.tree97                    .insert(&path(id, b"last_block_index"), uleb(index));98                self.tree99                    .insert(&path(id, b"last_block_hash"), hash.to_vec());100            }101            _ => {102                self.tree.delete(&path(id, b"last_block_index"));103                self.tree.delete(&path(id, b"last_block_hash"));104            }105        }106        self.published.insert(id, tip);107    }108    /// A new chain publishes only its own tip, preserving others' deferred state.109    pub fn register(&mut self, id: u8, tip: Tip) -> Hash {110        self.latest.insert(id, tip);111        self.put(id, tip);112        self.digest()113    }114    pub fn digest(&self) -> Hash {115        let rechain_root = self.tree.root_hash();116        match self.application_root {117            Some(application_root) => fork(pruned(application_root), pruned(rechain_root)).digest(),118            None => rechain_root,119        }120    }121    /// Register the complete application subtree, including its top-level122    /// label. HTTP certification supplies a tree already labeled `http_expr`.123    /// The application branch sorts before this publisher's `rechain` branch.124    /// Re-register after restoring the transient publisher from durable tips.125    pub fn set_application_root(&mut self, root: Hash) -> Hash {126        self.application_root = Some(root);127        self.digest()128    }129    /// Combine the application's witness with the current published Rechain130    /// sibling. The returned witness and every tip proof share `digest()`.131    pub fn application_witness(132        &self,133        witness: HashTree,134    ) -> core::result::Result<HashTree, ApplicationWitnessError> {135        let root = self136            .application_root137            .ok_or(ApplicationWitnessError::NotRegistered)?;138        if witness.digest() != root {139            return Err(ApplicationWitnessError::RootMismatch);140        }141        Ok(fork(witness, pruned(self.tree.root_hash())))142    }143    pub fn deadline(&self) -> Option<u64> {144        self.deadline145    }146    pub fn deferred(&self) -> bool {147        self.hot148    }149    pub fn recorded(&mut self, id: u8, tip: Tip, now: u64) -> Option<Hash> {150        if tip == Tip::Unrecorded {151            return None;152        }153        self.latest.insert(id, tip);154        self.dirty.insert(id);155        self.until = self156            .until157            .max(now)158            .saturating_add(CREDIT)159            .min(now.saturating_add(SECOND));160        let score = self.until.saturating_sub(now);161        self.hot = if self.hot {162            score > RESUME163        } else {164            score >= ENTER165        };166        if !self.hot {167            self.deadline = None;168            Some(self.publish())169        } else {170            self.deadline.get_or_insert(now.saturating_add(SECOND));171            None172        }173    }174    fn publish(&mut self) -> Hash {175        for id in std::mem::take(&mut self.dirty) {176            self.put(id, self.latest[&id]);177        }178        self.digest()179    }180    pub fn publish_due(&mut self, now: u64) -> Option<Hash> {181        if !self.deadline.is_some_and(|at| at <= now) {182            return None;183        }184        self.deadline = None;185        if self.until.saturating_sub(now) <= RESUME {186            self.hot = false187        }188        Some(self.publish())189    }190    pub fn proof(&self, selected: Option<u8>) -> Option<Proof> {191        let tips = match selected {192            Some(id) => vec![(id, *self.published.get(&id)?)],193            None => self.published.iter().map(|(id, t)| (*id, *t)).collect(),194        };195        let tree: HashTree = match selected {196            Some(id) => self197                .tree198                .witness(&[b"rechain".to_vec(), b"chains".to_vec(), vec![id]]),199            None => self.tree.as_hash_tree(),200        };201        let tree = match self.application_root {202            Some(application_root) => fork(pruned(application_root), tree),203            None => tree,204        };205        let hash_tree = serde_cbor::to_vec(&tree).expect("finite certificate tree serialization");206        Some(Proof {207            hash_tree,208            tips,209            digest: self.digest(),210        })211    }212}213214#[cfg(test)]215mod tests {216    use super::*;217    use ic_certification::{labeled, leaf};218219    fn application(value: u8) -> HashTree {220        labeled(b"http_expr".to_vec(), leaf(vec![value]))221    }222    fn assert_proofs(p: &Publisher, application: &HashTree) {223        assert_eq!(224            p.application_witness(application.clone()).unwrap().digest(),225            p.digest()226        );227        for selected in [None, Some(0)] {228            let proof = p.proof(selected).unwrap();229            let tree: HashTree = serde_cbor::from_slice(&proof.hash_tree).unwrap();230            assert_eq!(tree.digest(), proof.digest);231            assert_eq!(proof.digest, p.digest());232        }233    }234235    #[test]236    fn chain_only_publication_keeps_its_direct_root_and_witness() {237        let p = Publisher::restore([(0, Tip::Empty), (1, Tip::Unrecorded)]);238        assert_eq!(p.digest(), p.tree.root_hash());239        for selected in [None, Some(0), Some(1)] {240            let proof = p.proof(selected).unwrap();241            let tree: HashTree = serde_cbor::from_slice(&proof.hash_tree).unwrap();242            assert_eq!(tree.digest(), p.tree.root_hash());243            assert_eq!(proof.digest, tree.digest());244        }245    }246247    #[test]248    fn application_and_selected_tip_witnesses_share_one_root() {249        let mut p = Publisher::restore([(0, Tip::Empty)]);250        let chain_root = p.digest();251        let app = application(1);252        let combined = p.set_application_root(app.digest());253        assert_ne!(combined, chain_root);254        assert_eq!(combined, fork(app.clone(), pruned(chain_root)).digest());255        assert_proofs(&p, &app);256        assert_eq!(p.proof(Some(0)).unwrap().tips, vec![(0, Tip::Empty)]);257        assert_eq!(p.proof(Some(99)), None);258    }259260    #[test]261    fn alternating_app_and_deferred_rechain_publications_keep_both_proofs_current() {262        let mut p = Publisher::restore([(0, Tip::Empty)]);263        let first = application(1);264        p.set_application_root(first.digest());265        for index in 0..2 {266            let published = p.recorded(267                0,268                Tip::Tip {269                    index,270                    hash: [index as u8; 32],271                },272                0,273            );274            assert_eq!(published, Some(p.digest()));275            assert_proofs(&p, &first);276        }277        assert_eq!(278            p.recorded(279                0,280                Tip::Tip {281                    index: 2,282                    hash: [2; 32]283                },284                0285            ),286            None287        );288        let deadline = p.deadline();289        let next = application(2);290        p.set_application_root(next.digest());291        assert_eq!(292            p.deadline(),293            deadline,294            "Application publication cannot flush deferred tips"295        );296        assert_eq!(297            p.proof(Some(0)).unwrap().tips,298            vec![(299                0,300                Tip::Tip {301                    index: 1,302                    hash: [1; 32]303                }304            )]305        );306        assert_eq!(307            p.application_witness(first),308            Err(ApplicationWitnessError::RootMismatch)309        );310        assert_proofs(&p, &next);311        assert_eq!(p.publish_due(999_999_999), None);312        assert_eq!(p.publish_due(1_000_000_000), Some(p.digest()));313        assert_eq!(314            p.proof(Some(0)).unwrap().tips,315            vec![(316                0,317                Tip::Tip {318                    index: 2,319                    hash: [2; 32]320                }321            )]322        );323        assert_proofs(&p, &next);324        assert_eq!(p.register(1, Tip::Unrecorded), p.digest());325        assert_proofs(&p, &next);326    }327328    #[test]329    fn only_the_registered_application_root_can_supply_a_witness() {330        let mut p = Publisher::restore([(0, Tip::Unrecorded)]);331        let app = application(3);332        assert_eq!(333            p.application_witness(app.clone()),334            Err(ApplicationWitnessError::NotRegistered)335        );336        p.set_application_root(app.digest());337        let before = p.digest();338        assert_eq!(339            p.application_witness(application(4)),340            Err(ApplicationWitnessError::RootMismatch)341        );342        assert_eq!(p.digest(), before);343        assert_eq!(p.recorded(0, Tip::Unrecorded, 0), None);344        assert_proofs(&p, &app);345    }346347    #[test]348    fn restoring_tips_then_registering_application_reconstructs_the_same_root() {349        let tip = Tip::Tip {350            index: 5,351            hash: [7; 32],352        };353        let mut p = Publisher::restore([(0, tip)]);354        let app = application(9);355        let expected = p.set_application_root(app.digest());356        let mut restored = Publisher::restore(p.proof(None).unwrap().tips);357        assert_eq!(358            restored.application_witness(app.clone()),359            Err(ApplicationWitnessError::NotRegistered)360        );361        assert_eq!(restored.set_application_root(app.digest()), expected);362        assert_proofs(&restored, &app);363    }364}