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 3248af0a..2e3ed79c 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" @@ -33,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" @@ -65,17 +46,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 +210,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" @@ -323,28 +287,10 @@ 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" +name = "cfg_aliases" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" -dependencies = [ - "aead", - "chacha20", - "cipher", - "poly1305", - "zeroize", -] +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chrono" @@ -358,26 +304,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" @@ -495,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" @@ -520,7 +440,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] @@ -600,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" @@ -719,6 +627,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 +693,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 +708,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 +729,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 +753,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 +819,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 +876,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 +1126,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 +1202,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" @@ -1342,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" @@ -1357,12 +1305,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 +1366,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 +1399,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 +1488,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 +1569,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 +1608,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 +1856,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" @@ -1991,9 +1946,9 @@ 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 1.1.4", + "rustix", "windows-sys 0.61.2", ] @@ -2039,7 +1994,7 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "flate2", @@ -2060,7 +2015,7 @@ dependencies = [ [[package]] name = "tinybus-macros" -version = "0.1.5" +version = "0.1.6" dependencies = [ "proc-macro2", "quote", @@ -2069,7 +2024,7 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "serde", @@ -2079,84 +2034,163 @@ dependencies = [ "tracing", ] +[[package]] +name = "tinystoragedrivers-api" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "async-trait", + "bytes", + "futures-core", + "serde", + "serde_json", + "tinystoragedrivers-types", + "zeroize", +] + +[[package]] +name = "tinystoragedrivers-blob" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +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.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" 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.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" 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-client" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +name = "tinystoragedrivers-connect" +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.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", + "data-encoding", + "rusqlite", "serde", "serde_json", - "tinystoragedrivers-bus", - "tinystoragedrivers-core", - "tinystoragedrivers-secrets", + "sha2 0.11.0", + "tinystoragedrivers-api", + "tinystoragedrivers-connect", + "tinystoragedrivers-types", "tokio", + "zstd", +] + +[[package]] +name = "tinystoragedrivers-kv" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +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.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "data-encoding", "serde", "serde_json", - "sha2 0.10.9", - "thiserror 2.0.20", + "sha2 0.11.0", + "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.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" 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.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +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.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.20", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -2225,7 +2259,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.20", - "tinystoragedrivers-core", + "tinystoragedrivers-types", ] [[package]] @@ -2264,10 +2298,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 +2358,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 +2455,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", @@ -2480,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" @@ -2508,16 +2550,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 +2620,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 +2740,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 +2781,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 +2887,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 +2915,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.4", + "rustix", ] [[package]] @@ -3032,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]] @@ -3053,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 8b18e63c..ce0678a4 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" @@ -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 = { 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.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/Cargo.toml b/crates/tinywallet-bus/Cargo.toml index b0b9c7ef..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,26 +20,16 @@ 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 } +# 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"] } 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-bus/src/lib.rs b/crates/tinywallet-bus/src/lib.rs index 59a0b196..281fcafb 100644 --- a/crates/tinywallet-bus/src/lib.rs +++ b/crates/tinywallet-bus/src/lib.rs @@ -23,7 +23,6 @@ pub mod mnemonic; pub mod names; -#[cfg(feature = "storage")] pub mod storage; #[cfg(feature = "wire")] pub mod tools; @@ -36,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..511f8709 --- /dev/null +++ b/crates/tinywallet-bus/src/storage.rs @@ -0,0 +1,81 @@ +//! Pure storage declarations the host can ensure before starting the module. + +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")] +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, +} + +#[cfg(feature = "wire")] +/// 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. +/// +/// 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-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-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" 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(), diff --git a/crates/tinywallet-module/Cargo.toml b/crates/tinywallet-module/Cargo.toml index c56070f1..6c6023af 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" @@ -80,9 +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-core = { workspace = true } -tinystoragedrivers-bus = { workspace = true } -tinystoragedrivers-client = { workspace = true } +tinystoragedrivers-types = { workspace = true } +tinystoragedrivers-api = { workspace = true } tinystoragedrivers-busproxy = { workspace = true } # Diagnostics for the storage connection and hold-lease renewal. log = "0.4" @@ -96,15 +95,13 @@ 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] +# 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" # The native lifecycle fixture stages and hashes the actual cdylib to attest it. diff --git a/crates/tinywallet-module/src/lib.rs b/crates/tinywallet-module/src/lib.rs index f8db063b..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 and generates the module's storage grant from the same items. -pub use tinywallet_x402::ledger::storage_schema; +/// 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-module/src/lib_tests.rs b/crates/tinywallet-module/src/lib_tests.rs index c3124f99..70b95832 100644 --- a/crates/tinywallet-module/src/lib_tests.rs +++ b/crates/tinywallet-module/src/lib_tests.rs @@ -4,16 +4,21 @@ 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(); + 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/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/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-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 86c515e1..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 { @@ -585,6 +585,14 @@ fn take_request_secrets( #[cfg(test)] 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"); + 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..0485d410 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 { @@ -376,49 +376,18 @@ 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); + use tinystoragedrivers_testkit::{Failing, FaultPlan}; + use tinystoragedrivers_types::{ErrorKind, Scope}; - #[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 - } - } - - 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; 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..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,19 +9,18 @@ use super::*; 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_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}; struct Fixture { wallet: crate::service::Wallet, /// The host's own handle on the scope the module is bound to. - host: ScopedStorage, + host: Storage, _served: tinystoragedrivers_busproxy::ServedStorage, broker: tokio::task::JoinHandle>, } @@ -34,8 +33,10 @@ 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 +69,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, @@ -239,8 +240,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; @@ -374,41 +373,13 @@ 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_core::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-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-module/tests/lifecycle_e2e.rs b/crates/tinywallet-module/tests/lifecycle_e2e.rs index 7342dee4..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; @@ -146,9 +149,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) => { @@ -992,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, @@ -1024,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-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/Cargo.toml b/crates/tinywallet-x402/Cargo.toml index d884a834..20054d2e 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" @@ -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,8 @@ 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] default = ["wire"] @@ -106,7 +108,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", "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/README.md b/crates/tinywallet-x402/README.md index c8326dc9..394c6e06 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 - 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. + the stable `tinystoragedrivers-api` / `tinystoragedrivers-types` contracts + (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/blocking.rs b/crates/tinywallet-x402/src/ledger/blocking.rs new file mode 100644 index 00000000..d823b594 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/blocking.rs @@ -0,0 +1,96 @@ +//! 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(runtime_start_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(thread_start_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() + } + } +} + +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..cfef54ba --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/blocking_tests.rs @@ -0,0 +1,68 @@ +//! Tests for the dedicated runtime used by blocking x402 callers. + +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 { .. }"); + + 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] +#[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); + 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] +#[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() + .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/faulty.rs b/crates/tinywallet-x402/src/ledger/faulty.rs index 7b55807f..718e85ef 100644 --- a/crates/tinywallet-x402/src/ledger/faulty.rs +++ b/crates/tinywallet-x402/src/ledger/faulty.rs @@ -1,88 +1,54 @@ -//! 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; +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 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 55564282..3033e733 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 //! @@ -59,6 +58,7 @@ //! [`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; @@ -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/mod_holds_tests.rs b/crates/tinywallet-x402/src/ledger/mod_holds_tests.rs index 0118d175..0fd46e6e 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::*; @@ -247,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::None, + Precondition::Version(version), ) .await .unwrap(); @@ -356,7 +364,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..7f224dd4 100644 --- a/crates/tinywallet-x402/src/ledger/mod_tests.rs +++ b/crates/tinywallet-x402/src/ledger/mod_tests.rs @@ -7,11 +7,12 @@ use std::sync::atomic::{AtomicU64, Ordering}; use chrono::{DateTime, Duration, TimeZone, Utc}; +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_core::{Blocking, Version}; +use tinystoragedrivers_types::{Precondition, Version}; const SESSION: &str = "session-a"; static NEXT_TEST_RECORD: AtomicU64 = AtomicU64::new(1); @@ -265,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(); @@ -565,10 +599,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 +613,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 +628,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 +645,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 +654,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"); } @@ -740,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}), - tinystoragedrivers_core::Precondition::None, + precondition, ) .await .unwrap(); diff --git a/crates/tinywallet-x402/src/ledger/persist.rs b/crates/tinywallet-x402/src/ledger/persist.rs index d59246af..d49242b0 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,14 +13,12 @@ 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, Storage, StreamStore}; +use tinystoragedrivers_types::{ErrorKind, Precondition, Version, WriteOptions}; +use super::blocking::Blocking; use super::schema::{ - BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, LEGACY_BUDGET_COLLECTION, - LEGACY_PAYMENTS_STREAM, OWNER, PAYMENTS_STREAM, StoredPayment, + self, BUDGETS_COLLECTION, BUDGETS_VERSION, HOLDS_ID, PAYMENTS_STREAM, StoredPayment, }; use super::types::PaymentRecord; @@ -52,28 +50,18 @@ 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. + /// Create a fresh real in-memory backend for this crate's unit tests. + #[cfg(test)] #[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) + #[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)) } } @@ -177,7 +165,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,34 +176,12 @@ 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()?; - 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 + 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 })?; - 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(()) + Ok(persist) } /// Records from stream offset `from` to the end, with the next offset. 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.rs b/crates/tinywallet-x402/src/ledger/schema.rs index 9b22d516..be53ddd9 100644 --- a/crates/tinywallet-x402/src/ledger/schema.rs +++ b/crates/tinywallet-x402/src/ledger/schema.rs @@ -1,28 +1,160 @@ -//! 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 serde_json::{Map, Value, json}; +use tinystoragedrivers_api::{DocumentStore, StreamStore}; +use tinystoragedrivers_types::{ + CollectionSpec, ErrorKind, Precondition, StorageError, WriteOptions, }; -use super::types::PaymentStatus; +#[path = "schema_payment.rs"] +mod payment; +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"; +/// Schema version for [`BUDGETS_COLLECTION`]. +pub(super) const BUDGETS_VERSION: u32 = 2; +/// Identifier of the budget-hold document. +pub(super) const HOLDS_ID: &str = "holds"; +/// Append-only payment history stream. +pub(super) const PAYMENTS_STREAM: &str = "wallet.payments"; +/// Previous budget collection name migrated on first open. +const LEGACY_BUDGET_COLLECTION: &str = "x402_budget"; +/// Previous payment stream name migrated on first open. +const LEGACY_PAYMENTS_STREAM: &str = "x402.payments"; + +const MIGRATIONS_COLLECTION: &str = "wallet.migrations"; +const MIGRATIONS_ID: &str = "x402"; +const BATCH_SIZE: usize = 512; + +/// 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.doc.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_or(Precondition::Absent, |record| { + Precondition::Version(record.version) + }); + match documents + .put(MIGRATIONS_COLLECTION, MIGRATIONS_ID, next, precondition) + .await + { + Ok(_) => Ok(()), + Err(error) if matches!(error.kind(), ErrorKind::Conflict | ErrorKind::AlreadyExists) => { + let latest = documents.get(MIGRATIONS_COLLECTION, MIGRATIONS_ID).await?; + let completed = latest + .as_ref() + .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) } + } + Err(error) => Err(error), + } +} -impl From for StoredPaymentStatus { - fn from(status: PaymentStatus) -> Self { +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.doc).unwrap_or_default(); + let migrated = json!({ "holds": holds.clone() }); + match documents.get(BUDGETS_COLLECTION, HOLDS_ID).await? { + Some(existing) if budget_target_matches(&existing, &migrated, legacy.meta.expires_ms) => { + Ok(()) + } + Some(_) => Err(StorageError::backend( + "wallet budget migration found conflicting target data", + )), + None => { + // `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); + } + match documents + .put_with( + BUDGETS_COLLECTION, + HOLDS_ID, + migrated.clone(), + Precondition::Absent, + options, + ) + .await + { + Ok(_) => Ok(()), + 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) + }) { + Ok(()) + } else { + Err(error) + } + } + Err(error) => Err(error), + } + } + } +} + +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 { - PaymentStatus::Pending => Self::Pending, - PaymentStatus::Settled => Self::Settled, - PaymentStatus::Failed => Self::Failed, - PaymentStatus::Denied => Self::Denied, + 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 PaymentStatus { +impl From for super::types::PaymentStatus { fn from(status: StoredPaymentStatus) -> Self { match status { StoredPaymentStatus::Pending => Self::Pending, @@ -33,6 +165,201 @@ impl From for 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 { + let batch_start = source_offset; + let window = streams + .read_window(LEGACY_PAYMENTS_STREAM, source_offset, BATCH_SIZE) + .await?; + for (index, entry) in window.iter().enumerate() { + 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", + )); + } + } + let Some(last) = window.last() else { + return Err(StorageError::backend( + "wallet payment migration source ended before its reported length", + )); + }; + 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", + )); + } + 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 = 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( + "wallet payment migration source changed while being read", + )); + } + 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", + )); + } + Ok(()) +} + +async fn append_migration_batch( + streams: &dyn StreamStore, + target_offset: u64, + migrated: &[Value], +) -> tinystoragedrivers_types::Result<()> { + if migrated.is_empty() { + return Ok(()); + } + let target_len = streams.len(PAYMENTS_STREAM).await?; + if target_len < target_offset { + return Err(StorageError::backend( + "wallet payment migration target stream changed while being written", + )); + } + 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 = offset_after( + target_offset, + already_written, + "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), + } +} + +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, + entries: Vec, +) -> tinystoragedrivers_types::Result)>> { + 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 (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.saturating_add(index as u64); + log::warn!( + "[x402::ledger] skipping invalid legacy payment at offset {offset}: {error}" + ); + } + } + } + Ok(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() +} + #[cfg(test)] #[path = "schema_tests.rs"] mod tests; diff --git a/crates/tinywallet-bus/src/storage/payment.rs b/crates/tinywallet-x402/src/ledger/schema_payment.rs similarity index 57% rename from crates/tinywallet-bus/src/storage/payment.rs rename to crates/tinywallet-x402/src/ledger/schema_payment.rs index c693bd4f..1cde5906 100644 --- a/crates/tinywallet-bus/src/storage/payment.rs +++ b/crates/tinywallet-x402/src/ledger/schema_payment.rs @@ -1,102 +1,86 @@ -//! The payment record as it is stored, and the v1 shape it migrates from. +//! Owner-local conversion from legacy x402 payment rows to the shared +//! `wallet.payments` storage record. -use serde::{Deserialize, Deserializer, Serialize}; +use serde::Deserialize; +use serde::de::Deserializer; +use tinywallet_bus::storage::{StoredPaymentRecord, StoredPaymentStatus}; -/// 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, +pub(crate) type StoredPayment = StoredPaymentRecord; + +/// 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(crate) fn convert_legacy_payment(legacy: LegacyPayment) -> StoredPaymentRecord { + legacy.into() } -/// 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. +/// 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, - /// The amount in atomic units of `asset`. + /// Amount in atomic units. pub amount_atomic: u64, - /// The amount formatted for people. + /// Human-readable amount. pub amount_display: String, - /// Who was paid. + /// Payment recipient. pub recipient: String, - /// The network, in CAIP-2 form. + /// CAIP-2 network identifier. pub network: String, - /// The settlement transaction, once reported. - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default)] + /// Settlement transaction, if available. pub tx_signature: Option, - /// Where the payment stands. + /// Payment lifecycle state. pub status: StoredPaymentStatus, - /// When this state was written, in epoch milliseconds. + #[serde(rename = "timestamp", deserialize_with = "instant_ms")] + /// Timestamp of this state, normalized to epoch milliseconds. pub timestamp_ms: i64, - /// When an exported authorization becomes unusable, in epoch milliseconds. - #[serde(default, skip_serializing_if = "Option::is_none")] + #[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. - #[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")] + #[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, - /// The block height at which the expiry was observed. - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default)] + /// Block height at which expiry was observed. pub authorization_expiry_observed_height: Option, - /// The session that made the payment. + /// Session that initiated 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, + /// 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 StoredPayment { +impl From for StoredPaymentRecord { fn from(legacy: LegacyPayment) -> Self { Self { id: legacy.id, @@ -108,10 +92,10 @@ impl From for StoredPayment { 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, @@ -138,10 +122,10 @@ fn optional_instant_ms<'de, D: Deserializer<'de>>( .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 { +/// 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)?; @@ -162,12 +146,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 +176,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 +196,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..60b92dc8 --- /dev/null +++ b/crates/tinywallet-x402/src/ledger/schema_payment_tests.rs @@ -0,0 +1,186 @@ +//! Tests for the x402 owner's conversion of legacy payment records. + +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", + "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(); + let payment = convert_legacy_payment(legacy); + + 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()); +} + +fn convert(value: serde_json::Value) -> Result { + serde_json::from_value::(value).map(convert_legacy_payment) +} + +#[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", + "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, 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] +#[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!({ + "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] +#[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!({ + "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, 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); + assert_eq!(pending.committed_hold, None); +} + +#[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", + "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_tests.rs b/crates/tinywallet-x402/src/ledger/schema_tests.rs index 77f07572..a6de97f0 100644 --- a/crates/tinywallet-x402/src/ledger/schema_tests.rs +++ b/crates/tinywallet-x402/src/ledger/schema_tests.rs @@ -1,21 +1,180 @@ -//! 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 super::*; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; -use serde_json::{Value, json}; -use tinystoragedrivers_core::{ - Blocking, MemoryStorage, MigrateOptions, Registry, Scope, ScopedStorage, StorageBackend, +use async_trait::async_trait; +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 super::storage_schema; +use crate::ledger::blocking::Blocking; -const V1_PAYMENT_MS: i64 = 1_773_576_000_000; // 2026-03-15T12:00:00Z +const V1_PAYMENT_MS: i64 = 1_773_576_000_000; -fn v1_payment() -> Value { +#[derive(Debug, Clone, Copy)] +enum RaceAction { + CompleteMarker, + ExistingMarker, + MatchingBudget, + ExistingBudget, + 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", + )); + } + 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) + } + + 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::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( + kind, + "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()) +} + +fn legacy_payment() -> Value { json!({ "id": "pay-1", "url": "https://api.example.com/data", @@ -34,52 +193,228 @@ 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 +fn legacy_payments(count: usize) -> Vec { + (0..count) + .map(|index| { + let mut payment = legacy_payment(); + payment["id"] = json!(format!("pay-{index}")); + payment }) - .unwrap() + .collect() } -fn append_v1(scoped: &ScopedStorage, entries: Vec) { - let streams = Arc::clone(scoped.streams()); +fn append_values( + storage: &tinystoragedrivers_api::Storage, + stream: &'static str, + values: Vec, +) { + let streams = Arc::clone(storage.streams()); Blocking::new() .unwrap() .run(async move { - for entry in entries { - streams.append("x402.payments", entry).await.unwrap(); - } + 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), + WrongOffset(&'static str), + ReadError(&'static str), + Overshoot(&'static str), + AppendError(&'static str), + AppendConflictAfterWrite(&'static str), +} + +#[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 { + if matches!(self.fault, ReadFault::AppendError(name) if stream == name) { + return Err(tinystoragedrivers_types::StorageError::backend( + "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 + } + + async fn read_window( + &self, + stream: &str, + from: u64, + 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, + } + } + + 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) + ); +} + #[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); +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(); + let streams = std::sync::Arc::clone(storage.streams()); + Blocking::new() + .unwrap() + .run(async move { + streams + .append("x402.payments", legacy_payment()) + .await + .unwrap(); + }) + .unwrap(); let ledger = PaymentLedger::open( - LedgerStorage::from_scoped(&scoped), + LedgerStorage::from_storage(&storage), "session-a", SpendingBudget::default(), ) @@ -91,50 +426,877 @@ 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")); + + let reopened = PaymentLedger::open( + LedgerStorage::from_storage(&storage), + "session-a", + SpendingBudget::default(), + ) + .unwrap(); + assert_eq!(reopened.recent_payments(10), records); } #[test] -fn a_ledger_refuses_to_open_while_unmigrated_payments_remain() { - let (_backend, scoped) = scoped(); - append_v1(&scoped, vec![v1_payment()]); +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_with( + "x402_budget", + HOLDS_ID, + json!({ + "holds": { + "old-writer:7": { + "amount": 321, + "expires_at_ms": 1_800_000_000_000_i64 + } + } + }), + 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 payments must block opening"); - }; - assert!(error.contains("unmigrated x402.payments"), "{error}"); + assert_eq!(migrated.meta.schema, 2); + 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 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 a_ledger_refuses_to_open_while_legacy_budget_holds_remain() { - let (_backend, scoped) = scoped(); - let documents = Arc::clone(scoped.documents()); +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", - json!({ "holds": {} }), - tinystoragedrivers_core::Precondition::None, + HOLDS_ID, + json!({ "holds": { "old": { "amount": 12, "expires_at_ms": 1_800_000_000_000_i64 }}}), + Precondition::Absent, ) .await - .unwrap(); }) + .unwrap() .unwrap(); - let opened = PaymentLedger::open( - LedgerStorage::from_scoped(&scoped), - "session-a", - SpendingBudget::default(), + 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![])) ); - let Err(error) = opened else { - panic!("legacy holds must block opening"); + 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 owner_migration_accepts_an_already_existing_matching_marker() { + let storage = test_storage(); + let documents = RacingDocuments { + inner: Arc::clone(storage.documents()), + action: RaceAction::ExistingMarker, }; - assert!(error.contains("legacy x402 budget holds"), "{error}"); + 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] { + 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::WrongBudgetSchema => assert_eq!(target.meta.schema, 1), + RaceAction::WrongBudgetExpiry => { + assert_eq!(target.meta.expires_ms, Some(1_900_000_000_001)); + } + RaceAction::CompleteMarker + | RaceAction::ExistingMarker + | RaceAction::MatchingBudget + | RaceAction::ExistingBudget => 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 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 })]] { + 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(); + 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 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(); + 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", 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); +} + +#[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_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(); + 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_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()); + let streams = Arc::clone(storage.streams()); + assert_eq!( + Blocking::new() + .unwrap() + .run(async move { streams.len("wallet.payments").await }) + .unwrap() + .unwrap(), + 1 + ); +} + +#[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); +} + +#[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 + ); } 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/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 deleted file mode 100644 index c59347df..00000000 Binary files a/scripts/__pycache__/check-bus-boundaries.cpython-314.pyc and /dev/null differ diff --git a/scripts/check-bus-boundaries.py b/scripts/check-bus-boundaries.py index ca17ad88..dddd628a 100644 --- a/scripts/check-bus-boundaries.py +++ b/scripts/check-bus-boundaries.py @@ -10,24 +10,26 @@ "itoa", "memchr", "zmij", } 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"} +TSD_TYPES = "tinystoragedrivers-types" +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 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_KINDS = {"lib", "rlib", "dylib", "cdylib", "staticlib", "proc-macro"} + def forbidden(name): """Whether `name` is a chain/key implementation the bus must never link.""" @@ -35,6 +37,28 @@ 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 + return name == TSD_TYPES and is_canonical_tsd_source(source, require_full_hash=True) + + def audit(metadata): packages = {package["id"]: package for package in metadata["packages"]} nodes = {node["id"]: node for node in metadata["resolve"]["nodes"]} @@ -50,7 +74,7 @@ def audit(metadata): continue seen.add(identity) package = packages[identity] - if len(path) > 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"]): @@ -63,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: @@ -82,8 +106,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 +115,72 @@ 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]): + if name == TSD_TYPES and is_canonical_tsd_source(source): 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 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 = [ + "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 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) + 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..e3dfab34 100644 --- a/scripts/check_bus_boundaries_tests.py +++ b/scripts/check_bus_boundaries_tests.py @@ -26,31 +26,106 @@ def test_dev_dependencies_are_exempt(self): 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) + 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 + + "05eaada962decbab33bafa4763d2bd1a67f6b456", + ) + ), + [], + ) + + def test_fork_tsd_types_source_is_rejected(self): + self.assertTrue( + boundary.audit( + metadata( + boundary.TSD_TYPES, + source="git+https://github.com/senamakel/tinystoragedrivers" + "?tag=v2.1.0#3332061434c01872b0161191268166c12563af87", + ) + ) + ) + + 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 + "05eaada962decbab33bafa4763d2bd1a67f6b456")]), + [], + ) + self.assertTrue( + 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", + ) + ] + ) + ) + + +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.1.0 (https://github.com/tinyhumansai/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"]) + + 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__": 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" 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()) 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