From d2b44a17a6f280edc932d237af49e075fd4e86a2 Mon Sep 17 00:00:00 2001 From: RunTimeAdmin <248247024+RunTimeAdmin@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:37:38 -0600 Subject: [PATCH] Keep a finalized proposal's slots for the next one to overwrite finalizeReputation deleted the whole pending struct. That earned a refund, and then the agent's next proposal paid about 22,100 gas for each slot it filled from zero. It now clears only exists, which every reader checks first, and the next proposal writes every field, so nothing carries over. Rejecting, discarding and zeroing still delete the slot. Measured as separate transactions, the next proposal falls from 227,155 to 121,755 gas and a propose and finalize cycle from 351,082 to 252,540; the finalize alone costs 6,858 more for its smaller refund. Tests pin that nothing acts on the fields left behind or inherits them, and bound the next proposal's gas. The invariant model, mutation R26 and the docs that read a finalized slot as empty follow the change. 799 forge tests. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/authorisation-matrix.md | 2 +- docs/incident-operator-key.md | 2 +- docs/whitepaper.md | 2 +- oracle/RUNBOOK-second-operator.md | 7 ++- oracle/chain.js | 15 ++--- scripts/mutation/mutate-invariants.sh | 2 +- src/SigvaraReputation.sol | 7 ++- test/ReputationInvariant.t.sol | 4 +- test/SigvaraReputation.t.sol | 82 ++++++++++++++++++++++++++- 10 files changed, 108 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 07738a9..c906557 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 | 796 | `forge test` | +| Contracts: unit, fuzz, E2E, upgrade, deploy-script, handover and 22 invariants | 799 | `forge test` | | Oracle | 1514 | `cd oracle && node --test` | | SDK | 381 | `cd packages/sdk && npx vitest run` | -Counts are individual tests, so each of the 22 invariants counts once. The contracts were counted on 10 November 2026 and have not changed since; the SDK on 13 November and the oracle on 14 November. Without a fork URL, 784 of the contract tests run and 12 skip. Run after `npm run build`, 372 of the SDK's 381 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 13 November and the oracle on 14 November. Without a fork URL, 787 of the contract tests run and 12 skip. Run after `npm run build`, 372 of the SDK's 381 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/authorisation-matrix.md b/docs/authorisation-matrix.md index cbdb303..8538df7 100644 --- a/docs/authorisation-matrix.md +++ b/docs/authorisation-matrix.md @@ -96,7 +96,7 @@ README's [Access Control Summary](../README.md#access-control-summary). | Function | Caller | Guard | Requires | Effect | |---|---|---|---|---| | `discardStrandedScore(bytes32)` | `anyone` | `-` | Any account. A proposal is pending and its proposer is no longer authorized: it does not hold `ORACLE_ROLE` or, if `operatorBond` is set, is not an active operator (`NoScorePending` when nothing is pending, `ScoreAlreadyPending` while the proposer is authorized or was never recorded). Inside the window or after. | Deletes the pending proposal, so it cannot finalize if its proposer is authorized again; the finalized score is untouched. Emits `StrandedScoreDiscarded` with the proposer and the caller. | -| `finalizeReputation(bytes32)` | `anyone` | `-` | Any account. A proposal is pending and its `finalizableAt` has passed; the agent is registered, not slashed and holds minimum stake; the proposer still holds `ORACLE_ROLE` and, if `operatorBond` is set, is an active operator. | Copies the pending data to `reputations` with `lastUpdated` at the proposal's `proposedAt`, stores its `evidenceRoots` entry, deletes the proposal, and re-anchors `maturedScore` and `maturedAt` at the score matured so far, keeping the time built up toward the next point. Emits `ReputationUpdated`. | +| `finalizeReputation(bytes32)` | `anyone` | `-` | Any account. A proposal is pending and its `finalizableAt` has passed; the agent is registered, not slashed and holds minimum stake; the proposer still holds `ORACLE_ROLE` and, if `operatorBond` is set, is an active operator. | Copies the pending data to `reputations` with `lastUpdated` at the proposal's `proposedAt`, stores its `evidenceRoots` entry, ends the proposal by clearing its `exists` flag (its other fields stay in the slot for the next proposal to overwrite, which costs less than filling zeroed storage), and re-anchors `maturedScore` and `maturedAt` at the score matured so far, keeping the time built up toward the next point. Emits `ReputationUpdated`. | | `grantRole(bytes32,address)` | `inherited` | `-` | Caller holds the role's admin (`getRoleAdmin`). `initialize` makes `UPGRADER_ROLE` the admin of `UPGRADER_ROLE`, `STAKING_CORE_ROLE` and `SLASHING_COMMITTEE_ROLE`; `ORACLE_ROLE`, `GUARDIAN_ROLE` and `DEFAULT_ADMIN_ROLE` stay under `DEFAULT_ADMIN_ROLE`. | Adds `account` to the role if it does not hold it and emits `RoleGranted`; otherwise does nothing. | | `initialize(address,address,address,address,uint256)` | `initializer` | `-` | Any account, once, on an uninitialized proxy (the implementation disables initializers in its constructor). `challengeWindow_` from `MIN_CHALLENGE_WINDOW` (1 hour) to `MAX_CHALLENGE_WINDOW` (7 days). `admin` is not checked for zero. | Grants `admin` `DEFAULT_ADMIN_ROLE` and `UPGRADER_ROLE`; makes `UPGRADER_ROLE` the admin of itself, `STAKING_CORE_ROLE` and `SLASHING_COMMITTEE_ROLE`; grants the oracle, staking core and committee roles to nonzero arguments; sets `challengeWindow`. Emits role events, `Initialized`. | | `initializeV2(address,uint256)` | `reinitializer:2`, `role:DEFAULT_ADMIN_ROLE` | `-` | `DEFAULT_ADMIN_ROLE` holder (through `upgradeToAndCall`, the upgrading account); initialized version below 2, so only a proxy from before optimistic scoring: `Deploy.s.sol` runs `initializeV3` and `initializeV4` at once, and `check-mainnet.sh` checks version 4. `challengeWindow_` from 1 hour to 7 days. | Grants `SLASHING_COMMITTEE_ROLE` to a nonzero `slashingCommittee` through `_grantRole`, without its `UPGRADER_ROLE` admin; sets `challengeWindow`. Emits `ChallengeWindowUpdated`, `Initialized(2)`. | diff --git a/docs/incident-operator-key.md b/docs/incident-operator-key.md index 9d6c1dd..7e0145b 100644 --- a/docs/incident-operator-key.md +++ b/docs/incident-operator-key.md @@ -17,7 +17,7 @@ Any of these is enough: the `.env` or a copy of it was readable by someone it sh - `revokeRole(ORACLE_ROLE, )` on `SigvaraReputation`. `finalizeReputation` then refuses a proposal whose proposer no longer holds the role. - `removeOperator()` on `SigvaraOracleBond` (admin). If the key is only a signer, the bond owner calls `clearSigner()` instead (any status works), and the `revokeRole` above still applies: a cleared signer must not keep `ORACLE_ROLE` or be admitted later as an operator of its own, since bonding as itself would make the proposals it made as a signer finalizable again. Neither testnet operator has a signer named, so that case does not arise there yet. Either way the key stays bound to its operator (`boundTo`): no other operator can name it as a signer and bring its pending proposals back, which before this was possible with one `setSigner` call. An address released before the registry carried `boundTo` has no record. The Arc testnet registry has never had a signer named or an operator leave (no `SignerSet`, `SignerCleared`, `BondWithdrawn`, `OperatorSlashed` or `OperatorRemoved` log as of 3 November 2026), so it holds none; check again just before upgrading it. - If funds could move, the guardian calls `pauseInflows()` (the admin can lift it). It closes registrations, deposits, proposals and bonds for 3 days and moves nothing. -3. **Reject what it already proposed.** The committee calls `rejectReputation(didHash)` for every pending proposal from that key, before the window closes (6 hours on the testnet). To find them: read the `ScoreProposed` logs of the last window and check the sender of each transaction; for each agent you can also read `getPendingScore(didHash)`, whose `proposer` field names who made the proposal. The checker's `GET /divergence` lists the ones it disagrees with. +3. **Reject what it already proposed.** The committee calls `rejectReputation(didHash)` for every pending proposal from that key, before the window closes (6 hours on the testnet). To find them: read the `ScoreProposed` logs of the last window and check the sender of each transaction; for each agent you can also read `getPendingScore(didHash)`, whose `proposer` field names who made the proposal. Count it only when `exists` is true: a finalized proposal clears that flag and leaves its other fields, `proposer` among them, in the slot. The checker's `GET /divergence` lists the ones it disagrees with. 4. **If no signer is named, watch for `initiateUnbond`.** If the thief starts it, the committee slashes the operator inside the 7 days. The 7 days are fixed when the unbond starts (`unbondingClaimableAt()`), so changing `unbondingPeriod` afterwards neither buys time nor shortens it. ## 2. Keep the evidence before anything is deleted diff --git a/docs/whitepaper.md b/docs/whitepaper.md index 3c93f7e..a067425 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 14 November 2026: 796 contract tests across 36 Foundry test files +**Test coverage**, as of 15 November 2026: 799 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`), 1514 oracle tests and 381 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/oracle/RUNBOOK-second-operator.md b/oracle/RUNBOOK-second-operator.md index ec2e428..7cabee7 100644 --- a/oracle/RUNBOOK-second-operator.md +++ b/oracle/RUNBOOK-second-operator.md @@ -581,10 +581,11 @@ not announce itself. The proposal is live while `block.timestamp < finalizableAt`, which is word 11 of the returndata and is fixed when the proposal is made. Where that word is zero or absent (a proposal from before it existed, which on the Arc testnet means any made before its upgrade to -`main`), the rule is `proposedAt + challengeWindow > block.timestamp`. If the -pending slot is empty, or holds a *different* `proposedAt` than the record, the disputed +`main`), the rule is `proposedAt + challengeWindow > block.timestamp`. If `exists` +(word 8) is zero, or the slot holds a *different* `proposedAt` than the record, the disputed proposal has already turned over: the record is `superseded`, still visible, no longer -actionable. +actionable. A finalize clears only `exists` and leaves the proposal's other words in place, +so a finalized proposal does not read as an empty slot. **3. Diff the inputs before blaming either side.** This is the step that decides it. diff --git a/oracle/chain.js b/oracle/chain.js index 572ccf4..2d6faa3 100644 --- a/oracle/chain.js +++ b/oracle/chain.js @@ -1000,7 +1000,8 @@ async function finalizeScore(didHash) { return (await settle(tx)).hash; } -// Returns { exists, proposedAt, finalizableAt, data, evidenceRoot }; proposedAt is 0 when no proposal is pending. +// Returns { exists, proposedAt, finalizableAt, data, evidenceRoot }. Only exists says whether a proposal is pending: +// a finalize clears it and leaves the other fields as the finalized proposal had them, so proposedAt is not 0 then. async function getPendingScore(didHash) { const pending = await readWithBackoff('getPendingScore', () => reputationContract.getPendingScore(didHash)); // The factors come back too, for checker mode to compare against its own arithmetic. @@ -1016,9 +1017,9 @@ async function getPendingScore(didHash) { const data = {}; for (const f of SCORE_FACTORS) { const v = Number(pending.data?.[f]); - // Only meaningful when something is pending. An empty slot decodes to a zeroed - // struct that nothing compares against: decideCheckerAction returns 'propose' on - // !exists without reading a single factor. + // Only meaningful when something is pending. With nothing pending the struct is zeroed, + // or still holds the proposal a finalize ended, and nothing compares against it: + // decideCheckerAction returns 'propose' on !exists without reading a single factor. if (!Number.isFinite(v)) { if (!pending.exists) continue; throw new Error(`getPendingScore: ${f} did not decode to a number (got ${pending.data?.[f]}); the ReputationData ABI may no longer match the contract`); @@ -1026,9 +1027,9 @@ async function getPendingScore(didHash) { data[f] = v; } // The deadline the contract fixed when the proposal was made. Zero for a proposal that was already - // pending when the field was added, which the contract judges against the live window, and for an - // empty slot. A value that does not decode must not read as zero: zero brings back the arithmetic - // this replaces (see finalizableAtOf in epoch-policy.js). + // pending when the field was added, which the contract judges against the live window, and for a + // slot that never held a proposal. A value that does not decode must not read as zero: zero brings + // back the arithmetic this replaces (see finalizableAtOf in epoch-policy.js). const finalizableAt = Number(pending.finalizableAt ?? 0); if (!Number.isFinite(finalizableAt)) { throw new Error(`getPendingScore: finalizableAt did not decode to a number (got ${pending.finalizableAt}); the PendingScore ABI may no longer match the contract`); diff --git a/scripts/mutation/mutate-invariants.sh b/scripts/mutation/mutate-invariants.sh index 41ee311..06758a5 100644 --- a/scripts/mutation/mutate-invariants.sh +++ b/scripts/mutation/mutate-invariants.sh @@ -75,7 +75,7 @@ runl R22 $RS $R 'function finalizeReputation(' '(uint8 anchor, uint256 clock) = runl R23 $RS $R 'function finalizeReputation(' 'maturedAt[didHash] = clock;' 'maturedAt.didHash. = clock;' '' 'finalize does not restart the maturity clock' runl R24 $RS $R 'function finalizeReputation(' 'maturedScore[didHash] = anchor;' 'maturedScore.didHash. = anchor;' '' 'finalize does not store the anchor' runl R25 $RS $R 'function finalizeReputation(' 'data.lastUpdated = pending.proposedAt;' 'data.lastUpdated = pending.proposedAt;' '' 'finalize keeps the date the proposer sent' -runl R26 $RS $R 'function finalizeReputation(' 'delete pendingScores[didHash];' 'delete pendingScores.didHash.;' '' 'a finalized proposal stays pending' +runl R26 $RS $R 'function finalizeReputation(' 'pending.exists = false;' 'pending.exists = false;' '' 'a finalized proposal stays pending' runl R27 $RS $R 'function finalizeReputation(' 'evidenceRoots[didHash] = root;' 'evidenceRoots.didHash. = root;' '' 'finalize does not store the evidence root' runl R28 $RS $R 'function rejectReputation(' 'if (block.timestamp >= finalizableAt)' 'block.timestamp >= finalizableAt' 'false' 'a proposal can be rejected after its window' runl R29 $RS $R 'function rejectReputation(' 'onlyRole(SLASHING_COMMITTEE_ROLE)' 'onlyRole(SLASHING_COMMITTEE_ROLE)' '' 'anyone can reject a proposal' diff --git a/src/SigvaraReputation.sol b/src/SigvaraReputation.sol index a07fc4e..b7638a1 100644 --- a/src/SigvaraReputation.sol +++ b/src/SigvaraReputation.sol @@ -496,7 +496,12 @@ contract SigvaraReputation is Initializable, TimelockedGrants, UUPSUpgradeable, bytes32 root = pending.evidenceRoot; reputations[didHash] = data; evidenceRoots[didHash] = root; - delete pendingScores[didHash]; + // Clears the flag and leaves the other fields where they are. Everything that reads a + // pending proposal checks `exists` first, and the next proposal writes every field, so + // nothing of this one carries into it. Deleting the whole struct earned a refund and then + // made the next proposal pay about 22,100 gas for each slot it filled from zero, where + // overwriting a slot that still holds a value costs about 5,000. + pending.exists = false; maturedScore[didHash] = anchor; maturedAt[didHash] = clock; diff --git a/test/ReputationInvariant.t.sol b/test/ReputationInvariant.t.sol index 3694417..7f2e267 100644 --- a/test/ReputationInvariant.t.sol +++ b/test/ReputationInvariant.t.sol @@ -299,7 +299,9 @@ contract ReputationHandler is Test { } else { okFinalizeCarried++; } - delete pend[did]; + // A finalize clears only the flag. The rest of the proposal stays in the slot until the + // next one overwrites it, and the books are compared field by field, so the model keeps it too. + pend[did].exists = false; // A jump in the earned score is released from where the agent stood, and a fall applies at once. // Checked in the block of the finalize, when no time has passed to release anything. A handover diff --git a/test/SigvaraReputation.t.sol b/test/SigvaraReputation.t.sol index d93bd97..4eb7e42 100644 --- a/test/SigvaraReputation.t.sol +++ b/test/SigvaraReputation.t.sol @@ -281,7 +281,7 @@ contract SigvaraReputationTest is Test, RegistrationHelper { vm.warp(block.timestamp + CHALLENGE_WINDOW + 1); rep.finalizeReputation(DID); - // Finalizing empties the pending slot, so cover is possible again. + // Finalizing clears the slot's `exists` flag, so cover is possible again. vm.prank(oracle); rep.proposeIfEmpty(DID, maxScore, bytes32(0)); assertTrue(rep.getPendingScore(DID).exists); @@ -371,6 +371,86 @@ contract SigvaraReputationTest is Test, RegistrationHelper { assertEq(rep.getTotalScore(DID), 100); } + // A finalize clears only the proposal's `exists` flag. The rest stays in the slot for the next + // proposal to overwrite, which costs less than filling zeroed storage. These pin that nothing + // acts on what is left, that none of it carries into the next proposal, and what it saves. + + function test_finalizeReputation_leavesNothingPendingToActOn() public { + uint256 t0 = vm.getBlockTimestamp(); + vm.prank(oracle); + rep.proposeReputation(DID, maxScore, keccak256("evidence")); + vm.warp(t0 + CHALLENGE_WINDOW + 1); + rep.finalizeReputation(DID); + + SigvaraReputation.PendingScore memory pending = rep.getPendingScore(DID); + assertFalse(pending.exists, "the proposal is still pending"); + assertEq(pending.proposedAt, t0, "the rest of the proposal stays for the next one to overwrite"); + + vm.expectRevert(abi.encodeWithSelector(SigvaraReputation.NoScorePending.selector, DID)); + rep.finalizeReputation(DID); + + vm.expectRevert(abi.encodeWithSelector(SigvaraReputation.NoScorePending.selector, DID)); + vm.prank(committee); + rep.rejectReputation(DID); + + // With its proposer's role gone, the proposal would be a stranded one if it still counted. + _revokeOracle(oracle); + vm.expectRevert(abi.encodeWithSelector(SigvaraReputation.NoScorePending.selector, DID)); + vm.prank(stranger); + rep.discardStrandedScore(DID); + } + + function test_finalizeReputation_theNextProposalCarriesNothingOver() public { + SigvaraReputation.ReputationData memory first = maxScore; + first.lastUpdated = 12_345; + vm.prank(oracle); + rep.proposeReputation(DID, first, keccak256("first")); + vm.warp(block.timestamp + CHALLENGE_WINDOW + 1); + rep.finalizeReputation(DID); + + // Another oracle, a day later and under another window, sends zeros wherever the first + // proposal had a value, so a field left over from the first would show through. + address checker = makeAddr("checker"); + _grantOracle(checker); + vm.prank(admin); + rep.setChallengeWindow(2 hours); + vm.warp(block.timestamp + 1 days); + SigvaraReputation.ReputationData memory second; + vm.prank(checker); + rep.proposeIfEmpty(DID, second, bytes32(0)); + + SigvaraReputation.PendingScore memory pending = rep.getPendingScore(DID); + assertTrue(pending.exists); + assertEq(pending.proposer, checker, "proposer"); + assertEq(pending.proposedAt, block.timestamp, "proposedAt"); + assertEq(pending.finalizableAt, block.timestamp + 2 hours, "finalizableAt"); + assertEq(pending.evidenceRoot, bytes32(0), "evidenceRoot"); + assertEq(keccak256(abi.encode(pending.data)), keccak256(abi.encode(second)), "factors and lastUpdated"); + } + + /// Measured with each call a transaction of its own, as on chain. Inside one transaction every + /// slot would already be warm, and each write would be priced against the value the test began + /// with. On 15 November 2026 the next proposal used 227,155 gas when a finalize deleted the slot + /// and 121,755 with the slot kept; the bound sits between the two. + /// forge-config: default.isolate = true + /// forge-config: ci.isolate = true + function test_finalizeReputation_theNextProposalOverwritesRatherThanRefills() public { + SigvaraReputation.ReputationData memory data = maxScore; + // The oracle stamps the time it scored, so lastUpdated holds a value like the other fields. + data.lastUpdated = block.timestamp; + vm.prank(oracle); + rep.proposeReputation(DID, data, keccak256("first")); + vm.warp(block.timestamp + CHALLENGE_WINDOW + 1); + rep.finalizeReputation(DID); + + data.feeScore -= 1; + data.lastUpdated = block.timestamp; + vm.prank(oracle); + rep.proposeReputation(DID, data, keccak256("second")); + uint256 used = vm.lastCallGas().gasTotalUsed; + assertLt(used, 140_000, "the next proposal filled zeroed slots again"); + } + // ------------------------------------------------------------------------- // rejectReputation // -------------------------------------------------------------------------