@ocap/tx-protocols 1.31.9 → 1.32.1
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.
- package/esm/execute.d.mts +6 -1
- package/esm/execute.mjs +151 -9
- package/esm/gas-security-guard.d.mts +19 -1
- package/esm/gas-security-guard.mjs +44 -1
- package/esm/index.d.mts +8 -2
- package/esm/index.mjs +2 -2
- package/esm/pipes/ensure-cost.mjs +39 -2
- package/esm/pipes/write-ledger.mjs +18 -3
- package/esm/protocols/rollup/bridge-create.mjs +10 -4
- package/esm/protocols/rollup/bridge-governance-tx-binding.d.mts +7 -0
- package/esm/protocols/rollup/bridge-governance-tx-binding.mjs +212 -0
- package/esm/protocols/rollup/bridge-governance-vote.d.mts +49 -0
- package/esm/protocols/rollup/bridge-governance-vote.mjs +563 -0
- package/esm/protocols/rollup/bridge-migrate.mjs +9 -9
- package/esm/protocols/rollup/bridge-v2.d.mts +6 -0
- package/esm/protocols/rollup/bridge-v2.mjs +5 -0
- package/esm/protocols/rollup/create.mjs +5 -4
- package/esm/protocols/rollup/token-authority.d.mts +17 -0
- package/esm/protocols/rollup/token-authority.mjs +40 -0
- package/esm/protocols/rollup/update.d.mts +2 -0
- package/esm/protocols/rollup/update.mjs +28 -6
- package/lib/execute.cjs +151 -9
- package/lib/execute.d.cts +6 -1
- package/lib/gas-security-guard.cjs +44 -0
- package/lib/gas-security-guard.d.cts +19 -1
- package/lib/index.cjs +1 -0
- package/lib/index.d.cts +8 -2
- package/lib/pipes/ensure-cost.cjs +39 -2
- package/lib/pipes/write-ledger.cjs +18 -3
- package/lib/protocols/rollup/bridge-create.cjs +10 -4
- package/lib/protocols/rollup/bridge-governance-tx-binding.cjs +213 -0
- package/lib/protocols/rollup/bridge-governance-tx-binding.d.cts +7 -0
- package/lib/protocols/rollup/bridge-governance-vote.cjs +572 -0
- package/lib/protocols/rollup/bridge-governance-vote.d.cts +49 -0
- package/lib/protocols/rollup/bridge-migrate.cjs +9 -9
- package/lib/protocols/rollup/bridge-v2.cjs +5 -0
- package/lib/protocols/rollup/bridge-v2.d.cts +6 -0
- package/lib/protocols/rollup/create.cjs +5 -4
- package/lib/protocols/rollup/token-authority.cjs +42 -0
- package/lib/protocols/rollup/token-authority.d.cts +17 -0
- package/lib/protocols/rollup/update.cjs +28 -6
- package/lib/protocols/rollup/update.d.cts +2 -0
- package/package.json +16 -16
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
import { isV1EvidenceRow, membershipTombstoneKey } from "./bridge-v2.mjs";
|
|
2
|
+
import { isOfficialToken, resolveTokenAuthority } from "./token-authority.mjs";
|
|
3
|
+
import { verifyOcapProposalTxBinding } from "./bridge-governance-tx-binding.mjs";
|
|
4
|
+
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";
|
|
5
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
6
|
+
import { account, evidence, rollup } from "@ocap/state";
|
|
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 tokenState = isOfficialToken(context.config, rollupState.tokenAddress) ? null : await context.statedb.token.get(rollupState.tokenAddress, context);
|
|
148
|
+
const authority = await resolveTokenAuthority(context, rollupState.tokenAddress, tokenState);
|
|
149
|
+
if (!authority || !rollup.sameAddress(authority, signer)) invalidSig(`Signer ${signer} is not the token authority`);
|
|
150
|
+
role = "authority";
|
|
151
|
+
} else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) {
|
|
152
|
+
if (signer !== owner) invalidSig("Only the current bridge owner may co-sign cancelOwnerProposal");
|
|
153
|
+
role = "owner";
|
|
154
|
+
} else {
|
|
155
|
+
if (signer !== owner && !activeValidators.has(signer)) invalidSig(`Signer ${signer} is neither the bridge owner nor an active validator`);
|
|
156
|
+
role = signer === owner ? "owner" : "validator";
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (voteRec.signer !== void 0 && checkedNonZeroAddress(voteRec.signer, "vote.signer") !== signer) invalidSig("vote.signer does not match recovered signature signer");
|
|
160
|
+
if (voteRec.role !== void 0 && voteRec.role !== role) invalidTx(`vote.role must be "${role}" for signer ${signer}`);
|
|
161
|
+
const signerLc = signer.toLowerCase();
|
|
162
|
+
const prev = existingVotes.find((v) => v.signer.toLowerCase() === signerLc);
|
|
163
|
+
const entry = {
|
|
164
|
+
signer,
|
|
165
|
+
role,
|
|
166
|
+
signature,
|
|
167
|
+
envelope,
|
|
168
|
+
isSeed: signer === owner,
|
|
169
|
+
votedAt: prev && prev.signature === signature ? prev.votedAt : txSec,
|
|
170
|
+
...publicKeyHex ? { publicKeyHex } : {}
|
|
171
|
+
};
|
|
172
|
+
const nextVotes = sortVotes([...existingVotes.filter((v) => v.signer.toLowerCase() !== signerLc), entry]);
|
|
173
|
+
const votedAddrs = new Set(nextVotes.map((v) => v.signer));
|
|
174
|
+
const valCount = [...votedAddrs].filter((a) => activeValidators.has(a)).length;
|
|
175
|
+
let quorumReached = false;
|
|
176
|
+
if (action.kind === "pause_rollup" && action.mode === "lone" || action.kind === "migrate_rollup" && action.migrateKind === "reserve" && action.step === "cancel") quorumReached = nextVotes.length >= 1;
|
|
177
|
+
else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) quorumReached = votedAddrs.has(owner);
|
|
178
|
+
else if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) quorumReached = valCount >= Math.ceil(2 * activeEpoch.validators.length / 3);
|
|
179
|
+
else if (action.kind === "join_rollup") quorumReached = votedAddrs.has(owner) && votedAddrs.has(action.validator) && valCount >= activeEpoch.threshold;
|
|
180
|
+
else quorumReached = votedAddrs.has(owner) && valCount >= activeEpoch.threshold;
|
|
181
|
+
return {
|
|
182
|
+
signer,
|
|
183
|
+
role,
|
|
184
|
+
signature,
|
|
185
|
+
signedDigest,
|
|
186
|
+
publicKeyHex,
|
|
187
|
+
nextVotes,
|
|
188
|
+
quorumReached
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
async function planBridgeGovProposalVote(context, rawData) {
|
|
192
|
+
if (Object.keys(rawData).length !== 1) invalidTx("govProposalVote cannot be combined with any rollup patch keys");
|
|
193
|
+
const txSec = context.txSec;
|
|
194
|
+
const bridge = context.itx.rollup;
|
|
195
|
+
const chainId = context.config.chainId;
|
|
196
|
+
const bridgeBody = context.bridgeBody;
|
|
197
|
+
const rollupState = context.rollupState;
|
|
198
|
+
let payload;
|
|
199
|
+
let voteRec;
|
|
200
|
+
let optionalTitle;
|
|
201
|
+
let optionalRationaleUrl;
|
|
202
|
+
try {
|
|
203
|
+
payload = assertPlainObject(rawData.govProposalVote, "govProposalVote");
|
|
204
|
+
assertAllowedKeys(payload, GOV_VOTE_PAYLOAD_KEYS, "govProposalVote");
|
|
205
|
+
voteRec = assertPlainObject(payload.vote, "govProposalVote.vote");
|
|
206
|
+
assertAllowedKeys(voteRec, VOTE_INPUT_KEYS, "govProposalVote.vote");
|
|
207
|
+
if (payload.title !== void 0) optionalTitle = assertValidProposalTitle(payload.title, "govProposalVote.title");
|
|
208
|
+
if (payload.rationaleUrl !== void 0) optionalRationaleUrl = assertValidRationaleUrl(payload.rationaleUrl, "govProposalVote.rationaleUrl");
|
|
209
|
+
} catch (err) {
|
|
210
|
+
invalidTx(err.message);
|
|
211
|
+
}
|
|
212
|
+
const rawProposal = (() => {
|
|
213
|
+
try {
|
|
214
|
+
return assertPlainObject(payload.proposal, "govProposalVote.proposal");
|
|
215
|
+
} catch (err) {
|
|
216
|
+
invalidTx(err.message);
|
|
217
|
+
}
|
|
218
|
+
})();
|
|
219
|
+
const plane = payload.plane ?? rawProposal.plane;
|
|
220
|
+
if (plane !== "ethereum" && plane !== "ocap") invalidTx("govProposalVote.plane must be 'ethereum' or 'ocap'");
|
|
221
|
+
if (rawProposal.plane !== plane) invalidTx("govProposalVote.plane does not match proposal.plane");
|
|
222
|
+
const envelopeRaw = voteRec.envelope ?? "eip712";
|
|
223
|
+
if (envelopeRaw !== "eip712" && envelopeRaw !== "eip191") invalidTx("govProposalVote.vote.envelope must be 'eip712' or 'eip191'");
|
|
224
|
+
const envelope = envelopeRaw;
|
|
225
|
+
let proposalId = "";
|
|
226
|
+
let canonicalProposalStr = "";
|
|
227
|
+
let canonicalProposalObj;
|
|
228
|
+
let actionKind = "";
|
|
229
|
+
let summary = "";
|
|
230
|
+
let expiresAt = 0n;
|
|
231
|
+
let certJson;
|
|
232
|
+
if (plane === "ethereum") {
|
|
233
|
+
if (envelope !== "eip712") invalidTx("Ethereum GovernanceCert votes require eip712 envelope");
|
|
234
|
+
if (bridgeBody.closingAt !== null || rollupState.closed) invalidTx("Ethereum governance proposals cannot be voted on a closed bridge");
|
|
235
|
+
const evmGov = bridgeBody.evmGovernance ?? null;
|
|
236
|
+
if (!evmGov) invalidTx("Bridge has no configured evmGovernance roster");
|
|
237
|
+
const proposal = (() => {
|
|
238
|
+
try {
|
|
239
|
+
return coerceEvmProposal(rawProposal);
|
|
240
|
+
} catch (err) {
|
|
241
|
+
invalidTx(err.message);
|
|
242
|
+
}
|
|
243
|
+
})();
|
|
244
|
+
if (proposal.ocapChainId !== chainId) invalidTx("proposal.ocapChainId does not match this OCAP chain");
|
|
245
|
+
if (proposal.ocapBridge !== bridge) invalidTx("proposal.ocapBridge does not match itx.rollup");
|
|
246
|
+
if (proposal.deployment.chainId !== BigInt(bridgeBody.ethChainId)) invalidTx("proposal.deployment.chainId does not match bridge ethChainId");
|
|
247
|
+
if (proposal.deployment.gateway.toLowerCase() !== bridgeBody.gateway.toLowerCase()) invalidTx("proposal.deployment.gateway does not match bridge gateway");
|
|
248
|
+
const expectedToken = rollup.bareEthAddress(rollupState.contractAddress);
|
|
249
|
+
if (expectedToken && !/^0x0{40}$/.test(expectedToken)) {
|
|
250
|
+
if (proposal.deployment.token === void 0 || proposal.deployment.token.toLowerCase() !== expectedToken) invalidTx("proposal.deployment.token must match bridge contractAddress");
|
|
251
|
+
}
|
|
252
|
+
const expectedVault = rollup.bareEthAddress(rollupState.vaultAddress);
|
|
253
|
+
if (expectedVault && !/^0x0{40}$/.test(expectedVault)) {
|
|
254
|
+
if (proposal.deployment.vault === void 0 || proposal.deployment.vault.toLowerCase() !== expectedVault) invalidTx("proposal.deployment.vault must match bridge vaultAddress");
|
|
255
|
+
}
|
|
256
|
+
if (proposal.deployment.signerManager !== evmGov.signerManager.address) invalidTx("proposal.deployment.signerManager does not match bridge evmGovernance.signerManager.address");
|
|
257
|
+
if (evmGov.vaultSignerManager === null) {
|
|
258
|
+
if (proposal.deployment.vaultSignerManager !== void 0) invalidTx("proposal.deployment.vaultSignerManager must be omitted when bridge vaultSignerManager is null");
|
|
259
|
+
} else if (proposal.deployment.vaultSignerManager !== evmGov.vaultSignerManager.address) invalidTx("proposal.deployment.vaultSignerManager must match bridge evmGovernance.vaultSignerManager.address");
|
|
260
|
+
const valSetLc = proposal.deployment.validatorSet.toLowerCase();
|
|
261
|
+
for (const [label, addr] of [
|
|
262
|
+
["gateway", proposal.deployment.gateway],
|
|
263
|
+
["token", proposal.deployment.token],
|
|
264
|
+
["vault", proposal.deployment.vault],
|
|
265
|
+
["signerManager", proposal.deployment.signerManager],
|
|
266
|
+
["vaultSignerManager", proposal.deployment.vaultSignerManager]
|
|
267
|
+
]) if (addr && valSetLc === addr.toLowerCase()) invalidTx(`proposal.deployment.validatorSet collides with ${label}`);
|
|
268
|
+
const cert = (() => {
|
|
269
|
+
try {
|
|
270
|
+
canonicalProposalStr = serializeEvmProposal(proposal);
|
|
271
|
+
return buildCertFromProposal(proposal);
|
|
272
|
+
} catch (err) {
|
|
273
|
+
invalidTx(err.message);
|
|
274
|
+
}
|
|
275
|
+
})();
|
|
276
|
+
proposalId = cert.proposalHash;
|
|
277
|
+
canonicalProposalObj = toJsonSafeValue(proposal);
|
|
278
|
+
certJson = toJsonSafeValue(cert);
|
|
279
|
+
actionKind = proposal.action.kind;
|
|
280
|
+
summary = proposal.summary;
|
|
281
|
+
expiresAt = proposal.expiresAt;
|
|
282
|
+
if (BigInt(txSec) >= expiresAt) invalidTx("Governance proposal has expired");
|
|
283
|
+
if (payload.proposalId !== void 0) {
|
|
284
|
+
let supplied = "";
|
|
285
|
+
try {
|
|
286
|
+
supplied = checkedBytes32(payload.proposalId, "proposalId");
|
|
287
|
+
} catch (err) {
|
|
288
|
+
invalidTx(err.message);
|
|
289
|
+
}
|
|
290
|
+
if (supplied !== proposalId) invalidTx("govProposalVote.proposalId does not match recomputed proposalHash");
|
|
291
|
+
}
|
|
292
|
+
const indexKey$1 = bridgeGovIndexKey(bridge);
|
|
293
|
+
const docKey$1 = bridgeGovDocKey(bridge, proposalId);
|
|
294
|
+
const [existingDocRow$1, existingIndexRow$1] = await Promise.all([context.statedb.evidence.get(docKey$1, context), context.statedb.evidence.get(indexKey$1, context)]);
|
|
295
|
+
const existingDoc$1 = parseStoredEvidenceObject(existingDocRow$1);
|
|
296
|
+
const existingVotes$1 = Array.isArray(existingDoc$1?.votes) ? existingDoc$1.votes : [];
|
|
297
|
+
let signer = "";
|
|
298
|
+
let signature = "";
|
|
299
|
+
try {
|
|
300
|
+
const rec = recoverGovernanceCertSigner(proposal.deployment, cert, String(voteRec.signature ?? ""));
|
|
301
|
+
signer = rec.signer;
|
|
302
|
+
signature = rec.signature;
|
|
303
|
+
} catch (err) {
|
|
304
|
+
invalidSig(`Invalid GovernanceCert signature: ${err.message}`);
|
|
305
|
+
}
|
|
306
|
+
if (voteRec.signer !== void 0 && checkedNonZeroAddress(voteRec.signer, "vote.signer") !== signer) invalidSig("vote.signer does not match recovered GovernanceCert signer");
|
|
307
|
+
const governingSm = signerManagerFor(proposal.deployment, proposal.target);
|
|
308
|
+
const isVaultSm = evmGov.vaultSignerManager !== null && governingSm === evmGov.vaultSignerManager.address && governingSm !== evmGov.signerManager.address;
|
|
309
|
+
const role = isVaultSm ? "vaultSignerManager" : "signerManager";
|
|
310
|
+
const roster = isVaultSm ? evmGov.vaultSignerManager : evmGov.signerManager;
|
|
311
|
+
if (voteRec.role !== void 0 && voteRec.role !== role) invalidTx(`vote.role must be "${role}"`);
|
|
312
|
+
if (!roster.signers.includes(signer)) invalidSig(`Signer ${signer} is not an active member of ${role}`);
|
|
313
|
+
const signerLc = signer.toLowerCase();
|
|
314
|
+
const prev = existingVotes$1.find((v) => v.signer.toLowerCase() === signerLc);
|
|
315
|
+
const voteEntry = {
|
|
316
|
+
signer,
|
|
317
|
+
role,
|
|
318
|
+
signature,
|
|
319
|
+
envelope,
|
|
320
|
+
isSeed: roster.seeds.includes(signer),
|
|
321
|
+
votedAt: prev && prev.signature === signature ? prev.votedAt : txSec
|
|
322
|
+
};
|
|
323
|
+
const nextVotes = sortVotes([...existingVotes$1.filter((v) => v.signer.toLowerCase() !== signerLc), voteEntry]);
|
|
324
|
+
const activeSet = new Set(nextVotes.filter((v) => v.role === role && roster.signers.includes(v.signer)).map((v) => v.signer));
|
|
325
|
+
const seedCount = roster.seeds.filter((s) => activeSet.has(s)).length;
|
|
326
|
+
const quorumReached = activeSet.size >= roster.threshold && seedCount >= roster.seedThreshold;
|
|
327
|
+
const signedDigest = toHexDigest(computeGovernanceCertDigest(proposal.deployment, cert));
|
|
328
|
+
return finalizeGovVotePlan({
|
|
329
|
+
bridge,
|
|
330
|
+
proposalId,
|
|
331
|
+
signedDigest,
|
|
332
|
+
plane: "ethereum",
|
|
333
|
+
actionKind,
|
|
334
|
+
summary,
|
|
335
|
+
proposalCreatedAt: proposal.createdAt,
|
|
336
|
+
expiresAt,
|
|
337
|
+
optionalTitle,
|
|
338
|
+
optionalRationaleUrl,
|
|
339
|
+
canonicalProposalStr,
|
|
340
|
+
canonicalProposalObj,
|
|
341
|
+
certJson,
|
|
342
|
+
signer,
|
|
343
|
+
nextVotes,
|
|
344
|
+
quorumReached,
|
|
345
|
+
txSec,
|
|
346
|
+
indexKey: indexKey$1,
|
|
347
|
+
docKey: docKey$1,
|
|
348
|
+
existingDocRow: existingDocRow$1,
|
|
349
|
+
existingIndexRow: existingIndexRow$1
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
const ocapProposal = (() => {
|
|
353
|
+
try {
|
|
354
|
+
const p = coerceOcapProposal(rawProposal);
|
|
355
|
+
canonicalProposalStr = serializeOcapProposal(p);
|
|
356
|
+
proposalId = computeOcapProposalId(p);
|
|
357
|
+
return p;
|
|
358
|
+
} catch (err) {
|
|
359
|
+
invalidTx(err.message);
|
|
360
|
+
}
|
|
361
|
+
})();
|
|
362
|
+
if (ocapProposal.ocapChainId !== chainId) invalidTx("proposal.ocapChainId does not match this OCAP chain");
|
|
363
|
+
if (ocapProposal.ocapBridge !== bridge) invalidTx("proposal.ocapBridge does not match itx.rollup");
|
|
364
|
+
canonicalProposalObj = toJsonSafeValue(ocapProposal);
|
|
365
|
+
actionKind = ocapProposal.action.kind;
|
|
366
|
+
summary = ocapProposal.summary;
|
|
367
|
+
expiresAt = ocapProposal.expiresAt;
|
|
368
|
+
if (BigInt(txSec) >= expiresAt) invalidTx("Governance proposal has expired");
|
|
369
|
+
if (payload.proposalId !== void 0) {
|
|
370
|
+
let supplied = "";
|
|
371
|
+
try {
|
|
372
|
+
supplied = checkedBytes32(payload.proposalId, "proposalId");
|
|
373
|
+
} catch (err) {
|
|
374
|
+
invalidTx(err.message);
|
|
375
|
+
}
|
|
376
|
+
if (supplied !== proposalId) invalidTx("govProposalVote.proposalId does not match recomputed proposalId");
|
|
377
|
+
}
|
|
378
|
+
const indexKey = bridgeGovIndexKey(bridge);
|
|
379
|
+
const docKey = bridgeGovDocKey(bridge, proposalId);
|
|
380
|
+
const [existingDocRow, existingIndexRow] = await Promise.all([context.statedb.evidence.get(docKey, context), context.statedb.evidence.get(indexKey, context)]);
|
|
381
|
+
const existingDoc = parseStoredEvidenceObject(existingDocRow);
|
|
382
|
+
const existingVotes = Array.isArray(existingDoc?.votes) ? existingDoc.votes : [];
|
|
383
|
+
const ocapScored = await verifyAndScoreOcapVote(context, ocapProposal, voteRec, envelope, existingVotes, !existingDocRow, txSec);
|
|
384
|
+
return finalizeGovVotePlan({
|
|
385
|
+
bridge,
|
|
386
|
+
proposalId,
|
|
387
|
+
signedDigest: ocapScored.signedDigest,
|
|
388
|
+
plane: "ocap",
|
|
389
|
+
actionKind,
|
|
390
|
+
summary,
|
|
391
|
+
proposalCreatedAt: ocapProposal.createdAt,
|
|
392
|
+
expiresAt,
|
|
393
|
+
optionalTitle,
|
|
394
|
+
optionalRationaleUrl,
|
|
395
|
+
canonicalProposalStr,
|
|
396
|
+
canonicalProposalObj,
|
|
397
|
+
signer: ocapScored.signer,
|
|
398
|
+
nextVotes: ocapScored.nextVotes,
|
|
399
|
+
quorumReached: ocapScored.quorumReached,
|
|
400
|
+
txSec,
|
|
401
|
+
indexKey,
|
|
402
|
+
docKey,
|
|
403
|
+
existingDocRow,
|
|
404
|
+
existingIndexRow
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
const MAX_EVICTED_OCAP_DIGESTS = 512;
|
|
408
|
+
function pruneGovIndexItems(items, priorEvictedOcapDigests, txSec) {
|
|
409
|
+
const out = [...items];
|
|
410
|
+
const evicted = [...priorEvictedOcapDigests];
|
|
411
|
+
const evictedSet = new Set(evicted.map((d) => d.toLowerCase()));
|
|
412
|
+
const recordEvicted = (victim) => {
|
|
413
|
+
if (victim.plane !== "ocap" || !victim.signedDigest) return;
|
|
414
|
+
const lc = victim.signedDigest.toLowerCase();
|
|
415
|
+
if (!evictedSet.has(lc)) {
|
|
416
|
+
evictedSet.add(lc);
|
|
417
|
+
evicted.push(lc);
|
|
418
|
+
while (evicted.length > MAX_EVICTED_OCAP_DIGESTS) {
|
|
419
|
+
const dropped = evicted.shift();
|
|
420
|
+
if (dropped) evictedSet.delete(dropped);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
const now = BigInt(txSec);
|
|
425
|
+
while (out.length > MAX_GOV_INDEX_RING_CAP) {
|
|
426
|
+
let victimIdx = -1;
|
|
427
|
+
for (let i = out.length - 1; i >= 0; i--) if (BigInt(out[i].expiresAt) <= now) {
|
|
428
|
+
victimIdx = i;
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
if (victimIdx === -1) {
|
|
432
|
+
for (let i = out.length - 1; i >= 0; i--) if (out[i].quorumReached) {
|
|
433
|
+
victimIdx = i;
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (victimIdx === -1) invalidTx(`Governance index active draft ring capacity (${MAX_GOV_INDEX_RING_CAP}) full`);
|
|
438
|
+
const [victim] = out.splice(victimIdx, 1);
|
|
439
|
+
if (victim) recordEvicted(victim);
|
|
440
|
+
}
|
|
441
|
+
return {
|
|
442
|
+
nextItems: out,
|
|
443
|
+
evictedOcapDigests: evicted
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
function finalizeGovVotePlan(o) {
|
|
447
|
+
const existingDoc = parseStoredEvidenceObject(o.existingDocRow);
|
|
448
|
+
const existingIndex = parseStoredEvidenceObject(o.existingIndexRow);
|
|
449
|
+
if (o.existingIndexRow && (existingIndex?.kind !== "bridge-gov-index" || existingIndex?.bridge !== o.bridge)) invalidTx("Corrupted bridge governance index record");
|
|
450
|
+
if (o.existingDocRow && !existingDoc) invalidTx("Corrupted bridge governance document record");
|
|
451
|
+
const existingItems = Array.isArray(existingIndex?.items) ? existingIndex.items : [];
|
|
452
|
+
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()) : [];
|
|
453
|
+
let proposer = o.signer;
|
|
454
|
+
let createdAt = o.txSec;
|
|
455
|
+
let finalTitle = o.optionalTitle;
|
|
456
|
+
let finalRationaleUrl = o.optionalRationaleUrl;
|
|
457
|
+
const singleSig = existingDoc ? Boolean(existingDoc.singleSig) : o.quorumReached;
|
|
458
|
+
if (existingDoc) {
|
|
459
|
+
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");
|
|
460
|
+
if (o.optionalTitle !== void 0 && o.optionalTitle !== existingDoc.title) invalidTx("Existing governance proposal title is immutable");
|
|
461
|
+
if (o.optionalRationaleUrl !== void 0 && o.optionalRationaleUrl !== existingDoc.rationaleUrl) invalidTx("Existing governance proposal rationaleUrl is immutable");
|
|
462
|
+
proposer = existingDoc.proposer;
|
|
463
|
+
createdAt = existingDoc.createdAt;
|
|
464
|
+
finalTitle = existingDoc.title;
|
|
465
|
+
finalRationaleUrl = existingDoc.rationaleUrl;
|
|
466
|
+
} else {
|
|
467
|
+
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");
|
|
468
|
+
if (o.expiresAt > BigInt(o.txSec) + BigInt(MAX_GOV_PROPOSAL_TTL_SEC)) invalidTx("Governance proposal expiresAt exceeds maximum 45-day TTL");
|
|
469
|
+
const signedDigestLc = o.signedDigest.toLowerCase();
|
|
470
|
+
if (existingItems.some((item) => item.signedDigest.toLowerCase() === signedDigestLc && item.proposalId !== o.proposalId) || priorEvictedOcapDigests.includes(signedDigestLc)) invalidTx("Duplicate governance signedDigest already bound to another proposal");
|
|
471
|
+
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`);
|
|
472
|
+
}
|
|
473
|
+
const docValue = {
|
|
474
|
+
kind: "bridge-gov-doc",
|
|
475
|
+
version: 1,
|
|
476
|
+
bridge: o.bridge,
|
|
477
|
+
proposalId: o.proposalId,
|
|
478
|
+
signedDigest: o.signedDigest,
|
|
479
|
+
plane: o.plane,
|
|
480
|
+
actionKind: o.actionKind,
|
|
481
|
+
proposer,
|
|
482
|
+
createdAt,
|
|
483
|
+
updatedAt: o.txSec,
|
|
484
|
+
expiresAt: o.expiresAt.toString(10),
|
|
485
|
+
summary: o.summary,
|
|
486
|
+
...finalTitle !== void 0 ? { title: finalTitle } : {},
|
|
487
|
+
...finalRationaleUrl !== void 0 ? { rationaleUrl: finalRationaleUrl } : {},
|
|
488
|
+
...o.certJson !== void 0 ? { cert: o.certJson } : {},
|
|
489
|
+
quorumReached: o.quorumReached,
|
|
490
|
+
...singleSig ? { singleSig: true } : {},
|
|
491
|
+
proposal: o.canonicalProposalObj,
|
|
492
|
+
votes: o.nextVotes
|
|
493
|
+
};
|
|
494
|
+
const docJsonStr = JSON.stringify(docValue);
|
|
495
|
+
if (utf8ByteLength(docJsonStr) > MAX_GOV_DOC_JSON_BYTES) invalidTx(`Governance document exceeds ${MAX_GOV_DOC_JSON_BYTES} byte limit`);
|
|
496
|
+
const summaryItem = {
|
|
497
|
+
proposalId: o.proposalId,
|
|
498
|
+
signedDigest: o.signedDigest,
|
|
499
|
+
plane: o.plane,
|
|
500
|
+
actionKind: o.actionKind,
|
|
501
|
+
proposer,
|
|
502
|
+
summary: o.summary,
|
|
503
|
+
...finalTitle !== void 0 ? { title: finalTitle } : {},
|
|
504
|
+
createdAt,
|
|
505
|
+
updatedAt: o.txSec,
|
|
506
|
+
expiresAt: o.expiresAt.toString(10),
|
|
507
|
+
voteCount: o.nextVotes.length,
|
|
508
|
+
quorumReached: o.quorumReached,
|
|
509
|
+
...singleSig ? { singleSig: true } : {}
|
|
510
|
+
};
|
|
511
|
+
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);
|
|
512
|
+
const createDoc = !o.existingDocRow;
|
|
513
|
+
const createIndex = !o.existingIndexRow;
|
|
514
|
+
return {
|
|
515
|
+
indexKey: o.indexKey,
|
|
516
|
+
docKey: o.docKey,
|
|
517
|
+
createDoc,
|
|
518
|
+
createIndex,
|
|
519
|
+
gasEstimate: {
|
|
520
|
+
create: (createDoc ? 1 : 0) + (createIndex ? 1 : 0),
|
|
521
|
+
update: 1 + (createDoc ? 0 : 1) + (createIndex ? 0 : 1),
|
|
522
|
+
payment: 0
|
|
523
|
+
},
|
|
524
|
+
docData: docJsonStr,
|
|
525
|
+
indexData: JSON.stringify({
|
|
526
|
+
kind: "bridge-gov-index",
|
|
527
|
+
version: 1,
|
|
528
|
+
bridge: o.bridge,
|
|
529
|
+
items: nextItems,
|
|
530
|
+
...evictedOcapDigests.length > 0 ? { evictedOcapDigests } : {}
|
|
531
|
+
})
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
async function commitBridgeGovProposalVote(context, plan) {
|
|
535
|
+
const { tx: tx$1, statedb, senderState, senderUpdates, updateVaults } = context;
|
|
536
|
+
const writeDoc = plan.createDoc ? statedb.evidence.create(plan.docKey, evidence.create({
|
|
537
|
+
hash: plan.docKey,
|
|
538
|
+
data: plan.docData
|
|
539
|
+
}, context), context) : statedb.evidence.update(plan.docKey, evidence.create({
|
|
540
|
+
hash: plan.docKey,
|
|
541
|
+
data: plan.docData
|
|
542
|
+
}, context), context);
|
|
543
|
+
const writeIndex = plan.createIndex ? statedb.evidence.create(plan.indexKey, evidence.create({
|
|
544
|
+
hash: plan.indexKey,
|
|
545
|
+
data: plan.indexData
|
|
546
|
+
}, context), context) : statedb.evidence.update(plan.indexKey, evidence.create({
|
|
547
|
+
hash: plan.indexKey,
|
|
548
|
+
data: plan.indexData
|
|
549
|
+
}, context), context);
|
|
550
|
+
const [newSenderState] = await Promise.all([
|
|
551
|
+
statedb.account.update(senderState.address, account.update(senderState, {
|
|
552
|
+
nonce: tx$1.nonce,
|
|
553
|
+
...senderUpdates
|
|
554
|
+
}, context), context),
|
|
555
|
+
writeDoc,
|
|
556
|
+
writeIndex
|
|
557
|
+
]);
|
|
558
|
+
if (updateVaults) await updateVaults();
|
|
559
|
+
context.senderState = newSenderState;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
//#endregion
|
|
563
|
+
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 };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { VerifyBridgeAuthority, bridgeUpdates, readItxData } from "./bridge-v2.mjs";
|
|
2
|
+
import { resolveTokenAuthority } from "./token-authority.mjs";
|
|
2
3
|
import { CustomError } from "@ocap/util/lib/error";
|
|
3
4
|
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
4
5
|
import { toBridgeReserveAddress } from "@arcblock/did-util";
|
|
@@ -35,11 +36,7 @@ const migrateSchemaV2 = function MigrateSchemaV2(context, next) {
|
|
|
35
36
|
return next();
|
|
36
37
|
};
|
|
37
38
|
const TOKEN_AUTHORITY_ERROR = "Only the token authority can cancel a reserve migration";
|
|
38
|
-
|
|
39
|
-
function tokenAuthority(context, tokenState) {
|
|
40
|
-
const { config } = context;
|
|
41
|
-
return !!config?.token?.address && isSameDid(context.rollupState.tokenAddress, config.token.address) ? config?.moderator?.address : tokenState?.issuer;
|
|
42
|
-
}
|
|
39
|
+
const ZERO_ETH_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
43
40
|
async function migrateBridgeChecks(context, next) {
|
|
44
41
|
if (!context.isBridgeV2) return next();
|
|
45
42
|
const { itx, statedb } = context;
|
|
@@ -50,8 +47,10 @@ async function migrateBridgeChecks(context, next) {
|
|
|
50
47
|
if (itx.type === "vault") {
|
|
51
48
|
if (state.closed) throw new CustomError("INVALID_TX", "The rollup is closed");
|
|
52
49
|
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
|
|
50
|
+
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\"");
|
|
51
|
+
const nextVault = rollup.bareEthAddress(itx.to);
|
|
52
|
+
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");
|
|
53
|
+
const same = (a) => rollup.bareEthAddress(a) === nextVault;
|
|
55
54
|
if (state.vaultAddress && same(state.vaultAddress)) throw new CustomError("INVALID_TX", "can not migrate vault to self");
|
|
56
55
|
if ((state.vaultHistory || []).some(same)) throw new CustomError("INVALID_TX", "can not migrate vault to history vaults");
|
|
57
56
|
context.migratePlan = { kind: "vault" };
|
|
@@ -65,7 +64,8 @@ async function migrateBridgeChecks(context, next) {
|
|
|
65
64
|
].includes(action)) throw new CustomError("INVALID_TX", "itx.data.action must be announce, execute or cancel");
|
|
66
65
|
if (action === "cancel") {
|
|
67
66
|
if (!body.pendingMigration) throw new CustomError("INVALID_TX", "There is no pending reserve migration to cancel");
|
|
68
|
-
|
|
67
|
+
const tokenState = await statedb.token.get(state.tokenAddress, context);
|
|
68
|
+
context.tokenAuthority = await resolveTokenAuthority(context, state.tokenAddress, tokenState);
|
|
69
69
|
context.migratePlan = { kind: "cancel" };
|
|
70
70
|
return next();
|
|
71
71
|
}
|
|
@@ -84,7 +84,7 @@ async function migrateBridgeChecks(context, next) {
|
|
|
84
84
|
if (rollup.sameAddress(target.address, state.address)) throw new CustomError("INVALID_TX", "Can not migrate a reserve to its own bridge");
|
|
85
85
|
if (target.closed) throw new CustomError("INVALID_TX", "The migration target is closed");
|
|
86
86
|
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.
|
|
87
|
+
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
88
|
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
89
|
context.migrateTarget = target;
|
|
90
90
|
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)]);
|
|
@@ -2,6 +2,7 @@ import { decodeAnySafe, getDelegationRequirements } from "../../util.mjs";
|
|
|
2
2
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
3
3
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
4
4
|
import { indexBlocks, isRollupV1Enabled, tokenIndexKey } from "./bridge-v2.mjs";
|
|
5
|
+
import { isOfficialToken, resolveTokenAuthority } from "./token-authority.mjs";
|
|
5
6
|
import { createBridgeStep, verifyBridgeCreate } from "./bridge-create.mjs";
|
|
6
7
|
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
7
8
|
import { CustomError } from "@ocap/util/lib/error";
|
|
@@ -143,12 +144,12 @@ runner.use(pipes.VerifyInfo([{
|
|
|
143
144
|
return isEmpty(ctx.tokenState?.foreignToken) === false;
|
|
144
145
|
}
|
|
145
146
|
}]));
|
|
146
|
-
runner.use((context, next) => {
|
|
147
|
+
runner.use(async (context, next) => {
|
|
147
148
|
const { tx: tx$1, itx, config, tokenState } = context;
|
|
148
|
-
const
|
|
149
|
-
const authority =
|
|
149
|
+
const isOfficial = isOfficialToken(config, itx.tokenAddress);
|
|
150
|
+
const authority = await resolveTokenAuthority(context, itx.tokenAddress, tokenState);
|
|
150
151
|
const creators = [tx$1.from, tx$1.delegator].filter(Boolean);
|
|
151
|
-
if (!authority || !creators.some((x) => isSameDid(x, authority))) return next(new CustomError("FORBIDDEN",
|
|
152
|
+
if (!authority || !creators.some((x) => isSameDid(x, authority))) return next(new CustomError("FORBIDDEN", isOfficial ? "Only the chain moderator can create a rollup for the official token" : "Only the token issuer can create a rollup for the token"));
|
|
152
153
|
return next();
|
|
153
154
|
});
|
|
154
155
|
runner.use(async (context, next) => {
|