lib.rs

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

1#![feature(arbitrary_self_types_pointers)]2//! Scoped, owner-private chain histories with Nyxus data.3use cdk_rsx_store::{4    Access, ModuleRef, Scope,5    binding::{Memory as Binding, MemoryView},6};7pub mod archive;8pub mod block;9pub mod certification;10pub mod cleanup;11pub mod ic;12pub mod idempotency;13pub mod memory;14pub mod reader;15pub mod reducer;16pub mod settings;17pub mod wire;1819pub use block::{20    Disclosure, ReadBlock, ReadContext, ReadDecision, RecordContext, RecordHeader, RecordedPayload,21};22use cdk_rsx_reactor::{Error, Result};23use memory::v1::ParentHash;24pub use reducer::{Commit, CommitToken, Prepare};25pub use settings::{ChainConfig, ChainReadConfig, CommitmentMode, Limits, RecordContract};26use std::rc::Rc;27pub type BlockId = u64;28pub type ChainId = u8;29/// A statically bound action stream. Cleanup uses a distinct marker/action type.30pub trait Chain {31    const ID: u8;32    type Action: serde::Serialize;33    const CONTRACT: RecordContract = RecordContract::IDENTITY;34    fn record(35        action: &Self::Action,36        _: &RecordContext,37        _: &[u8],38    ) -> core::result::Result<RecordedPayload, String> {39        block::encode(action).map(RecordedPayload::new)40    }41    fn read(42        _: &RecordHeader,43        _: &[u8],44        _: &ReadContext,45    ) -> core::result::Result<ReadDecision, String> {46        Ok(ReadDecision::Original)47    }48}49impl<'a> ChainConfig<'a> {50    pub fn of<C: Chain>(name: &'a str, description: &'a str, limits: Limits) -> Self {51        Self {52            id: C::ID,53            name,54            description,55            limits,56            source: default_source(),57            genesis: [0; 32],58            contract: C::CONTRACT,59            hook_data: Vec::new(),60            read: C::read,61        }62    }63}64#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Deserialize, serde::Serialize)]65pub enum LibraryError {66    UnknownChain(u8),67    StorageFull,68    TransactionTooLarge { actual_bytes: u64, max_bytes: u64 },69    PayloadEncodingFailed(String),70    RecordTransformFailed(String),71    ReadTransformFailed(String),72    BlindingKeyUnavailable,73}74#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Deserialize, serde::Serialize)]75pub enum DispatchError<E> {76    App(E),77    Rechain(LibraryError),78}79pub type DispatchResult<E> = core::result::Result<BlockId, DispatchError<E>>;80#[derive(Clone, Copy, Debug, cdk_rsx::WireType, serde::Deserialize, serde::Serialize)]81pub struct TransactionRange {82    pub start: u64,83    pub length: u64,84}85#[derive(Clone, Debug, cdk_rsx::WireType, serde::Deserialize, serde::Serialize)]86pub struct GetBlocksResult {87    pub chain: u8,88    pub log_length: u64,89    pub blocks: Vec<block::ServiceBlock>,90}91pub(crate) struct OriginalBlocksResult {92    pub chain: u8,93    pub log_length: u64,94    pub blocks: Vec<block::OriginalServiceBlock>,95}96#[derive(Clone, Debug, PartialEq, Eq, cdk_rsx::WireType, serde::Deserialize, serde::Serialize)]97pub struct Stats {98    pub chain: u8,99    pub first_index: u64,100    pub next_index: u64,101    pub local_records: u64,102    pub local_bytes: u64,103    pub phash: Option<block::Hash>,104    pub recorded: bool,105}106107struct Registered {108    name: String,109    description: String,110    limits: Limits,111    source: cdk_rsx::Principal,112    genesis: block::Hash,113    contract: RecordContract,114    hook_data: Vec<u8>,115    read: settings::ReadHook,116}117/// Process-local configuration and a nonowning module binding. The actor root118/// owns persistent history; dropping this service changes no data lifetime.119pub struct Runtime {120    chains: [Option<Registered>; 256],121    state: Binding<memory::Memory>,122}123/// A borrowed service view in the caller's shared root frame. No method opens a124/// second frame, and no access guard can survive the caller's scope.125/// Query views cannot dispatch:126/// ```compile_fail127/// use cdk_rsx_rechain::{Runtime, Chain, Commit};128/// use cdk_rsx_store::ReadScope;129/// fn query<C: Chain, R: Commit<C::Action>>(runtime: &Runtime, scope: &ReadScope<'_>,130///     action: &C::Action, reducers: &R) {131///     let _ = runtime.view(scope).dispatch::<C, R>(action, reducers, 0, |_, _| Ok(()));132/// }133/// ```134pub struct View<'a, A: Access> {135    runtime: &'a Runtime,136    state: MemoryView<'a, A, memory::Memory>,137}138impl<A: Access> Copy for View<'_, A> {}139impl<A: Access> Clone for View<'_, A> {140    fn clone(&self) -> Self {141        *self142    }143}144#[cdk_rsx::service_view(view = View<'a, A>)]145impl Runtime {146    pub fn bind(147        access: &impl Access,148        state: ModuleRef<memory::Memory>,149        configs: &[ChainConfig<'_>],150    ) -> Result<Rc<Self>> {151        validate_configs(configs)?;152        let state = memory::bind(state);153        {154            let view = state.view(access);155            let saved = view.read()?;156            if saved.chains.len() != configs.len()157                || configs.iter().any(|c| {158                    saved.chains.get(&c.id).is_none_or(|s| {159                        s.name.as_str() != c.name160                            || s.description.as_str() != c.description161                            || s.limits != memory::limits(c.limits)162                            || !memory::same_contract(s, c)163                    })164                })165            {166                return Err(Error::InvalidInput(167                    "Rechain configuration differs from saved contract",168                ));169            }170        }171        let mut chains = std::array::from_fn(|_| None);172        for c in configs {173            chains[c.id as usize] = Some(Registered {174                name: c.name.into(),175                description: c.description.into(),176                limits: c.limits,177                source: c.source,178                genesis: c.genesis,179                contract: c.contract,180                hook_data: c.hook_data.clone(),181                read: c.read,182            });183        }184        Ok(Rc::new(Self { chains, state }))185    }186    pub fn view<'a, A: Access>(&'a self, access: &'a A) -> View<'a, A> {187        View {188            runtime: self,189            state: self.state.view(access),190        }191    }192}193pub(crate) fn validate_configs(configs: &[ChainConfig<'_>]) -> Result<()> {194    let mut ids = [false; 256];195    let mut names = std::collections::BTreeSet::new();196    for c in configs {197        if std::mem::replace(&mut ids[c.id as usize], true)198            || !names.insert(c.name)199            || c.name.is_empty()200            || c.name.len() > 128201            || c.description.len() > 2048202            || c.hook_data.len() > settings::MAX_HOOK_DATA_BYTES203            || (c.limits.record204                && (c.limits.max_payload_bytes == 0205                    || c.limits.max_payload_bytes > 1_000_000206                    || c.limits.max_local_records == 0207                    || c.limits.max_local_bytes == 0))208        {209            return Err(Error::InvalidInput(210                "invalid or duplicate Rechain configuration",211            ));212        }213    }214    Ok(())215}216impl<A: Access> View<'_, A> {217    pub fn stats(&self, id: u8) -> Result<Option<Stats>> {218        let Some(c) = &self.runtime.chains[id as usize] else {219            return Ok(None);220        };221        let saved = self.state.read()?;222        let state = saved223            .chains224            .get(&id)225            .ok_or(Error::Corrupt("missing Rechain chain"))?;226        Ok(Some(Stats {227            chain: id,228            first_index: state.first,229            next_index: state.next,230            local_records: state.history.len() as u64,231            local_bytes: state.local_bytes,232            phash: state.phash.get(),233            recorded: c.limits.record,234        }))235    }236    pub fn chain_ids(&self) -> Result<Vec<u8>> {237        Ok(self238            .runtime239            .chains240            .iter()241            .enumerate()242            .filter_map(|(i, c)| c.as_ref().map(|_| i as u8))243            .collect())244    }245    pub fn get_blocks(246        &self,247        id: u8,248        requests: &[TransactionRange],249        context: &ReadContext,250    ) -> Result<core::result::Result<GetBlocksResult, LibraryError>> {251        let Some(config) = self.runtime.chains[id as usize].as_ref() else {252            return Ok(Err(LibraryError::UnknownChain(id)));253        };254        let read = ChainReadConfig {255            id,256            contract: config.contract,257            read: config.read,258        };259        let saved = self.state.read()?;260        let state = saved261            .chains262            .get(&id)263            .ok_or(Error::Corrupt("missing Rechain chain"))?;264        let next = if config.limits.record { state.next } else { 0 };265        let mut blocks = Vec::new();266        let mut bytes = 512u64;267        let mut scanned = 512u64;268        'requests: for request in requests {269            let end = request.start.saturating_add(request.length).min(next);270            for index in request.start.max(state.first)..end {271                if blocks.len() == 1000 {272                    break 'requests;273                }274                let Some(record) = state.history.get((index - state.first) as usize) else {275                    break;276                };277                // A restricted response is small, but computing its original278                // commitment still reads/hashes the retained body. Bound both.279                let original_cost = memory::stored_bytes(record);280                if scanned + original_cost > 1_450_000 {281                    break 'requests;282                }283                scanned += original_cost;284                let header: RecordHeader = block::decode_header(record.header.as_slice())285                    .map_err(|_| Error::Corrupt("retained record header"))?;286                if header.context.source != config.source287                    || header.context.genesis != config.genesis288                    || header.context.index != index289                {290                    return Err(Error::Corrupt("retained record domain differs"));291                }292                let view = match read.read_parts(293                    &header,294                    record.payload.as_slice(),295                    &record.opening,296                    context,297                ) {298                    Ok(value) => value,299                    Err(error) => return Ok(Err(LibraryError::ReadTransformFailed(error))),300                };301                let cost = block::encode(&view)302                    .map_err(|_| Error::Corrupt("bounded record read encoding"))?303                    .len() as u64304                    + 16;305                if bytes + cost > 1_450_000 {306                    break 'requests;307                }308                bytes += cost;309                blocks.push(block::ServiceBlock {310                    id: index,311                    block: view,312                });313            }314        }315        Ok(Ok(GetBlocksResult {316            chain: id,317            log_length: next,318            blocks,319        }))320    }321322    /// Internal original-record transfer. Never expose as a public query.323    pub(crate) fn original_blocks(324        &self,325        id: u8,326        requests: &[TransactionRange],327    ) -> Result<core::result::Result<OriginalBlocksResult, LibraryError>> {328        let Some(c) = &self.runtime.chains[id as usize] else {329            return Ok(Err(LibraryError::UnknownChain(id)));330        };331        let saved = self.state.read()?;332        let state = saved333            .chains334            .get(&id)335            .ok_or(Error::Corrupt("missing Rechain chain"))?;336        let next = if c.limits.record { state.next } else { 0 };337        let mut blocks = Vec::new();338        let mut bytes = 512u64;339        'requests: for request in requests {340            let end = request.start.saturating_add(request.length).min(next);341            for index in request.start.max(state.first)..end {342                if blocks.len() == 1000 {343                    break 'requests;344                }345                let Some(saved) = state.history.get((index - state.first) as usize) else {346                    break;347                };348                let block = memory::load_block(saved)?;349                let cost = block::encode(&block)350                    .map_err(|_| Error::Corrupt("bounded retained record"))?351                    .len() as u64352                    + 16;353                if bytes + cost > 1_450_000 {354                    break 'requests;355                }356                blocks.push(block::OriginalServiceBlock { id: index, block });357                bytes += cost;358            }359        }360        Ok(Ok(OriginalBlocksResult {361            chain: id,362            log_length: next,363            blocks,364        }))365    }366}367impl View<'_, Scope<'_>> {368    /// Install an owner-private per-chain commitment key. No key is a record,369    /// configuration DTO, query response or Debug value. Installation is once-only.370    pub fn install_blinding_key(&self, chain: u8, epoch: u64, seed: [u8; 32]) -> Result<()> {371        if epoch == 0 || seed == [0; 32] {372            return Err(Error::InvalidInput("invalid record blinding key"));373        }374        let Some(config) = &self.runtime.chains[chain as usize] else {375            return Err(Error::InvalidInput("unknown blinding chain"));376        };377        if config.contract.commitment != CommitmentMode::Blinded {378            return Err(Error::InvalidInput("public chain has no blinding key"));379        }380        let mut saved = self.state.write()?;381        let state = saved382            .chains383            .get_mut(&chain)384            .ok_or(Error::Corrupt("missing blinding chain"))?;385        if state.blinding.ready {386            if state.blinding.epoch == epoch && state.blinding.seed == seed {387                return Ok(());388            }389            return Err(Error::InvalidInput("record blinding key already installed"));390        }391        state.blinding.seed = seed;392        state.blinding.epoch = epoch;393        state.blinding.ready = true;394        Ok(())395    }396    // Only the archive coordinator can release a retained prefix after a397    // source/chain/range/hash-bound acknowledgement. The business tip and next398    // counter are permanent and do not change when local storage is reclaimed.399    pub(crate) fn release_archived_prefix(400        &self,401        id: u8,402        start: u64,403        count: u64,404        hash: Option<block::Hash>,405    ) -> Result<()> {406        let mut saved = self.state.write()?;407        let state = saved408            .chains409            .get_mut(&id)410            .ok_or(Error::Corrupt("missing Rechain chain"))?;411        if state.first != start || count > state.history.len() as u64 {412            return Err(Error::Corrupt("archive prefix changed during transfer"));413        }414        if count > 0 {415            let tail = state416                .history417                .get(count as usize - 1)418                .expect("checked archive prefix");419            let block = memory::load_block(tail)?;420            if hash != Some(block.hash()) {421                return Err(Error::Corrupt("archive prefix hash differs"));422            }423        }424        for _ in 0..count {425            let block = state.history.pop_front().expect("checked archive prefix");426            state.local_bytes -= memory::stored_bytes(&block);427        }428        state.first += count;429        Ok(())430    }431432    pub fn dispatch<C: Chain, R: Commit<C::Action>>(433        &self,434        action: &C::Action,435        reducers: &R,436        timestamp: u64,437        listener: impl FnOnce(&C::Action, BlockId) -> Result<()>,438    ) -> Result<DispatchResult<R::Error>> {439        let id = C::ID;440        let Some(c) = &self.runtime.chains[id as usize] else {441            return Ok(Err(DispatchError::Rechain(LibraryError::UnknownChain(id))));442        };443        let plan = match reducers.prepare(action)? {444            Ok(plan) => plan,445            Err(error) => return Ok(Err(DispatchError::App(error))),446        };447        let (block_id, phash, local_records, local_bytes) = {448            let saved = self.state.read()?;449            let s = saved450                .chains451                .get(&id)452                .ok_or(Error::Corrupt("missing Rechain chain"))?;453            (s.next, s.phash.get(), s.history.len() as u64, s.local_bytes)454        };455        let next = block_id.checked_add(1).ok_or(Error::Overflow)?;456        if c.contract != C::CONTRACT {457            return Err(Error::InvalidInput(458                "dispatch record contract differs from registered chain",459            ));460        }461        let committed_at_ns = record_time(timestamp);462        let prepared_record = if c.limits.record {463            let blinding_epoch = {464                let saved = self.state.read()?;465                let state = saved466                    .chains467                    .get(&id)468                    .ok_or(Error::Corrupt("missing chain"))?;469                match c.contract.commitment {470                    CommitmentMode::Public => 0,471                    CommitmentMode::Blinded if state.blinding.ready => state.blinding.epoch,472                    CommitmentMode::Blinded => {473                        return Ok(Err(DispatchError::Rechain(474                            LibraryError::BlindingKeyUnavailable,475                        )));476                    }477                }478            };479            let context = RecordContext {480                source: c.source,481                genesis: c.genesis,482                chain: id,483                index: block_id,484                phash,485                committed_at_ns,486                contract: c.contract,487                blinding_epoch,488            };489            let record = match C::record(action, &context, &c.hook_data) {490                Ok(value) => value,491                Err(error) => {492                    return Ok(Err(DispatchError::Rechain(493                        LibraryError::RecordTransformFailed(error),494                    )));495                }496            };497            if record.bytes.len() > c.limits.max_payload_bytes as usize498                || record.read_policy.len() > settings::MAX_READ_POLICY_BYTES499            {500                return Ok(Err(DispatchError::Rechain(501                    LibraryError::TransactionTooLarge {502                        actual_bytes: record.bytes.len() as u64,503                        max_bytes: c.limits.max_payload_bytes as u64,504                    },505                )));506            }507            let header = RecordHeader {508                format: block::RECORD_FORMAT,509                context,510                read_policy: record.read_policy,511            };512            let opening = match c.contract.commitment {513                CommitmentMode::Public => [0; 32],514                CommitmentMode::Blinded => {515                    let saved = self.state.read()?;516                    let state = saved517                        .chains518                        .get(&id)519                        .ok_or(Error::Corrupt("missing chain"))?;520                    let mut h = blake3::Hasher::new_keyed(&state.blinding.seed);521                    h.update(b"rechain/private-opening/v3\0");522                    let encoded = block::encode_header(&header)523                        .map_err(|_| Error::Corrupt("bounded record header"))?;524                    h.update(&(encoded.len() as u64).to_le_bytes());525                    h.update(&encoded);526                    h.update(blake3::hash(&record.bytes).as_bytes());527                    *h.finalize().as_bytes()528                }529            };530            let block = block::Block {531                header,532                payload: record.bytes,533                opening,534            };535            if let Err(error) = block.validate() {536                return Ok(Err(DispatchError::Rechain(537                    LibraryError::RecordTransformFailed(error),538                )));539            }540            let size = (block::encode_header(&block.header)541                .map_err(|_| Error::Corrupt("record header"))?542                .len()543                + block.payload.len()544                + 32) as u64;545            if local_records >= c.limits.max_local_records546                || size > c.limits.max_local_bytes.saturating_sub(local_bytes)547            {548                return Ok(Err(DispatchError::Rechain(LibraryError::StorageFull)));549            }550            Some((block, size))551        } else {552            None553        };554        // Rejections are complete. An invariant failure after this point traps555        // so IC rollback covers the history and every reducer synchronously.556        let committed = (|| -> Result<()> {557            let recorded_hash = if let Some((block, size)) = prepared_record {558                let hash = block.hash();559                let stored = memory::save_block(block)?;560                let mut saved = self.state.write()?;561                let state = saved562                    .chains563                    .get_mut(&id)564                    .ok_or(Error::Corrupt("missing Rechain chain"))?;565                state.local_bytes += size;566                state.phash = ParentHash::from_option(Some(hash));567                state.history.push_back(stored);568                Some(hash)569            } else {570                None571            };572            reducers.commit(plan, block_id, &CommitToken { chain: id })?;573            {574                let mut saved = self.state.write()?;575                saved576                    .chains577                    .get_mut(&id)578                    .ok_or(Error::Corrupt("missing Rechain chain"))?579                    .next = next;580            }581            if let Some(hash) = recorded_hash {582                ic::recorded(583                    id,584                    certification::Tip::Tip {585                        index: block_id,586                        hash,587                    },588                    committed_at_ns,589                );590            }591            listener(action, block_id)?;592            Ok(())593        })();594        abort_on_commit_error(committed);595        Ok(Ok(block_id))596    }597}598pub(crate) fn abort_on_commit_error<T>(result: Result<T>) -> T {599    result.unwrap_or_else(|error| {600        cdk_rsx::trap(format!("Rechain committed mutation failed: {error:?}"))601    })602}603fn default_source() -> cdk_rsx::Principal {604    #[cfg(target_family = "wasm")]605    {606        cdk_rsx::api::canister_self()607    }608    #[cfg(not(target_family = "wasm"))]609    {610        cdk_rsx::Principal::anonymous()611    }612}613fn record_time(timestamp: u64) -> u64 {614    #[cfg(target_family = "wasm")]615    {616        let _ = timestamp;617        cdk_rsx::api::time()618    }619    #[cfg(not(target_family = "wasm"))]620    {621        timestamp622    }623}624fn leb_size(mut n: u64) -> u64 {625    let mut b = 1;626    while n >= 128 {627        n >>= 7;628        b += 1;629    }630    b631}632#[cfg(test)]633mod tests;