Verified contractExactMIT
StellarLogSetVerifier
Address0xfc817115ca4259a0bc6d6eec8ed9f0186535fdfc
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- shanghai
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,405,350
- Creation transaction
- 0x20b3b3c5d1…5ffdac99c2
5 files
- contracts/src/StellarLogSetVerifier.solmain24.32 KB
- contracts/src/ISP1Verifier.sol1.31 KB
- contracts/src/LogSetKeyTable.sol30.75 KB
- contracts/src/StellarHeader.sol2.3 KB
- contracts/src/erc/ILogSet.sol11.02 KB
contracts/src/StellarLogSetVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ISP1Verifier} from "./ISP1Verifier.sol";
import {ILogSetRegistry, ILogSetVerifier, LogSetStatement, LogSetHashing} from "./erc/ILogSet.sol";
import {LogSetKeyTable} from "./LogSetKeyTable.sol";
import {StellarHeader} from "./StellarHeader.sol";
/// @title StellarLogSetVerifier
/// @author Willow
/// @notice ERC-draft "Verified Complete Log Sets" registry (`ILogSetRegistry`) on Ethereum for a
/// Stellar network. Same top proof as every other registry — the fold, public values
/// `abi.encode(LogSetStatement[1]) | indexListHash | leafVKey` — over Stellar leaves, and
/// the same key table, policy slot and governance (`LogSetKeyTable`). What differs is
/// the anchor and the positions.
///
/// @dev ANCHOR. Stellar does not settle on Ethereum, so the end ledger is anchored by a second
/// SP1 proof (key kind ANCHOR, the Stellar anchor program): a quorum of the pinned SCP
/// quorum set signed EXTERNALIZE for ledger `end + 1`, whose transaction set names
/// `hash(header_end)`. Its 288-byte public values are `abi.encode(uint64 kind, uint64
/// chainId, uint64 ledger, uint64 closeTime, bytes32 ledgerHash, bytes32 quorumSetHash,
/// bytes32 nextQuorumSetHash, uint64 signedEntries, uint64 totalEntries)`. The quorum set is
/// the trust root: SCP quorum sets are node configuration, not chain state, so the registry
/// pins one by hash per epoch.
///
/// @dev SUPERMAJORITY. SCP needs only a quorum (mainnet: 7 of 10 organisations). The registry
/// requires `signedEntries / totalEntries >= minSignedBps / 10000` of the pinned set's
/// top-level entries (mainnet: organisations), fixed at deployment, so forging an anchor
/// takes that many organisations' keys rather than a bare quorum's.
///
/// @dev QUORUM-SET EPOCHS. Append-only `(quorumSetHash, fromBlock)`, positions in close time.
/// An anchor must use the set of the epoch its ledger falls in. Two ways to append:
/// (1) handoff — an accepted anchor whose signers declaring a new set form a quorum under
/// both the current and the new set (proven in the guest) appends that set, with no admin,
/// the way a light client follows a validator set. The anchor must be fresh (within
/// `MAX_HANDOFF_AGE`) and in the latest epoch, and the new epoch starts after every close
/// time the registry has already accepted, so a handoff never re-judges an accepted ledger
/// and a stale one cannot revive a set the network has left. `applyHandoff` applies one for
/// a statement already accepted without it;
/// (2) the governor, through the same timelock as keys, for a change the network makes
/// faster than a handoff can show.
/// Epochs are a revocable table (`KIND_QUORUM`, system 0): the governor or guardian revokes
/// one like a key, and the governor can replace a revoked epoch's set for its span through
/// the 7-day timelock (the new hash in `programVKey`, no verifier, no leaf key).
///
/// @dev WITHDRAWAL. An acceptance's grounds are its LOGSET and ANCHOR entries and the quorum-set
/// epoch its anchor was judged under, all held here, so `verifiedAt` re-reads them with no
/// outside call. An epoch stands while its entry is live at the recorded generation and, for
/// a handoff epoch, while the ANCHOR entries that proved the handoff and the epoch it was
/// handed from still stand (walked back to a pinned epoch). Revoking an anchor key therefore
/// also withdraws the sets it handed off and every statement judged under them. Withdrawals
/// here are permanent: nothing un-revokes an entry, and a replacement is a new generation.
///
/// @dev POSITIONS ARE LEDGER CLOSE TIMES (`scpValue.closeTime`, agreed by SCP), as the L2
/// registries use L2 header time: Stellar protocol upgrades are scheduled by time, and an
/// entry's `from` must be >= `block.timestamp + MAX_CLOCK_DRIFT` at proposal, so no entry
/// speaks about ledgers that existed when it was proposed. Each proof carries the START
/// PARENT header (its hash is `startParentHash`, its sequence `startBlock - 1`); the END
/// close time comes from the anchor. No finality margin: an externalized ledger is final.
///
/// @dev PROOF BYTES (opaque to the ERC):
/// abi.encode(bytes32 indexListHash, SystemProof[] logsetProofs, bytes startParentHeader,
/// bytes anchorPV, SystemProof[] anchorProofs)
contract StellarLogSetVerifier is LogSetKeyTable, ILogSetRegistry {
/// @dev `anchorMask`/`anchorRefs`: the ANCHOR entries that proved a handoff epoch (mask 0 for
/// an epoch pinned at deployment or by the governor); `parentGeneration`: the generation of
/// the epoch it was handed from (always the one before it).
struct QuorumEpoch {
bytes32 quorumSetHash;
uint64 fromBlock;
uint8 anchorMask;
uint8 parentGeneration;
bytes32 anchorRefs;
}
struct PendingQuorum {
QuorumEpoch epoch;
uint64 eta;
bool live;
}
struct Decoded {
bytes32 ilh;
SystemProof[] logsetProofs;
bytes startParentHeader;
bytes anchorPV;
SystemProof[] anchorProofs;
}
struct AnchorValues {
uint64 kind;
uint64 chainId;
uint64 ledger;
uint64 closeTime;
bytes32 ledgerHash;
bytes32 quorumSetHash;
bytes32 nextQuorumSetHash;
uint64 signedEntries;
uint64 totalEntries;
}
struct Checked {
bytes32 ilh;
uint64 endTs;
bytes32 quorumSetHash;
bytes32 nextQuorumSetHash;
uint256 epoch;
uint32 epochRef;
uint8 mask;
bytes32 logsetRefs;
bytes32 anchorRefs;
}
/// @dev What a statement was last accepted under: the block, the systems in `mask` (whose
/// LOGSET and ANCHOR entry refs are kept beside it, one 32-bit ref per system) and the
/// quorum-set epoch (`index << 8 | generation`).
struct Record {
uint64 verifiedAt;
uint8 mask;
uint32 epochRef;
}
uint64 public constant ANCHOR_KIND = 0x5354_4c52; // "STLR"
/// @notice The quorum-set epoch table, for revocation and replacement (system 0).
uint8 public constant KIND_QUORUM = 0xFE;
uint256 public constant ANCHOR_PUBLIC_VALUES_LEN = 288;
/// @notice How far a ledger close time may lead Ethereum time (SCP rejects values far from
/// the validators' clocks; the margin matches the L2 registries).
uint256 public constant MAX_CLOCK_DRIFT = 1 days;
/// @notice How old an anchor may be and still hand the pin to a new quorum set.
uint256 public constant MAX_HANDOFF_AGE = 1 days;
uint256 public immutable sourceChainId;
/// @notice The share of the pinned set's top-level entries that must sign, in basis points.
uint256 public immutable minSignedBps;
QuorumEpoch[] internal _quorums;
/// @notice The latest end close time of any accepted statement.
uint64 public latestAnchoredTs;
PendingQuorum public pendingQuorum;
mapping(bytes32 => Record) private _record;
mapping(bytes32 => bytes32) private _logsetRefs;
mapping(bytes32 => bytes32) private _anchorRefs;
mapping(bytes32 => bytes32) private _indexListHashOf;
event LogSetIndexed(bytes32 indexed statementHash, bytes32 indexListHash);
/// @notice The entries and quorum-set epoch a statement was accepted under; a withdrawal of
/// any of them voids it.
event LogSetEntries(
bytes32 indexed statementHash, uint8 mask, bytes32 logsetRefs, bytes32 anchorRefs, uint32 epochRef
);
event StellarAnchored(bytes32 indexed statementHash, uint64 ledger, uint64 closeTime, bytes32 quorumSetHash);
event QuorumSetProposed(bytes32 quorumSetHash, uint64 fromBlock, uint64 eta);
event QuorumSetCancelled();
event QuorumSetAppended(uint256 index, bytes32 quorumSetHash, uint64 fromBlock, bool handoff);
error WrongChain(uint256 got, uint256 want);
error RangeOrder(uint64 startBlock, uint64 endBlock);
error ZeroChainId();
error ZeroQuorumSet();
error StartParentNumber(uint32 got, uint64 want);
error AnchorShape(uint256 length);
error AnchorKindMismatch(uint64 got);
error AnchorChainMismatch(uint64 got);
error AnchorLedgerMismatch(uint64 got, uint64 want);
error AnchorHashMismatch(bytes32 got, bytes32 want);
error TimeOrder(uint64 startTs, uint64 endTs);
error QuorumSetMismatch(bytes32 got, bytes32 want);
error QuorumEpochNotActive(uint64 position);
error QuorumEpochWithdrawn(uint256 epoch);
error StaleHandoff(uint64 closeTime);
error NoHandoff();
error InsufficientSigners(uint64 signedEntries, uint64 totalEntries);
error BadSignedBps(uint256 bps);
/// @param _chainId The Stellar network's statement chain id (first 8 bytes of its
/// network id; pubnet 0x7ac33997544e3175).
/// @param _appendDelay Seconds every proposal waits. Floor 7 days.
/// @param _governor May propose appends; `address(0)` deploys frozen.
/// @param _verifier The initial entries' version-pinned verifier (never the gateway).
/// @param _foldVKey The fold's `vk.bytes32()`.
/// @param _leafVKey The Stellar leaf key the fold commits (KoalaBear words, big-endian).
/// @param _anchorVKey The Stellar anchor guest's `vk.bytes32()`.
/// @param _from First close time the initial keys and quorum set cover.
/// @param _quorumSetHash `sha256(XDR(SCPQuorumSet))` of the pinned set.
/// @param _minSignedBps Share of the set's top-level entries that must sign (basis points).
constructor(
uint256 _chainId,
uint256 _appendDelay,
address _governor,
address _verifier,
bytes32 _foldVKey,
bytes32 _leafVKey,
bytes32 _anchorVKey,
uint64 _from,
bytes32 _quorumSetHash,
uint256 _minSignedBps
) LogSetKeyTable(_appendDelay, _governor) {
if (_minSignedBps == 0 || _minSignedBps > 10_000) revert BadSignedBps(_minSignedBps);
minSignedBps = _minSignedBps;
if (_chainId == 0) revert ZeroChainId();
if (_verifier == address(0)) revert ZeroAddress();
if (_foldVKey == bytes32(0) || _leafVKey == bytes32(0) || _anchorVKey == bytes32(0)) revert ZeroVKey();
if (_quorumSetHash == bytes32(0)) revert ZeroQuorumSet();
sourceChainId = _chainId;
_initKey(KIND_LOGSET, SYSTEM_SP1, ProgramKey(_foldVKey, _leafVKey, _verifier, _from));
_initKey(KIND_ANCHOR, SYSTEM_SP1, ProgramKey(_anchorVKey, bytes32(0), _verifier, _from));
_quorums.push(QuorumEpoch(_quorumSetHash, _from, 0, 0, bytes32(0)));
emit QuorumSetAppended(0, _quorumSetHash, _from, false);
}
// ------------------------------------------------------------------ positions = close time
function _appendFloor() internal view override returns (uint256) {
return block.timestamp + MAX_CLOCK_DRIFT;
}
function _maxKind() internal pure override returns (uint8) {
return KIND_ANCHOR;
}
function _systemReady(uint8 system) internal view override returns (bool) {
return _keys[KIND_LOGSET][system].length != 0 && _keys[KIND_ANCHOR][system].length != 0;
}
function _entryCount(uint8 kind, uint8 system) internal view override returns (uint256) {
if (kind == KIND_QUORUM) return system == 0 ? _quorums.length : 0;
return super._entryCount(kind, system);
}
/// @dev A quorum-set replacement carries the new set's hash in `programVKey` and nothing else.
function _checkReplacement(uint8 kind, address verifier, bytes32 programVKey, bytes32 leafVKey)
internal
pure
override
{
if (kind != KIND_QUORUM) return super._checkReplacement(kind, verifier, programVKey, leafVKey);
if (verifier != address(0) || leafVKey != bytes32(0)) revert LeafKeyShape(kind);
if (programVKey == bytes32(0)) revert ZeroQuorumSet();
}
// ------------------------------------------------------------------ ILogSetVerifier / Registry
/// @inheritdoc ILogSetVerifier
function checkLogSet(LogSetStatement calldata statement, bytes calldata proof) public view {
_check(statement, proof);
}
/// @inheritdoc ILogSetRegistry
/// @dev Returns without verifying while the statement's acceptance stands. Otherwise verifies
/// and records a new acceptance (block, `indexListHash`, entries, epoch), applies a proven
/// quorum-set handoff when the anchor sits in the latest epoch, and emits
/// `LogSetVerified`: once per acceptance, including a re-acceptance after a withdrawal.
function submitLogSet(LogSetStatement calldata statement, bytes calldata proof) external returns (bytes32 h) {
h = LogSetHashing.statementHash(statement);
if (_stands(h)) return h;
Checked memory c = _check(statement, proof);
_record[h] = Record(uint64(block.number), c.mask, c.epochRef);
_logsetRefs[h] = c.logsetRefs;
_anchorRefs[h] = c.anchorRefs;
_indexListHashOf[h] = c.ilh;
if (_handoffApplies(c)) _handoff(c);
if (c.endTs > latestAnchoredTs) latestAnchoredTs = c.endTs;
emit StellarAnchored(h, statement.endBlock, c.endTs, c.quorumSetHash);
emit LogSetIndexed(h, c.ilh);
emit LogSetEntries(h, c.mask, c.logsetRefs, c.anchorRefs, c.epochRef);
emit LogSetVerified(
h,
statement.chainId,
statement.filterHash,
statement.startBlock,
statement.endBlock,
statement.logSetRoot,
statement.logCount
);
}
/// @notice Apply the quorum-set handoff an anchor proves, for a statement accepted (or
/// front-run) without it. Same checks as `submitLogSet`.
function applyHandoff(LogSetStatement calldata statement, bytes calldata proof) external {
Checked memory c = _check(statement, proof);
if (c.nextQuorumSetHash == c.quorumSetHash) revert NoHandoff();
if (!_handoffApplies(c)) revert StaleHandoff(c.endTs);
_handoff(c);
}
/// @dev A new set, fresh, from the latest epoch.
function _handoffApplies(Checked memory c) internal view returns (bool) {
return c.nextQuorumSetHash != c.quorumSetHash && c.epoch == _quorums.length - 1
&& uint256(c.endTs) + MAX_HANDOFF_AGE >= block.timestamp;
}
/// @dev The new epoch starts after the anchored ledger and after every accepted close time, and
/// keeps what it rests on: the anchor entries that proved it and its parent's generation.
function _handoff(Checked memory c) internal {
uint64 from = (c.endTs > latestAnchoredTs ? c.endTs : latestAnchoredTs) + 1;
_quorums.push(QuorumEpoch(c.nextQuorumSetHash, from, c.mask, uint8(c.epochRef), c.anchorRefs));
emit QuorumSetAppended(_quorums.length - 1, c.nextQuorumSetHash, from, true);
}
/// @inheritdoc ILogSetRegistry
/// @dev Fails closed: 0 once any entry or the quorum-set epoch the statement was accepted
/// under is withdrawn (see WITHDRAWAL), until the statement is accepted again.
function verifiedAt(bytes32 statementHash_) external view returns (uint256) {
return _stands(statementHash_) ? _record[statementHash_].verifiedAt : 0;
}
/// @notice The raw record (not voided by withdrawals): block, mask, epoch and packed entry refs
/// (`index << 8 | generation` per system, 32-bit lane = system).
function recordOf(bytes32 statementHash_)
external
view
returns (Record memory record, bytes32 logsetRefs, bytes32 anchorRefs)
{
return (_record[statementHash_], _logsetRefs[statementHash_], _anchorRefs[statementHash_]);
}
/// @dev Whether the statement's latest acceptance stands now.
function _stands(bytes32 h) internal view returns (bool) {
Record memory r = _record[h];
return r.verifiedAt != 0 && _refsValid(KIND_LOGSET, r.mask, _logsetRefs[h])
&& _refsValid(KIND_ANCHOR, r.mask, _anchorRefs[h]) && _epochStands(r.epochRef >> 8, uint8(r.epochRef));
}
/// @dev Whether epoch `i` at generation `g` stands (see WITHDRAWAL). A replaced epoch is pinned
/// by the governor; a handoff epoch rests on its anchor entries and its parent.
function _epochStands(uint256 i, uint8 g) internal view returns (bool stands) {
while (true) {
if (!_refValid(KIND_QUORUM, 0, _ref(i, g))) return false;
if (g != 0) return true;
QuorumEpoch storage q = _quorums[i];
if (q.anchorMask == 0) return true;
if (!_refsValid(KIND_ANCHOR, q.anchorMask, q.anchorRefs)) return false;
(i, g) = (i - 1, q.parentGeneration);
}
}
/// @dev Epoch `i`'s set as it stands now (a replacement's, if replaced) and its ref; reverts
/// if the epoch is revoked or withdrawn.
function _liveEpoch(uint256 i) internal view returns (bytes32 quorumSetHash, uint32 ref) {
(uint8 g, bytes32 id) = _liveGeneration(KIND_QUORUM, 0, i);
if (!_epochStands(i, g)) revert QuorumEpochWithdrawn(i);
quorumSetHash = g == 0 ? _quorums[i].quorumSetHash : _replacement[id].programVKey;
ref = _ref(i, g);
}
function indexListHashOf(bytes32 statementHash_) external view returns (bytes32) {
return _indexListHashOf[statementHash_];
}
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return interfaceId == type(ILogSetVerifier).interfaceId || interfaceId == type(ILogSetRegistry).interfaceId
|| interfaceId == 0x01ffc9a7;
}
function statementHash(LogSetStatement calldata statement) external pure returns (bytes32) {
return LogSetHashing.statementHash(statement);
}
function quorumCount() external view returns (uint256) {
return _quorums.length;
}
function quorumAt(uint256 i) external view returns (QuorumEpoch memory) {
return _quorums[i];
}
/// @notice The epoch whose quorum set an anchor for a ledger closed at `position` must use.
function quorumEpochAt(uint64 position) public view returns (uint256) {
for (uint256 i = _quorums.length; i > 0; i--) {
if (_quorums[i - 1].fromBlock <= position) return i - 1;
}
revert QuorumEpochNotActive(position);
}
function decodeProof(bytes calldata proof) external pure returns (Decoded memory d) {
(d.ilh, d.logsetProofs, d.startParentHeader, d.anchorPV, d.anchorProofs) =
abi.decode(proof, (bytes32, SystemProof[], bytes, bytes, SystemProof[]));
}
// ------------------------------------------------------------------ verification
function _check(LogSetStatement calldata s, bytes calldata proof) internal view returns (Checked memory c) {
// Decoded in place (not through `decodeProof`, to stay under EIP-170): a malformed proof
// reverts without data.
Decoded memory d;
(d.ilh, d.logsetProofs, d.startParentHeader, d.anchorPV, d.anchorProofs) =
abi.decode(proof, (bytes32, SystemProof[], bytes, bytes, SystemProof[]));
if (s.chainId != sourceChainId) revert WrongChain(s.chainId, sourceChainId);
if (s.startBlock > s.endBlock || s.startBlock == 0) revert RangeOrder(s.startBlock, s.endBlock);
(uint32 parentSeq, uint64 startTs) = StellarHeader.bind(d.startParentHeader, s.startParentHash);
if (parentSeq != s.startBlock - 1) revert StartParentNumber(parentSeq, s.startBlock - 1);
AnchorValues memory a = _anchorValues(d.anchorPV, s.endBlock, s.endBlockHash);
c.ilh = d.ilh;
c.endTs = a.closeTime;
c.quorumSetHash = a.quorumSetHash;
c.nextQuorumSetHash = a.nextQuorumSetHash;
if (startTs > c.endTs) revert TimeOrder(startTs, c.endTs);
c.epoch = quorumEpochAt(c.endTs);
bytes32 pinned;
(pinned, c.epochRef) = _liveEpoch(c.epoch);
if (c.quorumSetHash != pinned) revert QuorumSetMismatch(c.quorumSetHash, pinned);
c.mask = requiredSystemsAt(c.endTs);
c.logsetRefs = _foldLeg(s, c.ilh, d.logsetProofs, c.mask, startTs, c.endTs);
c.anchorRefs = _anchorLeg(d.anchorPV, d.anchorProofs, c.mask, c.endTs);
}
/// @dev One anchor proof per required system over the same 288 bytes; returns the entry refs.
function _anchorLeg(bytes memory pv, SystemProof[] memory proofs, uint8 mask, uint64 endTs)
internal
view
returns (bytes32 refs)
{
uint8 seen;
for (uint256 i = 0; i < proofs.length; i++) {
seen = _markSystem(mask, seen, proofs[i].system);
(ProgramKey memory k, uint32 ref) = _keyFor(KIND_ANCHOR, proofs[i].system, proofs[i].keyIndex, endTs, endTs);
ISP1Verifier(k.verifier).verifyProof(k.programVKey, pv, proofs[i].proof);
refs |= _lane(proofs[i].system, ref);
}
if (seen != mask) revert MissingSystemProof(mask, seen);
}
/// @dev The anchor names the statement's end ledger, number and hash, on this network.
function _anchorValues(bytes memory pv, uint64 endBlock, bytes32 endBlockHash)
internal
view
returns (AnchorValues memory a)
{
if (pv.length != ANCHOR_PUBLIC_VALUES_LEN) revert AnchorShape(pv.length);
a = abi.decode(pv, (AnchorValues));
if (a.kind != ANCHOR_KIND) revert AnchorKindMismatch(a.kind);
if (a.chainId != sourceChainId) revert AnchorChainMismatch(a.chainId);
if (a.ledger != endBlock) revert AnchorLedgerMismatch(a.ledger, endBlock);
if (a.ledgerHash != endBlockHash) revert AnchorHashMismatch(a.ledgerHash, endBlockHash);
if (uint256(a.signedEntries) * 10_000 < uint256(a.totalEntries) * minSignedBps || a.totalEntries == 0) {
revert InsufficientSigners(a.signedEntries, a.totalEntries);
}
}
// ------------------------------------------------------------------ quorum-set governance
/// @notice Propose appending a quorum-set epoch, for a change the network makes faster than
/// a handoff can show. Same timelock and non-retroactivity as keys.
function proposeQuorumSet(bytes32 quorumSetHash, uint64 fromBlock) external onlyGovernor {
if (quorumSetHash == bytes32(0)) revert ZeroQuorumSet();
if (pendingQuorum.live) revert ProposalPending();
uint256 floor = _appendFloor();
if (fromBlock < floor) revert RetroactiveFromBlock(fromBlock, floor);
uint64 last = _quorums[_quorums.length - 1].fromBlock;
if (fromBlock <= last) revert FromBlockNotIncreasing(fromBlock, last);
uint64 eta = uint64(block.timestamp + appendDelay);
pendingQuorum = PendingQuorum(QuorumEpoch(quorumSetHash, fromBlock, 0, 0, bytes32(0)), eta, true);
pendingCount++;
emit QuorumSetProposed(quorumSetHash, fromBlock, eta);
}
function cancelQuorumSet() external onlyGovernor {
if (!pendingQuorum.live) revert NoProposal();
delete pendingQuorum;
pendingCount--;
emit QuorumSetCancelled();
}
/// @notice Anyone may execute a matured proposal. A handoff appended meanwhile past its `from`
/// makes it stale; it is then cancelled and re-proposed.
function executeQuorumSet() external {
PendingQuorum memory p = pendingQuorum;
if (!p.live) revert NoProposal();
if (block.timestamp < p.eta) revert TooEarly(p.eta);
uint64 last = _quorums[_quorums.length - 1].fromBlock;
if (p.epoch.fromBlock <= last) revert FromBlockNotIncreasing(p.epoch.fromBlock, last);
delete pendingQuorum;
pendingCount--;
_quorums.push(p.epoch); // proposed with no handoff provenance: a pinned epoch
emit QuorumSetAppended(_quorums.length - 1, p.epoch.quorumSetHash, p.epoch.fromBlock, false);
}
}
contracts/src/ISP1Verifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title ISP1Verifier
/// @notice Vendored verbatim from succinctlabs/sp1-contracts (contracts/src/ISP1Verifier.sol).
/// Both the canonical `SP1VerifierGateway` and each concrete `SP1VerifierGroth16`
/// implement this interface, so a verifier contract can point at EITHER address.
/// @dev verifyProof is a `view` that REVERTS on an invalid proof and returns on success.
interface ISP1Verifier {
/// @notice Verifies a proof with given public values and vkey.
/// @param programVKey The verification key for the RISC-V program (the guest ELF).
/// @param publicValues The public values committed by the guest via `sp1_zkvm::io::commit_*`.
/// @param proofBytes The proof, prefixed with a 4-byte verifier selector.
function verifyProof(
bytes32 programVKey,
bytes calldata publicValues,
bytes calldata proofBytes
) external view;
}
/// @title ISP1VerifierWithHash
/// @notice Extends ISP1Verifier with the verifier identity hash whose first 4 bytes are the route selector.
interface ISP1VerifierWithHash is ISP1Verifier {
/// @notice The 32-byte verifier hash; `bytes4(VERIFIER_HASH())` is the proof selector.
function VERIFIER_HASH() external pure returns (bytes32);
}
contracts/src/LogSetKeyTable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ISP1Verifier} from "./ISP1Verifier.sol";
import {LogSetStatement} from "./erc/ILogSet.sol";
/// @title LogSetKeyTable
/// @author Willow
/// @notice The program-key table, policy slot and governance shared by every Willow log-set
/// registry: `LogSetVerifierV2` (Ethereum), `LogSetVerifierL2` (one per L2 that settles
/// on Ethereum) and `StellarLogSetVerifier`. Only the anchor leg differs between them.
///
/// @dev POSITIONS. A table entry covers source positions `[fromBlock_i, fromBlock_{i+1})`. A
/// position is whatever the registry can BIND for its source chain: the block number on
/// Ethereum (the registry runs there), the L2 header TIMESTAMP on an L2 (the registry checks
/// the boundary headers against the proven hashes; L2 forks activate by timestamp, and an
/// L2's block numbers are not known in advance). The field keeps the name `fromBlock` for
/// ABI continuity.
///
/// @dev PROGRAM-KEY TABLE. Per (kind, proof system), an APPEND-ONLY list of
/// `(programVKey, leafVKey, verifier, fromBlock)` with strictly increasing `fromBlock`.
/// `verifier` is the fixed, version-pinned verifier contract for that entry's proofs
/// (a concrete SP1 verifier, never a gateway whose owner can freeze routes), so an SP1
/// bump is one append. A statement must lie inside one entry's span (the caller names it).
/// Kind LOGSET: `programVKey` is the fold's vkey and `leafVKey` the leaf key the fold
/// COMMITS, so a receipt-format fork is one append.
///
/// @dev GOVERNANCE. The governor only PROPOSES (a key entry or a stricter policy). Every proposal
/// waits `appendDelay` (>= 7 days) and is executed by anyone. A proposal's `fromBlock` must
/// be >= `_appendFloor()` (the current position), so an entry never speaks about a position
/// that existed before it was public. Appended entries are never removed or overwritten (a
/// revoked entry is replaced through a side mapping, below); the policy mask only gains
/// systems; `renounceGovernor` (nothing pending) freezes the tables. A governor
/// handover is timelocked the same way: the governor proposes a successor, and after
/// `appendDelay` the successor itself must accept (two steps, so a mistyped address can
/// never take governance; the current governor can cancel until then).
///
/// @dev POLICY SLOT. Append-only `(requiredSystems, fromBlock)`; the mask in force at a
/// statement's END position names the proof systems that must each attest.
///
/// @dev REVOCATION. Any table entry (a program key; on an L2 also an anchor adapter, table
/// `KIND_ADAPTER`; on Stellar also a quorum-set epoch, table `KIND_QUORUM`) can be revoked:
/// `revokeKey` schedules it, and after `REVOKE_DELAY` (1 hour, short because a revocation only
/// shrinks what the registry accepts) anyone executes it. A revoked entry is refused for new
/// submissions, and every statement recorded under it stops counting: `verifiedAt` returns 0
/// and stays 0 (nothing un-revokes an entry). The governor can then
/// propose a REPLACEMENT for exactly that entry's span (same index, so proofs and records keep
/// their indices); after `appendDelay` the replacement serves the span, and statements over
/// it can be re-submitted under the fixed key. This is the table's one retroactive power, and
/// it only ever applies to a span whose entry was revoked.
///
/// @dev LIMITS ON REVOCATION POWER. Revocation can CENSOR a good key: whoever revokes can stop the
/// registry accepting correct proofs for that entry's whole span, and void the statements
/// already recorded under it, until a replacement passes the 7-day timelock. The checks on
/// that power: revocations wait `REVOKE_DELAY`, and only the governor can cancel one. The
/// GUARDIAN is optional (none at deployment), revoke-only (it cannot append, replace, cancel,
/// or change policy or governance), set or replaced only through the 7-day timelock, and
/// removable by the governor at once. `renounceGovernor` clears the guardian, so a frozen
/// registry can no longer be censored, and can no longer revoke either.
abstract contract LogSetKeyTable {
struct ProgramKey {
bytes32 programVKey;
bytes32 leafVKey;
address verifier;
uint64 fromBlock;
}
struct Policy {
uint8 requiredSystems;
uint64 fromBlock;
}
struct SystemProof {
uint8 system;
uint32 keyIndex;
bytes proof;
}
struct PendingKey {
ProgramKey key;
uint64 eta;
bool live;
}
struct PendingPolicy {
Policy policy;
uint64 eta;
bool live;
}
/// @dev Per entry: how many replacements it has had, and whether the current one is revoked.
struct EntryState {
uint8 generation;
bool revoked;
}
/// @dev A revoked entry's replacement. It keeps the entry's `fromBlock` (its span). For the
/// adapter table, `verifier` holds the adapter and both vkeys are zero.
struct Replacement {
bytes32 programVKey;
bytes32 leafVKey;
address verifier;
}
struct PendingReplacement {
Replacement key;
uint64 eta;
bool live;
}
struct PendingGuardian {
address guardian;
uint64 eta;
bool live;
}
uint8 public constant KIND_LOGSET = 0;
uint8 public constant KIND_ANCHOR = 1;
uint8 public constant SYSTEM_SP1 = 0;
uint8 public constant MAX_SYSTEMS = 8;
uint256 public constant MIN_APPEND_DELAY = 7 days;
uint256 public constant FOLD_PUBLIC_VALUES_LEN = 384;
/// @notice An L2 registry's anchor-adapter table, for revocation and replacement (system 0).
uint8 public constant KIND_ADAPTER = 0xFF;
uint256 public constant REVOKE_DELAY = 1 hours;
uint256 public immutable appendDelay;
address public governor;
address public pendingGovernor;
uint64 public pendingGovernorEta;
uint256 public pendingCount;
mapping(uint8 => mapping(uint8 => ProgramKey[])) internal _keys;
Policy[] internal _policies;
mapping(uint8 => mapping(uint8 => PendingKey)) public pendingKey;
PendingPolicy public pendingPolicy;
address public guardian;
PendingGuardian public pendingGuardian;
mapping(bytes32 => EntryState) internal _entryState;
mapping(bytes32 => Replacement) internal _replacement;
/// @notice Scheduled revocations: `entryId(kind, system, index)` => eta (0 = none).
mapping(bytes32 => uint64) public pendingRevocation;
mapping(bytes32 => PendingReplacement) public pendingReplacement;
event KeyProposed(
uint8 indexed kind,
uint8 indexed system,
bytes32 programVKey,
bytes32 leafVKey,
address verifier,
uint64 fromBlock,
uint64 eta
);
event KeyCancelled(uint8 indexed kind, uint8 indexed system);
event KeyAppended(
uint8 indexed kind,
uint8 indexed system,
uint256 index,
bytes32 programVKey,
bytes32 leafVKey,
address verifier,
uint64 fromBlock
);
event PolicyProposed(uint8 requiredSystems, uint64 fromBlock, uint64 eta);
event PolicyCancelled();
event PolicyAppended(uint256 index, uint8 requiredSystems, uint64 fromBlock);
event GovernorProposed(address indexed from, address indexed to, uint64 eta);
event GovernorHandoverCancelled(address indexed from, address indexed to);
event GovernorTransferred(address indexed from, address indexed to);
event RevokeScheduled(
uint8 indexed kind, uint8 indexed system, uint256 index, uint8 generation, address by, uint64 eta
);
event RevokeCancelled(uint8 indexed kind, uint8 indexed system, uint256 index);
event EntryRevoked(uint8 indexed kind, uint8 indexed system, uint256 index, uint8 generation);
event ReplacementProposed(
uint8 indexed kind,
uint8 indexed system,
uint256 index,
bytes32 programVKey,
bytes32 leafVKey,
address verifier,
uint64 eta
);
event ReplacementCancelled(uint8 indexed kind, uint8 indexed system, uint256 index);
event EntryReplaced(
uint8 indexed kind,
uint8 indexed system,
uint256 index,
uint8 generation,
bytes32 programVKey,
bytes32 leafVKey,
address verifier
);
event GuardianProposed(address indexed guardian, uint64 eta);
event GuardianProposalCancelled(address indexed guardian);
event GuardianSet(address indexed from, address indexed to);
error SystemNotRequired(uint8 system);
error DuplicateSystemProof(uint8 system);
error MissingSystemProof(uint8 requiredMask, uint8 providedMask);
error KeyIndexOutOfRange(uint8 kind, uint8 system, uint256 index);
error KeyNotYetActive(uint64 startBlock, uint64 fromBlock);
error KeySuperseded(uint64 endBlock, uint64 nextFromBlock);
error KeyRevoked(uint8 kind, uint8 system, uint256 index);
error NotGovernor();
error NotPendingGovernor();
error ZeroAddress();
error ZeroVKey();
error AppendDelayTooLow(uint256 got, uint256 floor);
error BadKind(uint8 kind);
error BadSystem(uint8 system);
error LeafKeyShape(uint8 kind);
error ProposalPending();
error NoProposal();
error TooEarly(uint64 eta);
error RetroactiveFromBlock(uint64 fromBlock, uint256 head);
error FromBlockNotIncreasing(uint64 fromBlock, uint64 last);
error PolicyNotStricter(uint8 current, uint8 proposed);
error PolicySystemUnready(uint8 system);
error ProposalsPending(uint256 count);
error NotGovernorOrGuardian();
error AlreadyRevoked(uint8 kind, uint8 system, uint256 index);
error NotRevoked(uint8 kind, uint8 system, uint256 index);
error GenerationLimit(uint8 kind, uint8 system, uint256 index);
constructor(uint256 _appendDelay, address _governor) {
if (_appendDelay < MIN_APPEND_DELAY) revert AppendDelayTooLow(_appendDelay, MIN_APPEND_DELAY);
appendDelay = _appendDelay;
governor = _governor;
_policies.push(Policy({requiredSystems: uint8(1) << SYSTEM_SP1, fromBlock: 0}));
emit PolicyAppended(0, uint8(1) << SYSTEM_SP1, 0);
if (_governor != address(0)) emit GovernorTransferred(address(0), _governor);
}
// ------------------------------------------------------------------ hooks
/// @dev The current position: an appended entry or policy must start at or after it.
function _appendFloor() internal view virtual returns (uint256);
/// @dev The largest key kind this registry uses.
function _maxKind() internal pure virtual returns (uint8);
/// @dev Whether `system` has every table it needs for a policy to require it.
function _systemReady(uint8 system) internal view virtual returns (bool);
/// @dev Entries in table (kind, system); 0 for a table this registry does not have. An L2
/// registry adds `KIND_ADAPTER`.
function _entryCount(uint8 kind, uint8 system) internal view virtual returns (uint256) {
if (kind > _maxKind() || system >= MAX_SYSTEMS) return 0;
return _keys[kind][system].length;
}
// ------------------------------------------------------------------ views
function keyCount(uint8 kind, uint8 system) external view returns (uint256) {
return _keys[kind][system].length;
}
function keyAt(uint8 kind, uint8 system, uint256 i) external view returns (ProgramKey memory) {
return _keys[kind][system][i];
}
function policyCount() external view returns (uint256) {
return _policies.length;
}
function policyAt(uint256 i) external view returns (Policy memory) {
return _policies[i];
}
function entryId(uint8 kind, uint8 system, uint256 index) public pure returns (bytes32) {
return keccak256(abi.encode(kind, system, index));
}
/// @notice An entry's replacement count and whether its current generation is revoked.
function entryState(uint8 kind, uint8 system, uint256 index) external view returns (EntryState memory) {
return _entryState[entryId(kind, system, index)];
}
/// @notice The replacement serving a revoked-then-replaced entry (zero before any).
function replacementOf(uint8 kind, uint8 system, uint256 index) external view returns (Replacement memory) {
return _replacement[entryId(kind, system, index)];
}
/// @notice The proof systems that must each attest to a statement ending at `position`.
function requiredSystemsAt(uint64 position) public view returns (uint8 mask) {
for (uint256 i = _policies.length; i > 0; i--) {
if (_policies[i - 1].fromBlock <= position) return _policies[i - 1].requiredSystems;
}
return 0; // unreachable: _policies[0].fromBlock == 0
}
/// @notice The exact public values a fold proof under `leafVKey` must commit for
/// `statement` with `indexListHash` — what the registry hands the verifier.
function foldPublicValues(LogSetStatement memory statement, bytes32 indexListHash, bytes32 leafVKey)
public
pure
returns (bytes memory)
{
LogSetStatement[] memory one = new LogSetStatement[](1);
one[0] = statement;
return abi.encodePacked(abi.encode(one), indexListHash, leafVKey);
}
// ------------------------------------------------------------------ verification
/// @dev One proof per required system, each over the pv built from the statement, the index
/// list hash and THAT entry's leaf key; the entry must cover `[startPos, endPos]`.
/// Returns each system's entry ref (`_ref`) in 32-bit lane `system`.
function _foldLeg(
LogSetStatement calldata s,
bytes32 ilh,
SystemProof[] memory proofs,
uint8 mask,
uint64 startPos,
uint64 endPos
) internal view returns (bytes32 refs) {
LogSetStatement[] memory one = new LogSetStatement[](1);
one[0] = s;
bytes memory head = abi.encode(one);
uint8 seen;
for (uint256 i = 0; i < proofs.length; i++) {
seen = _markSystem(mask, seen, proofs[i].system);
(ProgramKey memory k, uint32 ref) =
_keyFor(KIND_LOGSET, proofs[i].system, proofs[i].keyIndex, startPos, endPos);
ISP1Verifier(k.verifier)
.verifyProof(k.programVKey, abi.encodePacked(head, ilh, k.leafVKey), proofs[i].proof);
refs |= _lane(proofs[i].system, ref);
}
if (seen != mask) revert MissingSystemProof(mask, seen);
}
/// @dev An entry's index and generation, packed: `index << 8 | generation`.
function _ref(uint256 index, uint8 generation) internal pure returns (uint32) {
return uint32(index << 8) | generation;
}
function _lane(uint8 system, uint32 ref) internal pure returns (bytes32) {
return bytes32(uint256(ref) << (32 * uint256(system)));
}
/// @dev Whether the entry a ref names still holds that generation and is not revoked.
function _refValid(uint8 kind, uint8 system, uint32 ref) internal view returns (bool) {
EntryState memory e = _entryState[entryId(kind, system, ref >> 8)];
return !e.revoked && e.generation == uint8(ref);
}
/// @dev `_refValid` for every system in `mask`, refs packed as `_foldLeg` returns them.
function _refsValid(uint8 kind, uint8 mask, bytes32 refs) internal view returns (bool) {
for (uint8 s = 0; s < MAX_SYSTEMS; s++) {
if (mask & (uint8(1) << s) == 0) continue;
if (!_refValid(kind, s, uint32(uint256(refs) >> (32 * uint256(s))))) return false;
}
return true;
}
/// @dev The entry's current generation, refusing a revoked one.
function _liveGeneration(uint8 kind, uint8 system, uint256 idx) internal view returns (uint8 g, bytes32 id) {
id = entryId(kind, system, idx);
EntryState memory e = _entryState[id];
if (e.revoked) revert KeyRevoked(kind, system, idx);
g = e.generation;
}
/// @dev One proof per required system, no system twice, none outside the mask.
function _markSystem(uint8 mask, uint8 seen, uint8 system) internal pure returns (uint8) {
if (system >= MAX_SYSTEMS) revert BadSystem(system);
uint8 bit = uint8(1) << system;
if (mask & bit == 0) revert SystemNotRequired(system);
if (seen & bit != 0) revert DuplicateSystemProof(system);
return seen | bit;
}
/// @dev Entry `idx` of (kind, system) must cover `[startPos, endPos]` entirely and not be
/// revoked; a replaced entry serves its replacement's keys over its own span.
function _keyFor(uint8 kind, uint8 system, uint256 idx, uint64 startPos, uint64 endPos)
internal
view
returns (ProgramKey memory k, uint32 ref)
{
ProgramKey[] storage ks = _keys[kind][system];
if (idx >= ks.length) revert KeyIndexOutOfRange(kind, system, idx);
k = ks[idx];
if (startPos < k.fromBlock) revert KeyNotYetActive(startPos, k.fromBlock);
if (idx + 1 < ks.length && endPos >= ks[idx + 1].fromBlock) {
revert KeySuperseded(endPos, ks[idx + 1].fromBlock);
}
(uint8 g, bytes32 id) = _liveGeneration(kind, system, idx);
if (g != 0) {
Replacement memory r = _replacement[id];
(k.programVKey, k.leafVKey, k.verifier) = (r.programVKey, r.leafVKey, r.verifier);
}
ref = _ref(idx, g);
}
/// @dev Constructor-time entry: no timelock, any position (the registry did not exist before).
function _initKey(uint8 kind, uint8 system, ProgramKey memory k) internal {
_keys[kind][system].push(k);
emit KeyAppended(
kind, system, _keys[kind][system].length - 1, k.programVKey, k.leafVKey, k.verifier, k.fromBlock
);
}
// ------------------------------------------------------------------ governance
modifier onlyGovernor() {
if (msg.sender != governor) revert NotGovernor();
_;
}
// ------------------------------------------------------------------ revocation
/// @notice Schedule the revocation of entry `index` of table (kind, system). The governor or
/// the guardian may call it; anyone executes it after `REVOKE_DELAY`, and only the
/// governor can cancel it. `kind` is a program-key kind, or `KIND_ADAPTER` on an L2.
function revokeKey(uint8 kind, uint8 system, uint256 index) external {
if (msg.sender != governor && msg.sender != guardian) revert NotGovernorOrGuardian();
if (index >= _entryCount(kind, system)) revert KeyIndexOutOfRange(kind, system, index);
bytes32 id = entryId(kind, system, index);
EntryState memory e = _entryState[id];
if (e.revoked) revert AlreadyRevoked(kind, system, index);
if (pendingRevocation[id] != 0) revert ProposalPending();
uint64 eta = uint64(block.timestamp + REVOKE_DELAY);
pendingRevocation[id] = eta;
pendingCount++;
emit RevokeScheduled(kind, system, index, e.generation, msg.sender, eta);
}
function cancelRevoke(uint8 kind, uint8 system, uint256 index) external onlyGovernor {
bytes32 id = entryId(kind, system, index);
if (pendingRevocation[id] == 0) revert NoProposal();
delete pendingRevocation[id];
pendingCount--;
emit RevokeCancelled(kind, system, index);
}
function executeRevoke(uint8 kind, uint8 system, uint256 index) external {
bytes32 id = entryId(kind, system, index);
uint64 eta = pendingRevocation[id];
if (eta == 0) revert NoProposal();
if (block.timestamp < eta) revert TooEarly(eta);
delete pendingRevocation[id];
pendingCount--;
_entryState[id].revoked = true;
emit EntryRevoked(kind, system, index, _entryState[id].generation);
}
/// @notice Propose the replacement that serves a REVOKED entry's span, after `appendDelay`.
/// For `KIND_ADAPTER`, `verifier` is the new adapter and both vkeys are zero.
function proposeReplacement(
uint8 kind,
uint8 system,
uint256 index,
address verifier,
bytes32 programVKey,
bytes32 leafVKey
) external onlyGovernor {
if (index >= _entryCount(kind, system)) revert KeyIndexOutOfRange(kind, system, index);
_checkReplacement(kind, verifier, programVKey, leafVKey);
bytes32 id = entryId(kind, system, index);
EntryState memory e = _entryState[id];
if (!e.revoked) revert NotRevoked(kind, system, index);
if (e.generation == type(uint8).max) revert GenerationLimit(kind, system, index);
if (pendingReplacement[id].live) revert ProposalPending();
uint64 eta = uint64(block.timestamp + appendDelay);
pendingReplacement[id] = PendingReplacement(Replacement(programVKey, leafVKey, verifier), eta, true);
pendingCount++;
emit ReplacementProposed(kind, system, index, programVKey, leafVKey, verifier, eta);
}
/// @dev The shape a replacement for table `kind` must have. A registry with its own table
/// (`KIND_QUORUM` on Stellar) overrides this for it.
function _checkReplacement(uint8 kind, address verifier, bytes32 programVKey, bytes32 leafVKey)
internal
pure
virtual
{
if (verifier == address(0)) revert ZeroAddress();
if (kind == KIND_ADAPTER) {
if (programVKey != bytes32(0) || leafVKey != bytes32(0)) revert LeafKeyShape(kind);
} else {
if (programVKey == bytes32(0)) revert ZeroVKey();
if ((kind == KIND_LOGSET) != (leafVKey != bytes32(0))) revert LeafKeyShape(kind);
}
}
function cancelReplacement(uint8 kind, uint8 system, uint256 index) external onlyGovernor {
bytes32 id = entryId(kind, system, index);
if (!pendingReplacement[id].live) revert NoProposal();
delete pendingReplacement[id];
pendingCount--;
emit ReplacementCancelled(kind, system, index);
}
/// @notice Anyone may execute a matured replacement. The entry's generation advances, so
/// statements recorded under earlier generations stay void until re-submitted.
function executeReplacement(uint8 kind, uint8 system, uint256 index) external {
bytes32 id = entryId(kind, system, index);
PendingReplacement memory p = pendingReplacement[id];
if (!p.live) revert NoProposal();
if (block.timestamp < p.eta) revert TooEarly(p.eta);
delete pendingReplacement[id];
pendingCount--;
_replacement[id] = p.key;
EntryState storage e = _entryState[id];
e.generation += 1;
e.revoked = false;
emit EntryReplaced(kind, system, index, e.generation, p.key.programVKey, p.key.leafVKey, p.key.verifier);
}
// ------------------------------------------------------------------ guardian
/// @notice Propose a revoke-only guardian; it takes effect after `appendDelay`.
function proposeGuardian(address to) external onlyGovernor {
if (to == address(0)) revert ZeroAddress();
if (pendingGuardian.live) revert ProposalPending();
uint64 eta = uint64(block.timestamp + appendDelay);
pendingGuardian = PendingGuardian(to, eta, true);
pendingCount++;
emit GuardianProposed(to, eta);
}
function cancelGuardian() external onlyGovernor {
PendingGuardian memory p = pendingGuardian;
if (!p.live) revert NoProposal();
delete pendingGuardian;
pendingCount--;
emit GuardianProposalCancelled(p.guardian);
}
function executeGuardian() external {
PendingGuardian memory p = pendingGuardian;
if (!p.live) revert NoProposal();
if (block.timestamp < p.eta) revert TooEarly(p.eta);
delete pendingGuardian;
pendingCount--;
emit GuardianSet(guardian, p.guardian);
guardian = p.guardian;
}
/// @notice Remove the guardian at once (it only ever shrinks what the registry accepts).
function removeGuardian() external onlyGovernor {
emit GuardianSet(guardian, address(0));
guardian = address(0);
}
/// @notice Propose appending `(programVKey, leafVKey, verifier, fromBlock)` to the
/// (kind, system) table. `verifier` is the version-pinned verifier contract for
/// this entry's proofs; a new SP1 version is a new entry with its own verifier.
function proposeKey(
uint8 kind,
uint8 system,
address verifier,
bytes32 programVKey,
bytes32 leafVKey,
uint64 fromBlock
) external onlyGovernor {
if (kind > _maxKind()) revert BadKind(kind);
if (system >= MAX_SYSTEMS) revert BadSystem(system);
if (verifier == address(0)) revert ZeroAddress();
if (programVKey == bytes32(0)) revert ZeroVKey();
if ((kind == KIND_LOGSET) != (leafVKey != bytes32(0))) revert LeafKeyShape(kind);
if (pendingKey[kind][system].live) revert ProposalPending();
uint256 floor = _appendFloor();
if (fromBlock < floor) revert RetroactiveFromBlock(fromBlock, floor);
ProgramKey[] storage ks = _keys[kind][system];
if (ks.length > 0 && fromBlock <= ks[ks.length - 1].fromBlock) {
revert FromBlockNotIncreasing(fromBlock, ks[ks.length - 1].fromBlock);
}
uint64 eta = uint64(block.timestamp + appendDelay);
pendingKey[kind][system] = PendingKey(ProgramKey(programVKey, leafVKey, verifier, fromBlock), eta, true);
pendingCount++;
emit KeyProposed(kind, system, programVKey, leafVKey, verifier, fromBlock, eta);
}
function cancelKey(uint8 kind, uint8 system) external onlyGovernor {
if (!pendingKey[kind][system].live) revert NoProposal();
delete pendingKey[kind][system];
pendingCount--;
emit KeyCancelled(kind, system);
}
/// @notice Anyone may execute a matured proposal.
function executeKey(uint8 kind, uint8 system) external {
PendingKey memory p = pendingKey[kind][system];
if (!p.live) revert NoProposal();
if (block.timestamp < p.eta) revert TooEarly(p.eta);
delete pendingKey[kind][system];
pendingCount--;
_keys[kind][system].push(p.key);
emit KeyAppended(
kind,
system,
_keys[kind][system].length - 1,
p.key.programVKey,
p.key.leafVKey,
p.key.verifier,
p.key.fromBlock
);
}
/// @notice Propose a STRICTER policy (a superset of the current mask) from a future position.
function proposePolicy(uint8 requiredSystems, uint64 fromBlock) external onlyGovernor {
if (pendingPolicy.live) revert ProposalPending();
Policy memory cur = _policies[_policies.length - 1];
if (requiredSystems & cur.requiredSystems != cur.requiredSystems || requiredSystems == cur.requiredSystems) {
revert PolicyNotStricter(cur.requiredSystems, requiredSystems);
}
uint256 floor = _appendFloor();
if (fromBlock < floor) revert RetroactiveFromBlock(fromBlock, floor);
if (fromBlock <= cur.fromBlock) revert FromBlockNotIncreasing(fromBlock, cur.fromBlock);
uint64 eta = uint64(block.timestamp + appendDelay);
pendingPolicy = PendingPolicy(Policy(requiredSystems, fromBlock), eta, true);
pendingCount++;
emit PolicyProposed(requiredSystems, fromBlock, eta);
}
function cancelPolicy() external onlyGovernor {
if (!pendingPolicy.live) revert NoProposal();
delete pendingPolicy;
pendingCount--;
emit PolicyCancelled();
}
/// @notice Executes only if every required system is ready (`_systemReady`), so a policy
/// cannot switch on a system that cannot yet attest.
function executePolicy() external {
PendingPolicy memory p = pendingPolicy;
if (!p.live) revert NoProposal();
if (block.timestamp < p.eta) revert TooEarly(p.eta);
for (uint8 s = 0; s < MAX_SYSTEMS; s++) {
if (p.policy.requiredSystems & (uint8(1) << s) == 0) continue;
if (!_systemReady(s)) revert PolicySystemUnready(s);
}
delete pendingPolicy;
pendingCount--;
_policies.push(p.policy);
emit PolicyAppended(_policies.length - 1, p.policy.requiredSystems, p.policy.fromBlock);
}
/// @notice Propose `to` as the next governor. It takes effect only when `to` calls
/// `acceptGovernor` after `appendDelay`.
function proposeGovernor(address to) external onlyGovernor {
if (to == address(0)) revert ZeroAddress();
if (pendingGovernor != address(0)) revert ProposalPending();
uint64 eta = uint64(block.timestamp + appendDelay);
pendingGovernor = to;
pendingGovernorEta = eta;
pendingCount++;
emit GovernorProposed(governor, to, eta);
}
function cancelGovernor() external onlyGovernor {
address to = pendingGovernor;
if (to == address(0)) revert NoProposal();
pendingGovernor = address(0);
pendingGovernorEta = 0;
pendingCount--;
emit GovernorHandoverCancelled(governor, to);
}
/// @notice The proposed governor takes over, once the delay has passed.
function acceptGovernor() external {
if (msg.sender != pendingGovernor || msg.sender == address(0)) revert NotPendingGovernor();
if (block.timestamp < pendingGovernorEta) revert TooEarly(pendingGovernorEta);
emit GovernorTransferred(governor, msg.sender);
governor = msg.sender;
pendingGovernor = address(0);
pendingGovernorEta = 0;
pendingCount--;
}
/// @notice Freeze the tables forever, and clear the guardian. Refused while any proposal
/// or revocation is pending, so a renounce cannot leave a change behind it.
function renounceGovernor() external onlyGovernor {
if (pendingCount != 0) revert ProposalsPending(pendingCount);
emit GovernorTransferred(governor, address(0));
governor = address(0);
if (guardian != address(0)) {
emit GuardianSet(guardian, address(0));
guardian = address(0);
}
}
}
contracts/src/StellarHeader.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title StellarHeader
/// @notice Binds an XDR `LedgerHeader` to its hash and reads `ledgerSeq` and `closeTime`.
/// @dev Layout (XDR, big-endian): ledgerVersion u32 | previousLedgerHash 32 | scpValue
/// { txSetHash 32 | closeTime u64 | upgrades opaque<128>[<=6] | ext } | txSetResultHash 32 |
/// bucketListHash 32 | ledgerSeq u32 | ... ext is one of: 0 basic; 1 signed; 2 empty tx set
/// (txSetHash 32, previousLedgerHash 32, previousLedgerVersion u32, then the signature); 3 signed
/// with closeTimeMs u64 first; 4 empty tx set with closeTimeMs u64 first. The signature is
/// nodeId 36 + opaque<64>. Arms 3 and 4 are protocol 30's (CAP-88); `closeTime` stays in
/// seconds in every arm. A ledger's hash is `sha256` of these bytes.
library StellarHeader {
error HeaderHashMismatch(bytes32 got, bytes32 want);
error HeaderShape();
uint256 private constant CLOSE_TIME_OFFSET = 68;
uint256 private constant UPGRADES_OFFSET = 76;
function bind(bytes memory h, bytes32 want) internal pure returns (uint32 seq, uint64 closeTime) {
bytes32 got = sha256(h);
if (got != want) revert HeaderHashMismatch(got, want);
closeTime = uint64(_be(h, CLOSE_TIME_OFFSET, 8));
uint256 p = UPGRADES_OFFSET;
uint256 n = _be(h, p, 4);
if (n > 6) revert HeaderShape();
p += 4;
for (uint256 i = 0; i < n; i++) {
uint256 len = _be(h, p, 4);
if (len > 128) revert HeaderShape();
p += 4 + ((len + 3) & ~uint256(3));
}
uint256 ext = _be(h, p, 4);
p += 4;
if (ext > 4) revert HeaderShape();
if (ext >= 3) p += 8; // closeTimeMs
if (ext == 2 || ext == 4) p += 32 + 32 + 4; // the dropped value's txSetHash, previousLedgerHash, version
if (ext != 0) {
if (_be(h, p + 36, 4) != 64) revert HeaderShape();
p += 36 + 4 + 64;
}
seq = uint32(_be(h, p + 64, 4));
}
function _be(bytes memory b, uint256 off, uint256 n) private pure returns (uint256 v) {
if (off + n > b.length) revert HeaderShape();
assembly {
v := shr(sub(256, mul(n, 8)), mload(add(add(b, 32), off)))
}
}
}
contracts/src/erc/ILogSet.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.20;
/// @dev VENDORED VERBATIM from the ERC draft's reference assets —
/// `erc-complete-log-sets/assets/src/ILogSet.sol` of "Verified Complete Log Sets"
/// (Draft, requires: 155, 165, 712, 2935, 4788). Every declaration here is the
/// standard's, byte for byte: the structs, `ILogSetVerifier`, `ILogSetRegistry` and the
/// `LogSetHashing` library. Nothing in this file may be edited to suit a verifier — a
/// change here is a change to the ERC, and belongs in the draft first.
///
/// Willow's registries (`LogSetVerifierV2`, `LogSetVerifierL2`, `StellarLogSetVerifier`)
/// use only `LogSetHashing.statementHash`; the rest of the library is carried so that
/// consumers and tests compute the standard's hashes from the source the ERC publishes.
///
/// Test vectors for every hash below are in the draft's Test Cases section, reproduced by
/// `assets/test/Vectors.t.sol` and, against this copy, by `contracts/test/ErcConformance.t.sol`.
/// @notice A log filter with the semantics of `eth_getLogs`.
/// Every list is an OR-list; an empty list matches anything.
/// Each list MUST be sorted ascending (as unsigned integers) with no duplicates.
struct LogFilter {
address[] addresses;
bytes32[] topics0;
bytes32[] topics1;
bytes32[] topics2;
bytes32[] topics3;
}
/// @notice The claim a complete-log-set proof establishes: the logs emitted in blocks
/// `startBlock..endBlock` (inclusive) of chain `chainId` that match the filter
/// committed by `filterHash` are exactly the `logCount` logs committed by
/// `logSetRoot`, in canonical order, with nothing omitted.
struct LogSetStatement {
uint256 chainId;
uint64 startBlock;
uint64 endBlock;
bytes32 startParentHash;
bytes32 endBlockHash;
bytes32 filterHash;
bytes32 logSetRoot;
uint64 logCount;
}
/// @notice One log in canonical record form. `logIndex` is the block-wide log index
/// (the `logIndex` field of `eth_getLogs`), `txIndex` the transaction index.
struct LogRecord {
uint32 txIndex;
uint32 logIndex;
address emitter;
bytes32[] topics;
bytes data;
}
/// @notice Verifies a complete-log-set statement against a proof. Proof bytes are opaque
/// to this standard.
interface ILogSetVerifier {
/// @notice Reverts unless `proof` establishes `statement`.
function checkLogSet(LogSetStatement calldata statement, bytes calldata proof) external view;
}
/// @notice A verifier that also records the statements it has accepted. An acceptance stands
/// while none of its grounds (the key the proof was verified under, a settlement record
/// used for anchoring) is withdrawn by its source; `verifiedAt` returns 0 while one is,
/// and the original block again if the source reverses the withdrawal.
interface ILogSetRegistry is ILogSetVerifier {
/// @notice Emitted for every acceptance: when a statement is first accepted, and again each
/// time it is accepted while an earlier acceptance did not stand.
event LogSetVerified(
bytes32 indexed statementHash,
uint256 indexed chainId,
bytes32 indexed filterHash,
uint64 startBlock,
uint64 endBlock,
bytes32 logSetRoot,
uint64 logCount
);
/// @notice Verifies `statement` against `proof` and records an acceptance. Idempotent: while
/// the statement has an acceptance that stands, it returns without verifying.
/// @return statementHash The hash under which the statement is recorded.
function submitLogSet(LogSetStatement calldata statement, bytes calldata proof)
external
returns (bytes32 statementHash);
/// @notice The block number (on this chain) of the statement's latest acceptance while it
/// stands; 0 otherwise, including when the statement was never accepted.
function verifiedAt(bytes32 statementHash) external view returns (uint256);
}
/// @notice The hashing rules of this standard.
library LogSetHashing {
bytes32 internal constant STATEMENT_TYPEHASH = keccak256(
"LogSetStatement(uint256 chainId,uint64 startBlock,uint64 endBlock,bytes32 startParentHash,bytes32 endBlockHash,bytes32 filterHash,bytes32 logSetRoot,uint64 logCount)"
);
bytes32 internal constant FILTER_TYPEHASH = keccak256(
"LogFilter(address[] addresses,bytes32[] topics0,bytes32[] topics1,bytes32[] topics2,bytes32[] topics3)"
);
/// @dev Domain tag of a per-block log-set digest (a Merkle leaf).
bytes32 internal constant BLOCK_TAG = bytes32("COMPLETE_LOG_SET_BLOCK_V1");
/// @dev Domain tag of an interior Merkle node.
bytes32 internal constant NODE_TAG = bytes32("COMPLETE_LOG_SET_NODE_V1");
error FilterNotCanonical();
error TooManyTopics();
error EmptyRange();
/// @notice The identifier of a statement: its EIP-712 `hashStruct`, with no domain separator.
function statementHash(LogSetStatement memory s) internal pure returns (bytes32) {
return keccak256(
abi.encode(
STATEMENT_TYPEHASH,
s.chainId,
s.startBlock,
s.endBlock,
s.startParentHash,
s.endBlockHash,
s.filterHash,
s.logSetRoot,
s.logCount
)
);
}
/// @notice The commitment to a filter: its EIP-712 `hashStruct`. Reverts unless every
/// list is sorted ascending with no duplicates.
function filterHash(LogFilter memory f) internal pure returns (bytes32) {
_requireCanonical(f.addresses);
_requireCanonical(f.topics0);
_requireCanonical(f.topics1);
_requireCanonical(f.topics2);
_requireCanonical(f.topics3);
return keccak256(
abi.encode(
FILTER_TYPEHASH,
keccak256(abi.encodePacked(f.addresses)),
keccak256(abi.encodePacked(f.topics0)),
keccak256(abi.encodePacked(f.topics1)),
keccak256(abi.encodePacked(f.topics2)),
keccak256(abi.encodePacked(f.topics3))
)
);
}
/// @notice Whether `log` matches `f`, with the semantics of `eth_getLogs`.
function matches(LogFilter memory f, LogRecord memory log) internal pure returns (bool) {
if (f.addresses.length != 0 && !_containsAddress(f.addresses, log.emitter)) return false;
if (!_topicMatches(f.topics0, log.topics, 0)) return false;
if (!_topicMatches(f.topics1, log.topics, 1)) return false;
if (!_topicMatches(f.topics2, log.topics, 2)) return false;
if (!_topicMatches(f.topics3, log.topics, 3)) return false;
return true;
}
/// @notice The per-block digest, which is also the block's Merkle leaf. `records` MUST be
/// the matching logs of block `blockNumber` in ascending `logIndex` order.
function blockLogsHash(uint64 blockNumber, LogRecord[] memory records) internal pure returns (bytes32) {
bytes memory preimage = abi.encodePacked(BLOCK_TAG, blockNumber, uint32(records.length));
for (uint256 i = 0; i < records.length; i++) {
LogRecord memory r = records[i];
if (r.topics.length > 4) revert TooManyTopics();
preimage = abi.encodePacked(
preimage,
r.txIndex,
r.logIndex,
r.emitter,
uint8(r.topics.length),
abi.encodePacked(r.topics),
uint32(r.data.length),
r.data
);
}
return keccak256(preimage);
}
/// @notice The digest of a block in which no log matched.
function emptyBlockLogsHash(uint64 blockNumber) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(BLOCK_TAG, blockNumber, uint32(0)));
}
/// @notice An interior node of the log-set tree.
function nodeHash(bytes32 left, bytes32 right) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(NODE_TAG, left, right));
}
/// @notice The log-set root over per-block leaves in ascending block order, one leaf per
/// block of the range. The tree is a complete binary tree over the next power of
/// two, padded on the right with zero-valued leaves.
function logSetRoot(bytes32[] memory leaves) internal pure returns (bytes32) {
uint256 n = leaves.length;
if (n == 0) revert EmptyRange();
uint256 cap = 1;
while (cap < n) cap <<= 1;
bytes32[] memory level = new bytes32[](cap);
for (uint256 i = 0; i < n; i++) level[i] = leaves[i];
while (cap > 1) {
cap >>= 1;
for (uint256 i = 0; i < cap; i++) {
level[i] = nodeHash(level[2 * i], level[2 * i + 1]);
}
}
return level[0];
}
/// @notice Verifies that `leaf` sits at position `index` (0-based, from `startBlock`) of a
/// tree with `leafCount` leaves whose root is `root`, given the sibling path.
function verifyLeaf(bytes32 root, bytes32 leaf, uint256 index, uint256 leafCount, bytes32[] memory siblings)
internal
pure
returns (bool)
{
if (leafCount == 0 || index >= leafCount) return false;
uint256 cap = 1;
uint256 depth = 0;
while (cap < leafCount) {
cap <<= 1;
depth++;
}
if (siblings.length != depth) return false;
bytes32 node = leaf;
for (uint256 i = 0; i < depth; i++) {
node = (index & 1) == 0 ? nodeHash(node, siblings[i]) : nodeHash(siblings[i], node);
index >>= 1;
}
return node == root;
}
function _requireCanonical(address[] memory list) private pure {
for (uint256 i = 1; i < list.length; i++) {
if (uint160(list[i]) <= uint160(list[i - 1])) revert FilterNotCanonical();
}
}
function _requireCanonical(bytes32[] memory list) private pure {
for (uint256 i = 1; i < list.length; i++) {
if (uint256(list[i]) <= uint256(list[i - 1])) revert FilterNotCanonical();
}
}
function _containsAddress(address[] memory list, address a) private pure returns (bool) {
for (uint256 i = 0; i < list.length; i++) {
if (list[i] == a) return true;
}
return false;
}
function _topicMatches(bytes32[] memory allowed, bytes32[] memory topics, uint256 position)
private
pure
returns (bool)
{
if (allowed.length == 0) return true;
if (topics.length <= position) return false;
bytes32 t = topics[position];
for (uint256 i = 0; i < allowed.length; i++) {
if (allowed[i] == t) return true;
}
return false;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"forge-std/=lib/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.