diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f5797af --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + +jobs: + verify: + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, macos-15] + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@master + with: + toolchain: 1.95.0 + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: extractions/setup-just@v2 + - uses: foundry-rs/foundry-toolchain@v1 + with: + version: v1.9.0 + - run: forge build --root contracts + - run: just contracts-check + - run: just check + - run: just test + - run: just doc + - run: just package + - uses: actions/upload-artifact@v4 + with: + name: payments-plugin-${{ runner.os }}-${{ runner.arch }} + if-no-files-found: error + path: dist/tempo-*.tar.gz* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f419d3d --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +/target/ +/dist/ +/state/ +/private/ +/profiles/ +/mainnet/ +/smoke*/ +*.key +*.sqlite* +*.keystore +**/wallet.json +**/keystore-*.json +**/password +**/password.* +.env +/contracts/out/ +/contracts/cache/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..49d1995 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,11 @@ +# Payments Plugin development + +This repository is one Cargo crate and one production plugin process, `tempo`. Engine, wallet, protocol types, and native Tempo operations are internal modules. Keep Mesh core currency agnostic. The running plugin always provides payments and refundable identity bonds through one wallet and journal. Prices, bond publication and provider bond requirements are independently optional. Lightning lives in the independent LN Payments Plugin repository. + +Tempo uses one long-lived MPP payment channel per buyer and seller, with OUSD for payment and gas. Buyer configuration and the `control` commands mirror the LN Payments Plugin where they apply. Select `wallet.network` explicitly for mainnet (chain 4217); the default is Moderato testnet (chain 42431). Keep the wallet profile and state database bound to their network, and use a separate `data_dir` when switching. Do not change the asset, network, funding, or refund guarantees implicitly. Network wallet creation, faucet funding, and blockchain transactions require explicit user authorization. Never send mainnet transactions while developing. Routine tests remain deterministic and offline. Never log keys, passwords, invitations, or raw signed transactions. + +Run Cargo commands serially. Use `just check`, `just test`, `just doc`, and `just package`; preserve the lockfile and immutable Mesh dependency pin. Public API and documentation changes require `cargo doc`. Tests use deterministic temporary wallets and loopback fixtures. `offline-fixture` enables separate test executables; normal startup must never select a fabricated backend from configuration or environment. Production packaging builds only the normal binary without fixture features. + +Preserve unresolved obligations, immutable agreements, original signed bytes, and unknown usage across restarts of this version. Do not invent zero usage or replay dispatched inference. This is new code without prototype migration requirements. Keep journal and ledger ownership locks, wallet/node pins, and transaction idempotency intact. + +Keep changes focused and comments accurate. Avoid large comment blocks at function starts. Do not push to a remote or bypass commit hooks. Commit bodies are required, wrap at 72 columns, and must be reviewed when amending. Do not add co-author trailers. Avoid em dashes in prose and hard wrapping Markdown paragraphs. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..08b8abc --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,6721 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "alloy" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9677ab3454c237abe6307805bea17a7912b3a516b606c7b4d3d948b9fede137" +dependencies = [ + "alloy-consensus", + "alloy-contract", + "alloy-core", + "alloy-eips", + "alloy-ens", + "alloy-genesis", + "alloy-network", + "alloy-provider", + "alloy-rpc-client", + "alloy-rpc-types", + "alloy-serde", + "alloy-signer", + "alloy-signer-local", + "alloy-transport", + "alloy-transport-http", + "alloy-trie", +] + +[[package]] +name = "alloy-chains" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e0378e959aa6a885897522080a990e80eb317f1e9a222a604492ea50e13096" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "num_enum", + "serde", + "strum", +] + +[[package]] +name = "alloy-consensus" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ff0c4adba2abdcd9fb5829ae5f4394c06f8585ed283a9ba79aa33763c802e1" +dependencies = [ + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "alloy-trie", + "alloy-tx-macros", + "auto_impl", + "borsh", + "c-kzg", + "derive_more", + "either", + "k256", + "once_cell", + "rand 0.8.6", + "secp256k1 0.30.0", + "serde", + "serde_json", + "serde_with", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-consensus-any" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cdf48932b1db3216175e19a2b476d89d53076e004850ee7983c6807ba0fde74" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "serde", +] + +[[package]] +name = "alloy-contract" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee5c8b5baa015ef1d07a33983794e1539cce36954846a9bc6e1050d8a1ebf9b7" +dependencies = [ + "alloy-consensus", + "alloy-dyn-abi", + "alloy-json-abi", + "alloy-network", + "alloy-network-primitives", + "alloy-primitives", + "alloy-provider", + "alloy-rpc-types-eth", + "alloy-sol-types", + "alloy-transport", + "futures", + "futures-util", + "serde_json", + "thiserror 2.0.18", + "tracing", +] + +[[package]] +name = "alloy-core" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62ddde5968de6044d67af107ad835bc0069a7ca245870b94c5958a7d8712b184" +dependencies = [ + "alloy-dyn-abi", + "alloy-json-abi", + "alloy-primitives", + "alloy-rlp", + "alloy-sol-types", +] + +[[package]] +name = "alloy-dyn-abi" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a475bb02d9cef2dbb99065c1664ab3fe1f9352e21d6d5ed3f02cdbfc06ed1abc" +dependencies = [ + "alloy-json-abi", + "alloy-primitives", + "alloy-sol-type-parser", + "alloy-sol-types", + "itoa", + "serde", + "serde_json", + "winnow", +] + +[[package]] +name = "alloy-eip2124" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "741bdd7499908b3aa0b159bba11e71c8cddd009a2c2eb7a06e825f1ec87900a5" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "crc", + "serde", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-eip2930" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9441120fa82df73e8959ae0e4ab8ade03de2aaae61be313fbf5746277847ce25" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "borsh", + "serde", +] + +[[package]] +name = "alloy-eip7702" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2919c5a56a1007492da313e7a3b6d45ef5edc5d33416fdec63c0d7a2702a0d20" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "borsh", + "k256", + "serde", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-eip7928" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3b12337f74cbfa451cb04dac173974814a6ff463079e1793aa09600ba8813ab" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "borsh", + "once_cell", + "serde", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-eips" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea4c0453065b9206acc0f869a258dc8dcbbd595e144b4446f2c493a24a814d1f" +dependencies = [ + "alloy-eip2124", + "alloy-eip2930", + "alloy-eip7702", + "alloy-eip7928", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "auto_impl", + "borsh", + "c-kzg", + "derive_more", + "either", + "serde", + "serde_with", + "sha2 0.10.9", +] + +[[package]] +name = "alloy-ens" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709ddd5c63a05ac3274143ed0589e129119206f65cf094d2e727499da23efae8" +dependencies = [ + "alloy-contract", + "alloy-primitives", + "alloy-provider", + "alloy-sol-types", + "async-trait", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-evm" +version = "0.37.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acde665074b478c97047dc2a461b4916cac77922d690e5b7415d1941ae7ff7bf" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-hardforks", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-sol-types", + "auto_impl", + "derive_more", + "revm", + "thiserror 2.0.18", + "tracing", +] + +[[package]] +name = "alloy-genesis" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "027ba57264c5d05e4ff52e6090b3592e7526f5d5f5a844add6bbdd17c071c911" +dependencies = [ + "alloy-eips", + "alloy-primitives", + "alloy-serde", + "alloy-trie", + "borsh", + "serde", + "serde_with", +] + +[[package]] +name = "alloy-hardforks" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83ba208044232d14d4adbfa77e57d6329f51bc1acc21f5667bb7db72d88a0831" +dependencies = [ + "alloy-chains", + "alloy-eip2124", + "alloy-primitives", + "auto_impl", + "dyn-clone", + "serde", +] + +[[package]] +name = "alloy-json-abi" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c36c9d7f9021601b04bfef14a4b64849f6d73116a4e91e071d7fbfe10247901" +dependencies = [ + "alloy-primitives", + "alloy-sol-type-parser", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-json-rpc" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4691c60de5d628533752cd07e102d17c47874c06c04c91af33960fd94c484f4" +dependencies = [ + "alloy-primitives", + "alloy-sol-types", + "http", + "serde", + "serde_json", + "thiserror 2.0.18", + "tracing", +] + +[[package]] +name = "alloy-network" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d912bb639bf4ac31e83095afe9e907c8b9774ce0c405966228368309fcfc45f" +dependencies = [ + "alloy-consensus", + "alloy-consensus-any", + "alloy-eips", + "alloy-json-rpc", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rpc-types-any", + "alloy-rpc-types-eth", + "alloy-serde", + "alloy-signer", + "alloy-sol-types", + "async-trait", + "auto_impl", + "derive_more", + "futures-utils-wasm", + "serde", + "serde_json", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-network-primitives" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d875a11bd98595f57f73890f2e36f4a1cca0fa670623e59c9fb08b2389979c36" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-serde", + "serde", +] + +[[package]] +name = "alloy-primitives" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4885c1409b6936c4898e646ef58baf6ec54edaf6d8179f79df805a7b85b7cf3e" +dependencies = [ + "alloy-rlp", + "bytes", + "cfg-if", + "const-hex", + "derive_more", + "foldhash 0.2.0", + "getrandom 0.4.2", + "hashbrown 0.17.1", + "indexmap 2.14.0", + "itoa", + "k256", + "keccak-asm", + "paste", + "proptest", + "rand 0.9.4", + "rapidhash", + "ruint", + "rustc-hash", + "secp256k1 0.31.1", + "serde", + "sha3 0.11.0", +] + +[[package]] +name = "alloy-provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7d526d184d392a8fbcf4293e457789b307bb70646e4f8b902989a246529450" +dependencies = [ + "alloy-chains", + "alloy-consensus", + "alloy-eips", + "alloy-json-rpc", + "alloy-network", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rpc-client", + "alloy-rpc-types-eth", + "alloy-signer", + "alloy-sol-types", + "alloy-transport", + "alloy-transport-http", + "async-stream", + "async-trait", + "auto_impl", + "dashmap", + "either", + "futures", + "futures-utils-wasm", + "lru", + "parking_lot", + "pin-project", + "reqwest 0.13.3", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-rlp" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24671b1f62edcf0f9b62994c7bf72cd621a04a4b99f5020ece1a647b40e2f103" +dependencies = [ + "alloy-rlp-derive", + "arrayvec", + "bytes", +] + +[[package]] +name = "alloy-rlp-derive" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d4311c03125e8a18296504560b9de3d75ecbd0dcda7f71e6cf2a196d57e6fba" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "alloy-rpc-client" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "755447dc13a04c6fa6db8dedb5d32ab5edfa4dd7aa34487ff192a3d873e0e8cf" +dependencies = [ + "alloy-json-rpc", + "alloy-primitives", + "alloy-transport", + "alloy-transport-http", + "futures", + "pin-project", + "reqwest 0.13.3", + "serde", + "serde_json", + "tokio", + "tokio-stream", + "tower", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-rpc-types" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96deb317fe224e98a8ae17a7ed7ea63478867385bf50b7abd53642b24cfd811a" +dependencies = [ + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-serde", + "serde", +] + +[[package]] +name = "alloy-rpc-types-any" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "911a513723ef0b90c3b072f65eebf54d6ebc8b651d06734e252d024bd89b88ac" +dependencies = [ + "alloy-consensus-any", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-serde", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-rpc-types-engine" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b1f682c4881aa7000ac7cc86d7aeeb3b09836a77a90b329820140233651aeea" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "derive_more", + "strum", +] + +[[package]] +name = "alloy-rpc-types-eth" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e1bd19904581ee2075b61faabab1a4cefa8b96d8f2c85343adeae8ecf615e2b" +dependencies = [ + "alloy-consensus", + "alloy-consensus-any", + "alloy-eips", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "alloy-sol-types", + "itertools 0.14.0", + "serde", + "serde_json", + "serde_with", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-serde" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1e97b3e0b9f816b25083045dcfa69431bd059a078e828e4d82d296d1949b96c" +dependencies = [ + "alloy-primitives", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-signer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6913d06ccc0d9c6ab67e2f82e2fbe292706da1f91442f30cded2d04b56bf0d58" +dependencies = [ + "alloy-primitives", + "async-trait", + "auto_impl", + "either", + "elliptic-curve", + "k256", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-signer-local" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c880813cd26bd1ddf8c2236e31295896efd1fcc5cc761d8894ae894503aeea53" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-signer", + "async-trait", + "eth-keystore", + "k256", + "rand 0.8.6", + "thiserror 2.0.18", +] + +[[package]] +name = "alloy-sol-macro" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840128ed2b2971d6d4668a553fe403a82683d3acc646c73e75887e7157408033" +dependencies = [ + "alloy-sol-macro-expander", + "alloy-sol-macro-input", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "alloy-sol-macro-expander" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63ec265e5d65d725175f6ca7711c970824c90ef9c0d1f1973711d4150ee612dd" +dependencies = [ + "alloy-json-abi", + "alloy-sol-macro-input", + "const-hex", + "heck", + "indexmap 2.14.0", + "proc-macro-error2", + "proc-macro2", + "quote", + "sha3 0.11.0", + "syn 2.0.117", + "syn-solidity", +] + +[[package]] +name = "alloy-sol-macro-input" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89bf01077f18650876cfa682eb1f949967b5cde03f1a51c955c469d2c9b4aa67" +dependencies = [ + "alloy-json-abi", + "const-hex", + "dunce", + "heck", + "macro-string", + "proc-macro2", + "quote", + "serde_json", + "syn 2.0.117", + "syn-solidity", +] + +[[package]] +name = "alloy-sol-type-parser" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "857b470ecdd2ed38beaf82ad1a38c516a8ff75266750f38b9eeed001d575241b" +dependencies = [ + "serde", + "winnow", +] + +[[package]] +name = "alloy-sol-types" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384cf252de0db2dec52821eac037a7f57e2aa33fe5b900ce6fe39973402341f1" +dependencies = [ + "alloy-json-abi", + "alloy-primitives", + "alloy-sol-macro", + "serde", +] + +[[package]] +name = "alloy-transport" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "999adfe5c91035c6bf4c4210e0eb8d0caed79d76fbf5e1b70d78721f6097ac04" +dependencies = [ + "alloy-json-rpc", + "auto_impl", + "base64 0.22.1", + "derive_more", + "futures", + "futures-utils-wasm", + "parking_lot", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tower", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-transport-http" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e79a2c1793afc61eed9ca0963da370a988b27d2bbfa67c78013e262d47424c4" +dependencies = [ + "alloy-json-rpc", + "alloy-transport", + "itertools 0.14.0", + "reqwest 0.13.3", + "serde_json", + "tower", + "tracing", + "url", +] + +[[package]] +name = "alloy-trie" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "derive_more", + "nybbles", + "serde", + "smallvec", + "thiserror 2.0.18", + "tracing", +] + +[[package]] +name = "alloy-tx-macros" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406bc1183f6843e0aba09f7b3365e828b597213d60793ba5cb41befc863e3a78" +dependencies = [ + "darling 0.23.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" + +[[package]] +name = "ark-bls12-381" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" +dependencies = [ + "ark-ec", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", +] + +[[package]] +name = "ark-bn254" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" +dependencies = [ + "ark-ec", + "ark-ff 0.5.0", + "ark-std 0.5.0", +] + +[[package]] +name = "ark-ec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" +dependencies = [ + "ahash", + "ark-ff 0.5.0", + "ark-poly", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.5", + "itertools 0.13.0", + "num-bigint", + "num-integer", + "num-traits", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b3235cc41ee7a12aaaf2c575a2ad7b46713a8a50bda2fc3b003a04845c05dd6" +dependencies = [ + "ark-ff-asm 0.3.0", + "ark-ff-macros 0.3.0", + "ark-serialize 0.3.0", + "ark-std 0.3.0", + "derivative", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.3.3", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" +dependencies = [ + "ark-ff-asm 0.4.2", + "ark-ff-macros 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "derivative", + "digest 0.10.7", + "itertools 0.10.5", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.4.1", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a177aba0ed1e0fbb62aa9f6d0502e9b46dad8c2eab04c14258a1212d2557ea70" +dependencies = [ + "ark-ff-asm 0.5.0", + "ark-ff-macros 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "arrayvec", + "digest 0.10.7", + "educe", + "itertools 0.13.0", + "num-bigint", + "num-traits", + "paste", + "zeroize", +] + +[[package]] +name = "ark-ff-asm" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-asm" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-asm" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62945a2f7e6de02a31fe400aa489f0e0f5b2502e69f95f853adb82a96c7a6b60" +dependencies = [ + "quote", + "syn 2.0.117", +] + +[[package]] +name = "ark-ff-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" +dependencies = [ + "num-bigint", + "num-traits", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "ark-poly" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27" +dependencies = [ + "ahash", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "ark-std 0.5.0", + "educe", + "fnv", + "hashbrown 0.15.5", +] + +[[package]] +name = "ark-serialize" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d6c2b318ee6e10f8c2853e73a83adc0ccb88995aa978d8a3408d492ab2ee671" +dependencies = [ + "ark-std 0.3.0", + "digest 0.9.0", +] + +[[package]] +name = "ark-serialize" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" +dependencies = [ + "ark-std 0.4.0", + "digest 0.10.7", + "num-bigint", +] + +[[package]] +name = "ark-serialize" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" +dependencies = [ + "ark-serialize-derive", + "ark-std 0.5.0", + "arrayvec", + "digest 0.10.7", + "num-bigint", +] + +[[package]] +name = "ark-serialize-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213888f660fddcca0d257e88e54ac05bca01885f258ccdf695bafd77031bb69d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "ark-std" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1df2c09229cbc5a028b1d70e00fdb2acee28b1055dfb5ca73eea49c5a25c4e7c" +dependencies = [ + "num-traits", + "rand 0.8.6", +] + +[[package]] +name = "ark-std" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" +dependencies = [ + "num-traits", + "rand 0.8.6", +] + +[[package]] +name = "ark-std" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" +dependencies = [ + "num-traits", + "rand 0.8.6", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "aurora-engine-modexp" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "518bc5745a6264b5fd7b09dffb9667e400ee9e2bbe18555fac75e1fe9afa0df9" +dependencies = [ + "hex", + "num", +] + +[[package]] +name = "auto_impl" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffdcb70bdbc4d478427380519163274ac86e52916e10f0a8889adf0f96d3fee7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "aws-lc-rs" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitcoin-io" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dee39a0ee5b4095224a0cfc6bf4cc1baf0f9624b96b367e53b66d974e51d953" + +[[package]] +name = "bitcoin_hashes" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b" +dependencies = [ + "bitcoin-io", + "hex-conservative", +] + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +dependencies = [ + "serde_core", +] + +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "serde", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "blst" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcdb4c7013139a150f9fc55d123186dbfaba0d912817466282c73ac49e71fb45" +dependencies = [ + "cc", + "glob", + "threadpool", + "zeroize", +] + +[[package]] +name = "borsh" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "byte-slice-cast" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7575182f7272186991736b70173b0ea045398f984bf5ebbb3804736ce1330c9d" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +dependencies = [ + "serde", +] + +[[package]] +name = "c-kzg" +version = "2.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6648ed1e4ea8e8a1a4a2c78e1cda29a3fd500bc622899c340d8525ea9a76b24a" +dependencies = [ + "blst", + "cc", + "glob", + "hex", + "libc", + "once_cell", + "serde", +] + +[[package]] +name = "cc" +version = "1.2.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "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", +] + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-hex" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20d9a563d167a9cce0f94153382b33cb6eded6dfabff03c69ad65a28ea1514e0" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "proptest", + "serde_core", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "const_format" +version = "0.2.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "curve25519-dalek-ng" +version = "4.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c359b7249347e46fb28804470d071c921156ad62b3eef5d34e2ba867533dec8" +dependencies = [ + "byteorder", + "digest 0.9.0", + "rand_core 0.6.4", + "subtle-ng", + "zeroize", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "serde", + "strsim", + "syn 2.0.117", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", + "serde", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive-where" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d08b3a0bcc0d079199cd476b2cae8435016ec11d1c0986c6901c5ac223041534" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version 0.4.1", + "syn 2.0.117", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.0", + "const-oid 0.10.2", + "crypto-common 0.2.2", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "serdect", + "signature", + "spki", +] + +[[package]] +name = "ed25519-consensus" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8465edc8ee7436ffea81d21a019b16676ee3db267aa8d5a8d729581ecf998b" +dependencies = [ + "curve25519-dalek-ng", + "hex", + "rand_core 0.6.4", + "sha2 0.9.9", + "zeroize", +] + +[[package]] +name = "educe" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417" +dependencies = [ + "enum-ordinalize", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "either" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +dependencies = [ + "serde", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "serdect", + "subtle", + "zeroize", +] + +[[package]] +name = "enum-ordinalize" +version = "4.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a1091a7bb1f8f2c4b28f1fe2cef4980ca2d410a3d727d67ecc3178c9b0800f0" +dependencies = [ + "enum-ordinalize-derive", +] + +[[package]] +name = "enum-ordinalize-derive" +version = "4.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca9601fb2d62598ee17836250842873a413586e5d7ed88b356e38ddbb0ec631" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "eth-keystore" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fda3bf123be441da5260717e0661c25a2fd9cb2b2c1d20bf2e05580047158ab" +dependencies = [ + "aes", + "ctr", + "digest 0.10.7", + "hex", + "hmac", + "pbkdf2", + "rand 0.8.6", + "scrypt", + "serde", + "serde_json", + "sha2 0.10.9", + "sha3 0.10.9", + "thiserror 1.0.69", + "uuid 0.8.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.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "fastrlp" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139834ddba373bbdd213dffe02c8d110508dcf1726c2be27e8d1f7d7e1856418" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", +] + +[[package]] +name = "fastrlp" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce8dba4714ef14b8274c371879b175aa55b16b30f269663f19d576f380018dc4" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fixed-hash" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" +dependencies = [ + "byteorder", + "rand 0.8.6", + "rustc-hex", + "static_assertions", +] + +[[package]] +name = "fixed-map" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86ed19add84e8cb9e8cc5f7074de0324247149ffef0b851e215fb0edc50c229b" +dependencies = [ + "fixed-map-derive", +] + +[[package]] +name = "fixed-map-derive" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dc7a9cb3326bafb80642c5ce99b39a2c0702d4bfa8ee8a3e773791a6cbe2407" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "futures-utils-wasm" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42012b0f064e01aa58b545fe3727f90f7dd4020f4a3ea735b50344965f5a57e9" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", + "serde", + "serde_core", +] + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hex-conservative" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b24a59706036ba941c9476a55cd57b82b77f38a3c667d637ee7cabbc85eaedc" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" + +[[package]] +name = "icu_properties" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5a97b8ac6235e69506e8dacfb2adf38461d2ce6d3e9bd9c94c4cbc3cd4400a4" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "potential_utf", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "impl-codec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" +dependencies = [ + "parity-scale-codec", +] + +[[package]] +name = "impl-trait-for-tuples" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0eb5a3343abf848c0984fe4604b2b105da9539376e24fc0a3b0007411ae4fd9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror 2.0.18", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version 0.4.1", + "simd_cesu8", + "syn 2.0.117", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.117", +] + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "jsonrpsee-types" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc88ff4688e43cc3fa9883a8a95c6fa27aa2e76c96e610b737b6554d650d7fd5" +dependencies = [ + "http", + "serde", + "serde_json", + "thiserror 2.0.18", +] + +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "ecdsa", + "elliptic-curve", + "once_cell", + "serdect", + "sha2 0.10.9", +] + +[[package]] +name = "keccak" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" +dependencies = [ + "cpufeatures 0.2.17", +] + +[[package]] +name = "keccak" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e24a010dd405bd7ed803e5253182815b41bf2e6a80cc3bfc066658e03a198aa" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", +] + +[[package]] +name = "keccak-asm" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1766b89733097006f3a1388a02849865d6bc98c89273cb622e29fdd209922183" +dependencies = [ + "digest 0.10.7", + "sha3-asm", +] + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" +dependencies = [ + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "macro-string" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59a9dbbfc75d2688ed057456ce8a3ee3f48d12eec09229f560f3643b9f275653" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mesh-llm-config" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "anyhow", + "dirs", + "libc", + "mesh-llm-types", + "semver 1.0.28", + "serde", + "serde_json", + "skippy-native-runtime", + "skippy-protocol", + "toml", + "toml_edit", + "url", + "windows-sys 0.61.2", +] + +[[package]] +name = "mesh-llm-plugin" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "anyhow", + "async-trait", + "mesh-llm-config", + "prost", + "prost-build", + "protoc-bin-vendored", + "rmcp", + "schemars 1.2.1", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "mesh-llm-tempo" +version = "0.1.0" +dependencies = [ + "alloy", + "anyhow", + "axum", + "clap", + "fs2", + "hex", + "mesh-llm-plugin", + "rand 0.8.6", + "reqwest 0.12.28", + "rusqlite", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "tempo-alloy", + "tokio", + "tracing", + "uuid 1.23.1", + "zeroize", +] + +[[package]] +name = "mesh-llm-types" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "hex", + "serde", + "serde_json", + "sha2 0.11.1", + "skippy-model-artifact", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "modular-bitfield" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2956e537fc68236d2aa048f55704f231cc93f1c4de42fe1ecb5bd7938061fc4a" +dependencies = [ + "modular-bitfield-impl", + "static_assertions", +] + +[[package]] +name = "modular-bitfield-impl" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59b43b4fd69e3437618106f7754f34021b831a514f9e1a98ae863cabcd8d8dad" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" +dependencies = [ + "serde", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "nybbles" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d49ff0c0d00d4a502b39df9af3a525e1efeb14b9dabb5bb83335284c1309210" +dependencies = [ + "alloy-rlp", + "cfg-if", + "proptest", + "ruint", + "serde", + "smallvec", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "serdect", + "sha2 0.10.9", +] + +[[package]] +name = "parity-scale-codec" +version = "3.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799781ae679d79a948e13d4824a40970bfa500058d245760dd857301059810fa" +dependencies = [ + "arrayvec", + "bitvec", + "byte-slice-cast", + "const_format", + "impl-trait-for-tuples", + "parity-scale-codec-derive", + "rustversion", + "serde", +] + +[[package]] +name = "parity-scale-codec-derive" +version = "3.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b4653168b563151153c9e4c08ebed57fb8262bebfa79711552fa983c623e7a" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "pbkdf2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pest" +version = "2.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662" +dependencies = [ + "memchr", + "ucd-trie", +] + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap 2.14.0", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.117", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", + "serdect", +] + +[[package]] +name = "primitive-types" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b34d9fd68ae0b74a41b21c03c2f62847aa0ffea044eee893b4c140b37e244e2" +dependencies = [ + "fixed-hash", + "impl-codec", + "uint", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "num-traits", + "rand 0.9.4", + "rand_chacha 0.9.0", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "prost" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" +dependencies = [ + "heck", + "itertools 0.14.0", + "log", + "multimap", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn 2.0.117", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "prost-types" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" +dependencies = [ + "prost", +] + +[[package]] +name = "protoc-bin-vendored" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8760a25b6ff9c620324822737e468478fa092234190d2e449760344354896ed9" +dependencies = [ + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", +] + +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73fa2624782ca04cd44f51554566717377acd240e4c0016d757dd74fccc9324f" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2417e9817fa237dab803ad4dda7357a111656e242959cc6b8f9a1a583367d42" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d189c34636356a46a7ed3188233dc8a88c431278cc54d4a19b096a2d270e985" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171e39f1e846e5f322ced1ac3b8d4cd3a3833ca24b6e5d58b3632574fe6204fa" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "873cdcc097593432086661aa432b8078f1cd87bfb02847c332e98ae2c119e966" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb72df001783b8297847fe8f5f874ee400fd742c843d60583e8c23d96977c7f" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04652167eca899dda05f32f5481adeaf25c623a98ce2fc146a001cc59a2add7" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263a3f48f01e7309e857138bd47f785585b4a005e8e56c6d2824ce91195999c3" + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.4", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", + "serde", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", + "serde", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", + "serde", +] + +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core 0.9.5", +] + +[[package]] +name = "rapidhash" +version = "4.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e48930979c155e2f33aa36ab3119b5ee81332beb6482199a8ecd6029b80b59" +dependencies = [ + "rand 0.9.4", + "rustversion", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.18", +] + +[[package]] +name = "ref-cast" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "reqwest" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62e0021ea2c22aed41653bc7e1419abb2c97e038ff2c33d0e1309e49a97deec0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "reth-chainspec" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-chains", + "alloy-consensus", + "alloy-eips", + "alloy-evm", + "alloy-genesis", + "alloy-primitives", + "alloy-trie", + "auto_impl", + "derive_more", + "reth-ethereum-forks", + "reth-network-peers", + "reth-primitives-traits", + "serde_json", +] + +[[package]] +name = "reth-codecs" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb43f4858fef4e3b42b80954d2edf1ff67c8ad7498347083cdc7d0f6eff2f081" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-genesis", + "alloy-primitives", + "alloy-trie", + "bytes", + "modular-bitfield", + "reth-codecs-derive", + "reth-zstd-compressors", + "serde", +] + +[[package]] +name = "reth-codecs-derive" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5798ae4d6b264764bc0d742468bd32c7fb515e774645d4930f95ff6311f3ae14" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "reth-db-models" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-eips", + "alloy-primitives", + "reth-primitives-traits", +] + +[[package]] +name = "reth-ethereum-forks" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-eip2124", + "alloy-hardforks", + "alloy-primitives", + "auto_impl", + "once_cell", +] + +[[package]] +name = "reth-ethereum-primitives" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rpc-types-eth", + "reth-codecs", + "reth-primitives-traits", + "serde", +] + +[[package]] +name = "reth-evm" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-consensus", + "alloy-eip7928", + "alloy-eips", + "alloy-evm", + "alloy-primitives", + "auto_impl", + "derive_more", + "futures-util", + "reth-execution-errors", + "reth-execution-types", + "reth-primitives-traits", + "reth-storage-api", + "reth-storage-errors", + "reth-trie-common", + "revm", +] + +[[package]] +name = "reth-execution-errors" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-evm", + "alloy-primitives", + "alloy-rlp", + "nybbles", + "reth-storage-errors", + "thiserror 2.0.18", +] + +[[package]] +name = "reth-execution-types" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-evm", + "alloy-primitives", + "derive_more", + "reth-ethereum-primitives", + "reth-primitives-traits", + "reth-trie-common", + "revm", +] + +[[package]] +name = "reth-network-peers" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "serde_with", + "thiserror 2.0.18", + "url", +] + +[[package]] +name = "reth-primitives-traits" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f59c928b2865af5bcdbce94800270b7f7798f27a22ca0aabdd2b7d3e6587c9ce" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-genesis", + "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-eth", + "alloy-trie", + "bytes", + "dashmap", + "derive_more", + "once_cell", + "reth-codecs", + "revm-bytecode", + "revm-primitives", + "revm-state", + "secp256k1 0.30.0", + "serde", + "thiserror 2.0.18", +] + +[[package]] +name = "reth-prune-types" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-primitives", + "derive_more", + "strum", + "thiserror 2.0.18", + "tracing", +] + +[[package]] +name = "reth-rpc-convert" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-consensus", + "alloy-evm", + "alloy-json-rpc", + "alloy-network", + "alloy-primitives", + "alloy-rpc-types-eth", + "auto_impl", + "dyn-clone", + "jsonrpsee-types", + "reth-evm", + "reth-primitives-traits", + "reth-rpc-traits", + "thiserror 2.0.18", +] + +[[package]] +name = "reth-rpc-traits" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936ba1aa863f2bbb2a0b5f28ea8a114058154e74969385ab27355421d56f9a03" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-signer", + "reth-primitives-traits", + "thiserror 2.0.18", +] + +[[package]] +name = "reth-stages-types" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-primitives", + "reth-trie-common", +] + +[[package]] +name = "reth-static-file-types" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-primitives", + "derive_more", + "fixed-map", + "reth-stages-types", + "serde", + "strum", +] + +[[package]] +name = "reth-storage-api" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-consensus", + "alloy-eip7928", + "alloy-eips", + "alloy-primitives", + "alloy-rpc-types-engine", + "auto_impl", + "reth-chainspec", + "reth-db-models", + "reth-ethereum-primitives", + "reth-execution-types", + "reth-primitives-traits", + "reth-prune-types", + "reth-stages-types", + "reth-storage-errors", + "reth-trie-common", + "revm", +] + +[[package]] +name = "reth-storage-errors" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "derive_more", + "reth-codecs", + "reth-primitives-traits", + "reth-prune-types", + "reth-static-file-types", + "revm", + "thiserror 2.0.18", +] + +[[package]] +name = "reth-trie-common" +version = "2.3.0" +source = "git+https://github.com/paradigmxyz/reth?rev=39cf643#39cf643dbaf5f92c201839a7a624cce8cc535735" +dependencies = [ + "alloy-consensus", + "alloy-primitives", + "alloy-rlp", + "alloy-trie", + "derive_more", + "itertools 0.14.0", + "nybbles", + "reth-primitives-traits", + "revm", +] + +[[package]] +name = "reth-zstd-compressors" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1bd4ae4f54a2ba813eef082910bc646bd31cab8ed134308fa71f1068331fb84" +dependencies = [ + "zstd", +] + +[[package]] +name = "revm" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d51c254839fb36357d0b02d02e46ba57e683d7b017e2da33b47ae74685a9e59" +dependencies = [ + "revm-bytecode", + "revm-context", + "revm-context-interface", + "revm-database", + "revm-database-interface", + "revm-handler", + "revm-inspector", + "revm-interpreter", + "revm-precompile", + "revm-primitives", + "revm-state", +] + +[[package]] +name = "revm-bytecode" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e33493cf6d996e9242db4f2002caef48ec9aa8c4f3fff3b18aed10ef3942eec7" +dependencies = [ + "bitvec", + "phf", + "revm-primitives", + "serde", +] + +[[package]] +name = "revm-context" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e48fc736d9542c082ea5305be44b6a14b53a615f0147ad57f62189fd813068" +dependencies = [ + "bitvec", + "cfg-if", + "derive-where", + "revm-bytecode", + "revm-context-interface", + "revm-database-interface", + "revm-primitives", + "revm-state", + "serde", +] + +[[package]] +name = "revm-context-interface" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac68282a454318246817486835a446519291dd0a8167d09de14c7e96f2147696" +dependencies = [ + "alloy-eip2930", + "alloy-eip7702", + "auto_impl", + "either", + "revm-database-interface", + "revm-primitives", + "revm-state", + "serde", +] + +[[package]] +name = "revm-database" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d761681a43e48408ea23f7f66ff56ff7b6128cadb8f9135d1b94787d0c0fc6b4" +dependencies = [ + "alloy-eips", + "derive_more", + "either", + "revm-bytecode", + "revm-database-interface", + "revm-primitives", + "revm-state", + "serde", +] + +[[package]] +name = "revm-database-interface" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96e37d62fa60b45987b408486c84ebef4af4e7ddf1b3b96b4955a7263fd4e92" +dependencies = [ + "auto_impl", + "either", + "revm-primitives", + "revm-state", + "serde", + "thiserror 2.0.18", +] + +[[package]] +name = "revm-handler" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e043ebfc0899c435e44475796285898e4f822e637bd67856da79cc170bd9df" +dependencies = [ + "auto_impl", + "derive-where", + "revm-bytecode", + "revm-context", + "revm-context-interface", + "revm-database-interface", + "revm-interpreter", + "revm-precompile", + "revm-primitives", + "revm-state", + "serde", +] + +[[package]] +name = "revm-inspector" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e470b2a5e177918944d8cd26174455b61b8fbfbbe7fe411d28b4097e410d11e" +dependencies = [ + "auto_impl", + "either", + "revm-context", + "revm-database-interface", + "revm-handler", + "revm-interpreter", + "revm-primitives", + "revm-state", + "serde", +] + +[[package]] +name = "revm-interpreter" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa5547f653f9e4c47b4f9a9075a0b7c0faea5fa29b7873f392733a943837825d" +dependencies = [ + "revm-bytecode", + "revm-context-interface", + "revm-primitives", + "revm-state", + "serde", +] + +[[package]] +name = "revm-precompile" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d785931e4b8750cf9d79c808c22f05979c8d191baafc8badd4651db82584c1c" +dependencies = [ + "ark-bls12-381", + "ark-bn254", + "ark-ec", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "arrayref", + "aurora-engine-modexp", + "cfg-if", + "k256", + "p256", + "revm-context-interface", + "revm-primitives", + "ripemd", + "sha2 0.10.9", +] + +[[package]] +name = "revm-primitives" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66f39151a31afe93d97f7ac894dd9dcc989368d5ccba19ce079bfc1d73b77452" +dependencies = [ + "alloy-primitives", + "once_cell", + "serde", +] + +[[package]] +name = "revm-state" +version = "41.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ef2fffc28acc41e8ef7525f2b1d16288a10f80579a1b33e7e62abc9892314a" +dependencies = [ + "alloy-eip7928", + "bitflags", + "nonmax", + "revm-bytecode", + "revm-primitives", + "serde", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "ripemd" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "rlp" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb919243f34364b6bd2fc10ef797edbfa75f33c252e7998527479c6d6b47e1ec" +dependencies = [ + "bytes", + "rustc-hex", +] + +[[package]] +name = "rmcp" +version = "3.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8be15815186873ea063bf005011d16c356804973489e40c39116ae3a2878d1f" +dependencies = [ + "base64 0.23.1", + "chrono", + "futures", + "indexmap 2.14.0", + "libc", + "pastey", + "pin-project-lite", + "rmcp-macros", + "schemars 1.2.1", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "tracing", + "uuid 1.23.1", +] + +[[package]] +name = "rmcp-macros" +version = "3.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b0748e054a5f5598b3213cf72099ae6b2745ba4d996c59ccf455150a7dbb839" +dependencies = [ + "darling 0.24.1", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.9", +] + +[[package]] +name = "ruint" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0298da754d1395046b0afdc2f20ee76d29a8ae310cd30ffa84ed42acba9cb12a" +dependencies = [ + "alloy-rlp", + "ark-ff 0.3.0", + "ark-ff 0.4.2", + "ark-ff 0.5.0", + "bytes", + "fastrlp 0.3.1", + "fastrlp 0.4.0", + "num-bigint", + "num-integer", + "num-traits", + "parity-scale-codec", + "primitive-types", + "proptest", + "rand 0.8.6", + "rand 0.9.4", + "rlp", + "ruint-macro", + "serde_core", + "valuable", + "zeroize", +] + +[[package]] +name = "ruint-macro" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48fd7bd8a6377e15ad9d42a8ec25371b94ddc67abe7c8b9127bec79bebaaae18" + +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" +dependencies = [ + "rand 0.8.6", +] + +[[package]] +name = "rustc-hex" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" + +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver 1.0.28", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "aws-lc-rs", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +dependencies = [ + "chrono", + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.117", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scrypt" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f9e24d2b632954ded8ab2ef9fea0a0c769ea56ea98bddbafbad22caeeadf45d" +dependencies = [ + "hmac", + "pbkdf2", + "salsa20", + "sha2 0.10.9", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "serdect", + "subtle", + "zeroize", +] + +[[package]] +name = "secp256k1" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b50c5943d326858130af85e049f2661ba3c78b26589b8ab98e65e80ae44a1252" +dependencies = [ + "bitcoin_hashes", + "rand 0.8.6", + "secp256k1-sys 0.10.1", + "serde", +] + +[[package]] +name = "secp256k1" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3c81b43dc2d8877c216a3fccf76677ee1ebccd429566d3e67447290d0c42b2" +dependencies = [ + "bitcoin_hashes", + "rand 0.9.4", + "secp256k1-sys 0.11.0", +] + +[[package]] +name = "secp256k1-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +dependencies = [ + "cc", +] + +[[package]] +name = "secp256k1-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcb913707158fadaf0d8702c2db0e857de66eb003ccfdda5924b5f5ac98efb38" +dependencies = [ + "cc", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "semver-parser" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9900206b54a3527fdc7b8a938bffd94a568bac4f4aa8113b209df75a09c0dec2" +dependencies = [ + "pest", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e72c1c2cb7b223fafb600a619537a871c2818583d619401b785e7c0b746ccde2" +dependencies = [ + "base64 0.22.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.0", + "schemars 0.9.0", + "schemars 1.2.1", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b90c488738ecb4fb0262f41f43bc40efc5868d9fb744319ddf5f5317f417bfac" +dependencies = [ + "darling 0.23.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "serdect" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a84f14a19e9a014bb9f4512488d9829a68e04ecabffb0f9904cd1ace94598177" +dependencies = [ + "base16ct", + "serde", +] + +[[package]] +name = "sha2" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.9.0", + "opaque-debug", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "sha3" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" +dependencies = [ + "digest 0.10.7", + "keccak 0.1.6", +] + +[[package]] +name = "sha3" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be176f1a57ce4e3d31c1a166222d9768de5954f811601fb7ca06fc8203905ce1" +dependencies = [ + "digest 0.11.3", + "keccak 0.2.0", +] + +[[package]] +name = "sha3-asm" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f3f15d4e239ebe08413eed880e0f9b5af4b40ee0472543320efa91d488e96a7" +dependencies = [ + "cc", + "cfg-if", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "simd_cesu8" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +dependencies = [ + "rustc_version 0.4.1", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" + +[[package]] +name = "skippy-model-artifact" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "anyhow", + "async-trait", + "serde", + "serde_json", + "skippy-model-ref", +] + +[[package]] +name = "skippy-model-ref" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "serde", +] + +[[package]] +name = "skippy-native-runtime" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "anyhow", + "hex", + "serde", + "serde_json", + "sha2 0.11.1", +] + +[[package]] +name = "skippy-protocol" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "prost", + "prost-build", + "protoc-bin-vendored", + "serde", + "skippy-tokenizer", +] + +[[package]] +name = "skippy-tokenizer" +version = "0.80.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm?rev=46da729c7102108f71e41a4998f10d498b9d42dd#46da729c7102108f71e41a4998f10d498b9d42dd" +dependencies = [ + "serde", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "subtle-ng" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "734676eb262c623cec13c3155096e08d1f8f29adce39ba17948b18dad1e54142" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn-solidity" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec005042c7d952febc1a3ef5b0f6674e9054aa836877a31c90b20e25b3d31744" +dependencies = [ + "paste", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tempo-alloy" +version = "1.10.1" +source = "git+https://github.com/tempoxyz/tempo?tag=tempo-alloy%401.10.1#3e95ed3d80be0fad2973f1abd2fb403d6c33011a" +dependencies = [ + "alloy-consensus", + "alloy-contract", + "alloy-eips", + "alloy-json-rpc", + "alloy-network", + "alloy-primitives", + "alloy-provider", + "alloy-rpc-client", + "alloy-rpc-types-eth", + "alloy-serde", + "alloy-signer-local", + "alloy-sol-types", + "alloy-transport", + "async-trait", + "dashmap", + "derive_more", + "futures", + "http", + "reqwest 0.13.3", + "serde", + "serde_json", + "tempo-chainspec", + "tempo-contracts", + "tempo-primitives", + "tower", + "tracing", +] + +[[package]] +name = "tempo-chainspec" +version = "1.10.1" +source = "git+https://github.com/tempoxyz/tempo?tag=tempo-alloy%401.10.1#3e95ed3d80be0fad2973f1abd2fb403d6c33011a" +dependencies = [ + "alloy-eips", + "alloy-genesis", + "alloy-primitives", + "once_cell", + "paste", + "serde", + "serde_json", + "tempo-hardfork", + "tempo-primitives", +] + +[[package]] +name = "tempo-contracts" +version = "1.10.1" +source = "git+https://github.com/tempoxyz/tempo?tag=tempo-alloy%401.10.1#3e95ed3d80be0fad2973f1abd2fb403d6c33011a" +dependencies = [ + "alloy-contract", + "alloy-primitives", + "alloy-sol-types", + "serde", + "tempo-hardfork", +] + +[[package]] +name = "tempo-hardfork" +version = "1.10.1" +source = "git+https://github.com/tempoxyz/tempo?tag=tempo-alloy%401.10.1#3e95ed3d80be0fad2973f1abd2fb403d6c33011a" +dependencies = [ + "alloy-eips", + "alloy-hardforks", + "paste", + "serde", +] + +[[package]] +name = "tempo-primitives" +version = "1.10.1" +source = "git+https://github.com/tempoxyz/tempo?tag=tempo-alloy%401.10.1#3e95ed3d80be0fad2973f1abd2fb403d6c33011a" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-network", + "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-eth", + "alloy-serde", + "base64 0.22.1", + "derive_more", + "ed25519-consensus", + "once_cell", + "p256", + "reth-codecs", + "reth-ethereum-primitives", + "reth-primitives-traits", + "reth-rpc-convert", + "revm", + "serde", + "serde_json", + "sha2 0.10.9", + "tempo-contracts", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + +[[package]] +name = "time" +version = "0.3.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85c17d80feb7334b40c484e45ed1a5273dfd8bfda537c3be2e74a06a6686f327" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcef1a61bdb119096e153208ec5cbec23944ce8bca13be5c7f60c634f7403935" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap 2.14.0", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.11+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" +dependencies = [ + "indexmap 2.14.0", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + +[[package]] +name = "uint" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f64bba2c53b04fcab63c01a7d7427eadc821e3bc48c34dc9ba29c501164b52" +dependencies = [ + "byteorder", + "crunchy", + "hex", + "static_assertions", +] + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-segmentation" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" +dependencies = [ + "getrandom 0.2.17", + "serde", +] + +[[package]] +name = "uuid" +version = "1.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" +dependencies = [ + "getrandom 0.4.2", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.71" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.117", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap 2.14.0", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap 2.14.0", + "semver 1.0.28", +] + +[[package]] +name = "wasmtimer" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c598d6b99ea013e35844697fc4670d08339d5cda15588f193c6beedd12f644b" +dependencies = [ + "futures", + "js-sys", + "parking_lot", + "pin-utils", + "slab", + "wasm-bindgen", +] + +[[package]] +name = "web-sys" +version = "0.3.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31141ce3fc3e300ae89b78c0dd67f9708061d1d2eda54b8209346fd6be9a92c" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap 2.14.0", + "prettyplease", + "syn 2.0.117", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.117", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap 2.14.0", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap 2.14.0", + "log", + "semver 1.0.28", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..6ae0e3b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,60 @@ +[package] +name = "mesh-llm-tempo" +version = "0.1.0" +edition = "2024" +rust-version = "1.95" +license = "MIT OR Apache-2.0" +description = "OUSD payments and refundable identity bonds on Tempo for Mesh" +default-run = "tempo" + +[features] +offline-fixture = ["dep:axum"] + +[dependencies] +alloy = { version = "=2.1.1", features = ["signer-keystore"] } +anyhow = "1" +axum = { version = "0.8", optional = true } +clap = { version = "4", features = ["derive"] } +fs2 = "0.4" +hex = "0.4" +mesh-llm-plugin = { git = "https://github.com/Mesh-LLM/mesh-llm", rev = "46da729c7102108f71e41a4998f10d498b9d42dd" } +rand = "0.8" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +rusqlite = { version = "0.37", features = ["bundled"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +tempo-alloy = { git = "https://github.com/tempoxyz/tempo", tag = "tempo-alloy@1.10.1" } +tokio = { version = "1", features = ["full"] } +tracing = "0.1" +uuid = { version = "1", features = ["v4"] } +zeroize = { version = "1", features = ["alloc"] } + +[dev-dependencies] +tempfile = "3" +tokio = { version = "1", features = ["test-util"] } + +[[bin]] +name = "tempo" +path = "src/main.rs" + +[[bin]] +name = "tempo-fixture" +path = "src/bin/tempo-fixture.rs" +required-features = ["offline-fixture"] + +[[bin]] +name = "demo-backend-fixture" +path = "src/bin/demo-backend-fixture.rs" +required-features = ["offline-fixture"] + +[[bin]] +name = "host-smoke" +path = "src/bin/host-smoke.rs" +required-features = ["offline-fixture"] + +[profile.dev] +debug = 0 + +[profile.test] +debug = 0 diff --git a/ORIGIN.md b/ORIGIN.md new file mode 100644 index 0000000..c251523 --- /dev/null +++ b/ORIGIN.md @@ -0,0 +1,9 @@ +# Source provenance + +This repository started from the standalone stablecoin workspace in [Mesh-LLM/mesh-llm](https://github.com/Mesh-LLM/mesh-llm), directory `mesh/docs/plugins/exemplars/stablecoin-payments`, at commit `ef827f66c9fbbc835db00e5d038bd24340e54b64` (`feat(payments): use request-scoped MPP for Tempo`). The original Apache 2.0 license is preserved in [LICENSE](LICENSE). The original manifests declared `MIT OR Apache-2.0`; this distribution includes the Apache license supplied by the source repository. + +The current implementation consolidates the Tempo engine, wallet, shared types, and fixtures into one Cargo package. It ships one plugin process, with direct wallet calls and one combined configuration. Other payment rails, provider IPC, separate wallet packaging, and prototype migration code are omitted. + +The Mesh SDK dependency is pinned to `46da729c7102108f71e41a4998f10d498b9d42dd`. The current companion host is the `peer-evidence` branch based on `dc8a8fafb8bd51efc287840a84b764c35346b21b`. The [recorded exit-delay trial](docs/tempo-exit-testnet-trial.md) used the preceding host/plugin API on the former `codex/tempo-bonds` branch; its preserved revisions and binaries are historical. Tempo is pinned to `tempo-alloy@1.10.1`, commit `3e95ed3d80be0fad2973f1abd2fb403d6c33011a`. The Cargo lockfile preserves compatible dependency resolution. + +Private configuration, credentials, keys, wallet state, source repository Git metadata, fixtures, and build caches are excluded from the production archive. See [architecture](REFERENCE.md) and [release boundaries](docs/production-readiness.md). diff --git a/README.md b/README.md new file mode 100644 index 0000000..9fe2378 --- /dev/null +++ b/README.md @@ -0,0 +1,202 @@ +# Tempo Plugin + +`tempo` provides OUSD payments and refundable identity bonds on Tempo through one wallet and one plugin process. Sellers may set prices and publish a bond independently. Buyers use free inference by default and may separately authorize paid inference or require provider bonds. Choose test OUSD on Moderato or OUSD on mainnet through `wallet.network`; testnet is the default. One Rust crate and one plugin process own payment channels, request agreements, buyer policy, admission, wallet keys, native transactions, settlement, and recovery. Lightning lives in the independent [LN Payments Plugin](https://github.com/Mesh-LLM/ln-payments-plugin), whose configuration and controls this plugin mirrors where they apply. + +Payments use one long-lived native payment channel per buyer and seller. The first paid request opens it, later requests reuse it, and the seller captures only what it billed when the channel closes. See [payment channels](docs/mpp-demo.md). + +This is a developer preview. Two companion Mesh hosts have completed faucet-funded payments with no bonds, the provider bonded and the buyer unbonded, plus delayed exits and full bond refunds on Moderato. Buffered and streaming requests and buyer restart also passed. Those trials used the earlier design with one reserve per request; the long-lived channels have offline validation only. Inference used a canned backend. See the [trial record](docs/tempo-exit-testnet-trial.md) and [release boundaries](docs/production-readiness.md). + +See [bond setup and policies](docs/bonds.md) for origin-signed gossip evidence, provider eligibility, indefinite capital locks, delayed exits, and escrow refunds. The plugin requires the companion Mesh host changes. + +## Build + +Requires Rust 1.95.0, a C compiler, Python 3.12+, and `just`. Contract checks additionally use Foundry 1.9.0 and the pinned Solidity 0.8.30 compiler. Dependency revisions and the Cargo lockfile are pinned. + +```sh +just check +just test +just doc +just package +``` + +`just package` builds only the production `tempo` binary and produces one native archive and SHA-256 sidecar in `dist/`. The package validator checks contents, metadata, the extracted executable, and its manifest. No release is published automatically. + +`just build` also builds the explicitly enabled offline fixture executables. Production startup always opens the native wallet; settings and environment variables cannot select the fabricated backend. Fixture executables are excluded from release archives. + +## Install and configure + +Use the current companion Mesh `peer-evidence` branch for this plugin. The [recorded Moderato trial](docs/tempo-exit-testnet-trial.md) used a historical Mesh 0.80.0 revision and the preceding plugin API; its recorded binary is incompatible with this checkout. The SDK dependency is pinned to `46da729c7102108f71e41a4998f10d498b9d42dd`, the companion stack's additive verifier-contract preparation commit. Other host versions may have a different plugin ABI. + +The SDK revision currently exists in the local Mesh stack and Cargo cache. Fresh machines and CI need that commit published to the configured Git source before they can fetch the dependency. + +Once release archives named `tempo-v-.tar.gz` are published, install by repository name; until then, install a local archive: + +```sh +mesh-llm plugins install Mesh-LLM/ousd-payments-plugin +mesh-llm plugins install --archive dist/tempo-v0.1.0-.tar.gz \ + --name tempo --version 0.1.0 +``` + +### Quick start on testnet + +A buyer that only sees and relays bonded providers needs nothing beyond the install: + +```sh +mesh-llm client --join +``` + +A seller posts the default bond of 1 OUSD with a one-minute exit delay in two commands. `fund` creates the wallet and asks the Moderato faucet for test coins; once they arrive, run `bond_lock` once. The plugin follows the lock until it is finalized and then publishes the bond; `bond_context` shows the published reference: + +```sh +mesh-llm --model +mesh-llm plugins call tempo control --input '{"command":"fund"}' +mesh-llm plugins call tempo control --input '{"command":"bond_lock"}' +``` + +To get the bond back, run `bond_exit`. It needs no arguments, and once the exit delay has passed, the plugin withdraws the bond into the wallet. + +As in the Lightning plugin, a seller prices a model and a buyer turns on paid buying with one command each; no configuration file edit is needed. The seller's `fund` creates its wallet; a buyer creates one with `tempo wallet init` before it starts, then funds it: + +```sh +mesh-llm plugins call tempo control --input \ + '{"command":"set_pricing","model":"","value":{"input_per_million":"1000000","output_per_million":"1000000"}}' +mesh-llm plugins call tempo control --input '{"command":"fund"}' +mesh-llm plugins call tempo control --input \ + '{"command":"policy","value":{"mode":"automatic","daily_budget":"100000"}}' +``` + +The buyer then pays any seller at its quoted rates, within the daily budget, from a channel with a 1 OUSD deposit. + +### Configuration + +A package install needs no `[[plugin]]` entry: installing it grants the plugin's requested exchange hook, and the plugin keeps its configuration and state in `~/.mesh-llm/tempo/`, writing `config.json` there on first start with every setting at its default. Edit that file, or point a `[[plugin]]` entry's `config_path` at another one, as in [the Mesh template](demo/mesh.toml.example); the [buyer](demo/buyer-payments.json.example) and [seller](demo/seller-payments.json.example) examples show paid configurations. A combined configuration looks like this: + +```json +{ + "data_dir": "/absolute/private/node/payments", + "wallet": { + "network": "testnet", + "password_file": "/absolute/private/node/password", + "max_payment": "100000", + "max_fee": "1000" + }, + "prices": { + "SELLER_MODEL_ID": {"input_per_million": "1000000", "output_per_million": "10000000", "cache_discount_percent": 50} + }, + "admission_deposit": "10000", + "policy": {"mode": "automatic", "daily_budget": "50000"}, + "cap": "10000", + "buy_peers": ["SELLER_64_CHARACTER_HEX_PEER_ID"], + "buy_prices": { + "BOUGHT_MODEL_ID": {"input_per_million": "1000000", "output_per_million": "10000000"} + }, + "channel_topup": "50000" +} +``` + +All amounts are integer strings in millionths of OUSD on the selected network. + +| Setting | Meaning | +| --- | --- | +| `prices` | Seller rates per exact model ID, per million input and output tokens. `cache_discount_percent` (0..100) is taken off reported cached input tokens only. An absent or zero price means free inference. | +| `admission_deposit` | As a seller, the upfront a buyer pays on a new channel unless it has paid this seller since the seller started. As a buyer, the most unbilled credit it lets a seller hold on a channel, so at most one upfront. Unset means 0. | +| `policy` | `mode` is `free_only` (the default, no paid buying) or `automatic`. Automatic needs a positive `daily_budget`, which counts the voucher amounts the buyer signs per UTC day. | +| `cap` | The most one request may cost the buyer: its upfront plus the extra voucher amount its bill needs, checked for the worst case before dispatch and for the actual bill after. `0` means no cap; the remaining daily budget still applies. | +| `buy_peers` | Sellers the buyer may pay. Empty, the default, means any seller, as in the Lightning plugin. | +| `buy_prices` | Optional rate ceilings per model. A quote must not exceed the rates and must give at least the cache discount. A model without an entry is bought at the seller's rates, within `cap` and the daily budget, as in the Lightning plugin. | +| `channel_topup` | The deposit of each new channel and the amount of each top-up; 1 OUSD unless set. Automatic mode needs it to be no more than `wallet.max_payment`, and at least `cap`, or at least the daily budget when there is no cap; the `policy` control checks the same. Whatever the settings, the buyer refuses a request whose worst-case bill one top-up could not pay. | +| `wallet.max_payment` | The largest single channel open or top-up deposit the wallet signs. | +| `wallet.max_fee` | The largest fee of any one transaction attempt. | + +Startup writes `policy`, `prices`, and a set `admission_deposit` into the payment ledger, where the [controls](#inspect-and-control) can change them at runtime. Every start re-applies them, so a runtime switch to `free_only`, a removed price or a changed deposit reverts at the next start unless the configuration file is changed too. Startup only adds or updates prices: removing a model from `prices` does not unprice it, so use `set_pricing` without a value, or a zero price. Per-model admission deposits are set with controls only. `buy_peers`, `buy_prices`, and `cap` are read from the configuration file. Optional `bonds.providers` requirements are independent of pricing and seller bond publication. Payment and gas both use OUSD. Test coins have no monetary value; mainnet uses real OUSD. This plugin provides no card processing, bank transfers, or fiat conversion. + +For payments, both peers must select the same network and have unlocked wallets with OUSD for gas. The `fund` control creates the wallet on first use, with a random password in the state directory unless `wallet.password_file` names one, and on testnet asks the faucet for test coins; `bond_lock` creates it too. Payments start after a restart once the wallet exists. The local CLI can create it ahead of time, with the default configuration unless `--config` names another: + +```sh +tempo wallet init +tempo wallet address +``` + +On testnet a buyer only sees sellers with at least the default bond of 1 OUSD and a one-minute exit delay, unless its config sets `bonds.providers` to another requirement; installing the plugin always filters providers by bond. See [bonds](docs/bonds.md). A node without a wallet still verifies other providers' bonds through its RPC and serves free inference; configured prices or automatic buying make startup refuse until a wallet exists. Installation and startup never create or fund a wallet; only `fund`, `bond_lock` and `tempo wallet init` do. On mainnet, fund the address `fund` reports with OUSD on Tempo. Follow the operator setup for permissions, stable Mesh identities, and node startup. + +## Select testnet or mainnet + +| `wallet.network` | Chain ID | Default RPC | Payment and gas asset | +| --- | ---: | --- | --- | +| `"testnet"` (default) | 42431 | `https://rpc.moderato.tempo.xyz` | Test OUSD | +| `"mainnet"` | 4217 | `https://rpc.tempo.xyz` | Mainnet OUSD | + +Both networks use six-decimal OUSD at `0x20c0000000000000000000006a37da5c996874be` and the canonical native reserve. Omitting `wallet.rpc_url` selects the network's default; an explicit URL overrides it and must report the selected chain. The plugin never infers or changes the network from the RPC response. + +To switch, let open channels close or recover them on the current network, stop the node, and choose a config with the target `wallet.network` and its own `data_dir`. Initialize the target wallet once, fund it on that network, and restart. Use [the mainnet example](demo/mainnet-payments.json.example) as a starting point. Switching back uses the original config and state directories. The wallet profile and the state database's wallet pin reject reuse across networks; never edit a profile's chain ID or delete state to bypass those checks. The switch does not transfer or convert tokens. Bonds stay on their original chain; exit and refund them using the original config and state directory. `control fund` reports the active network and wallet asset. + +## Requests and settlement + +Clients send ordinary requests without payment fields; whether a request is paid is the buyer's decision, as in the Lightning plugin. The buyer pays when `policy.mode` is `automatic` and `buy_peers` is empty or lists the selected seller, and mints a request ID for it. Every other request is sent free, and a priced provider rejects it before execution. A seller that does not price the model serves it free. A paid request needs an exact model and a finite token limit at `/v1/chat/completions`: + +```json +{ + "model": "EXACT_ADVERTISED_MODEL_ID", + "messages": [{"role": "user", "content": "Reply OK"}], + "max_tokens": 4 +} +``` + +For streaming, include `"stream": true` and `"stream_options": {"include_usage": true}` in the body. Bodies must fit within 64 KiB and output limits must be 1..4096. Requests to one seller run at once. A request waits only while one with the same body is still in flight, while the buyer's first request to that seller opens the channel, or while the seller answers busy because the buyer has three unpaid bills. The buyer waits up to 25 seconds in all for these and for a new channel or a top-up to finalize, which normally suffices. A 402 while it is still pending is a rare fallback, for example when the wallet's transaction slot is busy, many new sellers are opened at once, or the RPC is slow: the buyer cancels the request with the seller, the channel keeps opening, and the client may send the request again as a new request. + +1. The seller quotes its rates, its view of the channel, and an upfront: the voucher increase over its view it requires before work. This seller asks its `admission_deposit` on a new channel from a buyer that has not paid it since the seller started, and 0 otherwise. +2. The buyer checks the quote against its policy and refuses an upfront that would leave the seller more than the buyer's `admission_deposit` of unbilled credit. Before opening or signing anything, it also checks the worst case: the upfront plus the extra voucher amount a bill would need if every body byte were an input token and the full output limit were used must fit `cap` and the remaining daily budget, and one top-up must be able to pay it. It then opens the channel with `channel_topup` if none exists and signs a cumulative voucher covering the seller's view of the channel plus the upfront. Vouchers are off-chain signatures, and a seller that missed one gets the buyer's latest voucher again. +3. After inference, the seller bills the request at the quoted rates. Output beyond the request's token limit is not billed. +4. The buyer signs a larger voucher only when the bill matches the usage it observed itself, the quoted rates capped at the worst case checked before dispatch (the seller absorbs any prompt longer than the body bound), the earlier bills, and fits `cap`. As in the Lightning plugin, the bills of work already dispatched are paid even when concurrent requests overshoot the daily budget, and a switch to `free_only` sends new requests free but still pays them. Upfront credit pays bills first. Bills are numbered per channel, and the buyer accepts them in order, holding one that arrives early. When a voucher would exceed the deposit, the buyer tops up once by `channel_topup`; later bills wait for that top-up. +5. When the channel closes, the seller captures the billed total, at most the best voucher, and the rest returns to the buyer. + +As in the Lightning plugin, a buyer that has paid a seller, by an upfront or a bill, has standing with it: its later requests and channels need no upfront, and it can run many requests at once. The seller keeps standing in memory for at most 1,024 buyers, and a restart clears it. The seller answers busy while a buyer has three unpaid bills: bills on its open channel that no voucher covers yet, and bills that a closed channel lost, until the operator runs `unblock`. A buyer with standing can still leave bills unpaid; the seller's loss is bounded only by how many requests the buyer starts before three of its bills are unpaid. Usage that arrives after a channel began closing is never billed and is not counted. + +The seller closes a channel when a bill stays unpaid 120 seconds after it was sent, after one hour without requests, or soon after the buyer requests close, and always within the buyer's 900-second grace. The buyer recovers a channel it has not used for two hours by requesting close and withdrawing after the grace. A dishonest seller can keep upfront credit by billing more than was used: vouchers do not prove computation, so choose sellers and `admission_deposit` accordingly. Nothing is settled before close, so a seller that stays unavailable for the buyer's whole 900-second grace after a close request loses everything the channel earned; see the [trust model](REFERENCE.md). Missing usage is never billed as zero, and it does not block the pair: the seller tells the buyer it never bills the request, the buyer closes it unpaid, and its next request is served on the same channel. See [payment channels](docs/mpp-demo.md). + +## Inspect and control + +```sh +mesh-llm plugins call tempo control --input '{"command":"pending"}' +mesh-llm plugins call tempo control --input '{"command":"transactions","limit":20}' +mesh-llm plugins call tempo control --input '{"command":"balance"}' +mesh-llm plugins call tempo control --input '{"command":"fund"}' +mesh-llm plugins call tempo control --input '{"command":"policy","value":{"mode":"automatic","daily_budget":"50000"}}' +mesh-llm plugins call tempo control --input '{"command":"set_pricing","model":"MODEL","value":{"input_per_million":"1000000","output_per_million":"10000000"}}' +mesh-llm plugins call tempo control --input '{"command":"send","operation_id":"UUID","to":"0xRECIPIENT","amount":"1000000","max_fee":"1000"}' +``` + +| Command | Effect | +| --- | --- | +| `balance` | Wallet balance, amounts reserved by unresolved transactions, and spendable balance. | +| `transactions {limit}` | The most recent requests, channels and wallet transactions, newest first, at most `limit` (1..100) of each. Signed bytes and voucher signatures are never shown. | +| `pending` | Active requests and channels, and unresolved wallet transactions, without signatures. | +| `fund` | The wallet address, network and asset to send OUSD to. | +| `send {operation_id, to, amount, max_fee}` | A journaled OUSD transfer from the wallet's own balance. Repeating the same operation UUID returns the same transaction. Sends to the wallet itself, the OUSD token or the reserve contract are refused. Channel deposits are never touched. | +| `policy {value?}` | Show or set the buyer policy, with today's spending and remaining budget. | +| `pricing` | Seller prices and admission deposits. | +| `set_pricing {model, value?}` | Set or, without `value`, remove a model's price. Removal also removes its admission deposit. The host is told to require or stop requiring the payment channel for that model; if that call fails, it is retried on the next reconciliation tick. | +| `set_cache_discount {model, percent}` | Change only the cache discount of a priced model. | +| `admission_deposit {value?, reset}` | Show, set, or reset the node-wide admission deposit. | +| `set_model_admission_deposit {model, value?}` | Set or clear one priced model's own admission deposit. | +| `retry {request_id?}` | Reconcile pending wallet transactions and active requests and channels, or one request. | +| `recover {peer?}` | Buyer: close the channel with a seller, named by its node ID or a unique prefix of at least eight characters, or without `peer` the only open channel. It requests close on chain; the seller then closes, or the buyer withdraws after the grace. | +| `cancel {request_id}` | Buyer: cancel a request that has not started. | +| `unblock {peer}` | Seller: forgive the bills a buyer's closed channels lost, so they no longer count toward the three unpaid bills that make the seller answer busy. The bills stay recorded. | +| `waive {request_id}` | Seller bookkeeping for a request with unknown usage: it only closes the request once the buyer was told that it is never billed or a later request was quoted, and otherwise sends a zero bill. | +| `bond_*` | Bond controls; see [operator actions](docs/bonds.md#operator-actions). | + +Preserve the payment ledger, wallet journal, keys, and persistent Mesh identity across restarts. Never delete state to clear pending work. Recovery and sends require gas and an unlocked wallet. + +The plugin exposes `control` and the read-only `verify_peer_evidence` operation. The companion Mesh host restricts plugin HTTP and MCP calls to trusted loopback clients. Those local clients can invoke wallet-moving `control` commands, including `send`, bond locking and withdrawal. Raw signed transaction submission is not exposed. While the plugin is stopped, the CLI only offers `wallet init` and `wallet address`. + +## Offline integration + +```sh +just build +just smoke /absolute/path/to/matching/mesh-llm /absolute/private/fresh-smoke-directory +``` + +The harness installs an explicitly built fixture entry point under the plugin name, then uses real hosts, plugin IPC, peer transport, an in-process fabricated wallet, and canned inference. It sends a buffered and a streaming request over one channel, restarts the buyer between them, and checks that both used the same open channel. It does not execute Tempo contracts. + +For an explicitly authorized faucet-funded trial, run `just testnet-smoke /absolute/path/to/mesh-llm /absolute/private/fresh-trial-directory` after `just build`. This installs the normal native payment binary on two temporary hosts, creates fresh encrypted wallets, requests Moderato faucet coins, and pays two canned inference requests from one channel opened with 100 atomic test OUSD units: an upfront of 10 covers both bills of 5. Gas is capped at 1000 atomic units per transaction. It preserves wallets, journals, logs, and `result.json` in the private trial directory, then stops both hosts. This command uses the public testnet and must be invoked deliberately. For the payment-and-bond matrix, follow the [trial reproduction steps](docs/tempo-exit-testnet-trial.md#reproduction-and-limits). See [validation](docs/validation.md), [architecture](REFERENCE.md), and [source provenance](ORIGIN.md). diff --git a/REFERENCE.md b/REFERENCE.md new file mode 100644 index 0000000..5999e16 --- /dev/null +++ b/REFERENCE.md @@ -0,0 +1,59 @@ +# Architecture + +Payments Plugin is one Cargo package with one production executable, `tempo`. Mesh supplies inference lifecycle events, authenticated peer transport, and request identity. Payment and bond policy, chain verification, signing and wallet state stay inside the plugin process. Mesh carries origin-signed opaque provider evidence and owns one eligibility cache. It invokes the namespace-restricted verifier on a cache miss and enforces provider eligibility for gossip relay, discovery listings and routing. Mesh refuses a verifier that starts lazily, runs at most one verifier, and registers it before accepting peers, without evidence permission plumbing. Mesh rejects a provider without evidence before asking Tempo. An omitted provider requirement means the network's standard bond; on a network without a configured escrow no bond qualifies. Pricing, paid buying and seller bond publication are independent. Existing identity reads and mesh-ID snapshots supply local context; the sole evidence host RPC publishes or withdraws the local reference. Evidence stays out of admission callbacks. Rejections without a configured escrow carry a deadline a year away, so Mesh keeps them until the verifier restarts or the provider or its evidence changes; bond-state checks and transient failures have nearer deadlines. Mesh caps any verdict at one year. Membership heartbeats never wait for bond verification. Bond-lock controls require the intended mesh ID explicitly and reject an observed mismatch before signing. + +```text +Mesh lifecycle and peer messages + | + +-- tempo + engine + ledger + | + +-- typed wallet calls + Tempo wallet + journal + keys + RPC verification +``` + +| Module | Ownership | +| --- | --- | +| `bonds` | Opaque bond references, independent amount/exit-delay policies and stateless finalized escrow verification with deadlines for the Mesh cache. | +| `tempo::bonds` | Atomic deposits, delayed exits, refunds and durable transaction recovery. | +| `tempo::transaction` | Shared native signing and exact-byte retries for payments, sends and bonds. | +| `tempo::send` | Journaled OUSD transfers out of the wallet's own balance. | +| `runtime` | Plugin registration, startup, host callbacks, and ordered per-peer message handling. | +| `control` | The `control` operation: payment controls named as in the Lightning plugin, wallet sends, recovery and bond commands. | +| `engine`, `engine_admission`, `engine_mpp`, `engine_seller`, `engine_serving` | Request agreements, the buyer's admission wait, bills, the seller's standing and strikes, peer coordination, and recovery for buyers and sellers. | +| `engine_bonds` | The published bond reference: set when a lock finalizes or by the operator, withdrawn with its bond, and repeated until the host accepts it. | +| `engine_channel` | The channel lifecycle: buyer open, top-up and recovery; seller watch, idle and unpaid-bill closes. | +| `protocol`, `contract` | Peer messages, channel and request terms, vouchers, bills, closures, and exact amount serialization. | +| `ledger`, `ledger_settings` | Requests, channels, daily spending, node and wallet pins, runtime settings (policy, prices, admission deposits), and atomic database updates. | +| `tempo::wallet`, `tempo::journal`, `tempo::keys` | Local signing policy, channel operations, nonce ownership, signed transaction persistence, encrypted keys, and exclusive wallet ownership. | +| `tempo::rpc`, `tempo::receipt` | Tempo RPC, native ABI, vouchers, and independent finalized evidence checks. | +| `request_stream` | Bounded request-body receipts required by the pinned host lifecycle. | +| `wallet` | The small typed backend interface used by the native wallet and deterministic fixtures. | + +The engine calls its wallet directly with typed Rust values. There is no wallet provider capability, operation binding, serialization boundary, child process, or separately installed wallet. The backend interface permits deterministic tests without weakening production startup: only the separate, feature-gated fixture executable can load fabricated wallet evidence. + +Authenticated membership and payment control messages remain available independently of provider eligibility. Inference routing requires a current provider verdict. A verifier disconnect, restart or shutdown discards its decisions and withdraws its publication. Projection also checks that the signed record is still current after asynchronous policy checks. + +The engine ledger and wallet journal are separate tables in one SQLite database in `data_dir`, beside the encrypted key. They represent different facts: requests, channels, spending and settings versus signed transactions and nonces. Writes are durable, and one exclusive lock gives a single process ownership of the key, nonces and state. A change to a request and its channel, such as a voucher with its daily spending or a channel close with its requests, commits in one transaction. Payments, sends and bonds share the signed transaction representation and pending-transaction reconciliation. Internal journal reads stay typed; public attempt output removes signed bytes. Idle wallet reconciliation performs no chain reads. Restart recovery reuses original identities and signed bytes; missing usage never becomes a measured zero charge. A request holds its pair's slot for its body, so identical bodies run one at a time; a request with unknown usage stays open for audit without holding it. The seller never bills it once it has told the buyer so, which the buyer acknowledges, or once a later request on the pair is quoted. Each role has its own slots per peer. This is new code with no compatibility or migration layer for earlier versions; the ledger refuses an older schema. + +Startup writes the configured policy, seller prices and a set admission deposit into the ledger settings, as the Lightning plugin does; the engine reads them from there, and controls change them at runtime. Every start re-applies the configured policy and prices, so a runtime switch to `free_only` or a price removed at runtime reverts at the next start unless the configuration file changes too. Startup does not remove ledger prices for models missing from the configuration. Each priced model is registered with the host as requiring the payment channel; changing a price re-registers it, and an unpriced or free model has the requirement withdrawn. One engine lock serializes each settings change with its host call, so host calls follow ledger order, and a host call that fails is repeated on the next reconciliation tick. + +The supported asset is six-decimal Open USD at `0x20c0000000000000000000006a37da5c996874be` on either Tempo network. `wallet.network` selects `testnet` (Moderato, chain 42431, default RPC `https://rpc.moderato.tempo.xyz`) or `mainnet` (chain 4217, default RPC `https://rpc.tempo.xyz`). Testnet is the default. A custom `wallet.rpc_url` does not change the selected network. For payments, both peers must use the same network and have an unlocked wallet funded for gas. Payment and gas use OUSD on that network. + +The wallet profile and the database's wallet pin bind their chain. Use a separate `data_dir` per network. Channel salts include the asset chain ID, and channel IDs, transaction signatures, and EIP-712 vouchers use the selected chain. Wallet calls reject another network's terms before querying or resuming transactions. + +The buyer's voucher authorizes the channel's running total of acknowledged bills plus any unused upfront credit. The seller alone chooses the capture when it closes; the plugin captures the billed total up to the best voucher, but chain enforcement only bounds the capture by the voucher. The upfront is the voucher increase over the seller's view that the seller requires before work. The buyer accepts it only while the seller's unbilled credit, the voucher minus the bills, stays within the buyer's `admission_deposit`: a new channel can get a full upfront and later upfronts can only refill credit to that limit, never stack. A seller that bills a request the buyer refuses, or overstates usage, can therefore keep at most that credit plus the bills the buyer signed. The buyer records an error when a close captures more than the bills it acknowledged. Bills beyond the credit need the buyer's own matching usage observation before it signs. Vouchers never prove computation. + +Standing follows the Lightning plugin. Once a seller admits a newly verified nonzero voucher from a buyer, the buyer has standing: later requests, and the first request on a new channel, need no upfront, so such a channel opens with a zero voucher. Standing lives in memory, for at most 1,024 buyers; the set is cleared when full and at restart. The seller answers `Busy` while the buyer has three unpaid bills: bills on its open channel above the best voucher, and bills on a closed channel that neither its capture nor the seller's best voucher covered, which count until the operator runs `unblock`. Running requests never count, nor does usage that arrives after a channel began closing, which is never billed. Requests run at once, so a buyer with standing can leave many bills unpaid before it reaches three; as in the Lightning plugin, nothing else bounds that exposure. + +Before dispatch, the buyer refuses a request unless its upfront plus the voucher increase a worst-case bill would need fits `cap` and the remaining daily budget. One top-up must also be able to pay its worst-case bill. The buyer tops up when a bill's voucher would exceed the deposit, once per bill, and later bills on the channel wait for it. The top-up must finalize within the seller's 120-second payment time, which a busy wallet transaction slot can delay. Concurrent requests may overshoot the daily budget by their bills, as in the Lightning plugin. The worst case counts every byte of the canonical request body as an input token, plus the full output limit. The seller admits the forwarded request only if its body digest equals the agreed one, which binds that bound to the request that runs. The seller caps every bill at that worst case, and at bill time the buyer refuses a bill above it and checks the cap again; neither the daily budget nor a switch to `free_only` stops paying for work already dispatched. Byte counting only approximates the prompt's token bound: a default system prompt or a tokenizer could produce more tokens than the body has bytes. The seller absorbs that difference, so an honest bill is never refused for it. + +A seller may be behind the buyer's latest voucher, for example after a lost message. The buyer accepts a quote whose voucher is at or below its own, with its channel and payee, and no more bills than its own accepted total plus what its other requests may still be billed; fewer is fine, since a bill may be on its way or may have overtaken the quote; it resends its latest voucher; only increases above its own count against the budget. A seller that never received the first voucher quotes no channel; while the buyer's channel has no bills, the buyer accepts that and sends the existing channel with its voucher. Bills are numbered per channel, and a bill that overtakes an earlier one waits for it. A quote showing a higher voucher than the buyer signed, or other bills, makes the buyer recover the channel. + +The seller never calls `settle`, so everything a channel has earned stays at risk until the seller's close finalizes, not just the latest bill. After a buyer's close request, a seller or its RPC that is unavailable for the whole 900-second grace loses every voucher on that channel: `withdraw` refunds the deposit minus the settled amount, which is zero, and deletes the channel. The seller then records the earned and captured amounts as a channel error. Because an active channel closes only after an hour without requests, the amount at risk grows with the channel's lifetime, bounded by its deposit. A later mitigation is a threshold settle that claims when the voucher exceeds the settled amount by a limit. It would bound the loss to unsettled earnings, at one transaction and one turn of the wallet's transaction slot per settle. + +Both peers trust their configured RPC for payments as well as bonds. Sellers rely on it for opening receipts, channel state, voucher checks, closure and broadcast; buyers rely on it for opening and top-up receipts and close evidence. A lying RPC cannot move funds, but it can lead a seller to serve unpaid requests, fake or hide a close, or censor recovery transactions. + +Each wallet signs at most one unresolved transaction at a time, shared by channel opens, top-ups, closes, recovery, sends and bonds. Reconciliation runs on a 3-second tick, so a wallet lands roughly one transaction per tick. Requests on an existing channel need no transaction: vouchers and bills are off-chain, and the only chain work per request is the seller's read-only verification of a new or higher voucher; a request that presents the voucher the seller already stores needs none. A buyer therefore needs a transaction only for each new seller channel and each top-up; about 8 of them fit within the 25-second admission wait, so a buyer opening channels to many sellers at once should expect retries. A buyer runs any number of requests at once on its channel with a seller, one at a time per body. A seller lands about 1,200 closes per hour. It closes as soon as it sees a close request unless a request on that channel is running, which may delay the close by up to 600 seconds; that leaves at least 300 seconds, about 100 queued closes, before the buyer can withdraw, and a longer close backlog loses those captures. A seller watches its channels with one `eth_getLogs` query per tick for close requests, cancelled close requests and closes naming its payee, from a cursor stored in the ledger. The cursor moves only after a complete scan, and each scan reads the last 16 blocks again. The tick reads channel state only for channels named in those events, channels with a close request still pending (so the 600-second deferral is checked again every tick), closing channels and idle candidates. Every channel is read on the first tick, after a failed scan or a gap of more than 10,000 blocks, and at least every 120 seconds as a backstop against missing logs. These reads do not take the wallet's transaction slot. Opens and top-ups expire after 10 minutes; close and recovery attempts after one hour, so the default three retries outlast the buyer's earliest withdrawal during a fee spike, at the cost of a stuck attempt holding the slot for up to an hour. Other wallet calls, including voucher verification, serialize on the send lock and repeat the reserve ABI check. + +See [payment channels and recovery](docs/mpp-demo.md), [setup](docs/demo.md), [validation](docs/validation.md), and [release boundaries](docs/production-readiness.md). diff --git a/contracts/creation.hex b/contracts/creation.hex new file mode 100644 index 0000000..d507ac9 --- /dev/null +++ b/contracts/creation.hex @@ -0,0 +1 @@ +0x6080604052348015600e575f5ffd5b50610c078061001c5f395ff3fe608060405234801561000f575f5ffd5b506004361061007a575f3560e01c80638e19899e116100585780638e19899e146101fa578063947aca1f1461020d578063f39b11df1461022e578063fc0c546a14610241575f5ffd5b806326d6c97b1461007e57806334980aaa146101c15780634616283a146101d6575b5f5ffd5b61014961008c366004610ac5565b6040805160e0810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810191909152505f9081526020818152604091829020825160e0810184528154815260018201549281019290925260028101546001600160a01b03811693830193909352600160a01b9092046001600160601b03166060820152600382015467ffffffffffffffff166080820152600482015460a082015260059091015460ff16151560c082015290565b6040516101b8919081518152602080830151908201526040808301516001600160a01b0316908201526060808301516001600160601b03169082015260808083015167ffffffffffffffff169082015260a0808301519082015260c09182015115159181019190915260e00190565b60405180910390f35b6101d46101cf366004610ac5565b61026e565b005b6101e163ffffffff81565b60405167ffffffffffffffff90911681526020016101b8565b6101d4610208366004610ac5565b6103bf565b61022061021b366004610adc565b610601565b6040519081526020016101b8565b61022061023c366004610b11565b61064d565b610256676a37da5c996874be608360961b0181565b6040516001600160a01b0390911681526020016101b8565b60015460ff161561029a5760405162461bcd60e51b815260040161029190610b76565b60405180910390fd5b6001805460ff1916811790555f81815260208190526040902060028101546001600160a01b031633146103055760405162461bcd60e51b81526020600482015260136024820152721bdb9b1e48199d5b991a5b99c81dd85b1b195d606a1b6044820152606401610291565b600581015460ff161561034b5760405162461bcd60e51b815260206004820152600e60248201526d3137b732103bb4ba34323930bbb760911b6044820152606401610291565b60048101541561035b57506103b2565b60038101546103749067ffffffffffffffff1642610b9e565b6004820181905560405190815282907f60cbb6dc74d525da91e0b42e761f013888c8089d2ba6949049758e9b0031e0b79060200160405180910390a2505b506001805460ff19169055565b60015460ff16156103e25760405162461bcd60e51b815260040161029190610b76565b6001805460ff1916811790555f81815260208190526040902060028101546001600160a01b0316331461044d5760405162461bcd60e51b81526020600482015260136024820152721bdb9b1e48199d5b991a5b99c81dd85b1b195d606a1b6044820152606401610291565b600581015460ff161580156104655750600481015415155b8015610475575080600401544210155b6104c15760405162461bcd60e51b815260206004820152601e60248201527f626f6e64207374696c6c206c6f636b6564206f722077697468647261776e00006044820152606401610291565b600581018054600160ff19909116179055600281015460405163a9059cbb60e01b81526001600160a01b0382166004820152600160a01b9091046001600160601b03166024820152676a37da5c996874be608360961b019063a9059cbb906044016020604051808303815f875af115801561053e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105629190610bbd565b61059e5760405162461bcd60e51b815260206004820152600d60248201526c1c99599d5b990819985a5b1959609a1b6044820152606401610291565b6002810154604051600160a01b82046001600160601b031681526001600160a01b039091169083907fe700d0d03537293bc0e853f80c1fabfaf919d505fffadc1aedb9f028dd4ae6569060200160405180910390a350506001805460ff19169055565b6040805146602082015230918101919091526001600160a01b0383166060820152608081018290525f9060a0016040516020818303038152906040528051906020012090505b92915050565b6001545f9060ff16156106725760405162461bcd60e51b815260040161029190610b76565b6001805460ff191681179055851580159061068c57508415155b6106c95760405162461bcd60e51b815260206004820152600e60248201526d656d707479206964656e7469747960901b6044820152606401610291565b6001600160601b038416158015906106ea575067ffffffffffffffff831615155b8015610704575063ffffffff67ffffffffffffffff841611155b61073f5760405162461bcd60e51b815260206004820152600c60248201526b696e76616c6964206c6f636b60a01b6044820152606401610291565b6107493383610601565b5f818152602081905260409020600201549091506001600160a01b0316156107a95760405162461bcd60e51b8152602060048201526013602482015272626f6e6420616c72656164792065786973747360681b6044820152606401610291565b6040805160e0810182528781526020808201888152338385019081526001600160601b038981166060860190815267ffffffffffffffff8a8116608088019081525f60a0890181815260c08a018281528c8352988290528a822099518a55965160018a0155945192516001600160a01b03909316600160a01b93909416929092029290921760028701555160038601805467ffffffffffffffff191691909216179055905160048085019190915591516005909301805460ff19169315159390931790925591516370a0823160e01b8152309281019290925290676a37da5c996874be608360961b01906370a0823190602401602060405180830381865afa1580156108b7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108db9190610be3565b6040516323b872dd60e01b81523360048201523060248201526001600160601b0387166044820152909150676a37da5c996874be608360961b01906323b872dd906064016020604051808303815f875af115801561093b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061095f9190610bbd565b61099c5760405162461bcd60e51b815260206004820152600e60248201526d19195c1bdcda5d0819985a5b195960921b6044820152606401610291565b6109af6001600160601b03861682610b9e565b6040516370a0823160e01b8152306004820152676a37da5c996874be608360961b01906370a0823190602401602060405180830381865afa1580156109f6573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a1a9190610be3565b14610a595760405162461bcd60e51b815260206004820152600f60248201526e1a5b995e1858dd0819195c1bdcda5d608a1b6044820152606401610291565b604080513381526001600160601b038716602082015267ffffffffffffffff86168183015290518791899185917f18b5fb8df0840cb34733241ae405b0ab92472b704ae419b279a60b73a3a66b3d919081900360600190a4506001805460ff1916905595945050505050565b5f60208284031215610ad5575f5ffd5b5035919050565b5f5f60408385031215610aed575f5ffd5b82356001600160a01b0381168114610b03575f5ffd5b946020939093013593505050565b5f5f5f5f5f60a08688031215610b25575f5ffd5b853594506020860135935060408601356001600160601b0381168114610b49575f5ffd5b9250606086013567ffffffffffffffff81168114610b65575f5ffd5b949793965091946080013592915050565b6020808252600e908201526d1c99595b9d1c985b9d0818d85b1b60921b604082015260600190565b8082018082111561064757634e487b7160e01b5f52601160045260245ffd5b5f60208284031215610bcd575f5ffd5b81518015158114610bdc575f5ffd5b9392505050565b5f60208284031215610bf3575f5ffd5b505191905056fea164736f6c634300081e000a diff --git a/contracts/foundry.toml b/contracts/foundry.toml new file mode 100644 index 0000000..0f45460 --- /dev/null +++ b/contracts/foundry.toml @@ -0,0 +1,13 @@ +[profile.default] +src = "src" +test = "test" +out = "out" +cache_path = "cache" +solc_version = "0.8.30" +evm_version = "cancun" +optimizer = true +optimizer_runs = 200 +bytecode_hash = "none" + +[fuzz] +runs = 256 diff --git a/contracts/runtime.hex b/contracts/runtime.hex new file mode 100644 index 0000000..28bd6d5 --- /dev/null +++ b/contracts/runtime.hex @@ -0,0 +1 @@ +0x608060405234801561000f575f5ffd5b506004361061007a575f3560e01c80638e19899e116100585780638e19899e146101fa578063947aca1f1461020d578063f39b11df1461022e578063fc0c546a14610241575f5ffd5b806326d6c97b1461007e57806334980aaa146101c15780634616283a146101d6575b5f5ffd5b61014961008c366004610ac5565b6040805160e0810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810191909152505f9081526020818152604091829020825160e0810184528154815260018201549281019290925260028101546001600160a01b03811693830193909352600160a01b9092046001600160601b03166060820152600382015467ffffffffffffffff166080820152600482015460a082015260059091015460ff16151560c082015290565b6040516101b8919081518152602080830151908201526040808301516001600160a01b0316908201526060808301516001600160601b03169082015260808083015167ffffffffffffffff169082015260a0808301519082015260c09182015115159181019190915260e00190565b60405180910390f35b6101d46101cf366004610ac5565b61026e565b005b6101e163ffffffff81565b60405167ffffffffffffffff90911681526020016101b8565b6101d4610208366004610ac5565b6103bf565b61022061021b366004610adc565b610601565b6040519081526020016101b8565b61022061023c366004610b11565b61064d565b610256676a37da5c996874be608360961b0181565b6040516001600160a01b0390911681526020016101b8565b60015460ff161561029a5760405162461bcd60e51b815260040161029190610b76565b60405180910390fd5b6001805460ff1916811790555f81815260208190526040902060028101546001600160a01b031633146103055760405162461bcd60e51b81526020600482015260136024820152721bdb9b1e48199d5b991a5b99c81dd85b1b195d606a1b6044820152606401610291565b600581015460ff161561034b5760405162461bcd60e51b815260206004820152600e60248201526d3137b732103bb4ba34323930bbb760911b6044820152606401610291565b60048101541561035b57506103b2565b60038101546103749067ffffffffffffffff1642610b9e565b6004820181905560405190815282907f60cbb6dc74d525da91e0b42e761f013888c8089d2ba6949049758e9b0031e0b79060200160405180910390a2505b506001805460ff19169055565b60015460ff16156103e25760405162461bcd60e51b815260040161029190610b76565b6001805460ff1916811790555f81815260208190526040902060028101546001600160a01b0316331461044d5760405162461bcd60e51b81526020600482015260136024820152721bdb9b1e48199d5b991a5b99c81dd85b1b195d606a1b6044820152606401610291565b600581015460ff161580156104655750600481015415155b8015610475575080600401544210155b6104c15760405162461bcd60e51b815260206004820152601e60248201527f626f6e64207374696c6c206c6f636b6564206f722077697468647261776e00006044820152606401610291565b600581018054600160ff19909116179055600281015460405163a9059cbb60e01b81526001600160a01b0382166004820152600160a01b9091046001600160601b03166024820152676a37da5c996874be608360961b019063a9059cbb906044016020604051808303815f875af115801561053e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105629190610bbd565b61059e5760405162461bcd60e51b815260206004820152600d60248201526c1c99599d5b990819985a5b1959609a1b6044820152606401610291565b6002810154604051600160a01b82046001600160601b031681526001600160a01b039091169083907fe700d0d03537293bc0e853f80c1fabfaf919d505fffadc1aedb9f028dd4ae6569060200160405180910390a350506001805460ff19169055565b6040805146602082015230918101919091526001600160a01b0383166060820152608081018290525f9060a0016040516020818303038152906040528051906020012090505b92915050565b6001545f9060ff16156106725760405162461bcd60e51b815260040161029190610b76565b6001805460ff191681179055851580159061068c57508415155b6106c95760405162461bcd60e51b815260206004820152600e60248201526d656d707479206964656e7469747960901b6044820152606401610291565b6001600160601b038416158015906106ea575067ffffffffffffffff831615155b8015610704575063ffffffff67ffffffffffffffff841611155b61073f5760405162461bcd60e51b815260206004820152600c60248201526b696e76616c6964206c6f636b60a01b6044820152606401610291565b6107493383610601565b5f818152602081905260409020600201549091506001600160a01b0316156107a95760405162461bcd60e51b8152602060048201526013602482015272626f6e6420616c72656164792065786973747360681b6044820152606401610291565b6040805160e0810182528781526020808201888152338385019081526001600160601b038981166060860190815267ffffffffffffffff8a8116608088019081525f60a0890181815260c08a018281528c8352988290528a822099518a55965160018a0155945192516001600160a01b03909316600160a01b93909416929092029290921760028701555160038601805467ffffffffffffffff191691909216179055905160048085019190915591516005909301805460ff19169315159390931790925591516370a0823160e01b8152309281019290925290676a37da5c996874be608360961b01906370a0823190602401602060405180830381865afa1580156108b7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108db9190610be3565b6040516323b872dd60e01b81523360048201523060248201526001600160601b0387166044820152909150676a37da5c996874be608360961b01906323b872dd906064016020604051808303815f875af115801561093b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061095f9190610bbd565b61099c5760405162461bcd60e51b815260206004820152600e60248201526d19195c1bdcda5d0819985a5b195960921b6044820152606401610291565b6109af6001600160601b03861682610b9e565b6040516370a0823160e01b8152306004820152676a37da5c996874be608360961b01906370a0823190602401602060405180830381865afa1580156109f6573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a1a9190610be3565b14610a595760405162461bcd60e51b815260206004820152600f60248201526e1a5b995e1858dd0819195c1bdcda5d608a1b6044820152606401610291565b604080513381526001600160601b038716602082015267ffffffffffffffff86168183015290518791899185917f18b5fb8df0840cb34733241ae405b0ab92472b704ae419b279a60b73a3a66b3d919081900360600190a4506001805460ff1916905595945050505050565b5f60208284031215610ad5575f5ffd5b5035919050565b5f5f60408385031215610aed575f5ffd5b82356001600160a01b0381168114610b03575f5ffd5b946020939093013593505050565b5f5f5f5f5f60a08688031215610b25575f5ffd5b853594506020860135935060408601356001600160601b0381168114610b49575f5ffd5b9250606086013567ffffffffffffffff81168114610b65575f5ffd5b949793965091946080013592915050565b6020808252600e908201526d1c99595b9d1c985b9d0818d85b1b60921b604082015260600190565b8082018082111561064757634e487b7160e01b5f52601160045260245ffd5b5f60208284031215610bcd575f5ffd5b81518015158114610bdc575f5ffd5b9392505050565b5f60208284031215610bf3575f5ffd5b505191905056fea164736f6c634300081e000a diff --git a/contracts/src/TempoBondEscrow.sol b/contracts/src/TempoBondEscrow.sol new file mode 100644 index 0000000..5f8d568 --- /dev/null +++ b/contracts/src/TempoBondEscrow.sol @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity 0.8.30; + +interface IOUSD { + function balanceOf(address account) external view returns (uint256); + function transferFrom(address from, address to, uint256 amount) external returns (bool); + function transfer(address to, uint256 amount) external returns (bool); +} + +/// A refundable capital lock for one mesh and one host key, without an administrator. +contract TempoBondEscrow { + uint64 public constant MAX_EXIT_DELAY = type(uint32).max; + address public constant token = 0x20c0000000000000000000006a37DA5C996874BE; + + struct Bond { + bytes32 meshId; + bytes32 hostKey; + address refundWallet; + uint96 amount; + uint64 exitDelay; + uint256 withdrawAt; + bool withdrawn; + } + + mapping(bytes32 => Bond) private records; + bool private entered; + + event Locked( + bytes32 indexed bondId, + bytes32 indexed meshId, + bytes32 indexed hostKey, + address refundWallet, + uint96 amount, + uint64 exitDelay + ); + event Withdrawn(bytes32 indexed bondId, address indexed refundWallet, uint96 amount); + + modifier nonReentrant() { + require(!entered, "reentrant call"); + entered = true; + _; + entered = false; + } + + function bondId(address fundingWallet, bytes32 salt) public view returns (bytes32) { + return keccak256(abi.encode(block.chainid, address(this), fundingWallet, salt)); + } + + function getBond(bytes32 id) external view returns (Bond memory) { + return records[id]; + } + + function lock(bytes32 meshId, bytes32 hostKey, uint96 amount, uint64 exitDelay, bytes32 salt) + external + nonReentrant + returns (bytes32 id) + { + require(meshId != bytes32(0) && hostKey != bytes32(0), "empty identity"); + require(amount != 0 && exitDelay != 0 && exitDelay <= MAX_EXIT_DELAY, "invalid lock"); + id = bondId(msg.sender, salt); + require(records[id].refundWallet == address(0), "bond already exists"); + records[id] = Bond(meshId, hostKey, msg.sender, amount, exitDelay, 0, false); + uint256 beforeBalance = IOUSD(token).balanceOf(address(this)); + require(IOUSD(token).transferFrom(msg.sender, address(this), amount), "deposit failed"); + require(IOUSD(token).balanceOf(address(this)) == beforeBalance + amount, "inexact deposit"); + emit Locked(id, meshId, hostKey, msg.sender, amount, exitDelay); + } + + event ExitRequested(bytes32 indexed bondId, uint256 withdrawAt); + + function requestExit(bytes32 id) external nonReentrant { + Bond storage bond = records[id]; + require(bond.refundWallet == msg.sender, "only funding wallet"); + require(!bond.withdrawn, "bond withdrawn"); + if (bond.withdrawAt != 0) return; + bond.withdrawAt = block.timestamp + uint256(bond.exitDelay); + emit ExitRequested(id, bond.withdrawAt); + } + + function withdraw(bytes32 id) external nonReentrant { + Bond storage bond = records[id]; + require(bond.refundWallet == msg.sender, "only funding wallet"); + require( + !bond.withdrawn && bond.withdrawAt != 0 && block.timestamp >= bond.withdrawAt, + "bond still locked or withdrawn" + ); + bond.withdrawn = true; + require(IOUSD(token).transfer(bond.refundWallet, bond.amount), "refund failed"); + emit Withdrawn(id, bond.refundWallet, bond.amount); + } +} diff --git a/contracts/test/TempoBondEscrow.t.sol b/contracts/test/TempoBondEscrow.t.sol new file mode 100644 index 0000000..a254fd9 --- /dev/null +++ b/contracts/test/TempoBondEscrow.t.sol @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity 0.8.30; + +import {TempoBondEscrow} from "../src/TempoBondEscrow.sol"; + +interface Vm { + function etch(address target, bytes calldata code) external; + function warp(uint256 timestamp) external; + function prank(address sender) external; + function expectRevert(bytes calldata reason) external; +} + +contract MockOUSD { + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; + bool public rejectTransfers; + bool public shortDeposit; + + function mint(address account, uint256 amount) external { + balanceOf[account] += amount; + } + + function setRejectTransfers(bool reject) external { + rejectTransfers = reject; + } + + function setShortDeposit(bool short) external { + shortDeposit = short; + } + + function approve(address spender, uint256 amount) external returns (bool) { + allowance[msg.sender][spender] = amount; + return true; + } + + function transferFrom(address from, address to, uint256 amount) external returns (bool) { + if (rejectTransfers) return false; + allowance[from][msg.sender] -= amount; + balanceOf[from] -= amount; + balanceOf[to] += shortDeposit ? amount - 1 : amount; + return true; + } + + function transfer(address to, uint256 amount) external returns (bool) { + if (rejectTransfers) return false; + balanceOf[msg.sender] -= amount; + balanceOf[to] += amount; + return true; + } +} + +contract TempoBondEscrowTest { + Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + TempoBondEscrow private escrow; + MockOUSD private ousd; + bytes32 private constant MESH = bytes32(uint256(1)); + bytes32 private constant HOST = bytes32(uint256(2)); + uint96 private constant AMOUNT = 20_000_000; + + function setUp() public { + escrow = new TempoBondEscrow(); + MockOUSD implementation = new MockOUSD(); + vm.etch(escrow.token(), address(implementation).code); + ousd = MockOUSD(escrow.token()); + ousd.mint(address(this), 1_000_000_000); + ousd.approve(address(escrow), type(uint256).max); + } + + function testIndefiniteLockAndDelayedExitPreserveIdentityAndPrincipal() public { + uint64 delay = 7 days; + bytes32 id = escrow.lock(MESH, HOST, AMOUNT, delay, bytes32(uint256(10))); + TempoBondEscrow.Bond memory bond = escrow.getBond(id); + require(bond.meshId == MESH && bond.hostKey == HOST, "identity changed"); + require(bond.refundWallet == address(this) && bond.amount == AMOUNT, "refund claim changed"); + require(bond.exitDelay == delay && bond.withdrawAt == 0 && !bond.withdrawn, "lock changed"); + vm.expectRevert(bytes("bond already exists")); + escrow.lock(MESH, bytes32(uint256(3)), AMOUNT, delay, bytes32(uint256(10))); + escrow.lock(MESH, bytes32(uint256(3)), AMOUNT, delay, bytes32(uint256(11))); + require(ousd.balanceOf(address(escrow)) == 2 * AMOUNT, "identities shared one deposit"); + vm.warp(block.timestamp + 365 days); + vm.expectRevert(bytes("bond still locked or withdrawn")); + escrow.withdraw(id); + vm.prank(address(0x1234)); + vm.expectRevert(bytes("only funding wallet")); + escrow.requestExit(id); + escrow.requestExit(id); + uint64 deadline = uint64(block.timestamp) + delay; + require(escrow.getBond(id).withdrawAt == deadline, "exit delay did not start at request"); + vm.warp(deadline - 1); + escrow.requestExit(id); + require(escrow.getBond(id).withdrawAt == deadline, "repeated exit reset delay"); + vm.expectRevert(bytes("bond still locked or withdrawn")); + escrow.withdraw(id); + vm.warp(deadline); + vm.prank(address(0x1234)); + vm.expectRevert(bytes("only funding wallet")); + escrow.withdraw(id); + uint256 beforeRefund = ousd.balanceOf(address(this)); + escrow.withdraw(id); + require(ousd.balanceOf(address(this)) == beforeRefund + AMOUNT, "incomplete refund"); + require(escrow.getBond(id).withdrawn, "withdrawal not recorded"); + vm.expectRevert(bytes("bond still locked or withdrawn")); + escrow.withdraw(id); + vm.expectRevert(bytes("bond withdrawn")); + escrow.requestExit(id); + vm.expectRevert(bytes("bond already exists")); + escrow.lock(MESH, HOST, AMOUNT, delay, bytes32(uint256(10))); + } + + function testDepositAndRefundFailuresRemainRecoverable() public { + bytes32 salt = bytes32(uint256(10)); + bytes32 id = escrow.bondId(address(this), salt); + ousd.setRejectTransfers(true); + vm.expectRevert(bytes("deposit failed")); + escrow.lock(MESH, HOST, AMOUNT, 1 days, salt); + require(escrow.getBond(id).refundWallet == address(0), "failed deposit left a bond"); + ousd.setRejectTransfers(false); + escrow.lock(MESH, HOST, AMOUNT, 1 days, salt); + escrow.requestExit(id); + vm.warp(escrow.getBond(id).withdrawAt); + ousd.setRejectTransfers(true); + vm.expectRevert(bytes("refund failed")); + escrow.withdraw(id); + require(!escrow.getBond(id).withdrawn, "failed refund consumed claim"); + ousd.setRejectTransfers(false); + escrow.withdraw(id); + require(ousd.balanceOf(address(this)) == 1_000_000_000, "refund lost principal"); + } + + function testInvalidLocksCannotCreateEvidence() public { + vm.expectRevert(bytes("empty identity")); + escrow.lock(bytes32(0), HOST, AMOUNT, 1, bytes32(0)); + vm.expectRevert(bytes("empty identity")); + escrow.lock(MESH, bytes32(0), AMOUNT, 1, bytes32(0)); + vm.expectRevert(bytes("invalid lock")); + escrow.lock(MESH, HOST, 0, 1, bytes32(0)); + vm.expectRevert(bytes("invalid lock")); + escrow.lock(MESH, HOST, AMOUNT, 0, bytes32(0)); + } + + function testInexactDepositCannotLeaveEvidenceOrLosePrincipal() public { + bytes32 salt = bytes32(uint256(31)); + bytes32 id = escrow.bondId(address(this), salt); + ousd.setShortDeposit(true); + vm.expectRevert(bytes("inexact deposit")); + escrow.lock(MESH, HOST, AMOUNT, 1 days, salt); + require(escrow.getBond(id).refundWallet == address(0), "inexact deposit left evidence"); + require(ousd.balanceOf(address(this)) == 1_000_000_000, "failed lock consumed principal"); + require(ousd.balanceOf(address(escrow)) == 0, "failed lock funded escrow"); + } + + function testMaximumExitDelayCannotOverflowAndTrapPrincipal() public { + vm.expectRevert(bytes("invalid lock")); + escrow.lock(MESH, HOST, AMOUNT, type(uint64).max, bytes32(uint256(98))); + bytes32 id = escrow.lock(MESH, HOST, AMOUNT, escrow.MAX_EXIT_DELAY(), bytes32(uint256(99))); + uint256 expected = block.timestamp + uint256(escrow.MAX_EXIT_DELAY()); + escrow.requestExit(id); + require(escrow.getBond(id).withdrawAt == expected, "exit timestamp truncated"); + vm.warp(expected); + escrow.withdraw(id); + require(ousd.balanceOf(address(this)) == 1_000_000_000, "large delay trapped principal"); + } + + function testFuzzRefundConservesPrincipal(uint96 proposedAmount, uint32 duration) public { + uint96 amount = 1 + proposedAmount % 1_000_000_000; + uint64 delay = 1 + uint64(duration) % 365 days; + bytes32 id = escrow.lock(MESH, HOST, amount, delay, bytes32(uint256(20))); + vm.warp(block.timestamp + 30 days); + escrow.requestExit(id); + vm.warp(escrow.getBond(id).withdrawAt); + escrow.withdraw(id); + require(ousd.balanceOf(address(this)) == 1_000_000_000, "principal changed"); + require(ousd.balanceOf(address(escrow)) == 0, "escrow retained principal"); + } +} diff --git a/demo/buyer-payments.json.example b/demo/buyer-payments.json.example new file mode 100644 index 0000000..0d1e88a --- /dev/null +++ b/demo/buyer-payments.json.example @@ -0,0 +1,25 @@ +{ + "data_dir": "/ABS/private/buyer/payments", + "policy": { + "mode": "free_only", + "daily_budget": "50000" + }, + "cap": "10000", + "buy_peers": [ + "REPLACE_WITH_SELLER_64_CHARACTER_HEX_PEER_ID" + ], + "buy_prices": { + "REPLACE_WITH_EXACT_ADVERTISED_MODEL_ID": { + "input_per_million": "1000000", + "output_per_million": "10000000" + } + }, + "admission_deposit": "10000", + "channel_topup": "50000", + "wallet": { + "network": "testnet", + "password_file": "/ABS/private/buyer/password", + "max_payment": "100000", + "max_fee": "1000" + } +} diff --git a/demo/mainnet-payments.json.example b/demo/mainnet-payments.json.example new file mode 100644 index 0000000..3d2c912 --- /dev/null +++ b/demo/mainnet-payments.json.example @@ -0,0 +1,18 @@ +{ + "data_dir": "/ABS/private/mainnet/payments", + "policy": { + "mode": "free_only", + "daily_budget": "50000" + }, + "cap": "10000", + "buy_peers": [], + "buy_prices": {}, + "admission_deposit": "10000", + "channel_topup": "50000", + "wallet": { + "network": "mainnet", + "password_file": "/ABS/private/mainnet/password", + "max_payment": "100000", + "max_fee": "1000" + } +} diff --git a/demo/mesh.toml.example b/demo/mesh.toml.example new file mode 100644 index 0000000..2b2c4a4 --- /dev/null +++ b/demo/mesh.toml.example @@ -0,0 +1,19 @@ +# Copy separately for each node. All paths are absolute, node-local paths. +# MPP: both peers select the same network and fund OUSD for gas. Defaults use Moderato. +version = 1 + +# BUYER ONLY: uncomment this table and run `mesh-llm serve` without --model. +# This routes remote inference while preserving the explicit node-key identity. +# [runtime] +# mode = "on_demand" + +# A package install needs no plugin entry: installing grants the requested +# exchange hook, and Tempo keeps its config in ~/.mesh-llm/tempo/config.json. +# Uncomment to use another config file instead. +# [[plugin]] +# name = "tempo" +# [plugin.settings] +# config_path = "/ABS/private/NODE/payments.json" + +# Tempo requires companion Mesh peer evidence and manifest-based enforcement. +# Its verifier and namespace are discovered from the manifest. diff --git a/demo/seller-payments.json.example b/demo/seller-payments.json.example new file mode 100644 index 0000000..5087f19 --- /dev/null +++ b/demo/seller-payments.json.example @@ -0,0 +1,17 @@ +{ + "data_dir": "/ABS/private/seller/payments", + "prices": { + "REPLACE_WITH_EXACT_ADVERTISED_MODEL_ID": { + "input_per_million": "1000000", + "output_per_million": "10000000", + "cache_discount_percent": 50 + } + }, + "admission_deposit": "10000", + "wallet": { + "network": "testnet", + "password_file": "/ABS/private/seller/password", + "max_payment": "100000", + "max_fee": "1000" + } +} diff --git a/docs/bonds.md b/docs/bonds.md new file mode 100644 index 0000000..901a5c0 --- /dev/null +++ b/docs/bonds.md @@ -0,0 +1,79 @@ +# Refundable Tempo bonds + +The running `tempo` process provides payments and bonds through one wallet, signer, journal and nonce stream when the node has a wallet. A node without one verifies other providers' bonds with only its RPC and serves free inference; it cannot pay, charge or post a bond. Sellers may configure prices, publish a bond, do both or do neither. Buyers may use free inference, explicitly authorize paid inference within spending limits and independently require a minimum provider bond. No price means free inference. Without a bond requirement, Tempo applies no bond-based filtering; fresh signed supply and normal Mesh discovery still apply. Starting the plugin never signs a new bond transaction. It reconciles and can rebroadcast previously signed attempts, and resumes outstanding payments under existing authorizations. + +A deposit binds one funding wallet, Mesh mesh ID and host public key. Another host or mesh needs its own deposit. The escrow has no administrator, seizure, slashing, fee recipient or upgrade proxy. Funds stay locked indefinitely. Only the funding wallet can request exit, which starts the fixed exit delay chosen at deposit, and reclaim the full principal after that delay. The bond remains eligible during the exit countdown and stops qualifying when withdrawal becomes possible, even if its owner has not submitted the withdrawal transaction. Gas is paid separately in OUSD. There is no renewal, periodic refresh transaction, exit cancellation or delay change. + +## Host integration + +Use the full companion Mesh branch `peer-evidence`. Tempo's pinned SDK supplies the interface, and the full host branch supplies enforcement. Tempo requires `peer_evidence.v1` at initialization. A node with a wallet needs a persistent Mesh identity, including an explicit `MESH_LLM_NODE_KEY_PATH` for a client-only buyer: its payment ledger and bond are bound to the node identity and must survive restarts. A node without a wallet pins nothing, so a buyer that only verifies bonds can keep the client's default identity. Use separate key paths and Tempo state directories for public and private operation: switching modes rotates the selected node key, including an explicitly configured path. + +Install a Tempo package declaring its verifier. Mesh makes selected verifier packages required and eager, and validates their packaged declarations before accepting peers. Its authenticated live manifest must agree with contract version 1, namespace `tempo.bond.v1` and handler `verify_peer_evidence`. No evidence permission or empty grant table is needed. Unsupported or malformed declarations and conflicting namespaces fail startup. Restart Mesh after changing plugin policy so old decisions cannot outlive it. A changed published reference needs no restart: Mesh keys decisions by the evidence itself. + +Tempo obtains its node identity through `ReadIdentityBundle` and subscribes to mesh-ID snapshots/events. Its local `bond_context` control reads that snapshot and the manifest namespace; `mesh_id` remains null until known and is cleared if Mesh clears its ID. New bond locks require a known mesh ID. `PublishPeerEvidence` is the only evidence host RPC, used to publish the local bond reference or withdraw it with null. + +Each receiving node checks the origin-signed record before invoking its own verifier with authenticated mesh/provider identity and the evidence from the declared namespace. Mesh rejects a provider that published no evidence without asking Tempo; Tempo verifies a supplied proof against finalized escrow state, and rejects every proof on a network without a configured escrow. Buyers never need to post their own collateral. + +Mesh owns the only eligibility cache and reuses decisions for gossip relay, discovery listings and routing. Its validity, retry and pruning rules are described under [Escrow and policy](#escrow-and-policy). Verification runs outside membership heartbeats. Expired or rejected decisions block provider propagation, selection, routing-table responses and new inference work while retaining bounded authentic signed records for revalidation. Relays cannot replace a held record with an older one; authenticated direct origins retain Mesh's existing restart sequence-reset behavior. After revalidation, routing uses supply from the current held signed body. Supply comes from the signed body, so relays cannot attach unsigned models to another identity. Ordinary record freshness and peer-health checks remain independent. Admission callbacks receive no bond evidence and perform no additional verification. + +Tempo permits one chain verification at a time, including direct calls to its published verifier operation. Contention fails immediately and uses the configured finite failure retry. The gate stores no eligibility decisions. + +Publication must also fit Mesh's total signed node record budget. Mesh rejects a reference that would overflow the current record without replacing prior evidence; reducing advertised metadata creates room. Withdrawing a reference remains allowed. Mesh orders identity snapshots and live updates and never replays an old mesh ID into a replacement plugin process. + +Mesh knows namespaces, signed records, acceptance and expiry. Currency, collateral and pricing policy remain in the plugin, so a Bitcoin verifier can use the same contract. With a verifier active, Mesh requires origin-signed provider records even when Tempo accepts missing bond evidence. + +Fresh authenticated direct admission alone cannot qualify unsigned provider supply for verification or reuse of a cached absent-evidence verdict. The buyer checks the seller it selects, and the seller chooses and operates its own infrastructure. Mesh does not require bonds from the workers behind that seller's local runtime. Internal stage control and transport retain their membership, topology and lifecycle authorization. Bond eligibility checks for the selected seller reuse Mesh's cache without additional verifier or blockchain calls; already admitted requests can finish. + +## Escrow and policy + +One escrow per network serves every mesh and provider. On Moderato the plugin uses the escrow at `0xd210B0356b3e45B37F29Ec763106dc23BF1cC3aa`, deployed from `contracts/src/TempoBondEscrow.sol` (its pinned creation bytecode is `contracts/creation.hex`); `bonds.contract` overrides it. Mainnet has no escrow yet: deploy it once with Foundry and set `bonds.contract`. The plugin never deploys it. Bond verification and explicit escrow operations check the selected chain, canonical OUSD token and exact deployed runtime bytecode, pinned in `contracts/runtime.hex`. Publication only serializes the published reference; receiving verifiers validate it when their policy requires a bond. `just contracts-check` compares both checked-in bytecode artifacts with the pinned Solidity 0.8.30 build and exercises the contract. + +Example plugin settings on Moderato, in addition to `data_dir`, `wallet`, and any payment configuration: + +```json +{ + "bonds": { + "max_lock": "20000000", + "max_exit_delay_seconds": 604800, + "verification_retry_seconds": 60, + "providers": { + "minimum_amount": "10000000", + "minimum_exit_delay_seconds": 86400 + } + } +} +``` + +All amounts are millionths of OUSD on the selected network. A config that omits `bonds.providers` requires the default bond: at least 1 OUSD with an exit delay of at least the network's default. The default exit delay is one minute on testnet, so a trial bond comes back within minutes, and one day on mainnet. A requirement can be lowered but not turned off: installing the plugin always filters providers by bond. On mainnet, where no escrow is deployed, no provider qualifies until `bonds.contract` names one. When supplied, its omitted fields default to one atomic unit and no additional minimum exit delay. Explicit production requirements should set both minimums, as above. On mainnet, checking bonds or publishing one needs `bonds.contract`. Neither a requirement nor publication implies the other. A qualifying bond must be funded, unwithdrawn, bound to the expected mesh and host key, and locked against withdrawal. Amount and exit delay are independent requirements, with no amount-times-duration score. `max_lock` and `max_exit_delay_seconds` authorize explicit new deposits and default to 1 OUSD and one day; they do not create a bond. + +When a requirement and proof are present, verification reads one finalized block through the locally configured RPC. It checks identity, amount, exit delay, contract and exit state. It trusts that RPC's finalized state rather than running a light client. An active bond's decision expires at that block's timestamp plus its exit delay: an exit requested immediately afterward still cannot release the principal during that window. For an exiting bond, the decision expires at its exact withdrawal deadline. A bond stops qualifying at that deadline, even while its principal remains in escrow awaiting withdrawal. There is no fixed positive polling interval. Longer exit delays safely reduce chain reads. Mesh uses the plugin's `valid_until` directly, with no core validity setting or fixed cap. Its routing and forwarding boundaries enforce expiry using local wall and monotonic clocks. Cache hits never move the original deadline. + +Exit delays must be between 1 and 4,294,967,295 seconds, approximately 136 years. Withdrawal timestamps use a full-width integer so supported delays cannot overflow; public `withdraw_at` metadata is a decimal string, with `"0"` meaning no exit request. Finalized observation timestamps must lie between 120 seconds behind and 5 seconds ahead of the local clock, and their derived deadline must still be in the future. A receipt alone never establishes continued eligibility. + +Mesh owns the only eligibility cache and keeps decisions only for the current evidence of current providers. A rejection on a network without a configured escrow carries a deadline a year away; a verifier restart or the provider leaving invalidates them sooner, and changed evidence uses a different key. These decisions perform no chain reads. This is independent of bond-backed deadlines derived from escrow exit delays. Its keys bind the mesh, the host key and a digest of the evidence; a provider without evidence is rejected without a cache entry or a call to Tempo. A Tempo restart discards every decision, including answers still in flight, so a changed policy cannot reuse them; other plugin restarts leave them in place. Positive decisions from gossip are reused for provider selection without invoking Tempo again. Mesh verifies from one background loop and consults the cache before each call. Tempo retains no second eligibility cache. Failed Tempo checks return a rejection deadline using `verification_retry_seconds` (default 60), which Mesh caches to avoid repeated chain reads during outages or repeated invalid proofs. Mesh wakes its existing background refresh path when a finite decision expires, without waiting for the next gossip heartbeat. Provider work stays blocked until revalidation succeeds. No event subscription, block cursor or chain monitor is implemented. + +## Operator actions + +A seller that posts the default bond runs two commands: `fund`, which creates the wallet and on Moderato asks the faucet for test OUSD, and then `bond_lock`. Signing a new bond lock or exit requires an explicit operator command; once an exit's delay has passed, the plugin withdraws that bond into the wallet by itself. A node that only verifies other providers' bonds needs no wallet. + +While Mesh is running, the local Tempo `control` operation accepts: + +- `bond_context`: read the local mesh ID, host key, manifest namespace, published bond reference and provider requirement. +- `bond_lock`, with every input optional: bind a deposit to this host and a mesh. `amount` and `exit_delay_seconds` default to 1 OUSD and the network's default exit delay, one minute on testnet and one day on mainnet. `mesh_id` defaults to the observed mesh; an explicit one that differs from it is rejected before signing, which preserves operator intent if a mesh update races the command. The 32-byte hex `salt` defaults to one derived from the mesh and host key, and `operation_id` to one derived from the salt, so repeating the command resumes the same bond instead of locking another. A second bond for the same mesh and host, for example after a withdrawal, needs its own `salt`. +- `bond_exit`, with every input optional: start the bond's exit countdown, then withdraw the principal to the wallet that funded it once the delay has passed. Eligibility lasts until the withdrawal deadline. `bond_id` defaults to the newest finalized lock, and `operation_id` to one derived from the bond, so repeating the command resumes the same exit. The exit attempt's `withdraw_after` shows when the plugin starts trying the withdrawal; it retries on each tick until the finalized chain reaches the deadline, and the node must be running for it. Once the withdrawal finalizes, the plugin withdraws the published reference. +- `bond_publish`, with an optional `bond_id`: publish that bond as this node's evidence, for example one locked before the state directory was replaced, or withdraw the reference without `bond_id`. +- `transactions` and `pending`: inspect public attempt metadata, including bond attempts. In-process `retry` without a `request_id` reconciles the shared wallet journal and resumes outstanding payments and channels under existing authorizations; it can sign payment transactions. With a `request_id`, it progresses that payment. + +A seller can join the mesh, read `bond_context`, and then fund a deposit. Once the lock finalizes the plugin publishes it, without a configuration change or restart, and republishes it at every start; a newer finalized lock replaces it, and a finalized withdrawal withdraws the reference. Membership does not require a bond; buyers select the seller once its signed publication meets their own bond policy. A node can check others' bonds without a wallet. With a wallet, it may leave the wallet locked when only verifying or publishing evidence; signing a new transaction requires unlocking. Remote callers cannot use the peer-evidence hook to sign transactions. + +Bond operations run only as controls on the running plugin; the CLI only initializes the wallet and reads its address. Every control that signs a new bond transaction has an operation UUID; each derives one when none is given. Equivalent UUID spellings identify the same operation. Repeating that UUID must retain identical intent; it never signs replacement bytes. + +A lock has no maturity date. To release it, run `bond_exit`; once the finalized chain timestamp reaches `withdrawAt`, the plugin withdraws it. Repeating the same signed exit operation reconciles its original bytes. The contract also makes repeated exit requests idempotent, so they cannot reset or shorten the delay. Exit requests and withdrawals remain available when authorization for new locks is zero. No background task initiates a new exit or signs replacement bytes merely because the wallet exists; the only bond transaction the plugin signs by itself is the withdrawal of a bond whose exit this wallet requested. The wallet skips reconciliation RPCs when its shared journal has no pending transaction. + +Deposits use native Tempo multicall to approve exactly the bond amount and lock it atomically. Payment, wallet send, deposit, exit and refund attempts share one journal, send mutex and unresolved-transaction gate. Signed bytes commit before broadcast. Receipt finality and expiry use the same finalized block cutoff. If a receipt is missing after expiry but the nonce was consumed at that cutoff, the attempt stays pending until its receipt can be resolved. Restarting, removing prices or removing authorization for new locks cannot release an uncertain nonce or replace its transaction. + +## Validation + +Routine tests use deterministic local wallets, RPC fixtures and plugin-process fixtures. The host smoke additionally runs two real Mesh nodes. The explicit `just testnet-bonds MESH_BINARY FRESH_PRIVATE_DIRECTORY` workflow creates fresh testnet wallets, requests faucet coins, uses the Moderato escrow, or the one named by `TEMPO_BOND_ESCROW`, and exercises paid/free inference, provider filtering, delayed exit and refunds. It requires a `host-smoke` harness from `just build` and uses the adjacent debug `tempo` binary. The [latest validation record](validation.md#current-mesh-compatibility-2026-11-21) records a completed trial against the current companion host and plugin. It uses 30-second exit delays and a 1-second failure retry; production retries default to 60 seconds. The backend returns canned usage, so the trial validates integration and settlement rather than model quality. + +The [earlier maturity-and-renewal trial](tempo-bonds-testnet-trial.md) used a different contract. Its address and runtime are historical. This exit-delay contract requires a fresh trial directory. The harness saves the escrow address and the lock, exit and refund inputs before submission and reuses them on resume. A saved checkpoint resumes at exit/refund processing after positive admission tests; release waits on finalized chain time. A terminally failed signed operation needs inspection; resuming never silently creates another deposit. Contract tests cover indefinite locks, exit ownership and exact delay boundaries, idempotent exit requests and full principal refunds. The [earlier exit-delay trial](tempo-exit-testnet-trial.md) records the preceding host/plugin API; current results are in the latest validation record. diff --git a/docs/demo.md b/docs/demo.md new file mode 100644 index 0000000..73104b3 --- /dev/null +++ b/docs/demo.md @@ -0,0 +1,78 @@ +# Operator setup + +The plugin supports test OUSD on Tempo Moderato (chain 42431) and OUSD on Tempo mainnet (chain 4217). `wallet.network` selects `testnet` or `mainnet`, with testnet as the default. Wallet creation, funding, and network spending are explicit operator actions. Development tests use deterministic temporary keys and local fixtures. + +## Build and install + +Use the companion Mesh `peer-evidence` branch for the current plugin. Earlier payment-and-bond trials used Mesh 0.80.0, and payment-only operation passed on Mesh 0.79.0; those binaries predate the current manifest-based verifier contract. Even a model-free buyer needs the native runtime. Older Mesh 0.77.0 is incompatible. + +```sh +just check +just test +just doc +just package +mesh-llm plugins install --archive dist/tempo-v0.1.0-.tar.gz \ + --name tempo --version 0.1.0 +``` + +Install the same archive on buyer and seller using their appropriate native architecture. Use the plugin store that each running Mesh node will use. There is no second wallet plugin to install. + +## Configure and initialize + +A package install needs no configuration: the plugin writes `~/.mesh-llm/tempo/config.json` on first start, with its state in the same owner-only directory. For paid inference, edit that file following the [buyer](../demo/buyer-payments.json.example) or [seller](../demo/seller-payments.json.example) example, or copy [the Mesh template](../demo/mesh.toml.example) and point `config_path` at your own file. All state and credential paths must be absolute. + +The `data_dir` holds the encrypted key, the payment ledger (requests, channels, daily spending and runtime settings) and the transaction journal. Keep it across restarts. The `fund` control creates the wallet when there is none, and so does `bond_lock`; the CLI creates it ahead of time: + +```sh +tempo wallet init +tempo wallet address +``` + +Pass `--config` to use another config file. Without `wallet.password_file` the wallet gets a random password in `data_dir/wallet.password`, so the key at rest is only as safe as that directory; name a private password file of at least 16 bytes with mode 600 to keep the password elsewhere. Creation refuses to replace an existing wallet and records the configured network in its profile. Startup never creates keys. Without a profile the node runs without a wallet: it verifies bonds and serves free inference, and refuses to start when prices or automatic buying are configured. Payments start after a restart once the wallet exists. A profile must match the configured network. A wallet with neither a configured nor a generated password stays locked; both buyer funding and seller capture require an unlocked wallet. + +## Switch networks + +Select `"network": "testnet"` or `"network": "mainnet"` inside `wallet`. Omit `rpc_url` to use the matching public RPC, or supply an HTTPS RPC for the selected chain. An RPC on the other chain is rejected before signing or broadcast. Both peers must select the same network. + +Maintain a config and a separate `data_dir` for each network. For example, testnet may use `/absolute/private/NODE/testnet` while mainnet uses `/absolute/private/NODE/mainnet`. See [the mainnet example](../demo/mainnet-payments.json.example). Initialize and fund each wallet once using its own config. + +Let open channels close, or recover them, before stopping the current node. To switch, point its `config_path` at the other network's config and restart. Use the local CLI with that same config to initialize the wallet. To return, restore the original config. The ledger and journal stay bound to their original network; do not edit `wallet.json`, copy a journal between networks, or delete pending state. `control fund` reports the active network. Bonds remain on their original chain. To release one, run `bond_exit` with that chain's original config and wallet, and keep that node running until the plugin has withdrawn it after the delay. + +Mainnet wallets must receive real OUSD on Tempo mainnet for deposits and gas. The Moderato faucet supplies test coins only. Network selection does not bridge or convert funds, and spending still requires an automatic buyer policy that lists the seller and the model. + +## Fund with test coins + +On testnet, `control fund` asks Tempo's Moderato faucet for test coins for the wallet's address. To request them by hand instead, replace `YOUR_WALLET_ADDRESS` with the address from `wallet address`: + +```sh +curl --fail-with-body https://rpc.moderato.tempo.xyz \ + -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":1,"method":"tempo_fundAddress","params":["YOUR_WALLET_ADDRESS"]}' + +``` + +Wait for faucet funding to finalize before checking the balance again. The plugin uses test OUSD at `0x20c0000000000000000000006a37da5c996874be` for both payments and gas. Buyers need each channel's deposit (`channel_topup`, 1 OUSD by default) plus gas; sellers need closing gas. No ETH or real funds are required. Never fund a published fixture address. The faucet is an explicit setup step and is never called by plugin startup. See the official [Tempo testnet instructions](https://github.com/tempoxyz/tempo#testnet) and [MPP session configuration](https://mpp.dev/payment-methods/tempo/session). + +## Set payment policy + +Sellers optionally configure exact model IDs, OUSD rates per million input and output tokens, and a cache discount under `prices`, and the upfront a new channel pays under `admission_deposit`. No price, or a zero price, means free inference. Buyers set `policy` to `{"mode": "automatic", "daily_budget": "..."}`, in the config or with the `policy` control. They may also narrow buying to sellers in `buy_peers` and to rate ceilings per model in `buy_prices`, set a per-request `cap`, the most unbilled credit a seller may hold in `admission_deposit`, and the channel deposit in `channel_topup`. The examples start in `free_only` mode, so spending stays off until that change. Amounts use the selected network's OUSD. Clients send no payment fields; the buyer's policy decides which requests are paid. The [README](../README.md#install-and-configure) explains each setting. + +Startup writes `policy`, `prices`, and a set `admission_deposit` into the payment ledger, and controls such as `policy`, `set_pricing` and `admission_deposit` change them while the node runs. Removing a model from `prices` does not unprice it at the next start; use `set_pricing` without a value. Provider bond requirements and seller bond publication are independent. On testnet a buyer that omits `bonds.providers` only sees sellers with at least the default bond of 1 OUSD and a one-minute exit delay, which `bond_lock` locks by default. Installing the plugin always filters sellers by bond. Wallet limits independently bound each deposit and transaction fee. Lowering them does not invalidate previously signed transactions. + +## Start nodes + +Use one persistent Mesh identity per node. Set `MESH_LLM_NODE_KEY_PATH` to a stable absolute file and leave `MESH_LLM_EPHEMERAL_KEY` unset. The template uses `[runtime] mode = "on_demand"` and `mesh-llm serve` without a model for a buyer. On the companion branch, a client-only buyer can instead use `[runtime] mode = "client"` and `mesh-llm client --join-file ` with an explicit `MESH_LLM_NODE_KEY_PATH`, as exercised by the latest trial. The earlier Mesh 0.79.0 setup used `serve` because its ordinary client mode did not preserve the required identity. + +Set `MESH_LLM_CONFIG` to the node's template copy and `MESH_LLM_PLUGIN_DIR` to its installed plugin store. Start the seller with its chosen model using the matching host's normal `serve` command. Start the buyer with `serve --join-file `. Keep invitations private. The plugin obtains the authenticated node ID from the host and pins it before recovering payment state. + +The template grants bounded request bodies, admission, and terminal lifecycle events to the single plugin. Keep the installed executable path, and avoid command overrides that bypass the host's identity grant. Do not enable another payment engine on these dedicated nodes. + +## Request and inspect + +Send the [README request example](../README.md#requests-and-settlement) to the buyer's `/v1/chat/completions` endpoint with the exact advertised model ID; the buyer pays for it under its policy. For streaming, include terminal usage in the original body. A 402 while the first channel opens is rare: the buyer cancelled that request, so send it again. + +Inspect both nodes through `mesh-llm plugins call tempo control`. `pending` shows active requests and channels; `transactions` shows recent requests, channels and wallet transactions, including each channel's voucher, billed total and, once closed, its capture and refund; `balance` and `fund` show wallet state. A paid request finishes when the buyer has signed its bill; the channel stays open for later requests until a close. Captured plus refunded equals the channel's deposit. + +The local CLI only initializes the wallet and reads its address; inspect wallet state through these `control` commands. Trusted local clients can also invoke `send` and the explicit bond commands, which move wallet funds; raw signed transaction submission is not exposed. See the [command list](../README.md#inspect-and-control) and [bond setup and controls](bonds.md). + +See [the recovery guide](mpp-demo.md#failure-and-recovery) for cancellation, unknown usage, waiver, and native withdrawal. Deleting state does not resolve a payment. Native payer recovery can beat long inference or outages, so a funded deployment needs the host work described in [release boundaries](production-readiness.md). diff --git a/docs/mpp-demo.md b/docs/mpp-demo.md new file mode 100644 index 0000000..0bc78cb --- /dev/null +++ b/docs/mpp-demo.md @@ -0,0 +1,70 @@ +# Long-lived Tempo MPP channels + +The plugin uses the native TIP-1034 reserve at `0x4d50500000000000000000000000000000000000` on the configured Tempo network: Moderato testnet (chain 42431, default) or mainnet (chain 4217). Its integrated wallet signs native type `0x76` transactions and pays gas in that network's OUSD. The peer exchange uses authenticated `pay.stablecoin.v1` messages with protocol version `1`; it does not implement the HTTP MPP challenge/credential envelope. + +## Channels, vouchers and bills + +Each buyer and seller pair shares one channel, reused by every paid request until it closes. Its terms bind the buyer and seller peers, payer and payee wallets, chain, token, and a random nonce chosen by the buyer, so the pair can open a fresh channel after a close. Their versioned hash is the native channel salt. All amounts are millionths of the selected network's OUSD. + +1. **Quote.** The buyer mints an ID for each paid request. Its `Hello` commits to the exact model, the canonical request digest, its byte length, and the output token limit. The seller quotes its rates and cache discount, its view of the channel (the best voucher it holds, `cum_before`, and the sum of its bills, `cost_before`), and an explicit `upfront`: the voucher increase over `cum_before` it requires before work. This seller asks the model's admission deposit, else the node-wide one, when it has no channel with this buyer and the buyer has not paid it since the seller started, and 0 otherwise; the wire allows any amount, so a later prepay mode needs no protocol change. A seller with a closing channel for this buyer refuses the quote. The seller answers `Busy` instead while it has no channel and another request from the buyer is opening one, while a request with the same body is in flight, or while the buyer has three unpaid bills; the buyer says hello again every 250 milliseconds within its admission wait. A request with unknown usage blocks none of these. +2. **Buyer checks.** The buyer pays only when `policy.mode` is `automatic` and `buy_peers` is empty or lists the seller; otherwise it sends the request free. When `buy_prices` has a ceiling for the model, the quoted rates must not exceed it and must give at least its cache discount, and the seller's unbilled credit after funding, the voucher minus the bills the buyer accepted, must stay within the buyer's `admission_deposit`. A new channel can therefore get a full upfront, while later upfronts can only refill credit to that limit. The quote must show the buyer's channel and payee, a `cost_before` no higher than the bills the buyer accepted plus what its other requests may still be billed (lower is fine, since a bill may be on its way or may have overtaken the quote), and a `cum_before` at or below the buyer's own voucher; a seller behind on vouchers then receives the buyer's latest. A quote without a channel is also accepted while the buyer's channel has no bills: the seller never received its first voucher, so the buyer sends that channel. When the views differ otherwise, the buyer refuses the request and recovers its channel. Before opening, topping up or signing anything, the buyer prices the worst case: every byte of the canonical body as an input token plus the full output limit, at the quoted rates. The upfront plus this request's share of the voucher increase must fit `cap`, when set, and the voucher increases must fit the remaining daily budget. The voucher that bill would need must fit the deposit plus one top-up. The actual bill is checked again in step 6. +3. **Funding.** Without a channel, the buyer journals a signed native `open` with a deposit of `channel_topup`, and waits up to 25 seconds for it to finalize. Once the channel is open it signs `Voucher(bytes32 channelId,uint96 cumulativeAmount)` for the seller's `cum_before` plus the upfront, or reuses its existing voucher when that is already higher, and persists it, with the day's spending, before sending it. An open or top-up still pending after the wait is a rare fallback: the buyer refuses the request with a 402 and sends `Cancel`, so the request does not keep holding the seller's slot for its body, and the open continues in the background. The EIP-712 domain is `TIP20 Channel Reserve`, version `1`, the configured chain ID, and the canonical reserve address. Channel IDs also include the chain ID, so vouchers cannot be replayed across networks. Only primitive secp256k1 signatures are supported. +4. **Admission.** The seller's wallet verifies the opening event, the voucher signature, and that the finalized and latest deposit back the voucher, with nothing settled and no close requested. The voucher must be at least `cum_before` plus the upfront; the buyer's resent or reused vouchers always are. The voucher the seller already stores, which an existing channel presents when the upfront is 0, is admitted without these chain reads: its signature and opening cannot change, the deposit only grows, and a close request moves the channel to closing on the next watch tick, within the close deferral. The seller keeps the best voucher and answers `Ready`; the buyer then dispatches once. An admitted voucher that the seller verified and that is above zero gives the buyer standing, so its next channel opens with no upfront and a zero voucher. +5. **Bill.** Terminal usage fixes the bill: `ceil((uncached_input × input_rate + cached_input × input_rate × (100 - discount)/100 + min(output, output_limit) × output_rate) / 1,000,000)`. Arithmetic saturates rather than wraps. The seller caps the bill at the worst case checked before dispatch, absorbing any prompt longer than the body bound, and sends `Bill{seq, usage, cost, running_total}`, where `seq` numbers the channel's bills from 0. Usage that arrives after the channel began closing is never billed, since the capture is already fixed. +6. **Payment.** The buyer records the usage it observed on its own terminal event. The bill may arrive before or after it, and bills may arrive out of order: the buyer accepts the bill numbered next and holds a later one until then. The buyer signs a voucher up to the running total only when the billed usage equals its own, the cost matches the quoted rates capped at the worst case, the running total equals the bills it accepted plus this cost, the cost is at most the worst case checked before dispatch, and the upfront plus the voucher increase fits `cap`. The daily budget is not checked again: as in the Lightning plugin, the bills of dispatched work are paid even when concurrent requests overshoot it. The policy mode does not apply here: work dispatched before a switch to `free_only` is still paid. Otherwise it refuses without signing and records why. Upfront credit pays bills first, so a covered bill needs no new voucher. When a voucher would exceed the deposit, the buyer tops up once by `channel_topup`, and later bills wait for it; the check before dispatch ensures that one top-up is enough for each bill. The top-up must finalize within the seller's 120-second payment time. +7. **Close.** The seller captures `min(best voucher, billed total)` with `close(descriptor, cum, capture, voucher)`; the rest of the deposit returns to the buyer atomically. A capture of 0 needs no voucher. The plugin never calls `settle`, so nothing moves before the close. + +The seller closes a channel: + +- when a bill stays unpaid 120 seconds after it was first sent; +- after one hour without requests; +- when it sees the buyer's close request. A running request may still be billed first, but the seller closes within 600 seconds, inside the reserve's 900-second grace. + +The buyer requests close on a channel it has not used for two hours and withdraws the whole deposit after the grace, since nothing settles before a close. If a top-up cancels a pending close request, recovery requests close again. The seller repeats its close notice on the buyer's next request until the buyer has recorded the close; the buyer verifies every close notice on chain. + +Daily spending counts the voucher increases the buyer signs, not channel deposits. Opens and top-ups are capital that returns at close. A `free_only` policy sends new requests free before anything is signed or opened; it does not stop the bills of work already dispatched. + +## Trust + +The buyer's voucher authorizes the bills it acknowledged plus any unused upfront credit, and chain enforcement only bounds the capture by the voucher. The unbilled credit never exceeds the buyer's `admission_deposit`, however often a seller asks for an upfront. A seller can therefore keep that credit for a bill the buyer refused or for overstated usage, but it cannot capture a larger bill the buyer did not sign. The buyer records an error when a close captures more than its acknowledged bills. Vouchers do not prove computation, so choose sellers and deposits accordingly. + +## Configuration and limits + +One [combined JSON configuration](../README.md#install-and-configure) contains the engine policy and nested wallet settings. There is one installed plugin and no wallet binding. In `automatic` mode, `channel_topup` (1 OUSD unless set) must not exceed `wallet.max_payment` and must be at least `cap`, or at least the daily budget without a cap. Startup writes `policy`, `prices`, and a set `admission_deposit` into the ledger, and controls change them at runtime; every start re-applies the configured values, so runtime changes revert unless the configuration file changes too. Each wallet transaction's fee is bounded by both the caller's limit and `wallet.max_fee`, and `wallet.max_payment` bounds each open or top-up deposit. Both peers need an unlocked, gas-funded wallet. + +Clients send no payment fields: buyer policy decides which requests are paid. A paid request needs an exact model, an output limit of 1..4096 in `max_tokens` or `max_completion_tokens`, and a body within 64 KiB. For SSE include `stream_options.include_usage` in the original body. Requests to one seller run at once, in each direction, so a node that also sells to that peer can still buy from it. A new request waits, within the admission wait, only for a request with the same body to release its slot and for the buyer's first request to open the channel. The seller matches a forwarded request to the buyer's agreed request by the authenticated peer and the digest of the body as the client sent it, which must equal the agreed one; that protects the seller's bill cap and the buyer's checks before dispatch. A forwarded request is admitted under its agreement even after the seller removes the price, and runs only once. On buying nodes and authenticated serving ingress, chat-completion routing requires an inspectable body within the same 64 KiB bound even when the selected route is free; a missing or oversized body cannot bypass identity checks. + +Each node handles a peer's messages one at a time in the order the plugin receives them. + +## Failure and recovery + +An authenticated `QuoteRejected` response closes only a buyer request that has no agreed quote. An `Unpriced` response, from a seller that does not price the model, closes it the same way and the buyer sends the request free. A buyer request that was not dispatched when its HTTP request ended, for example after a restart or a host deadline, is cancelled with the seller on the next retry tick; any voucher it signed stays as channel credit. A generic peer error remains retryable, including when a locked seller has already saved a quote whose reply was lost. + +A seller that restarts locked withholds `Ready` until it can sign closes. A dispatched request is admitted from the voucher verified at admission and the channel state, without another chain call; a channel moved to closing admits no inference. A buyer request that was dispatched but never billed closes locally one hour after its quote expired, without changing the channel. + +The wallet journals the channel terms, nonce, signed bytes, signing context, and transaction hash before broadcast. Uncertain outcomes reuse those bytes. An unresolved nonce blocks another signature. Receipt finality and expiry use one finalized block cutoff. Missing receipts with a consumed nonce keep an attempt pending. After a confirmed revert or proven expiry, top-ups, closes and payer recovery may sign a new attempt for the identical intent, while retaining every prior signed transaction. Opens are never recreated: an open that expired unsent or reverted closes the channel and refuses the request. + +The seller persists terminal usage and the bill before acknowledging the terminal hook, and sends the bill in the background. Each channel close commits together with closing its requests. Restart reconciles the original transactions, requests and channels. Interrupted seller execution becomes usage unknown and cannot execute again. A buyer interrupted before it recorded its own usage cannot verify that request's bill and refuses it. + +Known usage is billed even if HTTP delivery fails or is cancelled. Missing usage is never turned into a measured zero charge, and it does not block the pair. The seller keeps the request as unknown for the audit trail and sends `Unbilled` for it, repeated on each retry tick and on the buyer's next hello until the buyer acknowledges it with `UnbilledSeen`. The buyer closes its own request unpaid without changing its view of the channel, and its next request is quoted and served on the same channel. From the first notice, or from a later quote, the seller never bills the request, so bills stay in order: late usage is recorded but not billed. Without the notice, the buyer closes the request one hour after its quote expired. `waive` is operator bookkeeping: it only closes a request the buyer was told about, and otherwise sends a zero bill. Unstarted requests may be cancelled; any upfront stays as channel credit. + +`wallet.max_settlement_attempts` defaults to three failed signed attempts per top-up, `close`, `request_close` or `withdraw` step, and accepts 1 to 10. Close and recovery attempts expire after one hour; opens and top-ups after 10 minutes. Expired and reverted attempts count toward the limit; a close request later cancelled by a top-up does not. Retry counts survive restarts. Exhaustion remains an explicit error. + +The payer may independently start the native grace period at any time. Long inference or an unavailable seller can outlast it. The plugin cannot stop a backend already executing or recover usage the host never delivered. Production needs enforceable execution deadlines and durable terminal observations in Mesh. + +```sh +mesh-llm plugins call tempo control --input '{"command":"pending"}' +mesh-llm plugins call tempo control --input '{"command":"retry","request_id":"REQUEST_UUID"}' +mesh-llm plugins call tempo control --input '{"command":"cancel","request_id":"REQUEST_UUID"}' +mesh-llm plugins call tempo control --input '{"command":"recover","request_id":"REQUEST_UUID"}' +mesh-llm plugins call tempo control --input '{"command":"waive","request_id":"REQUEST_UUID"}' +mesh-llm plugins call tempo control --input '{"command":"unblock","peer":"BUYER_NODE_ID"}' +``` + +`cancel` and `recover` run on the buyer; `recover` closes the channel with a seller, named by `peer` or the only open one, through `requestClose`; the seller then closes it, or the buyer withdraws after the grace. `waive` runs on the seller only for unknown usage. `unblock` runs on the seller and forgives the bills a buyer's closed channels lost, so they no longer count toward its three unpaid bills. `retry` without an ID reconciles pending wallet transactions and every active request and channel. `pending` and `transactions` show requests, channels and wallet transactions without signed bytes or voucher signatures. The full command list is in the [README](../README.md#inspect-and-control). + +## Evidence and acceptance + +Local tests exercise actual native signing, ABI and event shapes for opens, top-ups, close requests, closes with a cumulative voucher and capture, withdrawals and transfers, vouchers, independent receipt validation, engine-to-wallet calls, crash and restart boundaries, and exact withdrawal timing through loopback fixtures. These fixtures are not a Tempo node. The default host smoke uses fabricated wallet evidence and canned inference. The [earlier native trial](testnet-trial.md) and the [companion-host trial](tempo-exit-testnet-trial.md) passed with the earlier design that opened one reserve per request; the long-lived channels have not yet run on Moderato. Broader failure acceptance and latency benchmarking remain outstanding. + +Protocol references: [Tempo MPP sessions](https://mpp.dev/payment-methods/tempo/session), [TIP-1034 at the researched revision](https://github.com/tempoxyz/tempo/blob/c281c5b3497f797ea823d826ce6106fe16461f60/tips/tip-1034.md), and [the pinned reserve ABI](https://github.com/tempoxyz/tempo/blob/3e95ed3d80be0fad2973f1abd2fb403d6c33011a/crates/contracts/src/precompiles/tip20_channel_reserve.rs). diff --git a/docs/production-readiness.md b/docs/production-readiness.md new file mode 100644 index 0000000..13e8297 --- /dev/null +++ b/docs/production-readiness.md @@ -0,0 +1,32 @@ +# Release boundaries + +This is a single-crate, single-process implementation of long-lived Tempo payment channels, one per buyer and seller. `wallet.network` selects Moderato testnet (default) or mainnet OUSD, with separate state directories. Basic two-host integration and faucet-funded native capture and refund passed on Moderato with Mesh 0.79.0, and the recorded companion-host trial passed paid inference with no bonds and with provider-only bonding, followed by delayed bond exits and full refunds. Those trials used the earlier design with one reserve per request; the long-lived channels, the Lightning-style configuration and the new controls have deterministic offline coverage only. Mainnet signing and settlement also have offline coverage only; no funded mainnet trial was run. It remains a developer preview with the host durability and deadline dependencies below. + +The manifest-only verifier contract, optional provider requirement and always-available capabilities have also changed since those trials. + +## Implemented boundaries + +The plugin owns channels, request agreements, admission, policy, usage billing, keys, signing, evidence verification, the wallet journal, and request accounting. Calls to the wallet are typed and stay in process. The operations are `control` and the read-only peer-evidence verifier; there is no separate wallet capability, host binding, or child process. + +Implemented: native channel opens, top-ups when a bill needs them, off-chain cumulative vouchers, per-request bills checked against the buyer's own usage and accepted in order, concurrent requests per pair, upfront credit with Lightning-style standing and strikes, a single capture of the billed total at close with an atomic refund, unpaid-bill and idle closes, closing within the close-request grace, payer recovery with `requestClose` and withdrawal, pending transaction recovery, unknown usage with explicit waiver, journaled wallet sends, and runtime settings with re-registration of model channel requirements. Immutable request identities prevent duplicate dispatch; uncertain transactions reuse exact signed bytes. Retries after proven expiry or a finalized revert preserve the original intent and retain all earlier attempts. Engine and wallet locks and identity pins protect current state during restart. + +This is new code without a migration layer for earlier versions. The state database rejects unsupported schema versions. These checks protect the current version's durable state, rather than upgrading older formats. + +Production startup always loads the native wallet. The fabricated backend is reachable only through the separate `tempo-fixture` executable, built with `offline-fixture`. Production packaging builds the normal binary without that feature and includes one executable, metadata, licenses, documentation and pinned escrow source/bytecode. + +## Required Mesh work + +The SDK is pinned to `46da729c7102108f71e41a4998f10d498b9d42dd`, which adds the versioned verifier declaration. Stronger payment guarantees require further host changes: + +1. Persist terminal usage and support acknowledged, repeatable delivery. The plugin saves received usage before acknowledging it, but host death before delivery can still lose a bill; the plugin preserves unknown usage and refuses execution replay. +2. Enforce execution deadlines and cancellation with settlement margin. A payer may independently start Tempo's 900-second withdrawal grace period. Admission alone cannot stop resource use beyond that deadline. +3. Preserve attempt identity through routing and failover. An agreement belongs to its seller and request; work already performed must remain distinguishable from a new attempt elsewhere. +4. Deliver each peer's payment messages in order. The plugin handles a peer's messages one at a time in the order it receives them, but the SDK may hand two closely spaced messages over in either order. Bills no longer depend on it, since the buyer accepts them by their number; other reorderings fall back to retries. + +## Acceptance still required + +The long-lived channels need an authorized Moderato trial: channel reuse across requests, top-ups, unpaid-bill and idle closes, a buyer close request during inference, payer withdrawal, seller restart during work, missing usage, and wallet sends. These cases currently have deterministic local coverage only. The earlier [trial evidence](testnet-trial.md) establishes the exercised host lifecycle and plugin IPC, not real model inference, all host failure paths, or production fee and latency benchmarks. + +Settling vouchers before close, a prepay mode in which sellers never serve on credit (the wire already carries what it needs), standard HTTP MPP interoperability, and simultaneous Lightning admission coordination are outside this implementation. A future streaming payment flow would need continuous metering and enforceable execution control. + +Bond-specific configuration, RPC trust, lease expiration and recovery guarantees are documented in [the bond guide](bonds.md). Escrow code and delayed exits are developer preview functionality. The [exit-delay trial](tempo-exit-testnet-trial.md) validates the escrow and admission lifecycle on Moderato using canned inference. diff --git a/docs/tempo-bonds-testnet-trial.json b/docs/tempo-bonds-testnet-trial.json new file mode 100644 index 0000000..59c344d --- /dev/null +++ b/docs/tempo-bonds-testnet-trial.json @@ -0,0 +1,161 @@ +{ + "date": "2026-11-19", + "chain_id": 42431, + "network": "Tempo Moderato", + "asset": "0x20c0000000000000000000006a37da5c996874be", + "escrow": "0x4dA347a95C1b49b8FC90Da083058682ac7613bf2", + "mesh_branch": "codex/tempo-bonds", + "mesh_base": "dc8a8fafb8bd51efc287840a84b764c35346b21b", + "canned_inference": true, + "bond_principal_atomic": "1000000", + "transactions": [ + { + "wallet": "seller", + "operation": "deploy", + "hash": "0x9101a77db8a0e86380aa42876b962cb47120578ce3dc3e6d341ee42035216a83", + "status": "finalized", + "bond_id": null + }, + { + "wallet": "seller", + "operation": "lock", + "hash": "0xf1585d39856231d552f8e14661e5e78a163cc52da43b62c43261c4ae6a8ced1b", + "status": "finalized", + "bond_id": "0xd54b5af46302765b472369f78058cf10a0b5a165468c04d13849e5c225eebe0b" + }, + { + "wallet": "seller", + "operation": "renew", + "hash": "0x8d96330ee33eb1f2193aa1ed449456f66d3afa371cc1468d3eb90276986a97db", + "status": "finalized", + "bond_id": "0xd54b5af46302765b472369f78058cf10a0b5a165468c04d13849e5c225eebe0b" + }, + { + "wallet": "seller", + "operation": "withdraw", + "hash": "0xd6cdbc4361a906785d128508ac3fed993b2b97f2846955ce7d84b770b2014cf2", + "status": "finalized", + "bond_id": "0xd54b5af46302765b472369f78058cf10a0b5a165468c04d13849e5c225eebe0b" + }, + { + "wallet": "buyer", + "operation": "lock", + "hash": "0xb72d17156f1600e50a1bbf22e77e36e2b48e9509b510e6c0d0500b378e8a6768", + "status": "finalized", + "bond_id": "0x6d2a44b7d0f3a8992c7c4d778dccf4121c3455dd3bb9b5c05ccc215fb653bbe4" + }, + { + "wallet": "buyer", + "operation": "renew", + "hash": "0x150515d2de8448823c32cfe7e3511a672a714d3786addc1d262515c14d83d7b4", + "status": "finalized", + "bond_id": "0x6d2a44b7d0f3a8992c7c4d778dccf4121c3455dd3bb9b5c05ccc215fb653bbe4" + }, + { + "wallet": "buyer", + "operation": "withdraw", + "hash": "0x9c4306ba585ab15ee91758d15bd1a19dc3c88d534c3af7c64350421fbbac757c", + "status": "finalized", + "bond_id": "0x6d2a44b7d0f3a8992c7c4d778dccf4121c3455dd3bb9b5c05ccc215fb653bbe4" + } + ], + "scenarios": { + "both_enabled": { + "status": 200, + "usage": { + "completion_tokens": 4, + "prompt_tokens": 1, + "total_tokens": 5 + } + }, + "bonds_only": { + "status": 200, + "usage": { + "completion_tokens": 4, + "prompt_tokens": 1, + "total_tokens": 5 + } + }, + "unbonded_buyer": { + "status": 402, + "usage": null + }, + "withdrawn_provider": { + "status": 404, + "usage": null + }, + "both_disabled": { + "status": 200, + "usage": { + "completion_tokens": 4, + "prompt_tokens": 1, + "total_tokens": 5 + } + } + }, + "bonds": [ + { + "bond_id": "0xd54b5af46302765b472369f78058cf10a0b5a165468c04d13849e5c225eebe0b", + "initial": { + "amount": "1000000", + "host": "52ceb285f9fc6c922a82becfffd09ca8c2eb8fc6657739df6b766394fcfd166c", + "locked_at": 1795075966, + "mesh": "0x32b7fc2a4d0aea3e8e9f949800d000afbbc9df47b02f4db3033075fd1409ee05", + "refund_wallet": "0x85b0c31cd51033e1d34c2a4b4f1d5c9fcb876c92", + "unlock_at": 1795076145, + "withdrawn": false + }, + "renewed": { + "amount": "1000000", + "host": "52ceb285f9fc6c922a82becfffd09ca8c2eb8fc6657739df6b766394fcfd166c", + "locked_at": 1795076116, + "mesh": "0x32b7fc2a4d0aea3e8e9f949800d000afbbc9df47b02f4db3033075fd1409ee05", + "refund_wallet": "0x85b0c31cd51033e1d34c2a4b4f1d5c9fcb876c92", + "unlock_at": 1795076294, + "withdrawn": false + }, + "refund_principal_verified": true + }, + { + "bond_id": "0x6d2a44b7d0f3a8992c7c4d778dccf4121c3455dd3bb9b5c05ccc215fb653bbe4", + "initial": { + "amount": "1000000", + "host": "1db3d4c78cb69971fc64bd895c688f859325de80976d3af5325fe4f204884498", + "locked_at": 1795076109, + "mesh": "0x32b7fc2a4d0aea3e8e9f949800d000afbbc9df47b02f4db3033075fd1409ee05", + "refund_wallet": "0x1976840708a1baed9590ab1f25da6db72031f7da", + "unlock_at": 1795076287, + "withdrawn": false + }, + "renewed": { + "amount": "1000000", + "host": "1db3d4c78cb69971fc64bd895c688f859325de80976d3af5325fe4f204884498", + "locked_at": 1795076141, + "mesh": "0x32b7fc2a4d0aea3e8e9f949800d000afbbc9df47b02f4db3033075fd1409ee05", + "refund_wallet": "0x1976840708a1baed9590ab1f25da6db72031f7da", + "unlock_at": 1795076319, + "withdrawn": false + }, + "refund_principal_verified": true + } + ], + "payment_only_transactions": [ + { + "open": "0xe03af69ce803ffe840b27e2ada21b453cf0100b00c7bba06aa3bd5902d5a684b", + "close": "0x71c9806c65d711141c3dc2125efb9af5a622990a68f113163e452a79d9e03b4a", + "reserved": "10", + "captured": "5", + "refunded": "5" + }, + { + "open": "0x5c228c7809a9a2bd5565951219dc1bbf9128d72f3e6c43f4ff151320726b6171", + "close": "0x989cf8ffaa2f75f2afd9be662a9add928bf904afd400798240f271c408100ef1", + "reserved": "10", + "captured": "5", + "refunded": "5" + } + ], + "buyer_restart_identity_preserved": true, + "pending_signed_attempts": 0, + "unresolved_payment_requests": 0 +} diff --git a/docs/tempo-bonds-testnet-trial.md b/docs/tempo-bonds-testnet-trial.md new file mode 100644 index 0000000..b15e76e --- /dev/null +++ b/docs/tempo-bonds-testnet-trial.md @@ -0,0 +1,43 @@ +# Tempo payments and bonds testnet trial + +This trial was recorded with the earlier payment design, which opened one native reserve per request; current payments reuse one channel per buyer and seller. + +This is a historical trial of the maturity-and-renewal escrow. The current source uses indefinite locks and delayed exits, requires a fresh deployment, and has different bytecode. The transactions below do not validate that newer contract. + +On 2026-11-19, two local Mesh hosts ran the production `tempo` plugin against Tempo Moderato, chain 42431, using fresh faucet-funded OUSD wallets. Inference used a canned OpenAI backend with one input and four output tokens. Mesh ran from `codex/tempo-bonds`, based on upstream `dc8a8fafb8bd51efc287840a84b764c35346b21b`. The immutable plugin SDK pin was unchanged. + +The escrow is `0x4dA347a95C1b49b8FC90Da083058682ac7613bf2`. Its deployed runtime matched the source and `contracts/runtime.hex` at the time of this historical trial, compiled with Solidity 0.8.30; it does not match the current exit-delay artifacts. Each host posted a separate 1 OUSD deposit, or 1,000,000 atomic units, binding its own host key to the same mesh. Automatic renewal extended each existing deposit without changing its amount, mesh, host key or refund wallet. Renewal was then disabled and both principals were refunded at maturity. OUSD Transfer logs confirmed the exact principal returned to each original funding wallet. + +## Observed behavior + +| Configuration or event | Result | +|---|---| +| Payments on, bonds off | Buffered and streaming requests succeeded; each reserved 10, captured 5 and refunded 5 atomic units. | +| Buyer restart | The explicit client node-key path preserved identity and payment state. | +| Payments and bonds on | Paid inference succeeded; both sides required the configured bond evidence. | +| In-place automatic renewal | Both on-chain deadlines advanced, preserving principal and identity bindings. | +| Bonds on, payments off | Inference succeeded without MPP request metadata. | +| Buyer omitted its bond reference | Seller returned HTTP 402 before inference dispatch. | +| Seller withdrew its bond | A fresh buyer did not admit or route to the seller; inference returned HTTP 404. | +| Payments and bonds off | Free inference succeeded. | +| Final journals and ledgers | Zero pending signed attempts and zero unresolved payment requests on both hosts. | + +## Finalized bond transactions + +| Wallet | Operation | Transaction | +|---|---|---| +| seller | deploy | [`0x9101a77db8a0e86380aa42876b962cb47120578ce3dc3e6d341ee42035216a83`](https://explore.tempo.xyz/tx/0x9101a77db8a0e86380aa42876b962cb47120578ce3dc3e6d341ee42035216a83) | +| seller | lock | [`0xf1585d39856231d552f8e14661e5e78a163cc52da43b62c43261c4ae6a8ced1b`](https://explore.tempo.xyz/tx/0xf1585d39856231d552f8e14661e5e78a163cc52da43b62c43261c4ae6a8ced1b) | +| seller | renew | [`0x8d96330ee33eb1f2193aa1ed449456f66d3afa371cc1468d3eb90276986a97db`](https://explore.tempo.xyz/tx/0x8d96330ee33eb1f2193aa1ed449456f66d3afa371cc1468d3eb90276986a97db) | +| seller | withdraw | [`0xd6cdbc4361a906785d128508ac3fed993b2b97f2846955ce7d84b770b2014cf2`](https://explore.tempo.xyz/tx/0xd6cdbc4361a906785d128508ac3fed993b2b97f2846955ce7d84b770b2014cf2) | +| buyer | lock | [`0xb72d17156f1600e50a1bbf22e77e36e2b48e9509b510e6c0d0500b378e8a6768`](https://explore.tempo.xyz/tx/0xb72d17156f1600e50a1bbf22e77e36e2b48e9509b510e6c0d0500b378e8a6768) | +| buyer | renew | [`0x150515d2de8448823c32cfe7e3511a672a714d3786addc1d262515c14d83d7b4`](https://explore.tempo.xyz/tx/0x150515d2de8448823c32cfe7e3511a672a714d3786addc1d262515c14d83d7b4) | +| buyer | withdraw | [`0x9c4306ba585ab15ee91758d15bd1a19dc3c88d534c3af7c64350421fbbac757c`](https://explore.tempo.xyz/tx/0x9c4306ba585ab15ee91758d15bd1a19dc3c88d534c3af7c64350421fbbac757c) | + +[Machine-readable public evidence](tempo-bonds-testnet-trial.json) includes initial and renewed state, outcomes and payment transaction hashes. Private wallet keys, passwords, signed transaction bytes, invitations and full host logs remain outside the tracked report. + +## Historical reproduction + +The maturity-and-renewal harness used for this trial has been replaced. Current `just testnet-bonds` and `--resume-bonds` commands exercise indefinite locks and delayed exits, and cannot reproduce or resume this historical escrow. Follow the [current trial instructions](tempo-exit-testnet-trial.md#reproduction-and-limits) with a fresh directory instead. Preserve historical wallets and journals separately. + +The trial found and corrected integration issues in explicit client identity persistence, constrained-stack peer ingress, host-owned grant configuration, deployment gas budgeting and private-mesh bootstrap order. Earlier setup attempts and their wallets were preserved. Every reserve created during those attempts finalized its settlement; no bond principal remains locked from the completed trial. Routine tests remain deterministic and offline. diff --git a/docs/tempo-exit-testnet-trial.json b/docs/tempo-exit-testnet-trial.json new file mode 100644 index 0000000..81479f6 --- /dev/null +++ b/docs/tempo-exit-testnet-trial.json @@ -0,0 +1,323 @@ +{ + "date": "2026-11-19", + "network": "Tempo Moderato", + "chain_id": 42431, + "asset": "0x20c0000000000000000000006a37da5c996874be", + "escrow": "0xd210B0356b3e45B37F29Ec763106dc23BF1cC3aa", + "runtime_keccak256": "0x2a5a7148b45dba623a798c19f910130cce6afafc651ef15534b59daaa8d1feb4", + "mesh_branch": "codex/tempo-bonds", + "mesh_base": "dc8a8fafb8bd51efc287840a84b764c35346b21b", + "canned_inference": true, + "exit_delay_seconds": 30, + "bond_principal_atomic": "1000000", + "transactions": [ + { + "wallet": "seller", + "feature": "payments", + "operation": "close", + "operation_id": "mpp/00000000-0000-4000-8000-000000000000/close", + "hash": "0x0ac0476246c6b08b5ea9f37c87df3fc8dcc1b16a61828a28f3295998bca1d0da", + "status": "finalized", + "block_number": 44954376, + "block_timestamp": 1795098204, + "gas_ousd_atomic": "191" + }, + { + "wallet": "seller", + "feature": "payments", + "operation": "close", + "operation_id": "mpp/00000000-0000-4000-8000-000000000001/close", + "hash": "0x8d3c42a12a261aea32521a4d84b2cf5492ae1e2b2307c45d21a88b69c9154245", + "status": "finalized", + "block_number": 44954411, + "block_timestamp": 1795098222, + "gas_ousd_atomic": "41" + }, + { + "wallet": "seller", + "feature": "payments", + "operation": "close", + "operation_id": "mpp/b2dec916-9148-4ca1-a14e-ef07a1b41bbc/close", + "hash": "0x4360ea4ffbf4e319e1fa3179be04d285df9ad9f44af4270ad3becb1a44988d6f", + "status": "finalized", + "block_number": 44954474, + "block_timestamp": 1795098256, + "gas_ousd_atomic": "41" + }, + { + "wallet": "seller", + "feature": "bonds", + "operation": "deploy", + "operation_id": "59252c61-24f6-4f0e-87bb-db3351a74cbc", + "hash": "0x430675a399c3f1b4ac44ff61e59fa8480606611278e88e30bc11939c5c3aff02", + "status": "finalized", + "block_number": 44954421, + "block_timestamp": 1795098228, + "gas_ousd_atomic": "2191" + }, + { + "wallet": "seller", + "feature": "bonds", + "operation": "lock", + "operation_id": "02f7c4c4-6a66-4950-ab3e-4ac249b2f867", + "hash": "0x950688e9a2988c4b9fc4f3e3c68a0ed0bb9c7724c7f94e48cd7b382899818ce9", + "status": "finalized", + "block_number": 44954431, + "block_timestamp": 1795098233, + "gas_ousd_atomic": "792" + }, + { + "wallet": "seller", + "feature": "bonds", + "operation": "request_exit", + "operation_id": "ef305d04-1e5e-476c-8188-7c557388d67f", + "hash": "0xf6e7bc06031309e974f564569179911608b03f7b661f21c804150ecb6f857359", + "status": "finalized", + "block_number": 44954604, + "block_timestamp": 1795098326, + "gas_ousd_atomic": "174" + }, + { + "wallet": "seller", + "feature": "bonds", + "operation": "withdraw", + "operation_id": "76f2a012-5d4b-4fcc-82bc-c0a658aedf2d", + "hash": "0x0157fcc4c618dab270329a07fcdb9923ae2926b8c95961862b8f7f3261750fd1", + "status": "finalized", + "block_number": 44954665, + "block_timestamp": 1795098359, + "gas_ousd_atomic": "183" + }, + { + "wallet": "buyer", + "feature": "payments", + "operation": "open", + "operation_id": "mpp/00000000-0000-4000-8000-000000000000/open", + "hash": "0xf7efe543b36f53c15b9a67190af7687242909626701a0d24dbf2d437ba300e8a", + "status": "finalized", + "block_number": 44954349, + "block_timestamp": 1795098189, + "gas_ousd_atomic": "327" + }, + { + "wallet": "buyer", + "feature": "payments", + "operation": "open", + "operation_id": "mpp/00000000-0000-4000-8000-000000000001/open", + "hash": "0x9075c3b298beddb0158111c932e216d993837f9404c930fcc6e27729af400e3e", + "status": "finalized", + "block_number": 44954385, + "block_timestamp": 1795098208, + "gas_ousd_atomic": "34" + }, + { + "wallet": "buyer", + "feature": "payments", + "operation": "open", + "operation_id": "mpp/b2dec916-9148-4ca1-a14e-ef07a1b41bbc/open", + "hash": "0x0e7f6e2d60b7c35e908cb6ffab700d8fba1e9dd0bc5178bf3ffc874b19933485", + "status": "finalized", + "block_number": 44954448, + "block_timestamp": 1795098242, + "gas_ousd_atomic": "34" + } + ], + "wallets": { + "seller": { + "address": "0x4e5a3223889A301363a5ad9F05baFBF648de47eE", + "balance_atomic": "999999996402", + "unresolved_transactions": 0, + "active_payment_obligations": 0, + "settled_payment_requests": 3, + "total_gas_ousd_atomic": "3613", + "initial_balance_atomic": "1000000000000" + }, + "buyer": { + "address": "0x86F9D0d3c10dE691e77f7Cc51bfCD14Ed6D4630e", + "balance_atomic": "999999999590", + "unresolved_transactions": 0, + "active_payment_obligations": 0, + "settled_payment_requests": 3, + "total_gas_ousd_atomic": "395", + "initial_balance_atomic": "1000000000000" + } + }, + "bond": { + "wallet": "seller", + "bond_id": "0xad5aaa4db404fcc0e74ded4ad12e6f0dcfb83969da504d8470922813d862931b", + "initial": { + "amount": "1000000", + "exit_delay_seconds": 30, + "host": "90cf193584e9628904f64377172df7c0d38e3353f330b86490956307c3e8d0dd", + "mesh": "0xde89b0e869e0721d7eeed941a99d52f11e0f0f965ce6c3d424e7d6859c821564", + "refund_wallet": "0x4e5a3223889a301363a5ad9f05bafbf648de47ee", + "withdraw_at": "0", + "withdrawn": false + }, + "active_after_restart": { + "amount": "1000000", + "exit_delay_seconds": 30, + "host": "90cf193584e9628904f64377172df7c0d38e3353f330b86490956307c3e8d0dd", + "mesh": "0xde89b0e869e0721d7eeed941a99d52f11e0f0f965ce6c3d424e7d6859c821564", + "refund_wallet": "0x4e5a3223889a301363a5ad9f05bafbf648de47ee", + "withdraw_at": "0", + "withdrawn": false + }, + "exiting": { + "amount": "1000000", + "exit_delay_seconds": 30, + "host": "90cf193584e9628904f64377172df7c0d38e3353f330b86490956307c3e8d0dd", + "mesh": "0xde89b0e869e0721d7eeed941a99d52f11e0f0f965ce6c3d424e7d6859c821564", + "refund_wallet": "0x4e5a3223889a301363a5ad9f05bafbf648de47ee", + "withdraw_at": "1795098356", + "withdrawn": false + }, + "exit_verification": { + "accepted": true, + "amount": "1000000", + "block": "0x2adf3f0", + "exit_delay_seconds": 30, + "valid_until": 1795098356, + "withdraw_at": "1795098356" + }, + "withdrawable_verification": { + "accepted": false, + "reason": "bond is withdrawable or finalized evidence lease already expired", + "valid_until": 1795098359 + }, + "early_withdraw_rejected": true, + "final": { + "mesh": "0xde89b0e869e0721d7eeed941a99d52f11e0f0f965ce6c3d424e7d6859c821564", + "host": "90cf193584e9628904f64377172df7c0d38e3353f330b86490956307c3e8d0dd", + "refund_wallet": "0x4e5a3223889a301363a5ad9f05bafbf648de47ee", + "amount": "1000000", + "exit_delay_seconds": 30, + "withdraw_at": "1795098356", + "withdrawn": true + }, + "refund_principal_verified": true, + "seconds_active_before_exit": 93, + "active_beyond_delay": { + "verified": true, + "block_number": 44954603, + "held_seconds": 92, + "state": { + "mesh": "0xde89b0e869e0721d7eeed941a99d52f11e0f0f965ce6c3d424e7d6859c821564", + "host": "90cf193584e9628904f64377172df7c0d38e3353f330b86490956307c3e8d0dd", + "refund_wallet": "0x4e5a3223889a301363a5ad9f05bafbf648de47ee", + "amount": "1000000", + "exit_delay_seconds": 30, + "withdraw_at": "0", + "withdrawn": false + } + } + }, + "scenarios": { + "payments_and_bonds": { + "status": 200, + "usage": { + "completion_tokens": 4, + "prompt_tokens": 1, + "total_tokens": 5 + } + }, + "bonds_only": { + "status": 200, + "usage": { + "completion_tokens": 4, + "prompt_tokens": 1, + "total_tokens": 5 + } + }, + "unbonded_provider": { + "status": 404, + "usage": null + }, + "withdrawn_provider": { + "status": 404, + "usage": null, + "verification": { + "accepted": false, + "reason": "bond absent, withdrawn or below minimum amount", + "valid_until": 1795098382 + } + }, + "both_disabled": { + "status": 200, + "usage": { + "completion_tokens": 4, + "prompt_tokens": 1, + "total_tokens": 5 + } + } + }, + "initial_payments": { + "inference_requests": 2, + "buffered_requests": 1, + "streaming_requests": 1, + "buyer_restart_identity_preserved": true, + "maximum_per_request_atomic": 10, + "capture_per_request_atomic": 5, + "refund_per_request_atomic": 5 + }, + "escrow_balance_atomic": "0", + "finalized_cutoff": { + "number": 44954791, + "hash": "0x9f918e0e45d3d80411636d1f1bcca6b70a03cd47273a6ce10cccbac3292204d5", + "timestamp": 1795098426 + }, + "eligibility_policy": { + "active": "finalized block timestamp plus exit delay", + "exiting": "exact withdrawal deadline", + "core_validity_cap": null, + "eligibility_cache_owner": "Mesh", + "failure_retry_seconds": 1, + "invalidation_scope": "stopped verifier only" + }, + "binary_sha256": { + "tempo": "775c7a3d3d7387c6f09f37757ea323a41d5761ffa8765a75a00e49a578738cae", + "host-smoke": "990486bacecf94d99375d039e1f515c4d4fadddb78cc6b17f40c79820cecc2df", + "demo-backend-fixture": "82f4da3f3396e76b30a528d56d3b442363e766950d6a89ca8ca202eedf46f55a", + "tempo-fixture": "6b718500d058310cde301714a49e45b5abc33c0e47302f8ccd1138f651df7749" + }, + "mesh_commit": "7b2b4568de768d893fe67977685626c6f8c1e032", + "mesh_version": "mesh-llm 0.80.0+g7B2B45", + "mesh_binary_sha256": "6b874481e4c6345d267882179960f7c7da17a0e639559c493b10d53b245ad9fd", + "mesh_worktree_clean": true, + "completed_resume": { + "verified": true, + "files_preserved": 105, + "network_transactions_sent": 0 + }, + "offline_integration": { + "buffered_requests": 1, + "buyer_restart_identity_preserved": true, + "capture_per_request_atomic": 5, + "fabricated_channels": 2, + "inference_requests": 2, + "maximum_per_request_atomic": 10, + "network_transactions_sent": 0, + "offline": true, + "real_mesh_hosts": 2, + "refund_per_request_atomic": 5, + "streaming_requests": 1, + "wallet_spending_not_http_exposed": true + }, + "buyer_requires_no_bond": { + "verified": true, + "buyer_bond_transactions": 0, + "paid_provider_close": "0x4360ea4ffbf4e319e1fa3179be04d285df9ad9f44af4270ad3becb1a44988d6f" + }, + "no_bond_payments_before_escrow_deployment": { + "verified": true, + "close_hashes": [ + "0x0ac0476246c6b08b5ea9f37c87df3fc8dcc1b16a61828a28f3295998bca1d0da", + "0x8d3c42a12a261aea32521a4d84b2cf5492ae1e2b2307c45d21a88b69c9154245" + ], + "deployment_hash": "0x430675a399c3f1b4ac44ff61e59fa8480606611278e88e30bc11939c5c3aff02" + }, + "daily_test_budget_atomic": "20000", + "mesh_stack_commit": "8bcdbedee515b0d2e7baf7807c574a55130ca10a", + "mesh_source_tree": "bcf638459ab8e65438bd49d239fad3ced896aa02", + "mesh_stack_source_equivalence_verified": true +} diff --git a/docs/tempo-exit-testnet-trial.md b/docs/tempo-exit-testnet-trial.md new file mode 100644 index 0000000..69da521 --- /dev/null +++ b/docs/tempo-exit-testnet-trial.md @@ -0,0 +1,64 @@ +# Provider bond testnet trial + +This trial was recorded with the earlier payment design, which opened one native reserve per request; current payments reuse one channel per buyer and seller. + +On 2026-11-19, two local Mesh hosts ran the production `tempo` plugin on Tempo Moderato, chain 42431, using fresh faucet-funded wallets and canned inference. The provider posted one refundable bond. The buyer posted no bond and its complete bond journal remained empty. No mainnet transactions were sent. + +The host was rebuilt from clean `codex/tempo-bonds` commit `7b2b4568de768d893fe67977685626c6f8c1e032`, reporting `mesh-llm 0.80.0+g7B2B45`. The Mesh SHA-256 was `6b874481e4c6345d267882179960f7c7da17a0e639559c493b10d53b245ad9fd`; the production Tempo SHA-256 was `775c7a3d3d7387c6f09f37757ea323a41d5761ffa8765a75a00e49a578738cae`. The SDK dependency was pinned to the companion verifier-contract preparation commit `c0d31fd2453478dd2f4ebf3514acdfed5bb16aee`. A separate two-host offline smoke passed buffered/SSE inference, partial refunds and buyer restart with preserved identity, sending zero network transactions. + +The escrow is `0xd210B0356b3e45B37F29Ec763106dc23BF1cC3aa`. Its deployed runtime exactly matched `contracts/runtime.hex`, with Keccak-256 `0x2a5a7148b45dba623a798c19f910130cce6afafc651ef15534b59daaa8d1feb4`. The provider deposited 1 test OUSD, or 1,000,000 atomic units, with a 30-second exit delay for this explicit trial. Production policies can require longer delays. Funds remained locked beyond that delay without renewal; the countdown started only when the provider requested exit. + +## Observed behavior + +| Scenario | Result | +| --- | --- | +| Payments without bonds | Buffered and SSE requests succeeded before escrow deployment. | +| Payments with provider eligibility enabled | Succeeded with a bonded provider and an unbonded buyer. | +| Provider bond with payments disabled | Free inference succeeded. | +| Provider omits its published proof | Provider inference became unavailable. | +| Restart and indefinite funding | Bond remained active without renewal transactions, including beyond its exit delay. | +| Exit countdown | Verification accepted the provider until the withdrawal deadline; early withdrawal reverted. | +| Deadline reached, principal still escrowed | Verification rejected the provider as withdrawable. | +| Withdrawal | Finalized and returned the full 1,000,000 atomic units to the original funding wallet. | +| Withdrawn provider | Verification rejected the proof and inference was unavailable. | +| Payments and bonds disabled | Free inference succeeded. | + +Three paid requests settled in total. Each reserved 10 atomic units, captured 5 and refunded 5. Buyer and seller ledgers agreed with finalized closure evidence. Mesh owned the only provider eligibility cache. Tempo returned deadlines from each bond's exit delay or known withdrawal deadline, with no core validity cap; failed verification used a test-only 1-second retry deadline. Admission callbacks received no bond evidence and performed no bond verification. Separate Mesh regression tests confirm that unrelated plugin stops preserve cached and in-flight verification, while a verifier stop invalidates only its own decisions. + +## Transactions and final state + +| Wallet | Bond operation | Finalized transaction | +| --- | --- | --- | +| seller | deploy | [`0x430675a399c3f1b4ac44ff61e59fa8480606611278e88e30bc11939c5c3aff02`](https://explore.tempo.xyz/tx/0x430675a399c3f1b4ac44ff61e59fa8480606611278e88e30bc11939c5c3aff02) | +| seller | lock | [`0x950688e9a2988c4b9fc4f3e3c68a0ed0bb9c7724c7f94e48cd7b382899818ce9`](https://explore.tempo.xyz/tx/0x950688e9a2988c4b9fc4f3e3c68a0ed0bb9c7724c7f94e48cd7b382899818ce9) | +| seller | request_exit | [`0xf6e7bc06031309e974f564569179911608b03f7b661f21c804150ecb6f857359`](https://explore.tempo.xyz/tx/0xf6e7bc06031309e974f564569179911608b03f7b661f21c804150ecb6f857359) | +| seller | withdraw | [`0x0157fcc4c618dab270329a07fcdb9923ae2926b8c95961862b8f7f3261750fd1`](https://explore.tempo.xyz/tx/0x0157fcc4c618dab270329a07fcdb9923ae2926b8c95961862b8f7f3261750fd1) | + +| Wallet | Address | Gas, atomic test OUSD | Unresolved transactions | Active payment obligations | +| --- | --- | --- | --- | --- | +| seller | `0x4e5a3223889A301363a5ad9F05baFBF648de47eE` | 3613 | 0 | 0 | +| buyer | `0x86F9D0d3c10dE691e77f7Cc51bfCD14Ed6D4630e` | 395 | 0 | 0 | + +All 10 signed transactions had successful canonical receipts below finalized block 44954791. Independent RPC checks confirmed the exact principal refund, a zero escrow balance, withdrawal at or after the exit deadline, and reconciled final wallet balances. The buyer sent zero bond transactions. Repeating completed-trial resume preserved all 105 private state and evidence files without sending transactions. + +[Public machine-readable evidence](tempo-exit-testnet-trial.json) includes transaction hashes and receipt summaries, deadlines, active/exiting/final bond state, rejection results, executable hashes and wallet reconciliation. Full receipts and transfer logs can be retrieved using the transaction hashes. Private keys, passwords, raw signed transaction bytes, invitations and host logs are excluded. + +## Reproduction and limits + +The recorded results above belong to the historical executable hashes and Mesh revision in the evidence file. Exact reproduction requires those preserved staged binaries and their matching configuration. Do not pair the recorded Mesh binary with the current checkout: its evidence-grant API differs. + +The commands below start a new trial of the current checkout against a newly built current Mesh `peer-evidence` host. This combination has offline validation only; the commands are not evidence that the current revision passed testnet. Build the fixture tools and production release, then stage the harness and canned backend beside the release binary: + +```sh +just build +just release +trial_bin_dir=$(mktemp -d "${TMPDIR:-/tmp}/tempo-trial-bin.XXXXXX") +cp target/debug/host-smoke target/debug/demo-backend-fixture "$trial_bin_dir/" +cp target/release/tempo "$trial_bin_dir/" +"$trial_bin_dir/host-smoke" --mesh-bin /absolute/path/to/companion/mesh-llm \ + --output-dir /absolute/fresh/private/trial-directory --tempo-testnet --tempo-bonds +``` + +This deliberately creates encrypted Moderato wallets, requests faucet OUSD, deploys the pinned escrow and refunds the provider's principal. Preserve the private directory, which contains wallet state, passwords, operation inputs, invitations, journals and logs. Resume an interrupted trial with the same staged binaries, directory and `--tempo-testnet --tempo-bonds --resume-bonds`. Saved transaction inputs and release checkpoints preserve the original operations. A completed run resumes without modifying its files. + +The recorded run validated native testnet payments and provider-bond integration using canned inference. It does not establish real model execution guarantees, mainnet acceptance, throughput or economic viability. Revert, expiry, missing-receipt and crash recovery paths retain deterministic offline regression coverage. The earlier maturity-and-renewal trial is historical and uses a different escrow runtime. diff --git a/docs/testnet-trial.md b/docs/testnet-trial.md new file mode 100644 index 0000000..1a7f937 --- /dev/null +++ b/docs/testnet-trial.md @@ -0,0 +1,60 @@ +# Faucet-funded buyer-seller trial + +This trial was recorded with the earlier payment design, which opened one native reserve per request; current payments reuse one channel per buyer and seller. + +On 2026-11-13, two local Mesh 0.79.0 hosts completed a native Tempo Moderato payment trial using faucet test OUSD only. The Homebrew release included its native runtime. Each host ran the normal `pay-stablecoin` executable. A separate canned OpenAI backend returned one input token and four output tokens, so this validates the payment and host lifecycle rather than model execution or metering accuracy. + +The buyer used an explicit seller allowlist and request approval. Each request reserved 10 atomic test OUSD units, captured 5, and refunded 5. One atomic unit is 0.000001 test OUSD. Payment and gas both used token `0x20c0000000000000000000006a37da5c996874be` on chain `42431`. + +| Request | Inference | Reserved | Captured | Refunded | +| --- | --- | ---: | ---: | ---: | +| 1 | Buffered | 10 | 5 | 5 | +| 2 | Streaming with terminal usage | 10 | 5 | 5 | + +The buyer restarted after the first settled request and retained its node identity, wallet, and accounting state. Both peers ended without active obligations. Wallet signing was unavailable through the public tool surface. + +## Finalized transaction evidence + +Buffered request `00000000-0000-4000-8000-000000000000`: + +- [Open transaction](https://explore.tempo.xyz/tx/0xe3e9fa3f76aa9b0770ec69a9decd91b3d5793d410083ba02be0fc75194813313) +- [Close transaction](https://explore.tempo.xyz/tx/0xee2d46edd93401e5f0f7fec6d48b74cfaa8970634f2b6c825fd5d1916cf90883) +- Channel: `0x0f0f5dc03ecfba4416cf5841e4c628432d3d10408019503e9ba498e92fa06b4a`. + +Streaming request `00000000-0000-4000-8000-000000000001`: + +- [Open transaction](https://explore.tempo.xyz/tx/0xa8b2d5e10afa8c454887f7d202dbc4c9784aea0d7e841621b679c7a9ee2ac51f) +- [Close transaction](https://explore.tempo.xyz/tx/0x000eca990ed44e962315374a9a623c20d7de1bbf7644cc80fb44eaefcc19074d) +- Channel: `0xdb551e952caa0f84bb0722229a9df164d6fec44392ed3d9cb3e255ffd662d321`. + +Independent fresh RPC reads confirmed all four successful transactions were finalized native type `0x76`, targeted the canonical reserve, and used test OUSD as the fee token. The close events paid 5 to the seller and returned 5 to the buyer for each channel. Both channels had deleted, zero state at finalized block `43970414`. + +## Balance and gas reconciliation + +| Wallet | Initial balance | Final balance | Payment delta | Gas | +| --- | ---: | ---: | ---: | ---: | +| Buyer | 1000000000000 | 999999999629 | -10 | 361 | +| Seller | 1000000000000 | 999999999778 | +10 | 232 | + +All table amounts are atomic test OUSD units. Each wallet received 1,000,000 test OUSD from the faucet. The final balance of each wallet equals its initial balance plus payment delta minus gas. Total gas was 593 atomic units, or 0.000593 test OUSD. First-use account/storage costs differ from subsequent transactions; these values are observations from this trial, not fee benchmarks. + +## Repeat the payment-only scenario + +This records the earlier `pay-stablecoin` executable, now named `tempo`. Current full payment-and-bond validation is recorded in the [exit-delay trial](tempo-exit-testnet-trial.md). To repeat this payment-only scenario with the current plugin, build the fixture tools and native plugin, then deliberately invoke testnet mode with a fresh private directory: + +```sh +just build +just testnet-smoke /opt/homebrew/bin/mesh-llm /absolute/private/fresh-trial-directory +``` + +Without `just`, use: + +```sh +cargo build --locked --all-features +target/debug/host-smoke --mesh-bin /opt/homebrew/bin/mesh-llm \ + --output-dir /absolute/private/fresh-trial-directory --tempo-testnet +``` + +The command creates encrypted wallets and private password files, requests faucet coins, runs buffered/SSE requests through both hosts, checks settlement receipts, and stops the hosts. Preserve the output directory: it contains wallet keys, credentials, journals, configs, private invitations, logs, and `result.json`. The completed local run is stored under `private/tempo-079-trial/`, which is ignored by Git and excluded from packages. Its `verification.json` records the independent RPC audit. + +This trial did not exercise seller death during inference, missing terminal usage, or the 900-second native payer withdrawal path. Those remain covered by local fixtures and require separate testnet acceptance. diff --git a/docs/validation.md b/docs/validation.md new file mode 100644 index 0000000..1dabec4 --- /dev/null +++ b/docs/validation.md @@ -0,0 +1,100 @@ +# Validation record + +Routine tests use deterministic offline wallets. Network funding and transactions run only in separately authorized trials. The current checks used Apple Silicon, Rust 1.99.0 for Mesh and Rust 1.95.0 for Tempo. + +## Long-lived payment channels, 2026-11-24 + +Payments changed from one native reserve per request to one long-lived channel per buyer and seller, with concurrent requests per pair, Lightning-style buyer configuration, standing and strikes, ledger settings, the new `control` commands and journaled wallet sends. This change has offline validation only. Every dated section below describes the earlier per-request design and its APIs. + +Formatting, `cargo check` and Clippy with warnings denied, `cargo test --locked --all-features` (155 library tests, one harness test and six process tests) and rustdoc with warnings denied passed. The engine tests run with a configuration that passes startup validation. The tests cover: + +- paid requests without client payment fields, decided by buyer policy: the first paying the upfront, later ones reusing the channel, a seller without a paid price serving the model free, a missing token limit refused with a clear reason, and a forwarded body with another digest refused; +- a request refused while its channel opens cancelled with the seller, so the next one proceeds, and undispatched requests cancelled after a restart; +- the seller admitting the voucher it already stores without a chain call, while a new or higher one is verified; +- top-ups only when a voucher would not fit, a concurrent bill waiting for a pending top-up, and the refusal before dispatch when one top-up could not pay the worst case; +- requests with different bodies running at once on one channel, a later bill held until the earlier one, a bill between another request's quote and voucher, also when it overtakes the quote, bills of concurrent requests paid beyond the daily budget, and two first requests opening one channel with the second at upfront 0; +- standing: a buyer that paid opening its next channel with a zero voucher, until a seller restart, and no standing from a refused voucher; a zero voucher signed and verified by the native wallet; +- strikes: three unpaid bills answered `Busy` until one is paid, bills lost to an unpaid close counted on a new channel until `unblock`, a bill the seller's voucher covers not counted after a missed withdrawal, and usage after a close began recorded without a bill; +- bill checks against the buyer's own usage, rates and running total, the cache discount, unbilled output beyond the limit, bills capped at the worst case when the prompt exceeds the body bound, and tampered bills above it; a seller offline through the grace recording the capture it lost; +- the daily budget counting voucher increments, the cap, `free_only` refusal, bills of work dispatched before a switch to `free_only`, and models without a buy price; +- the worst-case cost checked against the cap and the remaining budget before any open or voucher; +- a seller repeating the upfront on an existing channel, refused, and refilling credit up to the admission deposit, accepted; +- the seller requiring a voucher of at least its view plus the upfront; +- quotes from a seller behind on vouchers or that never received the first one, and refusal of a voucher above the buyer's own; +- unpaid-bill, idle and close-request closes, including a running request billed before the close; +- the close watch: a close event inspecting only the channel it names, a failed scan keeping its cursor and inspecting every channel, the backstop finding a close request without a log, and a deferred close checked every tick without another log; +- buyer idle recovery and its renewed close request after a cancelling top-up; +- restart recovery of vouchers, unknown usage and pending transactions with their original bytes; +- unknown usage after a seller restart leaving the pair unblocked: the acknowledged `Unbilled` notice closing the buyer's request unpaid, the next request served on the same channel, late usage recorded but not billed, and waivers before and after a later quote; +- back-to-back requests: an identical request sent before the seller has the previous payment answered `Busy` and served once it arrives, an identical body refused while in flight, and a covered bill delivered after the next quote accepted without recovering the channel; +- a node buying from and selling to the same peer at once; +- settings seeded from config, per-model deposits removed with their price, channel requirements re-registered on price changes, and a refused host call repeated on the next tick; +- bonds: the testnet escrow and the default requirement of 1 OUSD for one day used when unstated, null turning the requirement off, an explicit escrow required on mainnet, a finalized lock published once and replaced by a newer one, a withdrawal withdrawing the reference, the operator withdrawing it, and a refused publication repeated on the next tick; +- a node without a wallet starting the production binary to verify bonds, refusing automatic buying, prices and a balance, refusing to start with prices configured, and creating its unlocked wallet with a private random password on first use; +- the default configuration written once in an owner-only directory and kept after edits, and `bond_lock` without inputs resolving to the same default bond for the observed mesh; +- control listings without voucher signatures; +- wallet sends: idempotency, the unresolved-transaction gate, fee bounds, refusal of self, token and reserve recipients, and receipt verification. + +The loopback RPC fixture models opens, top-ups that cancel a close request, close requests, closes with a cumulative voucher and capture, withdrawals and OUSD transfers, with their events, and serves log queries filtered by block range and topics, which a test uses to check that a close-event scan names only its payee's channels and skips a long gap. The documented demo configurations are loaded and validated by a test. No mainnet transaction was sent. + +A two-host Moderato trial (`just testnet-bonds`) on 2026-11-25 passed against the companion Mesh `peer-evidence` branch at `e93032532` with one uncommitted host change: `PublishPeerEvidence` announces the signed record carrying a changed publication at once instead of at the next periodic gossip. Both nodes used fresh faucet-funded wallets, and the buyer required a bond of 1 OUSD with a 30-second exit delay in the Moderato escrow. With both nodes running, the buyer received the seller's advertisement but could not select it and its verifier reported no bond. The seller then locked its bond, and the plugin published it once finalized; without a restart on either node, the buyer selected the seller and paid for inference over a new channel (deposit 200, upfront voucher 10, one bill of 5 on both ledgers). Free inference against the bonded seller, rejection after the seller withdrew its published reference, eligibility through the exit countdown, early-withdrawal rejection and the full refund also passed. Before the host change, the buyer listed the seller within seconds of publication but routing refused it for about a minute, until the next gossip carried the record. Inference used the canned fixture backend. + +The same day, the tester walkthrough was run by hand on Moderato against the companion Mesh `peer-evidence` branch at `d98e30289`, with fresh homes and an empty environment for every command. The seller served `unsloth/Qwen3-0.6B-GGUF:Q4_K_M` with `mesh-llm serve --model Qwen3-0.6B`, and both nodes installed the plugin with no `[[plugin]]` entry and used its default config, with the buyer's paid settings added. Before the bond, the buyer's model list was empty and its request was refused. `bond_lock` with no arguments locked 1 OUSD with the testnet default exit delay of 60 seconds. The buyer listed the model about 2 seconds after publication and its paid request was answered (one bill of 22 for 13 prompt and 9 completion tokens; deposit 100000). The buyer's `recover` closed the channel 8 seconds later, with 22 captured and 99978 refunded. After `bond_request_exit`, the buyer stopped listing the seller at the withdrawal deadline, and `bond_withdraw` returned the principal, less gas, and withdrew the published reference. While the bond was active, the buyer's model list dropped the seller for about a second once a minute, when its bond decision expired before Mesh verified it again. A fourth run against `c86635316`, where Mesh renews an acceptance 10 seconds before it expires, listed the seller in all 300 polls over 2.5 minutes of an active bond. A fifth run replaced the exit and withdrawal commands with `bond_exit`, run once without arguments: its exit landed at 14:38:37, the buyer stopped listing the seller at the deadline a minute later, and the plugin's own withdrawal landed 2 seconds after the deadline, returning the principal and withdrawing the published reference. A sixth run left the buyer's generated config untouched: the buyer turned on paid buying with only the `policy` control (automatic, daily budget 100000), paid a bill of 24 over a channel with the default 1 OUSD deposit, and got 999976 back from `recover`; `bond_exit` and the automatic withdrawal then completed as before. A seventh run followed the PR walkthrough word for word, with `recover` given no arguments: it closed the buyer's only channel, 22 captured and 999978 refunded. An eighth run against the simplified companion host at `d9cf0d4a2` (since rebuilt as `c105fb819`, which differs only in the SDK manifest file layout), which runs one verifier, no longer forces installed verifiers to be required and has no restart-scoped verdicts, passed the same walkthrough with the plugin returning year-long deadlines for policy-only decisions. + +## Current Mesh compatibility, 2026-11-21 + +Validation used clean Mesh `14bb8f4f1ee5d0463fa3b1ef06a780e640a9566c` on branch `peer-evidence` and the Tempo working copy based on `f7f8c963ee41677d15a355106c639ff06fecff9a`. Tempo source and its immutable SDK pin `8094e51b476efdf4ccc0cd5d5ff56d8f46f2d997` were preserved. The SDK pin supplies the interface; the full companion host branch supplies enforcement. Tempo requires both `peer_evidence.v1` and `peer_evidence.manifest_enforcement.v1`. The operator will publish the pinned Git revision for fresh checkouts; it was not replaced with a dependency override or vendored copy. + +Buyers apply bond policy to the seller they select; sellers choose their workers. Each relay with a configured verifier applies its local policy to provider gossip. Configured verifiers require fresh signed provider records, including when policy accepts missing evidence. Mesh owns one bounded eligibility cache. Policy-only verdicts last until verifier restart or eviction; bond-state checks and transient failures retain finite deadlines. Mesh checks the selected seller's cached bond eligibility before payment callbacks, without another bond-verification call. Paid callbacks still perform payment RPCs. The [bond guide](bonds.md) describes validity and exit semantics. + +Focused tests passed for signed gossip, cache reuse and expiry, scoped restart invalidation, bounded verifier dispatch, cancellation-safe teardown, selected-seller admission, routing retries, stage authorization and ordinary lifecycle recovery. Final changes passed 72 evidence tests, 20 routing tests, 24 model-route tests and focused process lifecycle tests. Formatting, shipped-host Clippy with warnings denied, the full Mesh debug product build and API documentation passed. Host rustdoc retains 14 pre-existing warnings. The website rendered successfully. A two-host offline smoke passed buffered/SSE inference, exact capture/refund, private wallet operations and persistent buyer identity across restart. Slow/full suites were not run for this pass. + +Fresh independent correctness and minimality reviews of the complete final Mesh PR found no remaining actionable defects. Preparation, enforcement and the separate persistent client-key fix remain logical commits. Mesh is clean; Tempo documentation changes remain in its working copy. Nothing was pushed. + +A fresh two-host Moderato trial passed on chain 42431. It covered paid inference without bonds, paid and free inference with a bonded seller and unbonded buyer, and restart without renewal. Mesh catalogs excluded providers with missing required proof and after withdrawal. Direct verifier calls accepted the exiting bond and rejected it once withdrawal became possible; a read-only contract call rejected early withdrawal. The full principal was refunded. Removing the buyer requirement restored free inference after withdrawal. An independent audit confirmed all 10 transactions finalized on canonical blocks, exact escrow runtime bytecode, a 1,000,000-atomic-unit principal refund, zero escrow balance, three closed paid requests per peer with capture/refund of 5 atomic units each, no active transaction attempts and no buyer bond attempts. + +The trial used 30-second exit delays and a 1-second verification failure retry to exercise boundaries; production retries default to 60 seconds. Its backend returns canned usage, so this validates integration and settlement rather than model quality. No mainnet transaction was sent. Earlier dated sections below retain their historical APIs and validation scope. + +## Previous API cleanup, 2026-11-19 (superseded) + +At this earlier validation point, the uncommitted cleanup removed the two evidence lookup RPCs and the optional provider-filter switch. An empty evidence grant table requires provider verification; initialization reports grant presence, node identity uses the existing identity API, and Tempo tracks mesh ID from snapshots/events. Only local publication remains an evidence host RPC. Tempo’s provider policy is always applied when bonds are enabled; publication-only mode is removed. Mesh still initiates verification and owns the eligibility cache; admission performs no evidence lookup. + +Focused fast tests passed: 289 Mesh configuration tests, three SDK contract/compatibility tests, three host initialization tests, 13 host evidence/cache and loopback gossip tests, four Tempo runtime tests, three provider-policy tests, eight native bond fixture tests, two harness tests and six Tempo process tests. These cover mandatory enforcement, obsolete-switch rejection, cache reuse, scoped invalidation and expiry without deleting signed records. The process tests cover early configuration rejection and mesh-ID snapshot updates and clearing without a host lookup. Mesh and Tempo also passed incremental checks and Clippy with warnings denied. Configuration, SDK and Tempo rustdoc passed with warnings denied; host rustdoc completed with its 14 existing private-link warnings. Validation used an isolated Cargo manifest referencing the working-copy source and local SDK, preserving the repository's immutable dependency pin and lockfile. The uncommitted SDK API requires this local override until a new SDK revision is committed and pinned. + +Full suites, product/package builds and testnet trials were deliberately deferred for this cleanup. The complete validation and Moderato evidence below describe the preceding tested source, not this uncommitted API change. No changes had been folded into the Mesh commit stack at that validation point. + +## Last complete offline checks, 2026-11-19 + +The preceding full validation passed 70 library tests, two trial-harness tests, and five process-level integration tests. It covers capped funding, admission, exact request identity, unsupported endpoints/versions, partial/zero/full capture, overruns, unknown usage, waiver, lost replies, restart recovery, budgets, exclusive ownership, identity pins, typed controls, and recovery after reducing the new-channel payment limit. Regression checks cover explicit testnet/mainnet selection, network-specific default RPCs, wallet profile and journal/ledger isolation, cross-network agreement rejection before RPC or journal changes, and cross-network voucher rejection before capture. An RPC reporting the wrong selected chain is rejected before token reads, signing, journaling, or broadcast. Testnet remains the default. + +Read-only calls to `https://rpc.moderato.tempo.xyz` confirmed chain 42431, test OUSD symbol and six decimals, the reserve's 900-second close grace, and EIP-712 domain separator `0xa3aa475070603a80823360e5a4a0d3b4fe2cd4e82a109ee3c21a4640a199688d`. Read-only mainnet calls confirmed chain 4217, six-decimal OUSD, the same 900-second grace, and domain separator `0x6465ffa0b0c1e7cfc1a894ba54d79615bc06fd7cc9cfec558f3df82189d17367`. Both networks' domain and voucher digest vectors match independent ethers 6.17 calculations. These metadata reads do not establish funded mainnet settlement behavior; no mainnet wallet was initialized or funded and no mainnet transaction was sent. + +The engine-to-native-wallet roundtrip uses direct typed calls and actual native signing, ABI/events, capped vouchers, and finalized evidence checks against the local RPC fixture. It verifies one funding transaction, one close transaction, capture of 5 from a reserve of 10, and return of the other 5 on each simulated network. Lost-reply restart tests preserve the original signed bytes and flat journal representation on both networks, verify that public attempt output omits signed bytes, and reject reopening their journals under the other network. The fixture does not execute a Tempo node or the reserve contract. + +Process-level tests launch the actual binaries over private Unix sockets. The explicit fixture entry point initializes, advertises `control` and `verify_peer_evidence`, answers status/balance/attempts, shuts down, and restarts without any wallet capability or operation binding. The production entry point is tested with the same fixture environment variables: it still requires the native wallet profile and refuses startup without creating keys or a fake chain database. + +That tested revision passed `just check`, `just test`, `just doc`, `just package`, and `just contracts-check`. The contract suite includes six tests, with 256 cases in the principal-conservation fuzz test. Compiled creation and runtime bytecode matched the checked-in artifacts. + +Tests require local Unix/loopback sockets. Production packaging uses default features and ships one executable. Archive validation checks checksums, contents, metadata, version, the generated admission manifest, and absence of external wallet bindings. The normal CLI exposes local initialization, inspection, explicit bond transactions and reconciliation. Payments sign internally during request processing; bond transactions require explicit operator commands. + +## Two-host acceptance, 2026-11-13 + +After the offline checks, Mesh was upgraded through its existing Homebrew installation from 0.77.0 to the latest stable release, 0.79.0, including the bundled native runtime. The two-real-host harness passed with offline wallets, buffered/SSE canned inference, partial refunds, and buyer restart. + +An explicitly authorized native trial then created two fresh encrypted wallets and obtained Moderato faucet test OUSD. Two real hosts ran the normal native payment executable with the pinned SDK. One buffered request and one streaming request each reserved 10 atomic test OUSD units, captured 5, and refunded 5. The buyer restarted between requests with the same node and wallet identity. Both peers finished without active obligations. + +Independent fresh RPC reads confirmed four successful finalized type `0x76` transactions to the native reserve, the close events' capture/refund amounts, deleted channel state, and exact wallet balance reconciliation. Buyer gas was 361 atomic test OUSD units and seller gas was 232, for 593 total. See the [trial record and transaction links](testnet-trial.md). + +The backend supplied canned output and declared usage, so this trial does not validate model execution or metering accuracy. Seller failure during inference, missing usage, and payer withdrawal still need authorized testnet acceptance. See [release boundaries](production-readiness.md) for terminal usage durability and execution-deadline dependencies in Mesh. + +The [indefinite-bond Moderato trial](tempo-exit-testnet-trial.md) covers paid inference with no bonds, the provider bonded and the buyer unbonded, followed by eligibility during the exit delay, rejection at the withdrawal deadline and full principal refunds. Its machine-readable evidence independently reconciles finalized receipts, wallet balances and zero unresolved obligations. + +## Committed Mesh core compatibility, 2026-11-19 + +The final Mesh stack ends at `8bcdbedee515b0d2e7baf7807c574a55130ca10a`. Its Git source tree `bcf638459ab8e65438bd49d239fad3ced896aa02` exactly matches the tested commit; only commit-message wrapping changed afterward. The exact tested commit is retained on `codex/tempo-bonds-testnet-20261119`. + +Mesh was rebuilt from clean `codex/tempo-bonds` commit `7b2b4568de768d893fe67977685626c6f8c1e032`, reporting `mesh-llm 0.80.0+g7B2B45`. The production Tempo plugin passed a deterministic two-host offline smoke and the complete provider-only Moderato matrix against that binary: buffered/SSE requests, restart identity, payments with no bonds, paid inference with a bonded provider and an unbonded buyer, bond-only inference, missing-provider-proof rejection, delayed exit, early-withdrawal rejection, full principal refund and free inference with both features disabled. + +Mesh passed 4,667 host tests, with 31 ignored, and Clippy with warnings denied. Rustdoc completed with 14 existing private-link warnings. The SDK's additive versioned verifier contract declares the namespace and handler in the plugin manifest. At that tested revision, the operator's evidence grant contained the former `filter_providers` switch. Startup rejects missing, unsupported or conflicting declarations. Mesh owns the only eligibility cache and uses plugin deadlines without a core cap. Expired decisions retain signed records, routing-table responses enforce eligibility, and concurrent misses coalesce. Regression tests prove unrelated plugin stops cause no additional verifier calls, while each verifier's stop invalidates only its own cached and in-flight decisions. Tempo derives validity from finalized chain time plus the exit delay, or the known withdrawal deadline. Admission callbacks perform no bond verification. + +Independent RPC checks confirmed all 10 successful finalized transactions, the exact 1,000,000-atomic-unit provider refund, reconciled balances, zero escrow balance and zero unresolved transactions or active payment obligations. The buyer's bond journal remained empty. The [current trial report](tempo-exit-testnet-trial.md) records both executable hashes and the committed Mesh revision. Completed-trial resume preserved all 105 private state and evidence files. Inference remained canned; mainnet was not exercised. diff --git a/justfile b/justfile new file mode 100644 index 0000000..c225e6b --- /dev/null +++ b/justfile @@ -0,0 +1,51 @@ +set shell := ["bash", "-euo", "pipefail", "-c"] +target := `rustc -vV | sed -n 's/^host: //p'` +version := `sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1` + +default: check + +build: + cargo build --locked --all-features + +release: + cargo build --locked --release --bin tempo + +check: + cargo fmt --all --check + cargo check --locked --all-targets --all-features + cargo clippy --locked --all-targets --all-features -- -D warnings + +test: + cargo test --locked --all-features + +doc: + RUSTDOCFLAGS="-D warnings" cargo doc --locked --all-features --no-deps + +fmt: + cargo fmt --all + +smoke mesh_bin output_dir: + ./target/debug/host-smoke --mesh-bin "{{mesh_bin}}" --output-dir "{{output_dir}}" + +# Explicitly creates testnet wallets, requests faucet coins, and sends Moderato transactions. +testnet-smoke mesh_bin output_dir: + ./target/debug/host-smoke --mesh-bin "{{mesh_bin}}" --output-dir "{{output_dir}}" --tempo-testnet + +package target_triple=target package_version=version: release + bash scripts/package.sh target/release "{{target_triple}}" "{{package_version}}" + python3 scripts/verify-packages.py "{{target_triple}}" "{{package_version}}" + +# Local functional demos can package the already-built debug binaries. +package-debug target_triple=target package_version=version: build + bash scripts/package.sh target/debug "{{target_triple}}" "{{package_version}}" + python3 scripts/verify-packages.py "{{target_triple}}" "{{package_version}}" + +# Tests paid/bond-only inference, delayed exits and refunds against the Moderato escrow, or the one in TEMPO_BOND_ESCROW. +testnet-bonds mesh_bin output_dir: + ./target/debug/host-smoke --mesh-bin "{{mesh_bin}}" --output-dir "{{output_dir}}" --tempo-testnet --tempo-bonds + +contracts-check: + forge fmt --root contracts --check + forge test --root contracts --offline + test "$(forge inspect --root contracts TempoBondEscrow deployedBytecode)" = "$(cat contracts/runtime.hex)" + test "$(forge inspect --root contracts TempoBondEscrow bytecode)" = "$(cat contracts/creation.hex)" diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..6360c18 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.95.0" +components = ["rustfmt", "clippy"] diff --git a/scripts/package.sh b/scripts/package.sh new file mode 100755 index 0000000..5d33df8 --- /dev/null +++ b/scripts/package.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Package only the production plugin. No wallet state, credentials or fixtures. +set -euo pipefail +if [[ $# != 3 ]]; then + echo 'Usage: package.sh BINARY_DIRECTORY TARGET_TRIPLE VERSION' >&2 + exit 2 +fi +binary_directory=$(cd -- "$1" && pwd) +target_triple=$2 +package_version=$3 +[[ "$target_triple" =~ ^[a-zA-Z0-9_-]+$ && "$package_version" =~ ^[a-zA-Z0-9._+-]+$ ]] || exit 2 +workspace_root=$(cd -- "$(dirname -- "$0")/.." && pwd) +host_target=$(rustc -vV | sed -n 's/^host: //p') +if [[ "$target_triple" != "$host_target" ]]; then + echo "Package native binaries on their target platform ($host_target)." >&2 + exit 1 +fi +stage_root=$(mktemp -d) +trap 'rm -rf -- "$stage_root"' EXIT +plugin_name=tempo +actual_version=$("$binary_directory/$plugin_name" --version) +if [[ "$actual_version" != "$plugin_name $package_version" ]]; then + echo "Version mismatch for $plugin_name: expected $package_version, got $actual_version" >&2 + exit 1 +fi +plugin_stage="$stage_root/$plugin_name" +mkdir -- "$plugin_stage" +cp -- "$binary_directory/$plugin_name" "$plugin_stage/$plugin_name" +chmod 755 "$plugin_stage/$plugin_name" +printf 'name = "%s"\nversion = "%s"\n' "$plugin_name" "$package_version" > "$plugin_stage/plugin.toml" +"$plugin_stage/$plugin_name" --manifest > "$plugin_stage/plugin-manifest.json" +cp -- "$workspace_root/README.md" "$plugin_stage/README.md" +cp -- "$workspace_root/LICENSE" "$workspace_root/ORIGIN.md" "$workspace_root/REFERENCE.md" "$plugin_stage/" +mkdir -- "$plugin_stage/docs" "$plugin_stage/demo" "$plugin_stage/contracts" +mkdir -- "$plugin_stage/contracts/src" +cp -- "$workspace_root/contracts/src/TempoBondEscrow.sol" "$plugin_stage/contracts/src/" +cp -- "$workspace_root/contracts/foundry.toml" "$workspace_root/contracts/runtime.hex" "$workspace_root/contracts/creation.hex" "$plugin_stage/contracts/" +cp -- "$workspace_root/docs/"*.md "$plugin_stage/docs/" +cp -- "$workspace_root/docs/tempo-bonds-testnet-trial.json" "$workspace_root/docs/tempo-exit-testnet-trial.json" "$plugin_stage/docs/" +cp -- "$workspace_root/demo/"*.example "$plugin_stage/demo/" +mkdir -p -- "$workspace_root/dist" +archive="$workspace_root/dist/$plugin_name-v$package_version-$target_triple.tar.gz" +COPYFILE_DISABLE=1 tar -C "$stage_root" -czf "$archive" "$plugin_name" +if command -v sha256sum >/dev/null; then + (cd -- "$workspace_root/dist" && sha256sum "$(basename -- "$archive")") > "$archive.sha256" +else + (cd -- "$workspace_root/dist" && shasum -a 256 "$(basename -- "$archive")") > "$archive.sha256" +fi +printf '%s\n' "$archive" diff --git a/scripts/verify-packages.py b/scripts/verify-packages.py new file mode 100644 index 0000000..e8b158b --- /dev/null +++ b/scripts/verify-packages.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Verify and exercise native plugin archives without creating payment wallets.""" + +import argparse +import hashlib +import json +from pathlib import Path +import subprocess +import tarfile +import tempfile +import tomllib + + +def run(*args): + return subprocess.check_output(args, text=True, timeout=30) + + +def verify(dist, target, version): + name = "tempo" + archive = dist / f"{name}-v{version}-{target}.tar.gz" + checksum, filename = archive.with_suffix(".gz.sha256").read_text().split() + with archive.open("rb") as source: + actual = hashlib.file_digest(source, "sha256").hexdigest() + if filename != archive.name or actual != checksum: + raise ValueError(f"Checksum mismatch: {archive.name}") + with tempfile.TemporaryDirectory(prefix="payments-package-") as temporary: + root = Path(temporary) + with tarfile.open(archive) as package: + allowed = {name, "plugin.toml", "plugin-manifest.json", "README.md", "LICENSE", "ORIGIN.md", "REFERENCE.md", "docs", "demo", "contracts"} + for member in package.getmembers(): + parts = Path(member.name).parts + if not parts or parts[0] != name or (len(parts) > 1 and parts[1] not in allowed): + raise ValueError(f"Unexpected package content: {member.name}") + package.extractall(root, filter="data") + plugin = root / name + with (plugin / "plugin.toml").open("rb") as source: + metadata = tomllib.load(source) + if metadata != {"name": name, "version": version}: + raise ValueError(f"Invalid package metadata: {name}") + binary = str(plugin / name) + if run(binary, "--version").strip() != f"{name} {version}": + raise ValueError(f"Executable version mismatch: {name}") + manifest = json.loads((plugin / "plugin-manifest.json").read_text()) + if json.loads(run(binary, "--manifest")) != manifest: + raise ValueError(f"Manifest mismatch: {name}") + hook = manifest["openai_exchange_hook"] + if not (hook["required"] and hook["admission"] and hook["effective_request_body"]): + raise ValueError("Payment admission hook is missing") + if manifest.get("operation_bindings"): + raise ValueError("Unexpected external wallet binding") + print(f"Verified {archive.name}") + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("target") + parser.add_argument("version") + parser.add_argument("--dist", type=Path, default=Path(__file__).resolve().parent.parent / "dist") + args = parser.parse_args() + verify(args.dist, args.target, args.version) diff --git a/src/bin/demo-backend-fixture.rs b/src/bin/demo-backend-fixture.rs new file mode 100644 index 0000000..7686e0a --- /dev/null +++ b/src/bin/demo-backend-fixture.rs @@ -0,0 +1,96 @@ +//! Canned OpenAI backend owned by a real Mesh plugin process; never a model benchmark. +use anyhow::{Context, Result, ensure}; +use axum::{ + Json, Router, + body::Body, + http::{Response, StatusCode}, + routing::{get, post}, +}; +use mesh_llm_plugin::{ + PluginMetadata, PluginRuntime, SimplePlugin, openai_http_inference_endpoint, plugin_manifest, + plugin_server_info, +}; +use serde_json::{Value, json}; + +const MODEL: &str = "mesh-payment-fixture"; + +fn manifest(url: &str) -> mesh_llm_plugin::proto::PluginManifest { + plugin_manifest() + .item(openai_http_inference_endpoint("fixture", url).managed_by_plugin(true)) + .build() +} + +#[tokio::main] +async fn main() -> Result<()> { + let url = + std::env::var("MESH_LLM_PLUGIN_URL").unwrap_or_else(|_| "http://127.0.0.1:18080/v1".into()); + if std::env::args().any(|a| a == "--manifest") { + println!( + "{}", + mesh_llm_plugin::package_manifest_json(&manifest(&url))? + ); + return Ok(()); + } + let address = url + .strip_prefix("http://127.0.0.1:") + .and_then(|s| s.strip_suffix("/v1")) + .context("fixture URL must be loopback HTTP with /v1")?; + let port: u16 = address.parse()?; + ensure!(port != 0, "fixture requires an explicit reserved port"); + let listener = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port)).await?; + let router = Router::new() + .route("/health", get(|| async { "offline fixture" })) + .route("/v1/models", get(|| async { Json(json!({"object":"list","data":[{"id":MODEL,"object":"model","owned_by":"offline-fixture"}]})) })) + .route("/v1/chat/completions", post(completion)); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let plugin = SimplePlugin::new( + PluginMetadata::new( + "demo-backend-fixture", + env!("CARGO_PKG_VERSION"), + plugin_server_info( + "demo-backend-fixture", + env!("CARGO_PKG_VERSION"), + "Offline canned backend", + "Returns declared fixture usage; no model weights", + None::, + ), + ) + .with_manifest(manifest(&url)), + ); + let result = PluginRuntime::run(plugin).await; + server.abort(); + result +} + +async fn completion(Json(request): Json) -> Result, StatusCode> { + if request["model"] != MODEL + || request["max_tokens"] + .as_u64() + .is_none_or(|n| n == 0 || n > 16) + { + return Err(StatusCode::BAD_REQUEST); + } + let output = request["max_tokens"].as_u64().unwrap().min(4); + let usage = json!({"prompt_tokens":1,"completion_tokens":output,"total_tokens":output+1}); + let content = "OFFLINE FIXTURE RESPONSE"; + if request["stream"] == true { + let chunk = json!({"id":"fixture","object":"chat.completion.chunk","created":1,"model":MODEL, + "choices":[{"index":0,"delta":{"role":"assistant","content":content},"finish_reason":null}]}); + let finish = json!({"id":"fixture","object":"chat.completion.chunk","created":1,"model":MODEL, + "choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}); + let usage_chunk = json!({"id":"fixture","object":"chat.completion.chunk","created":1,"model":MODEL, + "choices":[],"usage":usage}); + return Response::builder() + .header("content-type", "text/event-stream") + .body(Body::from(format!( + "data: {chunk}\n\ndata: {finish}\n\ndata: {usage_chunk}\n\ndata: [DONE]\n\n" + ))) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR); + } + let response = json!({"id":"fixture","object":"chat.completion","created":1,"model":MODEL, + "choices":[{"index":0,"message":{"role":"assistant","content":content},"finish_reason":"stop"}],"usage":usage}); + Response::builder() + .header("content-type", "application/json") + .body(Body::from(response.to_string())) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) +} diff --git a/src/bin/host-smoke.rs b/src/bin/host-smoke.rs new file mode 100644 index 0000000..d456386 --- /dev/null +++ b/src/bin/host-smoke.rs @@ -0,0 +1,806 @@ +//! Two real Mesh hosts, canned inference, and either offline wallets or faucet-funded Moderato wallets. +use anyhow::{Context, Result, ensure}; +use clap::Parser; +use serde_json::{Value, json}; +use std::{ + fs::OpenOptions, + path::{Path, PathBuf}, + process::{Child, Command, Stdio}, + time::Duration, +}; + +#[path = "host-smoke/bonds.rs"] +mod bonds; + +#[derive(Parser)] +struct Args { + #[arg(long)] + mesh_bin: PathBuf, + /// Fresh owner-only output directory; contains private invitation/config/log files. + #[arg(long)] + output_dir: PathBuf, + /// Create fresh wallets, request faucet coins, and settle real Moderato testnet transactions. + #[arg(long)] + tempo_testnet: bool, + /// Also deploy and test indefinite bonds and delayed exits on Moderato. + #[arg(long, requires = "tempo_testnet")] + tempo_bonds: bool, + /// Resume the bond stages using the existing wallets, escrow and journals. + #[arg(long, requires = "tempo_bonds")] + resume_bonds: bool, +} +const TEMPO_RPC: &str = "https://rpc.moderato.tempo.xyz"; +const TEST_OUSD: &str = "0x20c0000000000000000000006a37da5c996874be"; + +async fn tempo_rpc(client: &reqwest::Client, method: &str, params: Value) -> Result { + let response: Value = client + .post(TEMPO_RPC) + .json(&json!({"jsonrpc":"2.0","id":1,"method":method,"params":params})) + .send() + .await? + .error_for_status()? + .json() + .await?; + ensure!( + response.get("error").is_none(), + "{method} failed: {}", + response["error"] + ); + response + .get("result") + .cloned() + .context("missing testnet RPC result") +} + +async fn prepare_testnet_wallet( + client: &reqwest::Client, + bins: &Path, + directory: &Path, +) -> Result<()> { + ensure!( + tempo_rpc(client, "eth_chainId", json!([])).await? == "0xa5bf", + "faucet trial requires Moderato chain 42431" + ); + private_write( + &directory.join("password"), + &hex::encode(rand::random::<[u8; 32]>()), + )?; + let output = Command::new(bins.join("tempo")) + .arg("--config") + .arg(directory.join("payments.json")) + .args(["wallet", "init"]) + .output()?; + ensure!( + output.status.success(), + "explicit testnet wallet initialization failed" + ); + let profile: Value = serde_json::from_slice(&output.stdout)?; + ensure!( + profile["chain_id"] == 42431 && profile["token"] == TEST_OUSD, + "wallet is not test OUSD on Moderato" + ); + let address = profile["address"] + .as_str() + .context("wallet address missing")?; + let funded = tempo_rpc(client, "tempo_fundAddress", json!([address])).await?; + private_write( + &directory.join("faucet.json"), + &serde_json::to_string_pretty(&funded)?, + )?; + let data = format!("0x70a08231{:0>64}", address.trim_start_matches("0x")); + let deadline = tokio::time::Instant::now() + Duration::from_secs(60); + loop { + let value = tempo_rpc( + client, + "eth_call", + json!([{"to":TEST_OUSD,"data":data},"finalized"]), + ) + .await?; + let balance = u64::from_str_radix( + value + .as_str() + .context("invalid test OUSD balance")? + .trim_start_matches("0x"), + 16, + )?; + if balance >= 10_000 { + break; + } + ensure!( + tokio::time::Instant::now() < deadline, + "faucet test OUSD did not finalize; wallet state preserved" + ); + tokio::time::sleep(Duration::from_secs(1)).await; + } + println!( + "{} wallet faucet-funded on Moderato: {address}", + directory.file_name().unwrap().to_string_lossy() + ); + Ok(()) +} + +struct Running(Child); +impl Drop for Running { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} +#[derive(Clone, Copy)] +struct Ports { + api: u16, + console: u16, +} +impl Ports { + fn new() -> Result { + Ok(Self { + api: port()?, + console: port()?, + }) + } +} +fn trial_client() -> Result { + Ok(reqwest::Client::builder() + .no_proxy() + .pool_max_idle_per_host(0) + .timeout(Duration::from_secs(45)) + .build()?) +} +fn port() -> Result { + Ok( + std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))? + .local_addr()? + .port(), + ) +} +fn private_write(path: &Path, content: &str) -> Result<()> { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + use std::io::Write; + let mut file = options.open(path)?; + file.write_all(content.as_bytes())?; + file.sync_all()?; + Ok(()) +} +fn quote(path: &Path) -> String { + serde_json::to_string(&path.to_string_lossy()).unwrap() +} +fn package_plugins(directory: &Path, bins: &Path, testnet: bool) -> Result> { + let packages = directory.join("packages"); + std::fs::create_dir(&packages)?; + let mut archives = Vec::new(); + for name in ["tempo", "demo-backend-fixture"] { + let stage = packages.join(name); + std::fs::create_dir(&stage)?; + std::fs::copy( + bins.join(if name == "tempo" && !testnet { + "tempo-fixture" + } else { + name + }), + stage.join(name), + )?; + private_write( + &stage.join("plugin.toml"), + &format!( + "name = \"{name}\"\nversion = \"{}\"\n", + env!("CARGO_PKG_VERSION") + ), + )?; + let output = Command::new(stage.join(name)).arg("--manifest").output()?; + ensure!( + output.status.success(), + "manifest generation failed for {name}" + ); + let manifest = String::from_utf8(output.stdout)?; + serde_json::from_str::(&manifest)?; + private_write(&stage.join("plugin-manifest.json"), &manifest)?; + let archive = packages.join(format!("{name}.tar.gz")); + let output = Command::new("tar") + .arg("-C") + .arg(&packages) + .arg("-czf") + .arg(&archive) + .arg(name) + .output()?; + ensure!( + output.status.success(), + "archive creation failed for {name}" + ); + archives.push((name.to_owned(), archive)); + } + Ok(archives) +} +fn install_plugins( + mesh: &Path, + directory: &Path, + archives: &[(String, PathBuf)], + include_backend: bool, +) -> Result<()> { + std::fs::create_dir(directory)?; + let bootstrap = directory.join("install-config.toml"); + private_write(&bootstrap, "version = 1\n")?; + for (name, archive) in archives { + if name == "demo-backend-fixture" && !include_backend { + continue; + } + let output = Command::new(mesh) + .args(["plugins", "install", "--archive"]) + .arg(archive) + .args(["--name", name, "--version", env!("CARGO_PKG_VERSION")]) + .env("MESH_LLM_CONFIG", &bootstrap) + .env("MESH_LLM_PLUGIN_DIR", directory.join("installed-plugins")) + .env("MESH_LLM_NODE_KEY_PATH", directory.join("node.key")) + .env("MESH_LLM_RUNTIME_ROOT", directory.join("runtime")) + .env("MESH_LLM_NO_UPDATE_CHECK", "1") + .stdin(Stdio::null()) + .output()?; + let log = format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + private_write(&directory.join(format!("install-{name}.log")), &log)?; + ensure!( + output.status.success(), + "install {name} failed; inspect the private install log" + ); + } + Ok(()) +} +fn config(directory: &Path, backend: Option, seller: &str, testnet: bool) -> Result<()> { + let seller_mode = backend.is_some(); + let price = json!({"mesh-payment-fixture":{"input_per_million":"1000000","output_per_million":"1000000"}}); + let mut payments = json!({"data_dir":directory.join("payments"),"wallet":{},"admission_deposit":"10", + "prices":if seller_mode {price.clone()} else {json!({})}, + "policy":if seller_mode {json!({"mode":"free_only"})} else {json!({"mode":"automatic","daily_budget":"20000"})}, + "buy_peers":if seller_mode {vec![]} else {vec![seller]},"buy_prices":price, + // The cap covers the trial request's worst case: its body bytes as + // input tokens, its 4 output tokens and the upfront. + "cap":"200","channel_topup":"200"}); + if testnet { + payments["wallet"] = json!({"network":"testnet","rpc_url":TEMPO_RPC, + "password_file":directory.join("password"),"max_payment":"200","max_fee":"10000"}); + } + let mut config = format!( + r#"version = 1 + +[[plugin]] +name = "tempo" +[plugin.settings] +config_path = {} + +[plugin.openai_exchange_grant] +endpoints = ["chat_completions", "completions", "responses"] +phases = ["request_received", "backend_selected", "exchange_finished"] +request_body = true +effective_request_body = true +admission = true +read_identity_bundle = true +deadline_ms = 30000 +max_body_bytes = 65536 +max_queue_bytes = 2097152 +max_in_flight = 32 +failure_policy = "required" +"#, + quote(&directory.join("payments.json")) + ); + if let Some(port) = backend { + config.push_str(&format!( + "\n[[plugin]]\nname = \"demo-backend-fixture\"\nurl = \"http://127.0.0.1:{port}/v1\"\n" + )); + } else { + config.push_str("\n[runtime]\nmode = \"client\"\n"); + } + private_write(&directory.join("config.toml"), &config)?; + save_settings(directory, &payments) +} +fn save_settings(directory: &Path, settings: &Value) -> Result<()> { + let settings_path = directory.join("payments.json"); + if settings_path.exists() { + std::fs::write(settings_path, serde_json::to_vec_pretty(settings)?)?; + } else { + private_write(&settings_path, &serde_json::to_string_pretty(settings)?)?; + } + Ok(()) +} +fn start( + mesh: &Path, + directory: &Path, + ports: Ports, + invitation: Option<&Path>, + testnet: bool, +) -> Result { + let log_path = directory.join("host.log"); + if !log_path.exists() { + private_write(&log_path, "")?; + } + let log = OpenOptions::new().append(true).open(log_path)?; + let mut command = Command::new(mesh); + if !testnet { + // The offline fixture has no chain to bond on, so it runs without + // a verifier and its payment smoke reaches the unbonded seller. + command.env("TEMPO_FIXTURE_NO_VERIFIER", "1"); + } + command + .arg(if invitation.is_some() { + "client" + } else { + "serve" + }) + .args([ + "--log-format", + "json", + "--disable-iroh-relays", + "--bind-ip", + "127.0.0.1", + "--mesh-discovery-mode", + "mdns", + ]) + .arg("--port") + .arg(ports.api.to_string()) + .arg("--console") + .arg(ports.console.to_string()) + .env("MESH_LLM_CONFIG", directory.join("config.toml")) + .env("MESH_LLM_NO_DEFAULT_PLUGINS", "1") + .env("MESH_LLM_DATA_DIR", directory.join("host-data")) + .env("MESH_LLM_PLUGIN_DIR", directory.join("installed-plugins")) + .env("MESH_LLM_RUNTIME_ROOT", directory.join("runtime")) + .env("MESH_LLM_NODE_KEY_PATH", directory.join("node.key")) + .env("MESH_LLM_NO_UPDATE_CHECK", "1") + .env("MESH_LLM_NO_RUNTIME_DOWNLOAD", "1") + .env_remove("MESH_LLM_JOIN") + .env_remove("MESH_LLM_JOIN_FILE") + .env_remove("MESH_LLM_EPHEMERAL_KEY") + .stdin(Stdio::null()) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log)); + if !testnet { + command + .env( + "MESH_LLM_OFFLINE_CHAIN_PATH", + directory + .parent() + .context("missing smoke root")? + .join("OFFLINE-fixture.sqlite3"), + ) + .env( + "MESH_LLM_OFFLINE_ADDRESS", + format!( + "0x{}", + (if invitation.is_some() { "11" } else { "22" }).repeat(20) + ), + ); + } + if let Some(path) = invitation { + command + .args(["--max-vram", "0", "--no-enumerate-host"]) + .arg("--join-file") + .arg(path); + } + Ok(Running(command.spawn().context("start Mesh smoke node")?)) +} +async fn get(client: &reqwest::Client, port: u16, path: &str) -> Result { + Ok(client + .get(format!("http://127.0.0.1:{port}{path}")) + .send() + .await? + .error_for_status()? + .json() + .await?) +} +async fn control(client: &reqwest::Client, port: u16, input: Value) -> Result { + plugin_operation(client, port, "control", input).await +} +async fn plugin_operation( + client: &reqwest::Client, + port: u16, + operation: &str, + input: Value, +) -> Result { + let response = client + .post(format!( + "http://127.0.0.1:{port}/api/plugins/tempo/tools/{operation}" + )) + .json(&input) + .send() + .await?; + let code = response.status(); + let response: Value = response.json().await?; + ensure!(code.is_success(), "{operation} HTTP {code}: {response}"); + ensure!( + response["isError"] != true, + "{operation} returned an error: {response}" + ); + if let Some(data) = response + .get("structuredContent") + .or_else(|| response.get("structured_content")) + { + return Ok(data.clone()); + } + if let Some(text) = response["content"] + .as_array() + .and_then(|xs| xs.first()) + .and_then(|x| x["text"].as_str()) + { + return Ok(serde_json::from_str(text)?); + } + Ok(response) +} +async fn status(client: &reqwest::Client, port: u16) -> Result { + control(client, port, json!({"command":"bond_context"})).await +} +async fn wait(label: &str, child: &mut Running, mut action: F) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let deadline = tokio::time::Instant::now() + Duration::from_secs(90); + loop { + if let Some(exit) = child.0.try_wait()? { + anyhow::bail!( + "Mesh exited ({exit}) while waiting for {label}; inspect private host logs" + ); + } + if let Ok(value) = action().await { + return Ok(value); + } + ensure!( + tokio::time::Instant::now() < deadline, + "timeout waiting for {label}; inspect private host logs" + ); + tokio::time::sleep(Duration::from_millis(200)).await; + } +} +async fn cleared(client: &reqwest::Client, port: u16, child: &mut Running) -> Result { + wait("cleared payment debt", child, || async { + let value = control(client, port, json!({"command":"pending"})).await?; + ensure!( + value["requests"].as_array().is_some_and(Vec::is_empty), + "settlement pending" + ); + Ok(value) + }) + .await +} +async fn buyer_ready( + client: &reqwest::Client, + ports: Ports, + child: &mut Running, +) -> Result { + let state = wait("buyer payment plugin", child, || async { + let state = status(client, ports.console).await?; + ensure!( + control(client, ports.console, json!({"command":"policy"})).await?["mode"] + == "automatic", + "buyer plugin not ready" + ); + ensure!( + state["node_id"] + .as_str() + .is_some_and(|id| id.len() == 64 && id.bytes().all(|b| b.is_ascii_hexdigit())), + "buyer full identity not ready" + ); + Ok(state) + }) + .await?; + wait("remote fixture model", child, || async { + let value = get(client, ports.api, "/v1/models").await?; + ensure!( + value["data"] + .as_array() + .is_some_and(|xs| xs.iter().any(|x| x["id"] == "mesh-payment-fixture")), + "model not advertised" + ); + Ok(value) + }) + .await?; + Ok(state["node_id"] + .as_str() + .context("missing buyer identity")? + .to_owned()) +} +async fn start_seller( + mesh: &Path, + root: &Path, + ports: Ports, + client: &reqwest::Client, + testnet: bool, +) -> Result<(Running, Value)> { + let mut child = start(mesh, &root.join("seller"), ports, None, testnet)?; + let state = wait("seller payment plugin", &mut child, || async { + let state = status(client, ports.console).await?; + ensure!( + state["node_id"] + .as_str() + .is_some_and(|id| id.len() == 64 && id.bytes().all(|b| b.is_ascii_hexdigit())), + "seller full identity not ready" + ); + Ok(state) + }) + .await?; + let host = get(client, ports.console, "/api/status").await?; + let invitation = host["token"].as_str().context("missing invitation")?; + let path = root.join("invite.token"); + if path.exists() { + std::fs::write(path, invitation)?; + } else { + private_write(&path, invitation)?; + } + Ok((child, state)) +} +async fn start_buyer( + mesh: &Path, + root: &Path, + ports: Ports, + client: &reqwest::Client, + testnet: bool, +) -> Result { + let mut child = start( + mesh, + &root.join("buyer"), + ports, + Some(&root.join("invite.token")), + testnet, + )?; + wait("buyer payment plugin", &mut child, || { + status(client, ports.console) + }) + .await?; + Ok(child) +} +async fn execute(args: Args) -> Result<()> { + let mesh = args.mesh_bin.canonicalize()?; + if args.resume_bonds { + return bonds::resume(&mesh, &args.output_dir).await; + } + ensure!(!args.output_dir.exists(), "--output-dir must be fresh"); + std::fs::create_dir_all(&args.output_dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&args.output_dir, std::fs::Permissions::from_mode(0o700))?; + } + let directory = args.output_dir.canonicalize()?; + let bins = std::env::current_exe()? + .parent() + .context("binary directory missing")? + .to_path_buf(); + for binary in [ + if args.tempo_testnet { + "tempo" + } else { + "tempo-fixture" + }, + "demo-backend-fixture", + ] { + ensure!( + bins.join(binary).is_file(), + "build missing companion binary {binary}" + ); + } + let chain = directory.join("OFFLINE-fixture.sqlite3"); + let seller_dir = directory.join("seller"); + let buyer_dir = directory.join("buyer"); + let seller_ports = Ports::new()?; + let buyer_ports = Ports::new()?; + let archives = package_plugins(&directory, &bins, args.tempo_testnet)?; + install_plugins(&mesh, &seller_dir, &archives, true)?; + install_plugins(&mesh, &buyer_dir, &archives, false)?; + config(&seller_dir, Some(port()?), "", args.tempo_testnet)?; + let client = trial_client()?; + if args.tempo_testnet { + prepare_testnet_wallet(&client, &bins, &seller_dir).await?; + } + let (mut seller, payment_status) = + start_seller(&mesh, &directory, seller_ports, &client, args.tempo_testnet).await?; + let seller_id = payment_status["node_id"] + .as_str() + .context("payment plugin status missing full node identity")?; + let public_wallet = client + .post(format!( + "http://127.0.0.1:{}/api/plugins/tempo/tools/wallet_pay", + seller_ports.console + )) + .json(&json!({})) + .send() + .await?; + ensure!( + public_wallet.status().as_u16() == 404, + "wallet spending operation was exposed as a public tool" + ); + config(&buyer_dir, None, seller_id, args.tempo_testnet)?; + if args.tempo_testnet { + prepare_testnet_wallet(&client, &bins, &buyer_dir).await?; + } + // A buyer requiring a bond never selects, let alone pays, an unbonded + // seller, so the bond trial starts the buyer itself. + if args.tempo_bonds { + return bonds::Trial { + mesh: &mesh, + root: &directory, + client: &client, + seller_ports, + buyer_ports, + seller: Some(seller), + buyer: None, + } + .execute() + .await; + } + let mut buyer = + start_buyer(&mesh, &directory, buyer_ports, &client, args.tempo_testnet).await?; + let buyer_id = buyer_ready(&client, buyer_ports, &mut buyer).await?; + let before = if args.tempo_testnet { + json!({"buyer":control(&client,buyer_ports.console,json!({"command":"balance"})).await?, + "seller":control(&client,seller_ports.console,json!({"command":"balance"})).await?}) + } else { + Value::Null + }; + for number in 0..2 { + let streaming = number == 1; + let mut request = json!({"model":"mesh-payment-fixture","messages":[{"role":"user","content":"test"}],"max_tokens":4,"stream":streaming}); + if streaming { + request["stream_options"] = json!({"include_usage":true}); + } + let response = client + .post(format!( + "http://127.0.0.1:{}/v1/chat/completions", + buyer_ports.api + )) + .json(&request) + .send() + .await?; + let code = response.status(); + let text = response.text().await?; + if !code.is_success() { + private_write(&directory.join("inference-error.json"), &text)?; + } + ensure!( + code.is_success(), + "fixture inference rejected (HTTP {code}); inspect private logs" + ); + let usage = if streaming { + ensure!( + text.contains("[DONE]") && text.contains("OFFLINE FIXTURE RESPONSE"), + "incomplete fixture SSE stream" + ); + text.lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter_map(|data| serde_json::from_str::(data).ok()) + .find_map(|chunk| chunk.get("usage").filter(|u| u.is_object()).cloned()) + .context("stream omitted terminal usage")? + } else { + let body: Value = serde_json::from_str(&text)?; + body["usage"].clone() + }; + ensure!( + usage["prompt_tokens"] == 1 && usage["completion_tokens"] == 4, + "wrong fixture usage" + ); + cleared(&client, buyer_ports.console, &mut buyer).await?; + cleared(&client, seller_ports.console, &mut seller).await?; + if number == 0 { + drop(buyer); + buyer = + start_buyer(&mesh, &directory, buyer_ports, &client, args.tempo_testnet).await?; + let restarted_id = buyer_ready(&client, buyer_ports, &mut buyer).await?; + ensure!( + restarted_id == buyer_id, + "buyer payment identity changed across restart" + ); + } + } + if args.tempo_testnet { + testnet_result(&client, buyer_ports, seller_ports, before, &directory).await + } else { + let connection = rusqlite::Connection::open(&chain)?; + mpp_result(&connection, &directory) + } +} +#[tokio::main] +async fn main() -> Result<()> { + execute(Args::parse()).await +} + +fn mpp_result(connection: &rusqlite::Connection, directory: &Path) -> Result<()> { + let mut query = + connection.prepare("SELECT deposit,closure FROM fixture_channels ORDER BY id")?; + let rows = query + .query_map([], |r| { + Ok((r.get::<_, u64>(0)?, r.get::<_, Option>(1)?)) + })? + .collect::, _>>()?; + ensure!( + rows == [(200, None)], + "expected one open channel reused by both inference requests" + ); + private_write( + &directory.join("result.json"), + &serde_json::to_string_pretty(&json!({ + "offline":true,"real_mesh_hosts":2,"inference_requests":2,"buffered_requests":1,"streaming_requests":1, + "fabricated_channels":1,"channel_deposit_atomic":200,"upfront_atomic":10,"cost_per_request_atomic":5, + "buyer_restart_identity_preserved":true,"wallet_spending_not_http_exposed":true,"network_transactions_sent":0 + }))?, + )?; + Ok(()) +} + +async fn testnet_result( + client: &reqwest::Client, + buyer: Ports, + seller: Ports, + before: Value, + directory: &Path, +) -> Result<()> { + let buyer_history = control( + client, + buyer.console, + json!({"command":"transactions","limit":20}), + ) + .await?; + let seller_history = control( + client, + seller.console, + json!({"command":"transactions","limit":20}), + ) + .await?; + let rows = buyer_history["requests"] + .as_array() + .context("missing buyer history")?; + let seller_rows = seller_history["requests"] + .as_array() + .context("missing seller history")?; + ensure!( + rows.len() == 2 && seller_rows.len() == 2, + "expected two paid native requests per peer" + ); + for row in rows { + ensure!(row["bill"]["cost"] == "5", "wrong native bill"); + ensure!( + seller_rows.iter().any(|seller| seller["id"] == row["id"] + && seller["bill"] == row["bill"] + && seller["channel"] == row["channel"]), + "buyer and seller disagree on the bill" + ); + } + let pending = control(client, buyer.console, json!({"command":"pending"})).await?; + let channels = pending["channels"].clone(); + let channel = &channels[0]; + ensure!( + channels.as_array().is_some_and(|c| c.len() == 1) + && channel["running_total"] == "10" + && channel["voucher"]["cum"] == "10", + "expected one channel with both bills paid" + ); + let receipt = tempo_rpc( + client, + "eth_getTransactionReceipt", + json!([channel["funding"]["open_tx"]]), + ) + .await?; + ensure!( + receipt["status"] == "0x1", + "native transaction did not succeed" + ); + let after = json!({"buyer":control(client,buyer.console,json!({"command":"balance"})).await?, + "seller":control(client,seller.console,json!({"command":"balance"})).await?}); + let result = json!({"offline":false,"chain_id":42431,"asset":TEST_OUSD,"real_mesh_hosts":2, + "canned_inference":true,"inference_requests":2,"buffered_requests":1,"streaming_requests":1, + "buyer_restart_identity_preserved":true,"wallet_spending_not_http_exposed":true, + "channel_deposit_atomic":100,"upfront_atomic":10,"cost_per_request_atomic":5, + "before":before,"after":after,"channel":channel,"open_receipt":receipt,"requests":rows}); + private_write( + &directory.join("result.json"), + &serde_json::to_string_pretty(&result)?, + )?; + println!( + "Two Moderato requests were paid from one channel: an upfront of 10 test OUSD atomic units covered both bills of 5." + ); + Ok(()) +} diff --git a/src/bin/host-smoke/bonds.rs b/src/bin/host-smoke/bonds.rs new file mode 100644 index 0000000..90ba511 --- /dev/null +++ b/src/bin/host-smoke/bonds.rs @@ -0,0 +1,712 @@ +//! Explicit Moderato trial using real wallets, escrow, gossip, and inference hooks. +use super::*; +use alloy::primitives::{B256, U256, keccak256}; + +pub(super) struct Trial<'a> { + pub mesh: &'a Path, + pub root: &'a Path, + pub client: &'a reqwest::Client, + pub seller_ports: Ports, + pub buyer_ports: Ports, + pub seller: Option, + pub buyer: Option, +} +impl Trial<'_> { + fn directory(&self, seller: bool) -> PathBuf { + self.root.join(if seller { "seller" } else { "buyer" }) + } + fn settings(&self, seller: bool) -> Result { + Ok(serde_json::from_slice(&std::fs::read( + self.directory(seller).join("payments.json"), + )?)?) + } + fn save(&self, seller: bool, value: &Value) -> Result<()> { + save_settings(&self.directory(seller), value) + } + async fn restart(&mut self) -> Result<()> { + drop(self.buyer.take()); + drop(self.seller.take()); + let (seller, _) = + start_seller(self.mesh, self.root, self.seller_ports, self.client, true).await?; + self.seller = Some(seller); + self.buyer = + Some(start_buyer(self.mesh, self.root, self.buyer_ports, self.client, true).await?); + Ok(()) + } + fn configure(&self, seller: bool, contract: &str) -> Result<()> { + let mut config = self.settings(seller)?; + config["bonds"] = json!({"contract":contract,"max_lock":if seller {"1000000"} else {"0"},"max_exit_delay_seconds":if seller {600} else {0}, + "verification_retry_seconds":1,"providers":{"minimum_amount":"1000000","minimum_exit_delay_seconds":30}}); + self.save(seller, &config) + } + async fn operation(&self, port: u16, input: Value) -> Result { + let deadline = tokio::time::Instant::now() + Duration::from_secs(90); + loop { + let result = control(self.client, port, input.clone()).await?; + match result["status"].as_str() { + Some("finalized") => return Ok(result), + Some("pending") => {} + _ => anyhow::bail!("bond operation did not succeed: {result}"), + } + ensure!( + tokio::time::Instant::now() < deadline, + "bond operation is still pending; journal preserved" + ); + tokio::time::sleep(Duration::from_secs(1)).await; + } + } + async fn state(&self, contract: &str, bond: &str) -> Result { + let selector = keccak256("getBond(bytes32)"); + let data = format!( + "0x{}{}", + hex::encode(&selector[..4]), + bond.trim_start_matches("0x") + ); + let response = tempo_rpc( + self.client, + "eth_call", + json!([{"to":contract,"data":data},"finalized"]), + ) + .await?; + let bytes = hex::decode( + response + .as_str() + .context("invalid bond state")? + .trim_start_matches("0x"), + )?; + ensure!(bytes.len() == 224, "unexpected bond ABI"); + let word = |n: usize| U256::from_be_slice(&bytes[n * 32..(n + 1) * 32]); + Ok( + json!({"mesh":format!("0x{}",hex::encode(&bytes[..32])),"host":hex::encode(&bytes[32..64]), + "refund_wallet":format!("0x{}",hex::encode(&bytes[76..96])),"amount":word(3).to_string(),"exit_delay_seconds":u64::try_from(word(4))?,"withdraw_at":word(5).to_string(),"withdrawn":word(6)!=U256::ZERO}), + ) + } + /// Sends one request; the buyer pays when the seller prices the model. + async fn inference(&mut self) -> Result { + buyer_ready(self.client, self.buyer_ports, self.buyer.as_mut().unwrap()).await?; + let request = json!({"model":"mesh-payment-fixture","messages":[{"role":"user","content":"bond trial"}],"max_tokens":4}); + let deadline = tokio::time::Instant::now() + Duration::from_secs(45); + loop { + let response = self + .client + .post(format!( + "http://127.0.0.1:{}/v1/chat/completions", + self.buyer_ports.api + )) + .json(&request) + .send() + .await?; + let status = response.status(); + let body: Value = response.json().await?; + if status.is_success() { + ensure!( + body["usage"]["completion_tokens"] == 4, + "unexpected inference usage" + ); + return Ok(json!({"status":status.as_u16(),"usage":body["usage"]})); + } + ensure!( + tokio::time::Instant::now() < deadline, + "unexpected inference admission status {status}: {body}" + ); + tokio::time::sleep(Duration::from_secs(1)).await; + } + } + async fn verification(&mut self, evidence: Value) -> Result { + let port = self.seller_ports.console; + let context = wait( + "provider mesh identity", + self.seller.as_mut().unwrap(), + || async { + let context = control(self.client, port, json!({"command":"bond_context"})).await?; + ensure!( + context["mesh_id"] + .as_str() + .is_some_and(|mesh| !mesh.is_empty()), + "mesh identity not established" + ); + Ok(context) + }, + ) + .await?; + let client = self.client; + let buyer_port = self.buyer_ports.console; + wait("bond verification", self.buyer.as_mut().unwrap(), || async { + let verdict = plugin_operation( + client, + buyer_port, + "verify_peer_evidence", + json!({"mesh_id":context["mesh_id"],"node_id":context["node_id"],"evidence":evidence}), + ).await?; + ensure!(verdict["reason"] != "bond verifier is busy", "bond verifier is busy"); + Ok(verdict) + }).await + } + async fn provider_unavailable(&mut self) -> Result { + let client = self.client; + let seller_ports = self.seller_ports; + let buyer_ports = self.buyer_ports; + let result = wait( + "connected provider unavailability", + self.buyer.as_mut().unwrap(), + || async { + let seller = status(client, seller_ports.console).await?; + let buyer = status(client, buyer_ports.console).await?; + for (port, expected) in [ + (seller_ports.console, &buyer["node_id"]), + (buyer_ports.console, &seller["node_id"]), + ] { + let host = get(client, port, "/api/status").await?; + let peer = host["peers"] + .as_array() + .context("peer list missing")? + .iter() + .find(|peer| peer["node_id"] == *expected && peer["connected"] == true) + .context("trial peer is not connected")?; + if port == buyer_ports.console { + ensure!( + ["models", "serving_models", "hosted_models"] + .iter() + .any(|field| { + peer[*field].as_array().is_some_and(|models| { + models.iter().any(|id| id == "mesh-payment-fixture") + }) + }), + "buyer has not received the provider advertisement" + ); + } + } + let seller_models = get(client, seller_ports.api, "/v1/models").await?; + ensure!( + seller_models["data"] + .as_array() + .context("seller models missing")? + .iter() + .any(|model| model["id"] == "mesh-payment-fixture"), + "seller fixture is not ready" + ); + let models = get(client, buyer_ports.api, "/v1/models").await?; + ensure!( + !models["data"] + .as_array() + .context("buyer models missing")? + .iter() + .any(|model| model["id"] == "mesh-payment-fixture"), + "provider is still selectable" + ); + // Catalog absence does not distinguish pending from rejected verdicts. + Ok(json!({"connected":true,"provider_advertised":true,"buyer_models":models,"mesh_verdict":"pending_or_rejected"})) + }, + ) + .await?; + ensure!( + self.seller.as_mut().unwrap().0.try_wait()?.is_none(), + "seller exited during catalog check" + ); + Ok(result) + } + fn policies(&self, priced: bool) -> Result<()> { + for seller in [true, false] { + let mut config = self.settings(seller)?; + // Startup writes config prices into the ledger without removing + // others, so an unpriced trial stores a free price. + let rate = if seller && priced { "1000000" } else { "0" }; + config["prices"] = json!({"mesh-payment-fixture":{"input_per_million":rate,"output_per_million":rate}}); + config["bonds"]["providers"] = + json!({"minimum_amount":"1000000","minimum_exit_delay_seconds":30}); + self.save(seller, &config)?; + } + Ok(()) + } + pub async fn execute(mut self) -> Result<()> { + if self.root.join("bond-result.json").exists() { + println!("Bond trial already completed; existing evidence preserved"); + return Ok(()); + } + let checkpoint_path = self.root.join("bond-release-checkpoint.json"); + if checkpoint_path.exists() { + let checkpoint: Value = serde_json::from_slice(&std::fs::read(&checkpoint_path)?)?; + return self.release(checkpoint).await; + } + let contract = self.escrow()?; + let bond = self.lock_bond(&contract).await?; + let checkpoint = self.check_admission(&contract, bond).await?; + saved_operation(&checkpoint_path, || checkpoint.clone())?; + self.release(checkpoint).await + } + /// The network's shared escrow is deployed once, outside the plugin; + /// `TEMPO_BOND_ESCROW` overrides the plugin's Moderato default. + fn escrow(&self) -> Result { + let path = self.root.join("bond-deployment.json"); + if !path.exists() { + let contract = std::env::var("TEMPO_BOND_ESCROW") + .ok() + .filter(|contract| !contract.is_empty()) + .unwrap_or_else(|| "0xd210B0356b3e45B37F29Ec763106dc23BF1cC3aa".into()); + saved_operation(&path, || json!({ "contract": contract }))?; + } + let deployment: Value = serde_json::from_slice(&std::fs::read(&path)?)?; + let contract = deployment["contract"] + .as_str() + .context("escrow record omitted its address")?; + println!("Using the bond escrow at {contract}"); + Ok(contract.to_string()) + } + async fn lock_bond(&mut self, contract: &str) -> Result { + for seller in [true, false] { + self.configure(seller, contract)?; + } + self.policies(true)?; + // Both nodes run while the provider bonds, so the buyer's view is + // observed before and after publication without a restart. + self.restart().await?; + let port = self.seller_ports.console; + let context = wait( + "provider mesh identity", + self.seller.as_mut().unwrap(), + || async { + let context = control(self.client, port, json!({"command":"bond_context"})).await?; + ensure!( + context["mesh_id"].is_string(), + "mesh identity not established" + ); + Ok(context) + }, + ) + .await?; + let existing = context["reference"]["bond_id"].clone(); + let unbonded = if existing.is_string() { + Value::Null + } else { + println!("Checking the buyer cannot select the provider before its bond"); + self.provider_unavailable().await? + }; + let result = if existing.is_string() { + json!({"bond_id":existing,"status":"existing"}) + } else { + let path = self.directory(true).join("bond-lock-input.json"); + let attempts = control( + self.client, + port, + json!({"command":"transactions","limit":100}), + ) + .await?; + if !path.exists() { + ensure!( + !attempts["attempts"] + .as_array() + .context("attempt list missing")? + .iter() + .any(|a| a["intent"]["kind"] == "lock"), + "existing bond lock has no saved input; inspect attempts and publish it with bond_publish before resuming" + ); + } + let input = saved_operation(&path, || { + json!({"command":"bond_lock","operation_id":uuid::Uuid::new_v4().to_string(), + "mesh_id":context["mesh_id"], + "amount":"1000000","exit_delay_seconds":30,"salt":B256::from(rand::random::<[u8;32]>()).to_string()}) + })?; + self.operation(port, input).await? + }; + let id = result["bond_id"] + .as_str() + .context("bond ID missing")? + .to_string(); + let initial = self.state(contract, &id).await?; + ensure!( + initial["withdrawn"] == false, + "existing bond was already refunded; use a fresh trial directory" + ); + // The plugin publishes the finalized lock; the running buyer then + // selects the provider and pays it, with neither node restarted. + println!("Checking the buyer selects the provider once its bond is published"); + buyer_ready(self.client, self.buyer_ports, self.buyer.as_mut().unwrap()).await?; + Ok(json!({"id":id,"initial":initial,"operation":result,"unbonded":unbonded})) + } + async fn check_admission(&mut self, contract: &str, mut bond: Value) -> Result { + println!("Testing paid inference with the provider bonded and the buyer unbonded"); + let paid = self.inference().await?; + cleared( + self.client, + self.buyer_ports.console, + self.buyer.as_mut().unwrap(), + ) + .await?; + cleared( + self.client, + self.seller_ports.console, + self.seller.as_mut().unwrap(), + ) + .await?; + println!("Checking the provider bond remains active across restart without renewal"); + self.restart().await?; + bond["active"] = self.state(contract, bond["id"].as_str().unwrap()).await?; + ensure!( + bond["active"]["withdraw_at"] == "0" + && bond["active"]["amount"] == bond["initial"]["amount"], + "active bond changed without an exit request" + ); + self.policies(false)?; + self.restart().await?; + println!("Testing free inference with a bonded provider"); + let free_bonded = self.inference().await?; + let id = bond["id"].clone(); + let port = self.seller_ports.console; + control(self.client, port, json!({"command":"bond_publish"})).await?; + self.restart().await?; + println!("Checking rejection of a provider with no published bond"); + let rejected = self.verification(Value::Null).await?; + ensure!( + rejected["accepted"] == false + && rejected["reason"] + .as_str() + .is_some_and(|reason| reason.contains("no bond")), + "missing proof was not rejected: {rejected}" + ); + let unbonded_catalog = self.provider_unavailable().await?; + let republish = json!({"command":"bond_publish","bond_id":id}); + control(self.client, self.seller_ports.console, republish).await?; + self.restart().await?; + self.inference().await?; + println!("Checking the provider stays funded beyond its exit delay without renewal"); + let finalized = tempo_rpc( + self.client, + "eth_getBlockByNumber", + json!(["finalized", false]), + ) + .await?; + let timestamp = |block: &Value| -> Result { + Ok(U256::from_str_radix( + block["timestamp"] + .as_str() + .context("finalized timestamp missing")? + .trim_start_matches("0x"), + 16, + )?) + }; + let target = timestamp(&finalized)? + U256::from(31); + let deadline = tokio::time::Instant::now() + Duration::from_secs(90); + loop { + let block = tempo_rpc( + self.client, + "eth_getBlockByNumber", + json!(["finalized", false]), + ) + .await?; + if timestamp(&block)? >= target { + break; + } + ensure!( + tokio::time::Instant::now() < deadline, + "finalized chain time did not advance" + ); + tokio::time::sleep(Duration::from_secs(2)).await; + } + bond["active"] = self.state(contract, bond["id"].as_str().unwrap()).await?; + ensure!( + bond["active"]["withdraw_at"] == "0" && bond["active"]["withdrawn"] == false, + "provider lock expired without an exit request" + ); + Ok( + json!({"escrow":contract,"bond":bond,"paid_bonded_provider":paid,"free_bonded_provider":free_bonded,"unbonded_provider":{"verification":rejected,"catalog":unbonded_catalog}}), + ) + } + async fn release(mut self, checkpoint: Value) -> Result<()> { + let contract = checkpoint["escrow"] + .as_str() + .context("checkpoint escrow missing")? + .to_string(); + let mut bond = checkpoint["bond"].clone(); + ensure!( + bond.is_object(), + "checkpoint must contain the provider bond" + ); + self.policies(false)?; + self.restart().await?; + println!("Requesting bond exits, then refunding full principals after the delay"); + self.request_exit(&contract, &mut bond).await?; + self.refund_bond(&contract, &mut bond).await?; + self.restart().await?; + let verification = self + .verification(json!({"chain_id":42431,"contract":contract,"bond_id":bond["id"]})) + .await?; + ensure!( + verification["accepted"] == false + && verification["reason"] + .as_str() + .is_some_and(|reason| reason.contains("withdrawn")), + "withdrawn seller was not rejected by bond verification: {verification}" + ); + let withdrawn = + json!({"verification":verification,"catalog":self.provider_unavailable().await?}); + let result = json!({"network":"Moderato","chain_id":42431,"escrow":contract,"bond":bond, + "paid_bonded_provider":checkpoint["paid_bonded_provider"],"free_bonded_provider":checkpoint["free_bonded_provider"],"unbonded_provider":checkpoint["unbonded_provider"],"withdrawn_provider":withdrawn}); + private_write( + &self.root.join("bond-result.json"), + &serde_json::to_string_pretty(&result)?, + )?; + println!("Moderato bond trial passed; evidence saved in bond-result.json"); + Ok(()) + } + /// The seller's withdrawal of `id`, which its plugin signs once the exit + /// delay has passed. + async fn swept(&self, port: u16, id: &str) -> Result { + let deadline = tokio::time::Instant::now() + Duration::from_secs(120); + loop { + let listing = control( + self.client, + port, + json!({"command":"transactions","limit":20}), + ) + .await?; + let refund = listing["attempts"] + .as_array() + .into_iter() + .flatten() + .find(|a| { + a["intent"]["kind"] == "withdraw" + && a["status"] == "finalized" + && a["bond_id"] + .as_str() + .is_some_and(|b| b.eq_ignore_ascii_case(id)) + }); + if let Some(refund) = refund { + return Ok(refund.clone()); + } + ensure!( + tokio::time::Instant::now() < deadline, + "the plugin did not withdraw the exited bond" + ); + tokio::time::sleep(Duration::from_secs(2)).await; + } + } + async fn request_exit(&mut self, contract: &str, bond: &mut Value) -> Result<()> { + let port = self.seller_ports.console; + let input = saved_operation( + &self.directory(true).join("bond-exit-input.json"), + || json!({"command":"bond_exit","operation_id":uuid::Uuid::new_v4().to_string(),"bond_id":bond["id"]}), + )?; + bond["exit"] = self.operation(port, input).await?; + let id = bond["id"].as_str().context("bond ID missing")?; + let exiting = self.state(contract, id).await?; + let finalized = tempo_rpc( + self.client, + "eth_getBlockByNumber", + json!(["finalized", false]), + ) + .await?; + let timestamp = U256::from_str_radix( + finalized["timestamp"] + .as_str() + .context("finalized timestamp missing")? + .trim_start_matches("0x"), + 16, + )?; + let deadline = U256::from_str_radix( + exiting["withdraw_at"] + .as_str() + .context("exit deadline missing")?, + 10, + )?; + let check_path = self.directory(true).join("bond-exit-check.json"); + if check_path.exists() { + let checks: Value = serde_json::from_slice(&std::fs::read(check_path)?)?; + for key in ["exiting", "exit_verification", "early_withdraw_rejected"] { + bond[key] = checks[key].clone(); + } + return Ok(()); + } + if deadline <= timestamp { + // A resumed trial still refunds funds if this observation window passed. + bond["exit_check_skipped"] = json!("resumed after exit delay elapsed"); + return Ok(()); + } + ensure!( + exiting["withdrawn"] == false + && exiting["amount"] == bond["initial"]["amount"] + && deadline > timestamp, + "exit did not retain the principal throughout its delay" + ); + let verification = self + .verification(json!({"chain_id":42431,"contract":contract,"bond_id":id})) + .await?; + ensure!( + verification["accepted"] == true + && verification["valid_until"] + .as_u64() + .is_some_and(|until| U256::from(until) <= deadline), + "exiting bond must qualify only while its principal is locked: {verification}" + ); + let selector = keccak256("withdraw(bytes32)"); + let response: Value = self.client.post(TEMPO_RPC).json(&json!({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{ + "from":exiting["refund_wallet"],"to":contract,"data":format!("0x{}{}",hex::encode(&selector[..4]),id.trim_start_matches("0x")) + },finalized["number"]]})).send().await?.error_for_status()?.json().await?; + ensure!( + response["error"]["message"] + .as_str() + .is_some_and(|reason| reason.contains("bond still locked or withdrawn")), + "early withdrawal did not revert for the exit delay: {response}" + ); + bond["exiting"] = exiting; + bond["exit_verification"] = verification; + bond["early_withdraw_rejected"] = json!(true); + saved_operation(&check_path, || { + json!({ + "exiting":bond["exiting"],"exit_verification":bond["exit_verification"], + "early_withdraw_rejected":true + }) + })?; + Ok(()) + } + async fn refund_bond(&mut self, contract: &str, bond: &mut Value) -> Result<()> { + let id = bond["id"].as_str().unwrap().to_string(); + loop { + let state = self.state(contract, &id).await?; + let deadline = U256::from_str_radix( + state["withdraw_at"] + .as_str() + .context("exit deadline missing")?, + 10, + )?; + let finalized = tempo_rpc( + self.client, + "eth_getBlockByNumber", + json!(["finalized", false]), + ) + .await?; + let timestamp = U256::from_str_radix( + finalized["timestamp"] + .as_str() + .context("finalized timestamp missing")? + .trim_start_matches("0x"), + 16, + )?; + if deadline != U256::ZERO && timestamp >= deadline { + break; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + let port = self.seller_ports.console; + let check_path = self.directory(true).join("bond-withdrawable-check.json"); + let verification = if check_path.exists() { + serde_json::from_slice(&std::fs::read(&check_path)?)? + } else { + let verification = self + .verification(json!({"chain_id":42431,"contract":contract,"bond_id":id})) + .await?; + ensure!( + verification["accepted"] == false + && verification["reason"] + .as_str() + .is_some_and(|reason| reason.contains("withdrawable") + || reason.contains("withdrawn")), + "withdrawable bond remained eligible: {verification}" + ); + saved_operation(&check_path, || verification)? + }; + bond["withdrawable_verification"] = verification; + bond["refund"] = self.swept(port, &id).await?; + ensure!( + self.state(contract, &id).await?["withdrawn"] == true, + "refund did not consume bond" + ); + let hash = bond["refund"]["hash"] + .as_str() + .context("refund transaction hash missing")?; + let receipt = tempo_rpc(self.client, "eth_getTransactionReceipt", json!([hash])).await?; + let expected = U256::from_str_radix(bond["initial"]["amount"].as_str().unwrap(), 10)?; + let wallet = self.state(contract, &id).await?["refund_wallet"] + .as_str() + .unwrap() + .to_string(); + let transfer = receipt["logs"] + .as_array() + .context("refund logs missing")? + .iter() + .any(|log| { + log["address"] + .as_str() + .is_some_and(|address| address.eq_ignore_ascii_case(TEST_OUSD)) + && log["topics"][0] + == keccak256("Transfer(address,address,uint256)").to_string() + && log["topics"][1].as_str().is_some_and(|from| { + from.eq_ignore_ascii_case(&format!( + "0x{:0>64}", + contract.trim_start_matches("0x") + )) + }) + && log["topics"][2].as_str().is_some_and(|to| { + to.eq_ignore_ascii_case(&format!( + "0x{:0>64}", + wallet.trim_start_matches("0x") + )) + }) + && log["data"].as_str().and_then(|data| { + U256::from_str_radix(data.trim_start_matches("0x"), 16).ok() + }) == Some(expected) + }); + ensure!( + transfer, + "refund receipt lacks the exact principal transfer to the original wallet" + ); + bond["refund_principal_verified"] = json!(true); + Ok(()) + } +} +fn saved_operation(path: &Path, create: impl FnOnce() -> Value) -> Result { + if path.exists() { + return Ok(serde_json::from_slice(&std::fs::read(path)?)?); + } + let input = create(); + private_write(path, &serde_json::to_string_pretty(&input)?)?; + #[cfg(unix)] + std::fs::File::open(path.parent().context("operation directory missing")?)?.sync_all()?; + Ok(input) +} + +pub(super) async fn resume(mesh: &Path, root: &Path) -> Result<()> { + let root = root.canonicalize()?; + if root.join("bond-result.json").exists() { + println!("Bond trial already completed; existing evidence preserved"); + return Ok(()); + } + ensure!( + root.join("bond-deployment.json").exists(), + "resume requires an existing escrow record" + ); + let client = trial_client()?; + let seller_ports = Ports::new()?; + let buyer_ports = Ports::new()?; + let (seller, _) = start_seller(mesh, &root, seller_ports, &client, true).await?; + let buyer = start_buyer(mesh, &root, buyer_ports, &client, true).await?; + Trial { + mesh, + root: &root, + client: &client, + seller_ports, + buyer_ports, + seller: Some(seller), + buyer: Some(buyer), + } + .execute() + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resumed_operations_keep_the_exact_original_inputs() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("lock.json"); + let input = json!({"command":"bond_lock","operation_id":uuid::Uuid::from_u128(42).to_string(),"exit_delay_seconds":123,"salt":B256::repeat_byte(3).to_string()}); + assert_eq!(saved_operation(&path, || input.clone()).unwrap(), input); + assert_eq!( + saved_operation(&path, || panic!("must not generate new transaction inputs")).unwrap(), + input + ); + std::fs::write(&path, "{").unwrap(); + assert!(saved_operation(&path, || panic!("must not replace damaged input")).is_err()); + } +} diff --git a/src/bin/tempo-fixture.rs b/src/bin/tempo-fixture.rs new file mode 100644 index 0000000..f359a39 --- /dev/null +++ b/src/bin/tempo-fixture.rs @@ -0,0 +1,11 @@ +#[tokio::main] +async fn main() -> anyhow::Result<()> { + if std::env::args().any(|arg| arg == "--manifest") { + println!( + "{}", + mesh_llm_plugin::package_manifest_json(&mesh_llm_tempo::runtime::fixture_manifest())? + ); + return Ok(()); + } + mesh_llm_tempo::runtime::run_fixture().await +} diff --git a/src/bonds.rs b/src/bonds.rs new file mode 100644 index 0000000..88a8d8d --- /dev/null +++ b/src/bonds.rs @@ -0,0 +1,485 @@ +//! Refundable Tempo bonds and finalized-state verification. +use crate::{ + config::now, + contract::decimal, + tempo::{ + receipt, + rpc::{Rpc, address, quantity}, + }, +}; +use alloy::{ + primitives::{Address, B256, U256, keccak256}, + sol, + sol_types::{SolCall, SolValue}, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::time::Duration; + +pub const NAMESPACE: &str = "tempo.bond.v1"; +pub const MAX_STATE_AGE: u64 = 120; +pub const MAX_EXIT_DELAY_SECONDS: u64 = u32::MAX as u64; +/// The default bond, 1 OUSD with the network's exit delay: what a seller +/// locks and a buyer with a known escrow requires unless configured otherwise. +pub const DEFAULT_AMOUNT: u64 = 1_000_000; +/// The default bond's exit delay on mainnet, and the longest exit delay a +/// seller authorizes unless configured otherwise. +pub const DEFAULT_EXIT_DELAY_SECONDS: u64 = 86_400; +/// The default bond's exit delay on testnet, short so a trial bond comes +/// back within minutes. +pub const TESTNET_EXIT_DELAY_SECONDS: u64 = 60; + +sol! { + interface Escrow { + struct Bond { + bytes32 meshId; + bytes32 hostKey; + address refundWallet; + uint96 amount; + uint64 exitDelay; + uint256 withdrawAt; + bool withdrawn; + } + function getBond(bytes32 id) external view returns (Bond memory); + function token() external view returns (address); + function lock(bytes32 meshId, bytes32 hostKey, uint96 amount, uint64 exitDelay, bytes32 salt) external returns (bytes32); + function withdraw(bytes32 id) external; + function requestExit(bytes32 id) external; + } + function approve(address spender, uint256 amount) external returns (bool); +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Requirement { + #[serde(with = "decimal")] + pub minimum_amount: u64, + pub minimum_exit_delay_seconds: u64, +} + +impl Default for Requirement { + fn default() -> Self { + Self { + minimum_amount: 1, + minimum_exit_delay_seconds: 0, + } + } +} +impl Requirement { + /// The requirement a buyer on `network` applies when its config names none. + pub fn standard(network: crate::contract::Network) -> Self { + Self { + minimum_amount: DEFAULT_AMOUNT, + minimum_exit_delay_seconds: network.bond_exit_delay(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Settings { + /// The escrow; defaults to the network's deployed one. + pub contract: Option, + /// The bond a provider needs; defaults to the network's standard bond. + pub providers: Requirement, + #[serde(with = "decimal")] + pub max_lock: u64, + pub max_exit_delay_seconds: u64, + pub verification_retry_seconds: u64, +} +impl Default for Settings { + fn default() -> Self { + Self { + contract: None, + providers: Requirement::default(), + max_lock: DEFAULT_AMOUNT, + max_exit_delay_seconds: DEFAULT_EXIT_DELAY_SECONDS, + verification_retry_seconds: 60, + } + } +} +impl Settings { + pub fn validate(&self) -> Result<()> { + ensure!( + self.verification_retry_seconds > 0, + "bond verification retry must be positive" + ); + ensure!( + self.max_exit_delay_seconds <= MAX_EXIT_DELAY_SECONDS, + "maximum exit delay exceeds the contract limit" + ); + if let Some(contract) = &self.contract { + ensure!(address(contract)? != Address::ZERO, "zero escrow address"); + } + ensure!( + self.providers.minimum_amount > 0, + "bond requirements must have a nonzero amount" + ); + Ok(()) + } + /// The published reference to `bond_id` in this escrow. + pub fn proof(&self, rpc: &Rpc, bond_id: Option<&str>) -> Result> { + bond_id + .map(|id| { + let _: B256 = id.parse()?; + Ok(Proof { + chain_id: rpc.network.chain_id(), + contract: self.contract.clone().context("missing escrow")?, + bond_id: id.into(), + }) + }) + .transpose() + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Proof { + pub chain_id: u64, + pub contract: String, + pub bond_id: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum Intent { + Lock { + mesh_id: String, + host_key: String, + #[serde(with = "decimal")] + amount: u64, + exit_delay_seconds: u64, + salt: String, + }, + Withdraw { + bond_id: String, + }, + RequestExit { + bond_id: String, + }, +} + +pub fn mesh_binding(mesh_id: &str) -> Result { + ensure!( + !mesh_id.is_empty() && mesh_id.len() <= 256, + "invalid mesh ID" + ); + Ok(keccak256( + [b"mesh.tempo.bond.v1/".as_slice(), mesh_id.as_bytes()].concat(), + )) +} +pub fn host_binding(host: &str) -> Result { + crate::config::validate_peer(host)?; + let key = B256::from_slice(&hex::decode(host)?); + ensure!(key != B256::ZERO, "empty host key"); + Ok(key) +} +/// The salt of the default bond: one per mesh and host key, so a repeated +/// `bond_lock` without a salt resumes that bond instead of locking another. +pub fn default_salt(mesh_id: &str, host: &str) -> Result { + let (mesh, host) = (mesh_binding(mesh_id)?, host_binding(host)?); + let seed = [ + b"tempo.bond.v1/default-salt/".as_slice(), + mesh.as_slice(), + host.as_slice(), + ]; + Ok(keccak256(seed.concat()).to_string()) +} +/// The operation ID of a lock that names none, derived from its salt. +pub fn lock_operation(salt: &str) -> Result { + let salt: B256 = salt.parse()?; + let digest = keccak256([b"tempo.bond.v1/operation/".as_slice(), salt.as_slice()].concat()); + Ok(uuid::Uuid::from_slice(&digest[..16])?.to_string()) +} +/// The operation ID of an exit or withdrawal that names none, derived from +/// its kind and bond, so it is resumed rather than repeated. +pub fn exit_operation(kind: &str, bond_id: &str) -> Result { + let bond: B256 = bond_id.parse()?; + let seed = [ + b"tempo.bond.v1/operation/".as_slice(), + kind.as_bytes(), + b"/", + bond.as_slice(), + ]; + let digest = keccak256(seed.concat()); + Ok(uuid::Uuid::from_slice(&digest[..16])?.to_string()) +} + +pub fn bond_id(rpc: &Rpc, contract: &str, wallet: &str, salt: &str) -> Result { + Ok(keccak256( + ( + U256::from(rpc.network.chain_id()), + address(contract)?, + address(wallet)?, + salt.parse::()?, + ) + .abi_encode(), + )) +} +pub fn runtime_hash() -> B256 { + keccak256( + hex::decode( + include_str!("../contracts/runtime.hex") + .trim() + .trim_start_matches("0x"), + ) + .expect("checked-in escrow bytecode"), + ) +} +pub async fn check_contract(rpc: &Rpc, contract: &str, tag: &str) -> Result<()> { + address(contract)?; + let code = rpc.call("eth_getCode", json!([contract, tag])).await?; + let bytes = hex::decode( + code.as_str() + .context("missing escrow code")? + .trim_start_matches("0x"), + )?; + ensure!( + keccak256(bytes) == runtime_hash(), + "escrow runtime bytecode does not match TempoBondEscrow" + ); + ensure!( + receipt::call(rpc, contract, Escrow::tokenCall {}, tag).await? + == address(crate::contract::OUSD)?, + "escrow uses another token" + ); + Ok(()) +} + +/// How long a decision that depends only on configuration stays valid; +/// Mesh discards it sooner when the verifier restarts or the evidence +/// changes. +const POLICY_VALIDITY_SECONDS: u64 = 365 * 24 * 60 * 60; + +/// Apply provider policy, checking required funds at one finalized block. +pub async fn verify( + rpc: &Rpc, + settings: &Settings, + mesh_id: &str, + host: &str, + evidence: Value, +) -> Result { + let requirement = &settings.providers; + let Some(contract) = settings.contract.as_deref() else { + // Without an escrow no bond can be checked, so none qualifies. + let valid_until = now().saturating_add(POLICY_VALIDITY_SECONDS); + let reason = "no bond escrow is configured on this network"; + return Ok(json!({"accepted":false,"reason":reason,"valid_until":valid_until})); + }; + ensure!( + serde_json::to_vec(&evidence)?.len() <= 1024, + "oversized bond reference" + ); + let proof: Proof = serde_json::from_value(evidence)?; + ensure!( + proof.chain_id == rpc.network.chain_id(), + "bond is on another network" + ); + ensure!( + address(&proof.contract)? == address(contract)?, + "untrusted escrow address" + ); + let id: B256 = proof.bond_id.parse()?; + let expected_mesh = mesh_binding(mesh_id)?; + let expected_host = host_binding(host)?; + rpc.check_network().await?; + let block = rpc.finalized().await?; + let timestamp = quantity(&block["timestamp"])?; + ensure!( + timestamp <= now().saturating_add(5) && now().saturating_sub(timestamp) <= MAX_STATE_AGE, + "finalized RPC state is stale or in the future" + ); + let tag = format!("0x{:x}", quantity(&block["number"])?); + check_contract(rpc, &proof.contract, &tag).await?; + let bond = receipt::call(rpc, &proof.contract, Escrow::getBondCall { id }, &tag).await?; + ensure!( + bond.meshId == expected_mesh && bond.hostKey == expected_host, + "bond belongs to another mesh or host key" + ); + ensure!( + !bond.withdrawn + && bond.refundWallet != Address::ZERO + && bond.amount >= requirement.minimum_amount, + "bond absent, withdrawn or below minimum amount" + ); + ensure!( + bond.exitDelay >= requirement.minimum_exit_delay_seconds, + "bond exit delay is below minimum" + ); + // Even an exit requested in the next block cannot release funds before this. + let valid_until = if bond.withdrawAt == U256::ZERO { + timestamp.saturating_add(bond.exitDelay) + } else { + u64::try_from(bond.withdrawAt).context("bond withdrawal deadline exceeds clock range")? + }; + ensure!( + valid_until > timestamp && valid_until > now(), + "bond is withdrawable or finalized evidence lease already expired" + ); + Ok( + json!({"accepted":true,"valid_until":valid_until,"amount":bond.amount.to_string(),"exit_delay_seconds":bond.exitDelay,"withdraw_at":bond.withdrawAt.to_string(),"block":tag}), + ) +} + +pub fn lock_data(intent: &Intent) -> Result> { + let Intent::Lock { + mesh_id, + host_key, + amount, + exit_delay_seconds, + salt, + } = intent + else { + anyhow::bail!("expected lock intent") + }; + Ok(Escrow::lockCall { + meshId: mesh_binding(mesh_id)?, + hostKey: host_binding(host_key)?, + amount: alloy::primitives::aliases::U96::from(*amount), + exitDelay: *exit_delay_seconds, + salt: salt.parse()?, + } + .abi_encode()) +} + +pub struct Service { + rpc: Rpc, + chain_verification: tokio::sync::Mutex<()>, +} +impl Service { + pub fn new(config: &crate::config::Config) -> Result { + Ok(Self { + rpc: Rpc::new(config.wallet.rpc_url().into(), config.wallet.network)?, + chain_verification: tokio::sync::Mutex::new(()), + }) + } + pub fn proof(&self, settings: &Settings, bond_id: Option<&str>) -> Result> { + settings.proof(&self.rpc, bond_id) + } + /// Apply provider policy on a Mesh cache miss; only Mesh caches eligibility. + pub async fn verify( + &self, + settings: &Settings, + mesh: &str, + host: &str, + evidence: Value, + ) -> Result { + settings.validate()?; + // Direct operation calls also need a bound on concurrent chain reads. + let _guard = self + .chain_verification + .try_lock() + .context("bond verifier is busy")?; + tokio::time::timeout( + Duration::from_secs(10), + verify(&self.rpc, settings, mesh, host, evidence), + ) + .await + .context("bond verification deadline exceeded")? + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exit_operations_are_derived_from_their_kind_and_bond() { + let bond = format!("0x{}", "ab".repeat(32)); + let operation = exit_operation("withdraw", &bond).unwrap(); + assert_eq!( + exit_operation("withdraw", &bond.to_uppercase().replace("0X", "0x")).unwrap(), + operation + ); + assert_ne!(exit_operation("request_exit", &bond).unwrap(), operation); + let other = format!("0x{}", "cd".repeat(32)); + assert_ne!(exit_operation("withdraw", &other).unwrap(), operation); + assert!(exit_operation("withdraw", "not a bond").is_err()); + } + + #[tokio::test] + async fn chain_verification_is_bounded_and_needs_an_escrow() { + let config: crate::config::Config = serde_json::from_value(json!({ + "data_dir":"/absolute/payments", "wallet":{} + })) + .unwrap(); + let service = Service::new(&config).unwrap(); + let required: Settings = serde_json::from_value(json!({ + "contract":"0x1111111111111111111111111111111111111111", + "providers":{} + })) + .unwrap(); + let guard = service.chain_verification.lock().await; + assert!( + service + .verify(&required, "mesh", "host", json!({})) + .await + .unwrap_err() + .to_string() + .contains("busy") + ); + drop(guard); + // Without an escrow no bond qualifies, and no chain is read. + let verdict = service + .verify(&config.bonds, "mesh", "host", json!({})) + .await + .unwrap(); + assert_eq!(verdict["accepted"], false); + assert!( + verdict["reason"] + .as_str() + .unwrap() + .contains("no bond escrow") + ); + assert!(verdict["valid_until"].as_u64().unwrap() > now() + 300 * 24 * 60 * 60); + } + + #[test] + fn provider_requirements_always_apply_and_need_funded_minimums() { + let settings: Settings = serde_json::from_value(json!({})).unwrap(); + settings.validate().unwrap(); + // A requirement can be lowered but not turned off. + assert!(serde_json::from_value::(json!({"providers":null})).is_err()); + let explicit: Settings = serde_json::from_value(json!({"providers":{}})).unwrap(); + assert_eq!(explicit.providers.minimum_amount, 1); + assert_eq!(explicit.providers.minimum_exit_delay_seconds, 0); + explicit.validate().unwrap(); + let zero: Settings = + serde_json::from_value(json!({"contract":"0x1111111111111111111111111111111111111111","providers":{"minimum_amount":"0"}})).unwrap(); + assert!(zero.validate().is_err()); + } + + #[test] + fn obsolete_renewal_and_maturity_settings_are_rejected() { + assert!(serde_json::from_value::(json!({"enabled":true})).is_err()); + assert!(serde_json::from_value::(json!({"renewal": {"enabled": true}})).is_err()); + assert!( + serde_json::from_value::(json!({"buyers": {"minimum_amount":"1"}})).is_err() + ); + assert!(serde_json::from_value::(json!({"max_lock_seconds": 60})).is_err()); + assert!( + serde_json::from_value::(json!({"minimum_lock_seconds": 60})).is_err() + ); + assert!( + Settings { + max_exit_delay_seconds: MAX_EXIT_DELAY_SECONDS + 1, + ..Default::default() + } + .validate() + .is_err() + ); + } + + #[test] + fn mesh_and_host_bindings_are_unambiguous() { + assert_ne!(mesh_binding("a").unwrap(), mesh_binding("b").unwrap()); + assert!(mesh_binding("").is_err()); + assert!(host_binding(&"00".repeat(32)).is_err()); + assert_eq!( + host_binding(&"ab".repeat(32)).unwrap().as_slice(), + &[0xab; 32] + ); + assert_ne!(runtime_hash(), keccak256([])); + } +} diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..61e58e8 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,76 @@ +use crate::{config::Config, runtime, tempo::keys}; +use anyhow::Result; +use clap::{Parser, Subcommand}; +use std::path::PathBuf; + +#[derive(Parser)] +#[command( + name = "tempo", + version, + about = "OUSD payments and refundable identity bonds on Tempo" +)] +struct Cli { + #[arg(long, global = true)] + config: Option, + #[command(subcommand)] + command: Option, +} +#[derive(Subcommand)] +enum Command { + /// Run the Mesh plugin (the default). + Serve, + /// Set up the local wallet before the plugin runs. Everything else is a + /// control operation on the running plugin. + Wallet { + #[command(subcommand)] + command: WalletCommand, + }, +} +#[derive(Subcommand)] +enum WalletCommand { + /// Initialize an encrypted wallet for the configured network. No transaction. + Init, + /// Read the persisted public address without unlocking or network access. + Address, +} + +/// Run the plugin or an explicit local wallet setup command. +pub async fn run() -> Result<()> { + if std::env::args().any(|arg| arg == "--manifest") { + println!( + "{}", + mesh_llm_plugin::package_manifest_json(&runtime::manifest())? + ); + return Ok(()); + } + let cli = Cli::parse(); + match cli.command.unwrap_or(Command::Serve) { + Command::Serve => runtime::run().await, + Command::Wallet { command } => { + let config = Config::load_from(cli.config)?; + let settings = config.wallet; + let dir = config.data_dir; + let value = match command { + // Without a configured password file the wallet gets a random + // one in its state directory, as when `fund` creates it. + WalletCommand::Init => { + let password = match settings.password_file { + Some(path) => path, + None => { + keys::secure_dir(&dir)?; + let path = keys::generated_password(&dir); + keys::create_password(&path)?; + path + } + }; + serde_json::to_value(keys::initialize(&dir, &password, settings.network)?)? + } + WalletCommand::Address => { + serde_json::to_value(keys::load_profile(&dir, settings.network)?)? + } + }; + println!("{}", serde_json::to_string_pretty(&value)?); + Ok(()) + } + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..161d4ac --- /dev/null +++ b/src/config.rs @@ -0,0 +1,407 @@ +use crate::contract::{decimal, decimal_option}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::PathBuf, +}; + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Price { + #[serde(with = "decimal")] + pub input_per_million: u64, + #[serde(with = "decimal")] + pub output_per_million: u64, + /// Percentage taken off reported cached input only. + #[serde(default)] + pub cache_discount_percent: u8, +} +impl Price { + pub fn is_free(&self) -> bool { + self.input_per_million == 0 && self.output_per_million == 0 + } + pub fn validate(&self) -> Result<()> { + ensure!( + self.cache_discount_percent <= 100, + "cache discount must be 0..=100 percent" + ); + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Mode { + #[default] + FreeOnly, + Automatic, +} + +/// The buyer's approval policy, as in the Lightning plugin. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Policy { + #[serde(default)] + pub mode: Mode, + /// The voucher increments the buyer may sign per day. + #[serde(default, with = "decimal_option")] + pub daily_budget: Option, +} +impl Policy { + pub fn validate(&self) -> Result<()> { + if self.mode == Mode::Automatic { + ensure!( + self.daily_budget + .is_some_and(|n| n > 0 && n <= i64::MAX as u64), + "automatic payments require a positive daily budget" + ); + } + Ok(()) + } + /// The daily budget when paid buying is allowed. + pub fn budget(&self) -> Option { + (self.mode == Mode::Automatic) + .then_some(self.daily_budget) + .flatten() + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + pub data_dir: PathBuf, + #[serde(default)] + pub wallet: crate::tempo::Settings, + #[serde(default)] + pub bonds: crate::bonds::Settings, + /// Seller rates, written into the ledger at startup. + #[serde(default)] + pub prices: BTreeMap, + /// Written into the ledger at startup. + #[serde(default)] + pub policy: Policy, + /// Upfront plus the bill's voucher increment for one request; 0 means none. + #[serde(default, with = "decimal")] + pub cap: u64, + /// The sellers paid inference is bought from; empty means any seller, + /// as in the Lightning plugin. + #[serde(default)] + pub buy_peers: BTreeSet, + /// Per-model rate ceilings; a model without one is bought at the + /// seller's rates, within the per-request cap and daily budget. + #[serde(default)] + pub buy_prices: BTreeMap, + /// The seller's node-wide upfront for a new channel and the largest + /// upfront the buyer accepts, written into the ledger at startup when set. + #[serde(default, with = "decimal_option")] + pub admission_deposit: Option, + /// The deposit of a new channel and the amount of each top-up; 1 OUSD + /// unless set. + #[serde(default = "default_channel_topup", with = "decimal")] + pub channel_topup: u64, +} +fn default_channel_topup() -> u64 { + 1_000_000 +} +impl Config { + pub fn load(path: &std::path::Path) -> Result { + ensure!(path.is_absolute(), "config_path must be absolute"); + let value: serde_json::Value = + serde_json::from_slice(&std::fs::read(path).context("read Tempo config")?)?; + let unstated = value["bonds"].get("providers").is_none(); + let mut config: Self = serde_json::from_value(value)?; + if config.bonds.contract.is_none() { + config.bonds.contract = config.wallet.network.bond_escrow().map(Into::into); + } + // Providers need the network's standard bond unless the config + // states another requirement. + if unstated { + config.bonds.providers = crate::bonds::Requirement::standard(config.wallet.network); + } + config.validate()?; + Ok(config) + } + /// Loads `path`, or without one (or an empty one) the default config, + /// which is created on first use with its state beside it. + pub fn load_from(path: Option) -> Result { + match path.filter(|p| !p.as_os_str().is_empty()) { + Some(path) => Self::load(&path), + None => Self::load_or_create(&default_dir()?), + } + } + /// Loads `dir/config.json`, first writing one that keeps the state in + /// `dir` and leaves every other setting at its default. + pub fn load_or_create(dir: &std::path::Path) -> Result { + let path = dir.join("config.json"); + if !path.exists() { + crate::tempo::keys::secure_dir(dir)?; + let config = serde_json::json!({ "data_dir": dir }); + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&path)?; + std::io::Write::write_all(&mut file, &serde_json::to_vec_pretty(&config)?)?; + file.sync_all()?; + } + Self::load(&path) + } + /// Whether the settings charge or pay for inference, which needs a wallet. + pub fn needs_wallet(&self) -> bool { + self.policy.mode == Mode::Automatic || self.prices.values().any(|p| !p.is_free()) + } + pub fn validate(&self) -> Result<()> { + ensure!(self.data_dir.is_absolute(), "data_dir must be absolute"); + if let Some(password) = &self.wallet.password_file { + ensure!( + password.is_absolute(), + "wallet.password_file must be absolute" + ); + } + self.bonds.validate()?; + self.policy.validate()?; + for price in self.prices.values().chain(self.buy_prices.values()) { + price.validate()?; + } + for peer in &self.buy_peers { + validate_peer(peer)?; + } + self.check_buying(&self.policy) + } + /// Whether this config can pay under `policy`, from the config or the + /// `policy` control. + pub fn check_buying(&self, policy: &Policy) -> Result<()> { + if policy.mode == Mode::Automatic { + ensure!( + self.channel_topup > 0, + "spending requires a nonzero channel top-up" + ); + ensure!( + self.channel_topup <= self.wallet.max_payment, + "channel_topup exceeds wallet.max_payment" + ); + // One top-up must fit any bill within the per-request limit, or + // the buyer could not pay it and the seller would close. + let limit = match self.cap { + 0 => policy.daily_budget.unwrap_or(0), + cap => cap, + }; + ensure!( + self.channel_topup >= limit, + "channel_topup must be at least cap, or the daily budget without a cap" + ); + } + Ok(()) + } +} +/// `~/.mesh-llm/tempo`, beside the Lightning plugin's `~/.mesh-llm/payments`. +pub fn default_dir() -> Result { + let home = std::env::var_os("HOME") + .filter(|home| !home.is_empty()) + .or_else(|| std::env::var_os("USERPROFILE").filter(|home| !home.is_empty())) + .context("cannot determine the home directory for Tempo's state")?; + Ok(PathBuf::from(home).join(".mesh-llm").join("tempo")) +} + +pub fn validate_peer(peer: &str) -> Result<()> { + ensure!( + peer.len() == 64 && hex::decode(peer)?.len() == 32, + "invalid Mesh peer ID" + ); + Ok(()) +} +pub fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn documented_examples_load_and_enable_buying_with_one_change() { + for example in [ + include_str!("../demo/buyer-payments.json.example"), + include_str!("../demo/seller-payments.json.example"), + include_str!("../demo/mainnet-payments.json.example"), + ] { + let filled = example.replace( + "REPLACE_WITH_SELLER_64_CHARACTER_HEX_PEER_ID", + &"bb".repeat(32), + ); + let mut config: Config = serde_json::from_str(&filled).unwrap(); + config.validate().unwrap(); + assert_eq!(config.policy.mode, Mode::FreeOnly); + // Switching the mode is the one change, given a daily budget. + config.policy.mode = Mode::Automatic; + assert_eq!( + config.validate().is_ok(), + config.policy.daily_budget.is_some() + ); + } + } + #[test] + fn default_config_never_authorizes_spending_and_rejects_unknown_settings() { + let mut value = serde_json::json!({"data_dir":"/absolute/payments", "wallet":{}}); + let config: Config = serde_json::from_value(value.clone()).unwrap(); + config.validate().unwrap(); + assert!(config.prices.is_empty()); + assert_eq!(config.bonds.max_exit_delay_seconds, 86_400); + assert_eq!(config.policy, Policy::default()); + assert_eq!(config.policy.budget(), None); + assert!(config.buy_peers.is_empty()); + assert_eq!((config.cap, config.admission_deposit), (0, None)); + assert_eq!(config.wallet.network, crate::contract::Network::Testnet); + assert_eq!(config.wallet.rpc_url(), "https://rpc.moderato.tempo.xyz"); + for removed in [ + serde_json::json!({"payments":{"enabled":true}}), + serde_json::json!({"bonds":{"enabled":true}}), + serde_json::json!({"wallet":{"data_dir":"/absolute/wallet"}}), + serde_json::json!({"buying":{"enabled":true}}), + ] { + let mut obsolete = value.clone(); + obsolete + .as_object_mut() + .unwrap() + .extend(removed.as_object().unwrap().clone()); + assert!(serde_json::from_value::(obsolete).is_err()); + } + value["unsupported_setting"] = serde_json::json!("0"); + assert!(serde_json::from_value::(value).is_err()); + } + + #[test] + fn automatic_buying_needs_a_positive_budget_and_a_top_up() { + let peer = "bb".repeat(32); + let mut value = serde_json::json!({"data_dir":"/absolute/payments", + "policy":{"mode":"automatic","daily_budget":"100"}, + "buy_peers":[peer],"channel_topup":"20","cap":"10","admission_deposit":"5", + "buy_prices":{"model":{"input_per_million":"1","output_per_million":"2"}}}); + let config: Config = serde_json::from_value(value.clone()).unwrap(); + config.validate().unwrap(); + assert_eq!(config.policy.budget(), Some(100)); + assert_eq!((config.cap, config.admission_deposit), (10, Some(5))); + for (field, invalid) in [ + ("policy", serde_json::json!({"mode":"automatic"})), + ( + "policy", + serde_json::json!({"mode":"automatic","daily_budget":"0"}), + ), + ("channel_topup", serde_json::json!("0")), + // One top-up must cover the cap. + ("channel_topup", serde_json::json!("9")), + // Without a cap, it must cover the daily budget. + ("cap", serde_json::json!("0")), + // The wallet must be allowed to sign each deposit. + ("wallet", serde_json::json!({"max_payment": "19"})), + ] { + let mut broken = value.clone(); + broken[field] = invalid; + let config: Config = serde_json::from_value(broken).unwrap(); + assert!(config.validate().is_err(), "{field}"); + } + let mut uncapped = value.clone(); + uncapped["cap"] = serde_json::json!("0"); + uncapped["channel_topup"] = serde_json::json!("100"); + let config: Config = serde_json::from_value(uncapped).unwrap(); + config.validate().unwrap(); + value["policy"] = serde_json::json!({"mode":"free_only"}); + let config: Config = serde_json::from_value(value).unwrap(); + config.validate().unwrap(); + assert_eq!(config.policy.budget(), None); + // As in the Lightning plugin, a policy alone enables buying: from + // any seller, at its rates, with a 1 OUSD channel top-up. + let policy = serde_json::json!({"mode":"automatic","daily_budget":"100000"}); + let minimal = serde_json::json!({"data_dir":"/absolute/payments","policy":policy}); + let config: Config = serde_json::from_value(minimal).unwrap(); + config.validate().unwrap(); + assert!(config.buy_peers.is_empty() && config.buy_prices.is_empty()); + assert_eq!((config.cap, config.channel_topup), (0, 1_000_000)); + } + + #[test] + fn network_selection_sets_rpc_default_without_inferring_network_from_url() { + let mut value = + serde_json::json!({"data_dir":"/absolute/payments", "wallet":{"network":"mainnet"}}); + let config: Config = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(config.wallet.network, crate::contract::Network::Mainnet); + assert_eq!(config.wallet.rpc_url(), "https://rpc.tempo.xyz"); + assert_eq!(config.policy.mode, Mode::FreeOnly); + value["wallet"]["rpc_url"] = serde_json::json!("https://custom.example/rpc"); + let config: Config = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(config.wallet.rpc_url(), "https://custom.example/rpc"); + assert_eq!(config.wallet.network, crate::contract::Network::Mainnet); + value["wallet"]["network"] = serde_json::json!("unknown"); + assert!(serde_json::from_value::(value.clone()).is_err()); + value["wallet"].as_object_mut().unwrap().remove("network"); + let config: Config = serde_json::from_value(value).unwrap(); + assert_eq!(config.wallet.network, crate::contract::Network::Testnet); + } + + #[test] + fn testnet_uses_the_deployed_escrow_and_providers_always_need_a_bond() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("payments.json"); + let load = |value: serde_json::Value| { + std::fs::write(&path, value.to_string()).unwrap(); + Config::load(&path) + }; + let required = serde_json::json!({"providers":{"minimum_amount":"1"}}); + let testnet = load(serde_json::json!({"data_dir":"/absolute/payments","bonds":required})); + assert_eq!( + testnet.unwrap().bonds.contract.as_deref(), + Some("0xd210B0356b3e45B37F29Ec763106dc23BF1cC3aa") + ); + // Without a stated requirement, testnet buyers require 1 OUSD for a minute. + let standard = load(serde_json::json!({"data_dir":"/absolute/payments"})).unwrap(); + let requirement = standard.bonds.providers; + let minimums = ( + requirement.minimum_amount, + requirement.minimum_exit_delay_seconds, + ); + assert_eq!(minimums, (1_000_000, 60)); + let none = serde_json::json!({"data_dir":"/absolute/payments","bonds":{"providers":null}}); + assert!(load(none).is_err()); + // Mainnet has no deployed escrow, so it loads but no bond qualifies + // until one is configured. + let unknown = + serde_json::json!({"data_dir":"/absolute/payments","wallet":{"network":"mainnet"}}); + let unknown = load(unknown).unwrap().bonds; + assert_eq!(unknown.contract, None); + assert_eq!(unknown.providers.minimum_exit_delay_seconds, 86_400); + let mut configured = serde_json::json!({"data_dir":"/absolute/payments", + "wallet":{"network":"mainnet"},"bonds":required}); + configured["bonds"]["contract"] = serde_json::json!(format!("0x{}", "12".repeat(20))); + assert!(!load(configured).unwrap().needs_wallet()); + } + + #[test] + fn the_default_config_is_written_once_with_its_state_beside_it() { + let home = tempfile::tempdir().unwrap(); + let dir = home.path().join("tempo"); + let created = Config::load_or_create(&dir).unwrap(); + assert_eq!(created.data_dir, dir); + assert!(!created.needs_wallet()); + assert_eq!(created.bonds.providers.minimum_amount, 1_000_000); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode(); + assert_eq!(mode(&dir) & 0o777, 0o700); + assert_eq!(mode(&dir.join("config.json")) & 0o777, 0o600); + } + // An edited file is kept. + let edited = + serde_json::json!({"data_dir": dir, "bonds": {"providers": {"minimum_amount": "5"}}}); + std::fs::write(dir.join("config.json"), edited.to_string()).unwrap(); + let kept = Config::load_or_create(&dir).unwrap().bonds.providers; + assert_eq!(kept.minimum_amount, 5); + assert!(Config::load_from(Some(PathBuf::from("relative.json"))).is_err()); + } +} diff --git a/src/contract.rs b/src/contract.rs new file mode 100644 index 0000000..cd42d52 --- /dev/null +++ b/src/contract.rs @@ -0,0 +1,202 @@ +//! Stablecoin operations are opaque to the Mesh host. +use anyhow::{Result, ensure}; +use serde::{Deserialize, Serialize}; + +pub mod mpp; + +pub const OUSD: &str = "0x20c0000000000000000000006a37da5c996874be"; +pub const SCALE: u64 = 1_000_000; + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Network { + #[default] + Testnet, + Mainnet, +} +impl Network { + pub fn chain_id(self) -> u64 { + match self { + Self::Testnet => 42431, + Self::Mainnet => 4217, + } + } + /// The deployed bond escrow every mesh on the network shares, if any. + pub fn bond_escrow(self) -> Option<&'static str> { + match self { + Self::Testnet => Some("0xd210B0356b3e45B37F29Ec763106dc23BF1cC3aa"), + Self::Mainnet => None, + } + } + /// The default bond's exit delay. + pub fn bond_exit_delay(self) -> u64 { + match self { + Self::Testnet => crate::bonds::TESTNET_EXIT_DELAY_SECONDS, + Self::Mainnet => crate::bonds::DEFAULT_EXIT_DELAY_SECONDS, + } + } + pub fn rpc_url(self) -> &'static str { + match self { + Self::Testnet => "https://rpc.moderato.tempo.xyz", + Self::Mainnet => "https://rpc.tempo.xyz", + } + } + pub fn from_chain_id(chain_id: u64) -> Result { + match chain_id { + 42431 => Ok(Self::Testnet), + 4217 => Ok(Self::Mainnet), + _ => anyhow::bail!("unsupported Tempo chain {chain_id}"), + } + } + pub fn asset(self) -> Asset { + Asset { + chain_id: self.chain_id(), + token: OUSD.into(), + decimals: 6, + } + } +} + +/// Never serialize native amounts as JSON floating-point numbers. +pub mod decimal { + use serde::{Deserialize, Deserializer, Serializer, de::Error}; + pub fn serialize(value: &u64, serializer: S) -> Result { + serializer.serialize_str(&value.to_string()) + } + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + value.parse().map_err(D::Error::custom) + } +} + +/// An optional amount as an exact decimal string, or `null`. +pub mod decimal_option { + use serde::{Deserialize, Deserializer, Serializer, de::Error}; + pub fn serialize(value: &Option, serializer: S) -> Result { + match value { + Some(value) => serializer.serialize_str(&value.to_string()), + None => serializer.serialize_none(), + } + } + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|value| value.parse().map_err(D::Error::custom)) + .transpose() + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct Asset { + pub chain_id: u64, + pub token: String, + pub decimals: u8, +} +impl Default for Asset { + fn default() -> Self { + Network::default().asset() + } +} +impl Asset { + /// Validate OUSD identity and return its Tempo network. + pub fn network(&self) -> Result { + let network = Network::from_chain_id(self.chain_id)?; + ensure!(self.token.eq_ignore_ascii_case(OUSD), "unsupported token"); + ensure!(self.decimals == 6, "unexpected token precision"); + Ok(network) + } +} + +pub fn validate_address(value: &str) -> Result<()> { + let bytes = hex::decode(value.strip_prefix("0x").unwrap_or(value))?; + ensure!( + bytes.len() == 20 && bytes.iter().any(|b| *b != 0), + "invalid account address" + ); + Ok(()) +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct WalletInfo { + pub wallet_id: String, + pub address: String, + pub asset: Asset, + pub can_send: bool, +} +impl WalletInfo { + /// A node without a wallet: it cannot sign, so it verifies bonds and + /// serves free inference only. + pub fn absent(network: Network) -> Self { + Self { + wallet_id: String::new(), + address: format!("0x{}", "00".repeat(20)), + asset: network.asset(), + can_send: false, + } + } + pub fn is_absent(&self) -> bool { + self.wallet_id.is_empty() + } + /// Validate the local wallet identity and the supported Tempo OUSD asset. + pub fn validate_tempo(&self) -> Result<()> { + self.asset.network()?; + validate_address(&self.address)?; + ensure!( + !self.wallet_id.is_empty() + && self.wallet_id.len() <= 256 + && !self.wallet_id.chars().any(char::is_control), + "invalid wallet ID" + ); + Ok(()) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Balance { + #[serde(with = "decimal")] + pub balance: u64, + #[serde(with = "decimal")] + pub reserved: u64, + #[serde(with = "decimal")] + pub spendable: u64, + pub block_number: u64, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wire_amounts_are_exact_decimal_strings() { + let value = Balance { + balance: u64::MAX, + reserved: 1, + spendable: 2, + block_number: 3, + }; + let encoded = serde_json::to_string(&value).unwrap(); + assert!(encoded.contains("\"18446744073709551615\"")); + assert_eq!( + serde_json::from_str::(&encoded).unwrap().balance, + u64::MAX + ); + assert!(serde_json::from_str::("{\"balance\":1.5}").is_err()); + } + #[test] + fn asset_identity_accepts_both_networks_and_rejects_lookalikes() { + let mut asset = Asset::default(); + assert_eq!(asset.network().unwrap(), Network::Testnet); + asset = Network::Mainnet.asset(); + assert_eq!(asset.network().unwrap(), Network::Mainnet); + asset.chain_id = 1; + assert!(asset.network().is_err()); + asset = Asset::default(); + asset.token = "0x20c0000000000000000000000000000000000000".into(); + assert!(asset.network().is_err()); + asset = Asset::default(); + asset.decimals = 18; + assert!(asset.network().is_err()); + assert!(validate_address("0x0000000000000000000000000000000000000000").is_err()); + } +} diff --git a/src/contract/mpp.rs b/src/contract/mpp.rs new file mode 100644 index 0000000..0a8961e --- /dev/null +++ b/src/contract/mpp.rs @@ -0,0 +1,450 @@ +//! Reusable TIP-1034 channels for OUSD on the selected Tempo network. +use super::{Asset, SCALE, decimal, validate_address}; +use anyhow::{Result, ensure}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub const RESERVE: &str = "0x4d50500000000000000000000000000000000000"; +pub const CLOSE_GRACE_SECONDS: u64 = 900; + +/// The identity of one channel between a buyer and a seller node. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ChannelTerms { + pub buyer_peer: String, + pub seller_peer: String, + pub payer: String, + pub payee: String, + pub asset: Asset, + /// 32 random bytes chosen by the buyer at open, so a pair can reopen after a close. + pub nonce: String, +} +impl ChannelTerms { + pub fn validate(&self) -> Result<()> { + self.asset.network()?; + validate_address(&self.payer)?; + validate_address(&self.payee)?; + ensure!( + !self.payer.eq_ignore_ascii_case(&self.payee), + "self channel refused" + ); + ensure!( + self.nonce.len() == 64 && hex::decode(&self.nonce).is_ok(), + "invalid channel nonce" + ); + Ok(()) + } + pub fn salt(&self) -> Result { + self.validate()?; + let mut digest = Sha256::new(); + digest.update(b"mesh-llm/mpp/channel/v1\0"); + digest.update(serde_json::to_vec(self)?); + Ok(format!("0x{}", hex::encode(digest.finalize()))) + } +} + +/// A finalized open; vouchers are separate. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ChannelFunding { + pub terms: ChannelTerms, + pub open_tx: String, + pub channel_id: String, + pub expiring_nonce_hash: String, +} + +/// A cumulative EIP-712 authorization of `cum` from the channel deposit. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Voucher { + pub channel_id: String, + #[serde(with = "decimal")] + pub cum: u64, + /// TIP-1020 primitive secp256k1 encoding. + pub signature: String, +} + +/// A seller's quote for one request on the pair's channel. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct RequestTerms { + pub request_id: String, + pub buyer_peer: String, + pub seller_peer: String, + pub model: String, + pub body_digest: String, + pub payee: String, + pub asset: Asset, + #[serde(with = "decimal")] + pub input_per_million: u64, + #[serde(with = "decimal")] + pub output_per_million: u64, + /// Percentage taken off reported cached input only. + pub cache_discount_percent: u8, + pub output_limit: u64, + pub input_bytes: u64, + /// The voucher increase over `cum_before` the seller requires before work. + /// It is credit netted against later bills; only buyer policy bounds it. + #[serde(with = "decimal")] + pub upfront: u64, + /// The seller's best voucher on the channel before this request. + #[serde(with = "decimal")] + pub cum_before: u64, + /// The sum of the channel's bills when quoted, which may include bills + /// the buyer has not received or paid yet. + #[serde(with = "decimal")] + pub cost_before: u64, + /// The seller's channel with this buyer, or `None` when a new one is expected. + pub channel_id: Option, + pub expires_at: u64, +} + +/// Backend-reported token counts; cached tokens are part of prompt tokens. +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Usage { + pub prompt_tokens: u64, + pub completion_tokens: u64, + pub cached_tokens: u64, +} +impl Usage { + /// A complete usage report, or `None` when it is missing or inconsistent, + /// so an unknown report never becomes a zero-token bill. + pub fn from_event(event: &serde_json::Value) -> Option { + let usage = event.get("usage")?; + let prompt_tokens = usage.get("prompt_tokens")?.as_u64()?; + let completion_tokens = usage.get("completion_tokens")?.as_u64()?; + let cached_tokens = match usage.get("prompt_tokens_details") { + None | Some(serde_json::Value::Null) => 0, + Some(details) => match details.as_object()?.get("cached_tokens") { + None => 0, + Some(value) => value.as_u64()?, + }, + }; + (cached_tokens <= prompt_tokens).then_some(Self { + prompt_tokens, + completion_tokens, + cached_tokens, + }) + } +} + +impl RequestTerms { + pub fn validate(&self) -> Result<()> { + self.asset.network()?; + validate_address(&self.payee)?; + ensure!( + !self.request_id.is_empty() && self.request_id.len() <= 128, + "invalid request ID" + ); + ensure!( + self.body_digest.len() == 64 && hex::decode(&self.body_digest)?.len() == 32, + "invalid body digest" + ); + ensure!( + (1..=4096).contains(&self.output_limit), + "invalid output limit" + ); + ensure!( + (1..=64 * 1024).contains(&self.input_bytes), + "invalid input size" + ); + ensure!( + self.cache_discount_percent <= 100, + "cache discount must be 0..=100 percent" + ); + if let Some(id) = &self.channel_id { + ensure!( + id.len() == 66 && id.starts_with("0x") && hex::decode(&id[2..]).is_ok(), + "invalid channel ID" + ); + } + Ok(()) + } + /// The largest bill the buyer accepts: every body byte as an uncached + /// input token plus the full output limit, at the quoted rates. + pub fn worst_case(&self) -> u64 { + self.charge(Usage { + prompt_tokens: self.input_bytes, + completion_tokens: self.output_limit, + cached_tokens: 0, + }) + } + /// What the seller bills and the buyer pays for `usage`: the charge, + /// capped at the worst case, so the seller absorbs any prompt longer + /// than the body bound and an honest bill is never refused. + pub fn bill(&self, usage: Usage) -> u64 { + self.charge(usage).min(self.worst_case()) + } + /// The bill for `usage` at the quoted rates. Output beyond `output_limit` + /// is not billed, and an unrepresentable bill saturates rather than wraps. + pub fn charge(&self, usage: Usage) -> u64 { + // Weight cached and uncached input in percent, then round once. + let cached = usage.cached_tokens.min(usage.prompt_tokens); + let input = u128::from(usage.prompt_tokens - cached) + .saturating_mul(100) + .saturating_add( + u128::from(cached) + .saturating_mul((100 - self.cache_discount_percent.min(100)).into()), + ); + let numerator = input + .saturating_mul(self.input_per_million.into()) + .saturating_add( + u128::from(usage.completion_tokens.min(self.output_limit)) + .saturating_mul(self.output_per_million.into()) + .saturating_mul(100), + ); + numerator + .div_ceil(u128::from(SCALE) * 100) + .min(u64::MAX.into()) as u64 + } +} + +/// A seller's bill after inference; `usage` is `None` only for a waived bill. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Bill { + /// The bill's number on its channel, from 0; the buyer accepts bills in + /// this order. + pub seq: u64, + pub usage: Option, + #[serde(with = "decimal")] + pub cost: u64, + /// The channel's bills including this one. + #[serde(with = "decimal")] + pub running_total: u64, +} + +/// A finalized close or withdrawal; the deposit at close is `captured + refunded`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Closure { + pub tx_hash: String, + pub channel_id: String, + #[serde(with = "decimal")] + pub captured: u64, + #[serde(with = "decimal")] + pub refunded: u64, + pub block_number: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] +pub enum Request { + Open { + terms: ChannelTerms, + #[serde(with = "decimal")] + deposit: u64, + #[serde(with = "decimal")] + max_fee: u64, + }, + /// The `index`th top-up of the channel; retries of one index never add twice. + TopUp { + funding: ChannelFunding, + #[serde(with = "decimal")] + amount: u64, + index: u32, + #[serde(with = "decimal")] + max_fee: u64, + }, + /// Off-chain signing; takes no transaction slot. + SignVoucher { + funding: ChannelFunding, + #[serde(with = "decimal")] + cum: u64, + }, + VerifyVoucher { + funding: ChannelFunding, + voucher: Voucher, + }, + /// Captures `capture` and refunds the rest; capture 0 needs no valid voucher. + Close { + funding: ChannelFunding, + voucher: Option, + #[serde(with = "decimal")] + capture: u64, + }, + /// Payer recovery starts a native grace period, then withdraws on later calls. + Recover { + funding: ChannelFunding, + #[serde(with = "decimal")] + max_fee: u64, + }, + Inspect { + funding: ChannelFunding, + }, +} +impl Request { + pub fn terms(&self) -> &ChannelTerms { + match self { + Self::Open { terms, .. } => terms, + Self::TopUp { funding, .. } + | Self::SignVoucher { funding, .. } + | Self::VerifyVoucher { funding, .. } + | Self::Close { funding, .. } + | Self::Recover { funding, .. } + | Self::Inspect { funding } => &funding.terms, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, Default)] +pub struct Response { + /// The open was never finalized: it expired unsent or reverted. + pub unfunded: bool, + pub funding: Option, + pub voucher: Option, + /// The channel deposit after an open, top-up, verification or inspection. + pub deposit: u64, + pub closure: Option, + pub pending: bool, + pub close_requested_at: u64, +} + +/// The seller's channels named in close events, from a scan of the reserve's +/// logs up to block `to`. +#[derive(Clone, Debug, Default)] +pub struct CloseEvents { + /// Lowercase channel IDs of close requests, cancellations and closes. + pub channels: std::collections::BTreeSet, + pub to: u64, + /// No logs were read, at the first scan or after a long gap, so the + /// caller inspects every channel instead. + pub skipped: bool, +} + +#[cfg(test)] +mod tests { + use super::*; + fn terms() -> RequestTerms { + RequestTerms { + request_id: "request".into(), + buyer_peer: "buyer".into(), + seller_peer: "seller".into(), + model: "model".into(), + body_digest: "11".repeat(32), + payee: "0x2222222222222222222222222222222222222222".into(), + asset: Asset::default(), + input_per_million: 1_000_000, + output_per_million: 2_000_000, + cache_discount_percent: 75, + output_limit: 100, + input_bytes: 10, + upfront: 0, + cum_before: 0, + cost_before: 0, + channel_id: None, + expires_at: 100, + } + } + + #[test] + fn charge_saturates_and_never_bills_output_beyond_the_limit() { + let mut terms = terms(); + terms.input_per_million = u64::MAX; + terms.output_per_million = u64::MAX; + let huge = Usage { + prompt_tokens: u64::MAX, + completion_tokens: u64::MAX, + cached_tokens: 0, + }; + assert_eq!(terms.charge(huge), u64::MAX); + let terms = self::terms(); + let output = |completion_tokens| Usage { + completion_tokens, + ..Default::default() + }; + assert_eq!(terms.charge(output(100)), 200); + assert_eq!(terms.charge(output(101)), 200); + assert_eq!(terms.charge(output(u64::MAX)), 200); + } + + #[test] + fn salt_commits_to_every_channel_field() { + let mut channel = ChannelTerms { + buyer_peer: "aa".repeat(32), + seller_peer: "bb".repeat(32), + payer: "0x1111111111111111111111111111111111111111".into(), + payee: "0x2222222222222222222222222222222222222222".into(), + asset: Asset::default(), + nonce: "33".repeat(32), + }; + let original = channel.salt().unwrap(); + channel.asset = super::super::Network::Mainnet.asset(); + assert_ne!(channel.salt().unwrap(), original); + channel.asset = Asset::default(); + channel.nonce = "34".repeat(32); + assert_ne!(channel.salt().unwrap(), original); + channel.nonce = "zz".repeat(32); + assert!(channel.validate().is_err()); + channel.nonce = "33".repeat(32); + channel.payee = channel.payer.clone(); + assert!(channel.validate().is_err()); + } + + #[test] + fn quotes_may_show_unpaid_bills_and_any_upfront_parses() { + let mut terms = terms(); + terms.upfront = u64::MAX; + terms.validate().unwrap(); + let wire = serde_json::to_string(&terms).unwrap(); + assert_eq!(serde_json::from_str::(&wire).unwrap(), terms); + terms.cost_before = 1; + terms.validate().unwrap(); + terms.cost_before = 0; + terms.channel_id = Some("0x12".into()); + assert!(terms.validate().is_err()); + terms.channel_id = Some(format!("0x{}", "12".repeat(32))); + terms.validate().unwrap(); + terms.input_bytes = 0; + assert!(terms.validate().is_err()); + } + + #[test] + fn cache_discount_applies_to_cached_input_with_one_rounding() { + let terms = terms(); + let usage = |prompt, cached, completion| Usage { + prompt_tokens: prompt, + completion_tokens: completion, + cached_tokens: cached, + }; + // 6 uncached + 4 cached at 25% = 7 input tokens, plus 3 output at 2 each. + assert_eq!(terms.charge(usage(10, 4, 3)), 13); + // One cached token at 25% of 1 rounds up to a whole unit. + assert_eq!(terms.charge(usage(1, 1, 0)), 1); + assert_eq!(terms.charge(usage(0, 0, 0)), 0); + } + + #[test] + fn usage_reads_cached_tokens_and_rejects_inconsistent_reports() { + let event = |usage| serde_json::json!({ "usage": usage }); + let parsed = Usage::from_event(&event(serde_json::json!({ + "prompt_tokens": 10, + "completion_tokens": 3, + "prompt_tokens_details": {"cached_tokens": 4} + }))); + assert_eq!( + parsed, + Some(Usage { + prompt_tokens: 10, + completion_tokens: 3, + cached_tokens: 4 + }) + ); + let uncached = Usage::from_event(&event(serde_json::json!({ + "prompt_tokens": 10, + "completion_tokens": 3, + "prompt_tokens_details": null + }))); + assert_eq!(uncached.map(|u| u.cached_tokens), Some(0)); + assert!( + Usage::from_event(&event(serde_json::json!({ + "prompt_tokens": 1, + "completion_tokens": 3, + "prompt_tokens_details": {"cached_tokens": 2} + }))) + .is_none() + ); + assert!(Usage::from_event(&event(serde_json::json!({"prompt_tokens": 1}))).is_none()); + } +} diff --git a/src/control.rs b/src/control.rs new file mode 100644 index 0000000..382dd06 --- /dev/null +++ b/src/control.rs @@ -0,0 +1,565 @@ +//! The `control` operation: payment controls named as in the Lightning +//! plugin, wallet sends, and the Tempo-only recovery and bond commands. +use crate::{ + config::{Policy, Price}, + contract::{decimal, decimal_option}, + engine::Engine, +}; +use anyhow::{Context, Result, ensure}; +use serde::Deserialize; +use serde_json::{Map, Value, json}; + +#[derive(Debug, Deserialize)] +#[serde(tag = "command", rename_all = "snake_case", deny_unknown_fields)] +pub(crate) enum Control { + Balance {}, + /// The most recent requests, channels and wallet attempts, newest first. + Transactions { + limit: u32, + }, + /// Active requests and channels, and unresolved wallet attempts. + Pending {}, + /// Where to send OUSD to fund this wallet. + Fund {}, + /// A journaled OUSD transfer out of the wallet, once per operation ID. + Send { + operation_id: String, + to: String, + #[serde(with = "decimal")] + amount: u64, + #[serde(with = "decimal")] + max_fee: u64, + }, + Policy { + value: Option, + }, + Pricing {}, + SetPricing { + model: String, + value: Option, + }, + /// Patch only the cached-input discount of an already priced model. + SetCacheDiscount { + model: String, + percent: u8, + }, + AdmissionDeposit { + #[serde(default, with = "decimal_option")] + value: Option, + /// Forget the set node-wide deposit. + #[serde(default)] + reset: bool, + }, + SetModelAdmissionDeposit { + model: String, + #[serde(default, with = "decimal_option")] + value: Option, + }, + Retry { + request_id: Option, + }, + /// Close the buyer's channel with a seller, named by its node ID or a + /// unique prefix of at least eight characters; without one, the + /// buyer's only open channel. + Recover { + peer: Option, + }, + Waive { + request_id: String, + }, + Cancel { + request_id: String, + }, + /// Forgive a buyer's bills that closed channels lost, so the seller + /// accepts its requests again. + Unblock { + peer: String, + }, + BondContext {}, + /// Lock a bond; amount and exit delay default to 1 OUSD and the + /// network's default delay, a minute on testnet and a day on mainnet. + /// Every input is optional: the observed mesh, the default bond, and a + /// salt and operation ID derived from the mesh and host key, so the + /// same command resumes the same bond. + BondLock { + operation_id: Option, + mesh_id: Option, + amount: Option, + exit_delay_seconds: Option, + salt: Option, + }, + /// Start a bond's exit countdown, after which the plugin withdraws it + /// to this wallet; the bond defaults to the newest locked one, and the + /// operation ID to one derived from it, so the same command resumes the + /// same exit. + BondExit { + operation_id: Option, + bond_id: Option, + }, + /// Publish a bond as this node's evidence, or withdraw the reference + /// without `bond_id`. + BondPublish { + bond_id: Option, + }, +} + +const COMMANDS: [&str; 20] = [ + "balance", + "transactions", + "pending", + "fund", + "send", + "policy", + "pricing", + "set_pricing", + "set_cache_discount", + "admission_deposit", + "set_model_admission_deposit", + "retry", + "recover", + "waive", + "cancel", + "unblock", + "bond_context", + "bond_lock", + "bond_exit", + "bond_publish", +]; + +/// The operation's input schema. +pub(crate) fn schema() -> Map { + let string = json!({"type": "string"}); + let properties = json!({ + "command": {"type": "string", "enum": COMMANDS}, + "limit": {"type": "integer", "minimum": 1, "maximum": 100}, + "value": {"type": ["object", "string", "null"]}, + "reset": {"type": "boolean"}, + "model": string, "percent": {"type": "integer", "minimum": 0, "maximum": 100}, + "to": string, "amount": string, "max_fee": string, + "request_id": string, "peer": string, "operation_id": string, "mesh_id": string, + "exit_delay_seconds": {"type": "integer"}, "salt": string, "bond_id": string + }); + let schema = json!({ + "type": "object", + "additionalProperties": false, + "properties": properties, + "required": ["command"] + }); + schema.as_object().unwrap().clone() +} + +impl Control { + pub(crate) async fn run(self, engine: &Engine, mesh_id: Option) -> Result { + match self { + Self::Balance {} => Ok(serde_json::to_value(engine.wallet.balance().await?)?), + Self::Transactions { limit } => transactions(engine, limit), + Self::Pending {} => pending(engine), + Self::Fund {} => match engine.wallet.fund().await? { + Some(funding) => Ok(funding), + None => Ok(json!({ + "address": engine.wallet_info.address, + "network": engine.config.wallet.network, + "asset": engine.wallet_info.asset, + })), + }, + Self::Send { + operation_id, + to, + amount, + max_fee, + } => { + engine + .wallet + .send(&operation_id, &to, amount, max_fee) + .await + } + Self::Policy { value } => { + if let Some(value) = value { + ensure!( + value.budget().is_none() || !engine.wallet_info.is_absent(), + crate::engine::NEEDS_WALLET + ); + engine.config.check_buying(&value)?; + engine.ledger.set_policy(&value)?; + } + engine.ledger.policy_status() + } + Self::Pricing {} => pricing(engine), + Self::SetPricing { model, value } => { + engine.set_pricing(&model, value.as_ref()).await?; + pricing(engine) + } + Self::SetCacheDiscount { model, percent } => { + engine.set_cache_discount(&model, percent).await?; + pricing(engine) + } + Self::AdmissionDeposit { value, reset } => { + ensure!( + !(reset && value.is_some()), + "set an admission deposit or reset it, not both" + ); + if reset { + engine.ledger.reset_admission_deposit()?; + } + if let Some(value) = value { + engine.ledger.set_admission_deposit(value)?; + } + deposits(engine) + } + Self::SetModelAdmissionDeposit { model, value } => { + engine.ledger.set_model_admission_deposit(&model, value)?; + deposits(engine) + } + other => other.operate(engine, mesh_id).await, + } + } + /// The Tempo-only payment recovery and bond commands. + async fn operate(self, engine: &Engine, mesh_id: Option) -> Result { + // A finalized lock is published, and a withdrawn bond unpublished, at once. + let bond = |operation_id: String, intent| async move { + let settings = &engine.config.bonds; + let result = engine.wallet.bond(settings, &operation_id, intent).await?; + engine.sync_bond().await?; + Ok::<_, anyhow::Error>(result) + }; + match self { + Self::Retry { request_id } => { + if let Some(id) = &request_id { + engine.mpp_retry_one(id).await?; + } else { + engine.retry().await?; + } + Ok(json!({"reconciled": true, "request_id": request_id})) + } + Self::Recover { peer } => { + let peer = engine.buyer_close(peer.as_deref()).await?; + Ok(json!({"command": "recover", "peer": peer})) + } + Self::Waive { request_id } => request_control(engine, request_id, "waive").await, + Self::Cancel { request_id } => request_control(engine, request_id, "cancel").await, + Self::Unblock { peer } => { + let bills = engine.unblock(&peer).await?; + Ok(json!({"peer": peer, "bills": bills})) + } + Self::BondContext {} => Ok(json!({ + "mesh_id": mesh_id, + "node_id": engine.node, + "namespace": crate::bonds::NAMESPACE, + "reference": engine + .bonds + .proof(&engine.config.bonds, engine.ledger.published_bond()?.as_deref())?, + "requirement": engine.config.bonds.providers, + })), + lock @ Self::BondLock { .. } => { + let (operation_id, intent) = lock.lock_intent( + &engine.node, + mesh_id, + engine.config.wallet.network.bond_exit_delay(), + )?; + bond(operation_id, intent).await + } + Self::BondExit { + operation_id, + bond_id, + } => { + let (operation_id, bond_id) = exit_inputs(engine, operation_id, bond_id)?; + bond(operation_id, crate::bonds::Intent::RequestExit { bond_id }).await + } + Self::BondPublish { bond_id } => { + engine.set_published_bond(bond_id.as_deref()).await?; + Ok(json!({"bond_id": bond_id})) + } + _ => unreachable!("payment controls run in Control::run"), + } + } +} + +impl Control { + /// The operation ID and intent of a `bond_lock`, filling in what it omits. + fn lock_intent( + self, + host: &str, + observed: Option, + default_exit_delay: u64, + ) -> Result<(String, crate::bonds::Intent)> { + let Self::BondLock { + operation_id, + mesh_id, + amount, + exit_delay_seconds, + salt, + } = self + else { + anyhow::bail!("not a bond lock"); + }; + let mesh_id = match mesh_id { + // An explicit mesh guards against a mesh change racing the command. + Some(intended) => { + ensure!( + observed.as_deref() == Some(intended.as_str()), + "intended mesh differs from observed mesh ID" + ); + intended + } + None => observed.context("the mesh ID is not known yet; join a mesh first")?, + }; + let salt = match salt { + Some(salt) => salt, + None => crate::bonds::default_salt(&mesh_id, host)?, + }; + let operation_id = match operation_id { + Some(id) => id, + None => crate::bonds::lock_operation(&salt)?, + }; + let intent = crate::bonds::Intent::Lock { + mesh_id, + host_key: host.into(), + amount: amount.map_or(Ok(crate::bonds::DEFAULT_AMOUNT), |a| { + a.parse().context("invalid bond amount") + })?, + exit_delay_seconds: exit_delay_seconds.unwrap_or(default_exit_delay), + salt, + }; + Ok((operation_id, intent)) + } +} + +/// The operation ID and bond of an exit, filling in what it omits. +fn exit_inputs( + engine: &Engine, + operation_id: Option, + bond_id: Option, +) -> Result<(String, String)> { + let bond_id = match bond_id { + Some(id) => id, + None => engine + .newest_bond()? + .context("no finalized bond lock; name the bond with bond_id")?, + }; + let operation_id = match operation_id { + Some(id) => id, + None => crate::bonds::exit_operation("request_exit", &bond_id)?, + }; + Ok((operation_id, bond_id)) +} + +async fn request_control(engine: &Engine, request_id: String, command: &str) -> Result { + engine.mpp_control(&request_id, command).await?; + Ok(json!({"command": command, "request_id": request_id})) +} + +fn transactions(engine: &Engine, limit: u32) -> Result { + ensure!( + (1..=100).contains(&limit), + "limit must be between 1 and 100" + ); + let mut attempts = engine.wallet.attempts()?; + attempts.reverse(); + attempts.truncate(limit as usize); + Ok(unsigned(json!({ + "requests": engine.ledger.mpp_history(limit)?, + "channels": engine.ledger.channel_history(limit)?, + "attempts": attempts, + }))) +} + +fn pending(engine: &Engine) -> Result { + let mut attempts = engine.wallet.attempts()?; + attempts.retain(|attempt| attempt["status"] == "pending"); + Ok(unsigned(json!({ + "requests": engine.ledger.mpp_active()?, + "channels": engine.ledger.channels_active()?, + "attempts": attempts, + }))) +} + +/// Removes voucher signatures from channel and attempt listings: control +/// output never shows signed bytes. +fn unsigned(mut listing: Value) -> Value { + for list in ["channels", "attempts"] { + for item in listing[list].as_array_mut().into_iter().flatten() { + if let Some(voucher) = item["voucher"].as_object_mut() { + voucher.remove("signature"); + } + } + } + listing +} + +/// The node-wide admission deposit and each model's own. +fn deposits(engine: &Engine) -> Result { + let models: Map = engine + .ledger + .model_admission_deposits()? + .into_iter() + .map(|(model, deposit)| (model, deposit.to_string().into())) + .collect(); + Ok(json!({ + "admission_deposit": engine.ledger.admission_deposit()?.to_string(), + "models": models, + })) +} + +/// Seller prices with the admission deposits. +fn pricing(engine: &Engine) -> Result { + let mut value = deposits(engine)?; + value["prices"] = serde_json::to_value(engine.ledger.pricing()?)?; + Ok(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn listings_drop_voucher_signatures_from_channels_and_attempts() { + let listing = unsigned(json!({ + "channels": [{"voucher": {"cum": "10", "signature": "0x01"}}, {"voucher": null}], + "attempts": [{"kind": "close", "voucher": {"cum": "5", "signature": "0x02"}}, {"kind": "open"}] + })); + assert_eq!(listing["channels"][0]["voucher"], json!({"cum": "10"})); + assert_eq!(listing["attempts"][0]["voucher"], json!({"cum": "5"})); + assert!(!listing.to_string().contains("signature")); + } + + #[test] + fn controls_require_request_ids_and_reject_ignored_arguments() { + for input in [ + json!({"command": "recover", "request_id": "id"}), + json!({"command": "waive", "request_id": 123}), + json!({"command": "cancel", "request_id": "id", "limit": 20}), + json!({"command": "balance", "request_id": "id"}), + json!({"command": "resubmit", "request_id": "id"}), + json!({"command": "status"}), + json!({"command": "history", "limit": 1}), + json!({"command": "attempts"}), + json!({"command": "transactions"}), + json!({"command": "pending", "limit": 1}), + json!({"command": "fund", "amount": "1"}), + json!({"command": "send", "operation_id": "id", "to": "0x1", "amount": 1, "max_fee": "1"}), + json!({"command": "send", "operation_id": "id", "to": "0x1", "amount": "1"}), + json!({"command": "policy", "value": {"mode": "always"}}), + json!({"command": "policy", "value": {"daily_budget_msat": "1"}}), + json!({"command": "pricing", "model": "m"}), + json!({"command": "set_pricing", "value": null}), + json!({"command": "set_cache_discount", "model": "m", "percent": 256}), + json!({"command": "admission_deposit", "value_msat": "1"}), + json!({"command": "set_model_admission_deposit", "model": "m", "value": 1}), + ] { + assert!( + serde_json::from_value::(input.clone()).is_err(), + "{input}" + ); + } + assert!( + matches!(serde_json::from_value::(json!({"command":"retry", "request_id":"id"})).unwrap(), Control::Retry { request_id: Some(id) } if id == "id") + ); + assert!(matches!( + serde_json::from_value::(json!({"command":"retry"})).unwrap(), + Control::Retry { request_id: None } + )); + } + + #[test] + fn lightning_style_controls_parse_amounts_as_decimal_strings() { + let parse = |value| serde_json::from_value::(value).unwrap(); + assert!(matches!( + parse(json!({"command":"transactions","limit":5})), + Control::Transactions { limit: 5 } + )); + assert!(matches!( + parse( + json!({"command":"send","operation_id":"op","to":"0xab","amount":"18446744073709551615","max_fee":"7"}) + ), + Control::Send { + amount: u64::MAX, + max_fee: 7, + .. + } + )); + assert!(matches!( + parse(json!({"command":"policy"})), + Control::Policy { value: None } + )); + assert!(matches!( + parse(json!({"command":"policy","value":{"mode":"automatic","daily_budget":"9"}})), + Control::Policy { + value: Some(Policy { + daily_budget: Some(9), + .. + }) + } + )); + assert!(matches!( + parse(json!({"command":"set_pricing","model":"m"})), + Control::SetPricing { value: None, .. } + )); + assert!(matches!( + parse( + json!({"command":"set_pricing","model":"m","value":{"input_per_million":"1","output_per_million":"2"}}) + ), + Control::SetPricing { + value: Some(Price { + output_per_million: 2, + .. + }), + .. + } + )); + assert!(matches!( + parse(json!({"command":"admission_deposit","reset":true})), + Control::AdmissionDeposit { + value: None, + reset: true + } + )); + assert!(matches!( + parse(json!({"command":"set_model_admission_deposit","model":"m","value":"4"})), + Control::SetModelAdmissionDeposit { value: Some(4), .. } + )); + let schema = schema(); + let listed = &schema["properties"]["command"]["enum"]; + assert_eq!(listed.as_array().unwrap().len(), COMMANDS.len()); + for command in COMMANDS { + // Every listed command is a variant: only argument errors remain. + let error = serde_json::from_value::(json!({"command": command})).err(); + assert!(error.is_none_or(|e| !e.to_string().contains("unknown variant"))); + } + } + + #[test] + fn a_bond_lock_without_inputs_resumes_the_default_bond_for_the_observed_mesh() { + let host = "aa".repeat(32); + let lock = || serde_json::from_value::(json!({"command": "bond_lock"})).unwrap(); + let (operation, intent) = lock().lock_intent(&host, Some("mesh".into()), 60).unwrap(); + let (again, same) = lock().lock_intent(&host, Some("mesh".into()), 60).unwrap(); + assert_eq!((&operation, &intent), (&again, &same)); + let crate::bonds::Intent::Lock { + mesh_id, + amount, + exit_delay_seconds, + salt, + .. + } = intent + else { + panic!("not a lock") + }; + assert_eq!( + (mesh_id.as_str(), amount, exit_delay_seconds), + ("mesh", 1_000_000, 60) + ); + assert_eq!(salt, crate::bonds::default_salt("mesh", &host).unwrap()); + assert_eq!(operation, crate::bonds::lock_operation(&salt).unwrap()); + // Another mesh gets another bond; an unknown mesh is refused. + let (other, _) = lock().lock_intent(&host, Some("other".into()), 60).unwrap(); + assert_ne!(other, operation); + assert!(lock().lock_intent(&host, None, 60).is_err()); + let explicit = json!({"command": "bond_lock", "mesh_id": "intended"}); + let explicit = serde_json::from_value::(explicit).unwrap(); + assert!( + explicit + .lock_intent(&host, Some("mesh".into()), 60) + .is_err() + ); + } +} diff --git a/src/engine.rs b/src/engine.rs new file mode 100644 index 0000000..76f1f70 --- /dev/null +++ b/src/engine.rs @@ -0,0 +1,304 @@ +use crate::contract::WalletInfo; +use crate::{ + config::{Config, Price, now, validate_peer}, + ledger::Ledger, + protocol::{CHANNEL, MPP_VERSION, Message}, + wallet::Backend, +}; +use anyhow::{Context, Result, bail, ensure}; +use mesh_llm_plugin::{ + PluginContext, + openai_exchange::{OpenAiAdmissionDecision, OpenAiExchangeDecision}, +}; +use serde_json::Value; +use std::{collections::BTreeSet, sync::Arc}; +#[path = "engine_admission.rs"] +mod admission; +#[path = "engine_bonds.rs"] +mod bonds; +#[path = "engine_channel.rs"] +mod channel; +#[path = "engine_mpp.rs"] +mod mpp; +#[path = "engine_seller.rs"] +mod seller; +#[path = "engine_serving.rs"] +mod serving; + +pub struct Engine { + pub config: Config, + pub bonds: crate::bonds::Service, + pub ledger: Ledger, + pub wallet: Arc, + pub wallet_info: WalletInfo, + pub node: String, + context: Option>, + changed: tokio::sync::Notify, + peers: std::sync::Mutex>>>, + ingress: std::sync::Mutex>, + /// Serializes settings changes with their host calls, so host calls follow + /// ledger order; holds models whose channel requirement the host has not + /// accepted yet. + unsynced: tokio::sync::Mutex>, + watch: std::sync::Mutex, + /// Buyers that paid the seller since it started, as in the Lightning + /// plugin; their new channels open without an upfront. + standing: std::sync::Mutex>, + /// The host has not accepted the current bond reference yet. + bond_unsynced: std::sync::atomic::AtomicBool, + #[cfg(test)] + outbox: std::sync::Mutex>, + /// Makes test sends fail as if the peer were unreachable. + #[cfg(test)] + unreachable: std::sync::atomic::AtomicBool, + /// Channel requirements sent to the test host: model and whether required. + #[cfg(test)] + requirements: std::sync::Mutex>, + /// Bond references published to the test host. + #[cfg(test)] + published: std::sync::Mutex>>, +} +impl Engine { + pub fn new( + config: Config, + ledger: Ledger, + wallet: Arc, + wallet_info: WalletInfo, + node: String, + context: PluginContext<'static>, + ) -> Result> { + validate_peer(&node)?; + if !wallet_info.is_absent() { + wallet_info.validate_tempo()?; + } + ensure!( + wallet_info.asset.network()? == config.wallet.network, + "wallet does not match configured Tempo network" + ); + // Payment state is bound to the node; a node without a wallet has none, + // so a client with a changing identity can still verify bonds. + if !wallet_info.is_absent() { + ledger.pin_node(&node)?; + } + ledger.seed(&config)?; + ledger.mpp_restart()?; + if wallet_info.is_absent() { + let paid = ledger.pricing()?.values().any(|p| !p.is_free()); + ensure!(!paid && ledger.policy()?.budget().is_none(), NEEDS_WALLET); + } + Ok(Arc::new(Self { + bonds: crate::bonds::Service::new(&config)?, + config, + ledger, + wallet, + wallet_info, + node, + context: Some(context), + changed: Default::default(), + peers: Default::default(), + ingress: Default::default(), + unsynced: Default::default(), + watch: Default::default(), + standing: Default::default(), + bond_unsynced: Default::default(), + #[cfg(test)] + outbox: Default::default(), + #[cfg(test)] + unreachable: Default::default(), + #[cfg(test)] + requirements: Default::default(), + #[cfg(test)] + published: Default::default(), + })) + } + pub async fn send(&self, peer: &str, message: &Message) -> Result<()> { + if let Some(context) = &self.context { + return context + .clone() + .send_json_channel(CHANNEL, peer, "payment", message) + .await; + } + #[cfg(test)] + { + ensure!( + !self.unreachable.load(std::sync::atomic::Ordering::SeqCst), + "peer unreachable" + ); + self.outbox + .lock() + .unwrap() + .push((peer.into(), message.clone())); + Ok(()) + } + #[cfg(not(test))] + bail!("peer transport is not initialized") + } + pub async fn message(&self, peer: &str, message: Message) -> Result<()> { + validate_peer(peer)?; + let serial = self.peer_lock(peer)?; + let _guard = serial.lock().await; + match message { + Message::Mpp { + version, + id, + message, + } => { + ensure!(version == MPP_VERSION, "unsupported MPP protocol version"); + self.mpp_message(peer, &id, *message).await + } + Message::Closed { + version, + channel_id, + closure, + } => { + ensure!(version == MPP_VERSION, "unsupported MPP protocol version"); + self.buyer_closed_notice(peer, &channel_id, closure).await + } + Message::Error { id, reason } => { + self.ledger.mpp_update(&id, |row| { + ensure!(row.peer == peer, "unexpected error peer"); + row.error = Some(reason.chars().take(512).collect()); + Ok(()) + })?; + self.changed.notify_waiters(); + Ok(()) + } + } + } + pub async fn hook(&self, mut event: Value) -> Result { + if let Err(error) = self.remember_ingress(&event) { + return Ok(deny(&error.to_string())); + } + self.restore_ingress(&mut event); + if event["phase"] == "backend_selected" + && event["endpoint"] == "chat_completions" + && (self.ledger.policy()?.budget().is_some() + || event["requested_by_node_id"].is_string()) + && (!event["body"].is_object() || serde_json::to_vec(&event["body"])?.len() > 64 * 1024) + { + return Ok(deny( + "bounded request body is required to enforce payment identity on every route", + )); + } + match event["phase"].as_str() { + Some("exchange_finished") => { + self.mpp_terminal(&event).await?; + Ok(Default::default()) + } + Some("backend_selected") if self.is_remote_paid_selection(&event)? => { + self.mpp_seller_hook(&event).await + } + Some("backend_selected") => self.mpp_buyer_hook(&event).await, + _ => Ok(Default::default()), + } + } + pub fn record_terminal(&self, event: &Value) -> Result> { + self.forget_ingress(event); + self.mpp_record_terminal(event) + } + /// Asks the host to route every model the ledger prices only to peers + /// on the payment channel. + pub async fn require_paid_models(&self) -> Result<()> { + for (model, price) in self.ledger.pricing()? { + if !price.is_free() { + self.require_model(&model).await?; + } + } + Ok(()) + } + /// Requires the payment channel for `model` while the ledger prices it, + /// and withdraws the requirement otherwise. + async fn require_model(&self, model: &str) -> Result<()> { + let paid = self.ledger.paid_price(model)?.is_some(); + if let Some(context) = &self.context { + let required: &[(&str, &[u8])] = if paid { &[(CHANNEL, &[])] } else { &[] }; + return context + .clone() + .require_channels_for_model(model, required) + .await; + } + #[cfg(test)] + { + ensure!( + !self.unreachable.load(std::sync::atomic::Ordering::SeqCst), + "host unreachable" + ); + self.requirements.lock().unwrap().push((model.into(), paid)); + Ok(()) + } + #[cfg(not(test))] + bail!("host context unavailable") + } + /// Sends `model`'s requirement, keeping it for the next retry tick when + /// the host does not accept it. + async fn sync_model(&self, unsynced: &mut BTreeSet, model: &str) -> Result<()> { + let result = self.require_model(model).await; + if result.is_ok() { + unsynced.remove(model); + } else { + unsynced.insert(model.into()); + } + result + } + /// Re-sends the channel requirements the host has not accepted yet. + pub(crate) async fn resync_requirements(&self) -> Result<()> { + let mut unsynced = self.unsynced.lock().await; + for model in unsynced.clone() { + self.sync_model(&mut unsynced, &model).await?; + } + Ok(()) + } + /// Sets, or with `None` removes, a model's seller price together with + /// its channel requirement; removal also drops its admission deposit. + pub async fn set_pricing(&self, model: &str, price: Option<&Price>) -> Result<()> { + ensure!( + price.is_none_or(Price::is_free) || !self.wallet_info.is_absent(), + NEEDS_WALLET + ); + let mut unsynced = self.unsynced.lock().await; + self.ledger.set_pricing(model, price)?; + self.sync_model(&mut unsynced, model).await + } + /// Changes only the cached-input discount of an already priced model. + pub async fn set_cache_discount(&self, model: &str, percent: u8) -> Result<()> { + let mut unsynced = self.unsynced.lock().await; + self.ledger.set_cache_discount(model, percent)?; + self.sync_model(&mut unsynced, model).await + } + /// Whether the policy allows paid buying now and `peer` is an allowed + /// seller: any seller unless `buy_peers` lists some. + fn buys_from(&self, peer: &str) -> Result { + let peers = &self.config.buy_peers; + Ok(self.ledger.policy()?.budget().is_some() && (peers.is_empty() || peers.contains(peer))) + } + fn peer_lock(&self, peer: &str) -> Result>> { + let mut peers = self.peers.lock().unwrap(); + if !peers.contains_key(peer) && peers.len() >= 4096 { + // A held or queued lock has another Arc and must remain shared. + peers.retain(|_, lock| Arc::strong_count(lock) > 1); + } + ensure!( + peers.contains_key(peer) || peers.len() < 4096, + "peer coordination capacity exhausted" + ); + Ok(peers.entry(peer.into()).or_default().clone()) + } +} +/// Why a node without a wallet refuses paid settings. +pub(crate) const NEEDS_WALLET: &str = + "prices and automatic buying need a wallet; run `tempo wallet init`, fund it and restart"; + +fn allow() -> OpenAiExchangeDecision { + OpenAiExchangeDecision { + decision: OpenAiAdmissionDecision::Allow, + ..Default::default() + } +} +fn deny(reason: &str) -> OpenAiExchangeDecision { + OpenAiExchangeDecision { + decision: OpenAiAdmissionDecision::Deny, + status: Some(402), + reason: Some(reason.into()), + ..Default::default() + } +} diff --git a/src/engine_admission.rs b/src/engine_admission.rs new file mode 100644 index 0000000..9fbb405 --- /dev/null +++ b/src/engine_admission.rs @@ -0,0 +1,216 @@ +//! The buyer's admission hook: whether a request is paid, the wait for the +//! pair's slot and the seller's answer, and cancelling what is not dispatched. +use super::*; +use crate::{ + ledger::{ChannelState, Request as Row, State}, + protocol::{Intent, Step as Wire}, +}; +use mpp::request_intent; + +/// How long the buyer's admission hook waits for a channel open or top-up +/// to finalize, inside the host's 30-second hook deadline. +const ADMISSION_WAIT_SECONDS: u64 = 25; +/// How often the buyer says hello again while the seller answers busy, for +/// example until its channel is open or a voucher paying a bill arrived. +const BUSY_RETRY_MILLIS: u64 = 250; +/// Why a buyer request closed when the seller serves its model free. +pub(super) const SERVED_FREE: &str = + "the seller has no paid price for this model; sent as a free request"; +/// The request IDs the buyer minted, by host observation, for tests. +#[cfg(test)] +pub(super) static MINTED: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +impl Engine { + /// Pays for a request when buyer policy says so: automatic buying and an + /// allowed seller. Every other request takes the free path, as does one + /// whose model the seller does not price. + pub(super) async fn mpp_buyer_hook(&self, event: &Value) -> Result { + if event["requested_by_node_id"].is_string() { + return Ok(Default::default()); + } + let Some(peer) = event["target_peer_id"].as_str() else { + return Ok(Default::default()); + }; + if !self.buys_from(peer)? { + return Ok(Default::default()); + } + Ok(match self.mpp_admit_buyer(peer, event).await { + Ok(true) => allow(), + Ok(false) => Default::default(), + Err(error) => deny(&error.to_string()), + }) + } + /// Negotiates the request under a newly minted ID until it can be + /// dispatched; `false` means the seller serves the model free. + async fn mpp_admit_buyer(&self, peer: &str, event: &Value) -> Result { + let intent = request_intent(event, &self.wallet_info.address)?; + let observation = serving::correlation(event)?; + ensure!(self.wallet_info.can_send, "buyer wallet locked"); + // Only an identical request, the channel open and a top-up wait; + // everything else is quick. + let deadline = + tokio::time::Instant::now() + std::time::Duration::from_secs(ADMISSION_WAIT_SECONDS); + self.buyer_await_slot(peer, &intent.body_digest, deadline) + .await?; + let id = uuid::Uuid::new_v4().to_string(); + let mut row = Row::new(id.clone(), peer.into(), false, intent.clone()); + row.observation = Some(observation.into()); + self.ledger.mpp_insert(&row)?; + #[cfg(test)] + MINTED + .lock() + .unwrap() + .insert(observation.into(), id.clone()); + let attachment = BuyerAttachment { + engine: self, + id: id.clone(), + observation: observation.into(), + }; + let result = self + .buyer_await_dispatch(peer, &id, intent, observation, deadline) + .await; + if let Err(error) = &result + && let Err(cancel) = self.buyer_abandon(peer, &id, &error.to_string()).await + { + tracing::warn!("cannot cancel the undispatched MPP request: {cancel}"); + } + drop(attachment); + result + } + /// Waits while a request to this seller with the same body holds its + /// slot, whose own usage usually arrives just after the response, or + /// while the buyer's first request to it opens the channel. + async fn buyer_await_slot( + &self, + peer: &str, + body_digest: &str, + deadline: tokio::time::Instant, + ) -> Result<()> { + loop { + let open = self + .ledger + .channel_active(peer, false)? + .is_some_and(|c| c.state == ChannelState::Open); + let waits = self.ledger.mpp_active()?.iter().any(|r| { + !r.seller + && r.peer == peer + && r.holds_peer() + && (!open || r.intent.body_digest == body_digest) + }); + if !waits { + return Ok(()); + } + ensure!( + tokio::time::Instant::now() < deadline, + "a paid request to this provider with the same body, or one opening its channel, is still in flight" + ); + tokio::select! {_=self.changed.notified()=>{},_=tokio::time::sleep(std::time::Duration::from_millis(100))=>{}} + } + } + /// Says hello again after a busy answer, at most every `BUSY_RETRY_MILLIS`. + async fn buyer_retry_busy( + &self, + peer: &str, + row: &Row, + hello_at: &mut tokio::time::Instant, + ) -> Result<()> { + let pace = std::time::Duration::from_millis(BUSY_RETRY_MILLIS); + if hello_at.elapsed() < pace { + return Ok(()); + } + self.ledger.mpp_update(&row.id, |r| { + r.busy = false; + Ok(()) + })?; + *hello_at = tokio::time::Instant::now(); + let intent = row.intent.clone(); + self.mpp_send(peer, &row.id, Wire::Hello { intent }).await + } + async fn buyer_await_dispatch( + &self, + peer: &str, + id: &str, + intent: Intent, + observation: &str, + deadline: tokio::time::Instant, + ) -> Result { + self.mpp_send(peer, id, Wire::Hello { intent }).await?; + let mut hello_at = tokio::time::Instant::now(); + loop { + let row = self.ledger.mpp_get(id)?.context("request disappeared")?; + if row.state == State::Closed { + if row.error.as_deref() == Some(SERVED_FREE) { + return Ok(false); + } + bail!("{}", row.error.as_deref().unwrap_or("request is closed")); + } + if row.state == State::Ready { + ensure!( + row.terms.as_ref().is_some_and(|t| t.expires_at > now()), + "quote expired before dispatch; any voucher stays as channel credit" + ); + self.ledger.mpp_update(id, |r| { + ensure!( + r.state == State::Ready && r.observation.as_deref() == Some(observation), + "request consumed concurrently" + ); + r.state = State::Running; + Ok(()) + })?; + return Ok(true); + } + ensure!( + row.state == State::Negotiating, + "request is no longer awaiting its channel" + ); + if row.busy { + self.buyer_retry_busy(peer, &row, &mut hello_at).await?; + } + if tokio::time::Instant::now() >= deadline { + bail!( + "{}; the request was cancelled and may be sent again", + if row.busy { + "the provider is still busy" + } else { + "the payment channel is not ready yet" + } + ); + } + tokio::select! {_=self.changed.notified()=>{},_=tokio::time::sleep(std::time::Duration::from_millis(100))=>{}} + } + } + /// Cancels a request that will not be dispatched, so it does not hold + /// the seller's slot for its body or delay its channel. + async fn buyer_abandon(&self, peer: &str, id: &str, reason: &str) -> Result<()> { + let serial = self.peer_lock(peer)?; + let _guard = serial.lock().await; + let row = self.ledger.mpp_get(id)?.context("unknown MPP request")?; + if matches!(row.state, State::Negotiating | State::Ready) { + self.buyer_refuse(&row, reason).await?; + } + Ok(()) + } +} +/// Detaches an undispatched request from its HTTP request when the hook +/// ends, also when the host drops it; the retry tick then cancels it. +struct BuyerAttachment<'a> { + engine: &'a Engine, + id: String, + observation: String, +} +impl Drop for BuyerAttachment<'_> { + fn drop(&mut self) { + let result = self.engine.ledger.mpp_update(&self.id, |r| { + if matches!(r.state, State::Negotiating | State::Ready) + && r.observation.as_deref() == Some(&self.observation) + { + r.observation = None; + } + Ok(()) + }); + if let Err(error) = result { + tracing::error!("cannot detach MPP request: {error}"); + } + } +} diff --git a/src/engine_bond_tests.rs b/src/engine_bond_tests.rs new file mode 100644 index 0000000..7aef816 --- /dev/null +++ b/src/engine_bond_tests.rs @@ -0,0 +1,145 @@ +//! The published bond reference and a node without a wallet. +use super::*; + +/// A seller using the network's escrow. +fn bonded() -> (tempfile::TempDir, Arc, Arc) { + let dir = tempfile::tempdir().unwrap(); + let chain = Arc::new(Chain::default()); + let mut seller = engine(dir.path(), true, chain.clone()); + let escrow = crate::contract::Network::Testnet + .bond_escrow() + .map(Into::into); + Arc::get_mut(&mut seller).unwrap().config.bonds.contract = escrow; + (dir, chain, seller) +} +fn attempt(operation: &str, kind: &str, bond: &str, status: &str) -> Value { + json!({"id":operation,"intent":{"kind":kind},"bond_id":bond,"status":status}) +} +fn published(seller: &Engine) -> Vec> { + let published = seller.published.lock().unwrap(); + published + .iter() + .map(|p| p.as_ref().map(|p| p.bond_id.clone())) + .collect() +} + +#[tokio::test] +async fn a_finalized_lock_is_published_once_and_withdrawn_with_its_bond() { + let (_dir, chain, seller) = bonded(); + let (first, second) = ( + format!("0x{}", "aa".repeat(32)), + format!("0x{}", "bb".repeat(32)), + ); + chain + .attempts + .lock() + .unwrap() + .push(attempt("one", "lock", &first, "pending")); + seller.retry().await.unwrap(); + assert!(published(&seller).is_empty()); + assert_eq!(seller.newest_bond().unwrap(), None); + *chain.attempts.lock().unwrap() = vec![attempt("one", "lock", &first, "finalized")]; + seller.retry().await.unwrap(); + seller.retry().await.unwrap(); + assert_eq!(published(&seller), [Some(first.clone())]); + // The operator withdraws the reference; the same lock is not published again. + seller.set_published_bond(None).await.unwrap(); + seller.retry().await.unwrap(); + assert_eq!(published(&seller), [Some(first.clone()), None]); + // A newer lock replaces it, and its withdrawal withdraws the reference. + chain + .attempts + .lock() + .unwrap() + .push(attempt("two", "lock", &second, "finalized")); + seller.retry().await.unwrap(); + chain + .attempts + .lock() + .unwrap() + .push(attempt("three", "withdraw", &second, "finalized")); + seller.retry().await.unwrap(); + assert_eq!( + published(&seller), + [Some(first), None, Some(second.clone()), None] + ); + // Exits default to the newest lock even after its reference is withdrawn. + assert_eq!(seller.newest_bond().unwrap(), Some(second)); + assert_eq!(seller.ledger.published_bond().unwrap(), None); +} + +#[tokio::test] +async fn an_exited_bond_is_withdrawn_once_its_delay_has_passed() { + let (_dir, chain, seller) = bonded(); + let bond = format!("0x{}", "aa".repeat(32)); + let exit = |after: u64| json!({"id":"exit","intent":{"kind":"request_exit"},"bond_id":bond,"withdraw_after":after,"status":"finalized"}); + chain + .attempts + .lock() + .unwrap() + .push(exit(crate::config::now() + 60)); + seller.retry().await.unwrap(); + assert!(chain.bonds.lock().unwrap().is_empty()); + *chain.attempts.lock().unwrap() = vec![exit(crate::config::now())]; + seller.retry().await.unwrap(); + let withdrawal = ( + crate::bonds::exit_operation("withdraw", &bond).unwrap(), + crate::bonds::Intent::Withdraw { + bond_id: bond.clone(), + }, + ); + assert_eq!(*chain.bonds.lock().unwrap(), [withdrawal]); + // Once the withdrawal finalizes, the bond is not withdrawn again. + chain + .attempts + .lock() + .unwrap() + .push(attempt("refund", "withdraw", &bond, "finalized")); + seller.retry().await.unwrap(); + assert_eq!(chain.bonds.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn a_publication_the_host_refused_is_repeated_on_the_next_tick() { + let (_dir, _chain, seller) = bonded(); + let bond = format!("0x{}", "aa".repeat(32)); + seller.unreachable.store(true, Ordering::SeqCst); + assert!(seller.set_published_bond(Some(&bond)).await.is_err()); + assert!(seller.retry().await.is_err()); + seller.unreachable.store(false, Ordering::SeqCst); + seller.retry().await.unwrap(); + seller.retry().await.unwrap(); + assert_eq!(published(&seller), [Some(bond)]); + assert!(seller.set_published_bond(Some("not-a-bond")).await.is_err()); +} + +#[tokio::test] +async fn a_node_without_a_wallet_refuses_prices_and_creates_its_wallet_on_first_use() { + let dir = tempfile::tempdir().unwrap(); + let state = tempfile::tempdir().unwrap(); + let network = crate::contract::Network::Testnet; + let absent = crate::contract::WalletInfo::absent(network); + let db = Ledger::open(state.path()).unwrap().db.clone(); + let unopened = Arc::new(crate::wallet::Unopened::new( + Default::default(), + state.path(), + db, + )); + let node = engine_with_wallet(dir.path(), true, unopened.clone(), absent, 0); + let refused = node.set_pricing("model", Some(&price(1))).await; + assert!(refused.unwrap_err().to_string().contains("need a wallet")); + node.set_pricing("model", Some(&price(0))).await.unwrap(); + let balance = node.wallet.balance().await.unwrap_err(); + assert!(balance.to_string().contains("no wallet yet"), "{balance}"); + // The retry tick has nothing to reconcile or publish. + node.retry().await.unwrap(); + assert!(!state.path().join("wallet.json").exists()); + // The first `fund` or `bond_lock` creates an unlocked wallet with a + // private random password. + let wallet = unopened.open().await.unwrap(); + assert!(wallet.signer.is_some()); + let password = crate::tempo::keys::generated_password(state.path()); + crate::tempo::keys::private_file(&password).unwrap(); + assert!(state.path().join("wallet.json").exists()); + assert!(std::ptr::eq(wallet, unopened.open().await.unwrap())); +} diff --git a/src/engine_bonds.rs b/src/engine_bonds.rs new file mode 100644 index 0000000..4e73c44 --- /dev/null +++ b/src/engine_bonds.rs @@ -0,0 +1,127 @@ +//! The node's published bond reference: set when a bond lock finalizes or +//! by the operator, withdrawn with its bond, and sent again until the host +//! accepts it. Bonds this wallet exits are withdrawn once their delay passes. +use super::*; +use std::sync::atomic::Ordering::SeqCst; + +impl Engine { + /// Publishes the current reference, or withdraws it when there is none. + pub async fn publish_bond(&self) -> Result<()> { + let bond = self.ledger.published_bond()?; + let evidence = self.bonds.proof(&self.config.bonds, bond.as_deref())?; + let result = self.send_evidence(evidence).await; + self.bond_unsynced.store(result.is_err(), SeqCst); + result + } + async fn send_evidence(&self, evidence: Option) -> Result<()> { + if let Some(context) = &self.context { + let _: Value = context + .clone() + .request_host( + "PublishPeerEvidence", + serde_json::json!({ "evidence": evidence }), + ) + .await?; + return Ok(()); + } + #[cfg(test)] + { + ensure!(!self.unreachable.load(SeqCst), "host unreachable"); + self.published.lock().unwrap().push(evidence); + Ok(()) + } + #[cfg(not(test))] + bail!("host context unavailable") + } + /// Publishes `bond_id`, or withdraws the reference with `None`. + pub async fn set_published_bond(&self, bond_id: Option<&str>) -> Result<()> { + self.bonds.proof(&self.config.bonds, bond_id)?; + self.ledger.set_published_bond(bond_id)?; + self.publish_bond().await + } + /// Withdraws each bond whose exit this wallet requested, once its delay + /// has passed, into the wallet. The wallet refuses a withdrawal before + /// the finalized chain reaches the deadline, without signing, so an + /// early try is repeated on a later tick. + async fn sweep_exits(&self) -> Result<()> { + let attempts = self.wallet.attempts()?; + let finalized = |kind: &'static str| { + attempts + .iter() + .filter(move |a| a["intent"]["kind"] == kind && a["status"] == "finalized") + }; + for exit in finalized("request_exit") { + let bond = exit["bond_id"] + .as_str() + .context("bond exit without a bond")?; + let withdrawn = finalized("withdraw").any(|a| { + a["bond_id"] + .as_str() + .is_some_and(|w| w.eq_ignore_ascii_case(bond)) + }); + let due = exit["withdraw_after"].as_u64().is_none_or(|at| now() >= at); + if withdrawn || !due { + continue; + } + let operation = crate::bonds::exit_operation("withdraw", bond)?; + let intent = crate::bonds::Intent::Withdraw { + bond_id: bond.into(), + }; + if let Err(error) = self + .wallet + .bond(&self.config.bonds, &operation, intent) + .await + { + tracing::debug!(bond, %error, "bond withdrawal not possible yet"); + } + } + Ok(()) + } + /// The bond of the newest finalized lock. + pub(crate) fn newest_bond(&self) -> Result> { + let attempts = self.wallet.attempts()?; + Ok(attempts + .iter() + .rev() + .find(|a| a["intent"]["kind"] == "lock" && a["status"] == "finalized") + .and_then(|a| a["bond_id"].as_str()) + .map(Into::into)) + } + /// Publishes the newest finalized bond lock once, withdraws the + /// reference once its bond is withdrawn, and repeats a publication the + /// host refused. + pub(crate) async fn sync_bond(&self) -> Result<()> { + self.sweep_exits().await?; + let attempts = self.wallet.attempts()?; + let finalized = |kind: &'static str| { + attempts + .iter() + .filter(move |a| a["intent"]["kind"] == kind && a["status"] == "finalized") + }; + if let Some(lock) = finalized("lock").next_back() { + let operation = lock["id"].as_str().context("bond lock without an ID")?; + if self.ledger.published_lock()?.as_deref() != Some(operation) { + let bond = lock["bond_id"] + .as_str() + .context("bond lock without a bond")?; + self.ledger.set_published_lock(operation)?; + return self.set_published_bond(Some(bond)).await; + } + } + let published = self.ledger.published_bond()?; + let withdrawn = published.as_ref().is_some_and(|id| { + finalized("withdraw").any(|a| { + a["bond_id"] + .as_str() + .is_some_and(|w| w.eq_ignore_ascii_case(id)) + }) + }); + if withdrawn { + return self.set_published_bond(None).await; + } + if self.bond_unsynced.load(SeqCst) { + return self.publish_bond().await; + } + Ok(()) + } +} diff --git a/src/engine_buyer_tests.rs b/src/engine_buyer_tests.rs new file mode 100644 index 0000000..71863e2 --- /dev/null +++ b/src/engine_buyer_tests.rs @@ -0,0 +1,305 @@ +//! Buyer budget, cap and channel-view checks against the in-memory engine pair. +use super::*; + +#[tokio::test] +async fn daily_budget_counts_voucher_increments_and_bounds_the_worst_case() { + let (_bd, _sd, chain, buyer, seller) = pair(); + // The first request signs the upfront of 10 and could need a worst-case + // bill of W; the second has 5 of credit left, so W + 5 fits both. + let w = worst(&uuid::Uuid::nil().to_string()); + buyer.ledger.set_policy(&automatic(w + 5)).unwrap(); + paid_request(&buyer, &seller, usage(1, 4)).await; + paid_request(&buyer, &seller, usage(1, 4)).await; + assert_eq!(buyer.ledger.spent_today().unwrap(), 10); + // A third worst-case bill would raise the voucher by W, beyond what remains. + let id = uuid::Uuid::new_v4().to_string(); + let decision = decide(&buyer, &seller, event(&id)).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!( + decision + .reason + .unwrap() + .contains("worst-case cost: daily budget") + ); + assert_eq!(buyer.ledger.spent_today().unwrap(), 10); + assert_eq!(channel(&buyer).cum(), 10); + assert_eq!(Chain::count(&chain.signs), 1); + assert_eq!(row(&seller, &id).state, State::Closed); +} + +#[tokio::test] +async fn the_worst_case_must_fit_the_cap_before_anything_is_opened_or_signed() { + let (_bd, _sd, chain, mut buyer, seller) = pair(); + let w = worst(&uuid::Uuid::nil().to_string()); + // Upfront 10 plus a worst-case bill's increment of W - 10 is W. + Arc::get_mut(&mut buyer).unwrap().config.cap = w - 1; + let decision = decide(&buyer, &seller, event(&uuid::Uuid::new_v4().to_string())).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!( + decision + .reason + .unwrap() + .contains("worst-case cost: payment exceeds the per-request cap") + ); + assert_eq!(Chain::count(&chain.opens), 0); + assert_eq!(Chain::count(&chain.signs), 0); + Arc::get_mut(&mut buyer).unwrap().config.cap = w; + admit(&buyer, &seller, &uuid::Uuid::new_v4().to_string()).await; +} + +#[tokio::test] +async fn a_seller_behind_on_vouchers_gets_the_latest_without_another_upfront() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = paid_request(&buyer, &seller, usage(1, 4)).await; + // A voucher for 12 that the seller never received. + let open = channel(&buyer); + let lost = Voucher { + channel_id: open.funding.unwrap().channel_id, + cum: 12, + signature: "signed-12".into(), + }; + buyer + .ledger + .mpp_update_both(&rid(&id), &open.key, 10000, |_, c| { + c.voucher = Some(lost); + Ok(()) + }) + .unwrap(); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + let quote = row(&seller, &next).terms.unwrap(); + assert_eq!((quote.cum_before, quote.upfront), (10, 0)); + assert_eq!(channel(&buyer).state, ChannelState::Open); + assert_eq!(channel(&seller).cum(), 12); + assert_eq!(buyer.ledger.spent_today().unwrap(), 12); + assert_eq!(Chain::count(&chain.signs), 1); + assert_eq!(Chain::count(&chain.opens), 1); +} + +#[tokio::test] +async fn a_lost_first_voucher_reuses_the_channel_the_seller_never_saw() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + let quotes: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + for (_, message) in quotes { + buyer.message(&seller.node, message).await.unwrap(); + } + buyer.outbox.lock().unwrap().clear(); + assert_eq!(channel(&buyer).cum(), 10); + buyer + .ledger + .mpp_update(&rid(&id), |r| { + r.terms.as_mut().unwrap().expires_at = now() - 1; + Ok(()) + }) + .unwrap(); + buyer.retry().await.unwrap(); + seller.mpp_close(&id, "expired").unwrap(); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + let quote = row(&seller, &next).terms.unwrap(); + assert_eq!((quote.channel_id, quote.upfront), (None, 10)); + assert_eq!(channel(&seller).key, channel(&buyer).key); + assert_eq!(channel(&seller).cum(), 10); + assert_eq!(buyer.ledger.spent_today().unwrap(), 10); + assert_eq!(Chain::count(&chain.signs), 1); + assert_eq!(Chain::count(&chain.opens), 1); +} + +#[tokio::test] +async fn a_seller_voucher_above_the_buyers_own_is_refused() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let open = channel(&seller); + let forged = Voucher { + channel_id: open.funding.clone().unwrap().channel_id, + cum: 15, + signature: "signed-15".into(), + }; + seller + .ledger + .channel_update(&open.key, |c| { + c.voucher = Some(forged); + Ok(()) + }) + .unwrap(); + let decision = decide(&buyer, &seller, event(&uuid::Uuid::new_v4().to_string())).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!( + decision + .reason + .unwrap() + .contains("view of the channel differs") + ); + assert_eq!(channel(&buyer).state, ChannelState::Closing); +} + +/// Delivers a quote for a new request with its upfront replaced, as a +/// dishonest seller would send it, and returns the request and whether the +/// buyer answered with a voucher. +async fn tampered_quote(buyer: &Engine, seller: &Engine, upfront: u64) -> (String, bool) { + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + let quotes: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + for (_, mut message) in quotes { + if let Message::Mpp { message, .. } = &mut message + && let Wire::Quote { terms } = message.as_mut() + { + terms.upfront = upfront; + } + buyer.message(&seller.node, message).await.unwrap(); + } + let voucher = buyer.outbox.lock().unwrap().iter().any(|(_, m)| { + matches!(m, Message::Mpp { message, .. } if matches!(message.as_ref(), Wire::Voucher { .. })) + }); + pump(buyer, seller).await.unwrap(); + (id, voucher) +} + +#[tokio::test] +async fn a_seller_cannot_charge_the_upfront_again_but_may_refill_credit_to_the_limit() { + let (_bd, _sd, chain, buyer, seller) = pair(); + // Voucher 10 and bills 5 leave 5 of credit; the admission deposit is 10. + paid_request(&buyer, &seller, usage(1, 4)).await; + for _ in 0..3 { + let (id, voucher) = tampered_quote(&buyer, &seller, 10).await; + assert!(!voucher); + assert!(row(&buyer, &id).error.unwrap().contains("unbilled credit")); + assert_eq!(row(&seller, &id).state, State::Closed); + } + assert_eq!(channel(&buyer).cum(), 10); + assert_eq!(buyer.ledger.spent_today().unwrap(), 10); + // An upfront of 5 brings the credit back to exactly 10. + let (id, voucher) = tampered_quote(&buyer, &seller, 5).await; + assert!(voucher); + assert_eq!(channel(&buyer).cum(), 15); + assert_eq!(channel(&seller).cum(), 15); + assert_eq!(row(&seller, &id).state, State::Ready); + assert_eq!(Chain::count(&chain.signs), 2); +} + +#[tokio::test] +async fn the_seller_requires_a_voucher_covering_its_view_and_the_upfront() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let open = channel(&seller); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + seller.outbox.lock().unwrap().clear(); + // A voucher for the bills alone (5) is below the seller's view of 10. + let stale = Voucher { + channel_id: open.funding.clone().unwrap().channel_id, + cum: 5, + signature: "signed-5".into(), + }; + let funding = open.funding.unwrap(); + let refused = seller + .message( + &buyer.node, + mpp( + &id, + Wire::Voucher { + funding, + voucher: stale, + }, + ), + ) + .await + .unwrap_err(); + assert!( + refused + .to_string() + .contains("does not cover the quoted voucher") + ); + assert_eq!(row(&seller, &id).state, State::Negotiating); +} + +#[tokio::test] +async fn work_dispatched_before_a_switch_to_free_only_is_still_paid() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + buyer.ledger.set_policy(&Policy::default()).unwrap(); + // 24 is more than the 5 of credit left, so the buyer must sign. + finish(&buyer, &seller, &id, usage(20, 4), false).await; + let paid = row(&buyer, &id); + assert_eq!((paid.state, paid.error), (State::Closed, None)); + assert_eq!(row(&seller, &id).state, State::Closed); + // New requests now go free. + assert_eq!(channel(&buyer).cum(), 29); + let decision = decide(&buyer, &seller, event(&uuid::Uuid::new_v4().to_string())).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Abstain); +} + +#[tokio::test] +async fn a_prompt_beyond_the_body_bound_is_billed_at_the_worst_case() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let w = worst(&id); + admit(&buyer, &seller, &id).await; + // W input tokens and 4 output tokens would charge W + 4; the seller + // caps the bill at the worst case W, and the buyer pays it. + finish(&buyer, &seller, &id, usage(w, 4), false).await; + let paid = row(&buyer, &id); + assert_eq!(paid.state, State::Closed); + assert!(paid.error.is_none()); + assert_eq!(paid.bill.unwrap().cost, w); + assert_eq!(channel(&buyer).state, ChannelState::Open); + assert_eq!(channel(&buyer).cum(), w.max(10)); + assert_eq!(channel(&seller).running_total, w); + assert_eq!(Chain::count(&chain.signs), 2); +} + +#[tokio::test] +async fn a_bill_above_the_worst_case_is_refused() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let w = worst(&id); + admit(&buyer, &seller, &id).await; + terminal(&buyer, "buyer", &id, &usage(w, 4)).await; + let own = row(&buyer, &id).usage.unwrap(); + let bill = Bill { + seq: 0, + usage: Some(own), + cost: w + 4, + running_total: w + 4, + }; + buyer + .message(&seller.node, mpp(&rid(&id), Wire::Bill(bill))) + .await + .unwrap(); + let refused = row(&buyer, &id); + assert!(refused.error.unwrap().contains("cost differs")); + assert_eq!(channel(&buyer).cum(), 10); + assert_eq!(Chain::count(&chain.signs), 1); +} + +#[tokio::test] +async fn only_a_new_or_higher_voucher_is_verified_on_chain_at_admission() { + let (_bd, _sd, chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let verified = Chain::count(&chain.verifies); + assert_eq!(verified, 1); + // The next request presents the voucher the seller already stores. + let id = paid_request(&buyer, &seller, usage(1, 4)).await; + assert_eq!(row(&seller, &id).cum_after, Some(10)); + assert_eq!(Chain::count(&chain.verifies), verified); + // A refill of the credit to 15 is a higher voucher. + let (id, voucher) = tampered_quote(&buyer, &seller, 5).await; + assert!(voucher); + assert_eq!(row(&seller, &id).state, State::Ready); + assert_eq!(Chain::count(&chain.verifies), verified + 1); +} diff --git a/src/engine_channel.rs b/src/engine_channel.rs new file mode 100644 index 0000000..13b25a3 --- /dev/null +++ b/src/engine_channel.rs @@ -0,0 +1,498 @@ +//! The lifecycle of each buyer-seller channel: buyer open, top-up and +//! recovery; seller watch and close. +use super::*; +use crate::contract::mpp::{ChannelTerms, Closure, Request, RequestTerms, Voucher}; +use crate::ledger::{Channel, ChannelState, Request as Row, State}; + +/// Seconds a seller waits after first sending a bill for a voucher covering it. +pub(super) const BILL_PAYMENT_SECONDS: u64 = 120; +/// After the buyer's close request, a running request may still be billed +/// for this long, well inside the 900 s grace before the buyer can withdraw. +const CLOSE_DEFER_SECONDS: u64 = 600; +/// A buyer stops waiting for the bill of a dispatched request this long +/// after its quote expired. +pub(super) const UNBILLED_SECONDS: u64 = 3600; +/// A seller closes a channel that served no request for this long. +const SELLER_IDLE_SECONDS: u64 = 3600; +/// A buyer recovers a channel that served no request for this long. +const BUYER_IDLE_SECONDS: u64 = 7200; +/// Every open seller channel is inspected at least this often, as a backstop +/// against gaps in the close-event logs, well inside the 900 s grace. +const WATCH_BACKSTOP_SECONDS: u64 = 120; +/// Blocks each close-event scan reads again before its cursor. +const CLOSE_LOG_OVERLAP: u64 = 16; + +/// Which open seller channels the retry tick inspects on chain. +#[derive(Default)] +pub(super) struct Watch { + /// Channels named in close events or seen with a close request; they are + /// inspected every tick until an inspection shows no close request. + pub(super) pending: std::collections::BTreeSet, + /// When every channel was last inspected. + pub(super) polled_at: u64, +} + +impl Engine { + /// The open seller channels this tick inspects, or `None` for all of them: + /// those named in close events since the last complete scan and those + /// still pending. Every channel is inspected on a backstop tick and after + /// a failed or skipped scan, which leaves the cursor where it was. + pub(super) async fn seller_watch_list( + &self, + open: &[Channel], + ) -> Result>> { + if open.is_empty() { + return Ok(Some(Default::default())); + } + let from = self.ledger.close_cursor()?; + let from = from.map(|block| block.saturating_sub(CLOSE_LOG_OVERLAP)); + let named = match self.wallet.close_events(from).await { + Ok(events) => { + self.ledger.set_close_cursor(events.to)?; + (!events.skipped).then_some(events.channels) + } + Err(error) => { + tracing::warn!("close event scan failed; inspecting every channel: {error}"); + None + } + }; + let mut watch = self.watch.lock().unwrap(); + let backstop = now() >= watch.polled_at.saturating_add(WATCH_BACKSTOP_SECONDS); + let Some(named) = named.filter(|_| !backstop) else { + watch.polled_at = now(); + return Ok(None); + }; + for c in open { + let id = c + .funding + .as_ref() + .map(|f| f.channel_id.to_ascii_lowercase()); + if id.is_some_and(|id| named.contains(&id)) { + watch.pending.insert(c.key.clone()); + } + } + Ok(Some( + open.iter() + .filter(|c| watch.pending.contains(&c.key)) + .map(|c| c.key.clone()) + .collect(), + )) + } + /// Whether the seller's idle close may be due, which needs no chain read + /// to decide. + pub(super) fn seller_idle_due(c: &Channel) -> bool { + now() >= c.active_at.saturating_add(SELLER_IDLE_SECONDS) + } + /// Keeps a channel with a close request on the per-tick list. + fn watch_close_request(&self, key: &str, requested: bool) { + let mut watch = self.watch.lock().unwrap(); + if requested { + watch.pending.insert(key.into()); + } else { + watch.pending.remove(key); + } + } + pub(crate) async fn channel_retry_one(&self, key: &str) -> Result<()> { + let channel = self.ledger.channel_get(key)?.context("unknown channel")?; + let serial = self.peer_lock(&channel.peer)?; + let _guard = serial.lock().await; + self.channel_progress(key).await + } + /// Drives pending chain work and idle timeouts of one channel. + pub(super) async fn channel_progress(&self, key: &str) -> Result<()> { + let channel = self.ledger.channel_get(key)?.context("unknown channel")?; + match (channel.seller, &channel.state) { + (_, ChannelState::Closed) | (true, ChannelState::Opening) => {} + (false, ChannelState::Opening) => { + self.buyer_open(&channel).await?; + } + (false, ChannelState::Open) => { + if now() >= channel.active_at.saturating_add(BUYER_IDLE_SECONDS) { + self.ledger.channel_update(key, |c| { + c.state = ChannelState::Closing; + c.error = Some("idle; recovering the deposit".into()); + Ok(()) + })?; + self.buyer_recover(key).await?; + } + } + (false, ChannelState::Closing) => self.buyer_recover(key).await?, + (true, ChannelState::Open) => self.seller_watch(channel).await?, + (true, ChannelState::Closing) => self.seller_close(channel).await?, + } + self.changed.notify_waiters(); + Ok(()) + } + /// Closes the buyer's open channel with the seller `peer`, named by its + /// node ID or a unique prefix of at least eight characters, or without + /// one the only open channel, and returns the seller. The close request + /// on chain makes the seller close; otherwise the buyer withdraws after + /// the grace. + pub async fn buyer_close(&self, peer: Option<&str>) -> Result { + let mut open: Vec = self + .ledger + .channels_active()? + .into_iter() + .filter(|c| !c.seller && matches!(c.state, ChannelState::Open | ChannelState::Closing)) + .collect(); + if let Some(peer) = peer { + ensure!( + peer.len() >= 8, + "name the seller by at least eight characters of its node ID" + ); + let peer = peer.to_ascii_lowercase(); + open.retain(|c| c.peer.starts_with(&peer)); + } + ensure!(!open.is_empty(), "no open channel to close"); + ensure!( + open.len() == 1, + "several open channels; name the seller with peer" + ); + let channel = open.remove(0); + let serial = self.peer_lock(&channel.peer)?; + let _guard = serial.lock().await; + self.ledger.channel_update(&channel.key, |c| { + ensure!( + matches!(c.state, ChannelState::Open | ChannelState::Closing), + "channel is not open" + ); + c.state = ChannelState::Closing; + Ok(()) + })?; + self.channel_progress(&channel.key).await?; + Ok(channel.peer) + } + /// The buyer's open channel with the quoting seller, opening one when + /// none exists. `None` means the open is pending or the request was refused. + pub(super) async fn buyer_channel( + &self, + row: &Row, + terms: &RequestTerms, + ) -> Result> { + let channel = match self.ledger.channel_active(&row.peer, false)? { + Some(channel) => channel, + None => { + let pair = ChannelTerms { + buyer_peer: self.node.clone(), + seller_peer: row.peer.clone(), + payer: self.wallet_info.address.clone(), + payee: terms.payee.clone(), + asset: terms.asset.clone(), + nonce: hex::encode(rand::random::<[u8; 32]>()), + }; + let deposit = self.config.channel_topup; + let channel = Channel::new(pair, row.peer.clone(), false, deposit)?; + self.ledger.channel_insert(&channel)?; + channel + } + }; + match channel.state { + ChannelState::Open => Ok(Some(channel)), + ChannelState::Opening => { + let opened = self.buyer_open(&channel).await?; + if opened.is_none() + && self + .ledger + .channel_get(&channel.key)? + .is_some_and(|c| c.state == ChannelState::Closed) + { + let reason = "the channel open expired unsent or reverted"; + self.buyer_refuse(row, reason).await?; + } + Ok(opened) + } + _ => { + let reason = "the channel is closing; retry after its closure"; + self.buyer_refuse(row, reason).await?; + Ok(None) + } + } + } + /// Drives the open to finality; `None` while it is pending or after it failed. + async fn buyer_open(&self, channel: &Channel) -> Result> { + let response = self + .wallet + .execute(Request::Open { + terms: channel.terms.clone(), + deposit: channel.deposit, + max_fee: self.config.wallet.max_fee, + }) + .await?; + if response.unfunded { + self.ledger.channel_update(&channel.key, |c| { + c.state = ChannelState::Closed; + c.error = + Some("channel open expired unsent or reverted; nothing was deposited".into()); + Ok(()) + })?; + return Ok(None); + } + let Some(funding) = response.funding else { + return Ok(None); + }; + ensure!( + funding.terms == channel.terms, + "wallet changed channel terms" + ); + let opened = self.ledger.channel_update(&channel.key, |c| { + c.funding = Some(funding); + c.deposit = response.deposit; + c.state = ChannelState::Open; + c.active_at = now(); + Ok(c.clone()) + })?; + Ok(Some(opened)) + } + /// The channel once its deposit fits `cum`, topping it up once when + /// needed. `None` means the top-up is pending or the request was refused. + pub(super) async fn buyer_capacity( + &self, + row: &Row, + channel: Channel, + cum: u64, + ) -> Result> { + if cum <= channel.deposit { + return Ok(Some(channel)); + } + let amount = self.config.channel_topup; + if cum > channel.deposit.saturating_add(amount) { + let reason = "one channel top-up cannot cover the next voucher"; + self.buyer_refuse(row, reason).await?; + return Ok(None); + } + let index = channel.topups + 1; + let response = self + .wallet + .execute(Request::TopUp { + funding: channel.funding.clone().context("channel is not open")?, + amount, + index, + max_fee: self.config.wallet.max_fee, + }) + .await?; + if let Some(closure) = response.closure { + self.buyer_record_close(&channel, closure)?; + self.buyer_refuse(row, "the channel closed before its top-up") + .await?; + return Ok(None); + } + if response.pending { + return Ok(None); + } + let channel = self.ledger.channel_update(&channel.key, |c| { + ensure!(c.topups + 1 == index, "top-up recorded concurrently"); + c.topups = index; + c.deposit = response.deposit; + Ok(c.clone()) + })?; + Ok(Some(channel)) + } + /// The channel's voucher for `cum`, signing a new one only when it grows. + pub(super) async fn buyer_voucher(&self, channel: &Channel, cum: u64) -> Result { + if let Some(voucher) = channel.voucher.as_ref().filter(|v| v.cum == cum) { + return Ok(voucher.clone()); + } + self.wallet + .execute(Request::SignVoucher { + funding: channel.funding.clone().context("channel is not open")?, + cum, + }) + .await? + .voucher + .context("wallet returned no voucher") + } + async fn buyer_recover(&self, key: &str) -> Result<()> { + let channel = self.ledger.channel_get(key)?.context("unknown channel")?; + let response = self + .wallet + .execute(Request::Recover { + funding: channel.funding.clone().context("channel never opened")?, + max_fee: self.config.wallet.max_fee, + }) + .await?; + if let Some(closure) = response.closure { + self.buyer_record_close(&channel, closure)?; + } + Ok(()) + } + pub(super) fn buyer_record_close(&self, channel: &Channel, closure: Closure) -> Result<()> { + let reason = "the payment channel closed"; + self.ledger.channel_close(&channel.key, reason, |c| { + ensure!( + c.funding + .as_ref() + .is_some_and(|f| f.channel_id == closure.channel_id), + "closure for another channel" + ); + ensure!( + c.closure.as_ref().is_none_or(|old| *old == closure), + "closure changed" + ); + if closure.captured > c.running_total { + c.error = Some(format!( + "seller captured {} but the buyer acknowledged bills of {}", + closure.captured, c.running_total + )); + } + c.closure = Some(closure); + c.state = ChannelState::Closed; + Ok(()) + }) + } + /// Verifies the seller's close notice on chain before recording it. + pub(super) async fn buyer_closed_notice( + &self, + peer: &str, + channel_id: &str, + closure: Closure, + ) -> Result<()> { + let Some(channel) = self.ledger.channel_active(peer, false)? else { + return Ok(()); + }; + let Some(funding) = channel + .funding + .clone() + .filter(|f| f.channel_id == channel_id) + else { + return Ok(()); + }; + let verified = self + .wallet + .execute(Request::Inspect { funding }) + .await? + .closure + .context("close not finalized")?; + ensure!( + verified == closure, + "close notice differs from chain evidence" + ); + self.buyer_record_close(&channel, verified)?; + self.changed.notify_waiters(); + Ok(()) + } + /// Closes the channel after a close request or idle time, or records the + /// buyer's withdrawal. + async fn seller_watch(&self, channel: Channel) -> Result<()> { + let status = self + .wallet + .execute(Request::Inspect { + funding: channel.funding.clone().context("missing funding")?, + }) + .await?; + // The 600 s deferral is checked again on every tick. + self.watch_close_request( + &channel.key, + status.closure.is_none() && status.close_requested_at > 0, + ); + if let Some(closure) = status.closure { + return self.seller_finish(&channel, closure).await; + } + // The capture is fixed when closing starts, so a running request is + // billed first; its usage is known or unknown once it ends. + let running = self.ledger.mpp_active()?.iter().any(|r| { + r.seller && r.state == State::Running && r.channel.as_ref() == Some(&channel.key) + }); + let reason = if status.close_requested_at > 0 { + if running + && now() + < status + .close_requested_at + .saturating_add(CLOSE_DEFER_SECONDS) + { + return Ok(()); + } + "the buyer requested close" + } else if !running && now() >= channel.active_at.saturating_add(SELLER_IDLE_SECONDS) { + "idle" + } else { + return Ok(()); + }; + self.seller_start_close(&channel.key, reason)?; + let channel = self + .ledger + .channel_get(&channel.key)? + .context("unknown channel")?; + self.seller_close(channel).await + } + fn seller_start_close(&self, key: &str, reason: &str) -> Result<()> { + self.ledger.channel_update(key, |c| { + start_close(c, reason); + Ok(()) + }) + } + async fn seller_close(&self, channel: Channel) -> Result<()> { + let response = self + .wallet + .execute(Request::Close { + funding: channel.funding.clone().context("missing funding")?, + voucher: channel.voucher.clone().filter(|v| v.cum > 0), + capture: channel.capture.context("missing capture")?, + }) + .await?; + if let Some(closure) = response.closure { + self.seller_finish(&channel, closure).await?; + } + Ok(()) + } + async fn seller_finish(&self, channel: &Channel, closure: Closure) -> Result<()> { + let reason = "the payment channel closed before this request was billed and paid"; + // Bills that neither the capture nor the seller's best voucher covers + // count as strikes; a missed withdrawal is not the buyer's fault. + let covered = closure.captured.max(channel.cum()); + let lost = self + .ledger + .mpp_active()? + .iter() + .filter(|r| r.seller && r.channel.as_ref() == Some(&channel.key)) + .filter(|r| r.state == State::Billed) + .filter(|r| r.bill.as_ref().is_some_and(|b| b.running_total > covered)) + .count() as u64; + self.ledger.channel_close(&channel.key, reason, |c| { + ensure!( + c.funding + .as_ref() + .is_some_and(|f| f.channel_id == closure.channel_id), + "closure for another channel" + ); + ensure!( + c.closure.as_ref().is_none_or(|old| *old == closure), + "closure changed" + ); + // A seller offline for the whole grace never fixed a capture, but + // still earned what its best voucher covers of the bills. + let earned = c + .capture + .unwrap_or_else(|| c.cum().min(c.running_total)); + if closure.captured < earned { + c.error = Some(format!( + "the buyer withdrew before the seller's capture: {} earned, {} captured; no second capture will be attempted", + earned, closure.captured + )); + } + if c.closure.is_none() { + c.lost_bills += lost; + } + c.closure = Some(closure.clone()); + c.state = ChannelState::Closed; + Ok(()) + })?; + self.send( + &channel.peer, + &Message::Closed { + version: MPP_VERSION, + channel_id: closure.channel_id.clone(), + closure, + }, + ) + .await + } +} +/// Moves an open seller channel to closing, fixing the capture at the bills +/// the best voucher covers. +pub(super) fn start_close(c: &mut Channel, reason: &str) { + if c.state == ChannelState::Open { + c.state = ChannelState::Closing; + c.capture = Some(c.cum().min(c.running_total)); + c.error = Some(format!("closing: {reason}")); + } +} diff --git a/src/engine_control_tests.rs b/src/engine_control_tests.rs new file mode 100644 index 0000000..c08f7e7 --- /dev/null +++ b/src/engine_control_tests.rs @@ -0,0 +1,125 @@ +//! Payment controls against the in-memory engine pair. +use super::*; +use crate::control::Control; + +async fn control(engine: &Engine, input: Value) -> Result { + serde_json::from_value::(input)? + .run(engine, None) + .await +} + +#[tokio::test] +async fn set_pricing_re_registers_the_model_and_drops_its_deposit() { + let (_bd, _sd, _chain, _buyer, seller) = pair(); + let priced = json!({"command":"set_pricing","model":"other", + "value":{"input_per_million":"5","output_per_million":"6"}}); + control(&seller, priced).await.unwrap(); + let override_deposit = + json!({"command":"set_model_admission_deposit","model":"other","value":"3"}); + let deposits = control(&seller, override_deposit).await.unwrap(); + assert_eq!(deposits["models"], json!({"other":"3"})); + let discount = json!({"command":"set_cache_discount","model":"other","percent":40}); + let pricing = control(&seller, discount).await.unwrap(); + assert_eq!(pricing["prices"]["other"]["cache_discount_percent"], 40); + assert_eq!(pricing["prices"]["other"]["output_per_million"], "6"); + let removed = control(&seller, json!({"command":"set_pricing","model":"other"})) + .await + .unwrap(); + assert!(removed["prices"].get("other").is_none()); + assert_eq!(removed["models"], json!({})); + assert_eq!(removed["admission_deposit"], "10"); + let requirements = seller.requirements.lock().unwrap().clone(); + let expected = [("other", true), ("other", true), ("other", false)]; + assert_eq!( + requirements, + expected.map(|(model, paid)| (model.to_string(), paid)) + ); + // An unpriced model gets no discount and no requirement change. + let unpriced = json!({"command":"set_cache_discount","model":"other","percent":40}); + assert!(control(&seller, unpriced).await.is_err()); + assert_eq!(seller.requirements.lock().unwrap().len(), 3); + // A free price withdraws the requirement too. + seller.set_pricing("model", Some(&price(0))).await.unwrap(); + assert_eq!( + seller.requirements.lock().unwrap().last().unwrap(), + &("model".to_string(), false) + ); +} + +#[tokio::test] +async fn policy_and_admission_deposits_are_shown_and_set() { + let (_bd, _sd, _chain, buyer, _seller) = pair(); + let policy = control(&buyer, json!({"command":"policy"})).await.unwrap(); + assert_eq!(policy["mode"], "automatic"); + assert_eq!(policy["daily_budget"], "10000"); + assert_eq!(policy["spent_today"], "0"); + let set = json!({"command":"policy","value":{"mode":"automatic","daily_budget":"30"}}); + let policy = control(&buyer, set).await.unwrap(); + assert_eq!(policy["remaining_daily_budget"], "30"); + let invalid = json!({"command":"policy","value":{"mode":"automatic"}}); + assert!(control(&buyer, invalid).await.is_err()); + assert_eq!(buyer.ledger.policy().unwrap(), automatic(30)); + let free = json!({"command":"policy","value":{"mode":"free_only"}}); + let policy = control(&buyer, free).await.unwrap(); + assert_eq!(policy["remaining_daily_budget"], "0"); + let set = json!({"command":"admission_deposit","value":"25"}); + let deposits = control(&buyer, set).await.unwrap(); + assert_eq!(deposits["admission_deposit"], "25"); + let both = json!({"command":"admission_deposit","value":"25","reset":true}); + assert!(control(&buyer, both).await.is_err()); + let reset = json!({"command":"admission_deposit","reset":true}); + let deposits = control(&buyer, reset).await.unwrap(); + assert_eq!(deposits["admission_deposit"], "0"); +} + +#[tokio::test] +async fn fund_names_the_wallet_and_pending_and_transactions_list_state() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let fund = control(&buyer, json!({"command":"fund"})).await.unwrap(); + assert_eq!( + fund, + json!({"address":format!("0x{}", "11".repeat(20)),"network":"testnet", + "asset":{"chain_id":42431,"token":crate::contract::OUSD,"decimals":6}}) + ); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + let pending = control(&buyer, json!({"command":"pending"})).await.unwrap(); + assert_eq!(pending["requests"][0]["id"], rid(&id)); + assert_eq!(pending["channels"].as_array().unwrap().len(), 1); + // Voucher signatures never appear in control output. + assert_eq!( + pending["channels"][0]["voucher"], + json!({"channel_id": pending["channels"][0]["funding"]["channel_id"], "cum": "10"}) + ); + finish(&buyer, &seller, &id, usage(1, 4), false).await; + let history = json!({"command":"transactions","limit":1}); + let transactions = control(&buyer, history).await.unwrap(); + assert_eq!(transactions["requests"][0]["state"], "closed"); + assert_eq!(transactions["channels"][0]["running_total"], "5"); + let pending = control(&buyer, json!({"command":"pending"})).await.unwrap(); + assert_eq!(pending["requests"], json!([])); + let too_many = json!({"command":"transactions","limit":101}); + assert!(control(&buyer, too_many).await.is_err()); + let send = json!({"command":"send","operation_id":id,"to":format!("0x{}", "22".repeat(20)),"amount":"1","max_fee":"1"}); + let refused = control(&buyer, send).await.unwrap_err(); + assert!(refused.to_string().contains("unavailable")); +} + +#[tokio::test] +async fn a_requirement_the_host_refused_is_sent_again_on_the_next_tick() { + let (_bd, _sd, _chain, _buyer, seller) = pair(); + seller.unreachable.store(true, Ordering::SeqCst); + let priced = json!({"command":"set_pricing","model":"other", + "value":{"input_per_million":"5","output_per_million":"6"}}); + assert!(control(&seller, priced).await.is_err()); + assert!(seller.ledger.paid_price("other").unwrap().is_some()); + assert!(seller.requirements.lock().unwrap().is_empty()); + assert!(seller.retry().await.is_err()); + seller.unreachable.store(false, Ordering::SeqCst); + seller.retry().await.unwrap(); + seller.retry().await.unwrap(); + assert_eq!( + seller.requirements.lock().unwrap().clone(), + [("other".to_string(), true)] + ); +} diff --git a/src/engine_mpp.rs b/src/engine_mpp.rs new file mode 100644 index 0000000..1d3db57 --- /dev/null +++ b/src/engine_mpp.rs @@ -0,0 +1,874 @@ +use super::*; +use crate::contract::mpp::{Bill, RequestTerms, Usage}; +use crate::{ + ledger::{Channel, ChannelState, Request as Row, State}, + protocol::{Intent, Step as Wire}, +}; +use admission::SERVED_FREE; +use sha2::{Digest, Sha256}; + +impl Engine { + pub(super) async fn mpp_send(&self, peer: &str, id: &str, message: Wire) -> Result<()> { + self.send( + peer, + &Message::Mpp { + version: crate::protocol::MPP_VERSION, + id: id.into(), + message: Box::new(message), + }, + ) + .await + } + pub(super) async fn mpp_message(&self, peer: &str, id: &str, message: Wire) -> Result<()> { + ensure!( + uuid::Uuid::parse_str(id).is_ok(), + "MPP request ID must be a UUID" + ); + if let Wire::Hello { intent } = message { + return self.mpp_hello(peer, id, intent).await; + } + let row = self.ledger.mpp_get(id)?.context("unknown MPP request")?; + ensure!(row.peer == peer, "wrong MPP peer"); + if row.state == State::Closed { + // A repeated bill means the voucher that paid it was lost. + if let Wire::Bill(bill) = &message + && !row.seller + && row.bill.as_ref() == Some(bill) + { + self.buyer_resend_voucher(&row).await?; + } + // A repeated notice means the acknowledgement was lost. + if matches!(message, Wire::Unbilled) && !row.seller { + self.mpp_send(peer, &row.id, Wire::UnbilledSeen).await?; + } + return Ok(()); + } + match message { + Wire::QuoteRejected { reason } => { + ensure!( + !row.seller && row.state == State::Negotiating && row.terms.is_none(), + "quote refusal after agreement" + ); + self.mpp_close(&row.id, &reason)?; + } + Wire::Unpriced => { + ensure!( + !row.seller && row.state == State::Negotiating && row.terms.is_none(), + "unpriced notice after agreement" + ); + self.mpp_close(&row.id, SERVED_FREE)?; + } + Wire::Busy => { + ensure!( + !row.seller && row.state == State::Negotiating && row.terms.is_none(), + "busy notice after agreement" + ); + self.ledger.mpp_update(&row.id, |r| { + r.busy = true; + Ok(()) + })?; + } + Wire::Unbilled => { + ensure!( + !row.seller + && matches!(row.state, State::Running | State::UsageUnknown) + && row.bill.is_none(), + "unexpected unbilled notice" + ); + // Nothing was billed, so the channel view stays as it is. + self.mpp_close( + &row.id, + "the seller has no usage for this request and never bills it; not paid", + )?; + self.mpp_send(peer, &row.id, Wire::UnbilledSeen).await?; + } + Wire::UnbilledSeen => { + ensure!(row.seller, "unexpected unbilled acknowledgement"); + self.ledger.mpp_update(&row.id, |r| { + r.unbilled_seen = true; + Ok(()) + })?; + } + Wire::Quote { terms } => { + ensure!(!row.seller, "unexpected quote"); + self.buyer_quote(&row, terms).await?; + } + Wire::Voucher { funding, voucher } => { + ensure!(row.seller, "unexpected voucher"); + match row.state { + State::Negotiating => self.seller_admit_voucher(&row, funding, voucher).await?, + State::Ready => self.mpp_send(peer, &row.id, Wire::Ready).await?, + State::Billed => self.seller_payment(&row, funding, voucher).await?, + _ => bail!("voucher while the request runs"), + } + } + Wire::Ready => { + ensure!( + !row.seller && row.cum_after.is_some(), + "ready before this request's voucher" + ); + self.ledger.mpp_update(&row.id, |r| { + if r.state == State::Negotiating { + r.state = State::Ready; + } + Ok(()) + })?; + } + Wire::Bill(bill) => { + ensure!( + !row.seller && matches!(row.state, State::Running | State::UsageUnknown), + "unexpected bill" + ); + self.ledger.mpp_update(&row.id, |r| { + ensure!( + r.bill.as_ref().is_none_or(|old| *old == bill), + "bill changed" + ); + r.bill = Some(bill); + Ok(()) + })?; + self.mpp_progress(&row.id).await?; + } + Wire::Cancel => { + ensure!(row.seller, "only buyer can cancel peer work"); + ensure!( + matches!(row.state, State::Negotiating | State::Ready), + "request already dispatched; await usage or explicitly waive unknown usage" + ); + self.mpp_close( + &row.id, + "buyer cancelled the unstarted request; any voucher stays as channel credit", + )?; + } + Wire::Hello { .. } => unreachable!(), + } + self.changed.notify_waiters(); + Ok(()) + } + pub(super) fn mpp_close(&self, id: &str, reason: &str) -> Result<()> { + self.ledger.mpp_update(id, |r| { + r.state = State::Closed; + r.error = Some(reason.chars().take(512).collect()); + Ok(()) + }) + } + async fn mpp_hello(&self, peer: &str, id: &str, intent: Intent) -> Result<()> { + if let Some(old) = self.ledger.mpp_get(id)? { + ensure!( + old.seller && old.peer == peer && old.intent == intent, + "request ID reused" + ); + ensure!( + self.wallet_info.can_send, + "MPP seller must unlock wallet for capture and refund" + ); + let terms = old.terms.context("missing quote")?; + return self.mpp_send(peer, id, Wire::Quote { terms }).await; + } + let Some(price) = self.ledger.paid_price(&intent.model)? else { + return self.mpp_send(peer, id, Wire::Unpriced).await; + }; + ensure!( + self.wallet_info.can_send, + "MPP seller must unlock wallet for capture and refund" + ); + let channel = self.ledger.channel_active(peer, true)?; + // Repeat the last close notice, in case the buyer still uses that channel. + if channel.is_none() + && let Some(closure) = self + .ledger + .channel_last_closed(peer, true)? + .and_then(|c| c.closure) + { + let channel_id = closure.channel_id.clone(); + let notice = Message::Closed { + version: MPP_VERSION, + channel_id, + closure, + }; + self.send(peer, ¬ice).await?; + } + // Repeat unacknowledged notices of requests that are never billed. + for old in self.ledger.mpp_active()? { + if old.seller + && old.peer == peer + && old.state == State::UsageUnknown + && !old.unbilled_seen + { + self.seller_unbilled(&old).await?; + } + } + if let Some(answer) = self.seller_refusal(peer, channel.as_ref(), &intent.body_digest)? { + return self.mpp_send(peer, id, answer).await; + } + let terms = RequestTerms { + request_id: id.into(), + buyer_peer: peer.into(), + seller_peer: self.node.clone(), + model: intent.model.clone(), + body_digest: intent.body_digest.clone(), + payee: self.wallet_info.address.clone(), + asset: self.wallet_info.asset.clone(), + input_per_million: price.input_per_million, + output_per_million: price.output_per_million, + cache_discount_percent: price.cache_discount_percent, + output_limit: intent.output_limit, + input_bytes: intent.input_bytes, + // Only a buyer that has not paid since the seller started pays + // upfront, and only to open a channel. + upfront: if channel.is_some() || self.seller_has_standing(peer) { + 0 + } else { + self.ledger.model_admission_deposit(&intent.model)? + }, + cum_before: channel.as_ref().map_or(0, Channel::cum), + cost_before: channel.as_ref().map_or(0, |c| c.running_total), + channel_id: channel + .as_ref() + .and_then(|c| c.funding.as_ref()) + .map(|f| f.channel_id.clone()), + expires_at: now() + 600, + }; + terms.validate()?; + // Bills stay in order: a request with unknown usage is never billed + // once a later one is quoted. + for old in self.ledger.mpp_active()? { + if old.seller && old.peer == peer && old.state == State::UsageUnknown { + self.ledger.mpp_update(&old.id, |r| { + r.superseded = true; + Ok(()) + })?; + } + } + let mut row = Row::new(id.into(), peer.into(), true, intent); + row.terms = Some(terms.clone()); + self.ledger.mpp_insert(&row)?; + self.mpp_send(peer, id, Wire::Quote { terms }).await + } + fn mpp_check_terms(&self, row: &Row, terms: &RequestTerms) -> Result<()> { + terms.validate()?; + ensure!( + terms.request_id == row.id + && terms.buyer_peer == self.node + && terms.seller_peer == row.peer + && terms.model == row.intent.model + && terms.body_digest == row.intent.body_digest + && terms.asset == self.wallet_info.asset + && terms.output_limit == row.intent.output_limit + && terms.input_bytes == row.intent.input_bytes, + "quote does not match explicit request approval" + ); + // Without a ceiling, the worst-case cost checks bound the rates. + if let Some(ceiling) = self.config.buy_prices.get(&terms.model) { + ensure!( + terms.input_per_million <= ceiling.input_per_million + && terms.output_per_million <= ceiling.output_per_million + && terms.cache_discount_percent >= ceiling.cache_discount_percent, + "rates exceed buyer policy" + ); + } + ensure!( + terms.upfront <= self.ledger.admission_deposit()?, + "upfront exceeds the buyer's admission deposit" + ); + ensure!( + self.config.cap == 0 || terms.upfront <= self.config.cap, + "upfront exceeds the per-request cap" + ); + ensure!( + terms.expires_at > now() && terms.expires_at <= now() + 600, + "invalid quote expiry" + ); + Ok(()) + } + /// Whether the quote shows the buyer's channel, no more bills than its own + /// accepted bills and other requests account for, and no voucher above + /// the buyer's own. Otherwise the buyer stops using its channel and + /// recovers the deposit. A quote may count fewer bills than the buyer + /// accepted since, so only the upper bound is checked, also when the + /// check repeats while a top-up is pending. + fn buyer_check_view(&self, row: &Row, terms: &RequestTerms) -> Result<()> { + let channel = self.ledger.channel_active(&row.peer, false)?; + let shows = match &channel { + None => terms.channel_id.is_none() && terms.cost_before == 0 && terms.cum_before == 0, + // The seller may lack the buyer's latest voucher, which the buyer + // then resends; a seller that never got the first one quotes no + // channel, which is right only before any bill. Its bills may + // include ones still on their way to the buyer. + Some(c) => { + let id = c.funding.as_ref().map(|f| &f.channel_id); + let unseen = terms.channel_id.is_none() && terms.cum_before == 0; + let billed = c.running_total; + let pending = self.buyer_pending(&row.id, c)?; + c.state != ChannelState::Closing + && c.terms.payee.eq_ignore_ascii_case(&terms.payee) + && terms.cost_before <= billed.saturating_add(pending) + && (terms.channel_id.as_ref() == id || unseen && billed == 0) + && terms.cum_before <= c.cum() + } + }; + if shows { + return Ok(()); + } + if let Some(c) = channel.filter(|c| c.state == ChannelState::Open) { + self.ledger.channel_update(&c.key, |c| { + c.state = ChannelState::Closing; + c.error = Some("the seller's view of the channel differs; recovering it".into()); + Ok(()) + })?; + } + bail!("the seller's view of the channel differs from the buyer's") + } + /// What the buyer's other unsettled requests on `channel` may still be + /// billed: a bill it holds, else the bill for its own usage, else the + /// worst case. + fn buyer_pending(&self, id: &str, channel: &Channel) -> Result { + Ok(self + .ledger + .mpp_active()? + .iter() + .filter(|r| !r.seller && r.id != id && r.channel.as_ref() == Some(&channel.key)) + .filter_map(|r| { + let terms = r.terms.as_ref()?; + Some(match (&r.bill, r.usage) { + (Some(bill), _) => bill.cost, + (None, Some(usage)) => terms.bill(usage), + (None, None) => terms.worst_case(), + }) + }) + .fold(0, u64::saturating_add)) + } + async fn buyer_quote(&self, row: &Row, terms: RequestTerms) -> Result<()> { + if let Some(old) = &row.terms { + ensure!(*old == terms, "MPP quote changed"); + return self.mpp_progress(&row.id).await; + } + ensure!(row.state == State::Negotiating, "unexpected quote"); + if let Err(error) = self.mpp_check_terms(row, &terms) { + return self.buyer_refuse(row, &error.to_string()).await; + } + self.ledger.mpp_update(&row.id, |r| { + ensure!(r.terms.is_none(), "MPP quote changed"); + r.terms = Some(terms); + Ok(()) + })?; + self.mpp_progress(&row.id).await + } + /// Closes a request the buyer will not pay and tells the seller if it has not started. + pub(super) async fn buyer_refuse(&self, row: &Row, reason: &str) -> Result<()> { + self.mpp_close(&row.id, reason)?; + if matches!(row.state, State::Negotiating | State::Ready) { + self.mpp_send(&row.peer, &row.id, Wire::Cancel).await?; + } + self.changed.notify_waiters(); + Ok(()) + } + /// The policy's daily budget, or 0 when it allows no paid buying. + fn daily_budget(&self) -> Result { + Ok(self.ledger.policy()?.budget().unwrap_or(0)) + } + /// `payment` is upfront plus voucher increment for one request, and + /// `increment` is what it signs now, within the daily `budget`. + fn buyer_check_spend(&self, payment: u64, increment: u64, budget: u64) -> Result<()> { + ensure!( + self.config.cap == 0 || payment <= self.config.cap, + "payment exceeds the per-request cap" + ); + ensure!( + self.ledger.spent_today()?.saturating_add(increment) <= budget, + "daily budget exceeded" + ); + Ok(()) + } + /// The checks before anything is opened or signed for a request that + /// would raise the voucher from `signed` to `cum`, on a channel with + /// `billed` accepted and `pending` still expected: the seller's unbilled + /// credit, this request's worst-case cost, and whether one top-up could + /// pay its worst-case bill. + fn buyer_check_admission( + &self, + terms: &RequestTerms, + (signed, cum): (u64, u64), + (billed, pending): (u64, u64), + deposit: u64, + ) -> Result<()> { + let policy = self.ledger.policy()?; + let budget = policy + .budget() + .context("the payment policy allows free requests only")?; + // A later upfront may refill credit, but never beyond one admission deposit. + ensure!( + cum.saturating_sub(billed) <= self.ledger.admission_deposit()?, + "the seller's unbilled credit would exceed the admission deposit" + ); + let before = billed.saturating_add(pending); + let after = before.saturating_add(terms.worst_case()); + // This request's share of what the voucher may still rise to. + let increment = cum.max(after) - cum.max(before); + self.buyer_check_spend( + terms.upfront.saturating_add(increment), + (cum - signed).saturating_add(increment), + budget, + ) + .map_err(|error| anyhow::anyhow!("worst-case cost: {error}"))?; + // Each bill tops up at most once when it arrives. + ensure!( + cum.max(billed.saturating_add(terms.worst_case())) + <= deposit.saturating_add(self.config.channel_topup), + "one channel top-up cannot cover the worst-case bill" + ); + Ok(()) + } + /// Ensures the channel, then persists and sends the voucher that covers + /// the seller's view of the channel and this request's upfront. + async fn buyer_fund(&self, row: Row, terms: RequestTerms) -> Result<()> { + if row.cum_after.is_some() { + return self.buyer_resend_voucher(&row).await; + } + if !self.buys_from(&row.peer)? { + let reason = "paid inference is no longer authorized for this provider"; + return self.buyer_refuse(&row, reason).await; + } + if let Err(error) = self.buyer_check_view(&row, &terms) { + return self.buyer_refuse(&row, &error.to_string()).await; + } + // The voucher covers the seller's view plus the upfront; usually + // that is the buyer's existing voucher. + let target = terms + .cum_before + .checked_add(terms.upfront) + .context("upfront overflow")?; + // Every refusal comes before an open, so a refused request costs no channel. + let current = self.ledger.channel_active(&row.peer, false)?; + let (signed, deposit, billed, pending) = match ¤t { + Some(c) => ( + c.cum(), + c.deposit, + c.running_total, + self.buyer_pending(&row.id, c)?, + ), + None => (0, self.config.channel_topup, 0, 0), + }; + let spend = (signed, signed.max(target)); + let checked = self.buyer_check_admission(&terms, spend, (billed, pending), deposit); + if let Err(error) = checked { + return self.buyer_refuse(&row, &error.to_string()).await; + } + let Some(channel) = self.buyer_channel(&row, &terms).await? else { + return Ok(()); + }; + let cum = channel.cum().max(target); + let Some(channel) = self.buyer_capacity(&row, channel, cum).await? else { + return Ok(()); + }; + let voucher = self.buyer_voucher(&channel, cum).await?; + let key = channel.key.clone(); + self.ledger + .mpp_update_both(&row.id, &key, self.daily_budget()?, |r, c| { + ensure!( + r.state == State::Negotiating + && r.cum_after.is_none() + && c.state == ChannelState::Open + && c.cum() <= cum, + "request or channel changed concurrently" + ); + c.voucher = Some(voucher.clone()); + c.active_at = now(); + r.channel = Some(key.clone()); + r.cum_after = Some(cum); + Ok(()) + })?; + let funding = channel.funding.context("channel is not open")?; + self.mpp_send(&row.peer, &row.id, Wire::Voucher { funding, voucher }) + .await + } + pub(super) async fn buyer_resend_voucher(&self, row: &Row) -> Result<()> { + let Some(key) = &row.channel else { + return Ok(()); + }; + let Some(channel) = self.ledger.channel_get(key)? else { + return Ok(()); + }; + if let (ChannelState::Open, Some(funding), Some(voucher)) = + (channel.state, channel.funding, channel.voucher) + { + self.mpp_send(&row.peer, &row.id, Wire::Voucher { funding, voucher }) + .await?; + } + Ok(()) + } + /// The voucher a bill needs, or the reason the buyer refuses to sign it. + fn buyer_check_bill( + &self, + row: &Row, + terms: &RequestTerms, + channel: &Channel, + bill: &Bill, + ) -> Result { + match (bill.usage, row.usage) { + (None, _) => ensure!(bill.cost == 0, "a bill without usage must waive the cost"), + (Some(billed), Some(own)) => { + ensure!( + billed == own, + "billed usage differs from the buyer's own observation" + ); + ensure!( + bill.cost == terms.bill(billed), + "cost differs from the quoted rates" + ); + } + (Some(_), None) => bail!("the buyer's own usage is unknown"), + } + ensure!( + channel.state == ChannelState::Open, + "the channel is closing" + ); + ensure!( + bill.seq == channel.bills, + "the bill reuses an earlier number" + ); + ensure!( + channel.running_total.checked_add(bill.cost) == Some(bill.running_total), + "running total differs from earlier bills plus this cost" + ); + ensure!( + bill.cost <= terms.worst_case(), + "cost exceeds the worst case checked before dispatch" + ); + let cum = channel.cum().max(bill.running_total); + let increment = cum - channel.cum(); + // Work already dispatched is paid even when concurrent bills overshoot + // the daily budget, as in the Lightning plugin; each request's worst + // case fit the budget at admission, and a `free_only` policy stops + // only new admissions. + self.buyer_check_spend(terms.upfront.saturating_add(increment), increment, u64::MAX)?; + Ok(cum) + } + /// Signs a checked bill once the buyer has its own usage, which may come + /// before or after the bill. + async fn buyer_settle(&self, row: Row) -> Result<()> { + let Some(bill) = row.bill.clone() else { + return Ok(()); + }; + if row.state == State::Running && row.usage.is_none() { + return Ok(()); + } + let terms = row.terms.clone().context("missing agreed rates")?; + let key = row.channel.clone().context("missing channel")?; + let channel = self.ledger.channel_get(&key)?.context("unknown channel")?; + // Bills are accepted in their channel's order; a later one waits on + // its request. + if bill.seq > channel.bills { + return Ok(()); + } + let cum = match self.buyer_check_bill(&row, &terms, &channel, &bill) { + Ok(cum) => cum, + Err(error) => { + return self + .buyer_refuse(&row, &format!("bill refused: {error}")) + .await; + } + }; + // A voucher beyond the deposit waits for one top-up; later bills on + // the channel wait with it. + let Some(channel) = self.buyer_capacity(&row, channel, cum).await? else { + return Ok(()); + }; + let voucher = self.buyer_voucher(&channel, cum).await?; + let raised = voucher.cum > channel.cum(); + self.ledger + .mpp_update_both(&row.id, &key, u64::MAX, |r, c| { + ensure!( + r.state == row.state + && c.state == ChannelState::Open + && c.running_total == channel.running_total + && c.bills == bill.seq, + "request or channel changed concurrently" + ); + c.voucher = Some(voucher.clone()); + c.running_total = bill.running_total; + c.bills += 1; + c.active_at = now(); + r.cum_after = Some(cum); + r.state = State::Closed; + Ok(()) + })?; + if raised { + let funding = channel.funding.context("channel is not open")?; + self.mpp_send(&row.peer, &row.id, Wire::Voucher { funding, voucher }) + .await?; + } + Ok(()) + } + /// Settles the bills held for an earlier one, in their channel's order. + async fn buyer_settle_held(&self, key: &str) -> Result<()> { + loop { + let Some(channel) = self.ledger.channel_get(key)? else { + return Ok(()); + }; + let next = self.ledger.mpp_active()?.into_iter().find(|r| { + !r.seller + && r.channel.as_deref() == Some(key) + && r.bill.as_ref().is_some_and(|b| b.seq == channel.bills) + }); + let Some(next) = next else { + return Ok(()); + }; + self.buyer_settle(next).await?; + let settled = self.ledger.channel_get(key)?; + if settled.is_none_or(|c| c.bills == channel.bills) { + return Ok(()); + } + } + } + pub(super) async fn mpp_terminal(&self, event: &Value) -> Result<()> { + if let Some(id) = self.record_terminal(event)? { + self.mpp_retry_one(&id).await?; + } + Ok(()) + } + /// Durably records terminal usage: the seller's bill or the buyer's own + /// observation. Returns the request whose payment can now progress. + pub(super) fn mpp_record_terminal(&self, event: &Value) -> Result> { + let Ok(observation) = serving::correlation(event) else { + return Ok(None); + }; + let Some(row) = self.ledger.mpp_observed(observation)? else { + return Ok(None); + }; + let usage = Usage::from_event(event); + if !row.seller { + let changed = self.ledger.mpp_update(&row.id, |r| { + if r.state != State::Running || r.usage.is_some() { + return Ok(false); + } + match usage { + Some(usage) => r.usage = Some(usage), + None => { + r.state = State::UsageUnknown; + r.error = Some( + "the buyer's own usage is unavailable; its bill cannot be verified" + .into(), + ); + } + } + Ok(true) + })?; + return Ok(changed.then_some(row.id)); + } + let Some(key) = row.channel.clone() else { + return Ok(None); + }; + let progress = self + .ledger + .mpp_update_both(&row.id, &key, 0, |r, c| seller::bill(r, c, usage))?; + Ok(progress.then_some(row.id)) + } + pub async fn retry(&self) -> Result<()> { + self.wallet.reconcile().await?; + let mut error = self.resync_requirements().await.err(); + if let Err(e) = self.sync_bond().await { + error.get_or_insert(e); + } + for row in self.ledger.mpp_active()? { + if let Some(key) = &row.channel + && self + .ledger + .channel_get(key)? + .is_some_and(|c| c.state == ChannelState::Closed) + { + self.mpp_close(&row.id, "the payment channel closed")?; + continue; + } + if let Err(e) = self.mpp_retry_one(&row.id).await { + self.ledger.mpp_update(&row.id, |r| { + r.error = Some(e.to_string()); + Ok(()) + })?; + error.get_or_insert(e); + } + } + let channels = self.ledger.channels_active()?; + let open: Vec<_> = channels + .iter() + .filter(|c| c.seller && c.state == ChannelState::Open) + .cloned() + .collect(); + let watched = self.seller_watch_list(&open).await?; + for channel in channels { + // An open seller channel needs a chain read only when watched or idle. + let quiet = channel.seller + && channel.state == ChannelState::Open + && watched.as_ref().is_some_and(|w| !w.contains(&channel.key)) + && !Self::seller_idle_due(&channel); + if quiet { + continue; + } + if let Err(e) = self.channel_retry_one(&channel.key).await { + self.ledger.channel_update(&channel.key, |c| { + c.error = Some(e.to_string()); + Ok(()) + })?; + error.get_or_insert(e); + } + } + error.map_or(Ok(()), Err) + } + pub(crate) async fn mpp_retry_one(&self, id: &str) -> Result<()> { + let row = self.ledger.mpp_get(id)?.context("unknown MPP request")?; + let serial = self.peer_lock(&row.peer)?; + let _guard = serial.lock().await; + self.mpp_progress(&row.id).await + } + async fn mpp_progress(&self, id: &str) -> Result<()> { + let row = self.ledger.mpp_get(id)?.context("unknown MPP request")?; + let expired = row.terms.as_ref().is_some_and(|t| t.expires_at <= now()); + match (row.seller, &row.state) { + (_, State::Closed) => return Ok(()), + (_, State::Negotiating | State::Ready) if expired => self.mpp_close( + id, + "quote expired before dispatch; any voucher stays as channel credit", + )?, + // No HTTP request can dispatch it any more, for example after a + // restart or a host deadline, so the seller is told to drop it. + (false, State::Negotiating | State::Ready) if row.observation.is_none() => { + let reason = + "the HTTP request ended before dispatch; any voucher stays as channel credit"; + self.buyer_refuse(&row, reason).await? + } + (false, State::Negotiating) => match row.terms.clone() { + None => { + let intent = row.intent.clone(); + self.mpp_send(&row.peer, id, Wire::Hello { intent }).await? + } + Some(terms) => self.buyer_fund(row, terms).await?, + }, + (false, State::Running | State::UsageUnknown) + if row.bill.is_none() + && row.terms.as_ref().is_some_and(|t| { + now() >= t.expires_at.saturating_add(channel::UNBILLED_SECONDS) + }) => + { + // No bill was acknowledged, so the channel view stays as it is. + self.mpp_close( + id, + "no bill arrived; closed without paying for this request", + )? + } + (false, State::Running | State::UsageUnknown) => { + let key = row.channel.clone(); + self.buyer_settle(row).await?; + if let Some(key) = key { + self.buyer_settle_held(&key).await?; + } + } + (true, State::Ready) if self.wallet_info.can_send => { + self.mpp_send(&row.peer, id, Wire::Ready).await? + } + (true, State::Billed) => self.seller_collect(row).await?, + (true, State::UsageUnknown) if !row.unbilled_seen => self.seller_unbilled(&row).await?, + _ => {} + } + self.changed.notify_waiters(); + Ok(()) + } + pub async fn mpp_control(&self, id: &str, command: &str) -> Result<()> { + let row = self.ledger.mpp_get(id)?.context("unknown MPP request")?; + let stored_id = row.id.clone(); + let id = stored_id.as_str(); + let serial = self.peer_lock(&row.peer)?; + let _guard = serial.lock().await; + let row = self.ledger.mpp_get(id)?.context("unknown MPP request")?; + match command { + "waive" => { + ensure!( + row.seller && row.state == State::UsageUnknown, + "waive requires seller's unknown usage" + ); + // After a later quote the request is never billed, so the + // waiver only records the operator's decision. + if row.superseded { + return self.mpp_close( + id, + "operator waived unknown usage; a later request was already quoted, so no bill is sent", + ); + } + let key = row.channel.context("request has no channel")?; + self.ledger.mpp_update_both(id, &key, 0, |r, c| { + ensure!(r.bill.is_none(), "request already billed"); + if c.state != ChannelState::Open { + r.state = State::Closed; + r.error = Some( + "operator waived unknown usage; the channel is closing, so no bill is sent" + .into(), + ); + return Ok(()); + } + r.bill = Some(Bill { + seq: c.bills, + usage: None, + cost: 0, + running_total: c.running_total, + }); + c.bills += 1; + r.state = State::Billed; + r.error = Some( + "operator waived unknown usage with a zero bill, not a zero usage measurement" + .into(), + ); + Ok(()) + })?; + } + "cancel" => { + ensure!(!row.seller, "buyer cancels requests"); + ensure!( + matches!(row.state, State::Negotiating | State::Ready), + "request already dispatched or closed" + ); + self.mpp_close(id, "cancelled; any voucher stays as channel credit")?; + self.mpp_send(&row.peer, id, Wire::Cancel).await?; + } + _ => bail!("unknown MPP control"), + } + self.mpp_progress(id).await + } +} +/// The request's terms both peers agree on; the digest of the body as the +/// client sent it binds the forwarded request to the agreement. +pub(super) fn request_intent(event: &Value, payer: &str) -> Result { + ensure!( + event["endpoint"] == "chat_completions", + "paid requests support chat_completions only" + ); + let body = event + .get("body") + .context("bounded request body permission is required")?; + ensure!( + serde_json::to_vec(body)?.len() <= 64 * 1024, + "request body exceeds 64 KiB" + ); + let model = event["model"].as_str().context("missing selected model")?; + ensure!( + body["model"] == model, + "paid requests require an exact model, without automatic selection or aliases" + ); + let output_limit = body + .get("max_completion_tokens") + .or_else(|| body.get("max_tokens")) + .and_then(Value::as_u64) + .filter(|limit| (1..=4096).contains(limit)) + .context("paid requests require max_tokens or max_completion_tokens of 1..4096")?; + let mut canonical = body.clone(); + canonical.sort_all_objects(); + let canonical = serde_json::to_vec(&canonical)?; + Ok(Intent { + model: model.into(), + body_digest: hex::encode(Sha256::digest(&canonical)), + payer: payer.into(), + output_limit, + input_bytes: canonical.len() as u64, + }) +} +#[cfg(test)] +#[path = "engine_mpp_tests.rs"] +mod tests; diff --git a/src/engine_mpp_tests.rs b/src/engine_mpp_tests.rs new file mode 100644 index 0000000..21e364b --- /dev/null +++ b/src/engine_mpp_tests.rs @@ -0,0 +1,1928 @@ +use super::super::admission::MINTED; +use super::*; +use crate::contract::{ + Asset, WalletInfo, + mpp::{ChannelFunding, ChannelTerms, CloseEvents, Closure, Request, Response, Voucher}, +}; +use crate::{ + config::{Mode, Policy, Price}, + wallet::{Backend, WalletFuture}, +}; +use serde_json::json; +use std::{ + collections::BTreeMap, + sync::{ + Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, +}; + +/// One channel of the in-memory reserve. +struct Fake { + funding: ChannelFunding, + deposit: u64, + topups: u32, + close_requested_at: u64, + closure: Option, +} +#[derive(Default)] +struct Chain { + channels: Mutex>, + opens: AtomicUsize, + topups: AtomicUsize, + signs: AtomicUsize, + verifies: AtomicUsize, + closes: AtomicUsize, + recovers: AtomicUsize, + inspects: AtomicUsize, + pending: AtomicBool, + /// Close events by block and channel ID; `None` means no event logs, so + /// every scan is skipped as with the default backend. + logs: Mutex>>, + height: std::sync::atomic::AtomicU64, + logs_fail: AtomicBool, + /// Public wallet attempts, such as bond locks and withdrawals. + attempts: Mutex>, + /// Bond transactions the engine asked the wallet for. + bonds: Mutex>, +} +fn known<'a>( + channels: &'a mut BTreeMap, + funding: &ChannelFunding, +) -> Result<&'a mut Fake> { + let fake = channels + .get_mut(&funding.channel_id) + .context("unknown channel")?; + ensure!(fake.funding == *funding, "funding changed"); + Ok(fake) +} +impl Chain { + fn count(counter: &AtomicUsize) -> usize { + counter.load(Ordering::SeqCst) + } + /// Sets the payer's close request time of a channel. + fn request_close(&self, channel_id: &str, at: u64) { + let mut channels = self.channels.lock().unwrap(); + channels.get_mut(channel_id).unwrap().close_requested_at = at; + } + fn open( + &self, + channels: &mut BTreeMap, + terms: ChannelTerms, + deposit: u64, + ) -> Result { + let id = terms.salt()?; + let fake = channels.entry(id.clone()).or_insert_with(|| { + self.opens.fetch_add(1, Ordering::SeqCst); + Fake { + funding: ChannelFunding { + terms: terms.clone(), + open_tx: "fixture-open".into(), + channel_id: id, + expiring_nonce_hash: "fixture-context".into(), + }, + deposit, + topups: 0, + close_requested_at: 0, + closure: None, + } + }); + ensure!(fake.funding.terms == terms, "open intent changed"); + Ok(Response { + funding: Some(fake.funding.clone()), + deposit, + ..Default::default() + }) + } + fn apply(&self, request: Request) -> Result { + let mut channels = self.channels.lock().unwrap(); + if self.pending.load(Ordering::SeqCst) + && matches!(request, Request::Open { .. } | Request::TopUp { .. }) + { + return Ok(Response { + pending: true, + ..Default::default() + }); + } + Ok(match request { + Request::Open { terms, deposit, .. } => self.open(&mut channels, terms, deposit)?, + Request::TopUp { + funding, + amount, + index, + .. + } => { + let fake = known(&mut channels, &funding)?; + ensure!(fake.closure.is_none(), "channel closed"); + if index == fake.topups + 1 { + self.topups.fetch_add(1, Ordering::SeqCst); + fake.topups = index; + fake.deposit += amount; + fake.close_requested_at = 0; + } + Response { + deposit: fake.deposit, + ..Default::default() + } + } + Request::SignVoucher { funding, cum } => { + self.signs.fetch_add(1, Ordering::SeqCst); + Response { + voucher: Some(Voucher { + channel_id: funding.channel_id, + cum, + signature: format!("signed-{cum}"), + }), + ..Default::default() + } + } + Request::VerifyVoucher { funding, voucher } => { + self.verifies.fetch_add(1, Ordering::SeqCst); + let fake = known(&mut channels, &funding)?; + ensure!( + fake.closure.is_none() && fake.close_requested_at == 0, + "channel closed or close requested" + ); + ensure!( + voucher.channel_id == funding.channel_id + && voucher.signature == format!("signed-{}", voucher.cum) + && voucher.cum <= fake.deposit, + "unbacked or unauthorized voucher" + ); + Response { + deposit: fake.deposit, + ..Default::default() + } + } + Request::Inspect { funding } => { + self.inspects.fetch_add(1, Ordering::SeqCst); + known(&mut channels, &funding)?.status() + } + Request::Close { + funding, + voucher, + capture, + } => { + ensure!( + capture <= voucher.map_or(0, |v| v.cum), + "capture exceeds voucher" + ); + let fake = known(&mut channels, &funding)?; + if fake.closure.is_none() { + self.closes.fetch_add(1, Ordering::SeqCst); + fake.close("fixture-close", capture); + } + fake.status() + } + Request::Recover { funding, .. } => { + self.recovers.fetch_add(1, Ordering::SeqCst); + let fake = known(&mut channels, &funding)?; + if fake.closure.is_none() { + if fake.close_requested_at == 0 { + fake.close_requested_at = now(); + } else if now() >= fake.close_requested_at + 900 { + fake.close("fixture-withdraw", 0); + } + } + fake.status() + } + }) + } +} +impl Fake { + fn close(&mut self, tx_hash: &str, capture: u64) { + self.closure = Some(Closure { + tx_hash: tx_hash.into(), + channel_id: self.funding.channel_id.clone(), + captured: capture, + refunded: self.deposit - capture, + block_number: 2, + }); + } + fn status(&self) -> Response { + Response { + deposit: self.deposit, + close_requested_at: self.close_requested_at, + closure: self.closure.clone(), + ..Default::default() + } + } +} +impl Backend for Chain { + fn execute(&self, request: Request) -> WalletFuture<'_, Response> { + Box::pin(async move { self.apply(request) }) + } + fn balance(&self) -> WalletFuture<'_, crate::contract::Balance> { + Box::pin(async { anyhow::bail!("engine fixture balance is not used") }) + } + fn attempts(&self) -> Result> { + Ok(self.attempts.lock().unwrap().clone()) + } + fn bond<'a>( + &'a self, + _settings: &'a crate::bonds::Settings, + id: &'a str, + intent: crate::bonds::Intent, + ) -> WalletFuture<'a, Value> { + self.bonds.lock().unwrap().push((id.into(), intent)); + Box::pin(async { Ok(json!({"status": "pending"})) }) + } + fn close_events(&self, from: Option) -> WalletFuture<'_, CloseEvents> { + Box::pin(async move { + ensure!(!self.logs_fail.load(Ordering::SeqCst), "logs unavailable"); + let to = self.height.load(Ordering::SeqCst); + let logs = self.logs.lock().unwrap(); + let (Some(logs), Some(from)) = (logs.as_ref(), from) else { + return Ok(CloseEvents { + to, + skipped: true, + ..Default::default() + }); + }; + let channels = logs + .iter() + .filter(|(block, _)| (from..=to).contains(block)) + .map(|(_, id)| id.to_ascii_lowercase()) + .collect(); + Ok(CloseEvents { + channels, + to, + skipped: false, + }) + }) + } +} + +fn engine(dir: &std::path::Path, seller: bool, chain: Arc) -> Arc { + let node = (if seller { "bb" } else { "aa" }).repeat(32); + let info = WalletInfo { + wallet_id: node.clone(), + address: format!("0x{}", (if seller { "22" } else { "11" }).repeat(20)), + asset: Asset::default(), + can_send: true, + }; + engine_with_wallet(dir, seller, chain, info, 0) +} +fn engine_with_wallet( + dir: &std::path::Path, + seller: bool, + wallet: Arc, + info: WalletInfo, + max_fee: u64, +) -> Arc { + let node = (if seller { "bb" } else { "aa" }).repeat(32); + let peer = (if seller { "aa" } else { "bb" }).repeat(32); + let price = Price { + input_per_million: 1_000_000, + output_per_million: 1_000_000, + cache_discount_percent: 0, + }; + let config = Config { + bonds: Default::default(), + data_dir: dir.into(), + wallet: crate::tempo::Settings { + network: info.asset.network().unwrap(), + max_fee, + ..Default::default() + }, + prices: if seller { + BTreeMap::from([("model".into(), price.clone())]) + } else { + BTreeMap::new() + }, + policy: if seller { + Policy::default() + } else { + automatic(10000) + }, + // One top-up covers the cap, and the cap covers a test request's worst case. + cap: 200, + buy_peers: [peer].into(), + buy_prices: BTreeMap::from([("model".into(), price)]), + admission_deposit: Some(10), + channel_topup: 200, + }; + config.validate().unwrap(); + let ledger = Ledger::open(dir).unwrap(); + ledger.pin_node(&node).unwrap(); + ledger.seed(&config).unwrap(); + ledger.mpp_restart().unwrap(); + Arc::new(Engine { + bonds: crate::bonds::Service::new(&config).unwrap(), + config, + ledger, + wallet, + wallet_info: info, + node, + context: None, + changed: Default::default(), + peers: Default::default(), + ingress: Default::default(), + unsynced: Default::default(), + watch: Default::default(), + standing: Default::default(), + bond_unsynced: Default::default(), + outbox: Default::default(), + unreachable: Default::default(), + requirements: Default::default(), + published: Default::default(), + }) +} +type Pair = ( + tempfile::TempDir, + tempfile::TempDir, + Arc, + Arc, + Arc, +); +/// A buyer and a seller sharing one in-memory reserve. +fn pair() -> Pair { + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let chain = Arc::new(Chain::default()); + let buyer = engine(bd.path(), false, chain.clone()); + let seller = engine(sd.path(), true, chain.clone()); + (bd, sd, chain, buyer, seller) +} +fn event(id: &str) -> Value { + json!({"phase":"backend_selected","endpoint":"chat_completions","target_peer_id":"bb".repeat(32),"model":"model","observation_id":format!("buyer-{id}"), + "body":{"model":"model","messages":[{"role":"user","content":"test"}],"max_tokens":4}}) +} +fn automatic(daily_budget: u64) -> Policy { + Policy { + mode: Mode::Automatic, + daily_budget: Some(daily_budget), + } +} +/// Rates of `rate` micro-OUSD per million input and output tokens. +fn price(rate: u64) -> Price { + Price { + input_per_million: rate, + output_per_million: rate, + cache_discount_percent: 0, + } +} +/// The worst case of a test request: every body byte as an input token plus +/// its four output tokens, at one micro-OUSD per token. +fn worst(id: &str) -> u64 { + let payer = format!("0x{}", "11".repeat(20)); + request_intent(&event(id), &payer).unwrap().input_bytes + 4 +} +fn usage(input: u64, output: u64) -> Value { + json!({"prompt_tokens":input,"completion_tokens":output}) +} +fn mpp(id: &str, step: Wire) -> Message { + Message::Mpp { + version: MPP_VERSION, + id: id.into(), + message: Box::new(step), + } +} +/// Delivers messages both ways until neither side has more to send. +async fn pump(buyer: &Engine, seller: &Engine) -> Result<()> { + for _ in 0..20 { + let messages: Vec<_> = buyer.outbox.lock().unwrap().drain(..).collect(); + let replies: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + if messages.is_empty() && replies.is_empty() { + return Ok(()); + } + for (_, message) in messages { + seller.message(&buyer.node, message).await?; + } + for (_, message) in replies { + buyer.message(&seller.node, message).await?; + } + } + bail!("messages never settled") +} +/// The buyer's admission decision while its messages are delivered. +async fn decide( + buyer: &Arc, + seller: &Arc, + request: Value, +) -> OpenAiExchangeDecision { + let b = buyer.clone(); + let task = tokio::spawn(async move { b.hook(request).await }); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while !task.is_finished() { + pump(buyer, seller).await.unwrap(); + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let decision = task.await.unwrap().unwrap(); + pump(buyer, seller).await.unwrap(); + decision +} +async fn admit(buyer: &Arc, seller: &Arc, id: &str) -> Value { + let request = event(id); + let decision = decide(buyer, seller, request.clone()).await; + assert_eq!( + decision.decision, + OpenAiAdmissionDecision::Allow, + "{:?}", + decision.reason + ); + let mut serving = request; + serving["target_peer_id"] = Value::Null; + serving["requested_by_node_id"] = json!(buyer.node); + serving["observation_id"] = json!(format!("seller-{id}")); + assert_eq!( + seller.hook(serving.clone()).await.unwrap().decision, + OpenAiAdmissionDecision::Allow + ); + serving +} +async fn terminal(engine: &Engine, role: &str, id: &str, usage: &Value) { + engine + .hook(json!({"phase":"exchange_finished","observation_id":format!("{role}-{id}"),"usage":usage})) + .await + .unwrap(); +} +/// Ends inference on both sides; the bill reaches the buyer before or after +/// its own usage. +async fn finish(buyer: &Engine, seller: &Engine, id: &str, usage: Value, bill_first: bool) { + terminal(seller, "seller", id, &usage).await; + if bill_first { + pump(buyer, seller).await.unwrap(); + } + terminal(buyer, "buyer", id, &usage).await; + pump(buyer, seller).await.unwrap(); +} +async fn paid_request(buyer: &Arc, seller: &Arc, usage: Value) -> String { + let id = uuid::Uuid::new_v4().to_string(); + admit(buyer, seller, &id).await; + finish(buyer, seller, &id, usage, false).await; + id +} +fn channel(engine: &Engine) -> Channel { + let peer = (if engine.node.starts_with("aa") { + "bb" + } else { + "aa" + }) + .repeat(32); + engine + .ledger + .channel_active(&peer, engine.node.starts_with("bb")) + .unwrap() + .unwrap() +} +/// The request ID the buyer minted for the request tagged `tag` by [`event`], +/// or `tag` itself for a request a test inserted under its own ID. +fn rid(tag: &str) -> String { + let minted = MINTED.lock().unwrap(); + minted + .get(&format!("buyer-{tag}")) + .cloned() + .unwrap_or_else(|| tag.into()) +} +fn row(engine: &Engine, tag: &str) -> Row { + engine.ledger.mpp_get(&rid(tag)).unwrap().unwrap() +} +/// A buyer request a test inserts itself, attached to the HTTP request of +/// [`event`] as the admission hook would attach it. +fn attached(id: &str, peer: &str, intent: crate::protocol::Intent) -> Row { + let mut row = Row::new(id.into(), peer.into(), false, intent); + row.observation = Some(format!("buyer-{id}")); + row +} + +#[tokio::test] +async fn first_request_pays_upfront_and_later_requests_reuse_the_channel_without_one() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let mut quotes = Vec::new(); + for (n, cum) in [(1, 10), (2, 10), (3, 15)] { + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + quotes.push(row(&seller, &id).terms.unwrap()); + finish(&buyer, &seller, &id, usage(1, 4), n % 2 == 0).await; + let (bought, sold) = (row(&buyer, &id), row(&seller, &id)); + assert_eq!( + (&bought.state, &sold.state), + (&State::Closed, &State::Closed) + ); + assert_eq!((&bought.error, &sold.error), (&None, &None)); + assert_eq!(bought.bill, sold.bill); + assert_eq!(bought.cum_after, Some(cum)); + for side in [channel(&buyer), channel(&seller)] { + assert_eq!((side.cum(), side.running_total), (cum, 5 * n)); + } + } + let views: Vec<_> = quotes + .iter() + .map(|q| (q.upfront, q.cum_before, q.cost_before)) + .collect(); + assert_eq!(views, [(10, 0, 0), (0, 10, 5), (0, 10, 10)]); + assert!(quotes[0].channel_id.is_none()); + assert_eq!(quotes[1].channel_id, quotes[2].channel_id); + assert_eq!( + quotes[1].channel_id.as_deref(), + Some(channel(&buyer).funding.unwrap().channel_id.as_str()) + ); + assert_eq!(Chain::count(&chain.opens), 1); + assert_eq!(Chain::count(&chain.signs), 2); + assert_eq!(Chain::count(&chain.closes), 0); + assert_eq!(buyer.ledger.spent_today().unwrap(), 15); +} + +#[tokio::test] +async fn top_up_only_when_the_next_voucher_does_not_fit() { + let (_bd, _sd, chain, buyer, seller) = pair(); + // Three bills of 64 fit the opening deposit of 200. + for _ in 0..3 { + paid_request(&buyer, &seller, usage(60, 4)).await; + } + assert_eq!(Chain::count(&chain.topups), 0); + assert_eq!((channel(&buyer).cum(), channel(&buyer).deposit), (192, 200)); + paid_request(&buyer, &seller, usage(60, 4)).await; + assert_eq!(Chain::count(&chain.topups), 1); + let topped = channel(&buyer); + assert_eq!((topped.cum(), topped.deposit, topped.topups), (256, 400, 1)); + assert_eq!(channel(&seller).deposit, 400); +} + +#[tokio::test] +async fn a_worst_case_one_top_up_cannot_pay_is_refused_before_dispatch() { + let (_bd, _sd, chain, mut buyer, seller) = pair(); + let engine = Arc::get_mut(&mut buyer).unwrap(); + engine.config.channel_topup = 30; + engine.config.cap = 0; + engine.config.policy = automatic(30); + engine.config.validate().unwrap(); + // The operator raises the budget at runtime, beyond what 30 plus one + // top-up of 30 could pay for a test request's worst case. + buyer.ledger.set_policy(&automatic(10000)).unwrap(); + let decision = decide(&buyer, &seller, event(&uuid::Uuid::new_v4().to_string())).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!( + decision + .reason + .unwrap() + .contains("one channel top-up cannot cover the worst-case bill") + ); + assert_eq!(Chain::count(&chain.opens), 0); +} + +#[tokio::test] +async fn bills_are_signed_only_when_they_match_the_buyers_own_usage_and_quote() { + let own = Usage { + prompt_tokens: 1, + completion_tokens: 4, + cached_tokens: 0, + }; + let other = Usage { + prompt_tokens: 2, + ..own + }; + for (bill, reason) in [ + ( + Bill { + seq: 0, + usage: Some(other), + cost: 6, + running_total: 6, + }, + "billed usage differs", + ), + ( + Bill { + seq: 0, + usage: Some(own), + cost: 6, + running_total: 6, + }, + "cost differs", + ), + ( + Bill { + seq: 0, + usage: Some(own), + cost: 5, + running_total: 6, + }, + "running total differs", + ), + ( + Bill { + seq: 0, + usage: None, + cost: 5, + running_total: 5, + }, + "must waive", + ), + ] { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + terminal(&buyer, "buyer", &id, &usage(1, 4)).await; + buyer + .message(&seller.node, mpp(&rid(&id), Wire::Bill(bill))) + .await + .unwrap(); + let refused = row(&buyer, &id); + assert_eq!(refused.state, State::Closed); + assert!(refused.error.unwrap().contains(reason)); + assert_eq!( + (channel(&buyer).cum(), channel(&buyer).running_total), + (10, 0) + ); + assert_eq!(Chain::count(&chain.signs), 1); + assert!(buyer.outbox.lock().unwrap().is_empty()); + } +} + +#[tokio::test] +async fn bills_apply_the_cache_discount_and_never_bill_output_beyond_the_limit() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let discounted = Price { + cache_discount_percent: 50, + ..price(1_000_000) + }; + seller + .ledger + .set_pricing("model", Some(&discounted)) + .unwrap(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + // 2 uncached and 2 cached input tokens at half price, and 4 of 8 output tokens. + let reported = json!({"prompt_tokens":4,"completion_tokens":8,"prompt_tokens_details":{"cached_tokens":2}}); + finish(&buyer, &seller, &id, reported, true).await; + let bought = row(&buyer, &id); + assert_eq!((bought.state, bought.error), (State::Closed, None)); + assert_eq!(bought.bill.unwrap().cost, 7); + assert_eq!(channel(&seller).running_total, 7); +} + +#[tokio::test] +async fn an_unpaid_bill_closes_the_channel_with_the_best_voucher_after_the_payment_time() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + terminal(&seller, "seller", &id, &usage(7, 4)).await; + terminal(&buyer, "buyer", &id, &usage(6, 4)).await; + pump(&buyer, &seller).await.unwrap(); + assert!(row(&buyer, &id).error.unwrap().contains("bill refused")); + seller.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(row(&seller, &id).state, State::Billed); + assert_eq!(Chain::count(&chain.closes), 0); + seller + .ledger + .mpp_update(&rid(&id), |r| { + r.billed_at = now() - channel::BILL_PAYMENT_SECONDS; + Ok(()) + }) + .unwrap(); + let key = channel(&seller).key; + seller.retry().await.unwrap(); + assert!(row(&seller, &id).error.unwrap().contains("bill unpaid")); + let closed = seller.ledger.channel_get(&key).unwrap().unwrap(); + assert_eq!(closed.lost_bills, 1); + let closure = closed.closure.unwrap(); + assert_eq!((closure.captured, closure.refunded), (10, 190)); + assert_eq!(Chain::count(&chain.closes), 1); + pump(&buyer, &seller).await.unwrap(); + assert!( + buyer + .ledger + .channel_active(&seller.node, false) + .unwrap() + .is_none() + ); + // The buyer paid its first upfront, so its new channel needs none. + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + assert_eq!(row(&seller, &next).terms.unwrap().upfront, 0); + assert_eq!(channel(&buyer).cum(), 0); + assert_eq!(Chain::count(&chain.opens), 2); +} + +#[tokio::test] +async fn seller_closes_an_idle_channel_and_one_whose_buyer_requested_close() { + for requested in [false, true] { + let (_bd, _sd, chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.closes), 0); + let open = channel(&seller); + if requested { + chain.request_close(&open.funding.unwrap().channel_id, now()); + } else { + seller + .ledger + .channel_update(&open.key, |c| { + c.active_at = now() - 3600; + Ok(()) + }) + .unwrap(); + } + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.closes), 1); + let closed = seller.ledger.channel_get(&open.key).unwrap().unwrap(); + let closure = closed.closure.unwrap(); + assert_eq!((closure.captured, closure.refunded), (5, 195)); + pump(&buyer, &seller).await.unwrap(); + let bought = buyer.ledger.channel_get(&open.key).unwrap().unwrap(); + assert_eq!((bought.state, bought.error), (ChannelState::Closed, None)); + } +} + +#[tokio::test] +async fn buyer_recovers_an_idle_channel_by_requesting_close_then_withdrawing() { + let (_bd, _sd, chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let open = channel(&buyer); + buyer.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.recovers), 0); + buyer + .ledger + .channel_update(&open.key, |c| { + c.active_at = now() - 7200; + Ok(()) + }) + .unwrap(); + buyer.retry().await.unwrap(); + buyer.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.recovers), 2); + assert_eq!(channel(&buyer).state, ChannelState::Closing); + let id = open.funding.unwrap().channel_id; + chain.request_close(&id, now() - 900); + buyer.retry().await.unwrap(); + let closed = buyer.ledger.channel_get(&open.key).unwrap().unwrap(); + assert_eq!(closed.state, ChannelState::Closed); + assert_eq!(closed.closure.unwrap().refunded, 200); +} + +#[tokio::test] +async fn the_buyer_closes_its_channel_by_seller() { + let (_bd, _sd, chain, buyer, seller) = pair(); + assert!(buyer.buyer_close(None).await.is_err()); + paid_request(&buyer, &seller, usage(1, 4)).await; + let open = channel(&buyer); + // Only the buyer's channels count, and a prefix needs eight characters. + assert!(seller.buyer_close(None).await.is_err()); + assert!(buyer.buyer_close(Some(&open.peer[..7])).await.is_err()); + assert!(buyer.buyer_close(Some("cccccccc")).await.is_err()); + // Without a seller, the only open channel closes. + assert_eq!(buyer.buyer_close(None).await.unwrap(), open.peer); + assert_eq!(Chain::count(&chain.recovers), 1); + assert_eq!(channel(&buyer).state, ChannelState::Closing); + // A prefix names the same seller. + let prefix = open.peer[..8].to_ascii_uppercase(); + assert_eq!(buyer.buyer_close(Some(&prefix)).await.unwrap(), open.peer); + assert_eq!(Chain::count(&chain.recovers), 2); +} + +#[tokio::test] +async fn a_seller_offline_through_the_grace_records_the_capture_it_lost() { + let (_bd, _sd, chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let open = channel(&seller); + let earned = open.cum().min(open.running_total); + assert!(earned > 0 && open.capture.is_none()); + // The buyer withdrew after the grace while the seller never started closing. + chain + .channels + .lock() + .unwrap() + .get_mut(&open.funding.clone().unwrap().channel_id) + .unwrap() + .close("fixture-withdraw", 0); + seller.retry().await.unwrap(); + let closed = seller.ledger.channel_get(&open.key).unwrap().unwrap(); + assert_eq!(closed.state, ChannelState::Closed); + assert_eq!(Chain::count(&chain.closes), 0); + let error = closed.error.unwrap(); + assert!( + error.contains(&format!("{earned} earned, 0 captured")), + "{error}" + ); +} + +#[tokio::test] +async fn a_quote_whose_upfront_exceeds_the_admission_deposit_parses_and_only_buyer_policy_refuses_it() + { + let (_bd, _sd, chain, buyer, seller) = pair(); + seller.ledger.set_admission_deposit(1000).unwrap(); + let id = uuid::Uuid::new_v4().to_string(); + let decision = decide(&buyer, &seller, event(&id)).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!( + decision + .reason + .unwrap() + .contains("upfront exceeds the buyer's admission deposit") + ); + let quote = row(&seller, &id).terms.unwrap(); + let wire = serde_json::to_string(&mpp( + &id, + Wire::Quote { + terms: quote.clone(), + }, + )) + .unwrap(); + let parsed = serde_json::from_str::(&wire).unwrap(); + assert!( + matches!(&parsed, Message::Mpp { message, .. } if matches!(message.as_ref(), Wire::Quote { terms } if terms.upfront == 1000 && *terms == quote)) + ); + assert_eq!(row(&buyer, &id).state, State::Closed); + assert_eq!(row(&seller, &id).state, State::Closed); + assert_eq!(Chain::count(&chain.opens), 0); +} + +#[tokio::test] +async fn the_voucher_is_persisted_before_it_is_sent_and_reused_after_a_restart() { + let (bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + let quotes: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + for (_, message) in quotes { + buyer.message(&seller.node, message).await.unwrap(); + } + // The signed voucher is durable even though its message is lost. + buyer.outbox.lock().unwrap().clear(); + assert_eq!(row(&buyer, &id).cum_after, Some(10)); + assert_eq!(buyer.ledger.spent_today().unwrap(), 10); + drop(buyer); + let buyer = engine(bd.path(), false, chain.clone()); + // The restart ended the HTTP request, so the request is cancelled and + // its voucher stays as credit for the next one. + buyer.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(row(&buyer, &id).state, State::Closed); + assert_eq!(row(&seller, &id).state, State::Closed); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + assert_eq!(row(&buyer, &next).cum_after, Some(10)); + assert_eq!(Chain::count(&chain.signs), 1); + assert_eq!(buyer.ledger.spent_today().unwrap(), 10); +} + +#[tokio::test] +async fn terminal_usage_is_billed_durably_before_the_bill_is_sent() { + let (_bd, sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::from_u128(44).to_string(); + admit(&buyer, &seller, &id).await; + let finished = json!({"phase":"exchange_finished","observation_id":format!("seller-{id}"),"usage":usage(2, 3)}); + assert_eq!(seller.record_terminal(&finished).unwrap(), Some(rid(&id))); + assert!(seller.outbox.lock().unwrap().is_empty()); + drop(seller); + let seller = engine(sd.path(), true, chain.clone()); + let restored = row(&seller, &id); + assert_eq!(restored.state, State::Billed); + assert_eq!( + restored.bill.map(|b| (b.cost, b.running_total)), + Some((5, 5)) + ); + assert_eq!(channel(&seller).running_total, 5); + seller.retry().await.unwrap(); + assert_eq!(row(&seller, &id).state, State::Closed); + assert!( + matches!(&seller.outbox.lock().unwrap()[0].1, Message::Mpp { message, .. } if matches!(message.as_ref(), Wire::Bill(bill) if bill.cost == 5)) + ); +} + +#[tokio::test] +async fn terminal_usage_after_the_channel_closed_is_saved_without_billing() { + let (_bd, sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::from_u128(0xdef).to_string(); + admit(&buyer, &seller, &id).await; + let open = channel(&seller); + // The running request had its whole margin to be billed. + chain.request_close(&open.funding.unwrap().channel_id, now() - 600); + seller.retry().await.unwrap(); + assert_eq!(row(&seller, &id).state, State::Closed); + let finished = json!({"phase":"exchange_finished","observation_id":format!("seller-{id}"),"usage":usage(2, 3)}); + assert!(seller.record_terminal(&finished).unwrap().is_none()); + drop(seller); + let seller = engine(sd.path(), true, chain.clone()); + let saved = row(&seller, &id); + assert_eq!(saved.usage.map(|u| u.prompt_tokens), Some(2)); + assert_eq!((saved.state, saved.bill), (State::Closed, None)); + let closed = seller.ledger.channel_get(&open.key).unwrap().unwrap(); + assert_eq!(closed.closure.unwrap().captured, 0); + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.closes), 1); +} + +#[tokio::test] +async fn an_expired_quote_closes_the_request_without_opening_a_channel() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + let mut row = Row::new(id.clone(), seller.node.clone(), false, intent.clone()); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + seller.outbox.lock().unwrap().clear(); + let mut terms = self::row(&seller, &id).terms.unwrap(); + terms.expires_at = now() - 1; + row.terms = Some(terms); + buyer.ledger.mpp_insert(&row).unwrap(); + buyer.retry().await.unwrap(); + let closed = self::row(&buyer, &id); + assert_eq!(closed.state, State::Closed); + assert!(closed.error.unwrap().contains("expired")); + assert_eq!(Chain::count(&chain.opens), 0); + assert!(buyer.ledger.channels_active().unwrap().is_empty()); +} + +#[tokio::test] +async fn unsupported_protocol_versions_fail_before_state_or_funding() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + let message = Message::Mpp { + version: 2, + id: id.clone(), + message: Box::new(Wire::Hello { intent }), + }; + assert!( + seller + .message(&buyer.node, message.clone()) + .await + .unwrap_err() + .to_string() + .contains("unsupported MPP protocol version") + ); + let mut unversioned = serde_json::to_value(message).unwrap(); + unversioned.as_object_mut().unwrap().remove("version"); + assert!(serde_json::from_value::(unversioned).is_err()); + assert!(seller.ledger.mpp_get(&rid(&id)).unwrap().is_none()); + assert_eq!(Chain::count(&chain.opens), 0); +} + +#[tokio::test] +async fn peer_errors_are_recorded_only_against_the_authenticated_mpp_request() { + let (_bd, _sd, _chain, buyer, _seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + let peer = "bb".repeat(32); + buyer + .ledger + .mpp_insert(&Row::new(id.clone(), peer.clone(), false, intent)) + .unwrap(); + let message = Message::Error { + id: id.clone(), + reason: "quote refused".into(), + }; + assert!( + buyer + .message(&"cc".repeat(32), message.clone()) + .await + .is_err() + ); + assert!(row(&buyer, &id).error.is_none()); + buyer.message(&peer, message).await.unwrap(); + let row = row(&buyer, &id); + assert_eq!(row.error.as_deref(), Some("quote refused")); + assert_eq!(row.state, State::Negotiating); +} + +#[tokio::test] +async fn body_identity_and_live_backing_are_required() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let mut invalid_requests = Vec::new(); + for limit in [0, 4097] { + let mut request = event(&id); + request["body"]["max_tokens"] = json!(limit); + invalid_requests.push(request); + } + let mut request = event(&id); + request["body"] + .as_object_mut() + .unwrap() + .remove("max_tokens"); + request["body"]["max_output_tokens"] = json!(4); + invalid_requests.push(request); + let mut request = event(&id); + request["body"]["messages"][0]["content"] = json!("x".repeat(64 * 1024)); + invalid_requests.push(request); + let mut reasons = Vec::new(); + for request in invalid_requests { + let decision = buyer.hook(request).await.unwrap(); + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + reasons.push(decision.reason.unwrap()); + } + // A paid route needs a finite output limit for its worst case. + assert!(reasons[..3].iter().all(|r| r.contains("max_tokens"))); + assert_eq!(Chain::count(&chain.opens), 0); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(row(&seller, &id).state, State::Ready); + let mut serving = event(&id); + serving["requested_by_node_id"] = json!(buyer.node); + serving["target_peer_id"] = Value::Null; + serving["body"]["messages"][0]["content"] = json!("different inference"); + assert_eq!( + seller.hook(serving.clone()).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + serving["body"]["messages"][0]["content"] = json!("test"); + // Dispatch trusts the voucher verified at admission and the channel state, + // which the seller's tick moves to closing on a close request. + let open = channel(&seller); + chain.request_close(&open.funding.unwrap().channel_id, now()); + let before = Chain::count(&chain.verifies); + seller.retry().await.unwrap(); + assert_eq!( + seller.hook(serving).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + assert_eq!(Chain::count(&chain.verifies), before); +} + +#[tokio::test] +async fn dispatch_needs_no_chain_call_and_an_open_channel() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(Chain::count(&chain.verifies), 1); + let mut serving = event(&id); + serving["requested_by_node_id"] = json!(buyer.node); + serving["target_peer_id"] = Value::Null; + serving["observation_id"] = json!(format!("seller-{id}")); + let key = channel(&seller).key; + seller + .ledger + .channel_update(&key, |c| { + c.state = ChannelState::Closing; + Ok(()) + }) + .unwrap(); + assert_eq!( + seller.hook(serving.clone()).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + seller + .ledger + .channel_update(&key, |c| { + c.state = ChannelState::Open; + Ok(()) + }) + .unwrap(); + assert_eq!( + seller.hook(serving).await.unwrap().decision, + OpenAiAdmissionDecision::Allow + ); + assert_eq!(Chain::count(&chain.verifies), 1); +} + +#[tokio::test] +async fn unsupported_endpoints_and_unpaid_resolved_models_fail_before_funding() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + for endpoint in ["responses", "completions"] { + let mut request = event(&id); + request["endpoint"] = json!(endpoint); + assert_eq!( + buyer.hook(request.clone()).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + request["requested_by_node_id"] = json!(buyer.node); + request["target_peer_id"] = Value::Null; + assert_eq!( + seller.hook(request).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + } + let mut ingress = event(&id); + ingress["phase"] = json!("request_received"); + ingress["requested_by_node_id"] = json!(buyer.node); + ingress["target_peer_id"] = Value::Null; + ingress["model"] = json!("unpriced-alias"); + seller.hook(ingress).await.unwrap(); + let selected = json!({"phase":"backend_selected", "model":"model", "observation_id":format!("buyer-{id}")}); + assert_eq!( + seller.hook(selected).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + assert_eq!(Chain::count(&chain.opens), 0); + assert!( + serde_json::from_value::( + json!({"type":"hello","id":id,"model":"model","payer":"payer"}) + ) + .is_err() + ); +} + +#[tokio::test] +async fn an_aborted_pending_buyer_hook_detaches_and_its_request_is_cancelled() { + let (_bd, _sd, chain, buyer, _seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let task = { + let buyer = buyer.clone(); + let request = event(&id); + tokio::spawn(async move { buyer.hook(request).await }) + }; + tokio::time::timeout(std::time::Duration::from_secs(2), async { + loop { + if buyer + .ledger + .mpp_get(&rid(&id)) + .unwrap() + .is_some_and(|r| r.observation.is_some()) + { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + assert!(row(&buyer, &id).observation.is_none()); + // No HTTP request can dispatch it now, so the tick cancels it. + buyer.retry().await.unwrap(); + assert_eq!(row(&buyer, &id).state, State::Closed); + assert!(matches!( + &buyer.outbox.lock().unwrap().last().unwrap().1, + Message::Mpp { message, .. } if matches!(message.as_ref(), Wire::Cancel) + )); + assert_eq!(Chain::count(&chain.opens), 0); +} + +#[tokio::test] +async fn recovery_and_messages_share_bounded_peer_coordination() { + let (_bd, _sd, chain, buyer, _seller) = pair(); + let known_peer = "bb".repeat(32); + let known_lock = buyer.peer_lock(&known_peer).unwrap(); + let mut held = Vec::new(); + { + let mut peers = buyer.peers.lock().unwrap(); + for index in 0..4095 { + let lock = Arc::default(); + held.push(Arc::clone(&lock)); + peers.insert(format!("{index:064x}"), lock); + } + } + assert!(Arc::ptr_eq( + &known_lock, + &buyer.peer_lock(&known_peer).unwrap() + )); + let id = uuid::Uuid::new_v4().to_string(); + let peer = "cc".repeat(32); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&Row::new(id.clone(), peer.clone(), false, intent)) + .unwrap(); + for result in [ + buyer.mpp_retry_one(&rid(&id)).await, + buyer.mpp_control(&rid(&id), "cancel").await, + buyer + .message( + &peer, + Message::Error { + id: id.clone(), + reason: "error".into(), + }, + ) + .await, + ] { + assert!( + result + .unwrap_err() + .to_string() + .contains("peer coordination capacity exhausted") + ); + } + assert_eq!(row(&buyer, &id).state, State::Negotiating); + assert_eq!(Chain::count(&chain.opens), 0); +} + +#[test] +fn idle_peer_locks_are_reclaimed_without_replacing_live_locks() { + let dir = tempfile::tempdir().unwrap(); + let buyer = engine(dir.path(), false, Arc::new(Chain::default())); + let live = buyer.peer_lock(&"bb".repeat(32)).unwrap(); + for number in 0..10_000 { + drop(buyer.peer_lock(&format!("{number:064x}")).unwrap()); + } + assert!(Arc::ptr_eq( + &live, + &buyer.peer_lock(&"bb".repeat(32)).unwrap() + )); + assert!(buyer.peers.lock().unwrap().len() <= 4096); +} + +#[tokio::test(start_paused = true)] +async fn a_paid_request_in_flight_blocks_only_an_identical_paid_request_to_that_seller() { + let dir = tempfile::tempdir().unwrap(); + let buyer = engine(dir.path(), false, Arc::new(Chain::default())); + let id = uuid::Uuid::from_u128(42).to_string(); + let request = event(&id); + let intent = request_intent(&request, &buyer.wallet_info.address).unwrap(); + let mut row = Row::new(id.clone(), "bb".repeat(32), false, intent); + row.state = State::Running; + buyer.ledger.mpp_insert(&row).unwrap(); + // The paused clock runs out the wait for the identical request. + let decision = buyer + .hook(event(&uuid::Uuid::from_u128(43).to_string())) + .await + .unwrap(); + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!(decision.reason.unwrap().contains("still in flight")); + // Other routes are outside buyer policy and take the free path. + for peer in [Value::Null, json!("cc".repeat(32))] { + let mut rerouted = event(&uuid::Uuid::new_v4().to_string()); + rerouted["target_peer_id"] = peer; + assert_eq!( + buyer.hook(rerouted).await.unwrap().decision, + OpenAiAdmissionDecision::Abstain + ); + } + assert!(buyer.outbox.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn uuid_aliases_are_one_identity_and_uninspectable_bodies_are_denied() { + let dir = tempfile::tempdir().unwrap(); + let buyer = engine(dir.path(), false, Arc::new(Chain::default())); + let id = uuid::Uuid::from_u128(0xabc); + let request = event(&id.to_string()); + let intent = request_intent(&request, &buyer.wallet_info.address).unwrap(); + let mut row = Row::new(id.to_string(), "bb".repeat(32), false, intent); + row.state = State::Running; + buyer.ledger.mpp_insert(&row).unwrap(); + for alias in [ + id.simple().to_string(), + id.to_string().to_uppercase(), + id.urn().to_string(), + ] { + let mut duplicate = row.clone(); + duplicate.id = alias; + assert!(buyer.ledger.mpp_insert(&duplicate).is_err()); + } + for body in [ + Value::Null, + json!({"messages":[{"content":"x".repeat(65*1024)}]}), + ] { + let mut replay = request.clone(); + replay["body"] = body; + replay["target_peer_id"] = Value::Null; + assert_eq!( + buyer.hook(replay).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + } +} + +#[tokio::test] +async fn free_requests_work_with_spending_enabled_and_never_open_a_channel() { + let (_bd, _sd, chain, mut buyer, seller) = pair(); + // A seller outside a listed `buy_peers` is never paid. + Arc::get_mut(&mut buyer).unwrap().config.buy_peers = ["cc".repeat(32)].into(); + assert_eq!( + buyer + .hook(event(&uuid::Uuid::new_v4().to_string())) + .await + .unwrap() + .decision, + OpenAiAdmissionDecision::Abstain + ); + let mut request = event(&uuid::Uuid::new_v4().to_string()); + request["requested_by_node_id"] = json!(buyer.node); + request["target_peer_id"] = Value::Null; + for price in [None, Some(Price::default())] { + seller.ledger.set_pricing("model", price.as_ref()).unwrap(); + assert_ne!( + seller.hook(request.clone()).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + } + assert_eq!(Chain::count(&chain.opens), 0); + assert!(buyer.outbox.lock().unwrap().is_empty()); + for engine in [&buyer, &seller] { + assert!(engine.ledger.mpp_active().unwrap().is_empty()); + assert!(engine.ledger.channels_active().unwrap().is_empty()); + } +} + +#[tokio::test] +async fn paid_buying_follows_buyer_policy_within_its_limits() { + let (_bd, _sd, chain, mut buyer, seller) = pair(); + // A priced seller refuses a request that arrives unpaid. + let mut free = event(&uuid::Uuid::new_v4().to_string()); + free["requested_by_node_id"] = json!(buyer.node); + assert_eq!( + seller.hook(free).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + // A free_only policy sends the request free, before any message, + // voucher or channel. + buyer.ledger.set_policy(&Policy::default()).unwrap(); + let decision = buyer + .hook(event(&uuid::Uuid::new_v4().to_string())) + .await + .unwrap(); + assert_eq!(decision.decision, OpenAiAdmissionDecision::Abstain); + assert!(buyer.outbox.lock().unwrap().is_empty()); + buyer.ledger.set_policy(&automatic(10000)).unwrap(); + // The cap bounds the upfront of 10. + Arc::get_mut(&mut buyer).unwrap().config.cap = 9; + let decision = decide(&buyer, &seller, event(&uuid::Uuid::new_v4().to_string())).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!(decision.reason.unwrap().contains("per-request cap")); + assert_eq!(Chain::count(&chain.opens), 0); + assert!(buyer.ledger.channels_active().unwrap().is_empty()); +} + +#[tokio::test] +async fn removing_a_price_keeps_original_agreements_available_for_reconciliation() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + seller + .mpp_hello(&buyer.node, &id, intent.clone()) + .await + .unwrap(); + let original = row(&seller, &id).terms.unwrap(); + seller.ledger.set_pricing("model", None).unwrap(); + seller.outbox.lock().unwrap().clear(); + seller + .mpp_hello(&buyer.node, &id, intent.clone()) + .await + .unwrap(); + { + let messages = seller.outbox.lock().unwrap(); + assert!( + matches!(&messages[0].1, Message::Mpp {message, ..} if matches!(message.as_ref(), Wire::Quote {terms} if terms == &original)) + ); + } + let refused = uuid::Uuid::new_v4().to_string(); + seller + .mpp_hello(&buyer.node, &refused, intent) + .await + .unwrap(); + assert!(seller.ledger.mpp_get(&rid(&refused)).unwrap().is_none()); + assert!( + matches!(&seller.outbox.lock().unwrap().last().unwrap().1, Message::Mpp {message, ..} if matches!(message.as_ref(), Wire::Unpriced)) + ); + assert_eq!(Chain::count(&chain.opens), 0); +} + +#[tokio::test] +async fn removing_a_price_cannot_turn_a_dispatched_seller_request_into_a_free_replay() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let id = uuid::Uuid::from_u128(0xabc).to_string(); + let mut serving = admit(&buyer, &seller, &id).await; + drop(buyer); + seller.ledger.set_pricing("model", None).unwrap(); + serving["observation_id"] = json!("another-serving-attempt"); + let mut ingress = serving.clone(); + ingress["phase"] = json!("request_received"); + seller.hook(ingress).await.unwrap(); + // Mesh supplies the authenticated peer on ingress, not on backend selection. + serving["requested_by_node_id"] = Value::Null; + serving["body"] = Value::Null; + assert_eq!( + seller.hook(serving).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); +} + +#[tokio::test] +async fn locked_seller_keeps_its_channel_without_reissuing_ready_notices() { + let (_bd, _sd, chain, buyer, mut seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let mut request = event(&id); + let intent = request_intent(&request, &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller + .mpp_hello(&buyer.node, &id, intent.clone()) + .await + .unwrap(); + pump(&buyer, &seller).await.unwrap(); + Arc::get_mut(&mut seller).unwrap().wallet_info.can_send = false; + assert!( + seller + .mpp_hello(&buyer.node, &id, intent) + .await + .unwrap_err() + .to_string() + .contains("unlock") + ); + seller.retry().await.unwrap(); + assert!(seller.outbox.lock().unwrap().is_empty()); + request["target_peer_id"] = Value::Null; + request["requested_by_node_id"] = json!(buyer.node); + request["observation_id"] = json!(format!("locked-{id}")); + assert_eq!( + seller.hook(request).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + let saved = row(&seller, &id); + assert_eq!(saved.state, State::Ready); + assert!(saved.channel.is_some()); + Arc::get_mut(&mut seller).unwrap().wallet_info.can_send = true; + seller.retry().await.unwrap(); + assert!(matches!(&seller.outbox.lock().unwrap().last().unwrap().1, + Message::Mpp { message, .. } if matches!(message.as_ref(), Wire::Ready))); + assert_eq!(Chain::count(&chain.opens), 1); +} + +#[tokio::test] +async fn a_seller_without_a_paid_price_serves_the_model_free() { + let (_bd, _sd, chain, buyer, seller) = pair(); + seller.ledger.set_pricing("model", Some(&price(0))).unwrap(); + let id = uuid::Uuid::new_v4().to_string(); + let request = event(&id); + let decision = decide(&buyer, &seller, request.clone()).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Abstain); + let bought = row(&buyer, &id); + assert_eq!(bought.state, State::Closed); + assert_eq!(bought.error.as_deref(), Some(SERVED_FREE)); + assert!(seller.ledger.mpp_get(&rid(&id)).unwrap().is_none()); + let mut serving = request; + serving["target_peer_id"] = Value::Null; + serving["requested_by_node_id"] = json!(buyer.node); + serving["observation_id"] = json!(format!("seller-{id}")); + assert_eq!( + seller.hook(serving).await.unwrap().decision, + OpenAiAdmissionDecision::Abstain + ); + assert_eq!(Chain::count(&chain.opens), 0); + let paid = Price { + input_per_million: 1_000_000, + ..price(0) + }; + seller.ledger.set_pricing("model", Some(&paid)).unwrap(); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + buyer + .message( + &seller.node, + Message::Error { + id: rid(&next), + reason: "transient failure".into(), + }, + ) + .await + .unwrap(); + assert_eq!(row(&buyer, &next).state, State::Running); +} + +#[tokio::test] +async fn a_generic_locked_seller_error_keeps_a_lost_quote_retryable() { + let (_bd, _sd, chain, buyer, mut seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller + .mpp_hello(&buyer.node, &id, intent.clone()) + .await + .unwrap(); + seller.outbox.lock().unwrap().clear(); + Arc::get_mut(&mut seller).unwrap().wallet_info.can_send = false; + let error = seller + .message(&buyer.node, mpp(&rid(&id), Wire::Hello { intent })) + .await + .unwrap_err(); + buyer + .message( + &seller.node, + Message::Error { + id: rid(&id), + reason: error.to_string(), + }, + ) + .await + .unwrap(); + assert_eq!(row(&buyer, &id).state, State::Negotiating); + Arc::get_mut(&mut seller).unwrap().wallet_info.can_send = true; + // The buyer repeats its hello and gets the original quote. + buyer.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(row(&buyer, &id).state, State::Ready); + assert_eq!(Chain::count(&chain.opens), 1); + assert!( + buyer + .mpp_message( + &seller.node, + &id, + Wire::QuoteRejected { + reason: "late refusal".into() + } + ) + .await + .is_err() + ); + assert_eq!(row(&buyer, &id).state, State::Ready); +} + +/// Native wallets against the loopback RPC fixture, for both networks. +async fn native_pair( + url: &str, + network: crate::contract::Network, + dirs: &[tempfile::TempDir; 4], +) -> (Arc, Arc) { + use crate::tempo::rpc_fixture_tests; + let buyer_wallet = Arc::new(rpc_fixture_tests::wallet_on_network( + dirs[2].path(), + url, + 1, + network, + )); + let seller_wallet = Arc::new(rpc_fixture_tests::wallet_on_network( + dirs[3].path(), + url, + 2, + network, + )); + let buyer_info = buyer_wallet.info().await.unwrap(); + let seller_info = seller_wallet.info().await.unwrap(); + ( + engine_with_wallet(dirs[0].path(), false, buyer_wallet, buyer_info, 1000), + engine_with_wallet(dirs[1].path(), true, seller_wallet, seller_info, 1000), + ) +} + +#[tokio::test] +async fn engine_uses_native_wallet_directly_for_one_channel_bills_and_close() { + for network in [ + crate::contract::Network::Testnet, + crate::contract::Network::Mainnet, + ] { + let (chain, url, server) = crate::tempo::rpc_fixture_tests::server().await; + chain.lock().unwrap().chain_id = network.chain_id(); + let dirs = std::array::from_fn(|_| tempfile::tempdir().unwrap()); + let (buyer, seller) = native_pair(&url, network, &dirs).await; + for _ in 0..2 { + let id = uuid::Uuid::new_v4().to_string(); + let request = event(&id); + let task = { + let buyer = buyer.clone(); + let request = request.clone(); + tokio::spawn(async move { buyer.hook(request).await }) + }; + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !task.is_finished() { + pump(&buyer, &seller).await.unwrap(); + buyer.retry().await.unwrap(); + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!( + task.await.unwrap().unwrap().decision, + OpenAiAdmissionDecision::Allow + ); + let mut serving = request; + serving["target_peer_id"] = Value::Null; + serving["requested_by_node_id"] = json!(buyer.node); + serving["observation_id"] = json!(format!("seller-{id}")); + assert_eq!( + seller.hook(serving).await.unwrap().decision, + OpenAiAdmissionDecision::Allow + ); + finish(&buyer, &seller, &id, usage(1, 4), false).await; + assert_eq!(row(&buyer, &id).state, State::Closed); + } + let open = channel(&seller); + assert_eq!( + (open.cum(), open.running_total, open.deposit), + (10, 10, 200) + ); + seller + .ledger + .channel_update(&open.key, |c| { + c.active_at = now() - 3600; + Ok(()) + }) + .unwrap(); + seller.retry().await.unwrap(); + seller.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + let closed = buyer.ledger.channel_get(&open.key).unwrap().unwrap(); + let closure = closed.closure.unwrap(); + assert_eq!((closure.captured, closure.refunded), (10, 190)); + assert_eq!(closed.error, None); + assert_eq!(buyer.wallet.attempts().unwrap().len(), 1); + assert_eq!(seller.wallet.attempts().unwrap().len(), 1); + server.abort(); + } +} + +#[tokio::test] +async fn a_pending_open_is_replayed_from_its_original_bytes_after_a_buyer_restart() { + let network = crate::contract::Network::Testnet; + let (chain, url, server) = crate::tempo::rpc_fixture_tests::server().await; + let dirs = std::array::from_fn(|_| tempfile::tempdir().unwrap()); + let (buyer, seller) = native_pair(&url, network, &dirs).await; + chain.lock().unwrap().hide_receipt = true; + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(channel(&buyer).state, ChannelState::Opening); + let raw = buyer.wallet.attempts().unwrap()[0]["hash"].clone(); + drop(buyer); + let (buyer, seller) = { + drop(seller); + native_pair(&url, network, &dirs).await + }; + chain.lock().unwrap().hide_receipt = false; + buyer.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + // The restart ended the HTTP request, so the request is cancelled while + // its channel still opens. + buyer.retry().await.unwrap(); + assert_eq!(channel(&buyer).state, ChannelState::Open); + assert_eq!(row(&buyer, &id).state, State::Closed); + assert_eq!(row(&seller, &id).state, State::Closed); + let attempts = buyer.wallet.attempts().unwrap(); + assert_eq!(attempts.len(), 1); + assert_eq!(attempts[0]["hash"], raw); + server.abort(); +} + +#[tokio::test] +async fn a_refused_first_request_opens_no_channel() { + let (_bd, _sd, chain, buyer, seller) = pair(); + buyer.ledger.set_policy(&automatic(5)).unwrap(); + let id = uuid::Uuid::new_v4().to_string(); + let decision = decide(&buyer, &seller, event(&id)).await; + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!(decision.reason.unwrap().contains("daily budget")); + assert_eq!(Chain::count(&chain.opens), 0); + assert!(buyer.ledger.channels_active().unwrap().is_empty()); + assert_eq!(row(&seller, &id).state, State::Closed); +} + +#[tokio::test] +async fn a_channel_without_a_voucher_is_still_new_to_the_seller() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&id), &buyer.wallet_info.address).unwrap(); + buyer + .ledger + .mpp_insert(&attached(&id, &seller.node, intent.clone())) + .unwrap(); + seller.mpp_hello(&buyer.node, &id, intent).await.unwrap(); + chain.pending.store(true, Ordering::SeqCst); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(channel(&buyer).state, ChannelState::Opening); + // The request expires before its open finalizes, so no voucher is signed. + buyer + .ledger + .mpp_update(&rid(&id), |r| { + r.terms.as_mut().unwrap().expires_at = now() - 1; + Ok(()) + }) + .unwrap(); + seller.mpp_close(&id, "expired").unwrap(); + chain.pending.store(false, Ordering::SeqCst); + buyer.retry().await.unwrap(); + let opened = channel(&buyer); + assert_eq!( + (opened.state.clone(), opened.voucher.is_none()), + (ChannelState::Open, true) + ); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + let quote = row(&seller, &next).terms.unwrap(); + assert_eq!((quote.channel_id, quote.upfront), (None, 10)); + assert_eq!(channel(&buyer).key, opened.key); + assert_eq!(Chain::count(&chain.opens), 1); +} + +#[tokio::test] +async fn a_dispatched_request_without_a_bill_closes_after_its_quote_expires() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + terminal(&buyer, "buyer", &id, &usage(1, 4)).await; + buyer.retry().await.unwrap(); + assert_eq!(row(&buyer, &id).state, State::Running); + buyer + .ledger + .mpp_update(&rid(&id), |r| { + r.terms.as_mut().unwrap().expires_at = now() - channel::UNBILLED_SECONDS; + Ok(()) + }) + .unwrap(); + buyer.retry().await.unwrap(); + let closed = row(&buyer, &id); + assert_eq!(closed.state, State::Closed); + assert!(closed.error.unwrap().contains("no bill")); + assert_eq!( + (channel(&buyer).cum(), channel(&buyer).running_total), + (10, 0) + ); +} + +#[tokio::test] +async fn retry_closes_requests_whose_channel_already_closed() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + let key = channel(&buyer).key; + buyer + .ledger + .channel_update(&key, |c| { + c.state = ChannelState::Closed; + Ok(()) + }) + .unwrap(); + buyer.retry().await.unwrap(); + let closed = row(&buyer, &id); + assert_eq!(closed.state, State::Closed); + assert!(closed.error.unwrap().contains("channel closed")); +} + +#[tokio::test] +async fn the_payment_time_starts_when_the_bill_is_first_sent() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + let finished = json!({"phase":"exchange_finished","observation_id":format!("seller-{id}"),"usage":usage(7, 4)}); + seller.record_terminal(&finished).unwrap(); + assert_eq!(row(&seller, &id).billed_at, 0); + // A bill records no creation time, so while no send succeeds no payment + // time runs, however long the outage lasts. + seller.unreachable.store(true, Ordering::SeqCst); + for _ in 0..3 { + assert!(seller.retry().await.is_err()); + } + let waiting = row(&seller, &id); + assert_eq!((waiting.state, waiting.billed_at), (State::Billed, 0)); + seller.unreachable.store(false, Ordering::SeqCst); + seller.retry().await.unwrap(); + let billed = row(&seller, &id); + assert_eq!(billed.state, State::Billed); + assert!(billed.billed_at > 0); + assert_eq!(Chain::count(&chain.closes), 0); + // The payment time runs from that first send. + seller + .ledger + .mpp_update(&rid(&id), |r| { + r.billed_at -= channel::BILL_PAYMENT_SECONDS; + Ok(()) + }) + .unwrap(); + seller.retry().await.unwrap(); + assert!(row(&seller, &id).error.unwrap().contains("bill unpaid")); + assert_eq!(Chain::count(&chain.closes), 1); +} + +#[tokio::test] +async fn a_bill_covered_by_credit_settles_only_once_it_was_sent() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + terminal(&buyer, "buyer", &id, &usage(1, 4)).await; + seller.unreachable.store(true, Ordering::SeqCst); + let finished = json!({"phase":"exchange_finished","observation_id":format!("seller-{id}"),"usage":usage(1, 4)}); + assert_eq!(seller.record_terminal(&finished).unwrap(), Some(rid(&id))); + assert!(seller.retry().await.is_err()); + assert_eq!(row(&seller, &id).state, State::Billed); + seller.unreachable.store(false, Ordering::SeqCst); + seller.retry().await.unwrap(); + assert_eq!(row(&seller, &id).state, State::Closed); + pump(&buyer, &seller).await.unwrap(); + let bought = row(&buyer, &id); + assert_eq!((bought.state, bought.error), (State::Closed, None)); + assert_eq!(channel(&buyer).running_total, 5); +} + +#[tokio::test] +async fn a_close_request_lets_the_running_request_bill_first() { + for late in [false, true] { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + let open = channel(&seller); + let requested = if late { now() - 600 } else { now() }; + chain.request_close(&open.funding.unwrap().channel_id, requested); + seller.retry().await.unwrap(); + let closure = |seller: &Engine| { + let closed = seller.ledger.channel_get(&open.key).unwrap().unwrap(); + closed.closure.unwrap().captured + }; + if late { + // Past the safe margin the seller closes with what is billed so far. + assert_eq!(closure(&seller), 0); + assert_eq!(row(&seller, &id).state, State::Closed); + continue; + } + assert_eq!(Chain::count(&chain.closes), 0); + assert_eq!(channel(&seller).state, ChannelState::Open); + terminal(&seller, "seller", &id, &usage(1, 4)).await; + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.closes), 1); + assert_eq!(closure(&seller), 5); + } +} + +#[tokio::test] +async fn a_lost_close_notice_is_repeated_on_the_next_hello() { + let (_bd, _sd, chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let old = channel(&seller); + seller + .ledger + .channel_update(&old.key, |c| { + c.active_at = now() - 3600; + Ok(()) + }) + .unwrap(); + seller.retry().await.unwrap(); + seller.outbox.lock().unwrap().clear(); + assert_eq!(channel(&buyer).state, ChannelState::Open); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + let closed = buyer.ledger.channel_get(&old.key).unwrap().unwrap(); + assert_eq!((closed.state, closed.error), (ChannelState::Closed, None)); + assert_eq!(Chain::count(&chain.opens), 2); +} + +#[tokio::test] +async fn a_new_channel_pays_the_models_own_deposit_until_its_price_is_removed() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + seller + .ledger + .set_model_admission_deposit("model", Some(7)) + .unwrap(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + assert_eq!(row(&seller, &id).terms.unwrap().upfront, 7); + assert_eq!(channel(&buyer).cum(), 7); + seller.ledger.set_pricing("model", None).unwrap(); + seller + .ledger + .set_pricing("model", Some(&price(1_000_000))) + .unwrap(); + assert_eq!(seller.ledger.model_admission_deposit("model").unwrap(), 10); +} + +#[path = "engine_bond_tests.rs"] +mod bond; +#[path = "engine_buyer_tests.rs"] +mod buyer; +#[path = "engine_control_tests.rs"] +mod control; +#[path = "engine_parallel_tests.rs"] +mod parallel; +#[path = "engine_sequence_tests.rs"] +mod sequence; +#[path = "engine_watch_tests.rs"] +mod watch; + +#[tokio::test(start_paused = true)] +async fn a_request_refused_while_its_channel_opens_is_cancelled_so_the_next_one_proceeds() { + let (_bd, _sd, chain, buyer, seller) = pair(); + chain.pending.store(true, Ordering::SeqCst); + let id = uuid::Uuid::new_v4().to_string(); + let task = { + let buyer = buyer.clone(); + tokio::spawn(async move { buyer.hook(event(&id)).await }) + }; + while buyer.outbox.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + pump(&buyer, &seller).await.unwrap(); + assert_eq!(channel(&buyer).state, ChannelState::Opening); + // The paused clock runs out the admission wait. + let decision = task.await.unwrap().unwrap(); + assert_eq!(decision.decision, OpenAiAdmissionDecision::Deny); + assert!(decision.reason.unwrap().contains("not ready yet")); + pump(&buyer, &seller).await.unwrap(); + assert!(seller.ledger.mpp_active().unwrap().is_empty()); + chain.pending.store(false, Ordering::SeqCst); + buyer.retry().await.unwrap(); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + assert_eq!(row(&buyer, &next).cum_after, Some(10)); + assert_eq!(Chain::count(&chain.opens), 1); +} diff --git a/src/engine_parallel_tests.rs b/src/engine_parallel_tests.rs new file mode 100644 index 0000000..67ba656 --- /dev/null +++ b/src/engine_parallel_tests.rs @@ -0,0 +1,465 @@ +//! Requests that run at once on one pair: headroom and top-ups before +//! dispatch, standing, bills accepted in order, and strikes. +use super::sequence::deliver; +use super::*; +use crate::control::Control; + +/// A request like [`event`] whose body says `content`, so its digest differs. +fn event_saying(tag: &str, content: &str) -> Value { + let mut request = event(tag); + request["body"]["messages"][0]["content"] = json!(content); + request +} +/// Starts the buyer's admission hook for `request`. +fn start( + buyer: &Arc, + request: &Value, +) -> tokio::task::JoinHandle> { + let buyer = buyer.clone(); + let request = request.clone(); + tokio::spawn(async move { buyer.hook(request).await }) +} +/// Delivers messages, and runs retry ticks when `tick`, until every hook has +/// decided; then dispatches each request at the seller. +async fn dispatch_all( + buyer: &Arc, + seller: &Arc, + requests: &[(&str, Value)], + tasks: Vec>>, + tick: bool, +) { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !tasks.iter().all(|t| t.is_finished()) { + pump(buyer, seller).await.unwrap(); + if tick { + buyer.retry().await.unwrap(); + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + pump(buyer, seller).await.unwrap(); + for ((tag, request), task) in requests.iter().zip(tasks) { + let decision = task.await.unwrap().unwrap(); + assert_eq!( + decision.decision, + OpenAiAdmissionDecision::Allow, + "{:?}", + decision.reason + ); + let mut serving = request.clone(); + serving["target_peer_id"] = Value::Null; + serving["requested_by_node_id"] = json!(buyer.node); + serving["observation_id"] = json!(format!("seller-{tag}")); + assert_eq!( + seller.hook(serving).await.unwrap().decision, + OpenAiAdmissionDecision::Allow + ); + } +} +/// Admits `requests` at once and dispatches them at the seller. +async fn admit_all(buyer: &Arc, seller: &Arc, requests: &[(&str, Value)]) { + let tasks = requests.iter().map(|(_, r)| start(buyer, r)).collect(); + dispatch_all(buyer, seller, requests, tasks, false).await; +} +fn ids() -> [String; N] { + std::array::from_fn(|_| uuid::Uuid::new_v4().to_string()) +} +/// The seller's answer to a hello for a new request saying `content`. +async fn answer(buyer: &Engine, seller: &Engine, content: &str) -> Wire { + let id = uuid::Uuid::new_v4().to_string(); + let request = event_saying(&id, content); + let intent = request_intent(&request, &buyer.wallet_info.address).unwrap(); + seller + .message(&buyer.node, mpp(&id, Wire::Hello { intent })) + .await + .unwrap(); + let sent: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + match sent.last() { + Some((_, Message::Mpp { message, .. })) => message.as_ref().clone(), + other => panic!("no answer: {other:?}"), + } +} +/// A warm channel with three dispatched requests whose bills of 24 the +/// buyer has not received; returns their tags. +async fn three_unpaid(buyer: &Arc, seller: &Arc) -> [String; 3] { + paid_request(buyer, seller, usage(1, 4)).await; + let tags: [String; 3] = ids(); + let requests: Vec<_> = tags + .iter() + .map(|t| (t.as_str(), event_saying(t, t))) + .collect(); + admit_all(buyer, seller, &requests).await; + for tag in &tags { + terminal(seller, "seller", tag, &usage(20, 4)).await; + } + seller.outbox.lock().unwrap().clear(); + tags +} + +#[tokio::test] +async fn requests_with_different_bodies_run_at_once_and_bills_settle_in_order() { + let (_bd, _sd, chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let [a, b] = ids(); + let requests = [ + (a.as_str(), event_saying(&a, "a")), + (b.as_str(), event_saying(&b, "b")), + ]; + admit_all(&buyer, &seller, &requests).await; + for tag in [&a, &b] { + let sold = row(&seller, tag); + assert_eq!( + (sold.state, sold.terms.unwrap().upfront), + (State::Running, 0) + ); + } + terminal(&buyer, "buyer", &a, &usage(20, 4)).await; + terminal(&buyer, "buyer", &b, &usage(30, 4)).await; + // The later bill reaches the buyer first and waits for the earlier one. + terminal(&seller, "seller", &a, &usage(20, 4)).await; + let first: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + terminal(&seller, "seller", &b, &usage(30, 4)).await; + deliver(&seller, &buyer).await; + let held = row(&buyer, &b); + assert_eq!((held.state, held.bill.unwrap().seq), (State::Running, 2)); + assert_eq!(channel(&buyer).bills, 1); + for (_, message) in first { + buyer.message(&seller.node, message).await.unwrap(); + } + pump(&buyer, &seller).await.unwrap(); + for tag in [&a, &b] { + let (bought, sold) = (row(&buyer, tag), row(&seller, tag)); + assert_eq!((bought.state, sold.state), (State::Closed, State::Closed)); + assert_eq!((bought.error, sold.error), (None, None)); + } + let open = channel(&buyer); + assert_eq!((open.cum(), open.running_total, open.bills), (63, 63, 3)); + assert_eq!(channel(&seller).cum(), 63); + assert_eq!(Chain::count(&chain.recovers), 0); +} + +#[tokio::test] +async fn a_bill_between_another_requests_quote_and_voucher_does_not_refuse_it() { + for reordered in [false, true] { + let (_bd, _sd, chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let [a, b] = ids(); + admit_all(&buyer, &seller, &[(a.as_str(), event_saying(&a, "a"))]).await; + let request = event_saying(&b, "b"); + let task = start(&buyer, &request); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while buyer.outbox.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + // The seller quotes b, then bills a before b's voucher arrives. + deliver(&buyer, &seller).await; + terminal(&seller, "seller", &a, &usage(20, 4)).await; + terminal(&buyer, "buyer", &a, &usage(20, 4)).await; + assert_eq!(row(&seller, &b).terms.unwrap().cost_before, 5); + assert_eq!(channel(&seller).running_total, 29); + // The bill may also overtake the quote, which then shows fewer bills + // than the buyer accepted. + if reordered { + let mut sent: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + sent.reverse(); + for (_, message) in sent { + buyer.message(&seller.node, message).await.unwrap(); + } + } + dispatch_all(&buyer, &seller, &[(b.as_str(), request)], vec![task], false).await; + assert_eq!(row(&buyer, &a).state, State::Closed); + let open = channel(&buyer); + assert_eq!((open.state, open.running_total), (ChannelState::Open, 29)); + assert_eq!(Chain::count(&chain.recovers), 0); + } +} + +#[tokio::test] +async fn a_refused_voucher_gives_no_standing() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event_saying(&id, "a"), &buyer.wallet_info.address).unwrap(); + seller + .message(&buyer.node, mpp(&id, Wire::Hello { intent })) + .await + .unwrap(); + // A real channel and a valid voucher of 1, below the quoted upfront of 10. + let terms = ChannelTerms { + buyer_peer: buyer.node.clone(), + seller_peer: seller.node.clone(), + payer: buyer.wallet_info.address.clone(), + payee: seller.wallet_info.address.clone(), + asset: seller.wallet_info.asset.clone(), + nonce: "01".repeat(32), + }; + let open = Request::Open { + terms, + deposit: 200, + max_fee: 0, + }; + let funding = chain.apply(open).unwrap().funding.unwrap(); + let voucher = Voucher { + channel_id: funding.channel_id.clone(), + cum: 1, + signature: "signed-1".into(), + }; + let refused = seller + .message(&buyer.node, mpp(&id, Wire::Voucher { funding, voucher })) + .await; + assert!(refused.unwrap_err().to_string().contains("does not cover")); + seller + .message(&buyer.node, mpp(&id, Wire::Cancel)) + .await + .unwrap(); + seller.outbox.lock().unwrap().clear(); + match answer(&buyer, &seller, "b").await { + Wire::Quote { terms } => assert_eq!(terms.upfront, 10), + other => panic!("not quoted: {other:?}"), + } +} + +#[tokio::test] +async fn bills_of_concurrent_requests_are_paid_beyond_the_daily_budget() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let [a, b] = ids(); + let requests = [ + (a.as_str(), event_saying(&a, "a")), + (b.as_str(), event_saying(&b, "b")), + ]; + // Each worst case fits what remains of the budget, but not both. + let worst = request_intent(&requests[0].1, "").unwrap().input_bytes + 4; + let budget = 10 + worst; + buyer.ledger.set_policy(&automatic(budget)).unwrap(); + admit_all(&buyer, &seller, &requests).await; + for tag in [&a, &b] { + finish(&buyer, &seller, tag, usage(60, 4), false).await; + let (bought, sold) = (row(&buyer, tag), row(&seller, tag)); + assert_eq!((bought.state, bought.error), (State::Closed, None)); + assert_eq!(sold.state, State::Closed); + } + assert_eq!(buyer.ledger.spent_today().unwrap(), 133); + assert!(133 > budget); +} + +#[tokio::test] +async fn a_concurrent_bill_beyond_the_deposit_waits_for_one_top_up() { + let (_bd, _sd, chain, buyer, seller) = pair(); + for _ in 0..2 { + paid_request(&buyer, &seller, usage(60, 4)).await; + } + let [a, b] = ids(); + let requests = [ + (a.as_str(), event_saying(&a, "a")), + (b.as_str(), event_saying(&b, "b")), + ]; + admit_all(&buyer, &seller, &requests).await; + assert_eq!(Chain::count(&chain.topups), 0); + // The first bill of 64 still fits the deposit of 200. + finish(&buyer, &seller, &a, usage(60, 4), false).await; + assert_eq!(channel(&buyer).deposit, 200); + // The second does not, so it waits while the top-up is pending. + chain.pending.store(true, Ordering::SeqCst); + finish(&buyer, &seller, &b, usage(60, 4), false).await; + let waiting = row(&buyer, &b); + assert_eq!( + (waiting.state, waiting.bill.is_some()), + (State::Running, true) + ); + assert_eq!(channel(&buyer).running_total, 192); + chain.pending.store(false, Ordering::SeqCst); + buyer.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(row(&seller, &b).state, State::Closed); + assert_eq!(Chain::count(&chain.topups), 1); + let topped = channel(&buyer); + assert_eq!((topped.cum(), topped.deposit), (256, 400)); + assert_eq!(channel(&seller).deposit, 400); +} + +#[tokio::test] +async fn first_requests_without_standing_open_one_channel_and_the_rest_need_no_upfront() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let [a, b] = ids(); + let requests = [ + (a.as_str(), event_saying(&a, "a")), + (b.as_str(), event_saying(&b, "b")), + ]; + admit_all(&buyer, &seller, &requests).await; + let mut upfronts = [&a, &b].map(|t| row(&seller, t).terms.unwrap().upfront); + upfronts.sort(); + assert_eq!(upfronts, [0, 10]); + assert_eq!(Chain::count(&chain.opens), 1); + assert_eq!(channel(&buyer).cum(), 10); +} + +#[tokio::test] +async fn a_buyer_with_standing_opens_its_next_channel_with_a_zero_voucher_until_a_restart() { + let (_bd, sd, chain, buyer, mut seller) = pair(); + for (upfront, restart) in [(10, false), (0, false), (10, true)] { + if restart { + drop(seller); + seller = engine(sd.path(), true, chain.clone()); + } + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + // The seller verified a voucher of just the upfront, zero with standing. + let ready = row(&seller, &id); + assert_eq!(ready.terms.unwrap().upfront, upfront); + assert_eq!(ready.cum_after, Some(upfront)); + finish(&buyer, &seller, &id, usage(1, 4), false).await; + assert_eq!(row(&seller, &id).state, State::Closed); + // The seller closes the idle channel, so the next request opens one. + let key = channel(&seller).key; + seller + .ledger + .channel_update(&key, |c| { + c.active_at = now() - 3600; + Ok(()) + }) + .unwrap(); + seller.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert!( + buyer + .ledger + .channel_active(&seller.node, false) + .unwrap() + .is_none() + ); + } + assert_eq!(Chain::count(&chain.opens), 3); +} + +#[tokio::test] +async fn an_identical_body_waits_while_the_seller_has_it_in_flight() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + assert!(matches!(answer(&buyer, &seller, "test").await, Wire::Busy)); + assert!(matches!( + answer(&buyer, &seller, "other").await, + Wire::Quote { .. } + )); +} + +#[tokio::test] +async fn three_unpaid_bills_make_the_seller_busy_until_one_is_paid() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + let tags = three_unpaid(&buyer, &seller).await; + assert_eq!( + seller + .seller_strikes(&buyer.node, Some(&channel(&seller))) + .unwrap(), + 3 + ); + assert!(matches!(answer(&buyer, &seller, "next").await, Wire::Busy)); + // The buyer knows its usage for the first request only, so it pays that bill. + terminal(&buyer, "buyer", &tags[0], &usage(20, 4)).await; + seller.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + assert_eq!(row(&seller, &tags[0]).state, State::Closed); + assert_eq!(row(&buyer, &tags[1]).state, State::Running); + assert!(matches!( + answer(&buyer, &seller, "next").await, + Wire::Quote { .. } + )); +} + +#[tokio::test] +async fn lost_bills_count_on_a_new_channel_until_the_operator_unblocks_the_buyer() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let tags = three_unpaid(&buyer, &seller).await; + for tag in &tags { + seller + .ledger + .mpp_update(&rid(tag), |r| { + r.billed_at = now() - channel::BILL_PAYMENT_SECONDS; + Ok(()) + }) + .unwrap(); + } + let key = channel(&seller).key; + seller.retry().await.unwrap(); + let closed = seller.ledger.channel_get(&key).unwrap().unwrap(); + assert_eq!((closed.state, closed.lost_bills), (ChannelState::Closed, 3)); + assert_eq!(Chain::count(&chain.closes), 1); + pump(&buyer, &seller).await.unwrap(); + assert!(matches!(answer(&buyer, &seller, "next").await, Wire::Busy)); + let unblock = |peer: &str| { + serde_json::from_value::(json!({"command": "unblock", "peer": peer})).unwrap() + }; + let forgiven = unblock(&buyer.node).run(&seller, None).await.unwrap(); + assert_eq!(forgiven, json!({"peer": buyer.node, "bills": 3})); + assert!(unblock(&buyer.node).run(&seller, None).await.is_err()); + // The forgiven bills stay recorded on the closed channel. + assert_eq!( + seller.ledger.channel_get(&key).unwrap().unwrap().lost_bills, + 3 + ); + match answer(&buyer, &seller, "next").await { + Wire::Quote { terms } => assert_eq!((terms.upfront, terms.channel_id), (0, None)), + other => panic!("not quoted: {other:?}"), + } +} + +#[tokio::test] +async fn usage_after_the_unpaid_close_started_is_never_billed() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + paid_request(&buyer, &seller, usage(1, 4)).await; + let [a, b] = ids(); + let requests = [ + (a.as_str(), event_saying(&a, "a")), + (b.as_str(), event_saying(&b, "b")), + ]; + admit_all(&buyer, &seller, &requests).await; + terminal(&seller, "seller", &a, &usage(20, 4)).await; + seller.outbox.lock().unwrap().clear(); + seller + .ledger + .mpp_update(&rid(&a), |r| { + r.billed_at = now() - channel::BILL_PAYMENT_SECONDS; + Ok(()) + }) + .unwrap(); + let key = channel(&seller).key; + seller.mpp_retry_one(&rid(&a)).await.unwrap(); + assert_eq!(channel(&seller).state, ChannelState::Closing); + // The capture is fixed, so b's usage is recorded but not billed. + terminal(&seller, "seller", &b, &usage(20, 4)).await; + let unbilled = row(&seller, &b); + assert_eq!((unbilled.state, unbilled.bill), (State::Closed, None)); + assert!(unbilled.error.unwrap().contains("began closing")); + seller.retry().await.unwrap(); + let closed = seller.ledger.channel_get(&key).unwrap().unwrap(); + assert_eq!((closed.lost_bills, closed.running_total), (1, 29)); +} + +#[tokio::test] +async fn a_bill_the_voucher_covers_is_not_lost_when_the_buyer_withdraws_first() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + // The upfront credit covers the bill, but the buyer never receives it. + seller.unreachable.store(true, Ordering::SeqCst); + let finished = json!({"phase":"exchange_finished","observation_id":format!("seller-{id}"),"usage":usage(1, 4)}); + seller.record_terminal(&finished).unwrap(); + assert_eq!(row(&seller, &id).state, State::Billed); + let open = channel(&seller); + chain + .channels + .lock() + .unwrap() + .get_mut(&open.funding.clone().unwrap().channel_id) + .unwrap() + .close("fixture-withdraw", 0); + // The close notice cannot be sent either; the close is still recorded. + assert!(seller.retry().await.is_err()); + let closed = seller.ledger.channel_get(&open.key).unwrap().unwrap(); + assert_eq!((closed.state, closed.lost_bills), (ChannelState::Closed, 0)); +} diff --git a/src/engine_seller.rs b/src/engine_seller.rs new file mode 100644 index 0000000..55bdcb5 --- /dev/null +++ b/src/engine_seller.rs @@ -0,0 +1,368 @@ +//! The seller's side of a paid request: whether to quote, voucher admission, +//! dispatch, billing and payment. +use super::*; +use crate::contract::mpp::{Bill, ChannelFunding, Request, Usage, Voucher}; +use crate::{ + ledger::{Channel, ChannelState, Request as Row, State}, + protocol::{Intent, Step as Wire}, +}; +use mpp::request_intent; + +/// Unpaid bills at which the seller refuses a buyer's new requests, as in +/// the Lightning plugin. +const STRIKE_LIMIT: u64 = 3; +/// At most this many buyers have standing; the set is cleared when full. +const STANDING_LIMIT: usize = 1024; + +impl Engine { + /// The buyer's request for `body_digest` that holds the pair's slot for + /// that body; the unique index keeps it to at most one. + pub(super) fn seller_agreement(&self, peer: &str, body_digest: &str) -> Result> { + Ok(self.ledger.mpp_active()?.into_iter().find(|r| { + r.seller && r.peer == peer && r.holds_peer() && r.intent.body_digest == body_digest + })) + } + /// The answer to a hello the seller cannot quote now: a refusal while the + /// buyer's channel closes, and `Busy`, which the buyer retries, while the + /// channel is still being opened, the same body is in flight, or the + /// buyer has `STRIKE_LIMIT` unpaid bills. + pub(super) fn seller_refusal( + &self, + peer: &str, + channel: Option<&Channel>, + body_digest: &str, + ) -> Result> { + if channel.is_some_and(|c| c.state != ChannelState::Open) { + let reason = "the buyer's channel is closing; retry after its closure".into(); + return Ok(Some(Wire::QuoteRejected { reason })); + } + let held: Vec<_> = self + .ledger + .mpp_active()? + .into_iter() + .filter(|r| r.seller && r.peer == peer && r.holds_peer()) + .collect(); + let opening = channel.is_none() && !held.is_empty(); + let same = held.iter().any(|r| r.intent.body_digest == body_digest); + let busy = opening || same || self.seller_strikes(peer, channel)? >= STRIKE_LIMIT; + Ok(busy.then_some(Wire::Busy)) + } + /// The buyer's unpaid bills: those on its open channel that no voucher + /// covers yet, and those closed channels lost until the operator + /// forgives them. + pub(super) fn seller_strikes(&self, peer: &str, channel: Option<&Channel>) -> Result { + let open = channel.filter(|c| c.state == ChannelState::Open).map_or( + Ok(0), + |c| -> Result { + Ok(self + .ledger + .mpp_active()? + .iter() + .filter(|r| r.seller && r.channel.as_ref() == Some(&c.key)) + .filter(|r| r.state == State::Billed) + .filter(|r| r.bill.as_ref().is_some_and(|b| b.running_total > c.cum())) + .count() as u64) + }, + )?; + Ok(open + self.ledger.lost_bills(peer)?) + } + /// Forgives the buyer's lost bills, so they no longer count as strikes; + /// returns how many. + pub async fn unblock(&self, peer: &str) -> Result { + validate_peer(peer)?; + let serial = self.peer_lock(peer)?; + let _guard = serial.lock().await; + let forgiven = self.ledger.forgive_lost_bills(peer)?; + ensure!( + forgiven > 0, + "the peer has no lost bills; nothing to unblock" + ); + Ok(forgiven) + } + /// Whether the buyer has paid this seller since it started. + pub(super) fn seller_has_standing(&self, peer: &str) -> bool { + self.standing.lock().unwrap().contains(peer) + } + fn seller_grant_standing(&self, peer: &str) { + let mut standing = self.standing.lock().unwrap(); + if standing.len() >= STANDING_LIMIT && !standing.contains(peer) { + standing.clear(); + } + standing.insert(peer.into()); + } + /// Tells the buyer that a request with unknown usage is never billed, so + /// it closes its own request instead of waiting for a bill; repeated + /// until the buyer acknowledges it. + pub(super) async fn seller_unbilled(&self, row: &Row) -> Result<()> { + if !row.superseded { + // Once told, the buyer would ignore a bill for it. + self.ledger.mpp_update(&row.id, |r| { + r.superseded = true; + Ok(()) + })?; + } + self.mpp_send(&row.peer, &row.id, Wire::Unbilled).await + } + pub(super) async fn seller_admit_voucher( + &self, + row: &Row, + funding: ChannelFunding, + voucher: Voucher, + ) -> Result<()> { + let terms = row.terms.clone().context("missing quote")?; + ensure!(terms.expires_at > now(), "quote expired"); + ensure!( + self.wallet_info.can_send, + "MPP seller must unlock wallet for capture and refund" + ); + let pair = &funding.terms; + ensure!( + pair.buyer_peer == row.peer + && pair.seller_peer == self.node + && pair.payer.eq_ignore_ascii_case(&row.intent.payer) + && pair.payee.eq_ignore_ascii_case(&self.wallet_info.address) + && pair.asset == self.wallet_info.asset, + "channel terms differ from this buyer and seller" + ); + let key = pair.salt()?; + let existing = self.ledger.channel_active(&row.peer, true)?; + match &existing { + None => ensure!( + terms.channel_id.is_none(), + "quoted channel is no longer open" + ), + // Other requests may have been billed since the quote. + Some(c) => ensure!( + c.funding.as_ref() == Some(&funding) + && terms.channel_id.as_ref() == Some(&funding.channel_id) + && c.state == ChannelState::Open, + "voucher channel differs from the quote" + ), + } + // The voucher the seller already verified and stores needs no second + // check: its signature and the open receipt cannot change, the + // deposit only grows, and a close request moves the channel to + // closing on the next watch tick, within the close deferral. + let stored = existing + .as_ref() + .filter(|c| c.voucher.as_ref() == Some(&voucher)); + let deposit = match stored { + Some(c) => c.deposit, + None => { + self.wallet + .execute(Request::VerifyVoucher { + funding: funding.clone(), + voucher: voucher.clone(), + }) + .await? + .deposit + } + }; + // A newly verified nonzero voucher gives standing once admitted. + let standing = stored.is_none() && voucher.cum > 0; + ensure!( + voucher.cum >= terms.cum_before.saturating_add(terms.upfront), + "voucher does not cover the quoted voucher and upfront" + ); + let admit = |r: &mut Row, c: &mut Channel| { + ensure!( + r.state == State::Negotiating, + "request consumed concurrently" + ); + if c.voucher.is_none() || voucher.cum > c.cum() { + c.voucher = Some(voucher); + } + c.deposit = deposit; + c.active_at = now(); + r.channel = Some(key.clone()); + r.cum_after = Some(c.cum()); + r.state = State::Ready; + Ok(()) + }; + if existing.is_none() { + let mut channel = Channel::new(pair.clone(), row.peer.clone(), true, deposit)?; + channel.funding = Some(funding); + channel.state = ChannelState::Open; + self.ledger.mpp_insert_channel(&row.id, &channel, admit)?; + } else { + self.ledger.mpp_update_both(&row.id, &key, 0, admit)?; + } + if standing { + self.seller_grant_standing(&row.peer); + } + self.mpp_send(&row.peer, &row.id, Wire::Ready).await + } + pub(super) async fn seller_payment( + &self, + row: &Row, + funding: ChannelFunding, + voucher: Voucher, + ) -> Result<()> { + let key = row.channel.clone().context("missing channel")?; + let channel = self.ledger.channel_get(&key)?.context("unknown channel")?; + ensure!( + channel.funding.as_ref() == Some(&funding), + "voucher for another channel" + ); + // A closing channel keeps the voucher its capture was fixed with. + if channel.state != ChannelState::Open || voucher.cum <= channel.cum() { + return Ok(()); + } + let deposit = self + .wallet + .execute(Request::VerifyVoucher { + funding, + voucher: voucher.clone(), + }) + .await? + .deposit; + self.seller_grant_standing(&row.peer); + let running_total = row.bill.as_ref().context("missing bill")?.running_total; + self.ledger.mpp_update_both(&row.id, &key, 0, |r, c| { + if c.state == ChannelState::Open && voucher.cum > c.cum() { + c.voucher = Some(voucher); + c.deposit = deposit; + } + if r.state == State::Billed && c.cum() >= running_total { + r.state = State::Closed; + r.cum_after = Some(c.cum()); + } + Ok(()) + }) + } + /// Sends the bill until a voucher covers it, or closes the channel once + /// the payment time is over. + pub(super) async fn seller_collect(&self, row: Row) -> Result<()> { + let bill = row.bill.clone().context("missing bill")?; + let sent = self + .mpp_send(&row.peer, &row.id, Wire::Bill(bill.clone())) + .await; + // The payment time starts with the first bill the buyer could receive. + let billed_at = match (&sent, row.billed_at) { + (Ok(()), 0) => now(), + (_, at) => at, + }; + let unpaid = + billed_at > 0 && now() >= billed_at.saturating_add(channel::BILL_PAYMENT_SECONDS); + let key = row.channel.clone().context("missing channel")?; + self.ledger.mpp_update_both(&row.id, &key, 0, |r, c| { + ensure!(r.state == State::Billed, "request changed concurrently"); + r.billed_at = billed_at; + // Only a bill the buyer could receive is settled, even from credit. + if billed_at > 0 && c.cum() >= bill.running_total { + r.state = State::Closed; + r.cum_after = Some(c.cum()); + } else if unpaid { + r.state = State::Closed; + r.error = Some("bill unpaid; the channel is closed with the best voucher".into()); + c.lost_bills += 1; + channel::start_close(c, "a bill is unpaid"); + } + Ok(()) + })?; + sent + } + pub(super) async fn mpp_seller_hook(&self, event: &Value) -> Result { + let result = self.mpp_admit_seller(event).await; + Ok(match result { + Ok(()) => allow(), + Err(error) => deny(&error.to_string()), + }) + } + async fn mpp_admit_seller(&self, event: &Value) -> Result<()> { + let peer = event["requested_by_node_id"] + .as_str() + .context("missing authenticated buyer")?; + // The body digest binds the forwarded request to the agreed bill cap. + let intent = request_intent(event, "")?; + let row = self + .seller_agreement(peer, &intent.body_digest)? + .context("negotiate MPP payment before inference")?; + let id = row.id.as_str(); + let intent = Intent { + payer: row.intent.payer.clone(), + ..intent + }; + ensure!( + row.intent == intent, + "inference differs from approved request" + ); + let observation = serving::correlation(event)?; + if row.state == State::Running && row.observation.as_deref() == Some(observation) { + return Ok(()); + } + ensure!( + row.state == State::Ready, + "payment not ready or request already executed" + ); + ensure!( + self.wallet_info.can_send, + "MPP seller must unlock wallet for capture and refund" + ); + ensure!( + row.terms.as_ref().is_some_and(|t| t.expires_at > now()), + "quote expired" + ); + // The voucher was verified on chain when the request became ready. + let key = row.channel.clone().context("missing channel")?; + self.ledger.mpp_update_both(id, &key, 0, |r, c| { + ensure!(r.state == State::Ready, "request consumed concurrently"); + ensure!(c.state == ChannelState::Open, "channel is closing"); + r.state = State::Running; + r.observation = Some(observation.into()); + c.active_at = now(); + Ok(()) + }) + } +} +/// Bills known terminal usage on the seller's open channel, numbering the +/// bill; unknown usage is never billed as zero. Returns whether the request +/// can progress. +pub(super) fn bill(r: &mut Row, c: &mut Channel, usage: Option) -> Result { + if let Some(usage) = usage { + ensure!( + r.usage.is_none_or(|old| old == usage), + "terminal usage changed" + ); + r.usage = Some(usage); + if r.state == State::Closed || r.bill.is_some() { + return Ok(false); + } + if r.superseded { + r.state = State::Closed; + r.error = Some("usage arrived after the channel moved on; not billed".into()); + return Ok(false); + } + // The capture was fixed when closing started. + if c.state != ChannelState::Open { + r.state = State::Closed; + r.error = Some("usage arrived after the channel began closing; not billed".into()); + return Ok(false); + } + ensure!( + matches!(r.state, State::Running | State::UsageUnknown), + "request was not dispatched" + ); + let cost = r + .terms + .as_ref() + .context("missing agreed rates")? + .bill(usage); + let running_total = c.running_total.saturating_add(cost); + r.bill = Some(Bill { + seq: c.bills, + usage: Some(usage), + cost, + running_total, + }); + r.state = State::Billed; + c.running_total = running_total; + c.bills += 1; + c.active_at = now(); + } else if r.state == State::Running { + r.state = State::UsageUnknown; + r.error = + Some("terminal usage unavailable; no zero bill invented; operator may waive".into()); + } + Ok(r.state != State::Closed) +} diff --git a/src/engine_sequence_tests.rs b/src/engine_sequence_tests.rs new file mode 100644 index 0000000..1f30688 --- /dev/null +++ b/src/engine_sequence_tests.rs @@ -0,0 +1,251 @@ +//! Back-to-back requests on one pair: busy answers, unbilled notices, +//! reordered bills, and a node that both buys from and sells to a peer. +use super::*; + +/// Delivers every message `from` has queued to `to`. +pub(super) async fn deliver(from: &Engine, to: &Engine) { + let messages: Vec<_> = from.outbox.lock().unwrap().drain(..).collect(); + for (_, message) in messages { + to.message(&from.node, message).await.unwrap(); + } +} +/// Starts the buyer's admission hook for a new request and hands its hello +/// to the seller, without delivering the seller's answer. +pub(super) async fn hello( + buyer: &Arc, + seller: &Engine, + tag: &str, +) -> tokio::task::JoinHandle> { + let task = { + let buyer = buyer.clone(); + let request = event(tag); + tokio::spawn(async move { buyer.hook(request).await }) + }; + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while buyer.outbox.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + deliver(buyer, seller).await; + task +} +/// The admission decision once all messages flow freely again. +pub(super) async fn settle( + buyer: &Engine, + seller: &Engine, + task: tokio::task::JoinHandle>, +) -> OpenAiExchangeDecision { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while !task.is_finished() { + pump(buyer, seller).await.unwrap(); + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + task.await.unwrap().unwrap() +} + +#[tokio::test] +async fn unknown_usage_after_a_seller_restart_is_never_billed_and_the_next_request_proceeds() { + let (bd, sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + let serving = admit(&buyer, &seller, &id).await; + terminal(&buyer, "buyer", &id, &usage(1, 4)).await; + drop((buyer, seller)); + let buyer = engine(bd.path(), false, chain.clone()); + let seller = engine(sd.path(), true, chain.clone()); + assert_eq!(row(&seller, &id).state, State::UsageUnknown); + assert_eq!(row(&buyer, &id).state, State::Running); + // The interrupted inference is never replayed. + assert_eq!( + seller.hook(serving).await.unwrap().decision, + OpenAiAdmissionDecision::Deny + ); + // The seller's notice closes the buyer's request unpaid at once. + seller.retry().await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + let unpaid = row(&buyer, &id); + assert_eq!(unpaid.state, State::Closed); + assert!(unpaid.error.unwrap().contains("never bills it")); + let unknown = row(&seller, &id); + assert_eq!( + (&unknown.state, &unknown.bill), + (&State::UsageUnknown, &None) + ); + assert!(unknown.superseded && unknown.unbilled_seen); + // An acknowledged notice is not repeated. + seller.retry().await.unwrap(); + assert!(seller.outbox.lock().unwrap().is_empty()); + let next = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &next).await; + assert_eq!(row(&seller, &next).terms.unwrap().upfront, 0); + finish(&buyer, &seller, &next, usage(1, 4), false).await; + assert_eq!(row(&buyer, &next).state, State::Closed); + // Usage that arrives after the notice is recorded, not billed. + let late = json!({"phase":"exchange_finished","observation_id":format!("seller-{id}"),"usage":usage(2, 3)}); + assert!(seller.record_terminal(&late).unwrap().is_none()); + let recorded = row(&seller, &id); + assert_eq!(recorded.state, State::Closed); + assert_eq!(recorded.usage.map(|u| u.prompt_tokens), Some(2)); + assert!(recorded.bill.is_none()); + assert!(recorded.error.unwrap().contains("not billed")); + for side in [channel(&buyer), channel(&seller)] { + assert_eq!((side.cum(), side.running_total), (10, 5)); + } + assert_eq!(Chain::count(&chain.closes), 0); +} + +#[tokio::test] +async fn a_waiver_bills_zero_before_a_later_quote_and_only_records_after_one() { + for later in [false, true] { + let (_bd, sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + drop(seller); + let seller = engine(sd.path(), true, chain.clone()); + terminal(&buyer, "buyer", &id, &usage(1, 4)).await; + let next = uuid::Uuid::new_v4().to_string(); + if later { + admit(&buyer, &seller, &next).await; + } + seller.mpp_control(&rid(&id), "waive").await.unwrap(); + pump(&buyer, &seller).await.unwrap(); + let (bought, sold) = (row(&buyer, &id), row(&seller, &id)); + assert_eq!((bought.state, sold.state), (State::Closed, State::Closed)); + assert_eq!(sold.usage, None); + // Before a later quote the zero bill settles the buyer's request. + assert_eq!(bought.error.is_none(), !later); + assert_eq!(sold.bill.is_some(), !later); + assert_eq!(channel(&buyer).running_total, 0); + if !later { + admit(&buyer, &seller, &next).await; + } + assert_eq!(row(&seller, &next).terms.unwrap().upfront, 0); + assert_eq!(Chain::count(&chain.closes), 0); + } +} + +#[tokio::test] +async fn an_identical_request_sent_before_the_seller_has_the_previous_payment_waits() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + // A bill of 24 exceeds the credit of 10, so it needs a new voucher. + terminal(&seller, "seller", &id, &usage(20, 4)).await; + terminal(&buyer, "buyer", &id, &usage(20, 4)).await; + deliver(&seller, &buyer).await; + assert_eq!(row(&buyer, &id).state, State::Closed); + // The paying voucher reaches the seller only after the next hello, for + // the same body, which waits for it. + let voucher: Vec<_> = buyer.outbox.lock().unwrap().drain(..).collect(); + assert_eq!(voucher.len(), 1); + let next = uuid::Uuid::new_v4().to_string(); + let task = hello(&buyer, &seller, &next).await; + assert!(matches!( + &seller.outbox.lock().unwrap()[..], + [(_, Message::Mpp { message, .. })] if matches!(message.as_ref(), Wire::Busy) + )); + deliver(&seller, &buyer).await; + assert!(row(&buyer, &next).busy); + for (_, message) in voucher { + seller.message(&buyer.node, message).await.unwrap(); + } + let decision = settle(&buyer, &seller, task).await; + assert_eq!( + decision.decision, + OpenAiAdmissionDecision::Allow, + "{:?}", + decision.reason + ); + assert_eq!(row(&seller, &next).terms.unwrap().cost_before, 24); + assert_eq!(Chain::count(&chain.opens), 1); +} + +#[tokio::test] +async fn a_covered_bill_delivered_after_the_next_quote_does_not_recover_the_channel() { + let (_bd, _sd, chain, buyer, seller) = pair(); + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + // The upfront credit of 10 covers the bill of 5, so the seller is done. + terminal(&seller, "seller", &id, &usage(1, 4)).await; + assert_eq!(row(&seller, &id).state, State::Closed); + let bill: Vec<_> = seller.outbox.lock().unwrap().drain(..).collect(); + terminal(&buyer, "buyer", &id, &usage(1, 4)).await; + let next = uuid::Uuid::new_v4().to_string(); + let task = hello(&buyer, &seller, &next).await; + // The quote, which counts the bill, overtakes it. + deliver(&seller, &buyer).await; + let waiting = row(&buyer, &next); + assert_eq!(waiting.state, State::Negotiating); + assert_eq!(waiting.terms.unwrap().cost_before, 5); + assert_eq!(channel(&buyer).state, ChannelState::Open); + for (_, message) in bill { + buyer.message(&seller.node, message).await.unwrap(); + } + let decision = settle(&buyer, &seller, task).await; + assert_eq!( + decision.decision, + OpenAiAdmissionDecision::Allow, + "{:?}", + decision.reason + ); + let paid = row(&buyer, &id); + assert_eq!((paid.state, paid.error), (State::Closed, None)); + let open = channel(&buyer); + assert_eq!((open.state, open.running_total), (ChannelState::Open, 5)); + assert_eq!(Chain::count(&chain.recovers), 0); +} + +#[tokio::test] +async fn a_node_can_buy_from_and_sell_to_the_same_peer_at_once() { + let (_bd, _sd, _chain, buyer, seller) = pair(); + // The buyer also sells the model, and the seller also buys it. + buyer + .ledger + .set_pricing("model", Some(&price(1_000_000))) + .unwrap(); + seller.ledger.set_policy(&automatic(10000)).unwrap(); + let reverse = uuid::Uuid::new_v4().to_string(); + let intent = request_intent(&event(&reverse), &seller.wallet_info.address).unwrap(); + buyer + .message(&seller.node, mpp(&reverse, Wire::Hello { intent })) + .await + .unwrap(); + buyer.outbox.lock().unwrap().clear(); + assert!(row(&buyer, &reverse).seller); + // With that seller request open, the node still buys from the peer. + let id = uuid::Uuid::new_v4().to_string(); + admit(&buyer, &seller, &id).await; + let roles: Vec<_> = buyer + .ledger + .mpp_active() + .unwrap() + .iter() + .map(|r| (r.peer.clone(), r.seller)) + .collect(); + assert_eq!( + roles, + [(seller.node.clone(), true), (seller.node.clone(), false)] + ); + // And the peer, serving that request, buys from the node in turn. + buyer + .ledger + .mpp_update(&reverse, |r| { + r.state = State::Closed; + Ok(()) + }) + .unwrap(); + let mut request = event(&uuid::Uuid::new_v4().to_string()); + request["target_peer_id"] = json!(buyer.node); + let decision = decide(&seller, &buyer, request).await; + assert_eq!( + decision.decision, + OpenAiAdmissionDecision::Allow, + "{:?}", + decision.reason + ); + assert_eq!(row(&seller, &id).state, State::Running); +} diff --git a/src/engine_serving.rs b/src/engine_serving.rs new file mode 100644 index 0000000..e3f10a5 --- /dev/null +++ b/src/engine_serving.rs @@ -0,0 +1,106 @@ +//! Tie authenticated serving ingress to the host's post-resolution admission hook. +use super::*; + +pub(super) struct RemoteIngress { + peer: String, + body: Option, + endpoint: Option, +} + +/// Observation IDs are host-minted and shared by this node's lifecycle phases. +pub(super) fn correlation(event: &Value) -> Result<&str> { + let id = event["observation_id"] + .as_str() + .or_else(|| event["exchange_id"].as_str()) + .context("host exchange correlation is missing")?; + ensure!( + !id.is_empty() && id.len() <= 256, + "invalid host exchange correlation" + ); + Ok(id) +} + +impl Engine { + pub(super) fn remember_ingress(&self, event: &Value) -> Result<()> { + if event["phase"] != "request_received" { + return Ok(()); + } + let Some(peer) = event["requested_by_node_id"].as_str() else { + return Ok(()); + }; + validate_peer(peer)?; + let key = correlation(event)?; + let mut ingress = self.ingress.lock().unwrap(); + ensure!( + ingress.contains_key(key) || ingress.len() < 256, + "paid serving request tracking capacity exhausted" + ); + if let Some(existing) = ingress.get(key) { + ensure!( + existing.peer == peer, + "authenticated serving peer changed within one observation" + ); + return Ok(()); + } + let body = event.get("body").filter(|body| !body.is_null()).cloned(); + if let Some(body) = &body { + ensure!( + serde_json::to_vec(body)?.len() <= 64 * 1024, + "serving request body exceeds tracking limit" + ); + } + ingress.insert( + key.into(), + RemoteIngress { + peer: peer.into(), + body, + endpoint: event["endpoint"].as_str().map(str::to_owned), + }, + ); + Ok(()) + } + pub(super) fn restore_ingress(&self, event: &mut Value) { + if event["phase"] != "backend_selected" { + return; + } + let Ok(key) = correlation(event) else { + return; + }; + let ingress = self.ingress.lock().unwrap(); + let Some(original) = ingress.get(key) else { + return; + }; + event["requested_by_node_id"] = Value::String(original.peer.clone()); + if event.get("body").is_none_or(Value::is_null) + && let Some(body) = &original.body + { + event["body"] = body.clone(); + } + if event.get("endpoint").is_none_or(Value::is_null) + && let Some(endpoint) = &original.endpoint + { + event["endpoint"] = Value::String(endpoint.clone()); + } + } + /// Whether a forwarded request is for a priced model, or for the model of + /// an agreement its buyer already made, even if the price is gone now. + pub(super) fn is_remote_paid_selection(&self, event: &Value) -> Result { + let (Some(peer), Some(model)) = ( + event["requested_by_node_id"].as_str(), + event["model"].as_str(), + ) else { + return Ok(false); + }; + Ok(self.ledger.paid_price(model)?.is_some() + || self + .ledger + .mpp_active()? + .iter() + .any(|r| r.seller && r.peer == peer && r.holds_peer() && r.intent.model == model)) + } + pub(super) fn forget_ingress(&self, event: &Value) { + if let Ok(key) = correlation(event) { + self.ingress.lock().unwrap().remove(key); + } + } +} diff --git a/src/engine_watch_tests.rs b/src/engine_watch_tests.rs new file mode 100644 index 0000000..9e4a7e5 --- /dev/null +++ b/src/engine_watch_tests.rs @@ -0,0 +1,132 @@ +//! The seller's close watch: close events name the channels a tick inspects, +//! with a backstop that inspects every channel. +use super::*; +use std::sync::atomic::Ordering::SeqCst; + +/// Opens a seller channel from buyer `n` on the in-memory reserve. +fn seller_channel(chain: &Chain, seller: &Engine, n: u8) -> Channel { + let byte = format!("{n:02x}"); + let terms = ChannelTerms { + buyer_peer: byte.repeat(32), + seller_peer: seller.node.clone(), + payer: format!("0x{}", byte.repeat(20)), + payee: seller.wallet_info.address.clone(), + asset: seller.wallet_info.asset.clone(), + nonce: byte.repeat(32), + }; + let funding = chain + .apply(Request::Open { + terms: terms.clone(), + deposit: 100, + max_fee: 0, + }) + .unwrap() + .funding + .unwrap(); + let mut channel = Channel::new(terms.clone(), terms.buyer_peer, true, 100).unwrap(); + channel.funding = Some(funding); + channel.state = ChannelState::Open; + seller.ledger.channel_insert(&channel).unwrap(); + channel +} +/// A chain with event logs at block 10 and `n` open seller channels, after +/// the first tick, which inspects every channel. +async fn watched(n: u8) -> (Pair, Vec) { + let pair = pair(); + let (_, _, chain, _, seller) = &pair; + *chain.logs.lock().unwrap() = Some(Vec::new()); + chain.height.store(10, SeqCst); + let channels: Vec<_> = (1..=n).map(|n| seller_channel(chain, seller, n)).collect(); + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.inspects), usize::from(n)); + assert_eq!(seller.ledger.close_cursor().unwrap(), Some(10)); + (pair, channels) +} +/// Requests close on `channel` at `at`, with a log at `block` when given. +fn request_close(chain: &Chain, channel: &Channel, at: u64, block: Option) { + let id = channel.funding.clone().unwrap().channel_id; + chain.request_close(&id, at); + if let Some(block) = block { + chain + .logs + .lock() + .unwrap() + .as_mut() + .unwrap() + .push((block, id)); + chain.height.store(block + 3, SeqCst); + } +} +fn state(seller: &Engine, channel: &Channel) -> ChannelState { + seller + .ledger + .channel_get(&channel.key) + .unwrap() + .unwrap() + .state +} + +#[tokio::test] +async fn a_close_event_inspects_only_the_channel_it_names() { + let ((_bd, _sd, chain, _buyer, seller), channels) = watched(3).await; + request_close(&chain, &channels[1], now(), Some(12)); + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.inspects), 4); + assert_eq!(Chain::count(&chain.closes), 1); + for (n, c) in channels.iter().enumerate() { + assert_eq!(state(&seller, c) == ChannelState::Closed, n == 1); + } + // A quiet tick reads no channel. + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.inspects), 4); +} + +#[tokio::test] +async fn a_failed_scan_keeps_the_cursor_and_inspects_every_channel() { + let ((_bd, _sd, chain, _buyer, seller), channels) = watched(2).await; + request_close(&chain, &channels[0], now(), Some(15)); + chain.logs_fail.store(true, SeqCst); + // Without a cursor move the close request is still found, by inspection. + seller.retry().await.unwrap(); + assert_eq!(seller.ledger.close_cursor().unwrap(), Some(10)); + assert_eq!(Chain::count(&chain.inspects), 4); + assert_eq!(state(&seller, &channels[0]), ChannelState::Closed); + chain.logs_fail.store(false, SeqCst); + seller.retry().await.unwrap(); + assert_eq!(seller.ledger.close_cursor().unwrap(), Some(18)); +} + +#[tokio::test] +async fn the_backstop_finds_a_close_request_without_a_log() { + let ((_bd, _sd, chain, _buyer, seller), channels) = watched(2).await; + request_close(&chain, &channels[0], now(), None); + seller.retry().await.unwrap(); + assert_eq!(state(&seller, &channels[0]), ChannelState::Open); + seller.watch.lock().unwrap().polled_at = 0; + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.inspects), 4); + assert_eq!(state(&seller, &channels[0]), ChannelState::Closed); +} + +#[tokio::test] +async fn a_deferred_close_is_checked_every_tick_without_another_log() { + let (_bd, _sd, chain, buyer, seller) = pair(); + *chain.logs.lock().unwrap() = Some(Vec::new()); + chain.height.store(10, SeqCst); + admit(&buyer, &seller, &uuid::Uuid::new_v4().to_string()).await; + seller.retry().await.unwrap(); + let open = channel(&seller); + // The running request defers the close. + request_close(&chain, &open, now(), Some(12)); + seller.retry().await.unwrap(); + let inspected = Chain::count(&chain.inspects); + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.inspects), inspected + 1); + assert_eq!(state(&seller, &open), ChannelState::Open); + assert_eq!(Chain::count(&chain.closes), 0); + // Once the deferral is over, the next tick closes without a new log. + request_close(&chain, &open, now() - 600, None); + seller.retry().await.unwrap(); + assert_eq!(Chain::count(&chain.closes), 1); + assert_eq!(state(&seller, &open), ChannelState::Closed); +} diff --git a/src/fixtures/mod.rs b/src/fixtures/mod.rs new file mode 100644 index 0000000..4edb6a4 --- /dev/null +++ b/src/fixtures/mod.rs @@ -0,0 +1,82 @@ +//! Explicit in-process fake wallet for the separately built offline entry point. +mod settlement; + +use crate::{ + config::Config, + contract::{Asset, Balance, Network, WalletInfo}, + wallet::{Backend, OpenedWallet, WalletFuture}, +}; +use anyhow::{Context, Result, ensure}; +use rusqlite::Connection; +use serde_json::Value; +use std::{ + path::PathBuf, + sync::{Arc, Mutex}, +}; + +struct Fixture { + connection: Mutex, + address: String, +} + +pub(crate) fn load_wallet( + config: &Config, + _db: crate::ledger::Database, +) -> WalletFuture<'_, OpenedWallet> { + Box::pin(async move { + ensure!( + config.wallet.network == Network::Testnet, + "offline fixture entry point requires testnet configuration" + ); + let path = PathBuf::from( + std::env::var("MESH_LLM_OFFLINE_CHAIN_PATH") + .context("explicit offline chain path required")?, + ); + ensure!(path.is_absolute(), "offline chain path must be absolute"); + let address = std::env::var("MESH_LLM_OFFLINE_ADDRESS") + .context("explicit offline address required")?; + crate::contract::validate_address(&address)?; + let connection = Connection::open(path)?; + connection.busy_timeout(std::time::Duration::from_secs(10))?; + connection.execute_batch("PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS fixture_channels(id TEXT PRIMARY KEY,funding TEXT NOT NULL,deposit INTEGER NOT NULL,topups INTEGER NOT NULL,closure TEXT);")?; + let info = WalletInfo { + wallet_id: format!("OFFLINE-{address}"), + address: address.clone(), + asset: Asset::default(), + can_send: true, + }; + Ok(( + Arc::new(Fixture { + connection: Mutex::new(connection), + address, + }) as Arc, + info, + )) + }) +} +impl Backend for Fixture { + fn execute( + &self, + request: crate::contract::mpp::Request, + ) -> WalletFuture<'_, crate::contract::mpp::Response> { + Box::pin(async move { self.execute_request(request) }) + } + fn balance(&self) -> WalletFuture<'_, Balance> { + Box::pin(async { + Ok(Balance { + balance: 1_000_000_000, + reserved: 0, + spendable: 1_000_000_000, + block_number: 10, + }) + }) + } + fn attempts(&self) -> Result> { + let db = self.connection.lock().unwrap(); + let mut query = + db.prepare("SELECT funding,deposit,closure FROM fixture_channels ORDER BY rowid")?; + query.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, u64>(1)?, r.get::<_, Option>(2)?)))? + .map(|row| { let (funding, deposit, closure)=row?; Ok(serde_json::json!({"funding":serde_json::from_str::(&funding)?, "deposit":deposit.to_string(), "closure":closure.map(|s| serde_json::from_str::(&s)).transpose()?})) }) + .collect() + } +} diff --git a/src/fixtures/settlement.rs b/src/fixtures/settlement.rs new file mode 100644 index 0000000..c86b923 --- /dev/null +++ b/src/fixtures/settlement.rs @@ -0,0 +1,168 @@ +//! Fabricated reserve state for host IPC smoke tests, never chain evidence. +use super::Fixture; +use crate::contract::mpp::{ChannelFunding, Closure, Request, Response, Voucher}; +use anyhow::{Context, Result, ensure}; +use rusqlite::{OptionalExtension, Transaction, params}; + +struct Channel { + funding: ChannelFunding, + deposit: u64, + topups: u32, + closure: Option, +} +fn load(tx: &Transaction, id: &str) -> Result> { + tx.query_row( + "SELECT funding,deposit,topups,closure FROM fixture_channels WHERE id=?1", + [id], + |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, u64>(1)?, + r.get::<_, u32>(2)?, + r.get::<_, Option>(3)?, + )) + }, + ) + .optional()? + .map(|(funding, deposit, topups, closure)| { + Ok(Channel { + funding: serde_json::from_str(&funding)?, + deposit, + topups, + closure: closure.map(|c| serde_json::from_str(&c)).transpose()?, + }) + }) + .transpose() +} +/// The fabricated channel `funding` names, which must match it exactly. +fn channel(tx: &Transaction, funding: &ChannelFunding) -> Result { + let channel = load(tx, &funding.channel_id)?.context("unknown fixture channel")?; + ensure!(channel.funding == *funding, "fixture funding mismatch"); + Ok(channel) +} +fn signature(cum: u64) -> String { + format!("OFFLINE-voucher-{cum}") +} + +impl Fixture { + pub(super) fn execute_request(&self, request: Request) -> Result { + let mut db = self.connection.lock().unwrap(); + let tx = db.transaction()?; + let response = match request { + Request::Open { terms, deposit, .. } => { + terms.validate()?; + ensure!(terms.payer == self.address, "fixture payer mismatch"); + let funding = ChannelFunding { + channel_id: terms.salt()?, + open_tx: format!("OFFLINE-open-{}", terms.nonce), + expiring_nonce_hash: "OFFLINE-context".into(), + terms, + }; + if let Some(old) = load(&tx, &funding.channel_id)? { + ensure!(old.funding == funding, "fixture intent changed"); + } else { + tx.execute( + "INSERT INTO fixture_channels(id,funding,deposit,topups) VALUES(?1,?2,?3,0)", + params![funding.channel_id, serde_json::to_string(&funding)?, deposit], + )?; + } + Response { + funding: Some(funding), + deposit, + ..Default::default() + } + } + Request::TopUp { + funding, + amount, + index, + .. + } => top_up(&tx, &funding, amount, index)?, + Request::SignVoucher { funding, cum } => Response { + voucher: Some(Voucher { + channel_id: funding.channel_id, + cum, + signature: signature(cum), + }), + ..Default::default() + }, + Request::VerifyVoucher { funding, voucher } => { + let channel = channel(&tx, &funding)?; + ensure!( + channel.closure.is_none() + && voucher.channel_id == funding.channel_id + && voucher.signature == signature(voucher.cum) + && voucher.cum <= channel.deposit, + "fixture voucher not backed" + ); + Response { + deposit: channel.deposit, + ..Default::default() + } + } + Request::Inspect { funding } => { + let channel = channel(&tx, &funding)?; + Response { + deposit: channel.deposit, + closure: channel.closure, + ..Default::default() + } + } + Request::Close { + funding, + voucher, + capture, + } => { + ensure!( + funding.terms.payee == self.address + && capture <= voucher.as_ref().map_or(0, |v| v.cum), + "fixture capture not authorized" + ); + close(&tx, &funding, capture)? + } + Request::Recover { .. } => anyhow::bail!( + "host smoke fixture does not simulate grace recovery; use native RPC tests" + ), + }; + tx.commit()?; + Ok(response) + } +} +fn top_up(tx: &Transaction, funding: &ChannelFunding, amount: u64, index: u32) -> Result { + let mut channel = channel(tx, funding)?; + ensure!(channel.closure.is_none(), "fixture channel closed"); + if index == channel.topups + 1 { + channel.deposit += amount; + tx.execute( + "UPDATE fixture_channels SET deposit=?2,topups=?3 WHERE id=?1", + params![funding.channel_id, channel.deposit, index], + )?; + } else { + ensure!(index <= channel.topups, "fixture top-up skipped an index"); + } + Ok(Response { + deposit: channel.deposit, + ..Default::default() + }) +} +fn close(tx: &Transaction, funding: &ChannelFunding, capture: u64) -> Result { + let channel = channel(tx, funding)?; + let closure = Closure { + tx_hash: format!("OFFLINE-close-{}", funding.terms.nonce), + channel_id: funding.channel_id.clone(), + captured: capture, + refunded: channel.deposit - capture, + block_number: 10, + }; + if let Some(old) = channel.closure { + ensure!(old == closure, "fixture close changed"); + } + tx.execute( + "UPDATE fixture_channels SET closure=?2 WHERE id=?1", + params![funding.channel_id, serde_json::to_string(&closure)?], + )?; + Ok(Response { + closure: Some(closure), + ..Default::default() + }) +} diff --git a/src/ledger.rs b/src/ledger.rs new file mode 100644 index 0000000..344602b --- /dev/null +++ b/src/ledger.rs @@ -0,0 +1,844 @@ +use crate::config::now; +use crate::contract::mpp::{Bill, ChannelFunding, ChannelTerms, Closure, RequestTerms, Voucher}; +use crate::protocol::Intent; +use anyhow::{Context, Result, ensure}; +use fs2::FileExt; +use rusqlite::{Connection, OptionalExtension, Transaction, params}; +use serde::{Deserialize, Serialize}; +use std::{ + fs::{File, OpenOptions}, + path::Path, + sync::{Arc, Mutex}, +}; + +#[path = "ledger_settings.rs"] +mod settings; + +/// The payment state database, shared with the wallet's transaction journal. +pub type Database = Arc>; + +const VERSION: u32 = 1; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum State { + Negotiating, + Ready, + Running, + UsageUnknown, + /// The seller billed the request and awaits a voucher covering it. + Billed, + Closed, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Request { + pub id: String, + pub peer: String, + pub seller: bool, + pub intent: Intent, + pub terms: Option, + /// The key of the channel this request is paid from. + pub channel: Option, + pub state: State, + pub observation: Option, + /// The seller's terminal usage, or the usage the buyer observed itself. + pub usage: Option, + pub bill: Option, + /// When the seller first sent the bill; 0 until then. + pub billed_at: u64, + /// The channel's voucher after this request's admission or bill. + pub cum_after: Option, + pub error: Option, + /// The seller quoted a later request on this pair, or told the buyer that + /// this one is never billed, while its usage was unknown. + #[serde(default)] + pub superseded: bool, + /// The buyer acknowledged the seller's notice that this request is never + /// billed. + pub unbilled_seen: bool, + /// The seller answered the buyer's hello as busy; the buyer says hello + /// again within its admission wait. + pub busy: bool, +} +impl Request { + pub fn new(id: String, peer: String, seller: bool, intent: Intent) -> Self { + Self { + id, + peer, + seller, + intent, + terms: None, + channel: None, + state: State::Negotiating, + observation: None, + usage: None, + bill: None, + billed_at: 0, + cum_after: None, + error: None, + superseded: false, + unbilled_seen: false, + busy: false, + } + } + /// Whether the request takes its peer's slot for its body in its role, so + /// identical bodies run one at a time. Unknown usage does not, nor does a + /// buyer's finished request awaiting its bill or the seller's notice that + /// none follows. + pub fn holds_peer(&self) -> bool { + match self.state { + State::Closed | State::UsageUnknown => false, + State::Running => self.seller || self.usage.is_none(), + _ => true, + } + } + /// The `active` column: 0 when closed, 1 while it holds the peer's slot + /// for its body, and 2 while it stays open without it. + fn activity(&self) -> u8 { + match (self.state == State::Closed, self.holds_peer()) { + (true, _) => 0, + (false, true) => 1, + (false, false) => 2, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ChannelState { + Opening, + Open, + Closing, + Closed, +} + +/// One buyer-seller channel, reused by requests until it closes. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Channel { + pub key: String, + pub peer: String, + pub seller: bool, + pub terms: ChannelTerms, + pub funding: Option, + #[serde(with = "crate::contract::decimal")] + pub deposit: u64, + /// Finalized top-ups, so a retried top-up keeps its index. + pub topups: u32, + /// The buyer's highest signed voucher, or the seller's best received one. + pub voucher: Option, + /// The sum of bills: sent by the seller, acknowledged by the buyer. + #[serde(with = "crate::contract::decimal")] + pub running_total: u64, + /// The number of bills: sent by the seller, accepted in order by the buyer. + pub bills: u64, + /// The seller's bills this channel closed without being paid. + pub lost_bills: u64, + /// The operator forgave the lost bills, so they no longer count as strikes. + pub forgiven: bool, + pub active_at: u64, + pub state: ChannelState, + /// The seller's capture, fixed when closing starts. + pub capture: Option, + pub closure: Option, + pub error: Option, +} +impl Channel { + pub fn new(terms: ChannelTerms, peer: String, seller: bool, deposit: u64) -> Result { + Ok(Self { + key: terms.salt()?, + peer, + seller, + terms, + funding: None, + deposit, + topups: 0, + voucher: None, + running_total: 0, + bills: 0, + lost_bills: 0, + forgiven: false, + active_at: now(), + state: ChannelState::Opening, + capture: None, + closure: None, + error: None, + }) + } + pub fn cum(&self) -> u64 { + self.voucher.as_ref().map_or(0, |v| v.cum) + } +} + +pub struct Ledger { + pub(crate) db: Database, + _lock: File, +} +impl Ledger { + pub fn open(directory: &Path) -> Result { + std::fs::create_dir_all(directory)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700))?; + } + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let lock = options.open(directory.join("payments.lock"))?; + lock.try_lock_exclusive() + .context("another payment engine owns this state directory")?; + let path = directory.join("payments.sqlite"); + let _private_db = options.open(&path)?; + let mut db = Connection::open(path)?; + let version: u32 = db.pragma_query_value(None, "user_version", |row| row.get(0))?; + ensure!( + version == 0 || version == VERSION, + "unsupported payment ledger version {version}; use a compatible plugin without resetting state" + ); + db.execute_batch( + "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;", + )?; + let tx = db.transaction()?; + // A request row's `active` is 1 only while it holds its peer's slot + // for its body in its role; see `Request::activity`. + tx.execute_batch("CREATE TABLE IF NOT EXISTS mpp_requests(id TEXT PRIMARY KEY,peer TEXT NOT NULL,active INTEGER NOT NULL,body TEXT NOT NULL); + CREATE UNIQUE INDEX IF NOT EXISTS mpp_one_body ON mpp_requests(peer,json_extract(body,'$.seller'),json_extract(body,'$.intent.body_digest')) WHERE active=1; + CREATE TABLE IF NOT EXISTS channels(key TEXT PRIMARY KEY,peer TEXT NOT NULL,seller INTEGER NOT NULL,active INTEGER NOT NULL,body TEXT NOT NULL); + CREATE UNIQUE INDEX IF NOT EXISTS channel_one_peer ON channels(peer,seller) WHERE active=1; + CREATE TABLE IF NOT EXISTS spend(day INTEGER PRIMARY KEY,amount INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY,value TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS identity(singleton INTEGER PRIMARY KEY CHECK(singleton=1),node TEXT,wallet_id TEXT,address TEXT,chain_id INTEGER); + INSERT OR IGNORE INTO identity(singleton) VALUES(1);")?; + tx.pragma_update(None, "user_version", VERSION)?; + tx.commit()?; + Ok(Self { + db: Arc::new(Mutex::new(db)), + _lock: lock, + }) + } + pub fn pin_node(&self, node: &str) -> Result<()> { + crate::config::validate_peer(node)?; + ensure!( + node == node.to_ascii_lowercase(), + "Mesh node identity must be canonical lowercase hexadecimal" + ); + let db = self.db.lock().unwrap(); + let pinned: Option = db.query_row("SELECT node FROM identity", [], |r| r.get(0))?; + match pinned { + Some(pinned) => ensure!( + pinned == node, + "stable Mesh identity required: node ID changed; restore the pinned node key and configure a persistent Mesh host identity" + ), + None => { + db.execute("UPDATE identity SET node=?1", [node])?; + } + } + Ok(()) + } + /// Voucher increments the buyer signed today. + pub fn spent_today(&self) -> Result { + spent(&self.db.lock().unwrap(), now() / 86400) + } + + pub fn mpp_get(&self, id: &str) -> Result> { + let db = self.db.lock().unwrap(); + let body: Option = db + .query_row( + "SELECT body FROM mpp_requests WHERE id=?1", + [request_key(id)], + |r| r.get(0), + ) + .optional()?; + Ok(body.map(|body| serde_json::from_str(&body)).transpose()?) + } + pub fn mpp_observed(&self, observation: &str) -> Result> { + let db = self.db.lock().unwrap(); + let mut query = db.prepare( + "SELECT body FROM mpp_requests WHERE json_extract(body,'$.observation')=?1 LIMIT 2", + )?; + let mut found = None; + for body in query.query_map([observation], |r| r.get::<_, String>(0))? { + ensure!(found.is_none(), "ambiguous terminal observation"); + found = Some(serde_json::from_str(&body?)?); + } + Ok(found) + } + pub fn mpp_active(&self) -> Result> { + let db = self.db.lock().unwrap(); + let mut query = + db.prepare("SELECT body FROM mpp_requests WHERE active<>0 ORDER BY rowid")?; + query + .query_map([], |r| r.get::<_, String>(0))? + .map(|body| Ok(serde_json::from_str(&body?)?)) + .collect() + } + pub fn mpp_history(&self, limit: u32) -> Result> { + ensure!((1..=100).contains(&limit), "history limit must be 1..100"); + let db = self.db.lock().unwrap(); + let mut query = db.prepare("SELECT body FROM mpp_requests ORDER BY rowid DESC LIMIT ?1")?; + query + .query_map([limit], |r| r.get::<_, String>(0))? + .map(|body| Ok(serde_json::from_str(&body?)?)) + .collect() + } + pub fn mpp_insert(&self, request: &Request) -> Result<()> { + let db = self.db.lock().unwrap(); + let key = request_key(&request.id); + ensure!( + !db.query_row( + "SELECT EXISTS(SELECT 1 FROM mpp_requests WHERE id=?1)", + [&key], + |r| r.get::<_, bool>(0) + )?, + "request identity already exists" + ); + db.execute( + "INSERT INTO mpp_requests VALUES(?1,?2,?3,?4)", + params![ + key, + request.peer, + request.activity(), + serde_json::to_string(request)? + ], + )?; + Ok(()) + } + /// Applies one state change to a request in a single transaction. + pub fn mpp_update( + &self, + id: &str, + update: impl FnOnce(&mut Request) -> Result, + ) -> Result { + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + let result = update_in(&tx, id, update)?; + tx.commit()?; + Ok(result) + } + /// Applies one state change to a request and its channel in a single + /// transaction. A buyer voucher increase counts against `daily_budget`. + pub fn mpp_update_both( + &self, + id: &str, + key: &str, + daily_budget: u64, + update: impl FnOnce(&mut Request, &mut Channel) -> Result, + ) -> Result { + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + let result = channel_update_in(&tx, key, Some(daily_budget), |channel| { + update_in(&tx, id, |request| update(request, channel)) + })?; + tx.commit()?; + Ok(result) + } + pub fn mpp_restart(&self) -> Result<()> { + for request in self.mpp_active()? { + self.mpp_update(&request.id, |r| { + // A buyer that already recorded its own usage can still verify its bill. + if r.state == State::Running && (r.seller || r.usage.is_none()) { + r.state = State::UsageUnknown; + r.error = Some(if r.seller {"restart interrupted terminal observation; usage is unknown, inference must not be replayed"} else {"restart interrupted the buyer's own usage observation; its bill cannot be verified"}.into()); + } + if !r.seller && matches!(r.state, State::Negotiating | State::Ready) {r.observation = None;} + Ok(()) + })?; + } + Ok(()) + } + + pub fn channel_insert(&self, channel: &Channel) -> Result<()> { + insert_channel(&self.db.lock().unwrap(), channel) + } + /// Inserts a seller's new channel and applies the request change that + /// uses it in a single transaction. + pub fn mpp_insert_channel( + &self, + id: &str, + channel: &Channel, + update: impl FnOnce(&mut Request, &mut Channel) -> Result, + ) -> Result { + ensure!(channel.seller, "buyer channels open before any voucher"); + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + insert_channel(&tx, channel)?; + let result = channel_update_in(&tx, &channel.key, None, |channel| { + update_in(&tx, id, |request| update(request, channel)) + })?; + tx.commit()?; + Ok(result) + } + /// Applies a channel's closing change and closes its active requests + /// with `reason` in a single transaction. + pub fn channel_close( + &self, + key: &str, + reason: &str, + update: impl FnOnce(&mut Channel) -> Result<()>, + ) -> Result<()> { + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + channel_update_in(&tx, key, None, update)?; + let ids = { + let mut query = tx.prepare( + "SELECT id FROM mpp_requests WHERE active<>0 AND json_extract(body,'$.channel')=?1", + )?; + query + .query_map([key], |r| r.get::<_, String>(0))? + .collect::>>()? + }; + for id in ids { + update_in(&tx, &id, |r| { + r.state = State::Closed; + r.error = Some(reason.into()); + Ok(()) + })?; + } + tx.commit()?; + Ok(()) + } + /// The most recently closed channel with `peer` in one role. + pub fn channel_last_closed(&self, peer: &str, seller: bool) -> Result> { + let db = self.db.lock().unwrap(); + let body: Option = db + .query_row( + "SELECT body FROM channels WHERE peer=?1 AND seller=?2 AND active=0 ORDER BY rowid DESC LIMIT 1", + params![peer, seller], + |r| r.get(0), + ) + .optional()?; + Ok(body.map(|body| serde_json::from_str(&body)).transpose()?) + } + pub fn channel_get(&self, key: &str) -> Result> { + let db = self.db.lock().unwrap(); + let body: Option = db + .query_row("SELECT body FROM channels WHERE key=?1", [key], |r| { + r.get(0) + }) + .optional()?; + Ok(body.map(|body| serde_json::from_str(&body)).transpose()?) + } + /// The open, opening or closing channel with `peer` in one role. + pub fn channel_active(&self, peer: &str, seller: bool) -> Result> { + let db = self.db.lock().unwrap(); + let body: Option = db + .query_row( + "SELECT body FROM channels WHERE peer=?1 AND seller=?2 AND active=1", + params![peer, seller], + |r| r.get(0), + ) + .optional()?; + Ok(body.map(|body| serde_json::from_str(&body)).transpose()?) + } + /// The seller's bills to `peer` that closed channels lost and the + /// operator has not forgiven. + pub fn lost_bills(&self, peer: &str) -> Result { + let db = self.db.lock().unwrap(); + Ok(db.query_row( + "SELECT COALESCE(SUM(json_extract(body,'$.lost_bills')),0) FROM channels WHERE peer=?1 AND seller=1 AND active=0 AND json_extract(body,'$.forgiven')=0", + [peer], + |r| r.get(0), + )?) + } + /// Forgives the seller's lost bills to `peer`; returns how many. + pub fn forgive_lost_bills(&self, peer: &str) -> Result { + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + let keys = { + let mut query = tx.prepare("SELECT key FROM channels WHERE peer=?1 AND seller=1 AND active=0 AND json_extract(body,'$.lost_bills')>0 AND json_extract(body,'$.forgiven')=0")?; + query + .query_map([peer], |r| r.get::<_, String>(0))? + .collect::>>()? + }; + let mut forgiven = 0; + for key in keys { + forgiven += channel_update_in(&tx, &key, None, |c| { + c.forgiven = true; + Ok(c.lost_bills) + })?; + } + tx.commit()?; + Ok(forgiven) + } + pub fn channels_active(&self) -> Result> { + let db = self.db.lock().unwrap(); + let mut query = db.prepare("SELECT body FROM channels WHERE active=1 ORDER BY rowid")?; + query + .query_map([], |r| r.get::<_, String>(0))? + .map(|body| Ok(serde_json::from_str(&body?)?)) + .collect() + } + /// The most recent channels, newest first. + pub fn channel_history(&self, limit: u32) -> Result> { + ensure!((1..=100).contains(&limit), "limit must be 1..100"); + let db = self.db.lock().unwrap(); + let mut query = db.prepare("SELECT body FROM channels ORDER BY rowid DESC LIMIT ?1")?; + query + .query_map([limit], |r| r.get::<_, String>(0))? + .map(|body| Ok(serde_json::from_str(&body?)?)) + .collect() + } + /// Applies one state change to a channel in a single transaction; it + /// cannot raise a buyer voucher, which needs `mpp_update_both`. + pub fn channel_update( + &self, + key: &str, + update: impl FnOnce(&mut Channel) -> Result, + ) -> Result { + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + let result = channel_update_in(&tx, key, None, update)?; + tx.commit()?; + Ok(result) + } +} + +fn insert_channel(db: &Connection, channel: &Channel) -> Result<()> { + ensure!( + channel.voucher.is_none() || channel.seller, + "buyer vouchers must be budgeted" + ); + db.execute( + "INSERT INTO channels VALUES(?1,?2,?3,?4,?5)", + params![ + channel.key, + channel.peer, + channel.seller, + channel.state != ChannelState::Closed, + serde_json::to_string(channel)? + ], + )?; + Ok(()) +} + +fn spent(db: &Connection, day: u64) -> Result { + Ok(db + .query_row("SELECT amount FROM spend WHERE day=?1", [day], |r| { + r.get::<_, u64>(0) + }) + .optional()? + .unwrap_or(0)) +} + +fn update_in( + tx: &Transaction, + id: &str, + update: impl FnOnce(&mut Request) -> Result, +) -> Result { + let key = request_key(id); + let body: String = tx + .query_row("SELECT body FROM mpp_requests WHERE id=?1", [&key], |r| { + r.get(0) + }) + .optional()? + .context("unknown MPP request")?; + let mut request: Request = serde_json::from_str(&body)?; + let result = update(&mut request)?; + tx.execute( + "UPDATE mpp_requests SET body=?2,active=?3 WHERE id=?1", + params![key, serde_json::to_string(&request)?, request.activity()], + )?; + Ok(result) +} + +fn channel_update_in( + tx: &Transaction, + key: &str, + daily_budget: Option, + update: impl FnOnce(&mut Channel) -> Result, +) -> Result { + let body: String = tx + .query_row("SELECT body FROM channels WHERE key=?1", [key], |r| { + r.get(0) + }) + .optional()? + .context("unknown payment channel")?; + let mut channel: Channel = serde_json::from_str(&body)?; + let before = channel.cum(); + let result = update(&mut channel)?; + ensure!(channel.key == key, "channel identity changed"); + if !channel.seller && channel.cum() != before { + let increment = channel + .cum() + .checked_sub(before) + .context("buyer voucher decreased")?; + let limit = daily_budget.context("buyer voucher increase must be budgeted")?; + let day = now() / 86400; + let total = spent(tx, day)? + .checked_add(increment) + .context("daily budget overflow")?; + ensure!(total <= limit, "daily budget exceeded"); + tx.execute( + "INSERT INTO spend VALUES(?1,?2) ON CONFLICT(day) DO UPDATE SET amount=?2", + params![day, total], + )?; + } + tx.execute( + "UPDATE channels SET body=?2,active=?3 WHERE key=?1", + params![ + key, + serde_json::to_string(&channel)?, + channel.state != ChannelState::Closed + ], + )?; + Ok(result) +} + +/// Every spelling of a request UUID addresses one record. +fn request_key(id: &str) -> String { + uuid::Uuid::parse_str(id).map_or_else(|_| id.to_owned(), |id| id.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::contract::Asset; + + #[test] + fn only_one_engine_can_own_and_recover_a_ledger() { + let temp = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(temp.path()).unwrap(); + assert!(Ledger::open(temp.path()).is_err()); + drop(ledger); + Ledger::open(temp.path()).unwrap(); + } + + fn channel(peer: &str, nonce: u8) -> Channel { + let terms = ChannelTerms { + buyer_peer: "aa".repeat(32), + seller_peer: peer.into(), + payer: "0x1111111111111111111111111111111111111111".into(), + payee: "0x2222222222222222222222222222222222222222".into(), + asset: Asset::default(), + nonce: format!("{nonce:02x}").repeat(32), + }; + Channel::new(terms, peer.into(), false, 100).unwrap() + } + fn voucher(cum: u64) -> Option { + Some(Voucher { + channel_id: "channel".into(), + cum, + signature: "signature".into(), + }) + } + /// Raises the buyer voucher of `channel` to `cum` within `limit`. + fn sign(ledger: &Ledger, id: &str, channel: &Channel, cum: u64, limit: u64) -> Result<()> { + ledger.mpp_update_both(id, &channel.key, limit, |_, c| { + c.voucher = voucher(cum); + Ok(()) + }) + } + + #[test] + fn budget_counts_voucher_increments_across_restarts_and_future_versions_fail_closed() { + let temp = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(temp.path()).unwrap(); + let open = channel("bb", 1); + ledger.channel_insert(&open).unwrap(); + ledger.mpp_insert(&request()).unwrap(); + sign(&ledger, "request", &open, 6, 10).unwrap(); + sign(&ledger, "request", &open, 8, 10).unwrap(); + assert_eq!(ledger.spent_today().unwrap(), 8); + assert!( + ledger + .channel_update(&open.key, |c| { + c.voucher = voucher(9); + Ok(()) + }) + .is_err() + ); + drop(ledger); + let ledger = Ledger::open(temp.path()).unwrap(); + assert!(sign(&ledger, "request", &open, 11, 10).is_err()); + assert!(sign(&ledger, "request", &open, 7, 10).is_err()); + assert_eq!(ledger.channel_get(&open.key).unwrap().unwrap().cum(), 8); + sign(&ledger, "request", &open, 10, 10).unwrap(); + let db = ledger.db.lock().unwrap(); + db.pragma_update(None, "user_version", VERSION + 1).unwrap(); + drop(db); + drop(ledger); + assert!( + Ledger::open(temp.path()) + .err() + .unwrap() + .to_string() + .contains("unsupported payment ledger version") + ); + } + + #[test] + fn concurrent_vouchers_cannot_overspend_the_daily_budget() { + let temp = tempfile::tempdir().unwrap(); + let ledger = std::sync::Arc::new(Ledger::open(temp.path()).unwrap()); + let channels: Vec<_> = (0..2) + .map(|n| { + let channel = channel(&format!("peer-{n}"), n + 1); + ledger.channel_insert(&channel).unwrap(); + let mut row = request(); + row.id = n.to_string(); + row.peer = channel.peer.clone(); + ledger.mpp_insert(&row).unwrap(); + channel + }) + .collect(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); + let tasks: Vec<_> = channels + .into_iter() + .enumerate() + .map(|(n, channel)| { + let ledger = ledger.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + sign(&ledger, &n.to_string(), &channel, 6, 10).is_ok() + }) + }) + .collect(); + assert_eq!( + tasks + .into_iter() + .filter_map(|t| t.join().unwrap().then_some(())) + .count(), + 1 + ); + } + + #[test] + fn one_active_channel_per_peer_and_role_and_closed_history_survives() { + let temp = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(temp.path()).unwrap(); + let first = channel("bb", 1); + ledger.channel_insert(&first).unwrap(); + assert!(ledger.channel_insert(&channel("bb", 2)).is_err()); + let mut seller = channel("bb", 3); + seller.seller = true; + seller.voucher = voucher(5); + ledger.channel_insert(&seller).unwrap(); + ledger + .channel_update(&first.key, |c| { + c.state = ChannelState::Closed; + Ok(()) + }) + .unwrap(); + ledger.channel_insert(&channel("bb", 2)).unwrap(); + drop(ledger); + let ledger = Ledger::open(temp.path()).unwrap(); + assert_eq!(ledger.channels_active().unwrap().len(), 2); + assert_eq!( + ledger.channel_get(&first.key).unwrap().unwrap().state, + ChannelState::Closed + ); + assert_eq!(ledger.channel_active("bb", true).unwrap().unwrap().cum(), 5); + } + + #[test] + fn a_channel_closes_with_its_requests_and_a_seller_channel_opens_with_its_request() { + let temp = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(temp.path()).unwrap(); + let mut seller = channel("bb", 1); + seller.seller = true; + let mut paid = request(); + paid.peer = "bb".into(); + ledger.mpp_insert(&paid).unwrap(); + let refused = ledger.mpp_insert_channel("request", &seller, |_, _| -> Result<()> { + anyhow::bail!("request consumed concurrently") + }); + assert!(refused.is_err()); + assert!(ledger.channels_active().unwrap().is_empty()); + ledger + .mpp_insert_channel("request", &seller, |r, c| { + r.channel = Some(c.key.clone()); + Ok(()) + }) + .unwrap(); + let failed = ledger.channel_close(&seller.key, "closed", |_| anyhow::bail!("conflict")); + assert!(failed.is_err()); + assert_eq!(ledger.mpp_active().unwrap().len(), 1); + ledger + .channel_close(&seller.key, "closed", |c| { + c.state = ChannelState::Closed; + Ok(()) + }) + .unwrap(); + assert!(ledger.mpp_active().unwrap().is_empty()); + assert_eq!( + ledger.mpp_get("request").unwrap().unwrap().error.as_deref(), + Some("closed") + ); + assert_eq!( + ledger.channel_last_closed("bb", true).unwrap().unwrap().key, + seller.key + ); + } + + #[test] + fn node_identity_is_pinned_across_restarts() { + let temp = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(temp.path()).unwrap(); + ledger.pin_node(&"aa".repeat(32)).unwrap(); + drop(ledger); + let ledger = Ledger::open(temp.path()).unwrap(); + ledger.pin_node(&"aa".repeat(32)).unwrap(); + assert!(ledger.pin_node(&"bb".repeat(32)).is_err()); + assert!(ledger.pin_node(&"AA".repeat(32)).is_err()); + } + fn request() -> Request { + Request::new( + "request".into(), + "peer".into(), + false, + crate::protocol::Intent { + model: "model".into(), + body_digest: "11".repeat(32), + payer: "payer".into(), + output_limit: 4, + input_bytes: 10, + }, + ) + } + + #[test] + fn every_uuid_spelling_addresses_one_agreement() { + let dir = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(dir.path()).unwrap(); + let uuid = uuid::Uuid::from_u128(0xabcdef); + let mut original = request(); + original.id = uuid.to_string().to_uppercase(); + ledger.mpp_insert(&original).unwrap(); + let mut duplicate = original.clone(); + duplicate.id = uuid.urn().to_string(); + assert!(ledger.mpp_insert(&duplicate).is_err()); + ledger + .mpp_update(&uuid.simple().to_string(), |row| { + row.state = State::Closed; + Ok(()) + }) + .unwrap(); + let stored = ledger.mpp_get(&uuid.braced().to_string()).unwrap().unwrap(); + assert_eq!(stored.state, State::Closed); + } + + #[test] + fn request_identity_and_closed_history_survive_restart() { + let dir = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(dir.path()).unwrap(); + ledger.mpp_insert(&request()).unwrap(); + drop(ledger); + let ledger = Ledger::open(dir.path()).unwrap(); + assert_eq!(ledger.mpp_active().unwrap()[0].intent.input_bytes, 10); + ledger + .mpp_update("request", |r| { + r.state = State::Closed; + Ok(()) + }) + .unwrap(); + assert!(ledger.mpp_active().unwrap().is_empty()); + assert_eq!(ledger.mpp_history(1).unwrap()[0].state, State::Closed); + assert!(ledger.mpp_history(0).is_err()); + assert!(ledger.mpp_history(101).is_err()); + } +} diff --git a/src/ledger_settings.rs b/src/ledger_settings.rs new file mode 100644 index 0000000..31e7693 --- /dev/null +++ b/src/ledger_settings.rs @@ -0,0 +1,274 @@ +//! Runtime-changeable settings in the payment ledger: the buyer policy, +//! seller prices and admission deposits, as in the Lightning plugin. +use super::Ledger; +use crate::config::{Config, Policy, Price}; +use anyhow::{Context, Result, ensure}; +use rusqlite::{OptionalExtension, params}; +use std::collections::BTreeMap; + +impl Ledger { + /// Writes the config's policy, seller prices and, when set, admission + /// deposit into the ledger at startup, as the Lightning plugin does. + /// Settings for models absent from the config stay. + pub fn seed(&self, config: &Config) -> Result<()> { + self.set_policy(&config.policy)?; + for (model, price) in &config.prices { + self.set_pricing(model, Some(price))?; + } + if let Some(deposit) = config.admission_deposit { + self.set_admission_deposit(deposit)?; + } + Ok(()) + } + pub fn policy(&self) -> Result { + self.setting("policy")? + .map_or_else(|| Ok(Policy::default()), |v| Ok(serde_json::from_str(&v)?)) + } + pub fn set_policy(&self, policy: &Policy) -> Result<()> { + policy.validate()?; + self.set_setting("policy", &serde_json::to_string(policy)?) + } + /// The policy with today's voucher increments and what remains of the + /// daily budget. + pub fn policy_status(&self) -> Result { + let policy = self.policy()?; + let spent = self.spent_today()?; + let remaining = policy.budget().unwrap_or(0).saturating_sub(spent); + let mut status = serde_json::to_value(&policy)?; + status["spent_today"] = spent.to_string().into(); + status["remaining_daily_budget"] = remaining.to_string().into(); + Ok(status) + } + /// Seller rates per model, including free ones. + pub fn pricing(&self) -> Result> { + self.prefixed("price/")? + .into_iter() + .map(|(model, value)| Ok((model, serde_json::from_str(&value)?))) + .collect() + } + /// Per-model admission deposits, as set. + pub fn model_admission_deposits(&self) -> Result> { + self.prefixed("deposit/")? + .into_iter() + .map(|(model, value)| Ok((model, value.parse()?))) + .collect() + } + /// Settings whose key starts with `prefix`, by the rest of the key. + fn prefixed(&self, prefix: &str) -> Result> { + let db = self.db.lock().unwrap(); + let mut query = db.prepare( + "SELECT substr(key,length(?1)+1),value FROM settings WHERE substr(key,1,length(?1))=?1 ORDER BY key", + )?; + Ok(query + .query_map([prefix], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect::>()?) + } + /// The seller's rates for `model`, unless it is unpriced or free. + pub fn paid_price(&self, model: &str) -> Result> { + let Some(value) = self.setting(&format!("price/{model}"))? else { + return Ok(None); + }; + let price: Price = serde_json::from_str(&value)?; + Ok((!price.is_free()).then_some(price)) + } + /// Sets, or with `None` removes, one model's rates; its admission deposit + /// goes with its price in the same transaction. + pub fn set_pricing(&self, model: &str, price: Option<&Price>) -> Result<()> { + ensure!( + !model.is_empty() && model.len() <= 1024, + "model must be 1..1024 bytes" + ); + let Some(price) = price else { + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + for key in [format!("price/{model}"), format!("deposit/{model}")] { + tx.execute("DELETE FROM settings WHERE key=?1", [key])?; + } + tx.commit()?; + return Ok(()); + }; + price.validate()?; + self.set_setting(&format!("price/{model}"), &serde_json::to_string(price)?) + } + /// Changes only the cached-input discount of a priced model, reading and + /// writing its price in one transaction. + pub fn set_cache_discount(&self, model: &str, percent: u8) -> Result<()> { + let key = format!("price/{model}"); + let mut db = self.db.lock().unwrap(); + let tx = db.transaction()?; + let value: String = tx + .query_row("SELECT value FROM settings WHERE key=?1", [&key], |r| { + r.get(0) + }) + .optional()? + .context("set the model's input and output rates before a cache discount")?; + let mut price: Price = serde_json::from_str(&value)?; + price.cache_discount_percent = percent; + price.validate()?; + tx.execute( + "UPDATE settings SET value=?2 WHERE key=?1", + params![key, serde_json::to_string(&price)?], + )?; + tx.commit()?; + Ok(()) + } + /// The seller's upfront for a new channel on a model without its own + /// deposit, and the largest upfront this node accepts as a buyer. + pub fn admission_deposit(&self) -> Result { + Ok(self + .setting("admission_deposit")? + .map(|v| v.parse()) + .transpose()? + .unwrap_or(0)) + } + pub fn set_admission_deposit(&self, deposit: u64) -> Result<()> { + self.set_setting("admission_deposit", &deposit.to_string()) + } + /// Forgets the set node-wide deposit, so it is 0 until set again. + pub fn reset_admission_deposit(&self) -> Result<()> { + self.db + .lock() + .unwrap() + .execute("DELETE FROM settings WHERE key='admission_deposit'", [])?; + Ok(()) + } + /// The seller's upfront for a new channel on `model`: its own deposit, + /// else the node-wide one. + pub fn model_admission_deposit(&self, model: &str) -> Result { + match self.setting(&format!("deposit/{model}"))? { + Some(value) => Ok(value.parse()?), + None => self.admission_deposit(), + } + } + /// Sets, or with `None` clears, the admission deposit of a priced model. + pub fn set_model_admission_deposit(&self, model: &str, deposit: Option) -> Result<()> { + let key = format!("deposit/{model}"); + let db = self.db.lock().unwrap(); + let Some(deposit) = deposit else { + db.execute("DELETE FROM settings WHERE key=?1", [key])?; + return Ok(()); + }; + // The price check and the write are one statement. + let written = db.execute( + "INSERT INTO settings(key,value) SELECT ?1,?2 WHERE EXISTS(SELECT 1 FROM settings WHERE key=?3) ON CONFLICT(key) DO UPDATE SET value=excluded.value", + params![key, deposit.to_string(), format!("price/{model}")], + )?; + ensure!( + written == 1, + "set the model's price before its admission deposit" + ); + Ok(()) + } + /// The last block whose close events the seller scanned completely. + pub fn close_cursor(&self) -> Result> { + Ok(self + .setting("close_cursor")? + .map(|b| b.parse()) + .transpose()?) + } + pub fn set_close_cursor(&self, block: u64) -> Result<()> { + self.set_setting("close_cursor", &block.to_string()) + } + /// The bond this node publishes as its peer evidence. + pub fn published_bond(&self) -> Result> { + self.setting("published_bond") + } + pub fn set_published_bond(&self, bond_id: Option<&str>) -> Result<()> { + match bond_id { + Some(id) => self.set_setting("published_bond", id), + None => self.clear_setting("published_bond"), + } + } + /// The operation ID of the newest finalized bond lock already published. + pub fn published_lock(&self) -> Result> { + self.setting("published_lock") + } + pub fn set_published_lock(&self, operation_id: &str) -> Result<()> { + self.set_setting("published_lock", operation_id) + } + fn clear_setting(&self, key: &str) -> Result<()> { + self.db + .lock() + .unwrap() + .execute("DELETE FROM settings WHERE key=?1", [key])?; + Ok(()) + } + fn setting(&self, key: &str) -> Result> { + Ok(self + .db + .lock() + .unwrap() + .query_row("SELECT value FROM settings WHERE key=?1", [key], |r| { + r.get(0) + }) + .optional()?) + } + fn set_setting(&self, key: &str, value: &str) -> Result<()> { + self.db.lock().unwrap().execute( + "INSERT INTO settings VALUES(?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value", + params![key, value], + )?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings_are_seeded_from_config_survive_restart_and_deposits_follow_prices() { + let temp = tempfile::tempdir().unwrap(); + let ledger = Ledger::open(temp.path()).unwrap(); + assert_eq!(ledger.policy().unwrap(), Policy::default()); + assert!(ledger.pricing().unwrap().is_empty()); + assert_eq!(ledger.admission_deposit().unwrap(), 0); + let mut config: Config = serde_json::from_value(serde_json::json!({ + "data_dir": temp.path(), + "policy": {"mode":"automatic","daily_budget":"50"}, + "prices": {"paid":{"input_per_million":"1","output_per_million":"2"}, + "free":{"input_per_million":"0","output_per_million":"0"}}, + "admission_deposit": "7" + })) + .unwrap(); + ledger.seed(&config).unwrap(); + assert!( + ledger + .set_model_admission_deposit("unpriced", Some(3)) + .is_err() + ); + ledger.set_model_admission_deposit("paid", Some(3)).unwrap(); + drop(ledger); + let ledger = Ledger::open(temp.path()).unwrap(); + assert_eq!(ledger.policy().unwrap().budget(), Some(50)); + assert_eq!(ledger.pricing().unwrap().len(), 2); + assert!(ledger.paid_price("free").unwrap().is_none()); + assert_eq!( + ledger + .paid_price("paid") + .unwrap() + .unwrap() + .output_per_million, + 2 + ); + assert_eq!(ledger.model_admission_deposit("paid").unwrap(), 3); + assert_eq!(ledger.model_admission_deposit("free").unwrap(), 7); + // Startup writes what the config sets and leaves the rest. + config.admission_deposit = None; + config.policy = Policy::default(); + ledger.seed(&config).unwrap(); + assert_eq!(ledger.policy().unwrap(), Policy::default()); + assert_eq!(ledger.admission_deposit().unwrap(), 7); + assert_eq!(ledger.model_admission_deposit("paid").unwrap(), 3); + // A model's deposit goes with its price. + ledger.set_pricing("paid", None).unwrap(); + assert!(ledger.paid_price("paid").unwrap().is_none()); + ledger.seed(&config).unwrap(); + assert_eq!(ledger.model_admission_deposit("paid").unwrap(), 7); + let invalid = Policy { + mode: crate::config::Mode::Automatic, + daily_budget: None, + }; + assert!(ledger.set_policy(&invalid).is_err()); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..95555e6 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,14 @@ +mod bonds; +pub mod cli; +mod config; +mod contract; +mod control; +mod engine; +#[cfg(feature = "offline-fixture")] +mod fixtures; +mod ledger; +mod protocol; +mod request_stream; +pub mod runtime; +mod tempo; +mod wallet; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..cdd64f3 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,4 @@ +#[tokio::main] +async fn main() -> anyhow::Result<()> { + mesh_llm_tempo::cli::run().await +} diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..b5640c3 --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,110 @@ +use crate::contract::mpp::{Bill, ChannelFunding, Closure, RequestTerms, Voucher}; +use serde::{Deserialize, Serialize}; + +pub const CHANNEL: &str = "pay.stablecoin.v1"; +pub const MPP_VERSION: u16 = 1; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum Message { + /// One step of a paid request, keyed by its request UUID. + Mpp { + version: u16, + id: String, + message: Box, + }, + /// The seller's finalized close of the pair's channel. + Closed { + version: u16, + channel_id: String, + closure: Closure, + }, + Error { + id: String, + reason: String, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Intent { + pub model: String, + pub body_digest: String, + pub payer: String, + pub output_limit: u64, + /// Byte length of the canonical body covered by `body_digest`. + pub input_bytes: u64, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "step", rename_all = "snake_case", deny_unknown_fields)] +pub enum Step { + Hello { + intent: Intent, + }, + Quote { + terms: RequestTerms, + }, + QuoteRejected { + reason: String, + }, + /// The seller has no paid price for the model and serves it free. + Unpriced, + /// The seller cannot quote yet: the buyer's channel is still being + /// opened, the same body is in flight, or the buyer has three unpaid + /// bills. The buyer says hello again. + Busy, + /// The buyer's latest voucher; after a bill it pays the bill. + Voucher { + funding: ChannelFunding, + voucher: Voucher, + }, + Ready, + Bill(Bill), + /// The seller has no usage for the request and never bills it. + Unbilled, + /// The buyer received the seller's `Unbilled` notice. + UnbilledSeen, + Cancel, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::contract::mpp::Usage; + use serde_json::json; + + #[test] + fn bills_and_close_notices_round_trip_with_exact_amounts() { + let bill = Bill { + seq: 0, + usage: Some(Usage { + prompt_tokens: 1, + completion_tokens: 4, + cached_tokens: 0, + }), + cost: 5, + running_total: u64::MAX, + }; + let message = Message::Mpp { + version: MPP_VERSION, + id: "id".into(), + message: Box::new(Step::Bill(bill.clone())), + }; + let wire = serde_json::to_value(&message).unwrap(); + assert_eq!(wire["message"]["step"], "bill"); + assert_eq!(wire["message"]["running_total"], u64::MAX.to_string()); + let parsed: Message = serde_json::from_value(wire.clone()).unwrap(); + assert!( + matches!(parsed, Message::Mpp { message, .. } if matches!(message.as_ref(), Step::Bill(b) if *b == bill)) + ); + let mut extra = wire; + extra["message"]["capture"] = json!("1"); + assert!(serde_json::from_value::(extra).is_err()); + let closed = json!({"type":"closed","version":MPP_VERSION,"channel_id":"0x01", + "closure":{"tx_hash":"0x02","channel_id":"0x01","captured":"5","refunded":"15","block_number":3}}); + let parsed: Message = serde_json::from_value(closed).unwrap(); + assert!( + matches!(parsed, Message::Closed { closure, .. } if closure.captured + closure.refunded == 20) + ); + } +} diff --git a/src/request_stream.rs b/src/request_stream.rs new file mode 100644 index 0000000..2671580 --- /dev/null +++ b/src/request_stream.rs @@ -0,0 +1,167 @@ +//! Authenticate and acknowledge exact request bytes without retaining prompt text. +use anyhow::{Context, Result, ensure}; +use mesh_llm_plugin::{PluginError, PluginResult, bind_side_stream, proto}; +use sha2::{Digest, Sha256}; +use std::sync::Arc; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; + +const LIMIT: u64 = 64 * 1024; + +#[derive(Clone)] +pub struct RequestStreams(Arc); +impl Default for RequestStreams { + fn default() -> Self { + Self(Arc::new(tokio::sync::Semaphore::new(32))) + } +} +impl RequestStreams { + pub async fn open( + &self, + request: proto::OpenStreamRequest, + ) -> PluginResult> { + validate(&request).map_err(PluginError::from)?; + let permit = + self.0.clone().try_acquire_owned().map_err(|_| { + PluginError::invalid_request("request side-stream capacity exhausted") + })?; + let socket_id = uuid::Uuid::parse_str(&request.stream_id) + .map_err(|error| PluginError::invalid_request(error.to_string()))? + .simple() + .to_string(); + let listener = bind_side_stream("scb", &socket_id[..16]) + .await + .map_err(PluginError::from)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(listener.endpoint(), std::fs::Permissions::from_mode(0o600)) + .map_err(anyhow::Error::from)?; + } + let mut response = listener.open_stream_response(&request); + let token = uuid::Uuid::new_v4().to_string(); + response.token = Some(token.clone()); + tokio::spawn(async move { + let _permit = permit; + let result = tokio::time::timeout(std::time::Duration::from_secs(30), async { + let stream = listener.accept().await?; + let (mut read, mut write) = stream.into_split(); + let mut authentication = [0u8; 36]; + read.read_exact(&mut authentication).await?; + ensure!( + authentication == token.as_bytes(), + "request side-stream token mismatch" + ); + let (sha256, byte_count) = hash_body( + &mut read, + request.expected_bytes.context("missing byte length")?, + ) + .await?; + let receipt = + serde_json::json!({"sha256":sha256,"byte_count":byte_count}).to_string() + "\n"; + write.write_all(receipt.as_bytes()).await?; + write.shutdown().await?; + Ok::<_, anyhow::Error>(()) + }) + .await; + if !matches!(result, Ok(Ok(()))) { + tracing::warn!("stablecoin request side-stream receipt unavailable"); + } + }); + Ok(Some(response)) + } +} +fn validate(request: &proto::OpenStreamRequest) -> Result<()> { + ensure!( + request.mode == proto::StreamMode::RawBytes as i32 && request.bidirectional, + "expected bidirectional raw request side stream" + ); + ensure!( + request.expected_bytes.is_some_and(|count| count <= LIMIT), + "request side stream exceeds 64 KiB or omits length" + ); + let metadata: serde_json::Value = + serde_json::from_str(request.metadata_json.as_deref().unwrap_or("{}"))?; + ensure!( + metadata["receipt_protocol"] == "sha256-v1", + "unsupported request receipt protocol" + ); + ensure!( + matches!( + metadata["kind"].as_str(), + Some( + "openai_exchange_request" + | "openai_exchange_original" + | "openai_exchange_effective" + ) + ), + "unsupported request side-stream kind" + ); + let correlation = metadata["exchange_id"] + .as_str() + .or(request.correlation_id.as_deref()) + .context("request side stream lacks correlation")?; + ensure!( + !correlation.is_empty() && correlation.len() <= 256, + "invalid request side-stream correlation" + ); + Ok(()) +} +async fn hash_body(read: &mut (impl AsyncRead + Unpin), expected: u64) -> Result<(String, u64)> { + ensure!(expected <= LIMIT, "request body exceeds 64 KiB"); + let mut digest = Sha256::new(); + let mut count = 0u64; + let mut buffer = [0u8; 8192]; + loop { + let size = read.read(&mut buffer).await?; + if size == 0 { + break; + } + count += size as u64; + ensure!( + count <= LIMIT && count <= expected, + "request body exceeded authorized byte length" + ); + digest.update(&buffer[..size]); + } + ensure!( + count == expected, + "request side stream ended before expected byte length" + ); + Ok((hex::encode(digest.finalize()), count)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn exact_receipt_preserves_json_whitespace_and_rejects_partial_or_extra_bytes() { + let bytes = b"{ \"max_tokens\" : 4 }\n"; + let (hash, count) = hash_body(&mut &bytes[..], bytes.len() as u64) + .await + .unwrap(); + assert_eq!(hash, hex::encode(Sha256::digest(bytes))); + assert_eq!(count, bytes.len() as u64); + assert!( + hash_body(&mut &bytes[..], bytes.len() as u64 + 1) + .await + .is_err() + ); + assert!( + hash_body(&mut &bytes[..], bytes.len() as u64 - 1) + .await + .is_err() + ); + assert!(hash_body(&mut &bytes[..], LIMIT + 1).await.is_err()); + } + #[test] + fn rejects_ungranted_response_streams_and_unbounded_request_streams() { + let mut request=proto::OpenStreamRequest{stream_id:uuid::Uuid::new_v4().to_string(),mode:proto::StreamMode::RawBytes as i32,bidirectional:true, + expected_bytes:Some(1),metadata_json:Some(serde_json::json!({"kind":"openai_exchange_original","receipt_protocol":"sha256-v1","exchange_id":"id"}).to_string()),..Default::default()}; + validate(&request).unwrap(); + request.expected_bytes = Some(LIMIT + 1); + assert!(validate(&request).is_err()); + request.expected_bytes = Some(1); + request.metadata_json=Some(serde_json::json!({"kind":"openai_exchange_response","receipt_protocol":"sha256-v1","exchange_id":"id"}).to_string()); + assert!(validate(&request).is_err()); + } +} diff --git a/src/runtime.rs b/src/runtime.rs new file mode 100644 index 0000000..3980c65 --- /dev/null +++ b/src/runtime.rs @@ -0,0 +1,455 @@ +use crate::{ + config::Config, + engine::Engine, + protocol::{CHANNEL, Message}, + wallet::{Backend, OpenedWallet, WalletFuture}, +}; +use anyhow::{Context, Result, ensure}; +use mesh_llm_plugin::peer_evidence::{PeerEvidenceVerificationRequest, peer_evidence_verifier}; +use mesh_llm_plugin::{ + OperationRouter, PluginMetadata, PluginRuntime, SimplePlugin, operation_with_schema, + plugin_manifest, plugin_server_info, structured_tool_result, +}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::sync::{Arc, OnceLock}; +use tokio::sync::mpsc::{Sender, error::TrySendError}; + +pub const NAME: &str = "tempo"; +const VERIFIER_HANDLER: &str = "verify_peer_evidence"; + +type Slot = Arc>>; +type MeshId = Arc>>; + +/// The offline fixture's manifest. Bonds need a chain, so with +/// `TEMPO_FIXTURE_NO_VERIFIER` set the fixture is no verifier, and the +/// offline payment smoke reaches sellers without a bond. +pub fn fixture_manifest() -> mesh_llm_plugin::proto::PluginManifest { + let mut manifest = manifest(); + if std::env::var_os("TEMPO_FIXTURE_NO_VERIFIER").is_some() { + manifest.peer_evidence_verifier = None; + } + manifest +} + +pub fn manifest() -> mesh_llm_plugin::proto::PluginManifest { + use mesh_llm_plugin::{config_path, config_schema, config_setting, mesh_channel, operation}; + let mut hook = mesh_llm_plugin::openai_exchange::openai_exchange_hook("payment_gate"); + hook.metadata = false; + hook.required = true; + hook.admission = true; + hook.deadline_ms = 30_000; + hook.request_body = true; + hook.effective_request_body = true; + hook.read_identity_bundle = true; + hook.max_body_bytes = 64 * 1024; + plugin_manifest() + .item( + config_schema(NAME) + .setting(config_setting("config_path", config_path()).required(false)), + ) + .item(hook) + .item(peer_evidence_verifier( + crate::bonds::NAMESPACE, + VERIFIER_HANDLER, + )) + .item(mesh_channel(CHANNEL)) + .item(mesh_llm_plugin::mesh_event_mesh_id_updated()) + .item(operation::( + "control", + "Manage Tempo payments, bonds and the shared wallet", + )) + .item(operation::( + VERIFIER_HANDLER, + "Verify a peer bond at finalized Tempo state", + )) + .build() +} + +/// The operator's `[plugin.settings]`; a package install runs without any. +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct Settings { + /// The config file; by default `~/.mesh-llm/tempo/config.json`, created + /// when absent. + config_path: Option, +} + +fn get(slot: &Slot) -> Result> { + slot.get().cloned().context("Tempo engine is not ready") +} + +pub async fn run() -> Result<()> { + run_with_wallet(manifest(), |config, db| { + Box::pin(async move { + // Without a wallet the node verifies bonds and serves free + // inference until `fund` or `bond_lock` creates one. + if !config.data_dir.join("wallet.json").exists() { + ensure!(!config.needs_wallet(), crate::engine::NEEDS_WALLET); + let info = crate::contract::WalletInfo::absent(config.wallet.network); + let unopened = + crate::wallet::Unopened::new(config.wallet.clone(), &config.data_dir, db); + return Ok((Arc::new(unopened) as Arc, info)); + } + let wallet = crate::tempo::Wallet::load(config.wallet.clone(), &config.data_dir, db)?; + let info = wallet.info().await?; + Ok((wallet as Arc, info)) + }) + }) + .await +} + +/// Run the explicit offline entry point, never selected by production settings. +#[cfg(feature = "offline-fixture")] +pub async fn run_fixture() -> Result<()> { + run_with_wallet(fixture_manifest(), crate::fixtures::load_wallet).await +} + +async fn run_with_wallet( + manifest: mesh_llm_plugin::proto::PluginManifest, + load_wallet: fn(&Config, crate::ledger::Database) -> WalletFuture<'_, OpenedWallet>, +) -> Result<()> { + // Mesh accepts evidence only from its verifier. + let publishes = manifest.peer_evidence_verifier.is_some(); + let slot: Slot = Default::default(); + let prepared = Arc::new(std::sync::Mutex::new(None::)); + let metadata = PluginMetadata::new( + NAME, + env!("CARGO_PKG_VERSION"), + plugin_server_info( + NAME, + env!("CARGO_PKG_VERSION"), + "Tempo payments and bonds", + "OUSD payments and refundable identity bonds", + None::, + ), + ) + .with_manifest(manifest); + let mesh_id: MeshId = Default::default(); + let mesh_events = mesh_id.clone(); + let initialize = prepared.clone(); + let startup = slot.clone(); + let channels = slot.clone(); + let hooks = slot.clone(); + let queues = PeerQueues::new(); + let bodies = crate::request_stream::RequestStreams::default(); + let plugin = SimplePlugin::new(metadata) + .with_operation_router(controls(slot, mesh_id)) + .on_mesh_event(move |event, _| { + let mesh_id = mesh_events.clone(); + Box::pin(async move { + if event.kind == mesh_llm_plugin::proto::mesh_event::Kind::MeshIdUpdated as i32 { + *mesh_id.lock().unwrap() = (!event.mesh_id.is_empty()).then_some(event.mesh_id); + } + Ok(()) + }) + }) + .on_open_stream(move |request, _| { + let bodies = bodies.clone(); + Box::pin(async move { bodies.open(request).await }) + }) + .on_initialize(move |request, _| { + let prepared = initialize.clone(); + Box::pin(async move { + let settings: Settings = match request.settings_json.trim() { + "" => Settings::default(), + json => serde_json::from_str(json).map_err(anyhow::Error::from)?, + }; + let config = Config::load_from(settings.config_path)?; + let required = mesh_llm_plugin::peer_evidence::HOST_CAPABILITY; + if !request + .host_capabilities + .iter() + .any(|capability| capability == required) + { + return Err(anyhow::anyhow!( + "Tempo requires a Mesh host supporting {required}" + ) + .into()); + } + *prepared.lock().unwrap() = Some(config); + Ok(()) + }) + }) + .on_initialized(move |context| { + let slot = startup.clone(); + let prepared = prepared.clone(); + let context = context.owned(); + Box::pin(async move { + let config = prepared + .lock() + .unwrap() + .take() + .context("Tempo settings missing")?; + let identity: Value = context + .request_host("ReadIdentityBundle", json!({})) + .await?; + let node = identity["node_endpoint_id"] + .as_str() + .context("host identity omitted node endpoint")? + .into(); + let ledger = crate::ledger::Ledger::open(&config.data_dir)?; + let (wallet, info) = load_wallet(&config, ledger.db.clone()).await?; + let engine = Engine::new(config, ledger, wallet, info, node, context.clone())?; + if publishes { + engine.publish_bond().await?; + } + engine.require_paid_models().await?; + ensure!( + slot.set(engine.clone()).is_ok(), + "Tempo plugin initialized twice" + ); + let weak = Arc::downgrade(&engine); + tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(3)); + loop { + interval.tick().await; + let Some(engine) = weak.upgrade() else { break }; + if let Err(error) = engine.retry().await { + eprintln!("tempo: reconciliation failed: {error:#}"); + } + } + }); + Ok(()) + }) + }) + .on_channel_message(move |message, _context| { + let slot = channels.clone(); + let queues = queues.clone(); + Box::pin(async move { + if message.channel != CHANNEL || message.body.len() > 32 * 1024 { + return Ok(()); + } + let Ok(body) = serde_json::from_slice::(&message.body) else { + tracing::warn!("dropping malformed stablecoin channel message"); + return Ok(()); + }; + let Ok(engine) = get(&slot) else { + return Ok(()); + }; + let peer = message.source_peer_id; + let worker = peer.clone(); + let queued = queues.push(&peer, body, move |body| { + deliver(engine.clone(), worker.clone(), body) + }); + if !queued { + tracing::warn!("stablecoin channel capacity exhausted"); + } + Ok(()) + }) + }) + .with_openai_exchange_handler(move |_, event, _| { + let slot = hooks.clone(); + Box::pin(async move { + let engine = get(&slot)?; + if event["phase"] == "exchange_finished" { + if let Some(id) = engine.record_terminal(&event)? { + tokio::spawn(async move { + if let Err(error) = engine.mpp_retry_one(&id).await { + eprintln!("tempo: terminal settlement failed: {error:#}"); + } + }); + } + return Ok(Default::default()); + } + let decision = engine.hook(event).await.inspect_err(|error| { + eprintln!("tempo: payment hook failed: {error:#}"); + })?; + Ok(decision) + }) + }); + PluginRuntime::run(plugin).await +} + +async fn deliver(engine: Arc, peer: String, body: Message) { + // Errors answer request steps only; they are keyed by request ID. + let id = match &body { + Message::Mpp { id, .. } => Some(id.clone()), + Message::Closed { .. } | Message::Error { .. } => None, + }; + if let Err(error) = engine.message(&peer, body).await { + eprintln!("tempo: peer operation failed: {error:#}"); + let reason = error.to_string().chars().take(512).collect(); + if let Some(id) = id { + let _ = engine.send(&peer, &Message::Error { id, reason }).await; + } + } +} + +/// Handles each peer's messages one at a time, in the order this plugin +/// receives them, with a bounded queue per peer. +struct PeerQueues(Arc>>>); +impl Clone for PeerQueues { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} +impl PeerQueues { + fn new() -> Self { + Self(Default::default()) + } + /// Queues `item` behind the peer's earlier items, starting a worker that + /// runs `handle` when the peer has none; `false` when no room is left. + fn push(&self, peer: &str, item: T, handle: F) -> bool + where + F: Fn(T) -> Fut + Send + 'static, + Fut: std::future::Future + Send + 'static, + { + let mut queues = self.0.lock().unwrap(); + let item = match queues.get(peer) { + Some(queue) => match queue.try_send(item) { + Ok(()) => return true, + Err(TrySendError::Full(_)) => return false, + Err(TrySendError::Closed(item)) => item, + }, + None if queues.len() >= 4096 => return false, + None => item, + }; + let (queue, mut receiver) = tokio::sync::mpsc::channel(32); + let _ = queue.try_send(item); + queues.insert(peer.to_owned(), queue); + let (this, peer) = (self.clone(), peer.to_owned()); + tokio::spawn(async move { + loop { + let idle = std::time::Duration::from_secs(60); + match tokio::time::timeout(idle, receiver.recv()).await { + Ok(Some(item)) => handle(item).await, + // Pushes hold the same lock, so nothing is queued after this check. + _ => { + let mut queues = this.0.lock().unwrap(); + if receiver.is_empty() { + queues.remove(&peer); + return; + } + } + } + } + }); + true + } +} + +fn controls(slot: Slot, mesh_id: MeshId) -> OperationRouter { + let mut router = OperationRouter::new(); + let verification = slot.clone(); + router.add_raw( + operation_with_schema( + "control", + "Manage payments, pricing, wallet sends, bond deposits and refunds", + crate::control::schema(), + ), + move |request, _| { + let slot = slot.clone(); + let mesh_id = mesh_id.clone(); + Box::pin(async move { + let engine = get(&slot)?; + let command: crate::control::Control = request.arguments()?; + let mesh_id = mesh_id.lock().unwrap().clone(); + structured_tool_result(command.run(&engine, mesh_id).await?) + }) + }, + ); + router.add_raw( + mesh_llm_plugin::json_schema_operation::( + VERIFIER_HANDLER, + "Verify a provider bond", + ), + move |request, _| { + let slot = verification.clone(); + Box::pin(async move { + let input: PeerEvidenceVerificationRequest = request.arguments()?; + let engine = get(&slot)?; + let result = engine + .bonds + .verify( + &engine.config.bonds, + &input.mesh_id, + &input.node_id, + input.evidence, + ) + .await; + structured_tool_result( + result.unwrap_or_else( + |error| json!({"accepted":false,"reason":error.to_string(), + "valid_until":crate::config::now().saturating_add(engine.config.bonds.verification_retry_seconds)}), + ), + ) + }) + }, + ); + router +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn each_peers_messages_run_one_at_a_time_in_arrival_order() { + let queues = PeerQueues::new(); + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + for n in 0..64u64 { + let peer = format!("peer-{}", n % 2); + let seen = seen.clone(); + assert!(queues.push(&peer, n, move |n| { + let seen = seen.clone(); + async move { + // Later messages would overtake earlier ones if they ran concurrently. + tokio::time::sleep(std::time::Duration::from_millis(64 - n)).await; + seen.lock().unwrap().push(n); + } + })); + } + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while seen.lock().unwrap().len() < 64 { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let seen = seen.lock().unwrap(); + for parity in 0..2 { + let order: Vec<_> = seen.iter().filter(|n| *n % 2 == parity).collect(); + assert!(order.windows(2).all(|w| w[0] < w[1]), "{order:?}"); + } + } + #[test] + fn host_sees_admission_controls_and_the_evidence_verifier() { + let m = manifest(); + assert_eq!(m.mesh_channels[0].name, CHANNEL); + let hook = m.openai_exchange_hook.unwrap(); + assert!(hook.required && hook.admission && hook.read_identity_bundle); + assert!(!hook.delegate_signing_key && !hook.response_body); + assert_eq!( + m.operations + .iter() + .map(|op| op.name.as_str()) + .collect::>(), + vec!["control", "verify_peer_evidence"] + ); + assert!(m.capabilities.is_empty()); + assert!( + m.grant_requests + .is_none_or(|g| g.operation_bindings.is_empty()) + ); + } + + #[test] + fn documented_grant_fully_authorizes_the_admission_hook() { + let hook = manifest().openai_exchange_hook.unwrap(); + let grant = serde_json::from_value(json!({ + "endpoints":["chat_completions","completions","responses"], + "phases":["request_received","backend_selected","exchange_finished"], + "request_body":true,"effective_request_body":true, + "admission":true,"read_identity_bundle":true, + "deadline_ms":30000,"max_body_bytes":65536, + "max_queue_bytes":2097152,"max_in_flight":32, + "failure_policy":"required" + })) + .unwrap(); + assert!( + mesh_llm_plugin::openai_exchange::negotiate_openai_exchange(Some(&hook), Some(&grant)) + .unwrap() + .is_some() + ); + } +} diff --git a/src/tempo/bond_fixture_tests.rs b/src/tempo/bond_fixture_tests.rs new file mode 100644 index 0000000..44fd59d --- /dev/null +++ b/src/tempo/bond_fixture_tests.rs @@ -0,0 +1,631 @@ +//! Bond RPC fixtures use the real signer, native multicall encoding and durable journal. +use super::*; +use crate::bonds::{self, Escrow, Intent, Requirement, Settings as BondSettings}; +use crate::tempo::bonds::BondAttempt; +use tempo_alloy::primitives::transaction::Call; +pub(super) const ESCROW: &str = "0x11111111111111111111111111111111111111ab"; + +pub(super) fn view(fixture: &Fixture, data: &[u8]) -> Result { + if data[..4] == Escrow::tokenCall::SELECTOR { + return Ok(abi(OUSD.parse::
()?)); + } + let call = Escrow::getBondCall::abi_decode_validate(data)?; + let bond = fixture.bonds.get(&call.id).context("bond absent")?; + Ok(json!(format!("0x{}", hex::encode(bond.abi_encode())))) +} + +pub(super) fn execute(fixture: &mut Fixture, payer: Address, calls: &[Call]) -> Result<()> { + if calls.len() == 2 { + ensure!( + calls[0].to == TxKind::Call(OUSD.parse()?) + && calls[1].to == TxKind::Call(ESCROW.parse()?), + "unexpected lock targets" + ); + let approval = bonds::approveCall::abi_decode_validate(&calls[0].input)?; + let lock = Escrow::lockCall::abi_decode_validate(&calls[1].input)?; + ensure!( + approval.spender == ESCROW.parse::
()? + && approval.amount == U256::from(lock.amount), + "approval must match exact bond" + ); + ensure!( + lock.amount > U96::ZERO && lock.exitDelay > 0, + "invalid lock" + ); + let id = keccak256( + ( + U256::from(fixture.chain_id), + ESCROW.parse::
()?, + payer, + lock.salt, + ) + .abi_encode(), + ); + ensure!(!fixture.bonds.contains_key(&id), "duplicate bond"); + fixture.bonds.insert( + id, + Escrow::Bond { + meshId: lock.meshId, + hostKey: lock.hostKey, + refundWallet: payer, + amount: lock.amount, + exitDelay: lock.exitDelay, + withdrawAt: U256::ZERO, + withdrawn: false, + }, + ); + *fixture.balances.entry(payer).or_insert(1_000_000) -= u64::try_from(lock.amount)?; + } else { + ensure!( + calls.len() == 1 && calls[0].to == TxKind::Call(ESCROW.parse()?), + "unexpected refund call" + ); + if calls[0].input[..4] == Escrow::requestExitCall::SELECTOR { + let exit = Escrow::requestExitCall::abi_decode_validate(&calls[0].input)?; + let bond = fixture.bonds.get_mut(&exit.id).context("unknown bond")?; + ensure!( + bond.refundWallet == payer && !bond.withdrawn, + "unauthorized exit" + ); + if bond.withdrawAt == U256::ZERO { + bond.withdrawAt = U256::from(fixture.now) + U256::from(bond.exitDelay); + } + return Ok(()); + } + let withdraw = Escrow::withdrawCall::abi_decode_validate(&calls[0].input)?; + let bond = fixture + .bonds + .get_mut(&withdraw.id) + .context("unknown bond")?; + ensure!( + bond.refundWallet == payer + && !bond.withdrawn + && bond.withdrawAt != U256::ZERO + && U256::from(fixture.now) >= bond.withdrawAt, + "unauthorized or early refund" + ); + bond.withdrawn = true; + *fixture.balances.entry(payer).or_insert(1_000_000) += u64::try_from(bond.amount)?; + } + Ok(()) +} +fn bond_attempt(wallet: &Wallet, id: &str) -> BondAttempt { + wallet.journal.get(id).unwrap().unwrap() +} +fn settings() -> BondSettings { + BondSettings { + contract: Some(ESCROW.into()), + max_lock: 100, + max_exit_delay_seconds: 7200, + providers: Requirement { + minimum_amount: 50, + minimum_exit_delay_seconds: 600, + }, + ..Default::default() + } +} +fn intent() -> Intent { + Intent::Lock { + mesh_id: "fixture-mesh".into(), + host_key: "ab".repeat(32), + amount: 100, + exit_delay_seconds: 3600, + salt: B256::repeat_byte(3).to_string(), + } +} +fn op(n: u128) -> String { + uuid::Uuid::from_u128(n).to_string() +} +async fn finalized_lock(wallet: &Wallet, settings: &BondSettings, intent: &Intent) -> Value { + wallet.bond(settings, &op(1), intent.clone()).await.unwrap(); + wallet.bond(settings, &op(1), intent.clone()).await.unwrap() +} + +#[tokio::test] +async fn operation_uuid_aliases_reuse_the_original_transaction() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + let settings = settings(); + let id = uuid::Uuid::from_u128(0xabcdef); + let intent = intent(); + let original = wallet + .bond(&settings, &id.to_string().to_uppercase(), intent.clone()) + .await + .unwrap(); + for alias in [ + id.simple().to_string(), + id.urn().to_string(), + id.braced().to_string(), + ] { + let replay = wallet + .bond(&settings, &alias, intent.clone()) + .await + .unwrap(); + assert_eq!(replay["id"], id.to_string()); + assert_eq!(replay["hash"], original["hash"]); + } + assert_eq!(state.lock().unwrap().raws.len(), 1); + assert_eq!(wallet.journal.all::().unwrap().len(), 1); + server.abort(); +} + +#[tokio::test] +async fn advancing_finality_does_not_expire_an_included_transaction() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + let settings = settings(); + wallet.bond(&settings, &op(1), intent()).await.unwrap(); + let attempt = wallet + .journal + .unresolved::() + .unwrap() + .pop() + .unwrap(); + { + let mut fixture = state.lock().unwrap(); + fixture.finalized_height = 9; + fixture.now = attempt.tx.expires_at - 1; + fixture.next_finalized = Some((10, attempt.tx.expires_at)); + } + wallet.reconcile().await.unwrap(); + assert_eq!(bond_attempt(&wallet, &op(1)).tx.status, "pending"); + wallet.reconcile().await.unwrap(); + assert_eq!(bond_attempt(&wallet, &op(1)).tx.status, "finalized"); + server.abort(); +} + +#[tokio::test] +async fn missing_receipts_with_a_consumed_finalized_nonce_stay_pending() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + let settings = settings(); + wallet.bond(&settings, &op(1), intent()).await.unwrap(); + let attempt = wallet + .journal + .unresolved::() + .unwrap() + .pop() + .unwrap(); + { + let mut fixture = state.lock().unwrap(); + fixture.now = attempt.tx.expires_at; + fixture.hide_receipt = true; + } + wallet.reconcile().await.unwrap(); + assert_eq!(bond_attempt(&wallet, &op(1)).tx.status, "pending"); + assert!(wallet.bond(&settings, &op(2), intent()).await.is_err()); + state.lock().unwrap().hide_receipt = false; + wallet.reconcile().await.unwrap(); + assert_eq!(bond_attempt(&wallet, &op(1)).tx.status, "finalized"); + assert_eq!(state.lock().unwrap().raws.len(), 1); + server.abort(); +} +fn proof(result: &Value) -> Value { + json!({"chain_id":42431,"contract":ESCROW,"bond_id":result["bond_id"]}) +} + +#[tokio::test] +async fn idle_reconciliation_does_not_contact_the_chain() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + for _ in 0..3 { + wallet.reconcile().await.unwrap(); + } + assert!(state.lock().unwrap().calls.is_empty()); + server.abort(); +} + +#[tokio::test] +async fn without_an_escrow_no_bond_qualifies_and_no_chain_is_read() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + let mut policy = settings(); + policy.contract = None; + let before = state.lock().unwrap().calls.len(); + for evidence in [json!({"bond":"uninspected"}), json!({"chain_id":4217})] { + let decision = bonds::verify( + &wallet.rpc, + &policy, + "fixture-mesh", + &"ab".repeat(32), + evidence, + ) + .await + .unwrap(); + assert_eq!(decision["accepted"], false); + let far = crate::config::now() + 300 * 24 * 60 * 60; + assert!(decision["valid_until"].as_u64().unwrap() > far); + } + assert_eq!(state.lock().unwrap().calls.len(), before); + server.abort(); +} + +#[tokio::test] +async fn bond_state_verification_rejects_replays_withdrawals_wrong_code_and_stale_state() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + let settings = settings(); + let result = finalized_lock(&wallet, &settings, &intent()).await; + assert_eq!(result["status"], "finalized"); + let reference = proof(&result); + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference.clone(), + ) + .await + .is_ok() + ); + for (mesh, host) in [ + ("other-mesh", "ab".repeat(32)), + ("fixture-mesh", "ac".repeat(32)), + ] { + assert!( + bonds::verify(&wallet.rpc, &settings, mesh, &host, reference.clone(),) + .await + .is_err() + ); + } + for (field, value) in [ + ("chain_id", json!(4217)), + ("contract", json!(OUSD)), + ("bond_id", json!("bad")), + ] { + let mut wrong = reference.clone(); + wrong[field] = value; + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + wrong, + ) + .await + .is_err() + ); + } + state.lock().unwrap().bond_code_valid = false; + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference.clone(), + ) + .await + .is_err() + ); + state.lock().unwrap().bond_code_valid = true; + state.lock().unwrap().now -= 121; + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference.clone(), + ) + .await + .is_err() + ); + state.lock().unwrap().now += 121; + let id: B256 = result["bond_id"].as_str().unwrap().parse().unwrap(); + state.lock().unwrap().bonds.get_mut(&id).unwrap().amount = U96::from(49); + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference.clone(), + ) + .await + .is_err() + ); + state.lock().unwrap().bonds.get_mut(&id).unwrap().amount = U96::from(100); + state.lock().unwrap().bonds.get_mut(&id).unwrap().exitDelay = 599; + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference.clone(), + ) + .await + .is_err() + ); + state.lock().unwrap().bonds.get_mut(&id).unwrap().exitDelay = 3600; + state.lock().unwrap().bonds.get_mut(&id).unwrap().withdrawAt = + U256::from(crate::config::now() + 3600); + let deadline = crate::config::now() + 600; + state.lock().unwrap().bonds.get_mut(&id).unwrap().withdrawAt = U256::from(deadline); + let exiting = bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference.clone(), + ) + .await + .unwrap(); + assert_eq!(exiting["valid_until"], deadline); + state.lock().unwrap().bonds.get_mut(&id).unwrap().withdrawAt = U256::from(crate::config::now()); + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference.clone(), + ) + .await + .unwrap_err() + .to_string() + .contains("withdrawable") + ); + state.lock().unwrap().bonds.get_mut(&id).unwrap().withdrawn = true; + assert!( + bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + reference, + ) + .await + .is_err() + ); + server.abort(); +} + +#[tokio::test] +async fn bonds_and_payments_share_nonce_owner_and_restart_preserves_signed_bytes() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let operator = wallet(dir.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let lock = intent(); + let mut settings = settings(); + { + let mut state = state.lock().unwrap(); + state.lose_reply = true; + state.hide_receipt = true; + } + let pending = operator + .bond(&settings, &op(1), lock.clone()) + .await + .unwrap(); + assert_eq!(pending["status"], "pending"); + assert!(pending.get("raw").is_none()); + let original = bond_attempt(&operator, &op(1)); + let agreed = terms(&operator, &seller, 1); + assert!(operator.mpp(open_request(&agreed)).await.is_err()); + assert!(operator.balance().await.unwrap().reserved >= 100); + drop(operator); + let operator = wallet(dir.path(), &url, 1); + settings.max_lock = 0; + assert_eq!( + operator + .bond(&settings, &op(1), lock.clone()) + .await + .unwrap()["status"], + "pending" + ); + assert_eq!(bond_attempt(&operator, &op(1)).tx.raw, original.tx.raw); + state.lock().unwrap().hide_receipt = false; + operator.reconcile().await.unwrap(); + assert_eq!( + operator.bond(&settings, &op(1), lock).await.unwrap()["status"], + "finalized" + ); + assert!(operator.bond(&settings, &op(2), intent()).await.is_err()); + assert_eq!(state.lock().unwrap().raws.len(), 1); + // A subsequent payment uses nonce 1; the bond's native multicall used nonce 0. + fund(&operator, &agreed).await; + assert_eq!(attempt(&operator, &attempt_id(&agreed, "open")).tx.nonce, 1); + // A pending payment prevents signing a new bond, including with another salt. + state.lock().unwrap().hide_receipt = true; + operator + .mpp(open_request(&terms(&operator, &seller, 2))) + .await + .unwrap(); + settings.max_lock = 100; + let mut next = intent(); + if let Intent::Lock { salt, .. } = &mut next { + *salt = B256::repeat_byte(4).to_string(); + } + assert!(operator.bond(&settings, &op(3), next).await.is_err()); + assert!( + operator + .journal + .get::(&op(3)) + .unwrap() + .is_none() + ); + server.abort(); +} + +#[tokio::test] +async fn explicit_refund_works_without_authorization_for_new_locks() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + let mut settings = settings(); + let mut initial = intent(); + if let Intent::Lock { + exit_delay_seconds, .. + } = &mut initial + { + *exit_delay_seconds = 10; + } + let result = finalized_lock(&wallet, &settings, &initial).await; + let id = result["bond_id"].as_str().unwrap().to_string(); + assert!( + wallet + .bond( + &settings, + &op(2), + Intent::Withdraw { + bond_id: id.clone() + } + ) + .await + .is_err() + ); + settings.max_lock = 0; + settings.max_exit_delay_seconds = 0; + let exit = Intent::RequestExit { + bond_id: id.clone(), + }; + let before = crate::config::now(); + let exited = wallet.bond(&settings, &op(3), exit.clone()).await.unwrap(); + wallet.bond(&settings, &op(3), exit).await.unwrap(); + // The exit records when its delay has passed at the earliest. + let delay = state.lock().unwrap().bonds[&id.parse::().unwrap()].exitDelay; + let withdraw_after = exited["withdraw_after"].as_u64().unwrap(); + assert!((before + delay..=crate::config::now() + delay).contains(&withdraw_after)); + let deadline = + u64::try_from(state.lock().unwrap().bonds[&id.parse::().unwrap()].withdrawAt) + .unwrap(); + state.lock().unwrap().now = deadline - 1; + assert!( + wallet + .bond( + &settings, + &op(2), + Intent::Withdraw { + bond_id: id.clone() + } + ) + .await + .is_err() + ); + state.lock().unwrap().now = deadline; + let refund = Intent::Withdraw { bond_id: id }; + wallet + .bond(&settings, &op(2), refund.clone()) + .await + .unwrap(); + assert_eq!( + wallet.bond(&settings, &op(2), refund).await.unwrap()["status"], + "finalized" + ); + assert_eq!( + state.lock().unwrap().balances[&wallet.profile.address.parse::
().unwrap()], + 1_000_000 + ); + server.abort(); +} + +#[tokio::test] +async fn pending_exit_survives_restart_without_resetting_the_delay_or_principal() { + let (state, url, server) = server().await; + let directory = tempfile::tempdir().unwrap(); + let wallet = wallet(directory.path(), &url, 1); + let settings = settings(); + let locked = finalized_lock(&wallet, &settings, &intent()).await; + let bond_id = locked["bond_id"].as_str().unwrap().to_string(); + let exit = Intent::RequestExit { + bond_id: bond_id.clone(), + }; + state.lock().unwrap().lose_reply = true; + wallet.bond(&settings, &op(2), exit.clone()).await.unwrap(); + let original = bond_attempt(&wallet, &op(2)); + state + .lock() + .unwrap() + .hidden_receipts + .insert(original.tx.hash.clone()); + let deadline = state.lock().unwrap().bonds[&bond_id.parse::().unwrap()].withdrawAt; + drop(wallet); + let wallet = super::wallet(directory.path(), &url, 1); + assert_eq!( + wallet.bond(&settings, &op(2), exit.clone()).await.unwrap()["status"], + "pending" + ); + assert_eq!(bond_attempt(&wallet, &op(2)).tx.raw, original.tx.raw); + state.lock().unwrap().hidden_receipts.clear(); + assert_eq!( + wallet.bond(&settings, &op(2), exit.clone()).await.unwrap()["status"], + "finalized" + ); + assert!(wallet.bond(&settings, &op(3), exit).await.is_err()); + assert_eq!( + state.lock().unwrap().bonds[&bond_id.parse::().unwrap()].withdrawAt, + deadline + ); + assert_eq!( + state.lock().unwrap().bonds[&bond_id.parse::().unwrap()].amount, + U96::from(100) + ); + assert_eq!(state.lock().unwrap().raws.len(), 2); + let exiting = bonds::verify( + &wallet.rpc, + &settings, + "fixture-mesh", + &"ab".repeat(32), + proof(&locked), + ) + .await + .unwrap(); + assert_eq!(exiting["valid_until"], u64::try_from(deadline).unwrap()); + server.abort(); +} + +#[tokio::test] +async fn verifier_has_no_second_eligibility_cache() { + let (state, url, server) = server().await; + let dir = tempfile::tempdir().unwrap(); + let wallet = wallet(dir.path(), &url, 1); + let settings = settings(); + let locked = finalized_lock(&wallet, &settings, &intent()).await; + let reference = proof(&locked); + let config = crate::config::Config { + data_dir: dir.path().join("engine"), + wallet: wallet.settings.clone(), + bonds: settings.clone(), + prices: Default::default(), + policy: Default::default(), + cap: 0, + buy_peers: Default::default(), + buy_prices: Default::default(), + admission_deposit: None, + channel_topup: 0, + }; + let service = bonds::Service::new(&config).unwrap(); + let host = "ab".repeat(32); + let decision = service + .verify(&settings, "fixture-mesh", &host, reference.clone()) + .await + .unwrap(); + assert_eq!(decision["valid_until"], state.lock().unwrap().now + 3600); + let after = state.lock().unwrap().calls.len(); + let id: B256 = locked["bond_id"].as_str().unwrap().parse().unwrap(); + state.lock().unwrap().bonds.get_mut(&id).unwrap().withdrawAt = U256::from(crate::config::now()); + assert!( + service + .verify(&settings, "fixture-mesh", &host, reference) + .await + .unwrap_err() + .to_string() + .contains("withdrawable") + ); + assert!( + state.lock().unwrap().calls.len() > after, + "only Mesh may reuse eligibility decisions" + ); + server.abort(); +} diff --git a/src/tempo/bonds.rs b/src/tempo/bonds.rs new file mode 100644 index 0000000..ec27aba --- /dev/null +++ b/src/tempo/bonds.rs @@ -0,0 +1,180 @@ +use super::{ + Wallet, receipt, + rpc::address, + transaction::{SignedTransaction, call}, +}; +use crate::{ + bonds::{self, Escrow, Intent, Settings}, + config::now, + contract::OUSD, +}; +use alloy::{ + primitives::{B256, U256}, + sol_types::SolCall, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct BondAttempt { + pub id: String, + pub contract: String, + pub chain_id: u64, + pub intent: Intent, + pub bond_id: String, + /// For an exit, when its delay has passed at the earliest: the signing + /// time plus the bond's exit delay, since the chain starts the delay + /// when the exit lands. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub withdraw_after: Option, + #[serde(flatten)] + pub tx: SignedTransaction, +} +impl Wallet { + pub async fn bond( + &self, + settings: &Settings, + operation_id: &str, + intent: Intent, + ) -> Result { + let operation_id = uuid::Uuid::parse_str(operation_id) + .context("bond operation ID must be a UUID")? + .to_string(); + let _guard = self.send_lock.lock().await; + self.rpc.check_network().await?; + self.reconcile_pending_locked().await?; + let contract = settings + .contract + .as_deref() + .context("bond escrow missing")?; + bonds::check_contract(&self.rpc, contract, "finalized").await?; + let attempt = if let Some(old) = self.journal.get::(&operation_id)? { + ensure!( + old.intent == intent && address(&old.contract)? == address(contract)?, + "bond operation ID reused with another intent" + ); + old + } else { + let mut withdraw_after = None; + let (calls, amount, id) = match &intent { + Intent::Lock { + amount, + exit_delay_seconds, + salt, + .. + } => { + ensure!( + *amount > 0 && *amount <= settings.max_lock, + "bond exceeds explicit lock authorization" + ); + ensure!( + *exit_delay_seconds > 0 + && *exit_delay_seconds <= settings.max_exit_delay_seconds + && *exit_delay_seconds <= bonds::MAX_EXIT_DELAY_SECONDS, + "exit delay exceeds authorization" + ); + let id = bonds::bond_id(&self.rpc, contract, &self.profile.address, salt)?; + let calls = vec![ + call( + address(OUSD)?, + bonds::approveCall { + spender: address(contract)?, + amount: U256::from(*amount), + } + .abi_encode(), + ), + call(address(contract)?, bonds::lock_data(&intent)?), + ]; + (calls, *amount, id) + } + Intent::RequestExit { bond_id } => { + let id: B256 = bond_id.parse()?; + let bond = + receipt::call(&self.rpc, contract, Escrow::getBondCall { id }, "finalized") + .await?; + ensure!( + bond.refundWallet == address(&self.profile.address)? && !bond.withdrawn, + "bond is not owned and funded by this wallet" + ); + ensure!(bond.withdrawAt == U256::ZERO, "bond exit already requested"); + withdraw_after = Some(now().saturating_add(bond.exitDelay)); + ( + vec![call( + address(contract)?, + Escrow::requestExitCall { id }.abi_encode(), + )], + 0, + id, + ) + } + Intent::Withdraw { bond_id } => { + let id: B256 = bond_id.parse()?; + let bond = + receipt::call(&self.rpc, contract, Escrow::getBondCall { id }, "finalized") + .await?; + ensure!( + bond.refundWallet == address(&self.profile.address)?, + "only original funding wallet may withdraw" + ); + ensure!( + !bond.withdrawn + && bond.withdrawAt != U256::ZERO + && U256::from(crate::tempo::rpc::quantity( + &self.rpc.finalized().await?["timestamp"] + )?) >= bond.withdrawAt, + "bond still locked or withdrawn" + ); + ( + vec![call( + address(contract)?, + Escrow::withdrawCall { id }.abi_encode(), + )], + 0, + id, + ) + } + }; + // Approval and deposit are one atomic transaction with one shared wallet nonce. + let tx = self + .prepare_transaction(calls, now() + 600, amount, self.settings.max_fee, 8_000_000) + .await?; + let attempt = BondAttempt { + id: operation_id, + contract: contract.into(), + chain_id: self.settings.network.chain_id(), + intent, + bond_id: id.to_string(), + withdraw_after, + tx, + }; + self.journal.save(&attempt, true)?; + attempt + }; + let attempt = self.resume_bond(attempt).await?; + super::transaction::public_attempt(&attempt) + } + async fn resume_bond(&self, mut attempt: BondAttempt) -> Result { + ensure!( + attempt.chain_id == self.settings.network.chain_id(), + "bond journal network changed" + ); + if attempt.tx.status == "pending" { + attempt.tx.status = self + .resume_transaction( + &attempt.tx.hash, + &attempt.tx.raw, + attempt.tx.expires_at, + attempt.tx.nonce, + ) + .await?; + self.journal.save(&attempt, false)?; + } + Ok(attempt) + } + pub(super) async fn resume_bonds(&self) -> Result<()> { + for attempt in self.journal.unresolved::()? { + self.resume_bond(attempt).await?; + } + Ok(()) + } +} diff --git a/src/tempo/journal.rs b/src/tempo/journal.rs new file mode 100644 index 0000000..855ba2f --- /dev/null +++ b/src/tempo/journal.rs @@ -0,0 +1,230 @@ +//! A write-ahead journal of payments, bonds and wallet sends in the payment +//! ledger's database. Signed bytes commit before any broadcast. +use anyhow::{Context, Result, ensure}; +use rusqlite::{OptionalExtension, params}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; + +use super::{bonds::BondAttempt, send::SendAttempt, transaction::SignedTransaction}; +use crate::contract::{ + Network, + mpp::{ChannelFunding, ChannelTerms, Closure, Voucher}, +}; +use crate::ledger::Database; + +pub struct Journal { + db: Database, +} + +/// One channel transaction: open, top-up, close, request close or withdraw. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Attempt { + pub id: String, + pub terms: ChannelTerms, + pub kind: String, + /// The deposit of an open or top-up, or the capture of a close. + pub amount: u64, + /// The voucher a close presents. + pub voucher: Option, + #[serde(flatten)] + pub tx: SignedTransaction, + pub funding: Option, + /// The verified deposit after a finalized top-up. + pub deposit: Option, + pub closure: Option, +} + +/// A journaled signed transaction: a payment step or a bond operation. +pub trait Record: Serialize + DeserializeOwned { + const KIND: &'static str; + fn id(&self) -> &str; + fn tx(&self) -> &SignedTransaction; +} +impl Record for Attempt { + const KIND: &'static str = "payment"; + fn id(&self) -> &str { + &self.id + } + fn tx(&self) -> &SignedTransaction { + &self.tx + } +} +impl Record for BondAttempt { + const KIND: &'static str = "bond"; + fn id(&self) -> &str { + &self.id + } + fn tx(&self) -> &SignedTransaction { + &self.tx + } +} +impl Record for SendAttempt { + const KIND: &'static str = "send"; + fn id(&self) -> &str { + &self.id + } + fn tx(&self) -> &SignedTransaction { + &self.tx + } +} + +impl Journal { + /// Adds the journal to the ledger's database, pinned to one wallet and + /// network. + pub fn open(db: Database, wallet_id: &str, address: &str, network: Network) -> Result { + { + let mut conn = db.lock().unwrap(); + let tx = conn.transaction()?; + tx.execute_batch( + "CREATE TABLE IF NOT EXISTS attempts(id TEXT PRIMARY KEY, kind TEXT NOT NULL, active INTEGER NOT NULL, body TEXT NOT NULL);", + )?; + let pinned: (Option, Option, Option) = + tx.query_row("SELECT wallet_id,address,chain_id FROM identity", [], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?)) + })?; + if let (Some(pinned_id), Some(pinned_address), Some(chain_id)) = pinned { + ensure!( + pinned_id == wallet_id && pinned_address.eq_ignore_ascii_case(address), + "payment state belongs to another wallet" + ); + ensure!( + chain_id == network.chain_id(), + "payment state belongs to another Tempo network; use a separate data_dir" + ); + } else { + tx.execute( + "UPDATE identity SET wallet_id=?1,address=?2,chain_id=?3", + params![wallet_id, address, network.chain_id()], + )?; + } + tx.commit()?; + } + Ok(Self { db }) + } + pub fn get(&self, id: &str) -> Result> { + let body: Option = self + .db + .lock() + .unwrap() + .query_row( + "SELECT body FROM attempts WHERE id=?1 AND kind=?2", + [id, T::KIND], + |r| r.get(0), + ) + .optional()?; + Ok(body.map(|body| serde_json::from_str(&body)).transpose()?) + } + /// Whether any signed transaction is still unresolved. + pub fn pending(&self) -> Result { + Ok(self.db.lock().unwrap().query_row( + "SELECT EXISTS(SELECT 1 FROM attempts WHERE active=1)", + [], + |r| r.get(0), + )?) + } + pub fn unresolved(&self) -> Result> { + self.query( + "SELECT body FROM attempts WHERE kind=?1 AND active=1", + T::KIND, + ) + } + #[cfg(test)] + pub fn all(&self) -> Result> { + self.query( + "SELECT body FROM attempts WHERE kind=?1 ORDER BY rowid", + T::KIND, + ) + } + /// Every attempt's public metadata, oldest first, without signed bytes. + pub fn public(&self) -> Result> { + let records: Vec = { + let db = self.db.lock().unwrap(); + let mut query = db.prepare("SELECT body FROM attempts ORDER BY rowid")?; + query + .query_map([], |r| r.get::<_, String>(0))? + .map(|body| Ok(serde_json::from_str(&body?)?)) + .collect::>()? + }; + records + .iter() + .map(super::transaction::public_attempt) + .collect() + } + /// Funds held by unresolved transactions of any kind. + pub fn reserved(&self) -> Result { + let pending: Vec = { + let db = self.db.lock().unwrap(); + let mut query = db.prepare("SELECT body FROM attempts WHERE active=1")?; + query + .query_map([], |r| r.get::<_, String>(0))? + .map(|body| Ok(serde_json::from_str(&body?)?)) + .collect::>()? + }; + pending.iter().try_fold(0u64, |sum, tx| { + sum.checked_add(tx.reserved).context("reservation overflow") + }) + } + pub fn save(&self, record: &T, insert: bool) -> Result<()> { + let db = self.db.lock().unwrap(); + let active = record.tx().status == "pending"; + let body = serde_json::to_string(record)?; + if insert { + ensure!( + !db.query_row( + "SELECT EXISTS(SELECT 1 FROM attempts WHERE active=1)", + [], + |r| r.get::<_, bool>(0) + )?, + "another signed transaction is unresolved" + ); + db.execute( + "INSERT INTO attempts VALUES(?1,?2,?3,?4)", + params![record.id(), T::KIND, active, body], + )?; + } else { + ensure!( + db.execute( + "UPDATE attempts SET body=?3,active=?4 WHERE id=?1 AND kind=?2", + params![record.id(), T::KIND, body, active] + )? == 1, + "unknown {} attempt", + T::KIND + ); + } + Ok(()) + } + fn query(&self, sql: &str, kind: &str) -> Result> { + let db = self.db.lock().unwrap(); + let mut query = db.prepare(sql)?; + query + .query_map([kind], |r| r.get::<_, String>(0))? + .map(|body| Ok(serde_json::from_str(&body?)?)) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ledger::Ledger; + + #[test] + fn payment_state_stays_pinned_to_its_wallet_and_network() { + let address = "0x1111111111111111111111111111111111111111"; + for network in [Network::Testnet, Network::Mainnet] { + let dir = tempfile::tempdir().unwrap(); + let open = |wallet_id: &str, network| { + let db = Ledger::open(dir.path()).unwrap().db.clone(); + Journal::open(db, wallet_id, address, network) + }; + open("fixture", network).unwrap(); + let other = if network == Network::Testnet { + Network::Mainnet + } else { + Network::Testnet + }; + assert!(open("fixture", other).is_err()); + assert!(open("another-wallet", network).is_err()); + assert!(open("fixture", network).is_ok()); + } + } +} diff --git a/src/tempo/keys.rs b/src/tempo/keys.rs new file mode 100644 index 0000000..d429ca0 --- /dev/null +++ b/src/tempo/keys.rs @@ -0,0 +1,277 @@ +//! Local key management; credentials are never returned by plugin operations. +use crate::contract::{Network, OUSD}; +use alloy::signers::local::PrivateKeySigner; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use std::{ + fs::{self, OpenOptions}, + io::Write, + path::{Path, PathBuf}, +}; +use zeroize::Zeroizing; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Profile { + pub wallet_id: String, + pub address: String, + pub chain_id: u64, + pub token: String, + pub key_file: String, +} + +pub fn secure_dir(path: &Path) -> Result<()> { + if !path.exists() { + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path)?; + } + #[cfg(not(unix))] + fs::create_dir_all(path)?; + } + ensure!( + fs::symlink_metadata(path)?.file_type().is_dir(), + "state directory must be a real directory" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + fs::metadata(path)?.permissions().mode() & 0o077 == 0, + "state directory must have owner-only permissions (chmod 700)" + ); + } + Ok(()) +} + +pub fn private_file(path: &Path) -> Result<()> { + let metadata = fs::symlink_metadata(path)?; + ensure!( + metadata.is_file() && !metadata.file_type().is_symlink(), + "credential/keystore must be a regular non-symlink file" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + metadata.permissions().mode() & 0o077 == 0, + "credential/keystore file must have owner-only permissions (chmod 600)" + ); + } + Ok(()) +} + +fn password(path: &Path) -> Result>> { + private_file(path)?; + let mut bytes = Zeroizing::new(fs::read(path).context("reading password file")?); + while bytes.last().is_some_and(|b| *b == b'\n' || *b == b'\r') { + bytes.pop(); + } + ensure!(bytes.len() >= 16, "use a password of at least 16 bytes"); + ensure!(bytes.len() <= 4096, "password file is too large"); + Ok(bytes) +} + +pub fn load_profile(dir: &Path, network: Network) -> Result { + let profile: Profile = serde_json::from_slice( + &fs::read(dir.join("wallet.json")) + .context("wallet not initialized; run the local init command first")?, + )?; + ensure!( + profile.chain_id == network.chain_id() && profile.token.eq_ignore_ascii_case(OUSD), + "wallet profile does not match selected Tempo {:?}; use a separate data_dir for each network", + network + ); + ensure!( + matches!( + Path::new(&profile.key_file).components().next(), + Some(std::path::Component::Normal(_)) + ) && Path::new(&profile.key_file).components().count() == 1 + && !profile.key_file.starts_with('.'), + "invalid keystore filename" + ); + crate::contract::validate_address(&profile.address)?; + Ok(profile) +} + +pub fn unlock( + dir: &Path, + credential: Option<&Path>, + profile: &Profile, +) -> Result> { + let Some(credential) = credential else { + return Ok(None); + }; + let key_path = dir.join(&profile.key_file); + private_file(&key_path)?; + let password = password(credential)?; + let signer = PrivateKeySigner::decrypt_keystore(key_path, password.as_slice()) + .context("unable to unlock wallet keystore")?; + ensure!( + format!("{}", signer.address()).eq_ignore_ascii_case(&profile.address), + "keystore address does not match wallet profile" + ); + Ok(Some(signer)) +} + +/// Called only by an explicit operator command, never during plugin startup. +pub fn initialize(dir: &Path, credential: &Path, network: Network) -> Result { + secure_dir(dir)?; + ensure!( + !dir.join("wallet.json").exists(), + "wallet already initialized; refusing to replace it" + ); + let password = password(credential)?; + let staging = dir.join(format!("init-{}", uuid::Uuid::new_v4())); + secure_dir(&staging)?; + let key_name = format!("keystore-{}.json", uuid::Uuid::new_v4()); + let (signer, _) = PrivateKeySigner::new_keystore( + &staging, + &mut rand::rngs::OsRng, + password.as_slice(), + Some(&key_name), + )?; + let staged_key = staging.join(&key_name); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&staged_key, fs::Permissions::from_mode(0o600))?; + } + let restored = PrivateKeySigner::decrypt_keystore(&staged_key, password.as_slice())?; + ensure!( + restored.address() == signer.address(), + "keystore round-trip verification failed" + ); + OpenOptions::new() + .read(true) + .open(&staged_key)? + .sync_all()?; + fs::rename(&staged_key, dir.join(&key_name))?; + let profile = Profile { + wallet_id: uuid::Uuid::new_v4().to_string(), + address: signer.address().to_string(), + chain_id: network.chain_id(), + token: OUSD.into(), + key_file: key_name, + }; + let mut options = OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(dir.join("wallet.json"))?; + file.write_all(&serde_json::to_vec_pretty(&profile)?)?; + file.sync_all()?; + fs::remove_dir(&staging)?; + #[cfg(unix)] + OpenOptions::new().read(true).open(dir)?.sync_all()?; + Ok(profile) +} + +/// The password file of a wallet created without a configured one, kept in +/// its state directory. +pub fn generated_password(dir: &Path) -> PathBuf { + dir.join("wallet.password") +} +/// Writes a random password to `path` unless a file is already there. +pub fn create_password(path: &Path) -> Result<()> { + if path.exists() { + return private_file(path); + } + let mut options = OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(path)?; + file.write_all(hex::encode(rand::random::<[u8; 32]>()).as_bytes())?; + file.sync_all()?; + Ok(()) +} + +pub fn canonical_state_dir(path: &Path) -> Result { + secure_dir(path)?; + Ok(fs::canonicalize(path)?) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use alloy::primitives::B256; + use rand::SeedableRng; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn profile_must_match_selected_network_before_unlocking() { + let dir = tempfile::tempdir().unwrap(); + let mut profile = Profile { + wallet_id: "fixture".into(), + address: PrivateKeySigner::from_bytes(&B256::repeat_byte(1)) + .unwrap() + .address() + .to_string(), + chain_id: Network::Testnet.chain_id(), + token: OUSD.into(), + key_file: "unused-fixture-key".into(), + }; + let path = dir.path().join("wallet.json"); + fs::write(&path, serde_json::to_vec(&profile).unwrap()).unwrap(); + assert!(load_profile(dir.path(), Network::Testnet).is_ok()); + assert!(load_profile(dir.path(), Network::Mainnet).is_err()); + profile.chain_id = 4217; + fs::write(&path, serde_json::to_vec(&profile).unwrap()).unwrap(); + assert!(load_profile(dir.path(), Network::Testnet).is_err()); + assert!(load_profile(dir.path(), Network::Mainnet).is_ok()); + } + + #[test] + fn encrypted_fixture_unlocks_only_with_private_correct_credential() { + let dir = tempfile::tempdir().unwrap(); + let password_file = dir.path().join("password"); + fs::write(&password_file, b"fixture-only-credential-password\n").unwrap(); + fs::set_permissions(&password_file, fs::Permissions::from_mode(0o600)).unwrap(); + // A published deterministic fixture key, never a production wallet. + let signer = PrivateKeySigner::from_bytes(&B256::repeat_byte(1)).unwrap(); + let mut rng = rand::rngs::StdRng::seed_from_u64(7); + let key_file = String::from("fixture-key.json"); + let (_, _uuid) = PrivateKeySigner::encrypt_keystore( + dir.path(), + &mut rng, + signer.to_bytes(), + b"fixture-only-credential-password", + Some(&key_file), + ) + .unwrap(); + fs::set_permissions( + dir.path().join(&key_file), + fs::Permissions::from_mode(0o600), + ) + .unwrap(); + let profile = Profile { + wallet_id: "fixture".into(), + address: signer.address().to_string(), + chain_id: Network::Testnet.chain_id(), + token: OUSD.into(), + key_file, + }; + assert!(unlock(dir.path(), None, &profile).unwrap().is_none()); + assert_eq!( + unlock(dir.path(), Some(&password_file), &profile) + .unwrap() + .unwrap() + .address(), + signer.address() + ); + fs::write(&password_file, b"another-fake-password-for-tests").unwrap(); + assert!(unlock(dir.path(), Some(&password_file), &profile).is_err()); + fs::set_permissions(&password_file, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(unlock(dir.path(), Some(&password_file), &profile).is_err()); + } +} diff --git a/src/tempo/mod.rs b/src/tempo/mod.rs new file mode 100644 index 0000000..463600f --- /dev/null +++ b/src/tempo/mod.rs @@ -0,0 +1,12 @@ +mod bonds; +pub(crate) mod journal; +pub(crate) mod keys; +pub(crate) mod receipt; +pub(crate) mod rpc; +#[cfg(test)] +pub(crate) mod rpc_fixture_tests; +pub(crate) mod send; +pub(crate) mod transaction; +mod wallet; + +pub(crate) use wallet::{Settings, Wallet}; diff --git a/src/tempo/receipt.rs b/src/tempo/receipt.rs new file mode 100644 index 0000000..eb876ab --- /dev/null +++ b/src/tempo/receipt.rs @@ -0,0 +1,434 @@ +use super::rpc::{Rpc, address, quantity}; +use crate::contract::{ + Network, OUSD, + mpp::{ChannelFunding, ChannelTerms, Closure, RESERVE, Voucher}, +}; +use alloy::{ + primitives::{Address, B256, U256, aliases::U96, keccak256}, + sol_types::{SolCall, SolEvent, SolValue}, +}; +use anyhow::{Context, Result, ensure}; +use serde_json::{Value, json}; +use tempo_alloy::contracts::precompiles::{ISignatureVerifier, ITIP20ChannelReserve as Reserve}; + +pub fn descriptor(funding: &ChannelFunding) -> Result { + funding.terms.validate()?; + Ok(Reserve::ChannelDescriptor { + payer: address(&funding.terms.payer)?, + payee: address(&funding.terms.payee)?, + operator: Address::ZERO, + token: address(OUSD)?, + salt: funding.terms.salt()?.parse()?, + authorizedSigner: Address::ZERO, + expiringNonceHash: funding.expiring_nonce_hash.parse()?, + }) +} +pub fn channel_id(network: Network, descriptor: &Reserve::ChannelDescriptor) -> B256 { + keccak256( + ( + descriptor.payer, + descriptor.payee, + descriptor.operator, + descriptor.token, + descriptor.salt, + descriptor.authorizedSigner, + descriptor.expiringNonceHash, + RESERVE.parse::
().unwrap(), + U256::from(network.chain_id()), + ) + .abi_encode(), + ) +} +pub fn domain(network: Network) -> B256 { + keccak256((keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), + keccak256("TIP20 Channel Reserve"), keccak256("1"), U256::from(network.chain_id()), RESERVE.parse::
().unwrap()).abi_encode()) +} +pub fn voucher_digest(network: Network, id: B256, cum: u64) -> B256 { + let hash = keccak256( + ( + keccak256("Voucher(bytes32 channelId,uint96 cumulativeAmount)"), + id, + U96::from(cum), + ) + .abi_encode(), + ); + keccak256( + [ + b"\x19\x01".as_slice(), + domain(network).as_slice(), + hash.as_slice(), + ] + .concat(), + ) +} +pub fn open_data(terms: &ChannelTerms, deposit: u64) -> Result> { + Ok(Reserve::openCall { + payee: address(&terms.payee)?, + operator: Address::ZERO, + token: address(OUSD)?, + deposit: U96::from(deposit), + salt: terms.salt()?.parse()?, + authorizedSigner: Address::ZERO, + } + .abi_encode()) +} +pub async fn call(rpc: &Rpc, to: &str, call: C, tag: &str) -> Result { + let value = rpc + .call( + "eth_call", + json!([{"to":to,"data":format!("0x{}",hex::encode(call.abi_encode()))},tag]), + ) + .await?; + Ok(C::abi_decode_returns_validate(&hex::decode( + value + .as_str() + .context("invalid ABI response")? + .trim_start_matches("0x"), + )?)?) +} +pub async fn check_abi(rpc: &Rpc) -> Result<()> { + rpc.check_network().await?; + ensure!( + call(rpc, RESERVE, Reserve::domainSeparatorCall {}, "finalized").await? + == domain(rpc.network), + "unsupported reserve domain" + ); + ensure!( + call( + rpc, + RESERVE, + Reserve::CLOSE_GRACE_PERIODCall {}, + "finalized" + ) + .await? + == crate::contract::mpp::CLOSE_GRACE_SECONDS, + "unsupported close grace period" + ); + Ok(()) +} +pub async fn state( + rpc: &Rpc, + funding: &ChannelFunding, + tag: &str, +) -> Result { + ensure!( + funding.terms.asset.network()? == rpc.network, + "channel belongs to another Tempo network" + ); + call( + rpc, + RESERVE, + Reserve::getChannelStateCall { + channelId: funding.channel_id.parse()?, + }, + tag, + ) + .await +} +pub async fn finalized_receipt(rpc: &Rpc, hash: &str) -> Result> { + let finalized = rpc.finalized().await?; + finalized_receipt_at(rpc, hash, &finalized).await +} + +pub(super) async fn finalized_receipt_at( + rpc: &Rpc, + hash: &str, + finalized: &Value, +) -> Result> { + let _: B256 = hash.parse()?; + let receipt = rpc.call("eth_getTransactionReceipt", json!([hash])).await?; + if receipt.is_null() { + return Ok(None); + } + ensure!( + receipt["transactionHash"] + .as_str() + .is_some_and(|v| v.eq_ignore_ascii_case(hash)), + "wrong transaction receipt" + ); + let height = quantity(&receipt["blockNumber"])?; + let block = rpc + .call( + "eth_getBlockByNumber", + json!([format!("0x{height:x}"), false]), + ) + .await?; + if block["hash"] != receipt["blockHash"] || quantity(&finalized["number"])? < height { + return Ok(None); + } + let _: B256 = receipt["blockHash"] + .as_str() + .context("missing block hash")? + .parse()?; + Ok(Some(receipt)) +} +pub fn event(receipt: &Value) -> Result { + let mut found = None; + for log in receipt["logs"].as_array().context("missing receipt logs")? { + if !log["address"] + .as_str() + .is_some_and(|v| v.eq_ignore_ascii_case(RESERVE)) + || log["removed"] == true + { + continue; + } + let topics: Vec = log["topics"] + .as_array() + .context("missing topics")? + .iter() + .map(|v| Ok(v.as_str().context("invalid topic")?.parse()?)) + .collect::>()?; + if topics.first() != Some(&E::SIGNATURE_HASH) { + continue; + } + ensure!( + log["transactionHash"] == receipt["transactionHash"] + && log["blockHash"] == receipt["blockHash"], + "log identity mismatch" + ); + let bytes = hex::decode( + log["data"] + .as_str() + .context("missing log data")? + .trim_start_matches("0x"), + )?; + ensure!(found.is_none(), "ambiguous reserve events"); + found = Some(E::decode_raw_log_validate(topics, &bytes)?); + } + found.context("missing native reserve event") +} +/// Verifies the opening transaction and returns its initial deposit. +pub fn verify_open(funding: &ChannelFunding, receipt: &Value) -> Result { + let d = descriptor(funding)?; + let network = funding.terms.asset.network()?; + ensure!( + channel_id(network, &d) == funding.channel_id.parse::()?, + "channel identity mismatch" + ); + ensure!(quantity(&receipt["status"])? == 1, "open reverted"); + ensure!( + receipt["from"] + .as_str() + .is_some_and(|v| v.eq_ignore_ascii_case(&funding.terms.payer)), + "wrong funding sender" + ); + let e = event::(receipt)?; + ensure!( + e.channelId == channel_id(network, &d) + && e.payer == d.payer + && e.payee == d.payee + && e.operator == d.operator + && e.token == d.token + && e.salt == d.salt + && e.authorizedSigner == d.authorizedSigner + && e.expiringNonceHash == d.expiringNonceHash, + "opening event differs from the agreed channel" + ); + Ok(u64::try_from(e.deposit)?) +} +/// Verifies a top-up of `amount` and returns the resulting deposit. +pub fn verify_top_up(funding: &ChannelFunding, receipt: &Value, amount: u64) -> Result { + ensure!(quantity(&receipt["status"])? == 1, "top-up reverted"); + let e = event::(receipt)?; + ensure!( + e.channelId == funding.channel_id.parse::()? + && e.payer == address(&funding.terms.payer)? + && e.additionalDeposit == U96::from(amount), + "top-up event differs from the requested amount" + ); + Ok(u64::try_from(e.newDeposit)?) +} +pub fn verify_close_requested(funding: &ChannelFunding, receipt: &Value) -> Result<()> { + ensure!(quantity(&receipt["status"])? == 1, "close request reverted"); + let e = event::(receipt)?; + ensure!( + e.channelId == funding.channel_id.parse::()? + && e.payer == address(&funding.terms.payer)?, + "close request event differs from the channel" + ); + Ok(()) +} +/// Checks that `voucher` is the payer's signature for this channel and network. +pub async fn verify_signature( + rpc: &Rpc, + funding: &ChannelFunding, + voucher: &Voucher, +) -> Result<()> { + ensure!( + voucher.channel_id == funding.channel_id, + "voucher belongs to another channel" + ); + let digest = voucher_digest(rpc.network, funding.channel_id.parse()?, voucher.cum); + ensure!( + call( + rpc, + RESERVE, + Reserve::getVoucherDigestCall { + channelId: funding.channel_id.parse()?, + cumulativeAmount: U96::from(voucher.cum) + }, + "finalized" + ) + .await? + == digest, + "voucher domain mismatch" + ); + let signature = hex::decode(voucher.signature.trim_start_matches("0x"))?; + ensure!( + signature.len() == 65, + "only primitive secp256k1 vouchers are supported" + ); + ensure!( + call( + rpc, + "0x5165300000000000000000000000000000000000", + ISignatureVerifier::verifyCall { + signer: address(&funding.terms.payer)?, + hash: digest, + signature: signature.into() + }, + "latest" + ) + .await?, + "invalid voucher signature" + ); + Ok(()) +} +/// Verifies a voucher against a finalized, open, unsettled channel that backs +/// it at finalized and latest state, and returns the finalized deposit. +pub async fn verify_voucher(rpc: &Rpc, funding: &ChannelFunding, voucher: &Voucher) -> Result { + ensure!( + funding.terms.asset.network()? == rpc.network, + "funding belongs to another Tempo network" + ); + check_abi(rpc).await?; + let receipt = finalized_receipt(rpc, &funding.open_tx) + .await? + .context("funding is not finalized")?; + verify_open(funding, &receipt)?; + verify_signature(rpc, funding, voucher).await?; + let mut deposit = 0; + for tag in ["finalized", "latest"] { + let s = state(rpc, funding, tag).await?; + ensure!( + s.deposit >= U96::from(voucher.cum) + && s.settled == U96::ZERO + && s.closeRequestedAt == 0, + "channel does not back the voucher, is settled or is closing" + ); + if tag == "finalized" { + deposit = u64::try_from(s.deposit)?; + } + } + Ok(deposit) +} +pub fn verify_close(funding: &ChannelFunding, receipt: &Value) -> Result { + ensure!(quantity(&receipt["status"])? == 1, "close reverted"); + let e = event::(receipt)?; + ensure!( + e.channelId == funding.channel_id.parse::()? + && e.payer == address(&funding.terms.payer)? + && e.payee == address(&funding.terms.payee)?, + "close event differs from the channel" + ); + Ok(Closure { + tx_hash: receipt["transactionHash"] + .as_str() + .context("missing close hash")? + .into(), + channel_id: funding.channel_id.clone(), + captured: u64::try_from(e.settledToPayee)?, + refunded: u64::try_from(e.refundedToPayer)?, + block_number: quantity(&receipt["blockNumber"])?, + }) +} +/// Lowercase IDs of `payee`'s channels named in close requests, cancelled +/// close requests and closes from block `from` through `to`. +pub async fn close_event_channels( + rpc: &Rpc, + payee: &str, + from: u64, + to: u64, +) -> Result> { + let kinds = [ + Reserve::CloseRequested::SIGNATURE_HASH, + Reserve::CloseRequestCancelled::SIGNATURE_HASH, + Reserve::ChannelClosed::SIGNATURE_HASH, + ]; + let payee = B256::left_padding_from(address(payee)?.as_slice()); + let logs = rpc + .call( + "eth_getLogs", + json!([{"address":RESERVE,"fromBlock":format!("0x{from:x}"),"toBlock":format!("0x{to:x}"), + "topics":[kinds.map(|k| k.to_string()),null,null,payee.to_string()]}]), + ) + .await?; + let mut channels = std::collections::BTreeSet::new(); + for log in logs.as_array().context("invalid close logs")? { + let topics: Vec = serde_json::from_value(log["topics"].clone())?; + ensure!( + log["address"] + .as_str() + .is_some_and(|a| a.eq_ignore_ascii_case(RESERVE)) + && topics.len() == 4 + && kinds.contains(&topics[0]) + && topics[3] == payee, + "close log does not match the query" + ); + channels.insert(topics[1].to_string()); + } + Ok(channels) +} +pub async fn find_close(rpc: &Rpc, funding: &ChannelFunding) -> Result> { + ensure!( + funding.terms.asset.network()? == rpc.network, + "funding belongs to another Tempo network" + ); + let open = finalized_receipt(rpc, &funding.open_tx) + .await? + .context("opening receipt unavailable")?; + verify_open(funding, &open)?; + let logs = rpc + .call( + "eth_getLogs", + json!([{"address":RESERVE,"fromBlock":open["blockNumber"],"toBlock":"finalized", + "topics":[Reserve::ChannelClosed::SIGNATURE_HASH.to_string(),funding.channel_id]}]), + ) + .await?; + for log in logs.as_array().context("invalid close logs")? { + let hash = log["transactionHash"] + .as_str() + .context("missing close transaction")?; + if let Some(receipt) = finalized_receipt(rpc, hash).await? { + return Ok(Some(verify_close(funding, &receipt)?)); + } + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn eip712_matches_independent_ethers_vectors_and_deployed_domains() { + // ethers 6.17 TypedDataEncoder, canonical reserve, channel 0x11..11, cumulative 10. + for (network, separator, digest) in [ + ( + Network::Testnet, + "0xa3aa475070603a80823360e5a4a0d3b4fe2cd4e82a109ee3c21a4640a199688d", + "0x163e39f492a9786e450377a6b3646b3da2b187eb5394a2e2c732158a5003c959", + ), + ( + Network::Mainnet, + "0x6465ffa0b0c1e7cfc1a894ba54d79615bc06fd7cc9cfec558f3df82189d17367", + "0x6577ae01dea92b9b5de11cd83e8ea88b050b1f6d407e1da0fba71cd6622da109", + ), + ] { + assert_eq!(domain(network).to_string(), separator); + assert_eq!( + voucher_digest(network, B256::repeat_byte(0x11), 10).to_string(), + digest + ); + } + } +} diff --git a/src/tempo/rpc.rs b/src/tempo/rpc.rs new file mode 100644 index 0000000..875a054 --- /dev/null +++ b/src/tempo/rpc.rs @@ -0,0 +1,154 @@ +use crate::contract::{Network, OUSD}; +use alloy::primitives::{Address, U256}; +use anyhow::{Context, Result, bail, ensure}; +use serde_json::{Value, json}; +use std::time::Duration; + +#[derive(Clone)] +pub struct Rpc { + pub network: Network, + client: reqwest::Client, + url: String, +} + +impl Rpc { + pub fn new(url: String, network: Network) -> Result { + let parsed = reqwest::Url::parse(&url)?; + ensure!( + parsed.scheme() == "https" + || (parsed.scheme() == "http" + && matches!(parsed.host_str(), Some("127.0.0.1" | "localhost" | "::1"))), + "RPC must use HTTPS (loopback HTTP is allowed for local tests)" + ); + ensure!( + parsed.username().is_empty() && parsed.password().is_none(), + "RPC credentials must not be embedded in a URL" + ); + Ok(Self { + network, + client: reqwest::Client::builder() + .timeout(Duration::from_secs(8)) + .connect_timeout(Duration::from_secs(3)) + .build()?, + url, + }) + } + pub async fn call(&self, method: &str, params: Value) -> Result { + let response = self + .client + .post(&self.url) + .json(&json!({"jsonrpc":"2.0","id":1,"method":method,"params":params})) + .send() + .await + .context("RPC transport failure")?; + ensure!( + response.status().is_success(), + "RPC HTTP status {}", + response.status() + ); + let body: Value = response.json().await.context("invalid RPC response")?; + if let Some(error) = body.get("error") { + let message = error + .get("message") + .and_then(Value::as_str) + .unwrap_or("RPC rejected request"); + bail!( + "{}: {}", + method, + message.chars().take(240).collect::() + ); + } + body.get("result") + .cloned() + .context("RPC response has no result") + } + pub async fn finalized(&self) -> Result { + let block = self + .call("eth_getBlockByNumber", json!(["finalized", false])) + .await?; + ensure!(block.is_object(), "RPC did not provide finalized state"); + Ok(block) + } + pub async fn token_call(&self, data: String, tag: &str) -> Result { + self.call("eth_call", json!([{"to":OUSD,"data":data},tag])) + .await? + .as_str() + .map(str::to_owned) + .context("invalid token call response") + } + pub async fn check_network(&self) -> Result<()> { + ensure!( + quantity(&self.call("eth_chainId", json!([])).await?)? == self.network.chain_id(), + "RPC is not the selected Tempo {:?} (chain {})", + self.network, + self.network.chain_id() + ); + let code = self.call("eth_getCode", json!([OUSD, "finalized"])).await?; + ensure!( + code.as_str().is_some_and(|x| x != "0x" && x != "0x0"), + "OUSD token is absent on RPC network" + ); + ensure!( + hex_u64(&self.token_call("0x313ce567".into(), "finalized").await?)? == 6, + "OUSD precision is not six decimals" + ); + Ok(()) + } + pub async fn balance(&self, address: Address) -> Result<(u64, u64)> { + let block = self.finalized().await?; + let height = quantity(&block["number"])?; + let data = format!("0x70a08231{:0>64}", hex::encode(address)); + let result = self.token_call(data, &format!("0x{height:x}")).await?; + let balance = U256::from_str_radix(result.trim_start_matches("0x"), 16)?; + Ok(( + u64::try_from(balance).context("wallet balance exceeds supported u64 native units")?, + height, + )) + } +} + +pub fn quantity(value: &Value) -> Result { + hex_u64(value.as_str().context("expected RPC hex quantity")?) +} +pub fn hex_u64(value: &str) -> Result { + u64::from_str_radix( + value + .strip_prefix("0x") + .context("quantity lacks 0x prefix")?, + 16, + ) + .context("invalid/oversized RPC quantity") +} +pub fn hex_u128(value: &Value) -> Result { + u128::from_str_radix( + value + .as_str() + .context("expected RPC quantity")? + .strip_prefix("0x") + .context("quantity lacks 0x prefix")?, + 16, + ) + .context("invalid/oversized RPC quantity") +} +pub fn address(value: &str) -> Result
{ + crate::contract::validate_address(value)?; + Ok(value.parse()?) +} +pub fn ceil_fee(gas: u64, price: u128) -> Result { + let raw = u128::from(gas) + .checked_mul(price) + .context("gas fee overflow")?; + u64::try_from(raw.div_ceil(1_000_000_000_000)).context("fee exceeds supported native units") +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn attodollars_round_up_to_micro_ousd() { + assert_eq!(ceil_fee(47_002, 600_000_000).unwrap(), 29); + assert_eq!(ceil_fee(0, 600_000_000).unwrap(), 0); + assert_eq!(ceil_fee(1, 1).unwrap(), 1); + assert!(quantity(&json!("0xffffffffffffffffffff")).is_err()); + } +} diff --git a/src/tempo/rpc_fixture_tests.rs b/src/tempo/rpc_fixture_tests.rs new file mode 100644 index 0000000..20267ff --- /dev/null +++ b/src/tempo/rpc_fixture_tests.rs @@ -0,0 +1,1632 @@ +//! Loopback RPC evidence only: real Tempo signing/ABI, deterministic reserve execution fixture. +use super::{ + journal::{Attempt, Journal}, + keys::Profile, + receipt as chain, + rpc::{Rpc, quantity}, + wallet::{Settings, Wallet}, +}; +use crate::contract::{ + Network, OUSD, + mpp::{ChannelFunding, ChannelTerms, RESERVE, Request, Response, Voucher}, +}; +use alloy::{ + consensus::transaction::SignerRecoverable, + eips::eip2718::Decodable2718, + primitives::{Address, B256, Signature, TxKind, U256, aliases::U96, keccak256}, + signers::{Signer, local::PrivateKeySigner}, + sol_types::{SolCall, SolEvent, SolValue}, +}; +use anyhow::{Context, Result, ensure}; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, + time::{SystemTime, UNIX_EPOCH}, +}; +use tempo_alloy::{ + contracts::precompiles::{ISignatureVerifier, ITIP20ChannelReserve as Reserve}, + primitives::TempoTxEnvelope, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; + +#[path = "bond_fixture_tests.rs"] +mod bond_tests; + +struct Channel { + descriptor: Reserve::ChannelDescriptor, + deposit: u64, + close_at: u32, + closed: bool, +} +pub(crate) struct Fixture { + pub(crate) chain_id: u64, + bonds: BTreeMap, + bond_code_valid: bool, + calls: Vec, + channels: BTreeMap, + receipts: BTreeMap, + raws: Vec, + nonces: BTreeMap, + balances: BTreeMap, + now: u64, + finalized_height: u64, + next_finalized: Option<(u64, u64)>, + lose_reply: bool, + pub(crate) hide_receipt: bool, + hidden_receipts: std::collections::BTreeSet, + revert: bool, +} +impl Default for Fixture { + fn default() -> Self { + Self { + chain_id: Network::Testnet.chain_id(), + bonds: Default::default(), + bond_code_valid: true, + calls: Vec::new(), + channels: BTreeMap::new(), + receipts: BTreeMap::new(), + raws: Vec::new(), + nonces: BTreeMap::new(), + balances: BTreeMap::new(), + now: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(), + finalized_height: 10, + next_finalized: None, + lose_reply: false, + hide_receipt: false, + hidden_receipts: Default::default(), + revert: false, + } + } +} +fn abi(value: impl SolValue) -> Value { + json!(format!("0x{}", hex::encode(value.abi_encode()))) +} +fn bytes(value: &Value) -> Result> { + Ok(hex::decode( + value + .as_str() + .context("expected hex")? + .trim_start_matches("0x"), + )?) +} +fn log(event: E, hash: &str) -> Value { + log_at(RESERVE, event, hash) +} +fn log_at(address: &str, event: E, hash: &str) -> Value { + let data = event.encode_log_data(); + json!({"address":address,"topics":data.topics().iter().map(ToString::to_string).collect::>(),"data":format!("0x{}",hex::encode(data.data)), + "transactionHash":hash,"blockHash":B256::repeat_byte(0xbb).to_string(),"logIndex":"0x0","removed":false}) +} +impl Fixture { + fn call(&mut self, method: &str, params: &Value) -> Result { + self.calls.push(method.into()); + match method { + "eth_chainId" => Ok(json!(format!("0x{:x}", self.chain_id))), + "eth_getCode" => Ok( + if params[0] + .as_str() + .unwrap() + .eq_ignore_ascii_case(bond_tests::ESCROW) + && self.bond_code_valid + { + json!(include_str!("../../contracts/runtime.hex").trim()) + } else { + json!("0xef") + }, + ), + "eth_gasPrice" => Ok(json!("0x23c34600")), + "eth_estimateGas" => { + ensure!( + params[0]["feeToken"] + .as_str() + .unwrap() + .eq_ignore_ascii_case(OUSD), + "wrong fee token" + ); + Ok(json!("0xc350")) + } + "eth_getBlockByNumber" => { + let finalized = params[0] == "finalized"; + let height = if finalized { + self.finalized_height + } else { + quantity(¶ms[0])? + }; + let block = json!({"number":format!("0x{height:x}"),"hash":B256::repeat_byte(0xbb).to_string(),"timestamp":format!("0x{:x}",self.now)}); + if finalized && let Some((height, timestamp)) = self.next_finalized.take() { + self.finalized_height = height; + self.now = timestamp; + } + Ok(block) + } + "eth_getTransactionCount" => { + if params[1] != "pending" { + ensure!( + params[1]["blockHash"] == B256::repeat_byte(0xbb).to_string() + && params[1]["requireCanonical"] == true, + "nonce lookup must use the finalized block hash" + ); + } + Ok(json!(format!( + "0x{:x}", + self.nonces + .get(¶ms[0].as_str().unwrap().parse::
()?) + .copied() + .unwrap_or_default() + ))) + } + "eth_getTransactionReceipt" => Ok( + if self.hide_receipt || self.hidden_receipts.contains(params[0].as_str().unwrap()) { + Value::Null + } else { + self.receipts + .get(params[0].as_str().unwrap()) + .cloned() + .unwrap_or(Value::Null) + }, + ), + "eth_blockNumber" => Ok(json!(format!("0x{:x}", self.finalized_height))), + "eth_getLogs" => self.logs(¶ms[0]), + "eth_call" => self.view(¶ms[0]), + "eth_sendRawTransaction" => self.send(params[0].as_str().unwrap()), + _ => anyhow::bail!("unexpected fixture RPC {method}"), + } + } + /// Logs of receipts in the filter's block range whose topics match, where a + /// null topic matches anything and a list matches any of its entries. + fn logs(&self, filter: &Value) -> Result { + let bound = |key: &str, default: u64| match &filter[key] { + Value::String(tag) if tag.starts_with("0x") => quantity(&filter[key]), + _ => Ok(default), + }; + let range = bound("fromBlock", 0)?..=bound("toBlock", u64::MAX)?; + let wanted = filter["topics"].as_array().context("missing topics")?; + let mut logs = Vec::new(); + for receipt in self.receipts.values() { + if !range.contains(&quantity(&receipt["blockNumber"])?) { + continue; + } + for log in receipt["logs"].as_array().context("missing logs")? { + let matches = wanted.iter().enumerate().all(|(i, want)| match want { + Value::Null => true, + Value::Array(any) => any.contains(&log["topics"][i]), + one => log["topics"][i] == *one, + }); + if matches { + logs.push(log.clone()); + } + } + } + Ok(json!(logs)) + } + fn view(&self, request: &Value) -> Result { + let data = bytes(&request["data"])?; + if request["to"].as_str().unwrap().eq_ignore_ascii_case(OUSD) { + return Ok(match data.get(..4) { + Some([0x31, 0x3c, 0xe5, 0x67]) => abi(U256::from(6)), + Some([0x70, 0xa0, 0x82, 0x31]) => { + let who = Address::from_slice(&data[16..36]); + abi(U256::from( + self.balances.get(&who).copied().unwrap_or(1_000_000), + )) + } + _ => abi(U256::ZERO), + }); + } + if request["to"] + .as_str() + .unwrap() + .eq_ignore_ascii_case(bond_tests::ESCROW) + { + return bond_tests::view(self, &data); + } + let selector = &data[..4]; + if selector == Reserve::domainSeparatorCall::SELECTOR { + return Ok(abi(chain::domain(Network::from_chain_id(self.chain_id)?))); + } + if selector == Reserve::CLOSE_GRACE_PERIODCall::SELECTOR { + return Ok(abi(900u64)); + } + if selector == Reserve::getVoucherDigestCall::SELECTOR { + let call = Reserve::getVoucherDigestCall::abi_decode_validate(&data)?; + return Ok(abi(chain::voucher_digest( + Network::from_chain_id(self.chain_id)?, + call.channelId, + u64::try_from(call.cumulativeAmount)?, + ))); + } + if selector == ISignatureVerifier::verifyCall::SELECTOR { + let call = ISignatureVerifier::verifyCall::abi_decode_validate(&data)?; + let valid = Signature::from_raw(&call.signature)? + .recover_address_from_prehash(&call.hash)? + == call.signer; + return Ok(abi(valid)); + } + let call = Reserve::getChannelStateCall::abi_decode_validate(&data)?; + let state = self + .channels + .get(&call.channelId) + .filter(|c| !c.closed) + .map(|c| Reserve::ChannelState { + settled: U96::ZERO, + deposit: U96::from(c.deposit), + closeRequestedAt: c.close_at, + }) + .unwrap_or(Reserve::ChannelState { + settled: U96::ZERO, + deposit: U96::ZERO, + closeRequestedAt: 0, + }); + Ok(abi(state)) + } + fn send(&mut self, raw: &str) -> Result { + let encoded = hex::decode(raw.trim_start_matches("0x"))?; + let hash = keccak256(&encoded).to_string(); + if self.receipts.contains_key(&hash) { + return Ok(json!(hash)); + } + let envelope = TempoTxEnvelope::decode_2718(&mut encoded.as_slice())?; + let signed = envelope.as_aa().context("not a native Tempo transaction")?; + let payer = signed.recover_signer()?; + let tx = signed.tx(); + ensure!( + tx.chain_id == self.chain_id && tx.fee_token == Some(OUSD.parse()?), + "wrong transaction domain" + ); + let reserve = tx.calls.len() == 1 && tx.calls[0].to == TxKind::Call(RESERVE.parse()?); + let token = tx.calls.len() == 1 && tx.calls[0].to == TxKind::Call(OUSD.parse()?); + ensure!( + tx.nonce == *self.nonces.get(&payer).unwrap_or(&0), + "nonce reused" + ); + let data = &tx.calls[0].input; + let context = signed.expiring_nonce_hash(payer); + let logs = if self.revert { + Vec::new() + } else if reserve { + self.execute(payer, context, data, &hash)? + } else if token { + self.transfer(payer, data, &hash)? + } else { + bond_tests::execute(self, payer, &tx.calls)?; + Vec::new() + }; + self.nonces.insert(payer, tx.nonce + 1); + self.raws.push(raw.into()); + self.receipts.insert(hash.clone(),json!({"transactionHash":hash,"blockNumber":"0xa","blockHash":B256::repeat_byte(0xbb).to_string(), + "status":if self.revert {"0x0"}else{"0x1"},"from":payer.to_string(),"logs":logs})); + if self.lose_reply { + self.lose_reply = false; + anyhow::bail!("fixture lost response after inclusion"); + } + Ok(json!(hash)) + } + /// A TIP-20 transfer from the payer's balance. + fn transfer(&mut self, payer: Address, data: &[u8], hash: &str) -> Result> { + let call = super::send::transferCall::abi_decode_validate(data)?; + let amount = u64::try_from(call.amount)?; + let balance = self.balances.entry(payer).or_insert(1_000_000); + ensure!(*balance >= amount, "insufficient token balance"); + *balance -= amount; + *self.balances.entry(call.to).or_insert(1_000_000) += amount; + let event = super::send::Transfer { + from: payer, + to: call.to, + amount: call.amount, + }; + Ok(vec![log_at(OUSD, event, hash)]) + } + fn channel_id(&self, descriptor: &Reserve::ChannelDescriptor) -> Result { + Ok(chain::channel_id( + Network::from_chain_id(self.chain_id)?, + descriptor, + )) + } + /// Executes one reserve call with the precompile's semantics and returns its logs. + fn execute( + &mut self, + payer: Address, + context: B256, + data: &[u8], + hash: &str, + ) -> Result> { + let selector: [u8; 4] = data[..4].try_into()?; + match selector { + Reserve::openCall::SELECTOR => self.open(payer, context, data, hash), + Reserve::topUpCall::SELECTOR => self.top_up(payer, data, hash), + Reserve::requestCloseCall::SELECTOR => { + let call = Reserve::requestCloseCall::abi_decode_validate(data)?; + let id = self.channel_id(&call.descriptor)?; + let now = self.now; + let c = self.channels.get_mut(&id).context("unknown channel")?; + ensure!(!c.closed && payer == c.descriptor.payer, "not payer"); + if c.close_at > 0 { + return Ok(Vec::new()); + } + c.close_at = now.try_into()?; + Ok(vec![log( + Reserve::CloseRequested { + channelId: id, + payer, + payee: c.descriptor.payee, + closeGraceEnd: U256::from(now + 900), + }, + hash, + )]) + } + Reserve::closeCall::SELECTOR => { + let call = Reserve::closeCall::abi_decode_validate(data)?; + ensure!( + payer == call.descriptor.payee && call.captureAmount <= call.cumulativeAmount, + "unauthorized capture" + ); + // Nothing ever settles, so only a nonzero capture needs a voucher. + if call.captureAmount > U96::ZERO { + let digest = chain::voucher_digest( + Network::from_chain_id(self.chain_id)?, + self.channel_id(&call.descriptor)?, + u64::try_from(call.cumulativeAmount)?, + ); + ensure!( + Signature::from_raw(&call.signature)? + .recover_address_from_prehash(&digest)? + == call.descriptor.payer, + "invalid voucher signature" + ); + } + self.close(&call.descriptor, u64::try_from(call.captureAmount)?, hash) + } + _ => { + let call = Reserve::withdrawCall::abi_decode_validate(data)?; + let c = self + .channels + .get(&self.channel_id(&call.descriptor)?) + .context("unknown channel")?; + ensure!( + payer == c.descriptor.payer + && c.close_at > 0 + && self.now >= u64::from(c.close_at) + 900, + "withdraw before grace end" + ); + self.close(&call.descriptor, 0, hash) + } + } + } + fn open( + &mut self, + payer: Address, + context: B256, + data: &[u8], + hash: &str, + ) -> Result> { + let call = Reserve::openCall::abi_decode_validate(data)?; + ensure!( + call.operator == Address::ZERO + && call.authorizedSigner == Address::ZERO + && call.token == OUSD.parse::
()?, + "unexpected channel authority" + ); + let d = Reserve::ChannelDescriptor { + payer, + payee: call.payee, + operator: call.operator, + token: call.token, + salt: call.salt, + authorizedSigner: call.authorizedSigner, + expiringNonceHash: context, + }; + let id = self.channel_id(&d)?; + let deposit = u64::try_from(call.deposit)?; + *self.balances.entry(payer).or_insert(1_000_000) -= deposit; + self.channels.insert( + id, + Channel { + descriptor: d.clone(), + deposit, + close_at: 0, + closed: false, + }, + ); + Ok(vec![log( + Reserve::ChannelOpened { + channelId: id, + payer, + payee: d.payee, + operator: d.operator, + token: d.token, + authorizedSigner: d.authorizedSigner, + salt: d.salt, + expiringNonceHash: context, + deposit: call.deposit, + }, + hash, + )]) + } + fn top_up(&mut self, payer: Address, data: &[u8], hash: &str) -> Result> { + let call = Reserve::topUpCall::abi_decode_validate(data)?; + let id = self.channel_id(&call.descriptor)?; + let amount = u64::try_from(call.additionalDeposit)?; + let c = self.channels.get_mut(&id).context("unknown channel")?; + ensure!(!c.closed && payer == c.descriptor.payer, "not payer"); + *self.balances.entry(payer).or_insert(1_000_000) -= amount; + let c = self.channels.get_mut(&id).unwrap(); + c.deposit += amount; + let mut logs = Vec::new(); + if c.close_at > 0 { + c.close_at = 0; + logs.push(log( + Reserve::CloseRequestCancelled { + channelId: id, + payer, + payee: c.descriptor.payee, + }, + hash, + )); + } + logs.push(log( + Reserve::TopUp { + channelId: id, + payer, + payee: c.descriptor.payee, + additionalDeposit: call.additionalDeposit, + newDeposit: U96::from(c.deposit), + }, + hash, + )); + Ok(logs) + } + fn close( + &mut self, + d: &Reserve::ChannelDescriptor, + capture: u64, + hash: &str, + ) -> Result> { + let id = self.channel_id(d)?; + let c = self.channels.get_mut(&id).context("unknown channel")?; + ensure!( + !c.closed && capture <= c.deposit, + "closed channel or excessive capture" + ); + c.closed = true; + let refund = c.deposit - capture; + *self.balances.entry(d.payee).or_insert(1_000_000) += capture; + *self.balances.entry(d.payer).or_insert(1_000_000) += refund; + Ok(vec![log( + Reserve::ChannelClosed { + channelId: id, + payer: d.payer, + payee: d.payee, + settledToPayee: U96::from(capture), + refundedToPayer: U96::from(refund), + }, + hash, + )]) + } +} +async fn connection(mut socket: TcpStream, fixture: Arc>) { + let mut data = Vec::new(); + let mut buffer = [0u8; 4096]; + let (start, length) = loop { + let count = socket.read(&mut buffer).await.unwrap(); + if count == 0 { + return; + } + data.extend_from_slice(&buffer[..count]); + if let Some(end) = data.windows(4).position(|w| w == b"\r\n\r\n") { + let header = std::str::from_utf8(&data[..end]).unwrap(); + let length = header + .lines() + .find_map(|line| { + let (k, v) = line.split_once(':')?; + k.eq_ignore_ascii_case("content-length") + .then(|| v.trim().parse::().unwrap()) + }) + .unwrap(); + break (end + 4, length); + } + }; + while data.len() < start + length { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + data.extend_from_slice(&buffer[..count]); + } + let request: Value = serde_json::from_slice(&data[start..start + length]).unwrap(); + let response = match fixture + .lock() + .unwrap() + .call(request["method"].as_str().unwrap(), &request["params"]) + { + Ok(value) => json!({"jsonrpc":"2.0","id":1,"result":value}), + Err(error) => { + json!({"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":error.to_string()}}) + } + }; + let body = serde_json::to_vec(&response).unwrap(); + let header = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + socket.write_all(header.as_bytes()).await.unwrap(); + socket.write_all(&body).await.unwrap(); +} +pub(crate) async fn server() -> (Arc>, String, tokio::task::JoinHandle<()>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let fixture = Arc::new(Mutex::new(Fixture::default())); + let state = fixture.clone(); + let task = tokio::spawn(async move { + loop { + let (socket, _) = listener.accept().await.unwrap(); + tokio::spawn(connection(socket, state.clone())); + } + }); + (fixture, url, task) +} +pub(crate) fn wallet(dir: &std::path::Path, url: &str, key: u8) -> Wallet { + wallet_on_network(dir, url, key, Network::Testnet) +} +pub(crate) fn wallet_on_network( + dir: &std::path::Path, + url: &str, + key: u8, + network: Network, +) -> Wallet { + let signer = PrivateKeySigner::from_bytes(&B256::repeat_byte(key)).unwrap(); + let address = signer.address().to_string(); + Wallet { + settings: Settings { + network, + rpc_url: Some(url.into()), + ..Default::default() + }, + profile: Profile { + wallet_id: format!("fixture-{key}"), + address: address.clone(), + chain_id: network.chain_id(), + token: OUSD.into(), + key_file: "unused-fixture-key".into(), + }, + signer: Some(signer), + rpc: Rpc::new(url.into(), network).unwrap(), + journal: Journal::open( + crate::ledger::Ledger::open(dir).unwrap().db.clone(), + &format!("fixture-{key}"), + &address, + network, + ) + .unwrap(), + send_lock: Default::default(), + } +} +fn attempt(wallet: &Wallet, id: &str) -> Attempt { + wallet.journal.get(id).unwrap().unwrap() +} +fn terms(buyer: &Wallet, seller: &Wallet, id: u8) -> ChannelTerms { + ChannelTerms { + buyer_peer: "aa".repeat(32), + seller_peer: "bb".repeat(32), + payer: buyer.profile.address.clone(), + payee: seller.profile.address.clone(), + asset: buyer.settings.network.asset(), + nonce: format!("{id:02x}").repeat(32), + } +} +/// The journal ID of a channel's `kind` attempt. +fn attempt_id(terms: &ChannelTerms, kind: &str) -> String { + format!("channel/{}/{kind}", terms.salt().unwrap()) +} +/// Opens a channel with a deposit of 10. +fn open_request(terms: &ChannelTerms) -> Request { + Request::Open { + terms: terms.clone(), + deposit: 10, + max_fee: 1000, + } +} + +#[tokio::test] +async fn rpc_network_mismatch_is_rejected_before_token_reads_signing_or_broadcast() { + for (selected, reported) in [ + (Network::Testnet, Network::Mainnet), + (Network::Mainnet, Network::Testnet), + ] { + let (fixture, url, task) = server().await; + fixture.lock().unwrap().chain_id = reported.chain_id(); + let buyer_dir = tempfile::tempdir().unwrap(); + let seller_dir = tempfile::tempdir().unwrap(); + let buyer = wallet_on_network(buyer_dir.path(), &url, 1, selected); + let seller = wallet_on_network(seller_dir.path(), &url, 2, selected); + assert!(buyer.info().await.is_err()); + assert!(buyer.balance().await.is_err()); + let error = buyer + .mpp(open_request(&terms(&buyer, &seller, 1))) + .await + .unwrap_err(); + assert!(error.to_string().contains("selected Tempo")); + assert!(buyer.journal.all::().unwrap().is_empty()); + let state = fixture.lock().unwrap(); + assert_eq!(state.calls, vec!["eth_chainId"; 3]); + assert!(state.raws.is_empty()); + task.abort(); + } +} + +#[tokio::test] +async fn cross_network_wallet_requests_are_rejected_without_rpc_or_journal_changes() { + for network in [Network::Testnet, Network::Mainnet] { + let (fixture, url, task) = server().await; + fixture.lock().unwrap().chain_id = network.chain_id(); + let buyer_dir = tempfile::tempdir().unwrap(); + let seller_dir = tempfile::tempdir().unwrap(); + let buyer = wallet_on_network(buyer_dir.path(), &url, 1, network); + let seller = wallet_on_network(seller_dir.path(), &url, 2, network); + let other = if network == Network::Testnet { + Network::Mainnet + } else { + Network::Testnet + }; + let mut wrong = terms(&buyer, &seller, 1); + wrong.asset = other.asset(); + let funding = ChannelFunding { + terms: wrong.clone(), + open_tx: String::new(), + channel_id: String::new(), + expiring_nonce_hash: String::new(), + }; + let voucher = Voucher { + channel_id: String::new(), + cum: 5, + signature: String::new(), + }; + for request in [ + open_request(&wrong), + Request::TopUp { + funding: funding.clone(), + amount: 10, + index: 1, + max_fee: 1000, + }, + Request::SignVoucher { + funding: funding.clone(), + cum: 5, + }, + Request::VerifyVoucher { + funding: funding.clone(), + voucher: voucher.clone(), + }, + Request::Inspect { + funding: funding.clone(), + }, + Request::Close { + funding: funding.clone(), + voucher: Some(voucher), + capture: 5, + }, + Request::Recover { + funding, + max_fee: 1000, + }, + ] { + assert!( + buyer + .mpp(request) + .await + .unwrap_err() + .to_string() + .contains("another Tempo network") + ); + } + assert!(buyer.journal.all::().unwrap().is_empty()); + assert!(fixture.lock().unwrap().calls.is_empty()); + task.abort(); + } +} + +#[tokio::test] +async fn voucher_signed_for_other_network_cannot_authorize_capture() { + for network in [Network::Testnet, Network::Mainnet] { + let (fixture, url, task) = server().await; + fixture.lock().unwrap().chain_id = network.chain_id(); + let buyer_dir = tempfile::tempdir().unwrap(); + let seller_dir = tempfile::tempdir().unwrap(); + let buyer = wallet_on_network(buyer_dir.path(), &url, 1, network); + let seller = wallet_on_network(seller_dir.path(), &url, 2, network); + let funding = fund(&buyer, &terms(&buyer, &seller, 1)).await; + let other = if network == Network::Testnet { + Network::Mainnet + } else { + Network::Testnet + }; + let digest = chain::voucher_digest(other, funding.channel_id.parse().unwrap(), 10); + let signature = buyer + .signer + .as_ref() + .unwrap() + .sign_hash(&digest) + .await + .unwrap(); + let wrong = Voucher { + channel_id: funding.channel_id.clone(), + cum: 10, + signature: format!("0x{}", hex::encode(signature.as_bytes())), + }; + assert!( + seller + .mpp(Request::VerifyVoucher { + funding: funding.clone(), + voucher: wrong.clone() + }) + .await + .is_err() + ); + assert!( + seller + .mpp(Request::Close { + funding: funding.clone(), + voucher: Some(wrong), + capture: 5 + }) + .await + .is_err() + ); + assert!(seller.journal.all::().unwrap().is_empty()); + assert_eq!(fixture.lock().unwrap().raws.len(), 1); + let voucher = sign(&buyer, &funding, 10).await; + let closure = close(&seller, &funding, Some(voucher), 5).await; + assert_eq!(closure.closure.unwrap().refunded, 5); + task.abort(); + } +} + +async fn fund(buyer: &Wallet, terms: &ChannelTerms) -> ChannelFunding { + for _ in 0..3 { + let result = buyer.mpp(open_request(terms)).await.unwrap(); + if let Some(funding) = result.funding { + assert_eq!(result.deposit, 10); + return funding; + } + } + panic!("fixture open did not finalize") +} +async fn sign(buyer: &Wallet, funding: &ChannelFunding, cum: u64) -> Voucher { + buyer + .mpp(Request::SignVoucher { + funding: funding.clone(), + cum, + }) + .await + .unwrap() + .voucher + .unwrap() +} +async fn close( + seller: &Wallet, + funding: &ChannelFunding, + voucher: Option, + capture: u64, +) -> Response { + for _ in 0..3 { + let result = seller + .mpp(Request::Close { + funding: funding.clone(), + voucher: voucher.clone(), + capture, + }) + .await + .unwrap(); + if result.closure.is_some() { + return result; + } + } + panic!("fixture close did not finalize") +} +async fn top_up(buyer: &Wallet, funding: &ChannelFunding, amount: u64, index: u32) -> u64 { + for _ in 0..3 { + let result = buyer + .mpp(Request::TopUp { + funding: funding.clone(), + amount, + index, + max_fee: 1000, + }) + .await + .unwrap(); + if !result.pending { + return result.deposit; + } + } + panic!("fixture top-up did not finalize") +} +/// The journal keeps the signed bytes flat in its record and hides them publicly. +fn assert_journal_encoding(original: &Attempt) { + let encoded = serde_json::to_value(original).unwrap(); + assert!(encoded.get("tx").is_none()); + assert_eq!(encoded["raw"], original.tx.raw); + assert_eq!( + encoded["expiring_nonce_hash"], + original.tx.expiring_nonce_hash + ); + let decoded: Attempt = serde_json::from_value(encoded.clone()).unwrap(); + assert_eq!(decoded.tx.raw, original.tx.raw); + assert_eq!(decoded.tx.nonce, original.tx.nonce); + let public = super::transaction::public_attempt(original).unwrap(); + assert!(public.get("raw").is_none()); + let mut expected = encoded; + expected.as_object_mut().unwrap().remove("raw"); + assert_eq!(public, expected); +} +#[tokio::test] +async fn signed_native_open_partial_capture_and_atomic_refund_survive_lost_reply_restart() { + for network in [Network::Testnet, Network::Mainnet] { + let (fixture, url, server) = server().await; + fixture.lock().unwrap().chain_id = network.chain_id(); + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet_on_network(bd.path(), &url, 1, network); + let seller = wallet_on_network(sd.path(), &url, 2, network); + let terms = terms(&buyer, &seller, 1); + buyer.info().await.unwrap().validate_tempo().unwrap(); + fixture.lock().unwrap().lose_reply = true; + assert!(buyer.mpp(open_request(&terms)).await.unwrap().pending); + let reserved = buyer.balance().await.unwrap().reserved; + assert!(reserved > 10); + let attempt_id = attempt_id(&terms, "open"); + let original = attempt(&buyer, &attempt_id); + let original_salt = original.terms.salt().unwrap(); + assert_journal_encoding(&original); + drop(buyer); + let other = if network == Network::Testnet { + Network::Mainnet + } else { + Network::Testnet + }; + let db = crate::ledger::Ledger::open(bd.path()).unwrap().db.clone(); + assert!(Journal::open(db, "fixture-1", &original.terms.payer, other).is_err()); + let buyer = wallet_on_network(bd.path(), &url, 1, network); + let restored = attempt(&buyer, &attempt_id); + assert_eq!(restored.tx.raw, original.tx.raw); + assert_eq!(restored.tx.hash, original.tx.hash); + assert_eq!(restored.terms.salt().unwrap(), original_salt); + assert_eq!(restored.tx.status, "pending"); + assert_eq!(buyer.balance().await.unwrap().reserved, reserved); + let funding = fund(&buyer, &terms).await; + assert_eq!(buyer.balance().await.unwrap().reserved, 0); + assert_eq!(fixture.lock().unwrap().raws.len(), 1); + let voucher = sign(&buyer, &funding, 10).await; + let verified = seller + .mpp(Request::VerifyVoucher { + funding: funding.clone(), + voucher: voucher.clone(), + }) + .await + .unwrap(); + assert_eq!(verified.deposit, 10); + assert!( + seller + .mpp(Request::Close { + funding: funding.clone(), + voucher: Some(voucher.clone()), + capture: 11 + }) + .await + .is_err() + ); + fixture.lock().unwrap().lose_reply = true; + assert!( + seller + .mpp(Request::Close { + funding: funding.clone(), + voucher: Some(voucher.clone()), + capture: 5 + }) + .await + .unwrap() + .pending + ); + drop(seller); + let seller = wallet_on_network(sd.path(), &url, 2, network); + let result = close(&seller, &funding, Some(voucher.clone()), 5) + .await + .closure + .unwrap(); + assert_eq!((result.captured, result.refunded), (5, 5)); + assert_eq!(fixture.lock().unwrap().raws.len(), 2); + assert_eq!( + buyer + .mpp(Request::Inspect { + funding: funding.clone() + }) + .await + .unwrap() + .closure + .unwrap(), + result + ); + assert!( + seller + .mpp(Request::VerifyVoucher { funding, voucher }) + .await + .is_err() + ); + let state = fixture.lock().unwrap(); + let balance = + |wallet: &Wallet| state.balances[&wallet.profile.address.parse::
().unwrap()]; + assert_eq!((balance(&buyer), balance(&seller)), (999_995, 1_000_005)); + server.abort(); + } +} +#[tokio::test] +async fn zero_full_capture_invalid_vouchers_and_funding_identity() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + for capture in [0, 10] { + let terms = terms(&buyer, &seller, capture as u8 + 1); + let funding = fund(&buyer, &terms).await; + let voucher = sign(&buyer, &funding, 10).await; + let verify = |funding: ChannelFunding, voucher: Voucher| { + seller.mpp(Request::VerifyVoucher { funding, voucher }) + }; + let mut wrong = voucher.clone(); + wrong.cum = 11; + assert!(verify(funding.clone(), wrong).await.is_err()); + let mut wrong = voucher.clone(); + wrong.signature = format!("0x{}", "00".repeat(65)); + assert!(verify(funding.clone(), wrong).await.is_err()); + let mut wrong = funding.clone(); + wrong.expiring_nonce_hash = B256::repeat_byte(9).to_string(); + assert!(verify(wrong, voucher.clone()).await.is_err()); + assert!( + verify(funding.clone(), sign(&buyer, &funding, 11).await) + .await + .is_err() + ); + // A channel opened without an upfront starts with a zero voucher. + let zero = sign(&buyer, &funding, 0).await; + assert_eq!(verify(funding.clone(), zero).await.unwrap().deposit, 10); + // A zero capture closes without presenting any voucher. + let voucher = (capture > 0).then_some(voucher); + let result = close(&seller, &funding, voucher, capture) + .await + .closure + .unwrap(); + assert_eq!((result.captured, result.refunded), (capture, 10 - capture)); + } + assert_eq!(fixture.lock().unwrap().raws.len(), 4); + server.abort(); +} +#[tokio::test] +async fn top_up_adds_deposit_once_per_index_and_cancels_a_close_request() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let terms = terms(&buyer, &seller, 4); + let funding = fund(&buyer, &terms).await; + let large = sign(&buyer, &funding, 30).await; + let verify = |voucher: Voucher| { + seller.mpp(Request::VerifyVoucher { + funding: funding.clone(), + voucher, + }) + }; + assert!(verify(large.clone()).await.is_err()); + let recover = Request::Recover { + funding: funding.clone(), + max_fee: 1000, + }; + buyer.mpp(recover.clone()).await.unwrap(); + let requested = buyer.mpp(recover).await.unwrap(); + assert!(requested.close_requested_at > 0); + assert_eq!(top_up(&buyer, &funding, 20, 1).await, 30); + let status = buyer + .mpp(Request::Inspect { + funding: funding.clone(), + }) + .await + .unwrap(); + assert_eq!((status.deposit, status.close_requested_at), (30, 0)); + assert_eq!(top_up(&buyer, &funding, 20, 1).await, 30); + assert!( + buyer + .mpp(Request::TopUp { + funding: funding.clone(), + amount: 21, + index: 1, + max_fee: 1000 + }) + .await + .is_err() + ); + assert_eq!(fixture.lock().unwrap().raws.len(), 3); + assert_eq!( + attempt(&buyer, &attempt_id(&terms, "topup/1")).deposit, + Some(30) + ); + assert_eq!(verify(large.clone()).await.unwrap().deposit, 30); + let result = close(&seller, &funding, Some(large), 25) + .await + .closure + .unwrap(); + assert_eq!((result.captured, result.refunded), (25, 5)); + server.abort(); +} +#[tokio::test] +async fn payer_recovery_enforces_exact_native_grace_and_refunds_without_seller() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let funding = fund(&buyer, &terms(&buyer, &seller, 3)).await; + let voucher = sign(&buyer, &funding, 5).await; + let recover = || Request::Recover { + funding: funding.clone(), + max_fee: 1000, + }; + buyer.mpp(recover()).await.unwrap(); + buyer.mpp(recover()).await.unwrap(); + assert!( + seller + .mpp(Request::VerifyVoucher { + funding: funding.clone(), + voucher + }) + .await + .is_err() + ); + fixture.lock().unwrap().now += 899; + assert!(buyer.mpp(recover()).await.unwrap().closure.is_none()); + assert_eq!(fixture.lock().unwrap().raws.len(), 2); + fixture.lock().unwrap().now += 1; + buyer.mpp(recover()).await.unwrap(); + let result = buyer.mpp(recover()).await.unwrap().closure.unwrap(); + assert_eq!((result.captured, result.refunded), (0, 10)); + assert_eq!(fixture.lock().unwrap().raws.len(), 3); + server.abort(); +} +#[tokio::test] +async fn unresolved_nonce_and_reverted_open_cannot_duplicate_funding() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let first = terms(&buyer, &seller, 1); + fixture.lock().unwrap().hide_receipt = true; + assert!(buyer.mpp(open_request(&first)).await.unwrap().pending); + assert!( + buyer + .mpp(open_request(&terms(&buyer, &seller, 2))) + .await + .is_err() + ); + assert!(buyer.mpp(open_request(&first)).await.unwrap().pending); + let mut changed = open_request(&first); + if let Request::Open { deposit, .. } = &mut changed { + *deposit = 11; + } + assert!(buyer.mpp(changed).await.is_err()); + fixture.lock().unwrap().hide_receipt = false; + fund(&buyer, &first).await; + fixture.lock().unwrap().revert = true; + let second = terms(&buyer, &seller, 2); + buyer.mpp(open_request(&second)).await.unwrap(); + assert!(buyer.mpp(open_request(&second)).await.unwrap().unfunded); + assert_eq!(fixture.lock().unwrap().raws.len(), 2); + server.abort(); +} + +#[tokio::test] +async fn native_close_evidence_must_identify_the_reserve_and_the_channel() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let funding = fund(&buyer, &terms(&buyer, &seller, 9)).await; + let voucher = sign(&buyer, &funding, 5).await; + let closure = close(&seller, &funding, Some(voucher), 5) + .await + .closure + .unwrap(); + let receipt = fixture.lock().unwrap().receipts[&closure.tx_hash].clone(); + assert_eq!(chain::verify_close(&funding, &receipt).unwrap(), closure); + let mut wrong = receipt.clone(); + wrong["logs"][0]["address"] = json!(OUSD); + assert!(chain::verify_close(&funding, &wrong).is_err()); + let mut wrong = receipt.clone(); + wrong["logs"][0]["removed"] = json!(true); + assert!(chain::verify_close(&funding, &wrong).is_err()); + let mut wrong = receipt; + wrong["logs"][0]["topics"][1] = json!(B256::repeat_byte(7).to_string()); + assert!(chain::verify_close(&funding, &wrong).is_err()); + server.abort(); +} + +#[tokio::test] +async fn finalized_expiry_releases_unbroadcast_nonce_without_recreating_the_open() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let terms = terms(&buyer, &seller, 10); + // Finality is already past the open's lifetime when it is first resumed. + fixture.lock().unwrap().now = crate::config::now() + 700; + for _ in 0..2 { + let response = buyer.mpp(open_request(&terms)).await.unwrap(); + assert!(response.unfunded); + } + assert!(fixture.lock().unwrap().raws.is_empty()); + assert!(!buyer.journal.pending().unwrap()); + server.abort(); +} + +#[tokio::test] +async fn lower_payment_limit_blocks_new_channels_but_preserves_existing_funding_and_recovery() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let agreed = terms(&buyer, &seller, 11); + assert!(buyer.mpp(open_request(&agreed)).await.unwrap().pending); + let attempt_id = attempt_id(&agreed, "open"); + let raw = attempt(&buyer, &attempt_id).tx.raw; + drop(buyer); + let mut buyer = wallet(bd.path(), &url, 1); + buyer.settings.max_payment = 1; + let funding = buyer + .mpp(open_request(&agreed)) + .await + .unwrap() + .funding + .unwrap(); + assert_eq!(attempt(&buyer, &attempt_id).tx.raw, raw); + assert!( + buyer + .mpp(open_request(&terms(&buyer, &seller, 12))) + .await + .is_err() + ); + assert!( + buyer + .mpp(Request::TopUp { + funding: funding.clone(), + amount: 2, + index: 1, + max_fee: 1000 + }) + .await + .is_err() + ); + let recover = || Request::Recover { + funding: funding.clone(), + max_fee: 1000, + }; + buyer.mpp(recover()).await.unwrap(); + buyer.mpp(recover()).await.unwrap(); + fixture.lock().unwrap().now += 900; + buyer.mpp(recover()).await.unwrap(); + let closure = buyer.mpp(recover()).await.unwrap().closure.unwrap(); + assert_eq!((closure.captured, closure.refunded), (0, 10)); + assert_eq!(fixture.lock().unwrap().raws.len(), 3); + server.abort(); +} + +#[tokio::test] +async fn reverted_close_retries_without_changing_capture_and_keeps_original_bytes() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let terms = terms(&buyer, &seller, 21); + let funding = fund(&buyer, &terms).await; + let voucher = Some(sign(&buyer, &funding, 10).await); + let close_request = |capture| Request::Close { + funding: funding.clone(), + voucher: voucher.clone(), + capture, + }; + fixture.lock().unwrap().revert = true; + seller.mpp(close_request(5)).await.unwrap(); + let original = attempt(&seller, &attempt_id(&terms, "close")); + assert!(seller.mpp(close_request(6)).await.is_err()); + drop(seller); + // Each attempt's fee stays within the wallet's per-transaction limit. + let mut seller = wallet(sd.path(), &url, 2); + seller.settings.max_fee = original.tx.reserved - 1; + assert!(seller.mpp(close_request(5)).await.is_err()); + assert_eq!(seller.journal.all::().unwrap().len(), 1); + seller.settings.max_fee = 10_000; + fixture.lock().unwrap().revert = false; + seller.mpp(close_request(5)).await.unwrap(); + let retry = attempt(&seller, &format!("{}/2", attempt_id(&terms, "close"))); + assert_ne!(retry.tx.hash, original.tx.hash); + assert_eq!(retry.tx.nonce, original.tx.nonce + 1); + let closure = close(&seller, &funding, voucher.clone(), 5) + .await + .closure + .unwrap(); + assert_eq!((closure.captured, closure.refunded), (5, 5)); + let retained = attempt(&seller, &original.id); + assert_eq!(retained.tx.status, "reverted"); + assert_eq!(retained.tx.raw, original.tx.raw); + assert_eq!(fixture.lock().unwrap().raws.len(), 3); + server.abort(); +} + +#[tokio::test] +async fn payment_settlement_retry_limit_survives_restart_and_can_be_explicitly_raised() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let funding = fund(&buyer, &terms(&buyer, &seller, 22)).await; + let voucher = Some(sign(&buyer, &funding, 5).await); + let close_request = || Request::Close { + funding: funding.clone(), + voucher: voucher.clone(), + capture: 5, + }; + fixture.lock().unwrap().revert = true; + for _ in 0..3 { + assert!(seller.mpp(close_request()).await.unwrap().pending); + } + drop(seller); + let mut seller = wallet(sd.path(), &url, 2); + assert!( + seller + .mpp(close_request()) + .await + .unwrap_err() + .to_string() + .contains("retry limit reached") + ); + assert_eq!(seller.journal.all::().unwrap().len(), 3); + assert_eq!(seller.balance().await.unwrap().reserved, 0); + fixture.lock().unwrap().revert = false; + seller.settings.max_settlement_attempts = 4; + assert_eq!( + close(&seller, &funding, voucher.clone(), 5) + .await + .closure + .unwrap() + .captured, + 5 + ); + assert_eq!(fixture.lock().unwrap().raws.len(), 5); + server.abort(); +} + +#[tokio::test] +async fn pending_settlement_with_a_missing_receipt_does_not_sign_a_retry() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let terms = terms(&buyer, &seller, 23); + let funding = fund(&buyer, &terms).await; + let voucher = Some(sign(&buyer, &funding, 5).await); + let close_request = || Request::Close { + funding: funding.clone(), + voucher: voucher.clone(), + capture: 5, + }; + seller.mpp(close_request()).await.unwrap(); + let original = attempt(&seller, &attempt_id(&terms, "close")); + { + let mut state = fixture.lock().unwrap(); + state.hidden_receipts.insert(original.tx.hash.clone()); + state.now = original.tx.expires_at; + } + // The channel's finalized close is also hidden, so the exact attempt remains unresolved. + assert!(seller.mpp(close_request()).await.is_err()); + assert_eq!(seller.journal.all::().unwrap().len(), 1); + assert_eq!(attempt(&seller, &original.id).tx.raw, original.tx.raw); + assert!(seller.journal.pending().unwrap()); + assert_eq!(fixture.lock().unwrap().raws.len(), 2); + server.abort(); +} + +#[tokio::test] +async fn expired_unbroadcast_close_can_retry_only_after_finalized_expiry() { + use super::transaction::call; + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let terms = terms(&buyer, &seller, 24); + let funding = fund(&buyer, &terms).await; + let voucher = sign(&buyer, &funding, 10).await; + let data = Reserve::closeCall { + descriptor: chain::descriptor(&funding).unwrap(), + cumulativeAmount: U96::from(10), + captureAmount: U96::from(5), + signature: hex::decode(voucher.signature.trim_start_matches("0x")) + .unwrap() + .into(), + } + .abi_encode(); + let expiry = crate::config::now() - 1; + let tx = seller + .prepare_transaction( + vec![call(RESERVE.parse().unwrap(), data)], + expiry, + 0, + 10_000, + 2_000_000, + ) + .await + .unwrap(); + let original = Attempt { + id: attempt_id(&terms, "close"), + terms: terms.clone(), + kind: "close".into(), + amount: 5, + voucher: Some(voucher.clone()), + tx, + funding: Some(funding.clone()), + deposit: None, + closure: None, + }; + seller.journal.save(&original, true).unwrap(); + fixture.lock().unwrap().now = expiry - 1; + assert!( + seller + .mpp(Request::Close { + funding: funding.clone(), + voucher: Some(voucher.clone()), + capture: 5 + }) + .await + .unwrap() + .pending + ); + assert_eq!(seller.journal.all::().unwrap().len(), 1); + fixture.lock().unwrap().now = expiry; + let closure = close(&seller, &funding, Some(voucher), 5) + .await + .closure + .unwrap(); + assert_eq!(closure.captured, 5); + let expired = attempt(&seller, &original.id); + assert_eq!(expired.tx.status, "expired"); + assert_eq!(expired.tx.raw, original.tx.raw); + assert_eq!( + attempt(&seller, &format!("{}/2", original.id)).tx.nonce, + original.tx.nonce + ); + server.abort(); +} + +#[tokio::test] +async fn payer_recovery_retries_both_failed_steps_with_each_fee_bounded() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let terms = terms(&buyer, &seller, 25); + let funding = fund(&buyer, &terms).await; + let recover = || Request::Recover { + funding: funding.clone(), + max_fee: 1000, + }; + fixture.lock().unwrap().revert = true; + buyer.mpp(recover()).await.unwrap(); + fixture.lock().unwrap().revert = false; + buyer.mpp(recover()).await.unwrap(); + buyer.mpp(recover()).await.unwrap(); + fixture.lock().unwrap().now += 900; + fixture.lock().unwrap().revert = true; + buyer.mpp(recover()).await.unwrap(); + fixture.lock().unwrap().revert = false; + buyer.mpp(recover()).await.unwrap(); + assert_eq!( + buyer + .mpp(recover()) + .await + .unwrap() + .closure + .unwrap() + .refunded, + 10 + ); + for kind in ["request_close/2", "withdraw/2"] { + assert!( + buyer + .journal + .get::(&attempt_id(&terms, kind)) + .unwrap() + .is_some() + ); + } + for attempt in buyer.journal.all::().unwrap() { + let fee = attempt.tx.reserved - if attempt.kind == "open" { 10 } else { 0 }; + assert!(fee <= 1000); + } + assert_eq!(fixture.lock().unwrap().raws.len(), 5); + server.abort(); +} + +#[tokio::test] +async fn recovery_requests_close_again_after_a_top_up_cancelled_the_request() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let mut buyer = wallet(bd.path(), &url, 1); + // Cancelled close requests succeeded, so they use up no retry. + buyer.settings.max_settlement_attempts = 1; + let seller = wallet(sd.path(), &url, 2); + let terms = terms(&buyer, &seller, 26); + let funding = fund(&buyer, &terms).await; + let recover = || Request::Recover { + funding: funding.clone(), + max_fee: 1000, + }; + buyer.mpp(recover()).await.unwrap(); + assert!(buyer.mpp(recover()).await.unwrap().close_requested_at > 0); + for (index, slot) in [(1, "request_close/2"), (2, "request_close/3")] { + assert_eq!( + top_up(&buyer, &funding, 10, index).await, + 10 + 10 * u64::from(index) + ); + buyer.mpp(recover()).await.unwrap(); + assert!(buyer.mpp(recover()).await.unwrap().close_requested_at > 0); + let again = attempt(&buyer, &attempt_id(&terms, slot)); + assert_eq!(again.tx.status, "finalized"); + } + assert_eq!(fixture.lock().unwrap().raws.len(), 6); + server.abort(); +} + +#[tokio::test] +async fn polling_an_open_channel_reads_only_its_state_without_the_transaction_slot() { + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let funding = fund(&buyer, &terms(&buyer, &seller, 27)).await; + let inspect = || Request::Inspect { + funding: funding.clone(), + }; + fixture.lock().unwrap().calls.clear(); + let held = seller.send_lock.lock().await; + let status = tokio::time::timeout(std::time::Duration::from_secs(5), seller.mpp(inspect())) + .await + .unwrap() + .unwrap(); + drop(held); + assert_eq!((status.deposit, status.closure), (10, None)); + assert_eq!(fixture.lock().unwrap().calls, ["eth_call"]); + let recover = || Request::Recover { + funding: funding.clone(), + max_fee: 1000, + }; + buyer.mpp(recover()).await.unwrap(); + buyer.mpp(recover()).await.unwrap(); + fixture.lock().unwrap().calls.clear(); + // A close request makes the poll look for closure evidence. + assert!(seller.mpp(inspect()).await.unwrap().close_requested_at > 0); + assert!( + fixture + .lock() + .unwrap() + .calls + .contains(&"eth_getLogs".to_string()) + ); + server.abort(); +} + +#[tokio::test] +async fn sends_are_journaled_once_per_operation_and_replay_their_original_bytes() { + use super::send::SendAttempt; + let (fixture, url, server) = server().await; + let bd = tempfile::tempdir().unwrap(); + let sd = tempfile::tempdir().unwrap(); + let mut buyer = wallet(bd.path(), &url, 1); + let seller = wallet(sd.path(), &url, 2); + let to = seller.profile.address.clone(); + let operation = uuid::Uuid::new_v4().to_string(); + let own = buyer.profile.address.clone(); + let refused = buyer.send(&operation, &own, 5, 1000).await.unwrap_err(); + assert!(refused.to_string().contains("this wallet")); + for contract in [OUSD, RESERVE] { + let refused = buyer.send(&operation, contract, 5, 1000).await.unwrap_err(); + assert!(refused.to_string().contains("token or reserve")); + } + // Each attempt's fee is bounded by the request and by the wallet. + assert!(buyer.send(&operation, &to, 5, 1).await.is_err()); + buyer.settings.max_fee = 1; + assert!(buyer.send(&operation, &to, 5, 1000).await.is_err()); + buyer.settings.max_fee = 10_000; + assert!(buyer.journal.all::().unwrap().is_empty()); + fixture.lock().unwrap().hide_receipt = true; + let pending = buyer.send(&operation, &to, 5, 1000).await.unwrap(); + assert_eq!(pending["status"], "pending"); + assert!(pending.get("raw").is_none()); + let other = uuid::Uuid::new_v4().to_string(); + assert!(buyer.send(&other, &to, 1, 1000).await.is_err()); + assert!(buyer.send(&operation, &to, 6, 1000).await.is_err()); + let id = format!("send/{operation}"); + let original: SendAttempt = buyer.journal.get(&id).unwrap().unwrap(); + drop(buyer); + let buyer = wallet(bd.path(), &url, 1); + fixture.lock().unwrap().hide_receipt = false; + let sent = buyer.send(&operation, &to, 5, 1000).await.unwrap(); + assert_eq!( + (&sent["status"], &sent["verified"]), + (&json!("finalized"), &json!(true)) + ); + assert_eq!(sent["hash"], pending["hash"]); + let restored: SendAttempt = buyer.journal.get(&id).unwrap().unwrap(); + assert_eq!(restored.tx.raw, original.tx.raw); + assert_eq!(buyer.send(&operation, &to, 5, 1000).await.unwrap(), sent); + let mut state = fixture.lock().unwrap(); + assert_eq!(state.raws.len(), 1); + let balance = + |wallet: &Wallet| state.balances[&wallet.profile.address.parse::
().unwrap()]; + assert_eq!((balance(&buyer), balance(&seller)), (999_995, 1_000_005)); + // The receipt must show exactly this transfer. + let receipt = state.receipts.get_mut(&original.tx.hash).unwrap(); + super::send::verify_transfer(&own, &restored, receipt).unwrap(); + receipt["logs"][0]["topics"][2] = json!(format!("0x{:0>64}", "ab")); + assert!(super::send::verify_transfer(&own, &restored, receipt).is_err()); + server.abort(); +} + +#[tokio::test] +async fn close_events_name_only_this_payees_channels_and_skip_long_gaps() { + let (fixture, url, server) = server().await; + let dirs: [_; 3] = std::array::from_fn(|_| tempfile::tempdir().unwrap()); + let buyer = wallet(dirs[0].path(), &url, 1); + let seller = wallet(dirs[1].path(), &url, 2); + let other = wallet(dirs[2].path(), &url, 3); + let funding = fund(&buyer, &terms(&buyer, &seller, 31)).await; + // The first scan only finds the current block. + let first = seller.close_events(None).await.unwrap(); + assert!(first.skipped && first.channels.is_empty()); + assert_eq!(first.to, 10); + let recover = || Request::Recover { + funding: funding.clone(), + max_fee: 1000, + }; + buyer.mpp(recover()).await.unwrap(); + buyer.mpp(recover()).await.unwrap(); + let scan = seller.close_events(Some(0)).await.unwrap(); + assert!(!scan.skipped); + assert_eq!( + scan.channels, + std::collections::BTreeSet::from([funding.channel_id.to_ascii_lowercase()]) + ); + assert!( + other + .close_events(Some(0)) + .await + .unwrap() + .channels + .is_empty() + ); + fixture.lock().unwrap().finalized_height = 20_000; + let gap = seller.close_events(Some(0)).await.unwrap(); + assert!(gap.skipped && gap.channels.is_empty()); + assert_eq!(gap.to, 20_000); + server.abort(); +} diff --git a/src/tempo/send.rs b/src/tempo/send.rs new file mode 100644 index 0000000..5798de3 --- /dev/null +++ b/src/tempo/send.rs @@ -0,0 +1,179 @@ +//! Journaled OUSD transfers out of the wallet's own balance. +use super::{ + Wallet, receipt, + rpc::{address, quantity}, + transaction::{SignedTransaction, call}, +}; +use crate::{ + config::now, + contract::{OUSD, mpp::RESERVE, validate_address}, +}; +use alloy::{ + primitives::{B256, U256}, + sol, + sol_types::{SolCall, SolEvent}, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +sol! { + function transfer(address to, uint256 amount) external returns (bool); + event Transfer(address indexed from, address indexed to, uint256 amount); +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct SendAttempt { + pub id: String, + pub chain_id: u64, + pub to: String, + #[serde(with = "crate::contract::decimal")] + pub amount: u64, + #[serde(flatten)] + pub tx: SignedTransaction, + /// Whether the finalized receipt shows this transfer. + pub verified: bool, +} + +impl Wallet { + /// Sends `amount` OUSD to `to` once per `operation_id`. It spends only + /// the wallet's own balance: channel deposits are held by the reserve. + pub async fn send( + &self, + operation_id: &str, + to: &str, + amount: u64, + max_fee: u64, + ) -> Result { + let operation_id = + uuid::Uuid::parse_str(operation_id).context("send operation ID must be a UUID")?; + let id = format!("send/{operation_id}"); + validate_address(to)?; + ensure!( + !to.eq_ignore_ascii_case(&self.profile.address), + "sending to this wallet refused" + ); + ensure!( + !to.eq_ignore_ascii_case(OUSD) && !to.eq_ignore_ascii_case(RESERVE), + "sending to the token or reserve contract refused" + ); + ensure!(amount > 0, "amount must be greater than zero"); + let chain_id = self.settings.network.chain_id(); + let _guard = self.send_lock.lock().await; + self.rpc.check_network().await?; + self.reconcile_pending_locked().await?; + let attempt = if let Some(old) = self.journal.get::(&id)? { + ensure!( + old.chain_id == chain_id + && address(&old.to)? == address(to)? + && old.amount == amount, + "send operation ID reused with another intent" + ); + old + } else { + let data = transferCall { + to: address(to)?, + amount: U256::from(amount), + } + .abi_encode(); + let tx = self + .prepare_transaction( + vec![call(address(OUSD)?, data)], + now() + 600, + amount, + max_fee, + 2_000_000, + ) + .await?; + let attempt = SendAttempt { + id, + chain_id, + to: to.into(), + amount, + tx, + verified: false, + }; + self.journal.save(&attempt, true)?; + attempt + }; + let attempt = self.resume_send(attempt).await?; + super::transaction::public_attempt(&attempt) + } + async fn resume_send(&self, mut attempt: SendAttempt) -> Result { + ensure!( + attempt.chain_id == self.settings.network.chain_id(), + "send journal network changed" + ); + if attempt.tx.status == "pending" { + attempt.tx.status = self + .resume_transaction( + &attempt.tx.hash, + &attempt.tx.raw, + attempt.tx.expires_at, + attempt.tx.nonce, + ) + .await?; + self.journal.save(&attempt, false)?; + } + if attempt.tx.status == "finalized" && !attempt.verified { + let receipt = receipt::finalized_receipt(&self.rpc, &attempt.tx.hash) + .await? + .context("finalized send disappeared")?; + verify_transfer(&self.profile.address, &attempt, &receipt)?; + attempt.verified = true; + self.journal.save(&attempt, false)?; + } + Ok(attempt) + } + pub(super) async fn resume_sends(&self) -> Result<()> { + for attempt in self.journal.unresolved::()? { + self.resume_send(attempt).await?; + } + Ok(()) + } +} + +/// The receipt must show exactly one OUSD transfer of the amount from this +/// wallet to the recipient; other token events, such as fees, are ignored. +pub(super) fn verify_transfer(from: &str, attempt: &SendAttempt, receipt: &Value) -> Result<()> { + ensure!(quantity(&receipt["status"])? == 1, "transfer reverted"); + let expected = ( + address(from)?, + address(&attempt.to)?, + U256::from(attempt.amount), + ); + let mut found = 0; + for log in receipt["logs"].as_array().context("missing receipt logs")? { + if !log["address"] + .as_str() + .is_some_and(|v| v.eq_ignore_ascii_case(OUSD)) + || log["removed"] == true + { + continue; + } + let topics: Vec = log["topics"] + .as_array() + .context("missing topics")? + .iter() + .map(|v| Ok(v.as_str().context("invalid topic")?.parse()?)) + .collect::>()?; + if topics.first() != Some(&Transfer::SIGNATURE_HASH) { + continue; + } + let data = hex::decode( + log["data"] + .as_str() + .context("missing log data")? + .trim_start_matches("0x"), + )?; + let event = Transfer::decode_raw_log_validate(topics, &data)?; + if (event.from, event.to, event.amount) == expected { + found += 1; + } + } + ensure!( + found == 1, + "receipt does not show exactly this OUSD transfer" + ); + Ok(()) +} diff --git a/src/tempo/transaction.rs b/src/tempo/transaction.rs new file mode 100644 index 0000000..1c37352 --- /dev/null +++ b/src/tempo/transaction.rs @@ -0,0 +1,185 @@ +//! Native transactions shared by payments and bonds. Callers journal before sending. +use super::{ + Wallet, receipt, + rpc::{address, ceil_fee, hex_u128, quantity}, +}; +use crate::{config::now, contract::OUSD}; +use alloy::{ + eips::eip2718::Encodable2718, + network::{EthereumWallet, NetworkTransactionBuilder, TransactionBuilder}, + primitives::{Address, U256, keccak256}, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::num::NonZeroU64; +use tempo_alloy::{primitives::transaction::Call, rpc::TempoTransactionRequest}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct SignedTransaction { + pub reserved: u64, + pub hash: String, + pub raw: String, + pub nonce: u64, + pub expires_at: u64, + pub expiring_nonce_hash: String, + pub status: String, +} +pub fn call(to: Address, input: Vec) -> Call { + Call { + to: to.into(), + value: U256::ZERO, + input: input.into(), + } +} +impl Wallet { + pub async fn reconcile(&self) -> Result<()> { + let _guard = self.send_lock.lock().await; + if !self.journal.pending()? { + return Ok(()); + } + self.rpc.check_network().await?; + self.reconcile_pending_locked().await + } + pub(super) async fn reconcile_pending_locked(&self) -> Result<()> { + self.resume_bonds().await?; + self.resume_sends().await?; + for attempt in self.journal.unresolved::()? { + self.mpp_resume(attempt).await?; + } + Ok(()) + } + pub(super) async fn prepare_transaction( + &self, + calls: Vec, + expires_at: u64, + amount: u64, + max_fee: u64, + max_gas: u64, + ) -> Result { + ensure!( + !self.journal.pending()?, + "another signed payment or bond is unresolved; reconcile its exact bytes first" + ); + let signer = self + .signer + .as_ref() + .context("transaction requires an unlocked wallet")?; + let nonce = quantity( + &self + .rpc + .call( + "eth_getTransactionCount", + json!([self.profile.address, "pending"]), + ) + .await?, + )?; + let mut tx = TempoTransactionRequest::default() + .with_chain_id(self.settings.network.chain_id()) + .with_from(address(&self.profile.address)?) + .with_calls(calls) + .with_nonce(nonce) + .with_nonce_key(U256::ZERO) + .with_fee_token(address(OUSD)?) + .with_valid_before(NonZeroU64::new(expires_at).context("zero expiry")?); + let gas = quantity( + &self + .rpc + .call("eth_estimateGas", json!([serde_json::to_value(&tx)?])) + .await?, + )? + .checked_mul(120) + .context("gas overflow")? + .div_ceil(100); + ensure!( + gas > 0 && gas <= max_gas, + "unreasonable transaction gas limit: {gas}" + ); + let price = hex_u128(&self.rpc.call("eth_gasPrice", json!([])).await?)? + .checked_mul(2) + .context("fee overflow")?; + ensure!(price > 0, "zero gas price"); + let fee = ceil_fee(gas, price)?; + ensure!( + fee <= max_fee && fee <= self.settings.max_fee, + "transaction fee {fee} exceeds authorization {}", + max_fee.min(self.settings.max_fee) + ); + let reserved = fee.checked_add(amount).context("debit overflow")?; + ensure!( + self.rpc.balance(address(&self.profile.address)?).await?.0 >= reserved, + "insufficient OUSD for transaction and gas" + ); + tx = tx + .with_gas_limit(gas) + .with_max_fee_per_gas(price) + .with_max_priority_fee_per_gas(0); + let envelope = tx.build(&EthereumWallet::from(signer.clone())).await?; + let expiring_nonce_hash = envelope + .as_aa() + .context("expected native Tempo transaction")? + .expiring_nonce_hash(address(&self.profile.address)?) + .to_string(); + let raw = envelope.encoded_2718(); + Ok(SignedTransaction { + reserved, + hash: keccak256(&raw).to_string(), + raw: format!("0x{}", hex::encode(raw)), + nonce, + expires_at, + expiring_nonce_hash, + status: "pending".into(), + }) + } + pub(super) async fn resume_transaction( + &self, + hash: &str, + raw: &str, + expires_at: u64, + nonce: u64, + ) -> Result { + // Receipt eligibility and expiry must use the same finalized cutoff. + let finalized = self.rpc.finalized().await?; + if let Some(receipt) = receipt::finalized_receipt_at(&self.rpc, hash, &finalized).await? { + return Ok(if quantity(&receipt["status"])? == 1 { + "finalized" + } else { + "reverted" + } + .into()); + } + if quantity(&finalized["timestamp"])? >= expires_at { + let consumed = quantity( + &self + .rpc + .call( + "eth_getTransactionCount", + json!([self.profile.address, {"blockHash":finalized["hash"],"requireCanonical":true}]), + ) + .await?, + )? > nonce; + // A lagging receipt index must not turn an included transaction into expiry. + return Ok(if consumed { "pending" } else { "expired" }.into()); + } + if now() < expires_at { + // Transport failure retains the reservation and the original signed bytes. + if let Ok(sent) = self.rpc.call("eth_sendRawTransaction", json!([raw])).await { + ensure!( + sent.as_str() + .is_some_and(|sent| sent.eq_ignore_ascii_case(hash)), + "RPC returned wrong transaction hash" + ); + } + } + Ok("pending".into()) + } +} + +pub(crate) fn public_attempt(attempt: &impl Serialize) -> Result { + let mut value = serde_json::to_value(attempt)?; + value + .as_object_mut() + .context("invalid attempt metadata")? + .remove("raw"); + Ok(value) +} diff --git a/src/tempo/wallet.rs b/src/tempo/wallet.rs new file mode 100644 index 0000000..026ca09 --- /dev/null +++ b/src/tempo/wallet.rs @@ -0,0 +1,721 @@ +use super::{ + journal::{Attempt, Journal}, + keys::{self, Profile}, + receipt as chain, + rpc::{Rpc, address, quantity}, + transaction::{SignedTransaction, call}, +}; +use crate::config::now; +use crate::contract::{ + Balance, Network, WalletInfo, + mpp::{ChannelFunding, ChannelTerms, CloseEvents, RESERVE, Request, Response, Voucher}, +}; +use alloy::{ + primitives::aliases::U96, + signers::{Signer, local::PrivateKeySigner}, + sol_types::SolCall, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use std::{ + path::{Path, PathBuf}, + sync::Arc, +}; +use tempo_alloy::contracts::precompiles::ITIP20ChannelReserve as Reserve; + +/// Lifetime of each close, request-close or withdraw attempt. Expired +/// attempts count toward `max_settlement_attempts`, so the retries together +/// must outlast the buyer's earliest withdrawal; a stuck attempt holds the +/// wallet's single transaction slot for at most this long. +const SETTLEMENT_ATTEMPT_SECONDS: u64 = 3600; +/// The longest block range one close-event scan reads; a longer gap is +/// covered by inspecting every channel instead. +const MAX_CLOSE_LOG_BLOCKS: u64 = 10_000; +/// Lifetime of each open or top-up attempt, which a paid request waits for. +const FUNDING_ATTEMPT_SECONDS: u64 = 600; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Settings { + pub network: Network, + pub rpc_url: Option, + pub password_file: Option, + pub max_settlement_attempts: u32, + /// The largest channel open or top-up deposit. + #[serde(with = "crate::contract::decimal")] + pub max_payment: u64, + /// The largest fee of any one transaction attempt. + #[serde(with = "crate::contract::decimal")] + pub max_fee: u64, +} +impl Default for Settings { + fn default() -> Self { + Self { + network: Network::default(), + rpc_url: None, + password_file: None, + max_settlement_attempts: 3, + max_payment: 1_000_000, + max_fee: 10_000, + } + } +} +impl Settings { + pub fn rpc_url(&self) -> &str { + self.rpc_url.as_deref().unwrap_or(self.network.rpc_url()) + } + /// The configured password file, else the one a wallet created on first + /// use keeps in its state directory `dir`. + pub fn password(&self, dir: &Path) -> Option { + self.password_file + .clone() + .or_else(|| Some(keys::generated_password(dir)).filter(|p| p.exists())) + } +} + +pub struct Wallet { + pub settings: Settings, + pub profile: Profile, + pub(crate) signer: Option, + pub rpc: Rpc, + pub journal: Journal, + pub(crate) send_lock: tokio::sync::Mutex<()>, +} +impl Wallet { + /// Loads the wallet whose key lives in the payment state directory `dir`. + pub fn load(settings: Settings, dir: &Path, db: crate::ledger::Database) -> Result> { + ensure!( + (1..=10).contains(&settings.max_settlement_attempts), + "max_settlement_attempts must be between 1 and 10" + ); + let dir = keys::canonical_state_dir(dir)?; + let profile = keys::load_profile(&dir, settings.network)?; + let signer = keys::unlock(&dir, settings.password(&dir).as_deref(), &profile)?; + let journal = Journal::open(db, &profile.wallet_id, &profile.address, settings.network)?; + let rpc = Rpc::new(settings.rpc_url().into(), settings.network)?; + Ok(Arc::new(Self { + settings, + profile, + signer, + rpc, + journal, + send_lock: tokio::sync::Mutex::new(()), + })) + } + /// Creates the wallet in `dir`, with a random password there unless one + /// is configured, and loads it. + pub fn create( + settings: Settings, + dir: &Path, + db: crate::ledger::Database, + ) -> Result> { + let state = keys::canonical_state_dir(dir)?; + let password = match &settings.password_file { + Some(path) => path.clone(), + None => { + let path = keys::generated_password(&state); + keys::create_password(&path)?; + path + } + }; + keys::initialize(&state, &password, settings.network)?; + Self::load(settings, dir, db) + } + /// Where to send OUSD to fund this wallet; on testnet it also asks the + /// faucet for test coins. + pub async fn fund(&self) -> Result { + let network = self.settings.network; + let mut funding = serde_json::json!({ + "address": self.profile.address, + "network": network, + "asset": network.asset(), + }); + if network == Network::Testnet { + self.rpc.check_network().await?; + let params = serde_json::json!([self.profile.address]); + funding["faucet"] = self.rpc.call("tempo_fundAddress", params).await?; + } + Ok(funding) + } + pub async fn info(&self) -> Result { + self.rpc.check_network().await?; + Ok(WalletInfo { + wallet_id: self.profile.wallet_id.clone(), + address: self.profile.address.clone(), + asset: self.settings.network.asset(), + can_send: self.signer.is_some(), + }) + } + pub async fn balance(&self) -> Result { + self.rpc.check_network().await?; + let (balance, block_number) = self.rpc.balance(address(&self.profile.address)?).await?; + let reserved = self.journal.reserved()?; + Ok(Balance { + balance, + reserved, + spendable: balance.saturating_sub(reserved), + block_number, + }) + } + pub async fn mpp(&self, request: Request) -> Result { + self.check_terms(request.terms())?; + // Signing and polling take no transaction slot. + let request = match request { + Request::SignVoucher { funding, cum } => return self.sign_voucher(&funding, cum).await, + Request::Inspect { funding } => return self.channel_poll(&funding).await, + request => request, + }; + let _guard = self.send_lock.lock().await; + chain::check_abi(&self.rpc).await?; + self.reconcile_pending_locked().await?; + match request { + Request::Open { + terms, + deposit, + max_fee, + } => self.channel_open(terms, deposit, max_fee).await, + Request::TopUp { + funding, + amount, + index, + max_fee, + } => self.channel_top_up(funding, amount, index, max_fee).await, + Request::VerifyVoucher { funding, voucher } => Ok(Response { + deposit: chain::verify_voucher(&self.rpc, &funding, &voucher).await?, + ..Default::default() + }), + Request::Close { + funding, + voucher, + capture, + } => self.channel_close(funding, voucher, capture).await, + Request::Recover { funding, max_fee } => self.channel_recover(funding, max_fee).await, + Request::SignVoucher { .. } | Request::Inspect { .. } => unreachable!(), + } + } + /// The channels of this payee named in close events from block `from` to + /// the latest block. Without a starting block, or after a gap longer than + /// `MAX_CLOSE_LOG_BLOCKS`, it reads no logs and reports the scan skipped. + pub async fn close_events(&self, from: Option) -> Result { + let to = quantity( + &self + .rpc + .call("eth_blockNumber", serde_json::json!([])) + .await?, + )?; + let Some(from) = from.filter(|from| to.saturating_sub(*from) <= MAX_CLOSE_LOG_BLOCKS) + else { + return Ok(CloseEvents { + to, + skipped: true, + ..Default::default() + }); + }; + let payee = &self.profile.address; + Ok(CloseEvents { + channels: chain::close_event_channels(&self.rpc, payee, from.min(to), to).await?, + to, + skipped: false, + }) + } + /// One state read while the channel is open; closure evidence is looked + /// up only once it is closing or gone. + async fn channel_poll(&self, funding: &ChannelFunding) -> Result { + let state = chain::state(&self.rpc, funding, "latest").await?; + if state.deposit > U96::ZERO && state.closeRequestedAt == 0 { + return Ok(Response { + deposit: u64::try_from(state.deposit)?, + ..Default::default() + }); + } + chain::check_abi(&self.rpc).await?; + self.channel_inspect(funding).await + } + fn check_terms(&self, terms: &ChannelTerms) -> Result<()> { + terms.validate()?; + ensure!( + terms.asset.network()? == self.settings.network, + "payment terms belong to another Tempo network" + ); + Ok(()) + } + fn check_payer(&self, terms: &ChannelTerms) -> Result<()> { + ensure!( + terms.payer.eq_ignore_ascii_case(&self.profile.address), + "payer is not this wallet" + ); + Ok(()) + } + async fn sign_voucher(&self, funding: &ChannelFunding, cum: u64) -> Result { + self.check_payer(&funding.terms)?; + let signature = self + .signer + .as_ref() + .context("unlock wallet to sign vouchers")? + .sign_hash(&chain::voucher_digest( + self.settings.network, + funding.channel_id.parse()?, + cum, + )) + .await?; + Ok(Response { + voucher: Some(Voucher { + channel_id: funding.channel_id.clone(), + cum, + signature: format!("0x{}", hex::encode(signature.as_bytes())), + }), + ..Default::default() + }) + } + async fn channel_open( + &self, + terms: ChannelTerms, + deposit: u64, + max_fee: u64, + ) -> Result { + self.check_payer(&terms)?; + let id = format!("channel/{}/open", terms.salt()?); + let attempt = if let Some(old) = self.journal.get::(&id)? { + ensure!( + old.terms == terms && old.amount == deposit, + "channel reused with different terms" + ); + old + } else { + ensure!( + deposit > 0 && deposit <= self.settings.max_payment, + "deposit exceeds wallet limit" + ); + let data = chain::open_data(&terms, deposit)?; + let tx = self + .reserve_transaction(data, FUNDING_ATTEMPT_SECONDS, deposit, max_fee) + .await?; + let attempt = Attempt { + id, + terms: terms.clone(), + kind: "open".into(), + amount: deposit, + voucher: None, + tx, + funding: None, + deposit: None, + closure: None, + }; + self.journal.save(&attempt, true)?; + attempt + }; + let mut attempt = self.mpp_resume(attempt).await?; + if matches!(attempt.tx.status.as_str(), "expired" | "reverted") { + return Ok(Response { + unfunded: true, + ..Default::default() + }); + } + if attempt.tx.status != "finalized" { + return pending(&attempt); + } + if attempt.funding.is_none() { + let mut funding = ChannelFunding { + terms, + open_tx: attempt.tx.hash.clone(), + channel_id: String::new(), + expiring_nonce_hash: attempt.tx.expiring_nonce_hash.clone(), + }; + funding.channel_id = + chain::channel_id(self.settings.network, &chain::descriptor(&funding)?).to_string(); + let receipt = chain::finalized_receipt(&self.rpc, &attempt.tx.hash) + .await? + .context("finalized open disappeared")?; + ensure!( + chain::verify_open(&funding, &receipt)? == deposit, + "opening deposit differs from the request" + ); + attempt.funding = Some(funding); + self.journal.save(&attempt, false)?; + } + Ok(Response { + funding: attempt.funding, + deposit, + ..Default::default() + }) + } + async fn channel_top_up( + &self, + funding: ChannelFunding, + amount: u64, + index: u32, + max_fee: u64, + ) -> Result { + self.check_payer(&funding.terms)?; + let base = format!("channel/{}/topup/{index}", funding.terms.salt()?); + let (id, previous) = self.attempt_slot(&base, false, |old| { + old.funding.as_ref() == Some(&funding) && old.amount == amount + })?; + let attempt = if let Some(old) = previous { + old + } else { + ensure!( + amount > 0 && amount <= self.settings.max_payment, + "top-up exceeds wallet limit" + ); + let inspected = self.channel_inspect(&funding).await?; + if inspected.closure.is_some() { + return Ok(inspected); + } + let data = Reserve::topUpCall { + descriptor: chain::descriptor(&funding)?, + additionalDeposit: U96::from(amount), + } + .abi_encode(); + let tx = self + .reserve_transaction(data, FUNDING_ATTEMPT_SECONDS, amount, max_fee) + .await?; + let attempt = Attempt { + id, + terms: funding.terms.clone(), + kind: "topup".into(), + amount, + voucher: None, + tx, + funding: Some(funding.clone()), + deposit: None, + closure: None, + }; + self.journal.save(&attempt, true)?; + attempt + }; + let mut attempt = self.mpp_resume(attempt).await?; + if attempt.tx.status != "finalized" { + return pending(&attempt); + } + if attempt.deposit.is_none() { + let receipt = chain::finalized_receipt(&self.rpc, &attempt.tx.hash) + .await? + .context("finalized top-up disappeared")?; + attempt.deposit = Some(chain::verify_top_up(&funding, &receipt, amount)?); + self.journal.save(&attempt, false)?; + } + Ok(Response { + deposit: attempt.deposit.unwrap_or_default(), + ..Default::default() + }) + } + async fn channel_inspect(&self, funding: &ChannelFunding) -> Result { + let closure = chain::find_close(&self.rpc, funding).await?; + if closure.is_some() { + return Ok(Response { + closure, + ..Default::default() + }); + } + let state = chain::state(&self.rpc, funding, "latest").await?; + ensure!( + state.deposit > U96::ZERO, + "channel absent without finalized close evidence" + ); + Ok(Response { + deposit: u64::try_from(state.deposit)?, + close_requested_at: state.closeRequestedAt.into(), + ..Default::default() + }) + } + async fn channel_close( + &self, + funding: ChannelFunding, + voucher: Option, + capture: u64, + ) -> Result { + ensure!( + funding + .terms + .payee + .eq_ignore_ascii_case(&self.profile.address), + "payee is not this wallet" + ); + let cum = voucher.as_ref().map_or(0, |v| v.cum); + ensure!(capture <= cum, "capture exceeds the presented voucher"); + let inspected = self.channel_inspect(&funding).await?; + if inspected.closure.is_some() { + return Ok(inspected); + } + let base = format!("channel/{}/close", funding.terms.salt()?); + let (id, previous) = self.attempt_slot(&base, false, |old| { + old.funding.as_ref() == Some(&funding) + && old.amount == capture + && old.voucher == voucher + })?; + let attempt = if let Some(old) = previous { + old + } else { + let mut signature = Vec::new(); + if let Some(voucher) = &voucher { + // A capture of what already settled (nothing) skips the native signature check. + if capture > 0 { + chain::verify_signature(&self.rpc, &funding, voucher).await?; + } + signature = hex::decode(voucher.signature.trim_start_matches("0x"))?; + } + let data = Reserve::closeCall { + descriptor: chain::descriptor(&funding)?, + cumulativeAmount: U96::from(cum), + captureAmount: U96::from(capture), + signature: signature.into(), + } + .abi_encode(); + let tx = self + .reserve_transaction(data, SETTLEMENT_ATTEMPT_SECONDS, 0, self.settings.max_fee) + .await?; + let attempt = Attempt { + id, + terms: funding.terms.clone(), + kind: "close".into(), + amount: capture, + voucher, + tx, + funding: Some(funding), + deposit: None, + closure: None, + }; + self.journal.save(&attempt, true)?; + attempt + }; + self.channel_finish(attempt).await + } + async fn channel_recover(&self, funding: ChannelFunding, max_fee: u64) -> Result { + ensure!( + funding + .terms + .payer + .eq_ignore_ascii_case(&self.profile.address), + "only payer can recover" + ); + let inspected = self.channel_inspect(&funding).await?; + if inspected.closure.is_some() { + return Ok(inspected); + } + let (kind, data) = if inspected.close_requested_at == 0 { + ( + "request_close", + Reserve::requestCloseCall { + descriptor: chain::descriptor(&funding)?, + } + .abi_encode(), + ) + } else { + let finalized = self.rpc.finalized().await?; + if quantity(&finalized["timestamp"])? + < inspected.close_requested_at + crate::contract::mpp::CLOSE_GRACE_SECONDS + { + return Ok(inspected); + } + ( + "withdraw", + Reserve::withdrawCall { + descriptor: chain::descriptor(&funding)?, + } + .abi_encode(), + ) + }; + let base = format!("channel/{}/{kind}", funding.terms.salt()?); + // A finalized close request that the chain no longer shows was + // cancelled by a top-up, so the next request takes a new slot. + let (id, previous) = self.attempt_slot(&base, kind == "request_close", |old| { + old.funding.as_ref() == Some(&funding) + })?; + let attempt = if let Some(old) = previous { + old + } else { + let tx = self + .reserve_transaction(data, SETTLEMENT_ATTEMPT_SECONDS, 0, max_fee) + .await?; + let attempt = Attempt { + id, + terms: funding.terms.clone(), + kind: kind.into(), + amount: 0, + voucher: None, + tx, + funding: Some(funding.clone()), + deposit: None, + closure: None, + }; + self.journal.save(&attempt, true)?; + attempt + }; + let response = self.channel_finish(attempt).await?; + if response.pending || response.closure.is_some() { + return Ok(response); + } + self.channel_inspect(&funding).await + } + async fn channel_finish(&self, attempt: Attempt) -> Result { + let mut attempt = self.mpp_resume(attempt).await?; + if attempt.tx.status != "finalized" { + return pending(&attempt); + } + let funding = attempt + .funding + .clone() + .context("missing channel descriptor")?; + if attempt.kind == "request_close" { + let receipt = chain::finalized_receipt(&self.rpc, &attempt.tx.hash) + .await? + .context("finalized close request disappeared")?; + chain::verify_close_requested(&funding, &receipt)?; + } else if attempt.closure.is_none() { + let receipt = chain::finalized_receipt(&self.rpc, &attempt.tx.hash) + .await? + .context("finalized close disappeared")?; + let closure = chain::verify_close(&funding, &receipt)?; + ensure!( + attempt.kind != "close" || closure.captured == attempt.amount, + "unexpected captured amount" + ); + attempt.closure = Some(closure); + self.journal.save(&attempt, false)?; + } + Ok(Response { + closure: attempt.closure, + ..Default::default() + }) + } + /// Signs one reserve call that debits `amount` plus its fee. + async fn reserve_transaction( + &self, + data: Vec, + lifetime: u64, + amount: u64, + max_fee: u64, + ) -> Result { + self.prepare_transaction( + vec![call(address(RESERVE)?, data)], + now() + lifetime, + amount, + max_fee, + 2_000_000, + ) + .await + } + /// The journal slot for `base`: its unresolved or finalized attempt, or + /// the next retry after expired or reverted ones, and after finalized + /// ones too when `skip_finalized`. + fn attempt_slot( + &self, + base: &str, + skip_finalized: bool, + same: impl Fn(&Attempt) -> bool, + ) -> Result<(String, Option)> { + let maximum = self.settings.max_settlement_attempts; + ensure!( + (1..=10).contains(&maximum), + "max_settlement_attempts must be between 1 and 10" + ); + // Only failed attempts count toward the limit; skipped finalized ones succeeded. + let mut failed = 0; + for number in 1u32.. { + let id = if number == 1 { + base.to_owned() + } else { + format!("{base}/{number}") + }; + let Some(old) = self.journal.get::(&id)? else { + return Ok((id, None)); + }; + ensure!(same(&old), "payment retry intent changed"); + if skip_finalized && old.tx.status == "finalized" { + continue; + } + if matches!(old.tx.status.as_str(), "expired" | "reverted") { + failed += 1; + ensure!( + failed < maximum, + "payment {} retry limit reached; operator attention required", + old.kind + ); + continue; + } + return Ok((id, Some(old))); + } + unreachable!() + } + pub(super) async fn mpp_resume(&self, mut attempt: Attempt) -> Result { + self.check_terms(&attempt.terms)?; + if attempt.tx.status != "pending" { + return Ok(attempt); + } + attempt.tx.status = self + .resume_transaction( + &attempt.tx.hash, + &attempt.tx.raw, + attempt.tx.expires_at, + attempt.tx.nonce, + ) + .await?; + self.journal.save(&attempt, false)?; + Ok(attempt) + } +} +fn pending(attempt: &Attempt) -> Result { + ensure!( + attempt.tx.status == "pending", + "native reserve transaction {}; reconcile the outstanding channel", + attempt.tx.status + ); + Ok(Response { + pending: true, + ..Default::default() + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Payment state in its own directory, so the wallet directory stays empty. + fn database() -> (tempfile::TempDir, crate::ledger::Database) { + let state = tempfile::tempdir().unwrap(); + let db = crate::ledger::Ledger::open(state.path()) + .unwrap() + .db + .clone(); + (state, db) + } + + #[test] + fn settlement_attempt_limits_are_explicit_and_bounded() { + assert_eq!(Settings::default().max_settlement_attempts, 3); + for maximum in [0, 11] { + let dir = tempfile::tempdir().unwrap(); + let (_state, db) = database(); + let result = Wallet::load( + Settings { + max_settlement_attempts: maximum, + ..Default::default() + }, + dir.path(), + db, + ); + assert!( + result + .err() + .unwrap() + .to_string() + .contains("max_settlement_attempts") + ); + assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none()); + } + } + + #[test] + fn startup_never_creates_a_wallet_implicitly() { + let dir = tempfile::tempdir().unwrap(); + let (_state, db) = database(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + } + assert!(Wallet::load(Settings::default(), dir.path(), db,).is_err()); + assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none()); + } +} diff --git a/src/wallet.rs b/src/wallet.rs new file mode 100644 index 0000000..c14c7fe --- /dev/null +++ b/src/wallet.rs @@ -0,0 +1,182 @@ +use crate::contract::{ + Balance, WalletInfo, + mpp::{CloseEvents, Request, Response}, +}; +use anyhow::Result; +use std::{future::Future, pin::Pin}; + +pub(crate) type OpenedWallet = (std::sync::Arc, WalletInfo); + +pub(crate) type WalletFuture<'a, T> = Pin> + Send + 'a>>; + +pub(crate) trait Backend: Send + Sync { + fn execute(&self, request: Request) -> WalletFuture<'_, Response>; + fn balance(&self) -> WalletFuture<'_, Balance>; + fn attempts(&self) -> Result>; + fn bond<'a>( + &'a self, + _settings: &'a crate::bonds::Settings, + _id: &'a str, + _intent: crate::bonds::Intent, + ) -> WalletFuture<'a, serde_json::Value> { + Box::pin(async { anyhow::bail!("bond transactions unavailable on this backend") }) + } + /// A journaled OUSD transfer of `amount` to `to`, once per operation ID. + fn send<'a>( + &'a self, + _operation_id: &'a str, + _to: &'a str, + _amount: u64, + _max_fee: u64, + ) -> WalletFuture<'a, serde_json::Value> { + Box::pin(async { anyhow::bail!("wallet sends unavailable on this backend") }) + } + fn reconcile(&self) -> WalletFuture<'_, ()> { + Box::pin(async { Ok(()) }) + } + /// The funding address and network, after creating the wallet when it + /// has none; `None` when the engine's wallet info already answers. + fn fund(&self) -> WalletFuture<'_, Option> { + Box::pin(async { Ok(None) }) + } + /// The seller's channels named in close events since block `from`; a + /// backend without event logs reports every scan skipped, so the caller + /// inspects every channel. + fn close_events(&self, _from: Option) -> WalletFuture<'_, CloseEvents> { + Box::pin(async { + Ok(CloseEvents { + skipped: true, + ..Default::default() + }) + }) + } +} + +const NO_WALLET: &str = "this node has no wallet yet; `fund` creates one"; + +/// The backend of a node started without a wallet. It verifies bonds and +/// serves free inference, and creates the wallet when the operator first +/// runs `fund` or `bond_lock`; payments need a restart after that. +pub(crate) struct Unopened { + settings: crate::tempo::Settings, + dir: std::path::PathBuf, + db: crate::ledger::Database, + wallet: tokio::sync::OnceCell>, +} +impl Unopened { + pub(crate) fn new( + settings: crate::tempo::Settings, + dir: &std::path::Path, + db: crate::ledger::Database, + ) -> Self { + Self { + settings, + dir: dir.into(), + db, + wallet: Default::default(), + } + } + /// The wallet, created on the first call. + pub(crate) async fn open(&self) -> Result<&std::sync::Arc> { + self.wallet + .get_or_try_init(|| async { + crate::tempo::Wallet::create(self.settings.clone(), &self.dir, self.db.clone()) + }) + .await + } +} +impl Backend for Unopened { + fn execute(&self, request: Request) -> WalletFuture<'_, Response> { + Box::pin(async move { + match self.wallet.get() { + Some(wallet) => wallet.mpp(request).await, + None => anyhow::bail!(NO_WALLET), + } + }) + } + fn balance(&self) -> WalletFuture<'_, Balance> { + Box::pin(async move { + match self.wallet.get() { + Some(wallet) => wallet.balance().await, + None => anyhow::bail!(NO_WALLET), + } + }) + } + fn attempts(&self) -> Result> { + self.wallet + .get() + .map_or(Ok(Vec::new()), |wallet| wallet.journal.public()) + } + fn bond<'a>( + &'a self, + settings: &'a crate::bonds::Settings, + id: &'a str, + intent: crate::bonds::Intent, + ) -> WalletFuture<'a, serde_json::Value> { + Box::pin(async move { self.open().await?.bond(settings, id, intent).await }) + } + fn send<'a>( + &'a self, + operation_id: &'a str, + to: &'a str, + amount: u64, + max_fee: u64, + ) -> WalletFuture<'a, serde_json::Value> { + Box::pin(async move { + match self.wallet.get() { + Some(wallet) => wallet.send(operation_id, to, amount, max_fee).await, + None => anyhow::bail!(NO_WALLET), + } + }) + } + fn reconcile(&self) -> WalletFuture<'_, ()> { + Box::pin(async move { + match self.wallet.get() { + Some(wallet) => wallet.reconcile().await, + None => Ok(()), + } + }) + } + fn fund(&self) -> WalletFuture<'_, Option> { + Box::pin(async move { Ok(Some(self.open().await?.fund().await?)) }) + } +} + +impl Backend for crate::tempo::Wallet { + fn send<'a>( + &'a self, + operation_id: &'a str, + to: &'a str, + amount: u64, + max_fee: u64, + ) -> WalletFuture<'a, serde_json::Value> { + Box::pin(self.send(operation_id, to, amount, max_fee)) + } + fn bond<'a>( + &'a self, + settings: &'a crate::bonds::Settings, + id: &'a str, + intent: crate::bonds::Intent, + ) -> WalletFuture<'a, serde_json::Value> { + Box::pin(self.bond(settings, id, intent)) + } + fn reconcile(&self) -> WalletFuture<'_, ()> { + Box::pin(self.reconcile()) + } + fn close_events(&self, from: Option) -> WalletFuture<'_, CloseEvents> { + Box::pin(self.close_events(from)) + } + fn fund(&self) -> WalletFuture<'_, Option> { + Box::pin(async move { Ok(Some(self.fund().await?)) }) + } + + fn execute(&self, request: Request) -> WalletFuture<'_, Response> { + Box::pin(self.mpp(request)) + } + fn balance(&self) -> WalletFuture<'_, Balance> { + Box::pin(self.balance()) + } + fn attempts(&self) -> Result> { + self.journal.public() + } +} diff --git a/tests/plugin_process.rs b/tests/plugin_process.rs new file mode 100644 index 0000000..7577c3e --- /dev/null +++ b/tests/plugin_process.rs @@ -0,0 +1,496 @@ +#![cfg(all(unix, feature = "offline-fixture"))] + +use mesh_llm_plugin::{LocalStream, PROTOCOL_VERSION, proto, read_envelope, write_envelope}; +use proto::envelope::Payload; +use serde_json::{Value, json}; +use std::{path::Path, process::Stdio, time::Duration}; +use tokio::{ + net::UnixListener, + process::{Child, Command}, + time::timeout, +}; + +async fn send(stream: &mut LocalStream, id: u64, payload: Payload) { + write_envelope( + stream, + &proto::Envelope { + protocol_version: PROTOCOL_VERSION, + plugin_id: "tempo".into(), + request_id: id, + payload: Some(payload), + }, + ) + .await + .unwrap(); +} +async fn receive(stream: &mut LocalStream) -> proto::Envelope { + timeout(Duration::from_secs(10), read_envelope(stream)) + .await + .unwrap() + .unwrap() +} +async fn launch(binary: &str, root: &Path) -> (Child, LocalStream) { + let socket = root.join("host.sock"); + let _ = std::fs::remove_file(&socket); + let listener = UnixListener::bind(&socket).unwrap(); + let child = Command::new(binary) + .env("MESH_LLM_PLUGIN_NAME", "tempo") + .env("MESH_LLM_PLUGIN_ENDPOINT", &socket) + .env("MESH_LLM_PLUGIN_TRANSPORT", "unix") + .env("MESH_LLM_OFFLINE_CHAIN_PATH", root.join("chain.sqlite")) + .env("MESH_LLM_OFFLINE_ADDRESS", format!("0x{}", "11".repeat(20))) + .env_remove("TEMPO_FIXTURE_NO_VERIFIER") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let (stream, _) = timeout(Duration::from_secs(10), listener.accept()) + .await + .unwrap() + .unwrap(); + (child, LocalStream::Unix(stream)) +} +async fn initialize(stream: &mut LocalStream, root: &Path) { + initialize_config(stream, root, json!({}), true).await; +} +async fn initialize_config( + stream: &mut LocalStream, + root: &Path, + extra: Value, + expect_publication: bool, +) { + let config = root.join("payments.json"); + let mut settings = json!({"data_dir":root.join("payments")}); + settings + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + std::fs::write(&config, serde_json::to_vec(&settings).unwrap()).unwrap(); + send( + stream, + 1, + Payload::InitializeRequest(proto::InitializeRequest { + host_protocol_version: PROTOCOL_VERSION, + host_version: "test".into(), + host_info_json: "{}".into(), + mesh_visibility: proto::MeshVisibility::Private.into(), + host_capabilities: vec![ + mesh_llm_plugin::peer_evidence::HOST_CAPABILITY.into(), + mesh_llm_plugin::host_capabilities::OPENAI_EXCHANGE.into(), + mesh_llm_plugin::host_capabilities::MODEL_REQUIREMENTS.into(), + ], + settings_json: json!({"config_path":config}).to_string(), + }), + ) + .await; + let response = receive(stream).await; + let Some(Payload::InitializeResponse(initialized)) = response.payload else { + panic!("initialization failed") + }; + let manifest = initialized.manifest.unwrap(); + assert_eq!( + manifest + .operations + .iter() + .map(|op| op.name.as_str()) + .collect::>(), + ["control", "verify_peer_evidence"] + ); + let verifier = manifest + .peer_evidence_verifier + .as_ref() + .expect("provider verifier declaration missing"); + assert_eq!(verifier.contract_version, 1); + assert_eq!(verifier.namespace, "tempo.bond.v1"); + assert_eq!(verifier.handler, "verify_peer_evidence"); + assert!( + manifest + .grant_requests + .is_none_or(|g| g.operation_bindings.is_empty()) + ); + assert!( + manifest + .mesh_event_subscriptions + .iter() + .any(|subscription| subscription.kind == proto::mesh_event::Kind::MeshIdUpdated as i32) + ); + assert!(initialized.capabilities.is_empty()); + send( + stream, + 0, + Payload::MeshEvent(proto::MeshEvent { + kind: proto::mesh_event::Kind::MeshIdUpdated as i32, + local_peer_id: "aa".repeat(32), + mesh_id: "fixture".into(), + ..Default::default() + }), + ) + .await; + let request = receive(stream).await; + let Some(Payload::RpcRequest(rpc)) = request.payload else { + panic!("expected identity request") + }; + assert_eq!(rpc.method, "ReadIdentityBundle"); + send( + stream, + request.request_id, + Payload::RpcResponse(proto::RpcResponse { + result_json: json!({"node_endpoint_id":"aa".repeat(32)}).to_string(), + }), + ) + .await; + if expect_publication { + let request = receive(stream).await; + assert!( + matches!(&request.payload,Some(Payload::RpcRequest(rpc)) if rpc.method=="PublishPeerEvidence") + ); + send( + stream, + request.request_id, + Payload::RpcResponse(proto::RpcResponse { + result_json: json!({"published":false}).to_string(), + }), + ) + .await; + } +} + +#[tokio::test] +async fn evidence_that_is_no_bond_reference_is_rejected_without_chain_calls() { + let root = tempfile::Builder::new() + .prefix("tempo-unreadable-proof-") + .tempdir_in("/tmp") + .unwrap(); + let (mut child, mut stream) = launch(env!("CARGO_BIN_EXE_tempo-fixture"), root.path()).await; + initialize_config(&mut stream, root.path(), json!({}), true).await; + send(&mut stream, 20, Payload::RpcRequest(proto::RpcRequest { + method:"tools/call".into(), + params_json:json!({"name":"verify_peer_evidence","arguments":{"mesh_id":"fixture","node_id":"bb".repeat(32),"evidence":{}}}).to_string(), + invocation_id:None, + })).await; + let response = receive(&mut stream).await; + let Some(Payload::RpcResponse(response)) = response.payload else { + panic!("verification failed") + }; + let value: Value = serde_json::from_str(&response.result_json).unwrap(); + assert_eq!(value["structuredContent"]["accepted"], false); + assert!(value["structuredContent"]["reason"].is_string()); + assert!(value["structuredContent"]["valid_until"].as_u64().is_some()); + child.kill().await.unwrap(); +} + +#[tokio::test] +async fn prices_publications_and_requirements_are_independent_at_startup() { + let contract = "0x1111111111111111111111111111111111111111"; + for (priced, published, required) in [ + (false, false, false), + (true, false, false), + (false, true, false), + (true, true, false), + (false, false, true), + (true, true, true), + ] { + let root = tempfile::Builder::new() + .prefix("tempo-policy-") + .tempdir_in("/tmp") + .unwrap(); + let (mut child, mut stream) = + launch(env!("CARGO_BIN_EXE_tempo-fixture"), root.path()).await; + let mut settings = json!({}); + if priced { + settings["prices"] = + json!({"model":{"input_per_million":"1","output_per_million":"1"}}); + } + if published || required { + settings["bonds"] = json!({"contract":contract}); + } + // Without a stated requirement the standard bond applies. + if required { + settings["bonds"]["providers"] = json!({"minimum_amount":"1"}); + } + initialize_config(&mut stream, root.path(), settings, true).await; + if priced { + let requirements = receive(&mut stream).await; + assert!( + matches!(requirements.payload, Some(Payload::ModelRequirementRequest(request)) if request.model=="model" && request.requires.len()==1) + ); + send( + &mut stream, + requirements.request_id, + Payload::ModelRequirementResponse(proto::ModelRequirementResponse {}), + ) + .await; + } + if published { + publish(&mut stream, 9, &"aa".repeat(32)).await; + } + let policy = control(&mut stream, 10, json!({"command":"policy"})).await; + assert_eq!(policy["mode"], "free_only"); + let bonds = control(&mut stream, 11, json!({"command":"bond_context"})).await; + assert_eq!(bonds["reference"].is_object(), published); + let minimum = if required { "1" } else { "1000000" }; + assert_eq!(bonds["requirement"]["minimum_amount"], minimum); + let pending = control(&mut stream, 12, json!({"command":"pending"})).await; + assert!(pending["requests"].as_array().unwrap().is_empty()); + child.kill().await.unwrap(); + } +} + +/// Publishes `bond_id` through the `bond_publish` control, answering the +/// plugin's publication request as the host. +async fn publish(stream: &mut LocalStream, id: u64, bond_id: &str) { + let arguments = json!({"command":"bond_publish","bond_id":bond_id}); + send( + stream, + id, + Payload::RpcRequest(proto::RpcRequest { + method: "tools/call".into(), + params_json: json!({"name":"control","arguments":arguments}).to_string(), + invocation_id: None, + }), + ) + .await; + let request = receive(stream).await; + let Some(Payload::RpcRequest(rpc)) = &request.payload else { + panic!("expected a publication request") + }; + assert_eq!(rpc.method, "PublishPeerEvidence"); + let params: Value = serde_json::from_str(&rpc.params_json).unwrap(); + assert_eq!(params["evidence"]["bond_id"], bond_id); + send( + stream, + request.request_id, + Payload::RpcResponse(proto::RpcResponse { + result_json: json!({"published":true}).to_string(), + }), + ) + .await; + let response = receive(stream).await; + assert_eq!(response.request_id, id); + assert!(matches!(response.payload, Some(Payload::RpcResponse(_)))); +} +/// The error text of one refused `control` command. +async fn control_error(stream: &mut LocalStream, id: u64, arguments: Value) -> String { + send( + stream, + id, + Payload::RpcRequest(proto::RpcRequest { + method: "tools/call".into(), + params_json: json!({"name":"control","arguments":arguments}).to_string(), + invocation_id: None, + }), + ) + .await; + let response = receive(stream).await; + assert_eq!(response.request_id, id); + match response.payload { + Some(Payload::RpcResponse(response)) => response.result_json, + Some(Payload::ErrorResponse(error)) => error.message, + other => panic!("unexpected control answer: {other:?}"), + } +} +/// The structured result of one successful `control` command. +async fn control(stream: &mut LocalStream, id: u64, arguments: Value) -> Value { + send( + stream, + id, + Payload::RpcRequest(proto::RpcRequest { + method: "tools/call".into(), + params_json: json!({"name":"control","arguments":arguments}).to_string(), + invocation_id: None, + }), + ) + .await; + let response = receive(stream).await; + assert_eq!(response.request_id, id); + let Some(Payload::RpcResponse(response)) = response.payload else { + panic!("control failed") + }; + let mut value: Value = serde_json::from_str(&response.result_json).unwrap(); + assert_ne!(value["isError"], true, "{value}"); + value["structuredContent"].take() +} + +async fn expect_local_bond_context(stream: &mut LocalStream, expected_mesh: Option<&str>) { + timeout(Duration::from_secs(3), async { + loop { + send( + stream, + 12, + Payload::RpcRequest(proto::RpcRequest { + method: "tools/call".into(), + params_json: json!({"name":"control","arguments":{"command":"bond_context"}}) + .to_string(), + invocation_id: None, + }), + ) + .await; + let response = receive(stream).await; + let Some(Payload::RpcResponse(response)) = response.payload else { + panic!("bond context must not perform a host lookup"); + }; + let value: Value = serde_json::from_str(&response.result_json).unwrap(); + let context = &value["structuredContent"]; + assert_eq!(context["node_id"], "aa".repeat(32)); + assert_eq!(context["namespace"], "tempo.bond.v1"); + if context["mesh_id"].as_str() == expected_mesh { + return; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn bond_context_tracks_snapshots_and_mesh_changes_without_host_lookups() { + let root = tempfile::Builder::new() + .prefix("tempo-mesh-context-") + .tempdir_in("/tmp") + .unwrap(); + let (mut child, mut stream) = launch(env!("CARGO_BIN_EXE_tempo-fixture"), root.path()).await; + initialize(&mut stream, root.path()).await; + expect_local_bond_context(&mut stream, Some("fixture")).await; + send(&mut stream, 40, Payload::RpcRequest(proto::RpcRequest { + method: "tools/call".into(), + params_json: json!({"name":"control","arguments":{"command":"bond_lock","operation_id":uuid::Uuid::new_v4().to_string(),"mesh_id":"unintended-mesh","amount":"1","exit_delay_seconds":86400,"salt":"00".repeat(32)}}).to_string(), + invocation_id: None, + })).await; + let response = receive(&mut stream).await; + assert!(format!("{response:?}").contains("intended mesh differs")); + for mesh in ["changed-mesh", ""] { + send( + &mut stream, + 0, + Payload::MeshEvent(proto::MeshEvent { + kind: proto::mesh_event::Kind::MeshIdUpdated as i32, + local_peer_id: "aa".repeat(32), + mesh_id: mesh.into(), + ..Default::default() + }), + ) + .await; + expect_local_bond_context(&mut stream, (!mesh.is_empty()).then_some(mesh)).await; + } + child.kill().await.unwrap(); +} + +#[tokio::test] +async fn combined_plugin_starts_inspects_and_restarts_without_a_wallet_provider() { + let root = tempfile::Builder::new() + .prefix("pay-ipc-") + .tempdir_in("/tmp") + .unwrap(); + for _ in 0..2 { + let (mut child, mut stream) = + launch(env!("CARGO_BIN_EXE_tempo-fixture"), root.path()).await; + initialize(&mut stream, root.path()).await; + let fund = control(&mut stream, 2, json!({"command":"fund"})).await; + assert_eq!(fund["address"], format!("0x{}", "11".repeat(20))); + assert_eq!(fund["network"], "testnet"); + let balance = control(&mut stream, 3, json!({"command":"balance"})).await; + assert_eq!(balance["balance"], "1000000000"); + let pending = control(&mut stream, 4, json!({"command":"pending"})).await; + assert_eq!(pending["requests"], json!([])); + assert_eq!(pending["attempts"], json!([])); + let history = json!({"command":"transactions","limit":10}); + let transactions = control(&mut stream, 6, history).await; + assert_eq!(transactions["channels"], json!([])); + assert_eq!(transactions["attempts"], json!([])); + send( + &mut stream, + 5, + Payload::ShutdownRequest(proto::ShutdownRequest { + reason: "test complete".into(), + }), + ) + .await; + assert!(matches!( + receive(&mut stream).await.payload, + Some(Payload::ShutdownResponse(_)) + )); + assert!( + timeout(Duration::from_secs(10), child.wait()) + .await + .unwrap() + .unwrap() + .success() + ); + } + assert!(!root.path().join("wallet/wallet.json").exists()); +} + +#[tokio::test] +async fn production_entry_point_cannot_select_the_fake_wallet_from_environment() { + let root = tempfile::Builder::new() + .prefix("pay-native-") + .tempdir_in("/tmp") + .unwrap(); + // Without a wallet the node starts to verify bonds, and refuses payments. + let (mut child, mut stream) = launch(env!("CARGO_BIN_EXE_tempo"), root.path()).await; + initialize_config(&mut stream, root.path(), json!({}), true).await; + // `fund` would create a wallet and call the faucet, so the test reads + // the balance, which needs a wallet without creating one. + let balance = control_error(&mut stream, 10, json!({"command":"balance"})).await; + assert!(balance.contains("no wallet yet"), "{balance}"); + assert!(!root.path().join("payments/wallet.json").exists()); + let automatic = json!({"command":"policy","value":{"mode":"automatic","daily_budget":"10"}}); + let policy = control_error(&mut stream, 11, automatic).await; + assert!(policy.contains("need a wallet"), "{policy}"); + child.kill().await.unwrap(); + // A priced model needs a wallet, so the node does not start. + let (mut child, mut stream) = launch(env!("CARGO_BIN_EXE_tempo"), root.path()).await; + let priced = json!({"prices":{"model":{"input_per_million":"1","output_per_million":"1"}}}); + initialize_config(&mut stream, root.path(), priced, false).await; + assert!( + !timeout(Duration::from_secs(10), child.wait()) + .await + .unwrap() + .unwrap() + .success() + ); + assert!(!root.path().join("chain.sqlite").exists()); + assert!(!root.path().join("wallet/wallet.json").exists()); +} + +#[tokio::test] +async fn tempo_requires_the_evidence_capability_before_opening_a_wallet() { + let root = tempfile::Builder::new() + .prefix("tempo-old-host-") + .tempdir_in("/tmp") + .unwrap(); + let (_child, mut stream) = launch(env!("CARGO_BIN_EXE_tempo-fixture"), root.path()).await; + let config = root.path().join("payments.json"); + let settings = json!({ + "data_dir": root.path().join("payments"), + "bonds": { + "contract": "0x1111111111111111111111111111111111111111", + "providers": {"minimum_amount": "1"} + } + }); + std::fs::write(&config, serde_json::to_vec(&settings).unwrap()).unwrap(); + let host_capabilities = vec![mesh_llm_plugin::host_capabilities::OPENAI_EXCHANGE.into()]; + send( + &mut stream, + 1, + Payload::InitializeRequest(proto::InitializeRequest { + host_protocol_version: PROTOCOL_VERSION, + host_version: "old-host".into(), + host_info_json: "{}".into(), + mesh_visibility: proto::MeshVisibility::Private.into(), + host_capabilities, + settings_json: json!({"config_path":config}).to_string(), + }), + ) + .await; + let response = receive(&mut stream).await; + assert!( + matches!(&response.payload, Some(Payload::ErrorResponse(error)) if error.message.contains(mesh_llm_plugin::peer_evidence::HOST_CAPABILITY)), + "{response:?}" + ); + assert!(!root.path().join("chain.sqlite").exists()); + assert!(!root.path().join("payments").exists()); +}