@ocap/tx-protocols 1.31.9 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/esm/execute.d.mts +6 -1
  2. package/esm/execute.mjs +151 -9
  3. package/esm/gas-security-guard.d.mts +19 -1
  4. package/esm/gas-security-guard.mjs +44 -1
  5. package/esm/index.d.mts +8 -2
  6. package/esm/index.mjs +2 -2
  7. package/esm/pipes/ensure-cost.mjs +39 -2
  8. package/esm/pipes/write-ledger.mjs +18 -3
  9. package/esm/protocols/rollup/bridge-create.mjs +8 -3
  10. package/esm/protocols/rollup/bridge-governance-tx-binding.d.mts +7 -0
  11. package/esm/protocols/rollup/bridge-governance-tx-binding.mjs +212 -0
  12. package/esm/protocols/rollup/bridge-governance-vote.d.mts +49 -0
  13. package/esm/protocols/rollup/bridge-governance-vote.mjs +564 -0
  14. package/esm/protocols/rollup/bridge-migrate.mjs +6 -3
  15. package/esm/protocols/rollup/bridge-v2.d.mts +6 -0
  16. package/esm/protocols/rollup/bridge-v2.mjs +5 -0
  17. package/esm/protocols/rollup/update.d.mts +2 -0
  18. package/esm/protocols/rollup/update.mjs +28 -6
  19. package/lib/execute.cjs +151 -9
  20. package/lib/execute.d.cts +6 -1
  21. package/lib/gas-security-guard.cjs +44 -0
  22. package/lib/gas-security-guard.d.cts +19 -1
  23. package/lib/index.cjs +1 -0
  24. package/lib/index.d.cts +8 -2
  25. package/lib/pipes/ensure-cost.cjs +39 -2
  26. package/lib/pipes/write-ledger.cjs +18 -3
  27. package/lib/protocols/rollup/bridge-create.cjs +8 -3
  28. package/lib/protocols/rollup/bridge-governance-tx-binding.cjs +213 -0
  29. package/lib/protocols/rollup/bridge-governance-tx-binding.d.cts +7 -0
  30. package/lib/protocols/rollup/bridge-governance-vote.cjs +573 -0
  31. package/lib/protocols/rollup/bridge-governance-vote.d.cts +49 -0
  32. package/lib/protocols/rollup/bridge-migrate.cjs +6 -3
  33. package/lib/protocols/rollup/bridge-v2.cjs +5 -0
  34. package/lib/protocols/rollup/bridge-v2.d.cts +6 -0
  35. package/lib/protocols/rollup/update.cjs +28 -6
  36. package/lib/protocols/rollup/update.d.cts +2 -0
  37. package/package.json +16 -16
@@ -0,0 +1,564 @@
1
+ import { isV1EvidenceRow, membershipTombstoneKey } from "./bridge-v2.mjs";
2
+ import { verifyOcapProposalTxBinding } from "./bridge-governance-tx-binding.mjs";
3
+ import { MAX_GOV_DOC_JSON_BYTES, assertAllowedKeys, assertPlainObject, assertValidProposalTitle, assertValidRationaleUrl, bridgeGovDocKey, bridgeGovIndexKey, buildCertFromProposal, canonicalJson, checkedBytes32, checkedNonZeroAddress, coerceEvmProposal, coerceOcapProposal, computeBridgeMembershipDigest, computeGovernanceCertDigest, computeOcapProposalId, membershipFromOcapProposal, recoverArcBlockTxEnvelopeSigner, recoverGovernanceCertSigner, recoverOcapMembershipProposalSigner, serializeEvmProposal, serializeOcapProposal, signerManagerFor, toHexDigest, toJsonSafeValue, utf8ByteLength } from "@ocap/mcrypto";
4
+ import { CustomError } from "@ocap/util/lib/error";
5
+ import { account, evidence, rollup } from "@ocap/state";
6
+ import { isSameDid } from "@ocap/util";
7
+
8
+ //#region src/protocols/rollup/bridge-governance-vote.ts
9
+ /**
10
+ * On-chain dual-plane governance proposal & co-signing ledger (`update_rollup` `govProposalVote` branch, #1880 / #1839).
11
+ *
12
+ * Persists proposals and signatures exclusively in the 66-character self-identifying `gi:<63hex>` / `gd:<63hex>`
13
+ * `statedb.evidence` namespace without mutating `BridgeBodyV2` or `bridge.owner`'s OCAP `nonce`.
14
+ */
15
+ const MAX_ACTIVE_DRAFTS_PER_PROPOSER = 2;
16
+ const MAX_SINGLE_SIG_PROPOSALS_PER_PROPOSER = 2;
17
+ const MAX_GOV_INDEX_RING_CAP = 100;
18
+ const MAX_GOV_PROPOSAL_TTL_SEC = 45 * 86400;
19
+ const MAX_GOV_CREATED_AT_SKEW_SEC = 300;
20
+ const GOV_VOTE_PAYLOAD_KEYS = new Set([
21
+ "plane",
22
+ "proposalId",
23
+ "title",
24
+ "rationaleUrl",
25
+ "proposal",
26
+ "vote"
27
+ ]);
28
+ const VOTE_INPUT_KEYS = new Set([
29
+ "signer",
30
+ "role",
31
+ "signature",
32
+ "envelope"
33
+ ]);
34
+ function parseStoredEvidenceObject(row) {
35
+ const raw = row?.data;
36
+ if (typeof raw === "string") try {
37
+ const parsed = JSON.parse(raw);
38
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
39
+ } catch {
40
+ return;
41
+ }
42
+ const val = raw?.value;
43
+ return val && typeof val === "object" && !Array.isArray(val) ? val : void 0;
44
+ }
45
+ function isGovProposalVotePayload(rawData) {
46
+ return Object.prototype.hasOwnProperty.call(rawData, "govProposalVote");
47
+ }
48
+ function invalidTx(msg) {
49
+ throw new CustomError("INVALID_TX", msg);
50
+ }
51
+ function invalidSig(msg) {
52
+ throw new CustomError("INVALID_SIGNATURE", msg);
53
+ }
54
+ function sortVotes(votes) {
55
+ return [...votes].sort((a, b) => {
56
+ const da = BigInt(a.signer);
57
+ const db = BigInt(b.signer);
58
+ return da < db ? -1 : da > db ? 1 : 0;
59
+ });
60
+ }
61
+ async function verifyAndScoreOcapVote(context, proposal, voteRec, envelope, existingVotes, isNewDoc, txSec) {
62
+ const bridgeBody = context.bridgeBody;
63
+ const rollupState = context.rollupState;
64
+ if (bridgeBody.migratedTo !== null) invalidTx("The reserve has migrated: the bridge is frozen");
65
+ const { action } = proposal;
66
+ const allowedWhenClosed = action.kind === "migrate_rollup" && action.migrateKind === "reserve" || action.kind === "update_rollup" && (action.patch.proposeOwner !== void 0 || action.patch.cancelOwnerProposal === true);
67
+ if (bridgeBody.closingAt !== null && !allowedWhenClosed) invalidTx("A closed bridge is frozen for this OCAP governance action");
68
+ const owner = checkedNonZeroAddress(bridgeBody.owner, "bridgeBody.owner");
69
+ let quorumBody = bridgeBody;
70
+ if (action.kind === "migrate_rollup" && action.migrateKind === "reserve") if (action.step === "cancel") {
71
+ if (!bridgeBody.pendingMigration) invalidTx("There is no pending reserve migration to cancel");
72
+ } else {
73
+ if (!rollup.isBridgeFinalAt(bridgeBody, txSec)) invalidTx("The source bridge is not final yet");
74
+ if (action.step === "announce" && bridgeBody.pendingMigration) invalidTx("A reserve migration is already pending");
75
+ if (action.step === "execute") {
76
+ const p = bridgeBody.pendingMigration;
77
+ if (!p) invalidTx("No reserve migration was announced");
78
+ if (rollup.lc(p.to) !== rollup.lc(action.targetBridge)) invalidTx("The target differs from the announced migration");
79
+ }
80
+ const targetRow = await context.statedb.rollup.get(action.targetBridge, context);
81
+ if (!targetRow || !rollup.isBridgeV2(targetRow)) invalidTx("The migration target must be a v2 bridge");
82
+ if (rollup.sameAddress(targetRow.address, rollupState.address)) invalidTx("Can not migrate a reserve to its own bridge");
83
+ const tbody = rollup.getBridgeBody(targetRow);
84
+ if (targetRow.closed || tbody.closingAt !== null) invalidTx("The migration target is closed");
85
+ if (targetRow.tokenAddress !== rollupState.tokenAddress) invalidTx("The migration target bridges a different OCAP token");
86
+ if (tbody.ethChainId !== bridgeBody.ethChainId || rollup.bareEthAddress(targetRow.contractAddress) !== rollup.bareEthAddress(rollupState.contractAddress)) invalidTx("The migration target bridges a different ethereum token");
87
+ if (rollup.toSeconds(targetRow.context?.genesisTime) < bridgeBody.finalAt) invalidTx("The migration target must be created after the source bridge is final");
88
+ quorumBody = tbody;
89
+ }
90
+ const activeEpoch = rollup.activeEpochAt(quorumBody, txSec);
91
+ if (!activeEpoch) invalidTx("The bridge has no active epoch yet");
92
+ const activeValidators = new Set(activeEpoch.validators.map((v) => checkedNonZeroAddress(v, "validator")));
93
+ let signer = "";
94
+ let signature = "";
95
+ let signedDigest = "";
96
+ let publicKeyHex;
97
+ let role = "";
98
+ if (action.kind === "join_rollup" || action.kind === "leave_rollup") {
99
+ if (envelope !== "eip712") invalidTx("BridgeMembership proposals require eip712 envelope");
100
+ const lastEpoch = bridgeBody.epochs[bridgeBody.epochs.length - 1];
101
+ if (!lastEpoch || action.epoch !== BigInt(lastEpoch.epoch + 1)) invalidTx(`${action.kind}.epoch must equal ${lastEpoch ? lastEpoch.epoch + 1 : 2}`);
102
+ signedDigest = toHexDigest(computeBridgeMembershipDigest(membershipFromOcapProposal(proposal)));
103
+ const tombstoneKey = membershipTombstoneKey(rollupState.address, Number(action.epoch), signedDigest);
104
+ const tombstoneRow = await context.statedb.evidence.get(tombstoneKey, context);
105
+ if (tombstoneRow && !isV1EvidenceRow(tombstoneRow)) invalidTx("This membership approval was already used on this chain");
106
+ try {
107
+ const rec = recoverOcapMembershipProposalSigner(proposal, String(voteRec.signature ?? ""));
108
+ signer = rec.signer;
109
+ signature = rec.signature;
110
+ } catch (err) {
111
+ invalidSig(`Invalid BridgeMembership signature: ${err.message}`);
112
+ }
113
+ const isJoiner = action.kind === "join_rollup" && signer === action.validator;
114
+ const isOwner = signer === owner;
115
+ const isVal = activeValidators.has(signer);
116
+ if (!isJoiner && !isOwner && !isVal) invalidSig(`Signer ${signer} is not an authorized membership co-signer on this bridge`);
117
+ if (isNewDoc && isJoiner && !isOwner && !isVal) invalidSig("Only the bridge owner or an active validator may open a join_rollup proposal; the candidate validator may only co-sign an existing proposal");
118
+ role = isJoiner ? "joiner" : isOwner ? "owner" : "validator";
119
+ } else {
120
+ await verifyOcapProposalTxBinding(context, proposal);
121
+ signedDigest = action.challenge;
122
+ const rawExpectedSigner = voteRec.signer !== void 0 ? voteRec.signer : !("signerRoster" in action) && action.txFrom?.startsWith("0x") ? action.txFrom : void 0;
123
+ if (rawExpectedSigner === void 0) invalidTx("govProposalVote.vote.signer is required for ArcBlockTransaction vote");
124
+ const expectedSigner = checkedNonZeroAddress(rawExpectedSigner, "vote.signer");
125
+ try {
126
+ const rec = recoverArcBlockTxEnvelopeSigner({
127
+ chainId: proposal.ocapChainId,
128
+ action: action.kind,
129
+ from: expectedSigner,
130
+ nonce: action.frozenNonce.toString(10),
131
+ challenge: signedDigest
132
+ }, String(voteRec.signature ?? ""), envelope);
133
+ signer = rec.signer;
134
+ signature = rec.signature;
135
+ publicKeyHex = rec.publicKeyHex;
136
+ } catch (err) {
137
+ invalidSig(`Invalid ArcBlockTransaction signature: ${err.message}`);
138
+ }
139
+ if (signer !== expectedSigner) invalidSig(`Recovered signer ${signer} does not match vote.signer ${expectedSigner}`);
140
+ if ("signerRoster" in action && !action.signerRoster.some((e) => e.signer === signer && e.pk === publicKeyHex)) invalidSig(`Signer ${signer} (pk ${publicKeyHex}) is not in proposal signerRoster`);
141
+ if (!("signerRoster" in action) && signer !== action.txFrom) invalidSig(`Single-signer OCAP proposal vote.signer (${signer}) must match proposal.action.txFrom`);
142
+ if (action.kind === "pause_rollup" && action.mode === "lone") {
143
+ if (!bridgeBody.pausers.some((p) => rollup.sameAddress(p, signer))) invalidSig(`Signer ${signer} is not an authorized bridge pauser`);
144
+ if (signer !== owner && !activeValidators.has(signer)) invalidSig("Pauser-only key cannot submit govProposalVote; submit PauseRollupTx directly");
145
+ role = "pauser";
146
+ } else if (action.kind === "migrate_rollup" && action.migrateKind === "reserve" && action.step === "cancel") {
147
+ const isOfficial = !!context.config?.token?.address && isSameDid(rollupState.tokenAddress, context.config.token.address);
148
+ const tokenState = isOfficial ? null : await context.statedb.token.get(rollupState.tokenAddress, context);
149
+ const authority = isOfficial ? context.config?.moderator?.address : tokenState?.issuer;
150
+ if (!authority || !rollup.sameAddress(authority, signer)) invalidSig(`Signer ${signer} is not the token authority`);
151
+ role = "authority";
152
+ } else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) {
153
+ if (signer !== owner) invalidSig("Only the current bridge owner may co-sign cancelOwnerProposal");
154
+ role = "owner";
155
+ } else {
156
+ if (signer !== owner && !activeValidators.has(signer)) invalidSig(`Signer ${signer} is neither the bridge owner nor an active validator`);
157
+ role = signer === owner ? "owner" : "validator";
158
+ }
159
+ }
160
+ if (voteRec.signer !== void 0 && checkedNonZeroAddress(voteRec.signer, "vote.signer") !== signer) invalidSig("vote.signer does not match recovered signature signer");
161
+ if (voteRec.role !== void 0 && voteRec.role !== role) invalidTx(`vote.role must be "${role}" for signer ${signer}`);
162
+ const signerLc = signer.toLowerCase();
163
+ const prev = existingVotes.find((v) => v.signer.toLowerCase() === signerLc);
164
+ const entry = {
165
+ signer,
166
+ role,
167
+ signature,
168
+ envelope,
169
+ isSeed: signer === owner,
170
+ votedAt: prev && prev.signature === signature ? prev.votedAt : txSec,
171
+ ...publicKeyHex ? { publicKeyHex } : {}
172
+ };
173
+ const nextVotes = sortVotes([...existingVotes.filter((v) => v.signer.toLowerCase() !== signerLc), entry]);
174
+ const votedAddrs = new Set(nextVotes.map((v) => v.signer));
175
+ const valCount = [...votedAddrs].filter((a) => activeValidators.has(a)).length;
176
+ let quorumReached = false;
177
+ if (action.kind === "pause_rollup" && action.mode === "lone" || action.kind === "migrate_rollup" && action.migrateKind === "reserve" && action.step === "cancel") quorumReached = nextVotes.length >= 1;
178
+ else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) quorumReached = votedAddrs.has(owner);
179
+ else if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) quorumReached = valCount >= Math.ceil(2 * activeEpoch.validators.length / 3);
180
+ else if (action.kind === "join_rollup") quorumReached = votedAddrs.has(owner) && votedAddrs.has(action.validator) && valCount >= activeEpoch.threshold;
181
+ else quorumReached = votedAddrs.has(owner) && valCount >= activeEpoch.threshold;
182
+ return {
183
+ signer,
184
+ role,
185
+ signature,
186
+ signedDigest,
187
+ publicKeyHex,
188
+ nextVotes,
189
+ quorumReached
190
+ };
191
+ }
192
+ async function planBridgeGovProposalVote(context, rawData) {
193
+ if (Object.keys(rawData).length !== 1) invalidTx("govProposalVote cannot be combined with any rollup patch keys");
194
+ const txSec = context.txSec;
195
+ const bridge = context.itx.rollup;
196
+ const chainId = context.config.chainId;
197
+ const bridgeBody = context.bridgeBody;
198
+ const rollupState = context.rollupState;
199
+ let payload;
200
+ let voteRec;
201
+ let optionalTitle;
202
+ let optionalRationaleUrl;
203
+ try {
204
+ payload = assertPlainObject(rawData.govProposalVote, "govProposalVote");
205
+ assertAllowedKeys(payload, GOV_VOTE_PAYLOAD_KEYS, "govProposalVote");
206
+ voteRec = assertPlainObject(payload.vote, "govProposalVote.vote");
207
+ assertAllowedKeys(voteRec, VOTE_INPUT_KEYS, "govProposalVote.vote");
208
+ if (payload.title !== void 0) optionalTitle = assertValidProposalTitle(payload.title, "govProposalVote.title");
209
+ if (payload.rationaleUrl !== void 0) optionalRationaleUrl = assertValidRationaleUrl(payload.rationaleUrl, "govProposalVote.rationaleUrl");
210
+ } catch (err) {
211
+ invalidTx(err.message);
212
+ }
213
+ const rawProposal = (() => {
214
+ try {
215
+ return assertPlainObject(payload.proposal, "govProposalVote.proposal");
216
+ } catch (err) {
217
+ invalidTx(err.message);
218
+ }
219
+ })();
220
+ const plane = payload.plane ?? rawProposal.plane;
221
+ if (plane !== "ethereum" && plane !== "ocap") invalidTx("govProposalVote.plane must be 'ethereum' or 'ocap'");
222
+ if (rawProposal.plane !== plane) invalidTx("govProposalVote.plane does not match proposal.plane");
223
+ const envelopeRaw = voteRec.envelope ?? "eip712";
224
+ if (envelopeRaw !== "eip712" && envelopeRaw !== "eip191") invalidTx("govProposalVote.vote.envelope must be 'eip712' or 'eip191'");
225
+ const envelope = envelopeRaw;
226
+ let proposalId = "";
227
+ let canonicalProposalStr = "";
228
+ let canonicalProposalObj;
229
+ let actionKind = "";
230
+ let summary = "";
231
+ let expiresAt = 0n;
232
+ let certJson;
233
+ if (plane === "ethereum") {
234
+ if (envelope !== "eip712") invalidTx("Ethereum GovernanceCert votes require eip712 envelope");
235
+ if (bridgeBody.closingAt !== null || rollupState.closed) invalidTx("Ethereum governance proposals cannot be voted on a closed bridge");
236
+ const evmGov = bridgeBody.evmGovernance ?? null;
237
+ if (!evmGov) invalidTx("Bridge has no configured evmGovernance roster");
238
+ const proposal = (() => {
239
+ try {
240
+ return coerceEvmProposal(rawProposal);
241
+ } catch (err) {
242
+ invalidTx(err.message);
243
+ }
244
+ })();
245
+ if (proposal.ocapChainId !== chainId) invalidTx("proposal.ocapChainId does not match this OCAP chain");
246
+ if (proposal.ocapBridge !== bridge) invalidTx("proposal.ocapBridge does not match itx.rollup");
247
+ if (proposal.deployment.chainId !== BigInt(bridgeBody.ethChainId)) invalidTx("proposal.deployment.chainId does not match bridge ethChainId");
248
+ if (proposal.deployment.gateway.toLowerCase() !== bridgeBody.gateway.toLowerCase()) invalidTx("proposal.deployment.gateway does not match bridge gateway");
249
+ const expectedToken = rollup.bareEthAddress(rollupState.contractAddress);
250
+ if (expectedToken && !/^0x0{40}$/.test(expectedToken)) {
251
+ if (proposal.deployment.token === void 0 || proposal.deployment.token.toLowerCase() !== expectedToken) invalidTx("proposal.deployment.token must match bridge contractAddress");
252
+ }
253
+ const expectedVault = rollup.bareEthAddress(rollupState.vaultAddress);
254
+ if (expectedVault && !/^0x0{40}$/.test(expectedVault)) {
255
+ if (proposal.deployment.vault === void 0 || proposal.deployment.vault.toLowerCase() !== expectedVault) invalidTx("proposal.deployment.vault must match bridge vaultAddress");
256
+ }
257
+ if (proposal.deployment.signerManager !== evmGov.signerManager.address) invalidTx("proposal.deployment.signerManager does not match bridge evmGovernance.signerManager.address");
258
+ if (evmGov.vaultSignerManager === null) {
259
+ if (proposal.deployment.vaultSignerManager !== void 0) invalidTx("proposal.deployment.vaultSignerManager must be omitted when bridge vaultSignerManager is null");
260
+ } else if (proposal.deployment.vaultSignerManager !== evmGov.vaultSignerManager.address) invalidTx("proposal.deployment.vaultSignerManager must match bridge evmGovernance.vaultSignerManager.address");
261
+ const valSetLc = proposal.deployment.validatorSet.toLowerCase();
262
+ for (const [label, addr] of [
263
+ ["gateway", proposal.deployment.gateway],
264
+ ["token", proposal.deployment.token],
265
+ ["vault", proposal.deployment.vault],
266
+ ["signerManager", proposal.deployment.signerManager],
267
+ ["vaultSignerManager", proposal.deployment.vaultSignerManager]
268
+ ]) if (addr && valSetLc === addr.toLowerCase()) invalidTx(`proposal.deployment.validatorSet collides with ${label}`);
269
+ const cert = (() => {
270
+ try {
271
+ canonicalProposalStr = serializeEvmProposal(proposal);
272
+ return buildCertFromProposal(proposal);
273
+ } catch (err) {
274
+ invalidTx(err.message);
275
+ }
276
+ })();
277
+ proposalId = cert.proposalHash;
278
+ canonicalProposalObj = toJsonSafeValue(proposal);
279
+ certJson = toJsonSafeValue(cert);
280
+ actionKind = proposal.action.kind;
281
+ summary = proposal.summary;
282
+ expiresAt = proposal.expiresAt;
283
+ if (BigInt(txSec) >= expiresAt) invalidTx("Governance proposal has expired");
284
+ if (payload.proposalId !== void 0) {
285
+ let supplied = "";
286
+ try {
287
+ supplied = checkedBytes32(payload.proposalId, "proposalId");
288
+ } catch (err) {
289
+ invalidTx(err.message);
290
+ }
291
+ if (supplied !== proposalId) invalidTx("govProposalVote.proposalId does not match recomputed proposalHash");
292
+ }
293
+ const indexKey$1 = bridgeGovIndexKey(bridge);
294
+ const docKey$1 = bridgeGovDocKey(bridge, proposalId);
295
+ const [existingDocRow$1, existingIndexRow$1] = await Promise.all([context.statedb.evidence.get(docKey$1, context), context.statedb.evidence.get(indexKey$1, context)]);
296
+ const existingDoc$1 = parseStoredEvidenceObject(existingDocRow$1);
297
+ const existingVotes$1 = Array.isArray(existingDoc$1?.votes) ? existingDoc$1.votes : [];
298
+ let signer = "";
299
+ let signature = "";
300
+ try {
301
+ const rec = recoverGovernanceCertSigner(proposal.deployment, cert, String(voteRec.signature ?? ""));
302
+ signer = rec.signer;
303
+ signature = rec.signature;
304
+ } catch (err) {
305
+ invalidSig(`Invalid GovernanceCert signature: ${err.message}`);
306
+ }
307
+ if (voteRec.signer !== void 0 && checkedNonZeroAddress(voteRec.signer, "vote.signer") !== signer) invalidSig("vote.signer does not match recovered GovernanceCert signer");
308
+ const governingSm = signerManagerFor(proposal.deployment, proposal.target);
309
+ const isVaultSm = evmGov.vaultSignerManager !== null && governingSm === evmGov.vaultSignerManager.address && governingSm !== evmGov.signerManager.address;
310
+ const role = isVaultSm ? "vaultSignerManager" : "signerManager";
311
+ const roster = isVaultSm ? evmGov.vaultSignerManager : evmGov.signerManager;
312
+ if (voteRec.role !== void 0 && voteRec.role !== role) invalidTx(`vote.role must be "${role}"`);
313
+ if (!roster.signers.includes(signer)) invalidSig(`Signer ${signer} is not an active member of ${role}`);
314
+ const signerLc = signer.toLowerCase();
315
+ const prev = existingVotes$1.find((v) => v.signer.toLowerCase() === signerLc);
316
+ const voteEntry = {
317
+ signer,
318
+ role,
319
+ signature,
320
+ envelope,
321
+ isSeed: roster.seeds.includes(signer),
322
+ votedAt: prev && prev.signature === signature ? prev.votedAt : txSec
323
+ };
324
+ const nextVotes = sortVotes([...existingVotes$1.filter((v) => v.signer.toLowerCase() !== signerLc), voteEntry]);
325
+ const activeSet = new Set(nextVotes.filter((v) => v.role === role && roster.signers.includes(v.signer)).map((v) => v.signer));
326
+ const seedCount = roster.seeds.filter((s) => activeSet.has(s)).length;
327
+ const quorumReached = activeSet.size >= roster.threshold && seedCount >= roster.seedThreshold;
328
+ const signedDigest = toHexDigest(computeGovernanceCertDigest(proposal.deployment, cert));
329
+ return finalizeGovVotePlan({
330
+ bridge,
331
+ proposalId,
332
+ signedDigest,
333
+ plane: "ethereum",
334
+ actionKind,
335
+ summary,
336
+ proposalCreatedAt: proposal.createdAt,
337
+ expiresAt,
338
+ optionalTitle,
339
+ optionalRationaleUrl,
340
+ canonicalProposalStr,
341
+ canonicalProposalObj,
342
+ certJson,
343
+ signer,
344
+ nextVotes,
345
+ quorumReached,
346
+ txSec,
347
+ indexKey: indexKey$1,
348
+ docKey: docKey$1,
349
+ existingDocRow: existingDocRow$1,
350
+ existingIndexRow: existingIndexRow$1
351
+ });
352
+ }
353
+ const ocapProposal = (() => {
354
+ try {
355
+ const p = coerceOcapProposal(rawProposal);
356
+ canonicalProposalStr = serializeOcapProposal(p);
357
+ proposalId = computeOcapProposalId(p);
358
+ return p;
359
+ } catch (err) {
360
+ invalidTx(err.message);
361
+ }
362
+ })();
363
+ if (ocapProposal.ocapChainId !== chainId) invalidTx("proposal.ocapChainId does not match this OCAP chain");
364
+ if (ocapProposal.ocapBridge !== bridge) invalidTx("proposal.ocapBridge does not match itx.rollup");
365
+ canonicalProposalObj = toJsonSafeValue(ocapProposal);
366
+ actionKind = ocapProposal.action.kind;
367
+ summary = ocapProposal.summary;
368
+ expiresAt = ocapProposal.expiresAt;
369
+ if (BigInt(txSec) >= expiresAt) invalidTx("Governance proposal has expired");
370
+ if (payload.proposalId !== void 0) {
371
+ let supplied = "";
372
+ try {
373
+ supplied = checkedBytes32(payload.proposalId, "proposalId");
374
+ } catch (err) {
375
+ invalidTx(err.message);
376
+ }
377
+ if (supplied !== proposalId) invalidTx("govProposalVote.proposalId does not match recomputed proposalId");
378
+ }
379
+ const indexKey = bridgeGovIndexKey(bridge);
380
+ const docKey = bridgeGovDocKey(bridge, proposalId);
381
+ const [existingDocRow, existingIndexRow] = await Promise.all([context.statedb.evidence.get(docKey, context), context.statedb.evidence.get(indexKey, context)]);
382
+ const existingDoc = parseStoredEvidenceObject(existingDocRow);
383
+ const existingVotes = Array.isArray(existingDoc?.votes) ? existingDoc.votes : [];
384
+ const ocapScored = await verifyAndScoreOcapVote(context, ocapProposal, voteRec, envelope, existingVotes, !existingDocRow, txSec);
385
+ return finalizeGovVotePlan({
386
+ bridge,
387
+ proposalId,
388
+ signedDigest: ocapScored.signedDigest,
389
+ plane: "ocap",
390
+ actionKind,
391
+ summary,
392
+ proposalCreatedAt: ocapProposal.createdAt,
393
+ expiresAt,
394
+ optionalTitle,
395
+ optionalRationaleUrl,
396
+ canonicalProposalStr,
397
+ canonicalProposalObj,
398
+ signer: ocapScored.signer,
399
+ nextVotes: ocapScored.nextVotes,
400
+ quorumReached: ocapScored.quorumReached,
401
+ txSec,
402
+ indexKey,
403
+ docKey,
404
+ existingDocRow,
405
+ existingIndexRow
406
+ });
407
+ }
408
+ const MAX_EVICTED_OCAP_DIGESTS = 512;
409
+ function pruneGovIndexItems(items, priorEvictedOcapDigests, txSec) {
410
+ const out = [...items];
411
+ const evicted = [...priorEvictedOcapDigests];
412
+ const evictedSet = new Set(evicted.map((d) => d.toLowerCase()));
413
+ const recordEvicted = (victim) => {
414
+ if (victim.plane !== "ocap" || !victim.signedDigest) return;
415
+ const lc = victim.signedDigest.toLowerCase();
416
+ if (!evictedSet.has(lc)) {
417
+ evictedSet.add(lc);
418
+ evicted.push(lc);
419
+ while (evicted.length > MAX_EVICTED_OCAP_DIGESTS) {
420
+ const dropped = evicted.shift();
421
+ if (dropped) evictedSet.delete(dropped);
422
+ }
423
+ }
424
+ };
425
+ const now = BigInt(txSec);
426
+ while (out.length > MAX_GOV_INDEX_RING_CAP) {
427
+ let victimIdx = -1;
428
+ for (let i = out.length - 1; i >= 0; i--) if (BigInt(out[i].expiresAt) <= now) {
429
+ victimIdx = i;
430
+ break;
431
+ }
432
+ if (victimIdx === -1) {
433
+ for (let i = out.length - 1; i >= 0; i--) if (out[i].quorumReached) {
434
+ victimIdx = i;
435
+ break;
436
+ }
437
+ }
438
+ if (victimIdx === -1) invalidTx(`Governance index active draft ring capacity (${MAX_GOV_INDEX_RING_CAP}) full`);
439
+ const [victim] = out.splice(victimIdx, 1);
440
+ if (victim) recordEvicted(victim);
441
+ }
442
+ return {
443
+ nextItems: out,
444
+ evictedOcapDigests: evicted
445
+ };
446
+ }
447
+ function finalizeGovVotePlan(o) {
448
+ const existingDoc = parseStoredEvidenceObject(o.existingDocRow);
449
+ const existingIndex = parseStoredEvidenceObject(o.existingIndexRow);
450
+ if (o.existingIndexRow && (existingIndex?.kind !== "bridge-gov-index" || existingIndex?.bridge !== o.bridge)) invalidTx("Corrupted bridge governance index record");
451
+ if (o.existingDocRow && !existingDoc) invalidTx("Corrupted bridge governance document record");
452
+ const existingItems = Array.isArray(existingIndex?.items) ? existingIndex.items : [];
453
+ const priorEvictedOcapDigests = Array.isArray(existingIndex?.evictedOcapDigests) ? existingIndex.evictedOcapDigests.filter((x) => typeof x === "string" && /^0x[0-9a-fA-F]{64}$/.test(x)).map((x) => x.toLowerCase()) : [];
454
+ let proposer = o.signer;
455
+ let createdAt = o.txSec;
456
+ let finalTitle = o.optionalTitle;
457
+ let finalRationaleUrl = o.optionalRationaleUrl;
458
+ const singleSig = existingDoc ? Boolean(existingDoc.singleSig) : o.quorumReached;
459
+ if (existingDoc) {
460
+ if (existingDoc.kind !== "bridge-gov-doc" || existingDoc.bridge !== o.bridge || existingDoc.proposalId !== o.proposalId || existingDoc.plane !== o.plane || canonicalJson(existingDoc.proposal) !== o.canonicalProposalStr) invalidTx("Existing governance proposal document is immutable");
461
+ if (o.optionalTitle !== void 0 && o.optionalTitle !== existingDoc.title) invalidTx("Existing governance proposal title is immutable");
462
+ if (o.optionalRationaleUrl !== void 0 && o.optionalRationaleUrl !== existingDoc.rationaleUrl) invalidTx("Existing governance proposal rationaleUrl is immutable");
463
+ proposer = existingDoc.proposer;
464
+ createdAt = existingDoc.createdAt;
465
+ finalTitle = existingDoc.title;
466
+ finalRationaleUrl = existingDoc.rationaleUrl;
467
+ } else {
468
+ if (o.proposalCreatedAt > BigInt(o.txSec) + BigInt(MAX_GOV_CREATED_AT_SKEW_SEC)) invalidTx("Governance proposal createdAt cannot be more than 300s in the future");
469
+ if (o.expiresAt > BigInt(o.txSec) + BigInt(MAX_GOV_PROPOSAL_TTL_SEC)) invalidTx("Governance proposal expiresAt exceeds maximum 45-day TTL");
470
+ const signedDigestLc = o.signedDigest.toLowerCase();
471
+ if (existingItems.some((item) => item.signedDigest.toLowerCase() === signedDigestLc && item.proposalId !== o.proposalId) || priorEvictedOcapDigests.includes(signedDigestLc)) invalidTx("Duplicate governance signedDigest already bound to another proposal");
472
+ if (existingItems.filter((item) => item.proposer.toLowerCase() === o.signer.toLowerCase() && (!item.quorumReached || item.singleSig === true) && BigInt(item.expiresAt) > BigInt(o.txSec)).length >= MAX_ACTIVE_DRAFTS_PER_PROPOSER) invalidTx(o.quorumReached ? `Proposer ${o.signer} already has ${MAX_SINGLE_SIG_PROPOSALS_PER_PROPOSER} active single-signer proposals` : `Proposer ${o.signer} already has ${MAX_ACTIVE_DRAFTS_PER_PROPOSER} active un-quorumed drafts`);
473
+ }
474
+ const docValue = {
475
+ kind: "bridge-gov-doc",
476
+ version: 1,
477
+ bridge: o.bridge,
478
+ proposalId: o.proposalId,
479
+ signedDigest: o.signedDigest,
480
+ plane: o.plane,
481
+ actionKind: o.actionKind,
482
+ proposer,
483
+ createdAt,
484
+ updatedAt: o.txSec,
485
+ expiresAt: o.expiresAt.toString(10),
486
+ summary: o.summary,
487
+ ...finalTitle !== void 0 ? { title: finalTitle } : {},
488
+ ...finalRationaleUrl !== void 0 ? { rationaleUrl: finalRationaleUrl } : {},
489
+ ...o.certJson !== void 0 ? { cert: o.certJson } : {},
490
+ quorumReached: o.quorumReached,
491
+ ...singleSig ? { singleSig: true } : {},
492
+ proposal: o.canonicalProposalObj,
493
+ votes: o.nextVotes
494
+ };
495
+ const docJsonStr = JSON.stringify(docValue);
496
+ if (utf8ByteLength(docJsonStr) > MAX_GOV_DOC_JSON_BYTES) invalidTx(`Governance document exceeds ${MAX_GOV_DOC_JSON_BYTES} byte limit`);
497
+ const summaryItem = {
498
+ proposalId: o.proposalId,
499
+ signedDigest: o.signedDigest,
500
+ plane: o.plane,
501
+ actionKind: o.actionKind,
502
+ proposer,
503
+ summary: o.summary,
504
+ ...finalTitle !== void 0 ? { title: finalTitle } : {},
505
+ createdAt,
506
+ updatedAt: o.txSec,
507
+ expiresAt: o.expiresAt.toString(10),
508
+ voteCount: o.nextVotes.length,
509
+ quorumReached: o.quorumReached,
510
+ ...singleSig ? { singleSig: true } : {}
511
+ };
512
+ const { nextItems, evictedOcapDigests } = pruneGovIndexItems(existingDoc ? existingItems.some((i) => i.proposalId === o.proposalId) ? existingItems.map((i) => i.proposalId === o.proposalId ? summaryItem : i) : [summaryItem, ...existingItems] : [summaryItem, ...existingItems.filter((i) => i.proposalId !== o.proposalId)], priorEvictedOcapDigests, o.txSec);
513
+ const createDoc = !o.existingDocRow;
514
+ const createIndex = !o.existingIndexRow;
515
+ return {
516
+ indexKey: o.indexKey,
517
+ docKey: o.docKey,
518
+ createDoc,
519
+ createIndex,
520
+ gasEstimate: {
521
+ create: (createDoc ? 1 : 0) + (createIndex ? 1 : 0),
522
+ update: 1 + (createDoc ? 0 : 1) + (createIndex ? 0 : 1),
523
+ payment: 0
524
+ },
525
+ docData: docJsonStr,
526
+ indexData: JSON.stringify({
527
+ kind: "bridge-gov-index",
528
+ version: 1,
529
+ bridge: o.bridge,
530
+ items: nextItems,
531
+ ...evictedOcapDigests.length > 0 ? { evictedOcapDigests } : {}
532
+ })
533
+ };
534
+ }
535
+ async function commitBridgeGovProposalVote(context, plan) {
536
+ const { tx: tx$1, statedb, senderState, senderUpdates, updateVaults } = context;
537
+ const writeDoc = plan.createDoc ? statedb.evidence.create(plan.docKey, evidence.create({
538
+ hash: plan.docKey,
539
+ data: plan.docData
540
+ }, context), context) : statedb.evidence.update(plan.docKey, evidence.create({
541
+ hash: plan.docKey,
542
+ data: plan.docData
543
+ }, context), context);
544
+ const writeIndex = plan.createIndex ? statedb.evidence.create(plan.indexKey, evidence.create({
545
+ hash: plan.indexKey,
546
+ data: plan.indexData
547
+ }, context), context) : statedb.evidence.update(plan.indexKey, evidence.create({
548
+ hash: plan.indexKey,
549
+ data: plan.indexData
550
+ }, context), context);
551
+ const [newSenderState] = await Promise.all([
552
+ statedb.account.update(senderState.address, account.update(senderState, {
553
+ nonce: tx$1.nonce,
554
+ ...senderUpdates
555
+ }, context), context),
556
+ writeDoc,
557
+ writeIndex
558
+ ]);
559
+ if (updateVaults) await updateVaults();
560
+ context.senderState = newSenderState;
561
+ }
562
+
563
+ //#endregion
564
+ export { MAX_ACTIVE_DRAFTS_PER_PROPOSER, MAX_GOV_CREATED_AT_SKEW_SEC, MAX_GOV_INDEX_RING_CAP, MAX_GOV_PROPOSAL_TTL_SEC, MAX_SINGLE_SIG_PROPOSALS_PER_PROPOSER, commitBridgeGovProposalVote, isGovProposalVotePayload, planBridgeGovProposalVote };
@@ -35,6 +35,7 @@ const migrateSchemaV2 = function MigrateSchemaV2(context, next) {
35
35
  return next();
36
36
  };
37
37
  const TOKEN_AUTHORITY_ERROR = "Only the token authority can cancel a reserve migration";
38
+ const ZERO_ETH_ADDRESS = "0x0000000000000000000000000000000000000000";
38
39
  /** The token authority of #1411: the moderator for the official token, the token issuer otherwise. */
39
40
  function tokenAuthority(context, tokenState) {
40
41
  const { config } = context;
@@ -50,8 +51,10 @@ async function migrateBridgeChecks(context, next) {
50
51
  if (itx.type === "vault") {
51
52
  if (state.closed) throw new CustomError("INVALID_TX", "The rollup is closed");
52
53
  if (!rollup.isBridgePausedAt(state, txSec)) throw new CustomError("INVALID_TX", "The rollup is not paused");
53
- if (!itx.to || !rollup.isValidRollupVaultAddress(itx.to, "EVM")) throw new CustomError("INVALID_TX", "Invalid itx: \"to\" Expected wallet type to be \"ethereum\"");
54
- const same = (a) => rollup.lc(a) === rollup.lc(itx.to);
54
+ if (!itx.to || typeof itx.to !== "string" || itx.to !== itx.to.trim() || !rollup.isValidRollupVaultAddress(itx.to, "EVM")) throw new CustomError("INVALID_TX", "Invalid itx: \"to\" Expected wallet type to be \"ethereum\"");
55
+ const nextVault = rollup.bareEthAddress(itx.to);
56
+ if (nextVault === ZERO_ETH_ADDRESS || nextVault === rollup.bareEthAddress(state.contractAddress) || nextVault === rollup.bareEthAddress(body.gateway)) throw new CustomError("INVALID_TX", "vaultAddress must be a non-zero ethereum address distinct from contractAddress and gateway");
57
+ const same = (a) => rollup.bareEthAddress(a) === nextVault;
55
58
  if (state.vaultAddress && same(state.vaultAddress)) throw new CustomError("INVALID_TX", "can not migrate vault to self");
56
59
  if ((state.vaultHistory || []).some(same)) throw new CustomError("INVALID_TX", "can not migrate vault to history vaults");
57
60
  context.migratePlan = { kind: "vault" };
@@ -84,7 +87,7 @@ async function migrateBridgeChecks(context, next) {
84
87
  if (rollup.sameAddress(target.address, state.address)) throw new CustomError("INVALID_TX", "Can not migrate a reserve to its own bridge");
85
88
  if (target.closed) throw new CustomError("INVALID_TX", "The migration target is closed");
86
89
  if (target.tokenAddress !== state.tokenAddress) throw new CustomError("INVALID_TX", "The migration target bridges a different OCAP token");
87
- if (tbody.ethChainId !== body.ethChainId || rollup.lc(target.contractAddress) !== rollup.lc(state.contractAddress)) throw new CustomError("INVALID_TX", "The migration target bridges a different ethereum token");
90
+ if (tbody.ethChainId !== body.ethChainId || rollup.bareEthAddress(target.contractAddress) !== rollup.bareEthAddress(state.contractAddress)) throw new CustomError("INVALID_TX", "The migration target bridges a different ethereum token");
88
91
  if (rollup.toSeconds(target.context?.genesisTime) < body.finalAt) throw new CustomError("INVALID_TX", "The migration target must be created after the source bridge is final");
89
92
  context.migrateTarget = target;
90
93
  context.migratePlan = { kind: action };
@@ -50,6 +50,12 @@ interface AuthorityRule {
50
50
  owner: 'required' | 'alone' | 'none';
51
51
  /** `threshold`: >= threshold of the active epoch; `twoThirds`: >= ceil(2n/3); `none` */
52
52
  quorum: 'threshold' | 'twoThirds' | 'none';
53
+ /**
54
+ * When true (`evm-governance-sync` Path A and `govProposalVote`), governance authority was verified from EIP-712
55
+ * signatures inside `itx.data`: `tx.from` is a single gas-payer account (`tx.delegator` and outer `tx.signatures`
56
+ * are forbidden) and `context.signers` is set to `[]`.
57
+ */
58
+ externalAuth?: boolean;
53
59
  }
54
60
  /**
55
61
  * Governance authority of a v2 bridge. The signers are `tx.from` plus the signers of `tx.signatures` (their signatures
@@ -126,6 +126,11 @@ const VerifyBridgeAuthority = (rule) => function VerifyBridgeAuthorityPipe(conte
126
126
  if (tx$1.delegator) return next(new CustomError("INVALID_SIGNATURE", "Delegation is not allowed for bridge governance"));
127
127
  const signatures = getListField(context, "tx.signaturesList");
128
128
  if (signatures.some((x) => Boolean(x.delegator))) return next(new CustomError("INVALID_SIGNATURE", "Delegation is not allowed for bridge governance"));
129
+ if (r.externalAuth) {
130
+ if (signatures.length > 0) return next(new CustomError("INVALID_SIGNATURE", "Outer tx.signatures are not allowed when governance proof is carried in itx.data"));
131
+ context.signers = [];
132
+ return next();
133
+ }
129
134
  const signerList = signatures.map((x) => x.signer);
130
135
  if (new Set(signerList.map(rollup.lc)).size !== signerList.length) return next(new CustomError("INVALID_SIGNATURE", "Duplicate signers are not allowed"));
131
136
  const signers = new Set([rollup.lc(tx$1.from), ...signerList.map(rollup.lc)]);
@@ -1,4 +1,5 @@
1
1
  import { BridgeCtxMixin } from "./bridge-v2.mjs";
2
+ import { BridgeGovVotePlan } from "./bridge-governance-vote.mjs";
2
3
  import { Runner } from "@ocap/tx-pipeline";
3
4
  import { rollup } from "@ocap/state";
4
5
  import { IReadyContext, IWithRollup, IWithSender, IWithSigners, TUpdateRollupTx } from "@ocap/types";
@@ -12,6 +13,7 @@ import { IReadyContext, IWithRollup, IWithSender, IWithSigners, TUpdateRollupTx
12
13
  */
13
14
  type Context = IReadyContext<TUpdateRollupTx> & IWithRollup & IWithSender & IWithSigners & BridgeCtxMixin & {
14
15
  bridgePlan?: rollup.BridgePatchPlan;
16
+ govVotePlan?: BridgeGovVotePlan;
15
17
  };
16
18
  declare const runner: Runner<Context>;
17
19
  //#endregion