From f8d7876bab54e18871ed8140a34d19ae1f859ba0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:36:17 +0300 Subject: [PATCH 01/51] refactor(deps): update tinystoragedrivers dependencies This change updates the dependencies across several crates to use the newer v2.0.0 contracts from tinystoragedrivers. It replaces older, more specific dependencies with runtime-neutral API and types crates to better align with host integration patterns. Auto-committed-on: dragonfly --- Cargo.toml | 16 +- crates/tinywallet-bus/Cargo.toml | 13 -- crates/tinywallet-module/Cargo.toml | 8 +- crates/tinywallet-x402/Cargo.toml | 11 +- .../src/ledger/schema_payment.rs | 206 ++++++++++++++++++ 5 files changed, 218 insertions(+), 36 deletions(-) create mode 100644 crates/tinywallet-x402/src/ledger/schema_payment.rs diff --git a/Cargo.toml b/Cargo.toml index 8b18e63c..192c1f2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,17 +59,11 @@ resolver = "3" # one package and `tinytools::Tool` stays one type. Keep the rev equal to the # tinytools gitlink tinyagents pins. tinytools = { git = "https://github.com/tinyhumansai/tinytools", rev = "bd60b9b52f1998b4483b9cf107a72d3338e672f8" } -# The storage ports (documents, streams) the x402 ledger persists through. The -# ports crate only: no driver, no database client. A git tag rather than a path -# so a host that already links tinystoragedrivers (OpenHuman patches this exact -# URL to its vendored copy) unifies to one `DocumentStore` trait. `blocking` -# is the sync bridge the ledger's synchronous API runs the async ports on. -tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, features = ["blocking"] } -# The storage bus, for the loadable module only: it reaches the host's storage -# through the same ports over TinyBus rather than a process-local registry. -tinystoragedrivers-bus = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" } -tinystoragedrivers-client = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" } -tinystoragedrivers-busproxy = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" } +# Runtime-neutral contracts shared with the host's stable TSD release. +tinystoragedrivers-types = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } +tinystoragedrivers-api = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } +# The module connects to host-owned storage through the TinyBus adapter. +tinystoragedrivers-busproxy = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } [dependencies] # The wire contract. Split out so a host that has moved signing into the diff --git a/crates/tinywallet-bus/Cargo.toml b/crates/tinywallet-bus/Cargo.toml index b0b9c7ef..4824d8a0 100644 --- a/crates/tinywallet-bus/Cargo.toml +++ b/crates/tinywallet-bus/Cargo.toml @@ -20,26 +20,13 @@ serde = { version = "1", optional = true } serde_json = { version = "1", optional = true } # Error vocabulary derives; no crypto execution crosses this dependency. thiserror = "2" -# The storage schema's declarations (`Schema`, `Step`, `CollectionSpec`). This -# is the ports crate only: no backend, no driver, and with default features off -# its only tokio features are io-util and time, so the contract stays free of -# I/O and a runtime. Optional, behind `storage`. -tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, optional = true } [dev-dependencies] serde = { version = "1", features = ["derive"] } serde_json = "1" -# Migration tests run the steps over `MemoryStorage` through the sync bridge. -tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, features = ["blocking"] } [features] default = ["wire"] -# `storage::storage_schema()` and the pure v1 to v2 steps behind it. OFF by -# default: it is the only way `tinystoragedrivers-core` (ports, and with it -# tokio and zstd) enters this crate, so the default closure stays pure. Only a -# host that composes the schema enables it. `scripts/check-bus-boundaries.py` -# audits the default closure strictly and this feature under a named exemption. -storage = ["serde", "dep:serde_json", "dep:tinystoragedrivers-core"] serde = ["dep:serde", "serde/derive"] wire = ["serde", "dep:serde_json"] # Legacy feature names accepted for a transition release; none links behavior. diff --git a/crates/tinywallet-module/Cargo.toml b/crates/tinywallet-module/Cargo.toml index c56070f1..4399fc1f 100644 --- a/crates/tinywallet-module/Cargo.toml +++ b/crates/tinywallet-module/Cargo.toml @@ -80,9 +80,6 @@ zeroize = "1" # Storage over the bus: the module reaches the host's storage (x402 payments # stream and budget-hold documents) through the ports crate's bus transport, not # a process-local registry. -tinystoragedrivers-core = { workspace = true } -tinystoragedrivers-bus = { workspace = true } -tinystoragedrivers-client = { workspace = true } tinystoragedrivers-busproxy = { workspace = true } # Diagnostics for the storage connection and hold-lease renewal. log = "0.4" @@ -96,15 +93,12 @@ default = [] # are always built without it. static-link = [] linked = ["static-link"] -# Test-artifact only (the module E2E builds the cdylib with it): when the host -# has not provisioned x402 ledger storage, fall back to in-memory storage -# instead of failing closed. Released modules are never built with it. -e2e-memory-storage = [] [lints] workspace = true [dev-dependencies] +tinystoragedrivers-testkit = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } # Encodes and decodes the Solana transaction fixtures in native tests. base64 = "0.23" # The native lifecycle fixture stages and hashes the actual cdylib to attest it. diff --git a/crates/tinywallet-x402/Cargo.toml b/crates/tinywallet-x402/Cargo.toml index d884a834..5a69564f 100644 --- a/crates/tinywallet-x402/Cargo.toml +++ b/crates/tinywallet-x402/Cargo.toml @@ -66,13 +66,13 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "serd # Record ids in the `x402_request` tool. uuid = { version = "1", features = ["v4"], optional = true } -# The storage ports the ledger persists through (payments stream, budget hold -# document). Ports only; the host chooses the backend. -tinystoragedrivers-core = { workspace = true, optional = true } +# Runtime-neutral ports and DTOs supplied by the host. +tinystoragedrivers-api = { workspace = true, optional = true } +tinystoragedrivers-types = { workspace = true, optional = true } # `block_in_place` only: the ledger's synchronous API blocks on storage calls, # and on a multi-thread runtime that must hand its worker off first, or a # storage transport that needs the same runtime (the bus) starves. -tokio = { version = "1", default-features = false, features = ["rt-multi-thread"], optional = true } +tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "sync"], optional = true } [dev-dependencies] serde = { version = "1", features = ["derive"] } @@ -93,6 +93,7 @@ tinywallet = { path = "../..", default-features = false, features = ["key", "sol # signer from an EIP-3009 signature in tests. k256 = { version = "0.13", default-features = false, features = ["ecdsa"] } ed25519-dalek = { version = "2", default-features = false, features = ["std"] } +tinystoragedrivers-testkit = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } [features] default = ["wire"] @@ -106,7 +107,7 @@ eip712 = ["dep:sha3", "dep:thiserror"] abi = ["eip712", "dep:tinywallet-crypto", "tinywallet-crypto/evm", "tinywallet-crypto/keccak"] # The rail-neutral spending ledger: records, budgets, the JSONL file, and the # process-wide handle. -ledger = ["dep:serde", "dep:serde_json", "dep:chrono", "dep:log", "dep:tinystoragedrivers-core", "dep:tokio", "dep:tinywallet-bus", "tinywallet-bus/storage"] +ledger = ["dep:serde", "dep:serde_json", "dep:chrono", "dep:log", "dep:tinystoragedrivers-api", "dep:tinystoragedrivers-types", "dep:tokio"] # Paying a 402 challenge: header codec, the client, and the EVM and Solana # payment builders behind the `PaymentSigner` seam. Solana reads the recent # blockhash through `tinywallet_crypto::rpc::Transport`. diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs new file mode 100644 index 00000000..c693bd4f --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -0,0 +1,206 @@ +//! The payment record as it is stored, and the v1 shape it migrates from. + +use serde::{Deserialize, Deserializer, Serialize}; + +/// Where a stored payment stands. The same four states, spelled the same way, +/// as the implementation's public status type, which converts to and from this. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StoredPaymentStatus { + /// Signed and sent, not yet settled. + Pending, + /// A trusted settlement receipt confirms payment. + Settled, + /// A trusted result established that the payment did not settle. + Failed, + /// Refused before anything was signed. + Denied, +} + +/// One payment as stored in `wallet.payments`: `snake_case`, every instant an +/// epoch-millisecond `*_ms` field, no wrapper. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredPayment { + /// Unique id of the attempt. + pub id: String, + /// The URL the payment bought access to. + pub url: String, + /// The asset paid in. + pub asset: String, + /// The amount in atomic units of `asset`. + pub amount_atomic: u64, + /// The amount formatted for people. + pub amount_display: String, + /// Who was paid. + pub recipient: String, + /// The network, in CAIP-2 form. + pub network: String, + /// The settlement transaction, once reported. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tx_signature: Option, + /// Where the payment stands. + pub status: StoredPaymentStatus, + /// When this state was written, in epoch milliseconds. + pub timestamp_ms: i64, + /// When an exported authorization becomes unusable, in epoch milliseconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_valid_until_ms: Option, + /// Solana's `lastValidBlockHeight` for the exported transaction. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub solana_last_valid_block_height: Option, + /// When the authorization was observed expired, in epoch milliseconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_expired_at_ms: Option, + /// The block height at which the expiry was observed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_expiry_observed_height: Option, + /// The session that made the payment. + pub session_id: String, + /// The conversation thread, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thread_id: Option, + /// The budget hold this entry committed, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub committed_hold: Option, +} + +/// A v1 `x402.payments` entry: the camelCase wire record with RFC 3339 +/// instants, and the hold metadata beside it. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LegacyPayment { + id: String, + url: String, + asset: String, + amount_atomic: u64, + amount_display: String, + recipient: String, + network: String, + #[serde(default)] + tx_signature: Option, + status: StoredPaymentStatus, + #[serde(deserialize_with = "instant_ms")] + timestamp: i64, + #[serde(default, deserialize_with = "optional_instant_ms")] + authorization_valid_until: Option, + #[serde(default)] + solana_last_valid_block_height: Option, + #[serde(default, deserialize_with = "optional_instant_ms")] + authorization_expired_at: Option, + #[serde(default)] + authorization_expiry_observed_height: Option, + session_id: String, + #[serde(default)] + thread_id: Option, + #[serde(default, rename = "committed_hold")] + committed_hold: Option, +} + +impl From for StoredPayment { + fn from(legacy: LegacyPayment) -> Self { + Self { + id: legacy.id, + url: legacy.url, + asset: legacy.asset, + amount_atomic: legacy.amount_atomic, + amount_display: legacy.amount_display, + recipient: legacy.recipient, + network: legacy.network, + tx_signature: legacy.tx_signature, + status: legacy.status, + timestamp_ms: legacy.timestamp, + authorization_valid_until_ms: legacy.authorization_valid_until, + solana_last_valid_block_height: legacy.solana_last_valid_block_height, + authorization_expired_at_ms: legacy.authorization_expired_at, + authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, + session_id: legacy.session_id, + thread_id: legacy.thread_id, + committed_hold: legacy.committed_hold, + } + } +} + +fn instant_ms<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + parse_rfc3339_ms(&text) + .ok_or_else(|| serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant"))) +} + +fn optional_instant_ms<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|text| { + parse_rfc3339_ms(&text).ok_or_else(|| { + serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant")) + }) + }) + .transpose() +} + +/// An RFC 3339 instant (`2026-03-15T12:00:00.250Z`, or with a `+hh:mm` +/// offset) as epoch milliseconds, by integer arithmetic only. Fractions finer +/// than a millisecond are truncated. +pub(super) fn parse_rfc3339_ms(text: &str) -> Option { + let bytes = text.as_bytes(); + let digits = |from: usize, len: usize| -> Option { + let part = bytes.get(from..from + len)?; + if !part.iter().all(u8::is_ascii_digit) { + return None; + } + part.iter() + .try_fold(0_i64, |n, d| Some(n * 10 + i64::from(d - b'0'))) + }; + let separator = |at: usize, want: &[u8]| bytes.get(at).is_some_and(|b| want.contains(b)); + if !(separator(4, b"-") + && separator(7, b"-") + && separator(10, b"Tt ") + && separator(13, b":") + && separator(16, b":")) + { + return None; + } + let (year, month, day) = (digits(0, 4)?, digits(5, 2)?, digits(8, 2)?); + let (hour, minute, second) = (digits(11, 2)?, digits(14, 2)?, digits(17, 2)?); + if !(1..=12).contains(&month) + || !(1..=31).contains(&day) + || hour > 23 + || minute > 59 + || second > 60 + { + return None; + } + let mut at = 19; + let mut millis = 0; + if bytes.get(at) == Some(&b'.') { + let start = at + 1; + let mut end = start; + while bytes.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + if end == start { + return None; + } + for (place, digit) in bytes[start..end].iter().take(3).enumerate() { + millis += i64::from(digit - b'0') * [100, 10, 1][place]; + } + at = end; + } + let offset_minutes = match bytes.get(at)? { + b'Z' | b'z' if at + 1 == bytes.len() => 0, + sign @ (b'+' | b'-') if at + 6 == bytes.len() && separator(at + 3, b":") => { + let minutes = digits(at + 1, 2)? * 60 + digits(at + 4, 2)?; + if *sign == b'-' { -minutes } else { minutes } + } + _ => return None, + }; + // Days from civil (Howard Hinnant's algorithm), proleptic Gregorian. + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let year_of_era = y - era * 400; + let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + let days = era * 146_097 + day_of_era - 719_468; + let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; + Some(seconds * 1_000 + millis) +} From ccbd087d4b2f6cd0cf64b7b69986edfb05a5c8f3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:37:58 +0300 Subject: [PATCH 02/51] chore: files changed crates/tinywallet-bus/src/lib.rs,crates/tinywallet-bus/src/storage/mod.rs,crate Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/lib.rs | 2 - crates/tinywallet-bus/src/storage/mod.rs | 138 --------- .../tinywallet-bus/src/storage/mod_tests.rs | 291 ------------------ crates/tinywallet-bus/src/storage/payment.rs | 206 ------------- crates/tinywallet-module/src/lib.rs | 4 +- crates/tinywallet-module/src/lib_tests.rs | 14 +- crates/tinywallet-module/src/service/host.rs | 26 +- crates/tinywallet-x402/src/ledger/blocking.rs | 85 +++++ crates/tinywallet-x402/src/ledger/mod.rs | 10 +- crates/tinywallet-x402/src/ledger/persist.rs | 71 +---- crates/tinywallet-x402/src/ledger/schema.rs | 233 ++++++++++++-- 11 files changed, 326 insertions(+), 754 deletions(-) delete mode 100644 crates/tinywallet-bus/src/storage/mod.rs delete mode 100644 crates/tinywallet-bus/src/storage/mod_tests.rs delete mode 100644 crates/tinywallet-bus/src/storage/payment.rs create mode 100644 crates/tinywallet-x402/src/ledger/blocking.rs diff --git a/crates/tinywallet-bus/src/lib.rs b/crates/tinywallet-bus/src/lib.rs index 59a0b196..73a4959e 100644 --- a/crates/tinywallet-bus/src/lib.rs +++ b/crates/tinywallet-bus/src/lib.rs @@ -23,8 +23,6 @@ pub mod mnemonic; pub mod names; -#[cfg(feature = "storage")] -pub mod storage; #[cfg(feature = "wire")] pub mod tools; pub mod version; diff --git a/crates/tinywallet-bus/src/storage/mod.rs b/crates/tinywallet-bus/src/storage/mod.rs deleted file mode 100644 index 863f63e7..00000000 --- a/crates/tinywallet-bus/src/storage/mod.rs +++ /dev/null @@ -1,138 +0,0 @@ -//! The wallet module's storage schema (owner `wallet`) and the v1 to v2 steps -//! that bring the `x402` records forward. -//! -//! | v1 | v2 | -//! |---|---| -//! | collection `x402_budget` | collection `wallet.budgets` (hold `expires_at_ms` becomes `expires_ms`) | -//! | stream `x402.payments` | stream `wallet.payments` (`snake_case` entries, every instant `*_ms`) | -//! -//! The host composes [`storage_schema`] into its registry, and the module's -//! storage grant is generated from the same declaration. The steps are pure: a -//! re-run over the same input produces the same output. The ports crate this -//! uses declares no backend, so the contract stays synchronous and I/O-free. - -mod payment; - -use serde_json::{Map, Value, json}; -use tinystoragedrivers_core::{ - CollectionSpec, Owner, Schema, ScopeClass, SourceRecord, Step, StorageError, TargetRecord, -}; - -pub use payment::{LegacyPayment, StoredPayment, StoredPaymentStatus}; - -/// The schema owner: every name below starts with `wallet.`. -pub const OWNER: &str = "wallet"; -/// Collection holding the single budget-hold document. -pub const BUDGETS_COLLECTION: &str = "wallet.budgets"; -/// Body version of [`BUDGETS_COLLECTION`]. -pub const BUDGETS_VERSION: u32 = 2; -/// Id of the budget-hold document. -pub const HOLDS_ID: &str = "holds"; -/// Append-only stream of payment records. A payment that changes status is -/// appended again with the same id; readers fold to the latest per id. -pub const PAYMENTS_STREAM: &str = "wallet.payments"; - -/// v1 name of [`BUDGETS_COLLECTION`]. -pub const LEGACY_BUDGET_COLLECTION: &str = "x402_budget"; -/// v1 name of [`PAYMENTS_STREAM`]. -pub const LEGACY_PAYMENTS_STREAM: &str = "x402.payments"; - -/// What the wallet module stores: the budget-hold collection and the payments -/// stream, both in the module's own scope, with the steps that migrate the v1 -/// `x402_budget` collection and `x402.payments` stream into them. -/// -/// The payments stream is a spending history and is never sealed or deleted. -/// -/// # Panics -/// -/// Never in practice: `wallet` is a valid owner name. -#[must_use] -#[allow(clippy::expect_used, reason = "`wallet` is a fixed valid owner name")] -pub fn storage_schema() -> Schema { - Schema::new(Owner::new(OWNER).expect("`wallet` is a valid owner")) - .collection_with( - BUDGETS_VERSION, - CollectionSpec::new(BUDGETS_COLLECTION), - ScopeClass::Module, - ) - .stream(PAYMENTS_STREAM, ScopeClass::Module) - .step( - Step::new( - "budgets_v2", - BUDGETS_COLLECTION, - 1, - BUDGETS_VERSION, - |batch| Ok(migrate_budgets(batch)), - ) - .source(LEGACY_BUDGET_COLLECTION), - ) - .step( - Step::stream("payments_v2", PAYMENTS_STREAM, 1, 2, |source, entries| { - migrate_payments_stream(&source, entries) - }) - .source_prefix(LEGACY_PAYMENTS_STREAM), - ) -} - -/// `x402.payments` entries to `wallet.payments` entries. An entry that no -/// longer parses is dropped: the v1 reader skipped it with a warning too, so it -/// never counted toward a budget. -fn migrate_payments_stream( - source: &str, - entries: Vec, -) -> tinystoragedrivers_core::Result)>> { - if source != LEGACY_PAYMENTS_STREAM { - return Ok(None); - } - let mut migrated = Vec::with_capacity(entries.len()); - for entry in entries { - // An unreadable entry is dropped: the v1 reader skipped it too. - // Steps are pure, so nothing is logged. - if let Ok(legacy) = serde_json::from_value::(entry) { - migrated.push( - serde_json::to_value(StoredPayment::from(legacy)) - .map_err(|error| StorageError::invalid_input(error.to_string()))?, - ); - } - } - Ok(Some((PAYMENTS_STREAM.to_owned(), migrated))) -} - -/// The v1 hold document, renamed field by field. Holds are leases that expire -/// in minutes, so a document that is not a hold map migrates to an empty one -/// rather than wedging the host's migration; the budget the holds guarded is -/// recomputed from the payments stream. -fn migrate_budgets(batch: Vec) -> Vec { - batch - .into_iter() - .map(|record| { - let holds = renamed_holds(&record.body).unwrap_or_default(); - TargetRecord::new(BUDGETS_COLLECTION, record.id, json!({ "holds": holds })) - .created_ms(record.meta.created_ms) - .expires_ms(record.meta.expires_ms) - }) - .collect() -} - -/// `{holds: {key: {amount, expires_at_ms}}}` as `{key: {amount, expires_ms}}`. -fn renamed_holds(body: &Value) -> Option> { - let holds = match body.get("holds") { - None => return Some(Map::new()), - Some(holds) => holds.as_object()?, - }; - holds - .iter() - .map(|(key, hold)| { - let amount = hold.get("amount")?.as_u64()?; - let expires_ms = hold.get("expires_at_ms")?.as_i64()?; - Some(( - key.clone(), - json!({ "amount": amount, "expires_ms": expires_ms }), - )) - }) - .collect() -} - -#[cfg(test)] -#[path = "mod_tests.rs"] -mod tests; diff --git a/crates/tinywallet-bus/src/storage/mod_tests.rs b/crates/tinywallet-bus/src/storage/mod_tests.rs deleted file mode 100644 index 1aead744..00000000 --- a/crates/tinywallet-bus/src/storage/mod_tests.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! Tests for the wallet storage schema: its declarations compose, and the v1 -//! `x402` records migrate into the v2 collection and stream. - -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use super::*; - -use std::sync::Arc; - -use serde_json::json; -use tinystoragedrivers_core::{ - Blocking, Item, MemoryStorage, MigrateOptions, Precondition, Registry, Scope, ScopedStorage, - StorageBackend, -}; - -const V1_PAYMENT_MS: i64 = 1_773_576_000_000; // 2026-03-15T12:00:00Z - -fn v1_payment() -> Value { - json!({ - "id": "pay-1", - "url": "https://api.example.com/data", - "asset": "USDC", - "amountAtomic": 2500, - "amountDisplay": "0.002500 USDC", - "recipient": "Recipient", - "network": "eip155:8453", - "txSignature": "0xabc", - "status": "settled", - "timestamp": "2026-03-15T12:00:00Z", - "authorizationValidUntil": "2026-03-15T12:05:00.250Z", - "sessionId": "session-a", - "threadId": "thread-1", - "committed_hold": "owner:1" - }) -} - -fn scoped() -> (MemoryStorage, ScopedStorage) { - let backend = MemoryStorage::new(); - let scoped = backend - .for_scope(&Scope::local().module("wallet").unwrap()) - .unwrap(); - (backend, scoped) -} - -/// Declare the v2 items on `backend` and run the steps over `scoped`. -fn migrate(backend: &MemoryStorage, scoped: &ScopedStorage) -> Registry { - let registry = Registry::compose([storage_schema()]).unwrap(); - let bridge = Blocking::new().unwrap(); - let backend = backend.clone(); - let scoped = scoped.clone(); - bridge - .run(async move { - registry.prepare(&backend).await.unwrap(); - registry - .migrate(&scoped, &MigrateOptions::new()) - .await - .unwrap(); - registry - }) - .unwrap() -} - -fn put_v1(scoped: &ScopedStorage, collection: &'static str, id: &'static str, body: Value) { - let documents = Arc::clone(scoped.documents()); - Blocking::new() - .unwrap() - .run(async move { - documents - .ensure_collection(&CollectionSpec::new(collection)) - .await - .unwrap(); - documents - .put(collection, id, body, Precondition::None) - .await - .unwrap(); - }) - .unwrap(); -} - -fn append_v1(scoped: &ScopedStorage, entries: Vec) { - let streams = Arc::clone(scoped.streams()); - Blocking::new() - .unwrap() - .run(async move { - for entry in entries { - streams.append("x402.payments", entry).await.unwrap(); - } - }) - .unwrap(); -} - -#[test] -fn the_schema_composes_and_declares_module_scoped_wallet_items() { - let schema = storage_schema(); - assert_eq!(schema.owner.as_str(), "wallet"); - Registry::compose([schema.clone()]).unwrap(); - - let mut names: Vec<(String, ScopeClass)> = schema - .items - .iter() - .map(|item| (item.name().to_owned(), item.scope())) - .collect(); - names.sort_by(|a, b| a.0.cmp(&b.0)); - assert_eq!( - names, - vec![ - ("wallet.budgets".to_owned(), ScopeClass::Module), - ("wallet.payments".to_owned(), ScopeClass::Module), - ] - ); - assert!( - schema - .items - .iter() - .any(|item| matches!(item, Item::Collection { version: 2, .. })) - ); -} - -#[test] -fn v1_payments_migrate_to_snake_case_millisecond_entries() { - let (backend, scoped) = scoped(); - append_v1(&scoped, vec![v1_payment()]); - - migrate(&backend, &scoped); - - let streams = Arc::clone(scoped.streams()); - let (migrated, legacy_left) = Blocking::new() - .unwrap() - .run(async move { - ( - streams.read_window("wallet.payments", 0, 10).await.unwrap(), - streams.len("x402.payments").await.unwrap(), - ) - }) - .unwrap(); - assert_eq!(legacy_left, 0, "the v1 stream is removed"); - assert_eq!(migrated.len(), 1); - assert_eq!( - migrated[0].value, - json!({ - "id": "pay-1", - "url": "https://api.example.com/data", - "asset": "USDC", - "amount_atomic": 2500, - "amount_display": "0.002500 USDC", - "recipient": "Recipient", - "network": "eip155:8453", - "tx_signature": "0xabc", - "status": "settled", - "timestamp_ms": V1_PAYMENT_MS, - "authorization_valid_until_ms": V1_PAYMENT_MS + 300_250, - "session_id": "session-a", - "thread_id": "thread-1", - "committed_hold": "owner:1" - }) - ); -} - -#[test] -fn unreadable_v1_payment_entries_are_dropped() { - let (backend, scoped) = scoped(); - append_v1( - &scoped, - vec![json!("not a record"), v1_payment(), json!({"id": 7})], - ); - - migrate(&backend, &scoped); - - let streams = Arc::clone(scoped.streams()); - let migrated = Blocking::new() - .unwrap() - .run(async move { streams.read_window("wallet.payments", 0, 10).await.unwrap() }) - .unwrap(); - assert_eq!(migrated.len(), 1); -} - -#[test] -fn v1_holds_migrate_with_expires_ms_and_keep_their_creation_time() { - let (backend, scoped) = scoped(); - put_v1( - &scoped, - "x402_budget", - "holds", - json!({"holds": { - "owner:1": {"amount": 40, "expires_at_ms": 1_800_000_000_000_i64}, - "owner:2": {"amount": 7, "expires_at_ms": 1_800_000_500_000_i64} - }}), - ); - - let documents = Arc::clone(scoped.documents()); - let created_ms = Blocking::new() - .unwrap() - .run(async move { - documents - .get("x402_budget", "holds") - .await - .unwrap() - .unwrap() - .meta - .created_ms - }) - .unwrap(); - - migrate(&backend, &scoped); - - let documents = Arc::clone(scoped.documents()); - let (found, legacy) = Blocking::new() - .unwrap() - .run(async move { - ( - documents.get("wallet.budgets", "holds").await.unwrap(), - documents.get("x402_budget", "holds").await.unwrap(), - ) - }) - .unwrap(); - assert!(legacy.is_none(), "the v1 collection is emptied"); - let found = found.expect("the hold document was migrated"); - assert_eq!( - found.doc, - json!({"holds": { - "owner:1": {"amount": 40, "expires_ms": 1_800_000_000_000_i64}, - "owner:2": {"amount": 7, "expires_ms": 1_800_000_500_000_i64} - }}) - ); - assert_eq!(found.meta.schema, 2); - assert_eq!(found.meta.created_ms, created_ms); -} - -#[test] -fn an_unreadable_v1_hold_document_migrates_to_no_holds() { - let (backend, scoped) = scoped(); - put_v1(&scoped, "x402_budget", "holds", json!({"holds": 5})); - - migrate(&backend, &scoped); - - let documents = Arc::clone(scoped.documents()); - let found = Blocking::new() - .unwrap() - .run(async move { documents.get("wallet.budgets", "holds").await.unwrap() }) - .unwrap() - .unwrap(); - assert_eq!(found.doc, json!({"holds": {}})); -} - -#[test] -fn migrating_twice_changes_nothing() { - let (backend, scoped) = scoped(); - append_v1(&scoped, vec![v1_payment()]); - put_v1( - &scoped, - "x402_budget", - "holds", - json!({"holds": {"owner:1": {"amount": 1, "expires_at_ms": 5}}}), - ); - migrate(&backend, &scoped); - migrate(&backend, &scoped); - - let streams = Arc::clone(scoped.streams()); - let len = Blocking::new() - .unwrap() - .run(async move { streams.len("wallet.payments").await.unwrap() }) - .unwrap(); - assert_eq!(len, 1); -} - -#[test] -fn rfc3339_instants_parse_to_epoch_milliseconds() { - use super::payment::parse_rfc3339_ms as parse; - assert_eq!(parse("1970-01-01T00:00:00Z"), Some(0)); - assert_eq!(parse("2026-03-15T12:00:00Z"), Some(V1_PAYMENT_MS)); - assert_eq!( - parse("2026-03-15T12:05:00.250Z"), - Some(V1_PAYMENT_MS + 300_250) - ); - assert_eq!( - parse("2026-03-15T14:00:00.1239+02:00"), - Some(V1_PAYMENT_MS + 123) - ); - assert_eq!(parse("2024-02-29T00:00:00Z"), Some(1_709_164_800_000)); - assert_eq!(parse("1969-12-31T23:59:59Z"), Some(-1_000)); - for bad in [ - "", - "2026-03-15", - "2026-13-15T12:00:00Z", - "2026-03-15T12:00:00", - "2026-03-15T12:00:00.Z", - "2026-03-15T12:00:00+0200", - ] { - assert_eq!(parse(bad), None, "{bad}"); - } -} diff --git a/crates/tinywallet-bus/src/storage/payment.rs b/crates/tinywallet-bus/src/storage/payment.rs deleted file mode 100644 index c693bd4f..00000000 --- a/crates/tinywallet-bus/src/storage/payment.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! The payment record as it is stored, and the v1 shape it migrates from. - -use serde::{Deserialize, Deserializer, Serialize}; - -/// Where a stored payment stands. The same four states, spelled the same way, -/// as the implementation's public status type, which converts to and from this. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum StoredPaymentStatus { - /// Signed and sent, not yet settled. - Pending, - /// A trusted settlement receipt confirms payment. - Settled, - /// A trusted result established that the payment did not settle. - Failed, - /// Refused before anything was signed. - Denied, -} - -/// One payment as stored in `wallet.payments`: `snake_case`, every instant an -/// epoch-millisecond `*_ms` field, no wrapper. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct StoredPayment { - /// Unique id of the attempt. - pub id: String, - /// The URL the payment bought access to. - pub url: String, - /// The asset paid in. - pub asset: String, - /// The amount in atomic units of `asset`. - pub amount_atomic: u64, - /// The amount formatted for people. - pub amount_display: String, - /// Who was paid. - pub recipient: String, - /// The network, in CAIP-2 form. - pub network: String, - /// The settlement transaction, once reported. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tx_signature: Option, - /// Where the payment stands. - pub status: StoredPaymentStatus, - /// When this state was written, in epoch milliseconds. - pub timestamp_ms: i64, - /// When an exported authorization becomes unusable, in epoch milliseconds. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_valid_until_ms: Option, - /// Solana's `lastValidBlockHeight` for the exported transaction. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub solana_last_valid_block_height: Option, - /// When the authorization was observed expired, in epoch milliseconds. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_expired_at_ms: Option, - /// The block height at which the expiry was observed. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_expiry_observed_height: Option, - /// The session that made the payment. - pub session_id: String, - /// The conversation thread, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thread_id: Option, - /// The budget hold this entry committed, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub committed_hold: Option, -} - -/// A v1 `x402.payments` entry: the camelCase wire record with RFC 3339 -/// instants, and the hold metadata beside it. -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LegacyPayment { - id: String, - url: String, - asset: String, - amount_atomic: u64, - amount_display: String, - recipient: String, - network: String, - #[serde(default)] - tx_signature: Option, - status: StoredPaymentStatus, - #[serde(deserialize_with = "instant_ms")] - timestamp: i64, - #[serde(default, deserialize_with = "optional_instant_ms")] - authorization_valid_until: Option, - #[serde(default)] - solana_last_valid_block_height: Option, - #[serde(default, deserialize_with = "optional_instant_ms")] - authorization_expired_at: Option, - #[serde(default)] - authorization_expiry_observed_height: Option, - session_id: String, - #[serde(default)] - thread_id: Option, - #[serde(default, rename = "committed_hold")] - committed_hold: Option, -} - -impl From for StoredPayment { - fn from(legacy: LegacyPayment) -> Self { - Self { - id: legacy.id, - url: legacy.url, - asset: legacy.asset, - amount_atomic: legacy.amount_atomic, - amount_display: legacy.amount_display, - recipient: legacy.recipient, - network: legacy.network, - tx_signature: legacy.tx_signature, - status: legacy.status, - timestamp_ms: legacy.timestamp, - authorization_valid_until_ms: legacy.authorization_valid_until, - solana_last_valid_block_height: legacy.solana_last_valid_block_height, - authorization_expired_at_ms: legacy.authorization_expired_at, - authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, - session_id: legacy.session_id, - thread_id: legacy.thread_id, - committed_hold: legacy.committed_hold, - } - } -} - -fn instant_ms<'de, D: Deserializer<'de>>(deserializer: D) -> Result { - let text = String::deserialize(deserializer)?; - parse_rfc3339_ms(&text) - .ok_or_else(|| serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant"))) -} - -fn optional_instant_ms<'de, D: Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - Option::::deserialize(deserializer)? - .map(|text| { - parse_rfc3339_ms(&text).ok_or_else(|| { - serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant")) - }) - }) - .transpose() -} - -/// An RFC 3339 instant (`2026-03-15T12:00:00.250Z`, or with a `+hh:mm` -/// offset) as epoch milliseconds, by integer arithmetic only. Fractions finer -/// than a millisecond are truncated. -pub(super) fn parse_rfc3339_ms(text: &str) -> Option { - let bytes = text.as_bytes(); - let digits = |from: usize, len: usize| -> Option { - let part = bytes.get(from..from + len)?; - if !part.iter().all(u8::is_ascii_digit) { - return None; - } - part.iter() - .try_fold(0_i64, |n, d| Some(n * 10 + i64::from(d - b'0'))) - }; - let separator = |at: usize, want: &[u8]| bytes.get(at).is_some_and(|b| want.contains(b)); - if !(separator(4, b"-") - && separator(7, b"-") - && separator(10, b"Tt ") - && separator(13, b":") - && separator(16, b":")) - { - return None; - } - let (year, month, day) = (digits(0, 4)?, digits(5, 2)?, digits(8, 2)?); - let (hour, minute, second) = (digits(11, 2)?, digits(14, 2)?, digits(17, 2)?); - if !(1..=12).contains(&month) - || !(1..=31).contains(&day) - || hour > 23 - || minute > 59 - || second > 60 - { - return None; - } - let mut at = 19; - let mut millis = 0; - if bytes.get(at) == Some(&b'.') { - let start = at + 1; - let mut end = start; - while bytes.get(end).is_some_and(u8::is_ascii_digit) { - end += 1; - } - if end == start { - return None; - } - for (place, digit) in bytes[start..end].iter().take(3).enumerate() { - millis += i64::from(digit - b'0') * [100, 10, 1][place]; - } - at = end; - } - let offset_minutes = match bytes.get(at)? { - b'Z' | b'z' if at + 1 == bytes.len() => 0, - sign @ (b'+' | b'-') if at + 6 == bytes.len() && separator(at + 3, b":") => { - let minutes = digits(at + 1, 2)? * 60 + digits(at + 4, 2)?; - if *sign == b'-' { -minutes } else { minutes } - } - _ => return None, - }; - // Days from civil (Howard Hinnant's algorithm), proleptic Gregorian. - let y = if month <= 2 { year - 1 } else { year }; - let era = y.div_euclid(400); - let year_of_era = y - era * 400; - let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - let days = era * 146_097 + day_of_era - 719_468; - let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; - Some(seconds * 1_000 + millis) -} diff --git a/crates/tinywallet-module/src/lib.rs b/crates/tinywallet-module/src/lib.rs index f8db063b..b267a783 100644 --- a/crates/tinywallet-module/src/lib.rs +++ b/crates/tinywallet-module/src/lib.rs @@ -20,8 +20,8 @@ mod service; pub use service::linked_module; pub use service::{BUS_NAME, HOST_INTERFACE, HOST_OBJECT_PATH, OBJECT_PATH}; /// What the module stores (owner `wallet`). A host composes it into its schema -/// registry and generates the module's storage grant from the same items. -pub use tinywallet_x402::ledger::storage_schema; +/// registry's host-side collection declarations. +pub use tinywallet_x402::ledger::collections as storage_collections; #[cfg(test)] #[path = "lib_tests.rs"] diff --git a/crates/tinywallet-module/src/lib_tests.rs b/crates/tinywallet-module/src/lib_tests.rs index c3124f99..32e484eb 100644 --- a/crates/tinywallet-module/src/lib_tests.rs +++ b/crates/tinywallet-module/src/lib_tests.rs @@ -4,16 +4,14 @@ use super::*; -use tinystoragedrivers_core::{Registry, ScopeClass}; +use tinystoragedrivers_types::CollectionSpec; #[test] fn every_stored_item_is_wallet_owned_and_module_scoped() { - let schema = storage_schema(); - assert_eq!(schema.owner.as_str(), "wallet"); - assert!(!schema.items.is_empty()); - for item in &schema.items { - assert!(item.name().starts_with("wallet."), "{}", item.name()); - assert_eq!(item.scope(), ScopeClass::Module, "{}", item.name()); + let collections = storage_collections(); + assert!(!collections.is_empty()); + for collection in &collections { + assert!(collection.name.starts_with("wallet."), "{}", collection.name); } - Registry::compose([schema]).unwrap(); + assert!(collections.iter().any(|item| *item == CollectionSpec::new("wallet.budgets"))); } diff --git a/crates/tinywallet-module/src/service/host.rs b/crates/tinywallet-module/src/service/host.rs index 5292fbc6..3285cded 100644 --- a/crates/tinywallet-module/src/service/host.rs +++ b/crates/tinywallet-module/src/service/host.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use log::debug; use tinybus::{Connection, Error as BusError, Proxy}; -use tinystoragedrivers_core::{ScopedStorage, StorageBackend}; +use tinystoragedrivers_api::Storage; use tinywallet_bus::wire::{ AuthorizationResult, AuthorizeNativeWalletExecutionRequest, AuthorizeWeb3ExecutionRequest, AuthorizeX402PaymentRequest, ChainTransportRequest, ChainTransportResult, HostResponse, @@ -20,7 +20,7 @@ pub(crate) struct HostCallbacks { proxy: Proxy, connection: Connection, /// The host's storage, connected on first use and shared by every clone. - storage: Arc>>, + storage: Arc>>, /// Test seam: ledger storage used in place of the storage bus. #[cfg(test)] test_ledger_storage: Arc>>, @@ -49,16 +49,15 @@ impl HostCallbacks { /// The host binds the scope from the authenticated caller; nothing here /// names one. A connect failure is not cached, so a host that starts /// serving storage later is picked up by the next call. - async fn storage(&self) -> tinystoragedrivers_core::Result { + async fn storage(&self) -> tinystoragedrivers_types::Result { let mut slot = self.storage.lock().await; if let Some(scoped) = slot.as_ref() { return Ok(scoped.clone()); } debug!("[wallet::host] connecting to the host storage bus"); let bus = tinystoragedrivers_busproxy::connect_storage(self.connection.clone()).await?; - let scoped = bus.for_scope(&tinystoragedrivers_busproxy::module_scope_label())?; - *slot = Some(scoped.clone()); - Ok(scoped) + *slot = Some(bus.clone()); + Ok(bus) } /// The ports the x402 ledger persists through: the host's payments stream @@ -78,17 +77,10 @@ impl HostCallbacks { { return Ok(storage); } - match self.storage().await { - Ok(scoped) => Ok(LedgerStorage::from_scoped(&scoped)), - #[cfg(feature = "e2e-memory-storage")] - Err(error) => { - static MEMORY: std::sync::OnceLock = std::sync::OnceLock::new(); - log::warn!("[wallet::host] host storage unavailable ({error}); using memory"); - Ok(MEMORY.get_or_init(LedgerStorage::memory).clone()) - } - #[cfg(not(feature = "e2e-memory-storage"))] - Err(error) => Err(format!("x402 ledger storage is unavailable: {error}")), - } + self.storage() + .await + .map(|storage| LedgerStorage::from_storage(&storage)) + .map_err(|error| format!("x402 ledger storage is unavailable: {error}")) } /// Serve `storage` to the ledger in place of the storage bus. diff --git a/crates/tinywallet-x402/src/ledger/blocking.rs b/crates/tinywallet-x402/src/ledger/blocking.rs new file mode 100644 index 00000000..2ee7b421 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/blocking.rs @@ -0,0 +1,85 @@ +//! Dedicated tokio bridge for the ledger's synchronous API. + +use std::future::Future; +use std::pin::Pin; +use std::sync::mpsc as std_mpsc; +use std::thread; + +use tinystoragedrivers_types::{Result, StorageError}; +use tokio::sync::mpsc; + +type Job = Pin + Send>>; + +thread_local! { + static ON_BRIDGE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs storage-port futures on a dedicated runtime thread. +#[derive(Clone)] +pub(super) struct Blocking { + jobs: mpsc::UnboundedSender, +} + +impl std::fmt::Debug for Blocking { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.debug_struct("Blocking").finish_non_exhaustive() + } +} + +impl Blocking { + /// Start the dedicated runtime thread. + pub(super) fn new() -> Result { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| StorageError::backend("cannot build the ledger storage runtime").with_source(error))?; + let (jobs, mut receiver) = mpsc::unbounded_channel::(); + thread::Builder::new() + .name("tinywallet-storage".into()) + .spawn(move || { + ON_BRIDGE.with(|flag| flag.set(true)); + runtime.block_on(async move { + let mut running = tokio::task::JoinSet::new(); + while let Some(job) = receiver.recv().await { + running.spawn(job); + while running.try_join_next().is_some() {} + } + while running.join_next().await.is_some() {} + }); + }) + .map_err(|error| StorageError::backend("cannot start the ledger storage thread").with_source(error))?; + Ok(Self { jobs }) + } + + /// Run one future to completion and return its output. + pub(super) fn run(&self, future: F) -> Result + where + F: Future + Send + 'static, + T: Send + 'static, + { + if ON_BRIDGE.with(std::cell::Cell::get) { + return Err(StorageError::backend( + "a ledger storage future called back into its blocking bridge", + )); + } + let (reply, wait) = std_mpsc::sync_channel(1); + let job: Job = Box::pin(async move { + let _ = reply.send(future.await); + }); + self.jobs + .send(job) + .map_err(|_| StorageError::backend("the ledger storage bridge has stopped"))?; + let receive = || { + wait.recv().map_err(|_| { + StorageError::backend("the ledger storage bridge dropped a call") + }) + }; + if tokio::runtime::Handle::try_current().is_ok_and(|handle| { + handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread + }) { + tokio::task::block_in_place(receive) + } else { + receive() + } + } +} diff --git a/crates/tinywallet-x402/src/ledger/mod.rs b/crates/tinywallet-x402/src/ledger/mod.rs index 55564282..04020fe4 100644 --- a/crates/tinywallet-x402/src/ledger/mod.rs +++ b/crates/tinywallet-x402/src/ledger/mod.rs @@ -7,7 +7,7 @@ //! //! # Persistence //! -//! The ledger persists through the `tinystoragedrivers-core` ports only; the +//! The ledger persists through the runtime-neutral `tinystoragedrivers-api` ports; the //! host hands in a [`LedgerStorage`] and decides the backend. Records are //! appended to the `wallet.payments` stream. It is append-only: a payment that //! changes status is appended again with the same id, and readers see every @@ -16,9 +16,8 @@ //! ledger blind to its history would admit payments past the budget. //! //! Entries are `snake_case` objects with every instant an epoch-millisecond -//! `*_ms` field, and the ledger holds records at that precision. The names and -//! the steps that migrate the v1 `x402_budget` collection and `x402.payments` -//! stream are declared by [`storage_schema`]. +//! `*_ms` field. The ledger applies its own v1 to v2 migration when opened. +//! Hosts can inspect [`collections`] to ensure the module-bound declarations. //! //! # Budgets //! @@ -62,6 +61,7 @@ #[cfg(test)] pub(crate) mod faulty; mod global; +mod blocking; mod persist; mod reservation; mod schema; @@ -76,7 +76,7 @@ pub use global::{ }; pub use persist::{HOLD_RENEW_EVERY, LedgerStorage}; pub use reservation::{Reservation, reserve}; -pub use schema::storage_schema; +pub use schema::collections; pub use store::PaymentLedger; pub use types::{ BudgetCheck, BudgetRefusal, PaymentRecord, PaymentStatus, ReservationId, SpendingBudget, diff --git a/crates/tinywallet-x402/src/ledger/persist.rs b/crates/tinywallet-x402/src/ledger/persist.rs index d59246af..ef0ee47d 100644 --- a/crates/tinywallet-x402/src/ledger/persist.rs +++ b/crates/tinywallet-x402/src/ledger/persist.rs @@ -1,5 +1,5 @@ //! The ledger's storage: the `wallet.payments` stream and one `wallet.budgets` hold document, both -//! through the `tinystoragedrivers-core` ports. +//! through the runtime-neutral `tinystoragedrivers-api` ports. //! //! The ports are async and the ledger's API is synchronous (it runs under a //! std mutex), so every call goes through [`Blocking`], which drives the future @@ -13,15 +13,11 @@ use std::sync::Arc; use chrono::{DateTime, Utc}; use log::debug; use serde::{Deserialize, Serialize}; -use tinystoragedrivers_core::{ - Blocking, DocumentStore, ErrorKind, MemoryStorage, Precondition, Scope, ScopedStorage, - StorageBackend, StreamStore, Version, WriteOptions, -}; +use tinystoragedrivers_api::{DocumentStore, StreamStore, Storage}; +use tinystoragedrivers_types::{ErrorKind, Precondition, StorageError, Version, WriteOptions}; -use super::schema::{ - BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, LEGACY_BUDGET_COLLECTION, - LEGACY_PAYMENTS_STREAM, OWNER, PAYMENTS_STREAM, StoredPayment, -}; +use super::schema::{self, BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, PAYMENTS_STREAM, StoredPayment}; +use super::blocking::Blocking; use super::types::PaymentRecord; const LOG_PREFIX: &str = "[x402::persist]"; @@ -52,29 +48,9 @@ impl LedgerStorage { /// Persist through a host-provisioned scoped handle. #[must_use] - pub fn from_scoped(storage: &ScopedStorage) -> Self { + pub fn from_storage(storage: &Storage) -> Self { Self::new(storage.documents().clone(), storage.streams().clone()) } - - /// A private in-memory store. Nothing survives the process: for tests and - /// hosts that deliberately want an ephemeral ledger. - /// - /// # Panics - /// - /// Never in practice: the fixed scope name is valid and the memory backend - /// opens any valid scope. - #[must_use] - #[allow( - clippy::expect_used, - reason = "fixed valid scope on the memory backend" - )] - pub fn memory() -> Self { - let scope = Scope::local().module(OWNER).expect("valid scope"); - let scoped = MemoryStorage::new() - .for_scope(&scope) - .expect("memory backend opens any scope"); - Self::from_scoped(&scoped) - } } /// One budget hold as stored. @@ -177,7 +153,7 @@ impl Persist { fn run(&self, what: &str, future: F) -> Result where T: Send + 'static, - F: Future> + Send + 'static, + F: Future> + Send + 'static, { match self.bridge.run(future) { Ok(Ok(value)) => Ok(value), @@ -188,36 +164,15 @@ impl Persist { pub(super) fn open(storage: LedgerStorage) -> Result { let bridge = Blocking::new().map_err(|e| format!("start storage bridge: {e}"))?; let persist = Self { storage, bridge }; - persist.refuse_unmigrated()?; + let documents = Arc::clone(&persist.storage.documents); + let streams = Arc::clone(&persist.storage.streams); + persist + .run("migrate x402 storage", async move { + schema::migrate(documents.as_ref(), streams.as_ref()).await + })?; Ok(persist) } - /// Fail when v1 data is still in place: opening would read only the v2 - /// names and admit spend without counting that history. Migration is the - /// host's job (`storage_schema()`), so the ledger refuses rather than guess. - fn refuse_unmigrated(&self) -> Result<(), String> { - let streams = Arc::clone(&self.storage.streams); - let legacy = self.run("read legacy payments stream", async move { - streams.len(LEGACY_PAYMENTS_STREAM).await - })?; - if legacy > 0 { - return Err(format!( - "{legacy} unmigrated x402.payments entries: compose storage_schema() and migrate before opening the ledger" - )); - } - let documents = Arc::clone(&self.storage.documents); - let holds = self.run("check legacy budget holds", async move { - documents.get(LEGACY_BUDGET_COLLECTION, HOLDS_ID).await - })?; - if holds.is_some() { - return Err( - "legacy x402 budget holds remain: complete storage migration before opening the ledger" - .to_string(), - ); - } - Ok(()) - } - /// Records from stream offset `from` to the end, with the next offset. /// Entries that no longer parse are skipped with a warning. pub(super) fn read_from(&self, from: u64) -> Result<(Vec, u64), String> { diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 9b22d516..ffcac190 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -1,38 +1,217 @@ -//! The ledger's storage schema lives in the contract crate -//! (`tinywallet_bus::storage`), so a host reads it without linking this -//! implementation. This module re-exports it at its old path and adds the -//! conversions between the public records and their storage shape. - -pub use tinywallet_bus::storage::storage_schema; -pub(super) use tinywallet_bus::storage::{ - BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, LEGACY_BUDGET_COLLECTION, - LEGACY_PAYMENTS_STREAM, OWNER, PAYMENTS_STREAM, StoredPayment, StoredPaymentStatus, +//! The x402 ledger's owner-local storage declarations and migrations. + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use tinystoragedrivers_api::{DocumentStore, StreamStore}; +use tinystoragedrivers_types::{ + CollectionSpec, ErrorKind, Precondition, StorageError, WriteOptions, }; -use super::types::PaymentStatus; +mod payment; +pub use payment::{LegacyPayment, StoredPayment, StoredPaymentStatus}; + +/// The owner prefix for the x402 ledger's storage names. +pub const OWNER: &str = "wallet"; +/// Collection containing the single budget-hold document. +pub const BUDGETS_COLLECTION: &str = "wallet.budgets"; +/// Schema version for [`BUDGETS_COLLECTION`]. +pub const BUDGETS_VERSION: u32 = 2; +/// Identifier of the budget-hold document. +pub const HOLDS_ID: &str = "holds"; +/// Append-only payment history stream. +pub const PAYMENTS_STREAM: &str = "wallet.payments"; +/// Previous budget collection name migrated on first open. +pub const LEGACY_BUDGET_COLLECTION: &str = "x402_budget"; +/// Previous payment stream name migrated on first open. +pub const LEGACY_PAYMENTS_STREAM: &str = "x402.payments"; + +const MIGRATIONS_COLLECTION: &str = "wallet.migrations"; +const MIGRATIONS_ID: &str = "x402"; +const BATCH_SIZE: usize = 512; -impl From for StoredPaymentStatus { - fn from(status: PaymentStatus) -> Self { - match status { - PaymentStatus::Pending => Self::Pending, - PaymentStatus::Settled => Self::Settled, - PaymentStatus::Failed => Self::Failed, - PaymentStatus::Denied => Self::Denied, +/// Collections the host should ensure for a module-bound x402 ledger. +/// +/// The ledger applies its own migration on open; the host only ensures these +/// pure collection declarations in the scope it has already bound. +#[must_use] +pub fn collections() -> Vec { + vec![CollectionSpec::new(BUDGETS_COLLECTION), CollectionSpec::new(MIGRATIONS_COLLECTION)] +} + +/// Apply x402-owned migrations before the ledger reads or writes its history. +pub(super) async fn migrate( + documents: &dyn DocumentStore, + streams: &dyn StreamStore, +) -> tinystoragedrivers_types::Result<()> { + for spec in collections() { + documents.ensure_collection(&spec).await?; + } + let state = documents.get(MIGRATIONS_COLLECTION, MIGRATIONS_ID).await?; + let current = state + .as_ref() + .and_then(|record| record.value.get("version")) + .and_then(Value::as_u64) + .unwrap_or_default(); + if current >= BUDGETS_VERSION.into() { + return Ok(()); + } + + migrate_budgets(documents).await?; + migrate_payments(streams).await?; + + let next = json!({ "version": BUDGETS_VERSION }); + let precondition = state + .map(|record| Precondition::Version(record.version)) + .unwrap_or(Precondition::Absent); + match documents + .put(MIGRATIONS_COLLECTION, MIGRATIONS_ID, next, precondition) + .await + { + Ok(_) => Ok(()), + Err(error) if error.kind == ErrorKind::Conflict => { + let latest = documents.get(MIGRATIONS_COLLECTION, MIGRATIONS_ID).await?; + let completed = latest + .as_ref() + .and_then(|record| record.value.get("version")) + .and_then(Value::as_u64) + .is_some_and(|version| version >= BUDGETS_VERSION.into()); + if completed { + Ok(()) + } else { + Err(error) + } } + Err(error) => Err(error), } } -impl From for PaymentStatus { - fn from(status: StoredPaymentStatus) -> Self { - match status { - StoredPaymentStatus::Pending => Self::Pending, - StoredPaymentStatus::Settled => Self::Settled, - StoredPaymentStatus::Failed => Self::Failed, - StoredPaymentStatus::Denied => Self::Denied, +async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_types::Result<()> { + let Some(legacy) = documents + .get(LEGACY_BUDGET_COLLECTION, HOLDS_ID) + .await? + else { + return Ok(()); + }; + let holds = renamed_holds(&legacy.value).unwrap_or_default(); + let migrated = json!({ "holds": holds.clone() }); + match documents + .get(BUDGETS_COLLECTION, HOLDS_ID) + .await? + { + Some(existing) if existing.value == migrated => Ok(()), + Some(_) => Err(StorageError::backend( + "wallet budget migration found conflicting target data", + )), + None => { + let mut options = WriteOptions::new() + .schema(BUDGETS_VERSION) + .created_ms(legacy.meta.created_ms); + if let Some(expires_ms) = legacy.meta.expires_ms { + options = options.expires_ms(expires_ms); + } + match documents + .put_with( + BUDGETS_COLLECTION, + HOLDS_ID, + migrated, + Precondition::Absent, + options, + ) + .await + { + Ok(_) => Ok(()), + Err(error) if error.kind == ErrorKind::Conflict => { + let latest = documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?; + if latest.is_some_and(|record| record.value == json!({ "holds": holds })) { + Ok(()) + } else { + Err(error) + } + } + Err(error) => Err(error), + } } } } -#[cfg(test)] -#[path = "schema_tests.rs"] -mod tests; +async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types::Result<()> { + let source_len = streams.len(LEGACY_PAYMENTS_STREAM).await?; + let mut source = Vec::new(); + let mut offset = 0; + while offset < source_len { + let window = streams + .read_window(LEGACY_PAYMENTS_STREAM, offset, BATCH_SIZE) + .await?; + if window.is_empty() { + break; + } + offset = window.last().map_or(offset, |entry| entry.offset.saturating_add(1)); + source.extend(window.into_iter().map(|entry| entry.value)); + } + let migrated = migrate_payments_stream(LEGACY_PAYMENTS_STREAM, source)? + .map_or_else(Vec::new, |(_, entries)| entries); + if migrated.is_empty() { + return Ok(()); + } + + let target_len = streams.len(PAYMENTS_STREAM).await?; + if target_len > migrated.len() as u64 { + return Err(StorageError::backend( + "wallet payment migration found unexpected target entries", + )); + } + let existing = streams + .read_window(PAYMENTS_STREAM, 0, target_len as usize) + .await?; + if existing + .iter() + .zip(migrated.iter()) + .any(|(entry, value)| entry.value != *value) + { + return Err(StorageError::backend( + "wallet payment migration found conflicting target data", + )); + } + let start = target_len as usize; + if start < migrated.len() { + streams + .append_batch_if_offset(PAYMENTS_STREAM, target_len, migrated[start..].to_vec()) + .await?; + } + Ok(()) +} + +fn migrate_payments_stream( + source: &str, + entries: Vec, +) -> tinystoragedrivers_types::Result)>> { + if source != LEGACY_PAYMENTS_STREAM { + return Ok(None); + } + let mut migrated = Vec::with_capacity(entries.len()); + for entry in entries { + if let Ok(legacy) = serde_json::from_value::(entry) { + migrated.push( + serde_json::to_value(StoredPayment::from(legacy)) + .map_err(|error| StorageError::invalid_input(error.to_string()))?, + ); + } + } + Ok(Some((PAYMENTS_STREAM.to_owned(), migrated))) +} + +fn renamed_holds(body: &Value) -> Option> { + let holds = match body.get("holds") { + None => return Some(Map::new()), + Some(holds) => holds.as_object()?, + }; + holds + .iter() + .map(|(key, hold)| { + let amount = hold.get("amount")?.as_u64()?; + let expires_ms = hold.get("expires_at_ms")?.as_i64()?; + Some((key.clone(), json!({ "amount": amount, "expires_ms": expires_ms }))) + }) + .collect() +} From 0e4cdadfa0de346aed3c0c8844ad3426be8f3846 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:39:35 +0300 Subject: [PATCH 03/51] refactor(deps): update dependencies and test scripts This change updates the `tinywallet-module` Cargo.toml to include new storage driver dependencies and adjusts the E2E test scripts to remove the `e2e-memory-storage` feature flag during the build process. This aligns the build process with the new dependency structure. Auto-committed-on: dragonfly --- crates/tinywallet-module/Cargo.toml | 2 ++ crates/tinywallet-x402/src/ledger/schema.rs | 1 + scripts/test-e2e.ps1 | 2 +- scripts/test-e2e.sh | 2 +- 4 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/tinywallet-module/Cargo.toml b/crates/tinywallet-module/Cargo.toml index 4399fc1f..06f1670d 100644 --- a/crates/tinywallet-module/Cargo.toml +++ b/crates/tinywallet-module/Cargo.toml @@ -80,6 +80,8 @@ zeroize = "1" # Storage over the bus: the module reaches the host's storage (x402 payments # stream and budget-hold documents) through the ports crate's bus transport, not # a process-local registry. +tinystoragedrivers-types = { workspace = true } +tinystoragedrivers-api = { workspace = true } tinystoragedrivers-busproxy = { workspace = true } # Diagnostics for the storage connection and hold-lease renewal. log = "0.4" diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index ffcac190..b58caaa1 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -8,6 +8,7 @@ use tinystoragedrivers_types::{ CollectionSpec, ErrorKind, Precondition, StorageError, WriteOptions, }; +#[path = "schema_payment.rs"] mod payment; pub use payment::{LegacyPayment, StoredPayment, StoredPaymentStatus}; diff --git a/scripts/test-e2e.ps1 b/scripts/test-e2e.ps1 index c4f800b5..f94f9dd6 100644 --- a/scripts/test-e2e.ps1 +++ b/scripts/test-e2e.ps1 @@ -8,7 +8,7 @@ $rootPrefix = $root.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::Dire if (-not $target.StartsWith($rootPrefix, [StringComparison]::OrdinalIgnoreCase)) { throw 'CARGO_TARGET_DIR must stay inside the repository' } $stage = Join-Path $target 'tinywallet-module-e2e' -cargo build --locked --release --package tinywallet-module --features e2e-memory-storage +cargo build --locked --release --package tinywallet-module if ($LASTEXITCODE -ne 0) { throw 'Failed to build tinywallet-module' } Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force $stage | Out-Null diff --git a/scripts/test-e2e.sh b/scripts/test-e2e.sh index 06eea516..c1cceb7d 100755 --- a/scripts/test-e2e.sh +++ b/scripts/test-e2e.sh @@ -20,7 +20,7 @@ case "$host" in *) echo "unsupported E2E host target: $host" >&2; exit 2 ;; esac -cargo build --locked --release --package tinywallet-module --features e2e-memory-storage +cargo build --locked --release --package tinywallet-module stage="$target/tinywallet-module-e2e" rm -rf "$stage" mkdir -p "$stage" From 8f48df66137fa6c5ba4fd8b24b8ebc4d49c708f8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:40:02 +0300 Subject: [PATCH 04/51] chore: files changed Cargo.lock Auto-committed-on: dragonfly --- Cargo.lock | 456 ++++++++++++++++++++++++++--------------------------- 1 file changed, 223 insertions(+), 233 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3248af0a..d546a50a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,16 +8,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" -[[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" -dependencies = [ - "crypto-common 0.1.7", - "generic-array", -] - [[package]] name = "android_system_properties" version = "0.1.6" @@ -65,17 +55,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "atomicwrites" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ef1bb8d1b645fe38d51dfc331d720fb5fc2c94b440c76cc79c80ff265ca33e3" -dependencies = [ - "rustix 0.38.44", - "tempfile", - "windows-sys 0.52.0", -] - [[package]] name = "autocfg" version = "1.5.1" @@ -240,12 +219,6 @@ dependencies = [ "hex-conservative 0.2.2", ] -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - [[package]] name = "bitflags" version = "2.13.1" @@ -322,30 +295,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" -[[package]] -name = "chacha20" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", -] - -[[package]] -name = "chacha20poly1305" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" -dependencies = [ - "aead", - "chacha20", - "cipher", - "poly1305", - "zeroize", -] - [[package]] name = "chrono" version = "0.4.45" @@ -358,26 +307,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common 0.1.7", - "inout", - "zeroize", -] - -[[package]] -name = "clack-private-fs" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fcca21d8096fca7f1c3a22c3109e38927c9b587007c9c7a13b327e5a955baba" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "cmov" version = "0.5.4" @@ -520,7 +449,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] @@ -719,6 +647,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.5.0" @@ -773,6 +713,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -782,16 +728,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "fs4" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" -dependencies = [ - "rustix 1.1.4", - "windows-sys 0.61.2", -] - [[package]] name = "funty" version = "2.0.0" @@ -813,6 +749,17 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "futures-task" version = "0.3.34" @@ -826,6 +773,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", @@ -891,11 +839,32 @@ dependencies = [ "subtle", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.1", +] [[package]] name = "hex" @@ -927,15 +896,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3011d1213f159867b13cfd6ac92d2cd5f1345762c63be3554e84092d85a50bbd" -[[package]] -name = "hkdf" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" -dependencies = [ - "hmac 0.12.1", -] - [[package]] name = "hmac" version = "0.12.1" @@ -1186,16 +1146,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", - "hashbrown", -] - -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "generic-array", + "hashbrown 0.17.1", ] [[package]] @@ -1271,10 +1222,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] -name = "linux-raw-sys" -version = "0.4.15" +name = "libsqlite3-sys" +version = "0.38.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] [[package]] name = "linux-raw-sys" @@ -1357,12 +1313,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "parking_lot" version = "0.12.5" @@ -1424,17 +1374,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" -[[package]] -name = "poly1305" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" -dependencies = [ - "cpufeatures 0.2.17", - "opaque-debug", - "universal-hash", -] - [[package]] name = "potential_utf" version = "0.1.6" @@ -1468,7 +1407,7 @@ version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" dependencies = [ - "bitflags 2.13.1", + "bitflags", "num-traits", "rand", "rand_chacha", @@ -1557,7 +1496,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.13.1", + "bitflags", ] [[package]] @@ -1638,25 +1577,37 @@ dependencies = [ ] [[package]] -name = "rustc_version" -version = "0.4.1" +name = "rsqlite-vfs" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" dependencies = [ - "semver", + "hashbrown 0.16.1", + "thiserror 2.0.20", ] [[package]] -name = "rustix" -version = "0.38.44" +name = "rusqlite" +version = "0.40.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" dependencies = [ - "bitflags 2.13.1", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", ] [[package]] @@ -1665,10 +1616,10 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags 2.13.1", + "bitflags", "errno", "libc", - "linux-raw-sys 0.12.1", + "linux-raw-sys", "windows-sys 0.61.2", ] @@ -1913,6 +1864,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1993,7 +1956,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.4", + "rustix", "windows-sys 0.61.2", ] @@ -2079,84 +2042,161 @@ dependencies = [ "tracing", ] +[[package]] +name = "tinystoragedrivers-api" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +dependencies = [ + "async-trait", + "bytes", + "futures-core", + "serde", + "serde_json", + "tinystoragedrivers-types", + "zeroize", +] + +[[package]] +name = "tinystoragedrivers-blob" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +dependencies = [ + "async-trait", + "bytes", + "futures-core", + "serde", + "serde_json", + "tinystoragedrivers-api", + "tinystoragedrivers-types", +] + [[package]] name = "tinystoragedrivers-bus" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" dependencies = [ "serde", "serde_json", "tinybus", + "tinystoragedrivers-types", ] [[package]] name = "tinystoragedrivers-busproxy" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" dependencies = [ "async-trait", + "bytes", + "futures-core", "serde", "serde_json", "tinybus", + "tinystoragedrivers-api", "tinystoragedrivers-bus", - "tinystoragedrivers-client", - "tinystoragedrivers-core", + "tinystoragedrivers-types", + "tokio", + "zeroize", +] + +[[package]] +name = "tinystoragedrivers-connect" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +dependencies = [ + "rusqlite", + "tinystoragedrivers-types", "tokio", ] [[package]] -name = "tinystoragedrivers-client" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +name = "tinystoragedrivers-document" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" dependencies = [ "async-trait", + "data-encoding", + "rusqlite", "serde", "serde_json", - "tinystoragedrivers-bus", - "tinystoragedrivers-core", - "tinystoragedrivers-secrets", + "sha2 0.10.9", + "tinystoragedrivers-api", + "tinystoragedrivers-connect", + "tinystoragedrivers-types", "tokio", + "zstd", +] + +[[package]] +name = "tinystoragedrivers-kv" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +dependencies = [ + "async-trait", + "serde", + "serde_json", + "tinystoragedrivers-api", + "tinystoragedrivers-types", ] [[package]] -name = "tinystoragedrivers-core" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +name = "tinystoragedrivers-queue" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" dependencies = [ "async-trait", "data-encoding", "serde", "serde_json", "sha2 0.10.9", - "thiserror 2.0.20", + "tinystoragedrivers-api", + "tinystoragedrivers-types", "tokio", "ulid", - "zstd", ] [[package]] name = "tinystoragedrivers-secrets" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" dependencies = [ "async-trait", - "atomicwrites", - "chacha20poly1305", - "clack-private-fs", - "fs4", - "hkdf", - "rustix 1.1.4", - "serde", + "tinystoragedrivers-api", + "tinystoragedrivers-types", + "zeroize", +] + +[[package]] +name = "tinystoragedrivers-testkit" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +dependencies = [ + "async-trait", + "bytes", + "futures-util", "serde_json", - "sha2 0.10.9", - "tinystoragedrivers-core", + "tinystoragedrivers-api", + "tinystoragedrivers-blob", + "tinystoragedrivers-document", + "tinystoragedrivers-kv", + "tinystoragedrivers-queue", + "tinystoragedrivers-secrets", + "tinystoragedrivers-types", "tokio", - "winapi-util", - "windows-permissions", - "winsafe", + "ulid", "zeroize", ] +[[package]] +name = "tinystoragedrivers-types" +version = "2.0.0" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.20", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -2225,7 +2265,6 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.20", - "tinystoragedrivers-core", ] [[package]] @@ -2264,10 +2303,10 @@ dependencies = [ "tempfile", "tinybus", "tinybus-module", - "tinystoragedrivers-bus", + "tinystoragedrivers-api", "tinystoragedrivers-busproxy", - "tinystoragedrivers-client", - "tinystoragedrivers-core", + "tinystoragedrivers-testkit", + "tinystoragedrivers-types", "tinywallet", "tinywallet-bus", "tinywallet-crypto", @@ -2324,7 +2363,9 @@ dependencies = [ "sha2 0.11.0", "sha3 0.12.0", "thiserror 2.0.20", - "tinystoragedrivers-core", + "tinystoragedrivers-api", + "tinystoragedrivers-testkit", + "tinystoragedrivers-types", "tinytools", "tinywallet", "tinywallet-bus", @@ -2419,7 +2460,7 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags 2.13.1", + "bitflags", "bytes", "futures-util", "http", @@ -2508,16 +2549,6 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" -[[package]] -name = "universal-hash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common 0.1.7", - "subtle", -] - [[package]] name = "untrusted" version = "0.9.0" @@ -2588,6 +2619,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -2702,37 +2739,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "windows-core" version = "0.62.2" @@ -2774,16 +2780,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-permissions" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e2ccdc3c6bf4d4a094e031b63fadd08d8e42abd259940eb8aa5fdc09d4bf9be" -dependencies = [ - "bitflags 1.3.2", - "winapi", -] - [[package]] name = "windows-result" version = "0.4.1" @@ -2890,12 +2886,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" -[[package]] -name = "winsafe" -version = "0.0.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" - [[package]] name = "wit-bindgen" version = "0.46.0" @@ -2924,7 +2914,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.4", + "rustix", ] [[package]] From 02eb68ee0e1d66a629862024d3290e643d3a1c4a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:41:18 +0300 Subject: [PATCH 05/51] refactor(ledger): standardize ledger storage access in tests This change refactors how in-memory ledger storage is initialized across the module and crate. It introduces a dedicated `memory_ledger_storage` function in the module and a `memory()` method in the ledger storage implementation to centralize and standardize test setup. Auto-committed-on: dragonfly --- crates/tinywallet-module/src/service/x402.rs | 7 ++++ .../src/service/x402_lifecycle_tests.rs | 2 +- .../src/service/x402_tests.rs | 8 ++-- crates/tinywallet-x402/src/ledger/persist.rs | 12 +++++- crates/tinywallet-x402/src/ledger/schema.rs | 41 ++++++++++++++----- 5 files changed, 54 insertions(+), 16 deletions(-) diff --git a/crates/tinywallet-module/src/service/x402.rs b/crates/tinywallet-module/src/service/x402.rs index 86c515e1..5cf97407 100644 --- a/crates/tinywallet-module/src/service/x402.rs +++ b/crates/tinywallet-module/src/service/x402.rs @@ -585,6 +585,13 @@ fn take_request_secrets( #[cfg(test)] static LEDGER_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +#[cfg(test)] +fn memory_ledger_storage() -> ledger::LedgerStorage { + let scope = tinystoragedrivers_types::Scope::new("tinywallet.module-test") + .expect("the test scope is valid"); + ledger::LedgerStorage::from_storage(&tinystoragedrivers_testkit::memory_storage(&scope)) +} + #[cfg(test)] #[path = "x402_tests.rs"] mod tests; diff --git a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs index 0e2da191..51ae98fe 100644 --- a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs +++ b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs @@ -67,7 +67,7 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { .callbacks .as_ref() .unwrap() - .set_test_ledger_storage(tinywallet_x402::ledger::LedgerStorage::memory()); + .set_test_ledger_storage(memory_ledger_storage()); let handle = wallet .x402_configure(X402ConfigureRequest { config: X402ConfigResponse { diff --git a/crates/tinywallet-module/src/service/x402_tests.rs b/crates/tinywallet-module/src/service/x402_tests.rs index 3f9826aa..5cae60b5 100644 --- a/crates/tinywallet-module/src/service/x402_tests.rs +++ b/crates/tinywallet-module/src/service/x402_tests.rs @@ -138,7 +138,7 @@ async fn ledger_lifecycle_rejects_stale_handles_and_malformed_challenges() { daily_max_atomic: 100, monthly_max_atomic: 100, }, - tinywallet_x402::ledger::LedgerStorage::memory(), + memory_ledger_storage(), ) .unwrap(); assert!(format!("{runtime:?}").contains("X402Runtime")); @@ -326,7 +326,7 @@ async fn history_and_live_budget_operations_keep_the_configured_ledger() { daily_max_atomic: 200, monthly_max_atomic: 300, }, - tinywallet_x402::ledger::LedgerStorage::memory(), + memory_ledger_storage(), ) .unwrap(); let handle = runtime.handle(); @@ -390,7 +390,7 @@ async fn x402_bus_methods_serve_history_budget_and_detailed_summary() { .callbacks .as_ref() .unwrap() - .set_test_ledger_storage(tinywallet_x402::ledger::LedgerStorage::memory()); + .set_test_ledger_storage(memory_ledger_storage()); let service = wallet .x402_configure(X402ConfigureRequest { config: X402ConfigResponse { @@ -621,7 +621,7 @@ async fn x402_pending_capacity_is_reserved_before_authorization_and_released_on_ .callbacks .as_ref() .unwrap() - .set_test_ledger_storage(tinywallet_x402::ledger::LedgerStorage::memory()); + .set_test_ledger_storage(memory_ledger_storage()); let handle = wallet .x402_configure(X402ConfigureRequest { config: X402ConfigResponse { diff --git a/crates/tinywallet-x402/src/ledger/persist.rs b/crates/tinywallet-x402/src/ledger/persist.rs index ef0ee47d..14e4c591 100644 --- a/crates/tinywallet-x402/src/ledger/persist.rs +++ b/crates/tinywallet-x402/src/ledger/persist.rs @@ -14,7 +14,7 @@ use chrono::{DateTime, Utc}; use log::debug; use serde::{Deserialize, Serialize}; use tinystoragedrivers_api::{DocumentStore, StreamStore, Storage}; -use tinystoragedrivers_types::{ErrorKind, Precondition, StorageError, Version, WriteOptions}; +use tinystoragedrivers_types::{ErrorKind, Precondition, Version, WriteOptions}; use super::schema::{self, BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, PAYMENTS_STREAM, StoredPayment}; use super::blocking::Blocking; @@ -51,6 +51,16 @@ impl LedgerStorage { pub fn from_storage(storage: &Storage) -> Self { Self::new(storage.documents().clone(), storage.streams().clone()) } + + /// Create a fresh real in-memory backend for this crate's unit tests. + #[cfg(test)] + #[must_use] + #[allow(clippy::expect_used, reason = "the test scope is a fixed valid label")] + pub(crate) fn memory() -> Self { + let scope = tinystoragedrivers_types::Scope::new("tinywallet.test") + .expect("the test scope is valid"); + Self::from_storage(&tinystoragedrivers_testkit::memory_storage(&scope)) + } } /// One budget hold as stored. diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index b58caaa1..2f7d80a6 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -1,7 +1,5 @@ //! The x402 ledger's owner-local storage declarations and migrations. -use std::sync::Arc; - use serde_json::{Map, Value, json}; use tinystoragedrivers_api::{DocumentStore, StreamStore}; use tinystoragedrivers_types::{ @@ -10,7 +8,8 @@ use tinystoragedrivers_types::{ #[path = "schema_payment.rs"] mod payment; -pub use payment::{LegacyPayment, StoredPayment, StoredPaymentStatus}; +pub use payment::{LegacyPayment, StoredPayment}; +pub(super) use payment::StoredPaymentStatus; /// The owner prefix for the x402 ledger's storage names. pub const OWNER: &str = "wallet"; @@ -51,7 +50,7 @@ pub(super) async fn migrate( let state = documents.get(MIGRATIONS_COLLECTION, MIGRATIONS_ID).await?; let current = state .as_ref() - .and_then(|record| record.value.get("version")) + .and_then(|record| record.doc.get("version")) .and_then(Value::as_u64) .unwrap_or_default(); if current >= BUDGETS_VERSION.into() { @@ -70,11 +69,11 @@ pub(super) async fn migrate( .await { Ok(_) => Ok(()), - Err(error) if error.kind == ErrorKind::Conflict => { + Err(error) if error.kind() == ErrorKind::Conflict => { let latest = documents.get(MIGRATIONS_COLLECTION, MIGRATIONS_ID).await?; let completed = latest .as_ref() - .and_then(|record| record.value.get("version")) + .and_then(|record| record.doc.get("version")) .and_then(Value::as_u64) .is_some_and(|version| version >= BUDGETS_VERSION.into()); if completed { @@ -94,13 +93,13 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty else { return Ok(()); }; - let holds = renamed_holds(&legacy.value).unwrap_or_default(); + let holds = renamed_holds(&legacy.doc).unwrap_or_default(); let migrated = json!({ "holds": holds.clone() }); match documents .get(BUDGETS_COLLECTION, HOLDS_ID) .await? { - Some(existing) if existing.value == migrated => Ok(()), + Some(existing) if existing.doc == migrated => Ok(()), Some(_) => Err(StorageError::backend( "wallet budget migration found conflicting target data", )), @@ -122,9 +121,9 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty .await { Ok(_) => Ok(()), - Err(error) if error.kind == ErrorKind::Conflict => { + Err(error) if error.kind() == ErrorKind::Conflict => { let latest = documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?; - if latest.is_some_and(|record| record.value == json!({ "holds": holds })) { + if latest.is_some_and(|record| record.doc == json!({ "holds": holds })) { Ok(()) } else { Err(error) @@ -136,6 +135,28 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty } } +impl From for StoredPaymentStatus { + fn from(status: super::types::PaymentStatus) -> Self { + match status { + super::types::PaymentStatus::Pending => Self::Pending, + super::types::PaymentStatus::Settled => Self::Settled, + super::types::PaymentStatus::Failed => Self::Failed, + super::types::PaymentStatus::Denied => Self::Denied, + } + } +} + +impl From for super::types::PaymentStatus { + fn from(status: StoredPaymentStatus) -> Self { + match status { + StoredPaymentStatus::Pending => Self::Pending, + StoredPaymentStatus::Settled => Self::Settled, + StoredPaymentStatus::Failed => Self::Failed, + StoredPaymentStatus::Denied => Self::Denied, + } + } +} + async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types::Result<()> { let source_len = streams.len(LEGACY_PAYMENTS_STREAM).await?; let mut source = Vec::new(); From 2020a4378a1bdef229b1e5a7c0515fb1f529984a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:41:34 +0300 Subject: [PATCH 06/51] refactor(tests): update storage driver imports and usage This change updates the dependencies and usage within the storage bus tests to align with the newer tinystoragedrivers API. It replaces imports from `tinystoragedrivers_core` with those from `tinystoragedrivers_api` and adjusts how storage backends are initialized and accessed in the tests. Auto-committed-on: dragonfly --- crates/tinywallet-module/Cargo.toml | 1 + .../src/service/x402_storage_bus_tests.rs | 16 +++++++--------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/crates/tinywallet-module/Cargo.toml b/crates/tinywallet-module/Cargo.toml index 06f1670d..4567fbca 100644 --- a/crates/tinywallet-module/Cargo.toml +++ b/crates/tinywallet-module/Cargo.toml @@ -100,6 +100,7 @@ linked = ["static-link"] workspace = true [dev-dependencies] +tinystoragedrivers-client = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } tinystoragedrivers-testkit = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } # Encodes and decodes the Solana transaction fixtures in native tests. base64 = "0.23" diff --git a/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs b/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs index ebe0138a..6930cbee 100644 --- a/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs +++ b/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs @@ -11,17 +11,15 @@ use std::sync::Arc; use tinybus::Connection; use tinystoragedrivers_busproxy::{PerCallerEndpoint, serve}; use tinystoragedrivers_client::StorageServer; -use tinystoragedrivers_core::{ - DocumentStore, MemoryStorage, Precondition, Result as StorageResult, Scope, ScopedStorage, - StorageBackend, StreamEntry, StreamStore, async_trait, -}; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_types::{Precondition, Result as StorageResult, Scope, StreamEntry}; use tinywallet_bus::wire::{X402CloseRequest, X402ConfigureRequest, X402SummaryRequest}; use tinywallet_x402::ledger::{LedgerStorage, PaymentLedger, SpendingBudget}; struct Fixture { wallet: crate::service::Wallet, /// The host's own handle on the scope the module is bound to. - host: ScopedStorage, + host: tinystoragedrivers_api::Storage, _served: tinystoragedrivers_busproxy::ServedStorage, broker: tokio::task::JoinHandle>, } @@ -34,8 +32,8 @@ async fn fixture() -> Fixture { let host_connection = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); - let backend = MemoryStorage::new(); - let host = backend.for_scope(&Scope::local()).unwrap(); + let backend = tinystoragedrivers_testkit::MemoryBackend::new(); + let host = backend.for_scope(&Scope::new("wallet.module-bus-test").unwrap()).unwrap(); let served_scope = host.clone(); let endpoint = PerCallerEndpoint::new(move |_sender| Some(StorageServer::new(served_scope.clone()))); @@ -68,7 +66,7 @@ fn config(session: &str) -> X402ConfigResponse { fn host_ledger(fixture: &Fixture) -> PaymentLedger { PaymentLedger::open( - LedgerStorage::from_scoped(&fixture.host), + LedgerStorage::from_storage(&fixture.host), "host-side", SpendingBudget { per_request_max_atomic: 100, @@ -388,7 +386,7 @@ fn unreadable_stream_storage() -> LedgerStorage { self.0.append_batch(s, v).await } async fn read_window(&self, _: &str, _: u64, _: usize) -> StorageResult> { - Err(tinystoragedrivers_core::StorageError::backend( + Err(tinystoragedrivers_types::StorageError::backend( "injected read failure", )) } From 26f0494331d79f07eaddb9e5ee9110488e688000 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:42:06 +0300 Subject: [PATCH 07/51] test(ledger): update faulty storage tests and implementation Refactors the implementation of faulty storage for ledger testing to use the `tinystoragedrivers_testkit` for deterministic failure injection. This cleans up the previous manual implementation of stream failure simulation. Auto-committed-on: dragonfly --- .../src/service/x402_storage_bus_tests.rs | 54 +++------ crates/tinywallet-x402/src/ledger/faulty.rs | 103 ++++++------------ 2 files changed, 50 insertions(+), 107 deletions(-) diff --git a/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs b/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs index 6930cbee..ae0d98a9 100644 --- a/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs +++ b/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs @@ -11,15 +11,17 @@ use std::sync::Arc; use tinybus::Connection; use tinystoragedrivers_busproxy::{PerCallerEndpoint, serve}; use tinystoragedrivers_client::StorageServer; +use tinystoragedrivers_api::{Storage, StreamStore}; use tinystoragedrivers_api::StorageBackend; -use tinystoragedrivers_types::{Precondition, Result as StorageResult, Scope, StreamEntry}; +use tinystoragedrivers_types::{ErrorKind, Precondition, Scope}; +use tinystoragedrivers_testkit::{Failing, FaultPlan}; use tinywallet_bus::wire::{X402CloseRequest, X402ConfigureRequest, X402SummaryRequest}; use tinywallet_x402::ledger::{LedgerStorage, PaymentLedger, SpendingBudget}; struct Fixture { wallet: crate::service::Wallet, /// The host's own handle on the scope the module is bound to. - host: tinystoragedrivers_api::Storage, + host: Storage, _served: tinystoragedrivers_busproxy::ServedStorage, broker: tokio::task::JoinHandle>, } @@ -237,8 +239,6 @@ async fn a_failed_reconfigure_keeps_the_previous_service_usable() { fixture.broker.abort(); } -// With `e2e-memory-storage` a missing host falls back to memory by design. -#[cfg(not(feature = "e2e-memory-storage"))] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn configure_fails_closed_when_storage_goes_away_for_the_replacement() { let _guard = LEDGER_TEST_LOCK.lock().await; @@ -372,41 +372,15 @@ async fn concurrent_reservations_over_the_bus_do_not_starve_the_runtime() { fixture.broker.abort(); } -/// Memory storage whose payments stream refuses every read. +/// Memory storage whose payments stream refuses its next read. fn unreadable_stream_storage() -> LedgerStorage { - #[derive(Debug)] - struct NoRead(Arc); - - #[async_trait] - impl StreamStore for NoRead { - async fn append(&self, s: &str, v: serde_json::Value) -> StorageResult { - self.0.append(s, v).await - } - async fn append_batch(&self, s: &str, v: Vec) -> StorageResult { - self.0.append_batch(s, v).await - } - async fn read_window(&self, _: &str, _: u64, _: usize) -> StorageResult> { - Err(tinystoragedrivers_types::StorageError::backend( - "injected read failure", - )) - } - async fn len(&self, s: &str) -> StorageResult { - self.0.len(s).await - } - async fn truncate_before(&self, s: &str, o: u64) -> StorageResult { - self.0.truncate_before(s, o).await - } - async fn delete_stream(&self, s: &str) -> StorageResult { - self.0.delete_stream(s).await - } - async fn streams(&self, p: &str) -> StorageResult> { - self.0.streams(p).await - } - } - - let scoped = MemoryStorage::new() - .for_scope(&Scope::new("x402-unreadable").unwrap()) - .unwrap(); - let documents: Arc = Arc::clone(scoped.documents()); - LedgerStorage::new(documents, Arc::new(NoRead(Arc::clone(scoped.streams())))) + let scope = Scope::new("x402-unreadable").unwrap(); + let storage = tinystoragedrivers_testkit::memory_storage(&scope); + let faults = FaultPlan::new(); + faults.fail_operation_nth("streams.read_window", 1, ErrorKind::Backend); + let streams: Arc = Arc::new(Failing::with_plan( + Arc::clone(storage.streams()), + faults, + )); + LedgerStorage::new(Arc::clone(storage.documents()), streams) } diff --git a/crates/tinywallet-x402/src/ledger/faulty.rs b/crates/tinywallet-x402/src/ledger/faulty.rs index 7b55807f..4361ee8e 100644 --- a/crates/tinywallet-x402/src/ledger/faulty.rs +++ b/crates/tinywallet-x402/src/ledger/faulty.rs @@ -1,88 +1,51 @@ -//! Test support: a [`LedgerStorage`] whose payments stream can be made to fail -//! on demand, to pin down what the ledger does when storage refuses. +//! Test support for deterministic failures in the ledger's storage ports. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; use serde_json::Value; -use tinystoragedrivers_core::{ - DocumentStore, Result, StorageError, StreamEntry, StreamStore, async_trait, -}; +use tinystoragedrivers_api::StreamStore; +use tinystoragedrivers_testkit::{Failing, FaultPlan}; +use tinystoragedrivers_types::{ErrorKind, Scope}; +use super::blocking::Blocking; use super::persist::LedgerStorage; -/// Switches for the injected faults. -#[derive(Debug, Default)] +/// Fault schedules for stream append and read operations. +#[derive(Debug, Clone)] pub(crate) struct Faults { - /// Every stream append fails. - pub(crate) append: AtomicBool, - /// Every stream read fails. - pub(crate) read: AtomicBool, + /// Fails the next scheduled stream append. + pub(crate) append: FaultPlan, + /// Fails the next scheduled stream read. + pub(crate) read: FaultPlan, } -#[derive(Debug)] -struct FaultyStreams { - inner: Arc, - faults: Arc, -} - -#[async_trait] -impl StreamStore for FaultyStreams { - async fn append(&self, stream: &str, value: Value) -> Result { - if self.faults.append.load(Ordering::SeqCst) { - return Err(StorageError::backend("injected append failure")); - } - self.inner.append(stream, value).await - } - - async fn append_batch(&self, stream: &str, values: Vec) -> Result { - self.inner.append_batch(stream, values).await - } - - async fn read_window(&self, stream: &str, from: u64, limit: usize) -> Result> { - if self.faults.read.load(Ordering::SeqCst) { - return Err(StorageError::backend("injected read failure")); - } - self.inner.read_window(stream, from, limit).await - } - - async fn len(&self, stream: &str) -> Result { - self.inner.len(stream).await - } - - async fn truncate_before(&self, stream: &str, offset: u64) -> Result { - self.inner.truncate_before(stream, offset).await - } - - async fn delete_stream(&self, stream: &str) -> Result { - self.inner.delete_stream(stream).await - } - - async fn streams(&self, prefix: &str) -> Result> { - self.inner.streams(prefix).await - } +/// Real in-memory storage decorated with injectable storage-port failures. +pub(crate) fn faulty_storage() -> (LedgerStorage, Faults) { + let base = LedgerStorage::memory(); + let faults = Faults { + append: FaultPlan::new(), + read: FaultPlan::new(), + }; + let append = Arc::new(Failing::with_plan( + Arc::clone(&base.streams), + faults.append.clone(), + )); + let streams: Arc = Arc::new(Failing::with_plan(append, faults.read.clone())); + (LedgerStorage::new(Arc::clone(&base.documents), streams), faults) } -/// In-memory storage plus the switches that break its payments stream. -pub(crate) fn faulty_storage() -> (LedgerStorage, Arc) { - let base = LedgerStorage::memory(); - let faults = Arc::new(Faults::default()); - let streams: Arc = Arc::new(FaultyStreams { - inner: Arc::clone(&base.streams), - faults: Arc::clone(&faults), - }); - let documents: Arc = Arc::clone(&base.documents); - (LedgerStorage::new(documents, streams), faults) +/// Fail the next append or read, according to the supplied schedule. +pub(crate) fn fail_next(plan: &FaultPlan, operation: &str) { + plan.fail_operation_nth(operation, 1, ErrorKind::Backend); } -/// Append raw JSON entries to the payments stream behind `storage`, as another -/// writer (or an older version of this crate) would have left them. +/// Append raw JSON entries behind a ledger as another writer would. pub(crate) fn append_raw(storage: &LedgerStorage, values: Vec) { let streams = Arc::clone(&storage.streams); - let blocking = tinystoragedrivers_core::Blocking::new().unwrap(); - blocking + Blocking::new() + .unwrap() .run(async move { for value in values { streams @@ -93,3 +56,9 @@ pub(crate) fn append_raw(storage: &LedgerStorage, values: Vec) { }) .unwrap(); } + +/// A fixed scope used only by in-memory test fixtures. +#[allow(dead_code)] +fn test_scope() -> Scope { + Scope::new("tinywallet.test").unwrap() +} From c09d45884f84162c6eff6fcdc5d8b45c8e91fa0f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:42:19 +0300 Subject: [PATCH 08/51] refactor(ledger): update fault injection mechanism This change updates how fault injection is performed in ledger tests by replacing direct atomic store calls with a new `fail_next` helper function. This centralizes the logic for simulating stream failures across various test scenarios. Auto-committed-on: dragonfly --- crates/tinywallet-x402/src/ledger/faulty.rs | 7 +------ crates/tinywallet-x402/src/ledger/mod_holds_tests.rs | 2 +- crates/tinywallet-x402/src/ledger/mod_tests.rs | 12 ++++++------ 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/faulty.rs b/crates/tinywallet-x402/src/ledger/faulty.rs index 4361ee8e..8d7cfd99 100644 --- a/crates/tinywallet-x402/src/ledger/faulty.rs +++ b/crates/tinywallet-x402/src/ledger/faulty.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use tinystoragedrivers_api::StreamStore; use tinystoragedrivers_testkit::{Failing, FaultPlan}; -use tinystoragedrivers_types::{ErrorKind, Scope}; +use tinystoragedrivers_types::ErrorKind; use super::blocking::Blocking; use super::persist::LedgerStorage; @@ -57,8 +57,3 @@ pub(crate) fn append_raw(storage: &LedgerStorage, values: Vec) { .unwrap(); } -/// A fixed scope used only by in-memory test fixtures. -#[allow(dead_code)] -fn test_scope() -> Scope { - Scope::new("tinywallet.test").unwrap() -} diff --git a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs index 0118d175..667547de 100644 --- a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs @@ -356,7 +356,7 @@ fn a_payment_still_counts_against_the_cap_before_its_hold_is_released() { fn a_per_request_refusal_does_not_depend_on_storage_reads() { let (storage, faults) = super::faulty::faulty_storage(); let mut ledger = PaymentLedger::open(storage, SESSION, budget()).unwrap(); - faults.read.store(true, std::sync::atomic::Ordering::SeqCst); + super::faulty::fail_next(&faults.read, "streams.read_window"); assert_eq!( ledger.reserve_at(now(), 101).unwrap().unwrap_err(), BudgetRefusal::PerRequest { diff --git a/crates/tinywallet-x402/src/ledger/mod_tests.rs b/crates/tinywallet-x402/src/ledger/mod_tests.rs index 6f684f1c..6988f4af 100644 --- a/crates/tinywallet-x402/src/ledger/mod_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_tests.rs @@ -565,10 +565,10 @@ fn a_record_written_without_a_thread_still_loads() { fn a_payment_is_kept_in_memory_when_the_append_fails() { let (storage, faults) = faulty_storage(); let mut ledger = ledger_in(&storage); - faults.append.store(true, Ordering::SeqCst); + super::faulty::fail_next(&faults.append, "streams.append"); ledger.record_payment(record(5, PaymentStatus::Settled, now(), SESSION)); assert_eq!(ledger.recent_payments(10).len(), 1); - faults.append.store(false, Ordering::SeqCst); + faults.append.clear(); assert!( ledger_in(&storage).recent_payments(10).is_empty(), "nothing reached the stream" @@ -579,7 +579,7 @@ fn a_payment_is_kept_in_memory_when_the_append_fails() { fn a_fallible_record_is_not_visible_until_it_is_saved() { let (storage, faults) = faulty_storage(); let mut ledger = ledger_in(&storage); - faults.append.store(true, Ordering::SeqCst); + super::faulty::fail_next(&faults.append, "streams.append"); assert!( ledger @@ -594,7 +594,7 @@ fn a_failed_durable_commit_keeps_the_reservation_held() { let (storage, faults) = faulty_storage(); let mut ledger = ledger_in(&storage); let reservation = ledger.reserve(5).unwrap().unwrap(); - faults.append.store(true, Ordering::SeqCst); + super::faulty::fail_next(&faults.append, "streams.append"); assert!( ledger @@ -611,7 +611,7 @@ fn a_failed_durable_commit_keeps_the_reservation_held() { #[test] fn a_ledger_that_cannot_read_its_history_refuses_to_open() { let (storage, faults) = faulty_storage(); - faults.read.store(true, Ordering::SeqCst); + super::faulty::fail_next(&faults.read, "streams.read_window"); let error = PaymentLedger::open(storage, SESSION, budget()).unwrap_err(); assert!(error.contains("read payments stream"), "{error}"); } @@ -620,7 +620,7 @@ fn a_ledger_that_cannot_read_its_history_refuses_to_open() { fn a_reservation_fails_closed_when_the_stream_cannot_be_read() { let (storage, faults) = faulty_storage(); let mut ledger = ledger_in(&storage); - faults.read.store(true, Ordering::SeqCst); + super::faulty::fail_next(&faults.read, "streams.read_window"); assert!(ledger.reserve_at(now(), 1_000).is_err()); assert_eq!(ledger.reserved_atomic(), 0, "nothing was held"); } From 1151d52623dfd028e5456e85c21ea42ec8793942 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:42:44 +0300 Subject: [PATCH 09/51] test(service): update failing append storage test Refactors the implementation of `failing_append_storage` to use the testkit's `Failing` wrapper instead of a custom `NoAppend` struct, making the test setup cleaner and more idiomatic for simulating storage failures. Auto-committed-on: dragonfly --- .../src/service/x402_lifecycle_tests.rs | 46 ++++--------------- 1 file changed, 9 insertions(+), 37 deletions(-) diff --git a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs index 51ae98fe..e2cae309 100644 --- a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs +++ b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs @@ -376,49 +376,21 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { /// In-memory storage whose payments stream refuses every append: the ledger /// opens, holds budget, and then cannot durably record the authorization. fn failing_append_storage() -> tinywallet_x402::ledger::LedgerStorage { - use tinystoragedrivers_core::{ - MemoryStorage, Result as StorageResult, Scope, StorageBackend, StorageError, StreamEntry, - StreamStore, async_trait, - }; - - #[derive(Debug)] - struct NoAppend(Arc); - - #[async_trait] - impl StreamStore for NoAppend { - async fn append(&self, _: &str, _: serde_json::Value) -> StorageResult { - Err(StorageError::backend("injected append failure")) - } - async fn append_batch(&self, s: &str, v: Vec) -> StorageResult { - self.0.append_batch(s, v).await - } - async fn read_window(&self, s: &str, f: u64, l: usize) -> StorageResult> { - self.0.read_window(s, f, l).await - } - async fn len(&self, s: &str) -> StorageResult { - self.0.len(s).await - } - async fn truncate_before(&self, s: &str, o: u64) -> StorageResult { - self.0.truncate_before(s, o).await - } - async fn delete_stream(&self, s: &str) -> StorageResult { - self.0.delete_stream(s).await - } - async fn streams(&self, p: &str) -> StorageResult> { - self.0.streams(p).await - } - } + use tinystoragedrivers_api::StreamStore; + use tinystoragedrivers_testkit::{Failing, FaultPlan}; + use tinystoragedrivers_types::{ErrorKind, Scope}; - let scoped = MemoryStorage::new() - .for_scope(&Scope::new("x402-fail").unwrap()) - .unwrap(); + let scoped = tinystoragedrivers_testkit::memory_storage( + &Scope::new("x402-fail").unwrap(), + ); + let faults = FaultPlan::new(); + faults.fail_operation_nth("streams.append", 1, ErrorKind::Backend); tinywallet_x402::ledger::LedgerStorage::new( Arc::clone(scoped.documents()), - Arc::new(NoAppend(Arc::clone(scoped.streams()))), + Arc::new(Failing::with_plan(Arc::clone(scoped.streams()), faults)), ) } -#[cfg(not(feature = "e2e-memory-storage"))] #[tokio::test] async fn x402_configure_fails_closed_when_the_host_serves_no_storage() { use tinywallet_bus::wire::X402ConfigureRequest; From 17306a9de6d8b50cdc20260d00b19314f46b7d2a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:43:14 +0300 Subject: [PATCH 10/51] refactor(ledger): update schema tests to use new storage types This refactors the schema tests to use the updated `tinystoragedrivers_types` instead of the older `tinystoragedrivers_core`. It also updates several test functions to reflect the new API structure for testing ledger migration and schema declarations. Auto-committed-on: dragonfly --- .../src/ledger/schema_tests.rs | 137 ++++++++---------- 1 file changed, 64 insertions(+), 73 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 77f07572..d3888812 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -1,21 +1,21 @@ -//! The wallet schema's v1 records, migrated by the contract crate's steps, load -//! into the ledger. +//! Tests for owner-local x402 schema declarations and open-time migrations. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use std::sync::Arc; - use serde_json::{Value, json}; -use tinystoragedrivers_core::{ - Blocking, MemoryStorage, MigrateOptions, Registry, Scope, ScopedStorage, StorageBackend, -}; +use tinystoragedrivers_types::{Precondition, Scope, WriteOptions}; use super::super::{LedgerStorage, PaymentLedger, PaymentStatus, SpendingBudget}; -use super::storage_schema; +use super::{BUDGETS_COLLECTION, HOLDS_ID, collections}; +use crate::ledger::blocking::Blocking; + +const V1_PAYMENT_MS: i64 = 1_773_576_000_000; -const V1_PAYMENT_MS: i64 = 1_773_576_000_000; // 2026-03-15T12:00:00Z +fn test_storage() -> tinystoragedrivers_api::Storage { + tinystoragedrivers_testkit::memory_storage(&Scope::new("wallet.migration-test").unwrap()) +} -fn v1_payment() -> Value { +fn legacy_payment() -> Value { json!({ "id": "pay-1", "url": "https://api.example.com/data", @@ -34,52 +34,27 @@ fn v1_payment() -> Value { }) } -fn scoped() -> (MemoryStorage, ScopedStorage) { - let backend = MemoryStorage::new(); - let scoped = backend - .for_scope(&Scope::local().module("wallet").unwrap()) - .unwrap(); - (backend, scoped) -} - -/// Declare the v2 items on `backend` and run the steps over `scoped`. -fn migrate(backend: &MemoryStorage, scoped: &ScopedStorage) -> Registry { - let registry = Registry::compose([storage_schema()]).unwrap(); - let bridge = Blocking::new().unwrap(); - let backend = backend.clone(); - let scoped = scoped.clone(); - bridge - .run(async move { - registry.prepare(&backend).await.unwrap(); - registry - .migrate(&scoped, &MigrateOptions::new()) - .await - .unwrap(); - registry - }) - .unwrap() +#[test] +fn host_declarations_are_pure_wallet_collection_specs() { + let declared = collections(); + assert_eq!(declared.len(), 2); + assert!(declared.iter().all(|collection| collection.name.starts_with("wallet."))); + assert!(declared.iter().any(|collection| collection.name == BUDGETS_COLLECTION)); } -fn append_v1(scoped: &ScopedStorage, entries: Vec) { - let streams = Arc::clone(scoped.streams()); +#[test] +fn opening_the_ledger_migrates_legacy_payments_before_reading_them() { + let storage = test_storage(); + let streams = std::sync::Arc::clone(storage.streams()); Blocking::new() .unwrap() .run(async move { - for entry in entries { - streams.append("x402.payments", entry).await.unwrap(); - } + streams.append("x402.payments", legacy_payment()).await.unwrap(); }) .unwrap(); -} - -#[test] -fn migrated_payments_count_against_the_budget_of_a_reopened_ledger() { - let (backend, scoped) = scoped(); - append_v1(&scoped, vec![v1_payment()]); - migrate(&backend, &scoped); let ledger = PaymentLedger::open( - LedgerStorage::from_scoped(&scoped), + LedgerStorage::from_storage(&storage), "session-a", SpendingBudget::default(), ) @@ -91,50 +66,66 @@ fn migrated_payments_count_against_the_budget_of_a_reopened_ledger() { assert_eq!(records[0].amount_atomic, 2500); assert_eq!(records[0].timestamp.timestamp_millis(), V1_PAYMENT_MS); assert_eq!(records[0].thread_id.as_deref(), Some("thread-1")); -} -#[test] -fn a_ledger_refuses_to_open_while_unmigrated_payments_remain() { - let (_backend, scoped) = scoped(); - append_v1(&scoped, vec![v1_payment()]); - - let opened = PaymentLedger::open( - LedgerStorage::from_scoped(&scoped), + let reopened = PaymentLedger::open( + LedgerStorage::from_storage(&storage), "session-a", SpendingBudget::default(), - ); - let Err(error) = opened else { - panic!("legacy payments must block opening"); - }; - assert!(error.contains("unmigrated x402.payments"), "{error}"); + ) + .unwrap(); + assert_eq!(reopened.recent_payments(10), records); } #[test] -fn a_ledger_refuses_to_open_while_legacy_budget_holds_remain() { - let (_backend, scoped) = scoped(); - let documents = Arc::clone(scoped.documents()); +fn opening_the_ledger_migrates_legacy_holds_and_keeps_record_metadata() { + let storage = test_storage(); + let documents = std::sync::Arc::clone(storage.documents()); Blocking::new() .unwrap() .run(async move { documents - .put( + .put_with( "x402_budget", - "holds", - json!({ "holds": {} }), - tinystoragedrivers_core::Precondition::None, + HOLDS_ID, + json!({ + "holds": { + "old-writer:7": { + "amount": 321, + "expires_at_ms": 1_800_000_000_000 + } + } + }), + Precondition::Absent, + WriteOptions::new() + .schema(1) + .created_ms(1_700_000_000_000) + .expires_ms(1_900_000_000_000), ) .await .unwrap(); }) .unwrap(); - let opened = PaymentLedger::open( - LedgerStorage::from_scoped(&scoped), + let _ledger = PaymentLedger::open( + LedgerStorage::from_storage(&storage), "session-a", SpendingBudget::default(), + ) + .unwrap(); + let documents = std::sync::Arc::clone(storage.documents()); + let migrated = Blocking::new() + .unwrap() + .run(async move { documents.get(BUDGETS_COLLECTION, HOLDS_ID).await.unwrap().unwrap() }) + .unwrap(); + assert_eq!( + migrated.doc, + json!({ + "holds": { + "old-writer:7": { "amount": 321, "expires_ms": 1_800_000_000_000_i64 } + } + }) ); - let Err(error) = opened else { - panic!("legacy holds must block opening"); - }; - assert!(error.contains("legacy x402 budget holds"), "{error}"); + assert_eq!(migrated.meta.schema, 2); + assert_eq!(migrated.meta.created_ms, 1_700_000_000_000); + assert_eq!(migrated.meta.expires_ms, Some(1_900_000_000_000)); } From ae13586e52de1b115c4e1b1f7786c68ce8bc0d54 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:43:36 +0300 Subject: [PATCH 11/51] test(ledger): update storage driver imports in tests This change updates imports in ledger tests to use the newer tinystoragedrivers_types module instead of tinystoragedrivers_core. It also adjusts a precondition check in tests to use Precondition::Absent where appropriate. Auto-committed-on: dragonfly --- crates/tinywallet-x402/src/ledger/mod_holds_tests.rs | 10 ++++++---- crates/tinywallet-x402/src/ledger/mod_tests.rs | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs index 667547de..750d12c0 100644 --- a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs @@ -7,11 +7,13 @@ use std::sync::{Arc, Mutex}; use chrono::{DateTime, Duration, TimeZone, Utc}; use serde_json::Value; -use tinystoragedrivers_core::{ - Blocking, Capabilities, CollectionSpec, DocumentStore, Filter, Page, Precondition, Query, - Result, Sort, Version, Versioned, WriteOptions, async_trait, +use tinystoragedrivers_api::{DocumentStore, async_trait}; +use tinystoragedrivers_types::{ + Capabilities, CollectionSpec, Filter, Page, Precondition, Query, Result, Sort, Version, + Versioned, WriteOptions, }; +use super::blocking::Blocking; use super::persist::{HOLD_TTL_MS, HoldsDoc, Persist}; use super::schema::{BUDGETS_COLLECTION, HOLDS_ID}; use super::*; @@ -252,7 +254,7 @@ fn renewal_fails_loudly_when_the_hold_document_is_unreadable() { BUDGETS_COLLECTION, HOLDS_ID, serde_json::json!({"holds": "garbage"}), - Precondition::None, + Precondition::Absent, ) .await .unwrap(); diff --git a/crates/tinywallet-x402/src/ledger/mod_tests.rs b/crates/tinywallet-x402/src/ledger/mod_tests.rs index 6988f4af..856c6d72 100644 --- a/crates/tinywallet-x402/src/ledger/mod_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_tests.rs @@ -8,10 +8,11 @@ use std::sync::atomic::{AtomicU64, Ordering}; use chrono::{DateTime, Duration, TimeZone, Utc}; use super::faulty::{append_raw, faulty_storage}; +use super::blocking::Blocking; use super::persist::{HoldsDoc, Persist, stored_payment}; use super::schema::{BUDGETS_COLLECTION, HOLDS_ID}; use super::*; -use tinystoragedrivers_core::{Blocking, Version}; +use tinystoragedrivers_types::{Precondition, Version}; const SESSION: &str = "session-a"; static NEXT_TEST_RECORD: AtomicU64 = AtomicU64::new(1); @@ -745,7 +746,7 @@ fn corrupt_the_hold_document(storage: &LedgerStorage) { BUDGETS_COLLECTION, HOLDS_ID, serde_json::json!({"holds": 5}), - tinystoragedrivers_core::Precondition::None, + Precondition::Absent, ) .await .unwrap(); From f3822cbe74c3464e005bb7cc782263089cde1439 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:44:33 +0300 Subject: [PATCH 12/51] refactor(ledger): add schema tests module Adds a test module to schema.rs to facilitate testing ledger schema logic. This change also refactors the bus boundary checking scripts to better enforce separation between core logic and storage implementations. Auto-committed-on: dragonfly --- crates/tinywallet-x402/src/ledger/schema.rs | 4 ++ scripts/check-bus-boundaries.py | 69 +++++++++++++-------- scripts/check_bus_boundaries_tests.py | 47 +++++++------- 3 files changed, 71 insertions(+), 49 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 2f7d80a6..21a07b45 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -157,6 +157,10 @@ impl From for super::types::PaymentStatus { } } +#[cfg(test)] +#[path = "schema_tests.rs"] +mod tests; + async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types::Result<()> { let source_len = streams.len(LEGACY_PAYMENTS_STREAM).await?; let mut source = Vec::new(); diff --git a/scripts/check-bus-boundaries.py b/scripts/check-bus-boundaries.py index ca17ad88..7080e4a8 100644 --- a/scripts/check-bus-boundaries.py +++ b/scripts/check-bus-boundaries.py @@ -11,23 +11,25 @@ } REGISTRY = "registry+https://github.com/rust-lang/crates.io-index" -# The `storage` feature (OFF by default) is the one sanctioned way anything -# beyond ALLOWED enters the closure. It brings `tinystoragedrivers-core`, the -# storage ports crate, and with it that crate's own registry dependencies -# (tokio, zstd, ...). The exemption is deliberately narrow: -# * only when `storage` is enabled; the default closure is audited strictly -# and must not contain any of it, -# * only that git crate, pinned to the tinystoragedrivers repository, plus -# registry crates; a path or other git crate (any implementation) is -# still a violation. -STORAGE_FEATURE = "storage" -STORAGE_EXEMPT_GIT = {"tinystoragedrivers-core": "https://github.com/tinyhumansai/tinystoragedrivers"} - # Chain, key and crypto implementations never enter the bus closure, not even -# through the `storage` feature's registry-crate exemption. +# through transitive dependencies. FORBIDDEN_NAMES = {"bitcoin", "k256"} FORBIDDEN_PREFIXES = ("coins-",) +# Storage implementation crates must remain behind the host boundary. The +# names are checked against each library's full normal/build closure. +ENGINE_FORBIDDEN = { + "rusqlite", "libsqlite3-sys", "mongodb", "bson", "aws-sdk-s3", "lapin", + "amq-protocol", "sqlx", "redb", "sled", "rocksdb", + "tinystoragedrivers-document", "tinystoragedrivers-kv", "tinystoragedrivers-blob", + "tinystoragedrivers-queue", "tinystoragedrivers-secrets", "tinystoragedrivers-connect", + "tinystoragedrivers", +} +LIBRARY_CRATES = ( + "tinywallet", "tinywallet-crypto", "tinywallet-x402", "tinywallet-bus", + "tinywallet-web3", "tinywallet-module", +) + def forbidden(name): """Whether `name` is a chain/key implementation the bus must never link.""" @@ -82,8 +84,8 @@ def tree_packages(feature=None): return packages -def audit_tree(packages, storage=False): - """Violations for a `cargo tree` listing; `storage` applies the exemption.""" +def audit_tree(packages): + """Violations for a `cargo tree` listing.""" violations = [] for name, source in packages: if forbidden(name): @@ -91,21 +93,38 @@ def audit_tree(packages, storage=False): continue if name in ALLOWED and not source: continue - if storage and not source: - continue # a registry crate reached through the storage feature - if storage and name in STORAGE_EXEMPT_GIT and source.startswith(STORAGE_EXEMPT_GIT[name]): - continue violations.append(f"tinywallet-bus -> {name} ({source or 'registry'})") return violations +def tree_package_names(output): + """Extract package names from Cargo's versioned `--prefix none` lines.""" + return [line.split()[0] for line in output.splitlines() if line.split()] + + +def engine_tree_packages(crate): + """Return package names in one library's normal/build dependency tree.""" + command = [ + "cargo", "tree", "-p", crate, "--all-features", "-e", "normal,build", + "--prefix", "none", + ] + out = subprocess.run(command, check=True, capture_output=True, text=True).stdout + return tree_package_names(out) + + +def engine_violations(names): + """Find engine packages by normalized Cargo package name.""" + return sorted({name.replace("_", "-") for name in names} & ENGINE_FORBIDDEN) + + if __name__ == "__main__": failures = audit_tree(tree_packages()) if failures: - print("Forbidden contract dependencies (default features):\n" + "\n".join(failures), file=sys.stderr) - sys.exit(1) - failures = audit_tree(tree_packages(STORAGE_FEATURE), storage=True) - if failures: - print("Forbidden contract dependencies (storage feature):\n" + "\n".join(failures), file=sys.stderr) + print("Forbidden contract dependencies:\n" + "\n".join(failures), file=sys.stderr) sys.exit(1) - print("tinywallet-bus: default closure is pure; the storage feature adds only the storage ports crate and registry crates") + for crate in LIBRARY_CRATES: + engines = engine_violations(engine_tree_packages(crate)) + if engines: + print(f"{crate} normal/build tree contains storage engines: {', '.join(engines)}", file=sys.stderr) + sys.exit(1) + print("wallet library normal/build trees contain no storage engine crates") diff --git a/scripts/check_bus_boundaries_tests.py b/scripts/check_bus_boundaries_tests.py index 35b111b1..6dee1441 100644 --- a/scripts/check_bus_boundaries_tests.py +++ b/scripts/check_bus_boundaries_tests.py @@ -27,30 +27,29 @@ def test_local_package_cannot_impersonate_serde(self): self.assertTrue(boundary.audit(metadata("serde", source=None))) -class StorageExemptionTests(unittest.TestCase): - REGISTRY_CRATE = ("zstd", "") - PORTS = ("tinystoragedrivers-core", "https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed") - - def test_default_closure_rejects_the_storage_crates(self): - self.assertEqual(len(boundary.audit_tree([self.PORTS, self.REGISTRY_CRATE])), 2) - - def test_default_closure_accepts_the_allow_list(self): - self.assertEqual(boundary.audit_tree([("serde", ""), ("thiserror", "")]), []) - - def test_storage_feature_accepts_the_ports_crate_and_registry_crates(self): - self.assertEqual(boundary.audit_tree([self.PORTS, self.REGISTRY_CRATE], storage=True), []) - - def test_storage_feature_still_rejects_implementations(self): - path = ("tinywallet-crypto", "/work/crates/tinywallet-crypto") - self.assertEqual(len(boundary.audit_tree([path], storage=True)), 1) - - def test_storage_feature_rejects_forbidden_registry_crates(self): - for name in ("coins-bip32", "coins_bip32", "coins-core", "k256", "bitcoin"): - self.assertEqual(len(boundary.audit_tree([(name, "")], storage=True)), 1, name) - - def test_storage_feature_rejects_a_foreign_git_source(self): - fake = ("tinystoragedrivers-core", "https://example.com/evil") - self.assertEqual(len(boundary.audit_tree([fake], storage=True)), 1) +class EngineTreeTests(unittest.TestCase): + def test_versioned_cargo_tree_lines_are_checked_by_package_name(self): + output = """\ +tinywallet-module v0.24.1 (/work/tinywallet) +rusqlite v0.40.2 (registry+https://github.com/rust-lang/crates.io-index) +tinystoragedrivers-api v2.0.0 (https://github.com/senamakel/tinystoragedrivers) +""" + names = boundary.tree_package_names(output) + self.assertEqual( + boundary.engine_violations(names), + ["rusqlite"], + ) + + def test_storage_api_and_types_are_not_engine_crates(self): + self.assertEqual( + boundary.engine_violations( + ["tinystoragedrivers-api", "tinystoragedrivers-types"] + ), + [], + ) + + def test_underscore_names_are_normalized_before_engine_matching(self): + self.assertEqual(boundary.engine_violations(["libsqlite3_sys"]), ["libsqlite3-sys"]) if __name__ == "__main__": From db1b0efcbb5917d0ff4e647eea605500eff53521 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:45:03 +0300 Subject: [PATCH 13/51] docs: update readme and test comments Updated the README to clarify compiler requirements for features and refined a comment in the E2E test to better explain the failure mode when no storage host is present. Auto-committed-on: dragonfly --- crates/tinywallet-module/tests/lifecycle_e2e.rs | 5 ++--- crates/tinywallet-x402/README.md | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/tinywallet-module/tests/lifecycle_e2e.rs b/crates/tinywallet-module/tests/lifecycle_e2e.rs index 7342dee4..86da654d 100644 --- a/crates/tinywallet-module/tests/lifecycle_e2e.rs +++ b/crates/tinywallet-module/tests/lifecycle_e2e.rs @@ -146,9 +146,8 @@ async fn the_built_module_signs_every_chain_over_a_real_broker() { ) .await .map(|handle: X402ServiceHandle| handle); - // A released artifact has no ledger storage until the host provisions it, - // so x402 must fail closed; the artifact built with `e2e-memory-storage` - // runs the whole payment flow. + // This fixture has no storage host, so x402 must fail closed instead of + // silently switching to process-local state. let x402_service = match x402_configured { Ok(handle) => Some(handle), Err(error) => { diff --git a/crates/tinywallet-x402/README.md b/crates/tinywallet-x402/README.md index c8326dc9..507c40b9 100644 --- a/crates/tinywallet-x402/README.md +++ b/crates/tinywallet-x402/README.md @@ -87,7 +87,8 @@ configuration of its own. - The ledger owns one process-wide handle; hosts choose the budget when they call `ledger::init_global`. - `tools` needs a compiler new enough for `tinytools` (1.88), and `ledger` for - `tinystoragedrivers-core` (1.88). The other features + the stable `tinystoragedrivers-api` / `tinystoragedrivers-types` contracts + (1.88). The other features build on the crate's MSRV, except that `pay` pulls `reqwest`, whose `icu` dependencies need a newer compiler than 1.85 with a current lockfile. - Error strings are user-visible and pinned by tests. From f96532508e0d9160a449ced01ef3f7e2e524c77b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 18:45:30 +0300 Subject: [PATCH 14/51] chore(build): update cached script file This change updates the compiled Python cache file for the bus boundary check script. This is a routine build artifact update. Auto-committed-on: dragonfly --- .../check-bus-boundaries.cpython-314.pyc | Bin 6340 -> 7584 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/scripts/__pycache__/check-bus-boundaries.cpython-314.pyc b/scripts/__pycache__/check-bus-boundaries.cpython-314.pyc index c59347df9964bec518c9997be15c15dfbfad53c2..9d988b7ce7243fed8be5f6086f60b1a7dd31a51f 100644 GIT binary patch delta 2928 zcmZuzT}&I<6}~eb|Be6fU}OF>gaCFII|Q=%rAY|kFA!iSj@zWTjVT+<_sZ?pDst?(xm?ha{-EFs0`_Qebim>~#e(JenJ0S_z zn&UI)o_o(d=X~ef`OC5UXFJ|kb%H5~$u6hvqCwZw1OPTrRfA>0$l@Vyw zC>R8$i&jm7M>TgL!3%PWP@`G}qYtU9U;=6re1h4B(v)f!Eb#6StU#Rt3)CgpfL2A_ zg8kGF5lViHP$P;uT2R#9f{vF>9;Zr-%0;;jojnJt-`7>ETae%ooRfjF?!Lb$S6SG( zUuu~A-o0WA)u}a7Ejeoy8oY*(>Wfx^O&2`A%A(4@S{tn`Sw(2pK#YzyAQT0|QJ)d{3}O3L`Cnv#}F5-r7a8lAB3;RnBD`WVWleQEi#qYeZL4WymN z4()eVKXpcXZ2gtp4Wa@g$w?7=v>bcg?H~eUJd;eR_$2WD2Vb+p4Ce(l%LaopVqDE& zQ3?N6>vw(KZq>CF6{i*gG;Sns%t9QiFHC_1H)%pu8zpE;+Kb>;{mnh=~ScC|EA$!a>e+Om-h0p>OL6H35|8+o~0P^8{dE#fDKZx z_HR$07V-N14pi5&>qPdNJmbZ01i=W(dJulCQHBO>(!n~fQ5iafGW6gvgl@Uv>>dzX zwBNW~#(IPz#2a0b`!VVSL1m27qdg_JGV}sCmZ1;9vp}U#fXem{KqBJ_l`kiTm*VrH z!p~rNp6`$2S-C^u7e%b3WJyf&H-mrjkNszNY-8L0v-g=#vVY8e@{_w0 zcP_16e(&TwZm9YC9Lz@zeccY`6+Dq5&_lVXn-D00 z77P(2FoIDq31-0(vTFaex0$U1`LSB9qxt+4!LL3dbfrB2CT!V$L4*R6UW->s;vpaq zk7*po%N>d~;jGIMZ$tPJ?1Bdf83dAb27}NTUeqZbA~VB;j1Y1eNEnk?0K`U#WQ>q2 zgpg1L3j+3-sLm$s&j#E$K7 zo;my`XkUqR^9tHms8GNJzg+~saAE2AtO6hBP< zqW50!eZ&2$pH~Mq#ci(l@%f1-+{BKpX)@1De)k#It1z%;wf=;qV2Q=%<0&Z?%eH9m zdk^K#umy?@Pz7ctl@_zXvUf-IuFMmZ@d;T{VTHmgs*It(mSduv;j?rnpS@VRdMfyQ za|5Na15CZP2cOV>TCnsq#U#*M>7{}(9bZUE1@pWt&B`!m z#&Tj#0mgzeppa5UD1NvC%g0ON6lp3&Hhx$P>-o0B9lp%&{8&{D(%7FDI#aKKzr zPGsgqNe!3^ESWCFHS2!K2NQUCL6x(veWIn~UETVn`cj$`)!=P$y62Up^Kvqi76a6H zpsrw!#lToBR$$(Rkn63WV1P*I*AMnXGBCL(F=>1_L2~098@VX-3D;x&LSJ~`YU#!z zp9uP0tKUF+3&A%*Mq^RS`VI|{Z=HfkQQ`Xn7Z`B~zA9owWG-P_!SDfv^g=JS7fWyH zkms-l6Qn{FmeTUR)?o|sG;Pe}xwaM8GcTV<+@8hcq4TI}*Jr?$L1N6znX7w(w9vT^U7{KD>DzqUS7fK6rQoyzwuvU$0pQ}4fz3+m?V%U0a~gc5~o76ur&rkEVJ=Wk|k^Jc6JQJ zsv6F1B|vj(t13mk^ink~*B+p%)b>EZ8&clU>ae!$w}we^d~q5%BL7tQ8w2v6?a*xj=dD?uVi4&suW#4QPuYY-BT zs{ z5vg^|@t+>r{)Yn>zfzRC9iL=PqGNdhRTD%lFE=o%*_2g#@#4W-HyuYIT%x}@2Rg?NjvYvI{AF3w5J^`IlVBv5(imM* z(PcU$47kE9F!7cwOb9SQKl6SY+|Cpx54TUmA&Px_;5hx*w;E_;DoZHq3c~Gl%73mk z#1$^NqNoIqbNsC}|FqB+XJXZ#PR}EmR4_8LDe4dZ-p8q8xtM>|NICEhz7h->lV`4& z2JfUDkzRO`z80w@tB$mRZDWo!ss_qBF3H-!Tt(HCDy>B_XqRoHjII#8mx(ElOm0uwAj?AnQtteMo2;Szzvy;P_F7giYPQV6rb@hHN{|*?NKU z?Azvh>*nbxcdWIs$F_3L0Zs>6^CSXF-Q)WJWbLc_C79(`cV-1DM0>+u0^kEXSzO&9 z<*sJvc(k|cuy~=t&I_V!7@CSqkt`w+T|p&-sCt>^qc2}{VSWueiI~S?wY`;nQ<}(3 z7ADV5o;aB;WM0o=&YzUa&L!rlzz6sc;Den_7nAyUI_tUg+q^9BjN&tF>on`;D*Yuo zvG-w1+v@0pK#a}T$wue!Mq+qverq&ycQmsxJySbh*qpwwH7eg5mFY{d{vGY0qw7%| z1mZQJ9djmF-a?@ytK~wWIzr>4^NFR_Sa zf<#sfB1Q|UNgQ~Ye%WuOty;vw%!bMXr;|vecX)c>~E^vx3!_92 zD-{hL!EZAiFB$U>K(8gc*(VZBUJc)m57vfJt$n@*+UQrwXx#0DIruox4&zUUVleh} zUkJt@?V^7rlhw%|gr9sr`fAe5`t#ZNOJP3Du znEpJxzJ2_5&qg?Nb^4(v{J}K-g}_@;6gWwGaRR From d37e3bfd5567e0fdc8b19bc84b89436d4cc011ac Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 19:36:46 +0300 Subject: [PATCH 15/51] chore: files changed Cargo.lock,Cargo.toml,crates/tinywallet-module/Cargo.toml,crates/tinywallet-mod Auto-committed-on: dragonfly --- Cargo.lock | 44 ++-- Cargo.toml | 8 +- crates/tinywallet-module/Cargo.toml | 5 +- crates/tinywallet-module/src/lib_tests.rs | 12 +- .../src/service/x402_lifecycle_tests.rs | 5 +- .../src/service/x402_storage_bus_tests.rs | 17 +- crates/tinywallet-x402/Cargo.toml | 4 +- crates/tinywallet-x402/src/ledger/blocking.rs | 13 +- crates/tinywallet-x402/src/ledger/faulty.rs | 6 +- .../src/ledger/fixtures/README.md | 34 +++ .../src/ledger/fixtures/generate-v0.24.1.rs | 55 ++++ .../src/ledger/fixtures/v0.24.1-payment.json | 16 ++ crates/tinywallet-x402/src/ledger/mod.rs | 2 +- .../src/ledger/mod_holds_tests.rs | 8 +- .../tinywallet-x402/src/ledger/mod_tests.rs | 46 +++- crates/tinywallet-x402/src/ledger/persist.rs | 13 +- crates/tinywallet-x402/src/ledger/schema.rs | 122 ++++++--- .../src/ledger/schema_payment.rs | 4 +- .../src/ledger/schema_tests.rs | 244 +++++++++++++++++- crates/tinywallet-x402/src/tools/mod_tests.rs | 4 +- .../check-bus-boundaries.cpython-314.pyc | Bin 7584 -> 9575 bytes scripts/check-bus-boundaries.py | 39 ++- scripts/check_bus_boundaries_tests.py | 31 +++ 23 files changed, 610 insertions(+), 122 deletions(-) create mode 100644 crates/tinywallet-x402/src/ledger/fixtures/README.md create mode 100644 crates/tinywallet-x402/src/ledger/fixtures/generate-v0.24.1.rs create mode 100644 crates/tinywallet-x402/src/ledger/fixtures/v0.24.1-payment.json diff --git a/Cargo.lock b/Cargo.lock index d546a50a..172ffa88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2044,8 +2044,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-api" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "bytes", @@ -2058,8 +2058,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-blob" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "bytes", @@ -2072,8 +2072,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-bus" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "serde", "serde_json", @@ -2083,8 +2083,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-busproxy" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "bytes", @@ -2101,8 +2101,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-connect" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "rusqlite", "tinystoragedrivers-types", @@ -2111,8 +2111,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-document" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "data-encoding", @@ -2129,8 +2129,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-kv" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "serde", @@ -2141,8 +2141,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-queue" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "data-encoding", @@ -2157,8 +2157,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-secrets" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "tinystoragedrivers-api", @@ -2168,8 +2168,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-testkit" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "async-trait", "bytes", @@ -2189,8 +2189,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-types" -version = "2.0.0" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.0#e14eef3f52a16b09ed91892686cdadd3b39db56d" +version = "2.0.1" +source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" dependencies = [ "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 192c1f2d..2914f8ba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "tinywallet" version = "0.24.1" edition = "2024" -rust-version = "1.85" +rust-version = "1.88" license = "GPL-3.0-only" description = "Agent-friendly multi-chain wallet primitives in Rust." repository = "https://github.com/tinyhumansai/tinywallet" @@ -60,10 +60,10 @@ resolver = "3" # tinytools gitlink tinyagents pins. tinytools = { git = "https://github.com/tinyhumansai/tinytools", rev = "bd60b9b52f1998b4483b9cf107a72d3338e672f8" } # Runtime-neutral contracts shared with the host's stable TSD release. -tinystoragedrivers-types = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } -tinystoragedrivers-api = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } +tinystoragedrivers-types = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } +tinystoragedrivers-api = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } # The module connects to host-owned storage through the TinyBus adapter. -tinystoragedrivers-busproxy = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } +tinystoragedrivers-busproxy = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } [dependencies] # The wire contract. Split out so a host that has moved signing into the diff --git a/crates/tinywallet-module/Cargo.toml b/crates/tinywallet-module/Cargo.toml index 4567fbca..c224db4e 100644 --- a/crates/tinywallet-module/Cargo.toml +++ b/crates/tinywallet-module/Cargo.toml @@ -2,7 +2,7 @@ name = "tinywallet-module" version = "0.24.1" edition = "2024" -rust-version = "1.85" +rust-version = "1.88" license = "GPL-3.0-only" description = "Trusted TinyBus module adapter for TinyWallet." repository = "https://github.com/tinyhumansai/tinywallet" @@ -100,8 +100,7 @@ linked = ["static-link"] workspace = true [dev-dependencies] -tinystoragedrivers-client = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } -tinystoragedrivers-testkit = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } +tinystoragedrivers-testkit = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } # Encodes and decodes the Solana transaction fixtures in native tests. base64 = "0.23" # The native lifecycle fixture stages and hashes the actual cdylib to attest it. diff --git a/crates/tinywallet-module/src/lib_tests.rs b/crates/tinywallet-module/src/lib_tests.rs index 32e484eb..8032aec7 100644 --- a/crates/tinywallet-module/src/lib_tests.rs +++ b/crates/tinywallet-module/src/lib_tests.rs @@ -11,7 +11,15 @@ fn every_stored_item_is_wallet_owned_and_module_scoped() { let collections = storage_collections(); assert!(!collections.is_empty()); for collection in &collections { - assert!(collection.name.starts_with("wallet."), "{}", collection.name); + assert!( + collection.name.starts_with("wallet."), + "{}", + collection.name + ); } - assert!(collections.iter().any(|item| *item == CollectionSpec::new("wallet.budgets"))); + assert!( + collections + .iter() + .any(|item| *item == CollectionSpec::new("wallet.budgets")) + ); } diff --git a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs index e2cae309..0485d410 100644 --- a/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs +++ b/crates/tinywallet-module/src/service/x402_lifecycle_tests.rs @@ -376,13 +376,10 @@ async fn x402_service_lifecycle_records_approval_denial_and_cancellation() { /// In-memory storage whose payments stream refuses every append: the ledger /// opens, holds budget, and then cannot durably record the authorization. fn failing_append_storage() -> tinywallet_x402::ledger::LedgerStorage { - use tinystoragedrivers_api::StreamStore; use tinystoragedrivers_testkit::{Failing, FaultPlan}; use tinystoragedrivers_types::{ErrorKind, Scope}; - let scoped = tinystoragedrivers_testkit::memory_storage( - &Scope::new("x402-fail").unwrap(), - ); + let scoped = tinystoragedrivers_testkit::memory_storage(&Scope::new("x402-fail").unwrap()); let faults = FaultPlan::new(); faults.fail_operation_nth("streams.append", 1, ErrorKind::Backend); tinywallet_x402::ledger::LedgerStorage::new( diff --git a/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs b/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs index ae0d98a9..97593867 100644 --- a/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs +++ b/crates/tinywallet-module/src/service/x402_storage_bus_tests.rs @@ -9,12 +9,11 @@ use super::*; use std::sync::Arc; use tinybus::Connection; -use tinystoragedrivers_busproxy::{PerCallerEndpoint, serve}; -use tinystoragedrivers_client::StorageServer; -use tinystoragedrivers_api::{Storage, StreamStore}; use tinystoragedrivers_api::StorageBackend; -use tinystoragedrivers_types::{ErrorKind, Precondition, Scope}; +use tinystoragedrivers_api::{Storage, StreamStore}; +use tinystoragedrivers_busproxy::{PerCallerEndpoint, StorageServer, serve}; use tinystoragedrivers_testkit::{Failing, FaultPlan}; +use tinystoragedrivers_types::{ErrorKind, Precondition, Scope}; use tinywallet_bus::wire::{X402CloseRequest, X402ConfigureRequest, X402SummaryRequest}; use tinywallet_x402::ledger::{LedgerStorage, PaymentLedger, SpendingBudget}; @@ -35,7 +34,9 @@ async fn fixture() -> Fixture { .await .unwrap(); let backend = tinystoragedrivers_testkit::MemoryBackend::new(); - let host = backend.for_scope(&Scope::new("wallet.module-bus-test").unwrap()).unwrap(); + let host = backend + .for_scope(&Scope::new("wallet.module-bus-test").unwrap()) + .unwrap(); let served_scope = host.clone(); let endpoint = PerCallerEndpoint::new(move |_sender| Some(StorageServer::new(served_scope.clone()))); @@ -378,9 +379,7 @@ fn unreadable_stream_storage() -> LedgerStorage { let storage = tinystoragedrivers_testkit::memory_storage(&scope); let faults = FaultPlan::new(); faults.fail_operation_nth("streams.read_window", 1, ErrorKind::Backend); - let streams: Arc = Arc::new(Failing::with_plan( - Arc::clone(storage.streams()), - faults, - )); + let streams: Arc = + Arc::new(Failing::with_plan(Arc::clone(storage.streams()), faults)); LedgerStorage::new(Arc::clone(storage.documents()), streams) } diff --git a/crates/tinywallet-x402/Cargo.toml b/crates/tinywallet-x402/Cargo.toml index 5a69564f..310b6ee0 100644 --- a/crates/tinywallet-x402/Cargo.toml +++ b/crates/tinywallet-x402/Cargo.toml @@ -2,7 +2,7 @@ name = "tinywallet-x402" version = "0.24.1" edition = "2024" -rust-version = "1.85" +rust-version = "1.88" license = "GPL-3.0-only" description = "The x402 machine-payment protocol for TinyWallet: wire types, EIP-712 and ERC-20 encoding, the payment ledger, the 402 client, and the x402_request agent tool." repository = "https://github.com/tinyhumansai/tinywallet" @@ -93,7 +93,7 @@ tinywallet = { path = "../..", default-features = false, features = ["key", "sol # signer from an EIP-3009 signature in tests. k256 = { version = "0.13", default-features = false, features = ["ecdsa"] } ed25519-dalek = { version = "2", default-features = false, features = ["std"] } -tinystoragedrivers-testkit = { git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.0" } +tinystoragedrivers-testkit = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } [features] default = ["wire"] diff --git a/crates/tinywallet-x402/src/ledger/blocking.rs b/crates/tinywallet-x402/src/ledger/blocking.rs index 2ee7b421..f74b4734 100644 --- a/crates/tinywallet-x402/src/ledger/blocking.rs +++ b/crates/tinywallet-x402/src/ledger/blocking.rs @@ -32,7 +32,9 @@ impl Blocking { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() - .map_err(|error| StorageError::backend("cannot build the ledger storage runtime").with_source(error))?; + .map_err(|error| { + StorageError::backend("cannot build the ledger storage runtime").with_source(error) + })?; let (jobs, mut receiver) = mpsc::unbounded_channel::(); thread::Builder::new() .name("tinywallet-storage".into()) @@ -47,7 +49,9 @@ impl Blocking { while running.join_next().await.is_some() {} }); }) - .map_err(|error| StorageError::backend("cannot start the ledger storage thread").with_source(error))?; + .map_err(|error| { + StorageError::backend("cannot start the ledger storage thread").with_source(error) + })?; Ok(Self { jobs }) } @@ -70,9 +74,8 @@ impl Blocking { .send(job) .map_err(|_| StorageError::backend("the ledger storage bridge has stopped"))?; let receive = || { - wait.recv().map_err(|_| { - StorageError::backend("the ledger storage bridge dropped a call") - }) + wait.recv() + .map_err(|_| StorageError::backend("the ledger storage bridge dropped a call")) }; if tokio::runtime::Handle::try_current().is_ok_and(|handle| { handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread diff --git a/crates/tinywallet-x402/src/ledger/faulty.rs b/crates/tinywallet-x402/src/ledger/faulty.rs index 8d7cfd99..718e85ef 100644 --- a/crates/tinywallet-x402/src/ledger/faulty.rs +++ b/crates/tinywallet-x402/src/ledger/faulty.rs @@ -33,7 +33,10 @@ pub(crate) fn faulty_storage() -> (LedgerStorage, Faults) { faults.append.clone(), )); let streams: Arc = Arc::new(Failing::with_plan(append, faults.read.clone())); - (LedgerStorage::new(Arc::clone(&base.documents), streams), faults) + ( + LedgerStorage::new(Arc::clone(&base.documents), streams), + faults, + ) } /// Fail the next append or read, according to the supplied schedule. @@ -56,4 +59,3 @@ pub(crate) fn append_raw(storage: &LedgerStorage, values: Vec) { }) .unwrap(); } - diff --git a/crates/tinywallet-x402/src/ledger/fixtures/README.md b/crates/tinywallet-x402/src/ledger/fixtures/README.md new file mode 100644 index 00000000..a77d6242 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/fixtures/README.md @@ -0,0 +1,34 @@ +# Previous-release x402 writer fixture + +`v0.24.1-payment.json` is a stream row emitted by the public +`tinywallet_x402::ledger::PaymentLedger::record_payment` method from the +TinyWallet `v0.24.1` release (`c779230db3008934f97a61f8bdd297351ce66685`). +That release's TSD dependency is `v1.0.0` +(`141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d`); its TinyBus submodule is +`1f33d1be1901a2d44bfe674cd7cf294cf3848821`. The generator source below is +compiled and run only in that release checkout. The current regression loads +the resulting stream row into the current testkit backend, opens the real +ledger, checks typed readback, and appends a new current-format row. The +separately seeded `x402_budget` and `x402.payments` cases in `schema_tests.rs` +are domain migration tests, not data claimed to have been emitted by this +release writer. + +From the native TinyWallet repository root, regenerate it with: + +```sh +repo="$PWD" +source="$repo/target/legacy-v0.24.1-source" +mkdir -p "$source/vendor/tinybus" "$source/crates/tinywallet-x402/examples" "$repo/target/compiler-scratch" +git archive c779230db3008934f97a61f8bdd297351ce66685 | tar -x -C "$source" +git -C "$repo/vendor/tinybus" archive 1f33d1be1901a2d44bfe674cd7cf294cf3848821 | tar -x -C "$source/vendor/tinybus" +cp "$repo/crates/tinywallet-x402/src/ledger/fixtures/generate-v0.24.1.rs" "$source/crates/tinywallet-x402/examples/generate_previous_release_fixture.rs" +TMPDIR="$repo/target/compiler-scratch" CARGO_BUILD_JOBS=1 cargo run --locked --manifest-path "$source/Cargo.toml" -p tinywallet-x402 --features ledger --example generate_previous_release_fixture -- "$repo/crates/tinywallet-x402/src/ledger/fixtures/v0.24.1-payment.json" +``` + +The archived `Cargo.lock` pins TSD v1.0.0 to the commit above; the generator +does not use a local TSD checkout. The TinyBus directory is restored at the +release's exact gitlink even though the ledger-only generator does not enable +the module adapter. + +The checked-in output SHA-256 is +`c154765b15e78d7e6e136b8dab6baf3169ab243c2e28bce1f81986f090180e96`. diff --git a/crates/tinywallet-x402/src/ledger/fixtures/generate-v0.24.1.rs b/crates/tinywallet-x402/src/ledger/fixtures/generate-v0.24.1.rs new file mode 100644 index 00000000..5b3b2002 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/fixtures/generate-v0.24.1.rs @@ -0,0 +1,55 @@ +//! Run against tinywallet v0.24.1 with TSD v1.0.0 to generate the checked-in +//! previous-release payment stream row through the public ledger API. + +use chrono::{TimeZone, Utc}; +use tinystoragedrivers_core::{MemoryStorage, Scope, StorageBackend}; +use tinywallet_x402::ledger::{ + LedgerStorage, PaymentLedger, PaymentRecord, PaymentStatus, SpendingBudget, +}; + +fn main() { + let output = std::env::args().nth(1).expect("fixture output path"); + let backend = MemoryStorage::new(); + let scope = Scope::local().module("wallet").expect("valid wallet scope"); + let scoped = backend.for_scope(&scope).expect("open wallet scope"); + let mut ledger = PaymentLedger::open( + LedgerStorage::from_scoped(&scoped), + "release-fixture-session", + SpendingBudget::default(), + ) + .expect("open previous-release public ledger"); + ledger.record_payment(PaymentRecord { + id: "v0241-fixture-payment".into(), + url: "https://merchant.example.test/resource".into(), + asset: "USDC".into(), + amount_atomic: 250_000, + amount_display: "0.250000 USDC".into(), + recipient: "WalletRecipient".into(), + network: "solana:devnet".into(), + tx_signature: Some("release-fixture-signature".into()), + status: PaymentStatus::Settled, + timestamp: Utc.with_ymd_and_hms(2025, 7, 14, 12, 30, 0).unwrap(), + authorization_valid_until: None, + solana_last_valid_block_height: None, + authorization_expired_at: None, + authorization_expiry_observed_height: None, + session_id: "release-fixture-session".into(), + thread_id: Some("release-fixture-thread".into()), + }); + + let streams = scoped.streams().clone(); + let payments = tinystoragedrivers_core::Blocking::new() + .expect("blocking bridge") + .run(async move { + streams + .read_window("wallet.payments", 0, 10) + .await + .expect("read previous-release output") + .into_iter() + .map(|entry| entry.value) + .collect::>() + }) + .expect("read previous-release stream"); + std::fs::write(output, serde_json::to_vec_pretty(&payments).expect("encode fixture")) + .expect("write fixture"); +} diff --git a/crates/tinywallet-x402/src/ledger/fixtures/v0.24.1-payment.json b/crates/tinywallet-x402/src/ledger/fixtures/v0.24.1-payment.json new file mode 100644 index 00000000..e7a77282 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/fixtures/v0.24.1-payment.json @@ -0,0 +1,16 @@ +[ + { + "amount_atomic": 250000, + "amount_display": "0.250000 USDC", + "asset": "USDC", + "id": "v0241-fixture-payment", + "network": "solana:devnet", + "recipient": "WalletRecipient", + "session_id": "release-fixture-session", + "status": "settled", + "thread_id": "release-fixture-thread", + "timestamp_ms": 1752496200000, + "tx_signature": "release-fixture-signature", + "url": "https://merchant.example.test/resource" + } +] \ No newline at end of file diff --git a/crates/tinywallet-x402/src/ledger/mod.rs b/crates/tinywallet-x402/src/ledger/mod.rs index 04020fe4..3033e733 100644 --- a/crates/tinywallet-x402/src/ledger/mod.rs +++ b/crates/tinywallet-x402/src/ledger/mod.rs @@ -58,10 +58,10 @@ //! [`with_ledger`] / [`with_ledger_mut`]. The handle is the only shared state in //! this crate. +mod blocking; #[cfg(test)] pub(crate) mod faulty; mod global; -mod blocking; mod persist; mod reservation; mod schema; diff --git a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs index 750d12c0..0fd46e6e 100644 --- a/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs @@ -249,12 +249,18 @@ fn renewal_fails_loudly_when_the_hold_document_is_unreadable() { Blocking::new() .unwrap() .run(async move { + let version = documents + .get(BUDGETS_COLLECTION, HOLDS_ID) + .await + .unwrap() + .expect("opening the ledger creates the hold document") + .version; documents .put( BUDGETS_COLLECTION, HOLDS_ID, serde_json::json!({"holds": "garbage"}), - Precondition::Absent, + Precondition::Version(version), ) .await .unwrap(); diff --git a/crates/tinywallet-x402/src/ledger/mod_tests.rs b/crates/tinywallet-x402/src/ledger/mod_tests.rs index 856c6d72..7f224dd4 100644 --- a/crates/tinywallet-x402/src/ledger/mod_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_tests.rs @@ -7,10 +7,10 @@ use std::sync::atomic::{AtomicU64, Ordering}; use chrono::{DateTime, Duration, TimeZone, Utc}; -use super::faulty::{append_raw, faulty_storage}; use super::blocking::Blocking; +use super::faulty::{append_raw, faulty_storage}; use super::persist::{HoldsDoc, Persist, stored_payment}; -use super::schema::{BUDGETS_COLLECTION, HOLDS_ID}; +use super::schema::{BUDGETS_COLLECTION, HOLDS_ID, PAYMENTS_STREAM}; use super::*; use tinystoragedrivers_types::{Precondition, Version}; @@ -266,6 +266,39 @@ fn records_survive_a_restart() { assert_eq!(recent[1].amount_atomic, 100_000); } +#[test] +fn previous_release_writer_data_opens_and_accepts_a_new_append() { + let fixture: Vec = + serde_json::from_str(include_str!("fixtures/v0.24.1-payment.json")).unwrap(); + let storage = LedgerStorage::memory(); + let streams = std::sync::Arc::clone(&storage.streams); + Blocking::new() + .unwrap() + .run(async move { + for entry in fixture { + streams.append(PAYMENTS_STREAM, entry).await.unwrap(); + } + }) + .unwrap(); + + let mut ledger = PaymentLedger::open(storage.clone(), "current-session", budget()).unwrap(); + let previous = ledger.payment("v0241-fixture-payment").unwrap(); + assert_eq!(previous.amount_atomic, 250_000); + assert_eq!(previous.status, PaymentStatus::Settled); + assert_eq!( + previous.thread_id.as_deref(), + Some("release-fixture-thread") + ); + + ledger.record_payment(record( + 125_000, + PaymentStatus::Settled, + now(), + "current-session", + )); + assert_eq!(ledger.recent_payments(10).len(), 2); +} + #[test] fn a_record_serialises_camel_case_with_snake_case_status() { let json = serde_json::to_value(record(7, PaymentStatus::Denied, now(), SESSION)).unwrap(); @@ -741,12 +774,19 @@ fn corrupt_the_hold_document(storage: &LedgerStorage) { Blocking::new() .unwrap() .run(async move { + let precondition = documents + .get(BUDGETS_COLLECTION, HOLDS_ID) + .await + .unwrap() + .map_or(Precondition::Absent, |record| { + Precondition::Version(record.version) + }); documents .put( BUDGETS_COLLECTION, HOLDS_ID, serde_json::json!({"holds": 5}), - Precondition::Absent, + precondition, ) .await .unwrap(); diff --git a/crates/tinywallet-x402/src/ledger/persist.rs b/crates/tinywallet-x402/src/ledger/persist.rs index 14e4c591..d49242b0 100644 --- a/crates/tinywallet-x402/src/ledger/persist.rs +++ b/crates/tinywallet-x402/src/ledger/persist.rs @@ -13,11 +13,13 @@ use std::sync::Arc; use chrono::{DateTime, Utc}; use log::debug; use serde::{Deserialize, Serialize}; -use tinystoragedrivers_api::{DocumentStore, StreamStore, Storage}; +use tinystoragedrivers_api::{DocumentStore, Storage, StreamStore}; use tinystoragedrivers_types::{ErrorKind, Precondition, Version, WriteOptions}; -use super::schema::{self, BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, PAYMENTS_STREAM, StoredPayment}; use super::blocking::Blocking; +use super::schema::{ + self, BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, PAYMENTS_STREAM, StoredPayment, +}; use super::types::PaymentRecord; const LOG_PREFIX: &str = "[x402::persist]"; @@ -176,10 +178,9 @@ impl Persist { let persist = Self { storage, bridge }; let documents = Arc::clone(&persist.storage.documents); let streams = Arc::clone(&persist.storage.streams); - persist - .run("migrate x402 storage", async move { - schema::migrate(documents.as_ref(), streams.as_ref()).await - })?; + persist.run("migrate x402 storage", async move { + schema::migrate(documents.as_ref(), streams.as_ref()).await + })?; Ok(persist) } diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 21a07b45..0aa69f71 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -8,23 +8,21 @@ use tinystoragedrivers_types::{ #[path = "schema_payment.rs"] mod payment; -pub use payment::{LegacyPayment, StoredPayment}; pub(super) use payment::StoredPaymentStatus; +pub(crate) use payment::{LegacyPayment, StoredPayment}; -/// The owner prefix for the x402 ledger's storage names. -pub const OWNER: &str = "wallet"; /// Collection containing the single budget-hold document. -pub const BUDGETS_COLLECTION: &str = "wallet.budgets"; +pub(super) const BUDGETS_COLLECTION: &str = "wallet.budgets"; /// Schema version for [`BUDGETS_COLLECTION`]. -pub const BUDGETS_VERSION: u32 = 2; +pub(super) const BUDGETS_VERSION: u32 = 2; /// Identifier of the budget-hold document. -pub const HOLDS_ID: &str = "holds"; +pub(super) const HOLDS_ID: &str = "holds"; /// Append-only payment history stream. -pub const PAYMENTS_STREAM: &str = "wallet.payments"; +pub(super) const PAYMENTS_STREAM: &str = "wallet.payments"; /// Previous budget collection name migrated on first open. -pub const LEGACY_BUDGET_COLLECTION: &str = "x402_budget"; +const LEGACY_BUDGET_COLLECTION: &str = "x402_budget"; /// Previous payment stream name migrated on first open. -pub const LEGACY_PAYMENTS_STREAM: &str = "x402.payments"; +const LEGACY_PAYMENTS_STREAM: &str = "x402.payments"; const MIGRATIONS_COLLECTION: &str = "wallet.migrations"; const MIGRATIONS_ID: &str = "x402"; @@ -36,7 +34,10 @@ const BATCH_SIZE: usize = 512; /// pure collection declarations in the scope it has already bound. #[must_use] pub fn collections() -> Vec { - vec![CollectionSpec::new(BUDGETS_COLLECTION), CollectionSpec::new(MIGRATIONS_COLLECTION)] + vec![ + CollectionSpec::new(BUDGETS_COLLECTION), + CollectionSpec::new(MIGRATIONS_COLLECTION), + ] } /// Apply x402-owned migrations before the ledger reads or writes its history. @@ -61,9 +62,9 @@ pub(super) async fn migrate( migrate_payments(streams).await?; let next = json!({ "version": BUDGETS_VERSION }); - let precondition = state - .map(|record| Precondition::Version(record.version)) - .unwrap_or(Precondition::Absent); + let precondition = state.map_or(Precondition::Absent, |record| { + Precondition::Version(record.version) + }); match documents .put(MIGRATIONS_COLLECTION, MIGRATIONS_ID, next, precondition) .await @@ -76,37 +77,28 @@ pub(super) async fn migrate( .and_then(|record| record.doc.get("version")) .and_then(Value::as_u64) .is_some_and(|version| version >= BUDGETS_VERSION.into()); - if completed { - Ok(()) - } else { - Err(error) - } + if completed { Ok(()) } else { Err(error) } } Err(error) => Err(error), } } async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_types::Result<()> { - let Some(legacy) = documents - .get(LEGACY_BUDGET_COLLECTION, HOLDS_ID) - .await? - else { + let Some(legacy) = documents.get(LEGACY_BUDGET_COLLECTION, HOLDS_ID).await? else { return Ok(()); }; let holds = renamed_holds(&legacy.doc).unwrap_or_default(); let migrated = json!({ "holds": holds.clone() }); - match documents - .get(BUDGETS_COLLECTION, HOLDS_ID) - .await? - { + match documents.get(BUDGETS_COLLECTION, HOLDS_ID).await? { Some(existing) if existing.doc == migrated => Ok(()), Some(_) => Err(StorageError::backend( "wallet budget migration found conflicting target data", )), None => { - let mut options = WriteOptions::new() - .schema(BUDGETS_VERSION) - .created_ms(legacy.meta.created_ms); + // `created_ms` belongs to the host that performs the write, so a + // module migration may preserve application metadata, schema and + // expiry but must let the destination assign creation time. + let mut options = WriteOptions::new().schema(BUDGETS_VERSION); if let Some(expires_ms) = legacy.meta.expires_ms { options = options.expires_ms(expires_ms); } @@ -157,10 +149,6 @@ impl From for super::types::PaymentStatus { } } -#[cfg(test)] -#[path = "schema_tests.rs"] -mod tests; - async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types::Result<()> { let source_len = streams.len(LEGACY_PAYMENTS_STREAM).await?; let mut source = Vec::new(); @@ -170,11 +158,44 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types .read_window(LEGACY_PAYMENTS_STREAM, offset, BATCH_SIZE) .await?; if window.is_empty() { - break; + return Err(StorageError::backend( + "wallet payment migration source ended before its reported length", + )); + } + for (index, entry) in window.iter().enumerate() { + let expected = offset + .checked_add(u64::try_from(index).map_err(|_| { + StorageError::backend("wallet payment migration source offset overflowed") + })?) + .ok_or_else(|| { + StorageError::backend("wallet payment migration source offset overflowed") + })?; + if entry.offset != expected { + return Err(StorageError::backend( + "wallet payment migration source window was incomplete", + )); + } + } + let Some(last) = window.last() else { + return Err(StorageError::backend( + "wallet payment migration source ended before its reported length", + )); + }; + offset = last.offset.checked_add(1).ok_or_else(|| { + StorageError::backend("wallet payment migration source offset overflowed") + })?; + if offset > source_len { + return Err(StorageError::backend( + "wallet payment migration source exceeded its reported length", + )); } - offset = window.last().map_or(offset, |entry| entry.offset.saturating_add(1)); source.extend(window.into_iter().map(|entry| entry.value)); } + if streams.len(LEGACY_PAYMENTS_STREAM).await? != source_len { + return Err(StorageError::backend( + "wallet payment migration source changed while being read", + )); + } let migrated = migrate_payments_stream(LEGACY_PAYMENTS_STREAM, source)? .map_or_else(Vec::new, |(_, entries)| entries); if migrated.is_empty() { @@ -182,14 +203,30 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types } let target_len = streams.len(PAYMENTS_STREAM).await?; - if target_len > migrated.len() as u64 { + let target_len_usize = usize::try_from(target_len).map_err(|_| { + StorageError::backend("wallet payment migration target stream is too large") + })?; + let migrated_len = u64::try_from(migrated.len()).map_err(|_| { + StorageError::backend("wallet payment migration source stream is too large") + })?; + if target_len > migrated_len { return Err(StorageError::backend( "wallet payment migration found unexpected target entries", )); } let existing = streams - .read_window(PAYMENTS_STREAM, 0, target_len as usize) + .read_window(PAYMENTS_STREAM, 0, target_len_usize) .await?; + if u64::try_from(existing.len()).ok() != Some(target_len) + || existing + .iter() + .enumerate() + .any(|(index, entry)| u64::try_from(index).ok() != Some(entry.offset)) + { + return Err(StorageError::backend( + "wallet payment migration target prefix was incomplete", + )); + } if existing .iter() .zip(migrated.iter()) @@ -199,7 +236,7 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types "wallet payment migration found conflicting target data", )); } - let start = target_len as usize; + let start = target_len_usize; if start < migrated.len() { streams .append_batch_if_offset(PAYMENTS_STREAM, target_len, migrated[start..].to_vec()) @@ -237,7 +274,14 @@ fn renamed_holds(body: &Value) -> Option> { .map(|(key, hold)| { let amount = hold.get("amount")?.as_u64()?; let expires_ms = hold.get("expires_at_ms")?.as_i64()?; - Some((key.clone(), json!({ "amount": amount, "expires_ms": expires_ms }))) + Some(( + key.clone(), + json!({ "amount": amount, "expires_ms": expires_ms }), + )) }) .collect() } + +#[cfg(test)] +#[path = "schema_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index c693bd4f..1374d917 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -20,7 +20,7 @@ pub enum StoredPaymentStatus { /// One payment as stored in `wallet.payments`: `snake_case`, every instant an /// epoch-millisecond `*_ms` field, no wrapper. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct StoredPayment { +pub(crate) struct StoredPayment { /// Unique id of the attempt. pub id: String, /// The URL the payment bought access to. @@ -68,7 +68,7 @@ pub struct StoredPayment { /// instants, and the hold metadata beside it. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct LegacyPayment { +pub(crate) struct LegacyPayment { id: String, url: String, asset: String, diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index d3888812..771e8354 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -2,11 +2,17 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use super::*; use serde_json::{Value, json}; -use tinystoragedrivers_types::{Precondition, Scope, WriteOptions}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use async_trait::async_trait; +use tinystoragedrivers_api::StreamStore; +use tinystoragedrivers_types::{ + Capabilities, Precondition, Scope, SealOutcome, StreamEntry, StreamInfo, WriteOptions, +}; -use super::super::{LedgerStorage, PaymentLedger, PaymentStatus, SpendingBudget}; -use super::{BUDGETS_COLLECTION, HOLDS_ID, collections}; use crate::ledger::blocking::Blocking; const V1_PAYMENT_MS: i64 = 1_773_576_000_000; @@ -34,12 +40,160 @@ fn legacy_payment() -> Value { }) } +fn legacy_payments(count: usize) -> Vec { + (0..count) + .map(|index| { + let mut payment = legacy_payment(); + payment["id"] = json!(format!("pay-{index}")); + payment + }) + .collect() +} + +fn append_values( + storage: &tinystoragedrivers_api::Storage, + stream: &'static str, + values: Vec, +) { + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { + streams.append_batch(stream, values).await.unwrap(); + }) + .unwrap(); +} + +fn assert_migration_not_marked(storage: &tinystoragedrivers_api::Storage) { + let documents = Arc::clone(storage.documents()); + assert!( + Blocking::new() + .unwrap() + .run(async move { documents.get("wallet.migrations", "x402").await }) + .unwrap() + .unwrap() + .is_none() + ); +} + +#[derive(Debug, Clone, Copy)] +enum ReadFault { + EmptyAfterFirstPage(&'static str), + GrowthAfterSnapshot(&'static str), + Truncate(&'static str, usize), +} + +#[derive(Debug)] +struct FaultyReads { + inner: Arc, + fault: ReadFault, + len_calls: AtomicUsize, +} + +#[async_trait] +impl StreamStore for FaultyReads { + fn capabilities(&self) -> Capabilities { + self.inner.capabilities() + } + + async fn append(&self, stream: &str, value: Value) -> tinystoragedrivers_types::Result { + self.inner.append(stream, value).await + } + + async fn append_batch( + &self, + stream: &str, + values: Vec, + ) -> tinystoragedrivers_types::Result { + self.inner.append_batch(stream, values).await + } + + async fn append_batch_if_offset( + &self, + stream: &str, + expected_next_offset: u64, + values: Vec, + ) -> tinystoragedrivers_types::Result { + self.inner + .append_batch_if_offset(stream, expected_next_offset, values) + .await + } + + async fn read_window( + &self, + stream: &str, + from: u64, + limit: usize, + ) -> tinystoragedrivers_types::Result> { + match self.fault { + ReadFault::EmptyAfterFirstPage(name) if stream == name && from > 0 => Ok(Vec::new()), + ReadFault::Truncate(name, count) if stream == name => { + let mut entries = self.inner.read_window(stream, from, limit).await?; + entries.truncate(count); + Ok(entries) + } + _ => self.inner.read_window(stream, from, limit).await, + } + } + + async fn len(&self, stream: &str) -> tinystoragedrivers_types::Result { + let len = self.inner.len(stream).await?; + if let ReadFault::GrowthAfterSnapshot(name) = self.fault + && stream == name + && self.len_calls.fetch_add(1, Ordering::Relaxed) > 0 + { + return Ok(len.saturating_add(1)); + } + Ok(len) + } + + async fn truncate_before( + &self, + stream: &str, + offset: u64, + ) -> tinystoragedrivers_types::Result { + self.inner.truncate_before(stream, offset).await + } + + async fn delete_stream(&self, stream: &str) -> tinystoragedrivers_types::Result { + self.inner.delete_stream(stream).await + } + + async fn streams(&self, prefix: &str) -> tinystoragedrivers_types::Result> { + self.inner.streams(prefix).await + } + + async fn seal(&self, stream: &str) -> tinystoragedrivers_types::Result { + self.inner.seal(stream).await + } + + async fn delete_sealed_stream( + &self, + stream: &str, + sealed_ms: i64, + ) -> tinystoragedrivers_types::Result { + self.inner.delete_sealed_stream(stream, sealed_ms).await + } + + async fn info(&self, stream: &str) -> tinystoragedrivers_types::Result> { + self.inner.info(stream).await + } +} + #[test] fn host_declarations_are_pure_wallet_collection_specs() { let declared = collections(); assert_eq!(declared.len(), 2); - assert!(declared.iter().all(|collection| collection.name.starts_with("wallet."))); - assert!(declared.iter().any(|collection| collection.name == BUDGETS_COLLECTION)); + assert!( + declared + .iter() + .all(|collection| collection.name.starts_with("wallet.")) + ); + assert!( + declared + .iter() + .any(|collection| collection.name == BUDGETS_COLLECTION) + ); } #[test] @@ -49,7 +203,10 @@ fn opening_the_ledger_migrates_legacy_payments_before_reading_them() { Blocking::new() .unwrap() .run(async move { - streams.append("x402.payments", legacy_payment()).await.unwrap(); + streams + .append("x402.payments", legacy_payment()) + .await + .unwrap(); }) .unwrap(); @@ -91,7 +248,7 @@ fn opening_the_ledger_migrates_legacy_holds_and_keeps_record_metadata() { "holds": { "old-writer:7": { "amount": 321, - "expires_at_ms": 1_800_000_000_000 + "expires_at_ms": 1_800_000_000_000_i64 } } }), @@ -115,7 +272,13 @@ fn opening_the_ledger_migrates_legacy_holds_and_keeps_record_metadata() { let documents = std::sync::Arc::clone(storage.documents()); let migrated = Blocking::new() .unwrap() - .run(async move { documents.get(BUDGETS_COLLECTION, HOLDS_ID).await.unwrap().unwrap() }) + .run(async move { + documents + .get(BUDGETS_COLLECTION, HOLDS_ID) + .await + .unwrap() + .unwrap() + }) .unwrap(); assert_eq!( migrated.doc, @@ -126,6 +289,69 @@ fn opening_the_ledger_migrates_legacy_holds_and_keeps_record_metadata() { }) ); assert_eq!(migrated.meta.schema, 2); - assert_eq!(migrated.meta.created_ms, 1_700_000_000_000); + assert_ne!(migrated.meta.created_ms, 1_700_000_000_000); assert_eq!(migrated.meta.expires_ms, Some(1_900_000_000_000)); } + +#[test] +fn incomplete_legacy_payment_window_does_not_mark_migration_complete() { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(513)); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault: ReadFault::EmptyAfterFirstPage("x402.payments"), + len_calls: AtomicUsize::new(0), + }); + + let documents = Arc::clone(storage.documents()); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }); + + assert!(matches!(result, Ok(Err(_)))); + assert_migration_not_marked(&storage); +} + +#[test] +fn incomplete_existing_payment_prefix_does_not_mark_migration_complete() { + let storage = test_storage(); + let source = legacy_payments(2); + append_values(&storage, "x402.payments", source.clone()); + let migrated = super::migrate_payments_stream("x402.payments", source) + .unwrap() + .unwrap() + .1; + append_values(&storage, "wallet.payments", migrated); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault: ReadFault::Truncate("wallet.payments", 1), + len_calls: AtomicUsize::new(0), + }); + + let documents = Arc::clone(storage.documents()); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }); + + assert!(matches!(result, Ok(Err(_)))); + assert_migration_not_marked(&storage); +} + +#[test] +fn changed_legacy_payment_source_does_not_mark_migration_complete() { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(1)); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault: ReadFault::GrowthAfterSnapshot("x402.payments"), + len_calls: AtomicUsize::new(0), + }); + let documents = Arc::clone(storage.documents()); + + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }); + + assert!(matches!(result, Ok(Err(_)))); + assert_migration_not_marked(&storage); +} diff --git a/crates/tinywallet-x402/src/tools/mod_tests.rs b/crates/tinywallet-x402/src/tools/mod_tests.rs index 112c15fe..7d311d41 100644 --- a/crates/tinywallet-x402/src/tools/mod_tests.rs +++ b/crates/tinywallet-x402/src/tools/mod_tests.rs @@ -602,9 +602,7 @@ async fn a_signed_payment_is_not_retried_when_pending_state_cannot_be_saved() { let _guard = ledger::TEST_LOCK.lock().await; let (storage, faults) = ledger::faulty::faulty_storage(); ledger::init_global(storage, "tool-test", SpendingBudget::default()).unwrap(); - faults - .append - .store(true, std::sync::atomic::Ordering::SeqCst); + ledger::faulty::fail_next(&faults.append, "streams.append"); let server = TestServer::start(paid_config(evm_requirement())).await; let result = run(&tool(), json!({"url": server.url})).await; diff --git a/scripts/__pycache__/check-bus-boundaries.cpython-314.pyc b/scripts/__pycache__/check-bus-boundaries.cpython-314.pyc index 9d988b7ce7243fed8be5f6086f60b1a7dd31a51f..c157d43ec36804d28cc76c8ba80d3035f83724ef 100644 GIT binary patch delta 2498 zcmZ`)O>7&-6`on{@@KiENSc45=!mi$$&^G|byPTxWfh4WrIxIpZXKpY#S&|BC2d4< z+1ZututvzFKwzgqBx5fr+NO3xWo+VOCfLCEeBMo-ePJWFqNuLcSuCR}w|#GLe8+r2J}4T9y+^ zIias8TH>loRyEj_M-oetQdG*ziF{Gj`MU895j1R!Q3qZIRJ~*~D zcy3#m*c2xI5*zzgqh0a(sWIGi>^pL4iqL|sp4tbyW}&^Lu9XXkvf2T6XL2dlNrxF* zlUFpQtm#rYFE`nuqUq!qs3iSBns!YkkTfz3A4xl*IcYjN)7<3SUpb|qkrb-IIaiiS zvZmQVb|68AiBmIrSSSCD5TS`(f~oxzNF9Cc4X+n(7B_p+Ti%oP7k0WL>(_5ye`k8D zYq0+Pd+yN2@^AEQ_wg^>$NxBe_u8ky?UAW3MyBq0qnq9HwJq<$rgPz*Ke+Ld5wB0* z69V5vdUrWz&<^~@3p?(>`q`UjH}oxc{5Jo&duWeCuINKM^7wu^`GBV4>sa6KhJQ7D zTe%zfb8KvvgRS++^~pCMd-@RBJp7&m)ZB1v)a>hBH@d!x^gf^_cahWMs6YQOfCRtk z-|UumZqqrpKB;fP zqK*zbV1d>oGERnl-ZT94&imFu5lGs$L z(f4A%%0hB^St&o-goL)-&tYogK-f`K?lYV08ROkZU&9rC7IQkNdZRHP8NwV{fwl2k zw3{QVbaf~CBnQto+GzYK`Yv-}g7!kw1`sw`LMc~xg))1-&0Wxax{`;jfAbZh=2Imp zPt+uyOZGG!xm-cb=W;})ig$W?T~}a1B>Lr!$9xnNGdx25AyY2sfr;6d=_kNQqtqE=eOGv(RYqLSrop|MuiP5LT1F6gYrv_2(2aNAk8Et2&{Yjdqu)5%uo zKR#bET2DxGE6_tdE9CMU( z-fWr11VctDkut(L zFH@v*=_&7Di4Suxr2`+`Ne@#iJb9|PBr5nyfq0E;`G AVE_OC diff --git a/scripts/check-bus-boundaries.py b/scripts/check-bus-boundaries.py index 7080e4a8..4e739785 100644 --- a/scripts/check-bus-boundaries.py +++ b/scripts/check-bus-boundaries.py @@ -25,10 +25,7 @@ "tinystoragedrivers-queue", "tinystoragedrivers-secrets", "tinystoragedrivers-connect", "tinystoragedrivers", } -LIBRARY_CRATES = ( - "tinywallet", "tinywallet-crypto", "tinywallet-x402", "tinywallet-bus", - "tinywallet-web3", "tinywallet-module", -) +LIBRARY_KINDS = {"lib", "rlib", "dylib", "cdylib", "staticlib", "proc-macro"} def forbidden(name): @@ -102,6 +99,38 @@ def tree_package_names(output): return [line.split()[0] for line in output.splitlines() if line.split()] +def workspace_library_crates(metadata): + """Enumerate every library package in this workspace, failing closed.""" + members = metadata.get("workspace_members") + packages = metadata.get("packages") + if not isinstance(members, list) or not isinstance(packages, list): + raise ValueError("Cargo metadata omitted workspace members or packages") + member_ids = set(members) + names = sorted({ + package["name"] + for package in packages + if package.get("id") in member_ids + and any( + LIBRARY_KINDS.intersection(target.get("kind", [])) + for target in package.get("targets", []) + ) + }) + if not names: + raise ValueError("Cargo metadata found no workspace library packages") + return names + + +def engine_library_crates(): + """Read workspace library package identities without path assumptions.""" + metadata = subprocess.run( + ["cargo", "metadata", "--locked", "--format-version", "1", "--no-deps"], + check=True, + capture_output=True, + text=True, + ).stdout + return workspace_library_crates(json.loads(metadata)) + + def engine_tree_packages(crate): """Return package names in one library's normal/build dependency tree.""" command = [ @@ -122,7 +151,7 @@ def engine_violations(names): if failures: print("Forbidden contract dependencies:\n" + "\n".join(failures), file=sys.stderr) sys.exit(1) - for crate in LIBRARY_CRATES: + for crate in engine_library_crates(): engines = engine_violations(engine_tree_packages(crate)) if engines: print(f"{crate} normal/build tree contains storage engines: {', '.join(engines)}", file=sys.stderr) diff --git a/scripts/check_bus_boundaries_tests.py b/scripts/check_bus_boundaries_tests.py index 6dee1441..43aefe44 100644 --- a/scripts/check_bus_boundaries_tests.py +++ b/scripts/check_bus_boundaries_tests.py @@ -51,6 +51,37 @@ def test_storage_api_and_types_are_not_engine_crates(self): def test_underscore_names_are_normalized_before_engine_matching(self): self.assertEqual(boundary.engine_violations(["libsqlite3_sys"]), ["libsqlite3-sys"]) + def test_workspace_library_enumeration_covers_every_library_kind(self): + kinds = sorted(boundary.LIBRARY_KINDS) + members = [f"workspace-{index}" for index in range(len(kinds))] + metadata_value = { + "workspace_members": members, + "packages": [ + { + "id": member, + "name": f"library-{index}", + "targets": [{"kind": [kind]}], + } + for index, (member, kind) in enumerate(zip(members, kinds, strict=True)) + ] + + [ + {"id": "binary", "name": "binary-only", "targets": [{"kind": ["bin"]}]}, + {"id": "dependency", "name": "external-library", "targets": [{"kind": ["lib"]}]}, + ], + } + self.assertEqual( + boundary.workspace_library_crates(metadata_value), + [f"library-{index}" for index in range(len(kinds))], + ) + + def test_workspace_library_enumeration_fails_closed_without_members(self): + with self.assertRaises(ValueError): + boundary.workspace_library_crates({"workspace_members": [], "packages": []}) + + def test_workspace_library_enumeration_fails_closed_on_missing_metadata(self): + with self.assertRaises(ValueError): + boundary.workspace_library_crates({"packages": []}) + if __name__ == "__main__": unittest.main() From 5ac52fde01685594002fd52d7411fd46e78d0469 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 19:55:24 +0300 Subject: [PATCH 16/51] fix: satisfy wallet clippy gates --- crates/tinywallet-module/src/lib_tests.rs | 1 - .../src/service/construction/mod.rs | 2 +- crates/tinywallet-module/src/service/mod.rs | 2 +- crates/tinywallet-module/src/service/x402.rs | 11 ++++++----- crates/tinywallet-module/tests/lifecycle_e2e.rs | 13 +++++++++++-- crates/tinywallet-x402/README.md | 6 +++--- crates/tinywallet-x402/src/ledger/reservation.rs | 8 ++++---- crates/tinywallet-x402/src/ledger/schema_tests.rs | 6 ++---- crates/tinywallet-x402/src/protocol/client.rs | 14 +++++++------- src/tx/evm.rs | 2 +- 10 files changed, 36 insertions(+), 29 deletions(-) diff --git a/crates/tinywallet-module/src/lib_tests.rs b/crates/tinywallet-module/src/lib_tests.rs index 8032aec7..70b95832 100644 --- a/crates/tinywallet-module/src/lib_tests.rs +++ b/crates/tinywallet-module/src/lib_tests.rs @@ -9,7 +9,6 @@ use tinystoragedrivers_types::CollectionSpec; #[test] fn every_stored_item_is_wallet_owned_and_module_scoped() { let collections = storage_collections(); - assert!(!collections.is_empty()); for collection in &collections { assert!( collection.name.starts_with("wallet."), diff --git a/crates/tinywallet-module/src/service/construction/mod.rs b/crates/tinywallet-module/src/service/construction/mod.rs index 249fbd85..7263bd43 100644 --- a/crates/tinywallet-module/src/service/construction/mod.rs +++ b/crates/tinywallet-module/src/service/construction/mod.rs @@ -70,7 +70,7 @@ pub(super) fn construct( .strip_prefix("0x") .unwrap_or(data_hex.trim()); if body.len() > MAX_CALLDATA_BYTES * 2 - || body.len() % 2 != 0 + || !body.len().is_multiple_of(2) || !body.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err(invalid("calldata must be bounded byte-aligned hex")); diff --git a/crates/tinywallet-module/src/service/mod.rs b/crates/tinywallet-module/src/service/mod.rs index 62a730f0..1b748493 100644 --- a/crates/tinywallet-module/src/service/mod.rs +++ b/crates/tinywallet-module/src/service/mod.rs @@ -1375,7 +1375,7 @@ fn decode_hex(value: &str) -> Result, Failure> { if body.is_empty() { return Ok(Vec::new()); } - if body.len() % 2 != 0 { + if !body.len().is_multiple_of(2) { return Err(Failure::InvalidInput( "call data has an odd number of hex characters".to_string(), )); diff --git a/crates/tinywallet-module/src/service/x402.rs b/crates/tinywallet-module/src/service/x402.rs index 5cf97407..8ebe296c 100644 --- a/crates/tinywallet-module/src/service/x402.rs +++ b/crates/tinywallet-module/src/service/x402.rs @@ -237,11 +237,11 @@ impl X402Runtime { }) .await?; #[cfg(test)] - if let Some((pause_once, reached, release)) = &self.commit_handoff { - if pause_once.swap(false, std::sync::atomic::Ordering::SeqCst) { - reached.notify_one(); - release.notified().await; - } + if let Some((pause_once, reached, release)) = &self.commit_handoff + && pause_once.swap(false, std::sync::atomic::Ordering::SeqCst) + { + reached.notify_one(); + release.notified().await; } let payment_id = format!("x402_{}", uuid::Uuid::new_v4()); let response = X402PreparePaymentResponse { @@ -586,6 +586,7 @@ fn take_request_secrets( static LEDGER_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); #[cfg(test)] +#[allow(clippy::expect_used)] fn memory_ledger_storage() -> ledger::LedgerStorage { let scope = tinystoragedrivers_types::Scope::new("tinywallet.module-test") .expect("the test scope is valid"); diff --git a/crates/tinywallet-module/tests/lifecycle_e2e.rs b/crates/tinywallet-module/tests/lifecycle_e2e.rs index 86da654d..8a88e568 100644 --- a/crates/tinywallet-module/tests/lifecycle_e2e.rs +++ b/crates/tinywallet-module/tests/lifecycle_e2e.rs @@ -20,7 +20,10 @@ use std::sync::{ atomic::{AtomicBool, Ordering}, }; use std::time::Duration; -use std::{fs, path::PathBuf}; +use std::{ + fs, + path::{Path, PathBuf}, +}; use base64::Engine as _; use base64::engine::general_purpose::STANDARD as BASE64; @@ -991,6 +994,12 @@ async fn the_built_module_signs_every_chain_over_a_real_broker() { } /// Load the built artifact and check its manifest against the interface. +fn module_manifest(artifact: &Path, digest: &str) -> String { + let key = serde_json::to_string(&artifact.file_name().unwrap().to_string_lossy()).unwrap(); + let value = serde_json::to_string(digest).unwrap(); + format!("{key} = {value}\n") +} + async fn admit_module() -> ( Connection, Connection, @@ -1023,7 +1032,7 @@ async fn admit_module() -> ( let digest = hex(&Sha256::digest(fs::read(&staged_artifact).unwrap())); fs::write( staged.path().join("modules.toml"), - format!("{:?} = {:?}\n", artifact.file_name().unwrap(), digest), + module_manifest(&artifact, &digest), ) .unwrap(); diff --git a/crates/tinywallet-x402/README.md b/crates/tinywallet-x402/README.md index 507c40b9..394c6e06 100644 --- a/crates/tinywallet-x402/README.md +++ b/crates/tinywallet-x402/README.md @@ -88,7 +88,7 @@ configuration of its own. call `ledger::init_global`. - `tools` needs a compiler new enough for `tinytools` (1.88), and `ledger` for the stable `tinystoragedrivers-api` / `tinystoragedrivers-types` contracts - (1.88). The other features - build on the crate's MSRV, except that `pay` pulls `reqwest`, whose `icu` - dependencies need a newer compiler than 1.85 with a current lockfile. + (1.88), matching this crate's declared minimum. The other features build on + that MSRV, except that `pay` pulls `reqwest`, whose `icu` dependencies need a + newer compiler than 1.88 with a current lockfile. - Error strings are user-visible and pinned by tests. diff --git a/crates/tinywallet-x402/src/ledger/reservation.rs b/crates/tinywallet-x402/src/ledger/reservation.rs index ab5c42b8..fc384559 100644 --- a/crates/tinywallet-x402/src/ledger/reservation.rs +++ b/crates/tinywallet-x402/src/ledger/reservation.rs @@ -30,10 +30,10 @@ impl Reservation { /// Record the payment's outcome and end the hold in one critical section. pub fn commit(mut self, record: PaymentRecord) { - if let Some(id) = self.id.take() { - if with_ledger_mut(|l| l.commit_reservation(id, record)).is_err() { - debug!("{LOG_PREFIX} commit skipped: ledger gone"); - } + if let Some(id) = self.id.take() + && with_ledger_mut(|l| l.commit_reservation(id, record)).is_err() + { + debug!("{LOG_PREFIX} commit skipped: ledger gone"); } } diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 771e8354..d650d980 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -3,16 +3,14 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use super::*; -use serde_json::{Value, json}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use async_trait::async_trait; use tinystoragedrivers_api::StreamStore; -use tinystoragedrivers_types::{ - Capabilities, Precondition, Scope, SealOutcome, StreamEntry, StreamInfo, WriteOptions, -}; +use tinystoragedrivers_types::{Capabilities, Scope, SealOutcome, StreamEntry, StreamInfo}; +use super::super::{LedgerStorage, PaymentLedger, PaymentStatus, SpendingBudget}; use crate::ledger::blocking::Blocking; const V1_PAYMENT_MS: i64 = 1_773_576_000_000; diff --git a/crates/tinywallet-x402/src/protocol/client.rs b/crates/tinywallet-x402/src/protocol/client.rs index a6ddea78..1f3bfe91 100644 --- a/crates/tinywallet-x402/src/protocol/client.rs +++ b/crates/tinywallet-x402/src/protocol/client.rs @@ -91,13 +91,13 @@ impl X402Client { let requirement = &challenge.accepts[index]; let amount = parse_amount(requirement)?; - if let Some(cap) = max_amount { - if amount > cap { - return Err(X402Error::AmountExceedsCap { - requested: amount, - cap, - }); - } + if let Some(cap) = max_amount + && amount > cap + { + return Err(X402Error::AmountExceedsCap { + requested: amount, + cap, + }); } debug!( diff --git a/src/tx/evm.rs b/src/tx/evm.rs index 52c51ff1..e451f963 100644 --- a/src/tx/evm.rs +++ b/src/tx/evm.rs @@ -185,7 +185,7 @@ impl LegacyTransaction { /// Decode an even-length hex string into bytes. fn decode_hex(body: &str) -> Option> { - if body.len() % 2 != 0 { + if !body.len().is_multiple_of(2) { return None; } (0..body.len()) From 6d07a993d99d9e3639a5ccd755c79ddf895ead61 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 20:34:24 +0300 Subject: [PATCH 17/51] feat(bus): expose storage collection declarations from the bus contract Hosts can now read the module's collection declarations from the bus contract without linking the x402 implementation or its migration behavior. The declarations moved out of the ledger so the host can ensure collections in its already-bound scope, and the RFC 3339 parser now validates month lengths, leap years, and offset bounds. Auto-committed-on: dragonfly --- .gitignore | 2 + Cargo.lock | 1 + crates/tinywallet-bus/Cargo.toml | 5 +- crates/tinywallet-bus/src/lib.rs | 2 + crates/tinywallet-bus/src/lib_tests.rs | 10 + crates/tinywallet-bus/src/storage.rs | 15 + crates/tinywallet-module/src/lib.rs | 6 +- crates/tinywallet-web3/Cargo.toml | 2 +- .../src/crypto/chains/solana/mod.rs | 2 +- crates/tinywallet-x402/src/ledger/blocking.rs | 20 +- .../src/ledger/blocking_tests.rs | 65 ++ crates/tinywallet-x402/src/ledger/schema.rs | 20 +- .../src/ledger/schema_payment.rs | 26 +- .../src/ledger/schema_payment_tests.rs | 90 +++ .../src/ledger/schema_tests.rs | 752 +++++++++++++++++- deny.toml | 1 + .../check-bus-boundaries.cpython-314.pyc | Bin 9575 -> 0 bytes scripts/check-bus-boundaries.py | 15 +- scripts/check_bus_boundaries_tests.py | 20 + 19 files changed, 1029 insertions(+), 25 deletions(-) create mode 100644 crates/tinywallet-bus/src/storage.rs create mode 100644 crates/tinywallet-x402/src/ledger/blocking_tests.rs create mode 100644 crates/tinywallet-x402/src/ledger/schema_payment_tests.rs delete mode 100644 scripts/__pycache__/check-bus-boundaries.cpython-314.pyc diff --git a/.gitignore b/.gitignore index c880a65b..01087018 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ /target/ **/*.rs.bk *.pdb +__pycache__/ +*.py[cod] # Coverage output /coverage/ diff --git a/Cargo.lock b/Cargo.lock index 172ffa88..78fc3f1b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2265,6 +2265,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.20", + "tinystoragedrivers-types", ] [[package]] diff --git a/crates/tinywallet-bus/Cargo.toml b/crates/tinywallet-bus/Cargo.toml index 4824d8a0..83a21918 100644 --- a/crates/tinywallet-bus/Cargo.toml +++ b/crates/tinywallet-bus/Cargo.toml @@ -2,7 +2,7 @@ name = "tinywallet-bus" version = "0.24.1" edition = "2024" -rust-version = "1.85" +rust-version = "1.88" license = "GPL-3.0-only" description = "The TinyBus wire contract for TinyWallet: member names, payload types, and contract version." repository = "https://github.com/tinyhumansai/tinywallet" @@ -20,6 +20,9 @@ serde = { version = "1", optional = true } serde_json = { version = "1", optional = true } # Error vocabulary derives; no crypto execution crosses this dependency. thiserror = "2" +# Hosts read the module's collection declarations from this contract without +# linking the implementation or its migration behavior. +tinystoragedrivers-types = { workspace = true } [dev-dependencies] serde = { version = "1", features = ["derive"] } diff --git a/crates/tinywallet-bus/src/lib.rs b/crates/tinywallet-bus/src/lib.rs index 73a4959e..281fcafb 100644 --- a/crates/tinywallet-bus/src/lib.rs +++ b/crates/tinywallet-bus/src/lib.rs @@ -23,6 +23,7 @@ pub mod mnemonic; pub mod names; +pub mod storage; #[cfg(feature = "wire")] pub mod tools; pub mod version; @@ -34,6 +35,7 @@ mod error; pub mod transfer; pub use chain::Chain; pub use error::{Error, Result}; +pub use storage::collections as storage_collections; pub use transfer::TronTransfer; pub use mnemonic::{ diff --git a/crates/tinywallet-bus/src/lib_tests.rs b/crates/tinywallet-bus/src/lib_tests.rs index 99fb8a2c..bd939552 100644 --- a/crates/tinywallet-bus/src/lib_tests.rs +++ b/crates/tinywallet-bus/src/lib_tests.rs @@ -185,6 +185,16 @@ fn the_method_list_is_sorted_complete_and_free_of_duplicates() { } } +#[test] +fn storage_declarations_are_available_from_the_bus_contract() { + let names = super::storage_collections() + .into_iter() + .map(|collection| collection.name) + .collect::>(); + + assert_eq!(names, ["wallet.budgets", "wallet.migrations"]); +} + #[cfg(feature = "wire")] #[test] fn x402_history_and_budget_wire_vocabulary_preserves_rpc_record_shape() { diff --git a/crates/tinywallet-bus/src/storage.rs b/crates/tinywallet-bus/src/storage.rs new file mode 100644 index 00000000..97b41411 --- /dev/null +++ b/crates/tinywallet-bus/src/storage.rs @@ -0,0 +1,15 @@ +//! Pure storage declarations the host can ensure before starting the module. + +use tinystoragedrivers_types::CollectionSpec; + +/// Collection names used by the wallet's persistent module storage. +/// +/// Migration behavior remains in the x402 implementation. The host only needs +/// these declarations to ensure the collections in its already-bound scope. +#[must_use] +pub fn collections() -> Vec { + vec![ + CollectionSpec::new("wallet.budgets"), + CollectionSpec::new("wallet.migrations"), + ] +} diff --git a/crates/tinywallet-module/src/lib.rs b/crates/tinywallet-module/src/lib.rs index b267a783..3fbce8a9 100644 --- a/crates/tinywallet-module/src/lib.rs +++ b/crates/tinywallet-module/src/lib.rs @@ -19,9 +19,9 @@ mod service; #[cfg(feature = "static-link")] pub use service::linked_module; pub use service::{BUS_NAME, HOST_INTERFACE, HOST_OBJECT_PATH, OBJECT_PATH}; -/// What the module stores (owner `wallet`). A host composes it into its schema -/// registry's host-side collection declarations. -pub use tinywallet_x402::ledger::collections as storage_collections; +/// Pure collection declarations for the host; migration behavior stays in the +/// x402 implementation. +pub use tinywallet_bus::storage::collections as storage_collections; #[cfg(test)] #[path = "lib_tests.rs"] diff --git a/crates/tinywallet-web3/Cargo.toml b/crates/tinywallet-web3/Cargo.toml index 794aade8..999cac6e 100644 --- a/crates/tinywallet-web3/Cargo.toml +++ b/crates/tinywallet-web3/Cargo.toml @@ -2,7 +2,7 @@ name = "tinywallet-web3" version = "0.24.1" edition = "2024" -rust-version = "1.85" +rust-version = "1.88" license = "GPL-3.0-only" description = "Wallet, swap, bridge and dapp flows for TinyWallet, behind host seams." repository = "https://github.com/tinyhumansai/tinywallet" diff --git a/crates/tinywallet-web3/src/crypto/chains/solana/mod.rs b/crates/tinywallet-web3/src/crypto/chains/solana/mod.rs index 9546d3b0..fb26e679 100644 --- a/crates/tinywallet-web3/src/crypto/chains/solana/mod.rs +++ b/crates/tinywallet-web3/src/crypto/chains/solana/mod.rs @@ -87,7 +87,7 @@ async fn signer_pubkey(engine: &WalletEngine) -> Result<[u8; 32], String> { /// Decode lowercase hex. fn hex_to_bytes(value: &str) -> Result, String> { - if value.len() % 2 != 0 { + if !value.len().is_multiple_of(2) { return Err("odd-length hex from the wallet module".to_string()); } (0..value.len() / 2) diff --git a/crates/tinywallet-x402/src/ledger/blocking.rs b/crates/tinywallet-x402/src/ledger/blocking.rs index f74b4734..d823b594 100644 --- a/crates/tinywallet-x402/src/ledger/blocking.rs +++ b/crates/tinywallet-x402/src/ledger/blocking.rs @@ -32,9 +32,7 @@ impl Blocking { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() - .map_err(|error| { - StorageError::backend("cannot build the ledger storage runtime").with_source(error) - })?; + .map_err(runtime_start_error)?; let (jobs, mut receiver) = mpsc::unbounded_channel::(); thread::Builder::new() .name("tinywallet-storage".into()) @@ -49,9 +47,7 @@ impl Blocking { while running.join_next().await.is_some() {} }); }) - .map_err(|error| { - StorageError::backend("cannot start the ledger storage thread").with_source(error) - })?; + .map_err(thread_start_error)?; Ok(Self { jobs }) } @@ -86,3 +82,15 @@ impl Blocking { } } } + +fn runtime_start_error(error: std::io::Error) -> StorageError { + StorageError::backend("cannot build the ledger storage runtime").with_source(error) +} + +fn thread_start_error(error: std::io::Error) -> StorageError { + StorageError::backend("cannot start the ledger storage thread").with_source(error) +} + +#[cfg(test)] +#[path = "blocking_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/ledger/blocking_tests.rs b/crates/tinywallet-x402/src/ledger/blocking_tests.rs new file mode 100644 index 00000000..e3248e63 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/blocking_tests.rs @@ -0,0 +1,65 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +#[test] +fn bridge_debug_and_startup_errors_keep_their_context() { + let bridge = Blocking::new().unwrap(); + assert_eq!(format!("{bridge:?}"), "Blocking { .. }"); + + let source = std::io::Error::other("runtime cause"); + assert!( + runtime_start_error(source) + .to_string() + .contains("cannot build") + ); + let source = std::io::Error::other("thread cause"); + assert!( + thread_start_error(source) + .to_string() + .contains("cannot start") + ); +} + +#[test] +fn bridge_reports_a_stopped_worker_and_reentrant_calls() { + let (jobs, receiver) = mpsc::unbounded_channel(); + drop(receiver); + let stopped = Blocking { jobs }; + let error = stopped.run(async { 1 }).unwrap_err(); + assert!(error.to_string().contains("bridge has stopped")); + + let bridge = Blocking::new().unwrap(); + let nested = bridge.clone(); + let result = bridge + .run(async move { nested.run(async { 7 }).map_err(|error| error.to_string()) }) + .unwrap(); + assert!( + result + .unwrap_err() + .contains("called back into its blocking bridge") + ); +} + +#[test] +fn bridge_runs_from_current_and_multithread_tokio_contexts() { + let bridge = Blocking::new().unwrap(); + let current = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + assert_eq!( + current.block_on(async { bridge.run(async { 3 }).unwrap() }), + 3 + ); + + let multi = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .unwrap(); + assert_eq!( + multi.block_on(async { bridge.run(async { 5 }).unwrap() }), + 5 + ); +} diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 0aa69f71..515e237c 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -90,7 +90,9 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty let holds = renamed_holds(&legacy.doc).unwrap_or_default(); let migrated = json!({ "holds": holds.clone() }); match documents.get(BUDGETS_COLLECTION, HOLDS_ID).await? { - Some(existing) if existing.doc == migrated => Ok(()), + Some(existing) if budget_target_matches(&existing, &migrated, legacy.meta.expires_ms) => { + Ok(()) + } Some(_) => Err(StorageError::backend( "wallet budget migration found conflicting target data", )), @@ -106,7 +108,7 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty .put_with( BUDGETS_COLLECTION, HOLDS_ID, - migrated, + migrated.clone(), Precondition::Absent, options, ) @@ -115,7 +117,9 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty Ok(_) => Ok(()), Err(error) if error.kind() == ErrorKind::Conflict => { let latest = documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?; - if latest.is_some_and(|record| record.doc == json!({ "holds": holds })) { + if latest.is_some_and(|record| { + budget_target_matches(&record, &migrated, legacy.meta.expires_ms) + }) { Ok(()) } else { Err(error) @@ -127,6 +131,16 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty } } +fn budget_target_matches( + record: &tinystoragedrivers_types::Versioned, + migrated: &Value, + expires_ms: Option, +) -> bool { + record.doc == *migrated + && record.meta.schema == BUDGETS_VERSION + && record.meta.expires_ms == expires_ms +} + impl From for StoredPaymentStatus { fn from(status: super::types::PaymentStatus) -> Self { match status { diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index 1374d917..741f740f 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -162,12 +162,15 @@ pub(super) fn parse_rfc3339_ms(text: &str) -> Option { } let (year, month, day) = (digits(0, 4)?, digits(5, 2)?, digits(8, 2)?); let (hour, minute, second) = (digits(11, 2)?, digits(14, 2)?, digits(17, 2)?); - if !(1..=12).contains(&month) - || !(1..=31).contains(&day) - || hour > 23 - || minute > 59 - || second > 60 - { + let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if leap_year => 29, + 2 => 28, + _ => return None, + }; + if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 60 { return None; } let mut at = 19; @@ -189,7 +192,12 @@ pub(super) fn parse_rfc3339_ms(text: &str) -> Option { let offset_minutes = match bytes.get(at)? { b'Z' | b'z' if at + 1 == bytes.len() => 0, sign @ (b'+' | b'-') if at + 6 == bytes.len() && separator(at + 3, b":") => { - let minutes = digits(at + 1, 2)? * 60 + digits(at + 4, 2)?; + let hours = digits(at + 1, 2)?; + let minute_part = digits(at + 4, 2)?; + if hours > 23 || minute_part > 59 { + return None; + } + let minutes = hours * 60 + minute_part; if *sign == b'-' { -minutes } else { minutes } } _ => return None, @@ -204,3 +212,7 @@ pub(super) fn parse_rfc3339_ms(text: &str) -> Option { let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; Some(seconds * 1_000 + millis) } + +#[cfg(test)] +#[path = "schema_payment_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs new file mode 100644 index 00000000..6c4f60b4 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -0,0 +1,90 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +#[test] +fn rfc3339_milliseconds_handle_offsets_and_truncate_submillisecond_precision() { + assert_eq!( + parse_rfc3339_ms("2026-03-15T12:00:00.250Z"), + Some(1_773_576_000_250) + ); + assert_eq!( + parse_rfc3339_ms("2026-03-15t15:00:00.250000+03:00"), + Some(1_773_576_000_250) + ); + assert_eq!( + parse_rfc3339_ms("2026-03-15 12:00:00.9z"), + Some(1_773_576_000_900) + ); + assert_eq!( + parse_rfc3339_ms("2026-03-15T12:00:60Z"), + Some(1_773_576_060_000) + ); + assert!(parse_rfc3339_ms("2024-02-29T00:00:00Z").is_some()); +} + +#[test] +fn rfc3339_parser_rejects_malformed_fields_and_offsets() { + for value in [ + "2026-13-15T12:00:00Z", + "2026-03-00T12:00:00Z", + "2026-02-29T12:00:00Z", + "2024-02-31T12:00:00Z", + "2026-03-15T24:00:00Z", + "2026-03-15T12:60:00Z", + "2026-03-15T12:00:61Z", + "2026-03-15T12:00:00.", + "2026-03-15T12:00:00+01:0x", + "2026-03-15T12:00:00+24:00", + "2026-03-15T12:00:00+01:60", + "2026-03-15T12:00:00+01:00tail", + "2026/03/15T12:00:00Z", + ] { + assert_eq!(parse_rfc3339_ms(value), None, "{value}"); + } +} + +#[test] +fn legacy_payment_deserialization_defaults_absent_optional_fields_and_rejects_bad_instants() { + let base = serde_json::json!({ + "id":"id", "url":"https://example.test", "asset":"USD", "amountAtomic":1, + "amountDisplay":"1", "recipient":"r", "network":"n", "status":"pending", + "timestamp":"2026-03-15T12:00:00Z", "sessionId":"s" + }); + let legacy: LegacyPayment = serde_json::from_value(base.clone()).unwrap(); + let stored = StoredPayment::from(legacy); + assert_eq!(stored.timestamp_ms, 1_773_576_000_000); + assert_eq!(stored.tx_signature, None); + assert_eq!(stored.authorization_valid_until_ms, None); + assert_eq!(stored.solana_last_valid_block_height, None); + assert_eq!(stored.authorization_expired_at_ms, None); + assert_eq!(stored.thread_id, None); + let mut with_optionals = serde_json::json!({ + "id":"id", "url":"https://example.test", "asset":"USD", "amountAtomic":1, + "amountDisplay":"1", "recipient":"r", "network":"n", "status":"pending", + "timestamp":"2026-03-15T12:00:00Z", "sessionId":"s", + "authorizationValidUntil":"2026-03-15T12:00:01.9999Z", + "authorizationExpiredAt":"2026-03-15T12:00:02Z", + "solanaLastValidBlockHeight":42, "authorizationExpiryObservedHeight":43, + "threadId":"thread", "committed_hold":"hold", "txSignature":"sig" + }); + let parsed: LegacyPayment = serde_json::from_value(with_optionals.clone()).unwrap(); + let parsed = StoredPayment::from(parsed); + assert_eq!(parsed.authorization_valid_until_ms, Some(1_773_576_001_999)); + assert_eq!(parsed.authorization_expired_at_ms, Some(1_773_576_002_000)); + assert_eq!(parsed.solana_last_valid_block_height, Some(42)); + assert_eq!(parsed.authorization_expiry_observed_height, Some(43)); + assert_eq!(parsed.thread_id.as_deref(), Some("thread")); + assert_eq!(parsed.committed_hold.as_deref(), Some("hold")); + assert_eq!(parsed.tx_signature.as_deref(), Some("sig")); + with_optionals["authorizationValidUntil"] = serde_json::json!("tomorrow"); + assert!(serde_json::from_value::(with_optionals).is_err()); + assert!( + serde_json::from_value::({ + let mut bad = base; + bad["timestamp"] = serde_json::json!("yesterday"); + bad + }) + .is_err() + ); +} diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index d650d980..22beeadc 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -7,14 +7,150 @@ use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use async_trait::async_trait; -use tinystoragedrivers_api::StreamStore; -use tinystoragedrivers_types::{Capabilities, Scope, SealOutcome, StreamEntry, StreamInfo}; +use tinystoragedrivers_api::{DocumentStore, StreamStore}; +use tinystoragedrivers_types::{ + Capabilities, CollectionSpec, ErrorKind, Filter, Page, Precondition, Query, Scope, SealOutcome, + Sort, StreamEntry, StreamInfo, Version, Versioned, WriteOptions, +}; use super::super::{LedgerStorage, PaymentLedger, PaymentStatus, SpendingBudget}; use crate::ledger::blocking::Blocking; const V1_PAYMENT_MS: i64 = 1_773_576_000_000; +#[derive(Debug, Clone, Copy)] +enum RaceAction { + CompleteMarker, + MatchingBudget, + WrongBudgetSchema, + WrongBudgetExpiry, +} + +#[derive(Debug)] +struct RacingDocuments { + inner: Arc, + action: RaceAction, +} + +#[async_trait] +impl DocumentStore for RacingDocuments { + fn capabilities(&self) -> Capabilities { + self.inner.capabilities() + } + + async fn ensure_collection( + &self, + spec: &CollectionSpec, + ) -> tinystoragedrivers_types::Result<()> { + self.inner.ensure_collection(spec).await + } + + async fn get( + &self, + collection: &str, + id: &str, + ) -> tinystoragedrivers_types::Result>> { + self.inner.get(collection, id).await + } + + async fn put( + &self, + collection: &str, + id: &str, + doc: Value, + precondition: Precondition, + ) -> tinystoragedrivers_types::Result { + let version = self.inner.put(collection, id, doc, precondition).await?; + if matches!(self.action, RaceAction::CompleteMarker) + && collection == "wallet.migrations" + && id == "x402" + { + return Err(tinystoragedrivers_types::StorageError::new( + ErrorKind::Conflict, + "simulated competing migration completion", + )); + } + Ok(version) + } + + async fn delete( + &self, + collection: &str, + id: &str, + precondition: Precondition, + ) -> tinystoragedrivers_types::Result { + self.inner.delete(collection, id, precondition).await + } + + async fn query( + &self, + collection: &str, + query: &Query, + ) -> tinystoragedrivers_types::Result>> { + self.inner.query(collection, query).await + } + + async fn count( + &self, + collection: &str, + filter: &Filter, + ) -> tinystoragedrivers_types::Result { + self.inner.count(collection, filter).await + } + + async fn delete_where( + &self, + collection: &str, + filter: &Filter, + ) -> tinystoragedrivers_types::Result { + self.inner.delete_where(collection, filter).await + } + + async fn claim( + &self, + collection: &str, + filter: &Filter, + sort: &[Sort], + patch: &Value, + ) -> tinystoragedrivers_types::Result>> { + self.inner.claim(collection, filter, sort, patch).await + } + + async fn drop_collection(&self, collection: &str) -> tinystoragedrivers_types::Result<()> { + self.inner.drop_collection(collection).await + } + + async fn put_with( + &self, + collection: &str, + id: &str, + doc: Value, + precondition: Precondition, + mut options: WriteOptions, + ) -> tinystoragedrivers_types::Result { + let action = self.action; + if collection == BUDGETS_COLLECTION && id == HOLDS_ID { + match action { + RaceAction::WrongBudgetSchema => options = options.schema(1), + RaceAction::WrongBudgetExpiry => options = options.expires_ms(1_900_000_000_001), + RaceAction::CompleteMarker | RaceAction::MatchingBudget => {} + } + self.inner + .put_with(collection, id, doc.clone(), precondition, options) + .await?; + if !matches!(action, RaceAction::CompleteMarker) { + return Err(tinystoragedrivers_types::StorageError::new( + ErrorKind::Conflict, + "simulated competing budget migration", + )); + } + } + self.inner + .put_with(collection, id, doc, precondition, options) + .await + } +} + fn test_storage() -> tinystoragedrivers_api::Storage { tinystoragedrivers_testkit::memory_storage(&Scope::new("wallet.migration-test").unwrap()) } @@ -79,6 +215,10 @@ enum ReadFault { EmptyAfterFirstPage(&'static str), GrowthAfterSnapshot(&'static str), Truncate(&'static str, usize), + WrongOffset(&'static str), + ReadError(&'static str), + Overshoot(&'static str), + AppendError(&'static str), } #[derive(Debug)] @@ -112,6 +252,11 @@ impl StreamStore for FaultyReads { expected_next_offset: u64, values: Vec, ) -> tinystoragedrivers_types::Result { + if matches!(self.fault, ReadFault::AppendError(name) if stream == name) { + return Err(tinystoragedrivers_types::StorageError::backend( + "injected stream append failure", + )); + } self.inner .append_batch_if_offset(stream, expected_next_offset, values) .await @@ -124,12 +269,32 @@ impl StreamStore for FaultyReads { limit: usize, ) -> tinystoragedrivers_types::Result> { match self.fault { + ReadFault::ReadError(name) if stream == name => Err( + tinystoragedrivers_types::StorageError::backend("injected stream read failure"), + ), ReadFault::EmptyAfterFirstPage(name) if stream == name && from > 0 => Ok(Vec::new()), ReadFault::Truncate(name, count) if stream == name => { let mut entries = self.inner.read_window(stream, from, limit).await?; entries.truncate(count); Ok(entries) } + ReadFault::WrongOffset(name) if stream == name => { + let mut entries = self.inner.read_window(stream, from, limit).await?; + if let Some(first) = entries.first_mut() { + first.offset = first.offset.saturating_add(1); + } + Ok(entries) + } + ReadFault::Overshoot(name) if stream == name => { + let mut entries = self.inner.read_window(stream, from, limit).await?; + if let Some(last) = entries.last().cloned() { + entries.push(StreamEntry { + offset: last.offset.saturating_add(1), + value: last.value, + }); + } + Ok(entries) + } _ => self.inner.read_window(stream, from, limit).await, } } @@ -291,6 +456,491 @@ fn opening_the_ledger_migrates_legacy_holds_and_keeps_record_metadata() { assert_eq!(migrated.meta.expires_ms, Some(1_900_000_000_000)); } +#[test] +fn budget_migration_rejects_matching_target_bodies_with_different_metadata() { + for (schema, expires_ms) in [ + (1, Some(1_900_000_000_000)), + (2, Some(1_900_000_000_001)), + (2, None), + ] { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + let legacy = json!({ "holds": { "old": { + "amount": 12, + "expires_at_ms": 1_800_000_000_000_i64 + }}}); + documents + .put_with( + "x402_budget", + HOLDS_ID, + legacy, + Precondition::Absent, + WriteOptions::new().schema(1).expires_ms(1_900_000_000_000), + ) + .await?; + let target = json!({ "holds": { "old": { + "amount": 12, + "expires_ms": 1_800_000_000_000_i64 + }}}); + let mut options = WriteOptions::new().schema(schema); + if let Some(expires_ms) = expires_ms { + options = options.expires_ms(expires_ms); + } + documents + .put_with( + BUDGETS_COLLECTION, + HOLDS_ID, + target, + Precondition::Absent, + options, + ) + .await?; + Ok::<_, tinystoragedrivers_types::StorageError>(()) + }) + .unwrap() + .unwrap(); + + let documents = Arc::clone(storage.documents()); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate_budgets(documents.as_ref()).await }) + .unwrap(); + assert!(result.is_err(), "schema={schema}, expiry={expires_ms:?}"); + + let documents = Arc::clone(storage.documents()); + let (source, target) = Blocking::new() + .unwrap() + .run(async move { + Ok::<_, tinystoragedrivers_types::StorageError>(( + documents.get("x402_budget", HOLDS_ID).await?, + documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?, + )) + }) + .unwrap() + .unwrap(); + assert!(source.is_some(), "legacy source must remain intact"); + let target = target.expect("conflicting target must remain intact"); + assert_eq!(target.meta.schema, schema); + assert_eq!(target.meta.expires_ms, expires_ms); + assert_migration_not_marked(&storage); + } +} + +#[test] +fn budget_migration_does_not_mark_complete_after_an_absent_write_conflict() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + documents + .put( + "x402_budget", + HOLDS_ID, + json!({ "holds": { "old": { "amount": 12, "expires_at_ms": 1_800_000_000_000_i64 }}}), + Precondition::Absent, + ) + .await + }) + .unwrap() + .unwrap(); + + let documents = Arc::clone(storage.documents()); + let racing = tinystoragedrivers_testkit::ConflictOnce::new(documents); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate_budgets(&racing).await }) + .unwrap(); + assert!(result.is_err()); + + let documents = Arc::clone(storage.documents()); + let (source, target) = Blocking::new() + .unwrap() + .run(async move { + Ok::<_, tinystoragedrivers_types::StorageError>(( + documents.get("x402_budget", HOLDS_ID).await?, + documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?, + )) + }) + .unwrap() + .unwrap(); + assert!(source.is_some()); + assert!(target.is_none()); + assert_migration_not_marked(&storage); +} + +#[test] +fn budget_migration_accepts_a_matching_target_with_matching_metadata() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + let body = json!({ "holds": { "old": { + "amount": 12, + "expires_at_ms": 1_800_000_000_000_i64 + }}}); + documents + .put_with( + "x402_budget", + HOLDS_ID, + body, + Precondition::Absent, + WriteOptions::new().schema(1).expires_ms(1_900_000_000_000), + ) + .await?; + documents + .put_with( + BUDGETS_COLLECTION, + HOLDS_ID, + json!({ "holds": { "old": { + "amount": 12, + "expires_ms": 1_800_000_000_000_i64 + }}}), + Precondition::Absent, + WriteOptions::new() + .schema(BUDGETS_VERSION) + .expires_ms(1_900_000_000_000), + ) + .await?; + Ok::<_, tinystoragedrivers_types::StorageError>(()) + }) + .unwrap() + .unwrap(); + + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { super::migrate_budgets(documents.as_ref()).await }) + .unwrap() + .unwrap(); +} + +#[test] +fn stored_and_runtime_payment_statuses_round_trip_without_changing_the_variant() { + use super::super::types::PaymentStatus; + + for (runtime, stored) in [ + (PaymentStatus::Pending, StoredPaymentStatus::Pending), + (PaymentStatus::Settled, StoredPaymentStatus::Settled), + (PaymentStatus::Failed, StoredPaymentStatus::Failed), + (PaymentStatus::Denied, StoredPaymentStatus::Denied), + ] { + assert_eq!(StoredPaymentStatus::from(runtime), stored); + assert_eq!(PaymentStatus::from(stored), runtime); + } +} + +#[test] +fn owner_migration_marks_empty_sources_complete_and_is_idempotent() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap() + .unwrap(); + + let documents = Arc::clone(storage.documents()); + let marker = Blocking::new() + .unwrap() + .run(async move { documents.get("wallet.migrations", "x402").await }) + .unwrap() + .unwrap() + .expect("successful migration writes its completion marker"); + assert_eq!(marker.doc, json!({ "version": 2 })); + + let documents = Arc::clone(storage.documents()); + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap() + .unwrap(); +} + +#[test] +fn owner_migration_conflict_does_not_claim_a_missing_marker_was_written() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + let streams = Arc::clone(storage.streams()); + let racing = tinystoragedrivers_testkit::ConflictOnce::new(documents); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(&racing, streams.as_ref()).await }) + .unwrap(); + assert!(result.is_err()); + assert_migration_not_marked(&storage); +} + +#[test] +fn owner_migration_propagates_a_non_conflict_marker_write_failure() { + let storage = test_storage(); + let plan = tinystoragedrivers_testkit::FaultPlan::new(); + plan.fail_operation_nth("documents.put", 1, ErrorKind::Unavailable); + let documents = + tinystoragedrivers_testkit::Failing::with_plan(Arc::clone(storage.documents()), plan); + let streams = Arc::clone(storage.streams()); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(&documents, streams.as_ref()).await }) + .unwrap(); + assert!(result.is_err()); + assert_migration_not_marked(&storage); +} + +#[test] +fn budget_migration_propagates_a_non_conflict_target_write_failure() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + documents + .put( + "x402_budget", + HOLDS_ID, + json!({ "holds": { "old": { + "amount": 12, + "expires_at_ms": 1_800_000_000_000_i64 + }}}), + Precondition::Absent, + ) + .await + }) + .unwrap() + .unwrap(); + + let plan = tinystoragedrivers_testkit::FaultPlan::new(); + plan.fail_operation_nth("documents.put_with", 1, ErrorKind::Unavailable); + let documents = + tinystoragedrivers_testkit::Failing::with_plan(Arc::clone(storage.documents()), plan); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate_budgets(&documents).await }) + .unwrap(); + assert!(result.is_err()); + let documents = Arc::clone(storage.documents()); + let (source, target) = Blocking::new() + .unwrap() + .run(async move { + Ok::<_, tinystoragedrivers_types::StorageError>(( + documents.get("x402_budget", HOLDS_ID).await?, + documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?, + )) + }) + .unwrap() + .unwrap(); + assert!(source.is_some()); + assert!(target.is_none()); +} + +#[test] +fn invalid_legacy_payment_rows_are_skipped_without_changing_the_stream_name_contract() { + assert_eq!( + super::migrate_payments_stream("x402.payments", vec![json!({ "bad": true })]).unwrap(), + Some(("wallet.payments".into(), vec![])) + ); + assert_eq!( + super::renamed_holds(&json!({})).unwrap(), + serde_json::Map::new() + ); + assert!(super::renamed_holds(&json!({ "holds": [] })).is_none()); +} + +#[test] +fn owner_migration_advances_a_versioned_marker_and_skips_current_versions() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + documents + .put( + "wallet.migrations", + "x402", + json!({ "version": 1 }), + Precondition::Absent, + ) + .await + }) + .unwrap() + .unwrap(); + let documents = Arc::clone(storage.documents()); + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap() + .unwrap(); + + let documents = Arc::clone(storage.documents()); + let marker = Blocking::new() + .unwrap() + .run(async move { documents.get("wallet.migrations", "x402").await }) + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(marker.doc, json!({ "version": 2 })); + + let documents = Arc::clone(storage.documents()); + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap() + .unwrap(); +} + +#[test] +fn owner_migration_accepts_a_competing_completed_marker() { + let storage = test_storage(); + let documents = RacingDocuments { + inner: Arc::clone(storage.documents()), + action: RaceAction::CompleteMarker, + }; + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { super::migrate(&documents, streams.as_ref()).await }) + .unwrap() + .unwrap(); + let documents = Arc::clone(storage.documents()); + let marker = Blocking::new() + .unwrap() + .run(async move { documents.get("wallet.migrations", "x402").await }) + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(marker.doc, json!({ "version": 2 })); +} + +#[test] +fn budget_migration_conflict_retry_rejects_matching_bodies_with_wrong_metadata() { + for action in [RaceAction::WrongBudgetSchema, RaceAction::WrongBudgetExpiry] { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + documents + .put_with( + "x402_budget", + HOLDS_ID, + json!({ "holds": { "old": { + "amount": 12, + "expires_at_ms": 1_800_000_000_000_i64 + }}}), + Precondition::Absent, + WriteOptions::new().schema(1).expires_ms(1_900_000_000_000), + ) + .await + }) + .unwrap() + .unwrap(); + let documents = RacingDocuments { + inner: Arc::clone(storage.documents()), + action, + }; + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate_budgets(&documents).await }) + .unwrap(); + assert!(result.is_err(), "{action:?}"); + + let documents = Arc::clone(storage.documents()); + let (source, target) = Blocking::new() + .unwrap() + .run(async move { + Ok::<_, tinystoragedrivers_types::StorageError>(( + documents.get("x402_budget", HOLDS_ID).await?, + documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?, + )) + }) + .unwrap() + .unwrap(); + assert!(source.is_some(), "legacy row must be preserved"); + let target = target.expect("competing target row must be preserved"); + assert_eq!( + target.doc, + json!({ "holds": { "old": { + "amount": 12, + "expires_ms": 1_800_000_000_000_i64 + }}}) + ); + match action { + RaceAction::MatchingBudget => unreachable!(), + RaceAction::WrongBudgetSchema => assert_eq!(target.meta.schema, 1), + RaceAction::WrongBudgetExpiry => { + assert_eq!(target.meta.expires_ms, Some(1_900_000_000_001)); + } + RaceAction::CompleteMarker => unreachable!(), + } + assert_migration_not_marked(&storage); + } +} + +#[test] +fn budget_migration_accepts_a_matching_concurrent_write_after_conflict() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + documents + .put_with( + "x402_budget", + HOLDS_ID, + json!({ "holds": { "old": { + "amount": 12, + "expires_at_ms": 1_800_000_000_000_i64 + }}}), + Precondition::Absent, + WriteOptions::new().schema(1).expires_ms(1_900_000_000_000), + ) + .await + }) + .unwrap() + .unwrap(); + let documents = RacingDocuments { + inner: Arc::clone(storage.documents()), + action: RaceAction::MatchingBudget, + }; + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate_budgets(&documents).await }) + .unwrap(); + assert!(result.is_ok()); +} + +#[test] +fn payment_migration_refuses_a_longer_or_different_existing_target() { + for target in [vec![json!({}), json!({})], vec![json!({ "wrong": true })]] { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(1)); + append_values(&storage, "wallet.payments", target); + let streams = Arc::clone(storage.streams()); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate_payments(streams.as_ref()).await }) + .unwrap(); + assert!(result.is_err()); + assert_migration_not_marked(&storage); + } +} + +#[test] +fn unrelated_stream_names_are_not_migrated() { + assert_eq!( + super::migrate_payments_stream("other.stream", vec![]).unwrap(), + None + ); +} + #[test] fn incomplete_legacy_payment_window_does_not_mark_migration_complete() { let storage = test_storage(); @@ -319,6 +969,7 @@ fn incomplete_existing_payment_prefix_does_not_mark_migration_complete() { .unwrap() .unwrap() .1; + assert_eq!(migrated.len(), 2); append_values(&storage, "wallet.payments", migrated); let streams: Arc = Arc::new(FaultyReads { inner: Arc::clone(storage.streams()), @@ -353,3 +1004,100 @@ fn changed_legacy_payment_source_does_not_mark_migration_complete() { assert!(matches!(result, Ok(Err(_)))); assert_migration_not_marked(&storage); } + +#[test] +fn malformed_legacy_payment_offsets_do_not_mark_migration_complete() { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(1)); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault: ReadFault::WrongOffset("x402.payments"), + len_calls: AtomicUsize::new(0), + }); + let documents = Arc::clone(storage.documents()); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap(); + assert!(result.is_err()); + assert_migration_not_marked(&storage); +} + +#[test] +fn payment_migration_rejects_stream_read_errors_and_oversized_windows() { + for fault in [ + ReadFault::ReadError("x402.payments"), + ReadFault::Overshoot("x402.payments"), + ] { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(1)); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault, + len_calls: AtomicUsize::new(0), + }); + let documents = Arc::clone(storage.documents()); + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap(); + assert!(result.is_err()); + assert_migration_not_marked(&storage); + } +} + +#[test] +fn payment_migration_propagates_target_append_failure_without_marking_complete() { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(1)); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault: ReadFault::AppendError("wallet.payments"), + len_calls: AtomicUsize::new(0), + }); + let documents = Arc::clone(storage.documents()); + + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }); + + assert!(matches!(result, Ok(Err(_)))); + assert_migration_not_marked(&storage); +} + +#[test] +fn payment_migration_completes_a_matching_prefix_and_appends_only_its_suffix() { + let storage = test_storage(); + let source = legacy_payments(2); + append_values(&storage, "x402.payments", source.clone()); + let migrated = super::migrate_payments_stream("x402.payments", source) + .unwrap() + .unwrap() + .1; + assert_eq!(migrated.len(), 2); + append_values(&storage, "wallet.payments", vec![migrated[0].clone()]); + let streams = Arc::clone(storage.streams()); + assert_eq!( + Blocking::new() + .unwrap() + .run(async move { streams.len("wallet.payments").await }) + .unwrap() + .unwrap(), + 1 + ); + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { super::migrate_payments(streams.as_ref()).await }) + .unwrap() + .unwrap(); + let streams = Arc::clone(storage.streams()); + let entries = Blocking::new() + .unwrap() + .run(async move { streams.read_window("wallet.payments", 0, 10).await }) + .unwrap() + .unwrap(); + assert_eq!(entries.len(), 2); + assert_eq!(entries[0].offset, 0); + assert_eq!(entries[1].offset, 1); +} diff --git a/deny.toml b/deny.toml index d7b14c3d..7783337c 100644 --- a/deny.toml +++ b/deny.toml @@ -57,4 +57,5 @@ allow-registry = ["https://github.com/rust-lang/crates.io-index"] allow-git = [ "https://github.com/tinyhumansai/tinytools", "https://github.com/tinyhumansai/tinystoragedrivers", + "https://github.com/senamakel/tinystoragedrivers", ] diff --git a/scripts/__pycache__/check-bus-boundaries.cpython-314.pyc b/scripts/__pycache__/check-bus-boundaries.cpython-314.pyc deleted file mode 100644 index c157d43ec36804d28cc76c8ba80d3035f83724ef..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9575 zcmb_iYit`=cD^$lk|VxJOV-17G=9VuWs$Pwx8un1Lz4Bdq>N=M$x5L|*<9?>pyeughseaNV3+e&^RU2>mC1FfLZlJYi{sGKfbi zdK>XnC#6#4POCJzn^e<2#8*vHD#O#NnK$vwK3cW#n^h~kuZH(5+-u-o!JDg*YU3@C z+WA`ET8-kA>fl*;cJdXFx_BF;Zr%>5hj&2g<(-iFhBxu9qi-M-{bz)>qG9KDH0;=p z4(dZZNEI?_<#6R5{ay4`QnPA1;@!NbKcK%ZxeZqu?V3v8n)-t!k9wB(9)VTBS3Mdw z_3ta>OVjP>ZOZ5m>Uh>h=Rxfk5mIZ1eK2Y-{A!JQ#$Bx&t~16xX2Rp{-h$9@6|U<* zypP|s;rQ!}_72oyf>HfHjJtafp$ha8`8Ho%pL&q{PV)2DrO%&n+bj*Hw#O4*}u z2}zz5;>{zeSUk!_;*ye*MJ}bp5@Vb!DpLH480F3g@|eUWg~)_3CUUW;m{4PCOjLrs z=|i$O7E@GtYVWwJCY9sO&0{fjJT(%GNR!QSN>KxGAu-k*kp&g%$D}|k5f!g#){&SR zkzxsrnP@q5IHGF+kq84RtRnM7hD-*9P=9HuE;OFv>4UmVlT?Tr((?!%gBq_;MR{z- z@~B54s^6?PEx8R@j0Zy&JCWa%ZW|mIVS!}sQbL#%FL5!26S&B@5KA;qh*Ml_G8q>q zVGRT|CMAreDV2x{G8S@jN~;)^499+#Vm922{b}w;bDF8KvlU2SS&gvl+Euem{a<&y!J5 z<*PSDfDC`*7_7_~tS^j|>UTc>Ro-g!H-t5jTx8w0lQwL>*Lb^j=h^;EYfnZlR2-Sn zBg~_-bRK*~=@S6KcM(e3hboO8UZGxRx=>+V!N>ymh3ve&yp6H4SbGgw=vrb&ptZc? zd=1uK-g&+f!0sFSFvhvAA6QZNuB-IBNe9SzgOwQk_ra#pdgW3GQl(IOfHuBYkGj8K z(A_qwdoO&A-3hy(9)3wGX5>u89K7?pHCBfUMWbU;Yy%0FXy$|z6%`rgj#gc376{v% z^j`5=QjDkoIN~)SqQ<8@eIIsm^XM@3>|7!Z0L(+C809wsKmlU)`srTHOfd522+T4a+$YyU zE8QB)SW&f#6JufmrXaU!H3CN2;EA{t5#mZ~uvl^gH^MFd0OQH}1{Y6;ZmV;aAD@^% zd4E$&?qukh!a(V}HFcC$0dorDuPX!XnkhLk=C^C6xR}svAt9a;+hkdiHIpK$P$(re zlMsbr^Zf-st^@aL9^<@ zlCjPJ=zxr5tmc|omLyft%$HMQO4Jxd#Gk(sli~#X6phu%z?8-$1wb(yj2XToCL&Xs zIWi8MLcwdZn=82rt7RrjB;y5n8GgzfZ2Sz$A8x&qzJItY=k8uS+_i9Ij`^{3?&{~B z-SCt-mvwjN8(VH4yVv;Yow56k?KwxsVq^RKuGw8bd~2@qbLTdA%Cu!29k|x<`;DzR z$LL~X>)h45yZ@~@dr@3GE#4fS9-JMR8J-@70$g|Wq185h=ugwLum9QiAG&I?we2}q zN0#l#yEe_9`r&xC)}O6u%sTgG9Zi|Ghj!O{hcajL-c6aVFKzDWm-DqReO&ut?N7E` zcTKZ-`=%xPmIsc?JnNWYud}l?OKe@fG4;=tt7u4=%lQ z;#bz+*gv!1J(qj!;?kSK(rZHAv3c3CZPBr9ZuH}c4<{CO<%FC1*m+M!05J z?4)@JTPbptpfr6HY{ZzGpv`(brihbMz)i3{L&f=F*C}M?Ev2^CQ*?j;)ASi9Eg@4s z^u7LCkNhD^nRSj8tX9Yb^tB@WKMj~PHgN?5>F1&`AK-*InB1Vv zb}2$AKchB^f-5OI$=qBqWuKi^2pKOQ;g*IVz3{skq9?se}!W@2UXYTjin> zG>s)VeTaq)yA-s^Rj_VpTOeQza^UACY=wZ+YOaWo!~+jYDK(i=HAWS$sb$KGm5Bhx z4|1X`$r#m1 zKStaFzq>G@sDP+Yy|7oE=(tjX`zoT8|Y8AujtAvyjBJfPlQ4f$;#8?0p@ z3mDNV9Y_)ZLPlJ56g-|LGQU+e0A=E6>>7rqgqWrSqiNH(li&5T;6kNF@VbbKqM1Nb zfETDykTDb_<1rPKP6YTOc^N1o1~(AA?1!x1s#$eS(X8OEg5MO?Owd+GLEKg|lSP!V z0aUPg(~+!zVa~FpltWMsaSNpU0+I|`aUr)vWjemJy7H`hwr74%c2na$wh^$vRyh;A z5uB@DVD1duWtME`mu&-!wt>uo7*6y==AG?uv`y&r>RA%~QEU&UXful&op#KM%5tvpm=3qXf2oYCd zXNeILWh(b(?(D)5CKSV=pgl;hzy9mfv0QLzz#K5P>g=tw7Ofd9eGWyi_*lC0Y zUa+GEaKEMjQ%MYf>_Q;u43wB#iVhciaa1>)K==HX^zKlR*bwt37&Zor`4V{b3UJY} zVA{8ik^%uuJGh3TkL*v=T!Y3Mkr9pZ`%T1eCTb_|hI#oJqGWOl>-*IGLYFl!& zV@6_k|LDlglb;+W?8LXs)-JNO*{#6^bz$`O>DyP9k922`bpNU@d${NBscc>EeYWqh z6V+~iZlDrI-F2ddSir`{)2LtW6N8@( zMjRVa?46YQDSj$_rVX|}cov2e!C{~TD3hhhLW~RIVStnhgmu6Pxnx)!0L}!FKiHBW zSl3>dv5c)GcmkFJp2$QtCAL=cmD+|d`H(yeZ3Or!ShYcj4Z-DxV~Y*PmKt8k*?Sfn zUYTcpnf|BrFTZoMZ~E*^*Y&RVdgi<{ebaqVv}o_iGCj{exA!R6S^l823=xO^gfVpdq!t*z&6)kJY&o;WWuYx2F^oxjmV|@ z@8I;}5Fz1c%!aFB2_j<-Ypm^s9=-Mab^_w;`EB6QW9IjN=+zjtv99{Kufi^1%Ht6e zboaYOO)t(iX%3l-ZP%}JG2($^NyWXvfWK}}pKeQ}CPf^k)!AY^HX;ka8Vz0tluI3l zP-v0VHF2XtjIcT!HWs5n&08!BPl}Txu#k6Zu=P7~dtP03v}PTxU(_AcqX;br zDb1>nW1yYjOuA*AEJksl7c5+fFxE+4@mtBvG+PXg1t4UdfLJzz(NNw2Lz8zxg2OQ~ zh*XB~5J0I63y3spsS;?m!c#aFRb)VVV5`I^DmVsTU{wXwt9jA-$XM)v*hu+rNWgr$ zHqXSb$Fp04IahP0Bk!)B`Ofw4%t7p6Pv+c1d)4gNPt|4nuFvhe{<`b-wSTQ#ZfgI$ zsh#-veK}WumhFG&t(+bFU~8u9p~Lr8b^Q}FTWNv&bVuIqn|bB>E3<0OzIEQVXm5OK zMin(*TaeT9-kHY;(XnrZ8- zWyU@2eo$Ti7=Q5zVx87Z+t)ti@RHG;&$)WDY;WG~$@Dy1sfH@bOEBZlf;DG7?62)M zoNnHZ)8h@0{>vUGq!Fl5yzoweeZV}q37HJ~W3Dwg>ZU#jSd%~c8{KO(g!?Afka5O{ z`itRPql`H0MGwi?UBI%K^ch|hO1J(xZ7Vrm;_$%;;47E}b(|9vB{iAE`%DQA$k?WX zo}GmoQMNSr2oPEnLg(I-0W|%QDBFCs-H=i43ohuJMT% zj}Ijn9s&uxm1lz$Wp)n$fBi**CKWvXvwfpf={2c_iqH?zvSVq1+ng}0vd)+Q3xE;< zBPI~B{uHq!w17!aupp&27@gb>N!k?%z(G{eOP4!v$vK>K;-m`_UBJwGQDFuJR@h7| zrp)8&7a&n!p|BAtSddCxR;3I~kyWVj16&t>4jfwxs_@Kio~xWoWp^LG!`w;aS>J5? zBeThE$#gtrk-h2#KH5Y3wz){oz9Y-*_@h!Q@sGf7!be$zxKzG~1Y;>1R09AW+)jha zu2HY161uatv(^Ig5Gy#`4q;=6vtX4qM5k~gMhFNWB(6Ku#kM#oW0aJ!K?a9q9Ov<7 z*F0^#9i6>x;o=D;VB7>Q1?Q|h1n$*Wel0>Q19L&MxLyzv*dccBr((``;!|-Udh5jd zC+1D_7w&KJe=08ePAr}5yXWi6+559h|Fh41CrBv#M%`gnW5eM|IDQR>)7#sPlSnQi zB?@f5sBdsudEBN^Hb12?qp`S{4wT2dutJb#(3isL(Idwq$gwV;2^rBLPS9k<*2Ax01hMLvQ~jfl}KXw zHc}FfNHQGx7V^X>ISP4*$;YmUtM;`pP|K<_m54BcsNlpIt$=aYH)ch_>^4< zv|=))F(cTF(yHo6#^;~3S?L~!M_Y)6cOAR zI4#y^8^z<0l~tQ?RS783iGXro)geq?h9HfkN)ai(>H^D9Xm}u?Oew2X&$kXtTv@H& z;Ppsc8dviZvdNR${O!GEU9W zDSWd;3ik@&JZdZguU2hqi|?m;{aZ9^I1Jr{!?FZ@5Nm}6uMj6+Zouy_O3D}@Wo*c0 z?Ee*l0T5b5BxXdMd*U1tC?cRj%oW)@So!hp42Lxq6K))Rg|L(i%u@#Li>a3isv&EP zcrB*N3VvlR>_bI{lT<{ERKYT`Cnlw6DlWFl3s8XVh*AUTBNIhYU!eTjAJ^zWU77OuKh6ZljfYe zF>~%qtNQ`#%(_}`5B%espT2qLTJF%fd#-bLmEWa*o4&`sm1pfU> 1 and (package["name"] not in ALLOWED or package.get("source") != REGISTRY): + if len(path) > 1 and not dependency_allowed(package["name"], package.get("source")): violations.append(" -> ".join(path)) for dependency in nodes[identity]["deps"]: if any(kind["kind"] in (None, "build") for kind in dependency["dep_kinds"]): @@ -90,6 +101,8 @@ def audit_tree(packages): continue if name in ALLOWED and not source: continue + if name == TSD_TYPES and source.removeprefix("git+").startswith(TSD_TYPES_SOURCE): + continue violations.append(f"tinywallet-bus -> {name} ({source or 'registry'})") return violations diff --git a/scripts/check_bus_boundaries_tests.py b/scripts/check_bus_boundaries_tests.py index 43aefe44..4704b31e 100644 --- a/scripts/check_bus_boundaries_tests.py +++ b/scripts/check_bus_boundaries_tests.py @@ -26,6 +26,26 @@ def test_dev_dependencies_are_exempt(self): def test_local_package_cannot_impersonate_serde(self): self.assertTrue(boundary.audit(metadata("serde", source=None))) + def test_pinned_tsd_types_git_source_is_allowed(self): + self.assertEqual( + boundary.audit(metadata(boundary.TSD_TYPES, source="git+" + boundary.TSD_TYPES_SOURCE + "e3224a8")), + [], + ) + + def test_unapproved_tsd_types_source_is_rejected(self): + self.assertTrue( + boundary.audit(metadata(boundary.TSD_TYPES, source="git+https://github.com/attacker/tinystoragedrivers#deadbeef")) + ) + + def test_tree_allows_only_the_v201_fork_source_for_tsd_types(self): + self.assertEqual( + boundary.audit_tree([(boundary.TSD_TYPES, boundary.TSD_TYPES_SOURCE + "e3224a8")]), + [], + ) + self.assertTrue( + boundary.audit_tree([(boundary.TSD_TYPES, "https://github.com/tinyhumansai/tinystoragedrivers#v2")]) + ) + class EngineTreeTests(unittest.TestCase): def test_versioned_cargo_tree_lines_are_checked_by_package_name(self): From fec831287b8f46cc114fcb1e9ea5cf0ad42abd40 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 20:36:02 +0300 Subject: [PATCH 18/51] test(ledger): merge unreachable match arms in schema test Combine the two unreachable arms in the budget migration conflict retry test into a single pattern so the match stays exhaustive without duplicating the panic. Auto-committed-on: dragonfly --- crates/tinywallet-x402/src/ledger/schema_tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 22beeadc..a3b23664 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -873,12 +873,11 @@ fn budget_migration_conflict_retry_rejects_matching_bodies_with_wrong_metadata() }}}) ); match action { - RaceAction::MatchingBudget => unreachable!(), RaceAction::WrongBudgetSchema => assert_eq!(target.meta.schema, 1), RaceAction::WrongBudgetExpiry => { assert_eq!(target.meta.expires_ms, Some(1_900_000_000_001)); } - RaceAction::CompleteMarker => unreachable!(), + RaceAction::MatchingBudget | RaceAction::CompleteMarker => unreachable!(), } assert_migration_not_marked(&storage); } From 4247270ddf4616e5645c6ad361db32b97f5126da Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 20:37:18 +0300 Subject: [PATCH 19/51] test(ledger): cover wallet.payments read errors in migration Extend the payment migration fault matrix so a read error on wallet.payments is exercised alongside the existing x402.payments cases, ensuring the migration is rejected for both legacy tables. Auto-committed-on: dragonfly --- crates/tinywallet-x402/src/ledger/schema_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index a3b23664..d0df175e 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -1026,6 +1026,7 @@ fn malformed_legacy_payment_offsets_do_not_mark_migration_complete() { fn payment_migration_rejects_stream_read_errors_and_oversized_windows() { for fault in [ ReadFault::ReadError("x402.payments"), + ReadFault::ReadError("wallet.payments"), ReadFault::Overshoot("x402.payments"), ] { let storage = test_storage(); From dc36ef0e3cab47d82354ce8ef6c5fdbff8d897a7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 20:38:10 +0300 Subject: [PATCH 20/51] fix(ledger): accept already complete payment migration targets The migration no longer errors when a read window comes back empty, since a target that already holds every source entry legitimately reaches the end of the stream. A regression test covers the fully migrated case. Auto-committed-on: dragonfly --- crates/tinywallet-x402/src/ledger/schema.rs | 5 --- .../src/ledger/schema_tests.rs | 34 +++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 515e237c..7673c833 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -171,11 +171,6 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types let window = streams .read_window(LEGACY_PAYMENTS_STREAM, offset, BATCH_SIZE) .await?; - if window.is_empty() { - return Err(StorageError::backend( - "wallet payment migration source ended before its reported length", - )); - } for (index, entry) in window.iter().enumerate() { let expected = offset .checked_add(u64::try_from(index).map_err(|_| { diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index d0df175e..4a679d75 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -1101,3 +1101,37 @@ fn payment_migration_completes_a_matching_prefix_and_appends_only_its_suffix() { assert_eq!(entries[0].offset, 0); assert_eq!(entries[1].offset, 1); } + +#[test] +fn payment_migration_accepts_an_already_complete_matching_target() { + let storage = test_storage(); + let source = legacy_payments(2); + append_values(&storage, "x402.payments", source.clone()); + let migrated = super::migrate_payments_stream("x402.payments", source) + .unwrap() + .unwrap() + .1; + append_values(&storage, "wallet.payments", migrated.clone()); + let streams = Arc::clone(storage.streams()); + + Blocking::new() + .unwrap() + .run(async move { super::migrate_payments(streams.as_ref()).await }) + .unwrap() + .unwrap(); + + let streams = Arc::clone(storage.streams()); + let entries = Blocking::new() + .unwrap() + .run(async move { streams.read_window("wallet.payments", 0, 10).await }) + .unwrap() + .unwrap(); + assert_eq!(entries.len(), migrated.len()); + assert_eq!( + entries + .into_iter() + .map(|entry| entry.value) + .collect::>(), + migrated + ); +} From fb1d5dc94d38d88c35a991b678771e2b0b207b06 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 20:42:03 +0300 Subject: [PATCH 21/51] chore(tinywallet-crypto): bump minimum rust version to 1.88 Raise the crate's declared MSRV from 1.85 to 1.88 so it matches the toolchain the crate is actually built and tested against. Auto-committed-on: dragonfly --- crates/tinywallet-crypto/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinywallet-crypto/Cargo.toml b/crates/tinywallet-crypto/Cargo.toml index b11c35e5..def20f60 100644 --- a/crates/tinywallet-crypto/Cargo.toml +++ b/crates/tinywallet-crypto/Cargo.toml @@ -2,7 +2,7 @@ name = "tinywallet-crypto" version = "0.24.1" edition = "2024" -rust-version = "1.85" +rust-version = "1.88" license = "GPL-3.0-only" description = "Pure crypto-rail primitives for TinyWallet: chains, addresses, reference data, the RPC transport seam, and transaction verification." repository = "https://github.com/tinyhumansai/tinywallet" From b2ba2327c6cf8a31aca368141354e1bd1b5a14ba Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Tue, 20 Oct 2026 20:46:03 +0300 Subject: [PATCH 22/51] refactor(tron): simplify fee limit check and hex length test Collapse the nested fee_limit comparison into a let-chain and replace the modulo parity check in decode_hex with is_multiple_of. Both are behaviour-preserving cleanups. Auto-committed-on: dragonfly --- crates/tinywallet-crypto/src/tx/tron.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/tinywallet-crypto/src/tx/tron.rs b/crates/tinywallet-crypto/src/tx/tron.rs index 031f38ef..fec00175 100644 --- a/crates/tinywallet-crypto/src/tx/tron.rs +++ b/crates/tinywallet-crypto/src/tx/tron.rs @@ -197,10 +197,9 @@ pub fn verify_contract( if let (Some(expected), Some(actual)) = ( fee_limit_sun, proto::optional_varint(&raw_fields, 18, "Transaction.raw.fee_limit")?, - ) { - if actual != expected { - return Err(untrusted("the transaction has a different fee_limit")); - } + ) && actual != expected + { + return Err(untrusted("the transaction has a different fee_limit")); } let mut expected_data = decode_hex(TRC20_TRANSFER_SELECTOR_HEX)?; @@ -291,7 +290,7 @@ pub fn signature_hex(signature: &Signature) -> String { fn decode_hex(raw: &str) -> Result> { let body = raw.trim(); - if body.len() % 2 != 0 { + if !body.len().is_multiple_of(2) { return Err(Error::InvalidField { field: "raw_data_hex", reason: "odd length".to_string(), From 6b21e024b339ea080fac560a866d19e387b68803 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:51:32 +0300 Subject: [PATCH 23/51] feat(storage): add storage tests module This introduces a new module for testing storage functionality when the "wire" feature is enabled. This allows for isolated testing of the storage implementation. Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/storage.rs | 5 + crates/tinywallet-bus/src/storage_tests.rs | 104 +++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 crates/tinywallet-bus/src/storage_tests.rs diff --git a/crates/tinywallet-bus/src/storage.rs b/crates/tinywallet-bus/src/storage.rs index 97b41411..b3b5dff2 100644 --- a/crates/tinywallet-bus/src/storage.rs +++ b/crates/tinywallet-bus/src/storage.rs @@ -13,3 +13,8 @@ pub fn collections() -> Vec { CollectionSpec::new("wallet.migrations"), ] } + +#[cfg(feature = "wire")] +#[cfg(test)] +#[path = "storage_tests.rs"] +mod tests; diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs new file mode 100644 index 00000000..606197c3 --- /dev/null +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -0,0 +1,104 @@ +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + +use super::legacy_payments::{PaymentStatus, convert_legacy_payment}; + +#[test] +fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() { + let legacy = serde_json::json!({ + "id": "payment-1", + "url": "https://merchant.example/item", + "asset": "USDC", + "amountAtomic": 12345, + "amountDisplay": "0.012345", + "recipient": "recipient", + "network": "eip155:1", + "txSignature": "0xabc", + "status": "settled", + "timestamp": "2026-03-15T15:00:00.250000+03:00", + "authorizationValidUntil": "2026-03-15T12:00:01.9999Z", + "solanaLastValidBlockHeight": 42, + "authorizationExpiredAt": "2026-03-15T12:00:02Z", + "authorizationExpiryObservedHeight": 43, + "sessionId": "session-1", + "threadId": "thread-1", + "committed_hold": "hold-1" + }); + + let payment = convert_legacy_payment(legacy).unwrap(); + assert_eq!(payment.id, "payment-1"); + assert_eq!(payment.status, PaymentStatus::Settled); + assert_eq!(payment.timestamp_ms, 1_773_576_000_250); + assert_eq!(payment.authorization_valid_until_ms, Some(1_773_576_001_999)); + assert_eq!(payment.authorization_expired_at_ms, Some(1_773_576_002_000)); + assert_eq!(payment.solana_last_valid_block_height, Some(42)); + assert_eq!(payment.authorization_expiry_observed_height, Some(43)); + assert_eq!(payment.session_id, "session-1"); + assert_eq!(payment.thread_id.as_deref(), Some("thread-1")); + assert_eq!(payment.committed_hold.as_deref(), Some("hold-1")); + + let current = serde_json::to_value(payment).unwrap(); + assert_eq!(current["amount_atomic"], 12345); + assert_eq!(current["timestamp_ms"], 1_773_576_000_250_i64); + assert_eq!(current["authorization_valid_until_ms"], 1_773_576_001_999_i64); + assert_eq!(current["tx_signature"], "0xabc"); + assert!(current.get("timestamp").is_none()); +} + +#[test] +fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids() { + let row = |status: &str, timestamp: &str| { + serde_json::json!({ + "id": "same-attempt", + "url": "https://merchant.example/item", + "asset": "USD", + "amountAtomic": 1, + "amountDisplay": "1", + "recipient": "recipient", + "network": "eip155:1", + "status": status, + "timestamp": timestamp, + "sessionId": "session" + }) + }; + let pending = convert_legacy_payment(row("pending", "2026-03-15T12:00:00Z")).unwrap(); + let settled = convert_legacy_payment(row("settled", "2026-03-15T12:00:01Z")).unwrap(); + assert_eq!(pending.id, settled.id); + assert_eq!(pending.status, PaymentStatus::Pending); + assert_eq!(settled.status, PaymentStatus::Settled); + assert_eq!(pending.tx_signature, None); + assert_eq!(pending.authorization_valid_until_ms, None); + assert_eq!(pending.thread_id, None); + assert_eq!(pending.committed_hold, None); +} + +#[test] +fn legacy_payment_conversion_rejects_malformed_required_and_optional_data() { + let base = serde_json::json!({ + "id": "payment-1", + "url": "https://merchant.example/item", + "asset": "USD", + "amountAtomic": 1, + "amountDisplay": "1", + "recipient": "recipient", + "network": "eip155:1", + "status": "pending", + "timestamp": "2026-03-15T12:00:00Z", + "sessionId": "session" + }); + + for (field, value) in [ + ("timestamp", serde_json::json!("yesterday")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00+24:00")), + ( + "authorizationValidUntil", + serde_json::json!("not-a-timestamp"), + ), + ("status", serde_json::json!("unknown")), + ("amountAtomic", serde_json::json!(-1)), + ] { + let mut malformed = base.clone(); + malformed[field] = value; + assert!(convert_legacy_payment(malformed).is_err(), "field {field}"); + } + assert!(convert_legacy_payment(serde_json::json!([])).is_err()); +} From 155731daacce3747bea0e7c41a99a647d062b7b5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:54:40 +0300 Subject: [PATCH 24/51] refactor(ledger): migrate legacy payment handling to tinywallet-bus This change moves the logic for converting old payment records into the current schema into the tinywallet-bus crate. This centralizes the migration logic and updates the x402 ledger to use the new conversion function. Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/storage.rs | 5 + .../src/storage/legacy_payments.rs | 230 ++++++++++++++++++ crates/tinywallet-x402/Cargo.toml | 2 +- crates/tinywallet-x402/src/ledger/schema.rs | 6 +- .../src/ledger/schema_payment.rs | 218 +---------------- .../src/ledger/schema_payment_tests.rs | 105 ++------ 6 files changed, 265 insertions(+), 301 deletions(-) create mode 100644 crates/tinywallet-bus/src/storage/legacy_payments.rs diff --git a/crates/tinywallet-bus/src/storage.rs b/crates/tinywallet-bus/src/storage.rs index b3b5dff2..6463d8d5 100644 --- a/crates/tinywallet-bus/src/storage.rs +++ b/crates/tinywallet-bus/src/storage.rs @@ -2,6 +2,11 @@ use tinystoragedrivers_types::CollectionSpec; +/// Pure conversion of the previous x402 payment stream into the current +/// `wallet.payments` record contract. +#[cfg(feature = "wire")] +pub mod legacy_payments; + /// Collection names used by the wallet's persistent module storage. /// /// Migration behavior remains in the x402 implementation. The host only needs diff --git a/crates/tinywallet-bus/src/storage/legacy_payments.rs b/crates/tinywallet-bus/src/storage/legacy_payments.rs new file mode 100644 index 00000000..92e143b5 --- /dev/null +++ b/crates/tinywallet-bus/src/storage/legacy_payments.rs @@ -0,0 +1,230 @@ +//! Owner-defined conversion from the previous `x402.payments` row to the +//! canonical `wallet.payments` storage record. +//! +//! Hosts may use this pure converter while importing a legacy source. It does +//! not read storage or decide which rows to import; the wallet implementation +//! uses the same conversion during its own stream migration. + +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +/// Payment lifecycle state in the canonical `wallet.payments` record. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StoredPaymentStatus { + /// Signed and sent, not yet settled. + Pending, + /// A trusted settlement receipt confirms payment. + Settled, + /// A trusted result established that the payment did not settle. + Failed, + /// Refused before anything was signed. + Denied, +} + +/// Canonical body stored in the `wallet.payments` stream. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredPaymentRecord { + /// Unique id of the attempt. A status change may produce another row with + /// the same id; callers must preserve stream order and must not deduplicate. + pub id: String, + /// The URL the payment bought access to. + pub url: String, + /// The asset paid in. + pub asset: String, + /// The amount in atomic units of `asset`. + pub amount_atomic: u64, + /// The amount formatted for people. + pub amount_display: String, + /// Who was paid. + pub recipient: String, + /// The network, in CAIP-2 form. + pub network: String, + /// The settlement transaction, once reported. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tx_signature: Option, + /// Where the payment stands. + pub status: StoredPaymentStatus, + /// When this state was written, in epoch milliseconds. + pub timestamp_ms: i64, + /// When an exported authorization becomes unusable, in epoch milliseconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_valid_until_ms: Option, + /// Solana's `lastValidBlockHeight` for the exported transaction. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub solana_last_valid_block_height: Option, + /// When the authorization was observed expired, in epoch milliseconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_expired_at_ms: Option, + /// The block height at which the expiry was observed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_expiry_observed_height: Option, + /// The session that made the payment. + pub session_id: String, + /// The conversation thread, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thread_id: Option, + /// The budget hold this entry committed, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub committed_hold: Option, +} + +/// Convert one previous camelCase `x402.payments` body to the current typed +/// `wallet.payments` storage contract. +/// +/// The legacy row's ID and all optional payment and authorization data are +/// retained. RFC 3339 instants become epoch milliseconds, truncating +/// sub-millisecond precision. The caller owns source ordering and should keep +/// repeated IDs because they can represent successive payment states. +pub fn convert_legacy_payment(value: Value) -> Result { + let legacy: LegacyPayment = serde_json::from_value(value)?; + Ok(legacy.into()) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct LegacyPayment { + id: String, + url: String, + asset: String, + amount_atomic: u64, + amount_display: String, + recipient: String, + network: String, + #[serde(default)] + tx_signature: Option, + status: StoredPaymentStatus, + #[serde(deserialize_with = "instant_ms")] + timestamp: i64, + #[serde(default, deserialize_with = "optional_instant_ms")] + authorization_valid_until: Option, + #[serde(default)] + solana_last_valid_block_height: Option, + #[serde(default, deserialize_with = "optional_instant_ms")] + authorization_expired_at: Option, + #[serde(default)] + authorization_expiry_observed_height: Option, + session_id: String, + #[serde(default)] + thread_id: Option, + #[serde(default, rename = "committed_hold")] + committed_hold: Option, +} + +impl From for StoredPaymentRecord { + fn from(legacy: LegacyPayment) -> Self { + Self { + id: legacy.id, + url: legacy.url, + asset: legacy.asset, + amount_atomic: legacy.amount_atomic, + amount_display: legacy.amount_display, + recipient: legacy.recipient, + network: legacy.network, + tx_signature: legacy.tx_signature, + status: legacy.status, + timestamp_ms: legacy.timestamp, + authorization_valid_until_ms: legacy.authorization_valid_until, + solana_last_valid_block_height: legacy.solana_last_valid_block_height, + authorization_expired_at_ms: legacy.authorization_expired_at, + authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, + session_id: legacy.session_id, + thread_id: legacy.thread_id, + committed_hold: legacy.committed_hold, + } + } +} + +fn instant_ms<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + parse_rfc3339_ms(&text) + .ok_or_else(|| serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant"))) +} + +fn optional_instant_ms<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|text| { + parse_rfc3339_ms(&text).ok_or_else(|| { + serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant")) + }) + }) + .transpose() +} + +/// Parse an RFC 3339 instant using integer arithmetic, truncating fractions +/// finer than milliseconds without introducing a date/time dependency into +/// the bus contract crate. +fn parse_rfc3339_ms(text: &str) -> Option { + let bytes = text.as_bytes(); + let digits = |from: usize, len: usize| -> Option { + let part = bytes.get(from..from + len)?; + if !part.iter().all(u8::is_ascii_digit) { + return None; + } + part.iter() + .try_fold(0_i64, |n, d| Some(n * 10 + i64::from(d - b'0'))) + }; + let separator = |at: usize, want: &[u8]| bytes.get(at).is_some_and(|b| want.contains(b)); + if !(separator(4, b"-") + && separator(7, b"-") + && separator(10, b"Tt ") + && separator(13, b":") + && separator(16, b":")) + { + return None; + } + let (year, month, day) = (digits(0, 4)?, digits(5, 2)?, digits(8, 2)?); + let (hour, minute, second) = (digits(11, 2)?, digits(14, 2)?, digits(17, 2)?); + let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if leap_year => 29, + 2 => 28, + _ => return None, + }; + if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 60 { + return None; + } + let mut at = 19; + let mut millis = 0; + if bytes.get(at) == Some(&b'.') { + let start = at + 1; + let mut end = start; + while bytes.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + if end == start { + return None; + } + for (place, digit) in bytes[start..end].iter().take(3).enumerate() { + millis += i64::from(digit - b'0') * [100, 10, 1][place]; + } + at = end; + } + let offset_minutes = match bytes.get(at)? { + b'Z' | b'z' if at + 1 == bytes.len() => 0, + sign @ (b'+' | b'-') if at + 6 == bytes.len() && separator(at + 3, b":") => { + let hours = digits(at + 1, 2)?; + let minute_part = digits(at + 4, 2)?; + if hours > 23 || minute_part > 59 { + return None; + } + let minutes = hours * 60 + minute_part; + if *sign == b'-' { -minutes } else { minutes } + } + _ => return None, + }; + // Days from civil (Howard Hinnant's algorithm), proleptic Gregorian. + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let year_of_era = y - era * 400; + let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + let days = era * 146_097 + day_of_era - 719_468; + let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; + Some(seconds * 1_000 + millis) +} + diff --git a/crates/tinywallet-x402/Cargo.toml b/crates/tinywallet-x402/Cargo.toml index 310b6ee0..5a0b9b6a 100644 --- a/crates/tinywallet-x402/Cargo.toml +++ b/crates/tinywallet-x402/Cargo.toml @@ -107,7 +107,7 @@ eip712 = ["dep:sha3", "dep:thiserror"] abi = ["eip712", "dep:tinywallet-crypto", "tinywallet-crypto/evm", "tinywallet-crypto/keccak"] # The rail-neutral spending ledger: records, budgets, the JSONL file, and the # process-wide handle. -ledger = ["dep:serde", "dep:serde_json", "dep:chrono", "dep:log", "dep:tinystoragedrivers-api", "dep:tinystoragedrivers-types", "dep:tokio"] +ledger = ["dep:serde", "dep:serde_json", "dep:chrono", "dep:log", "dep:tinystoragedrivers-api", "dep:tinystoragedrivers-types", "dep:tokio", "dep:tinywallet-bus"] # Paying a 402 challenge: header codec, the client, and the EVM and Solana # payment builders behind the `PaymentSigner` seam. Solana reads the recent # blockhash through `tinywallet_crypto::rpc::Transport`. diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 7673c833..3795d70b 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -9,7 +9,7 @@ use tinystoragedrivers_types::{ #[path = "schema_payment.rs"] mod payment; pub(super) use payment::StoredPaymentStatus; -pub(crate) use payment::{LegacyPayment, StoredPayment}; +pub(crate) use payment::{StoredPayment, convert_legacy_payment}; /// Collection containing the single budget-hold document. pub(super) const BUDGETS_COLLECTION: &str = "wallet.budgets"; @@ -263,9 +263,9 @@ fn migrate_payments_stream( } let mut migrated = Vec::with_capacity(entries.len()); for entry in entries { - if let Ok(legacy) = serde_json::from_value::(entry) { + if let Ok(payment) = convert_legacy_payment(entry) { migrated.push( - serde_json::to_value(StoredPayment::from(legacy)) + serde_json::to_value(payment) .map_err(|error| StorageError::invalid_input(error.to_string()))?, ); } diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index 741f740f..44ebbd4b 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -1,217 +1,9 @@ -//! The payment record as it is stored, and the v1 shape it migrates from. +//! The owner-defined payment record and legacy converter live in the public +//! bus contract so host importers and the module migration share one mapping. -use serde::{Deserialize, Deserializer, Serialize}; - -/// Where a stored payment stands. The same four states, spelled the same way, -/// as the implementation's public status type, which converts to and from this. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum StoredPaymentStatus { - /// Signed and sent, not yet settled. - Pending, - /// A trusted settlement receipt confirms payment. - Settled, - /// A trusted result established that the payment did not settle. - Failed, - /// Refused before anything was signed. - Denied, -} - -/// One payment as stored in `wallet.payments`: `snake_case`, every instant an -/// epoch-millisecond `*_ms` field, no wrapper. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub(crate) struct StoredPayment { - /// Unique id of the attempt. - pub id: String, - /// The URL the payment bought access to. - pub url: String, - /// The asset paid in. - pub asset: String, - /// The amount in atomic units of `asset`. - pub amount_atomic: u64, - /// The amount formatted for people. - pub amount_display: String, - /// Who was paid. - pub recipient: String, - /// The network, in CAIP-2 form. - pub network: String, - /// The settlement transaction, once reported. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tx_signature: Option, - /// Where the payment stands. - pub status: StoredPaymentStatus, - /// When this state was written, in epoch milliseconds. - pub timestamp_ms: i64, - /// When an exported authorization becomes unusable, in epoch milliseconds. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_valid_until_ms: Option, - /// Solana's `lastValidBlockHeight` for the exported transaction. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub solana_last_valid_block_height: Option, - /// When the authorization was observed expired, in epoch milliseconds. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_expired_at_ms: Option, - /// The block height at which the expiry was observed. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_expiry_observed_height: Option, - /// The session that made the payment. - pub session_id: String, - /// The conversation thread, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thread_id: Option, - /// The budget hold this entry committed, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub committed_hold: Option, -} - -/// A v1 `x402.payments` entry: the camelCase wire record with RFC 3339 -/// instants, and the hold metadata beside it. -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct LegacyPayment { - id: String, - url: String, - asset: String, - amount_atomic: u64, - amount_display: String, - recipient: String, - network: String, - #[serde(default)] - tx_signature: Option, - status: StoredPaymentStatus, - #[serde(deserialize_with = "instant_ms")] - timestamp: i64, - #[serde(default, deserialize_with = "optional_instant_ms")] - authorization_valid_until: Option, - #[serde(default)] - solana_last_valid_block_height: Option, - #[serde(default, deserialize_with = "optional_instant_ms")] - authorization_expired_at: Option, - #[serde(default)] - authorization_expiry_observed_height: Option, - session_id: String, - #[serde(default)] - thread_id: Option, - #[serde(default, rename = "committed_hold")] - committed_hold: Option, -} - -impl From for StoredPayment { - fn from(legacy: LegacyPayment) -> Self { - Self { - id: legacy.id, - url: legacy.url, - asset: legacy.asset, - amount_atomic: legacy.amount_atomic, - amount_display: legacy.amount_display, - recipient: legacy.recipient, - network: legacy.network, - tx_signature: legacy.tx_signature, - status: legacy.status, - timestamp_ms: legacy.timestamp, - authorization_valid_until_ms: legacy.authorization_valid_until, - solana_last_valid_block_height: legacy.solana_last_valid_block_height, - authorization_expired_at_ms: legacy.authorization_expired_at, - authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, - session_id: legacy.session_id, - thread_id: legacy.thread_id, - committed_hold: legacy.committed_hold, - } - } -} - -fn instant_ms<'de, D: Deserializer<'de>>(deserializer: D) -> Result { - let text = String::deserialize(deserializer)?; - parse_rfc3339_ms(&text) - .ok_or_else(|| serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant"))) -} - -fn optional_instant_ms<'de, D: Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - Option::::deserialize(deserializer)? - .map(|text| { - parse_rfc3339_ms(&text).ok_or_else(|| { - serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant")) - }) - }) - .transpose() -} - -/// An RFC 3339 instant (`2026-03-15T12:00:00.250Z`, or with a `+hh:mm` -/// offset) as epoch milliseconds, by integer arithmetic only. Fractions finer -/// than a millisecond are truncated. -pub(super) fn parse_rfc3339_ms(text: &str) -> Option { - let bytes = text.as_bytes(); - let digits = |from: usize, len: usize| -> Option { - let part = bytes.get(from..from + len)?; - if !part.iter().all(u8::is_ascii_digit) { - return None; - } - part.iter() - .try_fold(0_i64, |n, d| Some(n * 10 + i64::from(d - b'0'))) - }; - let separator = |at: usize, want: &[u8]| bytes.get(at).is_some_and(|b| want.contains(b)); - if !(separator(4, b"-") - && separator(7, b"-") - && separator(10, b"Tt ") - && separator(13, b":") - && separator(16, b":")) - { - return None; - } - let (year, month, day) = (digits(0, 4)?, digits(5, 2)?, digits(8, 2)?); - let (hour, minute, second) = (digits(11, 2)?, digits(14, 2)?, digits(17, 2)?); - let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); - let days_in_month = match month { - 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, - 4 | 6 | 9 | 11 => 30, - 2 if leap_year => 29, - 2 => 28, - _ => return None, - }; - if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 60 { - return None; - } - let mut at = 19; - let mut millis = 0; - if bytes.get(at) == Some(&b'.') { - let start = at + 1; - let mut end = start; - while bytes.get(end).is_some_and(u8::is_ascii_digit) { - end += 1; - } - if end == start { - return None; - } - for (place, digit) in bytes[start..end].iter().take(3).enumerate() { - millis += i64::from(digit - b'0') * [100, 10, 1][place]; - } - at = end; - } - let offset_minutes = match bytes.get(at)? { - b'Z' | b'z' if at + 1 == bytes.len() => 0, - sign @ (b'+' | b'-') if at + 6 == bytes.len() && separator(at + 3, b":") => { - let hours = digits(at + 1, 2)?; - let minute_part = digits(at + 4, 2)?; - if hours > 23 || minute_part > 59 { - return None; - } - let minutes = hours * 60 + minute_part; - if *sign == b'-' { -minutes } else { minutes } - } - _ => return None, - }; - // Days from civil (Howard Hinnant's algorithm), proleptic Gregorian. - let y = if month <= 2 { year - 1 } else { year }; - let era = y.div_euclid(400); - let year_of_era = y - era * 400; - let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - let days = era * 146_097 + day_of_era - 719_468; - let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; - Some(seconds * 1_000 + millis) -} +pub(crate) use tinywallet_bus::storage::legacy_payments::{ + StoredPaymentRecord as StoredPayment, StoredPaymentStatus, convert_legacy_payment, +}; #[cfg(test)] #[path = "schema_payment_tests.rs"] diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs index 6c4f60b4..6fafe386 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -1,90 +1,27 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] use super::*; #[test] -fn rfc3339_milliseconds_handle_offsets_and_truncate_submillisecond_precision() { - assert_eq!( - parse_rfc3339_ms("2026-03-15T12:00:00.250Z"), - Some(1_773_576_000_250) - ); - assert_eq!( - parse_rfc3339_ms("2026-03-15t15:00:00.250000+03:00"), - Some(1_773_576_000_250) - ); - assert_eq!( - parse_rfc3339_ms("2026-03-15 12:00:00.9z"), - Some(1_773_576_000_900) - ); - assert_eq!( - parse_rfc3339_ms("2026-03-15T12:00:60Z"), - Some(1_773_576_060_000) - ); - assert!(parse_rfc3339_ms("2024-02-29T00:00:00Z").is_some()); -} +fn owner_migration_converter_emits_a_current_stored_payment_body() { + let payment = convert_legacy_payment(serde_json::json!({ + "id": "legacy-attempt", + "url": "https://merchant.example/item", + "asset": "USD", + "amountAtomic": 100, + "amountDisplay": "1.00", + "recipient": "recipient", + "network": "eip155:1", + "status": "settled", + "timestamp": "2026-03-15T15:00:00.250+03:00", + "sessionId": "session" + })) + .unwrap(); -#[test] -fn rfc3339_parser_rejects_malformed_fields_and_offsets() { - for value in [ - "2026-13-15T12:00:00Z", - "2026-03-00T12:00:00Z", - "2026-02-29T12:00:00Z", - "2024-02-31T12:00:00Z", - "2026-03-15T24:00:00Z", - "2026-03-15T12:60:00Z", - "2026-03-15T12:00:61Z", - "2026-03-15T12:00:00.", - "2026-03-15T12:00:00+01:0x", - "2026-03-15T12:00:00+24:00", - "2026-03-15T12:00:00+01:60", - "2026-03-15T12:00:00+01:00tail", - "2026/03/15T12:00:00Z", - ] { - assert_eq!(parse_rfc3339_ms(value), None, "{value}"); - } -} - -#[test] -fn legacy_payment_deserialization_defaults_absent_optional_fields_and_rejects_bad_instants() { - let base = serde_json::json!({ - "id":"id", "url":"https://example.test", "asset":"USD", "amountAtomic":1, - "amountDisplay":"1", "recipient":"r", "network":"n", "status":"pending", - "timestamp":"2026-03-15T12:00:00Z", "sessionId":"s" - }); - let legacy: LegacyPayment = serde_json::from_value(base.clone()).unwrap(); - let stored = StoredPayment::from(legacy); - assert_eq!(stored.timestamp_ms, 1_773_576_000_000); - assert_eq!(stored.tx_signature, None); - assert_eq!(stored.authorization_valid_until_ms, None); - assert_eq!(stored.solana_last_valid_block_height, None); - assert_eq!(stored.authorization_expired_at_ms, None); - assert_eq!(stored.thread_id, None); - let mut with_optionals = serde_json::json!({ - "id":"id", "url":"https://example.test", "asset":"USD", "amountAtomic":1, - "amountDisplay":"1", "recipient":"r", "network":"n", "status":"pending", - "timestamp":"2026-03-15T12:00:00Z", "sessionId":"s", - "authorizationValidUntil":"2026-03-15T12:00:01.9999Z", - "authorizationExpiredAt":"2026-03-15T12:00:02Z", - "solanaLastValidBlockHeight":42, "authorizationExpiryObservedHeight":43, - "threadId":"thread", "committed_hold":"hold", "txSignature":"sig" - }); - let parsed: LegacyPayment = serde_json::from_value(with_optionals.clone()).unwrap(); - let parsed = StoredPayment::from(parsed); - assert_eq!(parsed.authorization_valid_until_ms, Some(1_773_576_001_999)); - assert_eq!(parsed.authorization_expired_at_ms, Some(1_773_576_002_000)); - assert_eq!(parsed.solana_last_valid_block_height, Some(42)); - assert_eq!(parsed.authorization_expiry_observed_height, Some(43)); - assert_eq!(parsed.thread_id.as_deref(), Some("thread")); - assert_eq!(parsed.committed_hold.as_deref(), Some("hold")); - assert_eq!(parsed.tx_signature.as_deref(), Some("sig")); - with_optionals["authorizationValidUntil"] = serde_json::json!("tomorrow"); - assert!(serde_json::from_value::(with_optionals).is_err()); - assert!( - serde_json::from_value::({ - let mut bad = base; - bad["timestamp"] = serde_json::json!("yesterday"); - bad - }) - .is_err() - ); + let encoded = serde_json::to_value(&payment).unwrap(); + let decoded: StoredPayment = serde_json::from_value(encoded.clone()).unwrap(); + assert_eq!(decoded, payment); + assert_eq!(encoded["timestamp_ms"], 1_773_576_000_250_i64); + assert_eq!(encoded["status"], "settled"); + assert!(encoded.get("timestamp").is_none()); } From 86bc30e57623ee2bc8c8743b00cfbf4b1e0085b0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:54:52 +0300 Subject: [PATCH 25/51] test(storage): update legacy payment status assertions Updates the storage tests to use StoredPaymentStatus instead of PaymentStatus when asserting the status of converted legacy payments. This aligns the tests with the current enum definition. Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/storage_tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index 606197c3..f5054c54 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -1,6 +1,6 @@ #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -use super::legacy_payments::{PaymentStatus, convert_legacy_payment}; +use super::legacy_payments::{StoredPaymentStatus, convert_legacy_payment}; #[test] fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() { @@ -26,7 +26,7 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() let payment = convert_legacy_payment(legacy).unwrap(); assert_eq!(payment.id, "payment-1"); - assert_eq!(payment.status, PaymentStatus::Settled); + assert_eq!(payment.status, StoredPaymentStatus::Settled); assert_eq!(payment.timestamp_ms, 1_773_576_000_250); assert_eq!(payment.authorization_valid_until_ms, Some(1_773_576_001_999)); assert_eq!(payment.authorization_expired_at_ms, Some(1_773_576_002_000)); @@ -63,8 +63,8 @@ fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids let pending = convert_legacy_payment(row("pending", "2026-03-15T12:00:00Z")).unwrap(); let settled = convert_legacy_payment(row("settled", "2026-03-15T12:00:01Z")).unwrap(); assert_eq!(pending.id, settled.id); - assert_eq!(pending.status, PaymentStatus::Pending); - assert_eq!(settled.status, PaymentStatus::Settled); + assert_eq!(pending.status, StoredPaymentStatus::Pending); + assert_eq!(settled.status, StoredPaymentStatus::Settled); assert_eq!(pending.tx_signature, None); assert_eq!(pending.authorization_valid_until_ms, None); assert_eq!(pending.thread_id, None); From 2b7732886d8354a104b5d9855f2962263dd284a4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:56:06 +0300 Subject: [PATCH 26/51] refactor(storage): simplify rfc3339ms parsing The implementation of parse_rfc3339_ms was simplified by removing redundant calculations within the function body. This change also updates related tests to reflect the simplified structure. Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/storage/legacy_payments.rs | 1 - crates/tinywallet-bus/src/storage_tests.rs | 10 ++++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/tinywallet-bus/src/storage/legacy_payments.rs b/crates/tinywallet-bus/src/storage/legacy_payments.rs index 92e143b5..3467114c 100644 --- a/crates/tinywallet-bus/src/storage/legacy_payments.rs +++ b/crates/tinywallet-bus/src/storage/legacy_payments.rs @@ -227,4 +227,3 @@ fn parse_rfc3339_ms(text: &str) -> Option { let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; Some(seconds * 1_000 + millis) } - diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index f5054c54..8fc331fc 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -28,7 +28,10 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() assert_eq!(payment.id, "payment-1"); assert_eq!(payment.status, StoredPaymentStatus::Settled); assert_eq!(payment.timestamp_ms, 1_773_576_000_250); - assert_eq!(payment.authorization_valid_until_ms, Some(1_773_576_001_999)); + assert_eq!( + payment.authorization_valid_until_ms, + Some(1_773_576_001_999) + ); assert_eq!(payment.authorization_expired_at_ms, Some(1_773_576_002_000)); assert_eq!(payment.solana_last_valid_block_height, Some(42)); assert_eq!(payment.authorization_expiry_observed_height, Some(43)); @@ -39,7 +42,10 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() let current = serde_json::to_value(payment).unwrap(); assert_eq!(current["amount_atomic"], 12345); assert_eq!(current["timestamp_ms"], 1_773_576_000_250_i64); - assert_eq!(current["authorization_valid_until_ms"], 1_773_576_001_999_i64); + assert_eq!( + current["authorization_valid_until_ms"], + 1_773_576_001_999_i64 + ); assert_eq!(current["tx_signature"], "0xabc"); assert!(current.get("timestamp").is_none()); } From 727ad92313b58c8471d49a1aab4ab0993a427fad Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:57:51 +0300 Subject: [PATCH 27/51] refactor(storage): update legacy payment conversion to use struct input The legacy payment conversion functions are updated to accept the strongly typed `LegacyPayment` struct instead of a generic `serde_json::Value`. This change improves type safety across the bus and x402 modules, and the associated tests are updated to reflect this change in usage. Auto-committed-on: dragonfly --- .../src/storage/legacy_payments.rs | 87 ++++++++++++------- crates/tinywallet-bus/src/storage_tests.rs | 18 ++-- crates/tinywallet-x402/src/ledger/schema.rs | 5 +- .../src/ledger/schema_payment.rs | 3 +- .../src/ledger/schema_payment_tests.rs | 3 +- 5 files changed, 77 insertions(+), 39 deletions(-) diff --git a/crates/tinywallet-bus/src/storage/legacy_payments.rs b/crates/tinywallet-bus/src/storage/legacy_payments.rs index 3467114c..ea938b84 100644 --- a/crates/tinywallet-bus/src/storage/legacy_payments.rs +++ b/crates/tinywallet-bus/src/storage/legacy_payments.rs @@ -6,7 +6,6 @@ //! uses the same conversion during its own stream migration. use serde::{Deserialize, Deserializer, Serialize}; -use serde_json::Value; /// Payment lifecycle state in the canonical `wallet.payments` record. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -76,39 +75,69 @@ pub struct StoredPaymentRecord { /// retained. RFC 3339 instants become epoch milliseconds, truncating /// sub-millisecond precision. The caller owns source ordering and should keep /// repeated IDs because they can represent successive payment states. -pub fn convert_legacy_payment(value: Value) -> Result { - let legacy: LegacyPayment = serde_json::from_value(value)?; - Ok(legacy.into()) +pub fn convert_legacy_payment(legacy: LegacyPayment) -> StoredPaymentRecord { + legacy.into() } -#[derive(Debug, Deserialize)] +/// Typed row from the previous camelCase `x402.payments` stream. +/// +/// Deserialize the source row into this type before passing it to +/// [`convert_legacy_payment`]. Timestamp fields are parsed and normalized +/// during deserialization, so malformed or unsupported instants are rejected +/// before a canonical record is produced. +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] -struct LegacyPayment { - id: String, - url: String, - asset: String, - amount_atomic: u64, - amount_display: String, - recipient: String, - network: String, +pub struct LegacyPayment { + /// Stable ID shared by successive states of the same payment attempt. + pub id: String, + /// The URL the payment bought access to. + pub url: String, + /// The asset paid in. + pub asset: String, + /// Amount in atomic units. + pub amount_atomic: u64, + /// Human-readable amount. + pub amount_display: String, + /// Payment recipient. + pub recipient: String, + /// CAIP-2 network identifier. + pub network: String, #[serde(default)] - tx_signature: Option, - status: StoredPaymentStatus, - #[serde(deserialize_with = "instant_ms")] - timestamp: i64, - #[serde(default, deserialize_with = "optional_instant_ms")] - authorization_valid_until: Option, + /// Settlement transaction, if available. + pub tx_signature: Option, + /// Payment lifecycle state. + pub status: StoredPaymentStatus, + #[serde(rename = "timestamp", deserialize_with = "instant_ms")] + /// Timestamp of this state, normalized to epoch milliseconds. + pub timestamp_ms: i64, + #[serde( + default, + rename = "authorizationValidUntil", + deserialize_with = "optional_instant_ms" + )] + /// Authorization expiration, normalized to epoch milliseconds. + pub authorization_valid_until_ms: Option, #[serde(default)] - solana_last_valid_block_height: Option, - #[serde(default, deserialize_with = "optional_instant_ms")] - authorization_expired_at: Option, + /// Solana's `lastValidBlockHeight` for the exported transaction. + pub solana_last_valid_block_height: Option, + #[serde( + default, + rename = "authorizationExpiredAt", + deserialize_with = "optional_instant_ms" + )] + /// Time when the authorization was observed expired, in epoch milliseconds. + pub authorization_expired_at_ms: Option, #[serde(default)] - authorization_expiry_observed_height: Option, - session_id: String, + /// Block height at which expiry was observed. + pub authorization_expiry_observed_height: Option, + /// Session that initiated the payment. + pub session_id: String, #[serde(default)] - thread_id: Option, + /// Conversation thread that initiated the payment, if available. + pub thread_id: Option, #[serde(default, rename = "committed_hold")] - committed_hold: Option, + /// Budget hold committed by this payment, if available. + pub committed_hold: Option, } impl From for StoredPaymentRecord { @@ -123,10 +152,10 @@ impl From for StoredPaymentRecord { network: legacy.network, tx_signature: legacy.tx_signature, status: legacy.status, - timestamp_ms: legacy.timestamp, - authorization_valid_until_ms: legacy.authorization_valid_until, + timestamp_ms: legacy.timestamp_ms, + authorization_valid_until_ms: legacy.authorization_valid_until_ms, solana_last_valid_block_height: legacy.solana_last_valid_block_height, - authorization_expired_at_ms: legacy.authorization_expired_at, + authorization_expired_at_ms: legacy.authorization_expired_at_ms, authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, session_id: legacy.session_id, thread_id: legacy.thread_id, diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index 8fc331fc..98f8b80a 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -1,6 +1,12 @@ #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -use super::legacy_payments::{StoredPaymentStatus, convert_legacy_payment}; +use super::legacy_payments::{ + LegacyPayment, StoredPaymentStatus, convert_legacy_payment, +}; + +fn convert(value: serde_json::Value) -> Result { + serde_json::from_value::(value).map(convert_legacy_payment) +} #[test] fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() { @@ -24,7 +30,7 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() "committed_hold": "hold-1" }); - let payment = convert_legacy_payment(legacy).unwrap(); + let payment = convert(legacy).unwrap(); assert_eq!(payment.id, "payment-1"); assert_eq!(payment.status, StoredPaymentStatus::Settled); assert_eq!(payment.timestamp_ms, 1_773_576_000_250); @@ -66,8 +72,8 @@ fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids "sessionId": "session" }) }; - let pending = convert_legacy_payment(row("pending", "2026-03-15T12:00:00Z")).unwrap(); - let settled = convert_legacy_payment(row("settled", "2026-03-15T12:00:01Z")).unwrap(); + let pending = convert(row("pending", "2026-03-15T12:00:00Z")).unwrap(); + let settled = convert(row("settled", "2026-03-15T12:00:01Z")).unwrap(); assert_eq!(pending.id, settled.id); assert_eq!(pending.status, StoredPaymentStatus::Pending); assert_eq!(settled.status, StoredPaymentStatus::Settled); @@ -104,7 +110,7 @@ fn legacy_payment_conversion_rejects_malformed_required_and_optional_data() { ] { let mut malformed = base.clone(); malformed[field] = value; - assert!(convert_legacy_payment(malformed).is_err(), "field {field}"); + assert!(convert(malformed).is_err(), "field {field}"); } - assert!(convert_legacy_payment(serde_json::json!([])).is_err()); + assert!(convert(serde_json::json!([])).is_err()); } diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 3795d70b..466c86f8 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -9,7 +9,7 @@ use tinystoragedrivers_types::{ #[path = "schema_payment.rs"] mod payment; pub(super) use payment::StoredPaymentStatus; -pub(crate) use payment::{StoredPayment, convert_legacy_payment}; +pub(crate) use payment::{LegacyPayment, StoredPayment, convert_legacy_payment}; /// Collection containing the single budget-hold document. pub(super) const BUDGETS_COLLECTION: &str = "wallet.budgets"; @@ -263,7 +263,8 @@ fn migrate_payments_stream( } let mut migrated = Vec::with_capacity(entries.len()); for entry in entries { - if let Ok(payment) = convert_legacy_payment(entry) { + if let Ok(legacy) = serde_json::from_value::(entry) { + let payment = convert_legacy_payment(legacy); migrated.push( serde_json::to_value(payment) .map_err(|error| StorageError::invalid_input(error.to_string()))?, diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index 44ebbd4b..99acd57f 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -2,7 +2,8 @@ //! bus contract so host importers and the module migration share one mapping. pub(crate) use tinywallet_bus::storage::legacy_payments::{ - StoredPaymentRecord as StoredPayment, StoredPaymentStatus, convert_legacy_payment, + LegacyPayment, StoredPaymentRecord as StoredPayment, StoredPaymentStatus, + convert_legacy_payment, }; #[cfg(test)] diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs index 6fafe386..0d71fe80 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -4,7 +4,7 @@ use super::*; #[test] fn owner_migration_converter_emits_a_current_stored_payment_body() { - let payment = convert_legacy_payment(serde_json::json!({ + let legacy: LegacyPayment = serde_json::from_value(serde_json::json!({ "id": "legacy-attempt", "url": "https://merchant.example/item", "asset": "USD", @@ -17,6 +17,7 @@ fn owner_migration_converter_emits_a_current_stored_payment_body() { "sessionId": "session" })) .unwrap(); + let payment = convert_legacy_payment(legacy); let encoded = serde_json::to_value(&payment).unwrap(); let decoded: StoredPayment = serde_json::from_value(encoded.clone()).unwrap(); From b0b00c571ef3993318ab9a0dbeacb6c19045ef15 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:58:36 +0300 Subject: [PATCH 28/51] test(storage): adjust storage test imports and formatting This change refactors the import statements and adjusts the function signature formatting in the storage tests to improve readability. No functional change is introduced to the tests. Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/storage_tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index 98f8b80a..044ca11d 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -1,10 +1,10 @@ #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -use super::legacy_payments::{ - LegacyPayment, StoredPaymentStatus, convert_legacy_payment, -}; +use super::legacy_payments::{LegacyPayment, StoredPaymentStatus, convert_legacy_payment}; -fn convert(value: serde_json::Value) -> Result { +fn convert( + value: serde_json::Value, +) -> Result { serde_json::from_value::(value).map(convert_legacy_payment) } From b022bc40dedac0138bf026bf548a7b91916f32f3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 15:01:14 +0300 Subject: [PATCH 29/51] refactor(storage): add must_use to convert_legacy_payment This adds a must_use attribute to the convert_legacy_payment function to signal that the returned StoredPaymentRecord should be used. This helps prevent accidental discarding of the payment record after conversion. Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/storage/legacy_payments.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/tinywallet-bus/src/storage/legacy_payments.rs b/crates/tinywallet-bus/src/storage/legacy_payments.rs index ea938b84..f83c947e 100644 --- a/crates/tinywallet-bus/src/storage/legacy_payments.rs +++ b/crates/tinywallet-bus/src/storage/legacy_payments.rs @@ -75,6 +75,7 @@ pub struct StoredPaymentRecord { /// retained. RFC 3339 instants become epoch milliseconds, truncating /// sub-millisecond precision. The caller owns source ordering and should keep /// repeated IDs because they can represent successive payment states. +#[must_use] pub fn convert_legacy_payment(legacy: LegacyPayment) -> StoredPaymentRecord { legacy.into() } From 156f81be87975d2ab71c28d9ee88418886935d33 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 15:12:43 +0300 Subject: [PATCH 30/51] test(storage): add timestamp edge case tests for legacy payment conversion Adds a new test case to verify that the legacy payment conversion correctly handles various RFC3339 timestamp formats and edge cases, including leap years and out-of-range values. This ensures robust parsing of time data from legacy records. Auto-committed-on: dragonfly --- crates/tinywallet-bus/src/storage_tests.rs | 44 +++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index 044ca11d..b66a90e6 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -1,6 +1,6 @@ #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -use super::legacy_payments::{LegacyPayment, StoredPaymentStatus, convert_legacy_payment}; +use super::legacy_payments::{convert_legacy_payment, LegacyPayment, StoredPaymentStatus}; fn convert( value: serde_json::Value, @@ -56,6 +56,33 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() assert!(current.get("timestamp").is_none()); } +#[test] +fn legacy_payment_conversion_preserves_rfc3339_timestamp_edge_cases() { + let row = |timestamp: &str| { + serde_json::json!({ + "id": "payment-time", + "url": "https://merchant.example/item", + "asset": "USD", + "amountAtomic": 1, + "amountDisplay": "1", + "recipient": "recipient", + "network": "eip155:1", + "status": "pending", + "timestamp": timestamp, + "sessionId": "session" + }) + }; + + for (timestamp, expected_ms) in [ + ("2026-03-15t15:00:00.250000+03:00", 1_773_576_000_250), + ("2026-03-15 12:00:00.9z", 1_773_576_000_900), + ("2026-03-15T12:00:60Z", 1_773_576_060_000), + ] { + assert_eq!(convert(row(timestamp)).unwrap().timestamp_ms, expected_ms); + } + assert!(convert(row("2024-02-29T00:00:00Z")).is_ok()); +} + #[test] fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids() { let row = |status: &str, timestamp: &str| { @@ -100,7 +127,22 @@ fn legacy_payment_conversion_rejects_malformed_required_and_optional_data() { for (field, value) in [ ("timestamp", serde_json::json!("yesterday")), + ("timestamp", serde_json::json!("2026-13-15T12:00:00Z")), + ("timestamp", serde_json::json!("2026-03-00T12:00:00Z")), + ("timestamp", serde_json::json!("2026-02-29T12:00:00Z")), + ("timestamp", serde_json::json!("2024-02-31T12:00:00Z")), + ("timestamp", serde_json::json!("2026-03-15T24:00:00Z")), + ("timestamp", serde_json::json!("2026-03-15T12:60:00Z")), + ("timestamp", serde_json::json!("2026-03-15T12:00:61Z")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00.")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00+01:0x")), ("timestamp", serde_json::json!("2026-03-15T12:00:00+24:00")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00+01:60")), + ( + "timestamp", + serde_json::json!("2026-03-15T12:00:00+01:00tail"), + ), + ("timestamp", serde_json::json!("2026/03/15T12:00:00Z")), ( "authorizationValidUntil", serde_json::json!("not-a-timestamp"), From d9947761f886f7c4c84d8450ba1cd0c406cf93dc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:16:13 +0000 Subject: [PATCH 31/51] chore(deps): pin wallet to canonical TSD v2.1 Co-authored-by: Medulla --- Cargo.lock | 131 +++++++++------------ Cargo.toml | 6 +- crates/tinywallet-bus/src/storage_tests.rs | 2 +- crates/tinywallet-module/Cargo.toml | 2 +- crates/tinywallet-x402/Cargo.toml | 2 +- deny.toml | 1 - scripts/check-bus-boundaries.py | 28 +++-- scripts/check_bus_boundaries_tests.py | 41 +++++-- vendor/tinybus | 2 +- 9 files changed, 119 insertions(+), 96 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 78fc3f1b..2e3ed79c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,15 +23,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arrayvec" version = "0.7.8" @@ -295,6 +286,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chrono" version = "0.4.45" @@ -424,12 +421,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-utils" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" - [[package]] name = "crypto-bigint" version = "0.5.5" @@ -528,17 +519,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "digest" version = "0.10.7" @@ -1298,6 +1278,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1954,7 +1946,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", @@ -2002,7 +1994,7 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "flate2", @@ -2023,7 +2015,7 @@ dependencies = [ [[package]] name = "tinybus-macros" -version = "0.1.5" +version = "0.1.6" dependencies = [ "proc-macro2", "quote", @@ -2032,7 +2024,7 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "serde", @@ -2044,8 +2036,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-api" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "bytes", @@ -2058,8 +2050,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-blob" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "bytes", @@ -2072,8 +2064,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-bus" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "serde", "serde_json", @@ -2083,8 +2075,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-busproxy" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "bytes", @@ -2101,25 +2093,27 @@ dependencies = [ [[package]] name = "tinystoragedrivers-connect" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "rusqlite", + "serde_json", "tinystoragedrivers-types", "tokio", + "zstd", ] [[package]] name = "tinystoragedrivers-document" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "data-encoding", "rusqlite", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "tinystoragedrivers-api", "tinystoragedrivers-connect", "tinystoragedrivers-types", @@ -2129,8 +2123,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-kv" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "serde", @@ -2141,14 +2135,14 @@ dependencies = [ [[package]] name = "tinystoragedrivers-queue" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "data-encoding", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "tinystoragedrivers-api", "tinystoragedrivers-types", "tokio", @@ -2157,8 +2151,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-secrets" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "tinystoragedrivers-api", @@ -2168,8 +2162,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-testkit" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "bytes", @@ -2189,8 +2183,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-types" -version = "2.0.1" -source = "git+https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#e3224a8262193e7466b230a59ef1c4769e44bf02" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "serde", "serde_json", @@ -2522,6 +2516,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" + [[package]] name = "typenum" version = "1.20.1" @@ -3023,19 +3023,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.20", - "zopfli", + "nix", + "typed-path", ] [[package]] @@ -3044,18 +3041,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zstd" version = "0.13.3" diff --git a/Cargo.toml b/Cargo.toml index 2914f8ba..ce0678a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,10 +60,10 @@ resolver = "3" # tinytools gitlink tinyagents pins. tinytools = { git = "https://github.com/tinyhumansai/tinytools", rev = "bd60b9b52f1998b4483b9cf107a72d3338e672f8" } # Runtime-neutral contracts shared with the host's stable TSD release. -tinystoragedrivers-types = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } -tinystoragedrivers-api = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } +tinystoragedrivers-types = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +tinystoragedrivers-api = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } # The module connects to host-owned storage through the TinyBus adapter. -tinystoragedrivers-busproxy = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } +tinystoragedrivers-busproxy = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } [dependencies] # The wire contract. Split out so a host that has moved signing into the diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index b66a90e6..e37a618d 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -1,6 +1,6 @@ #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -use super::legacy_payments::{convert_legacy_payment, LegacyPayment, StoredPaymentStatus}; +use super::legacy_payments::{LegacyPayment, StoredPaymentStatus, convert_legacy_payment}; fn convert( value: serde_json::Value, diff --git a/crates/tinywallet-module/Cargo.toml b/crates/tinywallet-module/Cargo.toml index c224db4e..5da2387f 100644 --- a/crates/tinywallet-module/Cargo.toml +++ b/crates/tinywallet-module/Cargo.toml @@ -100,7 +100,7 @@ linked = ["static-link"] workspace = true [dev-dependencies] -tinystoragedrivers-testkit = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } +tinystoragedrivers-testkit = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } # Encodes and decodes the Solana transaction fixtures in native tests. base64 = "0.23" # The native lifecycle fixture stages and hashes the actual cdylib to attest it. diff --git a/crates/tinywallet-x402/Cargo.toml b/crates/tinywallet-x402/Cargo.toml index 5a0b9b6a..5c24e58a 100644 --- a/crates/tinywallet-x402/Cargo.toml +++ b/crates/tinywallet-x402/Cargo.toml @@ -93,7 +93,7 @@ tinywallet = { path = "../..", default-features = false, features = ["key", "sol # signer from an EIP-3009 signature in tests. k256 = { version = "0.13", default-features = false, features = ["ecdsa"] } ed25519-dalek = { version = "2", default-features = false, features = ["std"] } -tinystoragedrivers-testkit = { version = "2.0.1", git = "https://github.com/senamakel/tinystoragedrivers", tag = "v2.0.1" } +tinystoragedrivers-testkit = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } [features] default = ["wire"] diff --git a/deny.toml b/deny.toml index 7783337c..d7b14c3d 100644 --- a/deny.toml +++ b/deny.toml @@ -57,5 +57,4 @@ allow-registry = ["https://github.com/rust-lang/crates.io-index"] allow-git = [ "https://github.com/tinyhumansai/tinytools", "https://github.com/tinyhumansai/tinystoragedrivers", - "https://github.com/senamakel/tinystoragedrivers", ] diff --git a/scripts/check-bus-boundaries.py b/scripts/check-bus-boundaries.py index e9c692d1..dddd628a 100644 --- a/scripts/check-bus-boundaries.py +++ b/scripts/check-bus-boundaries.py @@ -11,7 +11,8 @@ } REGISTRY = "registry+https://github.com/rust-lang/crates.io-index" TSD_TYPES = "tinystoragedrivers-types" -TSD_TYPES_SOURCE = "https://github.com/senamakel/tinystoragedrivers?tag=v2.0.1#" +TSD_TYPES_REV = "05eaada962decbab33bafa4763d2bd1a67f6b456" +TSD_TYPES_SOURCE = f"https://github.com/tinyhumansai/tinystoragedrivers?rev={TSD_TYPES_REV}#" # Chain, key and crypto implementations never enter the bus closure, not even # through transitive dependencies. @@ -36,13 +37,26 @@ def forbidden(name): return normalized in FORBIDDEN_NAMES or normalized.startswith(FORBIDDEN_PREFIXES) +def is_canonical_tsd_source(source, *, require_full_hash=False): + """Whether Cargo resolved TSD types from the canonical pinned revision.""" + if not isinstance(source, str): + return False + resolved = source.removeprefix("git+") + if not resolved.startswith(TSD_TYPES_SOURCE): + return False + commit = resolved[len(TSD_TYPES_SOURCE):] + minimum_length = len(TSD_TYPES_REV) if require_full_hash else 8 + return ( + minimum_length <= len(commit) <= len(TSD_TYPES_REV) + and TSD_TYPES_REV.startswith(commit) + ) + + def dependency_allowed(name, source): """Whether a bus dependency is registry vocabulary or the pinned TSD DTO crate.""" if name in ALLOWED and source == REGISTRY: return True - if not isinstance(source, str): - return False - return name == TSD_TYPES and source.removeprefix("git+").startswith(TSD_TYPES_SOURCE) + return name == TSD_TYPES and is_canonical_tsd_source(source, require_full_hash=True) def audit(metadata): @@ -73,8 +87,8 @@ def tree_packages(feature=None): """(name, source) of every normal/build dependency of the bus alone. `cargo tree -p` resolves features for the selected package only, so a - workspace sibling that enables `storage` cannot leak into the default run - the way it does in `cargo metadata`. + workspace sibling's dependencies cannot leak into the bus closure the way + they do in full-workspace metadata. """ command = ["cargo", "tree", "-p", "tinywallet-bus", "-e", "normal,build", "--prefix", "none", "-f", "{p}"] if feature: @@ -101,7 +115,7 @@ def audit_tree(packages): continue if name in ALLOWED and not source: continue - if name == TSD_TYPES and source.removeprefix("git+").startswith(TSD_TYPES_SOURCE): + if name == TSD_TYPES and is_canonical_tsd_source(source): continue violations.append(f"tinywallet-bus -> {name} ({source or 'registry'})") return violations diff --git a/scripts/check_bus_boundaries_tests.py b/scripts/check_bus_boundaries_tests.py index 4704b31e..e3dfab34 100644 --- a/scripts/check_bus_boundaries_tests.py +++ b/scripts/check_bus_boundaries_tests.py @@ -26,24 +26,49 @@ def test_dev_dependencies_are_exempt(self): def test_local_package_cannot_impersonate_serde(self): self.assertTrue(boundary.audit(metadata("serde", source=None))) - def test_pinned_tsd_types_git_source_is_allowed(self): + def test_canonical_pinned_tsd_types_git_source_is_allowed(self): self.assertEqual( - boundary.audit(metadata(boundary.TSD_TYPES, source="git+" + boundary.TSD_TYPES_SOURCE + "e3224a8")), + boundary.audit( + metadata( + boundary.TSD_TYPES, + source="git+" + boundary.TSD_TYPES_SOURCE + + "05eaada962decbab33bafa4763d2bd1a67f6b456", + ) + ), [], ) - def test_unapproved_tsd_types_source_is_rejected(self): + def test_fork_tsd_types_source_is_rejected(self): self.assertTrue( - boundary.audit(metadata(boundary.TSD_TYPES, source="git+https://github.com/attacker/tinystoragedrivers#deadbeef")) + boundary.audit( + metadata( + boundary.TSD_TYPES, + source="git+https://github.com/senamakel/tinystoragedrivers" + "?tag=v2.1.0#3332061434c01872b0161191268166c12563af87", + ) + ) ) - def test_tree_allows_only_the_v201_fork_source_for_tsd_types(self): + def test_tree_allows_only_the_canonical_pinned_source_for_tsd_types(self): self.assertEqual( - boundary.audit_tree([(boundary.TSD_TYPES, boundary.TSD_TYPES_SOURCE + "e3224a8")]), + boundary.audit_tree([(boundary.TSD_TYPES, boundary.TSD_TYPES_SOURCE + "05eaada962decbab33bafa4763d2bd1a67f6b456")]), [], ) self.assertTrue( - boundary.audit_tree([(boundary.TSD_TYPES, "https://github.com/tinyhumansai/tinystoragedrivers#v2")]) + boundary.audit_tree( + [(boundary.TSD_TYPES, boundary.TSD_TYPES_SOURCE + "deadbeef")] + ) + ) + self.assertTrue( + boundary.audit_tree( + [ + ( + boundary.TSD_TYPES, + "https://github.com/senamakel/tinystoragedrivers" + "?tag=v2.1.0#3332061434c01872b0161191268166c12563af87", + ) + ] + ) ) @@ -52,7 +77,7 @@ def test_versioned_cargo_tree_lines_are_checked_by_package_name(self): output = """\ tinywallet-module v0.24.1 (/work/tinywallet) rusqlite v0.40.2 (registry+https://github.com/rust-lang/crates.io-index) -tinystoragedrivers-api v2.0.0 (https://github.com/senamakel/tinystoragedrivers) +tinystoragedrivers-api v2.1.0 (https://github.com/tinyhumansai/tinystoragedrivers) """ names = boundary.tree_package_names(output) self.assertEqual( diff --git a/vendor/tinybus b/vendor/tinybus index 1f33d1be..11b0a728 160000 --- a/vendor/tinybus +++ b/vendor/tinybus @@ -1 +1 @@ -Subproject commit 1f33d1be1901a2d44bfe674cd7cf294cf3848821 +Subproject commit 11b0a728e62a5b7ae213c1cf6366f82b9e1a65de From 64f53db04619436a513a0e1c8954c484f1348e2b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:40:40 +0000 Subject: [PATCH 32/51] test(storage): qualify legacy payment imports in tests Switch the test module to import the parent module and reference the legacy payment types through it, and add a module doc comment describing the conversion and storage contract under test. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-bus/src/storage_tests.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index e37a618d..a776ce80 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -1,11 +1,14 @@ +//! Tests for the legacy x402 payment conversion and storage contract. + #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -use super::legacy_payments::{LegacyPayment, StoredPaymentStatus, convert_legacy_payment}; +use super::*; fn convert( value: serde_json::Value, -) -> Result { - serde_json::from_value::(value).map(convert_legacy_payment) +) -> Result { + serde_json::from_value::(value) + .map(legacy_payments::convert_legacy_payment) } #[test] @@ -32,7 +35,7 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() let payment = convert(legacy).unwrap(); assert_eq!(payment.id, "payment-1"); - assert_eq!(payment.status, StoredPaymentStatus::Settled); + assert_eq!(payment.status, legacy_payments::StoredPaymentStatus::Settled); assert_eq!(payment.timestamp_ms, 1_773_576_000_250); assert_eq!( payment.authorization_valid_until_ms, @@ -102,8 +105,8 @@ fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids let pending = convert(row("pending", "2026-03-15T12:00:00Z")).unwrap(); let settled = convert(row("settled", "2026-03-15T12:00:01Z")).unwrap(); assert_eq!(pending.id, settled.id); - assert_eq!(pending.status, StoredPaymentStatus::Pending); - assert_eq!(settled.status, StoredPaymentStatus::Settled); + assert_eq!(pending.status, legacy_payments::StoredPaymentStatus::Pending); + assert_eq!(settled.status, legacy_payments::StoredPaymentStatus::Settled); assert_eq!(pending.tx_signature, None); assert_eq!(pending.authorization_valid_until_ms, None); assert_eq!(pending.thread_id, None); From 1c6dc4caca40508810e98d1bdf317bd71ad105e0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:41:09 +0000 Subject: [PATCH 33/51] docs: add comments explaining test dependencies and modules Document why the testkit dev-dependency is needed in the module and x402 crates, and add module-level docs to the blocking and schema payment test files so their purpose is clear at a glance. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-module/Cargo.toml | 1 + crates/tinywallet-x402/Cargo.toml | 1 + crates/tinywallet-x402/src/ledger/blocking_tests.rs | 2 ++ crates/tinywallet-x402/src/ledger/schema_payment_tests.rs | 2 ++ 4 files changed, 6 insertions(+) diff --git a/crates/tinywallet-module/Cargo.toml b/crates/tinywallet-module/Cargo.toml index 5da2387f..6c6023af 100644 --- a/crates/tinywallet-module/Cargo.toml +++ b/crates/tinywallet-module/Cargo.toml @@ -100,6 +100,7 @@ linked = ["static-link"] workspace = true [dev-dependencies] +# Testkit-backed module storage fixtures exercise the host's v2 storage ports. tinystoragedrivers-testkit = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } # Encodes and decodes the Solana transaction fixtures in native tests. base64 = "0.23" diff --git a/crates/tinywallet-x402/Cargo.toml b/crates/tinywallet-x402/Cargo.toml index 5c24e58a..20054d2e 100644 --- a/crates/tinywallet-x402/Cargo.toml +++ b/crates/tinywallet-x402/Cargo.toml @@ -93,6 +93,7 @@ tinywallet = { path = "../..", default-features = false, features = ["key", "sol # signer from an EIP-3009 signature in tests. k256 = { version = "0.13", default-features = false, features = ["ecdsa"] } ed25519-dalek = { version = "2", default-features = false, features = ["std"] } +# Native ledger migration tests use an in-memory v2 storage implementation. tinystoragedrivers-testkit = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } [features] diff --git a/crates/tinywallet-x402/src/ledger/blocking_tests.rs b/crates/tinywallet-x402/src/ledger/blocking_tests.rs index e3248e63..9fa808de 100644 --- a/crates/tinywallet-x402/src/ledger/blocking_tests.rs +++ b/crates/tinywallet-x402/src/ledger/blocking_tests.rs @@ -1,3 +1,5 @@ +//! Tests for the dedicated runtime used by blocking x402 callers. + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use super::*; diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs index 0d71fe80..016a98a2 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -1,3 +1,5 @@ +//! Tests for the x402 owner's conversion of legacy payment records. + #![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] use super::*; From dc1363a6e5e92a2e85f3655eef5e21c0b79e0515 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:41:28 +0000 Subject: [PATCH 34/51] style(tinywallet-bus): wrap long assertions in storage tests Reformatted three assert_eq! calls in the legacy payment conversion tests so their arguments span multiple lines, matching rustfmt's line width. No test behaviour changed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-bus/src/storage_tests.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs index a776ce80..0e10aef7 100644 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ b/crates/tinywallet-bus/src/storage_tests.rs @@ -35,7 +35,10 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() let payment = convert(legacy).unwrap(); assert_eq!(payment.id, "payment-1"); - assert_eq!(payment.status, legacy_payments::StoredPaymentStatus::Settled); + assert_eq!( + payment.status, + legacy_payments::StoredPaymentStatus::Settled + ); assert_eq!(payment.timestamp_ms, 1_773_576_000_250); assert_eq!( payment.authorization_valid_until_ms, @@ -105,8 +108,14 @@ fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids let pending = convert(row("pending", "2026-03-15T12:00:00Z")).unwrap(); let settled = convert(row("settled", "2026-03-15T12:00:01Z")).unwrap(); assert_eq!(pending.id, settled.id); - assert_eq!(pending.status, legacy_payments::StoredPaymentStatus::Pending); - assert_eq!(settled.status, legacy_payments::StoredPaymentStatus::Settled); + assert_eq!( + pending.status, + legacy_payments::StoredPaymentStatus::Pending + ); + assert_eq!( + settled.status, + legacy_payments::StoredPaymentStatus::Settled + ); assert_eq!(pending.tx_signature, None); assert_eq!(pending.authorization_valid_until_ms, None); assert_eq!(pending.thread_id, None); From a143d443aaf03c6150b8f6321814ea05d15d99b2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:41:59 +0000 Subject: [PATCH 35/51] refactor(storage): move payment record types into the x402 ledger schema The canonical `wallet.payments` record types and their conversion from the previous `x402.payments` rows now live in the x402 ledger schema instead of the bus storage module, so the schema that owns the stream also owns its record shape. The bus storage module keeps the collection names and re-exports the types, and the tests moved along with the code. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-bus/src/storage.rs | 65 ++++- .../src/storage/legacy_payments.rs | 259 ------------------ crates/tinywallet-bus/src/storage_tests.rs | 170 ------------ .../src/ledger/schema_payment.rs | 203 +++++++++++++- .../src/ledger/schema_payment_tests.rs | 165 +++++++++++ 5 files changed, 420 insertions(+), 442 deletions(-) delete mode 100644 crates/tinywallet-bus/src/storage/legacy_payments.rs delete mode 100644 crates/tinywallet-bus/src/storage_tests.rs diff --git a/crates/tinywallet-bus/src/storage.rs b/crates/tinywallet-bus/src/storage.rs index 6463d8d5..8def014e 100644 --- a/crates/tinywallet-bus/src/storage.rs +++ b/crates/tinywallet-bus/src/storage.rs @@ -2,10 +2,67 @@ use tinystoragedrivers_types::CollectionSpec; -/// Pure conversion of the previous x402 payment stream into the current -/// `wallet.payments` record contract. -#[cfg(feature = "wire")] -pub mod legacy_payments; +/// Payment lifecycle state in the canonical `wallet.payments` record. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StoredPaymentStatus { + /// Signed and sent, not yet settled. + Pending, + /// A trusted settlement receipt confirms payment. + Settled, + /// A trusted result established that the payment did not settle. + Failed, + /// Refused before anything was signed. + Denied, +} + +/// Canonical body stored in the `wallet.payments` stream. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredPaymentRecord { + /// Unique id of the attempt. A status change may produce another row with + /// the same id; callers must preserve stream order and must not deduplicate. + pub id: String, + /// The URL the payment bought access to. + pub url: String, + /// The asset paid in. + pub asset: String, + /// The amount in atomic units of `asset`. + pub amount_atomic: u64, + /// The amount formatted for people. + pub amount_display: String, + /// Who was paid. + pub recipient: String, + /// The network, in CAIP-2 form. + pub network: String, + /// The settlement transaction, once reported. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tx_signature: Option, + /// Where the payment stands. + pub status: StoredPaymentStatus, + /// When this state was written, in epoch milliseconds. + pub timestamp_ms: i64, + /// When an exported authorization becomes unusable, in epoch milliseconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_valid_until_ms: Option, + /// Solana's `lastValidBlockHeight` for the exported transaction. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub solana_last_valid_block_height: Option, + /// When the authorization was observed expired, in epoch milliseconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_expired_at_ms: Option, + /// The block height at which the expiry was observed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authorization_expiry_observed_height: Option, + /// The session that made the payment. + pub session_id: String, + /// The conversation thread, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thread_id: Option, + /// The budget hold this entry committed, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub committed_hold: Option, +} + /// Collection names used by the wallet's persistent module storage. /// diff --git a/crates/tinywallet-bus/src/storage/legacy_payments.rs b/crates/tinywallet-bus/src/storage/legacy_payments.rs deleted file mode 100644 index f83c947e..00000000 --- a/crates/tinywallet-bus/src/storage/legacy_payments.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Owner-defined conversion from the previous `x402.payments` row to the -//! canonical `wallet.payments` storage record. -//! -//! Hosts may use this pure converter while importing a legacy source. It does -//! not read storage or decide which rows to import; the wallet implementation -//! uses the same conversion during its own stream migration. - -use serde::{Deserialize, Deserializer, Serialize}; - -/// Payment lifecycle state in the canonical `wallet.payments` record. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum StoredPaymentStatus { - /// Signed and sent, not yet settled. - Pending, - /// A trusted settlement receipt confirms payment. - Settled, - /// A trusted result established that the payment did not settle. - Failed, - /// Refused before anything was signed. - Denied, -} - -/// Canonical body stored in the `wallet.payments` stream. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct StoredPaymentRecord { - /// Unique id of the attempt. A status change may produce another row with - /// the same id; callers must preserve stream order and must not deduplicate. - pub id: String, - /// The URL the payment bought access to. - pub url: String, - /// The asset paid in. - pub asset: String, - /// The amount in atomic units of `asset`. - pub amount_atomic: u64, - /// The amount formatted for people. - pub amount_display: String, - /// Who was paid. - pub recipient: String, - /// The network, in CAIP-2 form. - pub network: String, - /// The settlement transaction, once reported. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tx_signature: Option, - /// Where the payment stands. - pub status: StoredPaymentStatus, - /// When this state was written, in epoch milliseconds. - pub timestamp_ms: i64, - /// When an exported authorization becomes unusable, in epoch milliseconds. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_valid_until_ms: Option, - /// Solana's `lastValidBlockHeight` for the exported transaction. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub solana_last_valid_block_height: Option, - /// When the authorization was observed expired, in epoch milliseconds. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_expired_at_ms: Option, - /// The block height at which the expiry was observed. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub authorization_expiry_observed_height: Option, - /// The session that made the payment. - pub session_id: String, - /// The conversation thread, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thread_id: Option, - /// The budget hold this entry committed, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub committed_hold: Option, -} - -/// Convert one previous camelCase `x402.payments` body to the current typed -/// `wallet.payments` storage contract. -/// -/// The legacy row's ID and all optional payment and authorization data are -/// retained. RFC 3339 instants become epoch milliseconds, truncating -/// sub-millisecond precision. The caller owns source ordering and should keep -/// repeated IDs because they can represent successive payment states. -#[must_use] -pub fn convert_legacy_payment(legacy: LegacyPayment) -> StoredPaymentRecord { - legacy.into() -} - -/// Typed row from the previous camelCase `x402.payments` stream. -/// -/// Deserialize the source row into this type before passing it to -/// [`convert_legacy_payment`]. Timestamp fields are parsed and normalized -/// during deserialization, so malformed or unsupported instants are rejected -/// before a canonical record is produced. -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LegacyPayment { - /// Stable ID shared by successive states of the same payment attempt. - pub id: String, - /// The URL the payment bought access to. - pub url: String, - /// The asset paid in. - pub asset: String, - /// Amount in atomic units. - pub amount_atomic: u64, - /// Human-readable amount. - pub amount_display: String, - /// Payment recipient. - pub recipient: String, - /// CAIP-2 network identifier. - pub network: String, - #[serde(default)] - /// Settlement transaction, if available. - pub tx_signature: Option, - /// Payment lifecycle state. - pub status: StoredPaymentStatus, - #[serde(rename = "timestamp", deserialize_with = "instant_ms")] - /// Timestamp of this state, normalized to epoch milliseconds. - pub timestamp_ms: i64, - #[serde( - default, - rename = "authorizationValidUntil", - deserialize_with = "optional_instant_ms" - )] - /// Authorization expiration, normalized to epoch milliseconds. - pub authorization_valid_until_ms: Option, - #[serde(default)] - /// Solana's `lastValidBlockHeight` for the exported transaction. - pub solana_last_valid_block_height: Option, - #[serde( - default, - rename = "authorizationExpiredAt", - deserialize_with = "optional_instant_ms" - )] - /// Time when the authorization was observed expired, in epoch milliseconds. - pub authorization_expired_at_ms: Option, - #[serde(default)] - /// Block height at which expiry was observed. - pub authorization_expiry_observed_height: Option, - /// Session that initiated the payment. - pub session_id: String, - #[serde(default)] - /// Conversation thread that initiated the payment, if available. - pub thread_id: Option, - #[serde(default, rename = "committed_hold")] - /// Budget hold committed by this payment, if available. - pub committed_hold: Option, -} - -impl From for StoredPaymentRecord { - fn from(legacy: LegacyPayment) -> Self { - Self { - id: legacy.id, - url: legacy.url, - asset: legacy.asset, - amount_atomic: legacy.amount_atomic, - amount_display: legacy.amount_display, - recipient: legacy.recipient, - network: legacy.network, - tx_signature: legacy.tx_signature, - status: legacy.status, - timestamp_ms: legacy.timestamp_ms, - authorization_valid_until_ms: legacy.authorization_valid_until_ms, - solana_last_valid_block_height: legacy.solana_last_valid_block_height, - authorization_expired_at_ms: legacy.authorization_expired_at_ms, - authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, - session_id: legacy.session_id, - thread_id: legacy.thread_id, - committed_hold: legacy.committed_hold, - } - } -} - -fn instant_ms<'de, D: Deserializer<'de>>(deserializer: D) -> Result { - let text = String::deserialize(deserializer)?; - parse_rfc3339_ms(&text) - .ok_or_else(|| serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant"))) -} - -fn optional_instant_ms<'de, D: Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - Option::::deserialize(deserializer)? - .map(|text| { - parse_rfc3339_ms(&text).ok_or_else(|| { - serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant")) - }) - }) - .transpose() -} - -/// Parse an RFC 3339 instant using integer arithmetic, truncating fractions -/// finer than milliseconds without introducing a date/time dependency into -/// the bus contract crate. -fn parse_rfc3339_ms(text: &str) -> Option { - let bytes = text.as_bytes(); - let digits = |from: usize, len: usize| -> Option { - let part = bytes.get(from..from + len)?; - if !part.iter().all(u8::is_ascii_digit) { - return None; - } - part.iter() - .try_fold(0_i64, |n, d| Some(n * 10 + i64::from(d - b'0'))) - }; - let separator = |at: usize, want: &[u8]| bytes.get(at).is_some_and(|b| want.contains(b)); - if !(separator(4, b"-") - && separator(7, b"-") - && separator(10, b"Tt ") - && separator(13, b":") - && separator(16, b":")) - { - return None; - } - let (year, month, day) = (digits(0, 4)?, digits(5, 2)?, digits(8, 2)?); - let (hour, minute, second) = (digits(11, 2)?, digits(14, 2)?, digits(17, 2)?); - let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); - let days_in_month = match month { - 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, - 4 | 6 | 9 | 11 => 30, - 2 if leap_year => 29, - 2 => 28, - _ => return None, - }; - if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 60 { - return None; - } - let mut at = 19; - let mut millis = 0; - if bytes.get(at) == Some(&b'.') { - let start = at + 1; - let mut end = start; - while bytes.get(end).is_some_and(u8::is_ascii_digit) { - end += 1; - } - if end == start { - return None; - } - for (place, digit) in bytes[start..end].iter().take(3).enumerate() { - millis += i64::from(digit - b'0') * [100, 10, 1][place]; - } - at = end; - } - let offset_minutes = match bytes.get(at)? { - b'Z' | b'z' if at + 1 == bytes.len() => 0, - sign @ (b'+' | b'-') if at + 6 == bytes.len() && separator(at + 3, b":") => { - let hours = digits(at + 1, 2)?; - let minute_part = digits(at + 4, 2)?; - if hours > 23 || minute_part > 59 { - return None; - } - let minutes = hours * 60 + minute_part; - if *sign == b'-' { -minutes } else { minutes } - } - _ => return None, - }; - // Days from civil (Howard Hinnant's algorithm), proleptic Gregorian. - let y = if month <= 2 { year - 1 } else { year }; - let era = y.div_euclid(400); - let year_of_era = y - era * 400; - let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - let days = era * 146_097 + day_of_era - 719_468; - let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; - Some(seconds * 1_000 + millis) -} diff --git a/crates/tinywallet-bus/src/storage_tests.rs b/crates/tinywallet-bus/src/storage_tests.rs deleted file mode 100644 index 0e10aef7..00000000 --- a/crates/tinywallet-bus/src/storage_tests.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! Tests for the legacy x402 payment conversion and storage contract. - -#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] - -use super::*; - -fn convert( - value: serde_json::Value, -) -> Result { - serde_json::from_value::(value) - .map(legacy_payments::convert_legacy_payment) -} - -#[test] -fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() { - let legacy = serde_json::json!({ - "id": "payment-1", - "url": "https://merchant.example/item", - "asset": "USDC", - "amountAtomic": 12345, - "amountDisplay": "0.012345", - "recipient": "recipient", - "network": "eip155:1", - "txSignature": "0xabc", - "status": "settled", - "timestamp": "2026-03-15T15:00:00.250000+03:00", - "authorizationValidUntil": "2026-03-15T12:00:01.9999Z", - "solanaLastValidBlockHeight": 42, - "authorizationExpiredAt": "2026-03-15T12:00:02Z", - "authorizationExpiryObservedHeight": 43, - "sessionId": "session-1", - "threadId": "thread-1", - "committed_hold": "hold-1" - }); - - let payment = convert(legacy).unwrap(); - assert_eq!(payment.id, "payment-1"); - assert_eq!( - payment.status, - legacy_payments::StoredPaymentStatus::Settled - ); - assert_eq!(payment.timestamp_ms, 1_773_576_000_250); - assert_eq!( - payment.authorization_valid_until_ms, - Some(1_773_576_001_999) - ); - assert_eq!(payment.authorization_expired_at_ms, Some(1_773_576_002_000)); - assert_eq!(payment.solana_last_valid_block_height, Some(42)); - assert_eq!(payment.authorization_expiry_observed_height, Some(43)); - assert_eq!(payment.session_id, "session-1"); - assert_eq!(payment.thread_id.as_deref(), Some("thread-1")); - assert_eq!(payment.committed_hold.as_deref(), Some("hold-1")); - - let current = serde_json::to_value(payment).unwrap(); - assert_eq!(current["amount_atomic"], 12345); - assert_eq!(current["timestamp_ms"], 1_773_576_000_250_i64); - assert_eq!( - current["authorization_valid_until_ms"], - 1_773_576_001_999_i64 - ); - assert_eq!(current["tx_signature"], "0xabc"); - assert!(current.get("timestamp").is_none()); -} - -#[test] -fn legacy_payment_conversion_preserves_rfc3339_timestamp_edge_cases() { - let row = |timestamp: &str| { - serde_json::json!({ - "id": "payment-time", - "url": "https://merchant.example/item", - "asset": "USD", - "amountAtomic": 1, - "amountDisplay": "1", - "recipient": "recipient", - "network": "eip155:1", - "status": "pending", - "timestamp": timestamp, - "sessionId": "session" - }) - }; - - for (timestamp, expected_ms) in [ - ("2026-03-15t15:00:00.250000+03:00", 1_773_576_000_250), - ("2026-03-15 12:00:00.9z", 1_773_576_000_900), - ("2026-03-15T12:00:60Z", 1_773_576_060_000), - ] { - assert_eq!(convert(row(timestamp)).unwrap().timestamp_ms, expected_ms); - } - assert!(convert(row("2024-02-29T00:00:00Z")).is_ok()); -} - -#[test] -fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids() { - let row = |status: &str, timestamp: &str| { - serde_json::json!({ - "id": "same-attempt", - "url": "https://merchant.example/item", - "asset": "USD", - "amountAtomic": 1, - "amountDisplay": "1", - "recipient": "recipient", - "network": "eip155:1", - "status": status, - "timestamp": timestamp, - "sessionId": "session" - }) - }; - let pending = convert(row("pending", "2026-03-15T12:00:00Z")).unwrap(); - let settled = convert(row("settled", "2026-03-15T12:00:01Z")).unwrap(); - assert_eq!(pending.id, settled.id); - assert_eq!( - pending.status, - legacy_payments::StoredPaymentStatus::Pending - ); - assert_eq!( - settled.status, - legacy_payments::StoredPaymentStatus::Settled - ); - assert_eq!(pending.tx_signature, None); - assert_eq!(pending.authorization_valid_until_ms, None); - assert_eq!(pending.thread_id, None); - assert_eq!(pending.committed_hold, None); -} - -#[test] -fn legacy_payment_conversion_rejects_malformed_required_and_optional_data() { - let base = serde_json::json!({ - "id": "payment-1", - "url": "https://merchant.example/item", - "asset": "USD", - "amountAtomic": 1, - "amountDisplay": "1", - "recipient": "recipient", - "network": "eip155:1", - "status": "pending", - "timestamp": "2026-03-15T12:00:00Z", - "sessionId": "session" - }); - - for (field, value) in [ - ("timestamp", serde_json::json!("yesterday")), - ("timestamp", serde_json::json!("2026-13-15T12:00:00Z")), - ("timestamp", serde_json::json!("2026-03-00T12:00:00Z")), - ("timestamp", serde_json::json!("2026-02-29T12:00:00Z")), - ("timestamp", serde_json::json!("2024-02-31T12:00:00Z")), - ("timestamp", serde_json::json!("2026-03-15T24:00:00Z")), - ("timestamp", serde_json::json!("2026-03-15T12:60:00Z")), - ("timestamp", serde_json::json!("2026-03-15T12:00:61Z")), - ("timestamp", serde_json::json!("2026-03-15T12:00:00.")), - ("timestamp", serde_json::json!("2026-03-15T12:00:00+01:0x")), - ("timestamp", serde_json::json!("2026-03-15T12:00:00+24:00")), - ("timestamp", serde_json::json!("2026-03-15T12:00:00+01:60")), - ( - "timestamp", - serde_json::json!("2026-03-15T12:00:00+01:00tail"), - ), - ("timestamp", serde_json::json!("2026/03/15T12:00:00Z")), - ( - "authorizationValidUntil", - serde_json::json!("not-a-timestamp"), - ), - ("status", serde_json::json!("unknown")), - ("amountAtomic", serde_json::json!(-1)), - ] { - let mut malformed = base.clone(); - malformed[field] = value; - assert!(convert(malformed).is_err(), "field {field}"); - } - assert!(convert(serde_json::json!([])).is_err()); -} diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index 99acd57f..cfbb35f8 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -1,11 +1,196 @@ -//! The owner-defined payment record and legacy converter live in the public -//! bus contract so host importers and the module migration share one mapping. +//! Owner-local conversion from legacy x402 payment rows to the shared +//! `wallet.payments` storage record. -pub(crate) use tinywallet_bus::storage::legacy_payments::{ - LegacyPayment, StoredPaymentRecord as StoredPayment, StoredPaymentStatus, - convert_legacy_payment, -}; +use serde::Deserialize; +use serde::de::Deserializer; +use tinywallet_bus::storage::{StoredPaymentRecord, StoredPaymentStatus}; -#[cfg(test)] -#[path = "schema_payment_tests.rs"] -mod tests; +/// Convert one previous camelCase `x402.payments` body to the current typed +/// `wallet.payments` storage contract. +/// +/// The legacy row's ID and all optional payment and authorization data are +/// retained. RFC 3339 instants become epoch milliseconds, truncating +/// sub-millisecond precision. The caller owns source ordering and should keep +/// repeated IDs because they can represent successive payment states. +#[must_use] +pub fn convert_legacy_payment(legacy: LegacyPayment) -> StoredPaymentRecord { + legacy.into() +} + +/// Typed row from the previous camelCase `x402.payments` stream. +/// +/// Deserialize the source row into this type before passing it to +/// [`convert_legacy_payment`]. Timestamp fields are parsed and normalized +/// during deserialization, so malformed or unsupported instants are rejected +/// before a canonical record is produced. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LegacyPayment { + /// Stable ID shared by successive states of the same payment attempt. + pub id: String, + /// The URL the payment bought access to. + pub url: String, + /// The asset paid in. + pub asset: String, + /// Amount in atomic units. + pub amount_atomic: u64, + /// Human-readable amount. + pub amount_display: String, + /// Payment recipient. + pub recipient: String, + /// CAIP-2 network identifier. + pub network: String, + #[serde(default)] + /// Settlement transaction, if available. + pub tx_signature: Option, + /// Payment lifecycle state. + pub status: StoredPaymentStatus, + #[serde(rename = "timestamp", deserialize_with = "instant_ms")] + /// Timestamp of this state, normalized to epoch milliseconds. + pub timestamp_ms: i64, + #[serde( + default, + rename = "authorizationValidUntil", + deserialize_with = "optional_instant_ms" + )] + /// Authorization expiration, normalized to epoch milliseconds. + pub authorization_valid_until_ms: Option, + #[serde(default)] + /// Solana's `lastValidBlockHeight` for the exported transaction. + pub solana_last_valid_block_height: Option, + #[serde( + default, + rename = "authorizationExpiredAt", + deserialize_with = "optional_instant_ms" + )] + /// Time when the authorization was observed expired, in epoch milliseconds. + pub authorization_expired_at_ms: Option, + #[serde(default)] + /// Block height at which expiry was observed. + pub authorization_expiry_observed_height: Option, + /// Session that initiated the payment. + pub session_id: String, + #[serde(default)] + /// Conversation thread that initiated the payment, if available. + pub thread_id: Option, + #[serde(default, rename = "committed_hold")] + /// Budget hold committed by this payment, if available. + pub committed_hold: Option, +} + +impl From for StoredPaymentRecord { + fn from(legacy: LegacyPayment) -> Self { + Self { + id: legacy.id, + url: legacy.url, + asset: legacy.asset, + amount_atomic: legacy.amount_atomic, + amount_display: legacy.amount_display, + recipient: legacy.recipient, + network: legacy.network, + tx_signature: legacy.tx_signature, + status: legacy.status, + timestamp_ms: legacy.timestamp_ms, + authorization_valid_until_ms: legacy.authorization_valid_until_ms, + solana_last_valid_block_height: legacy.solana_last_valid_block_height, + authorization_expired_at_ms: legacy.authorization_expired_at_ms, + authorization_expiry_observed_height: legacy.authorization_expiry_observed_height, + session_id: legacy.session_id, + thread_id: legacy.thread_id, + committed_hold: legacy.committed_hold, + } + } +} + +fn instant_ms<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + parse_rfc3339_ms(&text) + .ok_or_else(|| serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant"))) +} + +fn optional_instant_ms<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|text| { + parse_rfc3339_ms(&text).ok_or_else(|| { + serde::de::Error::custom(format!("`{text}` is not an RFC 3339 instant")) + }) + }) + .transpose() +} + +/// Parse an RFC 3339 instant using integer arithmetic, truncating fractions +/// finer than milliseconds without introducing a date/time dependency into +/// the bus contract crate. +fn parse_rfc3339_ms(text: &str) -> Option { + let bytes = text.as_bytes(); + let digits = |from: usize, len: usize| -> Option { + let part = bytes.get(from..from + len)?; + if !part.iter().all(u8::is_ascii_digit) { + return None; + } + part.iter() + .try_fold(0_i64, |n, d| Some(n * 10 + i64::from(d - b'0'))) + }; + let separator = |at: usize, want: &[u8]| bytes.get(at).is_some_and(|b| want.contains(b)); + if !(separator(4, b"-") + && separator(7, b"-") + && separator(10, b"Tt ") + && separator(13, b":") + && separator(16, b":")) + { + return None; + } + let (year, month, day) = (digits(0, 4)?, digits(5, 2)?, digits(8, 2)?); + let (hour, minute, second) = (digits(11, 2)?, digits(14, 2)?, digits(17, 2)?); + let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if leap_year => 29, + 2 => 28, + _ => return None, + }; + if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 60 { + return None; + } + let mut at = 19; + let mut millis = 0; + if bytes.get(at) == Some(&b'.') { + let start = at + 1; + let mut end = start; + while bytes.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + if end == start { + return None; + } + for (place, digit) in bytes[start..end].iter().take(3).enumerate() { + millis += i64::from(digit - b'0') * [100, 10, 1][place]; + } + at = end; + } + let offset_minutes = match bytes.get(at)? { + b'Z' | b'z' if at + 1 == bytes.len() => 0, + sign @ (b'+' | b'-') if at + 6 == bytes.len() && separator(at + 3, b":") => { + let hours = digits(at + 1, 2)?; + let minute_part = digits(at + 4, 2)?; + if hours > 23 || minute_part > 59 { + return None; + } + let minutes = hours * 60 + minute_part; + if *sign == b'-' { -minutes } else { minutes } + } + _ => return None, + }; + // Days from civil (Howard Hinnant's algorithm), proleptic Gregorian. + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let year_of_era = y - era * 400; + let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + let days = era * 146_097 + day_of_era - 719_468; + let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; + Some(seconds * 1_000 + millis) +} diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs index 016a98a2..50ab11b2 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -28,3 +28,168 @@ fn owner_migration_converter_emits_a_current_stored_payment_body() { assert_eq!(encoded["status"], "settled"); assert!(encoded.get("timestamp").is_none()); } + +fn convert( + value: serde_json::Value, +) -> Result { + serde_json::from_value::(value) + .map(legacy_payments::convert_legacy_payment) +} + +#[test] +fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() { + let legacy = serde_json::json!({ + "id": "payment-1", + "url": "https://merchant.example/item", + "asset": "USDC", + "amountAtomic": 12345, + "amountDisplay": "0.012345", + "recipient": "recipient", + "network": "eip155:1", + "txSignature": "0xabc", + "status": "settled", + "timestamp": "2026-03-15T15:00:00.250000+03:00", + "authorizationValidUntil": "2026-03-15T12:00:01.9999Z", + "solanaLastValidBlockHeight": 42, + "authorizationExpiredAt": "2026-03-15T12:00:02Z", + "authorizationExpiryObservedHeight": 43, + "sessionId": "session-1", + "threadId": "thread-1", + "committed_hold": "hold-1" + }); + + let payment = convert(legacy).unwrap(); + assert_eq!(payment.id, "payment-1"); + assert_eq!( + payment.status, + legacy_payments::StoredPaymentStatus::Settled + ); + assert_eq!(payment.timestamp_ms, 1_773_576_000_250); + assert_eq!( + payment.authorization_valid_until_ms, + Some(1_773_576_001_999) + ); + assert_eq!(payment.authorization_expired_at_ms, Some(1_773_576_002_000)); + assert_eq!(payment.solana_last_valid_block_height, Some(42)); + assert_eq!(payment.authorization_expiry_observed_height, Some(43)); + assert_eq!(payment.session_id, "session-1"); + assert_eq!(payment.thread_id.as_deref(), Some("thread-1")); + assert_eq!(payment.committed_hold.as_deref(), Some("hold-1")); + + let current = serde_json::to_value(payment).unwrap(); + assert_eq!(current["amount_atomic"], 12345); + assert_eq!(current["timestamp_ms"], 1_773_576_000_250_i64); + assert_eq!( + current["authorization_valid_until_ms"], + 1_773_576_001_999_i64 + ); + assert_eq!(current["tx_signature"], "0xabc"); + assert!(current.get("timestamp").is_none()); +} + +#[test] +fn legacy_payment_conversion_preserves_rfc3339_timestamp_edge_cases() { + let row = |timestamp: &str| { + serde_json::json!({ + "id": "payment-time", + "url": "https://merchant.example/item", + "asset": "USD", + "amountAtomic": 1, + "amountDisplay": "1", + "recipient": "recipient", + "network": "eip155:1", + "status": "pending", + "timestamp": timestamp, + "sessionId": "session" + }) + }; + + for (timestamp, expected_ms) in [ + ("2026-03-15t15:00:00.250000+03:00", 1_773_576_000_250), + ("2026-03-15 12:00:00.9z", 1_773_576_000_900), + ("2026-03-15T12:00:60Z", 1_773_576_060_000), + ] { + assert_eq!(convert(row(timestamp)).unwrap().timestamp_ms, expected_ms); + } + assert!(convert(row("2024-02-29T00:00:00Z")).is_ok()); +} + +#[test] +fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids() { + let row = |status: &str, timestamp: &str| { + serde_json::json!({ + "id": "same-attempt", + "url": "https://merchant.example/item", + "asset": "USD", + "amountAtomic": 1, + "amountDisplay": "1", + "recipient": "recipient", + "network": "eip155:1", + "status": status, + "timestamp": timestamp, + "sessionId": "session" + }) + }; + let pending = convert(row("pending", "2026-03-15T12:00:00Z")).unwrap(); + let settled = convert(row("settled", "2026-03-15T12:00:01Z")).unwrap(); + assert_eq!(pending.id, settled.id); + assert_eq!( + pending.status, + legacy_payments::StoredPaymentStatus::Pending + ); + assert_eq!( + settled.status, + legacy_payments::StoredPaymentStatus::Settled + ); + assert_eq!(pending.tx_signature, None); + assert_eq!(pending.authorization_valid_until_ms, None); + assert_eq!(pending.thread_id, None); + assert_eq!(pending.committed_hold, None); +} + +#[test] +fn legacy_payment_conversion_rejects_malformed_required_and_optional_data() { + let base = serde_json::json!({ + "id": "payment-1", + "url": "https://merchant.example/item", + "asset": "USD", + "amountAtomic": 1, + "amountDisplay": "1", + "recipient": "recipient", + "network": "eip155:1", + "status": "pending", + "timestamp": "2026-03-15T12:00:00Z", + "sessionId": "session" + }); + + for (field, value) in [ + ("timestamp", serde_json::json!("yesterday")), + ("timestamp", serde_json::json!("2026-13-15T12:00:00Z")), + ("timestamp", serde_json::json!("2026-03-00T12:00:00Z")), + ("timestamp", serde_json::json!("2026-02-29T12:00:00Z")), + ("timestamp", serde_json::json!("2024-02-31T12:00:00Z")), + ("timestamp", serde_json::json!("2026-03-15T24:00:00Z")), + ("timestamp", serde_json::json!("2026-03-15T12:60:00Z")), + ("timestamp", serde_json::json!("2026-03-15T12:00:61Z")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00.")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00+01:0x")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00+24:00")), + ("timestamp", serde_json::json!("2026-03-15T12:00:00+01:60")), + ( + "timestamp", + serde_json::json!("2026-03-15T12:00:00+01:00tail"), + ), + ("timestamp", serde_json::json!("2026/03/15T12:00:00Z")), + ( + "authorizationValidUntil", + serde_json::json!("not-a-timestamp"), + ), + ("status", serde_json::json!("unknown")), + ("amountAtomic", serde_json::json!(-1)), + ] { + let mut malformed = base.clone(); + malformed[field] = value; + assert!(convert(malformed).is_err(), "field {field}"); + } + assert!(convert(serde_json::json!([])).is_err()); +} From 4e0a416cf349ccd65caf1bacc5d44f1187c74060 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:42:23 +0000 Subject: [PATCH 36/51] refactor(x402): gate stored payment wire types behind feature The stored payment record and status types are now only compiled when the wire feature is enabled, and the payment schema module exposes a local alias for the record. Tests were updated to use the shared types instead of the legacy module paths. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-bus/src/storage.rs | 5 +++++ .../src/ledger/schema_payment.rs | 2 ++ .../src/ledger/schema_payment_tests.rs | 20 +++++-------------- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/crates/tinywallet-bus/src/storage.rs b/crates/tinywallet-bus/src/storage.rs index 8def014e..01670a0b 100644 --- a/crates/tinywallet-bus/src/storage.rs +++ b/crates/tinywallet-bus/src/storage.rs @@ -2,6 +2,10 @@ use tinystoragedrivers_types::CollectionSpec; +#[cfg(feature = "wire")] +use serde::{Deserialize, Serialize}; + +#[cfg(feature = "wire")] /// Payment lifecycle state in the canonical `wallet.payments` record. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -16,6 +20,7 @@ pub enum StoredPaymentStatus { Denied, } +#[cfg(feature = "wire")] /// Canonical body stored in the `wallet.payments` stream. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StoredPaymentRecord { diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index cfbb35f8..e77c1f47 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -5,6 +5,8 @@ use serde::Deserialize; use serde::de::Deserializer; use tinywallet_bus::storage::{StoredPaymentRecord, StoredPaymentStatus}; +pub(crate) type StoredPayment = StoredPaymentRecord; + /// Convert one previous camelCase `x402.payments` body to the current typed /// `wallet.payments` storage contract. /// diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs index 50ab11b2..90f42f5b 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -31,9 +31,8 @@ fn owner_migration_converter_emits_a_current_stored_payment_body() { fn convert( value: serde_json::Value, -) -> Result { - serde_json::from_value::(value) - .map(legacy_payments::convert_legacy_payment) +) -> Result { + serde_json::from_value::(value).map(convert_legacy_payment) } #[test] @@ -60,10 +59,7 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() let payment = convert(legacy).unwrap(); assert_eq!(payment.id, "payment-1"); - assert_eq!( - payment.status, - legacy_payments::StoredPaymentStatus::Settled - ); + assert_eq!(payment.status, StoredPaymentStatus::Settled); assert_eq!(payment.timestamp_ms, 1_773_576_000_250); assert_eq!( payment.authorization_valid_until_ms, @@ -133,14 +129,8 @@ fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids let pending = convert(row("pending", "2026-03-15T12:00:00Z")).unwrap(); let settled = convert(row("settled", "2026-03-15T12:00:01Z")).unwrap(); assert_eq!(pending.id, settled.id); - assert_eq!( - pending.status, - legacy_payments::StoredPaymentStatus::Pending - ); - assert_eq!( - settled.status, - legacy_payments::StoredPaymentStatus::Settled - ); + assert_eq!(pending.status, StoredPaymentStatus::Pending); + assert_eq!(settled.status, StoredPaymentStatus::Settled); assert_eq!(pending.tx_signature, None); assert_eq!(pending.authorization_valid_until_ms, None); assert_eq!(pending.thread_id, None); From 3bb5403c199b1a69b48f69ff030af5251cb8db0c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:42:36 +0000 Subject: [PATCH 37/51] chore(tinywallet-bus): remove unused test module declaration Drops the cfg-gated test module declaration from storage.rs along with a stray blank line, since the referenced storage_tests.rs file no longer exists. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-bus/src/storage.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/crates/tinywallet-bus/src/storage.rs b/crates/tinywallet-bus/src/storage.rs index 01670a0b..511f8709 100644 --- a/crates/tinywallet-bus/src/storage.rs +++ b/crates/tinywallet-bus/src/storage.rs @@ -68,7 +68,6 @@ pub struct StoredPaymentRecord { pub committed_hold: Option, } - /// Collection names used by the wallet's persistent module storage. /// /// Migration behavior remains in the x402 implementation. The host only needs @@ -80,8 +79,3 @@ pub fn collections() -> Vec { CollectionSpec::new("wallet.migrations"), ] } - -#[cfg(feature = "wire")] -#[cfg(test)] -#[path = "storage_tests.rs"] -mod tests; From 050a40822cc8011ad6dacd0df72e05c6a4a39bee Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:42:52 +0000 Subject: [PATCH 38/51] fix(ledger): source StoredPaymentStatus from tinywallet-bus The payment status type is now re-exported from tinywallet-bus instead of being defined in the local schema_payment module, so the ledger shares a single definition with the rest of the wallet stack. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 466c86f8..704ecb0f 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -8,8 +8,8 @@ use tinystoragedrivers_types::{ #[path = "schema_payment.rs"] mod payment; -pub(super) use payment::StoredPaymentStatus; pub(crate) use payment::{LegacyPayment, StoredPayment, convert_legacy_payment}; +pub(super) use tinywallet_bus::storage::StoredPaymentStatus; /// Collection containing the single budget-hold document. pub(super) const BUDGETS_COLLECTION: &str = "wallet.budgets"; From 6fba1d098c4a7fdaa240110314186ab2646e91a5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:43:08 +0000 Subject: [PATCH 39/51] refactor(ledger): restrict legacy payment conversion to crate The legacy payment conversion helper is now crate-private since it is only used within the ledger module and should not be part of the public API. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema_payment.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index e77c1f47..961e268d 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -15,7 +15,7 @@ pub(crate) type StoredPayment = StoredPaymentRecord; /// sub-millisecond precision. The caller owns source ordering and should keep /// repeated IDs because they can represent successive payment states. #[must_use] -pub fn convert_legacy_payment(legacy: LegacyPayment) -> StoredPaymentRecord { +pub(crate) fn convert_legacy_payment(legacy: LegacyPayment) -> StoredPaymentRecord { legacy.into() } From 6e8d4240a9ddb59113a0237c8ad7dcb9bf14b0bc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:43:26 +0000 Subject: [PATCH 40/51] test(ledger): wire payment schema tests into the module tree Register the payment schema test file as a cfg(test) submodule so its cases actually run, and reflow a helper signature to satisfy formatting. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema_payment.rs | 4 ++++ crates/tinywallet-x402/src/ledger/schema_payment_tests.rs | 4 +--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema_payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs index 961e268d..1cde5906 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -196,3 +196,7 @@ fn parse_rfc3339_ms(text: &str) -> Option { let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60; Some(seconds * 1_000 + millis) } + +#[cfg(test)] +#[path = "schema_payment_tests.rs"] +mod tests; diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs index 90f42f5b..15ec4d68 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -29,9 +29,7 @@ fn owner_migration_converter_emits_a_current_stored_payment_body() { assert!(encoded.get("timestamp").is_none()); } -fn convert( - value: serde_json::Value, -) -> Result { +fn convert(value: serde_json::Value) -> Result { serde_json::from_value::(value).map(convert_legacy_payment) } From 61b92576f0bfe24183bf1934449864ebc8446f60 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:44:16 +0000 Subject: [PATCH 41/51] refactor(ledger): stream payment migration in batches The payment migration now reads the legacy stream and appends to the target stream one batch at a time instead of buffering the whole source in memory, and it verifies any already-written target prefix per batch so a partially completed migration can resume without re-reading everything. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema.rs | 159 +++++++++++++------- 1 file changed, 106 insertions(+), 53 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 704ecb0f..031dec7b 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -165,14 +165,15 @@ impl From for super::types::PaymentStatus { async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types::Result<()> { let source_len = streams.len(LEGACY_PAYMENTS_STREAM).await?; - let mut source = Vec::new(); - let mut offset = 0; - while offset < source_len { + let mut source_offset = 0; + let mut target_offset = 0; + while source_offset < source_len { + let batch_start = source_offset; let window = streams - .read_window(LEGACY_PAYMENTS_STREAM, offset, BATCH_SIZE) + .read_window(LEGACY_PAYMENTS_STREAM, source_offset, BATCH_SIZE) .await?; for (index, entry) in window.iter().enumerate() { - let expected = offset + let expected = source_offset .checked_add(u64::try_from(index).map_err(|_| { StorageError::backend("wallet payment migration source offset overflowed") })?) @@ -190,68 +191,102 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types "wallet payment migration source ended before its reported length", )); }; - offset = last.offset.checked_add(1).ok_or_else(|| { + source_offset = last.offset.checked_add(1).ok_or_else(|| { StorageError::backend("wallet payment migration source offset overflowed") })?; - if offset > source_len { + if source_offset > source_len { return Err(StorageError::backend( "wallet payment migration source exceeded its reported length", )); } - source.extend(window.into_iter().map(|entry| entry.value)); + let values = window.into_iter().map(|entry| entry.value).collect(); + let migrated = migrate_payment_batch(values, batch_start)?; + append_migration_batch(streams, target_offset, &migrated).await?; + target_offset = target_offset + .checked_add(u64::try_from(migrated.len()).map_err(|_| { + StorageError::backend("wallet payment migration target offset overflowed") + })?) + .ok_or_else(|| { + StorageError::backend("wallet payment migration target offset overflowed") + })?; } if streams.len(LEGACY_PAYMENTS_STREAM).await? != source_len { return Err(StorageError::backend( "wallet payment migration source changed while being read", )); } - let migrated = migrate_payments_stream(LEGACY_PAYMENTS_STREAM, source)? - .map_or_else(Vec::new, |(_, entries)| entries); - if migrated.is_empty() { - return Ok(()); - } - - let target_len = streams.len(PAYMENTS_STREAM).await?; - let target_len_usize = usize::try_from(target_len).map_err(|_| { - StorageError::backend("wallet payment migration target stream is too large") - })?; - let migrated_len = u64::try_from(migrated.len()).map_err(|_| { - StorageError::backend("wallet payment migration source stream is too large") - })?; - if target_len > migrated_len { + let final_target_len = streams.len(PAYMENTS_STREAM).await?; + if final_target_len != target_offset { return Err(StorageError::backend( "wallet payment migration found unexpected target entries", )); } - let existing = streams - .read_window(PAYMENTS_STREAM, 0, target_len_usize) - .await?; - if u64::try_from(existing.len()).ok() != Some(target_len) - || existing - .iter() - .enumerate() - .any(|(index, entry)| u64::try_from(index).ok() != Some(entry.offset)) - { - return Err(StorageError::backend( - "wallet payment migration target prefix was incomplete", - )); + Ok(()) +} + +async fn append_migration_batch( + streams: &dyn StreamStore, + target_offset: u64, + migrated: &[Value], +) -> tinystoragedrivers_types::Result<()> { + if migrated.is_empty() { + return Ok(()); } - if existing - .iter() - .zip(migrated.iter()) - .any(|(entry, value)| entry.value != *value) - { + let target_len = streams.len(PAYMENTS_STREAM).await?; + if target_len < target_offset { return Err(StorageError::backend( - "wallet payment migration found conflicting target data", + "wallet payment migration target stream changed while being written", )); } - let start = target_len_usize; - if start < migrated.len() { - streams - .append_batch_if_offset(PAYMENTS_STREAM, target_len, migrated[start..].to_vec()) + let already_written = usize::try_from((target_len - target_offset).min(migrated.len() as u64)) + .map_err(|_| { + StorageError::backend("wallet payment migration target stream is too large") + })?; + if already_written > 0 { + let existing = streams + .read_window(PAYMENTS_STREAM, target_offset, already_written) .await?; + if existing.len() != already_written + || existing.iter().enumerate().any(|(index, entry)| { + target_offset.checked_add(index as u64) != Some(entry.offset) + || entry.value != migrated[index] + }) + { + return Err(StorageError::backend( + "wallet payment migration found conflicting target data", + )); + } + } + if already_written == migrated.len() { + return Ok(()); + } + let append_offset = target_offset + .checked_add(already_written as u64) + .ok_or_else(|| { + StorageError::backend("wallet payment migration target offset overflowed") + })?; + match streams + .append_batch_if_offset( + PAYMENTS_STREAM, + append_offset, + migrated[already_written..].to_vec(), + ) + .await + { + Ok(_) => Ok(()), + Err(error) if error.kind() == ErrorKind::Conflict => { + let latest = streams + .read_window(PAYMENTS_STREAM, target_offset, migrated.len()) + .await?; + let completed = latest.len() == migrated.len() + && latest.iter().enumerate().all(|(index, entry)| { + target_offset.checked_add(index as u64) == Some(entry.offset) + && entry.value == migrated[index] + }); + if completed { Ok(()) } else { Err(error) } + } + Err(error) => Err(error), } - Ok(()) } fn migrate_payments_stream( @@ -261,17 +296,35 @@ fn migrate_payments_stream( if source != LEGACY_PAYMENTS_STREAM { return Ok(None); } + Ok(Some(( + PAYMENTS_STREAM.to_owned(), + migrate_payment_batch(entries, 0)?, + ))) +} + +fn migrate_payment_batch( + entries: Vec, + source_offset: u64, +) -> tinystoragedrivers_types::Result> { let mut migrated = Vec::with_capacity(entries.len()); - for entry in entries { - if let Ok(legacy) = serde_json::from_value::(entry) { - let payment = convert_legacy_payment(legacy); - migrated.push( - serde_json::to_value(payment) - .map_err(|error| StorageError::invalid_input(error.to_string()))?, - ); + for (index, entry) in entries.into_iter().enumerate() { + match serde_json::from_value::(entry) { + Ok(legacy) => { + let payment = convert_legacy_payment(legacy); + migrated.push( + serde_json::to_value(payment) + .map_err(|error| StorageError::invalid_input(error.to_string()))?, + ); + } + Err(error) => { + let offset = source_offset.checked_add(index as u64).unwrap_or(u64::MAX); + log::warn!( + "[x402::ledger] skipping invalid legacy payment at offset {offset}: {error}" + ); + } } } - Ok(Some((PAYMENTS_STREAM.to_owned(), migrated))) + Ok(migrated) } fn renamed_holds(body: &Value) -> Option> { From 21f3b3743d3764f0cb79d02f1d532ae86865e51c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:45:04 +0000 Subject: [PATCH 42/51] fix(ledger): treat already-exists as an idempotent migration conflict Migration inserts now also tolerate ErrorKind::AlreadyExists alongside Conflict, so re-running a migration against a store that reports the duplicate differently no longer aborts. The payments stream helper is gated behind cfg(test) since it is only used by tests. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 031dec7b..a8d31ec8 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -70,7 +70,7 @@ pub(super) async fn migrate( .await { Ok(_) => Ok(()), - Err(error) if error.kind() == ErrorKind::Conflict => { + Err(error) if matches!(error.kind(), ErrorKind::Conflict | ErrorKind::AlreadyExists) => { let latest = documents.get(MIGRATIONS_COLLECTION, MIGRATIONS_ID).await?; let completed = latest .as_ref() @@ -115,7 +115,9 @@ async fn migrate_budgets(documents: &dyn DocumentStore) -> tinystoragedrivers_ty .await { Ok(_) => Ok(()), - Err(error) if error.kind() == ErrorKind::Conflict => { + Err(error) + if matches!(error.kind(), ErrorKind::Conflict | ErrorKind::AlreadyExists) => + { let latest = documents.get(BUDGETS_COLLECTION, HOLDS_ID).await?; if latest.is_some_and(|record| { budget_target_matches(&record, &migrated, legacy.meta.expires_ms) @@ -289,6 +291,7 @@ async fn append_migration_batch( } } +#[cfg(test)] fn migrate_payments_stream( source: &str, entries: Vec, From 940e5f1bdfd9e9badf23718e4faab548f4e25a4f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:45:22 +0000 Subject: [PATCH 43/51] test(ledger): cover migration read errors and concurrent appends Add a fault mode that writes the batch and then reports a conflict, so the migration's handling of a competing append can be exercised. Also split the existing target-prefix read error case into its own test and assert that a matching concurrent append is accepted without marking the migration complete. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/ledger/schema_tests.rs | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 4a679d75..148f1a2e 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -219,6 +219,7 @@ enum ReadFault { ReadError(&'static str), Overshoot(&'static str), AppendError(&'static str), + AppendConflictAfterWrite(&'static str), } #[derive(Debug)] @@ -257,6 +258,15 @@ impl StreamStore for FaultyReads { "injected stream append failure", )); } + if matches!(self.fault, ReadFault::AppendConflictAfterWrite(name) if stream == name) { + self.inner + .append_batch_if_offset(stream, expected_next_offset, values) + .await?; + return Err(tinystoragedrivers_types::StorageError::new( + ErrorKind::Conflict, + "simulated competing migration append", + )); + } self.inner .append_batch_if_offset(stream, expected_next_offset, values) .await @@ -1026,7 +1036,6 @@ fn malformed_legacy_payment_offsets_do_not_mark_migration_complete() { fn payment_migration_rejects_stream_read_errors_and_oversized_windows() { for fault in [ ReadFault::ReadError("x402.payments"), - ReadFault::ReadError("wallet.payments"), ReadFault::Overshoot("x402.payments"), ] { let storage = test_storage(); @@ -1046,6 +1055,27 @@ fn payment_migration_rejects_stream_read_errors_and_oversized_windows() { } } +#[test] +fn payment_migration_propagates_errors_reading_an_existing_target_prefix() { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(1)); + append_values(&storage, "wallet.payments", vec![json!({ "wrong": true })]); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault: ReadFault::ReadError("wallet.payments"), + len_calls: AtomicUsize::new(0), + }); + let documents = Arc::clone(storage.documents()); + + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap(); + + assert!(result.is_err()); + assert_migration_not_marked(&storage); +} + #[test] fn payment_migration_propagates_target_append_failure_without_marking_complete() { let storage = test_storage(); @@ -1065,6 +1095,26 @@ fn payment_migration_propagates_target_append_failure_without_marking_complete() assert_migration_not_marked(&storage); } +#[test] +fn payment_migration_accepts_a_matching_concurrent_append() { + let storage = test_storage(); + append_values(&storage, "x402.payments", legacy_payments(1)); + let streams: Arc = Arc::new(FaultyReads { + inner: Arc::clone(storage.streams()), + fault: ReadFault::AppendConflictAfterWrite("wallet.payments"), + len_calls: AtomicUsize::new(0), + }); + let documents = Arc::clone(storage.documents()); + + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate(documents.as_ref(), streams.as_ref()).await }) + .unwrap(); + + assert!(result.is_ok()); + assert_eq!(read_values(&storage, "wallet.payments").len(), 1); +} + #[test] fn payment_migration_completes_a_matching_prefix_and_appends_only_its_suffix() { let storage = test_storage(); From 6eb819ec70d8577303d8c4e20b82f58f7225f32e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:45:35 +0000 Subject: [PATCH 44/51] test(ledger): read payment count through the stream api The concurrent append test now checks the payment count via the storage streams handle instead of the read_values helper, so the assertion exercises the same async path the ledger uses at runtime. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema_tests.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 148f1a2e..7067f7ff 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -1112,7 +1112,15 @@ fn payment_migration_accepts_a_matching_concurrent_append() { .unwrap(); assert!(result.is_ok()); - assert_eq!(read_values(&storage, "wallet.payments").len(), 1); + let streams = Arc::clone(storage.streams()); + assert_eq!( + Blocking::new() + .unwrap() + .run(async move { streams.len("wallet.payments").await }) + .unwrap() + .unwrap(), + 1 + ); } #[test] From 35bca48f9e23daa1a934b4bd24596e2ee6b2ae55 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:46:14 +0000 Subject: [PATCH 45/51] test(ledger): scope clippy allows to individual tests Move the file-level clippy allow attributes onto the individual test functions so the lint suppressions no longer apply to the whole module. Add race actions covering AlreadyExists failures for the migration marker and budget writes, extending the migration race coverage to the already-exists error path. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/ledger/blocking_tests.rs | 5 ++-- .../src/ledger/schema_payment_tests.rs | 7 ++++-- .../src/ledger/schema_tests.rs | 23 +++++++++++++++++-- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/blocking_tests.rs b/crates/tinywallet-x402/src/ledger/blocking_tests.rs index 9fa808de..cfef54ba 100644 --- a/crates/tinywallet-x402/src/ledger/blocking_tests.rs +++ b/crates/tinywallet-x402/src/ledger/blocking_tests.rs @@ -1,10 +1,9 @@ //! Tests for the dedicated runtime used by blocking x402 callers. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - use super::*; #[test] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] fn bridge_debug_and_startup_errors_keep_their_context() { let bridge = Blocking::new().unwrap(); assert_eq!(format!("{bridge:?}"), "Blocking { .. }"); @@ -24,6 +23,7 @@ fn bridge_debug_and_startup_errors_keep_their_context() { } #[test] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] fn bridge_reports_a_stopped_worker_and_reentrant_calls() { let (jobs, receiver) = mpsc::unbounded_channel(); drop(receiver); @@ -44,6 +44,7 @@ fn bridge_reports_a_stopped_worker_and_reentrant_calls() { } #[test] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] fn bridge_runs_from_current_and_multithread_tokio_contexts() { let bridge = Blocking::new().unwrap(); let current = tokio::runtime::Builder::new_current_thread() diff --git a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs index 15ec4d68..60b92dc8 100644 --- a/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -1,10 +1,9 @@ //! Tests for the x402 owner's conversion of legacy payment records. -#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] - use super::*; #[test] +#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn owner_migration_converter_emits_a_current_stored_payment_body() { let legacy: LegacyPayment = serde_json::from_value(serde_json::json!({ "id": "legacy-attempt", @@ -34,6 +33,7 @@ fn convert(value: serde_json::Value) -> Result } #[test] +#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() { let legacy = serde_json::json!({ "id": "payment-1", @@ -82,6 +82,7 @@ fn legacy_payment_conversion_preserves_current_fields_and_normalizes_instants() } #[test] +#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn legacy_payment_conversion_preserves_rfc3339_timestamp_edge_cases() { let row = |timestamp: &str| { serde_json::json!({ @@ -109,6 +110,7 @@ fn legacy_payment_conversion_preserves_rfc3339_timestamp_edge_cases() { } #[test] +#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids() { let row = |status: &str, timestamp: &str| { serde_json::json!({ @@ -136,6 +138,7 @@ fn legacy_payment_conversion_defaults_optional_fields_and_preserves_repeated_ids } #[test] +#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn legacy_payment_conversion_rejects_malformed_required_and_optional_data() { let base = serde_json::json!({ "id": "payment-1", diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 7067f7ff..d0021966 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -21,7 +21,9 @@ const V1_PAYMENT_MS: i64 = 1_773_576_000_000; #[derive(Debug, Clone, Copy)] enum RaceAction { CompleteMarker, + ExistingMarker, MatchingBudget, + ExistingBudget, WrongBudgetSchema, WrongBudgetExpiry, } @@ -70,6 +72,15 @@ impl DocumentStore for RacingDocuments { "simulated competing migration completion", )); } + if matches!(self.action, RaceAction::ExistingMarker) + && collection == "wallet.migrations" + && id == "x402" + { + return Err(tinystoragedrivers_types::StorageError::new( + ErrorKind::AlreadyExists, + "simulated competing migration completion", + )); + } Ok(version) } @@ -133,14 +144,22 @@ impl DocumentStore for RacingDocuments { match action { RaceAction::WrongBudgetSchema => options = options.schema(1), RaceAction::WrongBudgetExpiry => options = options.expires_ms(1_900_000_000_001), - RaceAction::CompleteMarker | RaceAction::MatchingBudget => {} + RaceAction::CompleteMarker + | RaceAction::ExistingMarker + | RaceAction::MatchingBudget + | RaceAction::ExistingBudget => {} } self.inner .put_with(collection, id, doc.clone(), precondition, options) .await?; if !matches!(action, RaceAction::CompleteMarker) { + let kind = if matches!(action, RaceAction::ExistingBudget) { + ErrorKind::AlreadyExists + } else { + ErrorKind::Conflict + }; return Err(tinystoragedrivers_types::StorageError::new( - ErrorKind::Conflict, + kind, "simulated competing budget migration", )); } From d185f4553889e0055cc513dbe940aeeed1f5eb0f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:46:33 +0000 Subject: [PATCH 46/51] test(ledger): cover migrations against pre-existing matching state Add cases where the owner and budget migrations run against a marker or document that already matches the expected target, and extend the unreachable arm to the new race actions. This pins down that an already-satisfied migration succeeds instead of erroring. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/ledger/schema_tests.rs | 55 ++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index d0021966..1a243a88 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -848,6 +848,21 @@ fn owner_migration_accepts_a_competing_completed_marker() { assert_eq!(marker.doc, json!({ "version": 2 })); } +#[test] +fn owner_migration_accepts_an_already_existing_matching_marker() { + let storage = test_storage(); + let documents = RacingDocuments { + inner: Arc::clone(storage.documents()), + action: RaceAction::ExistingMarker, + }; + let streams = Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { super::migrate(&documents, streams.as_ref()).await }) + .unwrap() + .unwrap(); +} + #[test] fn budget_migration_conflict_retry_rejects_matching_bodies_with_wrong_metadata() { for action in [RaceAction::WrongBudgetSchema, RaceAction::WrongBudgetExpiry] { @@ -906,7 +921,10 @@ fn budget_migration_conflict_retry_rejects_matching_bodies_with_wrong_metadata() RaceAction::WrongBudgetExpiry => { assert_eq!(target.meta.expires_ms, Some(1_900_000_000_001)); } - RaceAction::MatchingBudget | RaceAction::CompleteMarker => unreachable!(), + RaceAction::CompleteMarker + | RaceAction::ExistingMarker + | RaceAction::MatchingBudget + | RaceAction::ExistingBudget => unreachable!(), } assert_migration_not_marked(&storage); } @@ -945,6 +963,41 @@ fn budget_migration_accepts_a_matching_concurrent_write_after_conflict() { assert!(result.is_ok()); } +#[test] +fn budget_migration_accepts_an_already_existing_matching_document() { + let storage = test_storage(); + let documents = Arc::clone(storage.documents()); + Blocking::new() + .unwrap() + .run(async move { + documents + .put_with( + "x402_budget", + HOLDS_ID, + json!({ "holds": { "old": { + "amount": 12, + "expires_at_ms": 1_800_000_000_000_i64 + }}}), + Precondition::Absent, + WriteOptions::new().schema(1), + ) + .await + }) + .unwrap() + .unwrap(); + let documents = RacingDocuments { + inner: Arc::clone(storage.documents()), + action: RaceAction::ExistingBudget, + }; + + let result = Blocking::new() + .unwrap() + .run(async move { super::migrate_budgets(&documents).await }) + .unwrap(); + + assert!(result.is_ok()); +} + #[test] fn payment_migration_refuses_a_longer_or_different_existing_target() { for target in [vec![json!({}), json!({})], vec![json!({ "wrong": true })]] { From 3437ee01a833114e8400bad80416cca615bed6f6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:46:53 +0000 Subject: [PATCH 47/51] refactor(ledger): use saturating add for legacy payment offsets Replace the checked_add fallback with saturating_add when computing the offset for a skipped legacy payment, which is simpler and expresses the same intent. Add a test covering migration of a large legacy payment stream across bounded batches. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema.rs | 2 +- .../src/ledger/schema_tests.rs | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index a8d31ec8..e8f2ea29 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -320,7 +320,7 @@ fn migrate_payment_batch( ); } Err(error) => { - let offset = source_offset.checked_add(index as u64).unwrap_or(u64::MAX); + let offset = source_offset.saturating_add(index as u64); log::warn!( "[x402::ledger] skipping invalid legacy payment at offset {offset}: {error}" ); diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 1a243a88..b7bac4d9 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -1041,6 +1041,30 @@ fn incomplete_legacy_payment_window_does_not_mark_migration_complete() { assert_migration_not_marked(&storage); } +#[test] +fn payment_migration_copies_a_large_legacy_stream_across_bounded_batches() { + let storage = test_storage(); + let count = 1_025; + append_values(&storage, "x402.payments", legacy_payments(count)); + let streams = Arc::clone(storage.streams()); + + Blocking::new() + .unwrap() + .run(async move { super::migrate_payments(streams.as_ref()).await }) + .unwrap() + .unwrap(); + + let streams = Arc::clone(storage.streams()); + assert_eq!( + Blocking::new() + .unwrap() + .run(async move { streams.len("wallet.payments").await }) + .unwrap() + .unwrap(), + count as u64 + ); +} + #[test] fn incomplete_existing_payment_prefix_does_not_mark_migration_complete() { let storage = test_storage(); From 5a393ec8d2ed309fb4c9b761a09554bdb9f47e5b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:49:10 +0000 Subject: [PATCH 48/51] test(ledger): assert ledger and bus declare the same collections Add a test that compares the ledger's collection declarations against the bus's, so the two schemas cannot drift apart unnoticed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema_tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index b7bac4d9..b585d095 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -388,6 +388,11 @@ fn host_declarations_are_pure_wallet_collection_specs() { ); } +#[test] +fn ledger_and_bus_declare_the_same_collections() { + assert_eq!(collections(), tinywallet_bus::storage::collections()); +} + #[test] fn opening_the_ledger_migrates_legacy_payments_before_reading_them() { let storage = test_storage(); From 775952584e0647774b0cf642c179c5d9204836c2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 11:54:32 +0000 Subject: [PATCH 49/51] fix(ledger): skip payment migration when legacy stream is empty The migration now returns early if the legacy payments stream has no entries, avoiding unnecessary work and a potential error when reading from an empty stream. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index e8f2ea29..94138ec2 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -167,6 +167,9 @@ impl From for super::types::PaymentStatus { async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types::Result<()> { let source_len = streams.len(LEGACY_PAYMENTS_STREAM).await?; + if source_len == 0 { + return Ok(()); + } let mut source_offset = 0; let mut target_offset = 0; while source_offset < source_len { From b271eb85a65dc439bb8a4299f088596809e96c23 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 12:01:49 +0000 Subject: [PATCH 50/51] refactor(ledger): extract offset_after helper for migration offsets The repeated checked-add and usize-to-u64 conversion logic used when advancing migration offsets is now centralised in an offset_after helper, so each call site passes its own overflow message instead of duplicating the conversion and error handling. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema.rs | 53 ++++++++++++--------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/crates/tinywallet-x402/src/ledger/schema.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 94138ec2..be53ddd9 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -178,13 +178,11 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types .read_window(LEGACY_PAYMENTS_STREAM, source_offset, BATCH_SIZE) .await?; for (index, entry) in window.iter().enumerate() { - let expected = source_offset - .checked_add(u64::try_from(index).map_err(|_| { - StorageError::backend("wallet payment migration source offset overflowed") - })?) - .ok_or_else(|| { - StorageError::backend("wallet payment migration source offset overflowed") - })?; + let expected = offset_after( + source_offset, + index, + "wallet payment migration source offset overflowed", + )?; if entry.offset != expected { return Err(StorageError::backend( "wallet payment migration source window was incomplete", @@ -196,9 +194,11 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types "wallet payment migration source ended before its reported length", )); }; - source_offset = last.offset.checked_add(1).ok_or_else(|| { - StorageError::backend("wallet payment migration source offset overflowed") - })?; + source_offset = offset_after( + last.offset, + 1, + "wallet payment migration source offset overflowed", + )?; if source_offset > source_len { return Err(StorageError::backend( "wallet payment migration source exceeded its reported length", @@ -207,13 +207,11 @@ async fn migrate_payments(streams: &dyn StreamStore) -> tinystoragedrivers_types let values = window.into_iter().map(|entry| entry.value).collect(); let migrated = migrate_payment_batch(values, batch_start)?; append_migration_batch(streams, target_offset, &migrated).await?; - target_offset = target_offset - .checked_add(u64::try_from(migrated.len()).map_err(|_| { - StorageError::backend("wallet payment migration target offset overflowed") - })?) - .ok_or_else(|| { - StorageError::backend("wallet payment migration target offset overflowed") - })?; + target_offset = offset_after( + target_offset, + migrated.len(), + "wallet payment migration target offset overflowed", + )?; } if streams.len(LEGACY_PAYMENTS_STREAM).await? != source_len { return Err(StorageError::backend( @@ -265,11 +263,11 @@ async fn append_migration_batch( if already_written == migrated.len() { return Ok(()); } - let append_offset = target_offset - .checked_add(already_written as u64) - .ok_or_else(|| { - StorageError::backend("wallet payment migration target offset overflowed") - })?; + let append_offset = offset_after( + target_offset, + already_written, + "wallet payment migration target offset overflowed", + )?; match streams .append_batch_if_offset( PAYMENTS_STREAM, @@ -294,6 +292,17 @@ async fn append_migration_batch( } } +fn offset_after( + offset: u64, + increment: usize, + error_message: &'static str, +) -> tinystoragedrivers_types::Result { + let increment = u64::try_from(increment).map_err(|_| StorageError::backend(error_message))?; + offset + .checked_add(increment) + .ok_or_else(|| StorageError::backend(error_message)) +} + #[cfg(test)] fn migrate_payments_stream( source: &str, From a56e7bc184bdb03802c41859fd57d75aa564dead Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 22 Oct 2026 12:02:24 +0000 Subject: [PATCH 51/51] test(ledger): cover migration offset overflow Add a test asserting that offset_after advances the offset on normal input and returns an error when the addition would overflow u64. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinywallet-x402/src/ledger/schema_tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/tinywallet-x402/src/ledger/schema_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index b585d095..a6de97f0 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -393,6 +393,12 @@ fn ledger_and_bus_declare_the_same_collections() { assert_eq!(collections(), tinywallet_bus::storage::collections()); } +#[test] +fn migration_offsets_report_overflow() { + assert_eq!(offset_after(10, 5, "offset overflow").unwrap(), 15); + assert!(offset_after(u64::MAX, 1, "offset overflow").is_err()); +} + #[test] fn opening_the_ledger_migrates_legacy_payments_before_reading_them() { let storage = test_storage();