ic.rs

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

1//! Certification of local chain histories on the shared Reactor scheduler.2use crate::{3    View,4    certification::{ApplicationWitnessError, Publisher, Tip},5};6use cdk_rsx_reactor::Result;7use cdk_rsx_reactor::{8    Priority,9    scheduler::{Driver, Lease, Readiness, Scheduler, Step},10};11use std::{12    cell::RefCell,13    rc::{Rc, Weak},14};15thread_local! {static CONTROLLER:RefCell<Option<Rc<Controller>>>=const{RefCell::new(None)};}16struct Controller {17    publisher: RefCell<Publisher>,18    lease: RefCell<Option<Lease>>,19}20/// Drop the old certification controller; history and tips remain root-owned.21pub fn shutdown() {22    let controller = CONTROLLER.with_borrow_mut(Option::take);23    drop(controller);24}25/// Allocation-free inspection for the root's explicit transient inventory.26pub fn is_shutdown() -> bool {27    CONTROLLER.with_borrow(Option::is_none)28}29fn publish(hash: [u8; 32]) {30    #[cfg(target_family = "wasm")]31    cdk_rsx::api::certified_data_set(hash);32    #[cfg(not(target_family = "wasm"))]33    let _ = hash;34}35pub fn start<A: cdk_rsx_store::Access>(runtime: View<'_, A>, scheduler: Scheduler) {36    let tips = runtime37        .chain_ids()38        .expect("chain ids")39        .into_iter()40        .map(|id| (id, Tip::from(&runtime.stats(id).unwrap().unwrap())));41    let publisher = Publisher::restore(tips);42    publish(publisher.digest());43    let controller = Rc::new(Controller {44        publisher: RefCell::new(publisher),45        lease: RefCell::new(None),46    });47    let lease = scheduler.register(48        Rc::new(Maintenance {49            controller: Rc::downgrade(&controller),50        }),51        false,52    );53    *controller.lease.borrow_mut() = Some(lease);54    CONTROLLER.with_borrow_mut(|slot| {55        assert!(slot.is_none(), "one Rechain runtime per process");56        *slot = Some(controller);57    });58}59/// Add the application's complete labeled subtree to the one certified root.60/// Call from init/restore or a replicated transition, after Rechain starts.61/// Ordinary Rechain publication keeps this branch until the next registration.62pub fn set_application_root(root: [u8; 32]) -> [u8; 32] {63    CONTROLLER.with_borrow(|slot| {64        let c = slot.as_ref().expect("Rechain runtime not started");65        let hash = c.publisher.borrow_mut().set_application_root(root);66        publish(hash);67        hash68    })69}70/// Build a query witness under the same root as `get_tip_certificate`.71/// Obtain the IC data certificate in this query after composing the witness.72pub fn application_witness(73    witness: ic_certification::HashTree,74) -> core::result::Result<ic_certification::HashTree, ApplicationWitnessError> {75    CONTROLLER.with_borrow(|slot| {76        let c = slot.as_ref().expect("Rechain runtime not started");77        c.publisher.borrow().application_witness(witness)78    })79}80pub(crate) fn recorded(id: u8, tip: Tip, now: u64) {81    CONTROLLER.with_borrow(|slot| {82        if let Some(c) = slot {83            let before = c.publisher.borrow().deadline();84            let hash = c.publisher.borrow_mut().recorded(id, tip, now);85            if let Some(hash) = hash {86                publish(hash)87            }88            if before != c.publisher.borrow().deadline() {89                if let Some(l) = c.lease.borrow().as_ref() {90                    l.changed();91                }92            }93        }94    });95}96pub fn get_tip_certificate(97    selected: Option<u8>,98) -> core::result::Result<Option<crate::wire::DataCertificate>, crate::wire::ChainError> {99    CONTROLLER.with_borrow(|slot| {100        let c = slot.as_ref().expect("Rechain runtime not started");101        #[cfg(target_family = "wasm")]102        let certificate = cdk_rsx::api::data_certificate();103        #[cfg(not(target_family = "wasm"))]104        let certificate = None;105        crate::wire::tip_certificate(&c.publisher.borrow(), certificate, selected)106    })107}108pub fn retry_maintenance() {109    CONTROLLER.with_borrow(|c| {110        if let Some(c) = c {111            if let Some(l) = c.lease.borrow().as_ref() {112                l.changed();113            }114        }115    });116}117struct Maintenance {118    controller: Weak<Controller>,119}120impl Driver for Maintenance {121    fn owner(&self) -> bool {122        self.controller.strong_count() > 0123    }124    fn readiness(&self, _: &cdk_rsx_store::ReadScope<'_>, now: u64) -> Readiness {125        let at = self126            .controller127            .upgrade()128            .and_then(|c| c.publisher.borrow().deadline());129        Readiness {130            priority: at.filter(|at| *at <= now).map(|_| Priority::Control),131            deadline: at.filter(|at| *at > now),132            backlog: u64::from(at.is_some()),133        }134    }135    fn step(&self, scope: &cdk_rsx_store::Scope<'_>, _: Priority, now: u64) -> Result<Step> {136        if let Some(c) = self.controller.upgrade() {137            if let Some(hash) = c.publisher.borrow_mut().publish_due(now) {138                publish(hash)139            }140        }141        Ok(Step::done(self.readiness(&scope.read_only(), now)))142    }143}