CONTRACT.md 21 KB

SwapCreator escrow contract: pinned bytecode, provenance, verification

This is a specification of the pinned SwapCreator escrow contract used by the ETH leg of the swap: what is pinned, where it is enforced, where the bytes came from, and how a third party verifies them. Operational launch steps are docs/OPERATIONS.md; nothing here changes any enforcement.

1. Role in the protocol

SwapCreator is the on-chain escrow that holds the ETH leg of a swap: the ETH side locks into newSwap. A READY swap (the ETH owner attested the XMR lock) is claimable by the counterparty before timeout2; from timeout2 on the two terminal calls alternate in WINDOW_PERIOD (1800 s) rings — the owner refunds in even rings (ring 0 opens at timeout2), the counterparty claims in odd ones. A swap the owner never set READY is refundable by the owner from creation through timeout2 + PENDING_CLAIM_GRACE (one day, to the end of the ring that contains that instant) and claimable by the counterparty in the odd rings after it, forever. Rings never overlap and every instant after an anchor belongs to exactly one of them, so a swap can never settle twice and no missed deadline is final: the fallback keeps the XMR provider from being stranded by an owner who locks and abandons, and a later ring is what lets a claimer that missed its window try again. The contract cannot verify Monero, so the fallback pays the claimer whether or not it ever locked XMR: the owner's protection is its own refund in a refund ring (the daemon's t2 timer fires in ring 0, a day before the fallback claim opens). Both roles refuse to trust a counterparty-named contract unless its bytecode is byte-identical to the pinned runtime code: the mainnet pre-flight gate checks the configured address before any daemon spawns (gate_contract, chainId == 0x1 plus sha256 over the decoded eth_getCode, engine/crates/moos/src/supervise.rs:2212-2293, DAEMON-008/DAEMON-009 outcomes at supervise.rs:2233 and :2247-2290), the daemon also re-checks the configured address at boot before serving RPC, and every peer NotifyETHLocked is verified against the same pin (check_notify_eth_locked, engine/crates/moos-daemon/src/swap.rs:5503-5573: address gate, pinned bytecode equality, tx recipient, receipt, New-log commitments). The bytecode equality itself is exact length + bytes (check_swap_creator_code, engine/crates/moos-core/src/contract.rs:299-302); the rationale is on contract.rs:295-298 — a hostile peer naming its own contract could otherwise satisfy every New-log predicate and harvest the maker's claim secret. The maker path verifies via check_contract (swap.rs:3132-3146) which calls check_notify_eth_locked at swap.rs:3136; the taker path calls it at engine/crates/moos-daemon/src/taker.rs:1766; the soak harness runs the same gate (engine/crates/moos/src/soak.rs:1527). The daemon has NO deploy path — the address must already hold the verified code (supervise.rs:19, engine/crates/moos/src/main.rs:186-192). The one deploy path is the separate operator binary deploy-swapcreator (engine/crates/moos-chain/src/bin/): it re-checks these pins, signs one creation tx, and verifies eth_getCode afterwards.

2. Pinned constants

All sha256 values are over the DECODED bytecode bytes, never the hex text — the same semantics the daemon gates on (supervise.rs:67-72). Mainnet has a baked default, the deployed v3 address 0xb39074e5f5bb5fd3a5fd48df867115d5c8b97e71 (moos_core::contract::MAINNET_SWAPCREATOR, contract.rs:279). The operator overrides it with --contract-address or MOOS_CONTRACT_ADDRESS, and either way the pre-flight gate requires the code at that address to match the pinned runtime — a stale baked address refuses to boot instead of trading against unknown bytecode. Stagenet has no baked address and must name its deployment. The runtime code is include_str!'d at engine/crates/moos-core/src/contract.rs:287-288, the deploy code at engine/crates/moos-chain/src/bin/deploy-swapcreator.rs:56.

Use Address Artifact (repo path) Bytes Decoded sha256 Enforced at
mainnet baked 0xb39074e5f5bb5fd3a5fd48df867115d5c8b97e71; --contract-address / MOOS_CONTRACT_ADDRESS override engine/crates/moos-core/src/swapcreator_runtime_code.hex 5978 856a21474d81dc6ef0473d9e5e61027978762b97168233f33cb058ea9cc07444 (pinned supervise.rs:71-72) supervise.rs:2212-2293 (launch gate); contract.rs:299-302 + swap.rs:5503-5573 (per-swap)
stagenet operator-supplied --contract-address / MOOS_CONTRACT_ADDRESS; no default engine/crates/moos-core/src/swapcreator_runtime_code.hex 5978 856a21474d81dc6ef0473d9e5e61027978762b97168233f33cb058ea9cc07444 (pinned supervise.rs:71-72) supervise.rs:2212-2293 (launch gate); contract.rs:299-302 + swap.rs:5503-5573 (per-swap)
creation input (operator deploy) none — the creation tx is signed by the operator key engine/crates/moos-chain/src/bin/swapcreator_deploy_code.hex 6144 e92da3d6351709bc311c59153c883a1c7a14749172276f532ece9f7f57902029 deploy-swapcreator.rs:208-251 (all of verify_artifact: length, suffix, prologue, runtime and creation sha256) and deploy-swapcreator.rs:523-542 (post-deploy eth_getCode bytes and sha256)

Relationship: the deploy artifact is constructor (166 bytes) + runtime; the runtime artifact is a strict byte suffix of it (checked by contracts/build.sh and packaging/contract-verify.sh). The prologue grew from 34 to 166 bytes because v3's constructor requires that PENDING_CLAIM_GRACE is a whole number of WINDOW_PERIOD rings: the check and its % helper are inlined into the creation code, so a deployment with mismatched constants cannot exist.

3. Provenance

The v3 source is in contracts/: a fork of the upstream AthanorLabs/atomic-swap SwapCreator (pinned at bd1e502cec0bf89efb88ddaeebdbc7a75f87f0ae, LGPL-3.0), with these security changes:

  • claim is allowed before timeout2 only at READY (the old v1 t1 fallback, which let a taker claim and publish the XMR provider's secret without the ETH side attesting the XMR lock, stays gone), and from the anchor on in every odd ring: at READY from timeout2 + WINDOW_PERIOD, at PENDING from timeout2 + PENDING_CLAIM_GRACE + WINDOW_PERIOD. A swap still PENDING after timeout2 + PENDING_CLAIM_GRACE (1 day) can therefore be claimed, The fallback settles an abandoned ETH lock in the taker's favour, but it does not dissolve the XMR lock: a claim publishes only the claimer's own half of the swap key, and the other half is published only by refund. So the XMR provider is paid the abandoned ETH leg at the agreed rate, and the locked XMR stays spendable by one party only - the former ETH owner, who has already paid for it - or by nobody if that owner never returns.
  • refund is allowed in every even ring of both anchors, and while PENDING from creation through the end of the ring that contains timeout2 + PENDING_CLAIM_GRACE (one contiguous run: the pre-existing v2 window, extended to a ring edge). The ring that contains the grace end is even, so the refund run ends where the first claim ring opens; the constructor requires PENDING_CLAIM_GRACE % WINDOW_PERIOD == 0, so the two paths are mutually exclusive by construction in every deployment.
  • A READY swap is closed to the claimer in the owner's rings: claim reverts TooLateToClaim there and refund reverts NotTimeToRefund in the claimer's, with no upper bound on the alternation. A claimer that misses one window gets another WINDOW_PERIOD later, so it never depends on the owner acting at all, and the owner keeps the first window (ring 0 at timeout2). What rings cannot fix is the key: the owner's half is published only by a refund and the claimer's only by a claim, so if the owner vanishes for good, the ETH stays refundable by them forever while the locked XMR stays spendable by nobody - the claimer is paid in ETH at the agreed rate instead. The XMR side carries that residual; the ETH side never does.
  • The daemon keeps CLAIM_SAFETY_MARGIN_SECS (300 s) clear of every ring edge on both calls: it never signs a claim or a refund that close to the instant its ring closes. A transaction mined past the edge reverts and leaves its secret in calldata, where the counterparty can pair it with its own half and spend the XMR without settling. The contract is exact; the client is deliberately stricter, so the last five minutes of each 30-minute ring are unused. (ready_claim_margin_secs caps the fence at half the swap's own timeout2 - timeout1 gap, so the 120 s devnet geometry keeps a usable pre-timeout2 claim window.)
  • setReady is closed at/after timeout1 (TooLateToSetReady), so the on-chain contract enforces the readiness deadline instead of trusting clients. A maker that attests late now reverts; it must refund instead.
  • WINDOW_PERIOD is a public constant (1800 s) and the rings are computed from it (k = (now - anchor) / WINDOW_PERIOD, even = owner refund, odd = claimer claim), so the schedule is one on-chain comparison per call and the engine mirrors it in moos_core::taker::{ring_index, window_state, may_send}. No storage, no ABI and no event changes: claim, refund and New are byte-identical in signature, which is why the pinned runtime hash remains the whole third-party answer to "is this the right contract".
  • Settlement is published before any payout: claim and refund verify the secret, emit the terminal event and store COMPLETED first, then pay out with a plain call. A payout that reverts or returns false at the call boundary (a claimer/owner contract rejecting the transfer, a token whose transfer reverts or returns false) is recorded in pending[swapID] and emits PayoutFailed; the funds stay in the contract. This removes the old path where an ordinary reverting payout rolled the settlement back while the secret stayed in calldata, published with no terminal event. The guarantee is not absolute: EIP-150 forwards at most 63/64 of the remaining gas, so a callee that burns all forwarded gas leaves the outer frame with only 1/64 and the pending write can out-of-gas, which reverts the whole transaction — Claimed log and COMPLETED write included. The daemon pins the asset to native ETH, so the recipient is an EOA and this is not user-reachable today. Payouts are plain calls, not transfer, so contract wallets can receive; terminal functions are nonReentrant.
  • A recorded payout is recoverable: withdraw(swapID, dest) may be called by the recorded recipient only, which chooses dest (an address it controls, which is what recovers a claimer contract whose own receive() is broken) and clears the entry. dest may be neither the zero address nor this contract (InvalidDestination), since a native payout to the contract itself would be unrecoverable. Here a failure may revert, because no secret is involved, and the revert restores the debt. The contract has no other way to move its balance.
  • newSwap rejects tokens that do not deliver exactly value (InvalidTokenAmount) and a token swap that carries native value (InvalidValue), and it refuses a token address with no deployed code (InvalidAsset), so a fee-on-transfer token or a mistyped asset cannot create an unpayable swap.
  • New carries claimer (indexed) and nonce (in addition to the indexed swapID), so a counterparty can check an offered Swap against the chain. The swapID still binds all nine struct fields.
  • claimRelayer and its RelaySwap struct are removed: no engine call site relayed claims, and the only secret-bearing path besides claim added no chain-id binding and a fee > value revert. Relaying can be layered on top of claim without contract support.

Rebuild with the pinned compiler:

SOLC=/path/to/solc-0.8.20 contracts/build.sh

The script compiles contracts/SwapCreator.sol with --optimize --optimize-runs=200, writes both hex artifacts into the Rust crates, and prints the decoded sha256 values. The deploy artifact is constructor + runtime; the runtime is a strict suffix (asserted by the script).

The old upstream v1 runtime (a3e3c6aa…30f8, 5116 bytes) and the v1 mainnet address 0x377ed3a60007048DF00135637521170628De89E5 are NOT the pinned v3 code. That v1 deployment claims PENDING swaps at any time while the owner can still refund, so the two terminal paths can race; do not use it. A v3 deployment must be made and its address supplied to every daemon and launch path.

Historical upstream provenance (base of the fork, not the v2 rebuild):

Fetched file (upstream path at pinned ref) sha256
atomic-swap-bd1e502…f0ae.tar.gz (codeload tarball, 520 entries) 0fe141eecae9adb10624ac3283c1373128a917ff8d96f3bf0668a24095cbdf15
ethereum/swap_creator.go ad5fb395901b178855f04843d0810611cedded9eb4df82ec17ae9e1291b250ce
ethereum/contracts/SwapCreator.sol (SPDX LGPLv3, pragma solidity ^0.8.19, line 1-2) a6cf9975002138a21cda5d63be37235998d7aa55513c1b17853f2b85dc4e8f33
ethereum/contracts/Secp256k1.sol 9eabe38bfe5ae7f3b8fdce84d3b2972eb10aff9ac6f6a00fce8526155bccf20a
ethereum/contracts/@openzeppelin/…/extensions/IERC20Permit.sol b7383c48331f3cc9901fc05e5d5830fcd533699a77f3ee1e756a98681bbbf2ee
LICENSE (LGPL-3.0) 74372e9f61b7e6b9033944127ee5735ac72d87ee5e32ef05057224f3617a94c9
scripts/generate-bindings.sh 15501c6a2f712c8a072f2165617ad5aec64491ef9e4a8d77a288090fe82072ff

Honest limits:

  • The v3 source and bytecode have not been independently audited; the diff above is the security-relevant surface and needs review.
  • The v3 pin is reproducible from this repo with solc 0.8.20 and the vendored OpenZeppelin sources in contracts/@openzeppelin/.

4. Verification recipe

4.1 Pinned artifacts vs pinned hashes (offline)

packaging/contract-verify.sh

exits 0 with:

ok   runtime artifact sha256 856a21474d81dc6ef0473d9e5e61027978762b97168233f33cb058ea9cc07444
ok   deploy artifact sha256 e92da3d6351709bc311c59153c883a1c7a14749172276f532ece9f7f57902029
ok   deploy artifact ends with the runtime artifact (strict suffix)
ok   solidity source digest 656ee3c3f5d5c663d07c594d75c1b9089df8a10d54725cc6effc07960611f738
note: solc 0.8.20 not on PATH and SOLC unset — the runtime bytecode was NOT re-derived here; the source digest above pins the sources it was derived from. Re-derivation needs solc 0.8.20 with --optimize --optimize-runs=200 (contracts/build.sh).
ok   supervise.rs runtime pin matches the script pin
verified (offline tier): pinned artifacts and source digest match; compiler step NOT performed

The final line is qualified precisely because the compiler step did not run: the script proved the artifacts, their strict-suffix relation, the Solidity source digest and the hardcoded pin copies — not that the artifacts follow from the sources.

Tier 2 — the same check with the pinned compiler — re-derives the runtime bytecode from source and ends unqualified:

SOLC=/path/to/solc-0.8.20 packaging/contract-verify.sh
ok   runtime artifact sha256 856a21474d81dc6ef0473d9e5e61027978762b97168233f33cb058ea9cc07444
ok   deploy artifact sha256 e92da3d6351709bc311c59153c883a1c7a14749172276f532ece9f7f57902029
ok   deploy artifact ends with the runtime artifact (strict suffix)
ok   solidity source digest 656ee3c3f5d5c663d07c594d75c1b9089df8a10d54725cc6effc07960611f738
ok   runtime bytecode re-derived from source matches the pinned artifact
ok   supervise.rs runtime pin matches the script pin
verified: pinned SwapCreator bytecode artifacts match (docs/CONTRACT.md)

Failure contract: an explicitly set SOLC that is missing or does not report Version: 0.8.20 fails the run (exit 1), naming the path and the actual Version: line — it never silently downgrades to the offline tier. A solc found on PATH at the wrong version is noted and the offline tier is used.

Equivalent by hand (hash the decoded bytes, not the hex text):

python3 - <<'EOF'
import hashlib
for p, want in [
    ("engine/crates/moos-core/src/swapcreator_runtime_code.hex",
     "856a21474d81dc6ef0473d9e5e61027978762b97168233f33cb058ea9cc07444"),
    ("engine/crates/moos-chain/src/bin/swapcreator_deploy_code.hex",
     "e92da3d6351709bc311c59153c883a1c7a14749172276f532ece9f7f57902029"),
]:
    got = hashlib.sha256(bytes.fromhex(open(p).read().strip())).hexdigest()
    print(p, got, "OK" if got == want else "MISMATCH")
EOF

The pins themselves are additionally asserted by unit tests: engine/crates/moos/src/supervise.rs:3689-3695 (the pinned-hash constant test) and engine/crates/moos-core/src/contract.rs:693-711 (artifact validity).

4.2 Deploying, and on-chain deployment vs pinned runtime code

Deployment is one operator-signed creation transaction; the daemon has no deploy path. deploy-swapcreator reads the key from the operator's own identity file (the daemon layout, opened read-only) and refuses a wrong chainId, a short/long artifact, a prologue other than the pinned 166 bytes, or a runtime sha256 other than the pin. --dry-run prints chainId, calldata length/hash, runtime sha256, gas estimate and estimated cost without a key; mainnet (chainId 1) additionally requires --yes. Creation used 1,370,313 gas on the reference build, so budget roughly 1.4M gas.

engine/target/debug/deploy-swapcreator --rpc-url https://<operator-endpoint> \
  --from-identity <identity-dir> --dry-run          # nothing signed or sent
engine/target/debug/deploy-swapcreator --rpc-url https://<operator-endpoint> \
  --from-identity <identity-dir> --yes              # chainId 1 only

For a cold-wallet deploy that never hands a key to a binary, contracts/deploy-calldata.sh [0xADDR] --chain mainnet prints the raw creation-code calldata to paste into the wallet — offline, and only after re-checking both artifacts against the pins; v3 takes no constructor arguments, so a supplied fee-recipient address is validated and then deliberately not encoded.

After the tx mines the binary compares eth_getCode at the predicted address with the pin and prints the address to hand to every daemon (--contract-address / MOOS_CONTRACT_ADDRESS). The independent check is the next block:

packaging/contract-verify.sh --rpc-url https://<operator-endpoint> \
  --address 0x<deployed-v3-address>

appends ok eth_getCode at 0x… equals the pinned runtime code. There is no default address. This is read-only (eth_getCode, never a transaction). Equivalent by hand:

curl -fsSL --proto '=https' --tlsv1.2 -X POST -H 'Content-Type: application/json' \
  --data '{"jsonrpc":"2.0","id":1,"method":"eth_getCode","params":["0x<deployed-v3-address>","latest"]}' \
  https://ethereum-rpc.publicnode.com

lowercase the result hex (without 0x) and require it to equal engine/crates/moos-core/src/swapcreator_runtime_code.hex; the decoded sha256 must be 856a2147…9cc07444 — the same comparison the daemon performs at supervise.rs:2212-2293. Transport failures (exit 3) say so explicitly and are not bytecode verdicts.

4.3 Rebuild from the repo source (optional)

Non-destructive check — re-derive in a temp dir, no repo writes:

SOLC=/path/to/solc-0.8.20 packaging/contract-verify.sh

The reference compiler is the official static linux-amd64 build 0.8.20+commit.a1b79de6.Linux.g++, sha256 0479d44fdf9c501c25337fdc540419f1593b884a87b47f023da4f1c700fda782 (pinned binaries.soliditylang.org/linux-amd64/list.json). The CBOR metadata records only the semver, so the byte comparison is the proof; a mismatched build shows up as a byte difference with its Version: line printed.

In-place rebuild — rewrites both hex artifacts and prints the decoded sha256 values:

SOLC=/path/to/solc-0.8.20 contracts/build.sh

Re-run packaging/contract-verify.sh afterwards; git status must show no artifact change. A byte-different result means the source or compiler changed — do not hand-edit artifacts; re-derive the pin and record the new provenance here.

5. Licensing

  • This project is GPL-3.0 (LICENSE at the repo root).
  • The SwapCreator and Secp256k1 sources in contracts/ are LGPL-3.0; the licence text is contracts/LICENSE and SPDX LGPLv3 is on SwapCreator.sol:1 and Secp256k1.sol:1.
  • The vendored OpenZeppelin files and AggregatorV3Interface.sol are MIT; the licence text is contracts/LICENSE-MIT and SPDX MIT is on each file.
  • The pinned bytecode enters this repo as data (include_str!, contract.rs:287-288 and deploy-swapcreator.rs:56) — it is not linked into the moos binaries. Packaged artifacts ship LICENSE-swapcreator and LICENSE-openzeppelin under share/doc/moos/ as governed by packaging/licenses/README.md.