@ocap/tx-pipeline 1.31.0 → 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 (107) hide show
  1. package/esm/bridge-release-keys.d.mts +33 -0
  2. package/esm/bridge-release-keys.mjs +81 -0
  3. package/esm/bridge-reserves.d.mts +107 -0
  4. package/esm/bridge-reserves.mjs +242 -0
  5. package/esm/helpers/bridge-withdraw.d.mts +86 -0
  6. package/esm/helpers/bridge-withdraw.mjs +123 -0
  7. package/esm/helpers/replay-guard.d.mts +19 -1
  8. package/esm/helpers/replay-guard.mjs +39 -1
  9. package/esm/index.d.mts +3 -1
  10. package/esm/index.mjs +8 -6
  11. package/esm/legacy-protocol-sunset.d.mts +2 -2
  12. package/esm/legacy-protocol-sunset.mjs +5 -5
  13. package/esm/legacy-rollup-archive.d.mts +67 -0
  14. package/esm/legacy-rollup-archive.mjs +199 -0
  15. package/esm/library.d.mts +4 -4
  16. package/esm/library.mjs +3 -3
  17. package/esm/native-abt-exchange.d.mts +3 -0
  18. package/esm/native-abt-exchange.mjs +93 -46
  19. package/esm/pipes/bridge-release-gate.d.mts +30 -0
  20. package/esm/pipes/bridge-release-gate.mjs +143 -0
  21. package/esm/pipes/bridge-reserve-v2-gate.d.mts +53 -0
  22. package/esm/pipes/bridge-reserve-v2-gate.mjs +264 -0
  23. package/esm/pipes/decode-itx.mjs +3 -0
  24. package/esm/pipes/decode-tx.mjs +32 -4
  25. package/esm/pipes/extract-signer.mjs +1 -1
  26. package/esm/pipes/extract-state.mjs +2 -2
  27. package/esm/pipes/post-execution-invariant-gate.d.mts +19 -2
  28. package/esm/pipes/post-execution-invariant-gate.mjs +121 -6
  29. package/esm/pipes/pre-flight-waf.d.mts +58 -2
  30. package/esm/pipes/pre-flight-waf.mjs +202 -14
  31. package/esm/pipes/update-owner.mjs +1 -1
  32. package/esm/pipes/verify-account-migration.mjs +1 -1
  33. package/esm/pipes/verify-delegation.mjs +49 -25
  34. package/esm/pipes/verify-multisig-v2.mjs +5 -4
  35. package/esm/pipes/verify-multisig.mjs +5 -4
  36. package/esm/pipes/verify-signature.d.mts +7 -1
  37. package/esm/pipes/verify-signature.mjs +119 -16
  38. package/esm/pipes/verify-signer.mjs +2 -2
  39. package/esm/pipes/verify-token-access.mjs +1 -1
  40. package/esm/pipes/verify-token-balance.mjs +1 -1
  41. package/esm/pipes/verify-tx-input.mjs +1 -1
  42. package/esm/pipes/verify-tx-size.mjs +1 -1
  43. package/esm/pipes/verify-tx.mjs +12 -5
  44. package/esm/super-suites-foundation.mjs +6 -6
  45. package/esm/transaction-block.d.mts +6 -2
  46. package/esm/transaction-block.mjs +282 -40
  47. package/esm/uniswap-router.d.mts +247 -1
  48. package/esm/uniswap-router.mjs +573 -2
  49. package/lib/bridge-release-keys.cjs +88 -0
  50. package/lib/bridge-release-keys.d.cts +33 -0
  51. package/lib/bridge-reserves.cjs +257 -0
  52. package/lib/bridge-reserves.d.cts +107 -0
  53. package/lib/helpers/bridge-withdraw.cjs +136 -0
  54. package/lib/helpers/bridge-withdraw.d.cts +86 -0
  55. package/lib/helpers/replay-guard.cjs +39 -0
  56. package/lib/helpers/replay-guard.d.cts +20 -2
  57. package/lib/index.cjs +25 -5
  58. package/lib/index.d.cts +3 -1
  59. package/lib/legacy-protocol-sunset.cjs +7 -7
  60. package/lib/legacy-protocol-sunset.d.cts +2 -2
  61. package/lib/legacy-rollup-archive.cjs +208 -0
  62. package/lib/legacy-rollup-archive.d.cts +67 -0
  63. package/lib/library.cjs +14 -68
  64. package/lib/library.d.cts +4 -4
  65. package/lib/native-abt-exchange.cjs +93 -46
  66. package/lib/native-abt-exchange.d.cts +3 -0
  67. package/lib/pipes/bridge-release-gate.cjs +145 -0
  68. package/lib/pipes/bridge-release-gate.d.cts +30 -0
  69. package/lib/pipes/bridge-reserve-v2-gate.cjs +273 -0
  70. package/lib/pipes/bridge-reserve-v2-gate.d.cts +53 -0
  71. package/lib/pipes/decode-itx.cjs +3 -0
  72. package/lib/pipes/decode-itx.d.cts +1 -1
  73. package/lib/pipes/decode-tx.cjs +31 -3
  74. package/lib/pipes/decode-tx.d.cts +1 -1
  75. package/lib/pipes/extract-signer.cjs +1 -1
  76. package/lib/pipes/extract-state.cjs +3 -3
  77. package/lib/pipes/post-execution-invariant-gate.cjs +121 -4
  78. package/lib/pipes/post-execution-invariant-gate.d.cts +19 -2
  79. package/lib/pipes/pre-flight-waf.cjs +209 -15
  80. package/lib/pipes/pre-flight-waf.d.cts +58 -2
  81. package/lib/pipes/update-owner.cjs +1 -1
  82. package/lib/pipes/update-owner.d.cts +1 -1
  83. package/lib/pipes/verify-account-migration.cjs +1 -1
  84. package/lib/pipes/verify-delegation.cjs +50 -26
  85. package/lib/pipes/verify-multisig-v2.cjs +5 -4
  86. package/lib/pipes/verify-multisig.cjs +5 -4
  87. package/lib/pipes/verify-service-fee.d.cts +1 -1
  88. package/lib/pipes/verify-signature.cjs +118 -14
  89. package/lib/pipes/verify-signature.d.cts +8 -2
  90. package/lib/pipes/verify-signer.cjs +2 -2
  91. package/lib/pipes/verify-token-access.cjs +1 -1
  92. package/lib/pipes/verify-token-balance.cjs +1 -1
  93. package/lib/pipes/verify-tx-input.cjs +1 -1
  94. package/lib/pipes/verify-tx-size.cjs +1 -1
  95. package/lib/pipes/verify-tx-size.d.cts +1 -1
  96. package/lib/pipes/verify-tx.cjs +11 -5
  97. package/lib/pipes/verify-tx.d.cts +1 -1
  98. package/lib/super-suites-foundation.cjs +6 -6
  99. package/lib/transaction-block.cjs +282 -40
  100. package/lib/transaction-block.d.cts +6 -2
  101. package/lib/uniswap-router.cjs +576 -1
  102. package/lib/uniswap-router.d.cts +247 -1
  103. package/package.json +10 -10
  104. package/esm/evm-simplified-bridge.d.mts +0 -1370
  105. package/esm/evm-simplified-bridge.mjs +0 -3875
  106. package/lib/evm-simplified-bridge.cjs +0 -3943
  107. package/lib/evm-simplified-bridge.d.cts +0 -1370
@@ -0,0 +1,273 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_bridge_reserves = require('../bridge-reserves.cjs');
3
+ let _ocap_util = require("@ocap/util");
4
+ let _arcblock_did_util = require("@arcblock/did-util");
5
+ let lodash_isEqual = require("lodash/isEqual");
6
+ lodash_isEqual = require_rolldown_runtime.__toESM(lodash_isEqual);
7
+
8
+ //#region src/pipes/bridge-reserve-v2-gate.ts
9
+ /**
10
+ * Gate rules R1-R5 for the per-bridge reserves (`ROLE_BRIDGE_RESERVE`, bridge/docs/ocap-protocols.md §v2.3, §1).
11
+ *
12
+ * Every account whose DID role is `ROLE_BRIDGE_RESERVE` is a reserve, recognised syntactically (no state scan). Which
13
+ * bridge a reserve belongs to comes from the `reserve -> bridge` index, resolved once per transaction by
14
+ * `prepareBridgeReserveGate` before this synchronous check runs (`bridge-reserves.ts`); the address is never trusted.
15
+ *
16
+ * - R1 debits: `release_bridge_token` of THAT bridge (the reserve of `itx.bridge`, or of its `migratedTo` chain for a
17
+ * REFUND), `migrate_rollup`, and the reconcile hook (a named, empty list today). The master switch
18
+ * `transaction.bridge.enabled` must be on for a release.
19
+ * - R2 credits: `transfer_v2` (the withdraw) into the reserve of a live, unpaused, not-closing bridge with the master
20
+ * switch on, in the bridge token only; `create_rollup` funding the reserve of the bridge it creates;
21
+ * `migrate_rollup` filling the successor's reserve. A role-25 address that maps to no bridge accepts nothing.
22
+ * - R3: a reserve account is only materialised by `create_rollup`, only token balances ever change, nothing writes the
23
+ * `balance` table directly, and no record of another table gains a reference to a reserve.
24
+ * - R4 (release accounting) lives in bridge-release-gate.ts (#1466). The gate
25
+ * guarantees the part that protects other bridges: a release debits exactly one reserve, the right one.
26
+ * - R5 is the early rejection in `@ocap/tx-protocols` (`bridge-reserve.ts`).
27
+ */
28
+ /** @deprecated use BRIDGE_RESERVE_DEBIT_TX_TYPES */
29
+ const BRIDGE_V2_RESERVE_DEBIT_TX_TYPES = require_bridge_reserves.BRIDGE_RESERVE_DEBIT_TX_TYPES;
30
+ /** @deprecated use BRIDGE_RESERVE_CREDIT_TX_TYPES */
31
+ const BRIDGE_V2_RESERVE_CREDIT_TX_TYPES = require_bridge_reserves.BRIDGE_RESERVE_CREDIT_TX_TYPES;
32
+ const isBridgeV2Row = (row) => !!row && row.data?.value?.version === 2;
33
+ const migratedToOf = (row) => {
34
+ const v = (row?.data)?.value?.migratedTo;
35
+ return typeof v === "string" && v ? v : null;
36
+ };
37
+ /**
38
+ * `balance` / `balanceNum` are the legacy fields that real account rows carry (kept on purpose, they stay at their
39
+ * default). They are not "other state" of the reserve, but no tx may change them: see the check in
40
+ * `assertBridgeReservesV2Protected`.
41
+ */
42
+ const LEGACY_BALANCE_FIELDS = new Set(["balance", "balanceNum"]);
43
+ /** Account fields other than balances; empty values and the context are ignored. */
44
+ const stableFields = (account) => {
45
+ const out = {};
46
+ for (const [k, v] of Object.entries(account || {})) {
47
+ if (LEGACY_BALANCE_FIELDS.has(k)) continue;
48
+ if (k === "tokens" || k === "context" || k === "meta" || k === "$loki" || k.startsWith("_")) continue;
49
+ if (v === void 0 || v === null || v === "" || Array.isArray(v) && v.length === 0) continue;
50
+ out[k] = v;
51
+ }
52
+ return out;
53
+ };
54
+ /** Fields that make an account the owner / creator / counterparty of a record in the other tables. */
55
+ const RESERVE_REFERENCE_FIELDS = [
56
+ "owner",
57
+ "issuer",
58
+ "creator",
59
+ "sender",
60
+ "receiver",
61
+ "from",
62
+ "to",
63
+ "delegator",
64
+ "vaultAddress",
65
+ "proposer",
66
+ "publisher",
67
+ "seedValidators",
68
+ "validators",
69
+ "spenders",
70
+ "minters",
71
+ "slashers",
72
+ "trustedIssuers"
73
+ ];
74
+ const RESERVE_REFERENCE_TABLES = [
75
+ "stake",
76
+ "asset",
77
+ "factory",
78
+ "tokenFactory",
79
+ "token",
80
+ "delegation",
81
+ "rollup",
82
+ "rollupBlock"
83
+ ];
84
+ const ZERO = new _ocap_util.BN(0);
85
+ /**
86
+ * R3 (references): a reserve is never the owner / creator / counterparty of a record. Only NEW references are refused
87
+ * (a record that already named a reserve before the tx can still be updated). `isReserve` is the syntactic role check.
88
+ */
89
+ function assertNoReserveReferences(input) {
90
+ const memo = /* @__PURE__ */ new Map();
91
+ const isReserve = (value) => {
92
+ let hit = memo.get(value);
93
+ if (hit === void 0) {
94
+ hit = input.isReserve(value);
95
+ memo.set(value, hit);
96
+ }
97
+ return hit;
98
+ };
99
+ const names = (value) => {
100
+ if (typeof value === "string") return !!value && isReserve(value);
101
+ if (Array.isArray(value)) return value.some(names);
102
+ if (value && typeof value === "object") return names(value.address);
103
+ return false;
104
+ };
105
+ for (const table of input.tables) {
106
+ const afterMap = input.after.get(table);
107
+ if (!afterMap) continue;
108
+ const beforeMap = input.before.get(table);
109
+ for (const [key, record] of afterMap.entries()) {
110
+ const prior = beforeMap?.get(key) ?? null;
111
+ if ((0, lodash_isEqual.default)(prior, record)) continue;
112
+ for (const field of input.fields) if (names(record[field]) && !names(prior?.[field])) throw input.createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: a bridge reserve can not be ${field} of ${table} ${key}`);
113
+ }
114
+ }
115
+ }
116
+ function assertBridgeReservesV2Protected(input) {
117
+ const { txType, isReserveAddress, before, after, norm, createGateError } = input;
118
+ for (const key of [...input.directBalanceWrites, ...input.writtenBalanceKeys ?? []]) if (isReserveAddress(norm(key))) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: bridge reserve ${key} balance table must not be written directly`);
119
+ assertNoReserveReferences({
120
+ createGateError,
121
+ before,
122
+ after,
123
+ isReserve: (value) => isReserveAddress(norm(value)),
124
+ tables: RESERVE_REFERENCE_TABLES,
125
+ fields: RESERVE_REFERENCE_FIELDS
126
+ });
127
+ const beforeAccounts = before.get("account");
128
+ const afterAccounts = after.get("account") ?? /* @__PURE__ */ new Map();
129
+ const touched = [];
130
+ for (const [key, rec] of afterAccounts.entries()) {
131
+ if (!isReserveAddress(key)) continue;
132
+ const prior = beforeAccounts?.get(key) ?? null;
133
+ if (prior && (0, lodash_isEqual.default)(prior, rec)) continue;
134
+ touched.push({
135
+ key,
136
+ before: prior,
137
+ after: rec
138
+ });
139
+ }
140
+ if (touched.length === 0) return;
141
+ const tokensOf = (rec, label) => input.tokenBalances(rec?.tokens, label);
142
+ const changes = touched.map((t) => {
143
+ const pre = tokensOf(t.before, `before[${t.key}]`);
144
+ const post = tokensOf(t.after, `after[${t.key}]`);
145
+ const debits = [];
146
+ const credits = [];
147
+ for (const tok of new Set([...Object.keys(pre), ...Object.keys(post)])) {
148
+ const a = pre[tok];
149
+ const b = post[tok];
150
+ if (a && b) {
151
+ if (b.lt(a)) debits.push(tok);
152
+ else if (b.gt(a)) credits.push(tok);
153
+ } else if (a) debits.push(tok);
154
+ else if (b) credits.push(tok);
155
+ }
156
+ return {
157
+ ...t,
158
+ pre,
159
+ post,
160
+ debits,
161
+ credits
162
+ };
163
+ });
164
+ const afterRollups = after.get("rollup") ?? /* @__PURE__ */ new Map();
165
+ const beforeRollups = before.get("rollup") ?? /* @__PURE__ */ new Map();
166
+ const reserveOfBridge = (bridge) => norm((0, _arcblock_did_util.toBridgeReserveAddress)(bridge));
167
+ for (const c of changes) {
168
+ if (c.debits.length > 0 && !require_bridge_reserves.BRIDGE_RESERVE_DEBIT_TX_TYPES.includes(txType)) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: bridge reserve ${c.key} was debited in a ${txType || "unknown"} tx (allowed: ${require_bridge_reserves.BRIDGE_RESERVE_DEBIT_TX_TYPES.join(", ")})`);
169
+ if (c.credits.length > 0 && !require_bridge_reserves.BRIDGE_RESERVE_CREDIT_TX_TYPES.includes(txType)) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: bridge reserve ${c.key} was credited in a ${txType || "unknown"} tx (allowed: ${require_bridge_reserves.BRIDGE_RESERVE_CREDIT_TX_TYPES.join(", ")})`);
170
+ if (!c.before && txType !== "create_rollup") throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: bridge reserve ${c.key} can only be materialised by create_rollup, not by a ${txType || "unknown"} tx`);
171
+ if (c.before && !(0, lodash_isEqual.default)(stableFields(c.before), stableFields(c.after))) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: bridge reserve ${c.key} may only change token balances`);
172
+ if (!require_bridge_reserves.BRIDGE_RESERVE_DEBIT_TX_TYPES.includes(txType) && !require_bridge_reserves.BRIDGE_RESERVE_CREDIT_TX_TYPES.includes(txType)) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: bridge reserve ${c.key} can not be written by a ${txType || "unknown"} tx`);
173
+ }
174
+ const legacy = (rec, field) => {
175
+ const v = rec?.[field];
176
+ return v === void 0 || v === null || v === "" ? "0" : String(v);
177
+ };
178
+ for (const c of changes) for (const field of LEGACY_BALANCE_FIELDS) if (legacy(c.after, field) !== legacy(c.before, field)) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: bridge reserve ${c.key} ${field} must not change (${legacy(c.before, field)} -> ${legacy(c.after, field)})`);
179
+ const resolution = input.resolution ?? null;
180
+ const bridgeOf = (key) => resolution?.reserves.get(require_bridge_reserves.bareAddress(key)) ?? null;
181
+ if (txType !== "create_rollup" && txType !== "migrate_rollup") {
182
+ const ledgerRows = txType === require_bridge_reserves.BRIDGE_RELEASE_TX_TYPE && Number(input.releaseKind) === 2 ? new Set([...input.resolution?.release?.debitable.values() ?? []].map((b) => require_bridge_reserves.bareAddress(b.address))) : /* @__PURE__ */ new Set();
183
+ for (const [key, row] of afterRollups.entries()) {
184
+ const prior = beforeRollups.get(key) ?? null;
185
+ if (ledgerRows.has(require_bridge_reserves.bareAddress(key))) continue;
186
+ if (isBridgeV2Row(row) && !(0, lodash_isEqual.default)(prior, row)) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: a ${txType || "unknown"} tx can not move a bridge reserve and write the bridge ${key} in the same tx`);
187
+ }
188
+ }
189
+ if (txType === require_bridge_reserves.BRIDGE_WITHDRAW_TX_TYPE) {
190
+ for (const c of changes) {
191
+ if (c.debits.length > 0 || c.credits.length === 0) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: a withdraw only credits a bridge reserve (${c.key})`);
192
+ if (!input.enabled) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: bridge reserve ${c.key} can not be credited while transaction.bridge.enabled is off`);
193
+ const bridge = bridgeOf(c.key);
194
+ if (!bridge) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: ${c.key} has the bridge reserve role but is not the reserve of any v2 bridge`);
195
+ if (!bridge.acceptingWithdraws) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: bridge ${bridge.address} does not accept withdraws (paused: ${bridge.paused}, closing: ${bridge.closing}, final: ${bridge.final}, migrated: ${bridge.migrated})`);
196
+ const token = norm(bridge.token);
197
+ for (const tok of c.credits) if (!token || tok !== token) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: bridge reserve ${c.key} can only be credited with the bridge token ${token}, not ${tok}`);
198
+ if (input.checkWithdraw) {
199
+ const credited = (c.post[token] ?? ZERO).sub(c.pre[token] ?? ZERO);
200
+ const problem = input.checkWithdraw(bridge, credited);
201
+ if (problem) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: the credit to bridge reserve ${c.key} is not a valid bridge withdraw (${problem})`);
202
+ }
203
+ }
204
+ return;
205
+ }
206
+ if (txType === require_bridge_reserves.BRIDGE_RELEASE_TX_TYPE || require_bridge_reserves.BRIDGE_RECONCILE_TX_TYPES.includes(txType)) {
207
+ const isRelease = txType === require_bridge_reserves.BRIDGE_RELEASE_TX_TYPE;
208
+ if (changes.some((c) => c.credits.length > 0 || c.debits.length === 0)) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: a ${txType} tx only debits a bridge reserve`);
209
+ if (isRelease && !input.enabled) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", "Post-Execution Invariant Gate: a bridge reserve can not be debited while transaction.bridge.enabled is off");
210
+ if (isRelease && changes.length !== 1) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: a release debits exactly one bridge reserve, got ${changes.length}`);
211
+ for (const c of changes) {
212
+ const owner = bridgeOf(c.key);
213
+ if (!owner) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: ${c.key} has the bridge reserve role but is not the reserve of any v2 bridge`);
214
+ if (isRelease) {
215
+ const release = resolution?.release ?? null;
216
+ const allowed = release?.debitable.get(require_bridge_reserves.bareAddress(c.key));
217
+ if (!release || !allowed) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: a release of bridge ${release?.bridge.address ?? "(unknown)"} can not debit reserve ${c.key}, which belongs to bridge ${owner.address}`);
218
+ if (require_bridge_reserves.bareAddress(c.key) !== require_bridge_reserves.bareAddress(release.reserve) && Number(input.releaseKind) !== 2) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: only a REFUND release may debit the reserve of the migratedTo bridge ${owner.address}`);
219
+ }
220
+ const token = norm(owner.token);
221
+ for (const tok of c.debits) if (!token || tok !== token) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: bridge reserve ${c.key} only holds the bridge token ${token}, not ${tok}`);
222
+ }
223
+ return;
224
+ }
225
+ if (txType === "create_rollup") {
226
+ for (const c of changes) {
227
+ if (c.before) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: create_rollup can not change the existing bridge reserve ${c.key}`);
228
+ const bridge = [...afterRollups.entries()].find(([k, row]) => !beforeRollups.get(k) && isBridgeV2Row(row) && reserveOfBridge(String(row.address)) === c.key);
229
+ if (!bridge) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: bridge reserve ${c.key} can only be created together with its v2 bridge`);
230
+ const own = Object.keys(stableFields(c.after)).filter((k) => ![
231
+ "address",
232
+ "moniker",
233
+ "nonce"
234
+ ].includes(k));
235
+ if (own.length > 0 || Number(c.after.nonce ?? 0) !== 0) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: bridge reserve ${c.key} may only hold token balances (unexpected fields: ${own.join(", ") || "nonce"})`);
236
+ const bridgeToken = norm(String(bridge[1].tokenAddress));
237
+ for (const tok of Object.keys(c.post)) if (tok !== bridgeToken) throw createGateError("BRIDGE_RESERVE_CREDIT_FORBIDDEN", `Post-Execution Invariant Gate: bridge reserve ${c.key} can only be funded with the bridge token, not ${tok}`);
238
+ }
239
+ return;
240
+ }
241
+ if (txType === "migrate_rollup") {
242
+ const debited = changes.filter((c) => c.debits.length > 0);
243
+ const credited = changes.filter((c) => c.credits.length > 0);
244
+ if (changes.some((c) => !c.before) || debited.length !== 1 || credited.length !== 1) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", "Post-Execution Invariant Gate: a reserve migration moves one reserve into exactly one other reserve");
245
+ const [from] = debited;
246
+ const [to] = credited;
247
+ if (from.key === to.key || Object.keys(from.post).length > 0 || from.credits.length > 0 || to.debits.length > 0) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", "Post-Execution Invariant Gate: a reserve migration must move the full balance, one way");
248
+ for (const tok of new Set([
249
+ ...Object.keys(from.pre),
250
+ ...Object.keys(to.pre),
251
+ ...Object.keys(to.post)
252
+ ])) {
253
+ const out = from.pre[tok] ?? ZERO;
254
+ if (!(to.post[tok] ?? ZERO).sub(to.pre[tok] ?? ZERO).eq(out)) throw createGateError("BRIDGE_RESERVE_DEBIT_FORBIDDEN", `Post-Execution Invariant Gate: a reserve migration must be zero-sum (token ${tok})`);
255
+ }
256
+ const source = [...afterRollups.entries()].find(([k, row]) => {
257
+ const prior = beforeRollups.get(k);
258
+ return isBridgeV2Row(row) && !!prior && migratedToOf(prior) === null && migratedToOf(row) !== null;
259
+ });
260
+ const migratedTo = source ? migratedToOf(source[1]) : null;
261
+ if (!source || !migratedTo || reserveOfBridge(String(source[1].address)) !== from.key || reserveOfBridge(migratedTo) !== to.key) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", "Post-Execution Invariant Gate: a reserve migration must match the bridge and the migratedTo written in the same tx");
262
+ }
263
+ }
264
+
265
+ //#endregion
266
+ exports.BRIDGE_RESERVE_CREDIT_TX_TYPES = require_bridge_reserves.BRIDGE_RESERVE_CREDIT_TX_TYPES;
267
+ exports.BRIDGE_RESERVE_DEBIT_TX_TYPES = require_bridge_reserves.BRIDGE_RESERVE_DEBIT_TX_TYPES;
268
+ exports.BRIDGE_V2_RESERVE_CREDIT_TX_TYPES = BRIDGE_V2_RESERVE_CREDIT_TX_TYPES;
269
+ exports.BRIDGE_V2_RESERVE_DEBIT_TX_TYPES = BRIDGE_V2_RESERVE_DEBIT_TX_TYPES;
270
+ exports.RESERVE_REFERENCE_FIELDS = RESERVE_REFERENCE_FIELDS;
271
+ exports.RESERVE_REFERENCE_TABLES = RESERVE_REFERENCE_TABLES;
272
+ exports.assertBridgeReservesV2Protected = assertBridgeReservesV2Protected;
273
+ exports.assertNoReserveReferences = assertNoReserveReferences;
@@ -0,0 +1,53 @@
1
+ import { BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BridgeReserveResolution, ResolvedBridge } from "../bridge-reserves.cjs";
2
+ import { BN } from "@ocap/util";
3
+
4
+ //#region src/pipes/bridge-reserve-v2-gate.d.ts
5
+ /** @deprecated use BRIDGE_RESERVE_DEBIT_TX_TYPES */
6
+ declare const BRIDGE_V2_RESERVE_DEBIT_TX_TYPES: readonly string[];
7
+ /** @deprecated use BRIDGE_RESERVE_CREDIT_TX_TYPES */
8
+ declare const BRIDGE_V2_RESERVE_CREDIT_TX_TYPES: readonly string[];
9
+ type Rec = Record<string, unknown>;
10
+ type Before = Map<string, Map<string, Rec | null>>;
11
+ type After = Map<string, Map<string, Rec>>;
12
+ /** Fields that make an account the owner / creator / counterparty of a record in the other tables. */
13
+ declare const RESERVE_REFERENCE_FIELDS: readonly string[];
14
+ declare const RESERVE_REFERENCE_TABLES: readonly string[];
15
+ type Bn = InstanceType<typeof BN>;
16
+ interface BridgeReserveV2GateInput {
17
+ txType: string;
18
+ /** whether a canonical entity key is a ROLE_BRIDGE_RESERVE address */
19
+ isReserveAddress: (key: string) => boolean;
20
+ /** the gate's canonical entity key (DID prefix / checksum insensitive) */
21
+ norm: (raw: unknown) => string;
22
+ /** the gate's error factory */
23
+ createGateError: (code: string, message: string) => Error;
24
+ /** canonical non-negative token balances, positive entries only */
25
+ tokenBalances: (tokens: unknown, label: string) => Record<string, Bn>;
26
+ before: Before;
27
+ after: After;
28
+ directBalanceWrites: string[];
29
+ writtenBalanceKeys: Set<string> | undefined;
30
+ /** `config.transaction.bridge.enabled` (master switch) */
31
+ enabled: boolean;
32
+ /** what `prepareBridgeReserveGate` resolved; absent means "nothing resolves" (fail closed) */
33
+ resolution?: BridgeReserveResolution | null;
34
+ /** `itx.kind` of a release (2 = REFUND may follow the `migratedTo` chain) */
35
+ releaseKind?: unknown;
36
+ /**
37
+ * Defence in depth for R2 (#1465): validates the transaction as a withdraw into `bridge` (shape, range, recipient) and
38
+ * returns a message when it is not, or when the reserve grew by anything other than the withdrawn amount.
39
+ */
40
+ checkWithdraw?: (bridge: ResolvedBridge, credited: Bn) => string | null;
41
+ }
42
+ /**
43
+ * R3 (references): a reserve is never the owner / creator / counterparty of a record. Only NEW references are refused
44
+ * (a record that already named a reserve before the tx can still be updated). `isReserve` is the syntactic role check.
45
+ */
46
+ declare function assertNoReserveReferences(input: Pick<BridgeReserveV2GateInput, 'createGateError' | 'before' | 'after'> & {
47
+ isReserve: (value: string) => boolean;
48
+ tables: readonly string[];
49
+ fields: readonly string[];
50
+ }): void;
51
+ declare function assertBridgeReservesV2Protected(input: BridgeReserveV2GateInput): void;
52
+ //#endregion
53
+ export { BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BRIDGE_V2_RESERVE_CREDIT_TX_TYPES, BRIDGE_V2_RESERVE_DEBIT_TX_TYPES, BridgeReserveV2GateInput, RESERVE_REFERENCE_FIELDS, RESERVE_REFERENCE_TABLES, assertBridgeReservesV2Protected, assertNoReserveReferences };
@@ -87,6 +87,9 @@ function normalizeItx(raw) {
87
87
  }
88
88
  function DecodeItx(context, next) {
89
89
  try {
90
+ context._preFlightWafScanned = false;
91
+ context._preFlightVerified = false;
92
+ context._preFlightSnapshotApplied = false;
90
93
  context._rawTxItxBeforeNormalize = context.tx?.itx;
91
94
  const normalized = normalizeItx(context.tx.itx);
92
95
  if (!normalized) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", "Failed to decode itx"));
@@ -1,5 +1,5 @@
1
- import { CustomError } from "@ocap/util/lib/error";
2
1
  import { ITxOnlyContext } from "@ocap/types";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
3
 
4
4
  //#region src/pipes/decode-itx.d.ts
5
5
  declare function DecodeItx(context: ITxOnlyContext, next: (err?: CustomError) => void): void;
@@ -2,13 +2,14 @@ Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
3
  const require_package = require('../package.cjs');
4
4
  const require_helpers_unwrap_opaque_any = require('../helpers/unwrap-opaque-any.cjs');
5
+ const require_pipes_pre_flight_waf = require('./pre-flight-waf.cjs');
5
6
  let _ocap_mcrypto = require("@ocap/mcrypto");
6
7
  let _ocap_util = require("@ocap/util");
7
8
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
8
9
  let _ocap_message = require("@ocap/message");
10
+ let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
9
11
  let _ocap_message_cbor = require("@ocap/message/cbor");
10
12
  let _ocap_message_protobuf = require("@ocap/message/protobuf");
11
- let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
12
13
  let lodash_cloneDeep = require("lodash/cloneDeep");
13
14
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
14
15
  let lodash_omit = require("lodash/omit");
@@ -71,10 +72,25 @@ function hasCborSelfDescribeTag(buf) {
71
72
  return buf.length >= _ocap_message_cbor.CANONICAL_SELF_DESCRIBE_PREFIX.length && buf[0] === _ocap_message_cbor.CANONICAL_SELF_DESCRIBE_PREFIX[0] && buf[1] === _ocap_message_cbor.CANONICAL_SELF_DESCRIBE_PREFIX[1] && buf[2] === _ocap_message_cbor.CANONICAL_SELF_DESCRIBE_PREFIX[2];
72
73
  }
73
74
  const NON_CANONICAL_MESSAGE = "Transaction encoding is not canonical";
75
+ const TIMESTAMP_OUT_OF_RANGE_MESSAGE = "Transaction contains a timestamp that is out of range";
76
+ const NESTED_UNDECODABLE_MESSAGE = "Transaction contains a nested message that can not be decoded";
77
+ const DECODE_FAILED_MESSAGE = "Can not decode base64 encoded transaction";
74
78
  function DecodeTx(context, next) {
79
+ if (typeof context.txBase64 === "string") try {
80
+ require_pipes_pre_flight_waf.assertWireByteCeiling(context.txBase64, context.config);
81
+ } catch (sizeErr) {
82
+ return next(sizeErr);
83
+ }
75
84
  let nonCanonical = false;
85
+ let timestampOutOfRange = false;
86
+ let nestedUndecodable = false;
76
87
  try {
77
- const txBuffer = (0, _ocap_util.toUint8Array)((0, _ocap_util.fromBase64)(context.txBase64));
88
+ if (typeof context.txBase64 !== "string") throw new _ocap_util_lib_error.CustomError("INVALID_TX", DECODE_FAILED_MESSAGE);
89
+ const rawWire = context.txBase64;
90
+ const txBuffer = (0, _ocap_util.toUint8Array)((0, _ocap_util.fromBase64)(rawWire));
91
+ const stdPadded = Buffer.from(txBuffer).toString("base64");
92
+ const stdUnpadded = stdPadded.replace(/=+$/, "");
93
+ if (!(rawWire === stdPadded || rawWire === stdUnpadded || rawWire === stdUnpadded.replace(/\+/g, "-").replace(/\//g, "_") || rawWire === stdPadded.replace(/\+/g, "-").replace(/\//g, "_"))) throw new _ocap_util_lib_error.CustomError("INVALID_TX", DECODE_FAILED_MESSAGE);
78
94
  const isCbor = hasCborSelfDescribeTag(txBuffer);
79
95
  const tx = isCbor ? (0, _ocap_message_cbor.decodeTx)(txBuffer) : (0, _ocap_message_protobuf.decodeTx)(txBuffer);
80
96
  const reencoded = isCbor ? (0, _ocap_message_cbor.encodeTx)(tx) : (0, _ocap_message_protobuf.encodeTx)(tx);
@@ -82,6 +98,15 @@ function DecodeTx(context, next) {
82
98
  nonCanonical = true;
83
99
  throw new _ocap_util_lib_error.CustomError("INVALID_TX", NON_CANONICAL_MESSAGE);
84
100
  }
101
+ const problem = (0, _ocap_message.findFormatProblem)("Transaction", tx);
102
+ if (problem?.kind === "invalid-timestamp") {
103
+ timestampOutOfRange = true;
104
+ throw new _ocap_util_lib_error.CustomError("INVALID_TX", TIMESTAMP_OUT_OF_RANGE_MESSAGE);
105
+ }
106
+ if (problem?.kind === "unformattable" && !isCbor) {
107
+ nestedUndecodable = true;
108
+ throw new _ocap_util_lib_error.CustomError("INVALID_TX", NESTED_UNDECODABLE_MESSAGE);
109
+ }
85
110
  const unsignedTx = (0, lodash_cloneDeep.default)(tx);
86
111
  unsignedTx.signature = void 0;
87
112
  const sigs = (0, _ocap_util_lib_get_list_field.getListField)(unsignedTx, "signatures");
@@ -114,6 +139,9 @@ function DecodeTx(context, next) {
114
139
  writable: true
115
140
  });
116
141
  context._extraSizeCounted = false;
142
+ context._preFlightWafScanned = false;
143
+ context._preFlightVerified = false;
144
+ context._preFlightSnapshotApplied = false;
117
145
  Object.defineProperty(context, "txHash", {
118
146
  value: (0, _ocap_mcrypto.toTxHash)(txBuffer),
119
147
  enumerable: true,
@@ -142,7 +170,7 @@ function DecodeTx(context, next) {
142
170
  txBase64: context.txBase64,
143
171
  error: err
144
172
  });
145
- return next(new _ocap_util_lib_error.CustomError("INVALID_TX", nonCanonical ? NON_CANONICAL_MESSAGE : "Can not decode base64 encoded transaction"));
173
+ return next(new _ocap_util_lib_error.CustomError("INVALID_TX", nonCanonical ? NON_CANONICAL_MESSAGE : timestampOutOfRange ? TIMESTAMP_OUT_OF_RANGE_MESSAGE : nestedUndecodable ? NESTED_UNDECODABLE_MESSAGE : DECODE_FAILED_MESSAGE));
146
174
  }
147
175
  next();
148
176
  }
@@ -1,5 +1,5 @@
1
- import { CustomError } from "@ocap/util/lib/error";
2
1
  import { IBaseContext } from "@ocap/types";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
3
 
4
4
  //#region src/pipes/decode-tx.d.ts
5
5
  declare function DecodeTx(context: IBaseContext, next: (err?: CustomError) => void): void;
@@ -2,11 +2,11 @@ Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
3
  let _ocap_mcrypto = require("@ocap/mcrypto");
4
4
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
5
+ let _arcblock_did = require("@arcblock/did");
5
6
  let _ocap_state = require("@ocap/state");
6
7
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
7
8
  let lodash_set = require("lodash/set");
8
9
  lodash_set = require_rolldown_runtime.__toESM(lodash_set);
9
- let _arcblock_did = require("@arcblock/did");
10
10
 
11
11
  //#region src/pipes/extract-signer.ts
12
12
  function CreateExtractSignerPipe({ signerKey = "signerStates", delegatorKey = "delegatorStates" } = {}) {
@@ -3,17 +3,17 @@ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
3
  const require_package = require('../package.cjs');
4
4
  let _ocap_mcrypto = require("@ocap/mcrypto");
5
5
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
+ let _arcblock_did = require("@arcblock/did");
6
7
  let _ocap_state = require("@ocap/state");
7
8
  let lodash_get = require("lodash/get");
8
9
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
9
10
  let debug = require("debug");
10
11
  debug = require_rolldown_runtime.__toESM(debug);
11
- let lodash_set = require("lodash/set");
12
- lodash_set = require_rolldown_runtime.__toESM(lodash_set);
13
- let _arcblock_did = require("@arcblock/did");
14
12
  let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
15
13
  let lodash_isEmpty = require("lodash/isEmpty");
16
14
  lodash_isEmpty = require_rolldown_runtime.__toESM(lodash_isEmpty);
15
+ let lodash_set = require("lodash/set");
16
+ lodash_set = require_rolldown_runtime.__toESM(lodash_set);
17
17
 
18
18
  //#region src/pipes/extract-state.ts
19
19
  const debug$1 = (0, debug.default)(`${require_package.name}:pipe:extract-state`);