@ocap/tx-protocols 1.32.0 → 1.32.2

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.
@@ -1,4 +1,5 @@
1
1
  import { gatewayIndexKey, indexBlocks, indexData, isV1EvidenceRow, membershipDigest, recoverAll, reserveIndexKey, tokenIndexKey, txSecOf, upsertIndexEvidence } from "./bridge-v2.mjs";
2
+ import { resolveTokenAuthority } from "./token-authority.mjs";
2
3
  import { BRIDGE_MEMBERSHIP_ACTION, computeBridgeOwnerAttestationDigest, recoverBridgeSigner } from "@ocap/mcrypto";
3
4
  import { CustomError } from "@ocap/util/lib/error";
4
5
  import { isEthereumDid } from "@arcblock/did";
@@ -27,7 +28,7 @@ async function verifyBridgeCreate(context, next) {
27
28
  const { tx: tx$1, itx, config, tokenState, statedb } = context;
28
29
  const input = context.bridgeInput;
29
30
  const txSec = txSecOf(context);
30
- const authority = !!config?.token?.address && isSameDid(itx.tokenAddress, config.token.address) ? config?.moderator?.address : tokenState?.issuer;
31
+ const authority = await resolveTokenAuthority(context, itx.tokenAddress, tokenState);
31
32
  const owner = [tx$1.from, tx$1.delegator].filter(Boolean).find((x) => isSameDid(x, authority));
32
33
  if (!owner) return next(new CustomError("FORBIDDEN", "Only the token owner can create a bridge for the token"));
33
34
  if (!isEthereumDid(owner)) return next(new CustomError("INVALID_TX", "The bridge owner must use an ethereum compatible address"));
@@ -62,13 +63,21 @@ async function verifyBridgeCreate(context, next) {
62
63
  statedb.evidence.get(tokenKey, context),
63
64
  statedb.evidence.get(reserveKey, context),
64
65
  statedb.account.get(reserve, context),
65
- Promise.all(epoch1.validators.map((a) => statedb.account.get(account.ensureChecksumAddress(a), context)))
66
+ Promise.all(epoch1.validators.map((a) => statedb.account.get(account.ensureChecksumAddress(a), {
67
+ ...context,
68
+ traceMigration: false
69
+ })))
66
70
  ]);
67
71
  if (indexBlocks(gatewayEntry, txSec, "bridge-gateway")) return next(new CustomError("DUPLICATE_ROLLUP", "A bridge that is not final already uses this ethereum gateway"));
68
72
  if (indexBlocks(tokenEntry, txSec, "bridge-token")) return next(new CustomError("DUPLICATE_ROLLUP", "Only 1 bridge that is not final can exist for the token"));
69
73
  if (reserveEntry && !isV1EvidenceRow(reserveEntry) || reserveAccount) return next(new CustomError("DUPLICATE_ROLLUP", "The reserve of this bridge already exists"));
70
74
  const missing = epoch1.validators.find((_, i) => !validatorAccounts[i]);
71
75
  if (missing) return next(new CustomError("INVALID_TX", `Initial validator ${missing} has no account on this chain`));
76
+ const migratedVal = epoch1.validators.find((addr, i) => {
77
+ const acct = validatorAccounts[i];
78
+ return Boolean(acct && (account.isMigrated(acct) || typeof acct.address === "string" && acct.address && !rollup.sameAddress(acct.address, addr)));
79
+ });
80
+ if (migratedVal) return next(new CustomError("INVALID_TX", `Initial validator ${migratedVal} account has been migrated`));
72
81
  let attestationSigner;
73
82
  try {
74
83
  attestationSigner = recoverBridgeSigner(computeBridgeOwnerAttestationDigest({
@@ -202,7 +202,10 @@ async function verifyOcapProposalTxBinding(context, proposal) {
202
202
  if (Object.keys(d).some((k) => k !== "action") || d.action !== action.step) invalidTx("unsignedTxBytesHex migrate_rollup(reserve) step does not match proposal");
203
203
  }
204
204
  } else if (action.kind === "update_rollup") assertUpdatePatchMatches(readItxData(itx), action.patch);
205
- const fromAcct = await context.statedb.account.get(action.txFrom, context);
205
+ const fromAcct = await context.statedb.account.get(action.txFrom, {
206
+ ...context,
207
+ traceMigration: false
208
+ });
206
209
  if (!fromAcct) invalidTx(`Proposal txFrom account ${action.txFrom} does not exist on-chain`);
207
210
  const currentAcctNonce = BigInt(String(fromAcct.nonce ?? 0));
208
211
  if (currentAcctNonce >= action.frozenNonce) invalidTx(`Proposal frozenNonce (${action.frozenNonce.toString(10)}) is already spent on ${action.txFrom} (account.nonce=${currentAcctNonce.toString(10)})`);
@@ -1,9 +1,9 @@
1
1
  import { isV1EvidenceRow, membershipTombstoneKey } from "./bridge-v2.mjs";
2
+ import { isOfficialToken, resolveTokenAuthority } from "./token-authority.mjs";
2
3
  import { verifyOcapProposalTxBinding } from "./bridge-governance-tx-binding.mjs";
3
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";
4
5
  import { CustomError } from "@ocap/util/lib/error";
5
6
  import { account, evidence, rollup } from "@ocap/state";
6
- import { isSameDid } from "@ocap/util";
7
7
 
8
8
  //#region src/protocols/rollup/bridge-governance-vote.ts
9
9
  /**
@@ -115,9 +115,18 @@ async function verifyAndScoreOcapVote(context, proposal, voteRec, envelope, exis
115
115
  const isVal = activeValidators.has(signer);
116
116
  if (!isJoiner && !isOwner && !isVal) invalidSig(`Signer ${signer} is not an authorized membership co-signer on this bridge`);
117
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
+ const isAcctMigratedFor = (acct, expectedAddr) => Boolean(acct && (account.isMigrated(acct) || typeof acct.address === "string" && acct.address && !rollup.sameAddress(acct.address, expectedAddr)));
119
+ if (!isOwner) {
120
+ const signerAcct = await context.statedb.account.get(signer, {
121
+ ...context,
122
+ traceMigration: false
123
+ });
124
+ if (isVal && (!signerAcct || isAcctMigratedFor(signerAcct, signer))) invalidSig(`Validator signer ${signer} account is missing or has been migrated`);
125
+ if (isJoiner && isAcctMigratedFor(signerAcct, signer)) invalidSig(`Candidate validator ${signer} account has been migrated`);
126
+ }
118
127
  role = isJoiner ? "joiner" : isOwner ? "owner" : "validator";
119
128
  } else {
120
- await verifyOcapProposalTxBinding(context, proposal);
129
+ const isAcctMigratedFor = (acct, expectedAddr) => Boolean(acct && (account.isMigrated(acct) || typeof acct.address === "string" && acct.address && !rollup.sameAddress(acct.address, expectedAddr)));
121
130
  signedDigest = action.challenge;
122
131
  const rawExpectedSigner = voteRec.signer !== void 0 ? voteRec.signer : !("signerRoster" in action) && action.txFrom?.startsWith("0x") ? action.txFrom : void 0;
123
132
  if (rawExpectedSigner === void 0) invalidTx("govProposalVote.vote.signer is required for ArcBlockTransaction vote");
@@ -142,20 +151,65 @@ async function verifyAndScoreOcapVote(context, proposal, voteRec, envelope, exis
142
151
  if (action.kind === "pause_rollup" && action.mode === "lone") {
143
152
  if (!bridgeBody.pausers.some((p) => rollup.sameAddress(p, signer))) invalidSig(`Signer ${signer} is not an authorized bridge pauser`);
144
153
  if (signer !== owner && !activeValidators.has(signer)) invalidSig("Pauser-only key cannot submit govProposalVote; submit PauseRollupTx directly");
154
+ if (signer !== owner) {
155
+ const signerAcct = await context.statedb.account.get(signer, {
156
+ ...context,
157
+ traceMigration: false
158
+ });
159
+ if (!signerAcct || isAcctMigratedFor(signerAcct, signer)) invalidSig(`Pauser signer ${signer} account is missing or has been migrated`);
160
+ }
145
161
  role = "pauser";
146
162
  } 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;
163
+ const tokenState = isOfficialToken(context.config, rollupState.tokenAddress) ? null : await context.statedb.token.get(rollupState.tokenAddress, context);
164
+ const authority = await resolveTokenAuthority(context, rollupState.tokenAddress, tokenState);
150
165
  if (!authority || !rollup.sameAddress(authority, signer)) invalidSig(`Signer ${signer} is not the token authority`);
151
166
  role = "authority";
152
167
  } else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) {
153
168
  if (signer !== owner) invalidSig("Only the current bridge owner may co-sign cancelOwnerProposal");
169
+ if ("signerRoster" in action && (action.signerRoster.length !== 1 || action.signerRoster[0]?.signer !== owner)) invalidTx("cancelOwnerProposal signerRoster must contain only the current bridge owner");
154
170
  role = "owner";
155
171
  } else {
156
172
  if (signer !== owner && !activeValidators.has(signer)) invalidSig(`Signer ${signer} is neither the bridge owner nor an active validator`);
173
+ if (signer !== owner) {
174
+ const signerAcct = await context.statedb.account.get(signer, {
175
+ ...context,
176
+ traceMigration: false
177
+ });
178
+ if (!signerAcct || isAcctMigratedFor(signerAcct, signer)) invalidSig(`Validator signer ${signer} account is missing or has been migrated`);
179
+ }
180
+ if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) {
181
+ const candAddr = action.patch.proposeOwner.newOwner;
182
+ const candAcct = await context.statedb.account.get(candAddr, {
183
+ ...context,
184
+ traceMigration: false
185
+ });
186
+ if (!candAcct) invalidTx("The proposed owner has no account on this chain");
187
+ if (isAcctMigratedFor(candAcct, candAddr)) invalidTx("The proposed owner account has been migrated");
188
+ }
189
+ if ("signerRoster" in action) {
190
+ const rosterAddrs = new Set(action.signerRoster.map((e) => e.signer));
191
+ for (const rAddr of rosterAddrs) {
192
+ if (rAddr !== owner && !activeValidators.has(rAddr)) invalidTx(`Proposal signerRoster entry ${rAddr} is neither the bridge owner nor an active validator`);
193
+ if (rAddr !== owner) {
194
+ const rAcct = await context.statedb.account.get(rAddr, {
195
+ ...context,
196
+ traceMigration: false
197
+ });
198
+ if (!rAcct || isAcctMigratedFor(rAcct, rAddr)) invalidTx(`Proposal signerRoster validator ${rAddr} account is missing or has been migrated`);
199
+ }
200
+ }
201
+ const rosterValCount = [...rosterAddrs].filter((a) => activeValidators.has(a)).length;
202
+ if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) {
203
+ const need = Math.ceil(2 * activeEpoch.validators.length / 3);
204
+ if (rosterValCount < need) invalidTx(`Proposal signerRoster has ${rosterValCount} active validators; proposeOwner requires ${need}`);
205
+ } else {
206
+ if (!rosterAddrs.has(owner)) invalidTx("Proposal signerRoster must include the bridge owner");
207
+ if (rosterValCount < activeEpoch.threshold) invalidTx(`Proposal signerRoster has ${rosterValCount} active validators; threshold is ${activeEpoch.threshold}`);
208
+ }
209
+ }
157
210
  role = signer === owner ? "owner" : "validator";
158
211
  }
212
+ await verifyOcapProposalTxBinding(context, proposal);
159
213
  }
160
214
  if (voteRec.signer !== void 0 && checkedNonZeroAddress(voteRec.signer, "vote.signer") !== signer) invalidSig("vote.signer does not match recovered signature signer");
161
215
  if (voteRec.role !== void 0 && voteRec.role !== role) invalidTx(`vote.role must be "${role}" for signer ${signer}`);
@@ -171,14 +225,29 @@ async function verifyAndScoreOcapVote(context, proposal, voteRec, envelope, exis
171
225
  ...publicKeyHex ? { publicKeyHex } : {}
172
226
  };
173
227
  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;
228
+ const liveVotedAddrs = /* @__PURE__ */ new Set();
229
+ for (const v of nextVotes) {
230
+ if (v.signer === owner) {
231
+ liveVotedAddrs.add(v.signer);
232
+ continue;
233
+ }
234
+ const vAcct = await context.statedb.account.get(v.signer, {
235
+ ...context,
236
+ traceMigration: false
237
+ });
238
+ const vMigrated = Boolean(vAcct && (account.isMigrated(vAcct) || typeof vAcct.address === "string" && vAcct.address && !rollup.sameAddress(vAcct.address, v.signer)));
239
+ if (action.kind === "join_rollup" && v.signer === action.validator) {
240
+ if (!vMigrated) liveVotedAddrs.add(v.signer);
241
+ } else if (vAcct && !vMigrated) liveVotedAddrs.add(v.signer);
242
+ }
243
+ const valCount = [...liveVotedAddrs].filter((a) => activeValidators.has(a)).length;
244
+ const allRosterCoSignersVoted = !("signerRoster" in action) || action.signerRoster.every((e) => e.signer === action.txFrom || liveVotedAddrs.has(e.signer));
176
245
  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;
246
+ if (action.kind === "pause_rollup" && action.mode === "lone" || action.kind === "migrate_rollup" && action.migrateKind === "reserve" && action.step === "cancel") quorumReached = nextVotes.length >= 1 && allRosterCoSignersVoted;
247
+ else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) quorumReached = liveVotedAddrs.has(owner) && allRosterCoSignersVoted;
248
+ else if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) quorumReached = valCount >= Math.ceil(2 * activeEpoch.validators.length / 3) && allRosterCoSignersVoted;
249
+ else if (action.kind === "join_rollup") quorumReached = liveVotedAddrs.has(owner) && liveVotedAddrs.has(action.validator) && valCount >= activeEpoch.threshold;
250
+ else quorumReached = liveVotedAddrs.has(owner) && valCount >= activeEpoch.threshold && allRosterCoSignersVoted;
182
251
  return {
183
252
  signer,
184
253
  role,
@@ -93,7 +93,18 @@ const membershipChecks = (action) => async function MembershipChecks(context, ne
93
93
  const owner = rollup.lc(body.owner);
94
94
  const quorum = new Set(plan.signingEpoch.validators);
95
95
  const joiner = rollup.lc(data.validator);
96
- for (const address of signers.keys()) if (!(address === owner || quorum.has(address) || action === "join" && address === joiner)) throw new CustomError("INVALID_SIGNATURE", `Signer ${address} is not the owner, a validator or the joiner`);
96
+ for (const address of signers.keys()) {
97
+ if (!(address === owner || quorum.has(address) || action === "join" && address === joiner)) throw new CustomError("INVALID_SIGNATURE", `Signer ${address} is not the owner, a validator or the joiner`);
98
+ if (address !== owner) {
99
+ const signerAcct = await statedb.account.get(account.ensureChecksumAddress(address), {
100
+ ...context,
101
+ traceMigration: false
102
+ });
103
+ const isSignerMigrated = Boolean(signerAcct && (account.isMigrated(signerAcct) || typeof signerAcct.address === "string" && signerAcct.address && !rollup.sameAddress(signerAcct.address, address)));
104
+ if (quorum.has(address) && (!signerAcct || isSignerMigrated)) throw new CustomError("INVALID_SIGNATURE", `Validator signer ${address} account is missing or has been migrated`);
105
+ if (action === "join" && address === joiner && isSignerMigrated) throw new CustomError("INVALID_SIGNATURE", `Joining validator ${address} account has been migrated`);
106
+ }
107
+ }
97
108
  if (!signers.has(owner)) throw new CustomError("INVALID_SIGNATURE", "The bridge owner must sign the membership change");
98
109
  const have = [...signers.keys()].filter((a) => quorum.has(a)).length;
99
110
  if (have < plan.signingEpoch.threshold) throw new CustomError("INVALID_SIGNATURE", `Expect at least ${plan.signingEpoch.threshold} validator signatures of epoch ${plan.signingEpoch.epoch}, got ${have}`);
@@ -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";
@@ -36,11 +37,6 @@ const migrateSchemaV2 = function MigrateSchemaV2(context, next) {
36
37
  };
37
38
  const TOKEN_AUTHORITY_ERROR = "Only the token authority can cancel a reserve migration";
38
39
  const ZERO_ETH_ADDRESS = "0x0000000000000000000000000000000000000000";
39
- /** The token authority of #1411: the moderator for the official token, the token issuer otherwise. */
40
- function tokenAuthority(context, tokenState) {
41
- const { config } = context;
42
- return !!config?.token?.address && isSameDid(context.rollupState.tokenAddress, config.token.address) ? config?.moderator?.address : tokenState?.issuer;
43
- }
44
40
  async function migrateBridgeChecks(context, next) {
45
41
  if (!context.isBridgeV2) return next();
46
42
  const { itx, statedb } = context;
@@ -68,7 +64,8 @@ async function migrateBridgeChecks(context, next) {
68
64
  ].includes(action)) throw new CustomError("INVALID_TX", "itx.data.action must be announce, execute or cancel");
69
65
  if (action === "cancel") {
70
66
  if (!body.pendingMigration) throw new CustomError("INVALID_TX", "There is no pending reserve migration to cancel");
71
- context.tokenAuthority = tokenAuthority(context, await statedb.token.get(state.tokenAddress, context));
67
+ const tokenState = await statedb.token.get(state.tokenAddress, context);
68
+ context.tokenAuthority = await resolveTokenAuthority(context, state.tokenAddress, tokenState);
72
69
  context.migratePlan = { kind: "cancel" };
73
70
  return next();
74
71
  }
@@ -204,8 +204,9 @@ const upsertIndexEvidence = async (statedb, key, data, context) => {
204
204
  };
205
205
  /** Decoded `itx.data.value` as a plain object (v2 governance payloads are JSON objects). */
206
206
  function readItxData(itx) {
207
- const value = decodeAnySafe(itx?.data ?? null)?.value;
208
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new CustomError("INVALID_TX", "Invalid itx: data must be a JSON object for a v2 bridge");
207
+ const decoded = decodeAnySafe(itx?.data ?? null);
208
+ const value = decoded?.value;
209
+ if (!decoded || decoded.type !== "json" || !value || typeof value !== "object" || Array.isArray(value)) throw new CustomError("INVALID_TX", "Invalid itx: data must be a JSON object for a v2 bridge");
209
210
  return value;
210
211
  }
211
212
  /** Digest of the membership struct for `epoch` (validators already sorted ascending by the epoch rules). */
@@ -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 isOfficialToken = !!config?.token?.address && isSameDid(itx.tokenAddress, config.token.address);
149
- const authority = isOfficialToken ? config?.moderator?.address : tokenState?.issuer;
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", isOfficialToken ? "Only the chain moderator can create a rollup for the official token" : "Only the token issuer can create a rollup for the token"));
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) => {
@@ -0,0 +1,20 @@
1
+ //#region src/protocols/rollup/token-authority.d.ts
2
+ type Ctx = any;
3
+ /** Whether `tokenAddress` is the chain's official token. */
4
+ declare const isOfficialToken: (config: Ctx, tokenAddress: string) => boolean;
5
+ /**
6
+ * The configured authority (`config.moderator.address` or `tokenState.issuer`) resolved along the account migration
7
+ * chain to its TERMINAL account (#1795). The configured address stays the old one after `account_migrate`, so only the
8
+ * account it migrated to (transitively) may act; the old address and any intermediate address of the chain are never
9
+ * an authority, and neither are the related addresses of the account.
10
+ *
11
+ * - not migrated: the configured address, unchanged;
12
+ * - no account at all: the configured address, unchanged (an account that does not exist was never migrated);
13
+ * - the chain is broken (cycle, hop cap, or a missing target): no authority, fail closed.
14
+ *
15
+ * Walks `migratedTo[0]` explicitly with `{ traceMigration: false }` so `OverlayStateDB` (`TransactionBlock`) never
16
+ * caches `null` across differing `traceMigration` flags or misses intra-block `account_migrate` writes.
17
+ */
18
+ declare function resolveTokenAuthority(context: Ctx, tokenAddress: string, tokenState?: Ctx): Promise<string | undefined>;
19
+ //#endregion
20
+ export { isOfficialToken, resolveTokenAuthority };
@@ -0,0 +1,55 @@
1
+ import { isSameDid } from "@ocap/util";
2
+
3
+ //#region src/protocols/rollup/token-authority.ts
4
+ /**
5
+ * The token authority of a rollup / bridge (#1411): the chain moderator for the official token, the token issuer for
6
+ * any other token. Shared by create_rollup, the v2 bridge create, and the reserve migration cancel (direct and by
7
+ * governance vote).
8
+ */
9
+ /** Whether `tokenAddress` is the chain's official token. */
10
+ const isOfficialToken = (config, tokenAddress) => !!config?.token?.address && isSameDid(tokenAddress, config.token.address);
11
+ const MAX_MIGRATION_HOPS = 64;
12
+ /**
13
+ * The configured authority (`config.moderator.address` or `tokenState.issuer`) resolved along the account migration
14
+ * chain to its TERMINAL account (#1795). The configured address stays the old one after `account_migrate`, so only the
15
+ * account it migrated to (transitively) may act; the old address and any intermediate address of the chain are never
16
+ * an authority, and neither are the related addresses of the account.
17
+ *
18
+ * - not migrated: the configured address, unchanged;
19
+ * - no account at all: the configured address, unchanged (an account that does not exist was never migrated);
20
+ * - the chain is broken (cycle, hop cap, or a missing target): no authority, fail closed.
21
+ *
22
+ * Walks `migratedTo[0]` explicitly with `{ traceMigration: false }` so `OverlayStateDB` (`TransactionBlock`) never
23
+ * caches `null` across differing `traceMigration` flags or misses intra-block `account_migrate` writes.
24
+ */
25
+ async function resolveTokenAuthority(context, tokenAddress, tokenState) {
26
+ const { config, statedb } = context;
27
+ const configured = isOfficialToken(config, tokenAddress) ? config?.moderator?.address : tokenState?.issuer;
28
+ if (!configured) return void 0;
29
+ const normKey = (addr) => String(addr || "").trim().replace(/^did:abt:/i, "").toLowerCase();
30
+ const visited = /* @__PURE__ */ new Set();
31
+ let current = configured;
32
+ for (let hop = 0; hop <= MAX_MIGRATION_HOPS; hop++) {
33
+ const key = normKey(current);
34
+ if (!key || visited.has(key)) return void 0;
35
+ visited.add(key);
36
+ const acct = await statedb.account.get(current, {
37
+ ...context,
38
+ traceMigration: false
39
+ });
40
+ if (!acct) return hop === 0 ? configured : void 0;
41
+ if (typeof acct.address === "string" && acct.address && !isSameDid(acct.address, current)) return;
42
+ const migratedTo = Array.isArray(acct.migratedTo) ? acct.migratedTo : [];
43
+ if (migratedTo.length === 0) {
44
+ if (hop === 0) return configured;
45
+ return typeof acct.address === "string" && acct.address ? acct.address : current;
46
+ }
47
+ if (hop === MAX_MIGRATION_HOPS) return void 0;
48
+ const next = typeof migratedTo[0] === "string" ? migratedTo[0].trim() : "";
49
+ if (!next) return void 0;
50
+ current = next;
51
+ }
52
+ }
53
+
54
+ //#endregion
55
+ export { isOfficialToken, resolveTokenAuthority };
@@ -90,7 +90,12 @@ runner.use(async (context, next) => {
90
90
  const plan = context.bridgePlan;
91
91
  if (!context.isBridgeV2 || plan?.kind !== "propose-owner") return next();
92
92
  const candidate = plan.body.pendingOwner?.address;
93
- if (!await context.statedb.account.get(candidate, context)) return next(new CustomError("INVALID_TX", "The proposed owner has no account on this chain"));
93
+ const candidateAcct = await context.statedb.account.get(candidate, {
94
+ ...context,
95
+ traceMigration: false
96
+ });
97
+ if (!candidateAcct) return next(new CustomError("INVALID_TX", "The proposed owner has no account on this chain"));
98
+ if (account.isMigrated(candidateAcct) || typeof candidateAcct.address === "string" && candidateAcct.address && !rollup.sameAddress(candidateAcct.address, candidate)) return next(new CustomError("INVALID_TX", "The proposed owner account has been migrated"));
94
99
  return next();
95
100
  });
96
101
  runner.use(ifV1(verify_signers_default({
@@ -1,5 +1,6 @@
1
1
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const require_protocols_rollup_bridge_v2 = require('./bridge-v2.cjs');
3
+ const require_protocols_rollup_token_authority = require('./token-authority.cjs');
3
4
  let _ocap_mcrypto = require("@ocap/mcrypto");
4
5
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
5
6
  let _arcblock_did = require("@arcblock/did");
@@ -29,7 +30,7 @@ async function verifyBridgeCreate(context, next) {
29
30
  const { tx, itx, config, tokenState, statedb } = context;
30
31
  const input = context.bridgeInput;
31
32
  const txSec = require_protocols_rollup_bridge_v2.txSecOf(context);
32
- const authority = !!config?.token?.address && (0, _ocap_util.isSameDid)(itx.tokenAddress, config.token.address) ? config?.moderator?.address : tokenState?.issuer;
33
+ const authority = await require_protocols_rollup_token_authority.resolveTokenAuthority(context, itx.tokenAddress, tokenState);
33
34
  const owner = [tx.from, tx.delegator].filter(Boolean).find((x) => (0, _ocap_util.isSameDid)(x, authority));
34
35
  if (!owner) return next(new _ocap_util_lib_error.CustomError("FORBIDDEN", "Only the token owner can create a bridge for the token"));
35
36
  if (!(0, _arcblock_did.isEthereumDid)(owner)) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", "The bridge owner must use an ethereum compatible address"));
@@ -64,13 +65,21 @@ async function verifyBridgeCreate(context, next) {
64
65
  statedb.evidence.get(tokenKey, context),
65
66
  statedb.evidence.get(reserveKey, context),
66
67
  statedb.account.get(reserve, context),
67
- Promise.all(epoch1.validators.map((a) => statedb.account.get(_ocap_state.account.ensureChecksumAddress(a), context)))
68
+ Promise.all(epoch1.validators.map((a) => statedb.account.get(_ocap_state.account.ensureChecksumAddress(a), {
69
+ ...context,
70
+ traceMigration: false
71
+ })))
68
72
  ]);
69
73
  if (require_protocols_rollup_bridge_v2.indexBlocks(gatewayEntry, txSec, "bridge-gateway")) return next(new _ocap_util_lib_error.CustomError("DUPLICATE_ROLLUP", "A bridge that is not final already uses this ethereum gateway"));
70
74
  if (require_protocols_rollup_bridge_v2.indexBlocks(tokenEntry, txSec, "bridge-token")) return next(new _ocap_util_lib_error.CustomError("DUPLICATE_ROLLUP", "Only 1 bridge that is not final can exist for the token"));
71
75
  if (reserveEntry && !(0, _ocap_tx_pipeline.isV1EvidenceRow)(reserveEntry) || reserveAccount) return next(new _ocap_util_lib_error.CustomError("DUPLICATE_ROLLUP", "The reserve of this bridge already exists"));
72
76
  const missing = epoch1.validators.find((_, i) => !validatorAccounts[i]);
73
77
  if (missing) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", `Initial validator ${missing} has no account on this chain`));
78
+ const migratedVal = epoch1.validators.find((addr, i) => {
79
+ const acct = validatorAccounts[i];
80
+ return Boolean(acct && (_ocap_state.account.isMigrated(acct) || typeof acct.address === "string" && acct.address && !_ocap_state.rollup.sameAddress(acct.address, addr)));
81
+ });
82
+ if (migratedVal) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", `Initial validator ${migratedVal} account has been migrated`));
74
83
  let attestationSigner;
75
84
  try {
76
85
  attestationSigner = (0, _ocap_mcrypto.recoverBridgeSigner)((0, _ocap_mcrypto.computeBridgeOwnerAttestationDigest)({
@@ -203,7 +203,10 @@ async function verifyOcapProposalTxBinding(context, proposal) {
203
203
  if (Object.keys(d).some((k) => k !== "action") || d.action !== action.step) invalidTx("unsignedTxBytesHex migrate_rollup(reserve) step does not match proposal");
204
204
  }
205
205
  } else if (action.kind === "update_rollup") assertUpdatePatchMatches(require_protocols_rollup_bridge_v2.readItxData(itx), action.patch);
206
- const fromAcct = await context.statedb.account.get(action.txFrom, context);
206
+ const fromAcct = await context.statedb.account.get(action.txFrom, {
207
+ ...context,
208
+ traceMigration: false
209
+ });
207
210
  if (!fromAcct) invalidTx(`Proposal txFrom account ${action.txFrom} does not exist on-chain`);
208
211
  const currentAcctNonce = BigInt(String(fromAcct.nonce ?? 0));
209
212
  if (currentAcctNonce >= action.frozenNonce) invalidTx(`Proposal frozenNonce (${action.frozenNonce.toString(10)}) is already spent on ${action.txFrom} (account.nonce=${currentAcctNonce.toString(10)})`);
@@ -1,10 +1,10 @@
1
1
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const require_protocols_rollup_bridge_v2 = require('./bridge-v2.cjs');
3
+ const require_protocols_rollup_token_authority = require('./token-authority.cjs');
3
4
  const require_protocols_rollup_bridge_governance_tx_binding = require('./bridge-governance-tx-binding.cjs');
4
5
  let _ocap_mcrypto = require("@ocap/mcrypto");
5
6
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
7
  let _ocap_state = require("@ocap/state");
7
- let _ocap_util = require("@ocap/util");
8
8
  let _ocap_tx_pipeline = require("@ocap/tx-pipeline");
9
9
 
10
10
  //#region src/protocols/rollup/bridge-governance-vote.ts
@@ -117,9 +117,18 @@ async function verifyAndScoreOcapVote(context, proposal, voteRec, envelope, exis
117
117
  const isVal = activeValidators.has(signer);
118
118
  if (!isJoiner && !isOwner && !isVal) invalidSig(`Signer ${signer} is not an authorized membership co-signer on this bridge`);
119
119
  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");
120
+ const isAcctMigratedFor = (acct, expectedAddr) => Boolean(acct && (_ocap_state.account.isMigrated(acct) || typeof acct.address === "string" && acct.address && !_ocap_state.rollup.sameAddress(acct.address, expectedAddr)));
121
+ if (!isOwner) {
122
+ const signerAcct = await context.statedb.account.get(signer, {
123
+ ...context,
124
+ traceMigration: false
125
+ });
126
+ if (isVal && (!signerAcct || isAcctMigratedFor(signerAcct, signer))) invalidSig(`Validator signer ${signer} account is missing or has been migrated`);
127
+ if (isJoiner && isAcctMigratedFor(signerAcct, signer)) invalidSig(`Candidate validator ${signer} account has been migrated`);
128
+ }
120
129
  role = isJoiner ? "joiner" : isOwner ? "owner" : "validator";
121
130
  } else {
122
- await require_protocols_rollup_bridge_governance_tx_binding.verifyOcapProposalTxBinding(context, proposal);
131
+ const isAcctMigratedFor = (acct, expectedAddr) => Boolean(acct && (_ocap_state.account.isMigrated(acct) || typeof acct.address === "string" && acct.address && !_ocap_state.rollup.sameAddress(acct.address, expectedAddr)));
123
132
  signedDigest = action.challenge;
124
133
  const rawExpectedSigner = voteRec.signer !== void 0 ? voteRec.signer : !("signerRoster" in action) && action.txFrom?.startsWith("0x") ? action.txFrom : void 0;
125
134
  if (rawExpectedSigner === void 0) invalidTx("govProposalVote.vote.signer is required for ArcBlockTransaction vote");
@@ -144,20 +153,65 @@ async function verifyAndScoreOcapVote(context, proposal, voteRec, envelope, exis
144
153
  if (action.kind === "pause_rollup" && action.mode === "lone") {
145
154
  if (!bridgeBody.pausers.some((p) => _ocap_state.rollup.sameAddress(p, signer))) invalidSig(`Signer ${signer} is not an authorized bridge pauser`);
146
155
  if (signer !== owner && !activeValidators.has(signer)) invalidSig("Pauser-only key cannot submit govProposalVote; submit PauseRollupTx directly");
156
+ if (signer !== owner) {
157
+ const signerAcct = await context.statedb.account.get(signer, {
158
+ ...context,
159
+ traceMigration: false
160
+ });
161
+ if (!signerAcct || isAcctMigratedFor(signerAcct, signer)) invalidSig(`Pauser signer ${signer} account is missing or has been migrated`);
162
+ }
147
163
  role = "pauser";
148
164
  } else if (action.kind === "migrate_rollup" && action.migrateKind === "reserve" && action.step === "cancel") {
149
- const isOfficial = !!context.config?.token?.address && (0, _ocap_util.isSameDid)(rollupState.tokenAddress, context.config.token.address);
150
- const tokenState = isOfficial ? null : await context.statedb.token.get(rollupState.tokenAddress, context);
151
- const authority = isOfficial ? context.config?.moderator?.address : tokenState?.issuer;
165
+ const tokenState = require_protocols_rollup_token_authority.isOfficialToken(context.config, rollupState.tokenAddress) ? null : await context.statedb.token.get(rollupState.tokenAddress, context);
166
+ const authority = await require_protocols_rollup_token_authority.resolveTokenAuthority(context, rollupState.tokenAddress, tokenState);
152
167
  if (!authority || !_ocap_state.rollup.sameAddress(authority, signer)) invalidSig(`Signer ${signer} is not the token authority`);
153
168
  role = "authority";
154
169
  } else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) {
155
170
  if (signer !== owner) invalidSig("Only the current bridge owner may co-sign cancelOwnerProposal");
171
+ if ("signerRoster" in action && (action.signerRoster.length !== 1 || action.signerRoster[0]?.signer !== owner)) invalidTx("cancelOwnerProposal signerRoster must contain only the current bridge owner");
156
172
  role = "owner";
157
173
  } else {
158
174
  if (signer !== owner && !activeValidators.has(signer)) invalidSig(`Signer ${signer} is neither the bridge owner nor an active validator`);
175
+ if (signer !== owner) {
176
+ const signerAcct = await context.statedb.account.get(signer, {
177
+ ...context,
178
+ traceMigration: false
179
+ });
180
+ if (!signerAcct || isAcctMigratedFor(signerAcct, signer)) invalidSig(`Validator signer ${signer} account is missing or has been migrated`);
181
+ }
182
+ if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) {
183
+ const candAddr = action.patch.proposeOwner.newOwner;
184
+ const candAcct = await context.statedb.account.get(candAddr, {
185
+ ...context,
186
+ traceMigration: false
187
+ });
188
+ if (!candAcct) invalidTx("The proposed owner has no account on this chain");
189
+ if (isAcctMigratedFor(candAcct, candAddr)) invalidTx("The proposed owner account has been migrated");
190
+ }
191
+ if ("signerRoster" in action) {
192
+ const rosterAddrs = new Set(action.signerRoster.map((e) => e.signer));
193
+ for (const rAddr of rosterAddrs) {
194
+ if (rAddr !== owner && !activeValidators.has(rAddr)) invalidTx(`Proposal signerRoster entry ${rAddr} is neither the bridge owner nor an active validator`);
195
+ if (rAddr !== owner) {
196
+ const rAcct = await context.statedb.account.get(rAddr, {
197
+ ...context,
198
+ traceMigration: false
199
+ });
200
+ if (!rAcct || isAcctMigratedFor(rAcct, rAddr)) invalidTx(`Proposal signerRoster validator ${rAddr} account is missing or has been migrated`);
201
+ }
202
+ }
203
+ const rosterValCount = [...rosterAddrs].filter((a) => activeValidators.has(a)).length;
204
+ if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) {
205
+ const need = Math.ceil(2 * activeEpoch.validators.length / 3);
206
+ if (rosterValCount < need) invalidTx(`Proposal signerRoster has ${rosterValCount} active validators; proposeOwner requires ${need}`);
207
+ } else {
208
+ if (!rosterAddrs.has(owner)) invalidTx("Proposal signerRoster must include the bridge owner");
209
+ if (rosterValCount < activeEpoch.threshold) invalidTx(`Proposal signerRoster has ${rosterValCount} active validators; threshold is ${activeEpoch.threshold}`);
210
+ }
211
+ }
159
212
  role = signer === owner ? "owner" : "validator";
160
213
  }
214
+ await require_protocols_rollup_bridge_governance_tx_binding.verifyOcapProposalTxBinding(context, proposal);
161
215
  }
162
216
  if (voteRec.signer !== void 0 && (0, _ocap_mcrypto.checkedNonZeroAddress)(voteRec.signer, "vote.signer") !== signer) invalidSig("vote.signer does not match recovered signature signer");
163
217
  if (voteRec.role !== void 0 && voteRec.role !== role) invalidTx(`vote.role must be "${role}" for signer ${signer}`);
@@ -173,14 +227,29 @@ async function verifyAndScoreOcapVote(context, proposal, voteRec, envelope, exis
173
227
  ...publicKeyHex ? { publicKeyHex } : {}
174
228
  };
175
229
  const nextVotes = sortVotes([...existingVotes.filter((v) => v.signer.toLowerCase() !== signerLc), entry]);
176
- const votedAddrs = new Set(nextVotes.map((v) => v.signer));
177
- const valCount = [...votedAddrs].filter((a) => activeValidators.has(a)).length;
230
+ const liveVotedAddrs = /* @__PURE__ */ new Set();
231
+ for (const v of nextVotes) {
232
+ if (v.signer === owner) {
233
+ liveVotedAddrs.add(v.signer);
234
+ continue;
235
+ }
236
+ const vAcct = await context.statedb.account.get(v.signer, {
237
+ ...context,
238
+ traceMigration: false
239
+ });
240
+ const vMigrated = Boolean(vAcct && (_ocap_state.account.isMigrated(vAcct) || typeof vAcct.address === "string" && vAcct.address && !_ocap_state.rollup.sameAddress(vAcct.address, v.signer)));
241
+ if (action.kind === "join_rollup" && v.signer === action.validator) {
242
+ if (!vMigrated) liveVotedAddrs.add(v.signer);
243
+ } else if (vAcct && !vMigrated) liveVotedAddrs.add(v.signer);
244
+ }
245
+ const valCount = [...liveVotedAddrs].filter((a) => activeValidators.has(a)).length;
246
+ const allRosterCoSignersVoted = !("signerRoster" in action) || action.signerRoster.every((e) => e.signer === action.txFrom || liveVotedAddrs.has(e.signer));
178
247
  let quorumReached = false;
179
- if (action.kind === "pause_rollup" && action.mode === "lone" || action.kind === "migrate_rollup" && action.migrateKind === "reserve" && action.step === "cancel") quorumReached = nextVotes.length >= 1;
180
- else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) quorumReached = votedAddrs.has(owner);
181
- else if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) quorumReached = valCount >= Math.ceil(2 * activeEpoch.validators.length / 3);
182
- else if (action.kind === "join_rollup") quorumReached = votedAddrs.has(owner) && votedAddrs.has(action.validator) && valCount >= activeEpoch.threshold;
183
- else quorumReached = votedAddrs.has(owner) && valCount >= activeEpoch.threshold;
248
+ if (action.kind === "pause_rollup" && action.mode === "lone" || action.kind === "migrate_rollup" && action.migrateKind === "reserve" && action.step === "cancel") quorumReached = nextVotes.length >= 1 && allRosterCoSignersVoted;
249
+ else if (action.kind === "update_rollup" && action.patch.cancelOwnerProposal === true) quorumReached = liveVotedAddrs.has(owner) && allRosterCoSignersVoted;
250
+ else if (action.kind === "update_rollup" && action.patch.proposeOwner !== void 0) quorumReached = valCount >= Math.ceil(2 * activeEpoch.validators.length / 3) && allRosterCoSignersVoted;
251
+ else if (action.kind === "join_rollup") quorumReached = liveVotedAddrs.has(owner) && liveVotedAddrs.has(action.validator) && valCount >= activeEpoch.threshold;
252
+ else quorumReached = liveVotedAddrs.has(owner) && valCount >= activeEpoch.threshold && allRosterCoSignersVoted;
184
253
  return {
185
254
  signer,
186
255
  role,
@@ -95,7 +95,18 @@ const membershipChecks = (action) => async function MembershipChecks(context, ne
95
95
  const owner = _ocap_state.rollup.lc(body.owner);
96
96
  const quorum = new Set(plan.signingEpoch.validators);
97
97
  const joiner = _ocap_state.rollup.lc(data.validator);
98
- for (const address of signers.keys()) if (!(address === owner || quorum.has(address) || action === "join" && address === joiner)) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Signer ${address} is not the owner, a validator or the joiner`);
98
+ for (const address of signers.keys()) {
99
+ if (!(address === owner || quorum.has(address) || action === "join" && address === joiner)) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Signer ${address} is not the owner, a validator or the joiner`);
100
+ if (address !== owner) {
101
+ const signerAcct = await statedb.account.get(_ocap_state.account.ensureChecksumAddress(address), {
102
+ ...context,
103
+ traceMigration: false
104
+ });
105
+ const isSignerMigrated = Boolean(signerAcct && (_ocap_state.account.isMigrated(signerAcct) || typeof signerAcct.address === "string" && signerAcct.address && !_ocap_state.rollup.sameAddress(signerAcct.address, address)));
106
+ if (quorum.has(address) && (!signerAcct || isSignerMigrated)) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Validator signer ${address} account is missing or has been migrated`);
107
+ if (action === "join" && address === joiner && isSignerMigrated) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Joining validator ${address} account has been migrated`);
108
+ }
109
+ }
99
110
  if (!signers.has(owner)) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", "The bridge owner must sign the membership change");
100
111
  const have = [...signers.keys()].filter((a) => quorum.has(a)).length;
101
112
  if (have < plan.signingEpoch.threshold) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Expect at least ${plan.signingEpoch.threshold} validator signatures of epoch ${plan.signingEpoch.epoch}, got ${have}`);
@@ -1,5 +1,6 @@
1
1
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const require_protocols_rollup_bridge_v2 = require('./bridge-v2.cjs');
3
+ const require_protocols_rollup_token_authority = require('./token-authority.cjs');
3
4
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
4
5
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
5
6
  let _arcblock_did_util = require("@arcblock/did-util");
@@ -37,11 +38,6 @@ const migrateSchemaV2 = function MigrateSchemaV2(context, next) {
37
38
  };
38
39
  const TOKEN_AUTHORITY_ERROR = "Only the token authority can cancel a reserve migration";
39
40
  const ZERO_ETH_ADDRESS = "0x0000000000000000000000000000000000000000";
40
- /** The token authority of #1411: the moderator for the official token, the token issuer otherwise. */
41
- function tokenAuthority(context, tokenState) {
42
- const { config } = context;
43
- return !!config?.token?.address && (0, _ocap_util.isSameDid)(context.rollupState.tokenAddress, config.token.address) ? config?.moderator?.address : tokenState?.issuer;
44
- }
45
41
  async function migrateBridgeChecks(context, next) {
46
42
  if (!context.isBridgeV2) return next();
47
43
  const { itx, statedb } = context;
@@ -69,7 +65,8 @@ async function migrateBridgeChecks(context, next) {
69
65
  ].includes(action)) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "itx.data.action must be announce, execute or cancel");
70
66
  if (action === "cancel") {
71
67
  if (!body.pendingMigration) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "There is no pending reserve migration to cancel");
72
- context.tokenAuthority = tokenAuthority(context, await statedb.token.get(state.tokenAddress, context));
68
+ const tokenState = await statedb.token.get(state.tokenAddress, context);
69
+ context.tokenAuthority = await require_protocols_rollup_token_authority.resolveTokenAuthority(context, state.tokenAddress, tokenState);
73
70
  context.migratePlan = { kind: "cancel" };
74
71
  return next();
75
72
  }
@@ -205,8 +205,9 @@ const upsertIndexEvidence = async (statedb, key, data, context) => {
205
205
  };
206
206
  /** Decoded `itx.data.value` as a plain object (v2 governance payloads are JSON objects). */
207
207
  function readItxData(itx) {
208
- const value = require_util.decodeAnySafe(itx?.data ?? null)?.value;
209
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Invalid itx: data must be a JSON object for a v2 bridge");
208
+ const decoded = require_util.decodeAnySafe(itx?.data ?? null);
209
+ const value = decoded?.value;
210
+ if (!decoded || decoded.type !== "json" || !value || typeof value !== "object" || Array.isArray(value)) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Invalid itx: data must be a JSON object for a v2 bridge");
210
211
  return value;
211
212
  }
212
213
  /** Digest of the membership struct for `epoch` (validators already sorted ascending by the epoch rules). */
@@ -4,6 +4,7 @@ const require_util = require('../../util.cjs');
4
4
  const require_pipes_ensure_cost = require('../../pipes/ensure-cost.cjs');
5
5
  const require_pipes_ensure_gas = require('../../pipes/ensure-gas.cjs');
6
6
  const require_protocols_rollup_bridge_v2 = require('./bridge-v2.cjs');
7
+ const require_protocols_rollup_token_authority = require('./token-authority.cjs');
7
8
  const require_protocols_rollup_bridge_create = require('./bridge-create.cjs');
8
9
  let _ocap_tx_pipeline = require("@ocap/tx-pipeline");
9
10
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
@@ -148,12 +149,12 @@ runner.use(_ocap_tx_pipeline.pipes.VerifyInfo([{
148
149
  return (0, lodash_isEmpty.default)(ctx.tokenState?.foreignToken) === false;
149
150
  }
150
151
  }]));
151
- runner.use((context, next) => {
152
+ runner.use(async (context, next) => {
152
153
  const { tx, itx, config, tokenState } = context;
153
- const isOfficialToken = !!config?.token?.address && (0, _ocap_util.isSameDid)(itx.tokenAddress, config.token.address);
154
- const authority = isOfficialToken ? config?.moderator?.address : tokenState?.issuer;
154
+ const isOfficial = require_protocols_rollup_token_authority.isOfficialToken(config, itx.tokenAddress);
155
+ const authority = await require_protocols_rollup_token_authority.resolveTokenAuthority(context, itx.tokenAddress, tokenState);
155
156
  const creators = [tx.from, tx.delegator].filter(Boolean);
156
- if (!authority || !creators.some((x) => (0, _ocap_util.isSameDid)(x, authority))) return next(new _ocap_util_lib_error.CustomError("FORBIDDEN", isOfficialToken ? "Only the chain moderator can create a rollup for the official token" : "Only the token issuer can create a rollup for the token"));
157
+ if (!authority || !creators.some((x) => (0, _ocap_util.isSameDid)(x, authority))) return next(new _ocap_util_lib_error.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"));
157
158
  return next();
158
159
  });
159
160
  runner.use(async (context, next) => {
@@ -0,0 +1,57 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ let _ocap_util = require("@ocap/util");
3
+
4
+ //#region src/protocols/rollup/token-authority.ts
5
+ /**
6
+ * The token authority of a rollup / bridge (#1411): the chain moderator for the official token, the token issuer for
7
+ * any other token. Shared by create_rollup, the v2 bridge create, and the reserve migration cancel (direct and by
8
+ * governance vote).
9
+ */
10
+ /** Whether `tokenAddress` is the chain's official token. */
11
+ const isOfficialToken = (config, tokenAddress) => !!config?.token?.address && (0, _ocap_util.isSameDid)(tokenAddress, config.token.address);
12
+ const MAX_MIGRATION_HOPS = 64;
13
+ /**
14
+ * The configured authority (`config.moderator.address` or `tokenState.issuer`) resolved along the account migration
15
+ * chain to its TERMINAL account (#1795). The configured address stays the old one after `account_migrate`, so only the
16
+ * account it migrated to (transitively) may act; the old address and any intermediate address of the chain are never
17
+ * an authority, and neither are the related addresses of the account.
18
+ *
19
+ * - not migrated: the configured address, unchanged;
20
+ * - no account at all: the configured address, unchanged (an account that does not exist was never migrated);
21
+ * - the chain is broken (cycle, hop cap, or a missing target): no authority, fail closed.
22
+ *
23
+ * Walks `migratedTo[0]` explicitly with `{ traceMigration: false }` so `OverlayStateDB` (`TransactionBlock`) never
24
+ * caches `null` across differing `traceMigration` flags or misses intra-block `account_migrate` writes.
25
+ */
26
+ async function resolveTokenAuthority(context, tokenAddress, tokenState) {
27
+ const { config, statedb } = context;
28
+ const configured = isOfficialToken(config, tokenAddress) ? config?.moderator?.address : tokenState?.issuer;
29
+ if (!configured) return void 0;
30
+ const normKey = (addr) => String(addr || "").trim().replace(/^did:abt:/i, "").toLowerCase();
31
+ const visited = /* @__PURE__ */ new Set();
32
+ let current = configured;
33
+ for (let hop = 0; hop <= MAX_MIGRATION_HOPS; hop++) {
34
+ const key = normKey(current);
35
+ if (!key || visited.has(key)) return void 0;
36
+ visited.add(key);
37
+ const acct = await statedb.account.get(current, {
38
+ ...context,
39
+ traceMigration: false
40
+ });
41
+ if (!acct) return hop === 0 ? configured : void 0;
42
+ if (typeof acct.address === "string" && acct.address && !(0, _ocap_util.isSameDid)(acct.address, current)) return;
43
+ const migratedTo = Array.isArray(acct.migratedTo) ? acct.migratedTo : [];
44
+ if (migratedTo.length === 0) {
45
+ if (hop === 0) return configured;
46
+ return typeof acct.address === "string" && acct.address ? acct.address : current;
47
+ }
48
+ if (hop === MAX_MIGRATION_HOPS) return void 0;
49
+ const next = typeof migratedTo[0] === "string" ? migratedTo[0].trim() : "";
50
+ if (!next) return void 0;
51
+ current = next;
52
+ }
53
+ }
54
+
55
+ //#endregion
56
+ exports.isOfficialToken = isOfficialToken;
57
+ exports.resolveTokenAuthority = resolveTokenAuthority;
@@ -0,0 +1,20 @@
1
+ //#region src/protocols/rollup/token-authority.d.ts
2
+ type Ctx = any;
3
+ /** Whether `tokenAddress` is the chain's official token. */
4
+ declare const isOfficialToken: (config: Ctx, tokenAddress: string) => boolean;
5
+ /**
6
+ * The configured authority (`config.moderator.address` or `tokenState.issuer`) resolved along the account migration
7
+ * chain to its TERMINAL account (#1795). The configured address stays the old one after `account_migrate`, so only the
8
+ * account it migrated to (transitively) may act; the old address and any intermediate address of the chain are never
9
+ * an authority, and neither are the related addresses of the account.
10
+ *
11
+ * - not migrated: the configured address, unchanged;
12
+ * - no account at all: the configured address, unchanged (an account that does not exist was never migrated);
13
+ * - the chain is broken (cycle, hop cap, or a missing target): no authority, fail closed.
14
+ *
15
+ * Walks `migratedTo[0]` explicitly with `{ traceMigration: false }` so `OverlayStateDB` (`TransactionBlock`) never
16
+ * caches `null` across differing `traceMigration` flags or misses intra-block `account_migrate` writes.
17
+ */
18
+ declare function resolveTokenAuthority(context: Ctx, tokenAddress: string, tokenState?: Ctx): Promise<string | undefined>;
19
+ //#endregion
20
+ export { isOfficialToken, resolveTokenAuthority };
@@ -93,7 +93,12 @@ runner.use(async (context, next) => {
93
93
  const plan = context.bridgePlan;
94
94
  if (!context.isBridgeV2 || plan?.kind !== "propose-owner") return next();
95
95
  const candidate = plan.body.pendingOwner?.address;
96
- if (!await context.statedb.account.get(candidate, context)) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", "The proposed owner has no account on this chain"));
96
+ const candidateAcct = await context.statedb.account.get(candidate, {
97
+ ...context,
98
+ traceMigration: false
99
+ });
100
+ if (!candidateAcct) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", "The proposed owner has no account on this chain"));
101
+ if (_ocap_state.account.isMigrated(candidateAcct) || typeof candidateAcct.address === "string" && candidateAcct.address && !_ocap_state.rollup.sameAddress(candidateAcct.address, candidate)) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", "The proposed owner account has been migrated"));
97
102
  return next();
98
103
  });
99
104
  runner.use(require_protocols_rollup_bridge_v2.ifV1(require_protocols_rollup_pipes_verify_signers.default({
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.32.0",
6
+ "version": "1.32.2",
7
7
  "description": "Predefined tx pipeline sets to execute certain type of transactions",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -46,22 +46,22 @@
46
46
  "author": "wangshijun <wangshijun2010@gmail.com> (http://github.com/wangshijun)",
47
47
  "license": "MIT",
48
48
  "dependencies": {
49
- "@arcblock/did": "1.32.0",
50
- "@arcblock/did-util": "1.32.0",
51
- "@arcblock/jwt": "1.32.0",
52
- "@arcblock/validator": "1.32.0",
53
- "@arcblock/vc": "1.32.0",
49
+ "@arcblock/did": "1.32.2",
50
+ "@arcblock/did-util": "1.32.2",
51
+ "@arcblock/jwt": "1.32.2",
52
+ "@arcblock/validator": "1.32.2",
53
+ "@arcblock/vc": "1.32.2",
54
54
  "@blocklet/xss": "^0.3.7",
55
- "@ocap/asset": "1.32.0",
56
- "@ocap/client": "1.32.0",
57
- "@ocap/mcrypto": "1.32.0",
58
- "@ocap/merkle-tree": "1.32.0",
59
- "@ocap/message": "1.32.0",
60
- "@ocap/state": "1.32.0",
61
- "@ocap/tx-pipeline": "1.32.0",
62
- "@ocap/types": "1.32.0",
63
- "@ocap/util": "1.32.0",
64
- "@ocap/wallet": "1.32.0",
55
+ "@ocap/asset": "1.32.2",
56
+ "@ocap/client": "1.32.2",
57
+ "@ocap/mcrypto": "1.32.2",
58
+ "@ocap/merkle-tree": "1.32.2",
59
+ "@ocap/message": "1.32.2",
60
+ "@ocap/state": "1.32.2",
61
+ "@ocap/tx-pipeline": "1.32.2",
62
+ "@ocap/types": "1.32.2",
63
+ "@ocap/util": "1.32.2",
64
+ "@ocap/wallet": "1.32.2",
65
65
  "debug": "^4.4.3",
66
66
  "deep-diff": "^1.0.2",
67
67
  "lodash": "^4.17.23",