diff --git a/README.md b/README.md index 5354045a..dc0debd4 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ The examples in this repository: - **modular_account**: A custom account contract that uses CAP-71 auth delegation to forward `__check_auth` to registered delegate signers - **other_custom_types**: The smart contract implements types, including custom types - **privacy-pools**: A prototype for Privacy Pools for Soroban. +- **receipt-anchor**: Commits to a contract invocation (target, function, args, result, ledger) so its result can be verified later from public data alone - **simple_account**: A minimal example of an account contract, owned by a single ed25519 public key - **single_offer**: This contract implements trading of one token pair between one seller and multiple buyers - **time_lock**: This contract demonstrates how to write a timelock and implements a greatly simplified claimable balance diff --git a/receipt-anchor/Cargo.toml b/receipt-anchor/Cargo.toml new file mode 100644 index 00000000..7f6904f3 --- /dev/null +++ b/receipt-anchor/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "soroban-receipt-anchor-contract" +version = "0.0.0" +edition = "2021" +publish = false +rust-version = "1.92.0" + +[lib] +crate-type = ["cdylib"] +doctest = false + +[dependencies] +soroban-sdk = { version = "28.0.0" } + +[dev-dependencies] +soroban-sdk = { version = "28.0.0", features = ["testutils"] } + +[profile.release] +opt-level = "z" +overflow-checks = true +debug = 0 +strip = "symbols" +debug-assertions = false +panic = "abort" +codegen-units = 1 +lto = true + +[profile.release-with-logs] +inherits = "release" +debug-assertions = true diff --git a/receipt-anchor/Makefile b/receipt-anchor/Makefile new file mode 100644 index 00000000..b9719346 --- /dev/null +++ b/receipt-anchor/Makefile @@ -0,0 +1,16 @@ +default: build + +all: test + +test: build + cargo test + +build: + stellar contract build + @ls -l target/wasm32v1-none/release/*.wasm + +fmt: + cargo fmt --all + +clean: + cargo clean diff --git a/receipt-anchor/README.md b/receipt-anchor/README.md new file mode 100644 index 00000000..c4cc09c2 --- /dev/null +++ b/receipt-anchor/README.md @@ -0,0 +1,101 @@ +# Receipt anchor + +A minimal example of committing to a contract invocation so that a third party +can later confirm — from public data alone — that a specific invocation +produced a specific result. + +## What it does + +`anchor` hashes a fixed tuple of invocation facts and stores the resulting +receipt under the caller's address: + +```text +commitment = sha256( "receipt-anchor/1" + ++ xdr(target) + ++ xdr(fn_name) + ++ sha256(xdr(args)) + ++ sha256(xdr(result)) + ++ xdr(ledger) ) +``` + +| function | what it is for | +| --- | --- | +| `anchor(caller, target, fn_name, args, result, ledger)` | require the caller's authorization, compute the commitment, store the receipt, return the commitment | +| `commitment(target, fn_name, args, result, ledger)` | recompute the same 32 bytes without writing anything | +| `verify(receipt, args, result)` | recompute and compare against a stored receipt | +| `receipt(caller, index)` / `count(caller)` | read a caller's receipts in anchoring order | + +The span of the commit is the invocation itself: the contract, the function, +the arguments, the result, and the ledger. Change any one of them and the +commitment changes. + +## What it does not do + +- It does not decide whether a call **should** happen. There is no policy, no + allowlist, no deadline check, no size limit. Those belong to whoever is + authorizing the call, not to the layer recording that it happened. +- It does not move funds, hold keys, or grant authority. +- It says nothing about whether the invocation was *correct*, only that these + are the facts of the invocation that was anchored. + +## Layout + +```text +src/lib.rs the contract +src/test.rs the tests +Cargo.toml soroban-sdk 28, matching this repository's other examples +``` + +## Run + +```sh +make test # cargo test +make build # stellar contract build +``` + +`make build` needs `stellar-cli` 25.2.0 or newer: soroban-sdk 28 refuses to build +for `wasm32-unknown-unknown`, and the CLI builds for `wasm32v1-none` and puts the +contract at `target/wasm32v1-none/release/soroban_receipt_anchor_contract.wasm`. + +Verified: `cargo test` reports 9 passed, and the release build exports the five +entry points (`anchor`, `commitment`, `verify`, `count`, `receipt`). + +## Verifying a receipt off-chain + +A verifier that has the receipt does not need to call the contract: + +1. Take `target`, `fn_name`, `args`, `result` and `ledger` from the invocation + being claimed. +2. Encode `target`, `fn_name` and `ledger` as XDR `ScVal`s, and take SHA-256 of + the XDR of `args` and of `result` separately. +3. Concatenate `"receipt-anchor/1"`, the three XDR encodings in the order above, + and the two 32-byte component hashes, then SHA-256 the result. +4. Compare with the receipt's `commitment`. + +Every component is either fixed-width or hash-fixed-width, so no two different +tuples can produce the same preimage by shifting a boundary. The stored +`args_hash` and `result_hash` are there so a verifier can report *which* +component disagreed instead of only that something did. + +## Tests + +Nine, and the tamper cases are the point: changing the args, the result, the +ledger, the target, or the function name each breaks verification on its own, +so a receipt that passes is not passing for an incidental reason. Two also +check the content-addressed property — the same invocation anchored by two +different callers produces the same commitment, and neither caller can occupy +the other's index. The last one calls `anchor` without mocking authorization +and expects it to fail, so the `require_auth` gate is tested rather than +assumed. + +## Limits + +- Storage entries are written to persistent storage without TTL management; + a production contract would `extend_ttl` on write and read. +- `anchor` is called by the party making the claim. It records that the caller + asserted these facts at this ledger, not that an independent observer + witnessed the invocation. Binding a receipt to a host-produced execution + result is a further step, and a larger one. +- The commitment covers the arguments as a whole list; it does not say which + argument matters to the caller. A policy that only cares about one field + would hash that field, not the list. diff --git a/receipt-anchor/src/lib.rs b/receipt-anchor/src/lib.rs new file mode 100644 index 00000000..67254d7a --- /dev/null +++ b/receipt-anchor/src/lib.rs @@ -0,0 +1,192 @@ +#![no_std] + +//! # Receipt anchor +//! +//! A small example of committing to a contract invocation, so that a third +//! party can later check — from public data alone — that a specific +//! invocation produced a specific result. +//! +//! The contract does one thing. On `anchor` it hashes a fixed tuple of +//! invocation facts: +//! +//! ```text +//! commitment = sha256( "receipt-anchor/1" +//! ++ xdr(target) // the contract that was called +//! ++ xdr(fn_name) // the function that was called +//! ++ sha256(xdr(args)) // the arguments, canonically encoded +//! ++ sha256(xdr(result)) // the result, canonically encoded +//! ++ xdr(ledger) ) // the ledger the invocation happened at +//! ``` +//! +//! and stores the receipt under the caller's address. `verify` recomputes the +//! same 32 bytes from the same inputs, so a mismatch is detectable without +//! trusting the caller, the contract, or this code. +//! +//! What this is not: a policy engine, an allowlist, a settlement surface, or a +//! token contract. It moves no funds and grants no authority — it pins a fact +//! about an invocation. Whether an invocation *should* happen is decided by +//! somebody else's policy; this is the layer that records what did happen. + +use soroban_sdk::{ + contract, contractimpl, contracttype, xdr::ToXdr, Address, Bytes, BytesN, Env, Symbol, Val, Vec, +}; + +/// Domain separator. These fixed bytes are the prefix of every commitment +/// preimage, so a hash produced here cannot be confused with a hash of the +/// same data computed for another purpose. +pub const DOMAIN: &[u8] = b"receipt-anchor/1"; + +/// A stored commitment to one invocation. +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Receipt { + pub target: Address, + pub fn_name: Symbol, + pub ledger: u32, + pub args_hash: BytesN<32>, + pub result_hash: BytesN<32>, + pub commitment: BytesN<32>, +} + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum DataKey { + /// One receipt, indexed per caller in the order it was anchored. + Receipt(Address, u32), + /// How many receipts a caller has anchored. + Count(Address), +} + +#[contract] +pub struct ReceiptAnchor; + +#[contractimpl] +impl ReceiptAnchor { + /// Anchor one invocation and return its commitment. + /// + /// Requires the caller's authorization: a receipt is a statement about + /// what the caller did, so the caller signs for it. That keeps a stranger + /// from writing into someone else's receipt list. + pub fn anchor( + env: Env, + caller: Address, + target: Address, + fn_name: Symbol, + args: Vec, + result: Val, + ledger: u32, + ) -> BytesN<32> { + caller.require_auth(); + + let args_hash = Self::hash_xdr(&env, args.clone()); + let result_hash = Self::hash_xdr(&env, result); + let commitment = Self::commit_parts( + &env, + target.clone(), + fn_name.clone(), + args_hash.clone(), + result_hash.clone(), + ledger, + ); + + let index = Self::count(env.clone(), caller.clone()); + env.storage().persistent().set( + &DataKey::Receipt(caller.clone(), index), + &Receipt { + target, + fn_name, + ledger, + args_hash, + result_hash, + commitment: commitment.clone(), + }, + ); + env.storage() + .persistent() + .set(&DataKey::Count(caller), &(index + 1)); + + commitment + } + + /// Recompute the commitment for one invocation. + /// + /// Pure: the same inputs produce the same 32 bytes on any machine, so an + /// off-chain verifier can derive the expected value itself instead of + /// trusting a call to this contract. + pub fn commitment( + env: Env, + target: Address, + fn_name: Symbol, + args: Vec, + result: Val, + ledger: u32, + ) -> BytesN<32> { + let args_hash = Self::hash_xdr(&env, args); + let result_hash = Self::hash_xdr(&env, result); + Self::commit_parts(&env, target, fn_name, args_hash, result_hash, ledger) + } + + /// Check a stored receipt against the invocation it claims to describe. + /// + /// Returns `false` on every mismatch: a different argument, a different + /// result, a different ledger, a different target or function name. There + /// is no partial credit and no error to ignore. + pub fn verify(env: Env, receipt: Receipt, args: Vec, result: Val) -> bool { + let expected = Self::commitment( + env, + receipt.target.clone(), + receipt.fn_name.clone(), + args, + result, + receipt.ledger, + ); + expected == receipt.commitment + } + + /// How many receipts an address has anchored. + pub fn count(env: Env, caller: Address) -> u32 { + env.storage() + .persistent() + .get(&DataKey::Count(caller)) + .unwrap_or(0) + } + + /// Read one of a caller's receipts, in the order it was anchored. + pub fn receipt(env: Env, caller: Address, index: u32) -> Option { + env.storage() + .persistent() + .get(&DataKey::Receipt(caller, index)) + } + + /// The commitment preimage, given the two component hashes. + /// + /// Split out so `anchor` hashes each component exactly once while still + /// producing the same value `commitment` produces. + fn commit_parts( + env: &Env, + target: Address, + fn_name: Symbol, + args_hash: BytesN<32>, + result_hash: BytesN<32>, + ledger: u32, + ) -> BytesN<32> { + let mut preimage = Bytes::from_slice(env, DOMAIN); + preimage.append(&target.to_xdr(env)); + preimage.append(&fn_name.to_xdr(env)); + // Fixed-width 32-byte components, so no two different tuples can + // concatenate to the same preimage by shifting a boundary. + preimage.append(&Bytes::from_array(env, &args_hash.to_array())); + preimage.append(&Bytes::from_array(env, &result_hash.to_array())); + preimage.append(&ledger.to_xdr(env)); + + env.crypto().sha256(&preimage).into() + } + + /// SHA-256 of a value's canonical XDR encoding. + fn hash_xdr(env: &Env, value: impl ToXdr) -> BytesN<32> { + let xdr = value.to_xdr(env); + env.crypto().sha256(&xdr).into() + } +} + +mod test; diff --git a/receipt-anchor/src/test.rs b/receipt-anchor/src/test.rs new file mode 100644 index 00000000..47c04a74 --- /dev/null +++ b/receipt-anchor/src/test.rs @@ -0,0 +1,248 @@ +#![cfg(test)] +use crate::{Receipt, ReceiptAnchor, ReceiptAnchorClient}; +use soroban_sdk::{symbol_short, testutils::Address as _, Address, Env, IntoVal, Val, Vec}; + +fn setup(env: &Env) -> (ReceiptAnchorClient<'_>, Address, Address) { + env.mock_all_auths(); + let contract_id = env.register(ReceiptAnchor, ()); + let client = ReceiptAnchorClient::new(env, &contract_id); + let caller = Address::generate(env); + let target = Address::generate(env); + (client, caller, target) +} + +fn call_args(env: &Env, amount: u32, deadline: u32) -> Vec { + let mut args = Vec::new(env); + args.push_back(amount.into_val(env)); + args.push_back(deadline.into_val(env)); + args +} + +fn result_val(env: &Env, value: u32) -> Val { + value.into_val(env) +} + +#[test] +fn anchor_stores_the_commitment_under_the_caller() { + let env = Env::default(); + let (client, caller, target) = setup(&env); + let args = call_args(&env, 100, 42); + let result = result_val(&env, 7); + + let commitment = client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &args, + &result, + &99, + ); + + assert_eq!(client.count(&caller), 1); + let stored = client.receipt(&caller, &0u32).unwrap(); + assert_eq!(stored.commitment, commitment); + assert_eq!(stored.ledger, 99); + assert_eq!( + stored.commitment, + client.commitment(&target, &symbol_short!("swap"), &args, &result, &99) + ); +} + +#[test] +fn verify_accepts_the_invocation_it_was_anchored_for() { + let env = Env::default(); + let (client, caller, target) = setup(&env); + let args = call_args(&env, 100, 42); + let result = result_val(&env, 7); + + client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &args, + &result, + &99, + ); + let stored = client.receipt(&caller, &0u32).unwrap(); + + assert!(client.verify(&stored, &args, &result)); +} + +#[test] +fn verify_rejects_a_different_result() { + let env = Env::default(); + let (client, caller, target) = setup(&env); + let args = call_args(&env, 100, 42); + + client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &args, + &result_val(&env, 7), + &99, + ); + let stored = client.receipt(&caller, &0u32).unwrap(); + + // Same caller's record, one unit of result changed. + assert!(!client.verify(&stored, &args, &result_val(&env, 8))); +} + +#[test] +fn verify_rejects_different_args() { + let env = Env::default(); + let (client, caller, target) = setup(&env); + let args = call_args(&env, 100, 42); + + client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &args, + &result_val(&env, 7), + &99, + ); + let stored = client.receipt(&caller, &0u32).unwrap(); + + assert!(!client.verify(&stored, &call_args(&env, 101, 42), &result_val(&env, 7))); + // Argument order is part of the commitment, not just the argument set. + assert!(!client.verify(&stored, &call_args(&env, 42, 100), &result_val(&env, 7))); + // A shorter argument list is not a prefix match. + let mut shorter = Vec::new(&env); + shorter.push_back(100u32.into_val(&env)); + assert!(!client.verify(&stored, &shorter, &result_val(&env, 7))); +} + +#[test] +fn verify_rejects_a_different_ledger() { + let env = Env::default(); + let (client, caller, target) = setup(&env); + let args = call_args(&env, 100, 42); + let result = result_val(&env, 7); + + client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &args, + &result, + &99, + ); + let stored = client.receipt(&caller, &0u32).unwrap(); + + // A receipt that claims a different ledger no longer describes this + // invocation, even though every other field is untouched. + let restamped = Receipt { + ledger: 100, + ..stored.clone() + }; + assert!(!client.verify(&restamped, &args, &result)); +} + +#[test] +fn verify_rejects_a_different_target() { + let env = Env::default(); + let (client, caller, _target) = setup(&env); + let args = call_args(&env, 100, 42); + let result = result_val(&env, 7); + let target = Address::generate(&env); + + client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &args, + &result, + &99, + ); + let stored = client.receipt(&caller, &0u32).unwrap(); + + // Same args, same result, same ledger: only the contract that was called + // differs, and the commitment has to notice. + let elsewhere = Receipt { + target: Address::generate(&env), + ..stored.clone() + }; + assert!(!client.verify(&elsewhere, &args, &result)); + + // The function name is committed too. + let renamed = Receipt { + fn_name: symbol_short!("mint"), + ..stored + }; + assert!(!client.verify(&renamed, &args, &result)); +} + +#[test] +fn the_same_invocation_commits_to_the_same_bytes_for_any_caller() { + let env = Env::default(); + let (client, alice, target) = setup(&env); + let bob = Address::generate(&env); + let args = call_args(&env, 100, 42); + let result = result_val(&env, 7); + + let a = client.anchor(&alice, &target, &symbol_short!("swap"), &args, &result, &99); + let b = client.anchor(&bob, &target, &symbol_short!("swap"), &args, &result, &99); + + // The commitment is content-addressed: who anchored it is not part of it, + // and anchoring the same facts twice is not a conflict. + assert_eq!(a, b); + assert_eq!(client.count(&alice), 1); + assert_eq!(client.count(&bob), 1); +} + +#[test] +fn receipts_are_indexed_per_caller_in_order() { + let env = Env::default(); + let (client, caller, target) = setup(&env); + let stranger = Address::generate(&env); + + let first = client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &call_args(&env, 1, 1), + &result_val(&env, 1), + &10, + ); + let second = client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &call_args(&env, 2, 2), + &result_val(&env, 2), + &11, + ); + + assert_ne!(first, second); + assert_eq!(client.count(&caller), 2); + assert_eq!(client.receipt(&caller, &0u32).unwrap().commitment, first); + assert_eq!(client.receipt(&caller, &1u32).unwrap().commitment, second); + + // Nothing landed in the stranger's list, and an unwritten index is None + // rather than an empty receipt. + assert_eq!(client.count(&stranger), 0); + assert!(client.receipt(&caller, &2u32).is_none()); + assert!(client.receipt(&stranger, &0u32).is_none()); +} + +#[test] +#[should_panic] +fn anchor_requires_the_callers_authorization() { + // No mock_all_auths here: a receipt is a statement about what the caller + // did, so anchoring one without the caller's signature must not succeed. + let env = Env::default(); + let contract_id = env.register(ReceiptAnchor, ()); + let client = ReceiptAnchorClient::new(&env, &contract_id); + let caller = Address::generate(&env); + let target = Address::generate(&env); + + client.anchor( + &caller, + &target, + &symbol_short!("swap"), + &call_args(&env, 1, 1), + &result_val(&env, 1), + &10, + ); +}