@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.
- package/esm/bridge-release-keys.d.mts +33 -0
- package/esm/bridge-release-keys.mjs +81 -0
- package/esm/bridge-reserves.d.mts +107 -0
- package/esm/bridge-reserves.mjs +242 -0
- package/esm/helpers/bridge-withdraw.d.mts +86 -0
- package/esm/helpers/bridge-withdraw.mjs +123 -0
- package/esm/helpers/replay-guard.d.mts +19 -1
- package/esm/helpers/replay-guard.mjs +39 -1
- package/esm/index.d.mts +3 -1
- package/esm/index.mjs +8 -6
- package/esm/legacy-protocol-sunset.d.mts +2 -2
- package/esm/legacy-protocol-sunset.mjs +5 -5
- package/esm/legacy-rollup-archive.d.mts +67 -0
- package/esm/legacy-rollup-archive.mjs +199 -0
- package/esm/library.d.mts +4 -4
- package/esm/library.mjs +3 -3
- package/esm/native-abt-exchange.d.mts +3 -0
- package/esm/native-abt-exchange.mjs +93 -46
- package/esm/pipes/bridge-release-gate.d.mts +30 -0
- package/esm/pipes/bridge-release-gate.mjs +143 -0
- package/esm/pipes/bridge-reserve-v2-gate.d.mts +53 -0
- package/esm/pipes/bridge-reserve-v2-gate.mjs +264 -0
- package/esm/pipes/decode-itx.mjs +3 -0
- package/esm/pipes/decode-tx.mjs +32 -4
- package/esm/pipes/extract-signer.mjs +1 -1
- package/esm/pipes/extract-state.mjs +2 -2
- package/esm/pipes/post-execution-invariant-gate.d.mts +19 -2
- package/esm/pipes/post-execution-invariant-gate.mjs +121 -6
- package/esm/pipes/pre-flight-waf.d.mts +58 -2
- package/esm/pipes/pre-flight-waf.mjs +202 -14
- package/esm/pipes/update-owner.mjs +1 -1
- package/esm/pipes/verify-account-migration.mjs +1 -1
- package/esm/pipes/verify-delegation.mjs +49 -25
- package/esm/pipes/verify-multisig-v2.mjs +5 -4
- package/esm/pipes/verify-multisig.mjs +5 -4
- package/esm/pipes/verify-signature.d.mts +7 -1
- package/esm/pipes/verify-signature.mjs +119 -16
- package/esm/pipes/verify-signer.mjs +2 -2
- package/esm/pipes/verify-token-access.mjs +1 -1
- package/esm/pipes/verify-token-balance.mjs +1 -1
- package/esm/pipes/verify-tx-input.mjs +1 -1
- package/esm/pipes/verify-tx-size.mjs +1 -1
- package/esm/pipes/verify-tx.mjs +12 -5
- package/esm/super-suites-foundation.mjs +6 -6
- package/esm/transaction-block.d.mts +6 -2
- package/esm/transaction-block.mjs +282 -40
- package/esm/uniswap-router.d.mts +247 -1
- package/esm/uniswap-router.mjs +573 -2
- package/lib/bridge-release-keys.cjs +88 -0
- package/lib/bridge-release-keys.d.cts +33 -0
- package/lib/bridge-reserves.cjs +257 -0
- package/lib/bridge-reserves.d.cts +107 -0
- package/lib/helpers/bridge-withdraw.cjs +136 -0
- package/lib/helpers/bridge-withdraw.d.cts +86 -0
- package/lib/helpers/replay-guard.cjs +39 -0
- package/lib/helpers/replay-guard.d.cts +20 -2
- package/lib/index.cjs +25 -5
- package/lib/index.d.cts +3 -1
- package/lib/legacy-protocol-sunset.cjs +7 -7
- package/lib/legacy-protocol-sunset.d.cts +2 -2
- package/lib/legacy-rollup-archive.cjs +208 -0
- package/lib/legacy-rollup-archive.d.cts +67 -0
- package/lib/library.cjs +14 -68
- package/lib/library.d.cts +4 -4
- package/lib/native-abt-exchange.cjs +93 -46
- package/lib/native-abt-exchange.d.cts +3 -0
- package/lib/pipes/bridge-release-gate.cjs +145 -0
- package/lib/pipes/bridge-release-gate.d.cts +30 -0
- package/lib/pipes/bridge-reserve-v2-gate.cjs +273 -0
- package/lib/pipes/bridge-reserve-v2-gate.d.cts +53 -0
- package/lib/pipes/decode-itx.cjs +3 -0
- package/lib/pipes/decode-itx.d.cts +1 -1
- package/lib/pipes/decode-tx.cjs +31 -3
- package/lib/pipes/decode-tx.d.cts +1 -1
- package/lib/pipes/extract-signer.cjs +1 -1
- package/lib/pipes/extract-state.cjs +3 -3
- package/lib/pipes/post-execution-invariant-gate.cjs +121 -4
- package/lib/pipes/post-execution-invariant-gate.d.cts +19 -2
- package/lib/pipes/pre-flight-waf.cjs +209 -15
- package/lib/pipes/pre-flight-waf.d.cts +58 -2
- package/lib/pipes/update-owner.cjs +1 -1
- package/lib/pipes/update-owner.d.cts +1 -1
- package/lib/pipes/verify-account-migration.cjs +1 -1
- package/lib/pipes/verify-delegation.cjs +50 -26
- package/lib/pipes/verify-multisig-v2.cjs +5 -4
- package/lib/pipes/verify-multisig.cjs +5 -4
- package/lib/pipes/verify-service-fee.d.cts +1 -1
- package/lib/pipes/verify-signature.cjs +118 -14
- package/lib/pipes/verify-signature.d.cts +8 -2
- package/lib/pipes/verify-signer.cjs +2 -2
- package/lib/pipes/verify-token-access.cjs +1 -1
- package/lib/pipes/verify-token-balance.cjs +1 -1
- package/lib/pipes/verify-tx-input.cjs +1 -1
- package/lib/pipes/verify-tx-size.cjs +1 -1
- package/lib/pipes/verify-tx-size.d.cts +1 -1
- package/lib/pipes/verify-tx.cjs +11 -5
- package/lib/pipes/verify-tx.d.cts +1 -1
- package/lib/super-suites-foundation.cjs +6 -6
- package/lib/transaction-block.cjs +282 -40
- package/lib/transaction-block.d.cts +6 -2
- package/lib/uniswap-router.cjs +576 -1
- package/lib/uniswap-router.d.cts +247 -1
- package/package.json +10 -10
- package/esm/evm-simplified-bridge.d.mts +0 -1370
- package/esm/evm-simplified-bridge.mjs +0 -3875
- package/lib/evm-simplified-bridge.cjs +0 -3943
- package/lib/evm-simplified-bridge.d.cts +0 -1370
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RELEASE_TX_TYPE, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BRIDGE_WITHDRAW_TX_TYPE, bareAddress } from "../bridge-reserves.mjs";
|
|
2
|
+
import { BN } from "@ocap/util";
|
|
3
|
+
import { toBridgeReserveAddress } from "@arcblock/did-util";
|
|
4
|
+
import isEqual from "lodash/isEqual.js";
|
|
5
|
+
|
|
6
|
+
//#region src/pipes/bridge-reserve-v2-gate.ts
|
|
7
|
+
/**
|
|
8
|
+
* Gate rules R1-R5 for the per-bridge reserves (`ROLE_BRIDGE_RESERVE`, bridge/docs/ocap-protocols.md §v2.3, §1).
|
|
9
|
+
*
|
|
10
|
+
* Every account whose DID role is `ROLE_BRIDGE_RESERVE` is a reserve, recognised syntactically (no state scan). Which
|
|
11
|
+
* bridge a reserve belongs to comes from the `reserve -> bridge` index, resolved once per transaction by
|
|
12
|
+
* `prepareBridgeReserveGate` before this synchronous check runs (`bridge-reserves.ts`); the address is never trusted.
|
|
13
|
+
*
|
|
14
|
+
* - R1 debits: `release_bridge_token` of THAT bridge (the reserve of `itx.bridge`, or of its `migratedTo` chain for a
|
|
15
|
+
* REFUND), `migrate_rollup`, and the reconcile hook (a named, empty list today). The master switch
|
|
16
|
+
* `transaction.bridge.enabled` must be on for a release.
|
|
17
|
+
* - R2 credits: `transfer_v2` (the withdraw) into the reserve of a live, unpaused, not-closing bridge with the master
|
|
18
|
+
* switch on, in the bridge token only; `create_rollup` funding the reserve of the bridge it creates;
|
|
19
|
+
* `migrate_rollup` filling the successor's reserve. A role-25 address that maps to no bridge accepts nothing.
|
|
20
|
+
* - R3: a reserve account is only materialised by `create_rollup`, only token balances ever change, nothing writes the
|
|
21
|
+
* `balance` table directly, and no record of another table gains a reference to a reserve.
|
|
22
|
+
* - R4 (release accounting) lives in bridge-release-gate.ts (#1466). The gate
|
|
23
|
+
* guarantees the part that protects other bridges: a release debits exactly one reserve, the right one.
|
|
24
|
+
* - R5 is the early rejection in `@ocap/tx-protocols` (`bridge-reserve.ts`).
|
|
25
|
+
*/
|
|
26
|
+
/** @deprecated use BRIDGE_RESERVE_DEBIT_TX_TYPES */
|
|
27
|
+
const BRIDGE_V2_RESERVE_DEBIT_TX_TYPES = BRIDGE_RESERVE_DEBIT_TX_TYPES;
|
|
28
|
+
/** @deprecated use BRIDGE_RESERVE_CREDIT_TX_TYPES */
|
|
29
|
+
const BRIDGE_V2_RESERVE_CREDIT_TX_TYPES = BRIDGE_RESERVE_CREDIT_TX_TYPES;
|
|
30
|
+
const isBridgeV2Row = (row) => !!row && row.data?.value?.version === 2;
|
|
31
|
+
const migratedToOf = (row) => {
|
|
32
|
+
const v = (row?.data)?.value?.migratedTo;
|
|
33
|
+
return typeof v === "string" && v ? v : null;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* `balance` / `balanceNum` are the legacy fields that real account rows carry (kept on purpose, they stay at their
|
|
37
|
+
* default). They are not "other state" of the reserve, but no tx may change them: see the check in
|
|
38
|
+
* `assertBridgeReservesV2Protected`.
|
|
39
|
+
*/
|
|
40
|
+
const LEGACY_BALANCE_FIELDS = new Set(["balance", "balanceNum"]);
|
|
41
|
+
/** Account fields other than balances; empty values and the context are ignored. */
|
|
42
|
+
const stableFields = (account) => {
|
|
43
|
+
const out = {};
|
|
44
|
+
for (const [k, v] of Object.entries(account || {})) {
|
|
45
|
+
if (LEGACY_BALANCE_FIELDS.has(k)) continue;
|
|
46
|
+
if (k === "tokens" || k === "context" || k === "meta" || k === "$loki" || k.startsWith("_")) continue;
|
|
47
|
+
if (v === void 0 || v === null || v === "" || Array.isArray(v) && v.length === 0) continue;
|
|
48
|
+
out[k] = v;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
};
|
|
52
|
+
/** Fields that make an account the owner / creator / counterparty of a record in the other tables. */
|
|
53
|
+
const RESERVE_REFERENCE_FIELDS = [
|
|
54
|
+
"owner",
|
|
55
|
+
"issuer",
|
|
56
|
+
"creator",
|
|
57
|
+
"sender",
|
|
58
|
+
"receiver",
|
|
59
|
+
"from",
|
|
60
|
+
"to",
|
|
61
|
+
"delegator",
|
|
62
|
+
"vaultAddress",
|
|
63
|
+
"proposer",
|
|
64
|
+
"publisher",
|
|
65
|
+
"seedValidators",
|
|
66
|
+
"validators",
|
|
67
|
+
"spenders",
|
|
68
|
+
"minters",
|
|
69
|
+
"slashers",
|
|
70
|
+
"trustedIssuers"
|
|
71
|
+
];
|
|
72
|
+
const RESERVE_REFERENCE_TABLES = [
|
|
73
|
+
"stake",
|
|
74
|
+
"asset",
|
|
75
|
+
"factory",
|
|
76
|
+
"tokenFactory",
|
|
77
|
+
"token",
|
|
78
|
+
"delegation",
|
|
79
|
+
"rollup",
|
|
80
|
+
"rollupBlock"
|
|
81
|
+
];
|
|
82
|
+
const ZERO = new BN(0);
|
|
83
|
+
/**
|
|
84
|
+
* R3 (references): a reserve is never the owner / creator / counterparty of a record. Only NEW references are refused
|
|
85
|
+
* (a record that already named a reserve before the tx can still be updated). `isReserve` is the syntactic role check.
|
|
86
|
+
*/
|
|
87
|
+
function assertNoReserveReferences(input) {
|
|
88
|
+
const memo = /* @__PURE__ */ new Map();
|
|
89
|
+
const isReserve = (value) => {
|
|
90
|
+
let hit = memo.get(value);
|
|
91
|
+
if (hit === void 0) {
|
|
92
|
+
hit = input.isReserve(value);
|
|
93
|
+
memo.set(value, hit);
|
|
94
|
+
}
|
|
95
|
+
return hit;
|
|
96
|
+
};
|
|
97
|
+
const names = (value) => {
|
|
98
|
+
if (typeof value === "string") return !!value && isReserve(value);
|
|
99
|
+
if (Array.isArray(value)) return value.some(names);
|
|
100
|
+
if (value && typeof value === "object") return names(value.address);
|
|
101
|
+
return false;
|
|
102
|
+
};
|
|
103
|
+
for (const table of input.tables) {
|
|
104
|
+
const afterMap = input.after.get(table);
|
|
105
|
+
if (!afterMap) continue;
|
|
106
|
+
const beforeMap = input.before.get(table);
|
|
107
|
+
for (const [key, record] of afterMap.entries()) {
|
|
108
|
+
const prior = beforeMap?.get(key) ?? null;
|
|
109
|
+
if (isEqual(prior, record)) continue;
|
|
110
|
+
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}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function assertBridgeReservesV2Protected(input) {
|
|
115
|
+
const { txType, isReserveAddress, before, after, norm, createGateError } = input;
|
|
116
|
+
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`);
|
|
117
|
+
assertNoReserveReferences({
|
|
118
|
+
createGateError,
|
|
119
|
+
before,
|
|
120
|
+
after,
|
|
121
|
+
isReserve: (value) => isReserveAddress(norm(value)),
|
|
122
|
+
tables: RESERVE_REFERENCE_TABLES,
|
|
123
|
+
fields: RESERVE_REFERENCE_FIELDS
|
|
124
|
+
});
|
|
125
|
+
const beforeAccounts = before.get("account");
|
|
126
|
+
const afterAccounts = after.get("account") ?? /* @__PURE__ */ new Map();
|
|
127
|
+
const touched = [];
|
|
128
|
+
for (const [key, rec] of afterAccounts.entries()) {
|
|
129
|
+
if (!isReserveAddress(key)) continue;
|
|
130
|
+
const prior = beforeAccounts?.get(key) ?? null;
|
|
131
|
+
if (prior && isEqual(prior, rec)) continue;
|
|
132
|
+
touched.push({
|
|
133
|
+
key,
|
|
134
|
+
before: prior,
|
|
135
|
+
after: rec
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
if (touched.length === 0) return;
|
|
139
|
+
const tokensOf = (rec, label) => input.tokenBalances(rec?.tokens, label);
|
|
140
|
+
const changes = touched.map((t) => {
|
|
141
|
+
const pre = tokensOf(t.before, `before[${t.key}]`);
|
|
142
|
+
const post = tokensOf(t.after, `after[${t.key}]`);
|
|
143
|
+
const debits = [];
|
|
144
|
+
const credits = [];
|
|
145
|
+
for (const tok of new Set([...Object.keys(pre), ...Object.keys(post)])) {
|
|
146
|
+
const a = pre[tok];
|
|
147
|
+
const b = post[tok];
|
|
148
|
+
if (a && b) {
|
|
149
|
+
if (b.lt(a)) debits.push(tok);
|
|
150
|
+
else if (b.gt(a)) credits.push(tok);
|
|
151
|
+
} else if (a) debits.push(tok);
|
|
152
|
+
else if (b) credits.push(tok);
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
...t,
|
|
156
|
+
pre,
|
|
157
|
+
post,
|
|
158
|
+
debits,
|
|
159
|
+
credits
|
|
160
|
+
};
|
|
161
|
+
});
|
|
162
|
+
const afterRollups = after.get("rollup") ?? /* @__PURE__ */ new Map();
|
|
163
|
+
const beforeRollups = before.get("rollup") ?? /* @__PURE__ */ new Map();
|
|
164
|
+
const reserveOfBridge = (bridge) => norm(toBridgeReserveAddress(bridge));
|
|
165
|
+
for (const c of changes) {
|
|
166
|
+
if (c.debits.length > 0 && !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: ${BRIDGE_RESERVE_DEBIT_TX_TYPES.join(", ")})`);
|
|
167
|
+
if (c.credits.length > 0 && !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: ${BRIDGE_RESERVE_CREDIT_TX_TYPES.join(", ")})`);
|
|
168
|
+
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`);
|
|
169
|
+
if (c.before && !isEqual(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`);
|
|
170
|
+
if (!BRIDGE_RESERVE_DEBIT_TX_TYPES.includes(txType) && !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`);
|
|
171
|
+
}
|
|
172
|
+
const legacy = (rec, field) => {
|
|
173
|
+
const v = rec?.[field];
|
|
174
|
+
return v === void 0 || v === null || v === "" ? "0" : String(v);
|
|
175
|
+
};
|
|
176
|
+
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)})`);
|
|
177
|
+
const resolution = input.resolution ?? null;
|
|
178
|
+
const bridgeOf = (key) => resolution?.reserves.get(bareAddress(key)) ?? null;
|
|
179
|
+
if (txType !== "create_rollup" && txType !== "migrate_rollup") {
|
|
180
|
+
const ledgerRows = txType === BRIDGE_RELEASE_TX_TYPE && Number(input.releaseKind) === 2 ? new Set([...input.resolution?.release?.debitable.values() ?? []].map((b) => bareAddress(b.address))) : /* @__PURE__ */ new Set();
|
|
181
|
+
for (const [key, row] of afterRollups.entries()) {
|
|
182
|
+
const prior = beforeRollups.get(key) ?? null;
|
|
183
|
+
if (ledgerRows.has(bareAddress(key))) continue;
|
|
184
|
+
if (isBridgeV2Row(row) && !isEqual(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`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (txType === BRIDGE_WITHDRAW_TX_TYPE) {
|
|
188
|
+
for (const c of changes) {
|
|
189
|
+
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})`);
|
|
190
|
+
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`);
|
|
191
|
+
const bridge = bridgeOf(c.key);
|
|
192
|
+
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`);
|
|
193
|
+
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})`);
|
|
194
|
+
const token = norm(bridge.token);
|
|
195
|
+
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}`);
|
|
196
|
+
if (input.checkWithdraw) {
|
|
197
|
+
const credited = (c.post[token] ?? ZERO).sub(c.pre[token] ?? ZERO);
|
|
198
|
+
const problem = input.checkWithdraw(bridge, credited);
|
|
199
|
+
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})`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (txType === BRIDGE_RELEASE_TX_TYPE || BRIDGE_RECONCILE_TX_TYPES.includes(txType)) {
|
|
205
|
+
const isRelease = txType === BRIDGE_RELEASE_TX_TYPE;
|
|
206
|
+
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`);
|
|
207
|
+
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");
|
|
208
|
+
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}`);
|
|
209
|
+
for (const c of changes) {
|
|
210
|
+
const owner = bridgeOf(c.key);
|
|
211
|
+
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`);
|
|
212
|
+
if (isRelease) {
|
|
213
|
+
const release = resolution?.release ?? null;
|
|
214
|
+
const allowed = release?.debitable.get(bareAddress(c.key));
|
|
215
|
+
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}`);
|
|
216
|
+
if (bareAddress(c.key) !== 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}`);
|
|
217
|
+
}
|
|
218
|
+
const token = norm(owner.token);
|
|
219
|
+
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}`);
|
|
220
|
+
}
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (txType === "create_rollup") {
|
|
224
|
+
for (const c of changes) {
|
|
225
|
+
if (c.before) throw createGateError("BRIDGE_RESERVE_STATE_VIOLATION", `Post-Execution Invariant Gate: create_rollup can not change the existing bridge reserve ${c.key}`);
|
|
226
|
+
const bridge = [...afterRollups.entries()].find(([k, row]) => !beforeRollups.get(k) && isBridgeV2Row(row) && reserveOfBridge(String(row.address)) === c.key);
|
|
227
|
+
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`);
|
|
228
|
+
const own = Object.keys(stableFields(c.after)).filter((k) => ![
|
|
229
|
+
"address",
|
|
230
|
+
"moniker",
|
|
231
|
+
"nonce"
|
|
232
|
+
].includes(k));
|
|
233
|
+
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"})`);
|
|
234
|
+
const bridgeToken = norm(String(bridge[1].tokenAddress));
|
|
235
|
+
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}`);
|
|
236
|
+
}
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (txType === "migrate_rollup") {
|
|
240
|
+
const debited = changes.filter((c) => c.debits.length > 0);
|
|
241
|
+
const credited = changes.filter((c) => c.credits.length > 0);
|
|
242
|
+
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");
|
|
243
|
+
const [from] = debited;
|
|
244
|
+
const [to] = credited;
|
|
245
|
+
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");
|
|
246
|
+
for (const tok of new Set([
|
|
247
|
+
...Object.keys(from.pre),
|
|
248
|
+
...Object.keys(to.pre),
|
|
249
|
+
...Object.keys(to.post)
|
|
250
|
+
])) {
|
|
251
|
+
const out = from.pre[tok] ?? ZERO;
|
|
252
|
+
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})`);
|
|
253
|
+
}
|
|
254
|
+
const source = [...afterRollups.entries()].find(([k, row]) => {
|
|
255
|
+
const prior = beforeRollups.get(k);
|
|
256
|
+
return isBridgeV2Row(row) && !!prior && migratedToOf(prior) === null && migratedToOf(row) !== null;
|
|
257
|
+
});
|
|
258
|
+
const migratedTo = source ? migratedToOf(source[1]) : null;
|
|
259
|
+
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");
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
//#endregion
|
|
264
|
+
export { BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BRIDGE_V2_RESERVE_CREDIT_TX_TYPES, BRIDGE_V2_RESERVE_DEBIT_TX_TYPES, RESERVE_REFERENCE_FIELDS, RESERVE_REFERENCE_TABLES, assertBridgeReservesV2Protected, assertNoReserveReferences };
|
package/esm/pipes/decode-itx.mjs
CHANGED
|
@@ -85,6 +85,9 @@ function normalizeItx(raw) {
|
|
|
85
85
|
}
|
|
86
86
|
function DecodeItx(context, next) {
|
|
87
87
|
try {
|
|
88
|
+
context._preFlightWafScanned = false;
|
|
89
|
+
context._preFlightVerified = false;
|
|
90
|
+
context._preFlightSnapshotApplied = false;
|
|
88
91
|
context._rawTxItxBeforeNormalize = context.tx?.itx;
|
|
89
92
|
const normalized = normalizeItx(context.tx.itx);
|
|
90
93
|
if (!normalized) return next(new CustomError("INVALID_TX", "Failed to decode itx"));
|
package/esm/pipes/decode-tx.mjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { name } from "../package.mjs";
|
|
2
2
|
import { unwrapOpaqueAnyData } from "../helpers/unwrap-opaque-any.mjs";
|
|
3
|
+
import { assertWireByteCeiling } from "./pre-flight-waf.mjs";
|
|
3
4
|
import { toTxHash } from "@ocap/mcrypto";
|
|
4
5
|
import { fromBase64, toUint8Array } from "@ocap/util";
|
|
5
6
|
import { CustomError } from "@ocap/util/lib/error";
|
|
6
|
-
import { decodeAny, encodeAny } from "@ocap/message";
|
|
7
|
+
import { decodeAny, encodeAny, findFormatProblem } from "@ocap/message";
|
|
8
|
+
import { getListField, setListField } from "@ocap/util/lib/get-list-field";
|
|
7
9
|
import { CANONICAL_SELF_DESCRIBE_PREFIX, decodeTx, encodeTx } from "@ocap/message/cbor";
|
|
8
10
|
import { decodeTx as decodeTx$1, encodeTx as encodeTx$1 } from "@ocap/message/protobuf";
|
|
9
|
-
import { getListField, setListField } from "@ocap/util/lib/get-list-field";
|
|
10
11
|
import cloneDeep from "lodash/cloneDeep.js";
|
|
11
12
|
import omit from "lodash/omit.js";
|
|
12
13
|
import Debug from "debug";
|
|
@@ -66,10 +67,25 @@ function hasCborSelfDescribeTag(buf) {
|
|
|
66
67
|
return buf.length >= CANONICAL_SELF_DESCRIBE_PREFIX.length && buf[0] === CANONICAL_SELF_DESCRIBE_PREFIX[0] && buf[1] === CANONICAL_SELF_DESCRIBE_PREFIX[1] && buf[2] === CANONICAL_SELF_DESCRIBE_PREFIX[2];
|
|
67
68
|
}
|
|
68
69
|
const NON_CANONICAL_MESSAGE = "Transaction encoding is not canonical";
|
|
70
|
+
const TIMESTAMP_OUT_OF_RANGE_MESSAGE = "Transaction contains a timestamp that is out of range";
|
|
71
|
+
const NESTED_UNDECODABLE_MESSAGE = "Transaction contains a nested message that can not be decoded";
|
|
72
|
+
const DECODE_FAILED_MESSAGE = "Can not decode base64 encoded transaction";
|
|
69
73
|
function DecodeTx(context, next) {
|
|
74
|
+
if (typeof context.txBase64 === "string") try {
|
|
75
|
+
assertWireByteCeiling(context.txBase64, context.config);
|
|
76
|
+
} catch (sizeErr) {
|
|
77
|
+
return next(sizeErr);
|
|
78
|
+
}
|
|
70
79
|
let nonCanonical = false;
|
|
80
|
+
let timestampOutOfRange = false;
|
|
81
|
+
let nestedUndecodable = false;
|
|
71
82
|
try {
|
|
72
|
-
|
|
83
|
+
if (typeof context.txBase64 !== "string") throw new CustomError("INVALID_TX", DECODE_FAILED_MESSAGE);
|
|
84
|
+
const rawWire = context.txBase64;
|
|
85
|
+
const txBuffer = toUint8Array(fromBase64(rawWire));
|
|
86
|
+
const stdPadded = Buffer.from(txBuffer).toString("base64");
|
|
87
|
+
const stdUnpadded = stdPadded.replace(/=+$/, "");
|
|
88
|
+
if (!(rawWire === stdPadded || rawWire === stdUnpadded || rawWire === stdUnpadded.replace(/\+/g, "-").replace(/\//g, "_") || rawWire === stdPadded.replace(/\+/g, "-").replace(/\//g, "_"))) throw new CustomError("INVALID_TX", DECODE_FAILED_MESSAGE);
|
|
73
89
|
const isCbor = hasCborSelfDescribeTag(txBuffer);
|
|
74
90
|
const tx = isCbor ? decodeTx(txBuffer) : decodeTx$1(txBuffer);
|
|
75
91
|
const reencoded = isCbor ? encodeTx(tx) : encodeTx$1(tx);
|
|
@@ -77,6 +93,15 @@ function DecodeTx(context, next) {
|
|
|
77
93
|
nonCanonical = true;
|
|
78
94
|
throw new CustomError("INVALID_TX", NON_CANONICAL_MESSAGE);
|
|
79
95
|
}
|
|
96
|
+
const problem = findFormatProblem("Transaction", tx);
|
|
97
|
+
if (problem?.kind === "invalid-timestamp") {
|
|
98
|
+
timestampOutOfRange = true;
|
|
99
|
+
throw new CustomError("INVALID_TX", TIMESTAMP_OUT_OF_RANGE_MESSAGE);
|
|
100
|
+
}
|
|
101
|
+
if (problem?.kind === "unformattable" && !isCbor) {
|
|
102
|
+
nestedUndecodable = true;
|
|
103
|
+
throw new CustomError("INVALID_TX", NESTED_UNDECODABLE_MESSAGE);
|
|
104
|
+
}
|
|
80
105
|
const unsignedTx = cloneDeep(tx);
|
|
81
106
|
unsignedTx.signature = void 0;
|
|
82
107
|
const sigs = getListField(unsignedTx, "signatures");
|
|
@@ -109,6 +134,9 @@ function DecodeTx(context, next) {
|
|
|
109
134
|
writable: true
|
|
110
135
|
});
|
|
111
136
|
context._extraSizeCounted = false;
|
|
137
|
+
context._preFlightWafScanned = false;
|
|
138
|
+
context._preFlightVerified = false;
|
|
139
|
+
context._preFlightSnapshotApplied = false;
|
|
112
140
|
Object.defineProperty(context, "txHash", {
|
|
113
141
|
value: toTxHash(txBuffer),
|
|
114
142
|
enumerable: true,
|
|
@@ -137,7 +165,7 @@ function DecodeTx(context, next) {
|
|
|
137
165
|
txBase64: context.txBase64,
|
|
138
166
|
error: err
|
|
139
167
|
});
|
|
140
|
-
return next(new CustomError("INVALID_TX", nonCanonical ? NON_CANONICAL_MESSAGE :
|
|
168
|
+
return next(new CustomError("INVALID_TX", nonCanonical ? NON_CANONICAL_MESSAGE : timestampOutOfRange ? TIMESTAMP_OUT_OF_RANGE_MESSAGE : nestedUndecodable ? NESTED_UNDECODABLE_MESSAGE : DECODE_FAILED_MESSAGE));
|
|
141
169
|
}
|
|
142
170
|
next();
|
|
143
171
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { types } from "@ocap/mcrypto";
|
|
2
2
|
import { CustomError } from "@ocap/util/lib/error";
|
|
3
|
+
import { toTypeInfo } from "@arcblock/did";
|
|
3
4
|
import { account } from "@ocap/state";
|
|
4
5
|
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
5
6
|
import set from "lodash/set.js";
|
|
6
|
-
import { toTypeInfo } from "@arcblock/did";
|
|
7
7
|
|
|
8
8
|
//#region src/pipes/extract-signer.ts
|
|
9
9
|
function CreateExtractSignerPipe({ signerKey = "signerStates", delegatorKey = "delegatorStates" } = {}) {
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { name } from "../package.mjs";
|
|
2
2
|
import { types } from "@ocap/mcrypto";
|
|
3
3
|
import { CustomError } from "@ocap/util/lib/error";
|
|
4
|
+
import { toTypeInfo, toTypeInfoStr } from "@arcblock/did";
|
|
4
5
|
import { account, tables } from "@ocap/state";
|
|
5
6
|
import get from "lodash/get.js";
|
|
6
7
|
import Debug from "debug";
|
|
7
|
-
import set from "lodash/set.js";
|
|
8
|
-
import { toTypeInfo, toTypeInfoStr } from "@arcblock/did";
|
|
9
8
|
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
10
9
|
import isEmpty from "lodash/isEmpty.js";
|
|
10
|
+
import set from "lodash/set.js";
|
|
11
11
|
|
|
12
12
|
//#region src/pipes/extract-state.ts
|
|
13
13
|
const debug = Debug(`${name}:pipe:extract-state`);
|
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
import { PipeFunction } from "../runner.mjs";
|
|
2
|
-
import { IBaseContext, IReadyContext } from "@ocap/types";
|
|
2
|
+
import { IBaseContext, IReadyContext, IStakeState, ITokenFactoryState, ITokenState } from "@ocap/types";
|
|
3
3
|
|
|
4
4
|
//#region src/pipes/post-execution-invariant-gate.d.ts
|
|
5
5
|
declare const MAX_POST_EXECUTION_WRITE_SET_ENTRIES = 256;
|
|
6
6
|
declare const TRACKED_STATE_TABLES: readonly ["account", "stake", "token", "tokenFactory", "asset", "factory", "delegation", "rollup", "rollupBlock", "evidence", "balance"];
|
|
7
7
|
type TrackedStateTable = (typeof TRACKED_STATE_TABLES)[number];
|
|
8
|
+
/**
|
|
9
|
+
* Whether `stake` is a Stake-for-Token of `token`: staked on the official token under the token's symbol as nonce
|
|
10
|
+
* (`toStakeAddress(sender, config.token.address, symbol)`, see `create_token_factory`). Any account can hold such a
|
|
11
|
+
* stake for a symbol; who may use it is decided by the caller (#1422).
|
|
12
|
+
*/
|
|
13
|
+
declare function isTokenIssuanceStakeOf(stake: Partial<IStakeState> | null | undefined, token: Partial<ITokenState> | null | undefined, officialTokenAddress: string): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Whether the token behind `factory` has been 100% redeemed: token and factory point at each other, nothing is in
|
|
16
|
+
* circulation (`totalSupply`, `currentSupply`) and no reserve is left in the curve (`reserveBalance`).
|
|
17
|
+
*/
|
|
18
|
+
declare function isTokenFullyRedeemed(token: Partial<ITokenState> | null | undefined, factory: Partial<ITokenFactoryState> | null | undefined): boolean;
|
|
8
19
|
interface IStateWriteTracker {
|
|
9
20
|
beforeStates: Map<TrackedStateTable, Map<string, Record<string, unknown> | null>>;
|
|
10
21
|
afterStates: Map<TrackedStateTable, Map<string, Record<string, unknown>>>;
|
|
@@ -12,6 +23,12 @@ interface IStateWriteTracker {
|
|
|
12
23
|
addressAliases: Map<string, string>;
|
|
13
24
|
totalWriteOps: number;
|
|
14
25
|
unauthorizedDeletions: number;
|
|
26
|
+
/**
|
|
27
|
+
* Addresses passed to `statedb.balance.updateBalance(...)` through the interceptor. Account, stake and factory
|
|
28
|
+
* tables sync the `balance` table internally (not through the proxy), so any entry here is a direct write that
|
|
29
|
+
* bypasses the `account.tokens` representation (#1464 R1/R2).
|
|
30
|
+
*/
|
|
31
|
+
directBalanceWrites: string[];
|
|
15
32
|
}
|
|
16
33
|
/**
|
|
17
34
|
* Canonicalizes a DID or hex address key so that `did:abt:` prefixes and
|
|
@@ -58,4 +75,4 @@ declare function inspectPostExecutionInvariants(context: IBaseContext): void;
|
|
|
58
75
|
*/
|
|
59
76
|
declare function CreatePostExecutionInvariantGatePipe<TContext extends IReadyContext = IReadyContext>(): PipeFunction<TContext>;
|
|
60
77
|
//#endregion
|
|
61
|
-
export { CreatePostExecutionInvariantGatePipe, CreatePostExecutionInvariantGatePipe as default, IStateWriteTracker, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, TRACKED_STATE_TABLES, TrackedStateTable, inspectPostExecutionInvariants, installStateWriteInterceptor, normalizeEntityKey, rollbackTrackedStateWrites };
|
|
78
|
+
export { CreatePostExecutionInvariantGatePipe, CreatePostExecutionInvariantGatePipe as default, IStateWriteTracker, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, TRACKED_STATE_TABLES, TrackedStateTable, inspectPostExecutionInvariants, installStateWriteInterceptor, isTokenFullyRedeemed, isTokenIssuanceStakeOf, normalizeEntityKey, rollbackTrackedStateWrites };
|
|
@@ -1,9 +1,14 @@
|
|
|
1
|
+
import { stripTxTypePrefix } from "../bridge-reserves.mjs";
|
|
2
|
+
import { checkBridgeWithdraw, isBridgeWithdrawFailure } from "../helpers/bridge-withdraw.mjs";
|
|
3
|
+
import { assertBridgeReleaseProtected } from "./bridge-release-gate.mjs";
|
|
4
|
+
import { assertBridgeReservesV2Protected } from "./bridge-reserve-v2-gate.mjs";
|
|
1
5
|
import { types } from "@ocap/mcrypto";
|
|
2
6
|
import { BN, isSameDid, toAddress } from "@ocap/util";
|
|
3
7
|
import { CustomError } from "@ocap/util/lib/error";
|
|
4
|
-
import { account, parseNonceBn, token } from "@ocap/state";
|
|
5
|
-
import cloneDeep from "lodash/cloneDeep.js";
|
|
6
8
|
import { isValid, toTypeInfo } from "@arcblock/did";
|
|
9
|
+
import { toStakeAddress } from "@arcblock/did-util";
|
|
10
|
+
import { account, parseNonceBn, rollup, token } from "@ocap/state";
|
|
11
|
+
import cloneDeep from "lodash/cloneDeep.js";
|
|
7
12
|
import isEqual from "lodash/isEqual.js";
|
|
8
13
|
|
|
9
14
|
//#region src/pipes/post-execution-invariant-gate.ts
|
|
@@ -24,6 +29,37 @@ const TRACKED_STATE_TABLES = [
|
|
|
24
29
|
"evidence",
|
|
25
30
|
"balance"
|
|
26
31
|
];
|
|
32
|
+
const isZeroAmount = (value) => {
|
|
33
|
+
const str = String(value ?? "0");
|
|
34
|
+
return CANONICAL_UINT_STRING_PATTERN.test(str) && new BN(str, 10).isZero();
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Whether `stake` is a Stake-for-Token of `token`: staked on the official token under the token's symbol as nonce
|
|
38
|
+
* (`toStakeAddress(sender, config.token.address, symbol)`, see `create_token_factory`). Any account can hold such a
|
|
39
|
+
* stake for a symbol; who may use it is decided by the caller (#1422).
|
|
40
|
+
*/
|
|
41
|
+
function isTokenIssuanceStakeOf(stake, token$1, officialTokenAddress) {
|
|
42
|
+
const nonce = stake?.nonce;
|
|
43
|
+
if (!stake?.address || !stake.sender || !stake.receiver || typeof nonce !== "string" || !nonce) return false;
|
|
44
|
+
if (!token$1?.address || !token$1.symbol || !token$1.tokenFactoryAddress) return false;
|
|
45
|
+
if (!officialTokenAddress || !isSameDid(stake.receiver, officialTokenAddress)) return false;
|
|
46
|
+
if (isSameDid(token$1.address, officialTokenAddress)) return false;
|
|
47
|
+
if (nonce.toUpperCase() !== String(token$1.symbol).toUpperCase()) return false;
|
|
48
|
+
try {
|
|
49
|
+
return isSameDid(toStakeAddress(stake.sender, stake.receiver, nonce), stake.address);
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Whether the token behind `factory` has been 100% redeemed: token and factory point at each other, nothing is in
|
|
56
|
+
* circulation (`totalSupply`, `currentSupply`) and no reserve is left in the curve (`reserveBalance`).
|
|
57
|
+
*/
|
|
58
|
+
function isTokenFullyRedeemed(token$1, factory) {
|
|
59
|
+
if (!token$1?.address || !factory?.address || !factory.tokenAddress || !token$1.tokenFactoryAddress) return false;
|
|
60
|
+
if (!isSameDid(factory.tokenAddress, token$1.address) || !isSameDid(token$1.tokenFactoryAddress, factory.address)) return false;
|
|
61
|
+
return isZeroAmount(token$1.totalSupply) && isZeroAmount(factory.currentSupply) && isZeroAmount(factory.reserveBalance);
|
|
62
|
+
}
|
|
27
63
|
const TX_TYPES_ALLOWED_TO_CREATE_ASSET = new Set([
|
|
28
64
|
"fg:t:create_asset",
|
|
29
65
|
"create_asset",
|
|
@@ -94,7 +130,8 @@ function createEmptyTracker() {
|
|
|
94
130
|
writtenKeys,
|
|
95
131
|
addressAliases: /* @__PURE__ */ new Map(),
|
|
96
132
|
totalWriteOps: 0,
|
|
97
|
-
unauthorizedDeletions: 0
|
|
133
|
+
unauthorizedDeletions: 0,
|
|
134
|
+
directBalanceWrites: []
|
|
98
135
|
};
|
|
99
136
|
}
|
|
100
137
|
function getEntityKey(table, rawKey, stateObj) {
|
|
@@ -254,6 +291,12 @@ function installStateWriteInterceptor(context) {
|
|
|
254
291
|
}
|
|
255
292
|
return res;
|
|
256
293
|
};
|
|
294
|
+
if (tableName === "balance" && prop === "updateBalance") return async function interceptedUpdateBalance(params, ...rest) {
|
|
295
|
+
const addr = normalizeEntityKey(params?.address);
|
|
296
|
+
if (addr) tracker.directBalanceWrites.push(addr);
|
|
297
|
+
tracker.totalWriteOps += 1;
|
|
298
|
+
return origVal.apply(origTable, [params, ...rest]);
|
|
299
|
+
};
|
|
257
300
|
if (prop === "remove" || prop === "delete" || prop === "destroy" || prop === "clear") return async function interceptedDelete(...args) {
|
|
258
301
|
tracker.unauthorizedDeletions += 1;
|
|
259
302
|
tracker.totalWriteOps += 1;
|
|
@@ -474,6 +517,51 @@ function inspectPostExecutionInvariants(context) {
|
|
|
474
517
|
const tracker = context._stateWriteTracker;
|
|
475
518
|
if (tracker && tracker.unauthorizedDeletions > 0) throw createInvariantError("STATE_DELETION_FORBIDDEN", `Post-Execution Invariant Gate: unauthorized state deletion detected (${tracker.unauthorizedDeletions} delete operation(s))`);
|
|
476
519
|
const { beforeByTable, afterByTable, writtenCount } = collectUnifiedBeforeAndAfterStates(context);
|
|
520
|
+
assertBridgeReservesV2Protected({
|
|
521
|
+
txType: stripTxTypePrefix(txType),
|
|
522
|
+
isReserveAddress: (key) => getDidRoleSafe(key) === RoleType.ROLE_BRIDGE_RESERVE,
|
|
523
|
+
norm: normalizeEntityKey,
|
|
524
|
+
createGateError: createInvariantError,
|
|
525
|
+
tokenBalances: (tokens, label) => normalizeTokenBalanceRecord(tokens, label),
|
|
526
|
+
before: beforeByTable,
|
|
527
|
+
after: afterByTable,
|
|
528
|
+
directBalanceWrites: tracker?.directBalanceWrites ?? [],
|
|
529
|
+
writtenBalanceKeys: tracker?.writtenKeys.get("balance"),
|
|
530
|
+
enabled: !!(context.config?.transaction)?.bridge?.enabled,
|
|
531
|
+
resolution: context._bridgeReserveGate ?? null,
|
|
532
|
+
releaseKind: context.itx?.kind,
|
|
533
|
+
checkWithdraw: (bridge, credited) => {
|
|
534
|
+
const withdraw = checkBridgeWithdraw(context, bridge);
|
|
535
|
+
if (isBridgeWithdrawFailure(withdraw)) return `${withdraw.code}: ${withdraw.message}`;
|
|
536
|
+
if (!credited.eq(new BN(withdraw.amount))) return `the reserve grew by ${credited.toString(10)}, not by the withdrawn amount ${withdraw.amount}`;
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
{
|
|
541
|
+
const cfgVaults = context.config?.vaults || {};
|
|
542
|
+
const asList = (x) => Array.isArray(x) ? x : [];
|
|
543
|
+
assertBridgeReleaseProtected({
|
|
544
|
+
txType: stripTxTypePrefix(txType),
|
|
545
|
+
itx: context.itx ?? {},
|
|
546
|
+
payer: normalizeEntityKey(context.tx?.from),
|
|
547
|
+
norm: normalizeEntityKey,
|
|
548
|
+
isReserveAddress: (key) => getDidRoleSafe(key) === RoleType.ROLE_BRIDGE_RESERVE,
|
|
549
|
+
createGateError: createInvariantError,
|
|
550
|
+
tokenBalances: (tokens, label) => normalizeTokenBalanceRecord(tokens, label),
|
|
551
|
+
before: beforeByTable,
|
|
552
|
+
after: afterByTable,
|
|
553
|
+
written: (table) => tracker?.writtenKeys.get(table),
|
|
554
|
+
directBalanceWrites: tracker?.directBalanceWrites ?? [],
|
|
555
|
+
officialToken: normalizeEntityKey(context.config?.token?.address || ""),
|
|
556
|
+
vaults: new Set([
|
|
557
|
+
cfgVaults.slashedStake,
|
|
558
|
+
cfgVaults.txFee,
|
|
559
|
+
...asList(cfgVaults.txFees),
|
|
560
|
+
...asList(cfgVaults.txGas)
|
|
561
|
+
].filter((x) => typeof x === "string" && !!x).map((x) => normalizeEntityKey(x))),
|
|
562
|
+
resolution: context._bridgeReserveGate ?? null
|
|
563
|
+
});
|
|
564
|
+
}
|
|
477
565
|
if (writtenCount > maxWriteSetEntries) throw createInvariantError("RW_SET_LIMIT_EXCEEDED", `Post-Execution Invariant Gate: transaction modified ${writtenCount} state entries, exceeding ceiling ${maxWriteSetEntries}`);
|
|
478
566
|
const beforeAccounts = beforeByTable.get("account");
|
|
479
567
|
const afterAccounts = afterByTable.get("account");
|
|
@@ -568,6 +656,7 @@ function inspectPostExecutionInvariants(context) {
|
|
|
568
656
|
} else if (!afterSupply.isZero()) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: create_token_factory must initialize token ${tokAddr} with totalSupply = 0`);
|
|
569
657
|
}
|
|
570
658
|
}
|
|
659
|
+
const isRevokeStakeTx = txType === "fg:t:revoke_stake" || txType === "revoke_stake";
|
|
571
660
|
const factoryByTokenAddr = /* @__PURE__ */ new Map();
|
|
572
661
|
for (const [factoryAddr, afterFac] of afterFactories.entries()) {
|
|
573
662
|
const beforeFac = beforeFactories.get(factoryAddr) ?? null;
|
|
@@ -582,6 +671,16 @@ function inspectPostExecutionInvariants(context) {
|
|
|
582
671
|
if (beforeTokenAddr && facTokenAddr !== beforeTokenAddr) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: tokenFactory ${factoryAddr} tokenAddress is immutable`);
|
|
583
672
|
if (beforeReserveAddr && facReserveAddr !== beforeReserveAddr) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: tokenFactory ${factoryAddr} reserveAddress is immutable`);
|
|
584
673
|
}
|
|
674
|
+
const afterFacStatus = afterFac.status;
|
|
675
|
+
const beforeFacStatus = beforeFac ? beforeFac.status : void 0;
|
|
676
|
+
if (beforeFacStatus === "RETIRED" && afterFacStatus !== "RETIRED") throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: retired tokenFactory ${factoryAddr} cannot be reactivated`);
|
|
677
|
+
if (afterFacStatus === "RETIRED") {
|
|
678
|
+
const facToken = afterTokens.get(facTokenAddr) ?? beforeTokens.get(facTokenAddr) ?? null;
|
|
679
|
+
if (!(isZeroAmount(afterFac.currentSupply) && isZeroAmount(afterFac.reserveBalance)) || !facSupplyDelta.isZero()) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: retired tokenFactory ${factoryAddr} must keep zero supply and zero reserve`);
|
|
680
|
+
if (beforeFacStatus !== "RETIRED") {
|
|
681
|
+
if (!(isRevokeStakeTx && (beforeFacStatus || "ACTIVE") === "ACTIVE" && Boolean(beforeFac) && isTokenFullyRedeemed(facToken, beforeFac) && isTokenFullyRedeemed(facToken, afterFac))) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: tokenFactory ${factoryAddr} can only be retired by revoke_stake once supply and reserve are zero`);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
585
684
|
if (facTokenAddr) {
|
|
586
685
|
if (factoryByTokenAddr.has(facTokenAddr) && factoryByTokenAddr.get(facTokenAddr) !== factoryAddr) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: multiple tokenFactories referencing token ${facTokenAddr}`);
|
|
587
686
|
factoryByTokenAddr.set(facTokenAddr, factoryAddr);
|
|
@@ -596,7 +695,13 @@ function inspectPostExecutionInvariants(context) {
|
|
|
596
695
|
}
|
|
597
696
|
const isCreateRollupBlockTx = txType === "fg:t:create_rollup_block" || txType === "create_rollup_block";
|
|
598
697
|
if (isCreateRollupBlockTx) {
|
|
698
|
+
if (!((context.config?.transaction)?.rollupV1?.enabled !== false)) throw createInvariantError("OFFICIAL_TOKEN_SUPPLY_VIOLATION", "Post-Execution Invariant Gate: Rollup v1 supply mint/burn exemption is disabled");
|
|
599
699
|
const rollupState = context.rollupState;
|
|
700
|
+
if ([
|
|
701
|
+
rollupState,
|
|
702
|
+
...Array.from(beforeByTable.get("rollup")?.values() ?? []),
|
|
703
|
+
...Array.from(afterByTable.get("rollup")?.values() ?? [])
|
|
704
|
+
].some((row) => row && rollup.isBridgeV2(row))) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", "Post-Execution Invariant Gate: create_rollup_block supply exemption is forbidden for v2 bridges");
|
|
600
705
|
const defaultRollupToken = normalizeEntityKey(rollupState?.tokenAddress || officialTokenAddress);
|
|
601
706
|
const txStates = context.txStates || [];
|
|
602
707
|
const seenRollupTxHashes = /* @__PURE__ */ new Set();
|
|
@@ -706,6 +811,15 @@ function inspectPostExecutionInvariants(context) {
|
|
|
706
811
|
const isSlashStakeTx = txType === "fg:t:slash_stake" || txType === "slash_stake";
|
|
707
812
|
const isRollupDepositTx = txType === "fg:t:deposit_token_v2" || txType === "deposit_token_v2";
|
|
708
813
|
const isClaimBlockRewardTx = txType === "fg:t:claim_block_reward" || txType === "claim_block_reward";
|
|
814
|
+
const isStakeOfRetiredToken = (stakeRec) => {
|
|
815
|
+
for (const afterFac of afterFactories.values()) {
|
|
816
|
+
const fac = afterFac;
|
|
817
|
+
if (fac.status !== "RETIRED") continue;
|
|
818
|
+
const tok = afterTokens.get(normalizeEntityKey(fac.tokenAddress)) ?? null;
|
|
819
|
+
if (isTokenIssuanceStakeOf(stakeRec, tok, officialTokenAddress) && isTokenFullyRedeemed(tok, fac)) return true;
|
|
820
|
+
}
|
|
821
|
+
return false;
|
|
822
|
+
};
|
|
709
823
|
for (const [stakeAddr, afterStakeRec] of afterStakes.entries()) {
|
|
710
824
|
const beforeStakeRec = beforeStakes.get(stakeAddr) ?? null;
|
|
711
825
|
const afterStake = afterStakeRec;
|
|
@@ -743,8 +857,9 @@ function inspectPostExecutionInvariants(context) {
|
|
|
743
857
|
const isRollupStake = receiverRole === RoleType.ROLE_ROLLUP && !isProtocolTokenOrAssetStake;
|
|
744
858
|
if (beforeStake.revocable === false) {
|
|
745
859
|
const isAllowedRollupCloseUnlock = (isCloseRollupTx || isLeaveRollupTx) && isRollupStake;
|
|
746
|
-
|
|
747
|
-
if (!isAllowedRollupCloseUnlock) {
|
|
860
|
+
const isAllowedRetiredTokenUnlock = isRevokeStakeTx && isStakeOfRetiredToken(beforeStake);
|
|
861
|
+
if (afterStake.revocable !== false && !isAllowedRollupCloseUnlock && !isAllowedRetiredTokenUnlock) throw createInvariantError("STAKE_PROTECTION_VIOLATION", `Post-Execution Invariant Gate: permanently locked stake ${stakeAddr} (revocable=false) cannot be unlocked`);
|
|
862
|
+
if (!isAllowedRollupCloseUnlock && !isAllowedRetiredTokenUnlock) {
|
|
748
863
|
const hasConfiguredSlashers = Array.isArray(beforeStake.slashers) && beforeStake.slashers.length > 0;
|
|
749
864
|
const isAllowedLockedStakeSlash = isSlashStakeTx && !isProtocolTokenOrAssetStake && hasConfiguredSlashers;
|
|
750
865
|
for (const lockedAsset of beforeStakedAssets) if (revokedSet.has(lockedAsset) || !stakedSet.has(lockedAsset) && !isAllowedLockedStakeSlash) throw createInvariantError("STAKE_PROTECTION_VIOLATION", `Post-Execution Invariant Gate: permanently locked stake ${stakeAddr} cannot revoke or drain asset ${lockedAsset}`);
|
|
@@ -786,4 +901,4 @@ function CreatePostExecutionInvariantGatePipe() {
|
|
|
786
901
|
var post_execution_invariant_gate_default = CreatePostExecutionInvariantGatePipe;
|
|
787
902
|
|
|
788
903
|
//#endregion
|
|
789
|
-
export { CreatePostExecutionInvariantGatePipe, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, TRACKED_STATE_TABLES, post_execution_invariant_gate_default as default, inspectPostExecutionInvariants, installStateWriteInterceptor, normalizeEntityKey, rollbackTrackedStateWrites };
|
|
904
|
+
export { CreatePostExecutionInvariantGatePipe, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, TRACKED_STATE_TABLES, post_execution_invariant_gate_default as default, inspectPostExecutionInvariants, installStateWriteInterceptor, isTokenFullyRedeemed, isTokenIssuanceStakeOf, normalizeEntityKey, rollbackTrackedStateWrites };
|