lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit f0a2a8ae95899574e698f93f223c90a0a7837490
parent e9838a88c90e0b5d88c6f8dbb6a0b2f8b0ba0f04
Author: triesap <tyson@radroots.org>
Date:   Sat, 24 Oct 2026 23:58:51 +0000

storage: reconcile pool projections with protected history

- Match current pool state to its latest authenticated effect.
- Verify intervening links instead of trusting mutable pool indexes.
- Recheck exact history witnesses inside read and write transactions.
- Cover partial restore and forged-index failures on native hosts.

Diffstat:
Mcrates/storage_sqlite/src/workspace/stock/inventory.rs | 38++++++++++++++++++++++++++++++++++++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcrates/storage_sqlite/tests/support/pool_creation.rs | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 261 insertions(+), 17 deletions(-)

diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -3,7 +3,7 @@ mod checkpoint; mod codec; mod plan; use super::*; -use checkpoint::{MinimumProof, authenticate_minimum}; +use checkpoint::{MinimumProof, authenticate_minimum, authenticate_projection}; pub(super) async fn grant_minimum( connection: &mut SqliteConnection, input: &AttachmentInput, @@ -71,6 +71,7 @@ struct Access { grant: Vec<u8>, current: WorkspaceBinding, minimum_proof: MinimumProof, + projection_proof: Option<MinimumProof>, } pub(in crate::workspace) struct Turn<'a> { pub connection: &'a mut SqliteConnection, @@ -134,6 +135,7 @@ impl Turn<'_> { grant, current, minimum_proof, + projection_proof: None, }) } pub async fn create( @@ -210,6 +212,21 @@ impl Turn<'_> { ) .await?; let before = existing.as_ref().map(|v| v.pool); + access.projection_proof = Some( + authenticate_projection( + self.connection, + self.selected, + self.crypto, + &access.current, + access + .authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?, + request.command().pool_id(), + before, + ) + .await?, + ); let (pool, quantity, movement_kind) = plan_effect(request.command(), before)?; let label = if let Some(input) = request.command().creation_input() { input.label() @@ -369,6 +386,7 @@ impl Turn<'_> { if let Some(state)=access.authority.authorization { grants::check_state(&mut tx,state).await?; } check_head(&mut tx,checkpoint).await?; access.minimum_proof.confirm(&mut tx).await?; + if let Some(proof)=&access.projection_proof {proof.confirm(&mut tx).await?;} let current=access.record.authenticate(request.binding().input(),&proof,self.clock.now()?)?; same_binding(request.binding(),&current)?; if current.observed_at()<access.current.observed_at() {return Err(WorkspaceError::Unavailable.into());} @@ -427,6 +445,7 @@ impl Turn<'_> { if let Some(state)=access.authority.authorization { grants::check_state(&mut tx,state).await?; } check_head(&mut tx,access.authority.inventory.ok_or(OperationError::UnsupportedOperation)?).await?; access.minimum_proof.confirm(&mut tx).await?; + if let Some(proof)=&access.projection_proof {proof.confirm(&mut tx).await?;} let current=access.record.authenticate(access.current.input(),proof,self.clock.now()?)?; same_binding(&access.current,&current)?; if let Some(operation)=absent_operation {let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=?").bind(current.actor().participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;if count!=0 {return Err(OperationError::RecoveryRequired);}} @@ -499,9 +518,24 @@ impl Turn<'_> { id: PoolId, proof: AttachmentProof, ) -> Result<Option<radroots_domain::stock::PoolView>, OperationError> { - let access = self.access(&binding, minimum, &proof).await?; + let mut access = self.access(&binding, minimum, &proof).await?; access.record.require(StockAction::ReadPools, id)?; let result = read_pool(self.connection, self.selected, self.crypto, id).await?; + access.projection_proof = Some( + authenticate_projection( + self.connection, + self.selected, + self.crypto, + &access.current, + access + .authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?, + id, + result.as_ref().map(|v| v.pool), + ) + .await?, + ); self.confirm( &access, &proof, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -83,21 +83,7 @@ pub(super) async fn authenticate_minimum( if revision == minimum.revision().get() && expected != minimum.head() { return Err(WorkspaceError::StaleCheckpoint.into()); } - hash.update(revision.to_be_bytes()); - hash.update(binding.actor().participant().as_bytes()); - hash.update(retained.original_grant.as_bytes()); - hash.update(operation.as_bytes()); - hash.update(retained.digest.as_bytes()); - hash.update( - receipt - .transaction_id() - .ok_or(OperationError::RecoveryRequired)? - .as_bytes(), - ); - hash.update(receipt.pool().id().as_bytes()); - hash.update(expected.ok_or(OperationError::RecoveryRequired)?.as_bytes()); - hash.update((retained.protected.len() as u64).to_be_bytes()); - hash.update(&retained.protected); + hash_retained(&mut hash, revision, binding, operation, &retained)?; expected = retained.previous_head; } if minimum.revision().get() == 0 && expected.is_some() { @@ -109,3 +95,87 @@ pub(super) async fn authenticate_minimum( digest: hash.finalize().into(), }) } + +fn hash_retained( + hash: &mut Sha256, + revision: u64, + binding: &WorkspaceBinding, + operation: OperationId, + retained: &Retained, +) -> Result<(), OperationError> { + let receipt = &retained.receipt; + hash.update(revision.to_be_bytes()); + hash.update(binding.actor().participant().as_bytes()); + hash.update(retained.original_grant.as_bytes()); + hash.update(operation.as_bytes()); + hash.update(retained.digest.as_bytes()); + hash.update( + receipt + .transaction_id() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + ); + hash.update(receipt.pool().id().as_bytes()); + hash.update( + receipt + .checkpoint() + .head() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + ); + hash.update((retained.protected.len() as u64).to_be_bytes()); + hash.update(&retained.protected); + Ok(()) +} + +/// Proves the current pool projection against the latest actual protected +/// effect, including every intervening link from the current root. A mutable +/// SQL pool index alone cannot prove the absence of a more recent effect. +pub(super) async fn authenticate_projection( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + current: InventoryCheckpoint, + pool: PoolId, + projected: Option<PoolSnapshot>, +) -> Result<MinimumProof, OperationError> { + let upper = current.revision.get(); + let mut expected = current.head; + let mut hash = history_hash(); + for revision in (1..=upper).rev() { + let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32").bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let operation = OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let retained = read_operation(connection, input, crypto, binding, operation) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.receipt.checkpoint().revision().get() != revision + || retained.receipt.checkpoint().head() != expected + { + return Err(OperationError::RecoveryRequired); + } + hash_retained(&mut hash, revision, binding, operation, &retained)?; + if retained.receipt.pool().id() == pool { + if projected != Some(retained.receipt.pool()) { + return Err(OperationError::RecoveryRequired); + } + return Ok(MinimumProof { + lower: revision, + upper, + digest: hash.finalize().into(), + }); + } + expected = retained.previous_head; + } + if expected.is_some() || projected.is_some() { + return Err(OperationError::RecoveryRequired); + } + Ok(MinimumProof { + lower: 1, + upper, + digest: hash.finalize().into(), + }) +} diff --git a/crates/storage_sqlite/tests/support/pool_creation.rs b/crates/storage_sqlite/tests/support/pool_creation.rs @@ -972,5 +972,145 @@ async fn acknowledged_branch_cannot_be_satisfied_by_unprotected_history_index_fi #[path = "pool_correction.rs"] mod correction; +#[tokio::test] +async fn acknowledged_history_refuses_an_older_individual_pool_projection() { + let f = Fixture::new(); + let (store, e, binding) = create(&f).await; + let initial = committed( + store + .execute_inventory(request(&binding, 1, 2, "projection"), proof(e.proof())) + .await + .unwrap(), + ); + let mut connection = database(&f).await; + let original: (i64, Vec<u8>) = + sqlx::query_as("SELECT revision,protected FROM stock_pools WHERE pool_id=?") + .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice()) + .fetch_one(&mut connection) + .await + .unwrap(); + let capture = request(&binding, 3, 2, "projection"); + let wire = serde_json::json!({"type":"stock.adjust","context":capture.command().context(),"input":{"pool_id":PoolId::from_bytes([2;32]),"expected_version":"1","direction":"add","amount":"0.125","reason":"projection continuity"}}); + let changed = committed( + store + .execute_inventory( + InventoryRequest::from_protected_wire( + binding.clone(), + initial.checkpoint(), + &serde_json::to_vec(&wire).unwrap(), + ) + .unwrap(), + proof(e.proof()), + ) + .await + .unwrap(), + ); + assert_eq!(changed.pool().balances().physical().available.get(), 375); + sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=?") + .bind(original.0) + .bind(original.1) + .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice()) + .execute(&mut connection) + .await + .unwrap(); + assert_eq!( + store + .pool( + binding.clone(), + changed.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await, + Err(OperationError::RecoveryRequired) + ); + let mut retry = wire; + retry["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([4; 32])); + let retry = InventoryRequest::from_protected_wire( + binding, + changed.checkpoint(), + &serde_json::to_vec(&retry).unwrap(), + ) + .unwrap(); + assert_eq!( + store.execute_inventory(retry, proof(e.proof())).await, + Err(OperationError::RecoveryRequired) + ); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations") + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!(count, 2); + connection.close().await.unwrap(); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn a_mutable_pool_index_cannot_hide_a_more_recent_protected_pool_effect() { + let f = Fixture::new(); + let (store, e, binding) = create(&f).await; + let initial = committed( + store + .execute_inventory(request(&binding, 1, 2, "projection"), proof(e.proof())) + .await + .unwrap(), + ); + let mut connection = database(&f).await; + let original: (i64, Vec<u8>) = + sqlx::query_as("SELECT revision,protected FROM stock_pools WHERE pool_id=?") + .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice()) + .fetch_one(&mut connection) + .await + .unwrap(); + let capture = request(&binding, 3, 2, "projection"); + let wire = serde_json::json!({"type":"stock.adjust","context":capture.command().context(),"input":{"pool_id":PoolId::from_bytes([2;32]),"expected_version":"1","direction":"add","amount":"0.125","reason":"projection continuity"}}); + committed( + store + .execute_inventory( + InventoryRequest::from_protected_wire( + binding.clone(), + initial.checkpoint(), + &serde_json::to_vec(&wire).unwrap(), + ) + .unwrap(), + proof(e.proof()), + ) + .await + .unwrap(), + ); + let newest = committed( + store + .execute_inventory(request(&binding, 4, 5, "other pool"), proof(e.proof())) + .await + .unwrap(), + ); + sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=?") + .bind(original.0) + .bind(original.1) + .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice()) + .execute(&mut connection) + .await + .unwrap(); + sqlx::query("UPDATE stock_operations SET pool_id=? WHERE operation_id=?") + .bind(PoolId::from_bytes([5; 32]).as_bytes().as_slice()) + .bind(OperationId::from_bytes([3; 32]).as_bytes().as_slice()) + .execute(&mut connection) + .await + .unwrap(); + assert_eq!( + store + .pool( + binding, + newest.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await, + Err(OperationError::RecoveryRequired) + ); + connection.close().await.unwrap(); + store.close().await.unwrap(); +} + #[path = "stock_grants.rs"] mod grants;