Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions receipt-anchor/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions receipt-anchor/Makefile
Original file line number Diff line number Diff line change
@@ -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
101 changes: 101 additions & 0 deletions receipt-anchor/README.md
Original file line number Diff line number Diff line change
@@ -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.
192 changes: 192 additions & 0 deletions receipt-anchor/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<Val>,
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<Val>,
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<Val>, 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<Receipt> {
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;
Loading