From 2f4469f4c4fe1e189660f0f2ac61cdedcb19477b Mon Sep 17 00:00:00 2001 From: RunTimeAdmin <248247024+RunTimeAdmin@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:32:27 -0600 Subject: [PATCH 1/2] Fix three minor contract findings from the 15 November performance review - 17: initiateSlash refuses evidence longer than MAX_EVIDENCE_BYTES (256) with EvidenceTooLong. Staking gains slashState, the state of the latest proposal alone, and the Reader reads it instead of copying the whole proposal with its evidence. A trust read of an agent with a slash open falls from 86,184 gas (one byte of evidence) and 104,554 (256 bytes) to 68,501 either way. - 18: verifyEvidence checks the proof with MerkleProof.verifyCalldata instead of copying it into memory. An eleven-hash proof falls from 10,654 to 10,411 gas. - 19: identity gains standingOf (operator, status, registeredAt). Reputation's scorability check and staking's deposit, withdrawal, claim and dispute read it instead of getIdentity, about 4,900 gas less a call. Upgrade.s.sol refuses a reputation or staking upgrade against an identity without it. No storage is added or moved: forge inspect gives the same layouts for identity, reputation and staking. On testnet the order is identity, then reputation, then staking once the drill ends, then a new Reader. getIdentity and getSlashProposal stay for the keeper, SDK, site and scripts. Mutations R8 and R10 follow the renamed locals. 815 forge tests, 12 of them skipped without a fork URL. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/adr/0010-what-can-be-slashed.md | 3 +- docs/authorisation-matrix.md | 2 +- docs/integration.md | 6 ++ docs/whitepaper.md | 2 +- script/Upgrade.s.sol | 16 +++- scripts/mutation/mutate-invariants.sh | 4 +- src/SigvaraIdentity.sol | 18 ++++ src/SigvaraReader.sol | 2 +- src/SigvaraReputation.sol | 10 ++- src/SigvaraStaking.sol | 53 ++++++++---- src/interfaces/ISigvara.sol | 4 + test/SigvaraIdentity.t.sol | 49 +++++++++++ test/SigvaraReader.t.sol | 63 ++++++++++++++ test/SigvaraReputation.t.sol | 86 +++++++++++++++---- test/SigvaraStaking.t.sol | 119 ++++++++++++++++++++++++++ test/Upgrade.t.sol | 38 ++++++++ 17 files changed, 433 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index b0498260..9820e15d 100644 --- a/README.md +++ b/README.md @@ -600,11 +600,11 @@ Everything below runs offline, with no deployed contracts, except three fork sui | Suite | Count | Command | |---|---|---| -| Contracts: unit, fuzz, E2E, upgrade, deploy-script, handover and 22 invariants | 799 | `forge test` | +| Contracts: unit, fuzz, E2E, upgrade, deploy-script, handover and 22 invariants | 815 | `forge test` | | Oracle | 1532 | `cd oracle && node --test` | | SDK | 385 | `cd packages/sdk && npx vitest run` | -Counts are individual tests, so each of the 22 invariants counts once. The contracts were counted on 15 November 2026, the SDK on 15 November and the oracle on 15 November. Without a fork URL, 787 of the contract tests run and 12 skip. Run after `npm run build`, 376 of the SDK's 385 pass and 9 skip: the 8 integration tests, which need a live deployment, and one check that runs only in CI. Without a build, the 9 built-package tests skip too. Vitest strips types without checking them, so `npm run typecheck` in `packages/sdk` checks the tests against the SDK's types as well as the sources. [`scripts/mutation`](scripts/mutation/README.md) holds the harnesses that measure whether these tests would catch a deliberate break in the contracts or deploy scripts. +Counts are individual tests, so each of the 22 invariants counts once. The contracts were counted on 15 November 2026, the SDK on 15 November and the oracle on 15 November. Without a fork URL, 803 of the contract tests run and 12 skip. Run after `npm run build`, 376 of the SDK's 385 pass and 9 skip: the 8 integration tests, which need a live deployment, and one check that runs only in CI. Without a build, the 9 built-package tests skip too. Vitest strips types without checking them, so `npm run typecheck` in `packages/sdk` checks the tests against the SDK's types as well as the sources. [`scripts/mutation`](scripts/mutation/README.md) holds the harnesses that measure whether these tests would catch a deliberate break in the contracts or deploy scripts. Merges to `main` carry `[skip ci]`, to save CI minutes, so the push to `main` does not run the suites again. A change to code runs them on its pull request and merges only once every job there has passed; a docs-only change is checked locally with `node scripts/check-docs.mjs`. Each is checked against the `main` its branch started from, so two changes merged close together can still break `main`. That happened once, on 11 November 2026, and the next merge fixed it. The rule that every job must pass dates from 14 November 2026: before it, #281, #282 and #288 merged with their oracle job failing, and #283 and #297 fixed the tests that failed. On 13 November the oracle and SDK suites were run on `main` at `eaccb91` and passed. diff --git a/docs/adr/0010-what-can-be-slashed.md b/docs/adr/0010-what-can-be-slashed.md index 5c8e6059..3191c39d 100644 --- a/docs/adr/0010-what-can-be-slashed.md +++ b/docs/adr/0010-what-can-be-slashed.md @@ -92,7 +92,8 @@ The contract takes one address, and it cannot be zero, the reporter, a committee `evidenceHash` is free-form, so no contract change is needed. The bytes read `sigvara/slash/v1;ground=A1;sha256=`, and the package is published when the slash is -filed, as the drill's log was. +filed, as the drill's log was. `initiateSlash` refuses more than 256 bytes (`MAX_EVIDENCE_BYTES`), and this +form takes about a hundred. ### 7. Wrongful slashes and stolen keys diff --git a/docs/authorisation-matrix.md b/docs/authorisation-matrix.md index 8538df7a..868526b4 100644 --- a/docs/authorisation-matrix.md +++ b/docs/authorisation-matrix.md @@ -130,7 +130,7 @@ README's [Access Control Summary](../README.md#access-control-summary). | `grantRole(bytes32,address)` | `inherited` | `-` | The caller holds `getRoleAdmin(role)`. `initialize` makes `UPGRADER_ROLE` the admin of `UPGRADER_ROLE` and `SLASHING_COMMITTEE_ROLE`; `DEFAULT_ADMIN_ROLE` administers itself and `GUARDIAN_ROLE` (OpenZeppelin default). | Grants `role` to `account` if not already held. Emits `RoleGranted`. | | `initialize(address,address,address,address,uint256,uint256,uint256)` | `initializer` | `-` | Once per proxy, by any account (the implementation's initializers are disabled). Nonzero `admin`, token and registries; `minimumStake_` nonzero; challenge period 3 to 10 days; unbonding period 1 to 90 days. | Grants `admin` `DEFAULT_ADMIN_ROLE` and `UPGRADER_ROLE`; makes `UPGRADER_ROLE` the admin of `UPGRADER_ROLE` and `SLASHING_COMMITTEE_ROLE`; stores registries, token and the three parameters. Grants no committee member or guardian. Emits `RoleGranted`, `RoleAdminChanged`, `Initialized`. | | `initializeV2(uint256)` | `reinitializer:2`, `role:DEFAULT_ADMIN_ROLE` | `-` | A `DEFAULT_ADMIN_ROLE` holder, once: initializer version 2 must be unconsumed, which is still true after a fresh `initialize`, so `Deploy.s.sol` calls it at once and `check-mainnet.sh` checks it ran. Period 1 to 90 days. | Sets `unbondingPeriod` and consumes version 2. Emits `UnbondingPeriodUpdated` and `Initialized(2)`. | -| `initiateSlash(bytes32,address,bytes)` | `role:SLASHING_COMMITTEE_ROLE` | `-` | A `SLASHING_COMMITTEE_ROLE` holder. Victim nonzero, not the caller, not any committee member, not a `DEFAULT_ADMIN_ROLE` holder; active plus queued stake nonzero; no `Pending` or `Disputed` proposal; one `challengePeriod` since the last drop; evidence not previously rejected by the admin. | Writes a `Pending` proposal (reporter, victim, evidence, `challengeDeadline` = now + `challengePeriod`), replacing any closed one; suspends the agent in `SigvaraIdentity` and freezes withdrawals. Emits `SlashInitiated`. | +| `initiateSlash(bytes32,address,bytes)` | `role:SLASHING_COMMITTEE_ROLE` | `-` | A `SLASHING_COMMITTEE_ROLE` holder. Victim nonzero, not the caller, not any committee member, not a `DEFAULT_ADMIN_ROLE` holder; active plus queued stake nonzero; no `Pending` or `Disputed` proposal; one `challengePeriod` since the last drop; evidence at most `MAX_EVIDENCE_BYTES` (256) long and not previously rejected by the admin. | Writes a `Pending` proposal (reporter, victim, evidence, `challengeDeadline` = now + `challengePeriod`), replacing any closed one; suspends the agent in `SigvaraIdentity` and freezes withdrawals. Emits `SlashInitiated`. | | `initiateWithdrawal(bytes32,uint256)` | `checked` | `-` | The agent's current operator. Stake and `amount` nonzero; no withdrawal already queued; no `Pending` or `Disputed` slash; `amount` at most the stake; an `Active` agent must keep at least `minimumStake`. | Moves `amount` from the stake into the unbonding queue, sets `unbondingAt` and fixes `unbondingClaimableAt` at now plus `unbondingPeriod`. Queued stake stays slashable. Emits `WithdrawalInitiated`. | | `pauseInflows()` | `checked` | `-` | A `GUARDIAN_ROLE` holder (`_checkGuardian`). No pause running, and `PAUSE_DURATION` plus `PAUSE_COOLDOWN` (4 days) since the previous pause began, even if it was lifted early. | Closes `depositStake`, the only `inflows`-guarded function, for 3 days; it reopens by itself. Withdrawals, claims, disputes, slashing and admin calls stay open. Records `lastPausedAt`. Emits `InflowsPaused`. | | `renounceRole(bytes32,address)` | `inherited` | `-` | Only the account itself: `callerConfirmation` must equal the caller. | Removes `role` from the caller if held. Emits `RoleRevoked`. If the last `UPGRADER_ROLE` holder renounces, upgrades and committee grants end for good. | diff --git a/docs/integration.md b/docs/integration.md index 5c5fd8af..845a040a 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -248,6 +248,12 @@ running older code than the interfaces expect. Registry addresses are in `deployments/.json`, which does not list a reader. If a registry upgrade ever changes a function the reader calls, deploy a new reader. +A reader built from the current source reads the slash state with staking's `slashState`, which +copies one field where `getSlashProposal` copied the whole proposal and its evidence. A staking +proxy running code from before that view cannot answer it, and every `trust` call for a +registered agent would revert, so deploy such a reader only after staking is upgraded, with +`SMOKE_AGENT` set. The reader already on Arc testnet calls `getSlashProposal`, which stays. + ## Example [`examples/gated-marketplace/GatedMarketplace.sol`](../examples/gated-marketplace/GatedMarketplace.sol) diff --git a/docs/whitepaper.md b/docs/whitepaper.md index 80d9bfc6..a883938c 100644 --- a/docs/whitepaper.md +++ b/docs/whitepaper.md @@ -633,7 +633,7 @@ roles, and administers `UPGRADER_ROLE`), and the timelocked role grants describe apply to a fresh deployment, not to the testnet. `node scripts/record-implementations.mjs --check` shows what is live. -**Test coverage**, as of 15 November 2026: 799 contract tests across 36 Foundry test files +**Test coverage**, as of 15 November 2026: 815 contract tests across 36 Foundry test files including fuzz and invariant tests (the two slash drill suites fork Arc testnet themselves, and the twelve in `SplitAuthorityFork` skip without `--fork-url`), 1532 oracle tests and 385 in the SDK (9 skip outside CI and without a live deployment; every test that runs passes). CI runs Foundry, the oracle and diff --git a/script/Upgrade.s.sol b/script/Upgrade.s.sol index a3b3b15e..c45b1d6a 100644 --- a/script/Upgrade.s.sol +++ b/script/Upgrade.s.sol @@ -117,8 +117,12 @@ contract Upgrade is Script { * upgrade landed. The tests never caught it because they deploy both * contracts from the same source every time; only a live pair can be skewed. * - * The contracts are now tolerant of the skew as well. This is the second + * The contracts are now tolerant of that skew as well. This is the second * layer: refuse the ordering rather than quietly degrade into it. + * + * For standingOf, which reputation and staking read on their write paths, this + * check is the only layer. They do not fall back to getIdentity, because + * upgrading identity first is safe: it only adds the view. */ function _checkDependencies(string memory target, address proxy) internal view { bytes32 t = keccak256(bytes(target)); @@ -129,6 +133,11 @@ contract Upgrade is Script { if (!_answers(identity, abi.encodeWithSignature("operatorChangedAt(bytes32)", bytes32(0)))) { revert DependencyMissing("reputation", "identity.operatorChangedAt: upgrade identity first", identity); } + // Every proposal and finalize reads the agent through standingOf, so against an + // identity without it the oracle could write no score at all. + if (!_answers(identity, abi.encodeWithSignature("standingOf(bytes32)", bytes32(0)))) { + revert DependencyMissing("reputation", "identity.standingOf: upgrade identity first", identity); + } } if (t == keccak256("staking")) { @@ -139,6 +148,11 @@ contract Upgrade is Script { if (!_answers(identity, abi.encodeWithSignature("stakeView()"))) { revert DependencyMissing("staking", "identity.stakeView: upgrade identity first", identity); } + // Deposits, withdrawals, claims and disputes read the agent through standingOf, + // so against an identity without it each of them would revert. + if (!_answers(identity, abi.encodeWithSignature("standingOf(bytes32)", bytes32(0)))) { + revert DependencyMissing("staking", "identity.standingOf: upgrade identity first", identity); + } } } diff --git a/scripts/mutation/mutate-invariants.sh b/scripts/mutation/mutate-invariants.sh index 06758a5b..c03edcc0 100644 --- a/scripts/mutation/mutate-invariants.sh +++ b/scripts/mutation/mutate-invariants.sh @@ -53,9 +53,9 @@ runl R7 $RS $R 'function _propose(' '_requireBondedOracle();' '_requireBondedOr # R8 and R10 are expected survivors. A slash zeroes the stake and a slashed agent cannot bond again, and a hash nobody # registered holds no stake, so the bond check refuses the same proposals and only the name of the error differs. The # invariants check what is refused, not why; E2E.t.sol and SigvaraReputation.t.sol pin the names. -runl R8 $RS $R 'function _requireScorable(' 'if (id.status == SigvaraIdentity.AgentStatus.Slashed)' 'id.status == SigvaraIdentity.AgentStatus.Slashed' 'false' 'a slashed agent can be scored' +runl R8 $RS $R 'function _requireScorable(' 'if (status == SigvaraIdentity.AgentStatus.Slashed)' 'status == SigvaraIdentity.AgentStatus.Slashed' 'false' 'a slashed agent can be scored' runl R9 $RS $R 'function _requireScorable(' 'if (!stakeView.hasMinimumStake(didHash))' '!stakeView.hasMinimumStake(didHash)' 'false' 'an unbonded agent can be scored' -runl R10 $RS $R 'function _requireScorable(' 'if (id.registeredAt == 0)' 'id.registeredAt == 0' 'false' 'an unregistered hash can be scored' +runl R10 $RS $R 'function _requireScorable(' 'if (registeredAt == 0)' 'registeredAt == 0' 'false' 'an unregistered hash can be scored' runl R11 $RS $R 'function proposeReputation(' 'onlyRole(ORACLE_ROLE)' 'onlyRole(ORACLE_ROLE)' '' 'anyone can propose' runl R12 $RS $R 'function proposeReputation(' 'whenInflowsOpen' 'whenInflowsOpen' '' 'a pause does not stop proposals' runl R13 $RS $R 'function proposeIfEmpty(' 'if (existing.exists && _proposerStillAuthorized(existing.proposer))' '_proposerStillAuthorized(existing.proposer)' 'false' 'proposeIfEmpty replaces a live proposal' diff --git a/src/SigvaraIdentity.sol b/src/SigvaraIdentity.sol index ced5f56a..d9643cb7 100644 --- a/src/SigvaraIdentity.sol +++ b/src/SigvaraIdentity.sol @@ -573,6 +573,24 @@ contract SigvaraIdentity is Initializable, TimelockedGrants, UUPSUpgradeable, In return identities[didHash]; } + /** + * @notice Who operates the agent, its status, and when it was registered. registeredAt is zero + * for a didHash that was never registered, and status then reads Active, the zero value, + * so check registeredAt first. + * @dev The three fields the reputation and staking registries act on. getIdentity copies all + * five out of storage, and the agent address and the Ed25519 key are two storage reads + * those callers never use. Both registries call this, so a live identity proxy runs this + * code before either of them does; script/Upgrade.s.sol refuses the other order. + */ + function standingOf(bytes32 didHash) + external + view + returns (address operator, AgentStatus status, uint256 registeredAt) + { + AgentIdentity storage id = identities[didHash]; + return (id.operator, id.status, id.registeredAt); + } + function isActive(bytes32 didHash) external view returns (bool) { AgentIdentity storage id = identities[didHash]; return id.registeredAt != 0 && id.status == AgentStatus.Active; diff --git a/src/SigvaraReader.sol b/src/SigvaraReader.sol index ef88e793..042f5971 100644 --- a/src/SigvaraReader.sol +++ b/src/SigvaraReader.sol @@ -111,7 +111,7 @@ contract SigvaraReader is ISigvaraReader { t.score = reputation.getTotalScore(didHash); t.earned = reputation.getEarnedScore(didHash); t.stake = staking.getStake(didHash); - t.slash = staking.getSlashProposal(didHash).state; + t.slash = staking.slashState(didHash); t.collateralized = staking.hasMinimumStake(didHash); t.scoreUpdatedAt = reputation.getReputation(didHash).lastUpdated; } diff --git a/src/SigvaraReputation.sol b/src/SigvaraReputation.sol index b7638a12..41c7a90b 100644 --- a/src/SigvaraReputation.sol +++ b/src/SigvaraReputation.sol @@ -657,9 +657,9 @@ contract SigvaraReputation is Initializable, TimelockedGrants, UUPSUpgradeable, SigvaraIdentity registry = identityRegistry; if (address(registry) == address(0)) revert IdentityRegistryNotSet(); - SigvaraIdentity.AgentIdentity memory id = registry.getIdentity(didHash); - if (id.registeredAt == 0) revert AgentNotRegistered(didHash); - if (id.status == SigvaraIdentity.AgentStatus.Slashed) revert AgentSlashed(didHash); + (, SigvaraIdentity.AgentStatus status, uint256 registeredAt) = registry.standingOf(didHash); + if (registeredAt == 0) revert AgentNotRegistered(didHash); + if (status == SigvaraIdentity.AgentStatus.Slashed) revert AgentSlashed(didHash); IStakeView stakeView = registry.stakeView(); if (address(stakeView) == address(0)) revert StakeViewNotSet(); @@ -818,7 +818,9 @@ contract SigvaraReputation is Initializable, TimelockedGrants, UUPSUpgradeable, { bytes32 root = evidenceRoots[didHash]; if (root == bytes32(0)) return false; - return MerkleProof.verify(proof, root, leaf); + // Reads the proof where it lies. verify takes it from memory, so the proof was copied + // there first, for the same answer. + return MerkleProof.verifyCalldata(proof, root, leaf); } /// @notice The score as computed, before maturity is applied. Max 100. diff --git a/src/SigvaraStaking.sol b/src/SigvaraStaking.sol index 242d3bd7..d93ee1d5 100644 --- a/src/SigvaraStaking.sol +++ b/src/SigvaraStaking.sol @@ -18,11 +18,11 @@ import "./SigvaraIdentity.sol"; * again) into this compile graph for a single `zeroReputation(bytes32)`. * * SigvaraIdentity is deliberately NOT narrowed the same way. This contract reads - * `AgentIdentity` and compares `AgentStatus` in sixteen places, so an interface - * would have to redeclare both. A redeclared enum that drifted from the real one - * would not fail to compile; it would silently reinterpret the status of every - * live agent, which is the failure this codebase keeps appending storage to avoid. - * Sharing one definition is worth the import. + * `AgentStatus` through `standingOf` and compares or sets it in seven places, so + * an interface would have to redeclare the enum. A redeclared enum that drifted + * from the real one would not fail to compile; it would silently reinterpret the + * status of every live agent, which is the failure this codebase keeps appending + * storage to avoid. Sharing one definition is worth the import. */ interface IReputationZero { function zeroReputation(bytes32 didHash) external; @@ -210,6 +210,8 @@ contract SigvaraStaking is error SlashCooldownActive(bytes32 didHash, uint256 refileAt); /// The admin already ruled against this evidence for this agent. File new evidence. error EvidenceAlreadyRejected(bytes32 didHash, bytes32 evidenceKey); + /// The evidence is longer than MAX_EVIDENCE_BYTES. File a reference to the package, not the package. + error EvidenceTooLong(uint256 provided, uint256 maximum); error DisputeResolutionActive(bytes32 didHash, uint256 expiresAt); error DisputeResolutionExpired(bytes32 didHash, uint256 expiredAt); /// A Pending proposal is still inside the fortnight in which anyone may execute it. @@ -321,11 +323,12 @@ contract SigvaraStaking is * identity permanently. Slashed agents are terminal and still rejected. */ function depositStake(bytes32 didHash, uint256 amount) external nonReentrant whenInflowsOpen { - SigvaraIdentity.AgentIdentity memory id = identityRegistry.getIdentity(didHash); - if (id.registeredAt == 0 || id.status == SigvaraIdentity.AgentStatus.Slashed) { + (address operator, SigvaraIdentity.AgentStatus status, uint256 registeredAt) = + identityRegistry.standingOf(didHash); + if (registeredAt == 0 || status == SigvaraIdentity.AgentStatus.Slashed) { revert AgentNotActive(didHash); } - if (id.operator != msg.sender) revert NotOperator(didHash, msg.sender); + if (operator != msg.sender) revert NotOperator(didHash, msg.sender); // Credit what arrived, not what was asked for. // @@ -355,7 +358,7 @@ contract SigvaraStaking is // The bond is what activates a new agent. Only from PendingBond: an agent that // suspended itself to withdraw, or that the staking core suspended for a // pending slash, must not be dragged back to Active by topping up. - if (id.status == SigvaraIdentity.AgentStatus.PendingBond + if (status == SigvaraIdentity.AgentStatus.PendingBond && stakes[didHash].amount >= minimumStake) { identityRegistry.updateStatus(didHash, SigvaraIdentity.AgentStatus.Active); } @@ -383,8 +386,9 @@ contract SigvaraStaking is if (amount == 0) revert ZeroWithdrawal(didHash); if (s.unbondingAmount != 0) revert WithdrawalAlreadyPending(didHash); - SigvaraIdentity.AgentIdentity memory id = identityRegistry.getIdentity(didHash); - if (id.operator != msg.sender) revert NotOperator(didHash, msg.sender); + (address operator, SigvaraIdentity.AgentStatus status, uint256 registeredAt) = + identityRegistry.standingOf(didHash); + if (operator != msg.sender) revert NotOperator(didHash, msg.sender); // A Pending or Disputed proposal freezes the bond. Disputing must not // release it: that is what let an operator cancel every proposal for free @@ -406,7 +410,7 @@ contract SigvaraStaking is // active agent drain its entire backing stake in one step, which the total-balance // check in initiateSlash also now guards, but an active agent should never be // unbacked to begin with. - bool active = id.registeredAt != 0 && id.status == SigvaraIdentity.AgentStatus.Active; + bool active = registeredAt != 0 && status == SigvaraIdentity.AgentStatus.Active; if (active && remaining < minimumStake) { revert InsufficientStake(didHash, remaining, minimumStake); } @@ -436,8 +440,8 @@ contract SigvaraStaking is Stake storage s = stakes[didHash]; if (s.unbondingAmount == 0) revert NoWithdrawalPending(didHash); - SigvaraIdentity.AgentIdentity memory id = identityRegistry.getIdentity(didHash); - if (id.operator != msg.sender) revert NotOperator(didHash, msg.sender); + (address operator,,) = identityRegistry.standingOf(didHash); + if (operator != msg.sender) revert NotOperator(didHash, msg.sender); // A queued withdrawal is still slashable. Without this check, safety would // depend on unbondingPeriod staying longer than challengePeriod (both are @@ -472,13 +476,15 @@ contract SigvaraStaking is * @notice Committee member initiates a slash proposal. * @dev Suspends the agent immediately to halt activity during the challenge window. * Evidence hash is the keccak256 of the off-chain evidence package (stored - * for auditability; the package itself lives off-chain). + * for auditability; the package itself lives off-chain). It is at most + * MAX_EVIDENCE_BYTES long. */ function initiateSlash( bytes32 didHash, address victim, bytes calldata evidenceHash ) external nonReentrant onlyRole(SLASHING_COMMITTEE_ROLE) { + if (evidenceHash.length > MAX_EVIDENCE_BYTES) revert EvidenceTooLong(evidenceHash.length, MAX_EVIDENCE_BYTES); if (victim == address(0)) revert ZeroAddress(); // The victim takes 25% of the bond. The committee that files and enforces a slash // must not profit from it, so neither the reporter nor any other member can be @@ -553,8 +559,8 @@ contract SigvaraStaking is revert ChallengePeriodExpired(didHash, deadline); } - SigvaraIdentity.AgentIdentity memory id = identityRegistry.getIdentity(didHash); - if (id.operator != msg.sender) revert NotOperator(didHash, msg.sender); + (address operator,,) = identityRegistry.standingOf(didHash); + if (operator != msg.sender) revert NotOperator(didHash, msg.sender); proposal.state = SlashState.Disputed; proposal.disputedAt = block.timestamp; @@ -842,6 +848,12 @@ contract SigvaraStaking is /// for good. uint256 public constant EXECUTION_PERIOD = 14 days; + /// @notice The most evidence a slash proposal may carry, in bytes. The evidence points at a package + /// published off chain, and ADR 0010 gives it a form (the ground and a sha256 of the package) + /// of about a hundred bytes. It is stored with the proposal, and every read of the whole + /// proposal copies it out, so without a bound its length set the gas of those reads. + uint256 public constant MAX_EVIDENCE_BYTES = 256; + /// @notice The challenge period stays shorter than the unbonding period, and setUnbondingPeriod /// holds the same order from the other side. The refile cooldown is one challenge period, /// and a withdrawal queued after a drop stays slashable only because it waits longer than @@ -892,6 +904,13 @@ contract SigvaraStaking is return slashProposals[didHash]; } + /// @notice Where the latest slash proposal against the agent stands: None if there never was one. + /// @dev The state alone. getSlashProposal copies the whole proposal out of storage, evidence + /// included, and SigvaraReader needs only this on every trust read. + function slashState(bytes32 didHash) external view returns (SlashState) { + return slashProposals[didHash].state; + } + // ------------------------------------------------------------------------- // Inflow pause (see InflowGuard) // ------------------------------------------------------------------------- diff --git a/src/interfaces/ISigvara.sol b/src/interfaces/ISigvara.sol index 79441768..9c5e52d6 100644 --- a/src/interfaces/ISigvara.sol +++ b/src/interfaces/ISigvara.sol @@ -117,6 +117,10 @@ interface ISigvaraStaking { /// was one. function getSlashProposal(bytes32 didHash) external view returns (SlashProposal memory); + /// @notice getSlashProposal(didHash).state alone, without copying the rest of the + /// proposal and its evidence. + function slashState(bytes32 didHash) external view returns (SlashState); + function minimumStake() external view returns (uint256); /// @notice Seconds an operator has to dispute a slash before it can be executed. diff --git a/test/SigvaraIdentity.t.sol b/test/SigvaraIdentity.t.sol index 0333d0be..72d331d9 100644 --- a/test/SigvaraIdentity.t.sol +++ b/test/SigvaraIdentity.t.sol @@ -890,6 +890,55 @@ contract SigvaraIdentityTest is Test, RegistrationHelper { identity.updateStatus(didHash, SigvaraIdentity.AgentStatus.PendingBond); } + // ------------------------------------------------------------------------- + // standingOf + // ------------------------------------------------------------------------- + + /// standingOf is what the reputation and staking registries read in place of getIdentity, so + /// it has to give the same three fields in every state they tell apart: a hash nobody + /// registered, each status an agent passes through, and a new operator after a handover. + function test_standingOf_matchesTheFullRecord() public { + bytes32 nobody = identity.computeDidHash(agent); + _assertStanding(nobody, address(0), SigvaraIdentity.AgentStatus.Active); + assertEq(identity.getIdentity(nobody).registeredAt, 0, "never registered"); + + bytes32 didHash = _register(); + _assertStanding(didHash, operator, SigvaraIdentity.AgentStatus.PendingBond); + + vm.prank(operator); + identity.updateStatus(didHash, SigvaraIdentity.AgentStatus.Active); + _assertStanding(didHash, operator, SigvaraIdentity.AgentStatus.Active); + + address buyer = makeAddr("buyer"); + vm.prank(operator); + identity.offerOperatorTransfer(didHash, buyer); + vm.prank(buyer); + identity.acceptOperatorTransfer(didHash); + _assertStanding(didHash, buyer, SigvaraIdentity.AgentStatus.Active); + + vm.prank(buyer); + identity.updateStatus(didHash, SigvaraIdentity.AgentStatus.Suspended); + _assertStanding(didHash, buyer, SigvaraIdentity.AgentStatus.Suspended); + + vm.prank(staking); + identity.updateStatus(didHash, SigvaraIdentity.AgentStatus.Slashed); + _assertStanding(didHash, buyer, SigvaraIdentity.AgentStatus.Slashed); + } + + /// The three fields agree with getIdentity, and are the state the test walked the agent into. + function _assertStanding(bytes32 didHash, address expectedOperator, SigvaraIdentity.AgentStatus expectedStatus) + internal + view + { + SigvaraIdentity.AgentIdentity memory full = identity.getIdentity(didHash); + (address op, SigvaraIdentity.AgentStatus status, uint256 registeredAt) = identity.standingOf(didHash); + assertEq(op, full.operator, "operator"); + assertEq(uint8(status), uint8(full.status), "status"); + assertEq(registeredAt, full.registeredAt, "registeredAt"); + assertEq(op, expectedOperator, "expected operator"); + assertEq(uint8(status), uint8(expectedStatus), "expected status"); + } + // ------------------------------------------------------------------------- // Storage layout // ------------------------------------------------------------------------- diff --git a/test/SigvaraReader.t.sol b/test/SigvaraReader.t.sol index 9aa1f529..800b61f4 100644 --- a/test/SigvaraReader.t.sol +++ b/test/SigvaraReader.t.sol @@ -422,6 +422,66 @@ contract SigvaraReaderTest is StackFixture { assertFalse(reader.isTrusted(agent, 0)); } + /// The reader reads the slash state through staking's slashState, not the whole proposal. Its + /// answer has to be the state field of the full record in every state a proposal passes through. + function test_trust_slashIsTheFullRecordsStateInEveryState() public { + bytes32 didHash = _registerAndBond(agentPk, 2 * MIN_STAKE); + _assertSlashMatches(didHash, ISigvaraStaking.SlashState.None); + + vm.prank(committee); + staking.initiateSlash(didHash, victim, "first"); + _assertSlashMatches(didHash, ISigvaraStaking.SlashState.Pending); + + vm.prank(operator); + staking.disputeSlash(didHash); + _assertSlashMatches(didHash, ISigvaraStaking.SlashState.Disputed); + + vm.prank(admin); + staking.resolveDispute(didHash, false); + _assertSlashMatches(didHash, ISigvaraStaking.SlashState.Cancelled); + + vm.warp(block.timestamp + SLASH_WINDOW); + vm.prank(committee); + staking.initiateSlash(didHash, victim, "second"); + vm.warp(block.timestamp + SLASH_WINDOW + 1); + staking.executeSlash(didHash); + _assertSlashMatches(didHash, ISigvaraStaking.SlashState.Executed); + } + + function _assertSlashMatches(bytes32 didHash, ISigvaraStaking.SlashState expected) internal view { + ISigvaraStaking.SlashState slash = reader.trust(agent).slash; + assertEq(uint8(slash), uint8(staking.getSlashProposal(didHash).state), "the full record's state"); + assertEq(uint8(slash), uint8(expected), "the state the test walked it into"); + } + + /// The reader reads the slash state alone, so neither the rest of the proposal nor the evidence + /// the committee filed sets what a trust read costs. Each read is measured as a call of its own. + /// On 15 November 2026, copying the whole proposal, a trust read used 86,184 gas with one byte of + /// evidence and 104,554 with 256; reading the state alone it used 68,501 with either. The bound + /// sits between 68,501 and the cheaper of the two old reads. + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_gas_trustCostsTheSameWhateverTheEvidenceLength() public { + (address other, uint256 otherPk) = makeAddrAndKey("other agent"); + bytes32 shortDid = _registerAndBond(agentPk, 2 * MIN_STAKE); + bytes32 longDid = _registerAndBond(otherPk, 2 * MIN_STAKE); + + bytes memory longEvidence; + uint256 words = staking.MAX_EVIDENCE_BYTES() / 32; + for (uint256 i = 0; i < words; i++) longEvidence = bytes.concat(longEvidence, keccak256(abi.encode(i))); + vm.prank(committee); + staking.initiateSlash(shortDid, victim, hex"01"); + vm.prank(committee); + staking.initiateSlash(longDid, victim, longEvidence); + + reader.trust(agent); + uint256 shortGas = vm.lastCallGas().gasTotalUsed; + reader.trust(other); + uint256 longGas = vm.lastCallGas().gasTotalUsed; + assertEq(longGas, shortGas, "the length of the evidence sets the cost of a trust read"); + assertLt(longGas, 77_000, "the reader copies the whole proposal again"); + } + function test_trustByDid_matchesTrustByAddress() public { bytes32 didHash = _registerAndBond(agentPk, 2 * MIN_STAKE); _finalize(didHash, _score40()); @@ -567,5 +627,8 @@ contract SigvaraReaderTest is StackFixture { assertEq(a.victim, victim); assertEq(uint8(a.state), uint8(ISigvaraStaking.SlashState.Pending)); assertEq(a.challengeDeadline, a.initiatedAt + SLASH_WINDOW); + + assertEq(uint8(viaInterface.slashState(didHash)), uint8(staking.slashState(didHash))); + assertEq(uint8(viaInterface.slashState(didHash)), uint8(a.state)); } } diff --git a/test/SigvaraReputation.t.sol b/test/SigvaraReputation.t.sol index 4eb7e428..06ef9759 100644 --- a/test/SigvaraReputation.t.sol +++ b/test/SigvaraReputation.t.sol @@ -5,6 +5,7 @@ import "forge-std/Test.sol"; import "./helpers/RegistrationHelper.sol"; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import "@openzeppelin/contracts/access/IAccessControl.sol"; +import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "../src/SigvaraIdentity.sol"; import "../src/SigvaraReputation.sol"; @@ -23,27 +24,19 @@ contract OperatorSetMock is IOperatorSet { function isActiveOperator(address who) external view returns (bool) { return active[who]; } } -/// An identity registry from before operator transfer: it answers what the bond and -/// scorability checks need, and has no operatorChangedAt at all. +/// An identity registry with no operatorChangedAt, as before operator transfer existed: it +/// answers what the bond and scorability checks read, and nothing else. contract LegacyIdentityMock { IStakeView public stakeView; address private op; - address private agent; - constructor(address stakeView_, address operator_, address agent_) { + constructor(address stakeView_, address operator_) { stakeView = IStakeView(stakeView_); op = operator_; - agent = agent_; } - function getIdentity(bytes32) external view returns (SigvaraIdentity.AgentIdentity memory) { - return SigvaraIdentity.AgentIdentity({ - operator: op, - agentAddress: agent, - ed25519PubKey: bytes32(uint256(1)), - status: SigvaraIdentity.AgentStatus.Active, - registeredAt: 1 - }); + function standingOf(bytes32) external view returns (address, SigvaraIdentity.AgentStatus, uint256) { + return (op, SigvaraIdentity.AgentStatus.Active, 1); } } @@ -58,7 +51,6 @@ contract SigvaraReputationTest is Test, RegistrationHelper { address committee = makeAddr("committee"); address stranger = makeAddr("stranger"); address operator = makeAddr("operator"); - address agentAddr; uint256 agentPk; // Reputation now rejects writes for a didHash the identity registry does not @@ -74,7 +66,7 @@ contract SigvaraReputationTest is Test, RegistrationHelper { SigvaraReputation.ReputationData maxScore; function setUp() public { - (agentAddr, agentPk) = makeAddrAndKey("agent"); + (, agentPk) = makeAddrAndKey("agent"); identity = SigvaraIdentity(address(new ERC1967Proxy( address(new SigvaraIdentity()), abi.encodeCall(SigvaraIdentity.initialize, (admin, address(0))) @@ -451,6 +443,21 @@ contract SigvaraReputationTest is Test, RegistrationHelper { assertLt(used, 140_000, "the next proposal filled zeroed slots again"); } + /// Measured as a transaction of its own, as on chain. A finalize reads three of the identity's five + /// fields through standingOf, where getIdentity also read the agent address and the Ed25519 key, + /// two cold storage reads it threw away. On 15 November 2026 the finalize used 177,137 gas with + /// getIdentity and 172,236 with standingOf; the bound sits between the two. + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_gas_finalizeReputationReadsOnlyTheStanding() public { + vm.prank(oracle); + rep.proposeReputation(DID, maxScore, keccak256("evidence")); + vm.warp(block.timestamp + CHALLENGE_WINDOW + 1); + rep.finalizeReputation(DID); + uint256 used = vm.lastCallGas().gasTotalUsed; + assertLt(used, 174_500, "finalize reads the whole identity again"); + } + // ------------------------------------------------------------------------- // rejectReputation // ------------------------------------------------------------------------- @@ -1416,7 +1423,7 @@ contract SigvaraReputationTest is Test, RegistrationHelper { /// revert when the two proxies are a version apart. This is the exact failure /// that took every score on Arc testnet unreadable. function test_maturity_survivesAnOlderIdentityRegistry() public { - LegacyIdentityMock legacy = new LegacyIdentityMock(address(stakeView), operator, agentAddr); + LegacyIdentityMock legacy = new LegacyIdentityMock(address(stakeView), operator); SigvaraReputation old = SigvaraReputation(address(new ERC1967Proxy( address(new SigvaraReputation()), @@ -1532,6 +1539,53 @@ contract SigvaraReputationTest is Test, RegistrationHelper { assertFalse(rep.verifyEvidence(DID, EV_LEAF0, _proof0())); } + /// verifyEvidence reads the proof from calldata, and MerkleProof.verify, which it called before, + /// copies it into memory first. They have to agree on every proof: a genuine one, the same proof + /// with any one hash changed, and the same proof offered for another leaf. + function testFuzz_evidence_sameVerdictAsTheMemoryVerify(bytes32 leaf, bytes32[] memory hashes, uint256 position) + public + { + // At most sixteen hashes, the depth of a tree of 65,536 payments. + bytes32[] memory proof = new bytes32[](hashes.length < 16 ? hashes.length : 16); + for (uint256 i = 0; i < proof.length; i++) proof[i] = hashes[i]; + bytes32 root = MerkleProof.processProof(proof, leaf); + vm.assume(root != bytes32(0)); // a zero root verifies nothing, by design + _finalizeWithRoot(root); + + assertTrue(rep.verifyEvidence(DID, leaf, proof), "a genuine proof verifies"); + assertEq(rep.verifyEvidence(DID, leaf, proof), MerkleProof.verify(proof, root, leaf), "genuine"); + + bytes32 otherLeaf = keccak256(abi.encode(leaf)); + assertFalse(rep.verifyEvidence(DID, otherLeaf, proof), "another leaf does not verify"); + assertEq( + rep.verifyEvidence(DID, otherLeaf, proof), MerkleProof.verify(proof, root, otherLeaf), "another leaf" + ); + + if (proof.length > 0) { + proof[position % proof.length] ^= bytes32(uint256(1)); + assertFalse(rep.verifyEvidence(DID, leaf, proof), "a changed hash does not verify"); + assertEq(rep.verifyEvidence(DID, leaf, proof), MerkleProof.verify(proof, root, leaf), "a changed hash"); + } + } + + /// An eleven-hash proof, the depth of a tree of 2,048 payments, checked in a call of its own. On + /// 15 November 2026 the check used 10,654 gas with the proof copied into memory for + /// MerkleProof.verify and 10,411 with verifyCalldata reading it in place; the bound sits between + /// the two. + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_gas_verifyEvidenceReadsTheProofInPlace() public { + bytes32 leaf = keccak256("payment"); + bytes32[] memory proof = new bytes32[](11); + for (uint256 i = 0; i < proof.length; i++) proof[i] = keccak256(abi.encode("sibling", i)); + _finalizeWithRoot(MerkleProof.processProof(proof, leaf)); + + bool verified = rep.verifyEvidence(DID, leaf, proof); + uint256 used = vm.lastCallGas().gasTotalUsed; + assertTrue(verified, "the proof is genuine"); + assertLt(used, 10_530, "the proof is copied into memory again"); + } + function test_maturity_rateOfZeroIsRejected() public { vm.expectRevert(SigvaraReputation.MaturityRateZero.selector); vm.prank(admin); diff --git a/test/SigvaraStaking.t.sol b/test/SigvaraStaking.t.sol index ae6c2365..27f3b2ca 100644 --- a/test/SigvaraStaking.t.sol +++ b/test/SigvaraStaking.t.sol @@ -500,6 +500,69 @@ contract SigvaraStakingTest is Test, RegistrationHelper { staking.initiateSlash(didHash, victim, ""); } + /// The evidence points at a package published elsewhere. One byte past the limit is refused, and + /// nothing is filed or suspended. + function test_initiateSlash_reverts_evidenceOverTheLimit() public { + _deposit(); + + vm.expectRevert(abi.encodeWithSelector(SigvaraStaking.EvidenceTooLong.selector, 257, 256)); + vm.prank(committee); + staking.initiateSlash(didHash, victim, new bytes(257)); + + assertEq(uint8(staking.slashState(didHash)), uint8(SigvaraStaking.SlashState.None), "nothing filed"); + assertTrue(identity.isActive(didHash), "the agent was not suspended"); + } + + /// Evidence of exactly the limit is filed and stored byte for byte. + function test_initiateSlash_acceptsEvidenceAtTheLimit() public { + _deposit(); + assertEq(staking.MAX_EVIDENCE_BYTES(), 256); + + bytes memory evidence; + for (uint256 i = 0; i < 8; i++) evidence = bytes.concat(evidence, keccak256(abi.encode(i))); + assertEq(evidence.length, 256); + vm.prank(committee); + staking.initiateSlash(didHash, victim, evidence); + + assertEq(staking.getSlashProposal(didHash).evidenceHash, evidence, "stored verbatim"); + assertEq(uint8(staking.slashState(didHash)), uint8(SigvaraStaking.SlashState.Pending)); + } + + /// slashState is the state field of getSlashProposal read alone, so it has to agree with the + /// full record in every state a proposal passes through. + function test_slashState_matchesTheFullRecordInEveryState() public { + _assertSlashState(SigvaraStaking.SlashState.None); + _deposit(); + + vm.prank(committee); + staking.initiateSlash(didHash, victim, "first"); + _assertSlashState(SigvaraStaking.SlashState.Pending); + + vm.prank(operator); + staking.disputeSlash(didHash); + _assertSlashState(SigvaraStaking.SlashState.Disputed); + + vm.prank(admin); + staking.resolveDispute(didHash, false); + _assertSlashState(SigvaraStaking.SlashState.Cancelled); + + // The committee may file again one challenge period after the drop, with new evidence. + vm.warp(block.timestamp + CHALLENGE); + vm.prank(committee); + staking.initiateSlash(didHash, victim, "second"); + _assertSlashState(SigvaraStaking.SlashState.Pending); + + vm.warp(block.timestamp + CHALLENGE + 1); + staking.executeSlash(didHash); + _assertSlashState(SigvaraStaking.SlashState.Executed); + } + + function _assertSlashState(SigvaraStaking.SlashState expected) internal view { + SigvaraStaking.SlashState state = staking.slashState(didHash); + assertEq(uint8(state), uint8(staking.getSlashProposal(didHash).state), "matches the full record"); + assertEq(uint8(state), uint8(expected), "the state the test walked it into"); + } + // ------------------------------------------------------------------------- // disputeSlash // ------------------------------------------------------------------------- @@ -2140,6 +2203,62 @@ contract SigvaraStakingTest is Test, RegistrationHelper { staking.setMinimumStake(1); } + // ------------------------------------------------------------------------- + // Gas: the agent is read through standingOf + // ------------------------------------------------------------------------- + + // Each call is measured as a transaction of its own, as on chain: inside one transaction the + // identity's slots would already be warm. The registry reads three of the identity's five + // fields through standingOf, where getIdentity also read the agent address and the Ed25519 + // key, two cold storage reads it threw away. Measured on 15 November 2026, with getIdentity + // and then with standingOf: depositStake 171,937 and 167,035, initiateWithdrawal 132,057 and + // 127,162, claimWithdrawal 74,185 and 69,288, disputeSlash 82,204 and 77,307. Each bound + // sits between the two. + + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_gas_depositStakeReadsOnlyTheStanding() public { + vm.prank(operator); + staking.depositStake(didHash, MIN_STAKE * 2); + uint256 used = vm.lastCallGas().gasTotalUsed; + assertLt(used, 169_500, "depositStake reads the whole identity again"); + } + + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_gas_initiateWithdrawalReadsOnlyTheStanding() public { + _deposit(); + vm.prank(operator); + staking.initiateWithdrawal(didHash, MIN_STAKE); + uint256 used = vm.lastCallGas().gasTotalUsed; + assertLt(used, 129_500, "initiateWithdrawal reads the whole identity again"); + } + + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_gas_claimWithdrawalReadsOnlyTheStanding() public { + _deposit(); + vm.prank(operator); + staking.initiateWithdrawal(didHash, MIN_STAKE); + vm.warp(block.timestamp + UNBONDING); + vm.prank(operator); + staking.claimWithdrawal(didHash); + uint256 used = vm.lastCallGas().gasTotalUsed; + assertLt(used, 71_500, "claimWithdrawal reads the whole identity again"); + } + + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_gas_disputeSlashReadsOnlyTheStanding() public { + _deposit(); + vm.prank(committee); + staking.initiateSlash(didHash, victim, "evidence"); + vm.prank(operator); + staking.disputeSlash(didHash); + uint256 used = vm.lastCallGas().gasTotalUsed; + assertLt(used, 79_500, "disputeSlash reads the whole identity again"); + } + // ------------------------------------------------------------------------- // Fuzz: stake roundtrip // ------------------------------------------------------------------------- diff --git a/test/Upgrade.t.sol b/test/Upgrade.t.sol index e43d9529..1cbca211 100644 --- a/test/Upgrade.t.sol +++ b/test/Upgrade.t.sol @@ -339,9 +339,17 @@ contract PreTransferIdentity { function getIdentity(bytes32) external pure returns (uint256) { return 1; } } +/// A registry with operator transfer and a stake view and no standingOf, as the Arc testnet +/// identity proxy runs until it is upgraded. +contract PreStandingIdentity { + function operatorChangedAt(bytes32) external pure returns (uint256) { return 0; } + function stakeView() external pure returns (address) { return address(1); } +} + contract CurrentIdentity { function operatorChangedAt(bytes32) external pure returns (uint256) { return 0; } function stakeView() external pure returns (address) { return address(1); } + function standingOf(bytes32) external pure returns (address, uint8, uint256) { return (address(0), 0, 0); } } /// Holds an identityRegistry the way reputation and staking do. @@ -462,6 +470,36 @@ contract UpgradeDependencyTest is Test { harness.check("staking", proxy); } + /// Reputation reads the agent through standingOf on every proposal and finalize. Upgraded + /// ahead of identity, the oracle could write no score until identity caught up. + function test_refusesReputationAgainstAnIdentityWithoutStandingOf() public { + address identity = address(new PreStandingIdentity()); + address proxy = address(new ProxyStub(identity)); + vm.expectRevert(abi.encodeWithSelector( + Upgrade.DependencyMissing.selector, "reputation", "identity.standingOf: upgrade identity first", identity + )); + harness.check("reputation", proxy); + } + + /// Staking reads the agent through standingOf to deposit, withdraw, claim and dispute. + /// Upgraded ahead of identity, every one of them would revert until identity caught up. + function test_refusesStakingAgainstAnIdentityWithoutStandingOf() public { + address identity = address(new PreStandingIdentity()); + address proxy = address(new ProxyStub(identity)); + vm.expectRevert(abi.encodeWithSelector( + Upgrade.DependencyMissing.selector, "staking", "identity.standingOf: upgrade identity first", identity + )); + harness.check("staking", proxy); + } + + /// The probes name functions the real identity has, so one built from this source passes both. + function test_allowsBothAgainstTheIdentityThisSourceBuilds() public { + (address[5] memory p,) = _proxies(); + address proxy = address(new ProxyStub(p[0])); + harness.check("reputation", proxy); + harness.check("staking", proxy); + } + /// An unwired proxy has nothing to depend on yet, and a fresh deployment must not /// be blocked by a check about contracts it has not been pointed at. function test_allowsWhenTheRegistryIsNotWiredYet() public { From c251b18cf54f3f0fe8c908d73661d6970da666c2 Mon Sep 17 00:00:00 2001 From: RunTimeAdmin <248247024+RunTimeAdmin@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:45:25 -0600 Subject: [PATCH 2/2] Check that the registries read only the standing by the calls they make, not by gas CI's forge measured the identity's reads warm under isolate, so the five bounds set between the cold figures failed there: a finalize read 177,036, the old code's cost. Each test now expects standingOf and no getIdentity, which fails on the old code in any toolchain. The measured figures stay in the comments. Co-Authored-By: Claude Opus 5.5 --- test/SigvaraReputation.t.sol | 16 ++++++------ test/SigvaraStaking.t.sol | 47 +++++++++++++++--------------------- 2 files changed, 26 insertions(+), 37 deletions(-) diff --git a/test/SigvaraReputation.t.sol b/test/SigvaraReputation.t.sol index 06ef9759..03e39f35 100644 --- a/test/SigvaraReputation.t.sol +++ b/test/SigvaraReputation.t.sol @@ -443,19 +443,17 @@ contract SigvaraReputationTest is Test, RegistrationHelper { assertLt(used, 140_000, "the next proposal filled zeroed slots again"); } - /// Measured as a transaction of its own, as on chain. A finalize reads three of the identity's five - /// fields through standingOf, where getIdentity also read the agent address and the Ed25519 key, - /// two cold storage reads it threw away. On 15 November 2026 the finalize used 177,137 gas with - /// getIdentity and 172,236 with standingOf; the bound sits between the two. - /// forge-config: default.isolate = true - /// forge-config: ci.isolate = true - function test_gas_finalizeReputationReadsOnlyTheStanding() public { + /// A finalize asks the identity registry for the three fields it uses (standingOf), never for the whole + /// record (getIdentity), whose agent address and Ed25519 key were two cold storage reads it threw away. On + /// 15 November 2026 a finalize measured on its own used 177,137 gas with getIdentity and 172,236 with + /// standingOf. Checked by the calls made rather than by gas, which CI's toolchain counts differently. + function test_finalizeReputation_readsOnlyTheStanding() public { vm.prank(oracle); rep.proposeReputation(DID, maxScore, keccak256("evidence")); vm.warp(block.timestamp + CHALLENGE_WINDOW + 1); + vm.expectCall(address(identity), abi.encodeWithSelector(SigvaraIdentity.getIdentity.selector), 0); + vm.expectCall(address(identity), abi.encodeCall(SigvaraIdentity.standingOf, (DID))); rep.finalizeReputation(DID); - uint256 used = vm.lastCallGas().gasTotalUsed; - assertLt(used, 174_500, "finalize reads the whole identity again"); } // ------------------------------------------------------------------------- diff --git a/test/SigvaraStaking.t.sol b/test/SigvaraStaking.t.sol index 27f3b2ca..b0e16bf3 100644 --- a/test/SigvaraStaking.t.sol +++ b/test/SigvaraStaking.t.sol @@ -2207,56 +2207,47 @@ contract SigvaraStakingTest is Test, RegistrationHelper { // Gas: the agent is read through standingOf // ------------------------------------------------------------------------- - // Each call is measured as a transaction of its own, as on chain: inside one transaction the - // identity's slots would already be warm. The registry reads three of the identity's five - // fields through standingOf, where getIdentity also read the agent address and the Ed25519 - // key, two cold storage reads it threw away. Measured on 15 November 2026, with getIdentity - // and then with standingOf: depositStake 171,937 and 167,035, initiateWithdrawal 132,057 and - // 127,162, claimWithdrawal 74,185 and 69,288, disputeSlash 82,204 and 77,307. Each bound - // sits between the two. - - /// forge-config: default.isolate = true - /// forge-config: ci.isolate = true - function test_gas_depositStakeReadsOnlyTheStanding() public { + // The registry asks the identity registry for the three fields it uses (standingOf), never for the whole + // record (getIdentity), whose agent address and Ed25519 key were two cold storage reads it threw away. + // Measured on 15 November 2026 as transactions of their own, with getIdentity and then with standingOf: + // depositStake 171,937 and 167,035, initiateWithdrawal 132,057 and 127,162, claimWithdrawal 74,185 and + // 69,288, disputeSlash 82,204 and 77,307. Checked by the calls made rather than by gas: how a cold read + // is counted depends on the toolchain, and CI's measured these reads warm. + function _expectOnlyTheStanding() internal { + vm.expectCall(address(identity), abi.encodeWithSelector(SigvaraIdentity.getIdentity.selector), 0); + vm.expectCall(address(identity), abi.encodeCall(SigvaraIdentity.standingOf, (didHash))); + } + + function test_depositStake_readsOnlyTheStanding() public { + _expectOnlyTheStanding(); vm.prank(operator); staking.depositStake(didHash, MIN_STAKE * 2); - uint256 used = vm.lastCallGas().gasTotalUsed; - assertLt(used, 169_500, "depositStake reads the whole identity again"); } - /// forge-config: default.isolate = true - /// forge-config: ci.isolate = true - function test_gas_initiateWithdrawalReadsOnlyTheStanding() public { + function test_initiateWithdrawal_readsOnlyTheStanding() public { _deposit(); + _expectOnlyTheStanding(); vm.prank(operator); staking.initiateWithdrawal(didHash, MIN_STAKE); - uint256 used = vm.lastCallGas().gasTotalUsed; - assertLt(used, 129_500, "initiateWithdrawal reads the whole identity again"); } - /// forge-config: default.isolate = true - /// forge-config: ci.isolate = true - function test_gas_claimWithdrawalReadsOnlyTheStanding() public { + function test_claimWithdrawal_readsOnlyTheStanding() public { _deposit(); vm.prank(operator); staking.initiateWithdrawal(didHash, MIN_STAKE); vm.warp(block.timestamp + UNBONDING); + _expectOnlyTheStanding(); vm.prank(operator); staking.claimWithdrawal(didHash); - uint256 used = vm.lastCallGas().gasTotalUsed; - assertLt(used, 71_500, "claimWithdrawal reads the whole identity again"); } - /// forge-config: default.isolate = true - /// forge-config: ci.isolate = true - function test_gas_disputeSlashReadsOnlyTheStanding() public { + function test_disputeSlash_readsOnlyTheStanding() public { _deposit(); vm.prank(committee); staking.initiateSlash(didHash, victim, "evidence"); + _expectOnlyTheStanding(); vm.prank(operator); staking.disputeSlash(didHash); - uint256 used = vm.lastCallGas().gasTotalUsed; - assertLt(used, 79_500, "disputeSlash reads the whole identity again"); } // -------------------------------------------------------------------------