@ocap/tx-protocols 1.31.1 → 1.31.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.
Files changed (161) hide show
  1. package/esm/bridge-release-crypto.d.mts +39 -0
  2. package/esm/bridge-release-crypto.mjs +88 -0
  3. package/esm/bridge-release-window.d.mts +47 -0
  4. package/esm/bridge-release-window.mjs +62 -0
  5. package/esm/bridge-reserve.d.mts +24 -0
  6. package/esm/bridge-reserve.mjs +41 -0
  7. package/esm/execute.d.mts +1 -1
  8. package/esm/execute.mjs +58 -5
  9. package/esm/gas-security-guard.d.mts +6 -2
  10. package/esm/gas-security-guard.mjs +16 -9
  11. package/esm/index.d.mts +37 -18
  12. package/esm/index.mjs +6 -2
  13. package/esm/pipes/ensure-cost.mjs +7 -1
  14. package/esm/pipes/write-ledger.d.mts +2 -2
  15. package/esm/pipes/write-ledger.mjs +6 -3
  16. package/esm/protocols/account/delegate.mjs +6 -4
  17. package/esm/protocols/account/migrate.mjs +5 -3
  18. package/esm/protocols/account/revoke-delegate.mjs +5 -3
  19. package/esm/protocols/asset/acquire-v2.mjs +3 -1
  20. package/esm/protocols/asset/acquire-v3.mjs +4 -2
  21. package/esm/protocols/asset/consume.mjs +3 -1
  22. package/esm/protocols/asset/create.mjs +4 -2
  23. package/esm/protocols/asset/mint.mjs +4 -2
  24. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +1 -1
  25. package/esm/protocols/asset/pipes/verify-itx-address.mjs +1 -1
  26. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +1 -1
  27. package/esm/protocols/asset/update.mjs +4 -2
  28. package/esm/protocols/bridge/release.d.mts +34 -0
  29. package/esm/protocols/bridge/release.mjs +385 -0
  30. package/esm/protocols/factory/create.mjs +4 -2
  31. package/esm/protocols/governance/claim-stake.mjs +4 -2
  32. package/esm/protocols/governance/return-stake.mjs +4 -2
  33. package/esm/protocols/governance/revoke-ledger.mjs +1 -1
  34. package/esm/protocols/governance/revoke-stake.d.mts +7 -2
  35. package/esm/protocols/governance/revoke-stake.mjs +49 -28
  36. package/esm/protocols/governance/slash-stake.mjs +5 -3
  37. package/esm/protocols/governance/stake.mjs +6 -4
  38. package/esm/protocols/rollup/bridge-create.d.mts +13 -0
  39. package/esm/protocols/rollup/bridge-create.mjs +206 -0
  40. package/esm/protocols/rollup/bridge-membership.d.mts +10 -0
  41. package/esm/protocols/rollup/bridge-membership.mjs +154 -0
  42. package/esm/protocols/rollup/bridge-migrate.d.mts +10 -0
  43. package/esm/protocols/rollup/bridge-migrate.mjs +208 -0
  44. package/esm/protocols/rollup/bridge-v2.d.mts +113 -0
  45. package/esm/protocols/rollup/bridge-v2.mjs +219 -0
  46. package/esm/protocols/rollup/claim-reward.mjs +4 -2
  47. package/esm/protocols/rollup/close.d.mts +2 -1
  48. package/esm/protocols/rollup/close.mjs +59 -6
  49. package/esm/protocols/rollup/create-block.mjs +4 -2
  50. package/esm/protocols/rollup/create.d.mts +3 -0
  51. package/esm/protocols/rollup/create.mjs +45 -6
  52. package/esm/protocols/rollup/join.d.mts +2 -1
  53. package/esm/protocols/rollup/join.mjs +31 -23
  54. package/esm/protocols/rollup/leave.d.mts +2 -1
  55. package/esm/protocols/rollup/leave.mjs +32 -24
  56. package/esm/protocols/rollup/migrate.d.mts +2 -1
  57. package/esm/protocols/rollup/migrate.mjs +19 -10
  58. package/esm/protocols/rollup/pause.d.mts +4 -1
  59. package/esm/protocols/rollup/pause.mjs +50 -6
  60. package/esm/protocols/rollup/pipes/verify-evidence.mjs +2 -2
  61. package/esm/protocols/rollup/resume.d.mts +2 -1
  62. package/esm/protocols/rollup/resume.mjs +26 -6
  63. package/esm/protocols/rollup/update.d.mts +5 -1
  64. package/esm/protocols/rollup/update.mjs +56 -9
  65. package/esm/protocols/token/create.mjs +4 -2
  66. package/esm/protocols/token/deposit-v2.mjs +5 -3
  67. package/esm/protocols/token/withdraw-v2.mjs +5 -3
  68. package/esm/protocols/token-factory/burn.mjs +4 -2
  69. package/esm/protocols/token-factory/create.mjs +8 -4
  70. package/esm/protocols/token-factory/mint.mjs +4 -2
  71. package/esm/protocols/token-factory/update.mjs +20 -5
  72. package/esm/protocols/trade/exchange-v2.d.mts +5 -1
  73. package/esm/protocols/trade/exchange-v2.mjs +89 -4
  74. package/esm/protocols/trade/transfer-v2.mjs +15 -4
  75. package/esm/protocols/trade/transfer-v3.mjs +5 -3
  76. package/esm/stateless-prefix.d.mts +16 -0
  77. package/esm/stateless-prefix.mjs +82 -0
  78. package/esm/tx-timer.d.mts +1 -1
  79. package/esm/tx-timer.mjs +1 -1
  80. package/esm/util.mjs +2 -2
  81. package/lib/bridge-release-crypto.cjs +93 -0
  82. package/lib/bridge-release-crypto.d.cts +39 -0
  83. package/lib/bridge-release-window.cjs +69 -0
  84. package/lib/bridge-release-window.d.cts +47 -0
  85. package/lib/bridge-reserve.cjs +45 -0
  86. package/lib/bridge-reserve.d.cts +24 -0
  87. package/lib/execute.cjs +58 -5
  88. package/lib/gas-security-guard.cjs +16 -9
  89. package/lib/gas-security-guard.d.cts +6 -2
  90. package/lib/index.cjs +8 -1
  91. package/lib/index.d.cts +36 -17
  92. package/lib/pipes/ensure-cost.cjs +7 -1
  93. package/lib/pipes/write-ledger.cjs +6 -3
  94. package/lib/pipes/write-ledger.d.cts +2 -2
  95. package/lib/protocols/account/delegate.cjs +6 -4
  96. package/lib/protocols/account/migrate.cjs +5 -3
  97. package/lib/protocols/account/revoke-delegate.cjs +5 -3
  98. package/lib/protocols/asset/acquire-v2.cjs +3 -1
  99. package/lib/protocols/asset/acquire-v3.cjs +4 -2
  100. package/lib/protocols/asset/consume.cjs +3 -1
  101. package/lib/protocols/asset/create.cjs +4 -2
  102. package/lib/protocols/asset/mint.cjs +4 -2
  103. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +1 -1
  104. package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
  105. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +1 -1
  106. package/lib/protocols/asset/update.cjs +4 -2
  107. package/lib/protocols/bridge/release.cjs +390 -0
  108. package/lib/protocols/bridge/release.d.cts +34 -0
  109. package/lib/protocols/factory/create.cjs +4 -2
  110. package/lib/protocols/governance/claim-stake.cjs +4 -2
  111. package/lib/protocols/governance/return-stake.cjs +4 -2
  112. package/lib/protocols/governance/revoke-ledger.cjs +1 -1
  113. package/lib/protocols/governance/revoke-stake.cjs +49 -28
  114. package/lib/protocols/governance/revoke-stake.d.cts +7 -2
  115. package/lib/protocols/governance/slash-stake.cjs +5 -3
  116. package/lib/protocols/governance/stake.cjs +6 -4
  117. package/lib/protocols/rollup/bridge-create.cjs +209 -0
  118. package/lib/protocols/rollup/bridge-create.d.cts +13 -0
  119. package/lib/protocols/rollup/bridge-membership.cjs +157 -0
  120. package/lib/protocols/rollup/bridge-membership.d.cts +10 -0
  121. package/lib/protocols/rollup/bridge-migrate.cjs +212 -0
  122. package/lib/protocols/rollup/bridge-migrate.d.cts +10 -0
  123. package/lib/protocols/rollup/bridge-v2.cjs +244 -0
  124. package/lib/protocols/rollup/bridge-v2.d.cts +113 -0
  125. package/lib/protocols/rollup/claim-reward.cjs +4 -2
  126. package/lib/protocols/rollup/close.cjs +59 -6
  127. package/lib/protocols/rollup/close.d.cts +2 -1
  128. package/lib/protocols/rollup/create-block.cjs +4 -2
  129. package/lib/protocols/rollup/create.cjs +45 -6
  130. package/lib/protocols/rollup/create.d.cts +3 -0
  131. package/lib/protocols/rollup/join.cjs +31 -23
  132. package/lib/protocols/rollup/join.d.cts +2 -1
  133. package/lib/protocols/rollup/leave.cjs +32 -24
  134. package/lib/protocols/rollup/leave.d.cts +2 -1
  135. package/lib/protocols/rollup/migrate.cjs +19 -10
  136. package/lib/protocols/rollup/migrate.d.cts +2 -1
  137. package/lib/protocols/rollup/pause.cjs +50 -6
  138. package/lib/protocols/rollup/pause.d.cts +4 -1
  139. package/lib/protocols/rollup/pipes/verify-evidence.cjs +2 -2
  140. package/lib/protocols/rollup/resume.cjs +26 -6
  141. package/lib/protocols/rollup/resume.d.cts +2 -1
  142. package/lib/protocols/rollup/update.cjs +56 -9
  143. package/lib/protocols/rollup/update.d.cts +5 -1
  144. package/lib/protocols/token/create.cjs +4 -2
  145. package/lib/protocols/token/deposit-v2.cjs +5 -3
  146. package/lib/protocols/token/withdraw-v2.cjs +5 -3
  147. package/lib/protocols/token-factory/burn.cjs +4 -2
  148. package/lib/protocols/token-factory/create.cjs +8 -4
  149. package/lib/protocols/token-factory/mint.cjs +4 -2
  150. package/lib/protocols/token-factory/update.cjs +20 -5
  151. package/lib/protocols/trade/exchange-v2.cjs +90 -3
  152. package/lib/protocols/trade/exchange-v2.d.cts +5 -1
  153. package/lib/protocols/trade/transfer-v2.cjs +15 -4
  154. package/lib/protocols/trade/transfer-v3.cjs +5 -3
  155. package/lib/stateless-prefix.cjs +88 -0
  156. package/lib/stateless-prefix.d.cts +16 -0
  157. package/lib/tx-timer.cjs +1 -1
  158. package/lib/tx-timer.d.cts +1 -1
  159. package/lib/util.cjs +2 -2
  160. package/package.json +16 -16
  161. package/tools/fixtures.ts +9 -4
@@ -1,14 +1,15 @@
1
1
  import { applyTokenChange, applyTokenUpdates, decodeAnySafe, isGasStakeAddress, isGasStakeInput } 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
- import { toTypeInfo } from "@arcblock/did";
5
- import { toStakeAddress } from "@arcblock/did-util";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
6
5
  import { types } from "@ocap/mcrypto";
7
- import { account, asset, stake, token } from "@ocap/state";
8
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
9
- import { BN, fromTokenToUnit } from "@ocap/util";
10
7
  import { CustomError } from "@ocap/util/lib/error";
11
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import { toTypeInfo } from "@arcblock/did";
10
+ import { toStakeAddress } from "@arcblock/did-util";
11
+ import { account, asset, stake, token } from "@ocap/state";
12
+ import { BN, fromTokenToUnit } from "@ocap/util";
12
13
  import pick from "lodash/pick.js";
13
14
  import Debug from "debug";
14
15
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -93,6 +94,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
93
94
  "tokens",
94
95
  "assets"
95
96
  ] }));
97
+ markStatelessPrefix(runner);
96
98
  runner.use(pipes.VerifyMultiSigV2({ signersKey: "senders" }));
97
99
  runner.use(pipes.ExtractState({
98
100
  from: "itx.address",
@@ -0,0 +1,13 @@
1
+ import { PipeNext } from "@ocap/tx-pipeline";
2
+
3
+ //#region src/protocols/rollup/bridge-create.d.ts
4
+ type Ctx = any;
5
+ /**
6
+ * Everything the v1 pipes do not cover for a v2 create. Runs after the token-authority check (#1411) and the
7
+ * one-bridge-per-token check, so it only sees a creator that already controls the token.
8
+ */
9
+ declare function verifyBridgeCreate(context: Ctx, next: PipeNext): Promise<void>;
10
+ /** The state writes of a v2 create: row, reserve account (funded zero-sum from tx.from), and the three index entries. */
11
+ declare function createBridgeStep(context: Ctx, next: PipeNext): Promise<void>;
12
+ //#endregion
13
+ export { createBridgeStep, verifyBridgeCreate };
@@ -0,0 +1,206 @@
1
+ import { gatewayIndexKey, indexBlocks, indexData, isBridgeIndex, membershipDigest, recoverAll, reserveIndexKey, tokenIndexKey, txSecOf, upsertIndexEvidence } from "./bridge-v2.mjs";
2
+ import { BRIDGE_MEMBERSHIP_ACTION, computeBridgeOwnerAttestationDigest, recoverBridgeSigner } from "@ocap/mcrypto";
3
+ import { CustomError } from "@ocap/util/lib/error";
4
+ import { isEthereumDid } from "@arcblock/did";
5
+ import { toBridgeReserveAddress } from "@arcblock/did-util";
6
+ import { account, delegation, rollup } from "@ocap/state";
7
+ import { BN, isSameDid } from "@ocap/util";
8
+
9
+ //#region src/protocols/rollup/bridge-create.ts
10
+ /**
11
+ * `create_rollup` for a v2 bridge (bridge/docs/ocap-protocols.md §v2.2, row `create_rollup`).
12
+ */
13
+ const isHttpUrl = (s) => {
14
+ try {
15
+ return typeof s === "string" && ["http:", "https:"].includes(new URL(s).protocol);
16
+ } catch {
17
+ return false;
18
+ }
19
+ };
20
+ /**
21
+ * Everything the v1 pipes do not cover for a v2 create. Runs after the token-authority check (#1411) and the
22
+ * one-bridge-per-token check, so it only sees a creator that already controls the token.
23
+ */
24
+ async function verifyBridgeCreate(context, next) {
25
+ if (!context.isBridgeV2) return next();
26
+ const { tx: tx$1, itx, config, tokenState, statedb } = context;
27
+ const input = context.bridgeInput;
28
+ const txSec = txSecOf(context);
29
+ const authority = !!config?.token?.address && isSameDid(itx.tokenAddress, config.token.address) ? config?.moderator?.address : tokenState?.issuer;
30
+ const owner = [tx$1.from, tx$1.delegator].filter(Boolean).find((x) => isSameDid(x, authority));
31
+ if (!owner) return next(new CustomError("FORBIDDEN", "Only the token owner can create a bridge for the token"));
32
+ if (!isEthereumDid(owner)) return next(new CustomError("INVALID_TX", "The bridge owner must use an ethereum compatible address"));
33
+ const seeds = context.seedValidators;
34
+ if (!seeds || seeds.length !== 1 || !rollup.sameAddress(seeds[0], owner)) return next(new CustomError("INVALID_TX", "seed_validators of a v2 bridge must be the bridge owner alone"));
35
+ if (!rollup.isValidRollupContractAddress(itx.contractAddress, "EVM")) return next(new CustomError("INVALID_TX", "contractAddress must be an ethereum token address"));
36
+ if (itx.vaultAddress && !rollup.isValidRollupVaultAddress(itx.vaultAddress, "EVM")) return next(new CustomError("INVALID_TX", "vaultAddress must be an ethereum address"));
37
+ if (!(itx.minBlockConfirmation >= 1 && itx.minBlockConfirmation <= 100)) return next(new CustomError("INVALID_TX", "minBlockConfirmation must be between 1 and 100"));
38
+ const ethToken = String(itx.contractAddress).toLowerCase();
39
+ const { body } = input;
40
+ const epoch1 = body.epochs[0];
41
+ const consents = input.consents;
42
+ if (consents.length !== epoch1.validators.length) return next(new CustomError("INVALID_SIGNATURE", "Every initial validator must sign a BridgeMembership consent"));
43
+ const endpointOf = {};
44
+ for (const c of consents) {
45
+ const addr = String(c?.address || "").toLowerCase();
46
+ if (!epoch1.validators.includes(addr)) return next(new CustomError("INVALID_SIGNATURE", `Consent signer ${addr} is not an initial validator`));
47
+ if (endpointOf[addr] !== void 0) return next(new CustomError("INVALID_SIGNATURE", `Duplicate consent of ${addr}`));
48
+ if (!isHttpUrl(c.endpoint)) return next(new CustomError("INVALID_TX", `Consent of ${addr} needs an http(s) endpoint`));
49
+ endpointOf[addr] = c.endpoint;
50
+ }
51
+ const gatewayKey = gatewayIndexKey(body.ethChainId, body.gateway);
52
+ const tokenKey = tokenIndexKey(itx.tokenAddress);
53
+ const reserve = toBridgeReserveAddress(itx.address);
54
+ const reserveKey = reserveIndexKey(reserve);
55
+ const [gatewayEntry, tokenEntry, reserveEntry, reserveAccount, validatorAccounts] = await Promise.all([
56
+ statedb.evidence.get(gatewayKey, context),
57
+ statedb.evidence.get(tokenKey, context),
58
+ statedb.evidence.get(reserveKey, context),
59
+ statedb.account.get(reserve, context),
60
+ Promise.all(epoch1.validators.map((a) => statedb.account.get(account.ensureChecksumAddress(a), context)))
61
+ ]);
62
+ if (indexBlocks(gatewayEntry, txSec, "bridge-gateway")) return next(new CustomError("DUPLICATE_ROLLUP", "A bridge that is not final already uses this ethereum gateway"));
63
+ if (indexBlocks(tokenEntry, txSec, "bridge-token")) return next(new CustomError("DUPLICATE_ROLLUP", "Only 1 bridge that is not final can exist for the token"));
64
+ if (isBridgeIndex(reserveEntry, "bridge-reserve") || reserveAccount) return next(new CustomError("DUPLICATE_ROLLUP", "The reserve of this bridge already exists"));
65
+ const missing = epoch1.validators.find((_, i) => !validatorAccounts[i]);
66
+ if (missing) return next(new CustomError("INVALID_TX", `Initial validator ${missing} has no account on this chain`));
67
+ let attestationSigner;
68
+ try {
69
+ attestationSigner = recoverBridgeSigner(computeBridgeOwnerAttestationDigest({
70
+ ocapChainId: config.chainId,
71
+ salt: body.salt,
72
+ ocapToken: itx.tokenAddress,
73
+ ethChainId: body.ethChainId,
74
+ gateway: body.gateway,
75
+ ethToken
76
+ }), body.ethOwnerAttestation.signature)?.address;
77
+ } catch (err) {
78
+ return next(new CustomError("INVALID_SIGNATURE", `Invalid ethOwnerAttestation: ${err.message}`));
79
+ }
80
+ if (!attestationSigner || attestationSigner !== body.ethOwnerAttestation.address) return next(new CustomError("INVALID_SIGNATURE", "ethOwnerAttestation signature does not match its address"));
81
+ const members = {};
82
+ try {
83
+ const recovered = recoverAll(membershipDigest({
84
+ ocapChainId: config.chainId,
85
+ bridge: itx.address,
86
+ epoch: epoch1,
87
+ action: BRIDGE_MEMBERSHIP_ACTION.CREATE,
88
+ endpoints: epoch1.validators.map((a) => endpointOf[a])
89
+ }), consents.map((c) => c?.signature));
90
+ consents.forEach((c, i) => {
91
+ const addr = String(c.address).toLowerCase();
92
+ if (addr !== recovered[i].address) throw new CustomError("INVALID_SIGNATURE", `Consent of ${c.address} was not signed by that address`);
93
+ members[addr] = {
94
+ address: account.ensureChecksumAddress(c.address),
95
+ pk: recovered[i].pk,
96
+ endpoint: c.endpoint
97
+ };
98
+ });
99
+ } catch (err) {
100
+ return next(err);
101
+ }
102
+ context.bridge = {
103
+ owner,
104
+ reserve,
105
+ members,
106
+ ethToken,
107
+ keys: {
108
+ gatewayKey,
109
+ tokenKey,
110
+ reserveKey
111
+ }
112
+ };
113
+ return next();
114
+ }
115
+ /** The state writes of a v2 create: row, reserve account (funded zero-sum from tx.from), and the three index entries. */
116
+ async function createBridgeStep(context, next) {
117
+ const { tx: tx$1, itx, formattedItx, statedb, senderState, delegationState, senderUpdates, updateVaults, bridge, bridgeInput } = context;
118
+ const input = bridgeInput;
119
+ const txSec = txSecOf(context);
120
+ const tokenAddress = itx.tokenAddress;
121
+ const amount = new BN(input.initialReserve);
122
+ const baseTokens = senderUpdates?.tokens ?? senderState.tokens ?? {};
123
+ const have = new BN(baseTokens[tokenAddress] || 0);
124
+ if (have.lt(amount)) return next(new CustomError("INSUFFICIENT_FUND", "Insufficient fund in tx.from to pay the initial reserve"));
125
+ const senderTokens = amount.gtn(0) ? {
126
+ ...baseTokens,
127
+ [tokenAddress]: have.sub(amount).toString(10)
128
+ } : baseTokens;
129
+ const body = {
130
+ ...input.body,
131
+ owner: bridge.owner,
132
+ reserve: bridge.reserve,
133
+ members: bridge.members,
134
+ pausers: input.body.pausers.length ? input.body.pausers : [bridge.owner],
135
+ lonePause: null,
136
+ lastLonePause: {},
137
+ pendingOwner: null,
138
+ pendingMigration: null,
139
+ closingAt: null,
140
+ depositCutoffEthBlock: null,
141
+ finalAt: null,
142
+ migratedTo: null,
143
+ migratedAmount: null
144
+ };
145
+ const epoch1 = body.epochs[0];
146
+ const attrs = rollup.syncBridgeView({
147
+ address: formattedItx.address,
148
+ tokenAddress,
149
+ vaultAddress: formattedItx.vaultAddress,
150
+ contractAddress: formattedItx.contractAddress,
151
+ seedValidators: formattedItx.seedValidators,
152
+ validators: [],
153
+ minSignerCount: epoch1.threshold,
154
+ maxSignerCount: epoch1.validators.length,
155
+ minBlockConfirmation: formattedItx.minBlockConfirmation,
156
+ issuer: bridge.owner,
157
+ data: {
158
+ type: "json",
159
+ value: body
160
+ }
161
+ }, txSec);
162
+ const rollupState = rollup.create(attrs, context);
163
+ const reserveState = account.create({
164
+ address: bridge.reserve,
165
+ tokens: amount.gtn(0) ? { [tokenAddress]: amount.toString(10) } : {}
166
+ }, context);
167
+ const bridgeAddress = rollupState.address;
168
+ const [newSenderState, newRollupState, newDelegationState, newReserveState] = await Promise.all([
169
+ statedb.account.update(senderState.address, account.update(senderState, {
170
+ nonce: tx$1.nonce,
171
+ ...senderUpdates,
172
+ tokens: senderTokens
173
+ }, context), context),
174
+ statedb.rollup.create(bridgeAddress, rollupState, context),
175
+ context.isDelegationChanged && delegationState ? statedb.delegation.update(delegationState.address, delegation.update(delegationState, {}, context), context) : Promise.resolve(delegationState),
176
+ statedb.account.create(bridge.reserve, reserveState, context)
177
+ ]);
178
+ await Promise.all([
179
+ upsertIndexEvidence(statedb, bridge.keys.gatewayKey, indexData("bridge-gateway", bridgeAddress, null), context),
180
+ upsertIndexEvidence(statedb, bridge.keys.tokenKey, indexData("bridge-token", bridgeAddress, null), context),
181
+ upsertIndexEvidence(statedb, bridge.keys.reserveKey, indexData("bridge-reserve", bridgeAddress, null), context)
182
+ ]);
183
+ if (updateVaults) await updateVaults();
184
+ if (amount.gtn(0)) {
185
+ context.updatedAccounts = context.updatedAccounts || [];
186
+ context.updatedAccounts.push({
187
+ address: senderState.address,
188
+ token: tokenAddress,
189
+ delta: `-${amount.toString(10)}`,
190
+ action: "transfer"
191
+ }, {
192
+ address: bridge.reserve,
193
+ token: tokenAddress,
194
+ delta: amount.toString(10),
195
+ action: "transfer"
196
+ });
197
+ }
198
+ context.senderState = newSenderState;
199
+ context.rollupState = newRollupState;
200
+ context.delegationState = newDelegationState;
201
+ context.reserveState = newReserveState;
202
+ return next();
203
+ }
204
+
205
+ //#endregion
206
+ export { createBridgeStep, verifyBridgeCreate };
@@ -0,0 +1,10 @@
1
+ import { PipeFunction, PipeNext } from "@ocap/tx-pipeline";
2
+
3
+ //#region src/protocols/rollup/bridge-membership.d.ts
4
+ type Ctx = any;
5
+ type Action = 'join' | 'leave';
6
+ declare const membershipSchemaV2: (action: Action) => PipeFunction<Ctx>;
7
+ declare const membershipChecks: (action: Action) => PipeFunction<Ctx>;
8
+ declare const membershipStep: (action: Action) => (context: Ctx, next: PipeNext) => Promise<void>;
9
+ //#endregion
10
+ export { membershipChecks, membershipSchemaV2, membershipStep };
@@ -0,0 +1,154 @@
1
+ import { bridgeUpdates, membershipDigest, membershipTombstoneKey, readItxData, recoverAll } from "./bridge-v2.mjs";
2
+ import { BRIDGE_MEMBERSHIP_ACTION } from "@ocap/mcrypto";
3
+ import { CustomError } from "@ocap/util/lib/error";
4
+ import { isEthereumDid } from "@arcblock/did";
5
+ import { account, evidence, rollup } from "@ocap/state";
6
+ import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
7
+
8
+ //#region src/protocols/rollup/bridge-membership.ts
9
+ /**
10
+ * `join_rollup` / `leave_rollup` for a v2 bridge (bridge/docs/ocap-protocols.md §v2.2, row `join_rollup / leave_rollup`).
11
+ *
12
+ * A membership change creates a NEW EPOCH. It is authorised by EIP-712 `BridgeMembership` signatures of the owner and a
13
+ * quorum of the epoch active at txTime (and, for a join, of the joiner itself), carried in `itx.data.signatures`. The
14
+ * transaction sender is irrelevant: anyone may submit the approved change. There is no stake and no global
15
+ * `validatorsHash` evidence, so one operator can serve several bridges and leave and rejoin.
16
+ */
17
+ const isHttpUrl = (s) => {
18
+ try {
19
+ return typeof s === "string" && ["http:", "https:"].includes(new URL(s).protocol);
20
+ } catch {
21
+ return false;
22
+ }
23
+ };
24
+ const itxSchemaV2 = v.pipe(v.object({
25
+ rollup: vDID({
26
+ prefix: true,
27
+ role: "ROLE_ROLLUP"
28
+ }),
29
+ endpoint: v.optional(v.string()),
30
+ data: v.optional(v.nullable(v.any()))
31
+ }), vStripUnknown());
32
+ const membershipSchemaV2 = (action) => function MembershipSchemaV2(context, next) {
33
+ if (!context.isBridgeV2) return next();
34
+ const { error } = vValidate(itxSchemaV2, context.itx);
35
+ if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
36
+ if (action === "join" && !isHttpUrl(context.itx.endpoint)) return next(new CustomError("INVALID_TX", "Invalid itx: endpoint must be a valid HTTP/HTTPS URL"));
37
+ return next();
38
+ };
39
+ function parseMembershipData(itx) {
40
+ const d = readItxData(itx);
41
+ for (const k of Object.keys(d)) if (![
42
+ "validator",
43
+ "threshold",
44
+ "activeFrom",
45
+ "voucherValidity",
46
+ "signatures"
47
+ ].includes(k)) throw new CustomError("INVALID_TX", `Unknown key in membership data: ${k}`);
48
+ if (typeof d.validator !== "string" || !isEthereumDid(d.validator)) throw new CustomError("INVALID_TX", "data.validator must be an ethereum address");
49
+ for (const k of [
50
+ "threshold",
51
+ "activeFrom",
52
+ "voucherValidity"
53
+ ]) if (!Number.isSafeInteger(d[k]) || d[k] < 0) throw new CustomError("INVALID_TX", `data.${k} must be a non-negative integer`);
54
+ if (!Array.isArray(d.signatures) || d.signatures.length === 0 || d.signatures.length > 18) throw new CustomError("INVALID_TX", "data.signatures must be a non-empty array of BridgeMembership signatures");
55
+ return d;
56
+ }
57
+ const membershipChecks = (action) => async function MembershipChecks(context, next) {
58
+ if (!context.isBridgeV2) return next();
59
+ const { itx, statedb, config } = context;
60
+ const state = context.rollupState;
61
+ const body = context.bridgeBody;
62
+ const txSec = context.txSec;
63
+ try {
64
+ rollup.assertV1FieldsUnused(itx, "INVALID_ROLLUP_UPDATE");
65
+ if (state.closed || body.closingAt !== null) throw new CustomError("INVALID_TX", "Membership is frozen after the bridge is closed");
66
+ const data = parseMembershipData(itx);
67
+ const plan = rollup.planMembership(body, {
68
+ action,
69
+ validator: data.validator,
70
+ threshold: data.threshold,
71
+ activeFrom: data.activeFrom,
72
+ voucherValidity: data.voucherValidity
73
+ }, txSec);
74
+ if (action === "join" && !isHttpUrl(itx.endpoint)) throw new CustomError("INVALID_TX", "itx.endpoint must be an http(s) URL");
75
+ if (action === "join" && !rollup.sameAddress(context.tx.from, data.validator)) throw new CustomError("INVALID_TX", "tx.from must be the joining validator");
76
+ const maxSignatures = plan.signingEpoch.validators.length + 2;
77
+ if (data.signatures.length > maxSignatures) throw new CustomError("INVALID_TX", `data.signatures may hold at most ${maxSignatures} approvals`);
78
+ const joinerKey = rollup.lc(data.validator);
79
+ const endpoints = plan.epoch.validators.map((a) => action === "join" && a === joinerKey ? itx.endpoint : body.members[a].endpoint);
80
+ const digest = membershipDigest({
81
+ ocapChainId: config.chainId,
82
+ bridge: state.address,
83
+ epoch: plan.epoch,
84
+ action: action === "join" ? BRIDGE_MEMBERSHIP_ACTION.JOIN : BRIDGE_MEMBERSHIP_ACTION.LEAVE,
85
+ endpoints
86
+ });
87
+ const digestHex = `0x${Buffer.from(digest).toString("hex")}`;
88
+ const tombstoneKey = membershipTombstoneKey(state.address, plan.epoch.epoch, digestHex);
89
+ if (await statedb.evidence.get(tombstoneKey, context)) throw new CustomError("INVALID_TX", "This membership approval was already used on this chain");
90
+ const recovered = recoverAll(digest, data.signatures);
91
+ const signers = new Map(recovered.map((r) => [r.address, r]));
92
+ const owner = rollup.lc(body.owner);
93
+ const quorum = new Set(plan.signingEpoch.validators);
94
+ const joiner = rollup.lc(data.validator);
95
+ 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
+ if (!signers.has(owner)) throw new CustomError("INVALID_SIGNATURE", "The bridge owner must sign the membership change");
97
+ const have = [...signers.keys()].filter((a) => quorum.has(a)).length;
98
+ 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}`);
99
+ const members = { ...body.members };
100
+ if (action === "join") {
101
+ const j = signers.get(joiner);
102
+ if (!j) throw new CustomError("INVALID_SIGNATURE", "The joining validator must sign the membership change");
103
+ members[joiner] = {
104
+ address: account.ensureChecksumAddress(data.validator),
105
+ pk: j.pk,
106
+ endpoint: itx.endpoint
107
+ };
108
+ }
109
+ context.membership = {
110
+ plan,
111
+ tombstoneKey,
112
+ members
113
+ };
114
+ context.signers = [];
115
+ return next();
116
+ } catch (err) {
117
+ const e = err;
118
+ return next(String(e.code || "").startsWith("INVALID_ROLLUP") ? new CustomError("INVALID_TX", e.message) : e);
119
+ }
120
+ };
121
+ const membershipStep = (action) => async function MembershipStep(context, next) {
122
+ const { tx: tx$1, statedb, senderState, senderUpdates, updateVaults } = context;
123
+ const body = context.bridgeBody;
124
+ const { plan, tombstoneKey, members } = context.membership;
125
+ const nextBody = {
126
+ ...body,
127
+ epochs: [...body.epochs, plan.epoch],
128
+ members
129
+ };
130
+ const [newSenderState, newRollupState] = await Promise.all([
131
+ statedb.account.update(senderState.address, account.update(senderState, {
132
+ nonce: tx$1.nonce,
133
+ ...senderUpdates
134
+ }, context), context),
135
+ statedb.rollup.update(context.rollupStateOrig.address, rollup.updateBridge(context.rollupStateOrig, bridgeUpdates(context, nextBody), context), context),
136
+ statedb.evidence.create(tombstoneKey, evidence.create({
137
+ hash: tombstoneKey,
138
+ data: {
139
+ type: "json",
140
+ value: {
141
+ kind: `bridge-${action}`,
142
+ epoch: plan.epoch.epoch
143
+ }
144
+ }
145
+ }, context), context)
146
+ ]);
147
+ if (updateVaults) await updateVaults();
148
+ context.senderState = newSenderState;
149
+ context.rollupState = newRollupState;
150
+ return next();
151
+ };
152
+
153
+ //#endregion
154
+ export { membershipChecks, membershipSchemaV2, membershipStep };
@@ -0,0 +1,10 @@
1
+ import { PipeFunction, PipeNext } from "@ocap/tx-pipeline";
2
+
3
+ //#region src/protocols/rollup/bridge-migrate.d.ts
4
+ type Ctx = any;
5
+ declare const migrateSchemaV2: PipeFunction<Ctx>;
6
+ declare function migrateBridgeChecks(context: Ctx, next: PipeNext): Promise<void>;
7
+ declare const migrateBridgeAuth: PipeFunction<Ctx>;
8
+ declare function migrateBridgeStep(context: Ctx, next: PipeNext): Promise<void>;
9
+ //#endregion
10
+ export { migrateBridgeAuth, migrateBridgeChecks, migrateBridgeStep, migrateSchemaV2 };
@@ -0,0 +1,208 @@
1
+ import { VerifyBridgeAuthority, bridgeUpdates, readItxData } from "./bridge-v2.mjs";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
+ import { getListField } from "@ocap/util/lib/get-list-field";
4
+ import { toBridgeReserveAddress } from "@arcblock/did-util";
5
+ import { account, rollup } from "@ocap/state";
6
+ import { BN, isSameDid } from "@ocap/util";
7
+ import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
8
+
9
+ //#region src/protocols/rollup/bridge-migrate.ts
10
+ /**
11
+ * `migrate_rollup` for a v2 bridge (bridge/docs/ocap-protocols.md §v2.2, row `migrate_rollup`).
12
+ *
13
+ * - `type = vault`: a new Ethereum Vault, owner + quorum.
14
+ * - `type = reserve`: moves the whole residual reserve of a FINAL bridge to a successor bridge. Announced first, executed
15
+ * after 30 days, vetoable in between by the token authority of #1411 alone. `data.action` selects the step.
16
+ * - `type = contract` is rejected: the gateway / Ethereum token of a bridge is immutable.
17
+ */
18
+ const schemaV2 = v.pipe(v.object({
19
+ rollup: vDID({
20
+ prefix: true,
21
+ role: "ROLE_ROLLUP"
22
+ }),
23
+ to: v.pipe(v.string(), v.minLength(1)),
24
+ type: v.picklist(["vault", "reserve"]),
25
+ message: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(512)),
26
+ data: v.optional(v.nullable(v.any()))
27
+ }), vStripUnknown());
28
+ const migrateSchemaV2 = function MigrateSchemaV2(context, next) {
29
+ if (!context.isBridgeV2) return next();
30
+ const { error } = vValidate(schemaV2, context.itx);
31
+ if (error) {
32
+ const hint = context.itx?.type === "contract" ? " (the gateway and the ethereum token of a bridge are immutable)" : "";
33
+ return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}${hint}`));
34
+ }
35
+ return next();
36
+ };
37
+ const TOKEN_AUTHORITY_ERROR = "Only the token authority can cancel a reserve migration";
38
+ /** The token authority of #1411: the moderator for the official token, the token issuer otherwise. */
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
+ }
43
+ async function migrateBridgeChecks(context, next) {
44
+ if (!context.isBridgeV2) return next();
45
+ const { itx, statedb } = context;
46
+ const state = context.rollupState;
47
+ const body = context.bridgeBody;
48
+ const txSec = context.txSec;
49
+ try {
50
+ if (itx.type === "vault") {
51
+ if (state.closed) throw new CustomError("INVALID_TX", "The rollup is closed");
52
+ if (!rollup.isBridgePausedAt(state, txSec)) throw new CustomError("INVALID_TX", "The rollup is not paused");
53
+ if (!itx.to || !rollup.isValidRollupVaultAddress(itx.to, "EVM")) throw new CustomError("INVALID_TX", "Invalid itx: \"to\" Expected wallet type to be \"ethereum\"");
54
+ const same = (a) => rollup.lc(a) === rollup.lc(itx.to);
55
+ if (state.vaultAddress && same(state.vaultAddress)) throw new CustomError("INVALID_TX", "can not migrate vault to self");
56
+ if ((state.vaultHistory || []).some(same)) throw new CustomError("INVALID_TX", "can not migrate vault to history vaults");
57
+ context.migratePlan = { kind: "vault" };
58
+ return next();
59
+ }
60
+ const action = (itx.data ? readItxData(itx) : {}).action;
61
+ if (![
62
+ "announce",
63
+ "execute",
64
+ "cancel"
65
+ ].includes(action)) throw new CustomError("INVALID_TX", "itx.data.action must be announce, execute or cancel");
66
+ if (action === "cancel") {
67
+ if (!body.pendingMigration) throw new CustomError("INVALID_TX", "There is no pending reserve migration to cancel");
68
+ context.tokenAuthority = tokenAuthority(context, await statedb.token.get(state.tokenAddress, context));
69
+ context.migratePlan = { kind: "cancel" };
70
+ return next();
71
+ }
72
+ if (!rollup.isBridgeFinalAt(body, txSec)) throw new CustomError("INVALID_TX", "The source bridge is not final yet");
73
+ if (body.migratedTo !== null) throw new CustomError("INVALID_TX", "The reserve of this bridge was already migrated");
74
+ if (action === "announce" && body.pendingMigration) throw new CustomError("INVALID_TX", "A reserve migration is already pending");
75
+ if (action === "execute") {
76
+ const p = body.pendingMigration;
77
+ if (!p) throw new CustomError("INVALID_TX", "No reserve migration was announced");
78
+ if (rollup.lc(p.to) !== rollup.lc(itx.to)) throw new CustomError("INVALID_TX", "The target differs from the announced migration");
79
+ if (txSec < p.effectiveAt) throw new CustomError("INVALID_TX", "The reserve migration window has not elapsed yet");
80
+ }
81
+ const target = await statedb.rollup.get(itx.to, context);
82
+ if (!target || !rollup.isBridgeV2(target)) throw new CustomError("INVALID_TX", "The migration target must be a v2 bridge");
83
+ const tbody = rollup.getBridgeBody(target);
84
+ if (rollup.sameAddress(target.address, state.address)) throw new CustomError("INVALID_TX", "Can not migrate a reserve to its own bridge");
85
+ if (target.closed) throw new CustomError("INVALID_TX", "The migration target is closed");
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.lc(target.contractAddress) !== rollup.lc(state.contractAddress)) throw new CustomError("INVALID_TX", "The migration target bridges a different ethereum token");
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
+ context.migrateTarget = target;
90
+ context.migratePlan = { kind: action };
91
+ if (action === "execute") {
92
+ const [sourceState, targetState] = await Promise.all([statedb.account.get(toBridgeReserveAddress(state.address), context), statedb.account.get(toBridgeReserveAddress(target.address), context)]);
93
+ if (!sourceState || !targetState) throw new CustomError("INVALID_TX", "The reserve account of the source or the target bridge does not exist");
94
+ context.sourceReserveState = sourceState;
95
+ context.targetReserveState = targetState;
96
+ }
97
+ return next();
98
+ } catch (err) {
99
+ return next(err);
100
+ }
101
+ }
102
+ const migrateBridgeAuth = function MigrateBridgeAuth(context, next) {
103
+ if (!context.isBridgeV2) return next();
104
+ const kind = context.migratePlan?.kind;
105
+ if (kind === "cancel") {
106
+ const { tx: tx$1 } = context;
107
+ const authority = context.tokenAuthority;
108
+ const signatures = getListField(context, "tx.signaturesList");
109
+ if (!authority || tx$1.delegator || signatures.length > 0 || !isSameDid(tx$1.from, authority)) return next(new CustomError("FORBIDDEN", TOKEN_AUTHORITY_ERROR));
110
+ context.signers = [];
111
+ return next();
112
+ }
113
+ if (kind === "vault") return VerifyBridgeAuthority({
114
+ owner: "required",
115
+ quorum: "threshold"
116
+ })(context, next);
117
+ return VerifyBridgeAuthority({
118
+ owner: "required",
119
+ quorum: "threshold",
120
+ quorumBody: (ctx) => rollup.getBridgeBody(ctx.migrateTarget)
121
+ })(context, next);
122
+ };
123
+ async function migrateBridgeStep(context, next) {
124
+ const { tx: tx$1, itx, statedb, rollupState, senderState, senderUpdates, updateVaults } = context;
125
+ const body = context.bridgeBody;
126
+ const txSec = context.txSec;
127
+ const kind = context.migratePlan.kind;
128
+ let nextBody = body;
129
+ let rowOverrides = {};
130
+ const accountWrites = [];
131
+ const updated = [];
132
+ if (kind === "vault") rowOverrides = {
133
+ vaultAddress: itx.to,
134
+ vaultHistory: rollupState.vaultAddress ? [...rollupState.vaultHistory || [], rollupState.vaultAddress] : [...rollupState.vaultHistory || []]
135
+ };
136
+ else if (kind === "announce") nextBody = {
137
+ ...body,
138
+ pendingMigration: {
139
+ to: context.migrateTarget.address,
140
+ announcedAt: txSec,
141
+ effectiveAt: txSec + rollup.BRIDGE_RESERVE_MIGRATION_WINDOW
142
+ }
143
+ };
144
+ else if (kind === "cancel") nextBody = {
145
+ ...body,
146
+ pendingMigration: null
147
+ };
148
+ else if (kind === "execute") {
149
+ const target = context.migrateTarget;
150
+ const sourceReserve = toBridgeReserveAddress(rollupState.address);
151
+ const targetReserve = toBridgeReserveAddress(target.address);
152
+ const sourceState = context.sourceReserveState;
153
+ const targetState = context.targetReserveState;
154
+ const moved = {};
155
+ const nextTarget = { ...targetState.tokens || {} };
156
+ for (const [token$1, value] of Object.entries(sourceState.tokens || {})) {
157
+ if (new BN(value).lten(0)) continue;
158
+ moved[token$1] = value;
159
+ nextTarget[token$1] = new BN(nextTarget[token$1] || 0).add(new BN(value)).toString(10);
160
+ updated.push({
161
+ address: sourceReserve,
162
+ token: token$1,
163
+ delta: `-${value}`,
164
+ action: "transfer"
165
+ });
166
+ updated.push({
167
+ address: targetReserve,
168
+ token: token$1,
169
+ delta: value,
170
+ action: "transfer"
171
+ });
172
+ }
173
+ if (Object.keys(moved).length > 0) accountWrites.push(statedb.account.update(sourceReserve, account.update(sourceState, { tokens: {} }, context), context), statedb.account.update(targetReserve, account.update(targetState, { tokens: nextTarget }, context), context));
174
+ context.reserveMigration = {
175
+ sourceReserve,
176
+ targetReserve
177
+ };
178
+ nextBody = {
179
+ ...body,
180
+ migratedTo: target.address,
181
+ pendingMigration: null,
182
+ migratedAmount: moved[rollupState.tokenAddress] ?? "0"
183
+ };
184
+ }
185
+ const [newSenderState, newRollupState, ...reserveStates] = await Promise.all([
186
+ statedb.account.update(senderState.address, account.update(senderState, {
187
+ nonce: tx$1.nonce,
188
+ ...senderUpdates
189
+ }, context), context),
190
+ statedb.rollup.update(itx.rollup, rollup.updateBridge(context.rollupStateOrig, bridgeUpdates(context, nextBody, rowOverrides), context), context),
191
+ ...accountWrites
192
+ ]);
193
+ if (reserveStates.length === 2) {
194
+ context.sourceReserveState = reserveStates[0];
195
+ context.targetReserveState = reserveStates[1];
196
+ }
197
+ if (updateVaults) await updateVaults();
198
+ if (updated.length) {
199
+ context.updatedAccounts = context.updatedAccounts || [];
200
+ context.updatedAccounts.push(...updated);
201
+ }
202
+ context.senderState = newSenderState;
203
+ context.rollupState = newRollupState;
204
+ return next();
205
+ }
206
+
207
+ //#endregion
208
+ export { migrateBridgeAuth, migrateBridgeChecks, migrateBridgeStep, migrateSchemaV2 };