diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index bf744c4..f54a6e4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,6 +22,9 @@ on: # `if: github.event_name == ...` guards on each job. - cron: '0 3 * * 1' +permissions: + contents: read + env: PYTHON_VERSION: '3.11' COVERAGE_THRESHOLD: 85 @@ -32,7 +35,7 @@ jobs: # ============================================================================= test-fast: name: Unit Tests - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 strategy: @@ -296,6 +299,8 @@ jobs: # ============================================================================= test-benchmarks: name: Performance Benchmarks + permissions: + contents: write runs-on: ubuntu-latest timeout-minutes: 15 if: github.ref == 'refs/heads/main' && github.event_name == 'push' diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f1a2bd..93ee27d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ All notable changes to AGIRAILS Python SDK will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- Resolve omitted providers through the actual local service-directory API, + rejecting missing provider addresses before funding a request. +- Verify both legacy and AIP-4 delivery signatures without their shared type name + selecting the wrong schema; reject ambiguous or incomplete delivery payloads. +- Require patched `cryptography` 50.x while retaining Python 3.9 support. +- Preserve successful `actp watch` exit codes instead of reporting them as errors. +- Forward the `actp tx transition --proof` value to the runtime. +- Await asynchronous AgentRegistry transaction construction before signing. +- Restrict the standard-library HTTP fallback to HTTP(S), including redirects, + while preserving fractional request timeouts. + ## [4.8.0] — 2026-06-19 > **Full 1:1 parity with `@agirails/sdk` (TypeScript) 4.8.0.** The Python SDK diff --git a/pyproject.toml b/pyproject.toml index ab10df0..0bfb25f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "agirails" -version = "4.8.0" +version = "4.9.0" description = "AGIRAILS Python SDK - Agent Commerce Transaction Protocol" readme = "README.md" license = "Apache-2.0" @@ -48,7 +48,7 @@ dependencies = [ "eth-hash[pycryptodome]>=0.7.0,<1.0.0", # AIP-16 delivery channel crypto: X25519 ECDH, HKDF-SHA256, AES-256-GCM # (byte-exact parity with the TS delivery surface). pyca/cryptography. - "cryptography>=46.0.7,<49.0.0", + "cryptography>=50.0.0,<51.0.0", "pydantic>=2.6.0,<3.0.0", "python-dateutil>=2.8.0,<3.0.0", "httpx>=0.27.0,<1.0.0", @@ -58,6 +58,11 @@ dependencies = [ "pyyaml>=6.0,<7.0", # CLI .env auto-load (AIP-18 §4.6.2) — parity with the TS CLI dotenv load. "python-dotenv>=1.0.0,<2.0.0", + # Evidence-bundle token cap (DISPUTE SYSTEM schema §4 / OQ-9). The cap is + # enforced over the canonical bytes with the cl100k_base tokenizer and MUST + # never be silently skipped, so the tokenizer is a core runtime dep (parity + # with the TS SDK's js-tiktoken dependency). + "tiktoken>=0.7.0,<1.0.0", "typing_extensions>=4.0.0,<5.0.0;python_version<'3.10'", ] diff --git a/src/agirails/__init__.py b/src/agirails/__init__.py index df41790..e561ad2 100644 --- a/src/agirails/__init__.py +++ b/src/agirails/__init__.py @@ -402,6 +402,33 @@ CircuitBreakerConfig, ) +# Dispute Module — Evidence Bundle canonical serializer (AIP-14b / PRD P2-3) +from agirails.dispute import ( + serialize_bundle, + serialize_bundle_to_string, + bundle_hash, + compute_bundle_hash, + validate_bundle, + assert_supported_version, + count_bundle_tokens, + enforce_token_cap, + set_bundle_tokenizer, + pin_evidence_bundle, + EVIDENCE_BUNDLE_SCHEMA_VERSION, + SUPPORTED_BUNDLE_MAJOR, + MAX_BUNDLE_TOKENS, + EvidenceBundle, + EvidenceBundleSpec, + EvidenceBundleDelivery, + EvidenceBundleDispute, + EvidenceBundleTimelineEvent, + EvidenceBundleReasoning, + PinEvidenceBundleResult, + BundleTooLargeError, + UnsupportedBundleVersionError, + InvalidBundleError, +) + # Negotiation Module (autonomous buyer-side negotiation) from agirails.negotiation import ( DEFAULT_WEIGHTS, @@ -754,6 +781,30 @@ "DownloadResult", # Types - Circuit Breaker "CircuitBreakerConfig", + # Dispute — Evidence Bundle serializer (AIP-14b / PRD P2-3) + "serialize_bundle", + "serialize_bundle_to_string", + "bundle_hash", + "compute_bundle_hash", + "validate_bundle", + "assert_supported_version", + "count_bundle_tokens", + "enforce_token_cap", + "set_bundle_tokenizer", + "pin_evidence_bundle", + "EVIDENCE_BUNDLE_SCHEMA_VERSION", + "SUPPORTED_BUNDLE_MAJOR", + "MAX_BUNDLE_TOKENS", + "EvidenceBundle", + "EvidenceBundleSpec", + "EvidenceBundleDelivery", + "EvidenceBundleDispute", + "EvidenceBundleTimelineEvent", + "EvidenceBundleReasoning", + "PinEvidenceBundleResult", + "BundleTooLargeError", + "UnsupportedBundleVersionError", + "InvalidBundleError", # Negotiation Module "DEFAULT_WEIGHTS", "PolicyEngine", diff --git a/src/agirails/abis/actp_kernel.json b/src/agirails/abis/actp_kernel.json index 04f3131..4bc92f3 100644 --- a/src/agirails/abis/actp_kernel.json +++ b/src/agirails/abis/actp_kernel.json @@ -26,6 +26,11 @@ "name": "_usdc", "type": "address", "internalType": "address" + }, + { + "name": "_recoveryGrace", + "type": "uint256", + "internalType": "uint256" } ], "stateMutability": "nonpayable" @@ -186,6 +191,19 @@ ], "stateMutability": "view" }, + { + "type": "function", + "name": "MIN_DEADLINE", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, { "type": "function", "name": "MIN_DISPUTE_BOND", @@ -225,6 +243,19 @@ ], "stateMutability": "view" }, + { + "type": "function", + "name": "MIN_RECOVERY_GRACE", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, { "type": "function", "name": "MIN_TRANSACTION_AMOUNT", @@ -455,6 +486,11 @@ "type": "bytes32", "internalType": "bytes32" }, + { + "name": "agreementHash", + "type": "bytes32", + "internalType": "bytes32" + }, { "name": "agentId", "type": "uint256", @@ -506,6 +542,25 @@ "outputs": [], "stateMutability": "nonpayable" }, + { + "type": "function", + "name": "escrowPrincipal", + "inputs": [ + { + "name": "transactionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, { "type": "function", "name": "executeAgentRegistryUpdate", @@ -520,6 +575,19 @@ "outputs": [], "stateMutability": "nonpayable" }, + { + "type": "function", + "name": "executeEscrowVaultRevocation", + "inputs": [ + { + "name": "vault", + "type": "address", + "internalType": "address" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, { "type": "function", "name": "feeRecipient", @@ -681,12 +749,35 @@ "name": "disputeBond", "type": "uint256", "internalType": "uint256" + }, + { + "name": "resultHash", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "agreementHash", + "type": "bytes32", + "internalType": "bytes32" } ] } ], "stateMutability": "view" }, + { + "type": "function", + "name": "kernelVersion", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "pure" + }, { "type": "function", "name": "linkEscrow", @@ -794,6 +885,25 @@ ], "stateMutability": "view" }, + { + "type": "function", + "name": "pendingVaultRevocationAt", + "inputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, { "type": "function", "name": "platformFeeBps", @@ -807,6 +917,32 @@ ], "stateMutability": "view" }, + { + "type": "function", + "name": "recoverStalledInProgress", + "inputs": [ + { + "name": "transactionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "recoveryGrace", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, { "type": "function", "name": "releaseEscrow", @@ -889,6 +1025,42 @@ ], "stateMutability": "view" }, + { + "type": "function", + "name": "resolveDisputeWhilePaused", + "inputs": [ + { + "name": "transactionId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "newState", + "type": "uint8", + "internalType": "enum IACTPKernel.State" + }, + { + "name": "proof", + "type": "bytes", + "internalType": "bytes" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "retryPlatformFee", + "inputs": [ + { + "name": "transactionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, { "type": "function", "name": "scheduleAgentRegistryUpdate", @@ -920,6 +1092,19 @@ "outputs": [], "stateMutability": "nonpayable" }, + { + "type": "function", + "name": "scheduleEscrowVaultRevocation", + "inputs": [ + { + "name": "vault", + "type": "address", + "internalType": "address" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, { "type": "function", "name": "setArchiveTreasury", @@ -1210,6 +1395,25 @@ ], "anonymous": false }, + { + "type": "event", + "name": "DisputeBondBpsUpdated", + "inputs": [ + { + "name": "oldBps", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + }, + { + "name": "newBps", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + } + ], + "anonymous": false + }, { "type": "event", "name": "DisputeOpened", @@ -1558,6 +1762,38 @@ ], "anonymous": false }, + { + "type": "event", + "name": "EscrowVaultRevocationCancelled", + "inputs": [ + { + "name": "vault", + "type": "address", + "indexed": true, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "EscrowVaultRevocationScheduled", + "inputs": [ + { + "name": "vault", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "executeAfter", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, { "type": "event", "name": "FeeRecipientUpdated", @@ -1740,6 +1976,31 @@ ], "anonymous": false }, + { + "type": "event", + "name": "StalledInProgressRecovered", + "inputs": [ + { + "name": "transactionId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "requester", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "amount", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, { "type": "event", "name": "StateTransitioned", @@ -1828,6 +2089,12 @@ "type": "uint256", "indexed": false, "internalType": "uint256" + }, + { + "name": "agreementHash", + "type": "bytes32", + "indexed": false, + "internalType": "bytes32" } ], "anonymous": false diff --git a/src/agirails/abis/agent_registry.json b/src/agirails/abis/agent_registry.json index 88b4d61..2d51086 100644 --- a/src/agirails/abis/agent_registry.json +++ b/src/agirails/abis/agent_registry.json @@ -211,6 +211,13 @@ ], "stateMutability": "view" }, + { + "type": "function", + "name": "deregisterAgent", + "inputs": [], + "outputs": [], + "stateMutability": "nonpayable" + }, { "type": "function", "name": "didToAddress", @@ -714,6 +721,31 @@ ], "anonymous": false }, + { + "type": "event", + "name": "AgentDeregistered", + "inputs": [ + { + "name": "agentAddress", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "did", + "type": "string", + "indexed": false, + "internalType": "string" + }, + { + "name": "timestamp", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, { "type": "event", "name": "AgentRegistered", diff --git a/src/agirails/abis/bond_escalation.json b/src/agirails/abis/bond_escalation.json new file mode 100644 index 0000000..1efd094 --- /dev/null +++ b/src/agirails/abis/bond_escalation.json @@ -0,0 +1,1747 @@ +[ + { + "type": "constructor", + "inputs": [ + { + "name": "kernel_", + "type": "address", + "internalType": "contract IACTPKernel" + }, + { + "name": "usdc_", + "type": "address", + "internalType": "contract IERC20" + }, + { + "name": "compositeMediator_", + "type": "address", + "internalType": "contract ICompositeMediator" + }, + { + "name": "admin_", + "type": "address", + "internalType": "address" + }, + { + "name": "fixedEvaluators_", + "type": "address[2]", + "internalType": "address[2]" + }, + { + "name": "rotatingPool_", + "type": "address[]", + "internalType": "address[]" + }, + { + "name": "umaOOV3_", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "DOMAIN_SEPARATOR", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "UMA_OOV3", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "USDC", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "contract IERC20" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "acceptAdmin", + "inputs": [], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "activePromptCID", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "string", + "internalType": "string" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "admin", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "assertionDisputedCallback", + "inputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "assertionResolvedCallback", + "inputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "assertedTruthfully", + "type": "bool", + "internalType": "bool" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "assertionToDispute", + "inputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "cancelFixedEvaluatorUpdate", + "inputs": [ + { + "name": "slot", + "type": "uint8", + "internalType": "uint8" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "cancelPromptCID", + "inputs": [], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "challenge", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "counterRuling", + "type": "uint8", + "internalType": "uint8" + }, + { + "name": "counterSplitBps", + "type": "uint16", + "internalType": "uint16" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "claimEscalationRefund", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "compositeMediator", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "contract ICompositeMediator" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "deposits", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "disputeToAssertion", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "disputes", + "inputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "transactionId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "currentRuling", + "type": "uint8", + "internalType": "uint8" + }, + { + "name": "splitBps", + "type": "uint16", + "internalType": "uint16" + }, + { + "name": "currentBond", + "type": "uint256", + "internalType": "uint256" + }, + { + "name": "accumulatedBonds", + "type": "uint256", + "internalType": "uint256" + }, + { + "name": "livenessEnd", + "type": "uint64", + "internalType": "uint64" + }, + { + "name": "disputedAt", + "type": "uint64", + "internalType": "uint64" + }, + { + "name": "lastProposer", + "type": "address", + "internalType": "address" + }, + { + "name": "tier", + "type": "uint8", + "internalType": "uint8" + }, + { + "name": "resolved", + "type": "bool", + "internalType": "bool" + }, + { + "name": "winnerPaid", + "type": "bool", + "internalType": "bool" + }, + { + "name": "originalPool", + "type": "uint256", + "internalType": "uint256" + }, + { + "name": "escrowAmount", + "type": "uint256", + "internalType": "uint256" + }, + { + "name": "escalatedAt", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "escalateToUMA", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "evidenceCID", + "type": "string", + "internalType": "string" + }, + { + "name": "reasoningCID", + "type": "string", + "internalType": "string" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "evidenceBundleHashOf", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "evidenceRefHashOf", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "executeFixedEvaluatorUpdate", + "inputs": [ + { + "name": "slot", + "type": "uint8", + "internalType": "uint8" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "executePromptCID", + "inputs": [], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "executeRotatingPoolAddition", + "inputs": [ + { + "name": "index", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "finalize", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "fixedEvaluatorUnlockTime", + "inputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "fixedEvaluators", + "inputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "forceResolveStale", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "kernel", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "contract IACTPKernel" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "lastProposerForRuling", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "internalType": "uint8" + } + ], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "mediatorRetryPending", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "pending", + "type": "bool", + "internalType": "bool" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "openDispute", + "inputs": [ + { + "name": "txId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "pause", + "inputs": [], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "paused", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bool", + "internalType": "bool" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "pendingAdmin", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "pendingFixedEvaluators", + "inputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "pendingPromptCID", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "string", + "internalType": "string" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "pendingRotatingAdditions", + "inputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "pendingRotatingAdditionsLength", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "pendingSettler", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "settler", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "promptCIDUnlockTime", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "proposeDirectly", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "internalType": "uint8" + }, + { + "name": "splitBps", + "type": "uint16", + "internalType": "uint16" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "proposeFixedEvaluatorUpdate", + "inputs": [ + { + "name": "slot", + "type": "uint8", + "internalType": "uint8" + }, + { + "name": "newEvaluator", + "type": "address", + "internalType": "address" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "proposePromptCID", + "inputs": [ + { + "name": "newCID", + "type": "string", + "internalType": "string" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "proposeRotatingPoolAddition", + "inputs": [ + { + "name": "evaluator", + "type": "address", + "internalType": "address" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "reasoningHashOf", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "reasoningRefHashOf", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "removeFromRotatingPool", + "inputs": [ + { + "name": "index", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "retryMediatorResolution", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "rotatingAdditionUnlockTime", + "inputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "rotatingPool", + "inputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "rotatingPoolLength", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "settleUMAAssertion", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "submitAIRuling", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "tuple", + "internalType": "struct AIRuling", + "components": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "internalType": "uint8" + }, + { + "name": "confidence", + "type": "uint16", + "internalType": "uint16" + }, + { + "name": "splitBps", + "type": "uint16", + "internalType": "uint16" + }, + { + "name": "timestamp", + "type": "uint64", + "internalType": "uint64" + }, + { + "name": "reasoningHash", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "bundleHash", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "evidenceRefHash", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "reasoningRefHash", + "type": "bytes32", + "internalType": "bytes32" + } + ] + }, + { + "name": "evidenceCID", + "type": "string", + "internalType": "string" + }, + { + "name": "reasoningCID", + "type": "string", + "internalType": "string" + }, + { + "name": "signatures", + "type": "bytes[]", + "internalType": "bytes[]" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "syncExternalResolution", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "tier1Refundable", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "bool", + "internalType": "bool" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "transferAdmin", + "inputs": [ + { + "name": "newAdmin", + "type": "address", + "internalType": "address" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "unpause", + "inputs": [], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "event", + "name": "AIRulingEvidenceCommitted", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "evidenceRefHash", + "type": "bytes32", + "indexed": false, + "internalType": "bytes32" + }, + { + "name": "reasoningRefHash", + "type": "bytes32", + "indexed": false, + "internalType": "bytes32" + }, + { + "name": "evidenceCID", + "type": "string", + "indexed": false, + "internalType": "string" + }, + { + "name": "reasoningCID", + "type": "string", + "indexed": false, + "internalType": "string" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "AIRulingSubmitted", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + }, + { + "name": "confidence", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + }, + { + "name": "submitter", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "bond", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "AdminTransferInitiated", + "inputs": [ + { + "name": "currentAdmin", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "pendingAdmin", + "type": "address", + "indexed": true, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "AdminTransferred", + "inputs": [ + { + "name": "oldAdmin", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "newAdmin", + "type": "address", + "indexed": true, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "ChallengeSubmitted", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "counterRuling", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + }, + { + "name": "counterSplitBps", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + }, + { + "name": "challenger", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "bond", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "DirectProposalSubmitted", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + }, + { + "name": "splitBps", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + }, + { + "name": "proposer", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "bond", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "DisputeFinalized", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + }, + { + "name": "winner", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "finalizer", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "bounty", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "DisputeOpened", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "txId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "escrowAmount", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + }, + { + "name": "opener", + "type": "address", + "indexed": false, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "EscalatedToUMA", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "assertionId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "escalator", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "bond", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + }, + { + "name": "evidenceCID", + "type": "string", + "indexed": false, + "internalType": "string" + }, + { + "name": "reasoningCID", + "type": "string", + "indexed": false, + "internalType": "string" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "EscalationRefundClaimed", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "claimant", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "share", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "ExternalResolutionSynced", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "txId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "kernelState", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "FixedEvaluatorUpdateCancelled", + "inputs": [ + { + "name": "slot", + "type": "uint8", + "indexed": true, + "internalType": "uint8" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "FixedEvaluatorUpdateProposed", + "inputs": [ + { + "name": "slot", + "type": "uint8", + "indexed": true, + "internalType": "uint8" + }, + { + "name": "newEvaluator", + "type": "address", + "indexed": false, + "internalType": "address" + }, + { + "name": "unlockTime", + "type": "uint64", + "indexed": false, + "internalType": "uint64" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "FixedEvaluatorUpdated", + "inputs": [ + { + "name": "slot", + "type": "uint8", + "indexed": true, + "internalType": "uint8" + }, + { + "name": "evaluator", + "type": "address", + "indexed": false, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "MediatorResolutionDeferred", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "txId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + }, + { + "name": "splitBps", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "MediatorResolutionRetried", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "txId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + }, + { + "name": "splitBps", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "Paused", + "inputs": [ + { + "name": "account", + "type": "address", + "indexed": true, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "PromptCIDProposalCancelled", + "inputs": [], + "anonymous": false + }, + { + "type": "event", + "name": "PromptCIDProposed", + "inputs": [ + { + "name": "newCID", + "type": "string", + "indexed": false, + "internalType": "string" + }, + { + "name": "unlockTime", + "type": "uint64", + "indexed": false, + "internalType": "uint64" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "PromptCIDUpdated", + "inputs": [ + { + "name": "cid", + "type": "string", + "indexed": false, + "internalType": "string" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "RotatingPoolAdditionProposed", + "inputs": [ + { + "name": "evaluator", + "type": "address", + "indexed": false, + "internalType": "address" + }, + { + "name": "unlockTime", + "type": "uint64", + "indexed": false, + "internalType": "uint64" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "RotatingPoolUpdated", + "inputs": [ + { + "name": "evaluator", + "type": "address", + "indexed": false, + "internalType": "address" + }, + { + "name": "added", + "type": "bool", + "indexed": false, + "internalType": "bool" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "StaleDisputeResolved", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "caller", + "type": "address", + "indexed": true, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "Tier1RefundsEnabled", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "UMACallbackIgnored", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "assertionId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "reason", + "type": "string", + "indexed": false, + "internalType": "string" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "UMADisputeEscalated", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "assertionId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "UMAResolutionReceived", + "inputs": [ + { + "name": "disputeId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "assertionId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "indexed": false, + "internalType": "uint8" + }, + { + "name": "winner", + "type": "address", + "indexed": false, + "internalType": "address" + }, + { + "name": "payout", + "type": "uint256", + "indexed": false, + "internalType": "uint256" + } + ], + "anonymous": false + }, + { + "type": "event", + "name": "Unpaused", + "inputs": [ + { + "name": "account", + "type": "address", + "indexed": true, + "internalType": "address" + } + ], + "anonymous": false + }, + { + "type": "error", + "name": "ReentrancyGuardReentrantCall", + "inputs": [] + }, + { + "type": "error", + "name": "SafeERC20FailedOperation", + "inputs": [ + { + "name": "token", + "type": "address", + "internalType": "address" + } + ] + } +] diff --git a/src/agirails/abis/composite_mediator.json b/src/agirails/abis/composite_mediator.json new file mode 100644 index 0000000..f2a2c07 --- /dev/null +++ b/src/agirails/abis/composite_mediator.json @@ -0,0 +1,119 @@ +[ + { + "type": "constructor", + "inputs": [ + { + "name": "kernel_", + "type": "address", + "internalType": "contract IACTPKernel" + } + ], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "bondEscalation", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "deployer", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "initialize", + "inputs": [ + { + "name": "bondEscalation_", + "type": "address", + "internalType": "address" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "kernel", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "contract IACTPKernel" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "resolve", + "inputs": [ + { + "name": "txId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "ruling", + "type": "uint8", + "internalType": "uint8" + }, + { + "name": "splitBps", + "type": "uint16", + "internalType": "uint16" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "event", + "name": "DisputeSplitRecorded", + "inputs": [ + { + "name": "txId", + "type": "bytes32", + "indexed": true, + "internalType": "bytes32" + }, + { + "name": "requester", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "provider", + "type": "address", + "indexed": true, + "internalType": "address" + }, + { + "name": "splitBps", + "type": "uint16", + "indexed": false, + "internalType": "uint16" + } + ], + "anonymous": false + } +] diff --git a/src/agirails/abis/escrow_vault.json b/src/agirails/abis/escrow_vault.json index 2b21ff2..93cc1c5 100644 --- a/src/agirails/abis/escrow_vault.json +++ b/src/agirails/abis/escrow_vault.json @@ -15,6 +15,44 @@ ], "stateMutability": "nonpayable" }, + { + "type": "function", + "name": "bondBalance", + "inputs": [ + { + "name": "escrowId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "bondBalances", + "inputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, { "type": "function", "name": "createEscrow", @@ -43,6 +81,29 @@ "outputs": [], "stateMutability": "nonpayable" }, + { + "type": "function", + "name": "depositBond", + "inputs": [ + { + "name": "escrowId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "from", + "type": "address", + "internalType": "address" + }, + { + "name": "amount", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, { "type": "function", "name": "escrows", @@ -172,6 +233,29 @@ ], "stateMutability": "nonpayable" }, + { + "type": "function", + "name": "releaseBond", + "inputs": [ + { + "name": "escrowId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "recipient", + "type": "address", + "internalType": "address" + }, + { + "name": "amount", + "type": "uint256", + "internalType": "uint256" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, { "type": "function", "name": "remaining", diff --git a/src/agirails/abis/i_optimistic_oracle_v3.json b/src/agirails/abis/i_optimistic_oracle_v3.json new file mode 100644 index 0000000..f4bedd5 --- /dev/null +++ b/src/agirails/abis/i_optimistic_oracle_v3.json @@ -0,0 +1,188 @@ +[ + { + "type": "function", + "name": "assertTruth", + "inputs": [ + { + "name": "claim", + "type": "bytes", + "internalType": "bytes" + }, + { + "name": "asserter", + "type": "address", + "internalType": "address" + }, + { + "name": "callbackRecipient", + "type": "address", + "internalType": "address" + }, + { + "name": "escalationManager", + "type": "address", + "internalType": "address" + }, + { + "name": "liveness", + "type": "uint64", + "internalType": "uint64" + }, + { + "name": "currency", + "type": "address", + "internalType": "contract IERC20" + }, + { + "name": "bond", + "type": "uint256", + "internalType": "uint256" + }, + { + "name": "identifier", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "domainId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "burnedBondPercentage", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "defaultCurrency", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "contract IERC20" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "defaultIdentifier", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "disputeAssertion", + "inputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + }, + { + "name": "disputer", + "type": "address", + "internalType": "address" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "getAssertionResult", + "inputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "bool", + "internalType": "bool" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "getMinimumBond", + "inputs": [ + { + "name": "currency", + "type": "address", + "internalType": "address" + } + ], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "settleAndGetAssertionResult", + "inputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "bool", + "internalType": "bool" + } + ], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "settleAssertion", + "inputs": [ + { + "name": "assertionId", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + } +] diff --git a/src/agirails/adapters/base.py b/src/agirails/adapters/base.py index 94c3ca5..b335abc 100644 --- a/src/agirails/adapters/base.py +++ b/src/agirails/adapters/base.py @@ -336,3 +336,45 @@ def encode_dispute_window_proof(self, dispute_window_seconds: int) -> str: from eth_abi import encode as abi_encode return "0x" + abi_encode(["uint256"], [int(dispute_window_seconds)]).hex() + + @staticmethod + def assert_real_result_hash(result_hash: Optional[Union[str, bytes]]) -> bytes: + """ + Fail-closed guard for the DELIVERED transition. A delivery path MUST + commit to a REAL deliverable: ``result_hash`` is either + ``compute_result_hash(result)`` (public) or the AIP-16 envelope hash + (encrypted). There is NO synthetic fallback — a missing/invalid/zero + hash raises. Byte-parity with TS ``assertRealResultHash`` + (utils/deliveryProof.ts). + """ + if result_hash is None: + raise ValueError( + "deliver() requires a real deliverable or an explicit resultHash: " + "pass compute_result_hash(result) (public) or the AIP-16 envelope " + "hash (encrypted). Refusing to send DELIVERED without a result commitment." + ) + rh = result_hash + if isinstance(rh, str): + try: + rh = bytes.fromhex(rh[2:] if rh.startswith(("0x", "0X")) else rh) + except ValueError as e: + raise ValueError(f"resultHash must be a 32-byte hex string: {e}") + rh = bytes(rh) + if len(rh) != 32: + raise ValueError(f"resultHash must be 32 bytes, got {len(rh)}") + if rh == b"\x00" * 32: + raise ValueError("resultHash must be non-zero (the v2 kernel rejects bytes32(0)).") + return rh + + def encode_delivery_proof(self, dispute_window_seconds: int, result_hash: Union[str, bytes]) -> str: + """ + Encode the AIP-14c 64-byte DELIVERED transition proof + ``abi.encode(uint256 window, bytes32 resultHash)``. The v2 kernel REJECTS the + legacy 32-byte window-only proof ("Delivery proof must be (window,resultHash)"). + ``result_hash`` MUST be a real, non-zero 32-byte commitment (there is no + synthetic fallback). Mirrors TS ``encodeDeliveryProof`` (utils/deliveryProof.ts). + """ + from eth_abi import encode as abi_encode + + rh = self.assert_real_result_hash(result_hash) + return "0x" + abi_encode(["uint256", "bytes32"], [int(dispute_window_seconds), rh]).hex() diff --git a/src/agirails/adapters/basic.py b/src/agirails/adapters/basic.py index a755228..6ca5f7f 100644 --- a/src/agirails/adapters/basic.py +++ b/src/agirails/adapters/basic.py @@ -579,21 +579,31 @@ async def start_work(self, tx_id: str) -> None: return await self._runtime.transition_state(tx_id, State.IN_PROGRESS) - async def deliver(self, tx_id: str, proof: Optional[str] = None) -> None: + async def deliver( + self, + tx_id: str, + proof: Optional[str] = None, + result_hash: Optional[Union[str, bytes]] = None, + ) -> None: """ Transition to DELIVERED (provider completes work). IAdapter compliance. - When no proof is provided, fetches the transaction's actual - disputeWindow and encodes it. Mirrors TS ``BasicAdapter.deliver`` - (BasicAdapter.ts:557-573). + When no ``proof`` is provided, fetches the transaction's actual + disputeWindow and encodes the 64-byte ``(window, resultHash)`` proof. + ``result_hash`` MUST commit to a REAL deliverable — there is NO synthetic + fallback, so a bare ``deliver(tx_id)`` with neither a pre-encoded + ``proof`` nor a ``result_hash`` fails closed. Mirrors TS + ``BasicAdapter.deliver`` (BasicAdapter.ts:560-578). Args: tx_id: Transaction ID. - proof: Optional ABI-encoded dispute-window proof. Defaults to the - transaction's own disputeWindow. + proof: Optional pre-encoded 64-byte delivery proof. + result_hash: bytes32 commitment to the delivered result, used when + ``proof`` is not supplied. REQUIRED in that case. Raises: RuntimeError: If transaction not found. + ValueError: If neither ``proof`` nor a real ``result_hash`` is given. """ from agirails.runtime.types import State @@ -602,7 +612,9 @@ async def deliver(self, tx_id: str, proof: Optional[str] = None) -> None: tx = await self._runtime.get_transaction(tx_id) if tx is None: raise RuntimeError(f"Transaction {tx_id} not found") - delivery_proof = self.encode_dispute_window_proof(tx.dispute_window) + # AIP-14c 64-byte (window, resultHash) proof — fails closed without a + # real resultHash (no synthetic fallback). + delivery_proof = self.encode_delivery_proof(tx.dispute_window, result_hash) router = self._smart_wallet_router if router is not None and router.should_route(): diff --git a/src/agirails/adapters/standard.py b/src/agirails/adapters/standard.py index 6c54505..8e5669f 100644 --- a/src/agirails/adapters/standard.py +++ b/src/agirails/adapters/standard.py @@ -792,28 +792,42 @@ async def start_work(self, tx_id: str) -> None: return await self._runtime.transition_state(tx_id, State.IN_PROGRESS) - async def deliver(self, tx_id: str, proof: Optional[str] = None) -> None: + async def deliver( + self, + tx_id: str, + proof: Optional[str] = None, + result_hash: Optional[Union[str, bytes]] = None, + ) -> None: """ Transition to DELIVERED (provider completes work). IAdapter compliance. - When no proof is provided, fetches the transaction's actual - disputeWindow and encodes it as proof. Mirrors TS - ``StandardAdapter.deliver`` (StandardAdapter.ts:654-672). + When no ``proof`` is provided, fetches the transaction's actual + disputeWindow and encodes the 64-byte ``(window, resultHash)`` proof. + ``result_hash`` MUST commit to a REAL deliverable + (``compute_result_hash(result)`` public / AIP-16 envelope hash + encrypted) — there is NO synthetic fallback, so a bare ``deliver(tx_id)`` + with neither a pre-encoded ``proof`` nor a ``result_hash`` fails closed. + Mirrors TS ``StandardAdapter.deliver`` (StandardAdapter.ts:658-677). Args: tx_id: Transaction ID. - proof: Optional ABI-encoded dispute-window proof. Defaults to the - transaction's own disputeWindow. + proof: Optional pre-encoded 64-byte delivery proof. When supplied it + is sent verbatim (the caller already committed the resultHash). + result_hash: bytes32 commitment to the delivered result, used when + ``proof`` is not supplied. REQUIRED in that case. Raises: RuntimeError: If transaction not found. + ValueError: If neither ``proof`` nor a real ``result_hash`` is given. """ delivery_proof = proof if not delivery_proof: tx = await self._runtime.get_transaction(tx_id) if tx is None: raise RuntimeError(f"Transaction {tx_id} not found") - delivery_proof = self.encode_dispute_window_proof(tx.dispute_window) + # AIP-14c 64-byte (window, resultHash) proof — fails closed without a + # real resultHash (no synthetic fallback). + delivery_proof = self.encode_delivery_proof(tx.dispute_window, result_hash) router = self._smart_wallet_router if router is not None and router.should_route(): diff --git a/src/agirails/adapters/types.py b/src/agirails/adapters/types.py index 7577c0c..4fe2838 100644 --- a/src/agirails/adapters/types.py +++ b/src/agirails/adapters/types.py @@ -15,6 +15,7 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass, field from decimal import Decimal from typing import Any, Dict, List, Optional, Union @@ -133,6 +134,9 @@ class PaymentMetadata(TypedDict, total=False): # ============================================================================ +AcceptedX402Quote = Optional[Mapping[str, str]] + + @dataclass class UnifiedPayParams: """ @@ -156,6 +160,8 @@ class UnifiedPayParams: DELETE). Ignored by ACTP adapters. TS parity, types/adapter.ts:168. http_body: HTTP body for x402 paid requests (POST/PUT/PATCH). Ignored by ACTP adapters. TS parity, types/adapter.ts:171. + accepted_quote: Accepted x402 base-unit amount, asset, pay_to, network + and opaque evaluator nonce. Copied immutably per pay invocation. http_headers: Extra HTTP headers for x402 paid requests. Ignored by ACTP adapters. TS parity, types/adapter.ts:174. """ @@ -173,6 +179,8 @@ class UnifiedPayParams: http_body: Optional[Union[str, bytes, bytearray]] = None http_headers: Optional[Dict[str, str]] = None + accepted_quote: AcceptedX402Quote = None + def __post_init__(self) -> None: """Validate dispute_window bounds (mirrors TS Zod schema, types/adapter.ts:198-203: int, min 3600, max 30 days).""" diff --git a/src/agirails/adapters/x402/http_options.py b/src/agirails/adapters/x402/http_options.py new file mode 100644 index 0000000..5a16f22 --- /dev/null +++ b/src/agirails/adapters/x402/http_options.py @@ -0,0 +1,41 @@ +"""Snapshot native and unified x402 HTTP options before asynchronous requests.""" + +import json +from typing import Any, Optional, Union + +from agirails.types.x402 import X402HttpMethod + + +def extract_http_options( + params: Any, native: bool +) -> tuple[X402HttpMethod, dict[str, str], Optional[str], Optional[str]]: + method: X402HttpMethod = "GET" + request_headers: dict[str, str] = {} + request_body: Optional[str] = None + content_type: Optional[str] = None + if native: + method = params.method or "GET" + request_headers = dict(params.headers or {}) + request_body = serialize_body(params.body) + content_type = params.content_type + if content_type is None and params.body and method != "GET": + content_type = "application/json" + else: + method = getattr(params, "http_method", None) or "GET" + request_headers = dict(getattr(params, "http_headers", None) or {}) + request_body = serialize_body(getattr(params, "http_body", None)) + if request_body is not None and method != "GET": + content_type = "application/json" + return method, request_headers, request_body, content_type + + +def serialize_body( + body: Optional[Union[str, dict[str, Any]]], +) -> Optional[str]: + if body is None: + return None + if isinstance(body, str): + return body + if isinstance(body, (bytes, bytearray)): + return bytes(body).decode("utf-8") + return json.dumps(body) diff --git a/src/agirails/adapters/x402/quote_binding.py b/src/agirails/adapters/x402/quote_binding.py new file mode 100644 index 0000000..0bd98d1 --- /dev/null +++ b/src/agirails/adapters/x402/quote_binding.py @@ -0,0 +1,95 @@ +"""Per-request accepted x402 terms, checked before any payment side effect.""" + +import json +import re +from collections.abc import Mapping +from types import MappingProxyType +from typing import Any, Optional + +from agirails.types.x402 import X402QuoteMismatchError + +_FIELDS = frozenset({"amount", "asset", "pay_to", "network", "nonce"}) + + +def _amount(value: Any) -> Optional[int]: + if isinstance(value, str) and value.isascii() and value.isdecimal(): + try: + return int(value) + except ValueError: + return None + return None + + +def snapshot_quote(value: Any, request_body: Optional[str]) -> Optional[Mapping[str, str]]: + """Copy scalar terms before await; validate the actual outgoing quote nonce.""" + if value is None: + return None + if not isinstance(value, Mapping) or not value or set(value) - _FIELDS: + raise X402QuoteMismatchError("Invalid accepted_quote fields") + copied = dict(value) + if any(not isinstance(v, str) or not v for v in copied.values()): + raise X402QuoteMismatchError("Accepted quote terms must be nonempty strings") + if "amount" in copied and _amount(copied["amount"]) is None: + raise X402QuoteMismatchError("Invalid accepted quote amount") + for field in ["asset", "pay_to"]: + if field in copied and re.fullmatch(r"0x[0-9a-fA-F]{40}", copied[field]) is None: + raise X402QuoteMismatchError("Invalid accepted quote address") + if "network" in copied and re.fullmatch(r"eip155:[1-9][0-9]*", copied["network"]) is None: + raise X402QuoteMismatchError("Accepted quote network must be canonical CAIP-2") + if "nonce" in copied: + try: + body = json.loads(request_body) if request_body is not None else None + except (ValueError, TypeError): + body = None + if not isinstance(body, dict) or body.get("disputeNonce") != copied["nonce"]: + raise X402QuoteMismatchError("Request disputeNonce differs from accepted quote") + return MappingProxyType(copied) + + +def matches_quote(requirement: Mapping[str, Any], quote: Mapping[str, str]) -> bool: + """Match defined economics and any advertised evaluator nonce commitments. + + EIP-3009 and Permit2 signing nonces remain independently random; they are + not the evaluator's opaque disputeNonce. + """ + if "network" in quote and requirement.get("network") != quote["network"]: + return False + for field, wire in [("asset", "asset"), ("pay_to", "payTo")]: + if field in quote: + offered = requirement.get(wire) + if not isinstance(offered, str) or offered.lower() != quote[field].lower(): + return False + if "amount" in quote: + offered = _amount(requirement.get("amount")) + if offered is None or offered != _amount(quote["amount"]): + return False + if "nonce" in quote: + sources = [requirement] + extra = requirement.get("extra") + if isinstance(extra, dict): + sources.append(extra) + for source in list(sources): + if "commit" in source: + if not isinstance(source["commit"], dict): + return False + sources.append(source["commit"]) + if any("disputeNonce" in s and s["disputeNonce"] != quote["nonce"] for s in sources): + return False + return True + + +def validate_wallet_network(wallet: Any, quote: Optional[Mapping[str, str]]) -> None: + """Require the configured wallet chain for a network-bound payment.""" + if quote is None or "network" not in quote: + return + try: + info = wallet.get_wallet_info() + chain_id = ( + info.get("chain_id") if isinstance(info, Mapping) else getattr(info, "chain_id", None) + ) + except Exception as error: + raise X402QuoteMismatchError("Cannot determine quoted payment wallet chain") from error + if isinstance(chain_id, bool) or not isinstance(chain_id, int) or chain_id <= 0: + raise X402QuoteMismatchError("Quoted payments require a valid wallet chain_id") + if quote["network"] != f"eip155:{chain_id}": + raise X402QuoteMismatchError("Wallet chain differs from accepted quote network") diff --git a/src/agirails/adapters/x402_adapter.py b/src/agirails/adapters/x402_adapter.py index 18ff982..f9b8f36 100644 --- a/src/agirails/adapters/x402_adapter.py +++ b/src/agirails/adapters/x402_adapter.py @@ -35,6 +35,8 @@ import json import re import time +from collections.abc import Mapping +from copy import deepcopy from dataclasses import dataclass from datetime import datetime, timezone from typing import ( @@ -61,11 +63,17 @@ encode_x_payment_header, network_name_for_caip2, ) +from agirails.adapters.x402.http_options import extract_http_options as _extract_http_options from agirails.adapters.x402.permit2 import ( PaymentRequirementsPermit2, build_permit2_payload, create_permit2_approval_tx, ) +from agirails.adapters.x402.quote_binding import ( + matches_quote, + snapshot_quote, + validate_wallet_network, +) from agirails.types.x402 import ( DEFAULT_EVM_NETWORKS, DEFAULT_USDC_BY_NETWORK, @@ -82,6 +90,7 @@ X402PaymentFailedError, X402PaymentHeaders, X402PublishRequiredError, + X402QuoteMismatchError, X402SettlementProofMissingError, is_paymaster_gate_error, is_valid_x402_network, @@ -489,11 +498,15 @@ async def pay( """ self.validate(params) - method, request_headers, request_body, content_type = _extract_http_options(params) + method, request_headers, request_body, content_type = _extract_http_options(params, isinstance(params, X402PayParams)) + wire_body = None if method in ("GET", "DELETE") else request_body + accepted_quote = snapshot_quote(getattr(params, "accepted_quote", None), wire_body) + validate_wallet_network(self._config.wallet_provider, accepted_quote) + endpoint = params.to # Step 1: initial request initial = await self._make_request( - params.to, method, request_headers, request_body, content_type + endpoint, method, request_headers, request_body, content_type ) # Free service: 200 on initial request, no payment. @@ -506,9 +519,10 @@ async def pay( # Step 2: parse + select requirements. requirements = self._parse_payment_requirements(initial) - chosen = self._select_requirements(requirements) + chosen = self._select_requirements(requirements, accepted_quote) # Step 3 + 4: build a signed payment payload. + validate_wallet_network(self._config.wallet_provider, accepted_quote) scheme_payload, network_name = await self._build_payment_payload(chosen) x_payment = encode_x_payment_header(scheme_payload, network_name) @@ -517,7 +531,7 @@ async def pay( retry_headers["X-PAYMENT"] = x_payment try: res = await self._make_request( - params.to, method, retry_headers, request_body, content_type + endpoint, method, retry_headers, request_body, content_type ) except Exception as exc: raise X402PaymentFailedError( @@ -593,7 +607,7 @@ def _parse_payment_requirements( return accepts def _select_requirements( - self, requirements: Sequence[Dict[str, Any]] + self, requirements: Sequence[Dict[str, Any]], accepted_quote: Optional[Mapping[str, str]] = None ) -> Dict[str, Any]: """Pick the best requirement (TS selectRequirements). @@ -633,6 +647,11 @@ def _passes(r: Dict[str, Any]) -> bool: f"allowed networks: [{', '.join(allowed)}]{asset_info}." ) + if accepted_quote is not None: + candidates = [r for r in candidates if matches_quote(r, accepted_quote)] + if not candidates: + raise X402QuoteMismatchError('No payment requirement matches the accepted quote') + def _is_permit2(r: Dict[str, Any]) -> bool: extra = r.get("extra") return isinstance(extra, dict) and extra.get("assetTransferMethod") == "permit2" @@ -643,7 +662,7 @@ def _is_permit2(r: Dict[str, Any]) -> bool: else: prioritized = sorted(candidates, key=lambda r: 1 if _is_permit2(r) else 0) - chosen = dict(prioritized[0]) + chosen = deepcopy(prioritized[0]) amount_big = int(chosen["amount"]) if amount_big > self._max_amount_per_tx: raise X402AmountExceededError( @@ -966,34 +985,6 @@ def _decode_payment_response_header(header: str) -> Dict[str, Any]: # ============================================================================ -def _extract_http_options( - params: Union[UnifiedPayParams, X402PayParams] -) -> "tuple[X402HttpMethod, Dict[str, str], Optional[str], Optional[str]]": - method: X402HttpMethod = "GET" - request_headers: Dict[str, str] = {} - request_body: Optional[str] = None - content_type: Optional[str] = None - if isinstance(params, X402PayParams): - method = params.method or "GET" - request_headers = dict(params.headers or {}) - request_body = _serialize_body(params.body, params.content_type) - content_type = params.content_type - if content_type is None and params.body and method != "GET": - content_type = "application/json" - return method, request_headers, request_body, content_type - - -def _serialize_body( - body: Optional[Union[str, Dict[str, Any]]], - content_type: Optional[str] = None, -) -> Optional[str]: - if body is None: - return None - if isinstance(body, str): - return body - return json.dumps(body) - - def _looks_like_legacy_config(config: Any) -> bool: """True if ``config`` is (or carries) the legacy transfer_fn-based shape. @@ -1091,6 +1082,8 @@ def validate(self, params: UnifiedPayParams) -> None: async def pay( self, params: Union[UnifiedPayParams, X402PayParams] ) -> X402PayResult: + if getattr(params, "accepted_quote", None) is not None: + raise X402QuoteMismatchError('Legacy x402 transport cannot enforce accepted quote terms') self.validate(params) endpoint = params.to diff --git a/src/agirails/api/agirails_app.py b/src/agirails/api/agirails_app.py index c6dd0d1..2b2889e 100644 --- a/src/agirails/api/agirails_app.py +++ b/src/agirails/api/agirails_app.py @@ -109,10 +109,9 @@ async def _get(url: str, timeout: float = 15.0) -> Dict[str, Any]: raise AgirailsAppError(f"GET {url} failed: {resp.status}", resp.status) return await resp.json() - from urllib.request import Request, urlopen + from agirails.utils.http import request_http - req = Request(url, headers={"Accept": "application/json"}) - with urlopen(req, timeout=int(timeout)) as resp: + with request_http(url, headers={"Accept": "application/json"}, timeout=timeout) as resp: if resp.status >= 400: raise AgirailsAppError(f"GET {url} failed: {resp.status}", resp.status) return _json.loads(resp.read().decode("utf-8")) @@ -144,16 +143,16 @@ async def _post(url: str, body: Dict[str, Any], timeout: float = 15.0) -> Dict[s raise AgirailsAppError(f"POST {url} failed: {resp.status}", resp.status) return await resp.json() - from urllib.request import Request, urlopen + from agirails.utils.http import request_http data = _json.dumps(body).encode("utf-8") - req = Request( + with request_http( url, data=data, headers={"Content-Type": "application/json", "Accept": "application/json"}, method="POST", - ) - with urlopen(req, timeout=int(timeout)) as resp: + timeout=timeout, + ) as resp: if resp.status >= 400: raise AgirailsAppError(f"POST {url} failed: {resp.status}", resp.status) return _json.loads(resp.read().decode("utf-8")) diff --git a/src/agirails/api/discover.py b/src/agirails/api/discover.py index d39ec00..9dc0c69 100644 --- a/src/agirails/api/discover.py +++ b/src/agirails/api/discover.py @@ -260,10 +260,10 @@ async def discover_agents(params: Optional[DiscoverParams] = None) -> DiscoverRe # Fallback: synchronous urllib (works everywhere) import json - from urllib.request import Request, urlopen - req = Request(url, headers={"Accept": "application/json"}) - with urlopen(req, timeout=15) as resp: + from agirails.utils.http import request_http + + with request_http(url, headers={"Accept": "application/json"}, timeout=15) as resp: if resp.status != 200: raise RuntimeError(f"discover API failed: {resp.status}") data = json.loads(resp.read().decode("utf-8")) diff --git a/src/agirails/builders/__init__.py b/src/agirails/builders/__init__.py index ab46dff..a6db70a 100644 --- a/src/agirails/builders/__init__.py +++ b/src/agirails/builders/__init__.py @@ -56,6 +56,18 @@ CounterAcceptMessage, CounterAcceptParams, ) +from agirails.builders.agreement import ( + AGREEMENT_SCHEMA_VERSION, + SUPPORTED_AGREEMENT_MAJOR, + ZERO_AGREEMENT_HASH, + InvalidAgreementError, + UnsupportedAgreementVersionError, + assert_supported_agreement_version, + validate_agreement, + serialize_agreement, + compute_agreement_hash, + agreement_hash, +) __all__ = [ # Quote (AIP-2 signed — TS parity) @@ -86,4 +98,15 @@ "CounterAcceptBuilder", "CounterAcceptMessage", "CounterAcceptParams", + # Agreement serializer (AIP-14c D3 — agreementHash preimage) + "AGREEMENT_SCHEMA_VERSION", + "SUPPORTED_AGREEMENT_MAJOR", + "ZERO_AGREEMENT_HASH", + "InvalidAgreementError", + "UnsupportedAgreementVersionError", + "assert_supported_agreement_version", + "validate_agreement", + "serialize_agreement", + "compute_agreement_hash", + "agreement_hash", ] diff --git a/src/agirails/builders/agreement.py b/src/agirails/builders/agreement.py new file mode 100644 index 0000000..c9f90db --- /dev/null +++ b/src/agirails/builders/agreement.py @@ -0,0 +1,158 @@ +# PARITY: sdk-js/src/builders/AgreementSerializer.ts +# This file and its TypeScript twin MUST produce byte-identical canonical bytes +# and agreementHash for the same logical agreement; keep the schema, error names, +# and public API surface 1:1. +""" +Agreement serializer — the single CANONICAL ``agreementHash`` preimage +serializer (AIP-14c D3). + +Python half of the cross-language (TS <-> Py) byte-identical serializer. Its +TypeScript twin is ``sdk-js/src/builders/AgreementSerializer.ts``. Both MUST +produce IDENTICAL canonical bytes and therefore an identical ``agreementHash`` +for the same logical agreement. + +What ``agreementHash`` commits (AIP-14c D3 — LOCKED): + The creation-time ``agreementHash`` (7th arg of the v2 ``createTransaction``, + stored in ``Transaction.agreementHash``) commits the **request + input + SLA + ONLY** — deliberately NOT the quote. The quote arrives *after* creation + (``INITIATED->QUOTED`` sets ``txn.metadata = quoteHash``; ``acceptQuote`` + sets the final ``txn.amount``). The evaluator verifies the effective + agreement **triple**: ``{agreementHash, txn.metadata (quoteHash), txn.amount}``. + + ``agreementHash == bytes32(0)`` => NO automatic signed ruling (D3 + fail-closed). Use :data:`ZERO_AGREEMENT_HASH` to opt out explicitly. + +Canonical byte rule (mirrors the evidence-bundle serializer): + ``canonical_bytes = canonical_json_dumps(agreement).encode("utf-8")`` — the + same cross-language-proven canonicalizer as the evidence bundle (byte- + identical to JS ``JSON.stringify`` over sorted keys). ``agreement_hash = + keccak256(canonical_bytes)``. +""" + +from __future__ import annotations + +from typing import Any + +from eth_utils import keccak as _keccak + +from agirails.utils.canonical_json import canonical_json_dumps + +# Current frozen agreement schema version (semver). +AGREEMENT_SCHEMA_VERSION = "1.0.0" + +# The major schema version this serializer understands. +SUPPORTED_AGREEMENT_MAJOR = 1 + +# bytes32(0) — the "no automatic AI ruling" sentinel for agreementHash (D3). +ZERO_AGREEMENT_HASH = "0x" + "00" * 32 + +_REQUIRED_KEYS = ("schemaVersion", "request", "input", "sla") + + +class InvalidAgreementError(ValueError): + """Raised when the agreement is structurally invalid (missing/extra key).""" + + def __init__(self, message: str) -> None: + super().__init__(f"Invalid agreement: {message}") + + +class UnsupportedAgreementVersionError(ValueError): + """Raised when the agreement schemaVersion major is unknown to this serializer.""" + + def __init__(self, schema_version: str) -> None: + self.schema_version = schema_version + super().__init__( + f'Unsupported agreement schemaVersion "{schema_version}": ' + f"this SDK understands major version {SUPPORTED_AGREEMENT_MAJOR}." + ) + + +def assert_supported_agreement_version(schema_version: str) -> None: + """ + Reject an agreement whose ``schemaVersion`` major is unknown. + + Raises: + UnsupportedAgreementVersionError + """ + major = schema_version.split(".")[0] + if not major.isdigit() or int(major) != SUPPORTED_AGREEMENT_MAJOR: + raise UnsupportedAgreementVersionError(schema_version) + + +def validate_agreement(agreement: Any) -> dict: + """ + Validate + normalize a logical agreement into the frozen 4-key shape. + + Rejects: non-dict input, a missing required key, or any extra top-level key + (exactly ``schemaVersion, request, input, sla`` — no additional properties). + An unknown MAJOR schema version raises + :class:`UnsupportedAgreementVersionError`. + + Returns: + The validated agreement dict. + + Raises: + InvalidAgreementError, UnsupportedAgreementVersionError + """ + if not isinstance(agreement, dict): + raise InvalidAgreementError( + "must be a dict with keys {schemaVersion, request, input, sla}" + ) + for req in _REQUIRED_KEYS: + if req not in agreement: + raise InvalidAgreementError(f'missing required key "{req}"') + for key in agreement: + if key not in _REQUIRED_KEYS: + raise InvalidAgreementError( + f'unexpected extra key "{key}" ' + f"(only {', '.join(_REQUIRED_KEYS)} allowed)" + ) + if not isinstance(agreement["schemaVersion"], str): + raise InvalidAgreementError("schemaVersion must be a string") + assert_supported_agreement_version(agreement["schemaVersion"]) + return agreement + + +def serialize_agreement(agreement: Any) -> str: + """ + Serialize an agreement to its canonical UTF-8 string form (the exact text + that is hashed). Byte-identical to the TS twin's ``serializeAgreement``. + + Raises: + InvalidAgreementError, UnsupportedAgreementVersionError + """ + valid = validate_agreement(agreement) + return canonical_json_dumps(valid) + + +def compute_agreement_hash(agreement: Any) -> str: + """ + Compute ``agreement_hash = keccak256(utf8(serialize_agreement(agreement)))`` + (AIP-14c D3). Identical hex to the TS twin's ``computeAgreementHash``. + + Returns: + ``0x`` + 64 lowercase hex chars. + + Raises: + InvalidAgreementError, UnsupportedAgreementVersionError + """ + canonical = serialize_agreement(agreement).encode("utf-8") + return "0x" + _keccak(canonical).hex() + + +# Alias (symmetry with the evidence-bundle ``bundle_hash``). +agreement_hash = compute_agreement_hash + + +__all__ = [ + "AGREEMENT_SCHEMA_VERSION", + "SUPPORTED_AGREEMENT_MAJOR", + "ZERO_AGREEMENT_HASH", + "InvalidAgreementError", + "UnsupportedAgreementVersionError", + "assert_supported_agreement_version", + "validate_agreement", + "serialize_agreement", + "compute_agreement_hash", + "agreement_hash", +] diff --git a/src/agirails/cli/commands/health.py b/src/agirails/cli/commands/health.py index 994c525..241ebfb 100644 --- a/src/agirails/cli/commands/health.py +++ b/src/agirails/cli/commands/health.py @@ -54,11 +54,10 @@ def _probe_endpoint(url: str, timeout_s: float) -> Dict[str, Any]: "response_time_ms": elapsed_ms, } except ImportError: - from urllib.request import Request, urlopen + from agirails.utils.http import request_http - req = Request(url, method=method) start = time.monotonic() - with urlopen(req, timeout=int(timeout_s)) as resp: + with request_http(url, method=method, timeout=timeout_s) as resp: elapsed_ms = int((time.monotonic() - start) * 1000) return { "reachable": True, diff --git a/src/agirails/cli/commands/negotiate.py b/src/agirails/cli/commands/negotiate.py index 1d0549b..ab93cba 100644 --- a/src/agirails/cli/commands/negotiate.py +++ b/src/agirails/cli/commands/negotiate.py @@ -236,10 +236,24 @@ async def _negotiate() -> None: ), ) + # F-5: best-effort read-only AgentRegistry so the orchestrator runs the + # pre-escrow price-band check before locking escrow. Fail-open — any + # failure (mock mode, no registry, RPC error) leaves it None and the + # guard is skipped, exactly as before. + agent_registry = None + if opts.mode in ("testnet", "mainnet"): + try: + from agirails.protocol.agent_registry import AgentRegistry + + agent_registry = await AgentRegistry.connect(network=opts.mode) + except Exception: + agent_registry = None + orchestrator = BuyerOrchestrator( policy=buyer_policy, runtime=client.runtime, requester_address=client.address, + agent_registry=agent_registry, ) # Progress callback for human mode diff --git a/src/agirails/cli/commands/tx.py b/src/agirails/cli/commands/tx.py index cfaa535..e625142 100644 --- a/src/agirails/cli/commands/tx.py +++ b/src/agirails/cli/commands/tx.py @@ -236,6 +236,7 @@ async def _transition() -> None: await client.standard.transition_state( tx_id=tx_id, new_state=new_state, + proof=proof, ) if opts.output_format == OutputFormat.JSON: diff --git a/src/agirails/cli/commands/watch.py b/src/agirails/cli/commands/watch.py index f699834..e8bfd15 100644 --- a/src/agirails/cli/commands/watch.py +++ b/src/agirails/cli/commands/watch.py @@ -248,7 +248,6 @@ def watch( mode=global_opts.mode, ) ) - raise typer.Exit(code=exit_code) except KeyboardInterrupt: if not global_opts.quiet: print_info("\nWatch stopped by user.") @@ -259,6 +258,8 @@ def watch( else: print_error(str(e)) raise typer.Exit(code=1) + else: + raise typer.Exit(code=exit_code) __all__ = ["watch", "run_watch"] diff --git a/src/agirails/client.py b/src/agirails/client.py index a315d7f..e2f36f2 100644 --- a/src/agirails/client.py +++ b/src/agirails/client.py @@ -153,6 +153,7 @@ def __init__( network_id: Optional[str] = None, erc8004_identity_registry_address: Optional[str] = None, pending_is_stale: bool = False, + dispute_client: Optional[object] = None, ) -> None: """ Initialize ACTPClient. @@ -196,6 +197,16 @@ def __init__( self._contract_addresses = contract_addresses self._reputation_reporter = reputation_reporter + # AIP-14b dispute facade (PRD P2-9). Present (non-None) only when the + # dispute contract addresses are configured for the network (Phase 6+); + # None on mock mode and pre-deployment networks, so existing flows are + # unaffected. Composes BondEscalation + CompositeMediator + + # EvaluatorClient + UMAHelper + DisputeSplitIndexer behind one object. + # PARITY: TS ``client.dispute`` (ACTPClient.ts). For the legacy + # single-shot kernel path see ``ACTPKernel.raise_dispute`` / + # ``resolve_dispute`` (their docstrings steer here). + self.dispute = dispute_client + # Lazy-publish state (consumed by get_activation_calls()). self._lazy_scenario = lazy_scenario self._pending_publish = pending_publish @@ -525,6 +536,38 @@ async def create( except Exception as exc: # pragma: no cover - best-effort _logger.warn(f"ReputationReporter wiring skipped: {exc}") + # AIP-14b DISPUTE FACADE (PRD P2-9): wire client.dispute ONLY when the + # dispute contracts are configured for this network. Addresses are None + # until Phase 6 (testnet) / later (mainnet), so on undeployed networks + # this stays None and existing flows are unchanged. Best-effort — a + # wiring failure must never block create(). Mirrors TS ACTPClient.create + # (present iff the dispute addresses are configured). + dispute_client: Optional[object] = None + if config.mode in ("testnet", "mainnet"): + try: + from agirails.config.networks import get_network as _get_network + + _net = _get_network( + network_id + or ("base-sepolia" if config.mode == "testnet" else "base-mainnet") + ) + _contracts = _net.contracts + if getattr(_contracts, "bond_escalation", None) and getattr( + _contracts, "composite_mediator", None + ): + from agirails.dispute.dispute_client import DisputeClient + + # runtime is a BlockchainRuntime on real networks; it exposes + # `.w3` and `.account` (blockchain_runtime.py:179-180). + _w3 = getattr(runtime, "w3", None) + _account = getattr(runtime, "account", None) + if _w3 is not None: + dispute_client = DisputeClient.from_config( + _w3, _account, _net + ) + except Exception as exc: # pragma: no cover - best-effort + _logger.warn(f"DisputeClient wiring skipped: {exc}") + # Staleness check (TS ACTPClient.ts:1088-1108): recompute the local # AGIRAILS.md hash; if it differs from the pending publish's configHash # the cached publish is stale, so lazy activation is skipped. Best-effort @@ -571,6 +614,7 @@ async def create( network_id=network_id, erc8004_identity_registry_address=erc8004_identity_registry_address, pending_is_stale=pending_is_stale, + dispute_client=dispute_client, ) # Drift detection: non-blocking AGIRAILS.md sync check on startup @@ -1246,8 +1290,93 @@ async def start_work(self, tx_id: str) -> None: return await self._runtime.transition_state(tx_id, "IN_PROGRESS") + @staticmethod + def _resolve_result_hash( + tx_id: str, + tx: Any, + *, + result: Any = None, + result_hash: Optional[Union[str, bytes]] = None, + ) -> bytes: + """ + Resolve the ``bytes32`` resultHash for the AIP-14c DELIVERED proof. + + Uses the SAME source as the AIP-4 delivery proof so the on-chain proof + binds to the exact deliverable (never a random hash). Resolution order: + + 1. An explicit ``result_hash`` (e.g. the AIP-16 ``envelopeHash``). + 2. A ``result`` payload, hashed via :func:`compute_result_hash` + (identical canonicalization to the delivery proof). + 3. The ``resultHash`` already recorded on the transaction's delivery + proof (when the provider wrote the AIP-4 proof before transitioning). + + There is NO synthetic fallback: a caller with NEITHER a ``result`` NOR + an explicit ``result_hash`` NOR a stored delivery proof fails closed + (raises) BEFORE any transition is sent. Parity with TS + ``assertRealResultHash`` — the delivery path never fabricates a hash. + + Returns: + Exactly 32 bytes. + + Raises: + ValueError: If no real result commitment can be resolved. + """ + + def _to_bytes32(value: Union[str, bytes]) -> bytes: + raw = ( + value + if isinstance(value, (bytes, bytearray)) + else bytes.fromhex(value[2:] if value.startswith(("0x", "0X")) else value) + ) + raw = bytes(raw) + if len(raw) != 32: + raise ValueError( + f"resultHash must be 32 bytes, got {len(raw)}" + ) + return raw + + if result_hash is not None: + return _to_bytes32(result_hash) + + if result is not None: + from agirails.types.message import compute_result_hash + + return _to_bytes32(compute_result_hash(result)) + + # Reuse the resultHash the provider already committed in the AIP-4 + # delivery proof, if present on the transaction. + stored_proof = getattr(tx, "delivery_proof", None) + if stored_proof: + import json as _json + + try: + parsed = _json.loads(stored_proof) + except (TypeError, ValueError): + parsed = None + if isinstance(parsed, dict): + rh = parsed.get("resultHash") or parsed.get("result_hash") + if rh: + try: + return _to_bytes32(rh) + except ValueError: + pass + + # AIP-14c: fail closed — a delivery path MUST commit to a REAL + # deliverable. There is NO synthetic txId-bound fallback. + raise ValueError( + "deliver() requires a real deliverable or an explicit resultHash: " + "pass result= (hashed via compute_result_hash) or " + "result_hash= (compute_result_hash(result) or the AIP-16 " + "envelope hash). Refusing to send DELIVERED without a result commitment." + ) + async def deliver( - self, tx_id: str, dispute_window_seconds: Optional[int] = None + self, + tx_id: str, + dispute_window_seconds: Optional[int] = None, + *, + result: Any = None, + result_hash: Optional[Union[str, bytes]] = None, ) -> None: """ Transition to DELIVERED (provider completes work). @@ -1257,9 +1386,22 @@ async def deliver( the tx is still COMMITTED, batches startWork + deliver in one UserOp. Mirrors TS ``ACTPClient.deliver`` (ACTPClient.ts:1507-1551). + AIP-14c (kernel v2): the DELIVERED proof MUST be the 64-byte + ``abi.encode(uint256 window, bytes32 resultHash)`` — a v2 kernel rejects + the legacy 32-byte window-only proof (``"Delivery proof must be + (window,resultHash)"``). ``resultHash`` comes from the SAME source as the + AIP-4 delivery proof (public: ``keccak256`` of the canonical plaintext + result; encrypted AIP-16: the envelope hash), so the on-chain proof binds + to the exact deliverable. + Args: tx_id: Transaction ID. dispute_window_seconds: Optional dispute-window override (seconds). + result: Optional deliverable payload — hashed via + :func:`compute_result_hash` (same canonicalization as the AIP-4 + delivery proof) to derive ``resultHash``. + result_hash: Optional pre-computed ``bytes32`` result hash (e.g. the + AIP-16 ``envelopeHash``). Takes precedence over ``result``. Raises: RuntimeError: If transaction not found, or DELIVERED step fails. @@ -1279,7 +1421,14 @@ async def deliver( if dispute_window_seconds is not None else tx.dispute_window ) - proof = "0x" + abi_encode(["uint256"], [int(effective_dispute_window)]).hex() + result_hash_bytes = self._resolve_result_hash( + tx_id, tx, result=result, result_hash=result_hash + ) + # AIP-14c 64-byte proof: abi.encode(uint256 window, bytes32 resultHash). + proof = "0x" + abi_encode( + ["uint256", "bytes32"], + [int(effective_dispute_window), result_hash_bytes], + ).hex() state_str = tx.state.value if hasattr(tx.state, "value") else str(tx.state) diff --git a/src/agirails/config/networks.py b/src/agirails/config/networks.py index 895b672..89a291f 100644 --- a/src/agirails/config/networks.py +++ b/src/agirails/config/networks.py @@ -108,6 +108,12 @@ class ContractAddresses: identity_registry: Optional[str] = None # AIP-7 (Sepolia only; ERC-1056 DID registry) x402_relay: Optional[str] = None # deprecated since SDK 3.3.0 (zero on mainnet V3) erc8004_identity_registry: Optional[str] = None # ERC-8004 canonical CREATE2 (same on all chains) + # AIP-14b three-tier dispute system (P2-2). None until the dispute stack is + # deployed: testnet lands in Phase 6, mainnet later. Keys mirror the TS SDK + # NetworkConfig.contracts (parity). + bond_escalation: Optional[str] = None # BondEscalation (Tier-1 bonded escalation + AIRuling verifier) + composite_mediator: Optional[str] = None # CompositeMediator (canonical 0/1/2 ruling → fund routing) + uma_optimistic_oracle_v3: Optional[str] = None # UMA OptimisticOracleV3 (Tier-2 optimistic oracle) @dataclass(frozen=True) @@ -168,6 +174,9 @@ def to_dict(self) -> Dict: "identityRegistry": self.contracts.identity_registry, "x402Relay": self.contracts.x402_relay, "erc8004IdentityRegistry": self.contracts.erc8004_identity_registry, + "bondEscalation": self.contracts.bond_escalation, + "compositeMediator": self.contracts.composite_mediator, + "umaOptimisticOracleV3": self.contracts.uma_optimistic_oracle_v3, }, "eas": { "deliverySchemaUID": self.eas.delivery_schema_uid, @@ -195,16 +204,27 @@ def to_dict(self) -> Dict: rpc_url=BASE_SEPOLIA_RPC_URL, block_explorer="https://sepolia.basescan.org", contracts=ContractAddresses( - actp_kernel="0x9d25A874f046185d9237Cd4954C88D2B74B0021b", - escrow_vault="0x7dF07327090efcA73DCBa70414aA3131Fc6d2efB", - usdc="0x444b4e1A65949AB2ac75979D5d0166Eb7A248Ccb", # MockUSDC + # AIP-14c kernel-v2 redeploy - 2026-07-13 (block 44093538). kernelVersion + # 0x6237ef5c... (ACTP_KERNEL_V2_AIP14C_REV2); runtime codehash 0xf42003e6... + # (== audited candidate). Supersedes the F-6 kernel 0xD8f7829c... (pre-v2). + actp_kernel="0xE8ba4133CC43bAb48c9c71bF82243e0b15915389", + escrow_vault="0x9d3CbD2c630E390F9179DAfE02Dd5dAd80B3A05B", + usdc="0x444b4e1A65949AB2ac75979D5d0166Eb7A248Ccb", # MockUSDC (unchanged) eas="0x4200000000000000000000000000000000000021", # Base native EAS eas_schema_registry="0x4200000000000000000000000000000000000020", - agent_registry="0xD91F9aBfBf60b4a2Fd5317ab0cDF3F44faB5D656", - archive_treasury="0x2eE4f7bE289fc9EFC2F9f2D6E53e50abDF23A3eb", + # NEW AgentRegistry bound to kernel-v2 (active on-chain after the 2-day + # executeAgentRegistryUpdate timelock, ~2026-07-15). + agent_registry="0x1bb1D4B0b84801FF8597d3e7988E00802252d962", + archive_treasury="0x415Ca522e1DfF9933ab5Eb7a8569B1879093324D", # v2, bound to kernel-v2 identity_registry="0xce9749c768b425fab0daa0331047d1340ec99a88", # AGIRAILSIdentityRegistry x402_relay="0x110b25bb3d45c40dfcf34bb451aa7069b2a1cb3b", # deprecated since SDK 3.3.0 erc8004_identity_registry="0x8004A818BFB912233c491871b3d84c89A494BD9e", + # AIP-14c dispute system (D7) - deployed 2026-07-13 against kernel-v2 (block 44093572). + # BondEscalation runtime codehash 0x9389b155... (Sepolia pin). Tier-2 uses a testnet + # MockOOV3 0x64C81e2F... Mediator resolver active after the 2-day timelock (~2026-07-15). + # Supersedes the pre-D7 stack (bond 0x62d5417B..., mediator 0xf8095f8d...). + bond_escalation="0x84CB23F1bCebC286270EE5E62A19a64686D3Ca0A", + composite_mediator="0x45a440a34303AEe597672C1D47d1ce83BEC8aD1C", ), eas=EASConfig( # Deployed 2025-11-23 - AIP-4 delivery proof schema @@ -214,7 +234,7 @@ def to_dict(self) -> Dict: max_fee_per_gas=2_000_000_000, # 2 gwei max_priority_fee_per_gas=1_000_000_000, # 1 gwei ), - actp_kernel_deployment_block=41_725_686, # V4 deploy on 2026-05-19 + actp_kernel_deployment_block=43_262_304, # 2026-06-24 F-6 redeploy aa=AAConfig( entry_point=ENTRYPOINT_V06, smart_wallet_factory=SMART_WALLET_FACTORY, diff --git a/src/agirails/dispute/__init__.py b/src/agirails/dispute/__init__.py new file mode 100644 index 0000000..b03096c --- /dev/null +++ b/src/agirails/dispute/__init__.py @@ -0,0 +1,193 @@ +""" +AGIRAILS dispute module — evidence-bundle canonical serializer (PRD P2-3). + +1:1 with the TypeScript SDK (`sdk-js/src/dispute/EvidenceBundle.ts`): same +public API names + arity, byte-identical canonical-bundle bytes + bundleHash. +""" + +from agirails.dispute.bond_escalation import ( + # Constants (AIP-14 §7.4) + ESCALATION_INITIAL_BPS, + MIN_ESCALATION_BOND, + MAX_ESCALATION_BOND, + ESCALATION_MULTIPLIER, + BPS_DENOMINATOR, + # Client (PRD P2-4) + BondEscalationClient, +) +from agirails.dispute.evidence_bundle import ( + # Constants + EVIDENCE_BUNDLE_SCHEMA_VERSION, + SUPPORTED_BUNDLE_MAJOR, + MAX_BUNDLE_TOKENS, + # Types + EvidenceBundle, + EvidenceBundleSpec, + EvidenceBundleDelivery, + EvidenceBundleDispute, + EvidenceBundleTimelineEvent, + EvidenceBundleReasoning, + PinEvidenceBundleResult, + EvidenceBundlePinner, + BundleTokenizer, + # Errors + BundleTooLargeError, + UnsupportedBundleVersionError, + InvalidBundleError, + # API + validate_bundle, + assert_supported_version, + serialize_bundle, + serialize_bundle_to_string, + bundle_hash, + compute_bundle_hash, + count_bundle_tokens, + enforce_token_cap, + set_bundle_tokenizer, + pin_evidence_bundle, +) +from agirails.dispute.evidence_artifact_v2 import ( + EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION, + assert_artifact_v2_version, + validate_evidence_artifact_v2, + serialize_artifact_v2, + serialize_artifact_v2_to_string, + compute_artifact_v2_hash, + count_artifact_v2_tokens, + UnsupportedArtifactVersionError, + InvalidArtifactError, +) +from agirails.dispute.composite_mediator import ( + # Types + DisputeSplitRecorded, + DecodedResolutionProof, + # Pure decoders / metrics (1:1 with TS standalone functions) + decode_dispute_split_recorded, + decode_resolution_proof, + compute_split_rate, + # Client (PRD P2-5) + CompositeMediator, +) +from agirails.dispute.uma_helper import ( + # Constants (AIP-14b §8.6 economics) + UMA_BOND, + SELF_DISPUTE_TOTAL, + SELF_DISPUTE_RECOVER, + SELF_DISPUTE_LOSS, + # Types + SelfDisputeCost, + # Helper (PRD P2-7) + UMAHelper, +) +from agirails.dispute.evaluator_client import ( + # Client (PRD P2-6) + EvaluatorClient, + # Config / params / result dataclasses + EvaluatorClientConfig, + EvaluatorPaymentClient, + RequestEvaluationParams, + EvaluationResult, + RulingVerification, + ProposeDirectlyRecommendation, + BundleSource, + # §4.7 verification (1:1 with TS standalone functions) + verify_ruling_signatures, + select_third_evaluator, + # Errors + EvaluatorClientError, + QuoteRejectedError, + EvaluateResponseError, +) +from agirails.dispute.dispute_client import ( + # Facade (PRD P2-9) + DisputeClient, + DisputeStatus, + DisputeSubState, + DISPUTE_SUBSTATES, + # §9 sub-state decode (1:1 with TS standalone function) + decode_dispute_sub_state, +) + +__all__ = [ + # Dispute facade (PRD P2-9) + "DisputeClient", + "DisputeStatus", + "DisputeSubState", + "DISPUTE_SUBSTATES", + "decode_dispute_sub_state", + # Off-chain dispute evaluator client (PRD P2-6) + "EvaluatorClient", + "EvaluatorClientConfig", + "EvaluatorPaymentClient", + "RequestEvaluationParams", + "EvaluationResult", + "RulingVerification", + "ProposeDirectlyRecommendation", + "BundleSource", + "verify_ruling_signatures", + "select_third_evaluator", + "EvaluatorClientError", + "QuoteRejectedError", + "EvaluateResponseError", + # UMA self-dispute DVM helper (PRD P2-7) + "UMA_BOND", + "SELF_DISPUTE_TOTAL", + "SELF_DISPUTE_RECOVER", + "SELF_DISPUTE_LOSS", + "SelfDisputeCost", + "UMAHelper", + # Composite mediator read/event client (PRD P2-5) + "DisputeSplitRecorded", + "DecodedResolutionProof", + "decode_dispute_split_recorded", + "decode_resolution_proof", + "compute_split_rate", + "CompositeMediator", + # Bond escalation client (PRD P2-4) + "ESCALATION_INITIAL_BPS", + "MIN_ESCALATION_BOND", + "MAX_ESCALATION_BOND", + "ESCALATION_MULTIPLIER", + "BPS_DENOMINATOR", + "BondEscalationClient", + "EVIDENCE_BUNDLE_SCHEMA_VERSION", + "SUPPORTED_BUNDLE_MAJOR", + "MAX_BUNDLE_TOKENS", + "EvidenceBundle", + "EvidenceBundleSpec", + "EvidenceBundleDelivery", + "EvidenceBundleDispute", + "EvidenceBundleTimelineEvent", + "EvidenceBundleReasoning", + "PinEvidenceBundleResult", + "EvidenceBundlePinner", + "BundleTokenizer", + "BundleTooLargeError", + "UnsupportedBundleVersionError", + "InvalidBundleError", + "validate_bundle", + "assert_supported_version", + "serialize_bundle", + "serialize_bundle_to_string", + "bundle_hash", + "compute_bundle_hash", + "count_bundle_tokens", + "enforce_token_cap", + "set_bundle_tokenizer", + "pin_evidence_bundle", + # Schema-2.0.0 evidence artifact (AIP-14c D5/D6) + "EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION", + "assert_artifact_v2_version", + "validate_evidence_artifact_v2", + "serialize_artifact_v2", + "serialize_artifact_v2_to_string", + "compute_artifact_v2_hash", + "count_artifact_v2_tokens", + "UnsupportedArtifactVersionError", + "InvalidArtifactError", +] + +from agirails.dispute.receipt_authorization import ( + ReceiptAuthorizationInput, ReceiptAuthorizer, receipt_authorization_typed_data, + authorize_payment_receipt, post_paid_evaluation, +) diff --git a/src/agirails/dispute/bond_escalation.py b/src/agirails/dispute/bond_escalation.py new file mode 100644 index 0000000..a76331d --- /dev/null +++ b/src/agirails/dispute/bond_escalation.py @@ -0,0 +1,565 @@ +# PARITY: sdk-js/src/dispute/BondEscalation.ts +# This file and its TypeScript twin MUST stay 1:1 — every public method here has +# a TS twin with the SAME name (camelCase) and arity, and vice-versa. The two +# quote helpers + get_dispute_state decode are anchored to the shared cross-SDK +# fixture `DISPUTE SYSTEM/test-vectors/bond-escalation-vectors.json`, which both +# the pytest and jest suites consume byte-identically. Any change here (rename, +# new method, formula tweak) must be mirrored in the twin. +""" +BondEscalationClient — typed wrapper for the AIP-14 three-tier dispute engine +(``BondEscalation.sol``). + +Wraps every method of the normative ``IBondEscalation`` core interface +(AIP-14 §7.1) plus the two bond-quote helpers and the on-chain ``disputes(...)`` +reader. This is the dispute counterpart to :class:`ACTPKernel` — it does NOT +touch the kernel's legacy ``raise_dispute``/``resolve_dispute`` (those settle +through the kernel's own SETTLED proof path; the tiered flow here is the AIP-14 +successor). + +Lifecycle (AIP-14 §3, §7.1):: + + open_dispute(tx_id) -> dispute_id + | + v (confident) (not confident) + submit_ai_ruling(ruling, sigs, evidence_cid, reasoning_cid) -- propose_directly(ruling, split) -- Tier 1 + | | + v challenge(...) (bond doubles, ceiling $500) + | + +--> finalize() (liveness expired) -> RESOLVED + +--> escalate_to_uma(cid) (at ceiling + active) -> Tier 2 (UMA) + | + sync_external_resolution() / force_resolve_stale() -------> RESOLVED + claim_escalation_refund() (split or no-winner UMA refunds, post-resolve) + +Reference: AIP-14 §7 (BondEscalation), §7.1 (IBondEscalation), §7.4 (constants), +§7.13 (bond formulas). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from eth_utils import keccak as _keccak + +from agirails.types.dispute import AIRuling, DisputeState, Ruling, Tier + +# --------------------------------------------------------------------------- +# Constants (AIP-14 §7.4) — load-bearing, mirror BondEscalation.sol + TS twin +# --------------------------------------------------------------------------- + +#: Initial bond rate: 2% of escrow (basis points). AIP-14 §7.4. +ESCALATION_INITIAL_BPS: int = 200 +#: Floor for the initial bond: $1 USDC (6 decimals). AIP-14 §7.4. +MIN_ESCALATION_BOND: int = 1_000_000 +#: Ceiling for any escalation bond: $500 USDC (6 decimals). AIP-14 §7.4. +MAX_ESCALATION_BOND: int = 500_000_000 +#: Each challenge doubles the bond. AIP-14 §7.4. +ESCALATION_MULTIPLIER: int = 2 +#: Basis-point denominator. +BPS_DENOMINATOR: int = 10_000 + + +def _load_abi() -> List[Dict[str, Any]]: + """Load the BondEscalation ABI from the abis directory.""" + abi_path = Path(__file__).parent.parent / "abis" / "bond_escalation.json" + with open(abi_path) as f: + return json.load(f) + + +def _to_bytes32(value: Union[str, bytes]) -> bytes: + """Normalize a bytes32 input (0x-hex string or raw bytes) to 32 bytes.""" + if isinstance(value, bytes): + raw = value + else: + s = value[2:] if value.startswith(("0x", "0X")) else value + raw = bytes.fromhex(s) + if len(raw) != 32: + raw = raw.rjust(32, b"\x00") + return raw + + +def _hex32(value: Union[str, bytes]) -> str: + """Normalize a bytes32 to a 0x-prefixed lowercase hex string.""" + return "0x" + _to_bytes32(value).hex() + + +class BondEscalationClient: + """ + Typed client for the AIP-14 BondEscalation dispute engine. + + Two construction paths (mirrors :class:`ReputationReporter`): + + - Production: pass ``contract`` (a web3 ``AsyncContract``) + ``account`` + + ``w3`` — write methods build calldata, sign, and broadcast. + - Testing: pass an injected ``contract`` whose functions record their args; + the client builds calldata via ``encode_abi`` so tests can assert the + exact selector + args (the same assertion surface as the TS twin). + + PARITY: BondEscalation.ts ``BondEscalationClient``. + """ + + def __init__( + self, + contract: Any, + *, + account: Any = None, + w3: Any = None, + address: Optional[str] = None, + confirmations: int = 2, + ) -> None: + if confirmations < 1: + raise ValueError(f"confirmations must be >= 1, got {confirmations}") + self._contract = contract + self._account = account + self._w3 = w3 + self._confirmations = confirmations + self._address = address or getattr(contract, "address", None) + + @classmethod + def from_config( + cls, + w3: Any, + account: Any, + config: Any, + *, + confirmations: int = 2, + ) -> "BondEscalationClient": + """ + Build a client from a network config (the ``bond_escalation`` address). + + PARITY: ``ACTPKernel.from_config`` (kernel.py). The dispute-contract + addresses are ``None`` until Phase-6 deployment, in which case this + raises — callers on undeployed networks must inject a contract directly. + """ + addr = getattr(config.contracts, "bond_escalation", None) + if not addr: + raise ValueError( + "BondEscalation is not deployed on this network " + "(config.contracts.bond_escalation is None)" + ) + contract = w3.eth.contract( + address=w3.to_checksum_address(addr), + abi=_load_abi(), + ) + return cls( + contract, + account=account, + w3=w3, + address=addr, + confirmations=confirmations, + ) + + # ------------------------------------------------------------------ + # Accessors (parity with the TS getAddress / getContract) + # ------------------------------------------------------------------ + + def get_address(self) -> Optional[str]: + """Deployed BondEscalation contract address.""" + return self._address + + def get_contract(self) -> Any: + """Underlying contract instance.""" + return self._contract + + # ------------------------------------------------------------------ + # Pure quote helpers (AIP-14 §7.13) — no chain access + # ------------------------------------------------------------------ + + @staticmethod + def quote_initial_bond(escrow_amount: int) -> int: + """ + Quote the initial Tier-1 bond: ``min(max(escrow_amount * 2%, $1), $500)``. + + Mirrors ``BondEscalation._calculateInitialBond`` and the TS + ``quoteInitialBond``, including the MAX_ESCALATION_BOND ($500) ceiling + the contract clamps to (F-5). AIP-14 §7.13. + + Args: + escrow_amount: Disputed escrow remaining (USDC, 6 decimals). + + Returns: + Initial bond in USDC base units (6 decimals), capped at $500. + """ + percent_bond = (escrow_amount * ESCALATION_INITIAL_BPS) // BPS_DENOMINATOR + bond = percent_bond if percent_bond > MIN_ESCALATION_BOND else MIN_ESCALATION_BOND + return bond if bond <= MAX_ESCALATION_BOND else MAX_ESCALATION_BOND + + @staticmethod + def quote_escalation_bond(current_bond: int) -> int: + """ + Quote the next challenge bond: ``min(current_bond * 2, $500)``. + + Mirrors the challenge bond rule + the TS ``quoteEscalationBond``. + AIP-14 §7.8 / §7.4. + + Args: + current_bond: The dispute's current bond (USDC, 6 decimals). + + Returns: + Next bond in USDC base units, capped at the $500 ceiling. + """ + nxt = current_bond * ESCALATION_MULTIPLIER + return MAX_ESCALATION_BOND if nxt > MAX_ESCALATION_BOND else nxt + + # ------------------------------------------------------------------ + # Read helper (decodes the public disputes() tuple) + # ------------------------------------------------------------------ + + async def get_dispute_state(self, dispute_id: str) -> DisputeState: + """ + Read + decode a dispute's on-chain state from ``disputes(bytes32)``. + + The raw getter returns the 14-field ``DisputeState`` storage struct + (AIP-14 §7.3); ``tier`` is decoded 0-based onto :class:`Tier`. PARITY: + TS ``getDisputeState``. + + Args: + dispute_id: keccak256 dispute identifier (bytes32 hex). + + Returns: + Decoded :class:`DisputeState`. + """ + raw = await self._contract.functions.disputes(_to_bytes32(dispute_id)).call() + return self.decode_dispute_state(dispute_id, raw) + + @staticmethod + def decode_dispute_state(dispute_id: str, raw: Any) -> DisputeState: + """ + Decode a raw ``disputes()`` tuple into a :class:`DisputeState`. + + Pure + static so the cross-SDK fixture test can exercise it without a + contract. Field order is load-bearing (AIP-14 §7.3): ``[transactionId, + currentRuling, splitBps, currentBond, accumulatedBonds, livenessEnd, + disputedAt, lastProposer, tier, resolved, winnerPaid, originalPool, + escrowAmount]``. PARITY: TS ``decodeDisputeState``. + """ + tx_id_raw = raw[0] + tx_id = ( + "0x" + tx_id_raw.hex() if isinstance(tx_id_raw, (bytes, bytearray)) else tx_id_raw + ) + current_ruling = int(raw[1]) + split_bps = int(raw[2]) + tier = int(raw[8]) + resolved = bool(raw[9]) + + return DisputeState( + tx_id=tx_id, + dispute_id=_hex32(dispute_id), + tier=tier, + ruling=current_ruling, + split_bps=split_bps, + resolved=resolved, + ) + + # ------------------------------------------------------------------ + # IBondEscalation write methods (AIP-14 §7.1) — identical sigs to TS twin + # ------------------------------------------------------------------ + + async def open_dispute(self, tx_id: str) -> Dict[str, str]: + """ + Open a dispute for a kernel tx already in the DISPUTED state. + + AIP-14 §7.5. Returns ``{"dispute_id", "eth_tx_hash"}``; ``dispute_id`` + is ``keccak256(abi.encode("ACTP_DISPUTE_V1", tx_id))`` (deterministic), + also surfaced via the ``DisputeOpened`` event. PARITY: TS ``openDispute``. + """ + receipt = await self._send("openDispute", [_to_bytes32(tx_id)]) + from eth_abi import encode as _abi_encode + + dispute_id = "0x" + _keccak( + _abi_encode(["string", "bytes32"], ["ACTP_DISPUTE_V1", _to_bytes32(tx_id)]) + ).hex() + return {"dispute_id": dispute_id, "eth_tx_hash": receipt} + + async def submit_ai_ruling( + self, + ruling: AIRuling, + signatures: List[Union[str, bytes]], + evidence_cid: str, + reasoning_cid: str, + ) -> Dict[str, str]: + """ + Submit an evaluator-signed AIRuling as the Tier-1 proposal. + + AIP-14c §7.7 / D7 (AIP14C-BOND-ABI-FREEZE.md). PARITY: TS + ``submitAIRuling``. Calls the FINAL 5-arg + ``submitAIRuling(disputeId, ruling, evidenceCID, reasoningCID, + signatures)`` (selector ``0xca74ab82``); the pre-D7 3-arg form is + removed on-chain. + + The evidence/reasoning CIDs travel alongside the ruling so the contract + recomputes ``evidenceRefHash`` / ``reasoningRefHash`` from them and + requires equality with the SIGNED refs before any bond transfer. The + submitted ruling tuple therefore carries refs derived from these SAME + CIDs (via :func:`compute_evidence_ref_hash` / + :func:`compute_reasoning_ref_hash`) — matching the 9-field ruling the + evaluator quorum signed. + + Args: + ruling: The :class:`AIRuling` (its ``dispute_id`` MUST match). + signatures: Evaluator EIP-712 signatures (``bytes[]``). + evidence_cid: IPFS CID of the canonical evidence bundle. + reasoning_cid: IPFS CID of the evaluator's reasoning. + """ + from agirails.types.dispute import ( + compute_evidence_ref_hash, + compute_reasoning_ref_hash, + ) + + # P2 HARDENING: the ref-hashes are part of the evaluator-SIGNED 9-field + # ruling. Recompute them from the CIDs and VERIFY they equal the signed + # refs — do NOT silently overwrite the ruling (that would ship the CIDs' + # refs under signatures that never covered them, and the on-chain quorum + # check would then reject the tx). Raise fail-closed on any mismatch. + expected_evidence_ref = compute_evidence_ref_hash(ruling.bundle_hash, evidence_cid) + expected_reasoning_ref = compute_reasoning_ref_hash( + ruling.reasoning_hash, reasoning_cid + ) + + def _norm(v: Optional[Union[str, bytes]]) -> Optional[str]: + if v is None: + return None + if isinstance(v, (bytes, bytearray)): + return "0x" + bytes(v).hex() + return v.lower() + + if _norm(ruling.evidence_ref_hash) != _norm(expected_evidence_ref): + raise ValueError( + "submit_ai_ruling: evidenceCID does not match the signed ruling — " + f"computed evidenceRefHash {expected_evidence_ref} != signed " + f"{ruling.evidence_ref_hash!r}. Refusing to submit " + "(signatures would be invalid on-chain)." + ) + if _norm(ruling.reasoning_ref_hash) != _norm(expected_reasoning_ref): + raise ValueError( + "submit_ai_ruling: reasoningCID does not match the signed ruling — " + f"computed reasoningRefHash {expected_reasoning_ref} != signed " + f"{ruling.reasoning_ref_hash!r}. Refusing to submit " + "(signatures would be invalid on-chain)." + ) + # Submit the ORIGINAL signed ruling unchanged (its refs are now verified). + tuple_arg = self._ai_ruling_to_tuple(ruling) + sigs = [_normalize_sig(s) for s in signatures] + receipt = await self._send( + "submitAIRuling", + [ + _to_bytes32(ruling.dispute_id), + tuple_arg, + evidence_cid, + reasoning_cid, + sigs, + ], + ) + return {"eth_tx_hash": receipt} + + async def propose_directly( + self, dispute_id: str, ruling: Union[Ruling, int], split_bps: int + ) -> Dict[str, str]: + """ + Submit a direct (unsigned) Tier-1 proposal. AIP-14 §7.6. + + PARITY: TS ``proposeDirectly``. + """ + receipt = await self._send( + "proposeDirectly", [_to_bytes32(dispute_id), int(ruling), int(split_bps)] + ) + return {"eth_tx_hash": receipt} + + async def challenge( + self, dispute_id: str, counter_ruling: Union[Ruling, int], counter_split_bps: int + ) -> Dict[str, str]: + """ + Counter an existing proposal with a different outcome + doubled bond. + + AIP-14 §7.8. PARITY: TS ``challenge``. + """ + receipt = await self._send( + "challenge", + [_to_bytes32(dispute_id), int(counter_ruling), int(counter_split_bps)], + ) + return {"eth_tx_hash": receipt} + + async def finalize(self, dispute_id: str) -> Dict[str, str]: + """ + Finalize a Tier-1 dispute after liveness expiry. AIP-14 §7.9. + + PARITY: TS ``finalize``. + """ + receipt = await self._send("finalize", [_to_bytes32(dispute_id)]) + return {"eth_tx_hash": receipt} + + async def escalate_to_uma( + self, dispute_id: str, evidence_cid: str, reasoning_cid: str + ) -> Dict[str, str]: + """ + Escalate a ceiling-bond, liveness-active dispute to UMA OOV3 (Tier 2), + embedding the IPFS evidence + reasoning CIDs. AIP-14 §7.1, §8.4. + + BLOCKER-2 (reasoning reaches the DVM): the v2 entrypoint is the 2-CID + ``escalateToUMA(disputeId, evidenceCID, reasoningCID)`` (selector + ``0xea487f8a``); the 1-CID form (``0xa3c23734``) is REMOVED. Both CIDs + are embedded in the UMA/DVM claim + the ``EscalatedToUMA`` event. + + PARITY: TS ``escalateToUMA``. + """ + receipt = await self._send( + "escalateToUMA", [_to_bytes32(dispute_id), evidence_cid, reasoning_cid] + ) + return {"eth_tx_hash": receipt} + + async def settle_uma_assertion(self, dispute_id: str) -> Dict[str, str]: + """ + Settle a Tier-2 UMA assertion back into BondEscalation once the DVM has + resolved: reads the OOV3 result and routes the resolved outcome to the + CompositeMediator. AIP-14 §8.2 STAGE 3. Callable by anyone + post-resolution. PARITY: TS ``settleUMAAssertion``. + """ + receipt = await self._send("settleUMAAssertion", [_to_bytes32(dispute_id)]) + return {"eth_tx_hash": receipt} + + async def retry_mediator_resolution(self, dispute_id: str) -> Dict[str, str]: + """ + Retry a mediator resolution left pending (e.g. the CompositeMediator call + reverted / ran out of gas during settlement). Drives + ``mediatorRetryPending[disputeId]`` to completion. AIP-14 §8.2. Not + pausable. PARITY: TS ``retryMediatorResolution``. + """ + receipt = await self._send( + "retryMediatorResolution", [_to_bytes32(dispute_id)] + ) + return {"eth_tx_hash": receipt} + + async def claim_escalation_refund(self, dispute_id: str) -> Dict[str, str]: + """ + Claim after a split or a UMA verdict with no Tier-1 winning proposer. + The latter preserves ruling 0/1; get_tier1_refundable exposes its flag. + The caller still needs an unclaimed deposit. + + AIP-14 §7.10. Not pausable. PARITY: TS ``claimEscalationRefund``. + """ + receipt = await self._send("claimEscalationRefund", [_to_bytes32(dispute_id)]) + return {"eth_tx_hash": receipt} + + async def get_tier1_refundable(self, dispute_id: str) -> bool: + """Additional no-winner UMA refund flag; splits do not need this flag. + + Unsupported legacy contracts and read failures propagate. + PARITY: TS getTier1Refundable. + """ + return bool(await self._contract.functions.tier1Refundable( + _to_bytes32(dispute_id) + ).call()) + + async def sync_external_resolution(self, dispute_id: str) -> Dict[str, str]: + """ + Sync a dispute already resolved in the kernel into BondEscalation. + + AIP-14 §7.11. Not pausable. PARITY: TS ``syncExternalResolution``. + """ + receipt = await self._send("syncExternalResolution", [_to_bytes32(dispute_id)]) + return {"eth_tx_hash": receipt} + + async def force_resolve_stale(self, dispute_id: str) -> Dict[str, str]: + """ + Force-resolve a dispute past MAX_DISPUTE_DURATION (30 days) to a 50/50 + split. AIP-14 §7.12. Not pausable. PARITY: TS ``forceResolveStale``. + """ + receipt = await self._send("forceResolveStale", [_to_bytes32(dispute_id)]) + return {"eth_tx_hash": receipt} + + # ------------------------------------------------------------------ + # Internals + # ------------------------------------------------------------------ + + @staticmethod + def _ai_ruling_to_tuple( + ruling: AIRuling, + ) -> Tuple[bytes, int, int, int, int, bytes, bytes, bytes, bytes]: + """ + Encode :class:`AIRuling` into the positional tuple the contract ABI + expects (struct field order is load-bearing — mirrors DisputeTypes.sol). + + AIP-14c: the struct is the 9-field type (``evidenceRefHash`` / + ``reasoningRefHash`` appended); these carry the D7 CID commitments the + on-chain ``submitAIRuling`` recomputes from the passed CIDs. + """ + return ( + _to_bytes32(ruling.dispute_id), + int(ruling.ruling), + int(ruling.confidence), + int(ruling.split_bps), + int(ruling.timestamp), + _to_bytes32(ruling.reasoning_hash), + _to_bytes32(ruling.bundle_hash), + _to_bytes32(ruling.evidence_ref_hash), + _to_bytes32(ruling.reasoning_ref_hash), + ) + + def encode_calldata(self, method: str, args: List[Any]) -> str: + """ + Build the 0x-hex calldata for ``method`` via ``encode_abi``. This is the + assertion surface the tests use (parity with the TS twin's + ``interface.encodeFunctionData``). + """ + return self._contract.encode_abi(abi_element_identifier=method, args=args) + + async def _send(self, method: str, args: List[Any]) -> str: + """ + Build calldata (validating the selector + args), then invoke the + contract function. Returns the tx-hash string. + + Test mocks supply a contract whose ``functions.(...)`` records + args and returns an awaitable; production wires through the web3 build / + sign / send path. Either way, calldata is built first so a malformed + call raises before broadcast. + """ + # Build + validate calldata first (assertion surface in tests). + self.encode_calldata(method, args) + + fn = getattr(self._contract.functions, method)(*args) + + # Production path: build, sign, broadcast via the injected account/w3. + if self._account is not None and self._w3 is not None: + nonce = await self._w3.eth.get_transaction_count( + self._account.address, "pending" + ) + tx = await fn.build_transaction( + {"from": self._account.address, "nonce": nonce} + ) + signed = self._w3.eth.account.sign_transaction(tx, self._account.key) + tx_hash = await self._w3.eth.send_raw_transaction(signed.raw_transaction) + await self._w3.eth.wait_for_transaction_receipt(tx_hash) + return "0x" + tx_hash.hex() if isinstance(tx_hash, (bytes, bytearray)) else str(tx_hash) + + # Test path: the mock fn exposes an awaitable returning a tx hash/receipt. + result = fn + send = getattr(result, "transact", None) + if send is not None: + tx_hash = await send() + else: + tx_hash = await result # fn itself is awaitable in mocks + if isinstance(tx_hash, (bytes, bytearray)): + return "0x" + tx_hash.hex() + return str(tx_hash) + + +def _normalize_sig(signature: Union[str, bytes]) -> bytes: + """Normalize a signature (0x-hex string or raw bytes) to bytes.""" + if isinstance(signature, (bytes, bytearray)): + return bytes(signature) + s = signature[2:] if signature.startswith(("0x", "0X")) else signature + return bytes.fromhex(s) + + +__all__ = [ + # Constants + "ESCALATION_INITIAL_BPS", + "MIN_ESCALATION_BOND", + "MAX_ESCALATION_BOND", + "ESCALATION_MULTIPLIER", + "BPS_DENOMINATOR", + # Client + "BondEscalationClient", +] diff --git a/src/agirails/dispute/composite_mediator.py b/src/agirails/dispute/composite_mediator.py new file mode 100644 index 0000000..dce089a --- /dev/null +++ b/src/agirails/dispute/composite_mediator.py @@ -0,0 +1,416 @@ +# PARITY: sdk-js/src/dispute/CompositeMediator.ts +# Keep the decode shape, split-rate semantics, and the "resolve is not public" +# rule 1:1 across both SDKs. +""" +CompositeMediator — read-only / event client for the AIP-14b split-outcome +mediator (PRD P2-5). + +The on-chain CompositeMediator (AIP-14b §6) is a *thin* contract: its ONLY +mutating entrypoint is ``resolve(txId, ruling, splitBps)``, and that function is +``onlyBondEscalation`` — it reverts for every caller except the BondEscalation +contract. There is therefore **no legitimate SDK action** that calls +``resolve()``; an agent or indexer can only *observe* what the mediator did. + +Accordingly this client exposes exactly two read surfaces: + 1. ``get_split_recorded_events()`` — pull ``DisputeSplitRecorded`` (every + ruling-2 resolution the mediator executed: finalize, force_resolve_stale — AIP-14b §3.4). + 2. ``decode_dispute_split_recorded(log)`` — pure decode of one such event. + +``resolve()`` is **deliberately ABSENT** from the public surface. See +:class:`CompositeMediator` docstring and the parity test +``tests/test_dispute/test_composite_mediator.py`` ("resolve is not a public +client method") for the normative assertion + rationale. + +UMA no-winner refunds preserve ruling 0/1 and are not split outcomes. + +ZERO-REMAINING CONSUMER RULE (AIP-14b §6, normative) +---------------------------------------------------- +When on-chain escrow ``remaining == 0``, the kernel resolution-proof amounts are +a phantom **1-wei sentinel** (placed only to satisfy the kernel's +``require(requesterAmount > 0 || providerAmount > 0)`` existence check) and are +NOT economic payouts. :func:`decode_resolution_proof` enforces this: with +``remaining == 0`` it surfaces a zero payout for BOTH parties — never a 1-wei +payout. The drained-dispute test pins this. + +PARITY: sdk-js/src/dispute/CompositeMediator.ts — every public symbol here has a +TS twin (same name/arity) and vice-versa. +""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Union + +from eth_abi import decode as _abi_decode + +# --------------------------------------------------------------------------- +# Decoded event shapes (1:1 with the TS interfaces) +# --------------------------------------------------------------------------- + + +@dataclass +class DisputeSplitRecorded: + """ + A decoded ``DisputeSplitRecorded(bytes32 indexed txId, address indexed + requester, address indexed provider, uint16 splitBps)`` event — the neutral + reputation trace CompositeMediator emits on every ruling-2 resolution + (AIP-14b §3.4). Carries NO on-chain penalty. + + PARITY: TS ``DisputeSplitRecorded`` interface. + """ + + tx_id: str + requester: str + provider: str + split_bps: int + block_number: Optional[int] = None + log_index: Optional[int] = None + transaction_hash: Optional[str] = None + + +@dataclass +class DecodedResolutionProof: + """ + Decoded kernel resolution proof, AFTER the zero-remaining consumer rule has + been applied. The amounts are the ECONOMICALLY REAL payouts — never a + phantom 1-wei sentinel. + + PARITY: TS ``DecodedResolutionProof`` interface. + + PARITY NOTE (representation differs — values match byte-for-byte under the + zero-remaining rule): this Py twin exposes FLAT ``requester_amount`` / + ``provider_amount`` ints; the TS twin exposes a NESTED + ``payouts: {{ requester, provider }}`` object. Field-access code is NOT + portable across SDKs — ``.requester_amount`` is Py-only; the TS twin reads + ``.payouts.requester``. This is a locked, documented per-SDK idiom (parity is + by type NAME, not field shape); there is no ``payouts`` object in Python. + + Attributes: + is_split: True when the kernel path was DISPUTED→CANCELLED. + provider_at_fault: SETTLED-branch flag (96-byte proof); ``None`` for the + CANCELLED/split branch (64-byte proof omits it). + requester_amount: real requester payout (0 when remaining == 0). + provider_amount: real provider payout (0 when remaining == 0). + phantom_sentinel: True when the proof amounts were ignored as a phantom + sentinel because remaining == 0 (AIP-14b §6). + """ + + is_split: bool + requester_amount: int + provider_amount: int + phantom_sentinel: bool + provider_at_fault: Optional[bool] = None + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _hex_str(value: Union[bytes, str]) -> str: + """Normalize a bytes/0x-hex value to a 0x-prefixed lowercase hex string.""" + if isinstance(value, bytes): + return "0x" + value.hex() + return value if value.startswith("0x") else "0x" + value + + +def _proof_to_bytes(proof: Union[bytes, str]) -> bytes: + """Normalize a proof (0x-hex string or raw bytes) to bytes.""" + if isinstance(proof, bytes): + return proof + s = proof[2:] if proof.startswith(("0x", "0X")) else proof + return bytes.fromhex(s) + + +# --------------------------------------------------------------------------- +# Pure decoders (no chain access — usable on a raw log) +# --------------------------------------------------------------------------- + + +def decode_dispute_split_recorded(log: Any) -> DisputeSplitRecorded: + """ + Decode a single ``DisputeSplitRecorded`` event log. + + Accepts a web3 ``LogReceipt`` / ``AttributeDict`` that already carries + decoded ``args`` (e.g. from ``contract.events.DisputeSplitRecorded() + .get_all_entries()`` or ``process_log``), mirroring how the TS twin accepts + an ethers ``EventLog``. PARITY: TS ``decodeDisputeSplitRecorded``. + + Raises: + ValueError: if the log is not a ``DisputeSplitRecorded`` event. + """ + event_name = log.get("event") if hasattr(log, "get") else getattr(log, "event", None) + if event_name is not None and event_name != "DisputeSplitRecorded": + raise ValueError( + f"decode_dispute_split_recorded: log is not a DisputeSplitRecorded " + f"event (got {event_name})" + ) + + args = log.get("args", {}) if hasattr(log, "get") else getattr(log, "args", {}) + if not args: + raise ValueError( + "decode_dispute_split_recorded: log carries no decoded args; pass a " + "processed event log (contract.events.DisputeSplitRecorded()...)." + ) + + def _get(key: str, default: Any = None) -> Any: + return args.get(key, default) if hasattr(args, "get") else getattr(args, key, default) + + tx_id = _get("txId", b"") + tx_hash = log.get("transactionHash") if hasattr(log, "get") else getattr(log, "transactionHash", None) + return DisputeSplitRecorded( + tx_id=_hex_str(tx_id), + requester=_get("requester", ""), + provider=_get("provider", ""), + split_bps=int(_get("splitBps", 0)), + block_number=(log.get("blockNumber") if hasattr(log, "get") else getattr(log, "blockNumber", None)), + log_index=(log.get("logIndex") if hasattr(log, "get") else getattr(log, "logIndex", None)), + transaction_hash=_hex_str(tx_hash) if isinstance(tx_hash, (bytes, str)) else tx_hash, + ) + + +def decode_resolution_proof( + proof: Union[bytes, str], + remaining: int, + *, escrow_principal: Optional[int] = None, +) -> DecodedResolutionProof: + """ + Decode a kernel resolution proof under the ZERO-REMAINING CONSUMER RULE + (AIP-14b §6). + + The CompositeMediator encodes two proof shapes (AIP-14b §6): + - SPLIT (CANCELLED): ``abi.encode(uint256 requesterAmount, + uint256 providerAmount)`` — 64 bytes + - SETTLE (SETTLED): ``abi.encode(uint256 requesterAmount, + uint256 providerAmount, bool providerAtFault)`` — 96 bytes + + When ``remaining == 0`` the prevailing party's amount field holds an **inert + 1-wei sentinel** placed solely to pass the kernel's + ``require(requesterAmount > 0 || providerAmount > 0)`` existence check. It is + never transferred (the kernel gates every move behind escrowPrincipal > 0). + This decoder therefore ZEROS both payouts when ``remaining == 0`` and sets + ``phantom_sentinel``. No 1-wei payout is ever surfaced. + PARITY: TS ``decodeResolutionProof``. + + Args: + proof: the raw proof bytes (0x-hex or bytes) passed to ``transitionState``. + remaining: legacy principal alias; fee-bearing raw balance requires explicit escrow_principal. + escrow_principal: kernel principal snapshot immediately before resolution. + + Raises: + ValueError: if neither principal snapshot nor legacy remaining is known. + """ + principal = remaining if escrow_principal is None else escrow_principal + if principal is None: + raise ValueError("Escrow principal is required to decode economic payouts") + raw = _proof_to_bytes(proof) + byte_len = len(raw) + + if byte_len == 96: + # SETTLED branch: (requesterAmount, providerAmount, providerAtFault) + req_amt, prov_amt, fault = _abi_decode(["uint256", "uint256", "bool"], raw) + is_split = False + provider_at_fault: Optional[bool] = bool(fault) + else: + # SPLIT/CANCELLED branch: (requesterAmount, providerAmount) — 64 bytes. + req_amt, prov_amt = _abi_decode(["uint256", "uint256"], raw) + is_split = True + provider_at_fault = None + + # ZERO-REMAINING CONSUMER RULE: proof amounts are a phantom sentinel — ignore. + if principal == 0: + return DecodedResolutionProof( + is_split=is_split, + requester_amount=0, + provider_amount=0, + phantom_sentinel=True, + provider_at_fault=provider_at_fault, + ) + + return DecodedResolutionProof( + is_split=is_split, + requester_amount=int(req_amt), + provider_amount=int(prov_amt), + phantom_sentinel=False, + provider_at_fault=provider_at_fault, + ) + + +def compute_split_rate( + split_recorded: int, + kernel_disputed_to_cancelled: int, + total_disputes: int, +) -> float: + """ + Compute the per-agent / global split rate over a set of resolved disputes + (AIP-14b §3.4, OQ-11 default). + + OQ-11 (normative default): the numerator counts BOTH + - ``DisputeSplitRecorded`` events (mediator-executed ruling-2), AND + - kernel ``DISPUTED → CANCELLED`` transitions (includes admin-CANCELLED), + at **identical weight**. Both are split outcomes for split-rate purposes. + + Args: + split_recorded: count of ``DisputeSplitRecorded`` events. + kernel_disputed_to_cancelled: count of kernel DISPUTED→CANCELLED transitions. + total_disputes: total disputes observed (denominator). + + Returns: + Split rate in ``[0, 1]``; ``0.0`` when ``total_disputes == 0``. + + PARITY: TS ``computeSplitRate``. + """ + if total_disputes <= 0: + return 0.0 + splits = split_recorded + kernel_disputed_to_cancelled + return splits / total_disputes + + +# --------------------------------------------------------------------------- +# Read-only client +# --------------------------------------------------------------------------- + + +class CompositeMediator: + """ + Read/event client for the on-chain CompositeMediator (AIP-14b §6). + + ``resolve()`` is intentionally not a method + --------------------------------------------- + The on-chain ``resolve(txId, ruling, splitBps)`` is guarded by + ``onlyBondEscalation`` — it reverts for any caller other than the + BondEscalation contract (AIP-14b §6: *"modifier onlyBondEscalation"*). There + is no signer an SDK user could hold that would let ``resolve()`` succeed, so + exposing it would be a footgun: every call would revert with + ``"Only tier system"``. Resolution is driven exclusively by the bond game + (finalize / force_resolve_stale / UMA callbacks inside BondEscalation), which + then calls the mediator internally. The SDK's job at the mediator boundary is + purely observational, so this client is **read-only**. The parity test + "resolve is not a public client method" pins this absence in both SDKs. + + PARITY: TS ``CompositeMediator`` class. + """ + + def __init__(self, contract: Any, address: str) -> None: + """ + Args: + contract: a web3 ``AsyncContract`` bound to the CompositeMediator ABI. + address: the on-chain CompositeMediator address. + """ + self.contract = contract + self.address = address + + @staticmethod + def _load_abi() -> List[Dict[str, Any]]: + """Load the CompositeMediator ABI from the abis directory.""" + abi_path = Path(__file__).parent.parent / "abis" / "composite_mediator.json" + with open(abi_path) as f: + return json.load(f) + + @classmethod + def from_config(cls, w3: Any, config: Any) -> "CompositeMediator": + """ + Create a CompositeMediator client from network configuration. + + PARITY: mirrors the ``new CompositeMediator(address, provider)`` ctor in + the TS twin (read-only; no signer required). + """ + address = w3.to_checksum_address(config.contracts.composite_mediator) + contract = w3.eth.contract(address=address, abi=cls._load_abi()) + return cls(contract, address) + + def get_address(self) -> str: + """Address of the on-chain CompositeMediator. PARITY: TS ``getAddress``.""" + return self.address + + def get_contract(self) -> Any: + """Underlying web3 contract (read-only surface). PARITY: TS ``getContract``.""" + return self.contract + + async def get_split_recorded_events( + self, + tx_id: Optional[str] = None, + requester: Optional[str] = None, + provider: Optional[str] = None, + from_block: Union[int, str] = "earliest", + to_block: Union[int, str] = "latest", + ) -> List[DisputeSplitRecorded]: + """ + Query historical ``DisputeSplitRecorded`` events. + + PARITY: TS ``getSplitRecordedEvents``. + """ + argument_filters: Dict[str, Any] = {} + if tx_id is not None: + argument_filters["txId"] = tx_id + if requester is not None: + argument_filters["requester"] = requester + if provider is not None: + argument_filters["provider"] = provider + + log_filter = await self.contract.events.DisputeSplitRecorded.create_filter( + from_block=from_block, + to_block=to_block, + argument_filters=argument_filters or None, + ) + logs = await log_filter.get_all_entries() + return [decode_dispute_split_recorded(log) for log in logs] + + def on_dispute_split_recorded( + self, + callback: Callable[[DisputeSplitRecorded], None], + poll_interval: float = 2.0, + ) -> Any: + """ + Subscribe to live ``DisputeSplitRecorded`` events. + + PARITY: TS ``CompositeMediator.onDisputeSplitRecorded``. The TS twin + returns an unsubscribe ``() => void``; the Py twin returns an + :class:`asyncio.Task` (the idiomatic async unsubscribe handle) — call + ``task.cancel()`` to stop watching. The callback receives a decoded + :class:`DisputeSplitRecorded` for each new event, exactly as the TS twin. + + Args: + callback: invoked with each decoded :class:`DisputeSplitRecorded`. + poll_interval: seconds between block-range polls (default 2.0). + """ + contract = self.contract + + async def _watch() -> None: + w3 = getattr(contract, "w3", None) or getattr(self, "_w3", None) + last_block = await w3.eth.block_number + while True: + try: + current_block = await w3.eth.block_number + if current_block > last_block: + log_filter = await contract.events.DisputeSplitRecorded.create_filter( + from_block=last_block + 1, + to_block=current_block, + ) + logs = await log_filter.get_all_entries() + for log in logs: + callback(decode_dispute_split_recorded(log)) + last_block = current_block + await asyncio.sleep(poll_interval) + except asyncio.CancelledError: + break + except Exception: + await asyncio.sleep(poll_interval) + + return asyncio.create_task(_watch()) + + +__all__ = [ + # Types + "DisputeSplitRecorded", + "DecodedResolutionProof", + # Pure decoders / metrics (1:1 with TS standalone functions) + "decode_dispute_split_recorded", + "decode_resolution_proof", + "compute_split_rate", + # Client + "CompositeMediator", +] diff --git a/src/agirails/dispute/dispute_client.py b/src/agirails/dispute/dispute_client.py new file mode 100644 index 0000000..c66ea9d --- /dev/null +++ b/src/agirails/dispute/dispute_client.py @@ -0,0 +1,367 @@ +"""DisputeClient — the SINGLE facade over the AIP-14b three-tier dispute system +(PRD P2-9). + +PARITY: sdk-js/src/dispute/DisputeClient.ts — every public symbol here +(``DisputeClient`` + its methods/properties, ``DisputeSubState``, +``DisputeStatus``, ``decode_dispute_sub_state``) has a TS twin with the SAME name +(camelCase there) and arity, and vice-versa. The §9 sub-state decode is anchored +to the shared cross-SDK fixture +``DISPUTE SYSTEM/test-vectors/dispute-client-status-vectors.json``, which both the +jest and pytest suites consume byte-identically and from which both derive the +SAME sub-state string. Any change here (rename, new method, decode tweak) must be +mirrored in the twin. + +It composes the five M1.5 dispute primitives behind one object so an agent +touches one surface instead of five: + +============== =========================== ===================================== +Property Underlying client Role (AIP-14b) +============== =========================== ===================================== +``bond`` :class:`BondEscalationClient` Tier-1 bond game + lifecycle (§7) +``mediator`` :class:`CompositeMediator` split-trace reads/decoders (§3.4, §6) +``evaluator`` :class:`EvaluatorClient` Tier-0 off-chain AI handshake (§4) +``uma`` :class:`UMAHelper` Tier-2 requester self-dispute (§8.6) +``split_indexer`` :class:`DisputeSplitIndexer` per-agent split-rate (§3.4, OQ-11) +============== =========================== ===================================== + +Each sub-client is OPTIONAL: the facade is usable with only the pieces a caller +configured. Properties raise a clear error when the corresponding piece was not +configured, rather than silently no-oping. + +The facade adds exactly ONE piece of net-new logic over the primitives: +:meth:`get_dispute_status`, which reads the on-chain dispute and decodes the §9 +sub-state (UNINITIALIZED / OPENED / PROPOSED / ESCALATED / RESOLVED) — the single +decode that both SDKs MUST agree on byte-for-byte. Everything else is pure +delegation. + +Relationship to the legacy kernel dispute path +---------------------------------------------- +``ACTPKernel.raise_dispute`` / ``resolve_dispute`` are the PRE-AIP-14 single-shot +kernel path. The tiered flow reached through THIS client is their AIP-14b +successor: ``raise_dispute`` still opens the kernel DISPUTED state, but resolution +then runs through the bond game here (open → propose/AI → challenge → finalize / +escalate_to_uma) instead of a privileged ``resolve_dispute``. The kernel +docstrings steer callers here (grep ``DisputeClient`` in ``protocol/kernel.py``). + +Reference: AIP-14b §3 (architecture), §7 (BondEscalation), §9 (state machine), +PRD P2-9. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, List, Optional + +from agirails.dispute.bond_escalation import BondEscalationClient +from agirails.dispute.composite_mediator import CompositeMediator +from agirails.dispute.evaluator_client import EvaluatorClient, EvaluatorClientConfig +from agirails.dispute.uma_helper import UMAHelper +from agirails.reputation.dispute_split_indexer import ( + DisputeOutcome, + DisputeSplitIndexer, +) +from agirails.types.dispute import Ruling, _to_bytes32 # type: ignore[attr-defined] + +# PARITY: sdk-js/src/dispute/DisputeClient.ts + +# ===================================================================== +# §9 sub-state model +# ===================================================================== + +#: The AIP-14b §9 dispute sub-state, decoded from the on-chain ``disputes(...)`` +#: struct. PARITY: TS ``DisputeSubState`` (string-literal values identical): +#: ``"UNINITIALIZED" | "OPENED" | "PROPOSED" | "ESCALATED" | "RESOLVED"``. +DisputeSubState = str + +#: The exhaustive set of §9 sub-states (for validation / parity assertions). +DISPUTE_SUBSTATES = ( + "UNINITIALIZED", + "OPENED", + "PROPOSED", + "ESCALATED", + "RESOLVED", +) + + +@dataclass +class DisputeStatus: + """Result of :meth:`DisputeClient.get_dispute_status`: the decoded + :class:`DisputeState` PLUS the §9 sub-state and the raw ``disputed_at`` + timestamp (0 ⇒ never opened). PARITY: TS ``DisputeStatus``. + + Attributes: + dispute_id: keccak256 dispute identifier (bytes32 hex). + substate: the §9 sub-state (the single cross-SDK decode). + tier: current escalation tier (0/1/2). + resolved: whether the dispute is finalized on-chain. + ruling: current/final ruling (0=provider, 1=requester, 2=split). + split_bps: provider share in bps (meaningful for ``ruling == 2``). + disputed_at: ``disputedAt`` from the struct (0 ⇒ never opened). + state: the base decoded :class:`DisputeState`. + """ + + dispute_id: str + substate: DisputeSubState + tier: int + resolved: bool + ruling: int + split_bps: int + disputed_at: int + state: Any + + +def _pick(raw: Any, idx: int, name: str) -> Any: + """Read a field from a raw ``disputes()`` tuple by name (named result) or + positional index (plain list/tuple). Mirrors the TS ``pick`` closure.""" + # Named-result access (web3 AttributeDict / namedtuple) — best effort. + try: + if isinstance(raw, dict): + if name in raw: + return raw[name] + else: + val = getattr(raw, name, None) + if val is not None: + return val + except Exception: # pragma: no cover - defensive + pass + return raw[idx] + + +def decode_dispute_sub_state(raw: Any) -> DisputeSubState: + """Decode the AIP-14b §9 sub-state from a raw ``disputes(bytes32)`` tuple. + + Pure so the cross-SDK fixture test exercises it without a chain. The tuple + field order is load-bearing (AIP-14b §7.3): ``[transactionId, currentRuling, + splitBps, currentBond, accumulatedBonds, livenessEnd, disputedAt, + lastProposer, tier, resolved, winnerPaid, originalPool, escrowAmount]``. + + Decode order is load-bearing (each branch mutually exclusive in priority): + 1. ``disputed_at == 0`` -> ``UNINITIALIZED`` (never opened — FIRST). + 2. ``resolved is True`` -> ``RESOLVED`` (dominates tier). + 3. ``tier == 2`` -> ``ESCALATED``. + 4. ``tier == 1`` -> ``PROPOSED`` (challenge keeps tier==1, so no + separate CHALLENGED). + 5. else (``tier == 0``) -> ``OPENED``. + + PARITY: TS ``decodeDisputeSubState`` — identical branch order + outputs + (anchored to ``dispute-client-status-vectors.json``). + """ + disputed_at = int(_pick(raw, 6, "disputedAt")) + tier = int(_pick(raw, 8, "tier")) + resolved = bool(_pick(raw, 9, "resolved")) + + if disputed_at == 0: + return "UNINITIALIZED" + if resolved: + return "RESOLVED" + if tier == 2: + return "ESCALATED" + if tier == 1: + return "PROPOSED" + return "OPENED" + + +# ===================================================================== +# Facade +# ===================================================================== + + +class DisputeClient: + """The one-object dispute facade (PRD P2-9). See the module docstring for the + table of sub-clients. Wired onto :class:`ACTPClient` as ``client.dispute`` iff + the dispute contract addresses are configured for the network. + + Two construction styles: + - Pass already-built sub-clients (``bond`` / ``mediator`` / ``uma`` / + ``evaluator`` / ``split_indexer``) — the unit-test / DI path. + - Use :meth:`from_config` to build the on-chain clients from + ``(w3, account, config)`` (the ACTPClient wiring path). + + PARITY: TS ``DisputeClient``. + """ + + def __init__( + self, + *, + bond: Optional[BondEscalationClient] = None, + mediator: Optional[CompositeMediator] = None, + uma: Optional[UMAHelper] = None, + evaluator: Optional[EvaluatorClient] = None, + evaluator_config: Optional[EvaluatorClientConfig] = None, + split_indexer: Optional[DisputeSplitIndexer] = None, + ) -> None: + self._bond = bond + self._mediator = mediator + self._uma = uma + if evaluator is not None: + self._evaluator: Optional[EvaluatorClient] = evaluator + elif evaluator_config is not None: + self._evaluator = EvaluatorClient(evaluator_config) + else: + self._evaluator = None + # The split indexer is ALWAYS present (pure accumulator). + self._split_indexer = split_indexer or DisputeSplitIndexer() + + # ------------------------------------------------------------------ + # Factory (parity with the per-primitive from_config classmethods) + # ------------------------------------------------------------------ + + @classmethod + def from_config( + cls, + w3: Any, + account: Any, + config: Any, + *, + confirmations: int = 2, + ) -> "DisputeClient": + """Build a facade from a network config, wiring whichever on-chain + clients have a configured address. Mirrors the TS facade's address-path + constructor + the per-primitive ``from_config`` classmethods. Pieces with + a ``None`` address are left unconfigured (their property raises on use). + + PARITY: TS ``new DisputeClient({signer, ...addresses})`` in + ``ACTPClient.create`` — present iff the dispute addresses are configured. + """ + contracts = config.contracts + bond = None + mediator = None + uma = None + + if getattr(contracts, "bond_escalation", None): + bond = BondEscalationClient.from_config( + w3, account, config, confirmations=confirmations + ) + if getattr(contracts, "composite_mediator", None): + mediator = CompositeMediator.from_config(w3, config) + # UMA helper needs all three addresses; from_config raises otherwise. + if ( + getattr(contracts, "bond_escalation", None) + and getattr(contracts, "uma_optimistic_oracle_v3", None) + and getattr(contracts, "usdc", None) + ): + try: + uma = UMAHelper.from_config( + w3, account, config, confirmations=confirmations + ) + except Exception: + uma = None + + return cls(bond=bond, mediator=mediator, uma=uma) + + # ------------------------------------------------------------------ + # Sub-client properties (raise a clear error when not configured) + # ------------------------------------------------------------------ + + @property + def bond(self) -> BondEscalationClient: + """The Tier-1 :class:`BondEscalationClient`. Raises if not configured.""" + if self._bond is None: + raise RuntimeError( + "DisputeClient.bond is not configured (no BondEscalation " + "address/account/contract). The dispute contracts are not " + "deployed on this network yet, or you constructed the facade " + "without a BondEscalation piece." + ) + return self._bond + + @property + def mediator(self) -> CompositeMediator: + """The :class:`CompositeMediator` split-trace read client. Raises if not + configured.""" + if self._mediator is None: + raise RuntimeError( + "DisputeClient.mediator is not configured (no CompositeMediator " + "address/provider)." + ) + return self._mediator + + @property + def uma(self) -> UMAHelper: + """The Tier-2 :class:`UMAHelper`. Raises if not configured.""" + if self._uma is None: + raise RuntimeError( + "DisputeClient.uma is not configured (needs BondEscalation + UMA " + "OOV3 + USDC addresses + account)." + ) + return self._uma + + @property + def evaluator(self) -> EvaluatorClient: + """The Tier-0 off-chain :class:`EvaluatorClient`. Raises if not + configured.""" + if self._evaluator is None: + raise RuntimeError( + "DisputeClient.evaluator is not configured (pass evaluator or " + "evaluator_config with a base_url + payment_client)." + ) + return self._evaluator + + @property + def split_indexer(self) -> DisputeSplitIndexer: + """The :class:`DisputeSplitIndexer` — always present (pure accumulator).""" + return self._split_indexer + + def has_bond(self) -> bool: + """True when the Tier-1 bond client is configured. PARITY: TS ``hasBond``.""" + return self._bond is not None + + def has_mediator(self) -> bool: + """True when the mediator read client is configured. PARITY: TS + ``hasMediator``.""" + return self._mediator is not None + + def has_uma(self) -> bool: + """True when the UMA helper is configured. PARITY: TS ``hasUMA``.""" + return self._uma is not None + + def has_evaluator(self) -> bool: + """True when the off-chain evaluator client is configured. PARITY: TS + ``hasEvaluator``.""" + return self._evaluator is not None + + # ------------------------------------------------------------------ + # The one net-new facade method: §9 sub-state + # ------------------------------------------------------------------ + + async def get_dispute_status(self, dispute_id: str) -> DisputeStatus: + """Read a dispute's on-chain state and decode its AIP-14b §9 sub-state. + + Reads the public ``disputes(bytes32)`` getter via the configured + :class:`BondEscalationClient`, then derives the sub-state with the pure + :func:`decode_dispute_sub_state` (anchored to the cross-SDK golden + fixture). The returned :class:`DisputeStatus` also carries the base + :class:`DisputeState` and the raw ``disputed_at``. PARITY: TS + ``getDisputeStatus``. + + Args: + dispute_id: keccak256 dispute identifier (bytes32 hex). + + Raises: + RuntimeError: if the bond client is not configured (dispute stack not + deployed). + """ + bond = self.bond # raises with the clear message if unconfigured + raw = await bond.get_contract().functions.disputes( + _to_bytes32(dispute_id) + ).call() + state = BondEscalationClient.decode_dispute_state(dispute_id, raw) + substate = decode_dispute_sub_state(raw) + disputed_at = int(_pick(raw, 6, "disputedAt")) + return DisputeStatus( + dispute_id=dispute_id, + substate=substate, + tier=state.tier, + resolved=state.resolved, + ruling=state.ruling if state.ruling is not None else int(Ruling.PROVIDER_WINS), + split_bps=state.split_bps if state.split_bps is not None else 0, + disputed_at=disputed_at, + state=state, + ) + + def record_outcomes(self, outcomes: List[DisputeOutcome]) -> None: + """Feed already-decoded :class:`DisputeOutcome` records to the split + indexer. Pure delegation to :meth:`DisputeSplitIndexer.add_outcomes`. + PARITY: TS ``recordOutcomes``. + """ + self._split_indexer.add_outcomes(outcomes) diff --git a/src/agirails/dispute/evaluator_client.py b/src/agirails/dispute/evaluator_client.py new file mode 100644 index 0000000..e27f1f0 --- /dev/null +++ b/src/agirails/dispute/evaluator_client.py @@ -0,0 +1,677 @@ +# PARITY: sdk-js/src/dispute/EvaluatorClient.ts +# This file and its TypeScript twin MUST stay 1:1 — every public symbol here +# (EvaluatorClient + its methods, the request/result dataclasses, +# verify_ruling_signatures, select_third_evaluator, the error classes) has a TS +# twin with the SAME name (camelCase there, snake_case here) and arity, and +# vice-versa. The §4.7 signature-verification math and the two-phase handshake +# step order are anchored to the shared cross-SDK fixture +# `DISPUTE SYSTEM/test-vectors/evaluator-client-vectors.json`, which both the +# pytest and jest suites consume byte-identically and from which both recover the +# SAME signer addresses. Any change here (rename, new method, verification tweak) +# must be mirrored in the twin. +""" +EvaluatorClient — the SDK half of the off-chain dispute-evaluator handshake +(PRD P2-6). Targets the FROZEN wire contract +``services/dispute-evaluator/API-CONTRACT.md`` and the AIP-14 FINAL §4.7 +2/3-signature verification spec. + +It performs the two-phase x402 quote handshake against the evaluator service:: + + STEP 0 DECLARE client -> POST /quote {bundleHash, declaredTokenCount, ...} (no money, no LLM) + STEP 1 QUOTE server -> 402 {quote, x402 commit (bundleHash,payer,disputeNonce)} + STEP 2 PAY client -> x402 facilitator (USDC on Base, via the existing X402Adapter buyer stack) + STEP 3 VERIFY server: receipt valid + settled + SINGLE-USE + identity-bound -> CONSUME atomically + STEP 4 RUN server: 3-eval + 3-screen ensemble (service-internal) + STEP 5 RETURN server -> 200 signed AIRuling(s) OR proposeDirectly recommendation + +The payment leg (STEP 2) is delegated to the EXISTING x402 buyer stack +(:class:`agirails.adapters.x402_adapter.X402Adapter`): its ``pay()`` POSTs to +``/evaluate``, transparently consumes the server's own 402, signs the +EIP-3009/Permit2 authorization, retries, and returns the settled 200 response. +This client never re-implements x402 — it passes the ``/evaluate`` body through +the adapter and parses the returned response body. + +After receiving an ``outcome="signed"`` response, the client REPLICATES the +on-chain ``_verifyEvaluatorSignatures`` logic (§4.7) client-side using the FROZEN +:func:`recover_ruling_signer`: it independently recovers each signer, matches it +against ``[fixed_evaluators[0], fixed_evaluators[1], third_evaluator]``, counts +each once (duplicates ignored, unknown signers ignored), enforces freshness, and +requires ``valid_count >= 2``. It does NOT trust the server's advisory +``evaluators[]``. If the response is ``outcome="proposeDirectly"`` OR the signed +response fails §4.7, the client returns a ``proposeDirectly`` recommendation with +NO signatures — it NEVER fabricates a signature and NEVER submits on-chain +(the caller does that via :class:`BondEscalationClient`). + +Reference: API-CONTRACT.md §3–§4; AIP-14 FINAL §4.7 (verification), §4.5 (domain), +§7.6 (proposeDirectly); INV-16 (2/3 valid sigs), INV-21 (AI never final). +""" + +from __future__ import annotations + +import json +import time +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any, Awaitable, Dict, List, Optional, Protocol, Sequence, Union + +from eth_abi import encode as _abi_encode +from eth_utils import keccak as _keccak + +from agirails.adapters.x402_adapter import X402PayParams +from agirails.dispute.payment_quote import accepted_quote_terms +from agirails.dispute.evidence_bundle import ( + EvidenceBundle, + bundle_hash as compute_bundle_hash, + count_bundle_tokens, + serialize_bundle_to_string, +) +from agirails.types.dispute import AIRuling, Ruling, Tier, recover_ruling_signer + + +# --------------------------------------------------------------------------- +# Wire / config dataclasses (API-CONTRACT.md §2, §3, §4) +# --------------------------------------------------------------------------- + + +@dataclass +class BundleSource: + """How the server obtains the evidence bundle (API-CONTRACT.md §3.1). + + Exactly one of ``cid`` / ``inline_bytes_b64`` should be set. + """ + + cid: Optional[str] = None + inline_bytes_b64: Optional[str] = None + + def to_wire(self) -> Dict[str, Any]: + """Serialize to the camelCase ``bundleSource`` wire object.""" + out: Dict[str, Any] = {} + if self.cid is not None: + out["cid"] = self.cid + if self.inline_bytes_b64 is not None: + out["inlineBytesB64"] = self.inline_bytes_b64 + return out + + +@dataclass +class RequestEvaluationParams: + """Inputs to :meth:`EvaluatorClient.request_evaluation`. + + ``bundle`` is the logical :class:`EvidenceBundle`; the client derives + ``bundleHash`` and ``tokenCount`` from the FROZEN serializer (it never trusts + a caller-supplied hash). + """ + + bundle: EvidenceBundle + dispute_id: str + payer: str + escrow_amount: str + tier: Union[Tier, int] + bundle_source: BundleSource + chain_id: int + verifying_contract: str + fixed_evaluators: Sequence[str] + rotating_pool: Sequence[str] + freshness_seconds: int = 3600 + + +@dataclass +class ProposeDirectlyRecommendation: + """A non-binding ``proposeDirectly`` recommendation (API-CONTRACT.md §4.3b).""" + + ruling: Union[Ruling, int] + split_bps: int + confidence: int + rationale: str + + +@dataclass +class RulingVerification: + """Result of replicating the §4.7 ``_verifyEvaluatorSignatures`` logic client-side.""" + + valid: bool + valid_count: int + recovered_signers: List[str] + third_evaluator: str + stale: bool + + +@dataclass +class EvaluationResult: + """Discriminated result of :meth:`EvaluatorClient.request_evaluation`. + + - ``outcome == "signed"`` — 2/3 §4.7 verification PASSED. Carries the FROZEN + :class:`AIRuling` + the 2–3 verified signatures the caller submits via + ``BondEscalationClient.submit_ai_ruling``. The SDK has already re-recovered + the signers; ``verification`` records the §4.7 result. + - ``outcome == "proposeDirectly"`` — either the server returned a + recommendation, OR a signed response FAILED §4.7 (insufficient valid sigs / + stale). NO signatures are surfaced; the caller may call + ``BondEscalationClient.propose_directly`` themselves. The SDK NEVER + fabricates a signature here. + """ + + outcome: str # "signed" | "proposeDirectly" + token_count: Optional[int] = None + reasoning: Optional[str] = None + # signed-only + ruling: Optional[AIRuling] = None + signatures: Optional[List[str]] = None + verification: Optional[RulingVerification] = None + # proposeDirectly-only + recommendation: Optional[ProposeDirectlyRecommendation] = None + reason: Optional[str] = None # "server-recommended" | "verification-failed" + + +class EvaluatorPaymentClient(Protocol): + """Minimal x402 buyer surface this client REUSES for STEP 2. + + The existing :class:`agirails.adapters.x402_adapter.X402Adapter` satisfies + this structurally — its ``pay(params)`` POSTs to the URL, transparently + handles the server 402 (sign + retry), and returns a result whose + ``.response`` is the settled HTTP response. Tests inject a stub exposing the + same shape. + """ + + def pay(self, params: Any) -> Awaitable[Any]: # pragma: no cover - protocol + ... + + +@dataclass +class EvaluatorClientConfig: + """Configuration for :class:`EvaluatorClient`.""" + + base_url: str + #: The x402 buyer used for STEP 2 — typically the SDK's ``X402Adapter``. + payment_client: EvaluatorPaymentClient + #: Async callable for the no-money STEP-0 ``/quote`` declare. Signature: + #: ``async (url, *, method, headers, body) -> _HttpResponse``. Injected in + #: tests to mock the HTTP endpoint; defaults to an httpx-backed POST. + fetch_impl: Optional[Any] = None + #: Body-level contract version (API-CONTRACT.md §1). Default ``"1.0.0"``. + api_version: str = "1.0.0" + + +# --------------------------------------------------------------------------- +# Errors (frozen names — 1:1 with the TS twin) +# --------------------------------------------------------------------------- + + +class EvaluatorClientError(Exception): + """Base class for evaluator-client errors.""" + + +class QuoteRejectedError(EvaluatorClientError): + """The ``/quote`` declare did not return the expected 402 quote. + + Attributes: + status: HTTP status returned instead of 402. + code: the frozen ``error.code`` from the §3.3 envelope, if present. + """ + + def __init__(self, status: int, code: Optional[str] = None, message: Optional[str] = None): + self.status = status + self.code = code + super().__init__( + f"Evaluator /quote rejected (HTTP {status}" + + (f", code={code}" if code else "") + + ")" + + (f": {message}" if message else "") + ) + + +class EvaluateResponseError(EvaluatorClientError): + """The ``/evaluate`` response was malformed or absent.""" + + def __init__(self, message: str): + super().__init__(f"Evaluator /evaluate response invalid: {message}") + + +# --------------------------------------------------------------------------- +# §4.7 third-evaluator selection (mirrors BondEscalation.sol + the TS twin) +# --------------------------------------------------------------------------- + + +def select_third_evaluator( + dispute_id: str, rotating_pool: Sequence[str] +) -> Optional[str]: + """Select the rotating third evaluator for a dispute (§4.7 step 4). + + ``rotatingPool[uint256(keccak256(abi.encode(disputeId))) % len]``. ``abi.encode`` + of a single ``bytes32`` is the 32-byte value itself, so we keccak the raw 32 + bytes. Returns ``None`` when the pool is empty. + + Args: + dispute_id: bytes32hex dispute id. + rotating_pool: the rotating evaluator addresses. + """ + if not rotating_pool: + return None + encoded = _abi_encode(["bytes32"], [_to_bytes32(dispute_id)]) + idx = int.from_bytes(_keccak(encoded), "big") % len(rotating_pool) + return rotating_pool[idx] + + +def verify_ruling_signatures( + ruling: AIRuling, + signatures: Sequence[str], + *, + chain_id: int, + verifying_contract: str, + fixed_evaluators: Sequence[str], + rotating_pool: Sequence[str], + now: Optional[int] = None, + freshness_seconds: int = 3600, +) -> RulingVerification: + """Replicate the on-chain ``_verifyEvaluatorSignatures`` logic (§4.7) client-side. + + Steps (§4.7): + 1. require ``2 <= len(signatures) <= 3`` + 2. freshness: require ``now <= ruling.timestamp + freshness_seconds`` + 3. require ``len(rotating_pool) >= 1`` (else only the two fixed slots count) + 4. ``third = rotating_pool[keccak(abi.encode(disputeId)) % len]`` + 5–6. for each signature, recover the signer via :func:`recover_ruling_signer`; + count it against ``[fixed0, fixed1, third]`` with a ``seen[3]`` dedupe map — + unknown signers silently ignored, duplicates counted once. + 7. threshold: ``valid_count >= 2``. + + ``valid`` is ``True`` iff the threshold holds AND freshness holds AND the + count gate (2–3) holds. NEVER raises — the caller maps a ``False`` result to a + ``proposeDirectly`` recommendation. + """ + if now is None: + now = int(time.time()) + + third_evaluator = select_third_evaluator(ruling.dispute_id, rotating_pool) + + # §4.7 step 4 — the ordered slot list the seen[] map tracks (fixed0, fixed1, third). + slots: List[Optional[str]] = [ + fixed_evaluators[0] if len(fixed_evaluators) > 0 else None, + fixed_evaluators[1] if len(fixed_evaluators) > 1 else None, + third_evaluator, + ] + slots_lc = [s.lower() if s else None for s in slots] + seen = [False, False, False] + + stale = now > int(ruling.timestamp) + freshness_seconds + + recovered_signers: List[str] = [] + valid_count = 0 + + # §4.7 step 1 gate — count must be 2..3. A count outside this range can never + # be valid, but we still recover signers (advisory) for diagnostics. + count_in_range = 2 <= len(signatures) <= 3 + + for sig in signatures: + try: + signer = recover_ruling_signer(ruling, sig, chain_id, verifying_contract) + except Exception: + # A malformed signature recovers nothing — silently ignored (unknown). + continue + signer_lc = signer.lower() + slot_idx = next( + (i for i, s in enumerate(slots_lc) if s is not None and s == signer_lc), + -1, + ) + if slot_idx == -1: + continue # unknown signer — silently ignored (§4.7) + if seen[slot_idx]: + continue # duplicate — counted once (§4.7) + seen[slot_idx] = True + valid_count += 1 + recovered_signers.append(slots[slot_idx]) # type: ignore[arg-type] + + valid = count_in_range and (not stale) and valid_count >= 2 + return RulingVerification( + valid=valid, + valid_count=valid_count, + recovered_signers=recovered_signers, + third_evaluator=third_evaluator or "", + stale=stale, + ) + + +# --------------------------------------------------------------------------- +# Client +# --------------------------------------------------------------------------- + + +class EvaluatorClient: + """Typed client for the off-chain dispute evaluator (PRD P2-6).""" + + def __init__(self, config: EvaluatorClientConfig) -> None: + if not config.base_url or not isinstance(config.base_url, str): + raise EvaluatorClientError("EvaluatorClient requires a base_url string.") + if config.payment_client is None or not hasattr(config.payment_client, "pay"): + raise EvaluatorClientError( + "EvaluatorClient requires a payment_client with a pay() method " + "(e.g. X402Adapter)." + ) + self._base_url = config.base_url.rstrip("/") + self._payment_client = config.payment_client + self._fetch_impl = config.fetch_impl or _default_http_post + self._api_version = config.api_version + + @property + def base_url(self) -> str: + return self._base_url + + async def request_evaluation( + self, params: RequestEvaluationParams + ) -> EvaluationResult: + """Run the full STEP 0→5 evaluator handshake for an evidence bundle. + + Returns either signed-and-§4.7-verified ruling(s) or a ``proposeDirectly`` + recommendation. NEVER submits on-chain — the caller decides whether to + call ``BondEscalationClient.submit_ai_ruling`` (on ``signed``) or + ``BondEscalationClient.propose_directly`` (on ``proposeDirectly``). + + Raises: + QuoteRejectedError: if ``/quote`` returns an error envelope instead of a 402. + EvaluateResponseError: if ``/evaluate`` returns no/invalid body or a hash mismatch. + """ + # Derive bundleHash + tokenCount from the FROZEN serializer — never trust a + # caller-supplied hash. (The token cap is enforced here too.) + bundle_hash_hex = compute_bundle_hash(params.bundle) + declared_token_count = self._count_tokens(params.bundle) + + # ---- STEP 0 DECLARE → STEP 1 QUOTE (no money, no LLM) ---------------- + quote = await self._declare(params, bundle_hash_hex, declared_token_count) + try: + accepted_quote = accepted_quote_terms(quote, params.chain_id) + except ValueError as error: + raise EvaluateResponseError(str(error)) from error + + # ---- STEP 2 PAY (delegated to the existing x402 buyer stack) --------- + # ---- STEP 3 VERIFY + STEP 4 RUN + STEP 5 RETURN (server-side) -------- + evaluate_body = { + "apiVersion": self._api_version, + "bundleHash": bundle_hash_hex, + "disputeId": params.dispute_id, + "disputeNonce": quote["disputeNonce"], + "payer": params.payer, + "chainId": params.chain_id, + "verifyingContract": params.verifying_contract, + } + response = await self._pay_and_evaluate(evaluate_body, accepted_quote) + + # ---- Parse the §4.3 200 body ----------------------------------------- + body = await self._parse_evaluate_response(response, bundle_hash_hex) + + outcome = body.get("outcome") + if outcome == "proposeDirectly": + rec = body["recommendation"] + return EvaluationResult( + outcome="proposeDirectly", + recommendation=ProposeDirectlyRecommendation( + ruling=int(rec["ruling"]), + split_bps=int(rec.get("splitBps", 0)), + confidence=int(rec.get("confidence", 0)), + rationale=str(rec.get("rationale", "")), + ), + reason="server-recommended", + token_count=body.get("tokenCount"), + reasoning=body.get("reasoning"), + ) + + # §4.3a — signed. REPLICATE §4.7 client-side; never trust evaluators[]. + ruling = self._normalize_ruling(body["ruling"]) + verification = verify_ruling_signatures( + ruling, + body["signatures"], + chain_id=params.chain_id, + verifying_contract=params.verifying_contract, + fixed_evaluators=params.fixed_evaluators, + rotating_pool=params.rotating_pool, + freshness_seconds=params.freshness_seconds, + ) + + if not verification.valid: + # < 2/3 (or stale): DOWNGRADE to a proposeDirectly recommendation with + # NO signatures (INV-21: AI never gains finality on a failed quorum). + return EvaluationResult( + outcome="proposeDirectly", + recommendation=ProposeDirectlyRecommendation( + ruling=int(ruling.ruling), + split_bps=int(ruling.split_bps), + confidence=int(ruling.confidence), + rationale=( + "Signed response failed §4.7 verification " + f"(validCount={verification.valid_count}" + + (", stale" if verification.stale else "") + + "); recommend calling propose_directly() instead of " + "submitting the AI ruling." + ), + ), + reason="verification-failed", + verification=verification, + token_count=body.get("tokenCount"), + reasoning=body.get("reasoning"), + ) + + return EvaluationResult( + outcome="signed", + ruling=ruling, + signatures=list(body["signatures"]), + verification=verification, + token_count=body.get("tokenCount"), + reasoning=body.get("reasoning"), + ) + + # ----------------------------------------------------------------------- + # Internals + # ----------------------------------------------------------------------- + + async def _declare( + self, + params: RequestEvaluationParams, + bundle_hash_hex: str, + declared_token_count: int, + ) -> Dict[str, Any]: + """STEP 0→1: POST ``/quote`` with the declaration (no money). + + A 402 carries the quote body (the normal success path); any other status + is a §3.3 error envelope. + """ + declare_body = { + "apiVersion": self._api_version, + "bundleHash": bundle_hash_hex, + "disputeId": params.dispute_id, + "declaredTokenCount": declared_token_count, + "escrowAmount": params.escrow_amount, + "tier": int(params.tier), + "payer": params.payer, + "bundleSource": params.bundle_source.to_wire(), + } + + res = await self._fetch_impl( + f"{self._base_url}/quote", + method="POST", + headers={"content-type": "application/json", "accept": "application/json"}, + body=json.dumps(declare_body), + ) + + status = _status_of(res) + # §3.2 — a 402 IS the quote success. Anything else is a §3.3 error envelope. + if status != 402: + code = None + message = None + try: + err_body = _json_of(res) + err = err_body.get("error") if isinstance(err_body, dict) else None + if isinstance(err, dict): + code = err.get("code") + message = err.get("message") + except Exception: + pass + raise QuoteRejectedError(status, code, message) + + quote = _json_of(res) + if not isinstance(quote, dict) or not isinstance(quote.get("disputeNonce"), str): + raise QuoteRejectedError(402, None, "quote body missing disputeNonce") + return quote + + async def _pay_and_evaluate(self, evaluate_body: Dict[str, Any], accepted_quote: Mapping[str, str]) -> Any: + """STEP 2: pay the quote and POST ``/evaluate`` via the existing x402 buyer stack. + + The :class:`EvaluatorPaymentClient` ``pay()`` posts the body, transparently + consumes the server 402, signs, retries, and returns the settled 200 + ``response``. + """ + body = json.dumps(evaluate_body) + params = _EvaluatePayParams( + method="POST", body=body, headers={"content-type": "application/json", "accept": "application/json"}, + accepted_quote=accepted_quote, + to=f"{self._base_url}/evaluate", + http_method="POST", + http_body=body, + http_headers={ + "content-type": "application/json", + "accept": "application/json", + }, + metadata={"payment_method": "x402"}, # explicit opt-in (X402Adapter gate) + ) + result = await self._payment_client.pay(params) + response = getattr(result, "response", None) + if response is None: + raise EvaluateResponseError("payment client returned no HTTP response") + return response + + async def _parse_evaluate_response( + self, response: Any, expected_bundle_hash: str + ) -> Dict[str, Any]: + """Parse + validate the §4.3 evaluate response body.""" + try: + body = _json_of(response) + except Exception as exc: # noqa: BLE001 + raise EvaluateResponseError(f"body is not valid JSON: {exc}") + if not isinstance(body, dict) or body.get("outcome") not in ( + "signed", + "proposeDirectly", + ): + raise EvaluateResponseError( + f"missing/unknown outcome (got {body.get('outcome') if isinstance(body, dict) else None})" + ) + # OQ-10: the returned bundleHash MUST equal the one we declared. + resp_hash = body.get("bundleHash") + if ( + not isinstance(resp_hash, str) + or resp_hash.lower() != expected_bundle_hash.lower() + ): + raise EvaluateResponseError( + f"bundleHash mismatch: response {resp_hash} != declared {expected_bundle_hash}" + ) + if body["outcome"] == "signed": + ruling = body.get("ruling") + if ( + not isinstance(ruling, dict) + or str(ruling.get("bundleHash", "")).lower() + != expected_bundle_hash.lower() + ): + raise EvaluateResponseError( + "signed ruling.bundleHash != declared bundleHash" + ) + if not isinstance(body.get("signatures"), list): + raise EvaluateResponseError("signed response missing signatures[]") + else: + if not isinstance(body.get("recommendation"), dict): + raise EvaluateResponseError( + "proposeDirectly response missing recommendation" + ) + return body + + @staticmethod + def _normalize_ruling(r: Dict[str, Any]) -> AIRuling: + """Normalize a wire ruling object into the FROZEN :class:`AIRuling`.""" + zero = "0x" + "00" * 32 + return AIRuling( + dispute_id=r["disputeId"], + ruling=int(r["ruling"]), + confidence=int(r["confidence"]), + split_bps=int(r["splitBps"]), + timestamp=int(r["timestamp"]), + reasoning_hash=r["reasoningHash"], + bundle_hash=r["bundleHash"], + # AIP-14c D7: carry the CID-commitment ref-hashes when present; a + # missing value defaults to bytes32(0) (matching the TS twin). + evidence_ref_hash=r.get("evidenceRefHash", zero), + reasoning_ref_hash=r.get("reasoningRefHash", zero), + ) + + @staticmethod + def _count_tokens(bundle: EvidenceBundle) -> int: + """Count cl100k_base tokens over the bundle's canonical bytes (advisory). + + The server re-counts authoritatively (§3.1/R3). Falls back to ``0`` when no + tokenizer is installed — the field is advisory, so a missing tokenizer must + not block the declare. ``compute_bundle_hash`` already enforced the hard + 100k cap when a tokenizer IS present. + """ + try: + text = serialize_bundle_to_string(bundle) + return count_bundle_tokens(text) + except Exception: + return 0 + + +# --------------------------------------------------------------------------- +# Local helpers +# --------------------------------------------------------------------------- + + +@dataclass +class _EvaluatePayParams(X402PayParams): + """The pay() params shape the x402 buyer stack consumes (mirrors X402PayParams). + + Carries both the generic ``http_*`` fields and an x402 ``metadata`` opt-in. + The real ``X402Adapter.pay`` reads ``to`` + the HTTP options; the stub in + tests records them. + """ + + + +def _to_bytes32(value: Union[str, bytes]) -> bytes: + """Coerce a bytes32hex string (or bytes) to exactly 32 bytes.""" + if isinstance(value, bytes): + b = value + else: + s = value[2:] if value.startswith("0x") else value + b = bytes.fromhex(s) + if len(b) != 32: + b = b.rjust(32, b"\x00")[:32] + return b + + +def _status_of(res: Any) -> int: + """Extract an HTTP status code from an httpx-like or dict-like response.""" + if hasattr(res, "status_code"): + return int(res.status_code) + if isinstance(res, dict) and "status" in res: + return int(res["status"]) + raise EvaluateResponseError("response has no status_code/status") + + +def _json_of(res: Any) -> Any: + """Decode a JSON body from an httpx-like (``.json()``) or dict-like response.""" + if hasattr(res, "json") and callable(res.json): + return res.json() + if isinstance(res, dict) and "body" in res: + body = res["body"] + return json.loads(body) if isinstance(body, (str, bytes)) else body + raise EvaluateResponseError("response has no json()/body") + + +async def _default_http_post( + url: str, + *, + method: str = "POST", + headers: Optional[Dict[str, str]] = None, + body: Optional[str] = None, +) -> Any: + """Default async HTTP POST for the no-money ``/quote`` declare (httpx-backed).""" + import httpx # local import — keeps httpx optional for pure-verification use + + async with httpx.AsyncClient() as client: + return await client.request( + method, url, headers=headers or {}, content=body + ) diff --git a/src/agirails/dispute/evidence_artifact_v2.py b/src/agirails/dispute/evidence_artifact_v2.py new file mode 100644 index 0000000..ada6841 --- /dev/null +++ b/src/agirails/dispute/evidence_artifact_v2.py @@ -0,0 +1,224 @@ +""" +evidence_artifact_v2.py — the Schema-2.0.0 IMMUTABLE evidence artifact serializer +(AIP-14c D5/D6). Python twin of the sdk-js ``dispute/EvidenceArtifactV2.ts``. + +The 2.0.0 artifact is the evidence object a v2 dispute freezes + hashes BEFORE +evaluation. It differs from the 1.0.0 bundle in exactly the D5/D6 ways: + - a top-level ``transaction`` block (authoritative economics/parties/timestamps, + cross-checked against the on-chain ``TransactionView`` by the evaluator); + - NO ``reasoning`` key (D6 — reasoning is a separate post-evaluation artifact, + committed via ``reasoningHash``/``reasoningRefHash`` in the 9-field AIRuling); + - NO ``timeline`` key (D5 — the timeline is derived from chain). + +CANONICALIZATION IS UNCHANGED: ``canonical_bytes = canonical_json_dumps(validated)`` +— the SAME frozen canonicalizer as the 1.0.0 bundle — and +``bundle_hash = keccak256(canonical_bytes)``. Validation is STRICT (no additional +properties at any level) so two different wire objects can never canonicalize to the +same bytes. Byte-identical to the TS twin (same golden vectors: +sdk-js ``tests/evidence-artifact-v2.test.ts``). +""" + +from __future__ import annotations + +import re +from typing import Any, Mapping, Optional + +from eth_utils import keccak as _keccak + +from agirails.utils.canonical_json import canonical_json_dumps +from agirails.dispute.evidence_bundle import count_bundle_tokens, enforce_token_cap + +EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION: str = "2.0.0" + +_BYTES32_HEX = re.compile(r"^0x[0-9a-f]{64}$") +_ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$") +_DECIMAL = re.compile(r"^[0-9]+$") + + +class UnsupportedArtifactVersionError(Exception): + """Raised when ``schemaVersion`` is not the exact frozen "2.0.0".""" + + def __init__(self, schema_version: str) -> None: + super().__init__( + f'Unsupported evidence-artifact schemaVersion "{schema_version}": only the ' + f'exact frozen "{EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION}" is accepted (strict — ' + "any other 2.x is rejected)." + ) + self.schema_version = schema_version + + +class InvalidArtifactError(Exception): + """Raised when the artifact shape is invalid (missing/extra/typed-wrong field).""" + + def __init__(self, detail: str) -> None: + super().__init__(f"Invalid Schema 2.0.0 evidence artifact: {detail}") + + +def _is_mapping(x: Any) -> bool: + return isinstance(x, Mapping) + + +def _require_str(obj: Mapping[str, Any], key: str, path: str, pattern: Optional[re.Pattern] = None) -> str: + v = obj.get(key) + if not isinstance(v, str) or len(v) == 0: + raise InvalidArtifactError(f"{path}{key}: must be a non-empty string") + if pattern is not None and not pattern.match(v): + raise InvalidArtifactError(f"{path}{key}: does not match {pattern.pattern}") + return v + + +def _require_uint(obj: Mapping[str, Any], key: str, path: str) -> int: + v = obj.get(key) + # bool is an int subclass in Python — reject it explicitly. + if isinstance(v, bool) or not isinstance(v, int) or v < 0: + raise InvalidArtifactError(f"{path}{key}: must be a non-negative integer") + return v + + +def _require_map(obj: Mapping[str, Any], key: str, path: str) -> Mapping[str, Any]: + v = obj.get(key) + if not _is_mapping(v): + raise InvalidArtifactError(f"{path}{key}: must be an object") + return v + + +def _no_extra_keys(obj: Mapping[str, Any], allowed: set[str], path: str) -> None: + extra = set(obj.keys()) - allowed + if extra: + raise InvalidArtifactError(f"{path}: unexpected key(s) {sorted(extra)}") + + +def assert_artifact_v2_version(schema_version: Any) -> None: + """Assert ``schemaVersion`` is EXACTLY "2.0.0" (strict D5).""" + if not isinstance(schema_version, str) or len(schema_version) == 0: + raise InvalidArtifactError("schemaVersion must be a non-empty semver string") + if schema_version != EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION: + raise UnsupportedArtifactVersionError(schema_version) + + +def validate_evidence_artifact_v2(artifact: Any) -> dict[str, Any]: + """ + Strictly validate + narrow to a canonical dict. Rejects missing required keys, + ANY extra key at ANY level (so a ``reasoning``/``timeline`` key — D6/D5 — is + rejected), wrong types, non-integer timestamps, malformed bytes32hex/address, + an agreement with neither ``bytes`` nor ``cid``. + """ + if not _is_mapping(artifact): + raise InvalidArtifactError(" must be an object") + assert_artifact_v2_version(artifact.get("schemaVersion")) + _no_extra_keys(artifact, {"schemaVersion", "disputeId", "transaction", "agreement", "delivery"}, "") + + dispute_id = _require_str(artifact, "disputeId", "", _BYTES32_HEX) + + txn = _require_map(artifact, "transaction", "") + _no_extra_keys(txn, {"transactionId", "parties", "amount", "initiator", "timestamps"}, "transaction") + transaction_id = _require_str(txn, "transactionId", "transaction.", _BYTES32_HEX) + amount = _require_str(txn, "amount", "transaction.", _DECIMAL) + initiator = _require_str(txn, "initiator", "transaction.", _ADDRESS) + parties = _require_map(txn, "parties", "transaction.") + _no_extra_keys(parties, {"requester", "provider"}, "transaction.parties") + requester = _require_str(parties, "requester", "transaction.parties.", _ADDRESS) + provider = _require_str(parties, "provider", "transaction.parties.", _ADDRESS) + ts = _require_map(txn, "timestamps", "transaction.") + _no_extra_keys(ts, {"createdAt", "deliveredAt", "disputedAt"}, "transaction.timestamps") + created_at = _require_uint(ts, "createdAt", "transaction.timestamps.") + delivered_at = _require_uint(ts, "deliveredAt", "transaction.timestamps.") + disputed_at = _require_uint(ts, "disputedAt", "transaction.timestamps.") + + agreement = _require_map(artifact, "agreement", "") + _no_extra_keys(agreement, {"bytes", "cid", "quote"}, "agreement") + agreement_bytes = agreement.get("bytes") + agreement_cid = agreement.get("cid") + if agreement_bytes is not None and not isinstance(agreement_bytes, str): + raise InvalidArtifactError("agreement.bytes: must be a string") + if agreement_cid is not None and (not isinstance(agreement_cid, str) or len(agreement_cid) == 0): + raise InvalidArtifactError("agreement.cid: must be a non-empty string") + if agreement_bytes is None and agreement_cid is None: + raise InvalidArtifactError("agreement: requires an inline `bytes` preimage or a `cid` to fetch it") + quote_out: Optional[dict[str, Any]] = None + if "quote" in agreement and agreement.get("quote") is not None: + q = _require_map(agreement, "quote", "agreement.") + _no_extra_keys(q, {"bytes", "quoteHash"}, "agreement.quote") + quote_out = { + "bytes": _require_str(q, "bytes", "agreement.quote."), + "quoteHash": _require_str(q, "quoteHash", "agreement.quote.", _BYTES32_HEX), + } + + delivery = _require_map(artifact, "delivery", "") + _no_extra_keys(delivery, {"resultHash", "encrypted", "inline", "cid", "retrievalInstructions"}, "delivery") + result_hash = _require_str(delivery, "resultHash", "delivery.", _BYTES32_HEX) + encrypted = delivery.get("encrypted") + if encrypted is not None and not isinstance(encrypted, bool): + raise InvalidArtifactError("delivery.encrypted: must be a boolean") + inline = delivery.get("inline") + if inline is not None and not isinstance(inline, str): + raise InvalidArtifactError("delivery.inline: must be a string") + cid = delivery.get("cid") + if cid is not None and (not isinstance(cid, str) or len(cid) == 0): + raise InvalidArtifactError("delivery.cid: must be a non-empty string") + retrieval = delivery.get("retrievalInstructions") + if retrieval is not None and not isinstance(retrieval, str): + raise InvalidArtifactError("delivery.retrievalInstructions: must be a string") + + # Rebuild in a canonical shape (only present optional keys), mirroring the TS twin. + agreement_out: dict[str, Any] = {} + if agreement_bytes is not None: + agreement_out["bytes"] = agreement_bytes + if isinstance(agreement_cid, str) and len(agreement_cid) > 0: + agreement_out["cid"] = agreement_cid + if quote_out is not None: + agreement_out["quote"] = quote_out + + # Mirror the TS twin (zod passthrough): only carry `encrypted` when the input had it, + # so an artifact without the key canonicalizes byte-identically across SDKs. + delivery_out: dict[str, Any] = {"resultHash": result_hash} + if "encrypted" in delivery: + delivery_out["encrypted"] = bool(encrypted is True) + if inline is not None: + delivery_out["inline"] = inline + if isinstance(cid, str) and len(cid) > 0: + delivery_out["cid"] = cid + if retrieval is not None: + delivery_out["retrievalInstructions"] = retrieval + + return { + "schemaVersion": EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION, + "disputeId": dispute_id, + "transaction": { + "transactionId": transaction_id, + "parties": {"requester": requester, "provider": provider}, + "amount": amount, + "initiator": initiator, + "timestamps": {"createdAt": created_at, "deliveredAt": delivered_at, "disputedAt": disputed_at}, + }, + "agreement": agreement_out, + "delivery": delivery_out, + } + + +def serialize_artifact_v2_to_string(artifact: Any) -> str: + """Canonical bytes as a UTF-8 string (the exact text that is hashed and pinned).""" + return canonical_json_dumps(validate_evidence_artifact_v2(artifact)) + + +def serialize_artifact_v2(artifact: Any) -> bytes: + """Canonical UTF-8 bytes of a validated 2.0.0 artifact.""" + return serialize_artifact_v2_to_string(artifact).encode("utf-8") + + +def compute_artifact_v2_hash(artifact: Any, *, skip_token_check: bool = False) -> str: + """ + ``bundle_hash = keccak256(canonical_bytes)`` for a Schema-2.0.0 evidence artifact — + the value committed in the signed 9-field AIRuling and CID-bound into + ``evidenceRefHash`` (D7). Enforces the 1.0.0 token cap unless ``skip_token_check``. + Returns ``0x`` + 64 lowercase hex. + """ + text = serialize_artifact_v2_to_string(artifact) + if not skip_token_check: + enforce_token_cap(text) + return "0x" + _keccak(text.encode("utf-8")).hex() + + +def count_artifact_v2_tokens(artifact: Any) -> int: + """Token count of the canonical artifact text (cl100k_base — same tokenizer as 1.0.0).""" + return count_bundle_tokens(serialize_artifact_v2_to_string(artifact)) diff --git a/src/agirails/dispute/evidence_bundle.py b/src/agirails/dispute/evidence_bundle.py new file mode 100644 index 0000000..e535d6c --- /dev/null +++ b/src/agirails/dispute/evidence_bundle.py @@ -0,0 +1,489 @@ +""" +Evidence Bundle — the single CANONICAL evidence-bundle serializer (PRD P2-3). + +Python half of a cross-language (TS ⇄ Py) byte-identical serializer. Its +TypeScript twin is ``sdk-js/src/dispute/EvidenceBundle.ts``. Both MUST produce +IDENTICAL ``canonical_bytes`` and therefore an identical ``bundle_hash`` for the +same logical bundle. + +FROZEN schema (normative): ``DISPUTE SYSTEM/EVIDENCE-BUNDLE-SCHEMA.md``. No field +set, canonical byte rule, ``bundle_hash`` rule, or token cap is defined here +independently — they are pinned in the schema and reproduced 1:1. + +Key invariants (schema §3, §4, §5): + - ``canonical_bytes = canonical_json_dumps(bundle).encode("utf-8")`` — reuses + the existing cross-language-proven canonicalizer (byte-identical to JS + fast-json-stable-stringify), NOT a new one. Sorted keys at every level, no + whitespace, ``ensure_ascii=False``. + - ``bundle_hash = keccak256(canonical_bytes)`` — what the on-chain AIRuling + commits and what OQ-10 binds to the pinned CID. + - Bundles whose cl100k_base token count over the canonical bytes exceeds + 100_000 are rejected with :class:`BundleTooLargeError` BEFORE hashing/pinning. + - All numeric fields are integers (``uint``); floats are rejected upstream so + the JSON number-formatting divergence between TS and Py never arises. + +Anchor: Example A (schema §7) → bundle_hash + ``0x379fb8140138f7d90cfbcb481898b6ec646e2c0378ff0d3a4a4572a6570ca257``. +""" + +# PARITY: sdk-js/src/dispute/EvidenceBundle.ts +# This file and its TypeScript twin MUST produce byte-identical canonical_bytes +# and bundle_hash for the same logical bundle; keep the schema, error names, and +# public API surface 1:1. + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Dict, List, Mapping, Optional, Protocol, Sequence, Union + +from eth_utils import keccak as _keccak +from pydantic import ( + BaseModel, + ConfigDict, + Field, + ValidationError, + field_validator, + model_validator, +) + +from agirails.utils.canonical_json import canonical_json_dumps + +# --------------------------------------------------------------------------- +# Schema version (schema §1) +# --------------------------------------------------------------------------- + +#: Current frozen evidence-bundle schema version (semver, schema §1). +EVIDENCE_BUNDLE_SCHEMA_VERSION: str = "1.0.0" + +#: The major version this deserializer understands (schema §1). +SUPPORTED_BUNDLE_MAJOR: int = 1 + +#: Canonical tokenizer cap (schema §4 / OQ-9). +MAX_BUNDLE_TOKENS: int = 100_000 + +_BYTES32HEX_RE = re.compile(r"^0x[0-9a-f]{64}$") + + +# --------------------------------------------------------------------------- +# Errors (schema §6 — frozen names, identical to the TS twin) +# --------------------------------------------------------------------------- + + +class BundleTooLargeError(Exception): + """Raised when the canonical-bytes token count exceeds ``MAX_BUNDLE_TOKENS``.""" + + def __init__(self, token_count: int, max_tokens: int = MAX_BUNDLE_TOKENS) -> None: + self.token_count = token_count + self.max_tokens = max_tokens + super().__init__( + f"Evidence bundle too large: {token_count} tokens > {max_tokens} cap " + f"(cl100k_base over canonical bytes). Submit large deliverables as " + f"deliverableHash + deliverableCID + retrievalInstructions " + f"(omit deliverableInline)." + ) + + +class UnsupportedBundleVersionError(Exception): + """Raised when ``schemaVersion`` major number is unknown to this deserializer.""" + + def __init__(self, schema_version: str) -> None: + self.schema_version = schema_version + super().__init__( + f'Unsupported evidence-bundle schemaVersion "{schema_version}": ' + f"this SDK understands major version {SUPPORTED_BUNDLE_MAJOR}." + ) + + +class InvalidBundleError(Exception): + """Raised on schema validation failure (missing/extra key, wrong type, etc.).""" + + def __init__(self, message: str, issues: Any = None) -> None: + self.issues = issues + super().__init__(f"Invalid evidence bundle: {message}") + + +# --------------------------------------------------------------------------- +# pydantic models (schema §2 / §6 — strict: forbid extra, integers only) +# --------------------------------------------------------------------------- + + +def _bytes32hex(value: str) -> str: + if not isinstance(value, str) or not _BYTES32HEX_RE.match(value): + raise ValueError("must be 0x + 64 lowercase hex chars (bytes32hex)") + return value + + +def _cid(value: str) -> str: + if not isinstance(value, str) or len(value) == 0: + raise ValueError("CID must be a non-empty string") + return value + + +class _StrictModel(BaseModel): + # forbid extra keys at every object level (additionalProperties: false); + # strict=True so a float is NOT silently coerced to int (integers only). + model_config = ConfigDict(extra="forbid", strict=True, frozen=False) + + @model_validator(mode="before") + @classmethod + def _reject_explicit_null(cls, data: Any) -> Any: + # schema §3.2.8: optional keys are EITHER present with a value OR + # entirely absent — NEVER null. An explicit `null` is a different + # (invalid) artifact and must be rejected, matching the TS/zod twin + # (`z.string().optional()` rejects null, accepts only string|absent). + if isinstance(data, Mapping): + for key, value in data.items(): + if value is None: + raise ValueError( + f'optional key "{key}" present as null; ' + f"omit it entirely (absent != null, schema §3.2.8)" + ) + return data + + +class EvidenceBundleSpec(_StrictModel): + """The original service spec (schema §2.3).""" + + agirailsMdCID: str + capabilities: List[str] + slaHash: str + + _v_sla = field_validator("slaHash")(staticmethod(_bytes32hex)) + _v_cid = field_validator("agirailsMdCID")(staticmethod(_cid)) + + +class EvidenceBundleDelivery(_StrictModel): + """Deliverable-or-content-hash + retrieval instructions (schema §2.4).""" + + deliverableHash: str + deliverableCID: str + deliverableInline: Optional[str] = None + retrievalInstructions: str + deliveredAt: int = Field(ge=0) + + _v_hash = field_validator("deliverableHash")(staticmethod(_bytes32hex)) + _v_cid = field_validator("deliverableCID")(staticmethod(_cid)) + + +class EvidenceBundleDispute(_StrictModel): + """Why the dispute was opened (schema §2.5).""" + + reason: str + evidenceCID: str + evidenceInline: Optional[str] = None + openedAt: int = Field(ge=0) + + _v_cid = field_validator("evidenceCID")(staticmethod(_cid)) + + +class EvidenceBundleTimelineEvent(_StrictModel): + """A single timeline event (schema §2.6).""" + + event: str = Field(min_length=1) + at: int = Field(ge=0) + + +class EvidenceBundleReasoning(_StrictModel): + """AI reasoning + evaluation metadata (schema §2.7).""" + + evaluatorPromptCID: str + modelVersions: List[str] + notes: str + + _v_cid = field_validator("evaluatorPromptCID")(staticmethod(_cid)) + + +class EvidenceBundle(_StrictModel): + """ + The canonical evidence bundle (schema §2). EXACTLY seven top-level keys — + no additional properties at any object level. + """ + + schemaVersion: str + disputeId: str + spec: EvidenceBundleSpec + delivery: EvidenceBundleDelivery + dispute: EvidenceBundleDispute + timeline: List[EvidenceBundleTimelineEvent] = Field(min_length=2) + reasoning: EvidenceBundleReasoning + + _v_dispute = field_validator("disputeId")(staticmethod(_bytes32hex)) + + def to_canonical_dict(self) -> Dict[str, Any]: + """ + Materialize the bundle as a plain dict with ONLY present keys (optional + keys that are ``None`` are dropped — absent ≠ empty-string, schema §3.2.8). + This is what the canonicalizer serializes. + """ + return _drop_none(self.model_dump(exclude_none=True)) + + +def _drop_none(obj: Any) -> Any: + """Recursively drop ``None``-valued keys (schema §3.2.8: absent, not null).""" + if isinstance(obj, Mapping): + return {k: _drop_none(v) for k, v in obj.items() if v is not None} + if isinstance(obj, (list, tuple)): + return [_drop_none(v) for v in obj] + return obj + + +# --------------------------------------------------------------------------- +# Validation (schema §2 / §6) +# --------------------------------------------------------------------------- + + +def assert_supported_version(schema_version: str) -> None: + """ + Reject a bundle whose ``schemaVersion`` major number is unknown (schema §1). + + The version string is an opaque semver token — only the major component is + checked. + + Raises: + UnsupportedBundleVersionError + """ + major = schema_version.split(".")[0] + if not major.isdigit() or int(major) != SUPPORTED_BUNDLE_MAJOR: + raise UnsupportedBundleVersionError(schema_version) + + +def validate_bundle(bundle: Union[EvidenceBundle, Mapping[str, Any]]) -> EvidenceBundle: + """ + Validate a logical bundle against the frozen schema (schema §2 / §6). + + Rejects: missing required key, extra key (extra="forbid" at every level), + wrong type, non-integer where a ``uint`` is expected (strict mode → a float + is NOT coerced), malformed ``bytes32hex``, optional key present as ``None`` + via an explicit-null path is treated as absent on output. + + ``schemaVersion`` is validated separately: an unknown MAJOR version raises + :class:`UnsupportedBundleVersionError`, not :class:`InvalidBundleError`. + + Returns: + The validated :class:`EvidenceBundle`. + + Raises: + InvalidBundleError, UnsupportedBundleVersionError + """ + if isinstance(bundle, EvidenceBundle): + model = bundle + else: + try: + model = EvidenceBundle.model_validate(bundle) + except ValidationError as exc: + issues = exc.errors() + summary = "; ".join( + f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}" for e in issues + ) + raise InvalidBundleError(summary, issues) from exc + assert_supported_version(model.schemaVersion) + return model + + +# --------------------------------------------------------------------------- +# Canonical serialization (schema §3) — reuse the existing canonicalizer +# --------------------------------------------------------------------------- + + +def serialize_bundle_to_string( + bundle: Union[EvidenceBundle, Mapping[str, Any]], +) -> str: + """ + Canonical bytes as a UTF-8 string (schema §3) — the exact text that is + hashed, pinned, and token-counted. Byte-identical to the TS twin's + ``serializeBundleToString``. + """ + valid = validate_bundle(bundle) + return canonical_json_dumps(valid.to_canonical_dict()) + + +def serialize_bundle(bundle: Union[EvidenceBundle, Mapping[str, Any]]) -> bytes: + """ + Serialize a bundle to its canonical UTF-8 byte form (schema §3). + + ``canonical_bytes = canonical_json_dumps(bundle).encode("utf-8")``. Keys are + sorted at every nesting level, no whitespace, minimal escaping, + ``ensure_ascii=False`` (raw UTF-8). Array order is preserved. Byte-identical + to the TS twin's ``serializeBundle``. + + Raises: + InvalidBundleError, UnsupportedBundleVersionError + """ + return serialize_bundle_to_string(bundle).encode("utf-8") + + +def bundle_hash( + bundle: Union[EvidenceBundle, Mapping[str, Any]], + *, + skip_token_check: bool = False, +) -> str: + """ + Compute ``bundle_hash = keccak256(canonical_bytes)`` (schema §3.3). + + The value committed on-chain inside the AIRuling (§4.4) and bound to the + pinned CID by OQ-10. Identical hex to the TS twin's ``bundleHash``. + + Enforces the token cap (schema §4) BEFORE hashing unless ``skip_token_check``. + + Returns: + ``0x`` + 64 lowercase hex chars. + + Raises: + BundleTooLargeError, InvalidBundleError, UnsupportedBundleVersionError + """ + text = serialize_bundle_to_string(bundle) + if not skip_token_check: + enforce_token_cap(text) + return "0x" + _keccak(text.encode("utf-8")).hex() + + +#: Alias matching the schema §8 acceptance-checklist name. +compute_bundle_hash = bundle_hash + + +# --------------------------------------------------------------------------- +# Token cap (schema §4 / OQ-9) — tiktoken cl100k_base over canonical bytes +# --------------------------------------------------------------------------- + + +class BundleTokenizer(Protocol): + """Protocol for a cl100k_base tokenizer (schema §4).""" + + def encode(self, text: str) -> Sequence[int]: # pragma: no cover - protocol + ... + + +_tokenizer: Optional[BundleTokenizer] = None + + +def set_bundle_tokenizer(tokenizer: BundleTokenizer) -> None: + """ + Inject the cl100k_base tokenizer (schema §4). Overrides the default + ``tiktoken.get_encoding('cl100k_base')`` lookup. The object only needs an + ``encode(text) -> Sequence[int]`` method. + """ + global _tokenizer + _tokenizer = tokenizer + + +def _resolve_tokenizer() -> Optional[BundleTokenizer]: + global _tokenizer + if _tokenizer is not None: + return _tokenizer + try: + import tiktoken # optional dependency + + _tokenizer = tiktoken.get_encoding("cl100k_base") + return _tokenizer + except Exception: # pragma: no cover - only when tiktoken absent + return None + + +def count_bundle_tokens(canonical_text: str) -> int: + """ + Count cl100k_base tokens over the canonical-bytes TEXT (schema §4). + + Raises: + RuntimeError: if no cl100k_base tokenizer is available — the cap must + never be silently skipped. Install ``tiktoken`` or inject one via + :func:`set_bundle_tokenizer`. + """ + tk = _resolve_tokenizer() + if tk is None: + raise RuntimeError( + "No cl100k_base tokenizer available. Install `tiktoken` or call " + "set_bundle_tokenizer(tiktoken.get_encoding('cl100k_base')) before " + "serializing bundles." + ) + return len(tk.encode(canonical_text)) + + +def enforce_token_cap(canonical_text: str) -> int: + """ + Enforce the token cap (schema §4). Counts cl100k_base tokens over the + canonical text; raises :class:`BundleTooLargeError` when ``> MAX_BUNDLE_TOKENS``. + + Returns: + The token count (when within the cap). + + Raises: + BundleTooLargeError + """ + count = count_bundle_tokens(canonical_text) + if count > MAX_BUNDLE_TOKENS: + raise BundleTooLargeError(count, MAX_BUNDLE_TOKENS) + return count + + +# --------------------------------------------------------------------------- +# IPFS pinning (schema §5 — INV-20 / OQ-10 integrity binding) +# --------------------------------------------------------------------------- + + +@dataclass +class PinEvidenceBundleResult: + """ + Result of pinning an evidence bundle (schema §5). + + The integrity invariant (OQ-10) is ``keccak256(fetch(cid)) == bundle_hash``; + the on-chain AIRuling commits ``bundle_hash``, the CID is the retrieval handle. + """ + + cid: str + bundle_hash: str + size: int + + +class EvidenceBundlePinner(Protocol): + """ + Minimal binary-pinning surface the bundle pinner needs (schema §5). Satisfied + by a G-IPFS client exposing ``upload_binary``. REUSED so bundles are pinned + through the same hot-storage tier as the rest of the SDK. + """ + + def upload_binary( + self, + data: bytes, + content_type: str, + options: Optional[Dict[str, Any]] = None, + ) -> Dict[str, Any]: # pragma: no cover - protocol + ... + + +def pin_evidence_bundle( + bundle: Union[EvidenceBundle, Mapping[str, Any]], + pinner: EvidenceBundlePinner, +) -> PinEvidenceBundleResult: + """ + Pin the EXACT canonical bytes of an evidence bundle to IPFS (schema §5.1). + + CRITICAL (OQ-10): the bytes pinned are exactly ``serialize_bundle(bundle)`` — + not a re-encoded / re-ordered / pretty-printed copy — so + ``keccak256(fetch(cid))`` round-trips to the returned ``bundle_hash``. The + token cap (schema §4) is enforced BEFORE pinning. + + Args: + bundle: the logical evidence bundle. + pinner: an IPFS binary pinner exposing ``upload_binary``. + + Returns: + :class:`PinEvidenceBundleResult` for the INV-20 / OQ-10 binding. + + Raises: + BundleTooLargeError, InvalidBundleError, UnsupportedBundleVersionError + """ + valid = validate_bundle(bundle) + text = canonical_json_dumps(valid.to_canonical_dict()) + enforce_token_cap(text) # schema §4 — before any pin/spend + canonical_bytes = text.encode("utf-8") + digest = "0x" + _keccak(canonical_bytes).hex() + result = pinner.upload_binary( + canonical_bytes, + "application/json", + {"metadata": {"bundleHash": digest, "schemaVersion": valid.schemaVersion}}, + ) + cid = result["cid"] if isinstance(result, dict) else getattr(result, "cid") + return PinEvidenceBundleResult( + cid=cid, bundle_hash=digest, size=len(canonical_bytes) + ) diff --git a/src/agirails/dispute/payment_quote.py b/src/agirails/dispute/payment_quote.py new file mode 100644 index 0000000..fac02dc --- /dev/null +++ b/src/agirails/dispute/payment_quote.py @@ -0,0 +1,60 @@ +"""Translate evaluator quote metadata into immutable per-payment expectations.""" + +import re +from collections.abc import Mapping +from typing import Any, NoReturn + +from agirails.dispute.receipt_authorization import _validate_quote_transport + + +def _reject(message: str) -> NoReturn: + raise ValueError(message) + + +def _term(sources, *, amount=False, address=False): + values = [] + for source, key in sources: + if key not in source: + continue + value = source[key] + if not isinstance(value, str) or not value: + _reject("Invalid declared quote term: " + key) + if amount: + if not value.isascii() or not value.isdecimal(): + _reject("Invalid quoted base-unit amount") + try: + value = str(int(value)) + except ValueError: + _reject("Invalid quoted base-unit amount") + if address and re.fullmatch(r"0x[0-9a-fA-F]{40}", value) is None: + _reject("Invalid quoted address") + values.append(value.lower() if address else value) + if values and any(v != values[0] for v in values): + _reject("Contradictory quote terms") + return values[0] if values else None + + +def accepted_quote_terms(quote: dict[str, Any], chain_id: int) -> Mapping[str, str]: + _validate_quote_transport(quote, chain_id) + economics, x402 = quote.get("quote", {}), quote.get("x402", {}) + if not isinstance(economics, dict) or not isinstance(x402, dict): + _reject("Invalid quote economics or x402 metadata") + nonce = _term([(quote, "disputeNonce")]) + if nonce is None: + _reject("Missing quote disputeNonce") + for source in [economics, x402, x402.get("commit", {})]: + if not isinstance(source, dict): + _reject("Invalid quote commitment") + if "disputeNonce" in source and source["disputeNonce"] != nonce: + _reject("Contradictory quote disputeNonce") + terms = {"network": f"eip155:{chain_id}", "nonce": nonce} + fields = { + "amount": ([(economics, "amount"), (x402, "amount"), (x402, "maxAmountRequired")], True), + "asset": ([(economics, "asset"), (x402, "asset")], False), + "pay_to": ([(economics, "payTo"), (x402, "payTo"), (x402, "recipient")], False), + } + for name, (sources, is_amount) in fields.items(): + value = _term(sources, amount=is_amount, address=not is_amount) + if value is not None: + terms[name] = value + return terms diff --git a/src/agirails/dispute/receipt_authorization.py b/src/agirails/dispute/receipt_authorization.py new file mode 100644 index 0000000..84eec49 --- /dev/null +++ b/src/agirails/dispute/receipt_authorization.py @@ -0,0 +1,91 @@ +"""Explicit quote-bound paid-receipt authorization and unverified HTTP transport.""" +from dataclasses import dataclass +from typing import Any, Dict, Optional, Protocol +import asyncio +import re +from urllib.parse import urlparse +import httpx +from web3 import Web3 + + +@dataclass(frozen=True) +class ReceiptAuthorizationInput: + chain_id: int + verifying_contract: str + quote_hash: str + dispute_nonce: str + tx_hash: str + payer: str + + +class ReceiptAuthorizer(Protocol): + def get_address(self) -> str: ... + def sign_typed_data(self, data: Dict[str, Any]) -> str: ... + + +def receipt_authorization_typed_data(value: ReceiptAuthorizationInput) -> Dict[str, Any]: + if isinstance(value.chain_id, bool) or not isinstance(value.chain_id, int) or not 0 < value.chain_id <= 9007199254740991: + raise ValueError("Invalid receipt authorization chain_id") + if not all(re.fullmatch(r"0x[0-9a-fA-F]{64}", item) for item in [value.quote_hash, value.tx_hash]): + raise ValueError("Invalid receipt authorization hash") + if not value.dispute_nonce or len(value.dispute_nonce) > 1024: + raise ValueError("Invalid receipt authorization nonce") + return { + "domain": {"name": "AGIRAILS Evaluator Receipt", "version": "1", "chainId": value.chain_id, + "verifyingContract": Web3.to_checksum_address(value.verifying_contract)}, + "primaryType": "ReceiptAuthorization", + "types": {"ReceiptAuthorization": [ + {"name": "quoteHash", "type": "bytes32"}, {"name": "disputeNonce", "type": "string"}, + {"name": "txHash", "type": "bytes32"}, {"name": "payer", "type": "address"}]}, + "message": {"quoteHash": value.quote_hash, "disputeNonce": value.dispute_nonce, + "txHash": value.tx_hash, "payer": Web3.to_checksum_address(value.payer)}, + } + + +async def authorize_payment_receipt(receipt: Dict[str, Any], value: ReceiptAuthorizationInput, signer: ReceiptAuthorizer) -> Dict[str, Any]: + if Web3.to_checksum_address(signer.get_address()) != Web3.to_checksum_address(value.payer): + raise ValueError("Receipt authorizer is not payer") + if receipt["txHash"].lower() != value.tx_hash.lower(): + raise ValueError("Receipt authorization tx_hash mismatch") + signature = await asyncio.to_thread(signer.sign_typed_data, receipt_authorization_typed_data(value)) + if not re.fullmatch(r"0x(?:[0-9a-fA-F]{2})+", signature): + raise ValueError("Invalid receipt authorization signature") + if signature.lower().endswith("6492" * 16): + raise ValueError("Counterfactual ERC-6492 receipt signatures unsupported; deploy wallet first") + return {**receipt, "authorization": {"version": "1", "signature": signature}} + + +async def post_paid_evaluation(base_url: str, body: Dict[str, Any], client: Optional[httpx.AsyncClient] = None) -> httpx.Response: + """Explicit receipt POST only; result and v2 ruling signatures are unverified.""" + url = urlparse(base_url) + if url.scheme != "https" and not (url.scheme == "http" and url.hostname in ["127.0.0.1", "::1", "localhost"]): + raise ValueError("Paid evaluation requires HTTPS or loopback") + if client is not None: + return await client.post(base_url.rstrip("/") + "/evaluate", json=body, follow_redirects=False) + async with httpx.AsyncClient(timeout=12, trust_env=False) as owned: + return await owned.post(base_url.rstrip("/") + "/evaluate", json=body, follow_redirects=False) + + +def _validate_quote_transport(quote: Dict[str, Any], chain_id: int) -> None: + from agirails.dispute.evaluator_client import EvaluateResponseError + if isinstance(chain_id, bool) or not isinstance(chain_id, int) or chain_id <= 0: + raise EvaluateResponseError("Invalid dispute chain_id") + x402 = quote.get("x402") or {} + if not isinstance(x402, dict): + raise ValueError("Invalid x402 quote") + if "receiptAuthorization" in x402: + raise EvaluateResponseError("Server requires signed paid receipts; use explicit receipt transport before payment") + economics = quote.get("quote") or {} + if not isinstance(economics, dict): + raise EvaluateResponseError("Invalid quote economics") + for value in [economics.get("chainId"), x402.get("chainId")]: + if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value != chain_id): + raise EvaluateResponseError("Quote chainId conflicts with dispute chain_id") + network = x402.get("network") + aliases = {"base-mainnet": 8453, "base-sepolia": 84532} + if network is not None and (not isinstance(network, str) or not network or + (network in aliases and aliases[network] != chain_id) or + (network not in aliases and network != "base" and not network.startswith("eip155:"))): + raise EvaluateResponseError("Quote network conflicts with dispute chain_id") + if isinstance(network, str) and network.startswith("eip155:") and network != f"eip155:{chain_id}": + raise EvaluateResponseError("Quote network conflicts with dispute chain_id") diff --git a/src/agirails/dispute/uma_helper.py b/src/agirails/dispute/uma_helper.py new file mode 100644 index 0000000..6f9a8e6 --- /dev/null +++ b/src/agirails/dispute/uma_helper.py @@ -0,0 +1,480 @@ +# PARITY: sdk-js/src/dispute/UMAHelper.ts +# This file and its TypeScript twin MUST stay 1:1 — every public method/constant +# here has a TS twin with the SAME name (camelCase) and arity, and vice-versa. +# ``quote_self_dispute_cost`` and the ``requester_force_dvm`` call sequence are +# anchored to the shared cross-SDK fixture +# ``DISPUTE SYSTEM/test-vectors/uma-self-dispute-vectors.json``, which both the +# pytest and jest suites consume byte-identically. Any change here (rename, new +# method, amount tweak, or reordering the call sequence) must be mirrored in the +# twin. +""" +UMAHelper — the requester-side "self-dispute to DVM" helper (AIP-14b §8.6). + +§8.6 ASYMMETRY WARNING (normative) +---------------------------------- +Tier-2 escalation is provider-directional by construction: the ONLY assertion +shape ``escalate_to_uma()`` can post is "Provider delivered" (= ruling 0). +``escalate_to_uma()`` is therefore economically rational only for the PROVIDER +side. A requester whose ruling-1 proposal stands unchallenged at the $500 +ceiling simply holds position and WINS for free via ``finalize()`` once liveness +expires — they should normally do nothing. This helper exists ONLY for the +residual case: a requester who wants DVM FINALITY now rather than continued +ceiling ping-pong (every ceiling challenge resets liveness). It is deliberately +EXPENSIVE and asymmetric — it does NOT make the requester side cheaper, it bounds +the worst-case dispute DURATION. Do not reach for it as a default; reach for +``finalize()``. + +The self-dispute path (§8.6): the requester posts BOTH sides of a UMA assertion +to force the Data Verification Mechanism to vote:: + + 1. escalate_to_uma(dispute_id, evidence_cid) — posts the $500 ASSERTER bond + ("Provider delivered"). The requester is the asserter here. + 2. read assertion_id from BondEscalation.disputeToAssertion(dispute_id). + 3. OOV3.disputeAssertion(assertion_id, disputer) — posts a SECOND $500 + DISPUTER bond against their own assertion, forcing DVM review. + +If the DVM rules FALSE ("provider did NOT deliver" → ruling 1), the requester as +DISPUTER recovers $750 of the $1,000 posted (§8.2 CASE C / §8.3) and ruling 1 +executes locally via the callback. Net cost: $250 (the UMA Store fee = 50% of the +losing asserter bond). See :meth:`UMAHelper.quote_self_dispute_cost`. + +SETTLEMENT WARNING (normative, §8.6 + Appendix B.4) +--------------------------------------------------- +UMA settlement is EXTERNAL. After the DVM resolves you (or anyone) MUST call +``OOV3.settleAssertion(assertion_id)`` yourself to trigger bond distribution and +the ``assertionResolvedCallback``. If NO ONE calls it, the dispute does not +resolve through UMA at all — and once 30 days elapse from ``disputedAt``, +``BondEscalation.forceResolveStale()`` force-resolves it to a 30-DAY FORCED 50/50 +SPLIT, which throws away the favorable DVM outcome you paid $250 for. Call +settleAssertion yourself or risk a 30-day forced 50/50 split. + +This helper does NOT itself call ``settle_assertion`` (it cannot know when the +DVM has resolved); it exposes :meth:`UMAHelper.settle_assertion` so the caller +can settle once the DVM result is available, and :meth:`UMAHelper.get_assertion_id` +to look the assertion up. + +Reference: AIP-14b §8.2 (UMA lifecycle), §8.3 (bond accounting), §8.4 +(escalate_to_uma), §8.6 (escalation directionality / self-dispute path). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +# --------------------------------------------------------------------------- +# Constants (AIP-14b §7.4 / §8) — load-bearing, mirror BondEscalation.sol + TS +# --------------------------------------------------------------------------- + +#: UMA Tier-2 stake: $500 USDC (6 decimals). One bond per side. AIP-14b §7.4. +UMA_BOND: int = 500_000_000 + +#: Total USDC a requester must post to force the DVM (§8.6): the $500 asserter +#: bond (via ``escalate_to_uma``) PLUS the $500 disputer bond (via +#: ``dispute_assertion``). = $1,000. +SELF_DISPUTE_TOTAL: int = UMA_BOND * 2 + +#: Amount the requester recovers if the DVM rules FALSE (§8.2 CASE C / §8.3): +#: $500 (own disputer bond returned) + $250 (half the losing asserter bond) = +#: $750. +SELF_DISPUTE_RECOVER: int = UMA_BOND + UMA_BOND // 2 + +#: Net cost of a successful self-dispute (§8.6): the UMA Store fee, = 50% of the +#: losing asserter bond = $250. ``SELF_DISPUTE_TOTAL - SELF_DISPUTE_RECOVER``. +SELF_DISPUTE_LOSS: int = SELF_DISPUTE_TOTAL - SELF_DISPUTE_RECOVER + + +def _load_abi(filename: str) -> List[Dict[str, Any]]: + """Load an ABI from the abis directory.""" + abi_path = Path(__file__).parent.parent / "abis" / filename + with open(abi_path) as f: + return json.load(f) + + +def _to_bytes32(value: Union[str, bytes]) -> bytes: + """Normalize a bytes32 input (0x-hex string or raw bytes) to 32 bytes.""" + if isinstance(value, (bytes, bytearray)): + raw = bytes(value) + else: + s = value[2:] if value.startswith(("0x", "0X")) else value + raw = bytes.fromhex(s) + if len(raw) != 32: + raw = raw.rjust(32, b"\x00") + return raw + + +def _hex32(value: Union[str, bytes]) -> str: + """Normalize a bytes32 to a 0x-prefixed lowercase hex string.""" + return "0x" + _to_bytes32(value).hex() + + +class SelfDisputeCost(Dict[str, int]): + """ + Result of a self-dispute cost quote (USDC base units, 6 decimals). + + A ``dict``-shaped value with keys ``total`` / ``recover`` / ``lose`` so it is + 1:1 with the TS ``SelfDisputeCost`` object (``cost["total"]`` ⇄ + ``cost.total``) AND attribute-accessible (``cost.total``) for ergonomics. + """ + + @property + def total(self) -> int: + return self["total"] + + @property + def recover(self) -> int: + return self["recover"] + + @property + def lose(self) -> int: + return self["lose"] + + +class UMAHelper: + """ + Typed helper for the requester-side self-dispute-to-DVM path (AIP-14b §8.6). + + Two construction paths (mirrors :class:`BondEscalationClient`): + + - Production: pass the three contracts + ``account`` + ``w3`` — write methods + build calldata, sign, and broadcast. + - Testing: pass injected contracts whose functions record their args; the + helper builds calldata via ``encode_abi`` so tests can assert the exact + selector + args (the same assertion surface as the TS twin). + + PARITY: UMAHelper.ts ``UMAHelper``. + """ + + def __init__( + self, + bond_escalation: Any, + oov3: Any, + usdc: Any, + *, + account: Any = None, + w3: Any = None, + bond_escalation_address: Optional[str] = None, + oov3_address: Optional[str] = None, + usdc_address: Optional[str] = None, + confirmations: int = 2, + ) -> None: + if confirmations < 1: + raise ValueError(f"confirmations must be >= 1, got {confirmations}") + self._bond_escalation = bond_escalation + self._oov3 = oov3 + self._usdc = usdc + self._account = account + self._w3 = w3 + self._confirmations = confirmations + self._bond_escalation_address = bond_escalation_address or getattr( + bond_escalation, "address", None + ) + self._oov3_address = oov3_address or getattr(oov3, "address", None) + self._usdc_address = usdc_address or getattr(usdc, "address", None) + + @classmethod + def from_config( + cls, + w3: Any, + account: Any, + config: Any, + *, + confirmations: int = 2, + ) -> "UMAHelper": + """ + Build a helper from a network config (the three dispute-contract + addresses). PARITY: ``BondEscalationClient.from_config``. The + dispute-contract addresses are ``None`` until Phase-6 deployment, in + which case this raises — callers on undeployed networks must inject + contracts directly. + """ + be_addr = getattr(config.contracts, "bond_escalation", None) + oov3_addr = getattr(config.contracts, "uma_oov3", None) or getattr( + config.contracts, "oov3", None + ) + usdc_addr = getattr(config.contracts, "usdc", None) + missing = [ + n + for n, v in ( + ("bond_escalation", be_addr), + ("uma_oov3", oov3_addr), + ("usdc", usdc_addr), + ) + if not v + ] + if missing: + raise ValueError( + "UMAHelper is not deployable on this network " + f"(missing config.contracts: {', '.join(missing)})" + ) + bond_escalation = w3.eth.contract( + address=w3.to_checksum_address(be_addr), + abi=_load_abi("bond_escalation.json"), + ) + oov3 = w3.eth.contract( + address=w3.to_checksum_address(oov3_addr), + abi=_load_abi("i_optimistic_oracle_v3.json"), + ) + usdc = w3.eth.contract( + address=w3.to_checksum_address(usdc_addr), + abi=_load_abi("usdc.json"), + ) + return cls( + bond_escalation, + oov3, + usdc, + account=account, + w3=w3, + bond_escalation_address=be_addr, + oov3_address=oov3_addr, + usdc_address=usdc_addr, + confirmations=confirmations, + ) + + # ------------------------------------------------------------------ + # Accessors (parity with the TS getBondEscalationAddress / getOOV3Address) + # ------------------------------------------------------------------ + + def get_bond_escalation_address(self) -> Optional[str]: + """BondEscalation contract address.""" + return self._bond_escalation_address + + def get_oov3_address(self) -> Optional[str]: + """UMA OOV3 contract address.""" + return self._oov3_address + + # ------------------------------------------------------------------ + # Pure quote (AIP-14b §8.6 / §8.2 CASE C / §8.3) — no chain access + # ------------------------------------------------------------------ + + @staticmethod + def quote_self_dispute_cost() -> SelfDisputeCost: + """ + Quote the cost of the requester self-dispute path (§8.6). + + The requester posts $500 (asserter bond via ``escalate_to_uma``) + $500 + (disputer bond via ``dispute_assertion``) = **$1,000 total**. If the DVM + rules FALSE (provider did NOT deliver), they recover **$750** ($500 own + disputer bond + $250 = half the losing asserter bond, §8.2 CASE C / §8.3) + and **lose $250** (the UMA Store fee = 50% of the losing asserter bond). + + PARITY: TS ``quoteSelfDisputeCost``. + + Returns: + ``{"total": $1000, "recover": $750, "lose": $250}`` in USDC base + units (also attribute-accessible: ``cost.total``). + """ + return SelfDisputeCost( + total=SELF_DISPUTE_TOTAL, # $1,000 + recover=SELF_DISPUTE_RECOVER, # $750 + lose=SELF_DISPUTE_LOSS, # $250 + ) + + # ------------------------------------------------------------------ + # Reads + # ------------------------------------------------------------------ + + async def get_assertion_id(self, dispute_id: str) -> str: + """ + Look up the UMA assertion id for a dispute via + ``BondEscalation.disputeToAssertion(dispute_id)``. Returns ``bytes32(0)`` + if the dispute has not been escalated to UMA yet. PARITY: TS + ``getAssertionId``. + """ + raw = await self._bond_escalation.functions.disputeToAssertion( + _to_bytes32(dispute_id) + ).call() + return _hex32(raw) if isinstance(raw, (bytes, bytearray)) else raw + + async def get_minimum_bond(self) -> int: + """ + Read the UMA oracle's minimum bond for USDC + (``OOV3.getMinimumBond(usdc)``). A direct read, never a recorded write. + PARITY: TS ``getMinimumBond``. + """ + return int( + await self._oov3.functions.getMinimumBond(self._usdc_address).call() + ) + + async def get_effective_bond(self) -> int: + """ + The effective per-side bond the SDK must post to escalate to UMA: + ``max($500, get_minimum_bond(USDC))`` (AIP-14b §7.4). BondEscalation.sol + posts this exact dynamic value; the SDK matches it so a raised UMA + minimum never under-approves and reverts ``escalateToUMA``. PARITY: TS + ``getEffectiveBond``. + """ + minimum = await self.get_minimum_bond() + return minimum if minimum > UMA_BOND else UMA_BOND + + # ------------------------------------------------------------------ + # The §8.6 self-dispute flow + # ------------------------------------------------------------------ + + async def requester_force_dvm( + self, dispute_id: str, evidence_cid: str, reasoning_cid: str, disputer: str + ) -> Dict[str, str]: + """ + Force the dispute to the UMA DVM by self-disputing (AIP-14b §8.6). + + Issues EXACTLY this call sequence, in order (a call-sequence test pins + it): + + 1. ``USDC.approve(bond_escalation, $500)`` — so ``escalate_to_uma`` + can pull the asserter bond. + 2. ``BondEscalation.escalateToUMA(dispute_id, evidence_cid, + reasoning_cid)`` — posts the $500 asserter bond ("Provider + delivered"). + 3. read ``assertion_id`` ← + ``BondEscalation.disputeToAssertion(dispute_id)``. + 4. ``USDC.approve(oov3, $500)`` — so ``disputeAssertion`` can pull the + disputer bond directly to OOV3. + 5. ``OOV3.disputeAssertion(assertion_id, disputer)`` — posts the + SECOND $500 bond against the requester's own assertion, forcing + DVM review. + + This does NOT settle the assertion. After the DVM resolves you MUST call + :meth:`settle_assertion` yourself or risk a 30-day forced 50/50 split + (see the module docstring). See :meth:`quote_self_dispute_cost` for the + $1000/$750/$250 economics, and the §8.6 asymmetry warning for why this is + provider-directional and expensive. PARITY: TS ``requesterForceDVM``. + + Args: + dispute_id: bytes32 dispute id (already at the Tier-1 $500 ceiling, + liveness active — ``escalate_to_uma``'s preconditions). + evidence_cid: IPFS CID of the canonical evidence bundle (§8.4). + reasoning_cid: IPFS CID of the evaluator reasoning (BLOCKER-2: both + CIDs are forwarded into the UMA/DVM claim). + disputer: Address that disputes the assertion (the requester themself; + receives the $750 if the DVM rules FALSE). + + Returns: + ``{"assertion_id", "escalate_tx_hash", "dispute_tx_hash"}``. + """ + # 0. read the effective per-side bond = max($500, getMinimumBond(USDC)), + # matching BondEscalation.sol's dynamic bond (a pure read, not recorded + # as a write). Under the default regime this is $500 (UMA_BOND). + bond = await self.get_effective_bond() + + # 1. approve BondEscalation for the asserter bond. + await self._send(self._usdc, "approve", [self._bond_escalation_address, bond]) + + # 2. escalateToUMA posts the asserter bond ("Provider delivered"). + # BLOCKER-2: forward BOTH evidence + reasoning CIDs into the DVM claim. + escalate = await self._send( + self._bond_escalation, + "escalateToUMA", + [_to_bytes32(dispute_id), evidence_cid, reasoning_cid], + ) + + # 3. read the assertionId the escalation registered. + raw_assertion = await self._bond_escalation.functions.disputeToAssertion( + _to_bytes32(dispute_id) + ).call() + assertion_id = ( + _hex32(raw_assertion) + if isinstance(raw_assertion, (bytes, bytearray)) + else raw_assertion + ) + + # 4. approve OOV3 for the disputer bond (same effective amount). + await self._send(self._usdc, "approve", [self._oov3_address, bond]) + + # 5. dispute the requester's own assertion, forcing DVM review. + dispute = await self._send( + self._oov3, "disputeAssertion", [_to_bytes32(assertion_id), disputer] + ) + + return { + "assertion_id": assertion_id, + "escalate_tx_hash": escalate, + "dispute_tx_hash": dispute, + } + + async def settle_assertion(self, assertion_id: str) -> Dict[str, str]: + """ + Settle a resolved UMA assertion, triggering bond distribution and the + ``assertionResolvedCallback`` (AIP-14b §8.2 STAGE 3, Appendix B.4). + + Callable by anyone once the DVM has resolved (or liveness expired). You + SHOULD call this yourself after winning the DVM — if no one settles and + 30 days elapse, ``force_resolve_stale()`` overrides the DVM outcome with a + forced 50/50 split (see the module settlement warning). PARITY: TS + ``settleAssertion``. + + Args: + assertion_id: bytes32 UMA assertion id (from :meth:`get_assertion_id` + or :meth:`requester_force_dvm`). + """ + receipt = await self._send( + self._oov3, "settleAssertion", [_to_bytes32(assertion_id)] + ) + return {"eth_tx_hash": receipt} + + # ------------------------------------------------------------------ + # Internals + # ------------------------------------------------------------------ + + def encode_calldata(self, contract: Any, method: str, args: List[Any]) -> str: + """ + Build the 0x-hex calldata for ``method`` via ``encode_abi``. The assertion + surface the tests use (parity with the TS twin's + ``interface.encodeFunctionData``). + """ + return contract.encode_abi(abi_element_identifier=method, args=args) + + async def _send(self, contract: Any, method: str, args: List[Any]) -> str: + """ + Build calldata (validating the selector + args), then invoke the contract + function. Returns the tx-hash string. + + Test mocks supply contracts whose ``functions.(...)`` record args + and return an awaitable; production wires through the web3 build / sign / + send path. Either way, calldata is built first so a malformed call raises + before broadcast. PARITY: ``BondEscalationClient._send``. + """ + # Build + validate calldata first (assertion surface in tests). + self.encode_calldata(contract, method, args) + + fn = getattr(contract.functions, method)(*args) + + # Production path: build, sign, broadcast via the injected account/w3. + if self._account is not None and self._w3 is not None: + nonce = await self._w3.eth.get_transaction_count( + self._account.address, "pending" + ) + tx = await fn.build_transaction( + {"from": self._account.address, "nonce": nonce} + ) + signed = self._w3.eth.account.sign_transaction(tx, self._account.key) + tx_hash = await self._w3.eth.send_raw_transaction(signed.raw_transaction) + await self._w3.eth.wait_for_transaction_receipt(tx_hash) + return ( + "0x" + tx_hash.hex() + if isinstance(tx_hash, (bytes, bytearray)) + else str(tx_hash) + ) + + # Test path: the mock fn exposes an awaitable returning a tx hash/receipt. + send = getattr(fn, "transact", None) + if send is not None: + tx_hash = await send() + else: + tx_hash = await fn # fn itself is awaitable in mocks + if isinstance(tx_hash, (bytes, bytearray)): + return "0x" + tx_hash.hex() + return str(tx_hash) + + +__all__ = [ + # Constants + "UMA_BOND", + "SELF_DISPUTE_TOTAL", + "SELF_DISPUTE_RECOVER", + "SELF_DISPUTE_LOSS", + # Types + "SelfDisputeCost", + # Helper + "UMAHelper", +] diff --git a/src/agirails/erc8004/reputation_reporter.py b/src/agirails/erc8004/reputation_reporter.py index 8edf924..3f6f318 100644 --- a/src/agirails/erc8004/reputation_reporter.py +++ b/src/agirails/erc8004/reputation_reporter.py @@ -283,6 +283,62 @@ async def report_dispute( tx_id=tx_id, ) + async def report_dispute_split( + self, + agent_id: str, + tx_id: str, + capability: str = "", + split_bps: Optional[int] = None, + ) -> Optional[ReportResult]: + """ + Report an ACTP dispute SPLIT outcome (AIP-14b §3.4, §3.5, INV-22). + + Call this after a dispute resolves to a SPLIT — either a + CompositeMediator ruling-2 (``DisputeSplitRecorded``) or a kernel + ``DISPUTED → CANCELLED`` transition (admin-CANCELLED). Submits: + + - value: **0** (NEUTRAL — no penalty for either party; INV-4) + - valueDecimals: 0 (binary) + - tag1: 'actp_dispute_split' (identical string in both SDKs) + - tag2: capability + - endpoint: '' (always empty for splits) + - feedbackURI: ``splitBps:`` when known (transparency only) + - feedbackHash: keccak256(txId) + + The neutral value makes the split rate INDEXABLE without punishing + legitimately ambiguous one-off cases. NEVER raises — failures are logged + and None returned. PARITY: TS ``reportDisputeSplit``. + + Args: + agent_id: The provider agent's token ID. + tx_id: The ACTP transaction ID. + capability: Agent capability (tag2, optional). + split_bps: Provider share in basis points from the + ``DisputeSplitRecorded`` event, if known (optional). + + Returns: + ReportResult on success, None on any failure. + """ + if self.is_reported(tx_id): + logger.info("Dispute split already reported for tx %s", tx_id) + return None + + tag1 = ACTP_FEEDBACK_TAGS["DISPUTE_SPLIT"] + feedback_hash = self._compute_feedback_hash(tx_id) + feedback_uri = f"splitBps:{split_bps}" if split_bps is not None else "" + + return await self._submit_feedback( + agent_id=agent_id, + value=0, # NEUTRAL split trace (no penalty — AIP-14b §3.4/INV-4) + value_decimals=0, + tag1=tag1, + tag2=capability, + endpoint="", + feedback_uri=feedback_uri, + feedback_hash=feedback_hash, + tx_id=tx_id, + ) + async def get_agent_reputation( self, agent_id: str, diff --git a/src/agirails/level0/request.py b/src/agirails/level0/request.py index 5763d79..2d5e479 100644 --- a/src/agirails/level0/request.py +++ b/src/agirails/level0/request.py @@ -165,6 +165,7 @@ class TransactionInfo: fee: float duration: int # ms proof: str + escrow_id: Optional[str] = None # SDK-2: requester-side escrow visibility @dataclass @@ -191,6 +192,7 @@ def from_delivery( budget: float, duration: int, proof: str, + escrow_id: Optional[str] = None, ) -> RequestResult: """Create result from delivery.""" return cls( @@ -202,6 +204,7 @@ def from_delivery( fee=budget * 0.01, # 1% ACTP fee duration=duration, proof=proof, + escrow_id=escrow_id, ), ) @@ -437,6 +440,7 @@ async def wait(self, timeout: Optional[int] = None) -> RequestResult: budget=self._options.budget, duration=duration, proof=self._get_tx_field(tx, "deliveryProof") or self._get_tx_field(tx, "delivery_proof") or "", + escrow_id=self._get_tx_field(tx, "escrowId") or self._get_tx_field(tx, "escrow_id"), ) return self._result except Exception as e: diff --git a/src/agirails/level1/agent.py b/src/agirails/level1/agent.py index 4fbad27..ee1831f 100644 --- a/src/agirails/level1/agent.py +++ b/src/agirails/level1/agent.py @@ -554,10 +554,10 @@ async def request( # Find provider if not specified if provider is None: # Import here to avoid circular import - from agirails.level0.directory import service_directory + from agirails.level0.directory import get_global_directory - entry = service_directory.find_one(service) - if entry is None: + entry = get_global_directory().get(service) + if entry is None or not entry.provider_address: raise NoProviderFoundError(service) provider = entry.provider_address @@ -1409,12 +1409,26 @@ async def _complete_job( # Get dispute window from metadata, fallback to 2 days (172800s) per Options.ts default dispute_window_seconds = job.metadata.get("disputeWindow", 172800) - # ABI encode dispute window as uint256 - if abi_encode is not None: - dispute_window_proof = "0x" + abi_encode(["uint256"], [dispute_window_seconds]).hex() - else: - # Fallback: manual encoding for uint256 (32 bytes, big-endian) - dispute_window_proof = "0x" + dispute_window_seconds.to_bytes(32, "big").hex() + # AIP-14c: the DELIVERED proof is the 64-byte (window, resultHash) tuple. Reuse the + # resultHash the AIP-4 delivery proof commits to (parity with TS Agent.ts, which passes + # computeResultHash(result)); if the structured proof lacks it, hash the REAL deliverable + # (``output``) via compute_result_hash — NEVER a synthetic fallback. The v2 kernel + # REJECTS the legacy 32-byte window-only proof AND resultHash == 0. + _pj = delivery_proof_json + if isinstance(_pj, str): + import json as _json + + try: + _pj = _json.loads(_pj) + except (TypeError, ValueError): + _pj = None + _result_hash = _pj.get("resultHash") or _pj.get("result_hash") if isinstance(_pj, dict) else None + _std = self._client.standard + if not _result_hash: + from agirails.types.message import compute_result_hash + + _result_hash = compute_result_hash(output) + dispute_window_proof = _std.encode_delivery_proof(dispute_window_seconds, _result_hash) _logger.debug( "Encoding dispute window proof", diff --git a/src/agirails/negotiation/buyer_orchestrator.py b/src/agirails/negotiation/buyer_orchestrator.py index d28758e..c16c55a 100644 --- a/src/agirails/negotiation/buyer_orchestrator.py +++ b/src/agirails/negotiation/buyer_orchestrator.py @@ -23,7 +23,10 @@ import math import time from dataclasses import dataclass, field -from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Tuple, Union + +if TYPE_CHECKING: + from agirails.protocol.agent_registry import AgentRegistry from agirails.builders.counter_offer import ( CounterOfferBuilder, @@ -240,6 +243,7 @@ def __init__( negotiation: Optional[BuyerNegotiationContext] = None, client: Optional[Any] = None, decide_quote: Optional[BuyerQuoteDecider] = None, + agent_registry: Optional["AgentRegistry"] = None, ) -> None: # Fail-fast on partial negotiation context. Pre-fix bug: a developer who # set ``negotiation_channel`` but forgot private_key / chain_id got NO @@ -277,6 +281,9 @@ def __init__( self._session_store = SessionStore(actp_dir) self._negotiation = negotiation self._client = client + # F-5: optional, injected AgentRegistry for the pre-escrow price-band + # check. Fail-open when absent (parity with TS BuyerOrchestrator). + self._agent_registry = agent_registry # BYO-brain: the default decider delegates to the built-in # DecisionEngine, so when ``decide_quote`` is absent the per-quote @@ -578,6 +585,32 @@ async def _negotiate( ) continue + # F-5: reject out-of-band requests before creating the transaction, + # so the buyer never locks escrow on a price the provider's published + # band will refuse to settle. Mirrors TS BuyerOrchestrator.ts:447-462. + offer_base_units = self._to_base_units(offer.unit_price) + band_allowed, band_reason = await self._check_provider_price_band( + provider_address, offer_base_units + ) + if not band_allowed: + rounds.append( + RoundResult( + round=round_idx + 1, + provider_slug=candidate.slug, + provider_address=provider_address, + action="rejected", + reason=band_reason or "out of price band", + ) + ) + emit( + RoundEndEvent( + round=round_idx + 1, + action="rejected", + reason=band_reason or "out of price band", + ) + ) + continue + # 3b. Create transaction tx_id: Optional[str] = None try: @@ -1330,6 +1363,32 @@ async def _commit_at_amount( "accept the quote" and "accept the counter" terminal branches. Mirror of TS ``_commitAtAmount`` (BuyerOrchestrator.ts:971-1020). """ + # F-5: re-check the (possibly negotiated) final amount against the + # provider's band before accepting and locking escrow. Multi-round + # counters can land on an amount the initial pre-create check never saw. + # Mirrors TS BuyerOrchestrator.ts:1015-1030. + band_allowed, band_reason = await self._check_provider_price_band( + provider_address, amount_base_units + ) + if not band_allowed: + try: + await self._transition_state(tx_id, "CANCELLED") + except Exception: + pass # best-effort rollback + reason = band_reason or "out of price band" + rounds.append( + RoundResult( + round=round_idx + 1, + provider_slug=candidate_slug, + provider_address=provider_address, + action="rejected", + reason=reason, + tx_id=tx_id, + ) + ) + emit(RoundEndEvent(round=round_idx + 1, action="rejected", reason=reason)) + return (True, False, reason) + accept_quote_succeeded = False try: await self._accept_quote(tx_id, amount_base_units) @@ -1610,6 +1669,57 @@ def check_requote_anchors( ) return None + async def _check_provider_price_band( + self, provider_address: str, amount_base_units: str + ) -> Tuple[bool, Optional[str]]: + """ + F-5: buyer-side pre-escrow price-band check. Escrow on ACTP is + requester-driven (the kernel pulls the buyer's USDC on linkEscrow before + the provider's policy filter runs), so a request priced outside the + provider's published [min_price, max_price] band would lock the buyer's + own capital until the deadline. This catches it before any escrow. + + Returns (False, reason) to hard-reject an out-of-band amount, (True, None) + to proceed. Fail-open: no registry, a failed read, no matching descriptor, + or an unparseable amount all return (True, None). Mirrors TS + BuyerOrchestrator.ts:_checkProviderPriceBand. + """ + if self._agent_registry is None: + return (True, None) + try: + descriptors = await self._agent_registry.get_service_descriptors( + provider_address + ) + except Exception: + # read failed (RPC error, registry not deployed) — fail-open + return (True, None) + + from agirails.protocol.agent_registry import compute_service_type_hash + + wanted_hash = compute_service_type_hash(self._policy.task).lower() + descriptor = next( + (d for d in descriptors if d.service_type_hash.lower() == wanted_hash), + None, + ) + if descriptor is None: + # no matching descriptor — fail-open rather than reject against a + # band that does not apply to this service + return (True, None) + try: + amount = int(amount_base_units) + except (ValueError, TypeError): + return (True, None) # unparseable amount — fail-open + if amount < descriptor.min_price or amount > descriptor.max_price: + req = amount / 1_000_000 + lo = descriptor.min_price / 1_000_000 + hi = descriptor.max_price / 1_000_000 + return ( + False, + f'Request ${req:.2f} is outside the provider\'s price band ' + f'${lo:.2f}-${hi:.2f} for "{self._policy.task}"', + ) + return (True, None) + @staticmethod def _to_base_units(amount: float) -> str: """Convert a USDC amount (e.g. 0.80) to base units string (e.g. '800000'). diff --git a/src/agirails/protocol/__init__.py b/src/agirails/protocol/__init__.py index e15c790..54d3ef5 100644 --- a/src/agirails/protocol/__init__.py +++ b/src/agirails/protocol/__init__.py @@ -75,6 +75,7 @@ ) from agirails.protocol.events import ( ACTPEvent, + DisputeSplitRecordedEvent, EscrowCreatedEvent, EscrowPayoutEvent, EventFilter, @@ -82,6 +83,7 @@ EventType, StateTransitionedEvent, TransactionCreatedEvent, + UMADisputeEscalatedEvent, ) from agirails.protocol.kernel import ( ACTPKernel, @@ -131,6 +133,8 @@ "StateTransitionedEvent", "EscrowCreatedEvent", "EscrowPayoutEvent", + "DisputeSplitRecordedEvent", + "UMADisputeEscalatedEvent", # Nonce "NonceManager", "NonceManagerPool", diff --git a/src/agirails/protocol/agent_registry.py b/src/agirails/protocol/agent_registry.py index b809672..8a3a4d3 100644 --- a/src/agirails/protocol/agent_registry.py +++ b/src/agirails/protocol/agent_registry.py @@ -554,6 +554,52 @@ async def create( chain_id=config.chain_id, ) + @classmethod + async def connect( + cls, + network: Union[str, NetworkConfig] = "base-sepolia", + rpc_url: Optional[str] = None, + ) -> "AgentRegistry": + """ + Create a READ-ONLY AgentRegistry (no signer) for view calls such as + ``get_service_descriptors`` (e.g. the F-5 buyer price-band check). + Write methods will fail because there is no account. + + Args: + network: Network name or config + rpc_url: Optional custom RPC URL + + Returns: + Read-only AgentRegistry instance + """ + if not HAS_WEB3: + raise ImportError( + "web3 is required for AgentRegistry. " + "Install with: pip install web3 eth-account" + ) + + config = get_network(network) if isinstance(network, str) else network + + if not config.contracts.agent_registry: + raise ValueError( + f"AgentRegistry not deployed on {config.name}. " + "This feature requires the agent registry contract." + ) + + rpc = rpc_url or config.rpc_url + w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider(rpc)) + abi = _load_agent_registry_abi() + contract = w3.eth.contract( + address=w3.to_checksum_address(config.contracts.agent_registry), + abi=abi, + ) + return cls( + contract=contract, + account=None, # type: ignore[arg-type] # read-only: view calls don't sign + w3=w3, + chain_id=config.chain_id, + ) + @property def address(self) -> str: """Get account address.""" @@ -583,7 +629,7 @@ async def _build_transaction( gas = await function.estimate_gas(tx_params) tx_params["gas"] = int(gas * 1.2) # 20% buffer - return function.build_transaction(tx_params) + return await function.build_transaction(tx_params) async def _send_transaction( self, diff --git a/src/agirails/protocol/base.py b/src/agirails/protocol/base.py index 49a82d3..f6909a6 100644 --- a/src/agirails/protocol/base.py +++ b/src/agirails/protocol/base.py @@ -70,6 +70,10 @@ async def _estimate_gas( except Exception: return default_limit + async def _estimate_gas_strict(self, contract_fn: Any, default_limit: int) -> int: + estimated = await contract_fn.estimate_gas({"from": self.account.address}) + return max((int(estimated) * 115 + 99) // 100, default_limit) + async def _build_tx_params( self, gas_limit: int, diff --git a/src/agirails/protocol/event_queries.py b/src/agirails/protocol/event_queries.py new file mode 100644 index 0000000..b366e9d --- /dev/null +++ b/src/agirails/protocol/event_queries.py @@ -0,0 +1,49 @@ +"""Adaptive AsyncWeb3 event queries shared by protocol event monitors.""" + +from typing import Any, Union + +from web3.types import LogReceipt + + +class EventLogQueries: + """Query async event filters, splitting oversized numeric block windows.""" + + _BLOCK_RANGE_ERROR_MARKERS = ( + "block range", + "range is too", + "range too", + "up to a", + "more than", + "response size", + "query timeout", + "limit exceeded", + "-32600", + "-32005", + ) + + @classmethod + def _is_block_range_error(cls, err: BaseException) -> bool: + message = str(err).lower() + return any(marker in message for marker in cls._BLOCK_RANGE_ERROR_MARKERS) + + async def _query_logs_chunked( + self, event_obj: Any, from_block: int, to_block: int + ) -> list[LogReceipt]: + try: + log_filter = await event_obj.create_filter(from_block=from_block, to_block=to_block) + return await log_filter.get_all_entries() + except Exception as err: + if from_block >= to_block or not self._is_block_range_error(err): + raise + mid = (from_block + to_block) // 2 + lower = await self._query_logs_chunked(event_obj, from_block, mid) + upper = await self._query_logs_chunked(event_obj, mid + 1, to_block) + return [*lower, *upper] + + async def _query_event_logs( + self, event_obj: Any, from_block: Union[int, str], to_block: Union[int, str] + ) -> list[LogReceipt]: + if isinstance(from_block, int) and isinstance(to_block, int): + return await self._query_logs_chunked(event_obj, from_block, to_block) + log_filter = await event_obj.create_filter(from_block=from_block, to_block=to_block) + return await log_filter.get_all_entries() diff --git a/src/agirails/protocol/events.py b/src/agirails/protocol/events.py index 91c881c..80c0a9d 100644 --- a/src/agirails/protocol/events.py +++ b/src/agirails/protocol/events.py @@ -51,6 +51,8 @@ _ABI_EVENT_MISSING_ERRORS = (AttributeError,) from agirails.config.networks import NetworkConfig +from agirails.protocol.event_queries import EventLogQueries +from agirails.protocol.kernel_creation import is_legacy_creation_kernel, kernel_creation_abi from agirails.types.transaction import TransactionState @@ -75,6 +77,10 @@ class EventType(str, Enum): ESCROW_PAYOUT = "EscrowPayout" ESCROW_COMPLETED = "EscrowCompleted" + # Dispute events (PRD P2-5 / AIP-14b §3.4) + DISPUTE_SPLIT_RECORDED = "DisputeSplitRecorded" # CompositeMediator + UMA_DISPUTE_ESCALATED = "UMADisputeEscalated" # BondEscalation + @dataclass class ACTPEvent: @@ -227,6 +233,48 @@ def to_dict(self) -> Dict[str, Any]: return base +@dataclass +class DisputeSplitRecordedEvent(ACTPEvent): + """CompositeMediator ruling-2 trace (AIP-14b §3.4). PARITY: TS DisputeEvent.""" + + tx_id: str = "" + requester: str = "" + provider: str = "" + split_bps: int = 0 + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary.""" + base = super().to_dict() + base.update( + { + "txId": self.tx_id, + "requester": self.requester, + "provider": self.provider, + "splitBps": self.split_bps, + } + ) + return base + + +@dataclass +class UMADisputeEscalatedEvent(ACTPEvent): + """BondEscalation Tier-2 assertion pushed to UMA DVM (AIP-14b §8.5).""" + + dispute_id: str = "" + assertion_id: str = "" + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary.""" + base = super().to_dict() + base.update( + { + "disputeId": self.dispute_id, + "assertionId": self.assertion_id, + } + ) + return base + + # Event type mapping EVENT_CLASSES = { EventType.TRANSACTION_CREATED: TransactionCreatedEvent, @@ -234,6 +282,8 @@ def to_dict(self) -> Dict[str, Any]: EventType.ESCROW_LINKED: EscrowLinkedEvent, EventType.ESCROW_CREATED: EscrowCreatedEvent, EventType.ESCROW_PAYOUT: EscrowPayoutEvent, + EventType.DISPUTE_SPLIT_RECORDED: DisputeSplitRecordedEvent, + EventType.UMA_DISPUTE_ESCALATED: UMADisputeEscalatedEvent, } @@ -271,7 +321,7 @@ class EventFilter: # ============================================================================ -class EventMonitor: +class EventMonitor(EventLogQueries): """ Monitor for ACTP protocol events. @@ -289,6 +339,8 @@ def __init__( kernel_contract: AsyncContract, escrow_contract: AsyncContract, w3: AsyncWeb3, + mediator_contract: Optional[AsyncContract] = None, + bond_escalation_contract: Optional[AsyncContract] = None, ) -> None: """ Initialize EventMonitor. @@ -297,10 +349,19 @@ def __init__( kernel_contract: The ACTPKernel contract instance escrow_contract: The EscrowVault contract instance w3: The AsyncWeb3 instance + mediator_contract: Optional CompositeMediator (for DisputeSplitRecorded) + bond_escalation_contract: Optional BondEscalation (for UMADisputeEscalated) """ + if is_legacy_creation_kernel(getattr(kernel_contract, "address", None)): + kernel_contract = w3.eth.contract( + address=kernel_contract.address, + abi=kernel_creation_abi(kernel_contract.address, kernel_contract.abi), + ) self.kernel_contract = kernel_contract self.escrow_contract = escrow_contract self.w3 = w3 + self.mediator_contract = mediator_contract + self.bond_escalation_contract = bond_escalation_contract @classmethod def from_config( @@ -437,6 +498,202 @@ async def get_escrow_events( from_block=from_block, ) + # ========================================================================= + # Dispute surfacing (PRD P2-5 / AIP-14b §3.4) + # ========================================================================= + + async def get_dispute_events( + self, + from_block: Union[int, str] = "earliest", + to_block: Union[int, str] = "latest", + ) -> List[ACTPEvent]: + """ + One-shot historical sweep of all three dispute signals across a block + window — the read half the split-rate indexer (P2-8) builds on. + + Surfaces, block/log-ordered: + - kernel ``DISPUTED → CANCELLED`` transitions (admin-CANCELLED + included — OQ-11 counts these at the same weight as splits), + - ``DisputeSplitRecorded`` (if a mediator contract is wired), + - ``UMADisputeEscalated`` (if a BondEscalation contract is wired). + + PARITY: TS ``EventMonitor.getDisputeEvents``. + """ + events: List[ACTPEvent] = [] + + # Kernel DISPUTED→CANCELLED — filter StateTransitioned by from/to states. + try: + state_logs = await self._query_event_logs( + self.kernel_contract.events.StateTransitioned, + from_block, + to_block, + ) + for log in state_logs: + event = self._parse_state_transitioned(log) + if ( + event.previous_state == TransactionState.DISPUTED + and event.new_state == TransactionState.CANCELLED + ): + events.append(event) + except _ABI_EVENT_MISSING_ERRORS: + pass + + # CompositeMediator DisputeSplitRecorded (if wired). + if self.mediator_contract is not None: + try: + split_logs = await self._query_event_logs( + self.mediator_contract.events.DisputeSplitRecorded, + from_block, + to_block, + ) + for log in split_logs: + events.append(self._parse_dispute_split_recorded(log)) + except _ABI_EVENT_MISSING_ERRORS: + pass + + # BondEscalation UMADisputeEscalated (if wired). + if self.bond_escalation_contract is not None: + try: + uma_logs = await self._query_event_logs( + self.bond_escalation_contract.events.UMADisputeEscalated, + from_block, + to_block, + ) + for log in uma_logs: + events.append(self._parse_uma_dispute_escalated(log)) + except _ABI_EVENT_MISSING_ERRORS: + pass + + events.sort(key=lambda e: (e.block_number, e.log_index)) + return events + + async def on_dispute_split_recorded( + self, + callback: Callable[[DisputeSplitRecordedEvent], None], + poll_interval: float = 2.0, + ) -> asyncio.Task: + """ + Subscribe to ``DisputeSplitRecorded`` (CompositeMediator ruling-2 trace). + + Requires a ``mediator_contract`` to have been passed to the constructor. + PARITY: TS ``EventMonitor.onDisputeSplitRecorded``. + + Raises: + ValueError: if no mediator contract was provided. + """ + if self.mediator_contract is None: + raise ValueError( + "on_dispute_split_recorded: EventMonitor was constructed without " + "a CompositeMediator contract" + ) + contract = self.mediator_contract + + async def _watch() -> None: + last_block = await self.w3.eth.block_number + while True: + try: + current_block = await self.w3.eth.block_number + if current_block > last_block: + logs = await self._query_event_logs( + contract.events.DisputeSplitRecorded, + last_block + 1, + current_block, + ) + for log in logs: + callback(self._parse_dispute_split_recorded(log)) + last_block = current_block + await asyncio.sleep(poll_interval) + except asyncio.CancelledError: + break + except Exception: + await asyncio.sleep(poll_interval) + + return asyncio.create_task(_watch()) + + async def on_disputed_to_cancelled( + self, + callback: Callable[[StateTransitionedEvent], None], + poll_interval: float = 2.0, + ) -> asyncio.Task: + """ + Subscribe to kernel ``DISPUTED → CANCELLED`` transitions — the + kernel-level split path (admin-CANCELLED disputes route here without + touching CompositeMediator). OQ-11 counts these in the headline + split-rate at the SAME weight as ``DisputeSplitRecorded``. + PARITY: TS ``EventMonitor.onDisputedToCancelled``. + """ + + async def _watch() -> None: + last_block = await self.w3.eth.block_number + while True: + try: + current_block = await self.w3.eth.block_number + if current_block > last_block: + logs = await self._query_event_logs( + self.kernel_contract.events.StateTransitioned, + last_block + 1, + current_block, + ) + for log in logs: + event = self._parse_state_transitioned(log) + if ( + event.previous_state == TransactionState.DISPUTED + and event.new_state == TransactionState.CANCELLED + ): + callback(event) + last_block = current_block + await asyncio.sleep(poll_interval) + except asyncio.CancelledError: + break + except Exception: + await asyncio.sleep(poll_interval) + + return asyncio.create_task(_watch()) + + async def on_uma_dispute_escalated( + self, + callback: Callable[[UMADisputeEscalatedEvent], None], + poll_interval: float = 2.0, + ) -> asyncio.Task: + """ + Subscribe to BondEscalation ``UMADisputeEscalated`` — a Tier-2 assertion + was disputed and pushed to UMA's DVM (AIP-14b §8.5). + + Requires a ``bond_escalation_contract`` to have been passed to the + constructor. PARITY: TS ``EventMonitor.onUMADisputeEscalated``. + + Raises: + ValueError: if no BondEscalation contract was provided. + """ + if self.bond_escalation_contract is None: + raise ValueError( + "on_uma_dispute_escalated: EventMonitor was constructed without " + "a BondEscalation contract" + ) + contract = self.bond_escalation_contract + + async def _watch() -> None: + last_block = await self.w3.eth.block_number + while True: + try: + current_block = await self.w3.eth.block_number + if current_block > last_block: + logs = await self._query_event_logs( + contract.events.UMADisputeEscalated, + last_block + 1, + current_block, + ) + for log in logs: + callback(self._parse_uma_dispute_escalated(log)) + last_block = current_block + await asyncio.sleep(poll_interval) + except asyncio.CancelledError: + break + except Exception: + await asyncio.sleep(poll_interval) + + return asyncio.create_task(_watch()) + # ========================================================================= # Real-time Watching # ========================================================================= @@ -600,80 +857,6 @@ async def _watch(): # Internal Methods # ========================================================================= - # Heuristic substrings that mean the eth_getLogs block range was too large. - # PARITY: EventMonitor.ts:198-207 (isBlockRangeError). - _BLOCK_RANGE_ERROR_MARKERS = ( - "block range", - "range is too", - "range too", - "up to a", - "more than", - "response size", - "query timeout", - "limit exceeded", - "-32600", - "-32005", - ) - - @classmethod - def _is_block_range_error(cls, err: BaseException) -> bool: - """Heuristic: does this error mean the eth_getLogs block range was too large? - - PARITY: EventMonitor.ts:198-207. - """ - message = str(err).lower() - return any(marker in message for marker in cls._BLOCK_RANGE_ERROR_MARKERS) - - async def _query_logs_chunked( - self, - event_obj: Any, - from_block: int, - to_block: int, - ) -> List[LogReceipt]: - """Adaptive eth_getLogs over ``[from_block, to_block]``. - - Tries the full window first; on a block-range error, splits the window - in half and retries each half — adapting to ANY RPC's eth_getLogs cap - (10, 1000, 10000, …) with no hardcoded chunk size. In practice a 10000 - block window halves toward ~1000 on a standard-tier RPC. A single-block - window that still fails is a genuine error and is re-raised (NOT - swallowed). PARITY: EventMonitor.ts:182-196 (queryFilterChunked). - """ - try: - log_filter = event_obj.create_filter( - fromBlock=from_block, - toBlock=to_block, - ) - return await log_filter.get_all_entries() - except Exception as err: - # Single-block window or a non-range error → genuine. Re-raise so the - # caller's ABI-existence guard handles "event not in ABI" but real - # RPC failures are never silently dropped. - if from_block >= to_block or not self._is_block_range_error(err): - raise - mid = (from_block + to_block) // 2 - lower = await self._query_logs_chunked(event_obj, from_block, mid) - upper = await self._query_logs_chunked(event_obj, mid + 1, to_block) - return [*lower, *upper] - - async def _query_event_logs( - self, - event_obj: Any, - from_block: Union[int, str], - to_block: Union[int, str], - ) -> List[LogReceipt]: - """Query logs for one event, chunking adaptively when bounds are numeric. - - Non-numeric bounds (e.g. ``"earliest"`` / ``"latest"``) fall through to a - single ``get_all_entries`` call — there's nothing to halve without - concrete block numbers. PARITY: EventMonitor.ts:131-136. - """ - if isinstance(from_block, int) and isinstance(to_block, int): - return await self._query_logs_chunked(event_obj, from_block, to_block) - - log_filter = event_obj.create_filter(fromBlock=from_block, toBlock=to_block) - return await log_filter.get_all_entries() - async def _get_kernel_events( self, event_filter: Optional[EventFilter], @@ -777,10 +960,19 @@ def _parse_transaction_created(self, log: LogReceipt) -> TransactionCreatedEvent ) def _parse_state_transitioned(self, log: LogReceipt) -> StateTransitionedEvent: - """Parse StateTransitioned event log.""" + """Parse StateTransitioned event log. + + The on-chain ABI names the fields ``oldState`` / ``newState`` / + ``triggeredBy`` (see ACTPKernel.json). Earlier code read the + non-existent ``previousState`` / ``actor`` keys, so state fields were + never populated against real logs — fixed here, with a fallback to the + legacy synthetic names so any existing caller keeps working. This decode + is load-bearing for P2-5 DISPUTED→CANCELLED surfacing (OQ-11). + """ args = log.get("args", {}) - prev_state = args.get("previousState") + prev_state = args.get("oldState", args.get("previousState")) new_state = args.get("newState") + actor = args.get("triggeredBy", args.get("actor", "")) return StateTransitionedEvent( event_type=EventType.STATE_TRANSITIONED, @@ -793,7 +985,7 @@ def _parse_state_transitioned(self, log: LogReceipt) -> StateTransitionedEvent: transaction_id=self._bytes_to_hex(args.get("transactionId", b"")), previous_state=TransactionState(prev_state) if prev_state is not None else None, new_state=TransactionState(new_state) if new_state is not None else None, - actor=args.get("actor", ""), + actor=actor, raw_data=dict(args), ) @@ -832,6 +1024,44 @@ def _parse_escrow_payout(self, log: LogReceipt) -> EscrowPayoutEvent: raw_data=dict(args), ) + def _parse_dispute_split_recorded( + self, log: LogReceipt + ) -> DisputeSplitRecordedEvent: + """Parse DisputeSplitRecorded event log. PARITY: decode_dispute_split_recorded.""" + args = log.get("args", {}) + return DisputeSplitRecordedEvent( + event_type=EventType.DISPUTE_SPLIT_RECORDED, + contract_address=log["address"], + block_number=log["blockNumber"], + transaction_hash="0x" + log["transactionHash"].hex() + if isinstance(log["transactionHash"], bytes) + else log["transactionHash"], + log_index=log["logIndex"], + tx_id=self._bytes_to_hex(args.get("txId", b"")), + requester=args.get("requester", ""), + provider=args.get("provider", ""), + split_bps=int(args.get("splitBps", 0)), + raw_data=dict(args), + ) + + def _parse_uma_dispute_escalated( + self, log: LogReceipt + ) -> UMADisputeEscalatedEvent: + """Parse UMADisputeEscalated event log (BondEscalation, AIP-14b §8.5).""" + args = log.get("args", {}) + return UMADisputeEscalatedEvent( + event_type=EventType.UMA_DISPUTE_ESCALATED, + contract_address=log["address"], + block_number=log["blockNumber"], + transaction_hash="0x" + log["transactionHash"].hex() + if isinstance(log["transactionHash"], bytes) + else log["transactionHash"], + log_index=log["logIndex"], + dispute_id=self._bytes_to_hex(args.get("disputeId", b"")), + assertion_id=self._bytes_to_hex(args.get("assertionId", b"")), + raw_data=dict(args), + ) + def _bytes_to_hex(self, value: Union[bytes, str]) -> str: """Convert bytes to hex string.""" if isinstance(value, bytes): diff --git a/src/agirails/protocol/kernel.py b/src/agirails/protocol/kernel.py index eb1c21f..061725a 100644 --- a/src/agirails/protocol/kernel.py +++ b/src/agirails/protocol/kernel.py @@ -33,6 +33,7 @@ from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union +from eth_abi import decode as decode_abi from eth_account.signers.local import LocalAccount from web3 import AsyncWeb3 from web3.contract import AsyncContract @@ -45,6 +46,7 @@ TransactionNotFoundError, ValidationError, ) +from agirails.protocol.kernel_creation import kernel_creation_arguments, kernel_creation_abi, is_legacy_creation_kernel from agirails.protocol.base import ContractBase from agirails.protocol.nonce import NonceManager from agirails.types.transaction import Transaction, TransactionReceipt, TransactionState @@ -168,6 +170,10 @@ class CreateTransactionParams: deadline: Transaction deadline (Unix timestamp) dispute_window: Dispute window in seconds (default: 48 hours) service_hash: Hash of service description (bytes32) + agreement_hash: keccak(request + input + SLA) binding the agreed terms + (bytes32). Defaults to bytes32(0) meaning "no auto AI ruling". + Optional and backward-compatible (AIP-14c v2, canonical + createTransaction 7th arg between serviceHash and agentId). agent_id: ERC-8004 agent ID for provider (0 if not applicable) """ @@ -179,6 +185,9 @@ class CreateTransactionParams: service_hash: str = ZERO_BYTES32 agent_id: int = 0 requester_agent_id: int = 0 # AIP-14: Requester's ERC-8004 agent ID + # AIP-14c v2: keccak(request+input+SLA); bytes32(0) = no auto AI ruling. + # Optional / non-breaking — defaults to the zero hash for existing callers. + agreement_hash: str = ZERO_BYTES32 @staticmethod def _is_valid_address(addr: str) -> bool: @@ -277,7 +286,7 @@ def to_transaction(self) -> Transaction: def from_tuple(cls, data: Tuple) -> "TransactionView": """Create from contract return tuple. - Expects the V3+ 21-field shape that ships with the bundled ABI: + Reads the V3 21-field prefix; the current ABI appends two hash words: [0] transaction_id [11] attestation_uid [1] requester [12] dispute_window [2] provider [13] metadata @@ -290,11 +299,9 @@ def from_tuple(cls, data: Tuple) -> "TransactionView": [9] escrow_contract [20] dispute_bond (AIP-14) [10] escrow_id - web3.py decodes against the bundled ABI, so tuples reaching this - method are already 21-field. Reading a pre-V3 (19-field) contract - with this SDK version will error at decode time before reaching - from_tuple — loud failure is the intended behavior so callers know - they're against the wrong contract generation. + The canonical decoder and exact-length historical fallback keep this + prefix aligned. The optional v2 hash suffix is not exposed by this view. + Unknown historical layouts are rejected rather than decoded as legacy. """ return cls( transaction_id="0x" + data[0].hex() if isinstance(data[0], bytes) else data[0], @@ -413,6 +420,8 @@ def __init__( chain_id: The chain ID of the network nonce_manager: Optional shared NonceManager for nonce tracking """ + if is_legacy_creation_kernel(contract.address): + contract = w3.eth.contract(address=contract.address, abi=kernel_creation_abi(contract.address, contract.abi)) super().__init__(contract, account, w3, chain_id, nonce_manager=nonce_manager) @classmethod @@ -501,20 +510,20 @@ async def create_transaction( provider_checksum = self.w3.to_checksum_address(params.provider) requester_checksum = self.w3.to_checksum_address(requester) - # Convert service_hash to bytes32 service_hash = self._to_bytes32(params.service_hash) + agreement_hash = self._to_bytes32(params.agreement_hash) - # Build transaction - contract_fn = self.contract.functions.createTransaction( + contract_fn = self.contract.functions.createTransaction(*kernel_creation_arguments(self.contract.address, [ provider_checksum, requester_checksum, params.amount, params.deadline, params.dispute_window, service_hash, + agreement_hash, params.agent_id, params.requester_agent_id, - ) + ], agreement_hash)) # P-2 fix: dynamic gas estimation with hardcoded floor fallback effective_gas = gas_limit or await self._estimate_gas( contract_fn, GAS_LIMITS["create_transaction"] @@ -586,6 +595,42 @@ async def transition_state( receipt = await self._sign_and_send(tx) return self._to_receipt(receipt) + async def recovery_grace(self) -> int: + """F-6: the immutable recovery grace (seconds) configured on the kernel.""" + return await self.contract.functions.recoveryGrace().call() + + async def get_recovery_deadline(self, transaction_id: str) -> int: + """ + F-6: timestamp at/after which a stalled IN_PROGRESS transaction becomes + recoverable (transaction deadline + recoveryGrace). SDK-side helper; + there is no on-chain getRecoveryDeadline. + """ + tx = await self.get_transaction(transaction_id) + grace = await self.recovery_grace() + return tx.deadline + grace + + async def recover_stalled_in_progress( + self, + transaction_id: str, + gas_limit: Optional[int] = None, + ) -> TransactionReceipt: + """ + F-6: permissionlessly recover a stalled IN_PROGRESS transaction once + deadline + recoveryGrace has elapsed. Moves it to CANCELLED and refunds + the remaining escrow to the requester (no penalty). Callable by anyone. + """ + tx_id_bytes = self._to_bytes32(transaction_id) + contract_fn = self.contract.functions.recoverStalledInProgress(tx_id_bytes) + effective_gas = gas_limit or await self._estimate_gas( + contract_fn, + GAS_LIMITS.get("recover_stalled_in_progress", GAS_LIMITS["transition_state"]), + ) + tx = await contract_fn.build_transaction( + await self._build_tx_params(gas_limit=effective_gas) + ) + receipt = await self._sign_and_send(tx) + return self._to_receipt(receipt) + async def accept_quote( self, transaction_id: str, @@ -893,12 +938,22 @@ async def raise_dispute( gas_limit: Optional[int] = None, ) -> TransactionReceipt: """ - Raise a dispute on a delivered transaction. + Raise a dispute on a delivered transaction (legacy single-shot kernel path). Reference: Yellow Paper §3.4 (Dispute Management) PARITY: Matches TS SDK raiseDispute() behavior. + TIERED FLOW: this is the PRE-AIP-14 path — it transitions the transaction + straight to DISPUTED, after which resolution historically required a + privileged :meth:`resolve_dispute`. The AIP-14b SUCCESSOR is the + three-tier bond game reached via the ``DisputeClient`` facade + (``client.dispute``): still call this to enter the kernel DISPUTED state, + but then drive resolution through ``client.dispute.bond`` (open -> + propose/AI -> challenge -> finalize / escalate_to_uma) and read state with + ``client.dispute.get_dispute_status()`` — NOT through ``resolve_dispute``. + See ``dispute/dispute_client.py`` (grep ``DisputeClient``). + Args: transaction_id: The transaction ID (bytes32 hex string) reason: Dispute reason (human-readable) @@ -952,7 +1007,7 @@ async def resolve_dispute( gas_limit: Optional[int] = None, ) -> TransactionReceipt: """ - Resolve a dispute with payment split. + Resolve a dispute with payment split (legacy privileged kernel path). Reference: Yellow Paper §3.4 @@ -960,6 +1015,15 @@ async def resolve_dispute( Disputes are settled via transitionState(SETTLED, proof) per §3.2. The kernel contract decodes the proof and handles escrow disbursement. + TIERED FLOW: this is the PRE-AIP-14 admin/mediator resolution. Under + AIP-14b resolution is driven by the bond game, not by a direct privileged + call here: route through the ``DisputeClient`` facade (``client.dispute``) + instead — ``client.dispute.bond.finalize()`` / ``escalate_to_uma()`` (then + the on-chain CompositeMediator settles), with + ``client.dispute.get_dispute_status()`` for the §9 sub-state. + ``resolve_dispute`` remains only for the legacy admin path. See + ``dispute/dispute_client.py`` (grep ``DisputeClient``). + Args: transaction_id: The transaction ID (bytes32 hex string) requester_amount: Amount to refund to requester (wei) @@ -1057,6 +1121,28 @@ async def settle_dispute( # Read Operations # ========================================================================= + async def get_escrow_principal(self, transaction_id: str) -> int: + """Distributable principal, excluding reserved fees and dispute bonds. + + Requires the fee-accounting kernel ABI. Read failures propagate. + """ + return int(await self.contract.functions.escrowPrincipal( + self._to_bytes32(transaction_id) + ).call()) + + async def retry_platform_fee( + self, transaction_id: str, gas_limit: Optional[int] = None + ) -> TransactionReceipt: + """Retry fees permissionlessly; a receipt does not prove funds moved. + + Zero debt is a no-op. A blocked fee recipient can leave debt pending. + Unknown transactions and revoked vaults propagate errors. + """ + fn = self.contract.functions.retryPlatformFee(self._to_bytes32(transaction_id)) + effective_gas = gas_limit if gas_limit is not None else await self._estimate_gas_strict(fn, 300_000) + tx = await fn.build_transaction(await self._build_tx_params(gas_limit=effective_gas)) + return self._to_receipt(await self._sign_and_send(tx)) + async def get_transaction(self, transaction_id: str) -> TransactionView: """ Get transaction details from the contract. @@ -1112,11 +1198,18 @@ async def get_transaction(self, transaction_id: str) -> TransactionView: raise try: - legacy = self.w3.eth.contract( - address=self.contract.address, - abi=_LEGACY_GET_TRANSACTION_ABI, - ) - result = await legacy.functions.getTransaction(tx_id_bytes).call() + # All supported tuples are static. eth_abi allows trailing words, + # so trying the 16-field decoder first silently corrupts V3 reads. + data = AsyncWeb3.keccak(text="getTransaction(bytes32)")[:4] + tx_id_bytes + raw = bytes(await self.w3.eth.call({"to": self.contract.address, "data": data})) + words = len(raw) // 32 + if len(raw) not in (16 * 32, 21 * 32, 23 * 32): + raise ValueError(f"Unsupported getTransaction return size: {len(raw)} bytes") + legacy_types = [c["type"] for c in _LEGACY_GET_TRANSACTION_ABI[0]["outputs"][0]["components"]] + v3_types = ("bytes32,address,address,uint8,uint256,uint256,uint256,uint256,bytes32,address," + "bytes32,bytes32,uint256,bytes32,uint16,uint16,uint16,uint256,uint256,address,uint256").split(",") + types = legacy_types if words == 16 else v3_types + (["bytes32", "bytes32"] if words == 23 else []) + result = decode_abi(["(" + ",".join(types) + ")"], raw)[0] except Exception as legacy_error: legacy_reason = str(legacy_error).lower() if "tx missing" in legacy_reason: @@ -1127,7 +1220,7 @@ async def get_transaction(self, transaction_id: str) -> TransactionView: tx_id=transaction_id, ) from legacy_error - return TransactionView.from_legacy_tuple(result) + return TransactionView.from_legacy_tuple(result) if words == 16 else TransactionView.from_tuple(result) return TransactionView.from_tuple(result) @@ -1187,17 +1280,19 @@ async def estimate_create_transaction( provider_checksum = self.w3.to_checksum_address(params.provider) requester_checksum = self.w3.to_checksum_address(requester) service_hash = self._to_bytes32(params.service_hash) + agreement_hash = self._to_bytes32(params.agreement_hash) - contract_fn = self.contract.functions.createTransaction( + contract_fn = self.contract.functions.createTransaction(*kernel_creation_arguments(self.contract.address, [ provider_checksum, requester_checksum, params.amount, params.deadline, params.dispute_window, service_hash, + agreement_hash, params.agent_id, params.requester_agent_id, - ) + ], agreement_hash)) return await contract_fn.estimate_gas({"from": self.account.address}) async def get_min_transaction_amount(self) -> int: @@ -1236,4 +1331,3 @@ def _extract_transaction_id(self, receipt: TxReceipt) -> str: "Could not extract transaction ID from receipt", tx_id=receipt.get("transactionHash", "unknown"), ) - diff --git a/src/agirails/protocol/kernel_creation.py b/src/agirails/protocol/kernel_creation.py new file mode 100644 index 0000000..5efcdc5 --- /dev/null +++ b/src/agirails/protocol/kernel_creation.py @@ -0,0 +1,42 @@ +"""Creation ABI selection for the locally pinned legacy deployment descriptor.""" +from typing import Any, List +from eth_abi import encode +from web3 import Web3 + +LEGACY_KERNEL = "0x048c811352e8a3fecd5b0ec4aa2c2b94083cc842" +CREATE_TYPES = ["address", "address", "uint256", "uint256", "uint256", "bytes32", "bytes32", "uint256", "uint256"] + + +def is_legacy_creation_kernel(address: Any) -> bool: + return isinstance(address, str) and address.lower() == LEGACY_KERNEL + + +def kernel_creation_arguments(address: str, args: List[Any], agreement_hash: bytes) -> List[Any]: + if len(args) != 9: + raise ValueError("Expected canonical nine creation arguments") + if not is_legacy_creation_kernel(address): + return args + if agreement_hash != bytes(32): + raise ValueError("Legacy kernel does not support agreement_hash; refusing to discard binding") + return args[:6] + args[7:] + + +def encode_kernel_creation(address: str, args: List[Any], agreement_hash: bytes) -> str: + values = kernel_creation_arguments(address, args, agreement_hash) + types = CREATE_TYPES[:6] + CREATE_TYPES[7:] if is_legacy_creation_kernel(address) else CREATE_TYPES + signature = "createTransaction(" + ",".join(types) + ")" + return Web3.to_hex(Web3.keccak(text=signature)[:4] + encode(types, values)) + + +def kernel_creation_abi(address: str, abi: List[Any]) -> List[Any]: + if not is_legacy_creation_kernel(address): + return abi + result = [] + for item in abi: + if item.get("name") == "createTransaction": + result.append({**item, "inputs": [field for field in item["inputs"] if field["name"] != "agreementHash"]}) + elif item.get("name") == "TransactionCreated": + result.append({**item, "inputs": [field for field in item["inputs"] if field["name"] != "agreementHash"]}) + else: + result.append(item) + return result diff --git a/src/agirails/protocol/messages.py b/src/agirails/protocol/messages.py index 8fb3270..d1a3250 100644 --- a/src/agirails/protocol/messages.py +++ b/src/agirails/protocol/messages.py @@ -100,6 +100,7 @@ ServiceRequest, ServiceResponse, SignedMessage, + _verification_type_definition, TypedData, ) @@ -939,14 +940,9 @@ def verify_signature( return False # Get the type definition based on message type - type_definitions = { - ServiceRequest.TYPE_NAME: ServiceRequest.TYPE_DEFINITION, - ServiceResponse.TYPE_NAME: ServiceResponse.TYPE_DEFINITION, - DeliveryProof.TYPE_NAME: DeliveryProof.TYPE_DEFINITION, - DeliveryProofMessage.TYPE_NAME: DeliveryProofMessage.TYPE_DEFINITION, - } - - type_def = type_definitions.get(signed_message.message_type) + type_def = _verification_type_definition( + signed_message.message_type, signed_message.message + ) if not type_def: return False diff --git a/src/agirails/reputation/__init__.py b/src/agirails/reputation/__init__.py new file mode 100644 index 0000000..8f9a787 --- /dev/null +++ b/src/agirails/reputation/__init__.py @@ -0,0 +1,29 @@ +# PARITY: sdk-js/src/reputation/ (DisputeSplitIndexer.ts) +""" +Reputation surfacing utilities (PRD P2-8). + +Exposes the :class:`DisputeSplitIndexer` — per-agent dispute split-rate +aggregation (AIP-14b §3.4/§3.5, OQ-11, INV-22). See +``dispute_split_indexer.py`` for the ZERO-REMAINING CONSUMER RULE and the +OQ-11 identical-weight semantics. +""" + +from agirails.reputation.dispute_split_indexer import ( + DisputeOutcome, + DisputeOutcomeKind, + DisputeSplitIndexer, + SplitRateBreakdown, + SplitRateResult, + is_split_kind, + outcome_from_split_recorded, +) + +__all__ = [ + "DisputeOutcome", + "DisputeOutcomeKind", + "DisputeSplitIndexer", + "SplitRateBreakdown", + "SplitRateResult", + "is_split_kind", + "outcome_from_split_recorded", +] diff --git a/src/agirails/reputation/dispute_split_indexer.py b/src/agirails/reputation/dispute_split_indexer.py new file mode 100644 index 0000000..006a00c --- /dev/null +++ b/src/agirails/reputation/dispute_split_indexer.py @@ -0,0 +1,290 @@ +# PARITY: sdk-js/src/reputation/DisputeSplitIndexer.ts +# Every public symbol here has a TS twin (same name/arity) and vice-versa. +""" +DisputeSplitIndexer — per-agent dispute split-rate surfacing (PRD P2-8, +AIP-14b §3.4 / §3.5, INV-22, INV-4). + +What it does +------------ +Surfaces the per-agent **split rate** — the fraction of an agent's resolved +disputes that ended in a SPLIT — so systematic dispute-to-split ambiguity +griefing is visible to future counterparties (e.g. *"14% of this agent's +disputes end in splits"*). A split carries NO on-chain reputation penalty +(INV-4); the rate is the ONLY signal, which is why under-counting it would +silently re-open the griefing path. + +OQ-11 (normative default — PRD §9, P2-8) +---------------------------------------- +A dispute counts as a SPLIT for the HEADLINE rate when it resolved via EITHER: + 1. ``DisputeSplitRecorded`` — CompositeMediator ruling-2 (finalize / + force_resolve_stale), OR + 2. kernel ``DISPUTED → CANCELLED`` — the kernel-level split path, which + includes **admin-CANCELLED** disputes that bypass CompositeMediator. +BOTH are counted at **IDENTICAL weight**. Counting only (1) would miss +admin-CANCELLED splits and undercount the rate (R11). The headline +``get_split_rate`` treats them as fungible; ``get_split_rate_breakdown`` exposes +the two sub-counts WITHOUT changing the headline number. + +ZERO-REMAINING CONSUMER RULE (AIP-14b §6, normative — load-bearing) +------------------------------------------------------------------- +Split classification derives from **event semantics + escrow ``remaining``**, +NEVER from resolution-proof amounts. When on-chain ``remaining == 0`` the proof +carries only a phantom 1-wei sentinel; this indexer NEVER reads it as a payout. +A drained dispute (remaining==0) still counts as a split. ``classify_payout`` +delegates to :func:`decode_resolution_proof`, which zeros the phantom sentinel. + +PARITY: sdk-js/src/reputation/DisputeSplitIndexer.ts — the shared golden fixture +``DISPUTE SYSTEM/test-vectors/dispute-split-indexer-vectors.json`` is consumed +byte-identically by both SDKs. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import List, Optional + +from agirails.dispute.composite_mediator import ( + DecodedResolutionProof, + DisputeSplitRecorded, + compute_split_rate, + decode_resolution_proof, +) + +# --------------------------------------------------------------------------- +# Outcome model +# --------------------------------------------------------------------------- + +# How a dispute resolved, for split-rate accounting (string literals identical +# to TS ``DisputeOutcomeKind``). Both split kinds are counted at identical weight +# (OQ-11); ``settled`` is a non-split resolution (kernel DISPUTED->SETTLED). +DisputeOutcomeKind = str # "disputeSplitRecorded" | "kernelDisputedToCancelled" | "settled" + +# The two split sources are fungible for the headline rate. +_SPLIT_KINDS = frozenset({"disputeSplitRecorded", "kernelDisputedToCancelled"}) + + +def is_split_kind(kind: str) -> bool: + """Return True for both split kinds (OQ-11: identical weight). + + PARITY: TS ``isSplitKind``. + """ + return kind in _SPLIT_KINDS + + +@dataclass +class DisputeOutcome: + """ + One resolved dispute, normalized for split-rate accounting. + + Assembled from ``DisputeSplitRecorded`` events + kernel + ``StateTransitioned(DISPUTED->CANCELLED / DISPUTED->SETTLED)`` events, joined + with the kernel transaction's ``provider``/``requester``. ``remaining`` is + the kernel escrowPrincipal at resolution time and is the ONLY thing + (with ``kind``) that drives classification — proof amounts are never trusted + (ZERO-REMAINING RULE). + + PARITY: TS ``DisputeOutcome`` interface. + """ + + provider: str + requester: str + kind: DisputeOutcomeKind + remaining: int = 0 + split_bps: Optional[int] = None + proof: Optional[str] = None + tx_id: Optional[str] = None + escrow_principal: Optional[int] = None + + +@dataclass +class SplitRateResult: + """Per-agent split-rate result. PARITY: TS ``SplitRateResult``.""" + + agent_id: str + split_count: int + total_disputes: int + split_rate: float + + +@dataclass +class SplitRateBreakdown(SplitRateResult): + """ + Split-rate result WITH the OQ-11 source breakdown. The headline ``split_rate`` + is unchanged (both sources at identical weight); the sub-counts are diagnostic. + + PARITY: TS ``SplitRateBreakdown``. + """ + + mediator_split_count: int = 0 + admin_split_count: int = 0 + + +# --------------------------------------------------------------------------- +# Address helper +# --------------------------------------------------------------------------- + + +def _same_address(a: str, b: str) -> bool: + """Case-insensitive address equality (checksum-agnostic).""" + return a.lower() == b.lower() + + +# --------------------------------------------------------------------------- +# Indexer +# --------------------------------------------------------------------------- + + +class DisputeSplitIndexer: + """ + Aggregates :class:`DisputeOutcome` records into per-agent split rates. + + The indexer is a PURE accumulator over already-decoded outcomes — it does NOT + hold a provider/signer. Callers feed it outcomes assembled from + ``EventMonitor.get_dispute_events()`` (which already surfaces + ``DisputeSplitRecorded`` AND kernel ``DISPUTED->CANCELLED``) joined with + kernel transaction lookups. This keeps it deterministic + trivially testable + against the shared golden fixture, and keeps the ZERO-REMAINING rule enforced + in one place. + + PARITY: TS ``DisputeSplitIndexer``. + """ + + def __init__(self, outcomes: Optional[List[DisputeOutcome]] = None) -> None: + """ + Args: + outcomes: optional initial outcomes to seed the indexer. + """ + self._outcomes: List[DisputeOutcome] = [] + if outcomes: + self.add_outcomes(outcomes) + + def add_outcome(self, outcome: DisputeOutcome) -> None: + """Record a single resolved dispute. PARITY: TS ``addOutcome``.""" + self._outcomes.append(outcome) + + def add_outcomes(self, outcomes: List[DisputeOutcome]) -> None: + """Record many resolved disputes. PARITY: TS ``addOutcomes``.""" + for o in outcomes: + self.add_outcome(o) + + def get_outcomes(self) -> List[DisputeOutcome]: + """All recorded outcomes (defensive copy). PARITY: TS ``getOutcomes``.""" + return list(self._outcomes) + + def size(self) -> int: + """Number of recorded outcomes. PARITY: TS ``size``.""" + return len(self._outcomes) + + def clear(self) -> None: + """Clear all recorded outcomes. PARITY: TS ``clear``.""" + self._outcomes.clear() + + def get_split_rate(self, agent_id: str) -> SplitRateResult: + """ + The HEADLINE split rate for an agent (OQ-11 default). + + Counts BOTH ``disputeSplitRecorded`` AND ``kernelDisputedToCancelled`` + (incl. admin-CANCELLED) at IDENTICAL weight over the agent's total + disputes. A drained dispute (remaining==0) still counts as a split. + PARITY: TS ``getSplitRate``. + + Args: + agent_id: the provider address whose rate to compute. + """ + mine = [o for o in self._outcomes if _same_address(o.provider, agent_id)] + split_recorded = sum(1 for o in mine if o.kind == "disputeSplitRecorded") + kernel_disputed_to_cancelled = sum( + 1 for o in mine if o.kind == "kernelDisputedToCancelled" + ) + total_disputes = len(mine) + + # Reuse the P2-5 primitive so the headline arithmetic is identical to the + # CompositeMediator client's compute_split_rate (OQ-11: equal weight). + split_rate = compute_split_rate( + split_recorded, + kernel_disputed_to_cancelled, + total_disputes, + ) + + return SplitRateResult( + agent_id=agent_id, + split_count=split_recorded + kernel_disputed_to_cancelled, + total_disputes=total_disputes, + split_rate=split_rate, + ) + + def get_split_rate_breakdown(self, agent_id: str) -> SplitRateBreakdown: + """ + The split rate WITH the OQ-11 source breakdown. The headline ``split_rate`` + is identical to :meth:`get_split_rate` (both sources at equal weight); the + sub-counts (``mediator_split_count``, ``admin_split_count``) are diagnostic + only. PARITY: TS ``getSplitRateBreakdown``. + """ + base = self.get_split_rate(agent_id) + mine = [o for o in self._outcomes if _same_address(o.provider, agent_id)] + return SplitRateBreakdown( + agent_id=base.agent_id, + split_count=base.split_count, + total_disputes=base.total_disputes, + split_rate=base.split_rate, + mediator_split_count=sum( + 1 for o in mine if o.kind == "disputeSplitRecorded" + ), + admin_split_count=sum( + 1 for o in mine if o.kind == "kernelDisputedToCancelled" + ), + ) + + def classify_payout( + self, outcome: DisputeOutcome + ) -> Optional[DecodedResolutionProof]: + """ + Classify the ECONOMIC payout of one outcome under the ZERO-REMAINING + CONSUMER RULE (AIP-14b §6). Delegates to the P2-5 + :func:`decode_resolution_proof`, which ZEROS both payouts and flags + ``phantom_sentinel`` when ``remaining == 0``. + + Used by the drained-dispute test to assert that NO 1-wei payout is ever + surfaced. Returns ``None`` when the outcome carried no proof (split + counting does not need it). PARITY: TS ``classifyPayout``. + """ + if outcome.proof is None: + return None + principal = outcome.escrow_principal if outcome.escrow_principal is not None else outcome.remaining + return decode_resolution_proof(outcome.proof, principal) + + +def outcome_from_split_recorded( + event: DisputeSplitRecorded, + remaining: int = 0, + proof: Optional[str] = None, +) -> DisputeOutcome: + """ + Build a :class:`DisputeOutcome` from a decoded ``DisputeSplitRecorded`` event. + The ``remaining`` MUST be supplied separately (read via ACTPKernel.get_escrow_principal immediately before + resolution) — it is NOT in the event. PARITY: TS + ``outcomeFromSplitRecorded``. + """ + return DisputeOutcome( + provider=event.provider, + requester=event.requester, + kind="disputeSplitRecorded", + remaining=remaining, + escrow_principal=remaining, + split_bps=event.split_bps, + proof=proof, + tx_id=event.tx_id, + ) + + +__all__ = [ + # Outcome model + "DisputeOutcomeKind", + "DisputeOutcome", + "SplitRateResult", + "SplitRateBreakdown", + "is_split_kind", + # Indexer + "DisputeSplitIndexer", + "outcome_from_split_recorded", +] diff --git a/src/agirails/types/__init__.py b/src/agirails/types/__init__.py index 0511841..c05f37f 100644 --- a/src/agirails/types/__init__.py +++ b/src/agirails/types/__init__.py @@ -37,6 +37,24 @@ is_valid_transition, VALID_TRANSITIONS, ) +from agirails.types.dispute import ( + Ruling, + Tier, + AIRuling, + DisputeState, + DisputeEIP712Domain, + DOMAIN_TYPEHASH, + RULING_TYPEHASH, + AIRULING_TYPES, + DISPUTE_EVALUATOR_DOMAIN_NAME, + DISPUTE_EVALUATOR_DOMAIN_VERSION, + dispute_evaluator_domain, + compute_ruling_struct_hash, + compute_ruling_domain_separator, + compute_ruling_digest, + sign_ruling, + recover_ruling_signer, +) __all__ = [ # DID types @@ -66,4 +84,21 @@ "TransactionFilter", "is_valid_transition", "VALID_TRANSITIONS", + # Dispute types (AIP-14b AIRuling EIP-712) + "Ruling", + "Tier", + "AIRuling", + "DisputeState", + "DisputeEIP712Domain", + "DOMAIN_TYPEHASH", + "RULING_TYPEHASH", + "AIRULING_TYPES", + "DISPUTE_EVALUATOR_DOMAIN_NAME", + "DISPUTE_EVALUATOR_DOMAIN_VERSION", + "dispute_evaluator_domain", + "compute_ruling_struct_hash", + "compute_ruling_domain_separator", + "compute_ruling_digest", + "sign_ruling", + "recover_ruling_signer", ] diff --git a/src/agirails/types/dispute.py b/src/agirails/types/dispute.py new file mode 100644 index 0000000..66a1f1b --- /dev/null +++ b/src/agirails/types/dispute.py @@ -0,0 +1,582 @@ +# PARITY: sdk-js/src/types/dispute.ts +# This file and its TypeScript twin MUST stay 1:1 — same public function/type/enum +# names + arity, same EIP-712 digest, same enum VALUES (Tier/Ruling). Any change +# here (rename, reorder, new export) must be mirrored in the twin and vice versa. +""" +AIP-14b dispute types + AIRuling EIP-712 signing for the AGIRAILS SDK. + +This module is the Python half of the cross-language AIRuling signer. It is +1:1 with the TypeScript SDK (`sdk-js/src/types/dispute.ts`): same public API +names + arity, same canonical EIP-712 digest, anchored to the GOLDEN VECTOR. + +Source of truth for the encoding: + Protocol/actp-kernel/src/interfaces/DisputeTypes.sol (AIRuling struct) + Protocol/actp-kernel/test/EncodingCanonical.t.sol (golden vector) + +The AIRuling field ORDER is load-bearing — it is hashed into RULING_TYPEHASH, +so any reorder breaks signature verification across the off-chain evaluator, +the SDK, and the on-chain `_verifyEvaluatorSignatures`. Field order matches +AIP-14b §4.4 exactly: + + disputeId, ruling, confidence, splitBps, timestamp, reasoningHash, bundleHash, + evidenceRefHash, reasoningRefHash (AIP-14c 9-field type) + +Golden vector (cross-language anchor, MUST reproduce GOLDEN_DIGEST exactly): + domain: name="ACTPDisputeEvaluator", version="1", chainId=8453, + verifyingContract=0x3c68CC8dFe901c7e89eC9f738F9a81709E6e7737 + AIRuling: disputeId=keccak256("ACTP_GOLDEN_VECTOR_DISPUTE"), ruling=1, + confidence=9500, splitBps=0, timestamp=1700000000, + reasoningHash=keccak256("golden-reasoning"), + bundleHash=keccak256("golden-bundle"), + evidenceRefHash=keccak256("golden-evidence-ref"), + reasoningRefHash=keccak256("golden-reasoning-ref") + => GOLDEN_DIGEST = 0xc14778f377cd385dd4686b798cb2a010c8ff95e8a35a4f170af7e05bc8c2d8a0 + +Example: + >>> ruling = AIRuling( + ... dispute_id="0x...", + ... ruling=Ruling.REQUESTER_WINS, + ... confidence=9500, + ... split_bps=0, + ... timestamp=1700000000, + ... reasoning_hash="0x...", + ... bundle_hash="0x...", + ... ) + >>> digest = compute_ruling_digest(ruling, chain_id=8453, + ... verifying_contract="0x3c68...") + >>> sig = sign_ruling(ruling, private_key, chain_id=8453, + ... verifying_contract="0x3c68...") + >>> signer = recover_ruling_signer(ruling, sig, chain_id=8453, + ... verifying_contract="0x3c68...") +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import IntEnum +from typing import Any, Dict, List, Optional, Union + +from eth_abi import encode as _abi_encode +from eth_account import Account +from eth_utils import keccak as _keccak, to_checksum_address + + +# --------------------------------------------------------------------------- +# Enums (1:1 with TS SDK Ruling / DisputeTier) +# --------------------------------------------------------------------------- + + +class Ruling(IntEnum): + """ + AIRuling.ruling values (INV-1 canonical mapping — load-bearing). + + Matches DisputeTypes.sol: + 0 = provider wins + 1 = requester wins + 2 = split (provider share given by splitBps) + """ + + PROVIDER_WINS = 0 + REQUESTER_WINS = 1 + SPLIT = 2 + + +class Tier(IntEnum): + """ + AIP-14b dispute escalation tier — 1:1 with the TS ``Tier`` twin AND the + on-chain ``BondEscalation.sol`` ``d.tier`` field (which is 0-based): + + tier: 0 (opened) -> d.tier = 1 (proposal/challenge live) -> d.tier = 2 (UMA) + + A ``disputes()`` / ``d.tier`` reader in either SDK MUST classify identically; + a 1-based enum would alias every on-chain tier value by one and misclassify + the moment a reader is wired (see the negative-control test pinning + ``Tier.TIER1 == 1``). + + - ``TIER0`` (0): dispute opened, no proposal yet (bond game not started). + - ``TIER1`` (1): a direct/AI proposal is live in the challengeable bond game. + - ``TIER2`` (2): escalated to UMA Optimistic Oracle V3. + """ + + TIER0 = 0 + TIER1 = 1 + TIER2 = 2 + + +# --------------------------------------------------------------------------- +# EIP-712 constants (frozen — match EncodingCanonical.t.sol) +# --------------------------------------------------------------------------- + +# keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") +# +# REPRESENTATION NOTE: this is `bytes` in Python; the TS twin (`DOMAIN_TYPEHASH`) +# exposes the same constant as a 0x-hex `string`. The underlying 32 bytes are +# identical — compare raw bytes across langs, not the surface type. +DOMAIN_TYPEHASH: bytes = _keccak( + text="EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" +) + +# keccak256("AIRuling(bytes32 disputeId,uint8 ruling,uint16 confidence,uint16 splitBps,uint64 timestamp,bytes32 reasoningHash,bytes32 bundleHash,bytes32 evidenceRefHash,bytes32 reasoningRefHash)") +# = 0x00e11bf3b34994a6bc6e216b116cbdaddee1227d0c97d46416f8d994ba8420ae (AIP-14c 9-field type) +# +# REPRESENTATION NOTE: this is `bytes` in Python; the TS twin (`RULING_TYPEHASH`) +# exposes the same constant as a 0x-hex `string`. Cross-language VALUE is +# byte-identical (golden test proves it) — a consumer comparing across langs +# must compare the 32 raw bytes (Py: `RULING_TYPEHASH`, +# TS: `ethers.getBytes(RULING_TYPEHASH)`), NOT the surface type. +RULING_TYPEHASH: bytes = _keccak( + text="AIRuling(bytes32 disputeId,uint8 ruling,uint16 confidence,uint16 splitBps,uint64 timestamp,bytes32 reasoningHash,bytes32 bundleHash,bytes32 evidenceRefHash,bytes32 reasoningRefHash)" +) + +# bytes32(0) — the default for an unset evidence_ref_hash / reasoning_ref_hash. +_ZERO_BYTES32: bytes = b"\x00" * 32 + +# EIP-712 domain identity for the dispute evaluator (AIP-14b §4.5). +# Names mirror the TS twin's `DISPUTE_EVALUATOR_DOMAIN_NAME` / `_VERSION` exactly. +DISPUTE_EVALUATOR_DOMAIN_NAME: str = "ACTPDisputeEvaluator" +DISPUTE_EVALUATOR_DOMAIN_VERSION: str = "1" + +# EIP-712 typed-data definition for AIRuling (mirrors the TS `AIRulingTypes` +# const). Field ORDER is load-bearing — it is hashed into RULING_TYPEHASH and is +# the single source the struct hash is derived from. +AIRULING_TYPES: Dict[str, List[Dict[str, str]]] = { + "AIRuling": [ + {"name": "disputeId", "type": "bytes32"}, + {"name": "ruling", "type": "uint8"}, + {"name": "confidence", "type": "uint16"}, + {"name": "splitBps", "type": "uint16"}, + {"name": "timestamp", "type": "uint64"}, + {"name": "reasoningHash", "type": "bytes32"}, + {"name": "bundleHash", "type": "bytes32"}, + {"name": "evidenceRefHash", "type": "bytes32"}, + {"name": "reasoningRefHash", "type": "bytes32"}, + ] +} + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _to_bytes32(value: Union[str, bytes]) -> bytes: + """ + Normalize a bytes32 input (0x-hex string or raw bytes) to exactly 32 bytes. + + Raises: + ValueError: if the decoded value is not 32 bytes. + """ + if isinstance(value, bytes): + raw = value + else: + s = value[2:] if value.startswith(("0x", "0X")) else value + raw = bytes.fromhex(s) + if len(raw) != 32: + raise ValueError(f"expected bytes32 (32 bytes), got {len(raw)} bytes") + return raw + + +def _normalize_signature(signature: Union[str, bytes]) -> bytes: + """Normalize a 65-byte signature (0x-hex string or raw bytes) to bytes.""" + if isinstance(signature, bytes): + return signature + s = signature[2:] if signature.startswith(("0x", "0X")) else signature + return bytes.fromhex(s) + + +# --------------------------------------------------------------------------- +# EIP712Domain for disputes +# --------------------------------------------------------------------------- + + +@dataclass +class DisputeEIP712Domain: + """ + EIP-712 domain for the ACTP dispute evaluator. + + Mirrors the TS SDK domain builder. Defaults to the AIP-14b dispute identity + (name="ACTPDisputeEvaluator", version="1"). + """ + + chain_id: int + verifying_contract: str + name: str = DISPUTE_EVALUATOR_DOMAIN_NAME + version: str = DISPUTE_EVALUATOR_DOMAIN_VERSION + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary (camelCase, for EIP-712 tooling).""" + return { + "name": self.name, + "version": self.version, + "chainId": self.chain_id, + "verifyingContract": to_checksum_address(self.verifying_contract), + } + + def separator(self) -> bytes: + """Compute the EIP-712 domain separator (32 bytes).""" + return _keccak( + _abi_encode( + ["bytes32", "bytes32", "bytes32", "uint256", "address"], + [ + DOMAIN_TYPEHASH, + _keccak(text=self.name), + _keccak(text=self.version), + self.chain_id, + to_checksum_address(self.verifying_contract), + ], + ) + ) + + +# --------------------------------------------------------------------------- +# AIRuling +# --------------------------------------------------------------------------- + + +@dataclass +class AIRuling: + """ + AIP-14b §4.4 AI ruling for EIP-712 signing. + + PARITY CRITICAL: field order is load-bearing and matches DisputeTypes.sol + AIRuling struct exactly. The TYPE_DEFINITION mirrors the TS SDK. + + Attributes: + dispute_id: bytes32 dispute id + ruling: uint8 — 0 provider wins, 1 requester wins, 2 split (INV-1) + confidence: uint16 — confidence in basis points (0..10000) + split_bps: uint16 — provider share when ruling == 2 (basis points) + timestamp: uint64 — unix epoch seconds + reasoning_hash: bytes32 — hash of the evaluator's reasoning + bundle_hash: bytes32 — hash of the canonical evidence bundle + evidence_ref_hash: bytes32 (AIP-14c D7) — evidence CID commitment + ``keccak256(abi.encode(bundle_hash, keccak256(bytes(evidence_cid))))``. + Optional; a missing value defaults to bytes32(0), exactly like on-chain. + reasoning_ref_hash: bytes32 (AIP-14c D7) — reasoning CID commitment + ``keccak256(abi.encode(reasoning_hash, keccak256(bytes(reasoning_cid))))``. + Optional; defaults to bytes32(0). + """ + + dispute_id: Union[str, bytes] + ruling: int + confidence: int + split_bps: int + timestamp: int + reasoning_hash: Union[str, bytes] + bundle_hash: Union[str, bytes] + # AIP-14c D7 CID-commitment ref-hashes. Defaulted so a pre-D7 / direct-proposal + # caller may omit them; they hash as bytes32(0) (matching the TS twin's + # withRefDefaults + the on-chain default). + evidence_ref_hash: Union[str, bytes] = _ZERO_BYTES32 + reasoning_ref_hash: Union[str, bytes] = _ZERO_BYTES32 + + # EIP-712 type constants — MUST match DisputeTypes.sol field order exactly. + TYPE_NAME = "AIRuling" + TYPE_DEFINITION = [ + {"name": "disputeId", "type": "bytes32"}, + {"name": "ruling", "type": "uint8"}, + {"name": "confidence", "type": "uint16"}, + {"name": "splitBps", "type": "uint16"}, + {"name": "timestamp", "type": "uint64"}, + {"name": "reasoningHash", "type": "bytes32"}, + {"name": "bundleHash", "type": "bytes32"}, + {"name": "evidenceRefHash", "type": "bytes32"}, + {"name": "reasoningRefHash", "type": "bytes32"}, + ] + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary (camelCase) for EIP-712 signing tooling.""" + return { + "disputeId": self.dispute_id + if isinstance(self.dispute_id, str) + else "0x" + self.dispute_id.hex(), + "ruling": int(self.ruling), + "confidence": int(self.confidence), + "splitBps": int(self.split_bps), + "timestamp": int(self.timestamp), + "reasoningHash": self.reasoning_hash + if isinstance(self.reasoning_hash, str) + else "0x" + self.reasoning_hash.hex(), + "bundleHash": self.bundle_hash + if isinstance(self.bundle_hash, str) + else "0x" + self.bundle_hash.hex(), + "evidenceRefHash": "0x" + _to_bytes32(self.evidence_ref_hash).hex(), + "reasoningRefHash": "0x" + _to_bytes32(self.reasoning_ref_hash).hex(), + } + + def struct_hash(self) -> bytes: + """ + Compute the EIP-712 struct hash (32 bytes): + + keccak256(abi.encode(RULING_TYPEHASH, disputeId, ruling, confidence, + splitBps, timestamp, reasoningHash, bundleHash, + evidenceRefHash, reasoningRefHash)) + + Each field is ABI-encoded (padded to 32 bytes). Field order is load-bearing. + """ + return _keccak( + _abi_encode( + [ + "bytes32", # RULING_TYPEHASH + "bytes32", # disputeId + "uint8", # ruling + "uint16", # confidence + "uint16", # splitBps + "uint64", # timestamp + "bytes32", # reasoningHash + "bytes32", # bundleHash + "bytes32", # evidenceRefHash (AIP-14c D7) + "bytes32", # reasoningRefHash (AIP-14c D7) + ], + [ + RULING_TYPEHASH, + _to_bytes32(self.dispute_id), + int(self.ruling), + int(self.confidence), + int(self.split_bps), + int(self.timestamp), + _to_bytes32(self.reasoning_hash), + _to_bytes32(self.bundle_hash), + _to_bytes32(self.evidence_ref_hash), + _to_bytes32(self.reasoning_ref_hash), + ], + ) + ) + + +# --------------------------------------------------------------------------- +# DisputeState (1:1 with the TS `DisputeState` interface) +# --------------------------------------------------------------------------- + + +@dataclass +class DisputeState: + """ + On-chain dispute state view (AIP-14b) — mirrors the TS ``DisputeState`` + interface. The fields a ``disputes(...)`` reader surfaces from BondEscalation. + + Attributes: + tx_id: the transaction this dispute is bound to (bytes32 txId). + dispute_id: keccak256 dispute identifier (bytes32). + tier: current escalation tier (0-based; see :class:`Tier`). + ruling: finalized ruling once resolved (``None`` while unresolved). + split_bps: provider share in basis points (relevant for ``ruling == 2``). + resolved: whether the dispute has been finalized / resolved on-chain. + """ + + tx_id: str + dispute_id: str + tier: int + resolved: bool + ruling: Optional[int] = None + split_bps: Optional[int] = None + + +# --------------------------------------------------------------------------- +# Top-level signing API (1:1 with TS SDK names + arity) +# --------------------------------------------------------------------------- + + +def dispute_evaluator_domain( + chain_id: int, + verifying_contract: str, +) -> DisputeEIP712Domain: + """ + Build the EIP-712 domain for the dispute evaluator (AIP-14b §4.5). + + Module-level builder mirroring the TS twin's ``disputeEvaluatorDomain`` + (same name + arity). Returns a :class:`DisputeEIP712Domain` pinned to the + frozen ``ACTPDisputeEvaluator`` / version ``1`` identity. + + Args: + chain_id: chain the verifying contract is deployed on (e.g. 8453 = Base). + verifying_contract: the BondEscalation (dispute evaluator) contract address. + """ + return DisputeEIP712Domain( + chain_id=chain_id, verifying_contract=verifying_contract + ) + + +def compute_ruling_struct_hash(ruling: AIRuling) -> bytes: + """ + Compute the EIP-712 struct hash for an AIRuling + (``keccak256(abi.encode(RULING_TYPEHASH, ...fields))``). + + Module-level free function mirroring the TS twin's ``computeRulingStructHash`` + (same name + arity); delegates to :meth:`AIRuling.struct_hash`. + + Returns: + 32-byte struct hash. + """ + return ruling.struct_hash() + + +def compute_ruling_domain_separator( + chain_id: int, + verifying_contract: str, +) -> bytes: + """ + Compute the EIP-712 domain separator for the dispute-evaluator domain + (``keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(name), keccak256(version), + chainId, verifyingContract))``). + + Module-level free function mirroring the TS twin's + ``computeRulingDomainSeparator`` (same name + arity); delegates to + :meth:`DisputeEIP712Domain.separator`. + + Returns: + 32-byte domain separator. + """ + return dispute_evaluator_domain(chain_id, verifying_contract).separator() + + +def compute_ruling_digest( + ruling: AIRuling, + chain_id: int, + verifying_contract: str, +) -> bytes: + """ + Compute the EIP-712 digest for an AIRuling. + + digest = keccak256(0x1901 || DOMAIN_SEPARATOR || structHash) + + Mirrors the TS SDK `computeRulingDigest`. The digest is exactly what the + on-chain `submitAIRuling` path verifies — sign THIS to produce an + on-chain-verifiable ruling. + + Args: + ruling: the AIRuling to hash. + chain_id: EIP-712 domain chain id (e.g. 8453 for Base mainnet). + verifying_contract: the dispute contract address (BondEscalation). + + Returns: + 32-byte EIP-712 digest. + """ + domain = DisputeEIP712Domain( + chain_id=chain_id, verifying_contract=verifying_contract + ) + return _keccak(b"\x19\x01" + domain.separator() + ruling.struct_hash()) + + +def sign_ruling( + ruling: AIRuling, + private_key: Union[str, bytes], + chain_id: int, + verifying_contract: str, +) -> str: + """ + Sign an AIRuling, producing a 65-byte (r||s||v) signature over the EIP-712 + digest. Mirrors the TS SDK `signRuling`. + + Args: + ruling: the AIRuling to sign. + private_key: evaluator private key (0x-hex string or raw bytes). + chain_id: EIP-712 domain chain id. + verifying_contract: the dispute contract address. + + Returns: + 0x-prefixed hex signature (65 bytes, canonical r||s||v). + """ + digest = compute_ruling_digest(ruling, chain_id, verifying_contract) + account = Account.from_key(private_key) + signed = account.unsafe_sign_hash(digest) + return signed.signature.hex() if signed.signature.hex().startswith("0x") else "0x" + signed.signature.hex() + + +def compute_evidence_ref_hash( + bundle_hash: Union[str, bytes], + evidence_cid: str, +) -> bytes: + """ + Compute the AIP-14c D7 evidence CID commitment: + + keccak256(abi.encode(bundleHash, keccak256(bytes(evidenceCID)))) + + This is the SAME formula ``BondEscalation.submitAIRuling`` recomputes + on-chain and requires to equal the SIGNED ``ruling.evidenceRefHash`` before + any bond transfer (AIP14C-BOND-ABI-FREEZE.md). Mirrors the TS twin. + + Returns: + 32-byte evidence ref hash. + """ + return _keccak( + _abi_encode( + ["bytes32", "bytes32"], + [_to_bytes32(bundle_hash), _keccak(text=evidence_cid)], + ) + ) + + +def compute_reasoning_ref_hash( + reasoning_hash: Union[str, bytes], + reasoning_cid: str, +) -> bytes: + """ + Compute the AIP-14c D7 reasoning CID commitment: + + keccak256(abi.encode(reasoningHash, keccak256(bytes(reasoningCID)))) + + Recomputed + equality-checked on-chain against the SIGNED + ``ruling.reasoningRefHash`` (AIP14C-BOND-ABI-FREEZE.md). Mirrors the TS twin. + + Returns: + 32-byte reasoning ref hash. + """ + return _keccak( + _abi_encode( + ["bytes32", "bytes32"], + [_to_bytes32(reasoning_hash), _keccak(text=reasoning_cid)], + ) + ) + + +def recover_ruling_signer( + ruling: AIRuling, + signature: Union[str, bytes], + chain_id: int, + verifying_contract: str, +) -> str: + """ + Recover the signer address from an AIRuling signature. Mirrors the TS SDK + `recoverRulingSigner`. + + Args: + ruling: the AIRuling that was signed. + signature: 65-byte signature (0x-hex string or raw bytes). + chain_id: EIP-712 domain chain id. + verifying_contract: the dispute contract address. + + Returns: + Checksummed signer address. + """ + digest = compute_ruling_digest(ruling, chain_id, verifying_contract) + sig = _normalize_signature(signature) + return Account._recover_hash(digest, signature=sig) + + +__all__ = [ + # Enums + "Ruling", + "Tier", + # Types + "AIRuling", + "DisputeState", + "DisputeEIP712Domain", + # Constants + "DOMAIN_TYPEHASH", + "RULING_TYPEHASH", + "AIRULING_TYPES", + "DISPUTE_EVALUATOR_DOMAIN_NAME", + "DISPUTE_EVALUATOR_DOMAIN_VERSION", + # Domain / digest helpers (1:1 with TS standalone functions) + "dispute_evaluator_domain", + "compute_ruling_struct_hash", + "compute_ruling_domain_separator", + # D7 CID-commitment ref-hash builders (1:1 with TS) + "compute_evidence_ref_hash", + "compute_reasoning_ref_hash", + # Signing API + "compute_ruling_digest", + "sign_ruling", + "recover_ruling_signer", +] diff --git a/src/agirails/types/erc8004.py b/src/agirails/types/erc8004.py index 8cb7c6f..6614b5b 100644 --- a/src/agirails/types/erc8004.py +++ b/src/agirails/types/erc8004.py @@ -48,6 +48,13 @@ "SETTLED": "actp_settled", "DISPUTE_WON": "actp_dispute_won", "DISPUTE_LOST": "actp_dispute_lost", + # Neutral split-outcome trace (AIP-14b §3.4, §3.5, INV-22). A dispute that + # resolved to a SPLIT (CompositeMediator ruling-2 or kernel DISPUTED->CANCELLED). + # Carries NO on-chain penalty — written with value=0 — but is NOT + # reputation-invisible: indexers surface per-agent split rates. + # PARITY: TS ACTP_FEEDBACK_TAGS.DISPUTE_SPLIT — the tag STRING + # 'actp_dispute_split' is identical across both SDKs. + "DISPUTE_SPLIT": "actp_dispute_split", } # --------------------------------------------------------------------------- diff --git a/src/agirails/types/message.py b/src/agirails/types/message.py index a25f68a..86823ab 100644 --- a/src/agirails/types/message.py +++ b/src/agirails/types/message.py @@ -697,3 +697,20 @@ def create_output_hash(output_data: Any) -> str: Hex-encoded keccak256 hash (bytes32, 0x prefixed) """ return create_input_hash(output_data) + + +def _verification_type_definition(message_type: str, message: dict[str, Any]) -> list[dict[str, str]]: + if not isinstance(message, dict): + return [] + if message_type != DeliveryProof.TYPE_NAME: + return { + ServiceRequest.TYPE_NAME: ServiceRequest.TYPE_DEFINITION, + ServiceResponse.TYPE_NAME: ServiceResponse.TYPE_DEFINITION, + }.get(message_type, []) + + matching = [ + proof.TYPE_DEFINITION + for proof in (DeliveryProof, DeliveryProofMessage) + if all(member["name"] in message for member in proof.TYPE_DEFINITION) + ] + return matching[0] if len(matching) == 1 else [] diff --git a/src/agirails/types/x402.py b/src/agirails/types/x402.py index 9aefdd3..c8f8291 100644 --- a/src/agirails/types/x402.py +++ b/src/agirails/types/x402.py @@ -289,6 +289,14 @@ def __init__(self, message: str, details: Optional[dict] = None) -> None: self.name = "X402NetworkNotAllowedError" +class X402QuoteMismatchError(X402V2Error): + """Accepted quote and actual payment request/requirements do not agree.""" + + def __init__(self, message: str) -> None: + super().__init__(message, "X402_QUOTE_MISMATCH") + self.name = "X402QuoteMismatchError" + + class X402AmountExceededError(X402V2Error): """Required amount exceeds maxAmountPerTx cap (code X402_AMOUNT_EXCEEDED).""" diff --git a/src/agirails/utils/http.py b/src/agirails/utils/http.py new file mode 100644 index 0000000..e99e56e --- /dev/null +++ b/src/agirails/utils/http.py @@ -0,0 +1,57 @@ +"""Standard-library HTTP fallback with an explicit protocol boundary.""" + +from typing import Any, Optional +from urllib.error import URLError +from urllib.parse import urlsplit +from urllib.request import ( + HTTPDefaultErrorHandler, + HTTPErrorProcessor, + HTTPHandler, + HTTPRedirectHandler, + HTTPSHandler, + OpenerDirector, + ProxyHandler, + Request, + UnknownHandler, +) + + +def _require_http(url: str) -> None: + if urlsplit(url).scheme.lower() not in {"http", "https"}: + raise URLError("Only HTTP and HTTPS URLs are supported") + + +class _HTTPRedirectHandler(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + _require_http(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +class _HTTPRequest(Request): + def __init__(self, url, *, data=None, headers=None, method=None): + _require_http(url) + super().__init__(url, data=data, headers=headers or {}, method=method) + + +def request_http( + url: str, + *, + timeout: float, + headers: Optional[dict[str, str]] = None, + data: Optional[bytes] = None, + method: Optional[str] = None, +) -> Any: + """Open HTTP(S), including redirects, without file/data/FTP handlers.""" + request = _HTTPRequest(url, data=data, headers=headers, method=method) + opener = OpenerDirector() + for handler in ( + ProxyHandler(), + UnknownHandler(), + HTTPHandler(), + HTTPDefaultErrorHandler(), + _HTTPRedirectHandler(), + HTTPErrorProcessor(), + HTTPSHandler(), + ): + opener.add_handler(handler) + return opener.open(request, timeout=timeout) diff --git a/src/agirails/version.py b/src/agirails/version.py index b38ecbe..e8481f2 100644 --- a/src/agirails/version.py +++ b/src/agirails/version.py @@ -1,4 +1,4 @@ """AGIRAILS SDK version information.""" -__version__ = "4.8.0" -__version_info__ = (4, 8, 0) +__version__ = "4.9.0" +__version_info__ = (4, 9, 0) diff --git a/src/agirails/wallet/aa/dual_nonce_manager.py b/src/agirails/wallet/aa/dual_nonce_manager.py index ae4fe6a..62cf6d0 100644 --- a/src/agirails/wallet/aa/dual_nonce_manager.py +++ b/src/agirails/wallet/aa/dual_nonce_manager.py @@ -21,6 +21,7 @@ from typing import Any, Awaitable, Callable, Generic, List, Optional, TypeVar from web3 import Web3 +from web3.exceptions import BadFunctionCallOutput, ContractLogicError from agirails.wallet.aa.constants import ENTRYPOINT_V06 @@ -56,14 +57,13 @@ } ] -# TransactionCreated(bytes32,address,address,uint256,bytes32,uint256,uint256,uint256) -# topic0 — used to derive the ACTP nonce from logs when requesterNonces is absent. -# Mirrors TS DualNonceManager.ts:32-34. -TX_CREATED_EVENT_TOPIC = Web3.keccak( - text="TransactionCreated(bytes32,address,address,uint256,bytes32,uint256,uint256,uint256)" -).hex() -if not TX_CREATED_EVENT_TOPIC.startswith("0x"): - TX_CREATED_EVENT_TOPIC = "0x" + TX_CREATED_EVENT_TOPIC +TX_CREATED_EVENT_TOPICS = [ + Web3.to_hex(Web3.keccak(text=signature)) + for signature in ( + "TransactionCreated(bytes32,address,address,uint256,bytes32,uint256,uint256,uint256)", + "TransactionCreated(bytes32,address,address,uint256,bytes32,uint256,uint256,uint256,bytes32)", + ) +] # Adaptive getLogs chunking bounds (TS DualNonceManager.ts:35-36). INITIAL_LOG_CHUNK_SIZE = 10_000 @@ -216,10 +216,17 @@ async def _read_entry_point_nonce(self) -> int: async def _read_actp_nonce(self) -> int: """Read current ACTP nonce for the requester. - requesterNonces is public on ACTPKernel (added in v2). Older + requesterNonces is public on ACTPKernel (canonical v2). Older deployments may not expose this -- derive the nonce from on-chain ``TransactionCreated`` logs (deployment-block binary search + - adaptive chunked getLogs), falling back to 0 only as a last resort. + adaptive chunked getLogs). + + FAIL CLOSED (F38 / HARD INVARIANT): a dependency/RPC/scan failure must + surface an explicit error and NEVER silently infer nonce = 0. Inferring + 0 on failure enables txId/batch replay (the deterministic txId is bound + to this nonce). A *verified* empty scan (deployment block found, full + range covered without error, zero matching logs) is a PROVEN 0 for a + first-time requester and is returned as such; a failed scan is not. Mirrors TS ``readActpNonce`` (DualNonceManager.ts:164-210). """ @@ -233,7 +240,13 @@ async def _read_actp_nonce(self) -> int: ) self._cached_actp_nonce = nonce return nonce - except Exception: + except Exception as nonce_error: + if not isinstance(nonce_error, (BadFunctionCallOutput, ContractLogicError)): + self._cached_actp_nonce = None + raise RuntimeError( + "Failed to read requesterNonces; refusing to infer the ACTP nonce " + f"from a transport or RPC failure: {nonce_error}" + ) from nonce_error # Older ACTPKernel deployments don't expose requesterNonces. # Derive nonce from TransactionCreated events for this requester. # Uses deployment-block binary search + chunked logs (avoids block-0 scans). @@ -266,14 +279,18 @@ async def _read_actp_nonce(self) -> int: self._cached_actp_nonce = derived_nonce return derived_nonce except Exception as derive_error: - # Last-resort fallback for very old/limited RPCs. - logger.warning( - "Could not derive ACTP nonce from events -- using 0 as last " - "resort: %s", - str(derive_error), - ) - self._cached_actp_nonce = 0 - return 0 + # FAIL CLOSED: we could neither read requesterNonces nor prove the + # nonce from events. Returning 0 here would silently reset the + # replay-protection counter, so we raise and leave the cache + # unset (forcing a fresh chain read on the next attempt) instead. + self._cached_actp_nonce = None + raise RuntimeError( + "Could not determine ACTP nonce for requester " + f"{self._sender_address}: requesterNonces call failed " + f"({nonce_error}) and event derivation failed " + f"({derive_error}). Refusing to infer nonce = 0 (replay " + "risk)." + ) from derive_error def set_cached_actp_nonce(self, nonce: int) -> None: """Override cached ACTP nonce. @@ -379,7 +396,7 @@ async def _count_requester_transaction_created_events( self._w3.eth.get_logs, { "address": self._actp_kernel_address, - "topics": [TX_CREATED_EVENT_TOPIC, None, requester_topic], + "topics": [TX_CREATED_EVENT_TOPICS, None, requester_topic], "fromBlock": cursor, "toBlock": chunk_end, }, diff --git a/src/agirails/wallet/aa/transaction_batcher.py b/src/agirails/wallet/aa/transaction_batcher.py index 5adcfbf..d8c9a28 100644 --- a/src/agirails/wallet/aa/transaction_batcher.py +++ b/src/agirails/wallet/aa/transaction_batcher.py @@ -19,6 +19,7 @@ from eth_abi import encode as abi_encode from web3 import Web3 +from agirails.protocol.kernel_creation import encode_kernel_creation from agirails.wallet.aa.constants import SmartWalletCall @@ -72,6 +73,7 @@ class ACTPBatchParams: service_hash: str # bytes32 agent_id: str # ERC-8004 agent ID ("0" if none) requester_agent_id: str = "0" # AIP-14: Requester's ERC-8004 agent ID + agreement_hash: str = "0x" + "00" * 32 # AIP-14c v2: bytes32(0) = no auto AI ruling actp_nonce: int = 0 # Current ACTP nonce for the requester contracts: ContractAddresses = None # type: ignore[assignment] @@ -104,9 +106,10 @@ class ActivationBatchParams: # ERC20.approve(address,uint256) _APPROVE_SELECTOR = Web3.keccak(text="approve(address,uint256)")[:4].hex() -# ACTPKernel.createTransaction(address,address,uint256,uint256,uint256,bytes32,uint256,uint256) +# [F26 FIX] Canonical AIP-14c v2 createTransaction — 9-input, agreementHash (bytes32) is the 7th +# arg (between serviceHash and agentId). The pre-v2 8-arg selector (0x432815a2) reverts on v2. _CREATE_TX_SELECTOR = Web3.keccak( - text="createTransaction(address,address,uint256,uint256,uint256,bytes32,uint256,uint256)" + text="createTransaction(address,address,uint256,uint256,uint256,bytes32,bytes32,uint256,uint256)" )[:4].hex() # ACTPKernel.linkEscrow(bytes32,address,bytes32) @@ -209,8 +212,8 @@ def build_actp_pay_batch(params: ACTPBatchParams) -> ACTPBatchResult: ).hex() # Call 2: ACTPKernel.createTransaction(...) - create_tx_data = "0x" + _CREATE_TX_SELECTOR + abi_encode( - ["address", "address", "uint256", "uint256", "uint256", "bytes32", "uint256", "uint256"], + create_tx_data = encode_kernel_creation( + params.contracts.actp_kernel, [ Web3.to_checksum_address(params.provider), Web3.to_checksum_address(params.requester), @@ -218,10 +221,12 @@ def build_actp_pay_batch(params: ACTPBatchParams) -> ACTPBatchResult: params.deadline, params.dispute_window, bytes.fromhex(params.service_hash.replace("0x", "")), + bytes.fromhex((params.agreement_hash or "0x" + "00" * 32).replace("0x", "")), int(params.agent_id or "0"), int(params.requester_agent_id or "0"), ], - ).hex() + bytes.fromhex((params.agreement_hash or "0x" + "00" * 32).replace("0x", "")), + ) # Call 3: ACTPKernel.linkEscrow(txId, escrowVault, escrowId) # escrowId = txId (ACTP standard) diff --git a/src/agirails/wallet/auto_wallet_provider.py b/src/agirails/wallet/auto_wallet_provider.py index 42bdba7..52121f6 100644 --- a/src/agirails/wallet/auto_wallet_provider.py +++ b/src/agirails/wallet/auto_wallet_provider.py @@ -21,6 +21,7 @@ from web3 import Web3 +from agirails.protocol.kernel_creation import encode_kernel_creation from agirails.wallet.aa.constants import SmartWalletCall, UserOperationV06 from agirails.wallet.aa.user_op_builder import ( build_create_account_factory_data, @@ -680,12 +681,7 @@ async def create_actp_transaction( else params.contracts["actp_kernel"] ) - create_tx_selector = Web3.keccak( - text=( - "createTransaction(address,address,uint256,uint256,uint256," - "bytes32,uint256,uint256)" - ) - )[:4].hex() + agreement_hash_hex = (getattr(params, "agreement_hash", None) or "0x" + "00" * 32) async def _execute(nonces: Any) -> EnqueueResult[CreateACTPTransactionResult]: tx_id = compute_transaction_id( @@ -696,17 +692,8 @@ async def _execute(nonces: Any) -> EnqueueResult[CreateACTPTransactionResult]: nonces.actp_nonce, ) - create_tx_data = "0x" + create_tx_selector + abi_encode( - [ - "address", - "address", - "uint256", - "uint256", - "uint256", - "bytes32", - "uint256", - "uint256", - ], + create_tx_data = encode_kernel_creation( + kernel_address, [ Web3.to_checksum_address(params.provider), Web3.to_checksum_address(params.requester), @@ -714,10 +701,12 @@ async def _execute(nonces: Any) -> EnqueueResult[CreateACTPTransactionResult]: params.deadline, params.dispute_window, bytes.fromhex(params.service_hash.replace("0x", "")), + bytes.fromhex(agreement_hash_hex.replace("0x", "")), int(params.agent_id or "0"), int(getattr(params, "requester_agent_id", "0") or "0"), ], - ).hex() + bytes.fromhex(agreement_hash_hex.replace("0x", "")), + ) calls = [ SmartWalletCall(target=kernel_address, value=0, data=create_tx_data), diff --git a/test-vectors/bond-escalation-vectors.json b/test-vectors/bond-escalation-vectors.json new file mode 100644 index 0000000..0af42d0 --- /dev/null +++ b/test-vectors/bond-escalation-vectors.json @@ -0,0 +1,83 @@ +{ + "_comment": "Cross-SDK golden fixture for BondEscalationClient (PRD P2-4). Consumed BYTE-IDENTICALLY by both the TS jest suite (sdk-js/tests/bond-escalation.test.ts) and the Py pytest suite (python-sdk-v2/tests/test_dispute/test_bond_escalation.py). Anchors the two quote helpers (quoteInitialBond / quoteEscalationBond) and the getDisputeState() tuple decode. Any change here MUST keep both SDKs green.", + "constants": { + "ESCALATION_INITIAL_BPS": 200, + "MIN_ESCALATION_BOND": 1000000, + "MAX_ESCALATION_BOND": 500000000, + "ESCALATION_MULTIPLIER": 2, + "BPS_DENOMINATOR": 10000 + }, + "quoteInitialBond": [ + { "_note": "tiny escrow -> $1 floor (2% of $5 = $0.10 < $1)", "escrowAmount": "5000000", "expected": "1000000" }, + { "_note": "exactly-at-floor boundary: 2% of $50 = $1, floor is strict >, so floor wins", "escrowAmount": "50000000", "expected": "1000000" }, + { "_note": "just over floor: 2% of $50.01 = $1.0002 > $1", "escrowAmount": "50005000", "expected": "1000100" }, + { "_note": "2% of $100 = $2", "escrowAmount": "100000000", "expected": "2000000" }, + { "_note": "2% of $1000 = $20", "escrowAmount": "1000000000", "expected": "20000000" }, + { "_note": "exactly-at-ceiling boundary: 2% of $25000 = $500 = MAX_ESCALATION_BOND (cap is inclusive, not exceeded)", "escrowAmount": "25000000000", "expected": "500000000" }, + { "_note": "over ceiling: 2% of $30000 = $600 -> clamped to $500 (F-5; uncapped code would return 600000000)", "escrowAmount": "30000000000", "expected": "500000000" }, + { "_note": "far over ceiling: 2% of $1000000 = $20000 -> clamped to $500 (F-5)", "escrowAmount": "1000000000000", "expected": "500000000" }, + { "_note": "zero escrow -> $1 floor", "escrowAmount": "0", "expected": "1000000" } + ], + "quoteEscalationBond": [ + { "_note": "$1 -> $2 (2x, below ceiling)", "currentBond": "1000000", "expected": "2000000" }, + { "_note": "$2 -> $4", "currentBond": "2000000", "expected": "4000000" }, + { "_note": "$200 -> $400 (still below $500 ceiling)", "currentBond": "200000000", "expected": "400000000" }, + { "_note": "$250 -> $500 (exactly ceiling)", "currentBond": "250000000", "expected": "500000000" }, + { "_note": "$300 -> capped at $500", "currentBond": "300000000", "expected": "500000000" }, + { "_note": "$500 (at ceiling) -> still $500", "currentBond": "500000000", "expected": "500000000" } + ], + "getDisputeState": { + "_comment": "Raw tuple returned by the public disputes(bytes32) getter (13 fields, see BondEscalation ABI). Field order: transactionId, currentRuling, splitBps, currentBond, accumulatedBonds, livenessEnd, disputedAt, lastProposer, tier, resolved, winnerPaid, originalPool, escrowAmount. The decoder MUST map this tuple onto the shared DisputeState type identically in both SDKs.", + "disputeId": "0x1234567890123456789012345678901234567890123456789012345678901234", + "tuple": [ + "0xabcdef0000000000000000000000000000000000000000000000000000000001", + 2, + 6500, + "4000000", + "7000000", + "1700003600", + "1700000000", + "0x1111111111111111111111111111111111111111", + 1, + false, + false, + "0", + "100000000" + ], + "expected": { + "txId": "0xabcdef0000000000000000000000000000000000000000000000000000000001", + "disputeId": "0x1234567890123456789012345678901234567890123456789012345678901234", + "tier": 1, + "ruling": 2, + "splitBps": 6500, + "resolved": false + } + }, + "getDisputeStateResolved": { + "_comment": "A finalized non-split dispute (ruling 0 = provider wins, resolved=true).", + "disputeId": "0x2222222222222222222222222222222222222222222222222222222222222222", + "tuple": [ + "0xabcdef0000000000000000000000000000000000000000000000000000000002", + 0, + 0, + "500000000", + "0", + "1700007200", + "1700000000", + "0x2222222222222222222222222222222222222222", + 1, + true, + true, + "500000000", + "200000000" + ], + "expected": { + "txId": "0xabcdef0000000000000000000000000000000000000000000000000000000002", + "disputeId": "0x2222222222222222222222222222222222222222222222222222222222222222", + "tier": 1, + "ruling": 0, + "splitBps": 0, + "resolved": true + } + } +} diff --git a/test-vectors/bundle-hashes.py.json b/test-vectors/bundle-hashes.py.json new file mode 100644 index 0000000..a75dd95 --- /dev/null +++ b/test-vectors/bundle-hashes.py.json @@ -0,0 +1,22 @@ +[ + { + "name": "A", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c6976222c2264656c6976657261626c6548617368223a22307863646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364222c2264656c6976657265644174223a313730303030303030302c2272657472696576616c496e737472756374696f6e73223a226970667320636174206261667964656c6976227d2c2264697370757465223a7b2265766964656e6365434944223a22626166796576222c226f70656e65644174223a313730303030333630302c22726561736f6e223a226e6f742064656c697665726564227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303031222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d7074222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a22227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a226261667973706563222c226361706162696c6974696573223a5b226563686f225d2c22736c6148617368223a22307861626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162227d2c2274696d656c696e65223a5b7b226174223a313730303030303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303030333630302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0x379fb8140138f7d90cfbcb481898b6ec646e2c0378ff0d3a4a4572a6570ca257" + }, + { + "name": "B", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c697632222c2264656c6976657261626c6548617368223a22307832323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232222c2264656c6976657261626c65496e6c696e65223a2254686520717569636b2062726f776e20666f782e222c2264656c6976657265644174223a313730303130303030302c2272657472696576616c496e737472756374696f6e73223a226970667320636174206261667964656c697632203b20766572696679206b656363616b323536203d3d2064656c6976657261626c6548617368227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657632222c2265766964656e6365496e6c696e65223a22526563656976656420312073656e74656e6365206f6e6c792e222c226f70656e65644174223a313730303130353030302c22726561736f6e223a2273756d6d617279207472756e63617465643b206578706563746564203e3d2032303020776f726473227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306161222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707432222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31222c2267656d696e692d322e352d70726f225d2c226e6f746573223a2244656c6976657261626c65206973203420776f72647320767320534c41206d696e696d756d203230303b2072756c696e67203120287265717565737465722920617420302e393620636f6e666964656e63652e227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656332222c226361706162696c6974696573223a5b2273756d6d6172697a65222c227472616e736c617465225d2c22736c6148617368223a22307831313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131227d2c2274696d656c696e65223a5b7b226174223a313730303039303030302c226576656e74223a22434f4d4d4954544544227d2c7b226174223a313730303039353030302c226576656e74223a22494e5f50524f4752455353227d2c7b226174223a313730303130303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303130353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0xeaf910a3d1d691dfa85534c67e7426a426666c38a492166bc34e4c432c5826cd" + }, + { + "name": "C", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a22626166796c6172676564656c6976222c2264656c6976657261626c6548617368223a22307834343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434222c2264656c6976657265644174223a313730303230303030302c2272657472696576616c496e737472756374696f6e73223a2244656c6976657261626c65206578636565647320696e6c696e65206361703b20666574636820626166796c6172676564656c697620616e6420766572696679206b656363616b323536203d3d2064656c6976657261626c65486173682e227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657633222c226f70656e65644174223a313730303230353030302c22726561736f6e223a2272c3a973756c74617420696e636f727265637420e2809420e59bb3206d697373696e6720f09f8e89227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306666222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707433222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a22227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656333222c226361706162696c6974696573223a5b2272656e646572225d2c22736c6148617368223a22307833333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333227d2c2274696d656c696e65223a5b7b226174223a313730303230303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303230353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0x4f244d13c111a398636a6fb77e71a3102cff6f47dfc4075d182eb0be4c1a5035" + }, + { + "name": "D", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c697634222c2264656c6976657261626c6548617368223a22307836363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636222c2264656c6976657265644174223a313730303330303030302c2272657472696576616c496e737472756374696f6e73223a226665746368207669612068747470733a2f2f697066732e696f2f697066732f6261667964656c697634207468656e2072756e20433a5c5c62696e5c5c7665726966792e657865227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657634222c226f70656e65644174223a313730303330353030302c22726561736f6e223a226374726c5b5c625c665c6e5c725c745c75303030375c75303031665d2071756f74653d5c22206261636b3d5c5c20736c6173683d2f20656d6f6a693df09f9a8020646f6e65227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306434222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707434222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a227061746820612f625c5c63205c22715c22207461623d5c74206e6c3d5c6e20656e6420f09f8e89227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656334222c226361706162696c6974696573223a5b227472616e73666f726d225d2c22736c6148617368223a22307835353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535227d2c2274696d656c696e65223a5b7b226174223a313730303330303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303330353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0xdbfd7e3c12fd7263bc9ce2d6ab8a45713472d8b45d58d8008fb3867377e5c76a" + } +] \ No newline at end of file diff --git a/test-vectors/bundle-hashes.ts.json b/test-vectors/bundle-hashes.ts.json new file mode 100644 index 0000000..a75dd95 --- /dev/null +++ b/test-vectors/bundle-hashes.ts.json @@ -0,0 +1,22 @@ +[ + { + "name": "A", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c6976222c2264656c6976657261626c6548617368223a22307863646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364222c2264656c6976657265644174223a313730303030303030302c2272657472696576616c496e737472756374696f6e73223a226970667320636174206261667964656c6976227d2c2264697370757465223a7b2265766964656e6365434944223a22626166796576222c226f70656e65644174223a313730303030333630302c22726561736f6e223a226e6f742064656c697665726564227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303031222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d7074222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a22227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a226261667973706563222c226361706162696c6974696573223a5b226563686f225d2c22736c6148617368223a22307861626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162227d2c2274696d656c696e65223a5b7b226174223a313730303030303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303030333630302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0x379fb8140138f7d90cfbcb481898b6ec646e2c0378ff0d3a4a4572a6570ca257" + }, + { + "name": "B", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c697632222c2264656c6976657261626c6548617368223a22307832323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232222c2264656c6976657261626c65496e6c696e65223a2254686520717569636b2062726f776e20666f782e222c2264656c6976657265644174223a313730303130303030302c2272657472696576616c496e737472756374696f6e73223a226970667320636174206261667964656c697632203b20766572696679206b656363616b323536203d3d2064656c6976657261626c6548617368227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657632222c2265766964656e6365496e6c696e65223a22526563656976656420312073656e74656e6365206f6e6c792e222c226f70656e65644174223a313730303130353030302c22726561736f6e223a2273756d6d617279207472756e63617465643b206578706563746564203e3d2032303020776f726473227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306161222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707432222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31222c2267656d696e692d322e352d70726f225d2c226e6f746573223a2244656c6976657261626c65206973203420776f72647320767320534c41206d696e696d756d203230303b2072756c696e67203120287265717565737465722920617420302e393620636f6e666964656e63652e227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656332222c226361706162696c6974696573223a5b2273756d6d6172697a65222c227472616e736c617465225d2c22736c6148617368223a22307831313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131227d2c2274696d656c696e65223a5b7b226174223a313730303039303030302c226576656e74223a22434f4d4d4954544544227d2c7b226174223a313730303039353030302c226576656e74223a22494e5f50524f4752455353227d2c7b226174223a313730303130303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303130353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0xeaf910a3d1d691dfa85534c67e7426a426666c38a492166bc34e4c432c5826cd" + }, + { + "name": "C", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a22626166796c6172676564656c6976222c2264656c6976657261626c6548617368223a22307834343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434222c2264656c6976657265644174223a313730303230303030302c2272657472696576616c496e737472756374696f6e73223a2244656c6976657261626c65206578636565647320696e6c696e65206361703b20666574636820626166796c6172676564656c697620616e6420766572696679206b656363616b323536203d3d2064656c6976657261626c65486173682e227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657633222c226f70656e65644174223a313730303230353030302c22726561736f6e223a2272c3a973756c74617420696e636f727265637420e2809420e59bb3206d697373696e6720f09f8e89227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306666222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707433222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a22227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656333222c226361706162696c6974696573223a5b2272656e646572225d2c22736c6148617368223a22307833333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333227d2c2274696d656c696e65223a5b7b226174223a313730303230303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303230353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0x4f244d13c111a398636a6fb77e71a3102cff6f47dfc4075d182eb0be4c1a5035" + }, + { + "name": "D", + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c697634222c2264656c6976657261626c6548617368223a22307836363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636222c2264656c6976657265644174223a313730303330303030302c2272657472696576616c496e737472756374696f6e73223a226665746368207669612068747470733a2f2f697066732e696f2f697066732f6261667964656c697634207468656e2072756e20433a5c5c62696e5c5c7665726966792e657865227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657634222c226f70656e65644174223a313730303330353030302c22726561736f6e223a226374726c5b5c625c665c6e5c725c745c75303030375c75303031665d2071756f74653d5c22206261636b3d5c5c20736c6173683d2f20656d6f6a693df09f9a8020646f6e65227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306434222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707434222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a227061746820612f625c5c63205c22715c22207461623d5c74206e6c3d5c6e20656e6420f09f8e89227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656334222c226361706162696c6974696573223a5b227472616e73666f726d225d2c22736c6148617368223a22307835353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535227d2c2274696d656c696e65223a5b7b226174223a313730303330303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303330353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0xdbfd7e3c12fd7263bc9ce2d6ab8a45713472d8b45d58d8008fb3867377e5c76a" + } +] \ No newline at end of file diff --git a/test-vectors/bundle-vectors.json b/test-vectors/bundle-vectors.json new file mode 100644 index 0000000..31a0ea2 --- /dev/null +++ b/test-vectors/bundle-vectors.json @@ -0,0 +1,214 @@ +{ + "_comment": "SHARED cross-SDK golden fixture for the evidence-bundle canonical serializer (PRD P2-3). Both the TS jest suite and the Py pytest suite load THIS file. Frozen from EVIDENCE-BUNDLE-SCHEMA.md §7. tokenCount is cl100k_base over the canonical bytes.", + "schemaDoc": "DISPUTE SYSTEM/EVIDENCE-BUNDLE-SCHEMA.md", + "vectors": [ + { + "name": "A", + "description": "small dispute, deliverable referenced by CID (not inlined); anchors EVIDENCE-BUNDLE-SCHEMA.md §7 Example A", + "bundle": { + "schemaVersion": "1.0.0", + "disputeId": "0x0000000000000000000000000000000000000000000000000000000000000001", + "spec": { + "agirailsMdCID": "bafyspec", + "capabilities": [ + "echo" + ], + "slaHash": "0xabababababababababababababababababababababababababababababababab" + }, + "delivery": { + "deliverableHash": "0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", + "deliverableCID": "bafydeliv", + "retrievalInstructions": "ipfs cat bafydeliv", + "deliveredAt": 1700000000 + }, + "dispute": { + "reason": "not delivered", + "evidenceCID": "bafyev", + "openedAt": 1700003600 + }, + "timeline": [ + { + "event": "DELIVERED", + "at": 1700000000 + }, + { + "event": "DISPUTED", + "at": 1700003600 + } + ], + "reasoning": { + "evaluatorPromptCID": "bafyprompt", + "modelVersions": [ + "claude-opus-4-6", + "gpt-4.1" + ], + "notes": "" + } + }, + "canonicalBytesUtf8Len": 719, + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c6976222c2264656c6976657261626c6548617368223a22307863646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364636463646364222c2264656c6976657265644174223a313730303030303030302c2272657472696576616c496e737472756374696f6e73223a226970667320636174206261667964656c6976227d2c2264697370757465223a7b2265766964656e6365434944223a22626166796576222c226f70656e65644174223a313730303030333630302c22726561736f6e223a226e6f742064656c697665726564227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303031222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d7074222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a22227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a226261667973706563222c226361706162696c6974696573223a5b226563686f225d2c22736c6148617368223a22307861626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162616261626162227d2c2274696d656c696e65223a5b7b226174223a313730303030303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303030333630302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0x379fb8140138f7d90cfbcb481898b6ec646e2c0378ff0d3a4a4572a6570ca257", + "tokenCount": 255, + "tokenizer": "cl100k_base" + }, + { + "name": "B", + "description": "deliverable inlined + Tier-0 reasoning present (post-evaluation)", + "bundle": { + "schemaVersion": "1.0.0", + "disputeId": "0x00000000000000000000000000000000000000000000000000000000000000aa", + "spec": { + "agirailsMdCID": "bafyspec2", + "capabilities": [ + "summarize", + "translate" + ], + "slaHash": "0x1111111111111111111111111111111111111111111111111111111111111111" + }, + "delivery": { + "deliverableHash": "0x2222222222222222222222222222222222222222222222222222222222222222", + "deliverableCID": "bafydeliv2", + "deliverableInline": "The quick brown fox.", + "retrievalInstructions": "ipfs cat bafydeliv2 ; verify keccak256 == deliverableHash", + "deliveredAt": 1700100000 + }, + "dispute": { + "reason": "summary truncated; expected >= 200 words", + "evidenceCID": "bafyev2", + "evidenceInline": "Received 1 sentence only.", + "openedAt": 1700105000 + }, + "timeline": [ + { + "event": "COMMITTED", + "at": 1700090000 + }, + { + "event": "IN_PROGRESS", + "at": 1700095000 + }, + { + "event": "DELIVERED", + "at": 1700100000 + }, + { + "event": "DISPUTED", + "at": 1700105000 + } + ], + "reasoning": { + "evaluatorPromptCID": "bafyprompt2", + "modelVersions": [ + "claude-opus-4-6", + "gpt-4.1", + "gemini-2.5-pro" + ], + "notes": "Deliverable is 4 words vs SLA minimum 200; ruling 1 (requester) at 0.96 confidence." + } + }, + "canonicalBytesUtf8Len": 1072, + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c697632222c2264656c6976657261626c6548617368223a22307832323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232222c2264656c6976657261626c65496e6c696e65223a2254686520717569636b2062726f776e20666f782e222c2264656c6976657265644174223a313730303130303030302c2272657472696576616c496e737472756374696f6e73223a226970667320636174206261667964656c697632203b20766572696679206b656363616b323536203d3d2064656c6976657261626c6548617368227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657632222c2265766964656e6365496e6c696e65223a22526563656976656420312073656e74656e6365206f6e6c792e222c226f70656e65644174223a313730303130353030302c22726561736f6e223a2273756d6d617279207472756e63617465643b206578706563746564203e3d2032303020776f726473227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306161222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707432222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31222c2267656d696e692d322e352d70726f225d2c226e6f746573223a2244656c6976657261626c65206973203420776f72647320767320534c41206d696e696d756d203230303b2072756c696e67203120287265717565737465722920617420302e393620636f6e666964656e63652e227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656332222c226361706162696c6974696573223a5b2273756d6d6172697a65222c227472616e736c617465225d2c22736c6148617368223a22307831313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131313131227d2c2274696d656c696e65223a5b7b226174223a313730303039303030302c226576656e74223a22434f4d4d4954544544227d2c7b226174223a313730303039353030302c226576656e74223a22494e5f50524f4752455353227d2c7b226174223a313730303130303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303130353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0xeaf910a3d1d691dfa85534c67e7426a426666c38a492166bc34e4c432c5826cd", + "tokenCount": 340, + "tokenizer": "cl100k_base" + }, + { + "name": "C", + "description": "Unicode + boundary: dispute.reason emitted as raw UTF-8 (ensure_ascii=false parity check)", + "bundle": { + "schemaVersion": "1.0.0", + "disputeId": "0x00000000000000000000000000000000000000000000000000000000000000ff", + "spec": { + "agirailsMdCID": "bafyspec3", + "capabilities": [ + "render" + ], + "slaHash": "0x3333333333333333333333333333333333333333333333333333333333333333" + }, + "delivery": { + "deliverableHash": "0x4444444444444444444444444444444444444444444444444444444444444444", + "deliverableCID": "bafylargedeliv", + "retrievalInstructions": "Deliverable exceeds inline cap; fetch bafylargedeliv and verify keccak256 == deliverableHash.", + "deliveredAt": 1700200000 + }, + "dispute": { + "reason": "résultat incorrect — 図 missing 🎉", + "evidenceCID": "bafyev3", + "openedAt": 1700205000 + }, + "timeline": [ + { + "event": "DELIVERED", + "at": 1700200000 + }, + { + "event": "DISPUTED", + "at": 1700205000 + } + ], + "reasoning": { + "evaluatorPromptCID": "bafyprompt3", + "modelVersions": [ + "claude-opus-4-6", + "gpt-4.1" + ], + "notes": "" + } + }, + "canonicalBytesUtf8Len": 831, + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a22626166796c6172676564656c6976222c2264656c6976657261626c6548617368223a22307834343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434222c2264656c6976657265644174223a313730303230303030302c2272657472696576616c496e737472756374696f6e73223a2244656c6976657261626c65206578636565647320696e6c696e65206361703b20666574636820626166796c6172676564656c697620616e6420766572696679206b656363616b323536203d3d2064656c6976657261626c65486173682e227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657633222c226f70656e65644174223a313730303230353030302c22726561736f6e223a2272c3a973756c74617420696e636f727265637420e2809420e59bb3206d697373696e6720f09f8e89227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306666222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707433222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a22227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656333222c226361706162696c6974696573223a5b2272656e646572225d2c22736c6148617368223a22307833333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333227d2c2274696d656c696e65223a5b7b226174223a313730303230303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303230353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0x4f244d13c111a398636a6fb77e71a3102cff6f47dfc4075d182eb0be4c1a5035", + "tokenCount": 267, + "tokenizer": "cl100k_base" + }, + { + "name": "D", + "description": "escape-stress: control chars (\\b\\f\\n\\r\\t), quote, backslash, forward-slash, and surrogate-pair emoji inside free-text fields — locks in cross-SDK JSON escape + sort parity permanently", + "bundle": { + "schemaVersion": "1.0.0", + "disputeId": "0x00000000000000000000000000000000000000000000000000000000000000d4", + "spec": { + "agirailsMdCID": "bafyspec4", + "capabilities": [ + "transform" + ], + "slaHash": "0x5555555555555555555555555555555555555555555555555555555555555555" + }, + "delivery": { + "deliverableHash": "0x6666666666666666666666666666666666666666666666666666666666666666", + "deliverableCID": "bafydeliv4", + "retrievalInstructions": "fetch via https://ipfs.io/ipfs/bafydeliv4 then run C:\\bin\\verify.exe", + "deliveredAt": 1700300000 + }, + "dispute": { + "reason": "ctrl[\b\f\n\r\t\u0007\u001f] quote=\" back=\\ slash=/ emoji=🚀 done", + "evidenceCID": "bafyev4", + "openedAt": 1700305000 + }, + "timeline": [ + { + "event": "DELIVERED", + "at": 1700300000 + }, + { + "event": "DISPUTED", + "at": 1700305000 + } + ], + "reasoning": { + "evaluatorPromptCID": "bafyprompt4", + "modelVersions": [ + "claude-opus-4-6", + "gpt-4.1" + ], + "notes": "path a/b\\c \"q\" tab=\t nl=\n end 🎉" + } + }, + "canonicalBytesUtf8Len": 875, + "canonicalBytesHex": "7b2264656c6976657279223a7b2264656c6976657261626c65434944223a226261667964656c697634222c2264656c6976657261626c6548617368223a22307836363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636222c2264656c6976657265644174223a313730303330303030302c2272657472696576616c496e737472756374696f6e73223a226665746368207669612068747470733a2f2f697066732e696f2f697066732f6261667964656c697634207468656e2072756e20433a5c5c62696e5c5c7665726966792e657865227d2c2264697370757465223a7b2265766964656e6365434944223a2262616679657634222c226f70656e65644174223a313730303330353030302c22726561736f6e223a226374726c5b5c625c665c6e5c725c745c75303030375c75303031665d2071756f74653d5c22206261636b3d5c5c20736c6173683d2f20656d6f6a693df09f9a8020646f6e65227d2c22646973707574654964223a22307830303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030306434222c22726561736f6e696e67223a7b226576616c7561746f7250726f6d7074434944223a226261667970726f6d707434222c226d6f64656c56657273696f6e73223a5b22636c617564652d6f7075732d342d36222c226770742d342e31225d2c226e6f746573223a227061746820612f625c5c63205c22715c22207461623d5c74206e6c3d5c6e20656e6420f09f8e89227d2c22736368656d6156657273696f6e223a22312e302e30222c2273706563223a7b226167697261696c734d64434944223a22626166797370656334222c226361706162696c6974696573223a5b227472616e73666f726d225d2c22736c6148617368223a22307835353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535353535227d2c2274696d656c696e65223a5b7b226174223a313730303330303030302c226576656e74223a2244454c495645524544227d2c7b226174223a313730303330353030302c226576656e74223a224449535055544544227d5d7d", + "bundleHash": "0xdbfd7e3c12fd7263bc9ce2d6ab8a45713472d8b45d58d8008fb3867377e5c76a", + "tokenCount": 300, + "tokenizer": "cl100k_base" + } + ] +} diff --git a/test-vectors/composite-mediator-vectors.json b/test-vectors/composite-mediator-vectors.json new file mode 100644 index 0000000..7b7ddb9 --- /dev/null +++ b/test-vectors/composite-mediator-vectors.json @@ -0,0 +1,109 @@ +{ + "_comment": "PRD P2-5 shared cross-SDK golden fixture for CompositeMediator. Consumed byte-identically by sdk-js/tests/composite-mediator.test.ts and python-sdk-v2/tests/test_dispute/test_composite_mediator.py. Proof bytes are abi.encode outputs the on-chain CompositeMediator (AIP-14b §6) produces; the zero-remaining rows encode the phantom 1-wei sentinel.", + + "disputeSplitRecordedTopic0": "0x64f3bb8deff5e5af1e6f49fe3ccdff2d59febd8d93f5926bc61fc25a2cdff99f", + + "splitRecordedEvent": { + "txId": "0xabcdef0000000000000000000000000000000000000000000000000000000001", + "requester": "0x1111111111111111111111111111111111111111", + "provider": "0x2222222222222222222222222222222222222222", + "splitBps": 3000 + }, + + "resolutionProofs": [ + { + "name": "split_normal", + "proof": "0x00000000000000000000000000000000000000000000000000000000000aae6000000000000000000000000000000000000000000000000000000000000493e0", + "remaining": "1000000", + "expected": { + "isSplit": true, + "phantomSentinel": false, + "requesterAmount": "700000", + "providerAmount": "300000", + "providerAtFault": null + } + }, + { + "name": "settle_provider_wins", + "proof": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000000", + "remaining": "1000000", + "expected": { + "isSplit": false, + "phantomSentinel": false, + "requesterAmount": "0", + "providerAmount": "1000000", + "providerAtFault": false + } + }, + { + "name": "settle_requester_wins", + "proof": "0x00000000000000000000000000000000000000000000000000000000000f424000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "remaining": "1000000", + "expected": { + "isSplit": false, + "phantomSentinel": false, + "requesterAmount": "1000000", + "providerAmount": "0", + "providerAtFault": true + } + }, + { + "name": "drained_settle_sentinel", + "_comment": "remaining==0; proof carries a phantom 1-wei sentinel in the provider field. CONSUMER RULE: must surface 0 payouts, never 1 wei.", + "proof": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000", + "remaining": "0", + "expected": { + "isSplit": false, + "phantomSentinel": true, + "requesterAmount": "0", + "providerAmount": "0", + "providerAtFault": false + } + }, + { + "name": "drained_split_sentinel", + "_comment": "remaining==0; split path with phantom 1-wei sentinel in the requester field. CONSUMER RULE: must surface 0 payouts.", + "proof": "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000", + "remaining": "0", + "expected": { + "isSplit": true, + "phantomSentinel": true, + "requesterAmount": "0", + "providerAmount": "0", + "providerAtFault": null + } + } + ], + + "splitRate": [ + { + "name": "oq11_both_counted_equal_weight", + "_comment": "OQ-11: DisputeSplitRecorded + kernel DISPUTED->CANCELLED counted at identical weight.", + "splitRecorded": 7, + "kernelDisputedToCancelled": 7, + "totalDisputes": 100, + "expected": 0.14 + }, + { + "name": "only_mediator_splits", + "splitRecorded": 5, + "kernelDisputedToCancelled": 0, + "totalDisputes": 50, + "expected": 0.1 + }, + { + "name": "only_kernel_cancels", + "splitRecorded": 0, + "kernelDisputedToCancelled": 4, + "totalDisputes": 40, + "expected": 0.1 + }, + { + "name": "zero_disputes_no_div_by_zero", + "splitRecorded": 0, + "kernelDisputedToCancelled": 0, + "totalDisputes": 0, + "expected": 0.0 + } + ] +} diff --git a/test-vectors/dispute-client-status-vectors.json b/test-vectors/dispute-client-status-vectors.json new file mode 100644 index 0000000..9e6cca8 --- /dev/null +++ b/test-vectors/dispute-client-status-vectors.json @@ -0,0 +1,55 @@ +{ + "_comment": "Cross-SDK golden fixture for the DisputeClient facade (PRD P2-9). Consumed byte-identically by jest (tests/dispute-client.test.ts) and pytest (tests/test_dispute/test_dispute_client.py). Each row maps a raw on-chain `disputes(bytes32)` tuple (AIP-14b §7.3 field order) to the canonical §9 sub-state string `DisputeClient.getDisputeStatus()` MUST return. The decode is pure (no chain) and MUST be identical across both SDKs. §9 sub-state machine: UNINITIALIZED -> OPENED(tier0) -> PROPOSED(tier1) -> ESCALATED(tier2) -> RESOLVED. CHALLENGED is NOT a distinct on-chain field (challenge() keeps tier==1), so a tier-1 unresolved dispute decodes to PROPOSED.", + "_tupleFields": ["transactionId", "currentRuling", "splitBps", "currentBond", "accumulatedBonds", "livenessEnd", "disputedAt", "lastProposer", "tier", "resolved", "winnerPaid", "originalPool", "escrowAmount"], + "_substates": ["UNINITIALIZED", "OPENED", "PROPOSED", "ESCALATED", "RESOLVED"], + "vectors": [ + { + "name": "never-opened: disputedAt==0 -> UNINITIALIZED", + "disputeId": "0x9b477800000000000000000000000000000000000000000000000000000be365", + "tuple": ["0x0000000000000000000000000000000000000000000000000000000000000000", 0, 0, "0", "0", 0, 0, "0x0000000000000000000000000000000000000000", 0, false, false, "0", "0"], + "expected": { "substate": "UNINITIALIZED", "tier": 0, "resolved": false, "ruling": 0, "splitBps": 0 } + }, + { + "name": "opened only (tier0, disputedAt set) -> OPENED", + "disputeId": "0x1111111111111111111111111111111111111111111111111111111111111111", + "tuple": ["0xaaaa000000000000000000000000000000000000000000000000000000000001", 0, 0, "0", "0", 0, 1718000000, "0x0000000000000000000000000000000000000000", 0, false, false, "0", "5000000"], + "expected": { "substate": "OPENED", "tier": 0, "resolved": false, "ruling": 0, "splitBps": 0 } + }, + { + "name": "tier1 direct/AI proposal live (unresolved) -> PROPOSED", + "disputeId": "0x2222222222222222222222222222222222222222222222222222222222222222", + "tuple": ["0xaaaa000000000000000000000000000000000000000000000000000000000002", 1, 0, "1000000", "1000000", 1718003600, 1718000000, "0x00000000000000000000000000000000000000A1", 1, false, false, "0", "5000000"], + "expected": { "substate": "PROPOSED", "tier": 1, "resolved": false, "ruling": 1, "splitBps": 0 } + }, + { + "name": "tier1 after challenge (still tier1, unresolved) -> PROPOSED (challenge not a distinct on-chain field)", + "disputeId": "0x3333333333333333333333333333333333333333333333333333333333333333", + "tuple": ["0xaaaa000000000000000000000000000000000000000000000000000000000003", 0, 0, "2000000", "3000000", 1718007200, 1718000000, "0x00000000000000000000000000000000000000B2", 1, false, false, "0", "5000000"], + "expected": { "substate": "PROPOSED", "tier": 1, "resolved": false, "ruling": 0, "splitBps": 0 } + }, + { + "name": "tier2 escalated to UMA (unresolved) -> ESCALATED", + "disputeId": "0x4444444444444444444444444444444444444444444444444444444444444444", + "tuple": ["0xaaaa000000000000000000000000000000000000000000000000000000000004", 0, 0, "500000000", "500000000", 1718010800, 1718000000, "0x00000000000000000000000000000000000000C3", 2, false, false, "0", "30000000000"], + "expected": { "substate": "ESCALATED", "tier": 2, "resolved": false, "ruling": 0, "splitBps": 0 } + }, + { + "name": "resolved winner-takes-all (ruling 0) -> RESOLVED", + "disputeId": "0x5555555555555555555555555555555555555555555555555555555555555555", + "tuple": ["0xaaaa000000000000000000000000000000000000000000000000000000000005", 0, 0, "0", "0", 1718003600, 1718000000, "0x00000000000000000000000000000000000000D4", 1, true, true, "1000000", "5000000"], + "expected": { "substate": "RESOLVED", "tier": 1, "resolved": true, "ruling": 0, "splitBps": 0 } + }, + { + "name": "resolved split (ruling 2) -> RESOLVED (resolved dominates tier)", + "disputeId": "0x6666666666666666666666666666666666666666666666666666666666666666", + "tuple": ["0xaaaa000000000000000000000000000000000000000000000000000000000006", 2, 5000, "0", "1500000", 1718003600, 1718000000, "0x00000000000000000000000000000000000000E5", 1, true, false, "3000000", "5000000"], + "expected": { "substate": "RESOLVED", "tier": 1, "resolved": true, "ruling": 2, "splitBps": 5000 } + }, + { + "name": "resolved from tier2/UMA (ruling 1) -> RESOLVED", + "disputeId": "0x7777777777777777777777777777777777777777777777777777777777777777", + "tuple": ["0xaaaa000000000000000000000000000000000000000000000000000000000007", 1, 0, "0", "0", 1718010800, 1718000000, "0x00000000000000000000000000000000000000F6", 2, true, true, "500000000", "30000000000"], + "expected": { "substate": "RESOLVED", "tier": 2, "resolved": true, "ruling": 1, "splitBps": 0 } + } + ] +} diff --git a/test-vectors/dispute-split-indexer-vectors.json b/test-vectors/dispute-split-indexer-vectors.json new file mode 100644 index 0000000..666bbea --- /dev/null +++ b/test-vectors/dispute-split-indexer-vectors.json @@ -0,0 +1,86 @@ +{ + "_comment": "PRD P2-8 shared cross-SDK golden fixture for DisputeSplitIndexer. Consumed byte-identically by sdk-js/tests/dispute-split-indexer.test.ts and python-sdk-v2/tests/test_reputation/test_dispute_split_indexer.py. The headline fixture is the AIP-14b §3.4 '~14%' case: a single agent resolved 7 disputes, 1 of which ended in a SPLIT (the other 6 SETTLED), so split-rate = 1/7 = ~14.29%. Per OQ-11 (normative default) the split is counted at IDENTICAL weight whether it came from CompositeMediator's DisputeSplitRecorded OR a kernel DISPUTED->CANCELLED (admin-CANCELLED). The fixture exercises BOTH: the single split here is an admin-CANCELLED (kernel) one, proving admin-CANCELLED IS counted in the headline rate (R11 under-count trap closed). The zero-remaining rows carry a phantom 1-wei sentinel in a proof field; the indexer MUST derive split classification from event semantics + escrow remaining, NEVER read the proof amount as a payout.", + + "agent": "0x2222222222222222222222222222222222222222", + "counterparty": "0x1111111111111111111111111111111111111111", + + "headlineFourteenPercent": { + "_comment": "1 split / 6 settled = 1/7 disputes for this agent end in a split. The split is an admin-CANCELLED (kernel DISPUTED->CANCELLED), proving OQ-11 counts admin-CANCELLED at identical weight in the HEADLINE rate.", + "outcomes": [ + { "name": "d1_admin_cancelled_split", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "kernelDisputedToCancelled", "remaining": "1000000" }, + { "name": "d2_settled", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "d3_settled", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "d4_settled", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "d5_settled", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "d6_settled", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "d7_settled", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" } + ], + "expected": { + "agentId": "0x2222222222222222222222222222222222222222", + "splitCount": 1, + "totalDisputes": 7, + "splitRate": 0.14285714285714285, + "approxPercent": 14 + } + }, + + "mixedSourceEqualWeight": { + "_comment": "Proves DisputeSplitRecorded (mediator) and kernel DISPUTED->CANCELLED (admin) are weighted IDENTICALLY: 1 mediator-split + 1 admin-split + 5 settled = 2/7 splits.", + "outcomes": [ + { "name": "mediator_split", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "disputeSplitRecorded", "splitBps": 5000, "remaining": "1000000" }, + { "name": "admin_split", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "kernelDisputedToCancelled", "remaining": "1000000" }, + { "name": "s1", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "s2", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "s3", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "s4", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "s5", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" } + ], + "expected": { + "splitCount": 2, + "totalDisputes": 7, + "splitRate": 0.2857142857142857, + "mediatorSplitCount": 1, + "adminSplitCount": 1 + } + }, + + "drainedSplitNoPhantomPayout": { + "_comment": "ZERO-REMAINING CONSUMER RULE: a split where escrow was fully milestone-drained (remaining==0). The on-chain proof carries a phantom 1-wei sentinel. The indexer MUST classify this as a split from EVENT SEMANTICS + remaining==0, and MUST NOT report any 1-wei payout. The split STILL counts toward the rate (the dispute resolved as a split regardless of drained escrow).", + "outcomes": [ + { "name": "drained_admin_split", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "kernelDisputedToCancelled", "remaining": "0", "proof": "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000" }, + { "name": "drained_mediator_split", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "disputeSplitRecorded", "splitBps": 0, "remaining": "0", "proof": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000" } + ], + "expected": { + "splitCount": 2, + "totalDisputes": 2, + "splitRate": 1.0, + "phantomPayoutReported": false, + "_comment": "Both surface 0 payout for BOTH parties (never 1 wei), yet both still count as splits." + } + }, + + "perAgentScoping": { + "_comment": "Outcomes for a DIFFERENT agent must NOT pollute the queried agent's rate. Agent A has 1 split / 2 disputes; agent B (counterparty as provider) has its own outcomes ignored when querying A.", + "outcomes": [ + { "name": "A_split", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "kernelDisputedToCancelled", "remaining": "1000000" }, + { "name": "A_settled", "provider": "0x2222222222222222222222222222222222222222", "requester": "0x1111111111111111111111111111111111111111", "kind": "settled", "remaining": "1000000" }, + { "name": "B_split", "provider": "0x3333333333333333333333333333333333333333", "requester": "0x1111111111111111111111111111111111111111", "kind": "disputeSplitRecorded", "splitBps": 4000, "remaining": "1000000" } + ], + "queryAgent": "0x2222222222222222222222222222222222222222", + "expected": { + "splitCount": 1, + "totalDisputes": 2, + "splitRate": 0.5 + } + }, + + "zeroDisputesNoDivByZero": { + "outcomes": [], + "queryAgent": "0x2222222222222222222222222222222222222222", + "expected": { + "splitCount": 0, + "totalDisputes": 0, + "splitRate": 0.0 + } + } +} diff --git a/test-vectors/dispute/golden-vectors.json b/test-vectors/dispute/golden-vectors.json new file mode 100644 index 0000000..d60e847 --- /dev/null +++ b/test-vectors/dispute/golden-vectors.json @@ -0,0 +1,225 @@ +{ + "_comment": "PRD P2-10 CAPSTONE — the single cross-SDK golden-vector fixture for the AIP-14b dispute clients. Loaded BYTE-IDENTICALLY by BOTH the TS jest suite (sdk-js/tests/dispute-parity.test.ts) and the Py pytest suite (python-sdk-v2/tests/test_cross_sdk/test_dispute_parity.py). Every value below is byte/value-identical across the two SDKs because each is reproduced from the SAME canonical encoder (ethers Interface.encodeFunctionData / web3 encode_abi, ethers.TypedDataEncoder / eth_abi+keccak, the shared canonical-JSON serializer). The five golden families (airulingDigest, bundleHash, bondEscalationCalldata, disputeSplitRecordedDecode, splitRate) are the P2-10 acceptance set. DO NOT regenerate values by hand — they are anchored to EncodingCanonical.t.sol (digest), EVIDENCE-BUNDLE-SCHEMA.md Example A (bundleHash), and the BondEscalation/CompositeMediator ABIs (calldata/topics). Any change here MUST keep BOTH suites green.", + "airulingDigest": { + "_comment": "AIRuling EIP-712 digest — the cross-language anchor (= GOLDEN_DIGEST in Protocol/actp-kernel/test/EncodingCanonical.t.sol). TS computeRulingDigest() and Py compute_ruling_digest() MUST both reproduce expected.digest from the SAME ruling+domain below. Mirrors the frozen dispute_golden_vector.json domain/ruling.", + "domain": { + "name": "ACTPDisputeEvaluator", + "version": "1", + "chainId": 8453, + "verifyingContract": "0x3c68CC8dFe901c7e89eC9f738F9a81709E6e7737" + }, + "ruling": { + "disputeId": "0x5d1b4b905dcd2f7b6de02f87bd74002a10bcb4294a0707c94981b282f8216546", + "ruling": 1, + "confidence": 9500, + "splitBps": 0, + "timestamp": 1700000000, + "reasoningHash": "0x88a38f2db5ac668e2543bbdb0c4c02390b9072aacdb46f2664435ce4376136dc", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "evidenceRefHash": "0x8add2032670e6bbc9348ec2bbb65bb14c9519e91c6a9716f6153fe5ad8fb7179", + "reasoningRefHash": "0xf558f77385482465e90591b3036f1c72f30bfc9cb75ed44486917ca2b9f156a7" + }, + "expected": { + "domainSeparator": "0x49c919619319169442e048297d8b8dc2f0c6a78b8601c78a39656bc2b3b25db8", + "structHash": "0x2b30b25ad0258f200a315a68b1a7ebffc4040679fca1a4bbdf1cae0b57c589b4", + "digest": "0xc14778f377cd385dd4686b798cb2a010c8ff95e8a35a4f170af7e05bc8c2d8a0" + } + }, + "bundleHash": { + "_comment": "Canonical evidence-bundle hash — EVIDENCE-BUNDLE-SCHEMA.md Example A. The bundle is inlined so BOTH SDKs serialize the SAME logical object through their canonical-JSON serializer (sorted keys, no whitespace, ensure_ascii=false) and MUST produce identical canonical_bytes (719 UTF-8 bytes) and bundleHash. TS bundleHash()/Py bundle_hash() with skip-token-check (count already enforced).", + "bundle": { + "schemaVersion": "1.0.0", + "disputeId": "0x0000000000000000000000000000000000000000000000000000000000000001", + "spec": { + "agirailsMdCID": "bafyspec", + "capabilities": [ + "echo" + ], + "slaHash": "0xabababababababababababababababababababababababababababababababab" + }, + "delivery": { + "deliverableHash": "0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", + "deliverableCID": "bafydeliv", + "retrievalInstructions": "ipfs cat bafydeliv", + "deliveredAt": 1700000000 + }, + "dispute": { + "reason": "not delivered", + "evidenceCID": "bafyev", + "openedAt": 1700003600 + }, + "timeline": [ + { + "event": "DELIVERED", + "at": 1700000000 + }, + { + "event": "DISPUTED", + "at": 1700003600 + } + ], + "reasoning": { + "evaluatorPromptCID": "bafyprompt", + "modelVersions": [ + "claude-opus-4-6", + "gpt-4.1" + ], + "notes": "" + } + }, + "expected": { + "canonicalBytesUtf8Len": 719, + "tokenizer": "cl100k_base", + "tokenCount": 255, + "bundleHash": "0x379fb8140138f7d90cfbcb481898b6ec646e2c0378ff0d3a4a4572a6570ca257" + } + }, + "bondEscalationCalldata": { + "_comment": "Byte-exact BondEscalation calldata for a fixed openDispute / challenge / submitAIRuling / escalateToUMA. Both SDKs build calldata for the SAME args (TS Interface.encodeFunctionData via BondEscalationClient.send / Py encode_abi via BondEscalationClient.encode_calldata) and MUST reproduce these hex strings EXACTLY. disputeId is the deterministic keccak256(abi.encode('ACTP_DISPUTE_V1', txId)) that openDispute() returns.", + "txId": "0xabcdef0000000000000000000000000000000000000000000000000000000001", + "disputeId": "0x5925b294f9cf3c79a7d17ae9e51eeb9f79434b7a63ad5487a607b7c6d38ccc47", + "openDispute": { + "args": { + "txId": "0xabcdef0000000000000000000000000000000000000000000000000000000001" + }, + "selector": "0xf08ef6cb", + "calldata": "0xf08ef6cbabcdef0000000000000000000000000000000000000000000000000000000001" + }, + "challenge": { + "args": { + "disputeId": "0x5925b294f9cf3c79a7d17ae9e51eeb9f79434b7a63ad5487a607b7c6d38ccc47", + "counterRuling": 2, + "counterSplitBps": 6500 + }, + "selector": "0x2dc0795c", + "calldata": "0x2dc0795c5925b294f9cf3c79a7d17ae9e51eeb9f79434b7a63ad5487a607b7c6d38ccc4700000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000001964" + }, + "submitAIRuling": { + "args": { + "ruling": { + "disputeId": "0x5d1b4b905dcd2f7b6de02f87bd74002a10bcb4294a0707c94981b282f8216546", + "ruling": 1, + "confidence": 9500, + "splitBps": 0, + "timestamp": 1700000000, + "reasoningHash": "0x88a38f2db5ac668e2543bbdb0c4c02390b9072aacdb46f2664435ce4376136dc", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "evidenceRefHash": "0x0ccc322f1c7133438e34001d0115a4c4c64f0cb6c9947fa08f7820a766bfba9b", + "reasoningRefHash": "0x5146155ebc33851e769cf7b2c25093cdd5b2b079a05e89562823b212857feccc" + }, + "signatures": [ + "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b" + ], + "evidenceCID": "bafybeigolden0evidence0cid", + "reasoningCID": "bafybeigolden0reasoning0cid" + }, + "selector": "0xca74ab82", + "calldata": "0xca74ab825d1b4b905dcd2f7b6de02f87bd74002a10bcb4294a0707c94981b282f82165465d1b4b905dcd2f7b6de02f87bd74002a10bcb4294a0707c94981b282f82165460000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000251c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006553f10088a38f2db5ac668e2543bbdb0c4c02390b9072aacdb46f2664435ce4376136dc3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb0ccc322f1c7133438e34001d0115a4c4c64f0cb6c9947fa08f7820a766bfba9b5146155ebc33851e769cf7b2c25093cdd5b2b079a05e89562823b212857feccc00000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000000000000001e00000000000000000000000000000000000000000000000000000000000000220000000000000000000000000000000000000000000000000000000000000001a62616679626569676f6c64656e3065766964656e636530636964000000000000000000000000000000000000000000000000000000000000000000000000001b62616679626569676f6c64656e30726561736f6e696e673063696400000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000411234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1b00000000000000000000000000000000000000000000000000000000000000" + }, + "escalateToUMA": { + "args": { + "disputeId": "0x5925b294f9cf3c79a7d17ae9e51eeb9f79434b7a63ad5487a607b7c6d38ccc47", + "evidenceCID": "bafybeigexampleCID", + "reasoningCID": "bafybeigexampleReasoningCID" + }, + "selector": "0xea487f8a", + "calldata": "0xea487f8a5925b294f9cf3c79a7d17ae9e51eeb9f79434b7a63ad5487a607b7c6d38ccc47000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000001262616679626569676578616d706c654349440000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001b62616679626569676578616d706c65526561736f6e696e674349440000000000" + } + }, + "disputeSplitRecordedDecode": { + "_comment": "DisputeSplitRecorded event decode + the ZERO-REMAINING CONSUMER RULE on the resolution proof. topic0 = keccak256('DisputeSplitRecorded(bytes32,address,address,uint16)'). Both SDKs decode the proof bytes the same way; when remaining==0 the 1-wei sentinel MUST be zeroed (phantomSentinel=true), NEVER reported as a payout.", + "disputeSplitRecordedTopic0": "0x64f3bb8deff5e5af1e6f49fe3ccdff2d59febd8d93f5926bc61fc25a2cdff99f", + "event": { + "txId": "0xabcdef0000000000000000000000000000000000000000000000000000000001", + "requester": "0x1111111111111111111111111111111111111111", + "provider": "0x2222222222222222222222222222222222222222", + "splitBps": 3000 + }, + "resolutionProofs": [ + { + "name": "split_normal", + "proof": "0x00000000000000000000000000000000000000000000000000000000000aae6000000000000000000000000000000000000000000000000000000000000493e0", + "remaining": "1000000", + "expected": { + "isSplit": true, + "phantomSentinel": false, + "requesterAmount": "700000", + "providerAmount": "300000", + "providerAtFault": null + } + }, + { + "name": "settle_provider_wins", + "proof": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000000", + "remaining": "1000000", + "expected": { + "isSplit": false, + "phantomSentinel": false, + "requesterAmount": "0", + "providerAmount": "1000000", + "providerAtFault": false + } + }, + { + "name": "drained_settle_sentinel", + "_comment": "ZERO-REMAINING: remaining==0; provider field holds the phantom 1-wei sentinel. Both SDKs MUST surface 0/0 payouts, never 1 wei.", + "proof": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000", + "remaining": "0", + "expected": { + "isSplit": false, + "phantomSentinel": true, + "requesterAmount": "0", + "providerAmount": "0", + "providerAtFault": false + } + }, + { + "name": "drained_split_sentinel", + "_comment": "ZERO-REMAINING on the 64-byte SPLIT/CANCELLED branch; remaining==0, requester field holds the phantom 1-wei sentinel. Must surface 0/0.", + "proof": "0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000aae60", + "remaining": "0", + "expected": { + "isSplit": true, + "phantomSentinel": true, + "requesterAmount": "0", + "providerAmount": "0", + "providerAtFault": null + } + } + ] + }, + "splitRate": { + "_comment": "OQ-11 split-rate computation. The numerator counts BOTH DisputeSplitRecorded AND kernel DISPUTED->CANCELLED (admin-CANCELLED IS counted) at IDENTICAL weight. Both SDKs' computeSplitRate / compute_split_rate (the P2-5 primitive the DisputeSplitIndexer reuses) MUST return the SAME float for each row. The 14% row is the headline R11 case (1 admin-CANCELLED split / 7 disputes).", + "cases": [ + { + "name": "headline_admin_cancelled_14pct", + "splitRecorded": 0, + "kernelDisputedToCancelled": 1, + "totalDisputes": 7, + "expectedSplitRate": 0.14285714285714285, + "approxPercent": 14 + }, + { + "name": "mixed_source_equal_weight", + "splitRecorded": 1, + "kernelDisputedToCancelled": 1, + "totalDisputes": 7, + "expectedSplitRate": 0.2857142857142857 + }, + { + "name": "all_mediator_splits", + "splitRecorded": 2, + "kernelDisputedToCancelled": 0, + "totalDisputes": 2, + "expectedSplitRate": 1 + }, + { + "name": "zero_disputes_no_div_by_zero", + "splitRecorded": 0, + "kernelDisputedToCancelled": 0, + "totalDisputes": 0, + "expectedSplitRate": 0 + } + ] + } +} diff --git a/test-vectors/dispute/parity-surface.json b/test-vectors/dispute/parity-surface.json new file mode 100644 index 0000000..3241f17 --- /dev/null +++ b/test-vectors/dispute/parity-surface.json @@ -0,0 +1,716 @@ +{ + "_comment": "PRD P2-10 CAPSTONE \u2014 the cross-SDK dispute PUBLIC-SURFACE manifest. This is the single source of truth for the META parity test: it enumerates EVERY intentional public symbol of the AIP-14b dispute clients and, for each, the TS name + Py name + kind + per-language required arity. BOTH the TS jest META test (sdk-js/tests/dispute-parity.test.ts) and the Py pytest META test (python-sdk-v2/tests/test_cross_sdk/test_dispute_parity.py) load THIS file and assert: (1) every symbol exists in their own SDK with the declared name + required arity, and (2) no symbol is present in only one language (each row carries BOTH a `ts` and a `py` name \u2014 a missing twin is a hard failure). `arity` is the count of REQUIRED logical parameters (excludes `self`/`cls`, excludes optional/default/rest params); a symbol may accept additional OPTIONAL params in either SDK without breaking parity. Framework-inherited members (pydantic model_*, IntEnum/str/dict/Exception builtins) are intentionally EXCLUDED \u2014 only the authored dispute API is listed. Any new public dispute symbol MUST be added here with both twins, or the META test fails. A class may carry an `accessors` array for getter/property members (TS `get x()` / Py `@property`): these are validated via their accessor DESCRIPTOR (TS `Object.getOwnPropertyDescriptor(proto, name).get` is a function; Py `inspect.getattr_static(cls, name)` is a `property`), NOT via prototype value access \u2014 reading a getter off the prototype would trigger it (and throw on an unconfigured facade). Per-SDK construction idiom is intentionally EXCLUDED: TS clients take a single config object + signer; Py takes positional contract/account/w3 and adds `from_config` classmethods, `encode_calldata`, and (EvaluatorClient) a `base_url` property \u2014 these are the standard ethers-vs-web3 idiom, consistently applied, so their absence from a row is NOT a gap. The 4 TS-only evaluate WIRE-PARSE shapes (SignedEvaluateResponse, ProposeDirectlyEvaluateResponse, EvaluateResponse, EvaluatorRuling) are NO LONGER on the public package entrypoint (de-exported from sdk-js/src/index.ts) precisely BECAUSE Py has no twin (it parses the evaluate response as a raw dict); they are listed under `absent` to lock that de-export.", + "enums": [ + { + "ts": "Ruling", + "py": "Ruling", + "kind": "enum", + "members": { + "PROVIDER_WINS": 0, + "REQUESTER_WINS": 1, + "SPLIT": 2 + } + }, + { + "ts": "Tier", + "py": "Tier", + "kind": "enum", + "members": { + "TIER0": 0, + "TIER1": 1, + "TIER2": 2 + } + } + ], + "constants": [ + { + "ts": "ESCALATION_INITIAL_BPS", + "py": "ESCALATION_INITIAL_BPS", + "kind": "const" + }, + { + "ts": "MIN_ESCALATION_BOND", + "py": "MIN_ESCALATION_BOND", + "kind": "const" + }, + { + "ts": "MAX_ESCALATION_BOND", + "py": "MAX_ESCALATION_BOND", + "kind": "const" + }, + { + "ts": "ESCALATION_MULTIPLIER", + "py": "ESCALATION_MULTIPLIER", + "kind": "const" + }, + { + "ts": "BPS_DENOMINATOR", + "py": "BPS_DENOMINATOR", + "kind": "const" + }, + { + "ts": "UMA_BOND", + "py": "UMA_BOND", + "kind": "const" + }, + { + "ts": "SELF_DISPUTE_TOTAL", + "py": "SELF_DISPUTE_TOTAL", + "kind": "const" + }, + { + "ts": "SELF_DISPUTE_RECOVER", + "py": "SELF_DISPUTE_RECOVER", + "kind": "const" + }, + { + "ts": "SELF_DISPUTE_LOSS", + "py": "SELF_DISPUTE_LOSS", + "kind": "const" + }, + { + "ts": "EVIDENCE_BUNDLE_SCHEMA_VERSION", + "py": "EVIDENCE_BUNDLE_SCHEMA_VERSION", + "kind": "const" + }, + { + "ts": "SUPPORTED_BUNDLE_MAJOR", + "py": "SUPPORTED_BUNDLE_MAJOR", + "kind": "const" + }, + { + "ts": "MAX_BUNDLE_TOKENS", + "py": "MAX_BUNDLE_TOKENS", + "kind": "const" + }, + { + "ts": "DOMAIN_TYPEHASH", + "py": "DOMAIN_TYPEHASH", + "kind": "const" + }, + { + "ts": "RULING_TYPEHASH", + "py": "RULING_TYPEHASH", + "kind": "const" + }, + { + "ts": "DISPUTE_EVALUATOR_DOMAIN_NAME", + "py": "DISPUTE_EVALUATOR_DOMAIN_NAME", + "kind": "const" + }, + { + "ts": "DISPUTE_EVALUATOR_DOMAIN_VERSION", + "py": "DISPUTE_EVALUATOR_DOMAIN_VERSION", + "kind": "const" + } + ], + "functions": [ + { + "ts": "signRuling", + "py": "sign_ruling", + "arity": 4 + }, + { + "ts": "recoverRulingSigner", + "py": "recover_ruling_signer", + "arity": 4 + }, + { + "ts": "computeRulingDigest", + "py": "compute_ruling_digest", + "arity": 3 + }, + { + "ts": "computeRulingDomainSeparator", + "py": "compute_ruling_domain_separator", + "arity": 2 + }, + { + "ts": "computeRulingStructHash", + "py": "compute_ruling_struct_hash", + "arity": 1 + }, + { + "ts": "disputeEvaluatorDomain", + "py": "dispute_evaluator_domain", + "arity": 2 + }, + { + "ts": "validateBundle", + "py": "validate_bundle", + "arity": 1 + }, + { + "ts": "assertSupportedVersion", + "py": "assert_supported_version", + "arity": 1 + }, + { + "ts": "serializeBundle", + "py": "serialize_bundle", + "arity": 1 + }, + { + "ts": "serializeBundleToString", + "py": "serialize_bundle_to_string", + "arity": 1 + }, + { + "ts": "bundleHash", + "py": "bundle_hash", + "tsArity": 2, + "pyArity": 1, + "_arityNote": "Both take 1 required arg (the bundle) + an optional skip-token-check control. TS counts the optional `options?` object in Function.length (=2); Py's `skip_token_check=False` default makes it non-required (=1). Same logical contract." + }, + { + "ts": "computeBundleHash", + "py": "compute_bundle_hash", + "tsArity": 2, + "pyArity": 1, + "_arityNote": "Alias of bundleHash \u2014 same arity split as bundleHash." + }, + { + "ts": "countBundleTokens", + "py": "count_bundle_tokens", + "arity": 1 + }, + { + "ts": "enforceTokenCap", + "py": "enforce_token_cap", + "arity": 1 + }, + { + "ts": "setBundleTokenizer", + "py": "set_bundle_tokenizer", + "arity": 1 + }, + { + "ts": "pinEvidenceBundle", + "py": "pin_evidence_bundle", + "arity": 2 + }, + { + "ts": "decodeDisputeSplitRecorded", + "py": "decode_dispute_split_recorded", + "arity": 1 + }, + { + "ts": "decodeResolutionProof", + "py": "decode_resolution_proof", + "arity": 2 + }, + { + "ts": "computeSplitRate", + "py": "compute_split_rate", + "arity": 3 + }, + { + "ts": "isSplitKind", + "py": "is_split_kind", + "arity": 1 + }, + { + "ts": "outcomeFromSplitRecorded", + "py": "outcome_from_split_recorded", + "arity": 1 + }, + { + "ts": "verifyRulingSignatures", + "py": "verify_ruling_signatures", + "tsArity": 3, + "pyArity": 6, + "_arityNote": "Idiomatic representation differs (parity preserved): TS bundles the 4 required config fields (chainId, verifyingContract, fixedEvaluators, rotatingPool) in one trailing `opts` object \u2192 3 positional; Py exposes them as 4 required keyword-only args \u2192 2 positional + 4 keyword-only = 6 required. Same logical signature; each SDK is checked against its own column." + }, + { + "ts": "selectThirdEvaluator", + "py": "select_third_evaluator", + "arity": 2 + }, + { + "ts": "decodeDisputeSubState", + "py": "decode_dispute_sub_state", + "arity": 1, + "_note": "PRD P2-9 \u00a79 facade sub-state decode \u2014 'the single decode both SDKs MUST agree on byte-for-byte', anchored to dispute-client-status-vectors.json. Standalone pure function exported alongside the DisputeClient facade." + }, + { + "ts": "receiptAuthorizationTypedData", + "py": "receipt_authorization_typed_data", + "arity": 1 + }, + { + "ts": "authorizePaymentReceipt", + "py": "authorize_payment_receipt", + "arity": 3 + }, + { + "ts": "postPaidEvaluation", + "py": "post_paid_evaluation", + "arity": 2 + } + ], + "classes": [ + { + "ts": "BondEscalationClient", + "py": "BondEscalationClient", + "staticMethods": [ + { + "ts": "quoteInitialBond", + "py": "quote_initial_bond", + "arity": 1 + }, + { + "ts": "quoteEscalationBond", + "py": "quote_escalation_bond", + "arity": 1 + }, + { + "ts": "decodeDisputeState", + "py": "decode_dispute_state", + "arity": 2 + } + ], + "methods": [ + { + "ts": "getAddress", + "py": "get_address", + "arity": 0 + }, + { + "ts": "getContract", + "py": "get_contract", + "arity": 0 + }, + { + "ts": "getDisputeState", + "py": "get_dispute_state", + "arity": 1 + }, + { + "ts": "getTier1Refundable", + "py": "get_tier1_refundable", + "arity": 1 + }, + { + "ts": "openDispute", + "py": "open_dispute", + "arity": 1 + }, + { + "ts": "submitAIRuling", + "py": "submit_ai_ruling", + "arity": 4 + }, + { + "ts": "proposeDirectly", + "py": "propose_directly", + "arity": 3 + }, + { + "ts": "challenge", + "py": "challenge", + "arity": 3 + }, + { + "ts": "finalize", + "py": "finalize", + "arity": 1 + }, + { + "ts": "escalateToUMA", + "py": "escalate_to_uma", + "arity": 3 + }, + { + "ts": "claimEscalationRefund", + "py": "claim_escalation_refund", + "arity": 1 + }, + { + "ts": "syncExternalResolution", + "py": "sync_external_resolution", + "arity": 1 + }, + { + "ts": "forceResolveStale", + "py": "force_resolve_stale", + "arity": 1 + } + ] + }, + { + "ts": "CompositeMediator", + "py": "CompositeMediator", + "staticMethods": [], + "methods": [ + { + "ts": "getAddress", + "py": "get_address", + "arity": 0 + }, + { + "ts": "getContract", + "py": "get_contract", + "arity": 0 + }, + { + "ts": "getSplitRecordedEvents", + "py": "get_split_recorded_events", + "tsArity": 3, + "pyArity": 0, + "_arityNote": "All query params are optional in both SDKs (zero required). TS bundles them as 3 optional positional params (filter?, fromBlock?, toBlock?) counted in Function.length (=3); Py exposes 5 keyword-args all defaulted (=0 required). Same observational query surface." + }, + { + "ts": "onDisputeSplitRecorded", + "py": "on_dispute_split_recorded", + "arity": 1 + } + ] + }, + { + "ts": "UMAHelper", + "py": "UMAHelper", + "staticMethods": [ + { + "ts": "quoteSelfDisputeCost", + "py": "quote_self_dispute_cost", + "arity": 0 + } + ], + "methods": [ + { + "ts": "getBondEscalationAddress", + "py": "get_bond_escalation_address", + "arity": 0 + }, + { + "ts": "getOOV3Address", + "py": "get_oov3_address", + "arity": 0 + }, + { + "ts": "getAssertionId", + "py": "get_assertion_id", + "arity": 1 + }, + { + "ts": "requesterForceDVM", + "py": "requester_force_dvm", + "arity": 4 + }, + { + "ts": "settleAssertion", + "py": "settle_assertion", + "arity": 1 + } + ] + }, + { + "ts": "DisputeSplitIndexer", + "py": "DisputeSplitIndexer", + "staticMethods": [], + "methods": [ + { + "ts": "addOutcome", + "py": "add_outcome", + "arity": 1 + }, + { + "ts": "addOutcomes", + "py": "add_outcomes", + "arity": 1 + }, + { + "ts": "getOutcomes", + "py": "get_outcomes", + "arity": 0 + }, + { + "ts": "size", + "py": "size", + "arity": 0 + }, + { + "ts": "clear", + "py": "clear", + "arity": 0 + }, + { + "ts": "getSplitRate", + "py": "get_split_rate", + "arity": 1 + }, + { + "ts": "getSplitRateBreakdown", + "py": "get_split_rate_breakdown", + "arity": 1 + }, + { + "ts": "classifyPayout", + "py": "classify_payout", + "arity": 1 + } + ] + }, + { + "ts": "EvaluatorClient", + "py": "EvaluatorClient", + "staticMethods": [], + "methods": [ + { + "ts": "requestEvaluation", + "py": "request_evaluation", + "arity": 1 + } + ] + }, + { + "ts": "DisputeClient", + "py": "DisputeClient", + "_note": "PRD P2-9 \u2014 the SINGLE facade over the five AIP-14b dispute primitives. The five sub-client accessors (bond/mediator/uma/evaluator/splitIndexer) are GETTERS, validated via the `accessors` array (descriptor-based), NOT `methods` (prototype value access would trigger the getter and throw on an unconfigured facade).", + "staticMethods": [], + "methods": [ + { + "ts": "getDisputeStatus", + "py": "get_dispute_status", + "arity": 1 + }, + { + "ts": "recordOutcomes", + "py": "record_outcomes", + "arity": 1 + }, + { + "ts": "hasBond", + "py": "has_bond", + "arity": 0 + }, + { + "ts": "hasMediator", + "py": "has_mediator", + "arity": 0 + }, + { + "ts": "hasUMA", + "py": "has_uma", + "arity": 0 + }, + { + "ts": "hasEvaluator", + "py": "has_evaluator", + "arity": 0 + } + ], + "accessors": [ + { + "ts": "bond", + "py": "bond" + }, + { + "ts": "mediator", + "py": "mediator" + }, + { + "ts": "uma", + "py": "uma" + }, + { + "ts": "evaluator", + "py": "evaluator" + }, + { + "ts": "splitIndexer", + "py": "split_indexer" + } + ] + } + ], + "types": [ + { + "ts": "AIRuling", + "py": "AIRuling", + "kind": "type" + }, + { + "ts": "DisputeState", + "py": "DisputeState", + "kind": "type" + }, + { + "ts": "DisputeSplitRecorded", + "py": "DisputeSplitRecorded", + "kind": "type" + }, + { + "ts": "DecodedResolutionProof", + "py": "DecodedResolutionProof", + "kind": "type", + "_note": "Representation differs (values match, byte-for-byte under the zero-remaining rule): TS exposes a nested `payouts: { requester: bigint; provider: bigint }`; Py exposes flat `requester_amount`/`provider_amount` ints. Field-access code is NOT portable (`.payouts.requester` is TS-only). Locked as parity by NAME; field shape is a documented per-SDK idiom." + }, + { + "ts": "DisputeStatus", + "py": "DisputeStatus", + "kind": "type", + "_note": "PRD P2-9 \u2014 result of DisputeClient.getDisputeStatus / get_dispute_status. TS interface (erased at runtime, compile-time guard); Py @dataclass (runtime class)." + }, + { + "ts": "DisputeSubState", + "py": "DisputeSubState", + "kind": "type", + "_note": "PRD P2-9 \u00a79 sub-state. TS string-literal union 'UNINITIALIZED'|'OPENED'|'PROPOSED'|'ESCALATED'|'RESOLVED' (erased at runtime); Py `DisputeSubState = str` (the alias resolves to the `str` runtime class). Same five string values; the exhaustive Py tuple DISPUTE_SUBSTATES mirrors them." + }, + { + "ts": "SelfDisputeCost", + "py": "SelfDisputeCost", + "kind": "type" + }, + { + "ts": "DisputeOutcome", + "py": "DisputeOutcome", + "kind": "type" + }, + { + "ts": "SplitRateResult", + "py": "SplitRateResult", + "kind": "type" + }, + { + "ts": "SplitRateBreakdown", + "py": "SplitRateBreakdown", + "kind": "type" + }, + { + "ts": "BundleSource", + "py": "BundleSource", + "kind": "type", + "_note": "EvaluatorClient \u00a73.1 \u2014 paired in BOTH SDKs (TS interface / Py @dataclass)." + }, + { + "ts": "RequestEvaluationParams", + "py": "RequestEvaluationParams", + "kind": "type", + "_note": "EvaluatorClient.requestEvaluation input \u2014 paired in BOTH SDKs." + }, + { + "ts": "EvaluationResult", + "py": "EvaluationResult", + "kind": "type", + "_note": "EvaluatorClient.requestEvaluation result (discriminated signed/proposeDirectly) \u2014 paired in BOTH SDKs." + }, + { + "ts": "RulingVerification", + "py": "RulingVerification", + "kind": "type", + "_note": "\u00a74.7 client-side verification result \u2014 paired in BOTH SDKs." + }, + { + "ts": "ProposeDirectlyRecommendation", + "py": "ProposeDirectlyRecommendation", + "kind": "type", + "_note": "\u00a74.3b advisory recommendation \u2014 paired in BOTH SDKs." + }, + { + "ts": "EvaluatorClientConfig", + "py": "EvaluatorClientConfig", + "kind": "type", + "_note": "EvaluatorClient construction config \u2014 paired in BOTH SDKs." + }, + { + "ts": "EvaluatorPaymentClient", + "py": "EvaluatorPaymentClient", + "kind": "type", + "_note": "x402 buyer surface the evaluator reuses for STEP 2 \u2014 paired in BOTH SDKs (TS interface / Py Protocol)." + }, + { + "ts": "EvidenceBundle", + "py": "EvidenceBundle", + "kind": "type" + }, + { + "ts": "EvidenceBundleSpec", + "py": "EvidenceBundleSpec", + "kind": "type" + }, + { + "ts": "EvidenceBundleDelivery", + "py": "EvidenceBundleDelivery", + "kind": "type" + }, + { + "ts": "EvidenceBundleDispute", + "py": "EvidenceBundleDispute", + "kind": "type" + }, + { + "ts": "EvidenceBundleTimelineEvent", + "py": "EvidenceBundleTimelineEvent", + "kind": "type" + }, + { + "ts": "EvidenceBundleReasoning", + "py": "EvidenceBundleReasoning", + "kind": "type" + }, + { + "ts": "PinEvidenceBundleResult", + "py": "PinEvidenceBundleResult", + "kind": "type" + }, + { + "ts": "BundleTooLargeError", + "py": "BundleTooLargeError", + "kind": "error" + }, + { + "ts": "UnsupportedBundleVersionError", + "py": "UnsupportedBundleVersionError", + "kind": "error" + }, + { + "ts": "InvalidBundleError", + "py": "InvalidBundleError", + "kind": "error" + }, + { + "ts": "EvaluatorClientError", + "py": "EvaluatorClientError", + "kind": "error" + }, + { + "ts": "QuoteRejectedError", + "py": "QuoteRejectedError", + "kind": "error" + }, + { + "ts": "EvaluateResponseError", + "py": "EvaluateResponseError", + "kind": "error" + } + ], + "absent": [ + { + "_comment": "resolve() exists on the CompositeMediator ABI but is guarded onlyBondEscalation. BOTH SDK clients DELIBERATELY omit it from the public surface (a footgun: every call reverts). The META test asserts this symbol is absent in BOTH SDKs \u2014 parity of an intentional omission.", + "ts": "resolve", + "py": "resolve", + "on": "CompositeMediator" + } + ], + "tsOnlyDeExported": [ + { + "_comment": "EvaluatorClient evaluate WIRE-PARSE shapes. They are internal HTTP-response shapes (not caller inputs), Py parses the evaluate response as a raw dict, so there is NO Py twin. To keep the public package surface symmetric they are DE-EXPORTED from sdk-js/src/index.ts (they remain `export`ed from the module file for intra-module typing, but are NOT on the package entrypoint). The META test asserts each is absent from the package entrypoint so the de-export cannot silently regress.", + "ts": "SignedEvaluateResponse", + "pyTwin": null + }, + { + "ts": "ProposeDirectlyEvaluateResponse", + "pyTwin": null + }, + { + "ts": "EvaluateResponse", + "pyTwin": null + }, + { + "ts": "EvaluatorRuling", + "pyTwin": null + } + ] +} diff --git a/test-vectors/dispute/receipt-authorization-v1.json b/test-vectors/dispute/receipt-authorization-v1.json new file mode 100644 index 0000000..a99e5fe --- /dev/null +++ b/test-vectors/dispute/receipt-authorization-v1.json @@ -0,0 +1,47 @@ +{ + "input": { + "chainId": 84532, + "verifyingContract": "0x3333333333333333333333333333333333333333", + "quoteHash": "0x4444444444444444444444444444444444444444444444444444444444444444", + "disputeNonce": "dn_non_bytes32", + "txHash": "0x5555555555555555555555555555555555555555555555555555555555555555", + "payer": "0x1a642f0E3c3aF545E7AcBD38b07251B3990914F1" + }, + "typedData": { + "domain": { + "name": "AGIRAILS Evaluator Receipt", + "version": "1", + "chainId": 84532, + "verifyingContract": "0x3333333333333333333333333333333333333333" + }, + "primaryType": "ReceiptAuthorization", + "types": { + "ReceiptAuthorization": [ + { + "name": "quoteHash", + "type": "bytes32" + }, + { + "name": "disputeNonce", + "type": "string" + }, + { + "name": "txHash", + "type": "bytes32" + }, + { + "name": "payer", + "type": "address" + } + ] + }, + "message": { + "quoteHash": "0x4444444444444444444444444444444444444444444444444444444444444444", + "disputeNonce": "dn_non_bytes32", + "txHash": "0x5555555555555555555555555555555555555555555555555555555555555555", + "payer": "0x1a642f0E3c3aF545E7AcBD38b07251B3990914F1" + } + }, + "digest": "0xede815b81386b967a23f0cd270da9c952a03349e8bdf3cc34647f568eff588a6", + "signature": "0xb948f4649e551ebe501cddc109ddd18e31ab782111cfe463918f920e8790b6d33bd0ad5b202d9726477e840eb7c2fcf458ef66414b981e3dd3e7f0806661c0b51b" +} diff --git a/test-vectors/evaluator-client-vectors.json b/test-vectors/evaluator-client-vectors.json new file mode 100644 index 0000000..7e6db74 --- /dev/null +++ b/test-vectors/evaluator-client-vectors.json @@ -0,0 +1,194 @@ +{ + "_comment": "Cross-SDK GOLDEN fixture for the P2-6 EvaluatorClient (TS dispute/EvaluatorClient.ts + Py dispute/evaluator_client.py). Frozen sources: services/dispute-evaluator/API-CONTRACT.md (wire shapes + handshake), AIP-14 FINAL \u00a74.7 (2/3 verification), the GOLDEN ruling/digest in dispute_golden_vector.json (digest 0x9b477852dd1ddad0105ca5e2a320c6ca72105215985b53878ae12b49eb34e365). Both SDK test suites consume this file byte-identically and MUST recover the SAME signer addresses for every signature. The four test private keys are 0x11..11 / 0x22..22 / 0x33..33 / 0x44..44 (fixedA / fixedB / rotating / unknown).", + "domain": { + "name": "ACTPDisputeEvaluator", + "version": "1", + "chainId": 8453, + "verifyingContract": "0x3c68CC8dFe901c7e89eC9f738F9a81709E6e7737" + }, + "ruling": { + "disputeId": "0x5d1b4b905dcd2f7b6de02f87bd74002a10bcb4294a0707c94981b282f8216546", + "ruling": 1, + "confidence": 9500, + "splitBps": 0, + "timestamp": 1700000000, + "reasoningHash": "0x88a38f2db5ac668e2543bbdb0c4c02390b9072aacdb46f2664435ce4376136dc", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "evidenceRefHash": "0x8add2032670e6bbc9348ec2bbb65bb14c9519e91c6a9716f6153fe5ad8fb7179", + "reasoningRefHash": "0xf558f77385482465e90591b3036f1c72f30bfc9cb75ed44486917ca2b9f156a7" + }, + "expectedDigest": "0xc14778f377cd385dd4686b798cb2a010c8ff95e8a35a4f170af7e05bc8c2d8a0", + "registry": { + "_comment": "thirdEvaluator = rotatingPool[uint256(keccak256(abi.encode(disputeId))) % len]. With len=1, the single rotating evaluator is always selected for this disputeId.", + "fixedEvaluators": [ + "0x19E7E376E7C213B7E7e7e46cc70A5dD086DAff2A", + "0x1563915e194D8CfBA1943570603F7606A3115508" + ], + "rotatingPool": [ + "0x5CbDd86a2FA8Dc4bDdd8a8f69dBa48572EeC07FB" + ], + "selectedRotatingEvaluator": "0x5CbDd86a2FA8Dc4bDdd8a8f69dBa48572EeC07FB", + "unknownSigner": "0x7564105E977516C53bE337314c7E53838967bDaC", + "freshnessSeconds": 3600 + }, + "signatures": { + "_comment": "Each is a 65-byte EIP-712 signature over the GOLDEN ruling+domain above. fixedA/fixedB/rotating recover to the registry addresses; unknown recovers to a non-registered address.", + "fixedA": "0xa64ee8d461dd135d18540dff36f8dec768e7761b3b0a31f905c954f42c2faf071039620eb13b98109ceeb52c74b640c49c0e0e524b59a3c4e7aeb98aca0b10e71c", + "fixedB": "0x894b23846c1d2c961c9daddadc6b8bd5e7fa61b3f7875a8620bfc56bec88b73a6bd85c04d5fe7db95adca11d77a3d3deba68377d2163a34c2ef42998c48ce9b71b", + "rotating": "0xdf6cdd508705ff1b722cf6ad17b83ac9078ef1b410bde5ba36e286a5ecbf199a7337550d646702f3faac62727c5551ec2d49a9ae62b53bb38347b0f3dc2011181b", + "unknown": "0x68a36fbb5bd46d21057152ee1b37f9fbd1f356b66b8567db3df1edb0aae53f4a7e2b06ebe4315ce8f948b66df84cfe08a6770bb2e15a561cb1698b20230f93e11c" + }, + "quoteResponse": { + "_comment": "STEP 1 \u2014 the HTTP 402 body the server returns from POST /quote. A 402 here is the normal quote success path (not an error envelope).", + "apiVersion": "1.0.0", + "status": "quote", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "tokenCount": 419, + "quote": { + "amount": "184000", + "currency": "USDC", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "chainId": 8453, + "expiresAt": 1718900000 + }, + "disputeNonce": "dn_b1b3e9aa", + "x402": { + "scheme": "exact", + "network": "base", + "payTo": "0x000000000000000000000000000000000000aBcD", + "maxAmountRequired": "184000", + "resource": "/v1/evaluate", + "description": "ACTP dispute evaluation", + "mimeType": "application/json", + "commit": { + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "payer": "0x1DC48019D708f3d7f1adCAAfA2Ffa198A6897E8d", + "disputeNonce": "dn_b1b3e9aa" + } + } + }, + "evaluateSignedResponse": { + "_comment": "STEP 5 (a) \u2014 HTTP 200 body for the SIGNED path. signatures = [fixedA, rotating] => 2 valid evaluators => passes 2/3. SDK re-recovers and does NOT trust evaluators[].", + "apiVersion": "1.0.0", + "outcome": "signed", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "tokenCount": 419, + "ruling": { + "disputeId": "0x5d1b4b905dcd2f7b6de02f87bd74002a10bcb4294a0707c94981b282f8216546", + "ruling": 1, + "confidence": 9500, + "splitBps": 0, + "timestamp": 1700000000, + "reasoningHash": "0x88a38f2db5ac668e2543bbdb0c4c02390b9072aacdb46f2664435ce4376136dc", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "evidenceRefHash": "0x8add2032670e6bbc9348ec2bbb65bb14c9519e91c6a9716f6153fe5ad8fb7179", + "reasoningRefHash": "0xf558f77385482465e90591b3036f1c72f30bfc9cb75ed44486917ca2b9f156a7" + }, + "signatures": [ + "0xa64ee8d461dd135d18540dff36f8dec768e7761b3b0a31f905c954f42c2faf071039620eb13b98109ceeb52c74b640c49c0e0e524b59a3c4e7aeb98aca0b10e71c", + "0xdf6cdd508705ff1b722cf6ad17b83ac9078ef1b410bde5ba36e286a5ecbf199a7337550d646702f3faac62727c5551ec2d49a9ae62b53bb38347b0f3dc2011181b" + ], + "evaluators": [ + "0x19E7E376E7C213B7E7e7e46cc70A5dD086DAff2A", + "0x5CbDd86a2FA8Dc4bDdd8a8f69dBa48572EeC07FB" + ], + "domain": { + "name": "ACTPDisputeEvaluator", + "version": "1", + "chainId": 8453, + "verifyingContract": "0x3c68CC8dFe901c7e89eC9f738F9a81709E6e7737" + }, + "reasoning": "Deliverable is 4 words vs SLA minimum 200; ruling 1 (requester) at 0.95 confidence." + }, + "evaluateProposeDirectlyResponse": { + "_comment": "STEP 5 (b) \u2014 HTTP 200 body for the proposeDirectly path. signatures ALWAYS []. The SDK surfaces the recommendation and NEVER fabricates a signature.", + "apiVersion": "1.0.0", + "outcome": "proposeDirectly", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "tokenCount": 419, + "recommendation": { + "ruling": 2, + "splitBps": 5000, + "confidence": 7200, + "rationale": "Models split 2:1 across ruling 0/2; no 2/3 supermajority at >= 90%." + }, + "signatures": [], + "reasoning": "Ensemble did not reach 2/3 @ >= 90%; recommend the disputer/proposer call proposeDirectly()." + }, + "verificationCases": { + "_comment": "\u00a74.7 verification scenarios the SDK MUST replicate. sigKeys index into signatures{} above. expectValid is the \u00a74.7 result for now=ruling.timestamp (fresh).", + "twoValidOneUnknown": { + "_comment": "2 valid (fixedA + rotating) + 1 unknown => validCount 2 => PASSES (unknown silently ignored).", + "sigKeys": [ + "fixedA", + "rotating", + "unknown" + ], + "now": 1700000000, + "expectValid": true, + "expectValidCount": 2 + }, + "twoFixedValid": { + "_comment": "fixedA + fixedB => validCount 2 => PASSES.", + "sigKeys": [ + "fixedA", + "fixedB" + ], + "now": 1700000000, + "expectValid": true, + "expectValidCount": 2 + }, + "threeAllValid": { + "sigKeys": [ + "fixedA", + "fixedB", + "rotating" + ], + "now": 1700000000, + "expectValid": true, + "expectValidCount": 3 + }, + "duplicateCountedOnce": { + "_comment": "fixedA signed twice + fixedB once => fixedA counted once => validCount 2 => PASSES.", + "sigKeys": [ + "fixedA", + "fixedA", + "fixedB" + ], + "now": 1700000000, + "expectValid": true, + "expectValidCount": 2 + }, + "duplicateUnderThreshold": { + "_comment": "fixedA signed twice only => counted once => validCount 1 => FAILS (< 2).", + "sigKeys": [ + "fixedA", + "fixedA" + ], + "now": 1700000000, + "expectValid": false, + "expectValidCount": 1 + }, + "stale": { + "_comment": "Fresh-by-count (fixedA+fixedB) but now > timestamp + freshnessSeconds => FAILS the freshness gate.", + "sigKeys": [ + "fixedA", + "fixedB" + ], + "now": 1700003601, + "expectValid": false, + "expectValidCount": 2, + "expectStale": true + }, + "oneValidOneUnknown": { + "_comment": "fixedA + unknown => validCount 1 => FAILS (< 2).", + "sigKeys": [ + "fixedA", + "unknown" + ], + "now": 1700000000, + "expectValid": false, + "expectValidCount": 1 + } + } +} diff --git a/test-vectors/uma-self-dispute-vectors.json b/test-vectors/uma-self-dispute-vectors.json new file mode 100644 index 0000000..646d059 --- /dev/null +++ b/test-vectors/uma-self-dispute-vectors.json @@ -0,0 +1,49 @@ +{ + "_comment": "P2-7 cross-SDK golden fixture for the UMA self-dispute DVM helper (AIP-14b §8.6). Consumed BYTE-IDENTICALLY by sdk-js/tests/uma-helper.test.ts AND python-sdk-v2/tests/test_dispute/test_uma_helper.py. The quoteSelfDisputeCost numbers and the requesterForceDVM call sequence are the load-bearing invariants the §8.6 asymmetry note pins: post $500 assertion bond (escalateToUMA) + $500 disputer bond (OOV3.disputeAssertion) = $1000 total; if the DVM rules FALSE (provider did NOT deliver) the requester-as-disputer recovers $750 ($500 own bond + $250 = half the asserter bond) and loses $250 to the UMA Store. All amounts are USDC base units (6 decimals).", + "quoteSelfDisputeCost": { + "_note": "AIP-14b §8.6 + §8.2 CASE C + §8.3 payout table. Amounts in USDC base units.", + "umaBond": "500000000", + "total": "1000000000", + "recover": "750000000", + "lose": "250000000", + "totalUsd": "1000", + "recoverUsd": "750", + "loseUsd": "250" + }, + "requesterForceDVM": { + "_note": "The EXACT call sequence requesterForceDVM must issue, in order. step.target identifies which contract the call hits (usdc | bondEscalation | oov3). assertionId is read between the escalateToUMA write and the disputeAssertion write.", + "disputeId": "0x1234567890123456789012345678901234567890123456789012345678901234", + "evidenceCID": "bafybeigdyrztabcdefghijklmnopqrstuvwxyz1234567890", + "reasoningCID": "bafybeigreasoningdyrztabcdefghijklmnopqrstuvwxyz00", + "disputer": "0x000000000000000000000000000000000000bEEF", + "assertionId": "0xaaaa0000000000000000000000000000000000000000000000000000000000aa", + "umaBond": "500000000", + "sequence": [ + { + "target": "usdc", + "method": "approve", + "argsHint": "[bondEscalation, 500000000]" + }, + { + "target": "bondEscalation", + "method": "escalateToUMA", + "argsHint": "[disputeId, evidenceCID]" + }, + { + "target": "bondEscalation", + "method": "disputeToAssertion", + "argsHint": "[disputeId] (read)" + }, + { + "target": "usdc", + "method": "approve", + "argsHint": "[oov3, 500000000]" + }, + { + "target": "oov3", + "method": "disputeAssertion", + "argsHint": "[assertionId, disputer]" + } + ] + } +} diff --git a/tests/benchmarks/test_performance.py b/tests/benchmarks/test_performance.py index 0025ca7..25742cc 100644 --- a/tests/benchmarks/test_performance.py +++ b/tests/benchmarks/test_performance.py @@ -398,24 +398,40 @@ def test_state_transition( loop = asyncio.new_event_loop() - # Fund the mock runtime with enough tokens - loop.run_until_complete( - mock_runtime.mint_tokens("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", 1000000000) + # Calibrating repeated create+fund+transition on one JSON store grows + # the dataset on every iteration, so later rounds measure a different + # workload. Prepare a fresh one-transaction store outside the timer. + params = CreateTransactionParams( + provider="0x70997970C51812dc3A010C7d01b50e0d17dc79C8", + requester="0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + amount="1000000", + deadline=int(time.time()) + 3600, + dispute_window=3600, ) - @benchmark - def measure() -> None: - p = CreateTransactionParams( - provider="0x70997970C51812dc3A010C7d01b50e0d17dc79C8", - requester="0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - amount="1000000", - deadline=int(time.time()) + 3600, - dispute_window=3600, - ) - tid = loop.run_until_complete(mock_runtime.create_transaction(p)) + def setup() -> Any: + loop.run_until_complete(mock_runtime.reset()) + loop.run_until_complete(mock_runtime.mint_tokens(params.requester, "1000000000")) + tid = loop.run_until_complete(mock_runtime.create_transaction(params)) loop.run_until_complete(mock_runtime.link_escrow(tid, "1000000")) + return (tid,), {} + + def measure(tid: str) -> None: loop.run_until_complete(mock_runtime.transition_state(tid, State.IN_PROGRESS)) + def verify(tid: str) -> None: + tx = loop.run_until_complete(mock_runtime.get_transaction(tid)) + assert tx is not None and tx.state == State.IN_PROGRESS + + try: + # A state mutation cannot be repeated on the same transaction. + # Ten independent rounds time only the real transition; every + # round checks the persisted outcome outside the timed region. + benchmark.pedantic(measure, setup=setup, teardown=verify, rounds=10, iterations=1) + finally: + loop.run_until_complete(loop.shutdown_default_executor()) + loop.close() + # ============================================================================= # Security Utility Benchmarks diff --git a/tests/fixtures/cross_sdk/dispute_golden_vector.json b/tests/fixtures/cross_sdk/dispute_golden_vector.json new file mode 100644 index 0000000..4ec855d --- /dev/null +++ b/tests/fixtures/cross_sdk/dispute_golden_vector.json @@ -0,0 +1,33 @@ +{ + "_comment": "Cross-SDK GOLDEN EIP-712 vector for AIP-14c 9-field AIRuling. Frozen source of truth: Protocol/actp-kernel/test/EncodingCanonical.t.sol. Both TS (sdk-js) and Python (python-sdk-v2) MUST reproduce digest EXACTLY. This file is committed byte-identically into both SDK trees; a parity test asserts the two copies match.", + "domain": { + "name": "ACTPDisputeEvaluator", + "version": "1", + "chainId": 8453, + "verifyingContract": "0x3c68CC8dFe901c7e89eC9f738F9a81709E6e7737" + }, + "ruling": { + "disputeId": "0x5d1b4b905dcd2f7b6de02f87bd74002a10bcb4294a0707c94981b282f8216546", + "ruling": 1, + "confidence": 9500, + "splitBps": 0, + "timestamp": 1700000000, + "reasoningHash": "0x88a38f2db5ac668e2543bbdb0c4c02390b9072aacdb46f2664435ce4376136dc", + "bundleHash": "0x3f3fab64c884d7a542f43eda4f4b29da96d3b562adfd3ec82f13ed4f649f67eb", + "evidenceRefHash": "0x8add2032670e6bbc9348ec2bbb65bb14c9519e91c6a9716f6153fe5ad8fb7179", + "reasoningRefHash": "0xf558f77385482465e90591b3036f1c72f30bfc9cb75ed44486917ca2b9f156a7" + }, + "expected": { + "domainSeparator": "0x49c919619319169442e048297d8b8dc2f0c6a78b8601c78a39656bc2b3b25db8", + "structHash": "0x2b30b25ad0258f200a315a68b1a7ebffc4040679fca1a4bbdf1cae0b57c589b4", + "digest": "0xc14778f377cd385dd4686b798cb2a010c8ff95e8a35a4f170af7e05bc8c2d8a0" + }, + "contracts": { + "_comment": "Network-config keys for the 3 dispute contracts (undefined until deployed). Keys MUST match TS NetworkConfig.contracts and Py ContractAddresses (camelCase wire form).", + "keys": [ + "bondEscalation", + "compositeMediator", + "umaOptimisticOracleV3" + ] + } +} diff --git a/tests/fixtures/cross_sdk/python_signed_manifest.json b/tests/fixtures/cross_sdk/python_signed_manifest.json index 64ee872..fbb9c7b 100644 --- a/tests/fixtures/cross_sdk/python_signed_manifest.json +++ b/tests/fixtures/cross_sdk/python_signed_manifest.json @@ -1,6 +1,6 @@ { "generated_by": "agirails.builders (CounterOfferBuilder + CounterAcceptBuilder)", - "python_sdk_version": "4.8.0", + "python_sdk_version": "4.9.0", "pinned_now_sec": 1700000000, "buyer_address": "0x19E7E376E7C213B7E7e7e46cc70A5dD086DAff2A", "provider_address": "0x1563915e194D8CfBA1943570603F7606A3115508", diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py new file mode 100644 index 0000000..7cbccad --- /dev/null +++ b/tests/helpers/__init__.py @@ -0,0 +1 @@ +"""Local boundary fixtures used by integration-shaped unit tests.""" diff --git a/tests/helpers/contract_rpc.py b/tests/helpers/contract_rpc.py new file mode 100644 index 0000000..010e848 --- /dev/null +++ b/tests/helpers/contract_rpc.py @@ -0,0 +1,79 @@ +"""In-memory JSON-RPC boundary; real AsyncWeb3 ABI coding and local signing.""" + +from eth_abi import decode, encode +from hexbytes import HexBytes +import rlp +from web3 import Web3 +from web3.providers import AsyncBaseProvider + + +def abi_type(item): + if not item["type"].startswith("tuple"): + return item["type"] + return "(" + ",".join(abi_type(x) for x in item["components"]) + ")" + item["type"][5:] + + +class ContractRPC(AsyncBaseProvider): + def __init__(self): + super().__init__() + self.nonce = 3 + self.block = 10 + self.methods = {} + self.results = {} + self.calls = [] + self.sent = [] + self.logs = [] + self.status = 1 + self.chain_id = 84532 + self.timestamp = 1700001000 + + def register(self, abi): + for item in abi: + if item.get("type") == "function": + signature = item["name"] + "(" + ",".join(abi_type(x) for x in item["inputs"]) + ")" + self.methods[Web3.keccak(text=signature)[:4].hex()] = item + + def reply(self, name, *values): + self.results[name] = values + + async def make_request(self, method, params): + if method == "eth_chainId": + result = hex(self.chain_id) + elif method == "eth_getTransactionCount": + result = hex(self.nonce) + elif method == "eth_blockNumber": + result = hex(self.block) + elif method == "eth_getBlockByNumber": + result = {"number": hex(self.block), "baseFeePerGas": hex(10**9), "timestamp": hex(self.timestamp)} + elif method == "eth_gasPrice": + result = hex(10**9) + elif method == "eth_estimateGas": + result = hex(50_000) + elif method == "eth_call": + call = params[0] + data = HexBytes(call.get("data", call.get("input"))) + abi = self.methods[data[:4].hex()] + arguments = decode([abi_type(x) for x in abi["inputs"]], data[4:]) + self.calls.append((abi["name"], arguments, call["to"])) + result = Web3.to_hex(encode([abi_type(x) for x in abi["outputs"]], self.results[abi["name"]])) + elif method == "eth_sendRawTransaction": + raw = HexBytes(params[0]) + fields = rlp.decode(raw[1:]) if raw[0] == 2 else rlp.decode(raw) + data = fields[7] if raw[0] == 2 else fields[5] + abi = self.methods[data[:4].hex()] + arguments = decode([abi_type(x) for x in abi["inputs"]], data[4:]) + self.sent.append((abi["name"], arguments, raw)) + self.nonce += 1 + result = Web3.to_hex(Web3.keccak(raw)) + elif method == "eth_getTransactionReceipt": + result = { + "transactionHash": params[0], "transactionIndex": "0x0", + "blockHash": "0x" + "bb" * 32, "blockNumber": hex(self.block), + "from": "0x" + "11" * 20, "to": "0x" + "22" * 20, + "cumulativeGasUsed": "0xc350", "gasUsed": "0xc350", + "contractAddress": None, "logs": self.logs, "status": hex(self.status), + "effectiveGasPrice": hex(10**9), "type": "0x2", + } + else: + raise AssertionError(f"Unexpected JSON-RPC method: {method}") + return {"jsonrpc": "2.0", "id": 1, "result": result} diff --git a/tests/test_adapters/test_basic.py b/tests/test_adapters/test_basic.py index 59e43b6..94dbbe0 100644 --- a/tests/test_adapters/test_basic.py +++ b/tests/test_adapters/test_basic.py @@ -249,7 +249,7 @@ async def test_full_lifecycle_start_deliver_release(self, client, provider_addre assert status_ip.state == "IN_PROGRESS" assert status_ip.can_deliver is True - await client.basic.deliver(tx_id) + await client.basic.deliver(tx_id, result_hash="0x" + "11" * 32) status_d = await client.basic.get_status(tx_id) assert status_d.state == "DELIVERED" diff --git a/tests/test_adapters/test_standard.py b/tests/test_adapters/test_standard.py index f16347a..995e5e7 100644 --- a/tests/test_adapters/test_standard.py +++ b/tests/test_adapters/test_standard.py @@ -506,7 +506,7 @@ async def test_get_status_delivered_dispute_then_release(self, client, provider_ ) await client.standard.link_escrow(tx_id) await client.standard.start_work(tx_id) - await client.standard.deliver(tx_id) + await client.standard.deliver(tx_id, result_hash="0x" + "11" * 32) status = await client.standard.get_status(tx_id) assert status.state == "DELIVERED" @@ -546,7 +546,7 @@ async def test_deliver_defaults_dispute_window_proof(self, client, provider_addr ) await client.standard.link_escrow(tx_id) await client.standard.start_work(tx_id) - await client.standard.deliver(tx_id) + await client.standard.deliver(tx_id, result_hash="0x" + "11" * 32) tx = await client.standard.get_transaction(tx_id) assert tx.state == "DELIVERED" @@ -559,7 +559,7 @@ async def test_release_settles_after_window(self, client, provider_address): ) await client.standard.link_escrow(tx_id) await client.standard.start_work(tx_id) - await client.standard.deliver(tx_id) + await client.standard.deliver(tx_id, result_hash="0x" + "11" * 32) await client.runtime.time.advance_time(3601) await client.standard.release(tx_id) diff --git a/tests/test_adapters/test_x402_quote_binding.py b/tests/test_adapters/test_x402_quote_binding.py new file mode 100644 index 0000000..ec0a51d --- /dev/null +++ b/tests/test_adapters/test_x402_quote_binding.py @@ -0,0 +1,266 @@ +"""Actual-adapter regression tests for accepted evaluator payment terms.""" +from __future__ import annotations + +import asyncio +import base64 +import copy +import json +from dataclasses import replace +from types import SimpleNamespace + +import pytest + +from agirails.adapters.x402_adapter import X402Adapter, X402AdapterConfig, X402PayParams, LegacyX402AdapterConfig +from agirails.dispute.evaluator_client import EvaluatorClient, EvaluatorClientConfig +from tests.test_adapters.test_x402_v2_adapter import MockWalletProvider, _requirements, _resp, _payment_response_header, SIGNER_ADDR, USDC_SEPOLIA +from tests.test_dispute.test_evaluator_client import _base_params, _make_quote_fetch, EXAMPLE_A_HASH + +NONCE = 'opaque-evaluator-quote' +PAY_TO = '0x90F79bf6EB2c4f870365E785982E1f101E93b906' + + +class Wallet(MockWalletProvider): + def __init__(self, tier='eoa'): + super().__init__(tier) + self.signatures = [] + + def get_wallet_info(self): + info = super().get_wallet_info() + info.chain_id = 84532 + return info + + def sign_typed_data(self, typed): + self.signatures.append(copy.deepcopy(typed)) + return super().sign_typed_data(typed) + + +def terms(**updates): + return dict(amount='10000', asset=USDC_SEPOLIA, pay_to=PAY_TO, network='eip155:84532', nonce=NONCE, **updates) + + +def params(quote=None, path='paid'): + return X402PayParams(to='https://evaluator.test/' + path, method='POST', body=json.dumps({'disputeNonce': NONCE}), metadata={'payment_method': 'x402'}) if quote is None else SimpleNamespace(to='https://evaluator.test/' + path, method='POST', body=json.dumps({'disputeNonce': NONCE}), headers={}, content_type=None, metadata={'payment_method': 'x402'}, accepted_quote=quote) + + +def completed(): + return _resp(200, json_body={'outcome': 'proposeDirectly', 'bundleHash': EXAMPLE_A_HASH, 'recommendation': {'ruling': 1, 'splitBps': 0, 'confidence': 8000, 'rationale': 'local fixture'}}, headers={'payment-response': _payment_response_header()}) + + +def adapter_for(offers, tier='eoa'): + wallet = Wallet(tier) + calls = [] + async def fetch(url='', **kwargs): + calls.append(kwargs) + return completed() if kwargs['headers'].get('X-PAYMENT') else _resp(402, json_body={'x402Version': 2, 'accepts': offers}) + return X402Adapter(wallet.get_address(), X402AdapterConfig(wallet_provider=wallet, fetch_fn=fetch)), wallet, calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize('tier', ['eoa', 'auto']) +@pytest.mark.parametrize('change', [ + {'network': 'eip155:8453', 'asset': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'}, + {'amount': '9000'}, {'asset': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'}, + {'payTo': '0x' + '33' * 20}, {'disputeNonce': 'other'}, + {'extra': {'name': 'USDC', 'version': '2', 'commit': {'disputeNonce': 'other'}}}, +]) +async def test_rebound_offer_rejected_before_signing_or_approval(change, tier): + offer = _requirements(); offer.update(change) + adapter, wallet, calls = adapter_for([offer], tier) + p = params(); p.accepted_quote = terms() + with pytest.raises(Exception) as caught: + await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert wallet.signatures == [] and wallet.sent == [] + assert len(calls) == 1 and 'X-PAYMENT' not in calls[0]['headers'] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('tier', ['eoa', 'auto']) +async def test_matching_quote_preserves_post_and_random_payment_nonce(tier): + offer = _requirements(permit2=tier == 'auto') + offer['extra']['commit'] = {'disputeNonce': NONCE} + adapter, wallet, calls = adapter_for([offer], tier) + p = params(); p.accepted_quote = terms() + assert (await adapter.pay(p)).success + assert len(wallet.signatures) == 1 and len(wallet.sent) == (1 if tier == 'auto' else 0) + for call in calls: + assert call['method'] == 'POST' and json.loads(call['content'])['disputeNonce'] == NONCE + payload = json.loads(base64.b64decode(calls[1]['headers']['X-PAYMENT']))['payload'] + auth = payload['permit2Authorization' if tier == 'auto' else 'authorization'] + assert auth['nonce'] != NONCE + assert str(auth['nonce']).isdigit() if tier == 'auto' else len(auth['nonce']) == 66 + + +@pytest.mark.asyncio +async def test_mixed_offers_choose_matching_terms_and_address_case(): + offers = [_requirements(amount='9000'), _requirements()] + adapter, wallet, _ = adapter_for(offers) + p = params(); p.accepted_quote = {**terms(), 'amount': '010000', 'asset': USDC_SEPOLIA.upper().replace('0X', '0x')} + assert (await adapter.pay(p)).success + assert int(wallet.signatures[0]['message']['value']) == 10000 + + +@pytest.mark.asyncio +async def test_quote_and_params_mutation_during_fetch_cannot_rebind_payment(): + quote = terms(); p = params(); p.accepted_quote = quote + adapter, wallet, calls = adapter_for([]) + async def fetch(url='', **kwargs): + calls.append(kwargs) + if len(calls) == 1: + quote['network'] = 'eip155:8453'; p.accepted_quote = None + return _resp(402, json_body={'accepts': [_requirements(network='eip155:8453', asset='0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913')]}) + return completed() + adapter._config.fetch_fn = fetch + with pytest.raises(Exception) as caught: + await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert not wallet.signatures and len(calls) == 1 + + +@pytest.mark.asyncio +async def test_overlapping_unquoted_pay_cannot_clear_another_calls_quote(): + entered, release = asyncio.Event(), asyncio.Event() + adapter, wallet, calls = adapter_for([]) + async def fetch(url='', **kwargs): + calls.append(kwargs) + if kwargs['headers'].get('X-PAYMENT'): return completed() + if url.endswith('/quoted'): + entered.set(); await release.wait() + return _resp(402, json_body={'accepts': [_requirements(amount='9000')]}) + adapter._config.fetch_fn = fetch + p = params(path='quoted'); p.accepted_quote = terms() + quoted = asyncio.create_task(adapter.pay(p)); await entered.wait() + assert (await adapter.pay(params(path='unquoted'))).success + release.set() + with pytest.raises(Exception) as caught: await quoted + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert len(wallet.signatures) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize('field,value', [('amount', ''), ('amount', '-1'), ('amount', 'nan'), ('network', None), ('pay_to', 42)]) +async def test_malformed_defined_binding_fails_before_http(field, value): + adapter, wallet, calls = adapter_for([_requirements()]) + p = params(); p.accepted_quote = {**terms(), field: value} + with pytest.raises(Exception) as caught: await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert not calls and not wallet.signatures and not wallet.sent + + +@pytest.mark.asyncio +async def test_request_nonce_conflict_fails_before_http(): + adapter, wallet, calls = adapter_for([_requirements()]) + p = params(); p.body = json.dumps({'disputeNonce': 'other'}); p.accepted_quote = terms() + with pytest.raises(Exception) as caught: await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert not calls and not wallet.signatures + + +@pytest.mark.asyncio +async def test_quoted_legacy_adapter_fails_before_transfer_or_http(): + calls = [] + async def transfer(*args): calls.append(args); return '0x' + 'aa' * 32 + adapter = X402Adapter(SIGNER_ADDR, LegacyX402AdapterConfig(expected_network='base-sepolia', transfer_fn=transfer)) + from unittest.mock import AsyncMock + adapter._make_request = AsyncMock() + p = params(); p.accepted_quote = terms() + with pytest.raises(Exception) as caught: await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + adapter._make_request.assert_not_awaited() + assert not calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize('rebound', [True, False]) +async def test_public_evaluator_uses_actual_adapter_with_chain_pin_and_post(rebound): + quote = {'disputeNonce': NONCE, 'quote': {'chainId': 84532, 'amount': '10000', 'asset': USDC_SEPOLIA}, 'x402': {'network': 'base', 'chainId': 84532, 'payTo': PAY_TO}} + fetch_quote, _ = _make_quote_fetch(quote) + offer = _requirements(network='eip155:8453', asset='0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913') if rebound else _requirements() + adapter, wallet, calls = adapter_for([offer]) + client = EvaluatorClient(EvaluatorClientConfig(base_url='https://evaluator.test', payment_client=adapter, fetch_impl=fetch_quote)) + request = replace(_base_params(), chain_id=84532, payer=SIGNER_ADDR) + if rebound: + with pytest.raises(Exception) as caught: await client.request_evaluation(request) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert not wallet.signatures and len(calls) == 1 + else: + assert (await client.request_evaluation(request)).outcome == 'proposeDirectly' + assert len(wallet.signatures) == 1 + assert calls[0]['method'] == 'POST' and json.loads(calls[0]['content'])['disputeNonce'] == NONCE + + +@pytest.mark.asyncio +@pytest.mark.parametrize('bad', [ + {'quote': {'amount': '10000'}, 'x402': {'amount': '20000'}}, + {'quote': {'asset': USDC_SEPOLIA}, 'x402': {'asset': '0x' + '22' * 20}}, + {'x402': {'payTo': PAY_TO, 'recipient': '0x' + '22' * 20}}, + {'x402': {'commit': {'disputeNonce': 'other'}}}, + {'x402': {'network': 'base-mainnet'}}, + {'quote': {'amount': True}}, {'quote': {'amount': '-1'}}, + {'quote': {'asset': 'invalid'}}, {'quote': []}, +]) +async def test_public_client_rejects_conflicting_or_invalid_quote_before_payment(bad): + quote = {'disputeNonce': NONCE, **bad} + fetch_quote, _ = _make_quote_fetch(quote) + adapter, wallet, calls = adapter_for([_requirements()]) + client = EvaluatorClient(EvaluatorClientConfig(base_url='https://evaluator.test', payment_client=adapter, fetch_impl=fetch_quote)) + with pytest.raises(Exception): + await client.request_evaluation(replace(_base_params(), chain_id=84532, payer=SIGNER_ADDR)) + assert not calls and not wallet.signatures and not wallet.sent + + +@pytest.mark.asyncio +async def test_unified_http_fields_and_quote_nonce_reach_native_adapter(): + from agirails.adapters.types import UnifiedPayParams + p = UnifiedPayParams(to='https://evaluator.test/evaluate', http_method='POST', http_body=json.dumps({'disputeNonce': NONCE}).encode(), http_headers={'X-Context': 'preserved'}, metadata={'payment_method': 'x402'}, accepted_quote=terms()) + adapter, wallet, calls = adapter_for([_requirements()]) + assert (await adapter.pay(p)).success + assert calls[0]['method'] == 'POST' and calls[0]['headers']['X-Context'] == 'preserved' + assert json.loads(calls[0]['content'])['disputeNonce'] == NONCE + assert len(wallet.signatures) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize('chain_id', [8453, None, True, '84532']) +async def test_quoted_wallet_chain_must_match_before_side_effects(chain_id): + adapter, wallet, calls = adapter_for([_requirements(permit2=True)], 'auto') + wallet.get_wallet_info = lambda: SimpleNamespace(tier='auto', chain_id=chain_id) + p = params(); p.accepted_quote = terms() + with pytest.raises(Exception) as caught: await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert not calls and not wallet.sent and not wallet.signatures + + +@pytest.mark.asyncio +async def test_wallet_chain_change_during_fetch_is_rechecked_before_approval(): + adapter, wallet, calls = adapter_for([_requirements(permit2=True)], 'auto') + chain = [84532] + wallet.get_wallet_info = lambda: SimpleNamespace(tier='auto', chain_id=chain[0]) + fetch = adapter._config.fetch_fn + async def changing_fetch(*args, **kwargs): + result = await fetch(*args, **kwargs) + chain[0] = 8453 + return result + adapter._config.fetch_fn = changing_fetch + p = params(); p.accepted_quote = terms() + with pytest.raises(Exception) as caught: await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert len(calls) == 1 and not wallet.sent and not wallet.signatures + + +@pytest.mark.asyncio +@pytest.mark.parametrize('method', ['GET', 'DELETE']) +@pytest.mark.parametrize('native', [True, False]) +async def test_nonce_binding_requires_body_that_is_actually_sent(method, native): + from agirails.adapters.types import UnifiedPayParams + adapter, wallet, calls = adapter_for([_requirements()]) + if native: + p = params(); p.method = method; p.accepted_quote = terms() + else: + p = UnifiedPayParams(to='https://evaluator.test/evaluate', http_method=method, + http_body=json.dumps({'disputeNonce': NONCE}), + metadata={'payment_method': 'x402'}, accepted_quote=terms()) + with pytest.raises(Exception) as caught: + await adapter.pay(p) + assert getattr(caught.value, 'code', None) == 'X402_QUOTE_MISMATCH' + assert not calls and not wallet.signatures and not wallet.sent diff --git a/tests/test_builders/test_agreement.py b/tests/test_builders/test_agreement.py new file mode 100644 index 0000000..3c5be95 --- /dev/null +++ b/tests/test_builders/test_agreement.py @@ -0,0 +1,86 @@ +""" +Golden agreement vector — the cross-language anchor (TS <-> Py). + +The TS twin test `sdk-js/src/builders/AgreementSerializer.test.ts` pins the SAME +canonical bytes + hash. If either drifts, the agreementHash preimage serializer +(AIP-14c D3) is no longer byte-identical across SDKs. +""" + +import pytest + +from agirails.builders.agreement import ( + AGREEMENT_SCHEMA_VERSION, + ZERO_AGREEMENT_HASH, + InvalidAgreementError, + UnsupportedAgreementVersionError, + compute_agreement_hash, + agreement_hash, + serialize_agreement, + validate_agreement, +) + +GOLDEN_AGREEMENT = { + "schemaVersion": "1.0.0", + "request": {"service": "summarize", "url": "https://example.com/doc"}, + "input": {"lang": "en", "maxTokens": 500}, + "sla": {"deadlineSeconds": 3600, "minQualityBps": 9000}, +} +GOLDEN_CANONICAL = ( + '{"input":{"lang":"en","maxTokens":500},' + '"request":{"service":"summarize","url":"https://example.com/doc"},' + '"schemaVersion":"1.0.0",' + '"sla":{"deadlineSeconds":3600,"minQualityBps":9000}}' +) +GOLDEN_AGREEMENT_HASH = ( + "0xb2ef8cf734173588408b48793a43cc53e86f1f3d5702778a29f4460f5c8e9db4" +) + + +def test_serializes_to_frozen_canonical_bytes(): + assert serialize_agreement(GOLDEN_AGREEMENT) == GOLDEN_CANONICAL + + +def test_computes_golden_agreement_hash(): + assert compute_agreement_hash(GOLDEN_AGREEMENT) == GOLDEN_AGREEMENT_HASH + assert agreement_hash(GOLDEN_AGREEMENT) == GOLDEN_AGREEMENT_HASH + + +def test_order_insensitive_canonical_sort(): + reordered = { + "sla": {"minQualityBps": 9000, "deadlineSeconds": 3600}, + "input": {"maxTokens": 500, "lang": "en"}, + "request": {"url": "https://example.com/doc", "service": "summarize"}, + "schemaVersion": "1.0.0", + } + assert compute_agreement_hash(reordered) == GOLDEN_AGREEMENT_HASH + + +def test_frozen_schema_version_and_zero_sentinel(): + assert AGREEMENT_SCHEMA_VERSION == "1.0.0" + assert ZERO_AGREEMENT_HASH == "0x" + "0" * 64 + + +def test_rejects_missing_required_key(): + with pytest.raises(InvalidAgreementError): + validate_agreement({"schemaVersion": "1.0.0", "request": {}, "input": {}}) + + +def test_rejects_extra_key(): + with pytest.raises(InvalidAgreementError): + validate_agreement( + {"schemaVersion": "1.0.0", "request": {}, "input": {}, "sla": {}, "quote": {}} + ) + + +def test_rejects_non_dict(): + with pytest.raises(InvalidAgreementError): + validate_agreement("nope") + with pytest.raises(InvalidAgreementError): + validate_agreement([]) + + +def test_rejects_unsupported_major_version(): + with pytest.raises(UnsupportedAgreementVersionError): + compute_agreement_hash( + {"schemaVersion": "2.0.0", "request": {}, "input": {}, "sla": {}} + ) diff --git a/tests/test_cli/test_e2e_publish_claim_discover.py b/tests/test_cli/test_e2e_publish_claim_discover.py index ffa5bd0..264e2aa 100644 --- a/tests/test_cli/test_e2e_publish_claim_discover.py +++ b/tests/test_cli/test_e2e_publish_claim_discover.py @@ -86,11 +86,17 @@ def test_publish_dry_run(self, tmp_path: Path, monkeypatch) -> None: md_path = tmp_path / "AGIRAILS.md" md_path.write_text(SAMPLE_AGIRAILS_MD) - result = runner.invoke(app, [ - "publish", - "--network", "mock", - "--dry-run", - ]) + with patch( + "agirails.api.agirails_app.check_slug", + new_callable=AsyncMock, + return_value={"available": True}, + ) as check_slug: + result = runner.invoke(app, [ + "publish", + "--network", "mock", + "--dry-run", + ]) + check_slug.assert_awaited_once_with("e2e-test-agent") assert result.exit_code == 0, f"Dry-run failed: {result.output}" diff --git a/tests/test_cli/test_local_operator_contracts.py b/tests/test_cli/test_local_operator_contracts.py new file mode 100644 index 0000000..e4ad790 --- /dev/null +++ b/tests/test_cli/test_local_operator_contracts.py @@ -0,0 +1,169 @@ +"""CLI reads/writes against isolated real runtime/config and policy boundaries.""" + +import asyncio +import importlib +import json +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest +from typer.testing import CliRunner +import typer + +from agirails.cli.main import app +from agirails.client import ACTPClient +from agirails.cli.utils.client import init_directory, load_config +from agirails.cli.utils import validation +from agirails.runtime.base import CreateTransactionParams +from agirails.server.policy import load_policy_from_file, load_policy_from_dict + +runner=CliRunner() +REQUESTER='0x'+'11'*20 +PROVIDER='0x'+'22'*20 +MISSING='0x'+'ff'*32 + + +@pytest.fixture +def operator(tmp_path,monkeypatch): + monkeypatch.chdir(tmp_path) + init_directory(tmp_path,mode='mock',address=REQUESTER) + async def create(): + client=await ACTPClient.create(mode='mock',requester_address=REQUESTER,state_directory=str(tmp_path/'.actp')) + tx1=await client.runtime.create_transaction(CreateTransactionParams(PROVIDER,REQUESTER,'1000000',client.runtime.time.now()+3600)) + tx2=await client.runtime.create_transaction(CreateTransactionParams(PROVIDER,REQUESTER,'2000000',client.runtime.time.now()+7200)) + await client.runtime.transition_state(tx1,'QUOTED') + return client,tx1,tx2 + client,tx1,tx2=asyncio.run(create()) + module=importlib.import_module('agirails.cli.commands.tx') + monkeypatch.setattr(module,'get_client',AsyncMock(return_value=client)) + return client,tx1,tx2,tmp_path,module + + +@pytest.mark.parametrize('flags',[[],['--json'],['--quiet']]) +def test_tx_status_list_filter_limit_and_transition_actual_state(operator,flags): + client,tx1,tx2,_,_=operator + status=runner.invoke(app,[*flags,'tx','status',tx1]) + assert status.exit_code==0,status.output + assert 'QUOTED' in status.stdout + if '--json' in flags: + data=json.loads(status.stdout) + assert data['id']==tx1 and data['amount']=='1000000' + assert data['requester']==REQUESTER and data['provider']==PROVIDER + listing=runner.invoke(app,[*flags,'tx','list','--state','QUOTED','--limit','1']) + assert listing.exit_code==0,listing.output + if '--json' in flags: + data=json.loads(listing.stdout) + assert data['count']==1 and data['transactions'][0]['id']==tx1 + else: + assert tx2 not in listing.stdout + transition=runner.invoke(app,[*flags,'tx','transition',tx2,'QUOTED']) + assert transition.exit_code==0,transition.output + actual=asyncio.run(client.runtime.get_transaction(tx2)) + assert actual.state=='QUOTED' + listing=runner.invoke(app,[*flags,'tx','list','--state','SETTLED']) + assert listing.exit_code==0,listing.output + if '--json' in flags:assert json.loads(listing.stdout)['transactions']==[] + + +@pytest.mark.parametrize('flags',[[],['--json'],['--quiet']]) +@pytest.mark.parametrize('command',[['status','bad'],['status',MISSING],['list','--state','bad'],['transition',MISSING,'QUOTED'],['transition',MISSING,'bad']]) +def test_tx_invalid_input_and_missing_transactions_fail_with_no_state_change(operator,flags,command): + client,tx1,tx2,_,_=operator + result=runner.invoke(app,[*flags,'tx',*command]) + assert result.exit_code==1,result.output + if '--json' in flags:assert json.loads(result.stdout)['error'] + assert asyncio.run(client.runtime.get_transaction(tx1)).state=='QUOTED' + assert asyncio.run(client.runtime.get_transaction(tx2)).state=='INITIATED' + + +@pytest.mark.parametrize('flags',[[],['--json']]) +@pytest.mark.parametrize('command',[['status',MISSING],['list'],['transition',MISSING,'QUOTED']]) +@pytest.mark.parametrize('failure',['uninitialized','unavailable']) +def test_tx_operator_failures_surface_without_success(operator,flags,command,failure,monkeypatch): + _,_,_,_,module=operator + if failure=='uninitialized':monkeypatch.setattr(module,'ensure_initialized',lambda directory:False) + else:monkeypatch.setattr(module,'get_client',AsyncMock(side_effect=ConnectionError('local unavailable'))) + result=runner.invoke(app,[*flags,'tx',*command]) + assert result.exit_code==1,result.output + if '--json' in flags:assert json.loads(result.stdout)['error'] + + +@pytest.mark.parametrize('flags',[[],['--json'],['--quiet']]) +@pytest.mark.parametrize('key,value',[('mode','testnet'),('address',PROVIDER),('rpc_url','https://rpc.example.invalid')]) +def test_config_round_trip_uses_real_local_storage(operator,flags,key,value): + _,_,_,directory,_=operator + changed=runner.invoke(app,[*flags,'config','set',key,value]) + assert changed.exit_code==0,changed.output + assert load_config(directory)[key]==value + result=runner.invoke(app,[*flags,'config','get',key]) + assert result.exit_code==0,result.output + if '--json' in flags: + data=json.loads(result.stdout);assert data['value']==value and data['exists'] is True + else:assert value in result.stdout + show=runner.invoke(app,[*flags,'config','show']) + assert show.exit_code==0,show.output + if '--json' in flags:assert json.loads(show.stdout)['config'][key]==value + missing=runner.invoke(app,[*flags,'config','get','not_set']) + assert missing.exit_code==0 + if '--json' in flags:assert json.loads(missing.stdout)['exists'] is False + + +@pytest.mark.parametrize('flags',[[],['--json']]) +@pytest.mark.parametrize('key,value',[('private_key','never-store-this'),('unknown','x'),('mode','bad'),('address','invalid')]) +def test_config_rejects_secrets_unknown_keys_and_invalid_values(operator,flags,key,value): + _,_,_,directory,_=operator + before=load_config(directory) + result=runner.invoke(app,[*flags,'config','set',key,value]) + assert result.exit_code==1,result.output + assert load_config(directory)==before + assert value not in json.dumps(load_config(directory)) or value in json.dumps(before) + + +def policy_data(): + return {'pricing':{'min_acceptable':{'amount':'50000'},'ideal_price':{'amount':'100000'}},'services':['echo']} + + +@pytest.mark.parametrize('duration,seconds',[('15m',900),('1h',3600),('2d',172800),('900',900),(60,60),(None,900)]) +def test_policy_file_preserves_duration_and_pricing_constraints(tmp_path,duration,seconds): + data=policy_data();data['quote_ttl']=duration + path=tmp_path/'policy.json';path.write_text(json.dumps(data)) + policy=load_policy_from_file(path) + assert policy.quote_ttl_seconds==seconds + assert policy.pricing.min_acceptable_amount==50000 + assert policy.pricing.ideal_amount==100000 + assert policy.services==['echo'] + + +@pytest.mark.parametrize('change,message',[ + ({'pricing':{'min_acceptable':{'amount':'1'},'ideal_price':{'amount':'100000'}}},'below platform'), + ({'pricing':{'min_acceptable':{'amount':'100000'},'ideal_price':{'amount':'50000'}}},'ideal_amount'), + ({'pricing':{'min_acceptable':{'amount':'50000','currency':'EUR'},'ideal_price':{'amount':'100000'}}},'Only USDC'), + ({'counter_strategy':'invalid'},'counter_strategy'),({'concede_pct':0},'concede_pct'), + ({'concede_pct':100},'concede_pct'),({'max_requotes':-1},'max_requotes'), + ({'min_deadline_seconds':-1},'min_deadline_seconds'),({'quote_ttl':'bad'},'Invalid duration'), + ({'quote_ttl':[]},'Invalid duration type'), +]) +def test_invalid_policy_rejected_at_load(change,message): + data=policy_data();data.update(change) + with pytest.raises(ValueError,match=message):load_policy_from_dict(data) + + +@pytest.mark.parametrize('fn,value,valid',[ + (validation.validate_seconds,0,True),(validation.validate_seconds,31536000,True), + (validation.validate_seconds,-1,False),(validation.validate_seconds,31536001,False), + (validation.validate_timestamp,1577836800,True),(validation.validate_timestamp,4102444800,True), + (validation.validate_timestamp,-1,False),(validation.validate_timestamp,1,False),(validation.validate_timestamp,4102444801,False), + (validation.validate_amount,'1.000001',True),(validation.validate_amount,'1.0000001',False), + (validation.validate_amount,'-1',False),(validation.validate_amount,'0',False),(validation.validate_amount,'bad',False), +]) +def test_validation_numeric_boundaries(fn,value,valid): + if valid:assert fn(value)==value + else: + with pytest.raises(typer.BadParameter):fn(value) + + +def test_path_validation_resolves_and_enforces_existence(tmp_path): + target=tmp_path/'file.txt';target.write_text('test') + assert validation.validate_path(target,must_exist=True)==target.resolve() + with pytest.raises(typer.BadParameter,match='does not exist'): + validation.validate_path(tmp_path/'missing',must_exist=True) diff --git a/tests/test_cli/test_negotiation_operator.py b/tests/test_cli/test_negotiation_operator.py new file mode 100644 index 0000000..8b2fdcd --- /dev/null +++ b/tests/test_cli/test_negotiation_operator.py @@ -0,0 +1,96 @@ +"""Supported negotiation CLI with local discovery and no transaction broadcast.""" + +import importlib +import json +from copy import deepcopy +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from typer.testing import CliRunner + +from agirails.cli.main import app +from agirails.api.discover import _parse_result +from tests.test_negotiation.test_buyer_orchestrator import MockRuntime, mock_agent + +runner = CliRunner() +POLICY = { + "task": "echo", + "constraints": { + "max_unit_price": {"amount": 1, "currency": "USDC", "unit": "request"}, + "max_daily_spend": {"amount": 10, "currency": "USDC"}, + }, + "negotiation": {"rounds_max": 2, "quote_ttl": "1s"}, + "selection": {"prioritize": ["price", "quality"]}, +} + + +@pytest.fixture +def operator(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + path = tmp_path / "buyer.json" + path.write_text(json.dumps(POLICY)) + client = SimpleNamespace(runtime=MockRuntime(), address="0x" + "11" * 20) + client_module = importlib.import_module("agirails.cli.utils.client") + monkeypatch.setattr(client_module, "get_client", AsyncMock(return_value=client)) + return path, client + + +@pytest.mark.parametrize("flags", [[], ["--json"], ["--quiet"]]) +@pytest.mark.parametrize("has_candidates", [True, False]) +def test_negotiate_dry_run_scores_real_candidates_without_creating_transactions(operator, monkeypatch, flags, has_candidates): + path, client = operator + module = importlib.import_module("agirails.negotiation.buyer_orchestrator") + candidates = [mock_agent("provider", 0.5, 95, "0x" + "22" * 20)] if has_candidates else [] + discover = AsyncMock(return_value=_parse_result({"agents": candidates, "total": len(candidates)})) + monkeypatch.setattr(module, "discover_agents", discover) + result = runner.invoke(app, [*flags, "negotiate", "--policy", str(path), "--dry-run"]) + assert result.exit_code == (0 if has_candidates else 1), result.output + assert client.runtime._transactions == {} + assert discover.await_count == 1 + if "--json" in flags: + data = json.loads(result.stdout) + assert data["success"] is has_candidates + assert data["rounds_used"] == 0 + assert len(data["rounds"]) == (1 if has_candidates else 0) + elif not flags: + assert ("Negotiation complete" if has_candidates else "No candidates") in result.stdout + + +@pytest.mark.parametrize("key,value,fragment", [ + ("task", "", "task"), + ("constraints", {}, "max_unit_price"), + ("negotiation", {"rounds_max": False, "quote_ttl": "1s"}, "rounds_max"), + ("negotiation", {"rounds_max": 1, "quote_ttl": "wrong"}, "quote_ttl"), + ("negotiation", {"rounds_max": 1}, "quote_ttl"), + ("selection", {"prioritize": []}, "prioritize"), +]) +def test_invalid_policy_returns_actionable_json(operator, key, value, fragment): + path, _ = operator + data = deepcopy(POLICY) + data[key] = value + path.write_text(json.dumps(data)) + result = runner.invoke(app, ["--json", "negotiate", "--policy", str(path), "--dry-run"]) + assert result.exit_code == 1 + assert fragment in json.loads(result.stdout)["error"] + + +@pytest.mark.parametrize("interval", ["bad", "99", "-1", "0.5"]) +def test_invalid_poll_interval_is_rejected_before_execution(operator, interval): + path, client = operator + result = runner.invoke(app, ["--json", "negotiate", "--policy", str(path), "--poll-interval", interval]) + assert result.exit_code == 1 + assert "poll-interval" in json.loads(result.stdout)["error"] + assert client.runtime._transactions == {} + + +@pytest.mark.parametrize("content", [None, "invalid-json"]) +def test_missing_or_unreadable_policy_has_nonzero_exit(operator, content): + path, _ = operator + if content is None: + path.unlink() + else: + path.write_text(content) + result = runner.invoke(app, ["--json", "negotiate", "--policy", str(path)]) + assert result.exit_code == 1 + assert "Failed to load policy" in json.loads(result.stdout)["error"] diff --git a/tests/test_cli/test_operator_paths.py b/tests/test_cli/test_operator_paths.py new file mode 100644 index 0000000..738d64e --- /dev/null +++ b/tests/test_cli/test_operator_paths.py @@ -0,0 +1,205 @@ +"""Operator-facing CLI outcomes on local fixtures and real mock runtime.""" + +import importlib +import json +import subprocess +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from typer.testing import CliRunner + +from agirails.cli.main import app + +batch_module = importlib.import_module("agirails.cli.commands.batch") +watch_module = importlib.import_module("agirails.cli.commands.watch") +runner = CliRunner() +TX = "0x" + "ab" * 32 +PROVIDER = "0x" + "22" * 20 + + +@pytest.fixture(autouse=True) +def local_directory(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + + +@pytest.mark.parametrize("flags", [[], ["--json"], ["--quiet"]]) +@pytest.mark.parametrize("amount,fee", [("1", "50000"), ("5", "50000"), ("10", "100000")]) +def test_simulation_reports_fees_without_creating_a_transaction(flags, amount, fee): + result = runner.invoke(app, [*flags, "simulate", "fee", amount]) + assert result.exit_code == 0, result.output + if "--json" in flags: + data = json.loads(result.stdout) + assert data["amountWei"] == str(int(amount) * 1_000_000) + assert data["feeWei"] == fee + assert data["minimumApplied"] is (int(amount) < 5) + else: + assert "Fee" in result.stdout + + +@pytest.mark.parametrize("flags", [[], ["--json"]]) +@pytest.mark.parametrize("to,amount,deadline,valid", [ + (PROVIDER, "1", "+24h", True), + (PROVIDER, "100", "+1h", True), + ("invalid", "1", "+24h", False), + (PROVIDER, "zero", "+24h", False), + (PROVIDER, "1", "1", False), +]) +def test_payment_simulation_validates_inputs(flags, to, amount, deadline, valid, tmp_path): + result = runner.invoke(app, [*flags, "simulate", "pay", to, amount, "--deadline", deadline]) + assert result.exit_code == (0 if valid else 1), result.output + if "--json" in flags: + data = json.loads(result.stdout) + assert data["valid"] is valid + if valid: + assert data["simulation"]["provider"] == to.lower() + assert data["simulation"]["action"] == "CREATE_AND_FUND_TRANSACTION" + else: + assert data["errors"] + assert not (tmp_path / ".actp" / "state.json").exists() + + +@pytest.mark.parametrize("command", ["", "unknown", "tx", "tx unknown", "balance; echo no", "pay 'unterminated"]) +def test_batch_rejects_invalid_commands_before_subprocess(command, monkeypatch): + calls = [] + monkeypatch.setattr(batch_module.subprocess, "run", lambda *a, **kw: calls.append(a)) + success, message, duration = batch_module.execute_command(command) + assert success is False + assert message + assert duration >= 0 + assert calls == [] + + +@pytest.mark.parametrize("status,stdout,stderr,success,message", [ + (0, " done ", "", True, "done"), + (0, "", "", True, "OK"), + (1, "", '{"error":{"message":"denied"}}', False, "denied"), + (2, "", "plain error", False, "plain error"), + (7, "", "", False, "Exit code: 7"), +]) +def test_batch_subprocess_result_and_argv_contract(monkeypatch, status, stdout, stderr, success, message): + calls = [] + def run(argv, **kwargs): + calls.append((argv, kwargs)) + return SimpleNamespace(returncode=status, stdout=stdout, stderr=stderr) + monkeypatch.setattr(batch_module.subprocess, "run", run) + ok, output, duration = batch_module.execute_command("balance") + assert (ok, output) == (success, message) + assert duration >= 0 + assert calls[0][0] == ["actp", "balance", "--json"] + assert calls[0][1]["shell"] is False + assert calls[0][1]["timeout"] == 120 + + +@pytest.mark.parametrize("error,message", [ + (FileNotFoundError(), "not found"), + (subprocess.TimeoutExpired("actp", 120), "timed out"), +]) +def test_batch_reports_execution_failures(monkeypatch, error, message): + def fail(*args, **kwargs): + raise error + monkeypatch.setattr(batch_module.subprocess, "run", fail) + ok, output, _ = batch_module.execute_command("balance") + assert ok is False + assert message in output + + +@pytest.mark.parametrize("flags", [[], ["--json"], ["--quiet"]]) +@pytest.mark.parametrize("stop", [False, True]) +def test_batch_dry_run_aggregates_results_and_preserves_line_numbers(tmp_path, flags, stop): + path = tmp_path / "commands.txt" + path.write_text("# ignored\n\nbalance\nunknown\ntime show\n") + args = [*flags, "batch", str(path), "--dry-run"] + if stop: + args.append("--stop-on-error") + result = runner.invoke(app, args) + assert result.exit_code == 1 + if "--json" in flags: + data = json.loads(result.stdout) + assert data["summary"]["failed"] == 1 + assert data["summary"]["succeeded"] == (1 if stop else 2) + assert [r["line"] for r in data["results"]] == ([3, 4] if stop else [3, 4, 5]) + + +@pytest.mark.parametrize("stop", [False, True]) +def test_batch_execution_stops_and_counts_remaining_commands(monkeypatch, stop): + responses = iter([(True, "ok", 1), (False, "failed", 2), (True, "next", 3)]) + calls = [] + def execute(command): + calls.append(command) + return next(responses) + monkeypatch.setattr(batch_module, "execute_command", execute) + args = ["--json", "batch", "-"] + (["--stop-on-error"] if stop else []) + result = runner.invoke(app, args, input="balance\ntime show\nconfig show\n") + assert result.exit_code == 1 + data = json.loads(result.stdout) + assert data["summary"] == {"total": 3, "succeeded": 1 if stop else 2, "failed": 1, "skipped": 1 if stop else 0} + assert len(calls) == (2 if stop else 3) + + +@pytest.mark.parametrize("source", ["empty", "missing"]) +def test_batch_handles_empty_and_missing_files(tmp_path, source): + path = tmp_path / "commands.txt" + if source == "empty": + path.write_text("# no commands\n") + result = runner.invoke(app, ["--json", "batch", str(path), "--dry-run"]) + assert result.exit_code == (0 if source == "empty" else 1) + if source == "empty": + assert json.loads(result.stdout)["total"] == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("json_output,quiet", [(False, False), (True, False), (False, True)]) +@pytest.mark.parametrize("states,until,expected", [ + (["SETTLED"], None, 0), + (["QUOTED"], "QUOTED", 0), + (["INITIATED", "DELIVERED"], "DELIVERED", 0), + (["INITIATED", "SETTLED"], None, 0), + (["INITIATED", None], None, 1), + ([None], None, 1), +]) +async def test_watch_observes_states_and_returns_meaningful_exit_codes(monkeypatch, capsys, states, until, expected, json_output, quiet): + txs = [None if state is None else SimpleNamespace(state=state, updated_at=1700000000) for state in states] + get_transaction = AsyncMock(side_effect=txs) + client = SimpleNamespace(standard=SimpleNamespace(get_transaction=get_transaction)) + monkeypatch.setattr(watch_module, "get_client", AsyncMock(return_value=client)) + code = await watch_module.run_watch(TX, 1, 0, until, json_output, quiet, None, "mock") + assert code == expected + assert get_transaction.await_count == len(states) + output = capsys.readouterr().out + if json_output and txs[0] is not None: + events = [json.loads(line) for line in output.splitlines()] + assert events[0]["toState"] == states[0] + assert events[0]["txId"] == TX + elif quiet and txs[0] is not None: + assert states[0] in output + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tx_id,until", [("invalid", None), (TX, "UNKNOWN"), ("0x" + "zz" * 32, None)]) +async def test_watch_rejects_invalid_input_without_loading_client(monkeypatch, tx_id, until): + get_client = AsyncMock() + monkeypatch.setattr(watch_module, "get_client", get_client) + assert await watch_module.run_watch(tx_id, 1, 0, until, True, False, None, "mock") == 1 + get_client.assert_not_awaited() + + +def test_watch_cli_retains_success_exit_code(monkeypatch): + client = SimpleNamespace(standard=SimpleNamespace(get_transaction=AsyncMock(return_value=SimpleNamespace(state="SETTLED", updated_at=1700000000)))) + monkeypatch.setattr(watch_module, "get_client", AsyncMock(return_value=client)) + result = runner.invoke(app, ["--json", "watch", TX]) + assert result.exit_code == 0, result.output + event = json.loads(result.stdout) + assert event["toState"] == "SETTLED" + + +def test_tx_transition_forwards_explicit_proof(monkeypatch): + module = importlib.import_module("agirails.cli.commands.tx") + transition = AsyncMock() + client = SimpleNamespace(standard=SimpleNamespace(transition_state=transition)) + monkeypatch.setattr(module, "ensure_initialized", lambda directory: True) + monkeypatch.setattr(module, "get_client", AsyncMock(return_value=client)) + proof = "0x" + "cd" * 32 + result = runner.invoke(app, ["--json", "tx", "transition", TX, "DELIVERED", "--proof", proof]) + assert result.exit_code == 0, result.output + transition.assert_awaited_once_with(tx_id=TX, new_state="DELIVERED", proof=proof) diff --git a/tests/test_cli/test_publish_parity.py b/tests/test_cli/test_publish_parity.py index 638936d..a70f385 100644 --- a/tests/test_cli/test_publish_parity.py +++ b/tests/test_cli/test_publish_parity.py @@ -243,6 +243,16 @@ def test_app_sync_failure_doesnt_crash( class TestEnhancedMessaging: """Test context-aware next steps messaging.""" + @pytest.fixture(autouse=True) + def available_slug(self): + with patch( + "agirails.api.agirails_app.check_slug", + new_callable=AsyncMock, + return_value={"available": True}, + ) as check_slug: + yield + check_slug.assert_awaited_once_with("test-agent") + @patch("agirails.cli.commands.publish.publish_config") def test_messaging_includes_health( self, diff --git a/tests/test_cli/test_time_operator.py b/tests/test_cli/test_time_operator.py new file mode 100644 index 0000000..0414644 --- /dev/null +++ b/tests/test_cli/test_time_operator.py @@ -0,0 +1,71 @@ +"""Time CLI drives the actual isolated MockRuntime and checks state readback.""" + +import asyncio +import importlib +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from typer.testing import CliRunner + +from agirails.client import ACTPClient +from agirails.cli.main import app + +runner = CliRunner() +module = importlib.import_module("agirails.cli.commands.time") + + +@pytest.fixture +def client(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + instance = asyncio.run(ACTPClient.create(mode="mock", requester_address="0x" + "11" * 20, state_directory=str(tmp_path / "state"))) + monkeypatch.setattr(module, "ensure_initialized", lambda directory: True) + monkeypatch.setattr(module, "get_client", AsyncMock(return_value=instance)) + return instance + + +@pytest.mark.parametrize("flags", [[], ["--json"], ["--quiet"]]) +@pytest.mark.parametrize("command", [[], ["show"], ["advance", "3600"], ["set", "1900000000"]]) +def test_time_commands_preserve_operator_output_and_runtime_state(client, flags, command): + before = client.runtime.time.now() + result = runner.invoke(app, [*flags, "time", *command]) + assert result.exit_code == 0, result.output + after = client.runtime.time.now() + if command[:1] == ["advance"]: + assert after - before >= 3600 + elif command[:1] == ["set"]: + assert 1900000000 <= after <= 1900000002 + if "--json" in flags: + data = json.loads(result.stdout) + if command and command[0] in ("advance", "set"): + assert data["success"] is True + assert data["newTime"] == after + else: + assert data["timestamp"] == after + elif "--quiet" in flags: + assert int(result.stdout.strip()) == after + else: + assert "Time" in result.stdout or "time" in result.stdout + + +@pytest.mark.parametrize("flags", [[], ["--json"], ["--quiet"]]) +@pytest.mark.parametrize("command", [["show"], ["advance", "1"], ["set", "1900000000"]]) +@pytest.mark.parametrize("failure", ["uninitialized", "nonmock", "rpc_error"]) +def test_time_refuses_unsupported_runtime_or_unavailable_client(client, monkeypatch, flags, command, failure): + if failure == "uninitialized": + monkeypatch.setattr(module, "ensure_initialized", lambda directory: False) + elif failure == "nonmock": + monkeypatch.setattr(module, "get_client", AsyncMock(return_value=SimpleNamespace(runtime=object()))) + else: + monkeypatch.setattr(module, "get_client", AsyncMock(side_effect=RuntimeError("local fixture unavailable"))) + result = runner.invoke(app, [*flags, "time", *command]) + assert result.exit_code == 1 + if "--json" in flags: + assert json.loads(result.stdout)["error"] + + +@pytest.mark.parametrize("command", [["advance", "-1"], ["set", "0"]]) +def test_time_rejects_invalid_ranges(client, command): + result = runner.invoke(app, ["--json", "time", *command]) + assert result.exit_code != 0 diff --git a/tests/test_client.py b/tests/test_client.py index d86644a..98518c3 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -544,7 +544,7 @@ async def test_start_work_deliver_release_full_flow(self, client, provider_addre tx = await client.runtime.get_transaction(tx_id) assert (tx.state.value if hasattr(tx.state, "value") else tx.state) == "IN_PROGRESS" - await client.deliver(tx_id) + await client.deliver(tx_id, result_hash="0x" + "11" * 32) tx = await client.runtime.get_transaction(tx_id) assert (tx.state.value if hasattr(tx.state, "value") else tx.state) == "DELIVERED" @@ -561,7 +561,7 @@ async def test_deliver_from_committed_two_step(self, client, provider_address): """deliver() from COMMITTED auto-runs IN_PROGRESS then DELIVERED (mock).""" result = await client.pay({"to": provider_address, "amount": 100}) tx_id = _tx_id_of(result) - await client.deliver(tx_id) + await client.deliver(tx_id, result_hash="0x" + "11" * 32) tx = await client.runtime.get_transaction(tx_id) assert (tx.state.value if hasattr(tx.state, "value") else tx.state) == "DELIVERED" @@ -776,7 +776,7 @@ async def test_deliver_batches_when_committed(self, runtime): assert client._smart_wallet_router is not None assert client._smart_wallet_router.should_route() is True - await client.deliver(tx_id) + await client.deliver(tx_id, result_hash="0x" + "11" * 32) # One batch of exactly 2 calls (startWork + deliver). assert len(wp.batches) == 1 assert len(wp.batches[0]) == 2 diff --git a/tests/test_client_failure_contracts.py b/tests/test_client_failure_contracts.py new file mode 100644 index 0000000..afb523a --- /dev/null +++ b/tests/test_client_failure_contracts.py @@ -0,0 +1,170 @@ +"""Client commitments, settlement ordering and read-only startup drift checks.""" + +import json +from functools import partial +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from web3 import Web3 + +from agirails.client import ACTPClient, ACTPClientConfig, ACTPClientInfo +from agirails.config.pending_publish import PendingPublishData, ServiceDescriptorData +from agirails.protocol.agent_registry import _load_agent_registry_abi + +ADDRESS='0x'+'12'*20 +REGISTRY='0x'+'23'*20 +HASH='0x'+'34'*32 +TX='0x'+'45'*32 + + +@pytest.mark.parametrize('value',[bytes.fromhex(HASH[2:]),bytearray.fromhex(HASH[2:]),HASH,HASH[2:],'0X'+HASH[2:]]) +def test_explicit_result_commitment_has_priority_over_payload_and_stored_data(value): + tx=SimpleNamespace(delivery_proof=json.dumps({'resultHash':'0x'+'99'*32})) + assert ACTPClient._resolve_result_hash(TX,tx,result={'a':1},result_hash=value)==bytes.fromhex(HASH[2:]) + + +def test_payload_hash_uses_actual_canonical_commitment(): + tx=SimpleNamespace(delivery_proof=json.dumps({'resultHash':HASH})) + assert ACTPClient._resolve_result_hash(TX,tx,result={'a':1})==Web3.keccak(text='{"a":1}') + + +@pytest.mark.parametrize('key',['resultHash','result_hash']) +def test_stored_proof_binds_the_existing_delivery_commitment(key): + tx=SimpleNamespace(delivery_proof=json.dumps({key:HASH})) + assert ACTPClient._resolve_result_hash(TX,tx)==bytes.fromhex(HASH[2:]) + + +@pytest.mark.parametrize('stored',[None,'bad','[]','{}',json.dumps({'resultHash':'short'}),json.dumps({'result_hash':'0x12'})]) +def test_missing_or_malformed_commitments_fail_without_a_synthetic_result(stored): + with pytest.raises(ValueError,match='requires a real deliverable'): + ACTPClient._resolve_result_hash(TX,SimpleNamespace(delivery_proof=stored)) + + +@pytest.mark.parametrize('value',[b'',b'1'*31,b'1'*33,'0x12']) +def test_explicit_wrong_length_result_hash_is_rejected(value): + with pytest.raises(ValueError,match='32 bytes'): + ACTPClient._resolve_result_hash(TX,SimpleNamespace(),result_hash=value) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('state',['DELIVERED','SETTLED']) +@pytest.mark.parametrize('route',[False,True]) +@pytest.mark.parametrize('report',['none','success','failure']) +async def test_settlement_routes_once_and_reputation_failure_does_not_undo_it(state,route,report): + trace=[] + async def record(name,*args):trace.append((name,args)) + runtime=SimpleNamespace(get_transaction=AsyncMock(return_value=SimpleNamespace(state=state,agent_id=42)),release_escrow=AsyncMock(side_effect=partial(record,'runtime'))) + router=SimpleNamespace(should_route=lambda:route,validate_release_preconditions=AsyncMock(side_effect=partial(record,'validate')),verify_release_attestation=AsyncMock(side_effect=partial(record,'attestation')),send_settle=AsyncMock(side_effect=partial(record,'settle'))) + client=ACTPClient(runtime,ADDRESS,ACTPClientInfo(mode='mock',address=ADDRESS)) + client._smart_wallet_router=router + if report!='none': + async def reporter(**kw): + trace.append(('report',kw)) + if report=='failure':raise RuntimeError('reporter unavailable after settlement') + return SimpleNamespace(tx_hash=HASH) + client._reputation_reporter=SimpleNamespace(report_settlement=AsyncMock(side_effect=reporter)) + await client.release(TX,HASH) + names=[entry[0] for entry in trace] + expected=[] if state=='SETTLED' else ['validate','attestation','settle'] if route else ['runtime'] + if report!='none':expected+=['report'] + assert names==expected + if state!='SETTLED' and route: + router.verify_release_attestation.assert_awaited_once_with(TX,HASH) + router.send_settle.assert_awaited_once_with(TX) + elif state!='SETTLED':runtime.release_escrow.assert_awaited_once_with(TX,HASH) + + +@pytest.mark.asyncio +async def test_attestation_failure_stops_settlement_and_reputation(): + runtime=SimpleNamespace(get_transaction=AsyncMock(return_value=SimpleNamespace(state='DELIVERED',agent_id=42)),release_escrow=AsyncMock()) + router=SimpleNamespace(should_route=lambda:True,validate_release_preconditions=AsyncMock(),verify_release_attestation=AsyncMock(side_effect=ValueError('invalid attestation')),send_settle=AsyncMock()) + client=ACTPClient(runtime,ADDRESS,ACTPClientInfo(mode='mock',address=ADDRESS)) + client._smart_wallet_router=router + reporter=AsyncMock();client._reputation_reporter=SimpleNamespace(report_settlement=reporter) + with pytest.raises(ValueError,match='invalid attestation'):await client.release(TX,HASH) + router.send_settle.assert_not_awaited();runtime.release_escrow.assert_not_awaited();reporter.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('scenario,expected',[('A',['registerAgent','publishConfig','setListed']),('B1',['publishConfig','setListed']),('B2',['publishConfig'])]) +@pytest.mark.parametrize('cleanup_failure',[False,True]) +async def test_activation_call_data_and_success_callback_do_not_repeat_registration(tmp_path,monkeypatch,scenario,expected,cleanup_failure): + pending=PendingPublishData(config_hash=HASH,cid='bafy-config',endpoint='https://agent.invalid',service_descriptors=[ServiceDescriptorData(HASH,'echo',min_price='50000',max_price='1000000')]) + runtime=SimpleNamespace() + client=ACTPClient(runtime,ADDRESS,ACTPClientInfo(mode='mock',address=ADDRESS),lazy_scenario=scenario,pending_publish=pending,agent_registry_address=REGISTRY,network_id='base-sepolia') + removed=[] + def remove(**kw): + removed.append(kw) + if cleanup_failure:raise OSError('local deletion unavailable') + monkeypatch.setattr('agirails.config.pending_publish.delete_pending_publish',remove) + batch=client.get_activation_calls() + decoder=Web3().eth.contract(abi=_load_agent_registry_abi()) + decoded=[decoder.decode_function_input(call.data) for call in batch['calls']] + assert [fn.fn_name for fn,_ in decoded]==expected + assert all(call.target==REGISTRY and call.value==0 for call in batch['calls']) + if scenario=='A': + assert 'https://agent.invalid' in decoded[0][1].values() + batch['on_success']() + assert removed==[{'network':'base-sepolia'}] + assert client.get_activation_calls()['calls']==[] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('case',['missing','template','published','different','identity','broken_pointer','pay','nested_pay','reader_failure','invalid']) +async def test_startup_drift_never_writes_identity_or_submits_calls(tmp_path,monkeypatch,case): + monkeypatch.chdir(tmp_path);monkeypatch.setenv('ACTP_DIR',str(tmp_path/'.actp')) + client=await ACTPClient.create(mode='mock',requester_address=ADDRESS,state_directory=str(tmp_path/'state')) + cfg=ACTPClientConfig(mode='testnet',requester_address=ADDRESS) + text='---\nname: local\nintent: earn\n'+('config_hash: stored\n' if case=='published' else '')+'---\n# local\n' + if case=='pay':text=text.replace('intent: earn','intent: pay') + if case=='nested_pay':text=text.replace('intent: earn','agent:\n intent: pay') + if case=='invalid':text='not a frontmatter file' + identity=tmp_path/('identity.md' if case=='identity' else 'AGIRAILS.md') + if case!='missing':identity.write_text(text) + if case in ('identity','broken_pointer'): + path=tmp_path/'.actp';path.mkdir(exist_ok=True) + (path/'config.json').write_text(json.dumps({'identity':'identity.md'}) if case=='identity' else 'invalid json') + reads=[] + def chain(*args): + reads.append(args) + if case=='reader_failure':raise ConnectionError('RPC unavailable') + return SimpleNamespace(config_hash='0x'+('ab' if case=='different' else '00')*32) + monkeypatch.setattr('agirails.config.on_chain_state.get_on_chain_config_state',chain) + await client.check_config_drift(cfg) + if case in ('missing','pay','nested_pay','invalid'):assert reads==[] + else:assert len(reads)==1 and reads[0][:2]==(ADDRESS,'base-sepolia') + if case!='missing':assert identity.read_text()==text + + +@pytest.mark.asyncio +@pytest.mark.parametrize('amount',['50000','1000000','123456789']) +async def test_x402_wallet_transfer_encodes_exact_token_principal_and_real_signature(amount): + import rlp + from eth_abi import decode + from eth_account import Account + from agirails.wallet.eoa_wallet_provider import EOAWalletProvider + from tests.test_wallet.test_wallet_wire_boundaries import LocalEOARPC,KEY + rpc=LocalEOARPC() + wallet=EOAWalletProvider(KEY,Web3(rpc),84532) + transfer=ACTPClient._build_x402_transfer_fn(wallet,REGISTRY,'http://offline.invalid') + tx_hash=await transfer(ADDRESS,amount) + raw=rpc.sent[0][0] + assert Account.recover_transaction(raw)==wallet.get_address() + assert tx_hash==Web3.keccak(raw).hex() + fields=rlp.decode(raw[1:]) + assert fields[5].hex()==REGISTRY[2:] + assert int.from_bytes(fields[6],'big')==0 + calldata=fields[7] + assert calldata[:4].hex()=='a9059cbb' + assert decode(['address','uint256'],calldata[4:])==(ADDRESS,int(amount)) + + +@pytest.mark.asyncio +async def test_x402_wallet_failure_or_fractional_base_units_cannot_return_a_proof(): + wallet=SimpleNamespace(send_transaction=AsyncMock(side_effect=RuntimeError('wallet unavailable'))) + transfer=ACTPClient._build_x402_transfer_fn(wallet,REGISTRY,'http://offline.invalid') + with pytest.raises(ValueError):await transfer(ADDRESS,'0.5') + wallet.send_transaction.assert_not_awaited() + with pytest.raises(RuntimeError,match='wallet unavailable'):await transfer(ADDRESS,'1000000') + wallet.send_transaction.assert_awaited_once() diff --git a/tests/test_cross_sdk/test_dispute_parity.py b/tests/test_cross_sdk/test_dispute_parity.py new file mode 100644 index 0000000..981f170 --- /dev/null +++ b/tests/test_cross_sdk/test_dispute_parity.py @@ -0,0 +1,492 @@ +# PARITY: sdk-js/tests/dispute-parity.test.ts +"""P2-10 CAPSTONE — cross-SDK META parity + golden-vector suite (Py side). + +Mirrors ``sdk-js/tests/dispute-parity.test.ts`` 1:1 and consumes the SAME two +shared fixtures under ``DISPUTE SYSTEM/test-vectors/dispute/``: + + - ``parity-surface.json`` — the META manifest: every intentional public dispute + symbol with its TS name + Py name + per-language required arity. This suite + asserts the Py SDK matches its ``py`` column (presence + required arity); the + TS suite asserts the ``ts`` column; and BOTH assert no symbol is + single-language (each manifest row carries a ``ts`` AND a ``py`` name). The + parity-surface DIFF is therefore the manifest itself — a symbol present in + only one SDK could not appear here with both twins AND pass both suites. + + - ``golden-vectors.json`` — five byte/value-identical golden families (AIRuling + digest, bundle-hash, BondEscalation calldata, DisputeSplitRecorded decode + + ZERO-REMAINING rule, split-rate). Both SDKs load THIS file and MUST reproduce + every expected value exactly. + +PARITY: sdk-js/tests/dispute-parity.test.ts +""" + +from __future__ import annotations + +import inspect +import json +from pathlib import Path +from typing import Any, Dict, List + +import pytest +from web3 import Web3 + +# ── The dispute public surface the manifest enumerates ────────────────────── +import agirails.dispute as DISPUTE_NS +import agirails.types.dispute as TYPES_NS +import agirails.reputation.dispute_split_indexer as INDEXER_NS +from agirails.dispute import ( + BondEscalationClient, + CompositeMediator, + DisputeSplitRecorded, + bundle_hash, + compute_bundle_hash, + compute_split_rate, + decode_dispute_split_recorded, + decode_resolution_proof, + serialize_bundle, + serialize_bundle_to_string, +) +from agirails.reputation.dispute_split_indexer import DisputeSplitIndexer +from agirails.types.dispute import ( + AIRuling, + DISPUTE_EVALUATOR_DOMAIN_NAME, + DISPUTE_EVALUATOR_DOMAIN_VERSION, + DOMAIN_TYPEHASH, + RULING_TYPEHASH, + Ruling, + compute_ruling_digest, + compute_ruling_domain_separator, + compute_ruling_struct_hash, +) + +# Shared fixtures (the SAME files the TS jest suite loads). +_VECTORS = Path(__file__).resolve().parents[2] / "test-vectors" / "dispute" +SURFACE = json.loads((_VECTORS / "parity-surface.json").read_text()) +GOLDEN = json.loads((_VECTORS / "golden-vectors.json").read_text()) + +# Flattened runtime namespace of every public dispute symbol. +_NS: Dict[str, Any] = {} +for _mod in (DISPUTE_NS, TYPES_NS, INDEXER_NS): + for _name in dir(_mod): + if not _name.startswith("_"): + _NS.setdefault(_name, getattr(_mod, _name)) + + +def _required_arity(fn: Any) -> int: + """Count REQUIRED parameters (excludes self/cls, *args/**kwargs, defaulted).""" + sig = inspect.signature(fn) + count = 0 + for name, p in sig.parameters.items(): + if name in ("self", "cls"): + continue + if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD): + continue + if p.default is inspect._empty and p.kind in ( + p.POSITIONAL_OR_KEYWORD, + p.POSITIONAL_ONLY, + p.KEYWORD_ONLY, + ): + count += 1 + return count + + +def _want_arity(entry: Dict[str, Any]) -> int: + """The Py-side required arity the manifest declares for this entry.""" + return entry["pyArity"] if "pyArity" in entry else entry["arity"] + + +# =========================================================================== +# META PARITY — Py surface == manifest (and every row has a TS twin) +# =========================================================================== + + +class TestMetaParity: + def test_every_manifest_row_has_both_twins(self): + """No symbol may be single-language: every row carries a ts AND a py name.""" + rows: List[Dict[str, Any]] = [] + rows += SURFACE["enums"] + rows += SURFACE["constants"] + rows += SURFACE["functions"] + rows += SURFACE["types"] + rows += SURFACE["classes"] + for c in SURFACE["classes"]: + rows += c["methods"] + rows += c["staticMethods"] + rows += c.get("accessors", []) + rows += SURFACE["absent"] + for r in rows: + assert isinstance(r.get("ts"), str) and r["ts"], r + assert isinstance(r.get("py"), str) and r["py"], r + + def test_enums_present_with_identical_member_values(self): + for e in SURFACE["enums"]: + cls = _NS.get(e["py"]) + assert cls is not None, f"enum missing: {e['py']}" + for member, value in e["members"].items(): + assert int(getattr(cls, member)) == value, f"{e['py']}.{member}" + + def test_constants_present(self): + for c in SURFACE["constants"]: + assert c["py"] in _NS, f"constant missing: {c['py']}" + + def test_top_level_functions_present_with_py_arity(self): + for f in SURFACE["functions"]: + fn = _NS.get(f["py"]) + assert callable(fn), f"function missing: {f['py']}" + assert _required_arity(fn) == _want_arity(f), ( + f"{f['py']} arity: want {_want_arity(f)} " + f"got {_required_arity(fn)}" + ) + + def test_classes_expose_every_method_and_static_at_py_arity(self): + for c in SURFACE["classes"]: + cls = _NS.get(c["py"]) + assert inspect.isclass(cls), f"class missing: {c['py']}" + for m in c["methods"] + c["staticMethods"]: + fn = getattr(cls, m["py"], None) + assert callable(fn), f"method missing: {c['py']}.{m['py']}" + assert _required_arity(fn) == _want_arity(m), ( + f"{c['py']}.{m['py']} arity: want {_want_arity(m)} " + f"got {_required_arity(fn)}" + ) + + def test_classes_expose_every_accessor_as_a_property_descriptor(self): + """Accessors (Py ``@property``) MUST be validated via their STATIC + descriptor — ``inspect.getattr_static`` returns the ``property`` object + WITHOUT invoking its getter, which would otherwise raise on an + unconfigured facade (e.g. ``DisputeClient.bond`` with no + BondEscalationClient wired). Mirrors the TS twin's + ``Object.getOwnPropertyDescriptor(proto, name).get`` check.""" + for c in SURFACE["classes"]: + for a in c.get("accessors", []): + cls = _NS.get(c["py"]) + assert inspect.isclass(cls), f"class missing: {c['py']}" + descriptor = inspect.getattr_static(cls, a["py"], None) + assert isinstance(descriptor, property), ( + f"{c['py']}.{a['py']} should be a @property accessor" + ) + + def test_types_are_runtime_classes_in_python(self): + """In Py ALL declared types are real runtime classes (dataclass / pydantic + / Exception); the TS twin erases ``kind:type`` interfaces at runtime and + enforces them at compile-time instead — a documented representation + difference, not a parity gap.""" + for t in SURFACE["types"]: + obj = _NS.get(t["py"]) + assert obj is not None, f"type missing: {t['py']}" + assert inspect.isclass(obj), f"type not a class: {t['py']}" + if t.get("kind") == "error": + assert issubclass(obj, Exception), f"{t['py']} not an Exception" + + def test_intentionally_absent_symbols_are_absent(self): + """resolve() is onlyBondEscalation — deliberately omitted from BOTH SDK + clients. Present on the ABI (proving the omission is intentional).""" + abi = json.loads( + ( + Path(__file__).resolve().parents[2] + / "src" / "agirails" / "abis" / "composite_mediator.json" + ).read_text() + ) + abi_fns = {x["name"] for x in abi if x.get("type") == "function"} + for ab in SURFACE["absent"]: + cls = _NS.get(ab["on"]) + assert cls is not None + assert not hasattr(cls, ab["py"]), ( + f"{ab['on']}.{ab['py']} should be absent (onlyBondEscalation)" + ) + assert ab["py"] in abi_fns # exists on-chain + + def test_ts_only_wire_shapes_have_no_python_twin(self): + """The 4 evaluate WIRE-PARSE shapes (SignedEvaluateResponse, + ProposeDirectlyEvaluateResponse, EvaluateResponse, EvaluatorRuling) are + TS-only: Py parses the evaluate response as a raw dict, so there is NO Py + twin. The manifest declares ``pyTwin: null`` for each; this test locks + that — none may appear on the Py public dispute surface, mirroring the TS + twin's de-export assertion on the package entrypoint.""" + ts_only = SURFACE["tsOnlyDeExported"] + assert len(ts_only) > 0 + for t in ts_only: + assert t["pyTwin"] is None, f"{t['ts']} must declare pyTwin: null" + # The TS symbol name must not resolve to anything on the Py surface + # (and no snake_case twin should exist either). + assert t["ts"] not in _NS, ( + f"{t['ts']} leaked onto the Py dispute surface" + ) + + +# =========================================================================== +# GOLDEN VECTOR 1 — AIRuling EIP-712 digest +# =========================================================================== + + +class TestGoldenAIRulingDigest: + def _ruling(self) -> AIRuling: + r = GOLDEN["airulingDigest"]["ruling"] + return AIRuling( + dispute_id=r["disputeId"], + ruling=r["ruling"], + confidence=r["confidence"], + split_bps=r["splitBps"], + timestamp=r["timestamp"], + reasoning_hash=r["reasoningHash"], + bundle_hash=r["bundleHash"], + evidence_ref_hash=r["evidenceRefHash"], + reasoning_ref_hash=r["reasoningRefHash"], + ) + + def test_domain_identity_matches_frozen(self): + d = GOLDEN["airulingDigest"]["domain"] + assert DISPUTE_EVALUATOR_DOMAIN_NAME == d["name"] + assert DISPUTE_EVALUATOR_DOMAIN_VERSION == d["version"] + + def test_struct_hash_matches_frozen(self): + exp = GOLDEN["airulingDigest"]["expected"]["structHash"] + assert "0x" + compute_ruling_struct_hash(self._ruling()).hex() == exp + + def test_domain_separator_matches_frozen(self): + d = GOLDEN["airulingDigest"]["domain"] + exp = GOLDEN["airulingDigest"]["expected"]["domainSeparator"] + sep = compute_ruling_domain_separator(d["chainId"], d["verifyingContract"]) + assert "0x" + sep.hex() == exp + + def test_digest_matches_frozen(self): + d = GOLDEN["airulingDigest"]["domain"] + exp = GOLDEN["airulingDigest"]["expected"]["digest"] + digest = compute_ruling_digest(self._ruling(), d["chainId"], d["verifyingContract"]) + assert "0x" + digest.hex() == exp + + def test_typehash_bytes_are_32_bytes(self): + # Py exposes raw bytes; TS exposes 0x-hex strings — the 32 raw bytes match. + assert len(RULING_TYPEHASH) == 32 + assert len(DOMAIN_TYPEHASH) == 32 + + +# =========================================================================== +# GOLDEN VECTOR 2 — evidence bundle hash +# =========================================================================== + + +class TestGoldenBundleHash: + def test_canonical_bytes_length_matches_frozen(self): + g = GOLDEN["bundleHash"] + assert len(serialize_bundle(g["bundle"])) == g["expected"]["canonicalBytesUtf8Len"] + + def test_bundle_hash_matches_frozen(self): + g = GOLDEN["bundleHash"] + assert bundle_hash(g["bundle"], skip_token_check=True) == g["expected"]["bundleHash"] + assert compute_bundle_hash(g["bundle"], skip_token_check=True) == g["expected"]["bundleHash"] + + def test_canonical_string_stable(self): + g = GOLDEN["bundleHash"] + s = serialize_bundle_to_string(g["bundle"]) + assert json.loads(s)["schemaVersion"] == "1.0.0" + + +# =========================================================================== +# GOLDEN VECTOR 3 — BondEscalation calldata (byte-exact, both SDKs) +# =========================================================================== + + +class TestGoldenBondEscalationCalldata: + _ABI = json.loads( + ( + Path(__file__).resolve().parents[2] + / "src" / "agirails" / "abis" / "bond_escalation.json" + ).read_text() + ) + + def _client(self) -> BondEscalationClient: + # A contract that builds calldata via encode_abi (the assertion surface the + # client uses through encode_calldata) — exactly mirrors the TS twin's + # `interface.encodeFunctionData` capture. + ref = Web3().eth.contract(abi=self._ABI) + + class _C: + def encode_abi(self, *, abi_element_identifier, args): + return ref.encode_abi(abi_element_identifier=abi_element_identifier, args=args) + + return BondEscalationClient(_C(), address="0x00") + + def test_dispute_id_is_deterministic(self): + g = GOLDEN["bondEscalationCalldata"] + from eth_abi import encode as abi_encode + from eth_utils import keccak + + tx_id = bytes.fromhex(g["txId"][2:]) + dispute_id = "0x" + keccak(abi_encode(["string", "bytes32"], ["ACTP_DISPUTE_V1", tx_id])).hex() + assert dispute_id == g["disputeId"] + + def test_open_dispute_calldata_matches_frozen(self): + g = GOLDEN["bondEscalationCalldata"] + client = self._client() + cd = client.encode_calldata("openDispute", [bytes.fromhex(g["txId"][2:])]) + assert cd == g["openDispute"]["calldata"] + assert cd[:10] == g["openDispute"]["selector"] + + def test_challenge_calldata_matches_frozen(self): + g = GOLDEN["bondEscalationCalldata"] + client = self._client() + a = g["challenge"]["args"] + cd = client.encode_calldata( + "challenge", + [bytes.fromhex(g["disputeId"][2:]), a["counterRuling"], a["counterSplitBps"]], + ) + assert cd == g["challenge"]["calldata"] + + def test_submit_ai_ruling_calldata_matches_frozen(self): + # AIP-14c D7: the FINAL 5-arg submitAIRuling (selector 0xca74ab82). The + # shared golden's stored calldata predates D7 (3-arg 7-field), so the + # ruling VALUES are still read from the frozen vector while the expected + # calldata is recomputed INDEPENDENTLY of the SDK ABI JSON — raw eth_abi + # packing + the pinned selector — so this stays a genuine cross-SDK anchor + # (ethers packs the identical bytes on the TS side). + from eth_abi import encode as abi_encode + + from agirails.types.dispute import ( + compute_evidence_ref_hash, + compute_reasoning_ref_hash, + ) + + g = GOLDEN["bondEscalationCalldata"] + client = self._client() + r = g["submitAIRuling"]["args"]["ruling"] + evidence_cid = "bafybeigevidenceCID" + reasoning_cid = "bafybeigreasoningCID" + evidence_ref = compute_evidence_ref_hash(r["bundleHash"], evidence_cid) + reasoning_ref = compute_reasoning_ref_hash(r["reasoningHash"], reasoning_cid) + tuple_arg = ( + bytes.fromhex(r["disputeId"][2:]), + r["ruling"], + r["confidence"], + r["splitBps"], + r["timestamp"], + bytes.fromhex(r["reasoningHash"][2:]), + bytes.fromhex(r["bundleHash"][2:]), + evidence_ref, + reasoning_ref, + ) + sigs = [bytes.fromhex(s[2:]) for s in g["submitAIRuling"]["args"]["signatures"]] + dispute_id = bytes.fromhex(r["disputeId"][2:]) + cd = client.encode_calldata( + "submitAIRuling", [dispute_id, tuple_arg, evidence_cid, reasoning_cid, sigs] + ) + # Independent reference: selector 0xca74ab82 + raw ABI-encoded head. + expected = "0xca74ab82" + abi_encode( + [ + "bytes32", + "(bytes32,uint8,uint16,uint16,uint64,bytes32,bytes32,bytes32,bytes32)", + "string", + "string", + "bytes[]", + ], + [dispute_id, tuple_arg, evidence_cid, reasoning_cid, sigs], + ).hex() + assert cd == expected + assert cd[:10] == "0xca74ab82" + + def test_escalate_to_uma_calldata_matches_frozen(self): + g = GOLDEN["bondEscalationCalldata"] + client = self._client() + cd = client.encode_calldata( + "escalateToUMA", + [ + bytes.fromhex(g["disputeId"][2:]), + g["escalateToUMA"]["args"]["evidenceCID"], + g["escalateToUMA"]["args"]["reasoningCID"], + ], + ) + assert cd == g["escalateToUMA"]["calldata"] + assert cd[:10] == g["escalateToUMA"]["selector"] == "0xea487f8a" + + +# =========================================================================== +# GOLDEN VECTOR 4 — DisputeSplitRecorded decode + ZERO-REMAINING rule +# =========================================================================== + + +class TestGoldenDisputeSplitRecordedDecode: + def test_topic0_matches_frozen(self): + from eth_utils import keccak + + topic0 = "0x" + keccak(text="DisputeSplitRecorded(bytes32,address,address,uint16)").hex() + assert topic0 == GOLDEN["disputeSplitRecordedDecode"]["disputeSplitRecordedTopic0"] + + def test_decode_event_surfaces_fields(self): + e = GOLDEN["disputeSplitRecordedDecode"]["event"] + # A processed-log dict shaped like web3's AttributeDict (carries `args`). + log = { + "event": "DisputeSplitRecorded", + "args": { + "txId": bytes.fromhex(e["txId"][2:]), + "requester": e["requester"], + "provider": e["provider"], + "splitBps": e["splitBps"], + }, + } + decoded: DisputeSplitRecorded = decode_dispute_split_recorded(log) + assert decoded.tx_id == e["txId"] + assert decoded.requester == e["requester"] + assert decoded.provider == e["provider"] + assert decoded.split_bps == e["splitBps"] + + @pytest.mark.parametrize( + "proof_row", + GOLDEN["disputeSplitRecordedDecode"]["resolutionProofs"], + ids=[p["name"] for p in GOLDEN["disputeSplitRecordedDecode"]["resolutionProofs"]], + ) + def test_resolution_proof_consumer_rule(self, proof_row): + decoded = decode_resolution_proof(proof_row["proof"], int(proof_row["remaining"])) + exp = proof_row["expected"] + assert decoded.is_split == exp["isSplit"] + assert decoded.phantom_sentinel == exp["phantomSentinel"] + assert decoded.requester_amount == int(exp["requesterAmount"]) + assert decoded.provider_amount == int(exp["providerAmount"]) + assert decoded.provider_at_fault == exp["providerAtFault"] + # ZERO-REMAINING hard assertion: a phantom sentinel NEVER surfaces as a payout. + if exp["phantomSentinel"]: + assert decoded.requester_amount != 1 + assert decoded.provider_amount != 1 + + +# =========================================================================== +# GOLDEN VECTOR 5 — split-rate computation (OQ-11) +# =========================================================================== + + +class TestGoldenSplitRate: + @pytest.mark.parametrize( + "case", + GOLDEN["splitRate"]["cases"], + ids=[c["name"] for c in GOLDEN["splitRate"]["cases"]], + ) + def test_compute_split_rate_matches_frozen(self, case): + rate = compute_split_rate( + case["splitRecorded"], case["kernelDisputedToCancelled"], case["totalDisputes"] + ) + assert rate == pytest.approx(case["expectedSplitRate"], abs=1e-15) + if "approxPercent" in case: + assert round(rate * 100) == case["approxPercent"] + + def test_indexer_reuses_the_same_primitive(self): + headline = next( + c for c in GOLDEN["splitRate"]["cases"] if c["name"] == "headline_admin_cancelled_14pct" + ) + provider = "0x2222222222222222222222222222222222222222" + indexer = DisputeSplitIndexer() + from agirails.reputation.dispute_split_indexer import DisputeOutcome + + # 1 admin-CANCELLED split + 6 settled = 1/7. + indexer.add_outcome( + DisputeOutcome(provider=provider, requester="0x1", kind="kernelDisputedToCancelled") + ) + for _ in range(6): + indexer.add_outcome( + DisputeOutcome(provider=provider, requester="0x1", kind="settled") + ) + r = indexer.get_split_rate(provider) + assert r.split_count == 1 + assert r.total_disputes == 7 + assert r.split_rate == pytest.approx(headline["expectedSplitRate"], abs=1e-15) + b = indexer.get_split_rate_breakdown(provider) + assert b.admin_split_count == 1 + assert b.mediator_split_count == 0 diff --git a/tests/test_cross_sdk/test_dispute_vendor_parity.py b/tests/test_cross_sdk/test_dispute_vendor_parity.py new file mode 100644 index 0000000..6d04b2a --- /dev/null +++ b/tests/test_cross_sdk/test_dispute_vendor_parity.py @@ -0,0 +1,178 @@ +"""P2-2 — Dispute-contract ABI + network-config vendoring parity (Python side). + +Mirror of the TS suite (sdk-js/tests/dispute-vendor-parity.test.ts). Asserts: + + 1. The 3 vendored dispute ABIs (bond_escalation, composite_mediator, + i_optimistic_oracle_v3) load from the package ``abis/`` dir and expose + their key on-chain surface. + 2. The network config carries the 3 dispute-contract keys + (bondEscalation, compositeMediator, umaOptimisticOracleV3) and they + resolve to None until deployed (testnet Phase 6, mainnet later) — with + the SAME camelCase keys the TS SDK uses (parity). + 3. The cross-SDK GOLDEN EIP-712 vector reproduces the FROZEN digest — the + same constant the Solidity EncodingCanonical.t.sol and the TS SDK + reproduce. The fixture file is byte-identical to the TS copy. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from agirails.config.networks import get_network, NETWORKS +from agirails.types.dispute import ( + AIRuling, + DisputeEIP712Domain, + compute_ruling_digest, +) + +# Package abis dir — the SAME path the runtime loads from +# (e.g. kernel.py: Path(__file__).parent.parent / "abis"). +_ABIS = Path(__file__).resolve().parents[2] / "src" / "agirails" / "abis" + +# Shared cross-SDK golden fixture. Byte-identical to the copy committed under +# sdk-js/tests/fixtures/cross_sdk/dispute_golden_vector.json. +_FIXTURE = ( + Path(__file__).resolve().parents[1] + / "fixtures" + / "cross_sdk" + / "dispute_golden_vector.json" +) +GOLDEN = json.loads(_FIXTURE.read_text()) + +DISPUTE_KEYS = ["bondEscalation", "compositeMediator", "umaOptimisticOracleV3"] + + +def _load_abi(filename: str) -> list: + return json.loads((_ABIS / filename).read_text()) + + +def _fn_names(abi: list) -> set: + return {e.get("name") for e in abi if e.get("type") == "function"} + + +# --------------------------------------------------------------------------- +# 1. ABIs load + expose surface +# --------------------------------------------------------------------------- + + +class TestDisputeAbisVendored: + def test_bond_escalation_abi_loads_with_verifier_surface(self): + abi = _load_abi("bond_escalation.json") + names = _fn_names(abi) + assert {"DOMAIN_SEPARATOR", "submitAIRuling", "openDispute", "finalize"} <= names + + def test_composite_mediator_abi_loads_with_resolve(self): + abi = _load_abi("composite_mediator.json") + names = _fn_names(abi) + assert {"resolve", "kernel", "bondEscalation"} <= names + + def test_optimistic_oracle_v3_abi_loads_with_uma_surface(self): + abi = _load_abi("i_optimistic_oracle_v3.json") + names = _fn_names(abi) + assert {"assertTruth", "settleAndGetAssertionResult", "getMinimumBond"} <= names + + def test_abis_byte_identical_to_ts_copies(self): + """The 3 Python ABIs must equal the TS-vendored ABIs exactly (parity).""" + ts_abi = Path(__file__).resolve().parents[3] / "sdk-js" / "src" / "abi" + if not ts_abi.exists(): + pytest.skip("sdk-js sibling not checked out (CI runs each SDK alone)") + pairs = [ + ("bond_escalation.json", "BondEscalation.json"), + ("composite_mediator.json", "CompositeMediator.json"), + ("i_optimistic_oracle_v3.json", "IOptimisticOracleV3.json"), + ] + for py_name, ts_name in pairs: + py = json.loads((_ABIS / py_name).read_text()) + ts = json.loads((ts_abi / ts_name).read_text()) + assert py == ts, f"{py_name} != {ts_name} (ABI drift between SDKs)" + + +# --------------------------------------------------------------------------- +# 2. Network-config dispute keys +# --------------------------------------------------------------------------- + + +class TestNetworkConfigDisputeKeys: + def test_fixture_lists_canonical_dispute_keys(self): + assert GOLDEN["contracts"]["keys"] == DISPUTE_KEYS + + # AIP-14b dispute layer deployment state per network (mirrors the TS SDK + # config). base-sepolia went live 2026-07-02 (P4-1): the Tier-1 bond engine + # + CompositeMediator are deployed; UMA OptimisticOracleV3 is absent on + # Sepolia (Tier-2 uses a MockOOV3, G2) so that key stays undeployed. + # base-mainnet's dispute layer is not yet live — all three remain None. + _DEPLOYED_DISPUTE_KEYS = { + "base-sepolia": {"bondEscalation", "compositeMediator"}, + "base-mainnet": set(), + } + # camelCase wire key -> snake_case dataclass attribute. + _KEY_TO_ATTR = { + "bondEscalation": "bond_escalation", + "compositeMediator": "composite_mediator", + "umaOptimisticOracleV3": "uma_optimistic_oracle_v3", + } + + @pytest.mark.parametrize("network", ["base-sepolia", "base-mainnet"]) + def test_dispute_keys_present_and_deployment_state(self, network): + cfg = get_network(network) + wire = cfg.to_dict()["contracts"] + deployed = self._DEPLOYED_DISPUTE_KEYS[network] + for key in DISPUTE_KEYS: + # The key must be present in the wire config for BOTH networks + # (parity anchor: the shape is identical across networks). + assert key in wire, f"{key} missing from {network} wire config" + attr = self._KEY_TO_ATTR[key] + if key in deployed: + # Deployed: both the snake_case attribute and the camelCase + # wire key resolve to a concrete address. + assert getattr(cfg.contracts, attr) is not None + assert wire[key] is not None + else: + # Undeployed on this network — None on both surfaces. + assert getattr(cfg.contracts, attr) is None + assert wire[key] is None + + def test_both_networks_present(self): + assert sorted(NETWORKS.keys()) == ["base-mainnet", "base-sepolia"] + + +# --------------------------------------------------------------------------- +# 3. GOLDEN EIP-712 vector (TS ↔ Py ↔ Solidity anchor) +# --------------------------------------------------------------------------- + + +class TestGoldenVector: + def _ruling(self) -> AIRuling: + r = GOLDEN["ruling"] + return AIRuling( + dispute_id=r["disputeId"], + ruling=r["ruling"], + confidence=r["confidence"], + split_bps=r["splitBps"], + timestamp=r["timestamp"], + reasoning_hash=r["reasoningHash"], + bundle_hash=r["bundleHash"], + evidence_ref_hash=r["evidenceRefHash"], + reasoning_ref_hash=r["reasoningRefHash"], + ) + + def test_domain_separator_matches_frozen(self): + domain = DisputeEIP712Domain( + chain_id=GOLDEN["domain"]["chainId"], + verifying_contract=GOLDEN["domain"]["verifyingContract"], + ) + assert "0x" + domain.separator().hex() == GOLDEN["expected"]["domainSeparator"] + + def test_struct_hash_matches_frozen(self): + assert "0x" + self._ruling().struct_hash().hex() == GOLDEN["expected"]["structHash"] + + def test_digest_matches_frozen(self): + digest = compute_ruling_digest( + self._ruling(), + chain_id=GOLDEN["domain"]["chainId"], + verifying_contract=GOLDEN["domain"]["verifyingContract"], + ) + assert "0x" + digest.hex() == GOLDEN["expected"]["digest"] diff --git a/tests/test_cross_sdk/test_evidence_bundle.py b/tests/test_cross_sdk/test_evidence_bundle.py new file mode 100644 index 0000000..a89ac98 --- /dev/null +++ b/tests/test_cross_sdk/test_evidence_bundle.py @@ -0,0 +1,263 @@ +""" +Evidence Bundle canonical serializer — Py golden + cross-SDK suite (PRD P2-3). + +Loads the SHARED cross-SDK fixture ``DISPUTE SYSTEM/test-vectors/bundle-vectors.json`` +(the SAME file the TS jest suite loads) and asserts, for every vector: + - serialize_bundle → EXACT canonical bytes == fixture.canonicalBytesHex + - bundle_hash == fixture.bundleHash + - cl100k_base token_count == fixture.tokenCount +Plus a CROSS-LANG assertion: the TS-produced hashes (written by the jest suite +to ``bundle-hashes.ts.json``) equal the Py-produced hashes == the fixture. And +malformed-bundle rejection parity. + +Anchor: Example A bundle_hash + 0x379fb8140138f7d90cfbcb481898b6ec646e2c0378ff0d3a4a4572a6570ca257. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from agirails.dispute.evidence_bundle import ( + BundleTooLargeError, + InvalidBundleError, + MAX_BUNDLE_TOKENS, + UnsupportedBundleVersionError, + bundle_hash, + compute_bundle_hash, + count_bundle_tokens, + enforce_token_cap, + pin_evidence_bundle, + serialize_bundle, + serialize_bundle_to_string, + validate_bundle, +) + +# --------------------------------------------------------------------------- +# Shared cross-SDK fixture (byte-identical to the copy the jest suite loads): +# /DISPUTE SYSTEM/test-vectors/bundle-vectors.json +# From this file: parents → tests/test_cross_sdk → tests → python-sdk-v2 +# → SDK and Runtime → AGIRAILS (repo root). +# --------------------------------------------------------------------------- + +_VECTORS_DIR = ( + Path(__file__).resolve().parents[2] / "test-vectors" +) +_FIXTURE = _VECTORS_DIR / "bundle-vectors.json" +FIXTURE = json.loads(_FIXTURE.read_text(encoding="utf-8")) +VECTORS = FIXTURE["vectors"] + +_TS_HASHES = _VECTORS_DIR / "bundle-hashes.ts.json" +_PY_HASHES = _VECTORS_DIR / "bundle-hashes.py.json" + + +def _by_name(name: str) -> dict: + return next(v for v in VECTORS if v["name"] == name) + + +# --------------------------------------------------------------------------- +# 1. Per-vector canonical bytes + bundle_hash + token_count +# --------------------------------------------------------------------------- + + +class TestGoldenVectors: + def test_fixture_has_four_seed_vectors(self): + assert [v["name"] for v in VECTORS] == ["A", "B", "C", "D"] + + @pytest.mark.parametrize("v", VECTORS, ids=lambda v: v["name"]) + def test_exact_canonical_bytes(self, v): + raw = serialize_bundle(v["bundle"]) + assert raw.hex() == v["canonicalBytesHex"] + assert len(raw) == v["canonicalBytesUtf8Len"] + + @pytest.mark.parametrize("v", VECTORS, ids=lambda v: v["name"]) + def test_bundle_hash_matches_fixture(self, v): + assert bundle_hash(v["bundle"]) == v["bundleHash"] + # alias parity + assert compute_bundle_hash(v["bundle"], skip_token_check=True) == v["bundleHash"] + + @pytest.mark.parametrize("v", VECTORS, ids=lambda v: v["name"]) + def test_token_count_matches_fixture(self, v): + assert v["tokenizer"] == "cl100k_base" + assert count_bundle_tokens(serialize_bundle_to_string(v["bundle"])) == v[ + "tokenCount" + ] + + def test_example_a_is_frozen_schema_anchor(self): + a = _by_name("A") + assert ( + a["bundleHash"] + == "0x379fb8140138f7d90cfbcb481898b6ec646e2c0378ff0d3a4a4572a6570ca257" + ) + assert a["canonicalBytesUtf8Len"] == 719 + + def test_vector_c_raw_utf8_not_escaped(self): + c = _by_name("C") + text = serialize_bundle_to_string(c["bundle"]) + assert "résultat incorrect — 図 missing 🎉" in text + assert "\\u" not in text + + def test_vector_d_escape_parity(self): + # Locks the escape + sort rules for arbitrary free-text fields so the + # cross-SDK byte-identity assertion (Py == TS) can never silently + # diverge on control-char / quote / backslash / slash / emoji handling. + d = _by_name("D") + text = serialize_bundle_to_string(d["bundle"]) + # Two-char escapes for \b \f \n \r \t and quote/backslash. + for esc in ("\\b", "\\f", "\\n", "\\r", "\\t", '\\"', "\\\\"): + assert esc in text + # Other C0 control chars escape as \u00XX (lowercase hex). + assert "\\u0007" in text # BEL + assert "\\u001f" in text # unit separator + # Forward slash NOT escaped; surrogate-pair emoji stays raw UTF-8. + assert "slash=/" in text + assert "🚀" in text + assert "\\/" not in text + assert "\\ud83d" not in text # emoji not escaped to surrogate \u + + +# --------------------------------------------------------------------------- +# 2. Cross-language assertion (Py == TS == fixture) +# --------------------------------------------------------------------------- + + +class TestCrossLanguageIdentity: + def test_write_py_produced_hashes(self): + produced = [ + { + "name": v["name"], + "canonicalBytesHex": serialize_bundle(v["bundle"]).hex(), + "bundleHash": bundle_hash(v["bundle"]), + } + for v in VECTORS + ] + _PY_HASHES.write_text(json.dumps(produced, indent=2), encoding="utf-8") + # Self-consistency: Py production equals the fixture. + for p, v in zip(produced, VECTORS): + assert p["bundleHash"] == v["bundleHash"] + assert p["canonicalBytesHex"] == v["canonicalBytesHex"] + + def test_ts_produced_hashes_equal_py_and_fixture(self): + if not _TS_HASHES.exists(): + pytest.skip( + f"{_TS_HASHES} not present — run the jest suite to cross-check." + ) + ts = json.loads(_TS_HASHES.read_text(encoding="utf-8")) + for v in VECTORS: + ts_entry = next(t for t in ts if t["name"] == v["name"]) + # TS bytes == Py bytes == fixture bytes. + assert ts_entry["canonicalBytesHex"] == serialize_bundle(v["bundle"]).hex() + assert ts_entry["canonicalBytesHex"] == v["canonicalBytesHex"] + # TS hash == Py hash == fixture hash. + assert ts_entry["bundleHash"] == bundle_hash(v["bundle"]) + assert ts_entry["bundleHash"] == v["bundleHash"] + + +# --------------------------------------------------------------------------- +# 3. Token cap (schema §4 / OQ-9) +# --------------------------------------------------------------------------- + + +class TestTokenCap: + def _a(self) -> dict: + return json.loads(json.dumps(_by_name("A")["bundle"])) + + def test_within_cap_returns_count(self): + count = enforce_token_cap(serialize_bundle_to_string(self._a())) + assert count <= MAX_BUNDLE_TOKENS + assert count == _by_name("A")["tokenCount"] + + def test_over_cap_raises_before_hashing(self): + big = self._a() + big["delivery"]["deliverableInline"] = "lorem ipsum dolor sit amet " * 20000 + with pytest.raises(BundleTooLargeError) as exc: + bundle_hash(big) + assert exc.value.token_count > MAX_BUNDLE_TOKENS + + def test_skip_token_check_bypasses_cap(self): + a = _by_name("A") + assert bundle_hash(a["bundle"], skip_token_check=True) == a["bundleHash"] + + +# --------------------------------------------------------------------------- +# 4. Malformed-bundle rejection (schema §6) +# --------------------------------------------------------------------------- + + +class TestMalformedRejection: + def _a(self) -> dict: + return json.loads(json.dumps(_by_name("A")["bundle"])) + + def test_missing_required_key(self): + bad = self._a() + del bad["spec"] + with pytest.raises(InvalidBundleError): + validate_bundle(bad) + + def test_extra_top_level_key(self): + bad = self._a() + bad["extra"] = "nope" + with pytest.raises(InvalidBundleError): + validate_bundle(bad) + + def test_non_integer_uint_float(self): + bad = self._a() + bad["delivery"]["deliveredAt"] = 1700000000.5 + with pytest.raises(InvalidBundleError): + validate_bundle(bad) + + def test_malformed_bytes32hex(self): + bad = self._a() + bad["disputeId"] = "0xnothex" + with pytest.raises(InvalidBundleError): + validate_bundle(bad) + + def test_optional_key_present_as_null(self): + bad = self._a() + bad["delivery"]["deliverableInline"] = None + with pytest.raises(InvalidBundleError): + validate_bundle(bad) + + def test_timeline_too_short(self): + bad = self._a() + bad["timeline"] = [bad["timeline"][0]] + with pytest.raises(InvalidBundleError): + validate_bundle(bad) + + def test_unknown_major_version(self): + bad = self._a() + bad["schemaVersion"] = "2.0.0" + with pytest.raises(UnsupportedBundleVersionError): + validate_bundle(bad) + + +# --------------------------------------------------------------------------- +# 5. pin_evidence_bundle round-trip (schema §5 — OQ-10) +# --------------------------------------------------------------------------- + + +class _FakePinner: + def __init__(self) -> None: + self.pinned: bytes | None = None + + def upload_binary(self, data, content_type, options=None): + self.pinned = bytes(data) + return {"cid": "bafyfakecid", "size": len(data)} + + +class TestPinEvidenceBundle: + def test_pins_exact_canonical_bytes_and_round_trips(self): + from eth_utils import keccak + + v = _by_name("A") + pinner = _FakePinner() + res = pin_evidence_bundle(v["bundle"], pinner) + assert res.cid == "bafyfakecid" + assert res.bundle_hash == v["bundleHash"] + # The pinned bytes ARE the canonical bytes (no re-encoding). + assert pinner.pinned.hex() == v["canonicalBytesHex"] + # OQ-10: keccak256(fetched) == bundle_hash. + assert "0x" + keccak(pinner.pinned).hex() == v["bundleHash"] diff --git a/tests/test_delivery/test_delivery_recovery.py b/tests/test_delivery/test_delivery_recovery.py new file mode 100644 index 0000000..3406e24 --- /dev/null +++ b/tests/test_delivery/test_delivery_recovery.py @@ -0,0 +1,118 @@ +"""Delivery verification-before-dedup, callback isolation, replay and HTTP recovery.""" + +import asyncio +import copy +import time +from urllib.parse import parse_qs + +import httpx +import pytest + +from agirails.delivery import ( + CANONICAL_EMPTY_BYTES32, BuildSetupParams, DeliverySetupBuilder, + MockDeliveryChannel, MockDeliveryChannelOptions, RelayDeliveryChannel, RelayDeliveryChannelOptions, +) +from tests.test_delivery.test_relay_channel import _make_envelope_wire, PROVIDER, KERNEL, CHAIN, TXID +from tests.test_delivery.test_roundtrip_channel import BUYER + + +def wire_for(kind): + if kind=='envelope':return _make_envelope_wire() + return DeliverySetupBuilder(signer=BUYER).build(BuildSetupParams(tx_id=TXID,chain_id=CHAIN,kernel_address=KERNEL,requester_address=BUYER.address,signer_address=BUYER.address,buyer_ephemeral_pubkey=CANONICAL_EMPTY_BYTES32,expected_privacy='public'))['wire'] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('kind',['setup','envelope']) +@pytest.mark.parametrize('async_callback',[False,True]) +async def test_mock_verifies_before_dedup_and_isolates_subscribers_and_replay(kind,async_callback): + logs=[] + channel=MockDeliveryChannel(MockDeliveryChannelOptions(log=lambda *a:logs.append(a),now=lambda:int(time.time()))) + wire=wire_for(kind) + publish=getattr(channel,'publish_'+kind) + subscribe=getattr(channel,'subscribe_'+('setups' if kind=='setup' else 'envelopes')) + get=getattr(channel,'get_'+('setups' if kind=='setup' else 'envelopes')) + get_all=getattr(channel,'get_all_'+('setups' if kind=='setup' else 'envelopes')) + bad=copy.deepcopy(wire);bad['requesterSig' if kind=='setup' else 'providerSig']='0x'+'00'*65 + with pytest.raises(RuntimeError,match='verify failed'):await publish(bad) + received=[] + def broken(_):raise RuntimeError('broken subscriber') + async def async_broken(_): + await asyncio.sleep(0) + raise RuntimeError('broken async subscriber') + broken_sub=await subscribe(TXID,async_broken if async_callback else broken) + good_sub=await subscribe(TXID.upper(),lambda item:received.append(item)) + await publish(wire) + await publish(wire) + for _ in range(5):await asyncio.sleep(0) + assert len(received)==1 and received[0]==wire + assert channel.active_subscription_count()==2 + assert len(await get(TXID))==1 and len(get_all())==1 + snapshot=get_all(TXID);snapshot.clear() + assert len(get_all(TXID))==1 and get_all('unknown')==[] + with pytest.raises(RuntimeError,match='verify failed'):await publish(bad) + replay=[] + replay_sub=await subscribe(TXID,lambda item:replay.append(item)) + cancelled=await subscribe(TXID,lambda item:pytest.fail('closed subscriber replayed')) + cancelled.close();cancelled.close() + for _ in range(3):await asyncio.sleep(0) + assert replay==[wire] + assert any('subscriber threw' in args[1] for args in logs) + for sub in [good_sub,broken_sub,replay_sub]:sub.close() + assert channel.active_subscription_count()==0 + await channel.close();await channel.close() + with pytest.raises(RuntimeError,match='closed'):await publish(wire) + with pytest.raises(RuntimeError,match='closed'):await subscribe(TXID,lambda _:None) + channel.clear() + assert get_all()==[] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('kind',['setup','envelope']) +async def test_relay_poll_recovers_http_failure_verifies_then_deduplicates_and_closes(kind): + wire=wire_for(kind);bad=copy.deepcopy(wire) + bad['requesterSig' if kind=='setup' else 'providerSig']='0x'+'00'*65 + requests=[];logs=[];received=[];ready=asyncio.Event();polling=[False];fail_next=[False] + def handler(request): + requests.append(request) + if request.method=='POST':return httpx.Response(200,json={'ok':True}) + if fail_next[0]: + fail_next[0]=False + return httpx.Response(503,text='try later') + if not polling[0]:return httpx.Response(200,json={'items':[{'cursor':'valid','wire':wire}]}) + return httpx.Response(200,json={'items':[{'cursor':'bad','wire':bad},{'cursor':'valid/1','wire':wire},{'cursor':'valid/2','wire':wire}]}) + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + channel=RelayDeliveryChannel(RelayDeliveryChannelOptions(base_url='https://relay.invalid',http_client=client,allow_private_hosts=True,poll_interval_ms=1,log=lambda *a:logs.append(a),expected_chain_id=CHAIN,expected_kernel_address=KERNEL,now=lambda:int(time.time()))) + publish=getattr(channel,'publish_'+kind) + subscribe=getattr(channel,'subscribe_'+('setups' if kind=='setup' else 'envelopes')) + get=getattr(channel,'get_'+('setups' if kind=='setup' else 'envelopes')) + assert await get() == [] + await publish(wire) + assert await get(TXID,after='a/b') == [wire] + assert parse_qs(requests[-1].url.query.decode()) == {'after':['a/b']} + requests.clear();polling[0]=True;fail_next[0]=True + async def receive(item): + received.append(item) + ready.set() + raise RuntimeError('subscriber failure after delivery') + subscription=await subscribe(TXID,receive) + try:await asyncio.wait_for(ready.wait(),1) + finally: + subscription.close();subscription.close();await channel.close() + assert received==[wire] + assert any('poll error' in args[1] for args in logs) + assert any('dropping unverified' in args[1] for args in logs) + assert any('subscriber threw' in args[1] for args in logs) + assert not client.is_closed + with pytest.raises(RuntimeError,match='closed'):await publish(wire) + with pytest.raises(RuntimeError,match='closed'):await subscribe(TXID,lambda _:None) + + +@pytest.mark.asyncio +async def test_relay_reports_transport_failure_and_closes_owned_client(monkeypatch): + original=httpx.AsyncClient + def fail(request):raise httpx.ConnectError('offline',request=request) + monkeypatch.setattr('agirails.delivery.relay_delivery_channel.httpx.AsyncClient',lambda **kw:original(transport=httpx.MockTransport(fail),**kw)) + channel=RelayDeliveryChannel(RelayDeliveryChannelOptions(base_url='https://relay.invalid',allow_private_hosts=True)) + with pytest.raises(RuntimeError,match='POST failed'):await channel.publish_setup(wire_for('setup')) + await channel.close() + assert channel._client.is_closed diff --git a/tests/test_dispute/__init__.py b/tests/test_dispute/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_dispute/test_bond_escalation.py b/tests/test_dispute/test_bond_escalation.py new file mode 100644 index 0000000..692aa39 --- /dev/null +++ b/tests/test_dispute/test_bond_escalation.py @@ -0,0 +1,424 @@ +# PARITY: sdk-js/tests/bond-escalation.test.ts +""" +P2-4 — BondEscalationClient unit tests (Py side). + +Mirrors ``sdk-js/tests/bond-escalation.test.ts`` 1:1 and consumes the SAME +shared cross-SDK fixture +``DISPUTE SYSTEM/test-vectors/bond-escalation-vectors.json``. + +Proves, with a mock contract (no live chain): + 1. Each IBondEscalation write method builds the CORRECT calldata + (selector + ABI-encoded args == what the contract's ``encode_abi`` produces + independently — the same assertion surface as the TS twin's + ``Interface.encodeFunctionData``). + 2. get_dispute_state decodes the disputes() tuple to the fixture-expected + DisputeState (the TS twin asserts the identical fixture). + 3. The two pure quote helpers match every fixture row. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, List + +import pytest +from web3 import Web3 + +from agirails.dispute.bond_escalation import BondEscalationClient +from agirails.types.dispute import ( + AIRuling, + Ruling, + compute_evidence_ref_hash, + compute_reasoning_ref_hash, +) + +# Shared cross-SDK fixture (the SAME file the TS jest suite loads). +_VECTORS_DIR = Path(__file__).resolve().parents[2] / "test-vectors" +_FIXTURE = json.loads((_VECTORS_DIR / "bond-escalation-vectors.json").read_text()) + +_ABI = json.loads( + ( + Path(__file__).resolve().parents[2] + / "src" + / "agirails" + / "abis" + / "bond_escalation.json" + ).read_text() +) + +# Reference contract for INDEPENDENT calldata encoding (the assertion oracle). +_REF_CONTRACT = Web3().eth.contract(abi=_ABI) + +TX_ID = "0xabcdef0000000000000000000000000000000000000000000000000000000001" +DISPUTE_ID = "0x1234567890123456789012345678901234567890123456789012345678901234" + + +def _ref_calldata(method: str, args: List[Any]) -> str: + """Independently encode calldata via the reference contract.""" + return _REF_CONTRACT.encode_abi(abi_element_identifier=method, args=args) + + +class _MockFunction: + """Awaitable mock that records the positional args it was called with.""" + + def __init__(self, recorder, name: str): + self._recorder = recorder + self._name = name + + def __call__(self, *args): + self._recorder.append((self._name, args)) + return self + + def __await__(self): + async def _coro(): + return b"\xaa" * 32 # mock tx hash + + return _coro().__await__() + + +class _MockFunctions: + def __init__(self, recorder, disputes_tuple): + self._recorder = recorder + self._disputes_tuple = disputes_tuple + + def __getattr__(self, name): + if name == "disputes": + return self._DisputesFn(self._disputes_tuple) + return _MockFunction(self._recorder, name) + + class _DisputesFn: + def __init__(self, tuple_): + self._tuple = tuple_ + + def __call__(self, *_args): + return self + + async def call(self): + return self._tuple + + +class _MockContract: + """Records calldata + args, returns a configurable disputes() tuple.""" + + def __init__(self, disputes_tuple=None): + self.calls: List = [] + self.functions = _MockFunctions(self.calls, disputes_tuple) + self.address = "0x000000000000000000000000000000000000dEaD" + + def encode_abi(self, *, abi_element_identifier: str, args): + return _ref_calldata(abi_element_identifier, args) + + +def _make_client(disputes_tuple=None): + contract = _MockContract(disputes_tuple) + client = BondEscalationClient( + contract, + address="0x000000000000000000000000000000000000dEaD", + ) + return client, contract + + +def _normalize_tuple(raw): + """Fixture stores big-ints as strings + tx ids as hex; coerce for decode.""" + out = list(raw) + # currentBond[3], accumulatedBonds[4], livenessEnd[5], disputedAt[6], + # originalPool[11], escrowAmount[12] are big-int strings in the fixture. + for idx in (3, 4, 5, 6, 11, 12): + out[idx] = int(out[idx]) + return out + + +# --------------------------------------------------------------------------- +# 1. Quote helpers (shared fixture) +# --------------------------------------------------------------------------- + + +def test_quote_initial_bond_matches_every_fixture_row(): + for row in _FIXTURE["quoteInitialBond"]: + got = BondEscalationClient.quote_initial_bond(int(row["escrowAmount"])) + assert str(got) == row["expected"], row.get("_note", "") + + +def test_quote_escalation_bond_matches_every_fixture_row(): + for row in _FIXTURE["quoteEscalationBond"]: + got = BondEscalationClient.quote_escalation_bond(int(row["currentBond"])) + assert str(got) == row["expected"], row.get("_note", "") + + +def test_quote_initial_bond_floor_and_rate(): + assert BondEscalationClient.quote_initial_bond(0) == 1_000_000 + assert BondEscalationClient.quote_initial_bond(100_000_000) == 2_000_000 + + +def test_quote_escalation_bond_double_then_cap(): + assert BondEscalationClient.quote_escalation_bond(1_000_000) == 2_000_000 + assert BondEscalationClient.quote_escalation_bond(300_000_000) == 500_000_000 + + +# --------------------------------------------------------------------------- +# 2. get_dispute_state decode (shared fixture) +# --------------------------------------------------------------------------- + + +async def test_get_dispute_state_decodes_fixture_open_split(): + fx = _FIXTURE["getDisputeState"] + client, _ = _make_client(_normalize_tuple(fx["tuple"])) + state = await client.get_dispute_state(fx["disputeId"]) + assert state.tx_id == fx["expected"]["txId"] + assert state.dispute_id == fx["expected"]["disputeId"] + assert int(state.tier) == fx["expected"]["tier"] + assert int(state.ruling) == fx["expected"]["ruling"] + assert state.split_bps == fx["expected"]["splitBps"] + assert state.resolved == fx["expected"]["resolved"] + + +async def test_get_dispute_state_decodes_resolved_non_split(): + fx = _FIXTURE["getDisputeStateResolved"] + client, _ = _make_client(_normalize_tuple(fx["tuple"])) + state = await client.get_dispute_state(fx["disputeId"]) + assert int(state.tier) == fx["expected"]["tier"] + assert int(state.ruling) == fx["expected"]["ruling"] + assert state.resolved is True + + +def test_decode_dispute_state_static_handles_bytes_tx_id(): + raw = [ + bytes.fromhex("ab" * 32), # transactionId as bytes + 1, # currentRuling + 0, # splitBps + 0, # currentBond + 0, # accumulatedBonds + 0, # livenessEnd + 0, # disputedAt + "0x" + "11" * 20, # lastProposer + 2, # tier + False, # resolved + False, # winnerPaid + 0, # originalPool + 0, # escrowAmount + ] + state = BondEscalationClient.decode_dispute_state(DISPUTE_ID, raw) + assert state.tx_id == "0x" + "ab" * 32 + assert int(state.tier) == 2 + assert int(state.ruling) == Ruling.REQUESTER_WINS + + +# --------------------------------------------------------------------------- +# 3. Calldata per IBondEscalation method +# --------------------------------------------------------------------------- + + +async def test_open_dispute_calldata(): + client, contract = _make_client() + result = await client.open_dispute(TX_ID) + name, args = contract.calls[0] + assert name == "openDispute" + assert contract.encode_abi( + abi_element_identifier="openDispute", args=list(args) + ) == _ref_calldata("openDispute", [bytes.fromhex(TX_ID[2:])]) + assert result["dispute_id"].startswith("0x") and len(result["dispute_id"]) == 66 + + +async def test_submit_ai_ruling_calldata(): + # AIP-14c D7: the FINAL 5-arg submitAIRuling(disputeId, ruling, evidenceCID, + # reasoningCID, signatures) — selector 0xca74ab82. The ruling tuple is the + # 9-field type; its evidence/reasoning refs are derived from the SAME CIDs + # the call carries (what the contract recomputes + equality-checks on-chain). + from agirails.types.dispute import ( + compute_evidence_ref_hash, + compute_reasoning_ref_hash, + ) + + client, contract = _make_client() + reasoning_hash = "0x" + "11" * 32 + bundle_hash = "0x" + "22" * 32 + evidence_cid = "bafybeigevidenceCID" + reasoning_cid = "bafybeigreasoningCID" + # P2: the SIGNED ruling already carries the D7 ref-hashes; the SDK VERIFIES + # them against the CIDs (raises on mismatch), it does NOT overwrite. + evidence_ref = compute_evidence_ref_hash(bundle_hash, evidence_cid) + reasoning_ref = compute_reasoning_ref_hash(reasoning_hash, reasoning_cid) + ruling = AIRuling( + dispute_id=DISPUTE_ID, + ruling=Ruling.SPLIT, + confidence=9500, + split_bps=6000, + timestamp=1700000000, + reasoning_hash=reasoning_hash, + bundle_hash=bundle_hash, + evidence_ref_hash=evidence_ref, + reasoning_ref_hash=reasoning_ref, + ) + sigs = ["0x" + "ab" * 65, "0x" + "cd" * 65] + await client.submit_ai_ruling(ruling, sigs, evidence_cid, reasoning_cid) + name, args = contract.calls[0] + assert name == "submitAIRuling" + # Selector pinned to the final D7 entrypoint. + assert contract.encode_abi( + abi_element_identifier="submitAIRuling", args=list(args) + )[:10] == "0xca74ab82" + tuple_arg = ( + bytes.fromhex(DISPUTE_ID[2:]), + 2, + 9500, + 6000, + 1700000000, + bytes.fromhex("11" * 32), + bytes.fromhex("22" * 32), + compute_evidence_ref_hash(bundle_hash, evidence_cid), + compute_reasoning_ref_hash(reasoning_hash, reasoning_cid), + ) + expected = _ref_calldata( + "submitAIRuling", + [ + bytes.fromhex(DISPUTE_ID[2:]), + tuple_arg, + evidence_cid, + reasoning_cid, + [bytes.fromhex("ab" * 65), bytes.fromhex("cd" * 65)], + ], + ) + assert contract.encode_abi(abi_element_identifier="submitAIRuling", args=list(args)) == expected + + +async def test_propose_directly_calldata(): + client, contract = _make_client() + await client.propose_directly(DISPUTE_ID, Ruling.SPLIT, 6500) + name, args = contract.calls[0] + assert name == "proposeDirectly" + assert contract.encode_abi( + abi_element_identifier="proposeDirectly", args=list(args) + ) == _ref_calldata("proposeDirectly", [bytes.fromhex(DISPUTE_ID[2:]), 2, 6500]) + + +async def test_challenge_calldata(): + client, contract = _make_client() + await client.challenge(DISPUTE_ID, Ruling.REQUESTER_WINS, 0) + name, args = contract.calls[0] + assert name == "challenge" + assert contract.encode_abi( + abi_element_identifier="challenge", args=list(args) + ) == _ref_calldata("challenge", [bytes.fromhex(DISPUTE_ID[2:]), 1, 0]) + + +async def test_finalize_calldata(): + client, contract = _make_client() + await client.finalize(DISPUTE_ID) + name, args = contract.calls[0] + assert name == "finalize" + assert contract.encode_abi( + abi_element_identifier="finalize", args=list(args) + ) == _ref_calldata("finalize", [bytes.fromhex(DISPUTE_ID[2:])]) + + +async def test_escalate_to_uma_calldata(): + # BLOCKER-2: the 2-CID escalateToUMA(disputeId, evidenceCID, reasoningCID), + # selector 0xea487f8a. The 1-CID form (0xa3c23734) is removed. + client, contract = _make_client() + evidence_cid = "bafybeigdyrztabcdefghijklmnopqrstuvwxyz1234567890" + reasoning_cid = "bafybeigreasoningdyrztabcdefghijklmnopqrstuvwxyz00" + await client.escalate_to_uma(DISPUTE_ID, evidence_cid, reasoning_cid) + name, args = contract.calls[0] + assert name == "escalateToUMA" + encoded = contract.encode_abi( + abi_element_identifier="escalateToUMA", args=list(args) + ) + assert encoded == _ref_calldata( + "escalateToUMA", + [bytes.fromhex(DISPUTE_ID[2:]), evidence_cid, reasoning_cid], + ) + assert encoded[:10] == "0xea487f8a" + + +async def test_submit_ai_ruling_rejects_mismatched_cid(): + # P2: submit_ai_ruling must RAISE when a CID does not match the signed ruling + # refs (fail-closed — sending would ship invalid signatures on-chain). + client, contract = _make_client() + reasoning_hash = "0x" + "11" * 32 + bundle_hash = "0x" + "22" * 32 + evidence_cid = "bafybeigevidenceCID" + reasoning_cid = "bafybeigreasoningCID" + ruling = AIRuling( + dispute_id=DISPUTE_ID, + ruling=Ruling.SPLIT, + confidence=9500, + split_bps=6000, + timestamp=1700000000, + reasoning_hash=reasoning_hash, + bundle_hash=bundle_hash, + evidence_ref_hash=compute_evidence_ref_hash(bundle_hash, evidence_cid), + reasoning_ref_hash=compute_reasoning_ref_hash(reasoning_hash, reasoning_cid), + ) + sigs = ["0x" + "ab" * 65] + with pytest.raises(ValueError, match="evidenceCID does not match the signed ruling"): + await client.submit_ai_ruling(ruling, sigs, "bafybeigTAMPEREDcid", reasoning_cid) + # Fail-closed: nothing was sent. + assert contract.calls == [] + + +async def test_settle_uma_assertion_calldata(): + client, contract = _make_client() + await client.settle_uma_assertion(DISPUTE_ID) + name, args = contract.calls[0] + assert name == "settleUMAAssertion" + assert contract.encode_abi( + abi_element_identifier="settleUMAAssertion", args=list(args) + ) == _ref_calldata("settleUMAAssertion", [bytes.fromhex(DISPUTE_ID[2:])]) + + +async def test_retry_mediator_resolution_calldata(): + client, contract = _make_client() + await client.retry_mediator_resolution(DISPUTE_ID) + name, args = contract.calls[0] + assert name == "retryMediatorResolution" + assert contract.encode_abi( + abi_element_identifier="retryMediatorResolution", args=list(args) + ) == _ref_calldata("retryMediatorResolution", [bytes.fromhex(DISPUTE_ID[2:])]) + + +async def test_claim_escalation_refund_calldata(): + client, contract = _make_client() + await client.claim_escalation_refund(DISPUTE_ID) + name, args = contract.calls[0] + assert name == "claimEscalationRefund" + assert contract.encode_abi( + abi_element_identifier="claimEscalationRefund", args=list(args) + ) == _ref_calldata("claimEscalationRefund", [bytes.fromhex(DISPUTE_ID[2:])]) + + +async def test_sync_external_resolution_calldata(): + client, contract = _make_client() + await client.sync_external_resolution(DISPUTE_ID) + name, args = contract.calls[0] + assert name == "syncExternalResolution" + assert contract.encode_abi( + abi_element_identifier="syncExternalResolution", args=list(args) + ) == _ref_calldata("syncExternalResolution", [bytes.fromhex(DISPUTE_ID[2:])]) + + +async def test_force_resolve_stale_calldata(): + client, contract = _make_client() + await client.force_resolve_stale(DISPUTE_ID) + name, args = contract.calls[0] + assert name == "forceResolveStale" + assert contract.encode_abi( + abi_element_identifier="forceResolveStale", args=list(args) + ) == _ref_calldata("forceResolveStale", [bytes.fromhex(DISPUTE_ID[2:])]) + + +# --------------------------------------------------------------------------- +# 4. Config guards +# --------------------------------------------------------------------------- + + +def test_rejects_confirmations_below_one(): + contract = _MockContract() + with pytest.raises(ValueError, match="confirmations must be >= 1"): + BondEscalationClient(contract, confirmations=0) + + +def test_accessors(): + client, _ = _make_client() + assert client.get_address() == "0x000000000000000000000000000000000000dEaD" + assert client.get_contract() is not None diff --git a/tests/test_dispute/test_composite_mediator.py b/tests/test_dispute/test_composite_mediator.py new file mode 100644 index 0000000..cf5ba1e --- /dev/null +++ b/tests/test_dispute/test_composite_mediator.py @@ -0,0 +1,299 @@ +# PARITY: sdk-js/tests/composite-mediator.test.ts +""" +P2-5 — CompositeMediator read/event client + decoders (Py side). + +Mirrors ``sdk-js/tests/composite-mediator.test.ts`` 1:1 and consumes the SAME +shared cross-SDK fixture +``DISPUTE SYSTEM/test-vectors/composite-mediator-vectors.json``. + +Proves: + 1. decode_dispute_split_recorded decodes a DisputeSplitRecorded log. + 2. decode_resolution_proof obeys the ZERO-REMAINING CONSUMER RULE — a drained + dispute (remaining==0) surfaces NO 1-wei payout (phantom sentinel). + 3. compute_split_rate counts DisputeSplitRecorded + kernel DISPUTED→CANCELLED + at identical weight (OQ-11) over the fixture rows. + 4. EventMonitor surfaces DisputeSplitRecorded, kernel DISPUTED→CANCELLED, + and UMADisputeEscalated. + 5. resolve() is NOT a public client method (it's onlyBondEscalation). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List + +import pytest +from eth_abi import encode +from eth_utils import keccak +from web3 import Web3 + +from agirails.dispute.composite_mediator import ( + CompositeMediator, + compute_split_rate, + decode_dispute_split_recorded, + decode_resolution_proof, +) +from agirails.protocol.events import EventMonitor +from agirails.types.transaction import TransactionState + +# Shared cross-SDK fixture (the SAME file the TS jest suite loads). +_VECTORS_DIR = Path(__file__).resolve().parents[2] / "test-vectors" +_FIXTURE = json.loads((_VECTORS_DIR / "composite-mediator-vectors.json").read_text()) + +_ABI_DIR = Path(__file__).resolve().parents[2] / "src" / "agirails" / "abis" +_MEDIATOR_ABI = json.loads((_ABI_DIR / "composite_mediator.json").read_text()) +_KERNEL_ABI = json.loads((_ABI_DIR / "actp_kernel.json").read_text()) +_BOND_ABI = json.loads((_ABI_DIR / "bond_escalation.json").read_text()) + +_MEDIATOR_CONTRACT = Web3().eth.contract(abi=_MEDIATOR_ABI) +_KERNEL_CONTRACT = Web3().eth.contract(abi=_KERNEL_ABI) +_BOND_CONTRACT = Web3().eth.contract(abi=_BOND_ABI) + + +def _bytes32(hexstr: str) -> bytes: + return bytes.fromhex(hexstr[2:] if hexstr.startswith("0x") else hexstr) + + +def _addr_topic(addr: str) -> bytes: + return bytes(12) + bytes.fromhex(addr[2:]) + + +def _make_split_log(ev: Dict[str, Any], block: int = 100, idx: int = 0) -> Dict[str, Any]: + """Build a raw DisputeSplitRecorded log + process it via the mediator ABI.""" + topic0 = keccak(text="DisputeSplitRecorded(bytes32,address,address,uint16)") + raw_log = { + "address": "0x0000000000000000000000000000000000000000", + "topics": [ + topic0, + _bytes32(ev["txId"]), + _addr_topic(ev["requester"]), + _addr_topic(ev["provider"]), + ], + "data": "0x" + encode(["uint16"], [ev["splitBps"]]).hex(), + "blockNumber": block, + "transactionHash": b"\xfe" * 32, + "logIndex": idx, + "transactionIndex": 0, + "blockHash": b"\x00" * 32, + } + return _MEDIATOR_CONTRACT.events.DisputeSplitRecorded().process_log(raw_log) + + +def _make_state_log( + old_state: int, new_state: int, tx_id: str, block: int, idx: int +) -> Dict[str, Any]: + topic0 = keccak(text="StateTransitioned(bytes32,uint8,uint8,address,uint256)") + raw_log = { + "address": "0x0000000000000000000000000000000000000000", + "topics": [ + topic0, + _bytes32(tx_id), + old_state.to_bytes(32, "big"), + new_state.to_bytes(32, "big"), + ], + "data": "0x" + + encode( + ["address", "uint256"], + ["0x3333333333333333333333333333333333333333", 1700000000], + ).hex(), + "blockNumber": block, + "transactionHash": b"\xaa" * 32, + "logIndex": idx, + "transactionIndex": 0, + "blockHash": b"\x00" * 32, + } + return _KERNEL_CONTRACT.events.StateTransitioned().process_log(raw_log) + + +def _make_uma_log( + dispute_id: str, assertion_id: str, block: int, idx: int +) -> Dict[str, Any]: + topic0 = keccak(text="UMADisputeEscalated(bytes32,bytes32)") + raw_log = { + "address": "0x0000000000000000000000000000000000000000", + "topics": [topic0, _bytes32(dispute_id), _bytes32(assertion_id)], + "data": "0x", + "blockNumber": block, + "transactionHash": b"\xbb" * 32, + "logIndex": idx, + "transactionIndex": 0, + "blockHash": b"\x00" * 32, + } + return _BOND_CONTRACT.events.UMADisputeEscalated().process_log(raw_log) + + +# --------------------------------------------------------------------------- +# 1. decode_dispute_split_recorded +# --------------------------------------------------------------------------- + + +def test_decode_dispute_split_recorded(): + ev = _FIXTURE["splitRecordedEvent"] + decoded = decode_dispute_split_recorded(_make_split_log(ev)) + assert decoded.tx_id.lower() == ev["txId"].lower() + assert decoded.requester.lower() == ev["requester"].lower() + assert decoded.provider.lower() == ev["provider"].lower() + assert decoded.split_bps == ev["splitBps"] + + +def test_decode_dispute_split_recorded_rejects_wrong_event(): + state_log = _make_state_log( + TransactionState.DISPUTED, TransactionState.CANCELLED, _FIXTURE["splitRecordedEvent"]["txId"], 1, 0 + ) + with pytest.raises(ValueError, match="not a DisputeSplitRecorded"): + decode_dispute_split_recorded(state_log) + + +# --------------------------------------------------------------------------- +# 2. decode_resolution_proof — ZERO-REMAINING CONSUMER RULE +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("row", _FIXTURE["resolutionProofs"], ids=lambda r: r["name"]) +def test_decode_resolution_proof_matches_fixture(row): + decoded = decode_resolution_proof(row["proof"], int(row["remaining"])) + exp = row["expected"] + assert decoded.is_split == exp["isSplit"] + assert decoded.phantom_sentinel == exp["phantomSentinel"] + assert str(decoded.requester_amount) == exp["requesterAmount"] + assert str(decoded.provider_amount) == exp["providerAmount"] + if exp["providerAtFault"] is None: + assert decoded.provider_at_fault is None + else: + assert decoded.provider_at_fault == exp["providerAtFault"] + + +def test_drained_dispute_no_1_wei_payout(): + # On-chain proof carries a 1-wei sentinel, but remaining==0 → both payouts 0. + sentinel_proof = "0x" + encode(["uint256", "uint256", "bool"], [0, 1, False]).hex() + decoded = decode_resolution_proof(sentinel_proof, 0) + assert decoded.phantom_sentinel is True + assert decoded.requester_amount == 0 + assert decoded.provider_amount == 0 + # Hard assertion of the rule: the surfaced amount is NEVER the 1-wei sentinel. + assert decoded.provider_amount != 1 + + +# --------------------------------------------------------------------------- +# 3. compute_split_rate — OQ-11 +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("row", _FIXTURE["splitRate"], ids=lambda r: r["name"]) +def test_compute_split_rate_matches_fixture(row): + got = compute_split_rate( + row["splitRecorded"], row["kernelDisputedToCancelled"], row["totalDisputes"] + ) + assert got == pytest.approx(row["expected"], abs=1e-10) + + +# --------------------------------------------------------------------------- +# 4. EventMonitor dispute surfacing +# --------------------------------------------------------------------------- + + +class _MockEvents: + """Mimics ``contract.events.`` returning a filter that replays logs.""" + + def __init__(self, logs_by_event: Dict[str, List[Any]]): + self._logs = logs_by_event + + def __getattr__(self, name: str): + logs = self._logs.get(name, []) + + class _EventObj: + @staticmethod + async def create_filter(*_a, **_k): + class _Filter: + async def get_all_entries(): # type: ignore[no-untyped-def] + return logs + + # get_all_entries needs to be an instance coroutine + f = _Filter() + + async def _get_all(): + return logs + + f.get_all_entries = _get_all # type: ignore[attr-defined] + return f + + return _EventObj() + + +class _MockContract: + def __init__(self, logs_by_event: Dict[str, List[Any]]): + self.events = _MockEvents(logs_by_event) + + +@pytest.mark.asyncio +async def test_get_dispute_events_surfaces_all_three(monkeypatch): + tx = _FIXTURE["splitRecordedEvent"]["txId"] + dispute_id = "0x" + "11" * 32 + assertion_id = "0x" + "22" * 32 + + kernel = _MockContract( + { + "StateTransitioned": [ + _make_state_log(TransactionState.DISPUTED, TransactionState.CANCELLED, tx, 10, 0), + _make_state_log(TransactionState.DELIVERED, TransactionState.SETTLED, tx, 11, 0), + ] + } + ) + mediator = _MockContract( + {"DisputeSplitRecorded": [_make_split_log(_FIXTURE["splitRecordedEvent"], 12, 0)]} + ) + bond = _MockContract( + {"UMADisputeEscalated": [_make_uma_log(dispute_id, assertion_id, 9, 0)]} + ) + + monitor = EventMonitor(kernel, object(), object(), mediator, bond) + events = await monitor.get_dispute_events() + + types = [e.event_type.value for e in events] + assert "DisputeSplitRecorded" in types + assert "UMADisputeEscalated" in types + # kernel DISPUTED→CANCELLED surfaces as a StateTransitioned event (exactly one). + cancelled = [ + e + for e in events + if e.event_type.value == "StateTransitioned" + and getattr(e, "previous_state", None) == TransactionState.DISPUTED + and getattr(e, "new_state", None) == TransactionState.CANCELLED + ] + assert len(cancelled) == 1 + # DELIVERED→SETTLED noise is NOT surfaced. + assert not any( + getattr(e, "new_state", None) == TransactionState.SETTLED for e in events + ) + # Block-ordered: UMA(9) < DisputedToCancelled(10) < Split(12). + assert [e.block_number for e in events] == [9, 10, 12] + + +@pytest.mark.asyncio +async def test_dispute_subscriptions_require_their_contracts(): + kernel = _MockContract({}) + monitor = EventMonitor(kernel, object(), object()) + + with pytest.raises(ValueError, match="without a CompositeMediator"): + await monitor.on_dispute_split_recorded(lambda _e: None) + with pytest.raises(ValueError, match="without a BondEscalation"): + await monitor.on_uma_dispute_escalated(lambda _e: None) + + +# --------------------------------------------------------------------------- +# 5. resolve() is NOT a public client method (onlyBondEscalation) +# --------------------------------------------------------------------------- + + +def test_resolve_is_not_a_public_client_method(): + # resolve() exists on the ABI but is guarded onlyBondEscalation; the SDK + # client deliberately omits it so callers cannot build a reverting tx. + abi_fns = {x["name"] for x in _MEDIATOR_ABI if x.get("type") == "function"} + assert "resolve" in abi_fns # exists on-chain + + client = CompositeMediator(object(), "0x000000000000000000000000000000000000dEaD") + assert not hasattr(client, "resolve") + # The observational surface it DOES expose: + assert hasattr(client, "get_split_recorded_events") + assert hasattr(client, "get_address") diff --git a/tests/test_dispute/test_composite_mediator_async_filters.py b/tests/test_dispute/test_composite_mediator_async_filters.py new file mode 100644 index 0000000..56d1529 --- /dev/null +++ b/tests/test_dispute/test_composite_mediator_async_filters.py @@ -0,0 +1,132 @@ +"""Exercise public mediator reads through real AsyncWeb3 event filters.""" + +import asyncio +from contextlib import suppress + +import pytest +from eth_abi import encode +from eth_utils.abi import event_abi_to_log_topic +from web3 import AsyncWeb3, Web3 +from web3.providers import AsyncBaseProvider + +from agirails.dispute.composite_mediator import CompositeMediator + +ADDRESS = Web3.to_checksum_address("0x" + "11" * 20) +REQUESTER = Web3.to_checksum_address("0x" + "22" * 20) +PROVIDER = Web3.to_checksum_address("0x" + "33" * 20) +TX_ID = "0x" + "44" * 32 +TX_HASH = "0x" + "55" * 32 + + +class SplitLogs(AsyncBaseProvider): + def __init__(self, failures=0): + super().__init__() + self.failures = failures + self.queries = [] + self.block_reads = 0 + self.filters = {} + event = next( + x for x in CompositeMediator._load_abi() if x.get("name") == "DisputeSplitRecorded" + ) + self.log = { + "address": ADDRESS, + "topics": [Web3.to_hex(event_abi_to_log_topic(event)), TX_ID] + + [Web3.to_hex(encode(["address"], [a])) for a in [REQUESTER, PROVIDER]], + "data": Web3.to_hex(encode(["uint16"], [3700])), + "blockNumber": "0xa", + "transactionHash": TX_HASH, + "transactionIndex": "0x0", + "blockHash": "0x" + "66" * 32, + "logIndex": "0x2", + "removed": False, + } + + async def make_request(self, method, params): + if method == "eth_chainId": + result = "0x7a69" + elif method == "eth_blockNumber": + self.block_reads += 1 + result = "0x9" if self.block_reads == 1 else "0xa" + elif method == "eth_newFilter": + query = params[0] + self.queries.append(query) + result = hex(len(self.queries)) + self.filters[result] = query + elif method == "eth_getFilterLogs": + if self.failures: + self.failures -= 1 + raise ConnectionError("local filter read unavailable") + query = self.filters[params[0]] + matching = all( + topic is None or topic.lower() == self.log["topics"][i].lower() + for i, topic in enumerate(query["topics"]) + ) + result = [self.log] if matching else [] + else: + raise AssertionError("Unexpected RPC operation: " + method) + return {"jsonrpc": "2.0", "id": 1, "result": result} + + +def client(failures=0): + provider = SplitLogs(failures) + w3 = AsyncWeb3(provider) + contract = w3.eth.contract(address=ADDRESS, abi=CompositeMediator._load_abi()) + return CompositeMediator(contract, ADDRESS), provider + + +@pytest.mark.parametrize("bounds", [(0, 10), ("earliest", "latest")]) +@pytest.mark.asyncio +async def test_history_decodes_real_log_with_all_indexed_filters(bounds): + mediator, provider = client() + events = await mediator.get_split_recorded_events( + tx_id=TX_ID, + requester=REQUESTER, + provider=PROVIDER, + from_block=bounds[0], + to_block=bounds[1], + ) + assert len(events) == 1 + event = events[0] + assert (event.tx_id, event.requester, event.provider) == (TX_ID, REQUESTER, PROVIDER) + assert (event.split_bps, event.block_number, event.log_index) == (3700, 10, 2) + assert event.transaction_hash == TX_HASH + query = provider.queries[0] + assert list(query["topics"]) == provider.log["topics"] + expected = [hex(x) if isinstance(x, int) else x for x in bounds] + assert [query["fromBlock"], query["toBlock"]] == expected + + +@pytest.mark.asyncio +async def test_history_preserves_empty_result_for_nonmatching_transaction(): + mediator, _ = client() + assert await mediator.get_split_recorded_events(tx_id="0x" + "77" * 32) == [] + + +@pytest.mark.asyncio +async def test_history_propagates_real_provider_read_failure(): + mediator, _ = client(failures=1) + with pytest.raises(ConnectionError, match="local filter read unavailable"): + await mediator.get_split_recorded_events(from_block=0, to_block=10) + + +@pytest.mark.parametrize("failures", [0, 1]) +@pytest.mark.asyncio +async def test_watcher_delivers_decoded_event_and_retries_same_range_after_read_error(failures): + mediator, provider = client(failures) + delivered = asyncio.get_running_loop().create_future() + task = mediator.on_dispute_split_recorded(delivered.set_result, poll_interval=0.005) + try: + event = await asyncio.wait_for(delivered, timeout=1) + assert (event.tx_id, event.split_bps, event.block_number) == (TX_ID, 3700, 10) + assert (event.requester, event.provider, event.transaction_hash) == ( + REQUESTER, + PROVIDER, + TX_HASH, + ) + assert len(provider.queries) == failures + 1 + assert all(q["fromBlock"] == q["toBlock"] == "0xa" for q in provider.queries) + finally: + task.cancel() + with suppress(asyncio.CancelledError): + await task + assert task.done() diff --git a/tests/test_dispute/test_dispute_client.py b/tests/test_dispute/test_dispute_client.py new file mode 100644 index 0000000..a1ff1ce --- /dev/null +++ b/tests/test_dispute/test_dispute_client.py @@ -0,0 +1,171 @@ +# PARITY: sdk-js/tests/dispute-client.test.ts +""" +P2-9 — DisputeClient facade unit tests (Py side). + +Mirrors ``sdk-js/tests/dispute-client.test.ts`` 1:1 and consumes the SAME shared +cross-SDK fixture +``DISPUTE SYSTEM/test-vectors/dispute-client-status-vectors.json``. + +Proves, with a mock contract / mock sub-clients (no live chain): + 1. The §9 sub-state decode (``decode_dispute_sub_state`` + ``get_dispute_status``) + matches every fixture row — the single cross-SDK decode. + 2. The facade composes the five primitives and exposes them via properties; + unconfigured properties raise; the split indexer is always present. + 3. ``get_dispute_status`` raises a clear error when the bond client is absent. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, List + +import pytest + +from agirails.dispute.bond_escalation import BondEscalationClient +from agirails.dispute.dispute_client import ( + DisputeClient, + decode_dispute_sub_state, +) +from agirails.reputation.dispute_split_indexer import ( + DisputeOutcome, + DisputeSplitIndexer, +) + +# Shared cross-SDK fixture (the SAME file the TS jest suite loads). +_VECTORS_DIR = Path(__file__).resolve().parents[2] / "test-vectors" +_FIXTURE = json.loads( + (_VECTORS_DIR / "dispute-client-status-vectors.json").read_text() +) + + +# --------------------------------------------------------------------------- +# Mock BondEscalation contract whose disputes().call() returns a fixed tuple. +# --------------------------------------------------------------------------- + + +class _DisputesFn: + def __init__(self, tuple_): + self._tuple = tuple_ + + def __call__(self, *_args): + return self + + async def call(self): + return self._tuple + + +class _MockFunctions: + def __init__(self, disputes_tuple): + self._disputes_tuple = disputes_tuple + + def __getattr__(self, name): + if name == "disputes": + return _DisputesFn(self._disputes_tuple) + raise AttributeError(name) + + +class _MockContract: + def __init__(self, disputes_tuple): + self.functions = _MockFunctions(disputes_tuple) + self.address = "0x000000000000000000000000000000000000dEaD" + + +def _normalize_tuple(raw) -> List[Any]: + """Fixture stores big-ints as strings; coerce the numeric fields for decode. + Indices: currentBond[3], accumulatedBonds[4], livenessEnd[5], disputedAt[6], + originalPool[11], escrowAmount[12].""" + out = list(raw) + for idx in (3, 4, 5, 6, 11, 12): + out[idx] = int(out[idx]) + return out + + +def _make_bond_client_with_tuple(tuple_) -> BondEscalationClient: + contract = _MockContract(_normalize_tuple(tuple_)) + return BondEscalationClient( + contract, + address="0x000000000000000000000000000000000000dEaD", + ) + + +# --------------------------------------------------------------------------- +# 1. §9 sub-state decode (cross-SDK golden fixture) +# --------------------------------------------------------------------------- + + +def test_decode_dispute_sub_state_matches_every_fixture_row(): + for vec in _FIXTURE["vectors"]: + got = decode_dispute_sub_state(_normalize_tuple(vec["tuple"])) + assert got == vec["expected"]["substate"], vec["name"] + + +@pytest.mark.asyncio +async def test_get_dispute_status_matches_every_fixture_row(): + for vec in _FIXTURE["vectors"]: + client = DisputeClient( + bond=_make_bond_client_with_tuple(vec["tuple"]) + ) + status = await client.get_dispute_status(vec["disputeId"]) + exp = vec["expected"] + assert status.substate == exp["substate"], vec["name"] + assert status.tier == exp["tier"], vec["name"] + assert status.resolved == exp["resolved"], vec["name"] + assert status.ruling == exp["ruling"], vec["name"] + assert status.split_bps == exp["splitBps"], vec["name"] + assert status.dispute_id == vec["disputeId"], vec["name"] + + +# --------------------------------------------------------------------------- +# 2. Composition + properties +# --------------------------------------------------------------------------- + + +def test_split_indexer_always_present_with_no_config(): + client = DisputeClient() + assert isinstance(client.split_indexer, DisputeSplitIndexer) + assert client.has_bond() is False + assert client.has_mediator() is False + assert client.has_uma() is False + assert client.has_evaluator() is False + + +def test_unconfigured_properties_raise_clear_error(): + client = DisputeClient() + with pytest.raises(RuntimeError, match="not configured"): + _ = client.bond + with pytest.raises(RuntimeError, match="not configured"): + _ = client.mediator + with pytest.raises(RuntimeError, match="not configured"): + _ = client.uma + with pytest.raises(RuntimeError, match="not configured"): + _ = client.evaluator + + +def test_configured_bond_is_exposed_via_property(): + bond = _make_bond_client_with_tuple(_FIXTURE["vectors"][0]["tuple"]) + client = DisputeClient(bond=bond) + assert client.bond is bond + assert client.has_bond() is True + + +@pytest.mark.asyncio +async def test_get_dispute_status_raises_when_bond_absent(): + client = DisputeClient() + with pytest.raises(RuntimeError, match="not configured"): + await client.get_dispute_status("0x" + "11" * 32) + + +def test_record_outcomes_feeds_split_indexer(): + client = DisputeClient() + client.record_outcomes( + [ + DisputeOutcome( + provider="0xabc", + requester="0xdef", + kind="disputeSplitRecorded", + remaining=0, + ) + ] + ) + assert client.split_indexer.size() == 1 diff --git a/tests/test_dispute/test_evaluator_client.py b/tests/test_dispute/test_evaluator_client.py new file mode 100644 index 0000000..3bfb89b --- /dev/null +++ b/tests/test_dispute/test_evaluator_client.py @@ -0,0 +1,387 @@ +# PARITY: sdk-js/tests/evaluator-client.test.ts +""" +P2-6 — EvaluatorClient unit tests (Py side). + +Mirrors ``sdk-js/tests/evaluator-client.test.ts`` 1:1 and consumes the SAME +shared cross-SDK fixture +``DISPUTE SYSTEM/test-vectors/evaluator-client-vectors.json``. + +Proves, with mocked HTTP (no live evaluator, no live chain): + 1. §4.7 signature verification replicated client-side — 2-valid+1-unknown + passes, two fixed pass, duplicate counted once, duplicate-under-threshold + fails, stale fails, one-valid+unknown fails. (PARITY: the TS twin asserts + the IDENTICAL fixture rows and recovers the SAME signers.) + 2. select_third_evaluator matches §4.7 step 4 (keccak(abi.encode(disputeId)) % len). + 3. request_evaluation runs the full STEP 0→5 handshake: POST /quote (declare, + no money) → 402 → pay via the injected x402 buyer stub → POST /evaluate → + parse signed response → §4.7 verify → return signed result. + 4. A proposeDirectly evaluate response surfaces a no-sig recommendation. + 5. A signed response that FAILS §4.7 downgrades to a proposeDirectly + recommendation with NO signatures (never fabricates a signature). + 6. The client NEVER submits on-chain (no contract is constructed). +""" + +from __future__ import annotations + +import json +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional + +import pytest + +from agirails.dispute.evaluator_client import ( + EvaluatorClient, + EvaluatorClientConfig, + RequestEvaluationParams, + BundleSource, + QuoteRejectedError, + verify_ruling_signatures, + select_third_evaluator, +) +from agirails.dispute.evidence_bundle import compute_bundle_hash +from agirails.types.dispute import AIRuling, recover_ruling_signer, sign_ruling + +# Shared cross-SDK fixtures (the SAME files the TS jest suite loads). +_VECTORS_DIR = Path(__file__).resolve().parents[2] / "test-vectors" +FIXTURE = json.loads((_VECTORS_DIR / "evaluator-client-vectors.json").read_text()) +BUNDLE_VECTORS = json.loads((_VECTORS_DIR / "bundle-vectors.json").read_text()) + +DOMAIN = FIXTURE["domain"] +RULING_FX = FIXTURE["ruling"] +REGISTRY = FIXTURE["registry"] +SIGS = FIXTURE["signatures"] + + +def _fixture_ruling() -> AIRuling: + r = RULING_FX + zero = "0x" + "00" * 32 + return AIRuling( + dispute_id=r["disputeId"], + ruling=r["ruling"], + confidence=r["confidence"], + split_bps=r["splitBps"], + timestamp=r["timestamp"], + reasoning_hash=r["reasoningHash"], + bundle_hash=r["bundleHash"], + evidence_ref_hash=r.get("evidenceRefHash", zero), + reasoning_ref_hash=r.get("reasoningRefHash", zero), + ) + + +# ===================================================================== +# 1. §4.7 signature verification (pure — consumes the static golden fixture) +# ===================================================================== + + +class TestVerification: + def test_recovers_exact_fixture_signers(self): + """PARITY anchor: recovers the SAME signers the TS twin recovers.""" + ruling = _fixture_ruling() + rec = lambda key: recover_ruling_signer( # noqa: E731 + ruling, SIGS[key], DOMAIN["chainId"], DOMAIN["verifyingContract"] + ) + assert rec("fixedA").lower() == REGISTRY["fixedEvaluators"][0].lower() + assert rec("fixedB").lower() == REGISTRY["fixedEvaluators"][1].lower() + assert rec("rotating").lower() == REGISTRY["selectedRotatingEvaluator"].lower() + assert rec("unknown").lower() == REGISTRY["unknownSigner"].lower() + + def test_select_third_evaluator(self): + third = select_third_evaluator(RULING_FX["disputeId"], REGISTRY["rotatingPool"]) + assert third is not None + assert third.lower() == REGISTRY["selectedRotatingEvaluator"].lower() + assert select_third_evaluator(RULING_FX["disputeId"], []) is None + + @pytest.mark.parametrize( + "name,case", + [ + (k, v) + for k, v in FIXTURE["verificationCases"].items() + if not k.startswith("_") + ], + ids=lambda x: x if isinstance(x, str) else "", + ) + def test_verification_cases(self, name, case): + ruling = _fixture_ruling() + signatures = [SIGS[k] for k in case["sigKeys"]] + v = verify_ruling_signatures( + ruling, + signatures, + chain_id=DOMAIN["chainId"], + verifying_contract=DOMAIN["verifyingContract"], + fixed_evaluators=REGISTRY["fixedEvaluators"], + rotating_pool=REGISTRY["rotatingPool"], + now=case["now"], + freshness_seconds=REGISTRY["freshnessSeconds"], + ) + assert v.valid is case["expectValid"] + assert v.valid_count == case["expectValidCount"] + if "expectStale" in case: + assert v.stale is case["expectStale"] + assert v.third_evaluator.lower() == REGISTRY["selectedRotatingEvaluator"].lower() + + +# ===================================================================== +# 2. Full handshake (mocked /quote + injected x402 buyer stub) +# ===================================================================== + +EXAMPLE_A_BUNDLE = BUNDLE_VECTORS["vectors"][0]["bundle"] +EXAMPLE_A_HASH = compute_bundle_hash(EXAMPLE_A_BUNDLE, skip_token_check=True) + +TEST_KEYS = { + "fixedA": "0x" + "11" * 32, + "fixedB": "0x" + "22" * 32, + "rotating": "0x" + "33" * 32, + "unknown": "0x" + "44" * 32, +} + + +def _build_signed_ruling_for_example_a(timestamp: int, signer_keys: List[str]): + """Build + sign a ruling for Example A's bundle at a chosen timestamp.""" + ruling = AIRuling( + dispute_id=RULING_FX["disputeId"], # same disputeId so rotating selection holds + ruling=1, + confidence=9500, + split_bps=0, + timestamp=timestamp, + reasoning_hash=RULING_FX["reasoningHash"], + bundle_hash=EXAMPLE_A_HASH, # OQ-10: ruling commits the bundle we send + ) + signatures = [ + sign_ruling(ruling, pk, DOMAIN["chainId"], DOMAIN["verifyingContract"]) + for pk in signer_keys + ] + return ruling, signatures + + +@dataclass +class _MockResponse: + """A minimal httpx-like response (status_code + json()).""" + + status_code: int + _body: Any + + def json(self) -> Any: + return self._body + + +@dataclass +class _StubPayResult: + response: Any + + +class _PaymentStub: + """A stub x402 buyer that records the /evaluate POST and returns a canned 200.""" + + def __init__(self, evaluate_body: Any): + self._evaluate_body = evaluate_body + self.calls: List[Any] = [] + + async def pay(self, params: Any) -> _StubPayResult: + self.calls.append(params) + return _StubPayResult(response=_MockResponse(200, self._evaluate_body)) + + +def _make_quote_fetch(quote_body: Any, status: int = 402): + """A mock /quote fetch that returns the fixture 402 quote body and records calls.""" + calls: List[Dict[str, Any]] = [] + + async def fetch_impl(url, *, method="POST", headers=None, body=None): + calls.append({"url": url, "body": json.loads(body) if body else None}) + return _MockResponse(status, quote_body) + + return fetch_impl, calls + + +def _base_params() -> RequestEvaluationParams: + return RequestEvaluationParams( + bundle=EXAMPLE_A_BUNDLE, + dispute_id=RULING_FX["disputeId"], + payer="0x1DC48019D708f3d7f1adCAAfA2Ffa198A6897E8d", + escrow_amount="5000000", + tier=0, + bundle_source=BundleSource(cid="bafyExampleACid"), + chain_id=DOMAIN["chainId"], + verifying_contract=DOMAIN["verifyingContract"], + fixed_evaluators=REGISTRY["fixedEvaluators"], + rotating_pool=REGISTRY["rotatingPool"], + freshness_seconds=REGISTRY["freshnessSeconds"], + ) + + +class TestHandshake: + @pytest.mark.asyncio + async def test_signed_path(self): + now = int(time.time()) + ruling, signatures = _build_signed_ruling_for_example_a( + now, [TEST_KEYS["fixedA"], TEST_KEYS["rotating"]] + ) + evaluate_body = { + "apiVersion": "1.0.0", + "outcome": "signed", + "bundleHash": EXAMPLE_A_HASH, + "tokenCount": 419, + "ruling": ruling.to_dict(), + "signatures": signatures, + "evaluators": ["0xLyingEvaluator", "0xAlsoLying"], # advisory; MUST be ignored + "reasoning": "requester wins", + } + fetch_impl, quote_calls = _make_quote_fetch(FIXTURE["quoteResponse"]) + pay = _PaymentStub(evaluate_body) + client = EvaluatorClient( + EvaluatorClientConfig( + base_url="https://evaluator.test", + payment_client=pay, + fetch_impl=fetch_impl, + ) + ) + + result = await client.request_evaluation(_base_params()) + + # STEP 0: declared to /quote with the SDK-derived bundleHash (no money). + assert len(quote_calls) == 1 + assert quote_calls[0]["url"] == "https://evaluator.test/quote" + assert quote_calls[0]["body"]["bundleHash"] == EXAMPLE_A_HASH + assert quote_calls[0]["body"]["payer"] == _base_params().payer + + # STEP 2: paid via the x402 buyer stub against /evaluate, echoing the nonce. + assert len(pay.calls) == 1 + assert pay.calls[0].to == "https://evaluator.test/evaluate" + assert pay.calls[0].http_method == "POST" + assert pay.calls[0].metadata["payment_method"] == "x402" + assert ( + json.loads(pay.calls[0].http_body)["disputeNonce"] + == FIXTURE["quoteResponse"]["disputeNonce"] + ) + + # STEP 5: signed result, §4.7 PASSED, signers re-recovered (evaluators[] ignored). + assert result.outcome == "signed" + assert result.verification.valid is True + assert result.verification.valid_count == 2 + assert result.signatures == signatures + assert int(result.ruling.ruling) == 1 + assert str(result.ruling.bundle_hash).lower() == EXAMPLE_A_HASH.lower() + + @pytest.mark.asyncio + async def test_propose_directly_path(self): + evaluate_body = dict(FIXTURE["evaluateProposeDirectlyResponse"]) + evaluate_body["bundleHash"] = EXAMPLE_A_HASH # echo the bundle we send (OQ-10) + fetch_impl, _ = _make_quote_fetch(FIXTURE["quoteResponse"]) + pay = _PaymentStub(evaluate_body) + client = EvaluatorClient( + EvaluatorClientConfig( + base_url="https://evaluator.test", + payment_client=pay, + fetch_impl=fetch_impl, + ) + ) + + result = await client.request_evaluation(_base_params()) + assert result.outcome == "proposeDirectly" + assert result.reason == "server-recommended" + assert int(result.recommendation.ruling) == 2 + assert result.recommendation.split_bps == 5000 + # No signatures are surfaced on the proposeDirectly result. + assert result.signatures is None + + @pytest.mark.asyncio + async def test_signed_but_stale_downgrades(self): + stale_ts = int(time.time()) - (REGISTRY["freshnessSeconds"] + 10) + ruling, signatures = _build_signed_ruling_for_example_a( + stale_ts, [TEST_KEYS["fixedA"], TEST_KEYS["fixedB"]] + ) + evaluate_body = { + "apiVersion": "1.0.0", + "outcome": "signed", + "bundleHash": EXAMPLE_A_HASH, + "tokenCount": 419, + "ruling": ruling.to_dict(), + "signatures": signatures, + } + fetch_impl, _ = _make_quote_fetch(FIXTURE["quoteResponse"]) + pay = _PaymentStub(evaluate_body) + client = EvaluatorClient( + EvaluatorClientConfig( + base_url="https://evaluator.test", + payment_client=pay, + fetch_impl=fetch_impl, + ) + ) + + result = await client.request_evaluation(_base_params()) + assert result.outcome == "proposeDirectly" + assert result.reason == "verification-failed" + assert result.verification.stale is True + assert result.signatures is None # never fabricated/surfaced + + @pytest.mark.asyncio + async def test_signed_but_insufficient_downgrades(self): + now = int(time.time()) + ruling, signatures = _build_signed_ruling_for_example_a( + now, [TEST_KEYS["fixedA"], TEST_KEYS["unknown"]] + ) + evaluate_body = { + "apiVersion": "1.0.0", + "outcome": "signed", + "bundleHash": EXAMPLE_A_HASH, + "tokenCount": 419, + "ruling": ruling.to_dict(), + "signatures": signatures, + } + fetch_impl, _ = _make_quote_fetch(FIXTURE["quoteResponse"]) + pay = _PaymentStub(evaluate_body) + client = EvaluatorClient( + EvaluatorClientConfig( + base_url="https://evaluator.test", + payment_client=pay, + fetch_impl=fetch_impl, + ) + ) + + result = await client.request_evaluation(_base_params()) + assert result.outcome == "proposeDirectly" + assert result.reason == "verification-failed" + assert result.verification.valid_count == 1 + + @pytest.mark.asyncio + async def test_quote_rejected_too_large(self): + error_envelope = { + "apiVersion": "1.0.0", + "error": { + "code": "BundleTooLargeError", + "message": "Pinned bundle is 142113 tokens; cap 100000.", + }, + } + fetch_impl, _ = _make_quote_fetch(error_envelope, status=413) + pay = _PaymentStub({}) + client = EvaluatorClient( + EvaluatorClientConfig( + base_url="https://evaluator.test", + payment_client=pay, + fetch_impl=fetch_impl, + ) + ) + + with pytest.raises(QuoteRejectedError) as exc: + await client.request_evaluation(_base_params()) + assert exc.value.status == 413 + assert exc.value.code == "BundleTooLargeError" + # Never paid — the x402 stub was not invoked. + assert len(pay.calls) == 0 + + @pytest.mark.asyncio + async def test_quote_rejected_non_402(self): + fetch_impl, _ = _make_quote_fetch( + {"error": {"code": "PricingUnavailableError"}}, status=503 + ) + pay = _PaymentStub({}) + client = EvaluatorClient( + EvaluatorClientConfig( + base_url="https://evaluator.test", + payment_client=pay, + fetch_impl=fetch_impl, + ) + ) + with pytest.raises(QuoteRejectedError): + await client.request_evaluation(_base_params()) diff --git a/tests/test_dispute/test_evidence_artifact_v2.py b/tests/test_dispute/test_evidence_artifact_v2.py new file mode 100644 index 0000000..ead0d49 --- /dev/null +++ b/tests/test_dispute/test_evidence_artifact_v2.py @@ -0,0 +1,115 @@ +""" +Schema-2.0.0 evidence artifact — golden-vector parity with the sdk-js twin. + +The GOLDEN canonical string + hash below MUST match sdk-js +`tests/evidence-artifact-v2.test.ts`. A diff here is an ABI-freeze-level event +(it would break every already-signed 9-field ruling's bundleHash), not a test to update. +""" +import pytest + +from agirails.dispute.evidence_artifact_v2 import ( + EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION, + compute_artifact_v2_hash, + serialize_artifact_v2_to_string, + validate_evidence_artifact_v2, + UnsupportedArtifactVersionError, + InvalidArtifactError, +) + +D = "0x" + "11" * 32 +T = "0x" + "22" * 32 +R = "0x" + "33" * 32 +A = "0x" + "44" * 32 +REQ = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" +PRV = "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC" + + +def artifact(): + return { + "schemaVersion": "2.0.0", + "disputeId": D, + "transaction": { + "transactionId": T, + "parties": {"requester": REQ, "provider": PRV}, + "amount": "1000000000", + "initiator": REQ, + "timestamps": {"createdAt": 1700000000, "deliveredAt": 1700000100, "disputedAt": 1700000200}, + }, + "agreement": {"bytes": "AGREEMENT: request+input+SLA", "quote": {"bytes": "QUOTE: 1000 USDC", "quoteHash": A}}, + "delivery": {"resultHash": R, "inline": "DELIVERABLE: content"}, + } + + +def test_golden_canonical_string_and_hash(): + # Byte-identical to the sdk-js golden (evidence-artifact-v2.test.ts). Built by + # concatenation to avoid f-string brace escaping. + expected = ( + '{"agreement":{"bytes":"AGREEMENT: request+input+SLA","quote":{"bytes":"QUOTE: 1000 USDC",' + '"quoteHash":"' + A + '"}},"delivery":{"inline":"DELIVERABLE: content","resultHash":"' + R + '"},' + '"disputeId":"' + D + '","schemaVersion":"2.0.0","transaction":{"amount":"1000000000",' + '"initiator":"' + REQ + '","parties":{"provider":"' + PRV + '","requester":"' + REQ + '"},' + '"timestamps":{"createdAt":1700000000,"deliveredAt":1700000100,"disputedAt":1700000200},' + '"transactionId":"' + T + '"}}' + ) + assert serialize_artifact_v2_to_string(artifact()) == expected + # keccak of the SAME canonical text as the TS twin. + from eth_utils import keccak + assert compute_artifact_v2_hash(artifact(), skip_token_check=True) == "0x" + keccak(expected.encode("utf-8")).hex() + + +def test_hash_insensitive_to_source_key_order(): + a = artifact() + reordered = { + "delivery": a["delivery"], "transaction": a["transaction"], + "agreement": a["agreement"], "disputeId": D, "schemaVersion": "2.0.0", + } + assert compute_artifact_v2_hash(reordered, skip_token_check=True) == compute_artifact_v2_hash(a, skip_token_check=True) + + +def test_cid_only_agreement_ok_neither_rejected(): + a = artifact() + del a["agreement"]["bytes"] + a["agreement"]["cid"] = "bafy-agreement" + validate_evidence_artifact_v2(a) # no raise + del a["agreement"]["cid"] + with pytest.raises(InvalidArtifactError): + validate_evidence_artifact_v2(a) + + +def test_strict_exact_version(): + assert EVIDENCE_ARTIFACT_V2_SCHEMA_VERSION == "2.0.0" + for v in ("2.0.1", "2.1.0", "1.0.0"): + a = artifact(); a["schemaVersion"] = v + with pytest.raises(UnsupportedArtifactVersionError): + validate_evidence_artifact_v2(a) + a = artifact(); a["schemaVersion"] = "" + with pytest.raises(InvalidArtifactError): + validate_evidence_artifact_v2(a) + + +def test_rejects_forbidden_and_unknown_keys(): + for mutate in ( + lambda a: a.__setitem__("reasoning", {"notes": "smuggled"}), # D6 + lambda a: a.__setitem__("timeline", []), # D5 + lambda a: a.__setitem__("extra", 1), + lambda a: a["transaction"].__setitem__("extra", 1), + lambda a: a["delivery"].__setitem__("extra", 1), + lambda a: a["agreement"]["quote"].__setitem__("extra", 1), + ): + a = artifact(); mutate(a) + with pytest.raises(InvalidArtifactError): + validate_evidence_artifact_v2(a) + + +def test_rejects_malformed_fields(): + for mutate in ( + lambda a: a.__setitem__("disputeId", D.upper()), + lambda a: a["transaction"]["parties"].__setitem__("requester", "not-an-address"), + lambda a: a["transaction"].__setitem__("amount", "1.5"), + lambda a: a["transaction"]["timestamps"].__setitem__("createdAt", 1.5), + lambda a: a["delivery"].__setitem__("resultHash", "0x1234"), + lambda a: a["transaction"]["timestamps"].__setitem__("createdAt", True), # bool not int + ): + a = artifact(); mutate(a) + with pytest.raises(InvalidArtifactError): + validate_evidence_artifact_v2(a) diff --git a/tests/test_dispute/test_resolution_principal_validation.py b/tests/test_dispute/test_resolution_principal_validation.py new file mode 100644 index 0000000..b054034 --- /dev/null +++ b/tests/test_dispute/test_resolution_principal_validation.py @@ -0,0 +1,64 @@ +import pytest +from eth_abi import encode + +from agirails.dispute.composite_mediator import decode_resolution_proof +from agirails.reputation.dispute_split_indexer import DisputeOutcome, DisputeSplitIndexer + + +@pytest.fixture(params=[False, True]) +def proof(request): + return ( + "0x" + + ( + encode(["uint256", "uint256", "bool"], [1, 0, True]) + if request.param + else encode(["uint256", "uint256"], [1, 0]) + ).hex() + ) + + +@pytest.mark.parametrize("entry", ["decoder", "indexer"]) +def test_unknown_principal_never_becomes_a_one_wei_payout(proof, entry): + with pytest.raises(ValueError, match="principal"): + if entry == "decoder": + decode_resolution_proof(proof, remaining=None) + else: + DisputeSplitIndexer().classify_payout( + DisputeOutcome( + provider="p", requester="r", kind="settled", remaining=None, proof=proof + ) + ) + + +@pytest.mark.parametrize("principal", [0, 50000]) +def test_explicit_principal_is_authoritative_even_when_legacy_alias_is_missing(proof, principal): + direct = decode_resolution_proof(proof, remaining=None, escrow_principal=principal) + indexed = DisputeSplitIndexer().classify_payout( + DisputeOutcome( + provider="p", + requester="r", + kind="settled", + remaining=None, + escrow_principal=principal, + proof=proof, + ) + ) + assert direct == indexed + assert direct.requester_amount == (0 if principal == 0 else 1) + assert direct.provider_amount == 0 and direct.phantom_sentinel == (principal == 0) + + +def test_no_proof_does_not_attempt_to_classify_unknown_principal(): + assert ( + DisputeSplitIndexer().classify_payout( + DisputeOutcome(provider="p", requester="r", kind="settled", remaining=None) + ) + is None + ) + + +def test_default_zero_principal_still_suppresses_sentinel(proof): + result = DisputeSplitIndexer().classify_payout( + DisputeOutcome(provider="p", requester="r", kind="settled", proof=proof) + ) + assert result.phantom_sentinel and result.requester_amount == result.provider_amount == 0 diff --git a/tests/test_dispute/test_uma_helper.py b/tests/test_dispute/test_uma_helper.py new file mode 100644 index 0000000..2228230 --- /dev/null +++ b/tests/test_dispute/test_uma_helper.py @@ -0,0 +1,390 @@ +# PARITY: sdk-js/tests/uma-helper.test.ts +""" +P2-7 — UMAHelper unit tests (Py side): the requester self-dispute DVM helper +(AIP-14b §8.6). + +Mirrors ``sdk-js/tests/uma-helper.test.ts`` 1:1 and consumes the SAME shared +cross-SDK fixture ``DISPUTE SYSTEM/test-vectors/uma-self-dispute-vectors.json``. + +Proves, with mock contracts (no live chain): + 1. requester_force_dvm issues EXACTLY the call sequence + approve -> escalateToUMA -> (read assertionId) -> approve -> disputeAssertion, + in that order, with the correct target contract + calldata per step. + 2. quote_self_dispute_cost returns {total $1000, recover $750, lose $250}. + 3. The §8.6 asymmetry warning AND the "settleAssertion yourself or risk a + 30-day forced 50/50 split" warning are BOTH present in the source + (a grep test reads the .py file). +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any, List + +import pytest +from web3 import Web3 + +from agirails.dispute.uma_helper import ( + UMAHelper, + UMA_BOND, + SELF_DISPUTE_TOTAL, + SELF_DISPUTE_RECOVER, + SELF_DISPUTE_LOSS, +) + +# Shared cross-SDK fixture (the SAME file the TS jest suite loads). +_VECTORS_DIR = Path(__file__).resolve().parents[2] / "test-vectors" +_FIXTURE = json.loads((_VECTORS_DIR / "uma-self-dispute-vectors.json").read_text()) + +_ABI_DIR = Path(__file__).resolve().parents[2] / "src" / "agirails" / "abis" +_BOND_ABI = json.loads((_ABI_DIR / "bond_escalation.json").read_text()) +_OOV3_ABI = json.loads((_ABI_DIR / "i_optimistic_oracle_v3.json").read_text()) +_USDC_ABI = json.loads((_ABI_DIR / "usdc.json").read_text()) + +# Reference contracts for INDEPENDENT calldata encoding (the assertion oracle). +_REF_BOND = Web3().eth.contract(abi=_BOND_ABI) +_REF_OOV3 = Web3().eth.contract(abi=_OOV3_ABI) +_REF_USDC = Web3().eth.contract(abi=_USDC_ABI) + +BOND_ADDR = "0x000000000000000000000000000000000000BE11" +OOV3_ADDR = "0x2aBf1Bd76655de80eDB3086114315Eec75AF500c" +USDC_ADDR = "0x000000000000000000000000000000000000C0dc" + + +def _b32(hexstr: str) -> bytes: + return bytes.fromhex(hexstr[2:] if hexstr.startswith("0x") else hexstr) + + +class _MockFunction: + """Awaitable mock that records (target, name, args) into a shared sink.""" + + def __init__(self, sink: List, target: str, name: str): + self._sink = sink + self._target = target + self._name = name + + def __call__(self, *args): + self._sink.append((self._target, self._name, args)) + return self + + def __await__(self): + async def _coro(): + return b"\xaa" * 32 + + return _coro().__await__() + + +class _DisputeToAssertionFn: + """Read fn: records the read into the sink, returns a configured assertion.""" + + def __init__(self, sink: List, assertion_id: str): + self._sink = sink + self._assertion_id = assertion_id + + def __call__(self, *_args): + return self + + async def call(self): + self._sink.append(("bondEscalation", "disputeToAssertion(read)", ())) + return _b32(self._assertion_id) + + +class _GetMinimumBondFn: + """Read fn: returns the configured minimum bond WITHOUT recording a write.""" + + def __init__(self, minimum_bond: int): + self._minimum_bond = minimum_bond + + def __call__(self, *_args): + return self + + async def call(self): + return self._minimum_bond + + +class _MockFunctions: + def __init__( + self, sink: List, target: str, assertion_id: str = None, minimum_bond: int = None + ): + self._sink = sink + self._target = target + self._assertion_id = assertion_id + self._minimum_bond = minimum_bond + + def __getattr__(self, name): + if name == "disputeToAssertion" and self._assertion_id is not None: + return _DisputeToAssertionFn(self._sink, self._assertion_id) + if name == "getMinimumBond" and self._minimum_bond is not None: + return _GetMinimumBondFn(self._minimum_bond) + return _MockFunction(self._sink, self._target, name) + + +class _MockContract: + """Records calldata via a reference contract's encode_abi.""" + + def __init__( + self, + sink: List, + target: str, + ref, + address: str, + assertion_id: str = None, + minimum_bond: int = None, + ): + self._ref = ref + self.address = address + self.functions = _MockFunctions(sink, target, assertion_id, minimum_bond) + + def encode_abi(self, *, abi_element_identifier: str, args): + return self._ref.encode_abi(abi_element_identifier=abi_element_identifier, args=args) + + +def _make_helper(assertion_id: str = None): + assertion_id = assertion_id or _FIXTURE["requesterForceDVM"]["assertionId"] + sink: List = [] + bond = _MockContract(sink, "bondEscalation", _REF_BOND, BOND_ADDR, assertion_id) + oov3 = _MockContract(sink, "oov3", _REF_OOV3, OOV3_ADDR, minimum_bond=UMA_BOND) + usdc = _MockContract(sink, "usdc", _REF_USDC, USDC_ADDR) + helper = UMAHelper( + bond, + oov3, + usdc, + bond_escalation_address=BOND_ADDR, + oov3_address=OOV3_ADDR, + usdc_address=USDC_ADDR, + ) + return helper, sink + + +# --------------------------------------------------------------------------- +# 1. quote_self_dispute_cost (shared fixture) +# --------------------------------------------------------------------------- + + +def test_quote_self_dispute_cost_matches_fixture(): + cost = UMAHelper.quote_self_dispute_cost() + fx = _FIXTURE["quoteSelfDisputeCost"] + assert str(cost["total"]) == fx["total"] + assert str(cost["recover"]) == fx["recover"] + assert str(cost["lose"]) == fx["lose"] + + +def test_quote_self_dispute_cost_exact_dollars(): + cost = UMAHelper.quote_self_dispute_cost() + assert cost["total"] == 1_000_000_000 # $1000 + assert cost["recover"] == 750_000_000 # $750 + assert cost["lose"] == 250_000_000 # $250 + # identity: total - recover == lose (UMA Store fee = 50% of losing bond) + assert cost["total"] - cost["recover"] == cost["lose"] + # attribute access parity with the TS object shape + assert cost.total == cost["total"] + assert cost.recover == cost["recover"] + assert cost.lose == cost["lose"] + + +def test_constants_internally_consistent(): + assert UMA_BOND == 500_000_000 + assert SELF_DISPUTE_TOTAL == UMA_BOND * 2 + assert SELF_DISPUTE_RECOVER == UMA_BOND + UMA_BOND // 2 + assert SELF_DISPUTE_LOSS == SELF_DISPUTE_TOTAL - SELF_DISPUTE_RECOVER + + +# --------------------------------------------------------------------------- +# 2. requester_force_dvm call sequence (shared fixture) +# --------------------------------------------------------------------------- + + +async def test_requester_force_dvm_exact_call_sequence(): + fx = _FIXTURE["requesterForceDVM"] + helper, sink = _make_helper(fx["assertionId"]) + + result = await helper.requester_force_dvm( + fx["disputeId"], fx["evidenceCID"], fx["reasoningCID"], fx["disputer"] + ) + + # Full ordered sequence INCLUDING the read between escalate and dispute. + seq = [(t, n) for (t, n, _a) in sink] + assert seq == [ + ("usdc", "approve"), + ("bondEscalation", "escalateToUMA"), + ("bondEscalation", "disputeToAssertion(read)"), + ("usdc", "approve"), + ("oov3", "disputeAssertion"), + ] + + # The fixture's declared sequence MUST match (read step mapped 1:1). + fixture_seq = [] + for step in fx["sequence"]: + method = "disputeToAssertion(read)" if step["method"] == "disputeToAssertion" else step["method"] + fixture_seq.append((step["target"], method)) + assert seq == fixture_seq + + # The read produced the assertionId returned to the caller. + assert result["assertion_id"] == fx["assertionId"] + + # Per-step calldata (writes only) matches an independent encode. + writes = [(t, n, a) for (t, n, a) in sink if "read" not in n] + # Step 1: approve(bondEscalation, $500) + t, n, a = writes[0] + assert (t, n) == ("usdc", "approve") + assert _REF_USDC.encode_abi(abi_element_identifier="approve", args=list(a)) == _REF_USDC.encode_abi( + abi_element_identifier="approve", args=[BOND_ADDR, UMA_BOND] + ) + # Step 2: escalateToUMA(disputeId, evidenceCID, reasoningCID) — BLOCKER-2. + t, n, a = writes[1] + assert (t, n) == ("bondEscalation", "escalateToUMA") + encoded_escalate = _REF_BOND.encode_abi(abi_element_identifier="escalateToUMA", args=list(a)) + assert encoded_escalate == _REF_BOND.encode_abi( + abi_element_identifier="escalateToUMA", + args=[_b32(fx["disputeId"]), fx["evidenceCID"], fx["reasoningCID"]], + ) + assert encoded_escalate[:10] == "0xea487f8a" + # Step 3: approve(oov3, $500) + t, n, a = writes[2] + assert (t, n) == ("usdc", "approve") + assert _REF_USDC.encode_abi(abi_element_identifier="approve", args=list(a)) == _REF_USDC.encode_abi( + abi_element_identifier="approve", args=[OOV3_ADDR, UMA_BOND] + ) + # Step 4: disputeAssertion(assertionId, disputer) + t, n, a = writes[3] + assert (t, n) == ("oov3", "disputeAssertion") + assert _REF_OOV3.encode_abi(abi_element_identifier="disputeAssertion", args=list(a)) == _REF_OOV3.encode_abi( + abi_element_identifier="disputeAssertion", args=[_b32(fx["assertionId"]), fx["disputer"]] + ) + + +async def test_read_happens_after_escalate_before_dispute(): + fx = _FIXTURE["requesterForceDVM"] + helper, sink = _make_helper(fx["assertionId"]) + await helper.requester_force_dvm(fx["disputeId"], fx["evidenceCID"], fx["reasoningCID"], fx["disputer"]) + names = [n for (_t, n, _a) in sink] + escalate_idx = names.index("escalateToUMA") + read_idx = names.index("disputeToAssertion(read)") + dispute_idx = names.index("disputeAssertion") + assert escalate_idx < read_idx < dispute_idx + + +async def test_get_assertion_id_reads_dispute_to_assertion(): + fx = _FIXTURE["requesterForceDVM"] + helper, _ = _make_helper(fx["assertionId"]) + got = await helper.get_assertion_id(fx["disputeId"]) + assert got == fx["assertionId"] + + +async def test_settle_assertion_calldata(): + fx = _FIXTURE["requesterForceDVM"] + helper, sink = _make_helper(fx["assertionId"]) + await helper.settle_assertion(fx["assertionId"]) + assert len(sink) == 1 + t, n, a = sink[0] + assert (t, n) == ("oov3", "settleAssertion") + assert _REF_OOV3.encode_abi(abi_element_identifier="settleAssertion", args=list(a)) == _REF_OOV3.encode_abi( + abi_element_identifier="settleAssertion", args=[_b32(fx["assertionId"])] + ) + + +# --------------------------------------------------------------------------- +# 2b. Dynamic bond parity (get_effective_bond) +# --------------------------------------------------------------------------- + + +def _make_helper_with_min_bond(minimum_bond: int): + fx_assertion = _FIXTURE["requesterForceDVM"]["assertionId"] + sink: List = [] + bond = _MockContract(sink, "bondEscalation", _REF_BOND, BOND_ADDR, fx_assertion) + oov3 = _MockContract(sink, "oov3", _REF_OOV3, OOV3_ADDR, minimum_bond=minimum_bond) + usdc = _MockContract(sink, "usdc", _REF_USDC, USDC_ADDR) + helper = UMAHelper( + bond, + oov3, + usdc, + bond_escalation_address=BOND_ADDR, + oov3_address=OOV3_ADDR, + usdc_address=USDC_ADDR, + ) + return helper, sink + + +async def test_get_effective_bond_floors_at_500(): + helper, _ = _make_helper_with_min_bond(100_000_000) # $100 < $500 + assert await helper.get_minimum_bond() == 100_000_000 + assert await helper.get_effective_bond() == UMA_BOND # max($500, $100) + + +async def test_get_effective_bond_uses_raised_minimum(): + raised = 800_000_000 # $800 > $500 + helper, _ = _make_helper_with_min_bond(raised) + assert await helper.get_effective_bond() == raised + + +async def test_requester_force_dvm_approves_raised_bond(): + raised = 800_000_000 + fx = _FIXTURE["requesterForceDVM"] + helper, sink = _make_helper_with_min_bond(raised) + await helper.requester_force_dvm(fx["disputeId"], fx["evidenceCID"], fx["reasoningCID"], fx["disputer"]) + writes = [(t, n, a) for (t, n, a) in sink if n != "disputeToAssertion(read)"] + # writes[0] = approve(bondEscalation, raised); writes[2] = approve(oov3, raised) + assert writes[0][0:2] == ("usdc", "approve") + assert _REF_USDC.encode_abi( + abi_element_identifier="approve", args=list(writes[0][2]) + ) == _REF_USDC.encode_abi( + abi_element_identifier="approve", args=[BOND_ADDR, raised] + ) + assert writes[2][0:2] == ("usdc", "approve") + assert _REF_USDC.encode_abi( + abi_element_identifier="approve", args=list(writes[2][2]) + ) == _REF_USDC.encode_abi( + abi_element_identifier="approve", args=[OOV3_ADDR, raised] + ) + + +# --------------------------------------------------------------------------- +# 3. Config guards +# --------------------------------------------------------------------------- + + +def test_rejects_confirmations_below_one(): + helper, _ = _make_helper() + with pytest.raises(ValueError, match="confirmations must be >= 1"): + UMAHelper( + helper._bond_escalation, + helper._oov3, + helper._usdc, + confirmations=0, + ) + + +def test_address_accessors(): + helper, _ = _make_helper() + assert helper.get_bond_escalation_address() == BOND_ADDR + assert helper.get_oov3_address() == OOV3_ADDR + + +# --------------------------------------------------------------------------- +# 4. Required docstring warnings (grep over source) +# --------------------------------------------------------------------------- + +_SRC = ( + Path(__file__).resolve().parents[2] + / "src" + / "agirails" + / "dispute" + / "uma_helper.py" +).read_text() + + +def test_source_contains_asymmetry_warning(): + # The §8.6 asymmetry: escalate_to_uma is provider-directional, rational only + # for the provider side; the requester normally wins for free via finalize(). + assert re.search(r"§8\.6 ASYMMETRY WARNING", _SRC) + assert re.search(r"provider-directional", _SRC, re.IGNORECASE) + assert re.search(r"asymmetr", _SRC, re.IGNORECASE) + + +def test_source_contains_settle_warning(): + assert re.search( + r"[Cc]all\s+settleAssertion\s+yourself\s+or\s+risk\s+a\s+30-day\s+forced\s+50/50\s+split", + _SRC, + ) diff --git a/tests/test_erc8004/test_reputation_reporter.py b/tests/test_erc8004/test_reputation_reporter.py index b684749..2bdd70b 100644 --- a/tests/test_erc8004/test_reputation_reporter.py +++ b/tests/test_erc8004/test_reputation_reporter.py @@ -358,6 +358,56 @@ async def test_dispute_dedup(self): assert r2 is None +# --------------------------------------------------------------------------- +# Tests: report_dispute_split (P2-8 — neutral split trace) +# PARITY: sdk-js/tests/dispute-split-indexer.test.ts "reportDisputeSplit". +# --------------------------------------------------------------------------- + + +class TestReportDisputeSplit: + async def test_writes_value_zero_neutral_and_split_tag(self): + reporter = _make_reporter() + result = await reporter.report_dispute_split( + agent_id="42", + tx_id="0xsplit1", + capability="code_generation", + split_bps=5000, + ) + assert result is not None + assert result.tag == ACTP_FEEDBACK_TAGS["DISPUTE_SPLIT"] + last = reporter._contract.functions.last_feedback_call + assert last["value"] == 0 # NEUTRAL — no penalty (INV-4) + assert last["value_decimals"] == 0 + assert last["tag1"] == "actp_dispute_split" + assert last["tag2"] == "code_generation" + assert last["endpoint"] == "" + assert last["feedback_uri"] == "splitBps:5000" + + async def test_tag_string_is_cross_sdk_canonical(self): + # PARITY: identical literal to TS ACTP_FEEDBACK_TAGS.DISPUTE_SPLIT. + assert ACTP_FEEDBACK_TAGS["DISPUTE_SPLIT"] == "actp_dispute_split" + + async def test_never_throws_returns_none_on_failure(self): + reporter = _make_reporter(give_feedback_raises=RuntimeError("boom")) + result = await reporter.report_dispute_split( + agent_id="42", tx_id="0xsplitfail" + ) + assert result is None # logged, never raised + + async def test_split_dedup(self): + reporter = _make_reporter() + r1 = await reporter.report_dispute_split(agent_id="42", tx_id="0xsplit2") + assert r1 is not None + r2 = await reporter.report_dispute_split(agent_id="42", tx_id="0xsplit2") + assert r2 is None + + async def test_no_split_bps_yields_empty_feedback_uri(self): + reporter = _make_reporter() + await reporter.report_dispute_split(agent_id="7", tx_id="0xsplit3") + last = reporter._contract.functions.last_feedback_call + assert last["feedback_uri"] == "" + + # --------------------------------------------------------------------------- # Tests: get_agent_reputation # --------------------------------------------------------------------------- diff --git a/tests/test_golden/test_airuling_golden.py b/tests/test_golden/test_airuling_golden.py new file mode 100644 index 0000000..1d8a15f --- /dev/null +++ b/tests/test_golden/test_airuling_golden.py @@ -0,0 +1,210 @@ +""" +GOLDEN VECTOR test for the AIRuling EIP-712 signer (AIP-14b §4.4). + +This is the cross-language anchor: the Python SDK MUST reproduce the exact same +EIP-712 digest as the TypeScript SDK and the on-chain contract path. The frozen +constants below come from: + + Protocol/actp-kernel/test/EncodingCanonical.t.sol + +If RULING_TYPEHASH, the AIRuling field order, the domain name/version, the +chainId binding, or the verifyingContract binding ever drifts, this test breaks +loudly. +""" + +from eth_utils import keccak + +from agirails.types.dispute import ( + AIRuling, + DisputeEIP712Domain, + Ruling, + Tier, + compute_ruling_digest, + compute_ruling_domain_separator, + compute_ruling_struct_hash, + recover_ruling_signer, + sign_ruling, +) + + +# ---- FIXED golden inputs (every byte hardcoded) ---- +GOLDEN_CHAIN_ID = 8453 # Base mainnet +GOLDEN_VERIFYING_CONTRACT = "0x3c68CC8dFe901c7e89eC9f738F9a81709E6e7737" + +GOLDEN_DISPUTE_ID = "0x" + keccak(text="ACTP_GOLDEN_VECTOR_DISPUTE").hex() +GOLDEN_RULING = 1 # requester wins +GOLDEN_CONFIDENCE = 9500 # 95% +GOLDEN_SPLIT_BPS = 0 +GOLDEN_TIMESTAMP = 1_700_000_000 +GOLDEN_REASONING_HASH = "0x" + keccak(text="golden-reasoning").hex() +GOLDEN_BUNDLE_HASH = "0x" + keccak(text="golden-bundle").hex() +GOLDEN_EVIDENCE_REF_HASH = "0x" + keccak(text="golden-evidence-ref").hex() +GOLDEN_REASONING_REF_HASH = "0x" + keccak(text="golden-reasoning-ref").hex() + +# ---- FROZEN EXPECTED VALUES (the canonical anchor, AIP-14c 9-field type) ---- +GOLDEN_DOMAIN_SEPARATOR = ( + "0x49c919619319169442e048297d8b8dc2f0c6a78b8601c78a39656bc2b3b25db8" +) +GOLDEN_STRUCT_HASH = ( + "0x2b30b25ad0258f200a315a68b1a7ebffc4040679fca1a4bbdf1cae0b57c589b4" +) +GOLDEN_DIGEST = ( + "0xc14778f377cd385dd4686b798cb2a010c8ff95e8a35a4f170af7e05bc8c2d8a0" +) + + +def _golden_ruling() -> AIRuling: + return AIRuling( + dispute_id=GOLDEN_DISPUTE_ID, + ruling=GOLDEN_RULING, + confidence=GOLDEN_CONFIDENCE, + split_bps=GOLDEN_SPLIT_BPS, + timestamp=GOLDEN_TIMESTAMP, + reasoning_hash=GOLDEN_REASONING_HASH, + bundle_hash=GOLDEN_BUNDLE_HASH, + evidence_ref_hash=GOLDEN_EVIDENCE_REF_HASH, + reasoning_ref_hash=GOLDEN_REASONING_REF_HASH, + ) + + +def _golden_domain() -> DisputeEIP712Domain: + return DisputeEIP712Domain( + chain_id=GOLDEN_CHAIN_ID, + verifying_contract=GOLDEN_VERIFYING_CONTRACT, + ) + + +def test_golden_domain_separator(): + """The EIP-712 domain separator must equal the frozen golden constant.""" + sep = _golden_domain().separator() + assert "0x" + sep.hex() == GOLDEN_DOMAIN_SEPARATOR + + +def test_golden_struct_hash(): + """The AIRuling struct hash must equal the frozen golden constant.""" + sh = _golden_ruling().struct_hash() + assert "0x" + sh.hex() == GOLDEN_STRUCT_HASH + + +def test_golden_digest(): + """The full EIP-712 digest must equal the frozen golden constant.""" + digest = compute_ruling_digest( + _golden_ruling(), GOLDEN_CHAIN_ID, GOLDEN_VERIFYING_CONTRACT + ) + assert "0x" + digest.hex() == GOLDEN_DIGEST + + +def test_golden_all_three_at_once(): + """domain_separator == GOLDEN, struct_hash == GOLDEN, digest == GOLDEN.""" + domain = _golden_domain() + ruling = _golden_ruling() + + domain_separator = "0x" + domain.separator().hex() + struct_hash = "0x" + ruling.struct_hash().hex() + digest = ( + "0x" + + compute_ruling_digest( + ruling, GOLDEN_CHAIN_ID, GOLDEN_VERIFYING_CONTRACT + ).hex() + ) + + assert domain_separator == GOLDEN_DOMAIN_SEPARATOR + assert struct_hash == GOLDEN_STRUCT_HASH + assert digest == GOLDEN_DIGEST + + +def test_ruling_enum_value(): + """INV-1 canonical mapping: requester wins == 1.""" + assert int(Ruling.REQUESTER_WINS) == GOLDEN_RULING + assert int(Ruling.PROVIDER_WINS) == 0 + assert int(Ruling.SPLIT) == 2 + + +def test_tier_enum_is_zero_based_matches_chain(): + """ + Negative control: Tier MUST be 0-based to match BondEscalation.sol's d.tier + field (opened=0 -> proposal=1 -> UMA=2). TIER1 == on-chain value 1, NOT 2. + A 1-based enum would misclassify every tier the moment a disputes()/d.tier + reader is wired. TS twin asserts the identical mapping. + """ + assert int(Tier.TIER0) == 0 + assert int(Tier.TIER1) == 1 + assert int(Tier.TIER2) == 2 + + +def test_standalone_digest_helpers_match_methods(): + """ + Module-level compute_ruling_struct_hash / compute_ruling_domain_separator + (added for TS parity) delegate to the methods and reproduce the golden values. + """ + ruling = _golden_ruling() + assert "0x" + compute_ruling_struct_hash(ruling).hex() == GOLDEN_STRUCT_HASH + sep = compute_ruling_domain_separator(GOLDEN_CHAIN_ID, GOLDEN_VERIFYING_CONTRACT) + assert "0x" + sep.hex() == GOLDEN_DOMAIN_SEPARATOR + + +def test_sign_and_recover_round_trip(): + """sign_ruling then recover_ruling_signer recovers the signing address.""" + private_key = "0x" + "11" * 32 + from eth_account import Account + + expected_signer = Account.from_key(private_key).address + + ruling = _golden_ruling() + signature = sign_ruling( + ruling, private_key, GOLDEN_CHAIN_ID, GOLDEN_VERIFYING_CONTRACT + ) + recovered = recover_ruling_signer( + ruling, signature, GOLDEN_CHAIN_ID, GOLDEN_VERIFYING_CONTRACT + ) + assert recovered == expected_signer + + +def test_bytes32_inputs_accepted(): + """AIRuling accepts raw bytes for bytes32 fields and reproduces the digest.""" + ruling = AIRuling( + dispute_id=keccak(text="ACTP_GOLDEN_VECTOR_DISPUTE"), + ruling=GOLDEN_RULING, + confidence=GOLDEN_CONFIDENCE, + split_bps=GOLDEN_SPLIT_BPS, + timestamp=GOLDEN_TIMESTAMP, + reasoning_hash=keccak(text="golden-reasoning"), + bundle_hash=keccak(text="golden-bundle"), + evidence_ref_hash=keccak(text="golden-evidence-ref"), + reasoning_ref_hash=keccak(text="golden-reasoning-ref"), + ) + digest = compute_ruling_digest( + ruling, GOLDEN_CHAIN_ID, GOLDEN_VERIFYING_CONTRACT + ) + assert "0x" + digest.hex() == GOLDEN_DIGEST + + +def test_ref_hashes_load_bearing_default_zero(): + """ + AIP-14c: evidence_ref_hash / reasoning_ref_hash default to bytes32(0) when + omitted (pre-D7 / direct-proposal path), and are load-bearing — supplying + the golden refs yields the golden digest, omitting them does NOT. + """ + zero_ref = AIRuling( + dispute_id=GOLDEN_DISPUTE_ID, + ruling=GOLDEN_RULING, + confidence=GOLDEN_CONFIDENCE, + split_bps=GOLDEN_SPLIT_BPS, + timestamp=GOLDEN_TIMESTAMP, + reasoning_hash=GOLDEN_REASONING_HASH, + bundle_hash=GOLDEN_BUNDLE_HASH, + ) + digest_zero = compute_ruling_digest( + zero_ref, GOLDEN_CHAIN_ID, GOLDEN_VERIFYING_CONTRACT + ) + assert "0x" + digest_zero.hex() != GOLDEN_DIGEST + + +def test_typehash_frozen_literal(): + """RULING_TYPEHASH equals the frozen AIP-14c literal (byte-for-byte).""" + from agirails.types.dispute import RULING_TYPEHASH + + assert ( + "0x" + RULING_TYPEHASH.hex() + == "0x00e11bf3b34994a6bc6e216b116cbdaddee1227d0c97d46416f8d994ba8420ae" + ) diff --git a/tests/test_level1/test_agent_operator_contracts.py b/tests/test_level1/test_agent_operator_contracts.py new file mode 100644 index 0000000..1d1b660 --- /dev/null +++ b/tests/test_level1/test_agent_operator_contracts.py @@ -0,0 +1,150 @@ +"""Agent terminal states, timeout/error propagation and handler cleanup.""" + +import asyncio +import importlib +from datetime import datetime,timedelta +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from agirails.level1.agent import Agent +from agirails.level1.config import AgentConfig,ServiceConfig,AgentBehavior +from agirails.level1.job import Job,JobResult +from agirails.errors import NoProviderFoundError +from tests.test_level1.test_agent_delivery_hook import _agent_with_delivery,_job + +TX='0x'+'ab'*32 +PROVIDER='0x'+'22'*20 + + +@pytest.mark.asyncio +@pytest.mark.parametrize('states,expected', [(['SETTLED'],'completed'),(['COMMITTED','SETTLED'],'completed'),(['CANCELLED'],'cancelled'),([None],'not found')]) +async def test_agent_request_reports_only_terminal_success_and_funds_once(states,expected,monkeypatch): + agent=Agent(AgentConfig(name='buyer',network='mock')) + standard=SimpleNamespace(create_transaction=AsyncMock(return_value=TX),link_escrow=AsyncMock(),get_transaction=AsyncMock(side_effect=[None if state is None else SimpleNamespace(state=state) for state in states])) + agent._client=SimpleNamespace(standard=standard) + original=asyncio.sleep + async def tick(_):await original(0) + monkeypatch.setattr('agirails.level1.agent.asyncio.sleep',tick) + if expected=='completed': + result=await agent.request('echo',{'message':'hello'},provider=PROVIDER,budget=1.25,timeout=1) + assert result['tx_id']==TX and result['status']=='completed' + else: + with pytest.raises(RuntimeError,match=expected): + await agent.request('echo',{},provider=PROVIDER,budget=1.25,timeout=1) + standard.create_transaction.assert_awaited_once() + payload=standard.create_transaction.await_args.args[0] + assert payload['provider']==PROVIDER and payload['amount']==1.25 + standard.link_escrow.assert_awaited_once_with(TX) + assert standard.get_transaction.await_count==len(states) + + +@pytest.mark.asyncio +async def test_agent_request_requires_started_client_and_handles_lookup_and_timeout(monkeypatch): + agent=Agent(AgentConfig(name='buyer',network='mock')) + with pytest.raises(RuntimeError,match='not started'):await agent.request('echo',{},budget=1) + standard=SimpleNamespace(create_transaction=AsyncMock(return_value=TX),link_escrow=AsyncMock(),get_transaction=AsyncMock()) + agent._client=SimpleNamespace(standard=standard) + directory_module=importlib.import_module('agirails.level0.directory') + directory=directory_module.ServiceDirectory() + monkeypatch.setattr(directory_module,'_global_directory',directory) + with pytest.raises(NoProviderFoundError):await agent.request('echo',{},budget=1) + standard.create_transaction.assert_not_awaited() + directory.register('echo') + with pytest.raises(NoProviderFoundError):await agent.request('echo',{},budget=1) + standard.create_transaction.assert_not_awaited() + directory.unregister('echo') + directory.register('echo',provider_address=PROVIDER) + standard.get_transaction.return_value=SimpleNamespace(state='COMMITTED') + with pytest.raises(TimeoutError,match='timed out'):await agent.request('echo',{},budget=1,timeout=1) + standard.create_transaction.assert_awaited_once() + standard.get_transaction.assert_awaited_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('state',['COMMITTED','IN_PROGRESS','CANCELLED','DISPUTED']) +@pytest.mark.parametrize('result',['plain','success','failure','exception']) +async def test_execute_handler_respects_state_and_always_cleans_active_job(state,result,monkeypatch): + agent=Agent(AgentConfig(name='provider',network='mock')) + async def handler(job,ctx): + if result=='exception':raise RuntimeError('handler unavailable') + if result=='success':return JobResult.ok({'output':42}) + if result=='failure':return JobResult.fail('handler declined') + return {'output':42} + agent.provide('echo',handler=handler) + agent._client=SimpleNamespace(runtime=SimpleNamespace(get_transaction=AsyncMock(return_value=SimpleNamespace(state=state))),standard=SimpleNamespace(transition_state=AsyncMock())) + complete=AsyncMock();fail=AsyncMock() + monkeypatch.setattr(agent,'_complete_job',complete);monkeypatch.setattr(agent,'_fail_job',fail) + job=_job();agent._active_jobs.set(job.id,job) + await agent._execute_job(job,agent._services['echo']) + assert agent.jobs==[] + if state in ('CANCELLED','DISPUTED'): + complete.assert_not_awaited();fail.assert_not_awaited() + agent._client.standard.transition_state.assert_not_awaited() + else: + if state=='COMMITTED':agent._client.standard.transition_state.assert_awaited_once_with(job.id,'IN_PROGRESS') + else:agent._client.standard.transition_state.assert_not_awaited() + if result in ('plain','success'): + complete.assert_awaited_once_with(job,{'output':42},agent._services['echo']);fail.assert_not_awaited() + else: + fail.assert_awaited_once();complete.assert_not_awaited() + assert fail.await_args.args[0] is job + + +@pytest.mark.asyncio +async def test_execute_timeout_and_state_read_failure_keep_cleanup_bounded(monkeypatch): + agent=Agent(AgentConfig(name='provider',network='mock')) + async def handler(job,ctx):await asyncio.Event().wait() + agent.provide(ServiceConfig(name='echo',timeout=0),handler=handler) + agent._client=SimpleNamespace(runtime=SimpleNamespace(get_transaction=AsyncMock(side_effect=ConnectionError('RPC unavailable'))),standard=SimpleNamespace(transition_state=AsyncMock(side_effect=ValueError('already in progress')))) + fail=AsyncMock();monkeypatch.setattr(agent,'_fail_job',fail) + job=_job();agent._active_jobs.set(job.id,job) + await agent._execute_job(job,agent._services['echo']) + assert agent.jobs==[] + fail.assert_awaited_once() + assert 'timed out' in fail.await_args.args[1] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('description,expected', [(None,None),('invalid',None),('service:echo;input:{"a":1}',{'a':1}),('service:echo;input:raw','raw'),(123,None)]) +async def test_job_input_legacy_parsing_is_bounded(description,expected): + agent=Agent(AgentConfig(name='provider',network='mock')) + assert agent._extract_job_input(SimpleNamespace(service_description=description))==expected + + +@pytest.mark.asyncio +@pytest.mark.parametrize('reason',['processed','locked','no_handler','declined']) +async def test_rejected_or_duplicate_transaction_does_not_spawn_work(reason): + agent=Agent(AgentConfig(name='provider',network='mock',behavior=AgentBehavior(auto_accept=False))) + tx=SimpleNamespace(id=TX,amount='1000000',deadline=int((datetime.now()+timedelta(hours=1)).timestamp()),requester=PROVIDER,service_description='0x'+'00'*32) + if reason=='processed':agent._processed_jobs.set(TX,True) + if reason=='locked':agent._processing_locks.add(TX) + if reason=='declined': + async def handler(job,ctx):pytest.fail('declined job executed') + agent.provide('echo',handler=handler) + await agent._process_transaction(tx) + assert agent.stats.jobs_received==0 and agent.jobs==[] + if reason!='locked':assert TX not in agent._processing_locks + + +@pytest.mark.asyncio +@pytest.mark.parametrize('fault',['state_read','signer_address','provider_address','missing_setups','setups_unavailable','malformed_setup']) +async def test_delivery_hook_dependency_errors_skip_publish_without_raising(fault,monkeypatch): + monkeypatch.setenv('ACTP_DELIVERY_CHANNEL','v1') + channel=SimpleNamespace(publish_envelope=AsyncMock()) + agent,_=_agent_with_delivery(channel) + if fault=='state_read':agent._client.runtime.get_transaction=AsyncMock(side_effect=ConnectionError('read unavailable')) + elif fault=='signer_address': + class BrokenSigner: + @property + def address(self):raise RuntimeError('signer unavailable') + agent._delivery_signer=BrokenSigner() + elif fault=='provider_address':agent._address='invalid' + else: + from agirails.level1.config import DeliveryServiceConfig + agent._services['echo'].config.delivery=DeliveryServiceConfig(privacy='encrypted') + if fault=='setups_unavailable':channel.get_setups=AsyncMock(side_effect=ConnectionError('relay unavailable')) + if fault=='malformed_setup':channel.get_setups=AsyncMock(return_value=[{'signed':[]}]) + await agent._maybe_publish_delivery_envelope(_job(),{'output':'private'}) + channel.publish_envelope.assert_not_awaited() diff --git a/tests/test_negotiation/test_f5_price_band.py b/tests/test_negotiation/test_f5_price_band.py new file mode 100644 index 0000000..8b18063 --- /dev/null +++ b/tests/test_negotiation/test_f5_price_band.py @@ -0,0 +1,153 @@ +"""F-5: BuyerOrchestrator pre-escrow price-band check (parity with TS).""" + +from __future__ import annotations + +from unittest.mock import Mock + +import pytest + +from agirails.negotiation.buyer_orchestrator import BuyerOrchestrator +from agirails.negotiation.policy_engine import ( + BuyerPolicy, + Constraints, + MaxDailySpend, + MaxUnitPrice, + Negotiation, + Selection, +) +from agirails.protocol.agent_registry import ServiceDescriptor + + +def _policy(task: str = "translation.fr_en") -> BuyerPolicy: + return BuyerPolicy( + task=task, + constraints=Constraints( + max_unit_price=MaxUnitPrice(amount=1.0, currency="USDC", unit="sentence"), + max_daily_spend=MaxDailySpend(amount=100.0, currency="USDC"), + ), + negotiation=Negotiation(rounds_max=3, quote_ttl="5s"), + selection=Selection(min_reputation=50, prioritize=["quality", "price"]), + ) + + +class _FakeRegistry: + """Minimal stand-in for AgentRegistry.get_service_descriptors.""" + + def __init__(self, descriptors, raise_: bool = False) -> None: + self._descriptors = descriptors + self._raise = raise_ + + async def get_service_descriptors(self, address: str): + if self._raise: + raise RuntimeError("rpc down") + return self._descriptors + + +def _band(min_usd: float = 0.5, max_usd: float = 2.0, task: str = "translation.fr_en"): + # service_type_hash is auto-computed from service_type in __post_init__ + return ServiceDescriptor( + service_type=task, + min_price=int(min_usd * 1_000_000), + max_price=int(max_usd * 1_000_000), + ) + + +def _orch(tmp_path, agent_registry): + return BuyerOrchestrator( + policy=_policy(), + runtime=Mock(), + requester_address="0xBuyer", + actp_dir=str(tmp_path), + agent_registry=agent_registry, + ) + + +def _units(usd: float) -> str: + return str(int(usd * 1_000_000)) + + +@pytest.mark.asyncio +async def test_f5_in_band_allows(tmp_path): + orch = _orch(tmp_path, _FakeRegistry([_band()])) + allowed, reason = await orch._check_provider_price_band("0xP", _units(1.0)) + assert allowed is True + assert reason is None + + +@pytest.mark.asyncio +async def test_f5_below_band_rejects(tmp_path): + orch = _orch(tmp_path, _FakeRegistry([_band(min_usd=0.5)])) + allowed, reason = await orch._check_provider_price_band("0xP", _units(0.10)) + assert allowed is False + assert reason is not None and "price band" in reason + + +@pytest.mark.asyncio +async def test_f5_above_band_rejects(tmp_path): + orch = _orch(tmp_path, _FakeRegistry([_band(max_usd=2.0)])) + allowed, reason = await orch._check_provider_price_band("0xP", _units(5.0)) + assert allowed is False + assert reason is not None and "price band" in reason + + +@pytest.mark.asyncio +async def test_f5_no_registry_fails_open(tmp_path): + orch = _orch(tmp_path, None) + allowed, reason = await orch._check_provider_price_band("0xP", _units(99.0)) + assert allowed is True + assert reason is None + + +@pytest.mark.asyncio +async def test_f5_registry_read_error_fails_open(tmp_path): + orch = _orch(tmp_path, _FakeRegistry([], raise_=True)) + allowed, reason = await orch._check_provider_price_band("0xP", _units(99.0)) + assert allowed is True + assert reason is None + + +@pytest.mark.asyncio +async def test_f5_no_matching_descriptor_fails_open(tmp_path): + # registry only publishes a band for a DIFFERENT service → fail-open + orch = _orch(tmp_path, _FakeRegistry([_band(task="summarization")])) + allowed, reason = await orch._check_provider_price_band("0xP", _units(99.0)) + assert allowed is True + assert reason is None + + +@pytest.mark.asyncio +async def test_f5_unparseable_amount_fails_open(tmp_path): + orch = _orch(tmp_path, _FakeRegistry([_band()])) + allowed, reason = await orch._check_provider_price_band("0xP", "not-a-number") + assert allowed is True + assert reason is None + + +@pytest.mark.asyncio +async def test_f5_commit_recheck_rejects_out_of_band_final(tmp_path): + # TS parity: _commit_at_amount re-checks the FINAL negotiated amount before + # accept+link (multi-round counters can land out-of-band). Mirrors TS:1015. + from unittest.mock import AsyncMock + + orch = _orch(tmp_path, _FakeRegistry([_band(min_usd=0.5, max_usd=2.0)])) + orch._transition_state = AsyncMock() + orch._accept_quote = AsyncMock() + orch._link_escrow = AsyncMock() + rounds: list = [] + done, success, reason = await orch._commit_at_amount( + tx_id="0x" + "0" * 64, + amount_base_units=_units(5.0), # above the $0.50-$2.00 band + candidate_slug="prov", + provider_address="0xP", + offer=None, + round_idx=0, + rounds=rounds, + emit=lambda e: None, + source_tag="test", + counter_round=0, + ) + assert done is True + assert success is False + assert "price band" in reason + orch._accept_quote.assert_not_awaited() # rejected before accept + orch._transition_state.assert_awaited_once() # rolled back to CANCELLED diff --git a/tests/test_protocol/test_attestation_release_contract.py b/tests/test_protocol/test_attestation_release_contract.py new file mode 100644 index 0000000..c29f07b --- /dev/null +++ b/tests/test_protocol/test_attestation_release_contract.py @@ -0,0 +1,99 @@ +"""Release validation through real ABI decoding and the real replay tracker.""" + +import time +from eth_abi import encode +import pytest + +from tests.test_protocol.test_local_contract_io import eas, ledger, TX, UID, OTHER, ACCOUNT + +OTHER_TX = '0x' + '44' * 32 + + +def reply_attestation(rpc, *, uid=UID, schema=UID, expiration=0, revocation=0, tx=TX, data=None): + payload = data if data is not None else encode( + ['bytes32','string','bytes32','uint256'], + [bytes.fromhex(tx[2:]), 'bafy-result', bytes.fromhex(TX[2:]), 1700000000], + ) + rpc.reply('getAttestation', ( + bytes.fromhex(uid[2:]), bytes.fromhex(schema[2:]), 1700000000, + expiration, revocation, bytes(32), OTHER, ACCOUNT.address, True, payload, + )) + + +@pytest.mark.asyncio +async def test_release_verifies_actual_attestation_and_records_idempotent_usage(eas): + rpc, helper = eas + reply_attestation(rpc) + result = await helper.get_delivery_attestation(UID) + assert result.transaction_id == TX and result.result_cid == 'bafy-result' + assert await helper.verify_delivery_attestation(TX, UID) is True + assert helper.attestation_tracker.get_usage_for_attestation(UID).lower() == TX.lower() + assert await helper.verify_and_record_for_release(TX, UID) is None + assert rpc.sent == [] + attestation = await helper.get_attestation(UID) + assert attestation.is_valid and not attestation.is_expired and not attestation.is_revoked + assert attestation.to_dict()['isValid'] is True + + +@pytest.mark.asyncio +@pytest.mark.parametrize('fields,message', [ + ({'uid':OTHER_TX}, 'not found'), + ({'schema':OTHER_TX}, 'Schema UID mismatch'), + ({'revocation':1}, 'revoked'), + ({'expiration':1}, 'expired'), + ({'tx':OTHER_TX}, 'txId mismatch'), + ({'data':b'bad'}, 'data format mismatch'), +]) +async def test_release_rejects_invalid_attestation_without_recording_or_sending(eas, fields, message): + rpc, helper = eas + reply_attestation(rpc, **fields) + with pytest.raises(ValueError, match=message): + await helper.verify_and_record_for_release(TX, UID) + assert helper.attestation_tracker.get_usage_for_attestation(UID) is None + assert rpc.sent == [] + + +@pytest.mark.asyncio +async def test_release_rejects_previously_recorded_other_transaction(eas): + rpc, helper = eas + reply_attestation(rpc) + await helper.attestation_tracker.record_usage(UID, OTHER_TX) + with pytest.raises(ValueError, match='replay'): + await helper.verify_delivery_attestation(TX, UID) + assert helper.attestation_tracker.get_usage_for_attestation(UID) == OTHER_TX + assert rpc.sent == [] + + +@pytest.mark.asyncio +async def test_release_rechecks_atomic_record_result(eas, monkeypatch): + rpc, helper = eas + reply_attestation(rpc) + async def lose_race(uid, tx): + await original(uid, OTHER_TX) + return False + original = helper.attestation_tracker.record_usage + monkeypatch.setattr(helper.attestation_tracker, 'record_usage', lose_race) + with pytest.raises(ValueError, match='replay'): + await helper.verify_delivery_attestation(TX, UID) + assert helper.attestation_tracker.get_usage_for_attestation(UID) == OTHER_TX + + +@pytest.mark.asyncio +@pytest.mark.parametrize('tx,uid', [('bad',UID), (TX,'bad'), ('',UID), (TX,'')]) +async def test_release_validates_identifiers_before_rpc(eas, tx, uid): + rpc, helper = eas + before = len(rpc.calls) + with pytest.raises(ValueError, match='format'): + await helper.verify_delivery_attestation(tx, uid) + assert len(rpc.calls) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize('expiration,revocation,valid', [(0,1,False), (1,0,False), (0,0,True)]) +async def test_attestation_lifetime_properties(eas, expiration, revocation, valid): + rpc, helper = eas + reply_attestation(rpc, expiration=expiration, revocation=revocation) + attestation = await helper.get_attestation(UID) + assert attestation.is_valid is valid + assert attestation.is_revoked is (revocation > 0) + assert attestation.is_expired is (0 < expiration < time.time()) diff --git a/tests/test_protocol/test_event_chunking_4_8_0.py b/tests/test_protocol/test_event_chunking_4_8_0.py index d748a05..322f61c 100644 --- a/tests/test_protocol/test_event_chunking_4_8_0.py +++ b/tests/test_protocol/test_event_chunking_4_8_0.py @@ -63,12 +63,12 @@ def __init__(self, cap: int, logs_at: dict[int, list]): self.logs_at = logs_at # from_block -> logs for single-block windows self.calls: list[tuple[int, int]] = [] - def create_filter(self, *, fromBlock: int, toBlock: int): - self.calls.append((fromBlock, toBlock)) - span = toBlock - fromBlock + 1 + async def create_filter(self, *, from_block: int, to_block: int): + self.calls.append((from_block, to_block)) + span = to_block - from_block + 1 entries = [] if span <= self.cap: - for b in range(fromBlock, toBlock + 1): + for b in range(from_block, to_block + 1): entries.extend(self.logs_at.get(b, [])) async def get_all_entries(): @@ -96,9 +96,9 @@ async def test_single_block_range_error_propagates(self): monitor = _make_monitor() event = MagicMock() - event.create_filter.return_value = MagicMock( + event.create_filter = AsyncMock(return_value=MagicMock( get_all_entries=AsyncMock(side_effect=Exception("block range too large")) - ) + )) # from_block == to_block → cannot split → genuine error re-raised. with pytest.raises(Exception) as exc_info: @@ -109,9 +109,9 @@ async def test_non_range_error_propagates_without_splitting(self): monitor = _make_monitor() event = MagicMock() - event.create_filter.return_value = MagicMock( + event.create_filter = AsyncMock(return_value=MagicMock( get_all_entries=AsyncMock(side_effect=Exception("connection refused")) - ) + )) with pytest.raises(Exception) as exc_info: await monitor._query_logs_chunked(event, 0, 1000) @@ -129,13 +129,13 @@ class TestQueryEventLogs: async def test_string_bounds_skip_chunking(self): monitor = _make_monitor() event = MagicMock() - event.create_filter.return_value = MagicMock( + event.create_filter = AsyncMock(return_value=MagicMock( get_all_entries=AsyncMock(return_value=["x"]) - ) + )) logs = await monitor._query_event_logs(event, "earliest", "latest") assert logs == ["x"] - event.create_filter.assert_called_once_with(fromBlock="earliest", toBlock="latest") + event.create_filter.assert_awaited_once_with(from_block="earliest", to_block="latest") async def test_numeric_bounds_use_chunked_path(self): monitor = _make_monitor() diff --git a/tests/test_protocol/test_event_lifecycle.py b/tests/test_protocol/test_event_lifecycle.py new file mode 100644 index 0000000..06f1159 --- /dev/null +++ b/tests/test_protocol/test_event_lifecycle.py @@ -0,0 +1,170 @@ +"""Public event streams, filters, recovery cursors and cancellable subscriptions.""" + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from agirails.config.networks import BASE_SEPOLIA +from agirails.protocol.events import EventFilter, EventType +from tests.test_protocol.test_event_monitor_layouts import setup_monitor, add_logs, TX_ID, REQUESTER, PROVIDER + + +def advance_blocks(provider, monkeypatch): + original=provider.make_request + count=[0] + async def rpc(method,params): + if method == 'eth_blockNumber': + count[0]+=1 + return {'jsonrpc':'2.0','id':1,'result':hex(9 if count[0]==1 else 12)} + return await original(method,params) + monkeypatch.setattr(provider,'make_request',rpc) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('kind,expected', [('watch_transactions',EventType.TRANSACTION_CREATED),('watch_escrows',EventType.ESCROW_CREATED)]) +async def test_public_stream_reads_actual_abi_logs_and_closes(kind,expected,monkeypatch): + monitor,provider,_=setup_monitor(BASE_SEPOLIA,'config') + add_logs(provider,False) + advance_blocks(provider,monkeypatch) + stream=getattr(monitor,kind)(requester=REQUESTER.lower(),provider=PROVIDER.lower(),poll_interval=0.001) + try: + event=await asyncio.wait_for(stream.__anext__(),timeout=1) + assert event.event_type == expected and event.amount == 50000 + assert event.requester == REQUESTER and event.provider == PROVIDER + finally: + await stream.aclose() + assert all(query['fromBlock']=='0xa' for query,_,_ in provider.filters.values()) + + +@pytest.mark.asyncio +async def test_subscription_callback_receives_ordered_logs_and_cancellation_stops_reads(monkeypatch): + monitor,provider,_=setup_monitor(BASE_SEPOLIA,'config') + add_logs(provider,False) + advance_blocks(provider,monkeypatch) + seen=[];ready=asyncio.Event() + def receive(event): + seen.append(event) + if len(seen)==3:ready.set() + task=await monitor.subscribe(receive,poll_interval=0.001) + try: + await asyncio.wait_for(ready.wait(),1) + finally: + task.cancel();await task + before=len(provider.requests) + await asyncio.sleep(0.003) + assert len(provider.requests)==before + assert [event.event_type for event in seen]==[EventType.TRANSACTION_CREATED,EventType.STATE_TRANSITIONED,EventType.ESCROW_CREATED] + assert [event.block_number for event in seen]==[10,11,12] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('field,value,expected', [ + ('transaction_id','0x'+TX_ID.hex(),3),('transaction_id','0x'+'ff'*32,1), + ('escrow_id','0x'+'88'*32,3),('escrow_id','0x'+'ff'*32,2), + ('requester',REQUESTER.lower(),3),('requester','0x'+'ff'*20,1), + ('provider',PROVIDER.lower(),3),('provider','0x'+'ff'*20,1), + ('event_types',[EventType.ESCROW_CREATED],1), +]) +async def test_event_filters_reject_nonmatching_fields_without_dropping_unrelated_shapes(field,value,expected): + monitor,provider,_=setup_monitor(BASE_SEPOLIA,'config') + add_logs(provider,False) + events=await monitor.get_events(EventFilter(**{field:value}),from_block=10,to_block=12) + assert len(events)==expected + for event in events: + wire=event.to_dict() + assert wire['eventType']==event.event_type.value + assert wire['blockNumber'] in (10,11,12) + + +class AdvancingEth: + def __init__(self):self.height=9 + @property + def block_number(self): + async def read(): + self.height+=1 + return self.height + return read() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('method,kind', [('on_dispute_split_recorded','split'),('on_uma_dispute_escalated','uma'),('on_disputed_to_cancelled','state')]) +async def test_dispute_subscriptions_recover_failed_read_and_do_not_advance_cursor(method,kind,monkeypatch): + monitor,_,_=setup_monitor(BASE_SEPOLIA,'config') + monitor.w3=SimpleNamespace(eth=AdvancingEth()) + monitor.mediator_contract=SimpleNamespace(events=SimpleNamespace(DisputeSplitRecorded=object())) + monitor.bond_escalation_contract=SimpleNamespace(events=SimpleNamespace(UMADisputeEscalated=object())) + args={'txId':bytes.fromhex('44'*32),'requester':REQUESTER,'provider':PROVIDER,'splitBps':4500} if kind=='split' else {'disputeId':bytes.fromhex('44'*32),'assertionId':bytes.fromhex('55'*32)} if kind=='uma' else {'transactionId':TX_ID,'oldState':6,'newState':7,'triggeredBy':PROVIDER} + log={'address':PROVIDER,'blockNumber':12,'transactionHash':bytes.fromhex('66'*32),'logIndex':0,'args':args} + query=AsyncMock(side_effect=[ConnectionError('temporary'),[log]]) + monkeypatch.setattr(monitor,'_query_event_logs',query) + ready=asyncio.Event();seen=[] + def receive(event):seen.append(event);ready.set() + task=await getattr(monitor,method)(receive,poll_interval=0.001) + try: + await asyncio.wait_for(ready.wait(),1) + finally: + task.cancel();await task + assert len(seen)==1 + assert query.await_args_list[0].args[1:]==(11,11) + assert query.await_args_list[1].args[1:]==(11,12) + wire=seen[0].to_dict() + assert wire['blockNumber']==12 + assert wire['eventType']=={'split':'DisputeSplitRecorded','uma':'UMADisputeEscalated','state':'StateTransitioned'}[kind] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('method',['on_dispute_split_recorded','on_uma_dispute_escalated']) +async def test_dispute_subscription_requires_configured_contract(method): + monitor,_,_=setup_monitor(BASE_SEPOLIA,'direct') + with pytest.raises(ValueError,match='without'): + await getattr(monitor,method)(lambda event:None) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('kind,count',[('watch_transactions',3),('watch_escrows',1)]) +async def test_event_stream_retries_failed_read_and_responds_to_cancellation(kind,count,monkeypatch): + monitor,provider,_=setup_monitor(BASE_SEPOLIA,'config') + add_logs(provider,False) + advance_blocks(provider,monkeypatch) + original=provider.make_request + failed=[False] + async def rpc(method,params): + if method=='eth_getFilterLogs' and not failed[0]: + failed[0]=True + raise ConnectionError('transient read failure') + return await original(method,params) + monkeypatch.setattr(provider,'make_request',rpc) + stream=getattr(monitor,kind)(poll_interval=0.001) + try: + events=[await asyncio.wait_for(stream.__anext__(),1) for _ in range(count)] + assert failed[0] and len(events)==count + next_event=asyncio.create_task(stream.__anext__()) + await asyncio.sleep(0) + next_event.cancel() + with pytest.raises(StopAsyncIteration):await next_event + finally:await stream.aclose() + + +@pytest.mark.asyncio +async def test_callback_subscription_recovers_before_first_callback(monkeypatch): + monitor,provider,_=setup_monitor(BASE_SEPOLIA,'config') + add_logs(provider,False) + advance_blocks(provider,monkeypatch) + original=provider.make_request + failed=[False] + async def rpc(method,params): + if method=='eth_getFilterLogs' and not failed[0]: + failed[0]=True + raise ConnectionError('transient read failure') + return await original(method,params) + monkeypatch.setattr(provider,'make_request',rpc) + ready=asyncio.Event();seen=[] + def receive(event): + seen.append(event) + if len(seen)==3:ready.set() + task=await monitor.subscribe(receive,poll_interval=0.001) + try:await asyncio.wait_for(ready.wait(),1) + finally:task.cancel();await task + assert failed[0] and [event.block_number for event in seen]==[10,11,12] diff --git a/tests/test_protocol/test_event_monitor_layouts.py b/tests/test_protocol/test_event_monitor_layouts.py new file mode 100644 index 0000000..dfa2811 --- /dev/null +++ b/tests/test_protocol/test_event_monitor_layouts.py @@ -0,0 +1,242 @@ +"""Descriptor compatibility through real AsyncWeb3 filter encoding and decoding.""" + +from unittest.mock import AsyncMock + +import pytest +from eth_abi import encode +from eth_utils.abi import event_abi_to_log_topic +from web3 import AsyncWeb3, Web3 +from web3.providers import AsyncBaseProvider + +from agirails.config.networks import BASE_MAINNET, BASE_SEPOLIA +from agirails.protocol.events import EventMonitor +from agirails.protocol.kernel import ACTPKernel +from agirails.runtime.blockchain_runtime import BlockchainRuntime +from tests.test_runtime.test_subscribe_provider_jobs_4_8_0 import _mock_tx + +REQUESTER = Web3.to_checksum_address("0x" + "11" * 20) +PROVIDER = Web3.to_checksum_address("0x" + "22" * 20) +TX_ID = bytes.fromhex("33" * 32) +AGREEMENT = bytes.fromhex("44" * 32) + + +def event_abi(filename, name, legacy=False): + item = next( + x + for x in EventMonitor._load_abi(filename) + if x.get("type") == "event" and x["name"] == name + ) + if legacy: + item = {**item, "inputs": [x for x in item["inputs"] if x["name"] != "agreementHash"]} + return item + + +def raw_log(abi, address, values, block, index): + indexed = [x for x in abi["inputs"] if x["indexed"]] + plain = [x for x in abi["inputs"] if not x["indexed"]] + return { + "address": Web3.to_checksum_address(address), + "topics": [Web3.to_hex(event_abi_to_log_topic(abi))] + + [Web3.to_hex(encode([x["type"]], [values[x["name"]]])) for x in indexed], + "data": Web3.to_hex(encode([x["type"] for x in plain], [values[x["name"]] for x in plain])), + "blockNumber": hex(block), + "transactionHash": "0x" + "55" * 32, + "transactionIndex": "0x0", + "blockHash": "0x" + "66" * 32, + "logIndex": hex(index), + "removed": False, + } + + +class LocalLogs(AsyncBaseProvider): + def __init__(self, config, cap=None): + super().__init__() + self.config = config + self.cap = cap + self.requests = [] + self.filters = {} + self.logs = [] + self.fail_reads = False + + async def make_request(self, method, params): + self.requests.append((method, params)) + if method == "eth_chainId": + result = hex(self.config.chain_id) + elif method == "eth_blockNumber": + result = "0xc" + elif method == "eth_newFilter": + query = params[0] + lower = int(query["fromBlock"], 16) if str(query["fromBlock"]).startswith("0x") else 0 + upper = int(query["toBlock"], 16) if str(query["toBlock"]).startswith("0x") else 12 + if self.cap and upper - lower + 1 > self.cap: + return { + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32005, "message": "block range too wide"}, + } + result = hex(len(self.filters) + 1) + self.filters[result] = (query, lower, upper) + elif method == "eth_getFilterLogs": + if self.fail_reads: + raise ConnectionError("local fixture unavailable") + query, lower, upper = self.filters[params[0]] + addresses = ( + query["address"] if isinstance(query["address"], list) else [query["address"]] + ) + topic = query["topics"][0] + result = [ + x + for x in self.logs + if x["address"].lower() in [a.lower() for a in addresses] + and x["topics"][0].lower() == topic.lower() + and lower <= int(x["blockNumber"], 16) <= upper + ] + else: + raise AssertionError("Unexpected RPC operation: " + method) + return {"jsonrpc": "2.0", "id": 1, "result": result} + + +def setup_monitor(config, factory, cap=None): + provider = LocalLogs(config, cap) + w3 = AsyncWeb3(provider) + if factory == "config": + monitor = EventMonitor.from_config(w3, config) + else: + escrow = w3.eth.contract( + address=w3.to_checksum_address(config.contracts.escrow_vault), + abi=EventMonitor._load_abi("escrow_vault.json"), + ) + if factory == "wrapped": + account = w3.eth.account.from_key("0x" + "01" * 32) + kernel = ACTPKernel.from_config(w3, account, config).contract + else: + kernel = w3.eth.contract( + address=w3.to_checksum_address(config.contracts.actp_kernel), + abi=EventMonitor._load_abi("actp_kernel.json"), + ) + monitor = EventMonitor(kernel, escrow, w3) + return monitor, provider, w3 + + +def add_logs(provider, legacy): + created = event_abi("actp_kernel.json", "TransactionCreated", legacy) + provider.logs = [ + raw_log( + created, + provider.config.contracts.actp_kernel, + { + "transactionId": TX_ID, + "requester": REQUESTER, + "provider": PROVIDER, + "amount": 50000, + "serviceHash": bytes.fromhex("77" * 32), + "deadline": 9999999999, + "timestamp": 1700000000, + "agentId": 42, + "agreementHash": AGREEMENT, + }, + 10, + 0, + ), + raw_log( + event_abi("actp_kernel.json", "StateTransitioned"), + provider.config.contracts.actp_kernel, + { + "transactionId": TX_ID, + "oldState": 0, + "newState": 1, + "triggeredBy": PROVIDER, + "timestamp": 1700000001, + }, + 11, + 0, + ), + raw_log( + event_abi("escrow_vault.json", "EscrowCreated"), + provider.config.contracts.escrow_vault, + { + "escrowId": bytes.fromhex("88" * 32), + "requester": REQUESTER, + "provider": PROVIDER, + "amount": 50000, + }, + 12, + 0, + ), + ] + return created + + +@pytest.mark.asyncio +@pytest.mark.parametrize("config,legacy", [(BASE_MAINNET, True), (BASE_SEPOLIA, False)]) +@pytest.mark.parametrize("factory", ["config", "direct", "wrapped"]) +async def test_factory_selects_descriptor_event_topic_without_mutating_packaged_abi( + config, legacy, factory +): + monitor, _, _ = setup_monitor(config, factory) + selected = next(x for x in monitor.kernel_contract.abi if x.get("name") == "TransactionCreated") + assert event_abi_to_log_topic(selected) == event_abi_to_log_topic( + event_abi("actp_kernel.json", "TransactionCreated", legacy) + ) + assert len(event_abi("actp_kernel.json", "TransactionCreated")["inputs"]) == 9 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("config,legacy", [(BASE_MAINNET, True), (BASE_SEPOLIA, False)]) +@pytest.mark.parametrize("factory", ["config", "direct", "wrapped"]) +@pytest.mark.parametrize("bounds", [(10, 12), ("earliest", "latest")]) +async def test_actual_encoded_logs_survive_get_events_and_other_events( + config, legacy, factory, bounds +): + monitor, provider, _ = setup_monitor(config, factory) + created_abi = add_logs(provider, legacy) + events = await monitor.get_events(from_block=bounds[0], to_block=bounds[1]) + assert [x.event_type.value for x in events] == [ + "TransactionCreated", + "StateTransitioned", + "EscrowCreated", + ] + created, state, escrow = events + assert created.transaction_id == "0x" + TX_ID.hex() + assert ( + created.requester == REQUESTER and created.provider == PROVIDER and created.amount == 50000 + ) + assert created.raw_data["agentId"] == 42 and created.raw_data["serviceHash"] == bytes.fromhex( + "77" * 32 + ) + assert created.raw_data.get("agreementHash") == (None if legacy else AGREEMENT) + assert ( + state.actor == PROVIDER and state.previous_state.value == 0 and state.new_state.value == 1 + ) + assert escrow.amount == 50000 and escrow.provider == PROVIDER + queried_topics = [ + p[0]["topics"][0] for method, p in provider.requests if method == "eth_newFilter" + ] + assert Web3.to_hex(event_abi_to_log_topic(created_abi)) in queried_topics + + +@pytest.mark.asyncio +@pytest.mark.parametrize("config,legacy", [(BASE_MAINNET, True), (BASE_SEPOLIA, False)]) +@pytest.mark.parametrize("factory", ["config", "direct", "wrapped"]) +async def test_provider_discovery_uses_real_encoded_event_monitor(config, legacy, factory): + monitor, provider, w3 = setup_monitor(config, factory) + add_logs(provider, legacy) + runtime = BlockchainRuntime.__new__(BlockchainRuntime) + runtime.events, runtime.w3 = monitor, w3 + tx = _mock_tx("0x" + TX_ID.hex(), provider=PROVIDER) + runtime.get_transaction = AsyncMock(return_value=tx) + assert await runtime.get_transactions_by_provider(PROVIDER.lower()) == [tx] + runtime.get_transaction.assert_awaited_once_with("0x" + TX_ID.hex()) + assert await runtime.get_transactions_by_provider("0x" + "99" * 20) == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("config,legacy", [(BASE_MAINNET, True), (BASE_SEPOLIA, False)]) +async def test_real_async_filters_preserve_chunking_and_rpc_failure(config, legacy): + monitor, provider, _ = setup_monitor(config, "config", cap=1) + add_logs(provider, legacy) + events = await monitor.get_events(from_block=10, to_block=12) + assert len(events) == 3 + provider.fail_reads = True + with pytest.raises(ConnectionError, match="local fixture unavailable"): + await monitor.get_events(from_block=10, to_block=10) diff --git a/tests/test_protocol/test_kernel_parity_4_8_0.py b/tests/test_protocol/test_kernel_parity_4_8_0.py index e4a7f7c..4ba7156 100644 --- a/tests/test_protocol/test_kernel_parity_4_8_0.py +++ b/tests/test_protocol/test_kernel_parity_4_8_0.py @@ -213,12 +213,10 @@ async def test_falls_back_to_legacy_abi_on_decode_failure(self): primary_fn.call = AsyncMock(side_effect=Exception("Could not decode contract function call")) kernel.contract.functions.getTransaction.return_value = primary_fn - # Legacy contract returns the 16-field tuple. - legacy_contract = MagicMock() - legacy_fn = MagicMock() - legacy_fn.call = AsyncMock(return_value=_legacy_tuple()) - legacy_contract.functions.getTransaction.return_value = legacy_fn - kernel.w3.eth.contract = MagicMock(return_value=legacy_contract) + # Feed actual ABI bytes through the exact-length fallback decoder. + from eth_abi import encode + types = '(bytes32,address,address,uint8,uint256,uint256,uint256,uint256,bytes32,address,bytes32,bytes32,uint256,bytes32,uint16,uint256)' + kernel.w3.eth.call = AsyncMock(return_value=encode([types], [_legacy_tuple()])) view = await kernel.get_transaction("0x" + "9" * 64) diff --git a/tests/test_protocol/test_kernel_parity_4_9_0.py b/tests/test_protocol/test_kernel_parity_4_9_0.py new file mode 100644 index 0000000..ba43587 --- /dev/null +++ b/tests/test_protocol/test_kernel_parity_4_9_0.py @@ -0,0 +1,122 @@ +"""Parity tests for the 4.9.0 additions against TS SDK. + +Covers: + 1. F-6 recovery helpers: ``recovery_grace``, ``get_recovery_deadline``, + ``recover_stalled_in_progress`` (PARITY: TS ACTPKernel F-6 helpers). + 2. SDK-2: ``RequestResult.transaction.escrow_id`` requester-side escrow + visibility (PARITY: TS RequestResult). +""" + +from __future__ import annotations + +import time +from unittest.mock import AsyncMock, MagicMock + +from agirails.level0.request import RequestResult +from agirails.protocol.kernel import ACTPKernel, TransactionView +from agirails.types.transaction import TransactionState + + +REQUESTER = "0x" + "1" * 40 +PROVIDER = "0x" + "2" * 40 +TX_ID = "0x" + "0" * 64 + + +def _make_kernel() -> ACTPKernel: + contract = MagicMock() + contract.address = "0x" + "c" * 40 + account = MagicMock() + account.address = REQUESTER + account.key = b"\x01" * 32 + w3 = MagicMock() + w3.to_checksum_address = lambda a: a + return ACTPKernel(contract, account, w3, chain_id=84532) + + +def _make_view(deadline: int) -> TransactionView: + return TransactionView( + transaction_id=TX_ID, + requester=REQUESTER, + provider=PROVIDER, + state=TransactionState.IN_PROGRESS, + amount=1_000_000, + created_at=int(time.time()), + updated_at=int(time.time()), + deadline=deadline, + service_hash="0x" + "0" * 64, + escrow_contract="0x" + "0" * 40, + escrow_id="0x" + "0" * 64, + attestation_uid="0x" + "0" * 64, + dispute_window=172800, + metadata="0x" + "0" * 64, + platform_fee_bps_locked=100, + ) + + +class TestF6RecoveryHelpers: + async def test_recovery_grace_reads_kernel(self): + kernel = _make_kernel() + kernel.contract.functions.recoveryGrace.return_value.call = AsyncMock( + return_value=3600 + ) + assert await kernel.recovery_grace() == 3600 + + async def test_get_recovery_deadline_is_deadline_plus_grace(self): + kernel = _make_kernel() + deadline = int(time.time()) + 3600 + kernel.get_transaction = AsyncMock(return_value=_make_view(deadline)) + kernel.recovery_grace = AsyncMock(return_value=7200) + assert await kernel.get_recovery_deadline(TX_ID) == deadline + 7200 + + async def test_recover_stalled_in_progress_builds_and_sends(self): + kernel = _make_kernel() + contract_fn = MagicMock() + contract_fn.build_transaction = AsyncMock(return_value={"to": "0x"}) + kernel.contract.functions.recoverStalledInProgress.return_value = contract_fn + kernel._estimate_gas = AsyncMock(return_value=150_000) + kernel._build_tx_params = AsyncMock(return_value={}) + sentinel = object() + kernel._sign_and_send = AsyncMock(return_value=MagicMock()) + kernel._to_receipt = MagicMock(return_value=sentinel) + + result = await kernel.recover_stalled_in_progress(TX_ID) + + assert result is sentinel + kernel.contract.functions.recoverStalledInProgress.assert_called_once() + kernel._sign_and_send.assert_awaited_once() + + +class TestSDK2EscrowId: + def test_escrow_id_passthrough(self): + r = RequestResult.from_delivery( + output={"ok": True}, + tx_id=TX_ID, + provider=PROVIDER, + budget=1.0, + duration=10, + proof="", + escrow_id="0xESCROW", + ) + assert r.transaction.escrow_id == "0xESCROW" + + def test_escrow_id_defaults_none(self): + r = RequestResult.from_delivery( + output={"ok": True}, + tx_id=TX_ID, + provider=PROVIDER, + budget=1.0, + duration=10, + proof="", + ) + assert r.transaction.escrow_id is None + + +class TestReadOnlyRegistryConnect: + async def test_connect_builds_read_only_registry(self): + # Read-only factory used by the negotiate CLI to wire the F-5 guard. + # Construction is lazy (no network I/O), so this is fast + offline. + from agirails.protocol.agent_registry import AgentRegistry + + reg = await AgentRegistry.connect("base-sepolia") + assert reg._account is None # read-only: no signer + assert hasattr(reg, "get_service_descriptors") diff --git a/tests/test_protocol/test_kernel_return_layouts.py b/tests/test_protocol/test_kernel_return_layouts.py new file mode 100644 index 0000000..1b8727b --- /dev/null +++ b/tests/test_protocol/test_kernel_return_layouts.py @@ -0,0 +1,35 @@ +"""Real web3/eth_abi decoding of historical static return layouts; no network.""" +import pytest +from eth_abi import encode +from web3 import AsyncWeb3 +from web3.providers.async_base import AsyncBaseProvider +from unittest.mock import MagicMock +from agirails.protocol.kernel import ACTPKernel + +V3='bytes32,address,address,uint8,uint256,uint256,uint256,uint256,bytes32,address,bytes32,bytes32,uint256,bytes32,uint16,uint16,uint16,uint256,uint256,address,uint256' +A='0x'+'11'*20; Z=b'\0'*32; ID=b'\1'*32 +VALUES=[ID,A,A,1,1000000,1,1,2,Z,A,Z,Z,3600,Z,100,500,1000,42,7,A,50000] +class EncodedProvider(AsyncBaseProvider): + def __init__(self,raw):super().__init__();self.raw=raw + async def make_request(self,method,params):return {'jsonrpc':'2.0','id':1,'result':'0x'+self.raw.hex() if method=='eth_call' else '0x7a69'} + async def is_connected(self,show_traceback=False):return True + +def kernel(raw): + w=AsyncWeb3(EncodedProvider(raw));c=w.eth.contract(address=AsyncWeb3.to_checksum_address('0x'+'cc'*20),abi=ACTPKernel._load_abi());a=MagicMock();a.address=A + return ACTPKernel(c,a,w,31337) + +@pytest.mark.parametrize('suffix',[False,True]) +async def test_v3_and_candidate_keep_economic_and_identity_fields(suffix): + raw=encode(['('+V3+(',bytes32,bytes32' if suffix else '')+')'],[VALUES+([Z,Z] if suffix else [])]) + tx=await kernel(raw).get_transaction('0x'+ID.hex()) + assert (tx.agent_id,tx.requester_agent_id,tx.requester_penalty_bps_locked,tx.dispute_bond_bps_locked,tx.dispute_bond)==(42,7,500,1000,50000) + +async def test_legacy_keeps_its_actual_agent_id(): + types=V3.split(',')[:15]+['uint256'];values=VALUES[:15]+[42] + tx=await kernel(encode(['('+','.join(types)+')'],[values])).get_transaction('0x'+ID.hex()) + assert tx.agent_id==42 and tx.dispute_bond==0 + +@pytest.mark.parametrize('words',[17,19,20,22]) +async def test_unknown_historical_layout_fails_loudly(words): + with pytest.raises(Exception,match='Unsupported getTransaction return size'): + await kernel(b'\0'*(words*32)).get_transaction('0x'+ID.hex()) diff --git a/tests/test_protocol/test_local_contract_io.py b/tests/test_protocol/test_local_contract_io.py new file mode 100644 index 0000000..471a1f8 --- /dev/null +++ b/tests/test_protocol/test_local_contract_io.py @@ -0,0 +1,208 @@ +"""Real ABI encoding/decoding and signatures over a controlled JSON-RPC ledger.""" + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +import pytest_asyncio +from eth_abi import decode +from eth_account import Account +from web3 import AsyncWeb3, Web3 + +from agirails.config.networks import BASE_SEPOLIA +from agirails.protocol.eas import EAS_ABI, SCHEMA_REGISTRY_ABI, EASHelper +from agirails.protocol.escrow import CreateEscrowParams, EscrowVault +from agirails.protocol.nonce import NonceManager, NonceManagerPool +from tests.helpers.contract_rpc import ContractRPC + +TX = "0x" + "ab" * 32 +UID = "0x" + "cd" * 32 +OTHER = Web3.to_checksum_address("0x" + "22" * 20) +ACCOUNT = Account.from_key("0x" + "11" * 32) + + +@pytest_asyncio.fixture +async def ledger(): + rpc = ContractRPC() + return rpc, AsyncWeb3(rpc) + + +@pytest.fixture +def escrow(ledger): + rpc, w3 = ledger + vault = EscrowVault.from_config(w3, ACCOUNT, BASE_SEPOLIA) + rpc.register(vault.contract.abi) + rpc.register(vault.usdc_contract.abi) + return rpc, vault + + +@pytest.mark.asyncio +@pytest.mark.parametrize("approve", [False, True]) +async def test_create_escrow_sends_exact_principal_and_distinct_transactions(escrow, approve): + rpc, vault = escrow + params = CreateEscrowParams(ACCOUNT.address, OTHER, 1_250_000, TX) + assert await vault.create_escrow(params, auto_approve=approve) == TX + assert [x[0] for x in rpc.sent] == (["approve", "createEscrow"] if approve else ["createEscrow"]) + assert rpc.sent[-1][1] == (bytes.fromhex(TX[2:]), ACCOUNT.address.lower(), OTHER.lower(), 1_250_000) + if approve: + assert rpc.sent[0][1] == (vault.contract.address.lower(), 1_250_000) + assert all(Account.recover_transaction(raw) == ACCOUNT.address for _, _, raw in rpc.sent) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method,wire,amount", [ + ("payout", "payout", 250_000), + ("payout_to_provider", "payoutToProvider", 350_000), + ("refund_to_requester", "refundToRequester", 450_000), +]) +async def test_payout_writes_encode_recipient_amount_and_return_receipt(escrow, method, wire, amount): + rpc, vault = escrow + args = [TX, OTHER, amount] if method == "payout" else [TX, amount] + paid, receipt = await getattr(vault, method)(*args) + assert paid == amount + assert receipt.success is True + assert receipt.gas_used == 50_000 + assert rpc.sent[0][0] == wire + assert rpc.sent[0][1][-1] == amount + assert rpc.sent[0][1][0] == bytes.fromhex(TX[2:]) + assert Account.recover_transaction(rpc.sent[0][2]) == ACCOUNT.address + + +@pytest.mark.asyncio +async def test_escrow_queries_decode_accounting_and_contract_addresses(escrow): + rpc, vault = escrow + rpc.reply("escrows", ACCOUNT.address, OTHER, 1_000_000, 250_000, True) + rpc.reply("remaining", 750_000) + rpc.reply("verifyEscrow", True, 750_000) + rpc.reply("balanceOf", 5_000_000) + rpc.reply("allowance", 2_000_000) + rpc.reply("token", BASE_SEPOLIA.contracts.usdc) + rpc.reply("kernel", BASE_SEPOLIA.contracts.actp_kernel) + info = await vault.get_escrow(TX) + assert info.to_dict()["remainingUsdc"] == 0.75 + assert info.amount_usdc == 1 + assert await vault.get_remaining(TX) == 750_000 + assert await vault.verify_escrow(TX, ACCOUNT.address, OTHER, 1_000_000) == (True, 750_000) + assert await vault.get_usdc_balance() == 5_000_000 + assert await vault.get_usdc_balance(OTHER) == 5_000_000 + assert await vault.get_usdc_allowance() == 2_000_000 + assert await vault.get_usdc_allowance(OTHER, ACCOUNT.address) == 2_000_000 + assert (await vault.get_token_address()).lower() == BASE_SEPOLIA.contracts.usdc.lower() + assert (await vault.get_kernel_address()).lower() == BASE_SEPOLIA.contracts.actp_kernel.lower() + + +@pytest.fixture +def eas(ledger): + rpc, w3 = ledger + rpc.register(EAS_ABI) + rpc.register(SCHEMA_REGISTRY_ABI) + helper = EASHelper( + w3.eth.contract(address=BASE_SEPOLIA.contracts.eas, abi=EAS_ABI), + w3.eth.contract(address=BASE_SEPOLIA.contracts.eas_schema_registry, abi=SCHEMA_REGISTRY_ABI), + ACCOUNT, w3, 84532, UID, + ) + rpc.logs = [{ + "address": BASE_SEPOLIA.contracts.eas, "topics": ["0x" + "ef" * 32, UID], + "data": "0x", "blockNumber": "0xa", "transactionHash": TX, + "transactionIndex": "0x0", "blockHash": "0x" + "bb" * 32, + "logIndex": "0x0", "removed": False, + }] + return rpc, helper + + +@pytest.mark.asyncio +@pytest.mark.parametrize("version", ["aip4", "aip6"]) +async def test_delivery_attestation_serializes_the_schema_and_signed_data(eas, version): + rpc, helper = eas + if version == "aip4": + uid = await helper.create_delivery_attestation_aip4(TX, TX, OTHER) + else: + uid = await helper.create_delivery_attestation(TX, "bafy-delivery", TX) + assert uid == UID + name, args, raw = rpc.sent[-1] + assert name == "attest" + assert args[0][0] == bytes.fromhex(UID[2:]) + recipient, expiry, revocable, ref, payload, value = args[0][1] + assert recipient == (OTHER if version == "aip4" else ACCOUNT.address).lower() + assert (expiry, revocable, ref, value) == (0, True, bytes(32), 0) + types = ["bytes32", "bytes32", "address", "uint64"] if version == "aip4" else ["bytes32", "string", "bytes32", "uint256"] + fields = decode(types, payload) + assert fields[0] == bytes.fromhex(TX[2:]) + assert fields[1] == (bytes.fromhex(TX[2:]) if version == "aip4" else "bafy-delivery") + assert Account.recover_transaction(raw) == ACCOUNT.address + + +@pytest.mark.asyncio +async def test_eas_schema_revocation_and_reads_preserve_wire_values(eas): + rpc, helper = eas + assert await helper.register_schema("bytes32 resultHash") == UID + assert rpc.sent[-1][0] == "register" + assert rpc.sent[-1][1][0] == "bytes32 resultHash" + receipt = await helper.revoke_attestation(UID) + assert receipt.success is True + assert rpc.sent[-1][0] == "revoke" + rpc.reply("isAttestationValid", False) + assert await helper.is_attestation_valid(UID) is False + rpc.reply("getSchema", (bytes.fromhex(UID[2:]), OTHER, True, "bytes32 resultHash")) + schema = await helper.get_schema(UID) + assert schema.uid == UID + assert schema.revocable is True + assert schema.schema == "bytes32 resultHash" + + +@pytest.mark.asyncio +async def test_eas_absent_uid_and_missing_receipt_events_fail_explicitly(eas): + rpc, helper = eas + rpc.logs = [] + with pytest.raises(ValueError, match="extract attestation UID"): + await helper.create_delivery_attestation(TX, "bafy-result", TX) + with pytest.raises(ValueError, match="extract schema UID"): + await helper.register_schema("bytes32 resultHash") + helper._delivery_schema_uid = "" + with pytest.raises(ValueError, match="not configured"): + await helper.create_delivery_attestation(TX, "bafy-result", TX) + with pytest.raises(ValueError, match="not configured"): + await helper.create_delivery_attestation_aip4(TX, TX, OTHER) + with pytest.raises(ValueError, match="required"): + await helper.revoke_attestation(UID) + + +@pytest.mark.asyncio +async def test_nonce_reservations_are_unique_and_release_only_rewinds_the_tail(ledger): + rpc, w3 = ledger + manager = NonceManager(w3, ACCOUNT.address) + values = await asyncio.gather(*(manager.get_nonce() for _ in range(20))) + assert sorted(values) == list(range(3, 23)) + await manager.release_nonce(22) + assert await manager.get_nonce() == 22 + await manager.release_nonce(5) + assert await manager.peek_nonce() == 23 + snapshot = manager.get_pending_nonces() + snapshot.clear() + assert manager.get_pending_count() == 19 + rpc.nonce = 30 + assert await manager.sync() == 30 + assert manager.get_pending_count() == 0 + assert await manager.wait_for_confirmations(timeout=0) is True + assert await manager.reset() == 30 + + +@pytest.mark.asyncio +async def test_nonce_pool_keeps_accounts_separate_and_reports_confirmation_timeouts(ledger): + rpc, w3 = ledger + pool = NonceManagerPool(w3) + assert await pool.get_nonce(ACCOUNT.address) == 3 + assert await pool.get_nonce(OTHER) == 3 + await pool.release_nonce(ACCOUNT.address, 3) + assert await pool.get_nonce(ACCOUNT.address) == 3 + await pool.confirm_nonce(OTHER, 3) + assert await pool.sync(OTHER) == 4 + manager = await pool._get_or_create_manager(ACCOUNT.address) + assert await manager.wait_for_confirmations(timeout=-1, poll_interval=0) is False + rpc.nonce = 5 + assert await manager.wait_for_confirmations(timeout=1, poll_interval=0) is True + await pool.reset(OTHER) + await pool.reset() + await pool.confirm_nonce("0x" + "33" * 20, 1) + await pool.release_nonce("0x" + "33" * 20, 1) diff --git a/tests/test_protocol/test_receipt_and_fee_guards.py b/tests/test_protocol/test_receipt_and_fee_guards.py new file mode 100644 index 0000000..15c9149 --- /dev/null +++ b/tests/test_protocol/test_receipt_and_fee_guards.py @@ -0,0 +1,76 @@ +import pytest +from unittest.mock import MagicMock, AsyncMock +from eth_account import Account +from eth_account.messages import encode_typed_data +from eth_abi import encode +from agirails.protocol.kernel import ACTPKernel +from agirails.protocol.kernel_creation import encode_kernel_creation, LEGACY_KERNEL +from agirails.dispute.composite_mediator import decode_resolution_proof +from agirails.reputation.dispute_split_indexer import DisputeOutcome, DisputeSplitIndexer +from agirails.dispute.receipt_authorization import ReceiptAuthorizationInput, receipt_authorization_typed_data, authorize_payment_receipt + + +@pytest.mark.asyncio +@pytest.mark.parametrize('reason', ['Tx missing', 'Vault not approved']) +async def test_retry_estimation_revert_never_signs_or_broadcasts(reason): + fn = MagicMock(estimate_gas=AsyncMock(side_effect=Exception(reason))) + contract = MagicMock(); contract.functions.retryPlatformFee.return_value = fn + account = MagicMock(); account.address = '0x' + '11' * 20 + w3 = MagicMock(); w3.eth.send_raw_transaction = AsyncMock() + kernel = ACTPKernel(contract, account, w3, 31337) + with pytest.raises(Exception, match=reason): + await kernel.retry_platform_fee('0x' + '99' * 32) + account.sign_transaction.assert_not_called() + w3.eth.send_raw_transaction.assert_not_awaited() + fn.build_transaction.assert_not_called() + + +def test_fee_only_debt_principal_snapshot_suppresses_sentinel(): + proof = '0x' + encode(['uint256', 'uint256', 'bool'], [1, 0, True]).hex() + result = decode_resolution_proof(proof, 0) + assert result.phantom_sentinel and result.requester_amount == result.provider_amount == 0 + outcome = DisputeOutcome(provider='p', requester='r', kind='settled', remaining=50000, escrow_principal=0, proof=proof) + assert DisputeSplitIndexer().classify_payout(outcome).phantom_sentinel + assert decode_resolution_proof(proof, remaining=50000, escrow_principal=0).phantom_sentinel + assert decode_resolution_proof(proof, remaining=50000).requester_amount == 1 + + +def test_legacy_creation_encoding_keeps_agent_ids_and_rejects_lost_binding(): + args = ['0x' + '11' * 20, '0x' + '22' * 20, 100000, 999999, 3600, bytes(32), bytes(32), 42, 43] + old = encode_kernel_creation(LEGACY_KERNEL, args, bytes(32)) + new = encode_kernel_creation('0x' + '33' * 20, args, bytes(32)) + assert len(bytes.fromhex(old[2:])) == 4 + 8 * 32 + assert len(bytes.fromhex(new[2:])) == 4 + 9 * 32 + assert old[:10] != new[:10] + assert old[-128:] == new[-128:] + with pytest.raises(ValueError, match='refusing to discard'): + encode_kernel_creation(LEGACY_KERNEL, args, bytes([1]) * 32) + + +@pytest.mark.asyncio +async def test_authorize_paid_receipt_has_recoverable_domain_bound_signature(): + account = Account.from_key(bytes([1]) * 32) + value = ReceiptAuthorizationInput(84532, '0x' + '33' * 20, '0x' + '44' * 32, 'dn_non_bytes32', '0x' + '55' * 32, account.address) + class Signer: + def get_address(self): return account.address + def sign_typed_data(self, data): return '0x' + account.sign_message(encode_typed_data(full_message=data)).signature.hex() + receipt = await authorize_payment_receipt({'scheme': 'exact', 'network': 'eip155:84532', 'txHash': value.tx_hash, 'payload': '{}'}, value, Signer()) + import json + from pathlib import Path + from web3 import Web3 + vector = json.loads((Path(__file__).resolve().parents[2] / 'test-vectors/dispute/receipt-authorization-v1.json').read_text()) + signed = account.sign_message(encode_typed_data(full_message=receipt_authorization_typed_data(value))) + assert Web3.to_hex(signed.message_hash) == vector['digest'] + assert receipt['authorization']['signature'] == vector['signature'] + assert Account.recover_message(encode_typed_data(full_message=receipt_authorization_typed_data(value)), signature=receipt['authorization']['signature']) == account.address + + +def test_python_legacy_client_capability_and_chain_guards(): + from agirails.dispute.receipt_authorization import _validate_quote_transport + from agirails.dispute.evaluator_client import EvaluateResponseError + with pytest.raises(EvaluateResponseError, match='signed paid receipts'): + _validate_quote_transport({'x402': {'receiptAuthorization': {'version': '1'}}}, 84532) + for quote in [{'quote': {'chainId': 8453}}, {'x402': {'chainId': 8453}}, {'x402': {'network': 'eip155:8453'}}]: + with pytest.raises(EvaluateResponseError, match='conflicts'): + _validate_quote_transport(quote, 84532) + _validate_quote_transport({'quote': {'chainId': 84532}, 'x402': {'network': 'base'}}, 84532) diff --git a/tests/test_protocol/test_registry_io.py b/tests/test_protocol/test_registry_io.py new file mode 100644 index 0000000..89d1f53 --- /dev/null +++ b/tests/test_protocol/test_registry_io.py @@ -0,0 +1,113 @@ +"""AgentRegistry public reads and writes through real AsyncWeb3 encoding.""" + +from unittest.mock import AsyncMock + +import pytest +import pytest_asyncio +from eth_account import Account +from web3 import AsyncWeb3 + +from agirails.errors import ValidationError, TransactionRevertedError +from agirails.protocol.agent_registry import AgentRegistry, ServiceDescriptor, _load_agent_registry_abi, compute_service_type_hash +from tests.helpers.contract_rpc import ContractRPC + +ACCOUNT = Account.from_key("0x" + "11" * 32) +ADDRESS = "0x" + "22" * 20 +HASH = "0x" + "ab" * 32 + + +@pytest_asyncio.fixture +async def registry(): + rpc = ContractRPC() + w3 = AsyncWeb3(rpc) + abi = _load_agent_registry_abi() + rpc.register(abi) + wrapper = AgentRegistry(w3.eth.contract(address=ADDRESS, abi=abi), ACCOUNT, w3, 84532) + return rpc, wrapper + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method,args,wire,expected", [ + ("update_endpoint", ["https://agent.example/new"], "updateEndpoint", ("https://agent.example/new",)), + ("add_service_type", ["echo"], "addServiceType", ("echo",)), + ("remove_service_type", ["echo"], "removeServiceType", (bytes.fromhex(compute_service_type_hash("echo")[2:]),)), + ("remove_service_type", [HASH], "removeServiceType", (bytes.fromhex(HASH[2:]),)), + ("set_active_status", [False], "setActiveStatus", (False,)), + ("set_listed", [True], "setListed", (True,)), + ("publish_config", ["bafy-config", HASH], "publishConfig", ("bafy-config", bytes.fromhex(HASH[2:]))), +]) +async def test_registry_writes_have_correct_signed_wire_values(registry, method, args, wire, expected): + rpc, client = registry + receipt = await getattr(client, method)(*args) + assert receipt.success is True + assert rpc.sent[-1][0:2] == (wire, expected) + assert Account.recover_transaction(rpc.sent[-1][2]) == ACCOUNT.address + assert client.address == ACCOUNT.address + assert client.contract_address == ADDRESS + + +@pytest.mark.asyncio +async def test_register_agent_includes_descriptors_and_canonical_service_hash(registry): + rpc, client = registry + descriptor = ServiceDescriptor("echo", min_price=50_000, max_price=1_000_000) + receipt = await client.register_agent("https://agent.example", [descriptor]) + assert receipt.success is True + name, args, raw = rpc.sent[-1] + assert name == "registerAgent" + assert args[0] == "https://agent.example" + assert args[1][0][0] == bytes.fromhex(compute_service_type_hash("echo")[2:]) + assert args[1][0][3:5] == (50_000, 1_000_000) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cid,hash_", [("", HASH), ("x" * 129, HASH), ("bafy", ""), ("bafy", "0x" + "00" * 32), ("bafy", "0xwrong")]) +async def test_invalid_publish_inputs_never_send_a_transaction(registry, cid, hash_): + rpc, client = registry + with pytest.raises(ValidationError): + await client.publish_config(cid, hash_) + assert rpc.sent == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method,args", [("set_listed", [True]), ("publish_config", ["bafy", HASH])]) +async def test_not_registered_errors_keep_actionable_context(registry, monkeypatch, method, args): + rpc, client = registry + monkeypatch.setattr(client, "_build_transaction", AsyncMock(side_effect=RuntimeError("Not registered"))) + with pytest.raises(TransactionRevertedError, match="Register first"): + await getattr(client, method)(*args) + assert rpc.sent == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("service", ["echo", HASH]) +async def test_service_queries_hash_names_and_preserve_pagination(registry, service): + rpc, client = registry + rpc.reply("supportsService", True) + rpc.reply("queryAgentsByService", [ADDRESS]) + rpc.reply("getServiceDescriptors", [(bytes.fromhex(HASH[2:]), "echo", "https://schema.example", 1, 2, 60, "bafy")]) + assert await client.supports_service(ADDRESS, service) is True + assert [x.lower() for x in await client.query_agents_by_service(service, 80, 2, 5)] == [ADDRESS.lower()] + assert rpc.calls[-1][1][1:] == (80, 2, 5) + descriptors = await client.get_service_descriptors(ADDRESS) + assert descriptors[0].service_type == "echo" + assert descriptors[0].min_price == 1 + + +@pytest.mark.asyncio +async def test_profiles_decode_config_and_reputation_from_rpc(registry): + rpc, client = registry + profile = (ADDRESS, "did:eth:agent", "https://agent.example", [bytes.fromhex(HASH[2:])], 0, 9500, 20, 2, 50_000_000, 1700000000, 1700000001, True, bytes.fromhex(HASH[2:]), "bafy-config", True) + rpc.reply("getAgent", profile) + rpc.reply("getAgentByDID", profile) + assert await client.is_registered(ADDRESS) is True + agent = await client.get_agent(ADDRESS) + assert agent.to_dict()["configHash"] == HASH + assert agent.reputation_percentage == 95 + assert agent.dispute_rate == 10 + assert agent.total_volume_usdc_human == 50 + assert (await client.get_agent_by_did("did:eth:agent")).config_cid == "bafy-config" + rpc.reply("queryAgentsByService", [ADDRESS]) + assert len(await client.find_providers_for_service("echo", 80)) == 1 + rpc.reply("getAgent", (*profile[:11], False, *profile[12:])) + assert await client.find_providers_for_service("echo", 80) == [] + assert len(await client.find_providers_for_service("echo", 80, active_only=False)) == 1 diff --git a/tests/test_reputation/__init__.py b/tests/test_reputation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_reputation/test_dispute_split_indexer.py b/tests/test_reputation/test_dispute_split_indexer.py new file mode 100644 index 0000000..fd4cc8a --- /dev/null +++ b/tests/test_reputation/test_dispute_split_indexer.py @@ -0,0 +1,187 @@ +""" +P2-8 — DisputeSplitIndexer (Python side). + +Mirrors sdk-js/tests/dispute-split-indexer.test.ts 1:1 and consumes the SAME +shared cross-SDK fixture +``DISPUTE SYSTEM/test-vectors/dispute-split-indexer-vectors.json``. + +Proves: + 1. get_split_rate is the headline ~14% case: 1 split / 6 settled = 1/7, + where the single split is an ADMIN-CANCELLED (kernel DISPUTED->CANCELLED) — + OQ-11 counts admin-CANCELLED at IDENTICAL weight in the headline. + 2. DisputeSplitRecorded + kernel DISPUTED->CANCELLED weighted identically. + 3. ZERO-REMAINING RULE: a drained split (remaining==0) still counts as a + split, and classify_payout reports NO 1-wei payout (phantom sentinel). + 4. Per-agent scoping + div-by-zero safety. + +PARITY: test asserts mirror the TS twin's assertions row-for-row. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +from agirails.reputation import ( + DisputeOutcome, + DisputeSplitIndexer, + is_split_kind, + outcome_from_split_recorded, +) +from agirails.dispute.composite_mediator import DisputeSplitRecorded + +# PARITY: dispute-split-indexer.test.ts — same fixture, same assertions. +_VECTORS_DIR = Path(__file__).resolve().parents[2] / "test-vectors" +_FIXTURE: Dict[str, Any] = json.loads( + (_VECTORS_DIR / "dispute-split-indexer-vectors.json").read_text() +) + +_AGENT: str = _FIXTURE["agent"] + + +def _indexer_from_fixture(outcomes: List[Dict[str, Any]]) -> DisputeSplitIndexer: + """Build a DisputeSplitIndexer seeded from a fixture ``outcomes`` array.""" + mapped = [ + DisputeOutcome( + provider=o["provider"], + requester=o["requester"], + kind=o["kind"], + remaining=int(o.get("remaining", "0")), + split_bps=o.get("splitBps"), + proof=o.get("proof"), + tx_id=o.get("txId"), + ) + for o in outcomes + ] + return DisputeSplitIndexer(mapped) + + +# --------------------------------------------------------------------------- +# get_split_rate — the headline ~14% fixture (OQ-11 admin-CANCELLED counted) +# --------------------------------------------------------------------------- + + +class TestHeadlineFourteenPercent: + def test_one_split_six_settled_is_one_seventh_admin_cancelled(self): + f = _FIXTURE["headlineFourteenPercent"] + indexer = _indexer_from_fixture(f["outcomes"]) + rate = indexer.get_split_rate(_AGENT) + + assert rate.split_count == f["expected"]["splitCount"] # 1 + assert rate.total_disputes == f["expected"]["totalDisputes"] # 7 + assert rate.split_rate == pytest.approx(f["expected"]["splitRate"], abs=1e-12) + # ~14% + assert round(rate.split_rate * 100) == f["expected"]["approxPercent"] + + # The single split was an admin-CANCELLED kernel transition — prove OQ-11 + # counts it in the HEADLINE (R11 under-count trap closed). + breakdown = indexer.get_split_rate_breakdown(_AGENT) + assert breakdown.mediator_split_count == 0 + assert breakdown.admin_split_count == 1 + assert breakdown.split_rate == pytest.approx( + f["expected"]["splitRate"], abs=1e-12 + ) # headline unchanged + + def test_mediator_and_admin_split_weighted_identically(self): + f = _FIXTURE["mixedSourceEqualWeight"] + indexer = _indexer_from_fixture(f["outcomes"]) + rate = indexer.get_split_rate(_AGENT) + breakdown = indexer.get_split_rate_breakdown(_AGENT) + + assert rate.split_count == f["expected"]["splitCount"] # 2 + assert rate.total_disputes == f["expected"]["totalDisputes"] # 7 + assert rate.split_rate == pytest.approx(f["expected"]["splitRate"], abs=1e-12) + assert breakdown.mediator_split_count == f["expected"]["mediatorSplitCount"] + assert breakdown.admin_split_count == f["expected"]["adminSplitCount"] + # identical weight: 1 mediator + 1 admin == 2 toward the same rate. + assert ( + breakdown.mediator_split_count + breakdown.admin_split_count + == rate.split_count + ) + + def test_per_agent_scoping(self): + f = _FIXTURE["perAgentScoping"] + indexer = _indexer_from_fixture(f["outcomes"]) + rate = indexer.get_split_rate(f["queryAgent"]) + assert rate.split_count == f["expected"]["splitCount"] # 1 + assert rate.total_disputes == f["expected"]["totalDisputes"] # 2 + assert rate.split_rate == pytest.approx(f["expected"]["splitRate"], abs=1e-12) + + def test_zero_disputes_no_div_by_zero(self): + f = _FIXTURE["zeroDisputesNoDivByZero"] + indexer = _indexer_from_fixture(f["outcomes"]) + rate = indexer.get_split_rate(f["queryAgent"]) + assert rate.split_count == 0 + assert rate.total_disputes == 0 + assert rate.split_rate == 0.0 + + +# --------------------------------------------------------------------------- +# ZERO-REMAINING CONSUMER RULE — drained split counts, no phantom payout +# --------------------------------------------------------------------------- + + +class TestZeroRemainingRule: + def test_drained_splits_count_but_report_no_phantom_payout(self): + f = _FIXTURE["drainedSplitNoPhantomPayout"] + indexer = _indexer_from_fixture(f["outcomes"]) + rate = indexer.get_split_rate(_AGENT) + + # The split STILL counts toward the rate even though escrow was drained. + assert rate.split_count == f["expected"]["splitCount"] # 2 + assert rate.total_disputes == f["expected"]["totalDisputes"] # 2 + assert rate.split_rate == pytest.approx(f["expected"]["splitRate"], abs=1e-12) + + # But the indexer NEVER surfaces a 1-wei payout — proof amounts are phantom. + for o in indexer.get_outcomes(): + decoded = indexer.classify_payout(o) + assert decoded is not None + assert decoded.phantom_sentinel is True + assert decoded.requester_amount == 0 + assert decoded.provider_amount == 0 + # Hard assertion of the rule: never the 1-wei sentinel. + assert decoded.requester_amount != 1 + assert decoded.provider_amount != 1 + assert f["expected"]["phantomPayoutReported"] is False + + +# --------------------------------------------------------------------------- +# Helpers / parity surface +# --------------------------------------------------------------------------- + + +class TestIndexerHelpers: + def test_is_split_kind(self): + assert is_split_kind("disputeSplitRecorded") is True + assert is_split_kind("kernelDisputedToCancelled") is True + assert is_split_kind("settled") is False + + def test_outcome_from_split_recorded(self): + o = outcome_from_split_recorded( + DisputeSplitRecorded( + tx_id="0x1", + requester="0x1111111111111111111111111111111111111111", + provider=_AGENT, + split_bps=3000, + ), + remaining=1000000, + ) + assert o.kind == "disputeSplitRecorded" + assert o.provider == _AGENT + assert o.split_bps == 3000 + assert o.remaining == 1000000 + + def test_classify_payout_returns_none_without_proof(self): + indexer = DisputeSplitIndexer() + decoded = indexer.classify_payout( + DisputeOutcome( + provider=_AGENT, + requester="0x1", + kind="settled", + remaining=100, + ) + ) + assert decoded is None diff --git a/tests/test_runtime/test_blockchain_local_io.py b/tests/test_runtime/test_blockchain_local_io.py new file mode 100644 index 0000000..c3bd6c5 --- /dev/null +++ b/tests/test_runtime/test_blockchain_local_io.py @@ -0,0 +1,201 @@ +"""Testnet-shaped SDK path against a local JSON-RPC transport, never a live chain.""" + +import importlib +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +import pytest_asyncio +from eth_account import Account +from web3 import AsyncWeb3 + +from agirails.client import ACTPClient, ACTPClientConfig +from agirails.config.networks import BASE_SEPOLIA +from agirails.errors import ValidationError, TransactionError, DisputeWindowActiveError +from agirails.runtime.base import CreateTransactionParams +from agirails.runtime.blockchain_runtime import BlockchainRuntime +from agirails.runtime.types import State +from tests.helpers.contract_rpc import ContractRPC +from tests.test_protocol.test_event_monitor_layouts import event_abi, raw_log + +KEY = "0x" + "11" * 32 +ACCOUNT = Account.from_key(KEY) +PROVIDER = "0x" + "22" * 20 +TX = "0x" + "ab" * 32 +ZERO = bytes(32) + + +@pytest_asyncio.fixture +async def runtime(monkeypatch): + rpc = ContractRPC() + monkeypatch.setattr(AsyncWeb3, "AsyncHTTPProvider", lambda url: rpc) + instance = await BlockchainRuntime.create(KEY, network=BASE_SEPOLIA, rpc_rate_limit=1000) + for abi in [instance.kernel.contract.abi, instance.escrow.contract.abi, instance.escrow.usdc_contract.abi]: + rpc.register(abi) + return rpc, instance + + +def view_tuple(state=0, requester=ACCOUNT.address): + return ( + bytes.fromhex(TX[2:]), requester, PROVIDER, state, 1_000_000, + 1700000000, 1700000100, 1900000000, bytes.fromhex(TX[2:]), + BASE_SEPOLIA.contracts.escrow_vault, bytes.fromhex(TX[2:]), ZERO, + 172800, ZERO, 100, 500, 1000, 42, 43, "0x" + "00" * 20, 0, ZERO, ZERO, + ) + + +@pytest.mark.asyncio +async def test_runtime_initialization_and_readback_are_bound_to_testnet(runtime): + rpc, instance = runtime + assert instance.address == ACCOUNT.address + assert await instance.get_chain_id() == 84532 + assert await instance.get_block_number() == 10 + assert instance.rate_limiter is not None + assert await instance.time.now_async() == rpc.timestamp + assert instance.time.now() == rpc.timestamp + rpc.reply("getTransaction", view_tuple()) + tx = await instance.get_transaction(TX) + assert tx.id == TX + assert tx.requester.lower() == ACCOUNT.address.lower() + assert tx.state == State.INITIATED + assert tx.amount == "1000000" + assert tx.platform_fee_bps_locked == 100 + assert tx.agent_id == 42 + assert tx.requester_agent_id == 43 + rpc.reply("getTransaction", view_tuple(requester="0x" + "00" * 20)) + assert await instance.get_transaction(TX) is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("chain", [1, 8453]) +async def test_wrong_chain_is_rejected_before_a_transaction(monkeypatch, chain): + rpc = ContractRPC() + rpc.chain_id = chain + monkeypatch.setattr(AsyncWeb3, "AsyncHTTPProvider", lambda url: rpc) + with pytest.raises(ValidationError, match="Chain ID mismatch"): + await BlockchainRuntime.create(KEY, BASE_SEPOLIA) + assert rpc.sent == [] + + +@pytest.mark.asyncio +async def test_creation_encodes_expected_principal_and_extracts_real_abi_event(runtime): + rpc, instance = runtime + values = { + "transactionId": bytes.fromhex(TX[2:]), "requester": ACCOUNT.address, + "provider": PROVIDER, "amount": 1_000_000, "serviceHash": bytes.fromhex(TX[2:]), + "deadline": 1900000000, "timestamp": rpc.timestamp, "agentId": 42, + "requesterAgentId": 0, "agreementHash": ZERO, + } + rpc.logs = [raw_log(event_abi("actp_kernel.json", "TransactionCreated"), BASE_SEPOLIA.contracts.actp_kernel, values, 10, 0)] + params = CreateTransactionParams(requester=ACCOUNT.address, provider=PROVIDER, amount="1000000", deadline=1900000000, service_description=TX, agent_id=42) + assert await instance.create_transaction(params) == TX + assert rpc.sent[-1][0] == "createTransaction" + assert 1_000_000 in rpc.sent[-1][1] + assert Account.recover_transaction(rpc.sent[-1][2]) == ACCOUNT.address + params.deadline = rpc.timestamp + count = len(rpc.sent) + with pytest.raises(ValidationError, match="future"): + await instance.create_transaction(params) + assert len(rpc.sent) == count + + +@pytest.mark.asyncio +@pytest.mark.parametrize("state,accepted", [(0, True), (1, True), (2, False), (5, False)]) +async def test_link_escrow_approves_principal_only_for_allowed_states(runtime, state, accepted): + rpc, instance = runtime + rpc.reply("getTransaction", view_tuple(state)) + if not accepted: + with pytest.raises(TransactionError, match="Cannot link escrow"): + await instance.link_escrow(TX, "1000000") + assert rpc.sent == [] + return + assert await instance.link_escrow(TX, "1000000") == TX + assert [name for name, _, _ in rpc.sent] == ["approve", "linkEscrow"] + assert rpc.sent[0][1][-1] == 1_000_000 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("proof,wire", [(None, b""), ("0x1234", b"\x12\x34"), ("text", b"text")]) +async def test_state_proof_wire_encoding(runtime, proof, wire): + rpc, instance = runtime + await instance.transition_state(TX, State.QUOTED, proof) + assert rpc.sent[-1][0] == "transitionState" + assert rpc.sent[-1][1] == (bytes.fromhex(TX[2:]), 1, wire) + + +@pytest.mark.asyncio +async def test_balances_allowances_and_nonce_controls_use_the_shared_runtime(runtime): + rpc, instance = runtime + rpc.reply("balanceOf", 2_500_000) + rpc.reply("remaining", 750_000) + rpc.reply("paused", False) + rpc.reply("platformFeeBps", 100) + assert await instance.get_balance(PROVIDER) == "2500000" + assert await instance.get_usdc_balance(PROVIDER) == 2_500_000 + assert await instance.get_escrow_balance(TX) == "750000" + await instance.approve_usdc(500_000) + assert rpc.sent[-1][0] == "approve" + assert await instance.sync_nonce() == rpc.nonce + assert await instance.wait_for_confirmations(timeout=0) is True + assert await instance.is_paused() is False + assert await instance.get_platform_fee_bps() == 100 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", ["missing", "INITIATED", "window", "verified", "bad_attestation", "no_verifier"]) +async def test_release_preconditions_and_attestation_failure_prevent_invalid_settlement(runtime, monkeypatch, status): + rpc, instance = runtime + tx = SimpleNamespace(state="DELIVERED", completed_at=1, dispute_window=1) + if status == "missing": + tx = None + elif status == "INITIATED": + tx.state = "INITIATED" + elif status == "window": + tx.completed_at = rpc.timestamp + tx.dispute_window = 100 + monkeypatch.setattr(instance, "get_transaction", AsyncMock(return_value=tx)) + transition = AsyncMock() + monkeypatch.setattr(instance, "transition_state", transition) + uid = TX if status in ("verified", "bad_attestation", "no_verifier") else None + if status in ("verified", "bad_attestation"): + verify = AsyncMock(side_effect=RuntimeError("invalid local fixture") if status == "bad_attestation" else None) + instance.eas_helper = SimpleNamespace(verify_and_record_for_release=verify) + if status in ("missing", "INITIATED", "bad_attestation"): + with pytest.raises(TransactionError): + await instance.release_escrow(TX, uid) + transition.assert_not_awaited() + elif status == "window": + with pytest.raises(DisputeWindowActiveError): + await instance.release_escrow(TX, uid) + transition.assert_not_awaited() + else: + await instance.release_escrow(TX, uid) + transition.assert_awaited_once_with(TX, State.SETTLED) + + +@pytest.mark.asyncio +async def test_client_can_bootstrap_the_testnet_runtime_with_a_controlled_provider(runtime, tmp_path, monkeypatch): + rpc, _ = runtime + monkeypatch.chdir(tmp_path) + client = await ACTPClient.create(mode="testnet", requester_address=ACCOUNT.address, private_key=KEY, wallet="eoa", state_directory=str(tmp_path / "state"), rpc_url="http://local-fixture.invalid") + rpc.register(client.runtime.escrow.usdc_contract.abi) + rpc.reply("balanceOf", 2_500_000) + assert await client.get_balance() == "2.50" + assert client.address == ACCOUNT.address.lower() + assert client.runtime.config.chain_id == 84532 + await client._drift_task + + +@pytest.mark.asyncio +@pytest.mark.parametrize("intent,config_hash,onchain", [("pay", False, "zero"), ("earn", False, "zero"), ("earn", True, "zero"), ("earn", True, "different")]) +async def test_config_drift_is_observational_and_never_sends_a_transaction(runtime, tmp_path, monkeypatch, intent, config_hash, onchain): + rpc, instance = runtime + monkeypatch.chdir(tmp_path) + client = await ACTPClient.create(requester_address=ACCOUNT.address, config=ACTPClientConfig(mode="testnet", requester_address=ACCOUNT.address, runtime=instance)) + await client._drift_task + text = f"---\nname: local\nintent: {intent}\n" + ("config_hash: example\n" if config_hash else "") + "---\n# local\n" + (tmp_path / "AGIRAILS.md").write_text(text) + module = importlib.import_module("agirails.config.on_chain_state") + monkeypatch.setattr(module, "get_on_chain_config_state", lambda *a: SimpleNamespace(config_hash="0x" + ("00" if onchain == "zero" else "aa") * 32)) + await client.check_config_drift() + assert rpc.sent == [] diff --git a/tests/test_utils/test_canonical_contracts.py b/tests/test_utils/test_canonical_contracts.py new file mode 100644 index 0000000..de2d756 --- /dev/null +++ b/tests/test_utils/test_canonical_contracts.py @@ -0,0 +1,79 @@ +"""Canonical bytes and EIP-712 hashes checked against independent public APIs.""" + +import json +import math + +import pytest +from eth_account.messages import encode_typed_data + +from agirails.utils.canonical_json import canonical_json_dumps, compute_domain_separator, compute_type_hash, hash_struct + + +@pytest.mark.parametrize("value,expected", [ + (None, "null"), (True, "true"), (False, "false"), (0, "0"), (0.0, "0"), (-0.0, "0"), + (1.0, "1"), (-1.25, "-1.25"), (1e-6, "0.000001"), (1e-7, "1e-7"), + (1e20, "100000000000000000000"), (1e21, "1e+21"), (1.2e21, "1.2e+21"), + (1.2345e-5, "0.000012345"), (-1e-7, "-1e-7"), (5e-324, "5e-324"), + (float("nan"), "null"), (float("inf"), "null"), (float("-inf"), "null"), + ("š\n🎉", '"š\\n🎉"'), ([1, None, True], "[1,null,true]"), + ((2, 3), "[2,3]"), ({"z": 1, "a": {"d": 3, "b": 2}}, '{"a":{"b":2,"d":3},"z":1}'), +]) +def test_canonical_bytes_at_ecmascript_number_boundaries(value, expected): + assert canonical_json_dumps(value) == expected + + +@pytest.mark.parametrize("value", [{True: 1}, {False: 1}, {None: 1}, {1.5: 1}, {7: 1}]) +def test_json_key_coercion_matches_json_data_model(value): + actual = canonical_json_dumps(value) + assert json.loads(actual) == json.loads(json.dumps(value)) + + +@pytest.mark.parametrize("settings", [ + {"sort_keys": False}, {"ensure_ascii": True}, {"separators": (", ", ": ")}, +]) +def test_explicit_legacy_formatting_preserves_the_same_json_values(settings): + value = {"z": [{"é": 1}, None], "a": True} + assert json.loads(canonical_json_dumps(value, **settings)) == value + + +def test_unsupported_values_and_unknown_types_fail_explicitly(): + with pytest.raises(TypeError, match="not JSON serializable"): + canonical_json_dumps(object()) + with pytest.raises(ValueError, match="not found"): + compute_type_hash("Absent", {}) + + +@pytest.mark.parametrize("field_type,value", [ + ("string", "hello"), ("bytes", b"\x01\x02"), ("bytes", "0x0102"), + ("uint256", 2**200), ("int256", -7), ("bool", True), + ("address", "0x" + "22" * 20), ("bytes32", bytes.fromhex("ab" * 32)), + ("uint256[]", [1, 2, 3]), ("uint256[]", []), +]) +def test_struct_hash_matches_eth_account_eip712_encoding(field_type, value): + types = {"Item": [{"name": "value", "type": field_type}]} + data = {"value": value} + wire = {"domain": {}, "types": types, "primaryType": "Item", "message": data} + oracle = encode_typed_data(full_message=wire) + assert hash_struct("Item", data, types) == "0x" + oracle.body.hex() + + +@pytest.mark.parametrize("field_type,default", [ + ("uint256", 0), ("int64", 0), ("bool", False), + ("address", "0x" + "00" * 20), ("bytes32", bytes(32)), + ("string", ""), ("bytes", b""), ("uint256[]", []), +]) +def test_absent_primitive_fields_use_documented_zero_defaults(field_type, default): + types = {"Item": [{"name": "value", "type": field_type}]} + assert hash_struct("Item", {}, types) == hash_struct("Item", {"value": default}, types) + + +def test_nested_struct_arrays_and_domain_match_eth_account(): + types = { + "Item": [{"name": "name", "type": "string"}, {"name": "amount", "type": "uint256"}], + "Bundle": [{"name": "first", "type": "Item"}, {"name": "others", "type": "Item[]"}], + } + data = {"first": {"name": "a", "amount": 1}, "others": [{"name": "b", "amount": 2}]} + domain = {"name": "ACTP", "version": "1", "chainId": 84532, "verifyingContract": "0x" + "11" * 20} + oracle = encode_typed_data(full_message={"types": types, "primaryType": "Bundle", "message": data, "domain": domain}) + assert hash_struct("Bundle", data, types) == "0x" + oracle.body.hex() + assert compute_domain_separator("ACTP", "1", 84532, "0x" + "11" * 20) == "0x" + oracle.header.hex() diff --git a/tests/test_utils/test_http_fallback.py b/tests/test_utils/test_http_fallback.py new file mode 100644 index 0000000..7462b0e --- /dev/null +++ b/tests/test_utils/test_http_fallback.py @@ -0,0 +1,126 @@ +"""Exercise real stdlib HTTP framing without external network or credentials.""" + +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.error import HTTPError, URLError + +import pytest + +from agirails.api import agirails_app, discover +from agirails.utils.http import request_http + + +@pytest.fixture(scope="module") +def http_origin(): + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + if self.path.startswith("/redirect"): + self.send_response(302) + self.send_header("Location", self.path.split("?", 1)[1]) + self.end_headers() + return + if self.path.startswith("/error"): + self.send_error(503) + return + body = { + "path": self.path, + "method": "GET", + "agents": [], + "total": 0, + "available": True, + "accept": self.headers.get("Accept"), + } + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps(body).encode()) + + def do_POST(self): + data = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps({"method": "POST", "body": data}).encode()) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + yield f"http://127.0.0.1:{server.server_port}" + server.shutdown() + server.server_close() + worker.join() + + +@pytest.mark.parametrize("url", ["file:///tmp/unused", "data:application/json,{}", "ftp://localhost/a", "relative"]) +def test_non_http_schemes_are_rejected_before_open(url): + with pytest.raises(URLError, match="Only HTTP and HTTPS"): + request_http(url, timeout=0.1) + + +@pytest.mark.parametrize("target", ["file:///tmp/unused", "data:text/plain,unused", "ftp://127.0.0.1/a"]) +def test_redirects_cannot_switch_to_a_non_http_protocol(http_origin, target): + with pytest.raises((URLError, HTTPError)): + request_http(f"{http_origin}/redirect?{target}", timeout=1) + + +def test_http_redirect_retains_normal_http_response(http_origin): + with request_http(f"{http_origin}/redirect?{http_origin}/ok", timeout=1) as response: + assert response.status == 200 + assert json.load(response)["path"] == "/ok" + + +@pytest.fixture +def stdlib_clients(monkeypatch, http_origin): + for module in (agirails_app, discover): + monkeypatch.setattr(module, "_HAS_HTTPX", False) + monkeypatch.setattr(module, "_HAS_AIOHTTP", False) + monkeypatch.setattr(module, "AGIRAILS_APP_BASE_URL", http_origin) + + +@pytest.mark.asyncio +async def test_get_and_post_fallback_preserve_headers_and_json(stdlib_clients, http_origin): + result = await agirails_app._get(f"{http_origin}/ok", timeout=1) + assert result["method"] == "GET" + assert result["accept"] == "application/json" + result = await agirails_app._post(f"{http_origin}/ok", {"amount": "250000"}, timeout=1) + assert result == {"method": "POST", "body": {"amount": "250000"}} + + +@pytest.mark.asyncio +async def test_slug_and_discovery_use_supported_endpoints(stdlib_clients): + result = await agirails_app.check_slug("test agent") + assert result["available"] is True + assert result["path"].endswith("check-slug?slug=test%20agent") + result = await discover.discover_agents() + assert result.agents == [] + assert result.total == 0 + + +@pytest.mark.asyncio +async def test_http_error_is_not_reinterpreted_as_success(stdlib_clients, http_origin): + with pytest.raises(HTTPError) as raised: + await agirails_app._get(f"{http_origin}/error", timeout=1) + assert raised.value.code == 503 + + +@pytest.mark.asyncio +async def test_profile_and_claim_payloads_preserve_wire_names(stdlib_clients): + profile = agirails_app.UpsertAgentParams( + slug="test", agent_id="42", wallet="0x123", config_cid="bafy-test", + config_hash="0x456", signature="example-signature", message="claim", timestamp=123, + network="base-sepolia", + ) + result = await agirails_app.upsert_agent(profile) + assert result["body"] == { + "slug": "test", "agentId": "42", "wallet": "0x123", "configCid": "bafy-test", + "configHash": "0x456", "signature": "example-signature", "message": "claim", + "timestamp": 123, "network": "base-sepolia", + } + + +def test_ftp_redirect_is_rejected_by_the_explicit_protocol_guard(http_origin): + with pytest.raises(URLError, match="Only HTTP and HTTPS"): + request_http(f"{http_origin}/redirect?ftp://127.0.0.1/unused", timeout=1) diff --git a/tests/test_utils/test_identity_operator.py b/tests/test_utils/test_identity_operator.py new file mode 100644 index 0000000..a0f902f --- /dev/null +++ b/tests/test_utils/test_identity_operator.py @@ -0,0 +1,139 @@ +"""Real signatures, resolver cache lifetimes, and terminal output contracts.""" +import asyncio +import json +from io import StringIO + +from eth_account import Account +from eth_account.messages import encode_defunct +from eth_keys import keys +import pytest +from rich.console import Console + +from agirails.protocol.did import DIDManager, DIDResolver, VerificationMethod, ServiceEndpoint +from agirails.cli.utils import output +from agirails.utils.semaphore import Semaphore, RateLimiter + +KEY = '0x' + '13' * 32 + +@pytest.mark.parametrize('network,chain', [('base-sepolia','84532'), ('local','31337'), ('mock','0'), ('unknown','0')]) +def test_did_document_and_real_owner_signature(network, chain): + manager = DIDManager(KEY, network=network) + did = str(manager.did) + message = 'prove ownership without authorizing payment' + signature = manager.sign_for_did(message) + assert Account.recover_message(encode_defunct(text=message), signature=signature) == manager.address + assert manager.verify_did_ownership(did, signature, message) + assert not manager.verify_did_ownership(did, signature, message + '!') + assert not manager.verify_did_ownership(did.replace(manager.address, '0x' + '22'*20), signature, message) + assert not manager.verify_did_ownership('invalid', signature, message) + assert not manager.verify_did_ownership(did, '0xzz', message) + doc = manager.create_did_document(endpoint='https://example.invalid', service_types=['echo'], metadata={'version':1}) + method = doc.verification_method[0] + assert method['blockchainAccountId'] == f'eip155:{chain}:{manager.did.identifier}' + assert method['publicKeyHex'] == keys.PrivateKey(bytes.fromhex(KEY[2:])).public_key.to_hex() + assert doc.service[1]['serviceEndpoint'] == 'https://example.invalid/services/echo' + assert doc.metadata == {'version':1} + assert manager.create_did_document(service_types=['echo']).service[0]['serviceEndpoint'] == '' + +@pytest.mark.asyncio +@pytest.mark.parametrize('method,network,identifier', [('agirails','base-sepolia','0x'+'ab'*20), ('eth','mainnet','0x'+'cd'*20), ('key','local','zPublicKey')]) +async def test_resolver_cache_bypass_and_expiry(method, network, identifier, monkeypatch): + now = [1000.0] + monkeypatch.setattr('agirails.protocol.did.time.time', lambda: now[0]) + resolver = DIDResolver(cache_ttl=10) + manager = DIDManager(resolver=resolver) + assert manager.resolver is resolver + did = f'did:{method}:{network}:{identifier}' + first = await manager.resolve(did) + assert first is not None and first.authentication == [f'{did}#key-1'] + assert await resolver.resolve(did) is first + bypass = await resolver.resolve(did, use_cache=False) + assert bypass is not first + assert await resolver.resolve(did) is first + now[0] = 1011 + renewed = await resolver.resolve(did) + assert renewed is not first + resolver.clear_cache() + assert await resolver.resolve(did) is not renewed + assert await resolver.resolve('garbage') is None + +@pytest.mark.parametrize('with_keys', [False, True]) +def test_verification_and_endpoint_optional_wire_fields(with_keys): + method = VerificationMethod('id', 'type', 'controller', '0xabc' if with_keys else '', 'zkey' if with_keys else '') + wire = method.to_dict() + assert ('publicKeyHex' in wire) is with_keys + assert ('publicKeyMultibase' in wire) is with_keys + endpoint = ServiceEndpoint('id', 'type', {'url':'https://example.invalid'}, 'description' if with_keys else '') + assert ('description' in endpoint.to_dict()) is with_keys + +@pytest.mark.parametrize('rich', [False, True]) +def test_terminal_output_contracts(rich, monkeypatch, capsys): + buffer = StringIO() + monkeypatch.setattr(output, 'HAS_RICH', rich) + monkeypatch.setattr(output, '_console', Console(file=buffer, color_system=None)) + output.print_success('Completed', {'id':42}) + output.print_success('Empty') + output.print_warning('Warning') + output.print_info('Information') + output.print_table(['id','value'], [[1,'long value'], [2,'ok']], title='Results') + output.print_table(['id'], [], title=None) + output.print_transaction({'id':'tx-1', 'state':'SETTLED'}) + rendered = buffer.getvalue() if rich else capsys.readouterr().out + for expected in ('Completed','42','Empty','Warning','Information','Results','long value','tx-1','SETTLED'): + assert expected in rendered + output.print_error('Failed', details='reason') + assert 'reason' in capsys.readouterr().out + output.print_transaction({'id':'tx-2'}, output.OutputFormat.JSON) + assert json.loads(capsys.readouterr().out) == {'id':'tx-2'} + output.print_transaction({'tx_id':'tx-3'}, output.OutputFormat.QUIET) + assert capsys.readouterr().out.strip() == 'tx-3' + assert output.format_state('settled') == ('[green]settled[/green]' if rich else 'settled') + assert output.format_state('unknown') == ('[white]unknown[/white]' if rich else 'unknown') + +@pytest.mark.parametrize('data,expected', [({'txId':'a'},'a'), ({'escrow_id':'b'},'b'), ({'other':4},'4'), ({},'{}'), (12,'12')]) +def test_quiet_output_fallback_priority(data, expected): + assert output.format_output(data, output.OutputFormat.QUIET) == expected + assert output.format_output(data, output.OutputFormat.QUIET, quiet_value='override') == 'override' + assert json.loads(output.format_output(data, output.OutputFormat.JSON)) == data + assert isinstance(output.format_output(data), str) + +@pytest.mark.asyncio +async def test_semaphore_fifo_timeout_and_context_release(): + semaphore = Semaphore(1) + assert await semaphore.acquire() + timeout = asyncio.create_task(semaphore.acquire(timeout_ms=1)) + assert not await timeout + assert semaphore.queue_length == 0 and semaphore.available_permits == 0 + waiting = asyncio.create_task(semaphore.acquire()) + await asyncio.sleep(0) + assert semaphore.queue_length == 1 + semaphore.release() + assert await waiting + semaphore.release() + assert semaphore.available_permits == 1 + with pytest.raises(ValueError, match='inside'): + async with semaphore: + assert semaphore.available_permits == 0 + raise ValueError('inside') + assert semaphore.available_permits == 1 + +@pytest.mark.asyncio +async def test_rate_limiter_window_reset_and_wait(monkeypatch): + now = [1000.0] + monkeypatch.setattr('agirails.utils.semaphore.time.time', lambda: now[0]) + limiter = RateLimiter(2, 10) + assert limiter.available == 2 and limiter.time_until_available == 0 + assert await limiter.acquire() and await limiter.acquire() + assert not await limiter.acquire() + assert limiter.available == 0 and limiter.time_until_available == 10 + async def advance(_): now[0] += 0.01 + monkeypatch.setattr('agirails.utils.semaphore.asyncio.sleep', advance) + assert not await limiter.wait_and_acquire(timeout_ms=20) + now[0] = 1011 + assert await limiter.wait_and_acquire(timeout_ms=20) + limiter.reset() + assert limiter.available == 2 + +@pytest.mark.parametrize('args', [(0, 1), (1, 0), (-1, 1)]) +def test_invalid_rate_limits(args): + with pytest.raises(ValueError): RateLimiter(*args) diff --git a/tests/test_utils/test_resolver_and_error_contracts.py b/tests/test_utils/test_resolver_and_error_contracts.py new file mode 100644 index 0000000..26f5ebe --- /dev/null +++ b/tests/test_utils/test_resolver_and_error_contracts.py @@ -0,0 +1,100 @@ +"""Real loopback DID resolution and operator-facing storage error contracts.""" + +import asyncio +import json +import threading +import time +from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer +from urllib.parse import unquote + +import pytest + +from agirails.protocol.did import DIDResolver +from agirails.errors import storage + + +@pytest.fixture +def resolver_origin(): + class Handler(BaseHTTPRequestHandler): + def log_message(self,*args):pass + def do_GET(self): + self.server.calls.append(self.path) + with self.server.guard: + self.server.active+=1 + self.server.peak=max(self.server.peak,self.server.active) + try: + if self.path.startswith('/slow'):time.sleep(0.01) + if self.path.startswith('/error'): + self.send_error(503);return + did=unquote(self.path.rsplit('/',1)[-1]) + body={} if self.path.startswith('/missing') else {'didDocument':{'id':'invalid' if self.path.startswith('/invalid') else did,'service':[{'id':did+'#api','type':'AgentAPI','serviceEndpoint':'https://agent.invalid'}]}} + self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers() + self.wfile.write(b'not json' if self.path.startswith('/broken') else json.dumps(body).encode()) + finally: + with self.server.guard:self.server.active-=1 + server=ThreadingHTTPServer(('127.0.0.1',0),Handler) + server.calls=[];server.active=0;server.peak=0;server.guard=threading.Lock() + worker=threading.Thread(target=server.serve_forever,daemon=True);worker.start() + yield f'http://127.0.0.1:{server.server_port}',server + server.shutdown();server.server_close();worker.join() + + +@pytest.mark.asyncio +async def test_unknown_did_method_uses_real_http_document_and_cache(resolver_origin): + url,server=resolver_origin + resolver=DIDResolver(resolver_url=url+'/ok',http_timeout=1) + did='did:web:base:node' + first=await resolver.resolve(did) + assert str(first.id)==did and first.service[0]['serviceEndpoint']=='https://agent.invalid' + assert await resolver.resolve(did) is first + assert len(server.calls)==1 + assert await resolver.resolve(did,use_cache=False) is not first + assert len(server.calls)==2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize('path',['error','missing','invalid','broken']) +async def test_resolution_failure_returns_none_and_does_not_cache_success(resolver_origin,path): + url,server=resolver_origin + resolver=DIDResolver(resolver_url=url+'/'+path,http_timeout=1) + assert await resolver.resolve('did:web:base:node') is None + assert await resolver.resolve('did:web:base:node') is None + assert len(server.calls)==2 + + +@pytest.mark.asyncio +async def test_http_resolution_obeys_concurrency_bound(resolver_origin): + url,server=resolver_origin + resolver=DIDResolver(resolver_url=url+'/slow',max_concurrent_requests=1,http_timeout=1) + documents=await asyncio.gather(*(resolver.resolve(f'did:web:base:node{i}') for i in range(3))) + assert [str(doc.id) for doc in documents]==[f'did:web:base:node{i}' for i in range(3)] + assert server.peak==1 and len(server.calls)==3 + + +@pytest.mark.parametrize('kind,args,kwargs,code,attributes',[ + ('InvalidCIDError',('bad-cid',),{'reason':'invalid encoding'},'INVALID_CID',{'cid':'bad-cid','reason':'invalid encoding'}), + ('UploadTimeoutError',(1500,),{'file_size':100,'gateway':'https://gateway.invalid'},'UPLOAD_TIMEOUT',{'timeout_ms':1500,'file_size':100}), + ('DownloadTimeoutError',('bafy-cid',1500),{'gateway':'https://gateway.invalid'},'DOWNLOAD_TIMEOUT',{'cid':'bafy-cid','timeout_ms':1500}), + ('FileSizeLimitExceededError',(100,90),{},'FILE_SIZE_LIMIT_EXCEEDED',{'file_size':100,'max_size':90}), + ('StorageAuthenticationError',(),{'gateway':'https://gateway.invalid'},'STORAGE_AUTH_ERROR',{'gateway':'https://gateway.invalid'}), + ('StorageRateLimitError',(500,),{'gateway':'https://gateway.invalid'},'STORAGE_RATE_LIMIT',{'retry_after_ms':500}), + ('ContentNotFoundError',('bafy-cid',),{},'CONTENT_NOT_FOUND',{'cid':'bafy-cid'}), + ('FilebaseUploadError',(),{'bucket':'bucket','key':'file'},'FILEBASE_UPLOAD_ERROR',{'bucket':'bucket','key':'file'}), + ('FilebaseDownloadError',(),{'cid':'bafy-cid','gateway':'https://gateway.invalid'},'FILEBASE_DOWNLOAD_ERROR',{'cid':'bafy-cid','gateway':'https://gateway.invalid'}), + ('ArweaveUploadError',(),{'node_url':'https://node.invalid','size_bytes':100},'ARWEAVE_UPLOAD_ERROR',{'node_url':'https://node.invalid','size_bytes':100}), + ('ArweaveDownloadError',(),{'tx_id':'tx1','gateway':'https://gateway.invalid'},'ARWEAVE_DOWNLOAD_ERROR',{'tx_id':'tx1','gateway':'https://gateway.invalid'}), + ('InsufficientFundsError',(10,50),{'currency':'AR'},'INSUFFICIENT_FUNDS',{'balance':10,'required':50,'currency':'AR'}), + ('SSRFProtectionError',('http://blocked.invalid',),{'reason':'blocked'},'SSRF_PROTECTION_ERROR',{'url':'http://blocked.invalid','reason':'blocked'}), + ('FileSizeLimitError',('too large',),{'file_size':100,'max_size':90},'FILE_SIZE_LIMIT',{'file_size':100,'max_size':90}), + ('CircuitBreakerOpenError',(),{'gateway':'https://gateway.invalid','reset_at':1000},'CIRCUIT_BREAKER_OPEN',{'gateway':'https://gateway.invalid','reset_at':1000}), +]) +def test_storage_failures_have_stable_codes_context_and_redacted_credentials(kind,args,kwargs,code,attributes,monkeypatch): + monkeypatch.setattr('agirails.errors.base.DEBUG_MODE',False) + error=getattr(storage,kind)(*args,**kwargs,details={'request_id':'r-1','api_key':'dummy-not-a-credential'}) + wire=error.to_dict() + assert wire['code']==code and wire['message'] + assert wire['details']['request_id']=='r-1' + assert wire['details']['api_key']=='[REDACTED]' + assert error.to_dict(include_sensitive=True)['details']['api_key']=='dummy-not-a-credential' + for name,value in attributes.items():assert getattr(error,name)==value + assert json.loads(json.dumps(wire))['code']==code diff --git a/tests/test_wallet/test_auto_wallet_create_actp.py b/tests/test_wallet/test_auto_wallet_create_actp.py index b18c169..dd37ea8 100644 --- a/tests/test_wallet/test_auto_wallet_create_actp.py +++ b/tests/test_wallet/test_auto_wallet_create_actp.py @@ -156,8 +156,10 @@ async def test_encodes_correct_create_transaction_calldata(self) -> None: calls, _ = submit.await_args.args data = bytes.fromhex(calls[0].data[2:])[4:] # strip 0x + 4-byte selector + # Canonical AIP-14c v2: 9-input createTransaction (agreementHash 7th, between serviceHash + # and agentId). agreementHash defaults to bytes32(0); agentId shifts to position 7. decoded = abi_decode( - ["address", "address", "uint256", "uint256", "uint256", "bytes32", "uint256", "uint256"], + ["address", "address", "uint256", "uint256", "uint256", "bytes32", "bytes32", "uint256", "uint256"], data, ) assert Web3.to_checksum_address(decoded[0]) == Web3.to_checksum_address(PROVIDER_ADDR) @@ -166,7 +168,8 @@ async def test_encodes_correct_create_transaction_calldata(self) -> None: assert decoded[3] == 1_900_000_000 assert decoded[4] == 172800 assert "0x" + decoded[5].hex() == service_hash - assert decoded[6] == 42 + assert decoded[6] == b"\x00" * 32 # agreementHash default (no auto AI ruling) + assert decoded[7] == 42 # agentId @pytest.mark.asyncio async def test_returns_failure_receipt_without_throwing(self) -> None: diff --git a/tests/test_wallet/test_dual_nonce_manager.py b/tests/test_wallet/test_dual_nonce_manager.py index e270368..b0048ae 100644 --- a/tests/test_wallet/test_dual_nonce_manager.py +++ b/tests/test_wallet/test_dual_nonce_manager.py @@ -5,7 +5,7 @@ - Sequential execution (mutex) - ACTP nonce increment on success - Cache reset on failure -- Fallback to 0 on missing requesterNonces +- Fail closed (raise) when the ACTP nonce is unprovable (never infer 0) - Cache invalidation - Error propagation """ @@ -17,6 +17,7 @@ from unittest.mock import MagicMock, patch from web3 import Web3 +from web3.exceptions import BadFunctionCallOutput from agirails.wallet.aa.dual_nonce_manager import ( DualNonceManager, @@ -61,8 +62,8 @@ def mock_contract_factory(address, abi): if any("getNonce" in str(item) for item in abi): contract.functions.getNonce.return_value.call.return_value = entry_point_nonce elif any("requesterNonces" in str(item) for item in abi): - contract.functions.requesterNonces.return_value.call.side_effect = Exception( - "method not found" + contract.functions.requesterNonces.return_value.call.side_effect = BadFunctionCallOutput( + "Could not decode contract function call to requesterNonces with return data 0x" ) return contract @@ -234,20 +235,28 @@ async def callback(nonces: NonceSet) -> EnqueueResult[str]: assert captured["nonce"] >= 1 @pytest.mark.asyncio - async def test_last_resort_zero_when_event_derivation_fails(self) -> None: - """Falls back to 0 only when event derivation itself fails.""" + async def test_fail_closed_when_event_derivation_fails(self) -> None: + """FAIL CLOSED (F38): raise, never silently infer nonce = 0. + + Returning 0 on a scan failure would reset the replay-protection + counter and enable txId/batch replay, so an unprovable nonce must + surface an explicit error and leave the cache unset. + """ w3 = _make_mock_w3_no_nonce(entry_point_nonce=0) type(w3.eth).block_number = property(lambda self: 100) - # No code anywhere → deployment-block search raises → last-resort 0. + # No code anywhere → deployment-block search raises → must fail closed. w3.eth.get_code.side_effect = lambda addr, block: b"" mgr = DualNonceManager(w3, SENDER, ACTP_KERNEL) async def callback(nonces: NonceSet) -> EnqueueResult[str]: - assert nonces.actp_nonce == 0 - return EnqueueResult(result="ok", success=True) + raise AssertionError("callback must not run when nonce is unprovable") - await mgr.enqueue(callback) + with pytest.raises(RuntimeError, match="Refusing to infer nonce"): + await mgr.enqueue(callback) + + # Cache must be left unset so the next attempt re-reads from chain. + assert mgr._cached_actp_nonce is None @pytest.mark.asyncio async def test_read_entry_point_nonce_is_public(self) -> None: @@ -329,3 +338,46 @@ async def callback(nonces: NonceSet) -> EnqueueResult[str]: assert len(results) == 3 # Execution order should be sequential (1,2,3) due to mutex assert execution_order == [1, 2, 3] + + +@pytest.mark.asyncio +async def test_real_encoded_legacy_and_canonical_history_and_requester_filter(): + from eth_abi import encode + + def creation(agreement, requester, index): + signature = "TransactionCreated(bytes32,address,address,uint256,bytes32,uint256,uint256,uint256" + (",bytes32)" if agreement else ")") + types = ["uint256", "bytes32", "uint256", "uint256", "uint256"] + values = [1, bytes(32), 1, 2, 1] + if agreement: + types.append("bytes32") + values.append(bytes(32)) + return { + "topics": [Web3.to_hex(Web3.keccak(text=signature)), "0x" + "00" * 32, "0x" + requester[2:].rjust(64, "0"), "0x" + "33" * 32], + "data": Web3.to_hex(encode(types, values)), "logIndex": index, + } + + other = "0x" + "33" * 20 + history = [creation(False, SENDER, 0), creation(True, SENDER, 1), creation(False, other, 2)] + w3 = _make_mock_w3_no_nonce() + w3.eth.block_number = 10 + w3.eth.get_code.side_effect = lambda address, block: b"\x60" if block >= 1 else b"" + w3.eth.get_logs.side_effect = lambda query: [log for log in history if log["topics"][0] in query["topics"][0] and log["topics"][2] == query["topics"][2]] + manager = DualNonceManager(w3, SENDER, ACTP_KERNEL, known_deployment_block=1) + assert await manager._read_actp_nonce() == 2 + fresh = DualNonceManager(w3, "0x" + "44" * 20, ACTP_KERNEL, known_deployment_block=1) + assert await fresh._read_actp_nonce() == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error", [ConnectionError("RPC offline"), TimeoutError("RPC timeout"), ValueError("RPC rate limit")]) +async def test_transport_failures_never_enter_legacy_scan(error): + w3 = _make_mock_w3() + contract = MagicMock() + contract.functions.requesterNonces.return_value.call.side_effect = error + w3.eth.contract.return_value = contract + w3.eth.contract.side_effect = None + manager = DualNonceManager(w3, SENDER, ACTP_KERNEL) + with pytest.raises(RuntimeError, match="refusing to infer"): + await manager._read_actp_nonce() + w3.eth.get_logs.assert_not_called() + assert manager._cached_actp_nonce is None diff --git a/tests/test_wallet/test_wallet_wire_boundaries.py b/tests/test_wallet/test_wallet_wire_boundaries.py new file mode 100644 index 0000000..ed3ecf1 --- /dev/null +++ b/tests/test_wallet/test_wallet_wire_boundaries.py @@ -0,0 +1,196 @@ +"""Wire-level wallet sponsorship failover, real EOA signatures, message verification.""" + +import copy +import json + +from eth_account import Account +from hexbytes import HexBytes +import httpx +import pytest +import rlp +from web3 import Web3 +from web3.providers import BaseProvider + +from agirails.config.networks import BASE_SEPOLIA +from agirails.protocol.messages import MessageSigner, SignatureComponents, SECP256K1_N +from agirails.types.message import ServiceRequest, ServiceResponse, DeliveryProof, DeliveryProofMessage +from agirails.wallet.eoa_wallet_provider import EOAWalletProvider +from agirails.wallet.auto_wallet_provider import TransactionRequest +from agirails.wallet.aa.paymaster_client import PaymasterClient, PaymasterConfig, PaymasterError +from agirails.wallet.aa.constants import UserOperationV06, ENTRYPOINT_V06 + +KEY = '0x' + '12' * 32 +ADDRESS = Web3.to_checksum_address('0x' + '23' * 20) +HASH = '0x' + '34' * 32 + + +class LocalEOARPC(BaseProvider): + def __init__(self, fail_estimate=False, rewards=True, statuses=(1,)): + super().__init__() + self.fail_estimate = fail_estimate + self.rewards = rewards + self.statuses = iter(statuses) + self.sent = [] + self.nonce = 5 + + def make_request(self, method, params): + if method == 'eth_chainId': + result = hex(84532) + elif method == 'eth_getTransactionCount': + result = hex(self.nonce) + elif method == 'eth_estimateGas': + if self.fail_estimate: raise ValueError('estimator unavailable') + result = hex(42000) + elif method == 'eth_feeHistory': + result = {'oldestBlock':'0x1','baseFeePerGas':['0x64','0x64'], 'gasUsedRatio':[0.5]} + if self.rewards: result['reward'] = [['0x2']] + elif method == 'eth_sendRawTransaction': + raw = HexBytes(params[0]) + self.sent.append((raw, next(self.statuses))) + self.nonce += 1 + result = Web3.to_hex(Web3.keccak(raw)) + elif method == 'eth_getTransactionReceipt': + result = {'transactionHash': params[0], 'status':hex(self.sent[-1][1]), + 'transactionIndex':'0x0','blockNumber':'0x1','blockHash':HASH, + 'from':Account.from_key(KEY).address,'to':ADDRESS,'gasUsed':'0xa410', + 'cumulativeGasUsed':'0xa410','contractAddress':None,'logs':[], + 'logsBloom':'0x'+'00'*256,'type':'0x2','effectiveGasPrice':'0x66'} + else: + raise AssertionError('Unexpected RPC method: '+method) + return {'jsonrpc':'2.0','id':1,'result':result} + + +@pytest.mark.asyncio +@pytest.mark.parametrize('fallback,rewards', [(False,True),(True,True),(False,False)]) +async def test_eoa_signs_actual_value_nonce_chain_and_fees(fallback, rewards): + rpc = LocalEOARPC(fail_estimate=fallback,rewards=rewards) + provider = EOAWalletProvider(KEY, Web3(rpc), 84532) + receipt = await provider.send_transaction(TransactionRequest(ADDRESS,'0x1234','123')) + raw = rpc.sent[0][0] + assert receipt.success is True + assert receipt.hash == Web3.keccak(raw).hex() + assert Account.recover_transaction(raw) == provider.get_address() + fields = rlp.decode(raw[1:]) + integer = lambda i: int.from_bytes(fields[i], 'big') + assert integer(0) == 84532 and integer(1) == 5 + assert integer(4) == (500000 if fallback else 42000) + assert integer(6) == 123 and fields[7] == bytes.fromhex('1234') + priority = 2 if rewards else 1000000000 + assert integer(2) == priority and integer(3) == 200+priority + info = provider.get_wallet_info() + assert info.tier == 'eoa' and info.gas_sponsored is False + assert info.supports_batching is False and info.chain_id == 84532 + + +@pytest.mark.asyncio +@pytest.mark.parametrize('statuses,count,success', [((1,1),2,True),((0,),1,False),((1,0),2,False)]) +async def test_eoa_batch_stops_on_failed_receipt(statuses,count,success): + rpc = LocalEOARPC(statuses=statuses) + provider = EOAWalletProvider(KEY, Web3(rpc), 84532) + receipt = await provider.send_batch_transaction([TransactionRequest(ADDRESS,'0x'),TransactionRequest(ADDRESS,'0x')]) + assert len(rpc.sent) == count and receipt.success is success + with pytest.raises(ValueError, match='at least one'): + await provider.send_batch_transaction([]) + assert len(rpc.sent) == count + + +@pytest.mark.asyncio +@pytest.mark.parametrize('method,wire', [('get_paymaster_stub_data','pm_getPaymasterStubData'),('get_paymaster_data','pm_getPaymasterData')]) +@pytest.mark.parametrize('primary_failure', [None,'http','rpc','transport']) +async def test_paymaster_serializes_network_and_uses_backup_only_on_failure(monkeypatch,method,wire,primary_failure): + seen = [] + original_client = httpx.AsyncClient + def handler(request): + body = json.loads(request.content) + seen.append((request.url.host,body)) + if request.url.host == 'primary.invalid' and primary_failure: + if primary_failure == 'transport': raise httpx.ConnectError('offline',request=request) + if primary_failure == 'http': return httpx.Response(503,text='unavailable') + return httpx.Response(200,json={'error':{'code':-32000,'message':'declined','data':'policy'}}) + return httpx.Response(200,json={'result':{'paymasterAndData':'0xabc123'}}) + monkeypatch.setattr('agirails.wallet.aa.paymaster_client.httpx.AsyncClient',lambda **kw: original_client(transport=httpx.MockTransport(handler),**kw)) + client = PaymasterClient(PaymasterConfig('https://primary.invalid',84532,backup_url='https://backup.invalid')) + operation = UserOperationV06(sender=ADDRESS,nonce=7,call_gas_limit=120000) + result = await getattr(client,method)(operation) + assert result.paymaster_and_data == '0xabc123' + assert [host for host,_ in seen] == (['primary.invalid','backup.invalid'] if primary_failure else ['primary.invalid']) + assert [body['id'] for _,body in seen] == list(range(1,len(seen)+1)) + for _,body in seen: + assert body['method'] == wire + op,entrypoint,chain,context = body['params'] + assert op['sender'] == ADDRESS and op['nonce'] == '0x7' + assert op['callGasLimit'] == hex(120000) + assert (entrypoint,chain,context) == (ENTRYPOINT_V06,hex(84532),{}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('backup', [False,True]) +async def test_unavailable_sponsorship_raises_without_pretending_success(monkeypatch,backup): + original_client = httpx.AsyncClient + hosts=[] + def handler(request): + hosts.append(request.url.host) + return httpx.Response(200,json={'error':{'code':-1,'message':'declined'}}) + monkeypatch.setattr('agirails.wallet.aa.paymaster_client.httpx.AsyncClient',lambda **kw: original_client(transport=httpx.MockTransport(handler),**kw)) + client=PaymasterClient(PaymasterConfig('https://primary.invalid',84532,backup_url='https://backup.invalid' if backup else None)) + with pytest.raises(PaymasterError,match='both Coinbase and Pimlico' if backup else 'No backup'): + await client.get_paymaster_data(UserOperationV06(sender=ADDRESS)) + assert len(hosts) == (2 if backup else 1) + + +@pytest.mark.parametrize('kind', ['request','response','delivery']) +@pytest.mark.parametrize('with_contract', [False,True]) +def test_legacy_typed_messages_recover_owner_and_reject_tampering(kind,with_contract): + signer = MessageSigner(KEY,chain_id=84532,verifying_contract=ADDRESS if with_contract else '') + if kind == 'request': + signed = signer.sign_request(ServiceRequest('echo',HASH,1000000,1700000000,provider=ADDRESS)) + field = 'budget' + elif kind == 'response': + signed = signer.sign_response(ServiceResponse(HASH,HASH,1)) + field = 'status' + else: + signed = signer.sign_delivery_proof(DeliveryProof(HASH,HASH,attestation_uid=HASH)) + field = 'timestamp' + assert signer.verify_signature(signed) + assert signer.verify_signature(signed,expected_signer=signer.address.lower()) + assert not signer.verify_signature(signed,expected_signer=ADDRESS) + bad = copy.deepcopy(signed) + bad.message[field] += 1 + assert not signer.verify_signature(bad) + bad = copy.deepcopy(signed);bad.message_type='unsupported' + assert not signer.verify_signature(bad) + bad = copy.deepcopy(signed);bad.signature='' + assert not signer.verify_signature(bad) + bad = copy.deepcopy(signed);bad.signature='0xzz' + assert not signer.verify_signature(bad,reject_malleable=False) + high = copy.deepcopy(signed) + parts = SignatureComponents.from_signature(high.signature) + high.signature=SignatureComponents(27 if parts.v==28 else 28,parts.r,(SECP256K1_N-int.from_bytes(parts.s,'big')).to_bytes(32,'big')).to_hex() + assert not signer.verify_signature(high) + assert signer.verify_signature(high,reject_malleable=False) + + +@pytest.mark.parametrize('kind',['actp_kernel','escrow_vault']) +def test_message_domain_selects_configured_contract(kind): + signer=MessageSigner.from_config(KEY,BASE_SEPOLIA,contract_type=kind) + assert signer.domain.verifying_contract == getattr(BASE_SEPOLIA.contracts,kind) + assert signer.domain.chain_id == 84532 + with pytest.raises(ValueError,match='Unknown contract'): + MessageSigner.from_config(KEY,BASE_SEPOLIA,contract_type='unknown') + + +@pytest.mark.parametrize('with_contract',[False,True]) +def test_modern_delivery_schema_and_ambiguous_payloads(with_contract): + signer=MessageSigner(KEY, chain_id=84532,verifying_contract=ADDRESS if with_contract else '') + proof=DeliveryProofMessage(HASH,'did:ethr:84532:'+signer.address,'did:ethr:84532:'+ADDRESS,'bafy-result',HASH,HASH,1700000000,84532,4) + signed=signer.sign_delivery_proof_message(proof) + assert signer.verify_signature(signed) + tampered=copy.deepcopy(signed);tampered.message['nonce']+=1 + assert not signer.verify_signature(tampered) + missing=copy.deepcopy(signed);del missing.message['txId'] + assert not signer.verify_signature(missing) + ambiguous=copy.deepcopy(signed) + ambiguous.message.update(transactionId=HASH,outputHash=HASH,attestationUid=HASH,timestamp=1700000000) + assert not signer.verify_signature(ambiguous) + malformed=copy.deepcopy(signed);malformed.message=None + assert not signer.verify_signature(malformed)