@ocap/tx-protocols 1.31.5 → 1.31.6
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-crypto.mjs +1 -1
- package/esm/execute.mjs +24 -5
- package/esm/gas-security-guard.d.mts +2 -8
- package/esm/gas-security-guard.mjs +16 -1
- package/esm/index.d.mts +16 -3
- package/esm/index.mjs +0 -2
- package/esm/pipes/ensure-cost.mjs +3 -0
- package/esm/pipes/ensure-gas.d.mts +2 -1
- package/esm/pipes/write-ledger.mjs +2 -1
- package/esm/protocols/bridge/release-checks.d.mts +69 -0
- package/esm/protocols/bridge/{release.mjs → release-checks.mjs} +101 -100
- package/esm/protocols/rollup/bridge-create.mjs +2 -2
- package/esm/protocols/rollup/bridge-membership.mjs +10 -12
- package/esm/protocols/rollup/bridge-v2.d.mts +15 -5
- package/esm/protocols/rollup/bridge-v2.mjs +33 -8
- package/esm/protocols/token/deposit-v2.mjs +126 -25
- package/esm/protocols/token/withdraw-v2.d.mts +13 -1
- package/esm/protocols/token/withdraw-v2.mjs +158 -25
- package/esm/protocols/trade/transfer-v2.mjs +3 -8
- package/lib/bridge-release-crypto.cjs +1 -1
- package/lib/execute.cjs +24 -5
- package/lib/gas-security-guard.cjs +16 -1
- package/lib/gas-security-guard.d.cts +2 -8
- package/lib/index.cjs +0 -2
- package/lib/index.d.cts +16 -3
- package/lib/pipes/ensure-cost.cjs +3 -0
- package/lib/pipes/ensure-gas.d.cts +2 -1
- package/lib/pipes/write-ledger.cjs +2 -1
- package/lib/protocols/bridge/{release.cjs → release-checks.cjs} +115 -101
- package/lib/protocols/bridge/release-checks.d.cts +69 -0
- package/lib/protocols/rollup/bridge-create.cjs +1 -1
- package/lib/protocols/rollup/bridge-membership.cjs +9 -10
- package/lib/protocols/rollup/bridge-v2.cjs +32 -5
- package/lib/protocols/rollup/bridge-v2.d.cts +15 -5
- package/lib/protocols/token/deposit-v2.cjs +125 -24
- package/lib/protocols/token/withdraw-v2.cjs +155 -22
- package/lib/protocols/token/withdraw-v2.d.cts +13 -1
- package/lib/protocols/trade/transfer-v2.cjs +2 -7
- package/package.json +16 -16
- package/esm/protocols/bridge/release.d.mts +0 -34
- package/lib/protocols/bridge/release.d.cts +0 -34
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
import { ZERO_ETH_ADDRESS, getDepositClaimDigest, getOcapReleaseDigest, isEthAddress, recoverEthSigner } from "../../bridge-release-crypto.mjs";
|
|
2
2
|
import { MAX_RING_SKEW_HOURS, evaluateRing, formatRingSlot, parseRingSlot } from "../../bridge-release-window.mjs";
|
|
3
3
|
import { applyTokenChange } from "../../util.mjs";
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import { markStatelessPrefix } from "../../stateless-prefix.mjs";
|
|
7
|
-
import { RELEASE_RING_SLOTS, Runner, formatBucketData, getReleaseBucketKey, getReleaseTombstoneKey, isBridgeReserveRole, normalizeEntityKey, parseBucketData, pipes, resolveBridgeForRelease } from "@ocap/tx-pipeline";
|
|
4
|
+
import { parseStrictEthAddress } from "@ocap/mcrypto";
|
|
5
|
+
import { RELEASE_RING_SLOTS, formatBucketData, getReleaseBucketKey, getReleaseTombstoneKey, isBridgeReserveRole, normalizeEntityKey, parseBucketData, resolveBridgeForRelease } from "@ocap/tx-pipeline";
|
|
8
6
|
import { CustomError } from "@ocap/util/lib/error";
|
|
9
7
|
import { account, evidence, rollup } from "@ocap/state";
|
|
10
8
|
import { BN } from "@ocap/util";
|
|
11
|
-
import { schemas, v, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
12
9
|
|
|
13
|
-
//#region src/protocols/bridge/release.ts
|
|
10
|
+
//#region src/protocols/bridge/release-checks.ts
|
|
14
11
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
12
|
+
* The checks of a bridge release (bridge/docs/ocap-protocols.md §3 checks 1-10, §v2.2, §v2.4): the bridge branch of
|
|
13
|
+
* `deposit_token_v2` with `kind ∈ {1,2,3}` on a v2 bridge (`protocols/token/deposit-v2.ts`,
|
|
14
|
+
* bridge/docs/deposit-withdraw-v2-unification.md §2.5), the only form a release can take.
|
|
18
15
|
*
|
|
19
|
-
* The
|
|
20
|
-
*
|
|
16
|
+
* The runner validates the itx shape and maps it onto one {@link ReleaseView} (`context.releaseItx`); every pipe below
|
|
17
|
+
* reads that view only. The tombstone and bucket keys are `getReleaseTombstoneKey` / `getReleaseBucketKey`.
|
|
21
18
|
*
|
|
22
|
-
* Lifecycle per kind (§v2.2 `pause_rollup` / `close_rollup
|
|
19
|
+
* Lifecycle per kind (§v2.2 `pause_rollup` / `close_rollup`):
|
|
23
20
|
* - not closing: a pause of any kind (lone or quorum) refuses every kind, REFUND included;
|
|
24
21
|
* - closing (`close_rollup` has run; the bridge is quorum-paused for good): DEPOSIT / DEPOSIT_B are accepted until
|
|
25
22
|
* `finalAt` (validators must release the backlog before finality), REFUND is accepted for as long as it is due,
|
|
26
23
|
* also after finality, and also from the reserve of a successor once the funds were migrated.
|
|
24
|
+
*
|
|
25
|
+
* The sender-state pipes, the snapshot and the state-diff check stay in each runner file (the #960 structural test reads
|
|
26
|
+
* them from the protocol source).
|
|
27
27
|
*/
|
|
28
28
|
const RELEASE_KIND = {
|
|
29
29
|
DEPOSIT: 1,
|
|
@@ -35,33 +35,13 @@ const MAX_MIGRATION_HOPS = 8;
|
|
|
35
35
|
const UINT256_MAX = (1n << 256n) - 1n;
|
|
36
36
|
const invalid = (message) => new CustomError("INVALID_TX", message);
|
|
37
37
|
const forbidden = (message) => new CustomError("FORBIDDEN", message);
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
RELEASE_KIND.DEPOSIT,
|
|
43
|
-
RELEASE_KIND.REFUND,
|
|
44
|
-
RELEASE_KIND.DEPOSIT_B
|
|
45
|
-
]),
|
|
46
|
-
bridge: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
|
|
47
|
-
evidence: v.pipe(v.string(), v.regex(/^0x[0-9a-f]{64}$/)),
|
|
48
|
-
ordinal: v.pipe(v.number(), v.integer(), v.minValue(0)),
|
|
49
|
-
to: schemas.tokenHolder,
|
|
50
|
-
amount: v.pipe(v.string(), v.regex(/^[1-9]\d{0,77}$/)),
|
|
51
|
-
ethChainId: v.pipe(v.string(), v.regex(/^[1-9]\d{0,18}$/)),
|
|
52
|
-
epoch: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)),
|
|
53
|
-
ethSender: v.optional(v.string(), ""),
|
|
54
|
-
claimSignature: v.optional(v.string(), ""),
|
|
55
|
-
signaturesList: v.pipe(v.array(v.string()), v.maxLength(16)),
|
|
56
|
-
data: v.optional(v.nullable(v.any()))
|
|
57
|
-
}), vStripUnknown());
|
|
58
|
-
runner.use((context, next) => {
|
|
59
|
-
const { error } = vValidate(schema, context.itx);
|
|
60
|
-
if (error) return next(invalid(`Invalid itx: ${error.message}`));
|
|
61
|
-
next();
|
|
38
|
+
/** The pipes below are named (structural tests and debugging find pipes by name). */
|
|
39
|
+
const named = (name, fn) => Object.defineProperty(fn, "name", {
|
|
40
|
+
value: name,
|
|
41
|
+
configurable: true
|
|
62
42
|
});
|
|
63
|
-
|
|
64
|
-
const
|
|
43
|
+
const checkReleaseFields = named("CheckReleaseFields", (context, next) => {
|
|
44
|
+
const itx = context.releaseItx;
|
|
65
45
|
if (itx.ordinal !== 0) return next(invalid("Release ordinal must be 0 in v1"));
|
|
66
46
|
if (BigInt(itx.amount) > UINT256_MAX) return next(invalid("Release amount exceeds uint256"));
|
|
67
47
|
if (itx.kind === RELEASE_KIND.DEPOSIT_B) {
|
|
@@ -70,24 +50,28 @@ runner.use((context, next) => {
|
|
|
70
50
|
} else if (itx.ethSender !== "" || itx.claimSignature !== "") return next(invalid("ethSender and claimSignature are only valid for DEPOSIT_B"));
|
|
71
51
|
next();
|
|
72
52
|
});
|
|
73
|
-
|
|
74
|
-
runner.use((context, next) => {
|
|
53
|
+
const rejectReleaseDelegator = named("RejectReleaseDelegator", (context, next) => {
|
|
75
54
|
if (context.tx.delegator) return next(invalid("A release can not be delegated"));
|
|
76
55
|
next();
|
|
77
56
|
});
|
|
78
|
-
|
|
57
|
+
const resolveReleaseTime = named("ResolveReleaseTime", (context, next) => {
|
|
79
58
|
const { txTime } = context;
|
|
80
59
|
const ms = typeof txTime === "string" ? new Date(txTime).getTime() : NaN;
|
|
81
60
|
if (!Number.isFinite(ms) || ms <= 0) return next(invalid("Release requires a valid tx time"));
|
|
82
61
|
context.releaseTimeMs = ms;
|
|
83
62
|
next();
|
|
84
63
|
});
|
|
85
|
-
|
|
86
|
-
|
|
64
|
+
/**
|
|
65
|
+
* 1. master switch, the bridge the release names, its lifecycle for this kind.
|
|
66
|
+
* `opts.token`: the release names the token (`itx.token.address`), which must be the bridge token (fail closed).
|
|
67
|
+
*/
|
|
68
|
+
const resolveReleaseBridge = (opts) => named("ResolveReleaseBridge", async (context, next) => {
|
|
69
|
+
const { config } = context;
|
|
70
|
+
const itx = context.releaseItx;
|
|
87
71
|
if (!config?.transaction?.bridge?.enabled) return next(forbidden("Bridges are not enabled on this chain"));
|
|
88
72
|
let release;
|
|
89
73
|
try {
|
|
90
|
-
release = await resolveBridgeForRelease(context, itx);
|
|
74
|
+
release = await resolveBridgeForRelease(context, { bridge: itx.bridge });
|
|
91
75
|
} catch (err) {
|
|
92
76
|
return next(err);
|
|
93
77
|
}
|
|
@@ -104,17 +88,22 @@ runner.use(async (context, next) => {
|
|
|
104
88
|
if (!signing) return next(invalid("The reserve that holds the funds of this bridge could not be resolved"));
|
|
105
89
|
if (signing !== bridge && !signing.closing && signing.paused) return next(forbidden(`Bridge ${signing.address}, which holds the funds, is paused`));
|
|
106
90
|
context.signingBridge = signing;
|
|
107
|
-
if (
|
|
91
|
+
if (opts.token) {
|
|
92
|
+
const token$1 = opts.token(context);
|
|
93
|
+
if (typeof token$1 !== "string" || token$1 !== bridge.token) return next(invalid(`Release token ${String(token$1)} is not the token of bridge ${bridge.address}`));
|
|
94
|
+
}
|
|
108
95
|
next();
|
|
109
96
|
});
|
|
110
|
-
|
|
111
|
-
const {
|
|
97
|
+
const checkReleaseMinimum = named("CheckReleaseMinimum", (context, next) => {
|
|
98
|
+
const { release, releaseAmount } = context;
|
|
99
|
+
const itx = context.releaseItx;
|
|
112
100
|
const min = BigInt(release.bridge.body.minDeposit);
|
|
113
101
|
if (itx.kind !== RELEASE_KIND.REFUND && releaseAmount < min) return next(invalid(`Release amount is below the minimum deposit ${min}`));
|
|
114
102
|
next();
|
|
115
103
|
});
|
|
116
|
-
|
|
117
|
-
const { config
|
|
104
|
+
const checkReleaseRecipient = named("CheckReleaseRecipient", (context, next) => {
|
|
105
|
+
const { config } = context;
|
|
106
|
+
const itx = context.releaseItx;
|
|
118
107
|
const to = normalizeEntityKey(itx.to);
|
|
119
108
|
if (typeof itx.to !== "string" || itx.to.startsWith("did:abt:") || account.ensureChecksumAddress(itx.to) !== itx.to) return next(invalid("Release recipient is not in canonical form (bare address, EIP-55 checksum for 0x)"));
|
|
120
109
|
if (isBridgeReserveRole(itx.to)) return next(invalid("A release can not pay a bridge reserve"));
|
|
@@ -128,15 +117,17 @@ runner.use((context, next) => {
|
|
|
128
117
|
].filter((x) => typeof x === "string" && !!x).map((x) => normalizeEntityKey(x)).includes(to)) return next(invalid("A release can not pay a vault"));
|
|
129
118
|
next();
|
|
130
119
|
});
|
|
131
|
-
|
|
132
|
-
const {
|
|
120
|
+
const checkReleaseTombstone = named("CheckReleaseTombstone", async (context, next) => {
|
|
121
|
+
const { statedb, release } = context;
|
|
122
|
+
const itx = context.releaseItx;
|
|
133
123
|
const key = getReleaseTombstoneKey(release.bridge.address, itx.kind, itx.evidence, itx.ordinal);
|
|
134
124
|
context.tombstoneKey = key;
|
|
135
125
|
if (await statedb.evidence.get(key, context)) return next(invalid("Release already executed for this evidence"));
|
|
136
126
|
next();
|
|
137
127
|
});
|
|
138
|
-
|
|
139
|
-
const {
|
|
128
|
+
const verifyReleaseSignatures = named("VerifyReleaseSignatures", (context, next) => {
|
|
129
|
+
const { release, releaseTimeMs } = context;
|
|
130
|
+
const itx = context.releaseItx;
|
|
140
131
|
const bridge = release.bridge;
|
|
141
132
|
const body = context.signingBridge.body;
|
|
142
133
|
const epochs = body.epochs;
|
|
@@ -176,8 +167,8 @@ runner.use((context, next) => {
|
|
|
176
167
|
}
|
|
177
168
|
next();
|
|
178
169
|
});
|
|
179
|
-
|
|
180
|
-
const
|
|
170
|
+
const verifyReleaseClaim = named("VerifyReleaseClaim", (context, next) => {
|
|
171
|
+
const itx = context.releaseItx;
|
|
181
172
|
if (itx.kind !== RELEASE_KIND.DEPOSIT_B) return next();
|
|
182
173
|
const body = context.signingBridge.body;
|
|
183
174
|
const signer = recoverEthSigner(getDepositClaimDigest({
|
|
@@ -209,25 +200,42 @@ async function resolveMigrated(context, address) {
|
|
|
209
200
|
current = migratedTo[0];
|
|
210
201
|
}
|
|
211
202
|
}
|
|
212
|
-
|
|
213
|
-
|
|
203
|
+
const CANONICAL_DECIMAL = /^(0|[1-9]\d{0,77})$/;
|
|
204
|
+
const isEmptyOrZero = (value) => value === void 0 || value === null || value === "" || value === "0";
|
|
205
|
+
const isEmptyData = (value) => {
|
|
206
|
+
if (value === void 0 || value === null || value === "") return true;
|
|
207
|
+
if (typeof value !== "object") return false;
|
|
208
|
+
const { typeUrl, type, value: inner } = value;
|
|
209
|
+
const empty = (x) => x === void 0 || x === null || x === "";
|
|
210
|
+
return empty(typeUrl) && empty(type) && (empty(inner) || inner instanceof Uint8Array && inner.length === 0);
|
|
211
|
+
};
|
|
212
|
+
/**
|
|
213
|
+
* The amount a stored withdraw moved into the reserve of `bridge`, or a rejection message. The only refundable withdraw
|
|
214
|
+
* is the bridge branch of `withdraw_token_v2` naming THIS bridge in `itx.rollup` (whether or not it migrated since).
|
|
215
|
+
*/
|
|
216
|
+
function refundableAmount(withdrawTx, bridge) {
|
|
217
|
+
const itxJson = withdrawTx.itxJson || {};
|
|
218
|
+
const token$1 = normalizeEntityKey(bridge.token);
|
|
219
|
+
if (typeof itxJson.rollup !== "string" || itxJson.rollup !== bridge.address) return { error: "Refund evidence is not a withdraw_token_v2 from this bridge" };
|
|
220
|
+
if (withdrawTx.delegator) return { error: "A delegated withdraw can not be refunded" };
|
|
221
|
+
if (!(itxJson.proposer === void 0 || itxJson.proposer === null || itxJson.proposer === "") || !isEmptyOrZero(itxJson.maxFee) || !isEmptyOrZero(itxJson.actualFee) || !parseStrictEthAddress(itxJson.to).ok || !isEmptyData(itxJson.data)) return { error: "Refund evidence is not a bridge withdraw_token_v2 (proposer, fees, recipient or data)" };
|
|
222
|
+
const entry = itxJson.token || {};
|
|
223
|
+
if (normalizeEntityKey(entry.address) !== token$1) return { error: "Refund evidence moved a token other than the bridge token" };
|
|
224
|
+
if (typeof entry.value !== "string" || !CANONICAL_DECIMAL.test(entry.value)) return { error: "Refund evidence has no canonical withdraw amount" };
|
|
225
|
+
return { amount: BigInt(entry.value) };
|
|
226
|
+
}
|
|
227
|
+
const checkReleaseRefund = named("CheckReleaseRefund", async (context, next) => {
|
|
228
|
+
const { release, statedb, releaseTimeMs, releaseAmount } = context;
|
|
229
|
+
const itx = context.releaseItx;
|
|
214
230
|
if (itx.kind !== RELEASE_KIND.REFUND) return next();
|
|
215
231
|
const bridge = release.bridge;
|
|
216
232
|
const body = bridge.body;
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
if (!withdraw || withdraw.code !== "OK" || withdraw.type !== "transfer_v2") return next(invalid("Refund evidence is not a successful transfer_v2"));
|
|
233
|
+
const withdraw = await statedb.tx.get(itx.evidence.replace(/^0x/i, "").toUpperCase(), context);
|
|
234
|
+
if (!withdraw || withdraw.code !== "OK" || withdraw.type !== "withdraw_token_v2") return next(invalid("Refund evidence is not a successful bridge withdraw_token_v2"));
|
|
220
235
|
const withdrawTx = withdraw.tx || {};
|
|
221
|
-
const
|
|
222
|
-
if (
|
|
223
|
-
if (
|
|
224
|
-
if ((itxJson.assets || []).length > 0) return next(invalid("Refund evidence moved assets"));
|
|
225
|
-
let paid = new BN(itxJson.value || "0");
|
|
226
|
-
for (const entry of itxJson.tokens || []) {
|
|
227
|
-
if (normalizeEntityKey(entry.address) !== token$1) return next(invalid("Refund evidence moved a token other than the bridge token"));
|
|
228
|
-
paid = paid.add(new BN(entry.value));
|
|
229
|
-
}
|
|
230
|
-
if (BigInt(paid.toString(10)) !== releaseAmount) return next(invalid("Refund amount does not match the withdraw"));
|
|
236
|
+
const paid = refundableAmount(withdrawTx, bridge);
|
|
237
|
+
if ("error" in paid) return next(invalid(paid.error));
|
|
238
|
+
if (paid.amount !== releaseAmount) return next(invalid("Refund amount does not match the withdraw"));
|
|
231
239
|
const withdrawMs = new Date(withdraw.time).getTime();
|
|
232
240
|
if (!Number.isFinite(withdrawMs)) return next(invalid("Refund evidence has no valid time"));
|
|
233
241
|
const withdrawSec = Math.floor(withdrawMs / 1e3);
|
|
@@ -254,14 +262,15 @@ runner.use(async (context, next) => {
|
|
|
254
262
|
context.refundLedger = ledger;
|
|
255
263
|
next();
|
|
256
264
|
});
|
|
257
|
-
|
|
258
|
-
const state = await context.statedb.account.get(context.
|
|
265
|
+
const checkReleaseRecipientState = named("CheckReleaseRecipientState", async (context, next) => {
|
|
266
|
+
const state = await context.statedb.account.get(context.releaseItx.to, rawRead(context));
|
|
259
267
|
if (state?.migratedTo?.length) return next(invalid("Release recipient has been migrated"));
|
|
260
268
|
context.receiverState = state ?? void 0;
|
|
261
269
|
next();
|
|
262
270
|
});
|
|
263
|
-
|
|
264
|
-
const {
|
|
271
|
+
const checkReleaseCap = named("CheckReleaseCap", async (context, next) => {
|
|
272
|
+
const { release, statedb, releaseTimeMs, releaseAmount } = context;
|
|
273
|
+
const itx = context.releaseItx;
|
|
265
274
|
const bridge = release.bridge;
|
|
266
275
|
const ring = itx.kind === RELEASE_KIND.REFUND ? "refund" : "deposit";
|
|
267
276
|
const cap = BigInt(ring === "refund" ? bridge.body.refundDailyCap : bridge.body.releaseDailyCap);
|
|
@@ -289,9 +298,9 @@ runner.use(async (context, next) => {
|
|
|
289
298
|
};
|
|
290
299
|
next();
|
|
291
300
|
});
|
|
292
|
-
|
|
293
|
-
const {
|
|
294
|
-
const reserveAddress =
|
|
301
|
+
const checkReleaseReserve = named("CheckReleaseReserve", async (context, next) => {
|
|
302
|
+
const { release, statedb, releaseAmount } = context;
|
|
303
|
+
const reserveAddress = context.releaseItx.kind === RELEASE_KIND.REFUND ? release.fundsReserve : release.reserve;
|
|
295
304
|
const reserveState = await statedb.account.get(reserveAddress, context);
|
|
296
305
|
if (!reserveState) return next(invalid("The bridge reserve account does not exist"));
|
|
297
306
|
const token$1 = release.debitable.get(reserveAddress).token;
|
|
@@ -300,29 +309,23 @@ runner.use(async (context, next) => {
|
|
|
300
309
|
context.releaseToken = token$1;
|
|
301
310
|
next();
|
|
302
311
|
});
|
|
303
|
-
|
|
312
|
+
/** Gas operations of a release (for `EnsureTxGas`). */
|
|
313
|
+
const releaseGasEstimate = (context) => {
|
|
304
314
|
const ledger = (context.refundLedger || []).length;
|
|
305
315
|
return {
|
|
306
316
|
create: 1 + (context.receiverState ? 0 : 1) + (context.releaseRing?.exists ? 0 : 1),
|
|
307
317
|
update: 3 + (context.releaseRing?.exists ? 1 : 0) + ledger,
|
|
308
318
|
payment: 0
|
|
309
319
|
};
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
addressKey: "tx.from"
|
|
320
|
-
}));
|
|
321
|
-
runner.use(pipes.VerifyBlocked({ stateKeys: ["senderState", "receiverState"] }));
|
|
322
|
-
runner.use(ensure_cost_default({ attachSenderChanges: true }));
|
|
323
|
-
runner.use(pipes.TakeStateSnapshot());
|
|
324
|
-
runner.use(async (context, next) => {
|
|
325
|
-
const { itx, tx: tx$1, statedb, senderState, receiverState, reserveState, senderChange, releaseAmount, releaseRing, releaseToken, tombstoneKey, updateVaults, refundLedger } = context;
|
|
320
|
+
};
|
|
321
|
+
/**
|
|
322
|
+
* The state writes of a release: the tombstone (create only: a second release of the same evidence was refused above,
|
|
323
|
+
* and `create` fails on an existing key), the one bucket it uses, the refund ledger of the migrated bridges a REFUND
|
|
324
|
+
* draws through, the reserve debit, the recipient credit and the sender (nonce, gas).
|
|
325
|
+
*/
|
|
326
|
+
const writeRelease = named("WriteRelease", async (context, next) => {
|
|
327
|
+
const { tx: tx$1, statedb, senderState, receiverState, reserveState, senderChange, releaseAmount, releaseRing, releaseToken, tombstoneKey, updateVaults, refundLedger } = context;
|
|
328
|
+
const itx = context.releaseItx;
|
|
326
329
|
const amount = new BN(releaseAmount.toString(10));
|
|
327
330
|
const selfRelease = normalizeEntityKey(senderState.address) === normalizeEntityKey(itx.to);
|
|
328
331
|
await statedb.evidence.create(tombstoneKey, evidence.create({
|
|
@@ -336,7 +339,7 @@ runner.use(async (context, next) => {
|
|
|
336
339
|
}, context), context);
|
|
337
340
|
for (const entry of refundLedger || []) {
|
|
338
341
|
const body = entry.state.data.value;
|
|
339
|
-
const
|
|
342
|
+
const updated = {
|
|
340
343
|
...entry.state,
|
|
341
344
|
data: {
|
|
342
345
|
...entry.state.data,
|
|
@@ -346,7 +349,7 @@ runner.use(async (context, next) => {
|
|
|
346
349
|
}
|
|
347
350
|
}
|
|
348
351
|
};
|
|
349
|
-
await statedb.rollup.update(entry.address, rollup.updateBridge(entry.state,
|
|
352
|
+
await statedb.rollup.update(entry.address, rollup.updateBridge(entry.state, updated, context), context);
|
|
350
353
|
}
|
|
351
354
|
const reserveTokens = { ...reserveState.tokens || {} };
|
|
352
355
|
reserveTokens[releaseToken] = new BN(reserveTokens[releaseToken] || "0").sub(amount).toString(10);
|
|
@@ -377,9 +380,7 @@ runner.use(async (context, next) => {
|
|
|
377
380
|
context.bridgeToken = releaseToken;
|
|
378
381
|
if (updateVaults) await updateVaults();
|
|
379
382
|
next();
|
|
380
|
-
}
|
|
381
|
-
runner.use(pipes.VerifyStateDiff());
|
|
382
|
-
var release_default = runner;
|
|
383
|
+
});
|
|
383
384
|
|
|
384
385
|
//#endregion
|
|
385
|
-
export { MAX_MIGRATION_HOPS, RELEASE_KIND,
|
|
386
|
+
export { MAX_MIGRATION_HOPS, RELEASE_KIND, checkReleaseCap, checkReleaseFields, checkReleaseMinimum, checkReleaseRecipient, checkReleaseRecipientState, checkReleaseRefund, checkReleaseReserve, checkReleaseTombstone, rejectReleaseDelegator, releaseGasEstimate, resolveMigrated, resolveReleaseBridge, resolveReleaseTime, verifyReleaseClaim, verifyReleaseSignatures, writeRelease };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { gatewayIndexKey, indexBlocks, indexData,
|
|
1
|
+
import { gatewayIndexKey, indexBlocks, indexData, isV1EvidenceRow, membershipDigest, recoverAll, reserveIndexKey, tokenIndexKey, txSecOf, upsertIndexEvidence } from "./bridge-v2.mjs";
|
|
2
2
|
import { BRIDGE_MEMBERSHIP_ACTION, computeBridgeOwnerAttestationDigest, recoverBridgeSigner } from "@ocap/mcrypto";
|
|
3
3
|
import { CustomError } from "@ocap/util/lib/error";
|
|
4
4
|
import { isEthereumDid } from "@arcblock/did";
|
|
@@ -61,7 +61,7 @@ async function verifyBridgeCreate(context, next) {
|
|
|
61
61
|
]);
|
|
62
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
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 (
|
|
64
|
+
if (reserveEntry && !isV1EvidenceRow(reserveEntry) || reserveAccount) return next(new CustomError("DUPLICATE_ROLLUP", "The reserve of this bridge already exists"));
|
|
65
65
|
const missing = epoch1.validators.find((_, i) => !validatorAccounts[i]);
|
|
66
66
|
if (missing) return next(new CustomError("INVALID_TX", `Initial validator ${missing} has no account on this chain`));
|
|
67
67
|
let attestationSigner;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { bridgeUpdates, membershipDigest, membershipTombstoneKey, readItxData, recoverAll } from "./bridge-v2.mjs";
|
|
1
|
+
import { bridgeUpdates, isV1EvidenceRow, membershipDigest, membershipTombstoneKey, readItxData, recoverAll, upsertIndexEvidence } from "./bridge-v2.mjs";
|
|
2
2
|
import { BRIDGE_MEMBERSHIP_ACTION } from "@ocap/mcrypto";
|
|
3
3
|
import { CustomError } from "@ocap/util/lib/error";
|
|
4
4
|
import { isEthereumDid } from "@arcblock/did";
|
|
5
|
-
import { account,
|
|
5
|
+
import { account, rollup } from "@ocap/state";
|
|
6
6
|
import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
7
7
|
|
|
8
8
|
//#region src/protocols/rollup/bridge-membership.ts
|
|
@@ -86,7 +86,8 @@ const membershipChecks = (action) => async function MembershipChecks(context, ne
|
|
|
86
86
|
});
|
|
87
87
|
const digestHex = `0x${Buffer.from(digest).toString("hex")}`;
|
|
88
88
|
const tombstoneKey = membershipTombstoneKey(state.address, plan.epoch.epoch, digestHex);
|
|
89
|
-
|
|
89
|
+
const tombstoneRow = await statedb.evidence.get(tombstoneKey, context);
|
|
90
|
+
if (tombstoneRow && !isV1EvidenceRow(tombstoneRow)) throw new CustomError("INVALID_TX", "This membership approval was already used on this chain");
|
|
90
91
|
const recovered = recoverAll(digest, data.signatures);
|
|
91
92
|
const signers = new Map(recovered.map((r) => [r.address, r]));
|
|
92
93
|
const owner = rollup.lc(body.owner);
|
|
@@ -133,16 +134,13 @@ const membershipStep = (action) => async function MembershipStep(context, next)
|
|
|
133
134
|
...senderUpdates
|
|
134
135
|
}, context), context),
|
|
135
136
|
statedb.rollup.update(context.rollupStateOrig.address, rollup.updateBridge(context.rollupStateOrig, bridgeUpdates(context, nextBody), context), context),
|
|
136
|
-
statedb
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
kind: `bridge-${action}`,
|
|
142
|
-
epoch: plan.epoch.epoch
|
|
143
|
-
}
|
|
137
|
+
upsertIndexEvidence(statedb, tombstoneKey, {
|
|
138
|
+
type: "json",
|
|
139
|
+
value: {
|
|
140
|
+
kind: `bridge-${action}`,
|
|
141
|
+
epoch: plan.epoch.epoch
|
|
144
142
|
}
|
|
145
|
-
}, context)
|
|
143
|
+
}, context)
|
|
146
144
|
]);
|
|
147
145
|
if (updateVaults) await updateVaults();
|
|
148
146
|
context.senderState = newSenderState;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BRIDGE_MEMBERSHIP_ACTION, toHexDigest } from "@ocap/mcrypto";
|
|
2
|
-
import { PipeFunction, reserveIndexKey } from "@ocap/tx-pipeline";
|
|
2
|
+
import { PipeFunction, isV1EvidenceRow, reserveIndexKey } from "@ocap/tx-pipeline";
|
|
3
3
|
import { isEthereumDid } from "@arcblock/did";
|
|
4
4
|
import { rollup } from "@ocap/state";
|
|
5
5
|
|
|
@@ -17,6 +17,15 @@ declare const isRollupV1Enabled: (config: AnyObj | undefined) => boolean;
|
|
|
17
17
|
declare const peekBridge: (rollupKey: "itx.rollup", opts?: {
|
|
18
18
|
rejectV1IfDisabled?: string;
|
|
19
19
|
}) => PipeFunction<Ctx>;
|
|
20
|
+
/**
|
|
21
|
+
* Branch selection of `deposit_token_v2` / `withdraw_token_v2` (#1691, #1692, bridge/docs/deposit-withdraw-v2-unification.md
|
|
22
|
+
* §2.3): by the version of the row `itx.rollup` names, read BEFORE the v1 itx schema. A v2 bridge takes the bridge branch;
|
|
23
|
+
* anything else (a v1 rollup, no row, an address that is not even a DID) takes the v1 branch, whose pipes run unchanged and
|
|
24
|
+
* in the original order. Unlike the governance `peekBridge`, a missing statedb or a failed read is an error and never a
|
|
25
|
+
* silent fallback to v1, which would judge a bridge tx by v1 rules (a statedb-less run would otherwise refuse every bridge
|
|
26
|
+
* deposit through the v1 checks: a permanent DoS).
|
|
27
|
+
*/
|
|
28
|
+
declare const peekBridgeFailClosed: (txName: string, pipeName: string) => PipeFunction<Ctx>;
|
|
20
29
|
/** Rejects a non-v2 rollup governance action after `loadBridge` when `transaction.rollupV1.enabled === false`. */
|
|
21
30
|
declare const rejectRollupV1IfDisabled: (txName: string) => PipeFunction<Ctx>;
|
|
22
31
|
/** Run `pipe` for v1 rollups only (v2 bridges have their own pipes). */
|
|
@@ -63,9 +72,10 @@ declare const membershipTombstoneKey: (bridge: string, epoch: number, digestHex:
|
|
|
63
72
|
*/
|
|
64
73
|
declare const isBridgeIndex: (entry: AnyObj | null | undefined, kind: string) => boolean;
|
|
65
74
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
75
|
+
* A row a legacy v1 tx planted at the key (`isV1EvidenceRow`: a v1 join / leave / deposit / claim record) is not an
|
|
76
|
+
* index entry, blocks nobody and is overwritten by the next `create_rollup` (index squatting, #1505 L2, #1680). With
|
|
77
|
+
* `kind`, any other row that is not a genuine index entry of that kind blocks (fail closed, #1680): it is never
|
|
78
|
+
* overwritten.
|
|
69
79
|
*/
|
|
70
80
|
declare const indexBlocks: (entry: AnyObj | null | undefined, txSec: number, kind?: string) => boolean;
|
|
71
81
|
declare const indexData: (kind: string, bridge: string, finalAt: number | null) => {
|
|
@@ -110,4 +120,4 @@ type BridgeCtxMixin = {
|
|
|
110
120
|
[key: string]: any;
|
|
111
121
|
};
|
|
112
122
|
//#endregion
|
|
113
|
-
export { AuthorityRule, BRIDGE_MEMBERSHIP_ACTION, BridgeCtxMixin, MembershipCheck, RecoveredSignature, VerifyBridgeAuthority, bridgeUpdates, createIndexEvidence, gatewayIndexKey, ifV1, ifV2, indexBlocks, indexData, isBridgeIndex, isEthereumDid, isRollupV1Enabled, loadBridge, membershipDigest, membershipTombstoneKey, peekBridge, readItxData, recoverAll, rejectBridgeV2, rejectRollupV1IfDisabled, reserveIndexKey, toHexDigest, tokenIndexKey, txSecOf, upsertIndexEvidence };
|
|
123
|
+
export { AuthorityRule, BRIDGE_MEMBERSHIP_ACTION, BridgeCtxMixin, MembershipCheck, RecoveredSignature, VerifyBridgeAuthority, bridgeUpdates, createIndexEvidence, gatewayIndexKey, ifV1, ifV2, indexBlocks, indexData, isBridgeIndex, isEthereumDid, isRollupV1Enabled, isV1EvidenceRow, loadBridge, membershipDigest, membershipTombstoneKey, peekBridge, peekBridgeFailClosed, readItxData, recoverAll, rejectBridgeV2, rejectRollupV1IfDisabled, reserveIndexKey, toHexDigest, tokenIndexKey, txSecOf, upsertIndexEvidence };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { decodeAnySafe } from "../../util.mjs";
|
|
2
2
|
import { BRIDGE_MEMBERSHIP_ACTION, bridgeEvidenceKey, computeBridgeEndpointsHash, computeBridgeMembershipDigest, recoverBridgeSigner, toHexDigest } from "@ocap/mcrypto";
|
|
3
|
-
import { reserveIndexKey } from "@ocap/tx-pipeline";
|
|
3
|
+
import { isV1EvidenceRow, reserveIndexKey } from "@ocap/tx-pipeline";
|
|
4
4
|
import { CustomError } from "@ocap/util/lib/error";
|
|
5
5
|
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
6
|
-
import { isEthereumDid } from "@arcblock/did";
|
|
6
|
+
import { isEthereumDid, isValid } from "@arcblock/did";
|
|
7
7
|
import { evidence, rollup } from "@ocap/state";
|
|
8
8
|
import { toAddress as toAddress$1, toHex } from "@ocap/util";
|
|
9
9
|
|
|
@@ -33,6 +33,30 @@ const peekBridge = (rollupKey, opts) => async function PeekBridge(context, next)
|
|
|
33
33
|
} catch {}
|
|
34
34
|
return next();
|
|
35
35
|
};
|
|
36
|
+
/**
|
|
37
|
+
* Branch selection of `deposit_token_v2` / `withdraw_token_v2` (#1691, #1692, bridge/docs/deposit-withdraw-v2-unification.md
|
|
38
|
+
* §2.3): by the version of the row `itx.rollup` names, read BEFORE the v1 itx schema. A v2 bridge takes the bridge branch;
|
|
39
|
+
* anything else (a v1 rollup, no row, an address that is not even a DID) takes the v1 branch, whose pipes run unchanged and
|
|
40
|
+
* in the original order. Unlike the governance `peekBridge`, a missing statedb or a failed read is an error and never a
|
|
41
|
+
* silent fallback to v1, which would judge a bridge tx by v1 rules (a statedb-less run would otherwise refuse every bridge
|
|
42
|
+
* deposit through the v1 checks: a permanent DoS).
|
|
43
|
+
*/
|
|
44
|
+
const peekBridgeFailClosed = (txName, pipeName) => Object.defineProperty(async (context, next) => {
|
|
45
|
+
context.isBridgeV2 = false;
|
|
46
|
+
const address = context.itx?.rollup;
|
|
47
|
+
if (typeof address !== "string" || !address || !isValid(address.replace(/^did:abt:/, ""))) return next();
|
|
48
|
+
let row;
|
|
49
|
+
try {
|
|
50
|
+
row = await context.statedb.rollup.get(address, context);
|
|
51
|
+
} catch (err) {
|
|
52
|
+
return next(new CustomError("INTERNAL", `${txName} can not read rollup ${address}: ${String(err?.message || err)}`));
|
|
53
|
+
}
|
|
54
|
+
context.isBridgeV2 = !!row && rollup.isBridgeV2(row);
|
|
55
|
+
return next();
|
|
56
|
+
}, "name", {
|
|
57
|
+
value: pipeName,
|
|
58
|
+
configurable: true
|
|
59
|
+
});
|
|
36
60
|
/** Rejects a non-v2 rollup governance action after `loadBridge` when `transaction.rollupV1.enabled === false`. */
|
|
37
61
|
const rejectRollupV1IfDisabled = (txName) => function RejectRollupV1IfDisabled(context, next) {
|
|
38
62
|
if (!context.isBridgeV2 && !isRollupV1Enabled(context.config)) return next(new CustomError("UNSUPPORTED_TX", `${txName} is disabled because Rollup v1 is sunset`));
|
|
@@ -143,13 +167,14 @@ const isBridgeIndex = (entry, kind) => {
|
|
|
143
167
|
return entry?.data?.type === "json" && !!value && typeof value === "object" && value.kind === kind && typeof value.bridge === "string" && value.bridge.length > 0;
|
|
144
168
|
};
|
|
145
169
|
/**
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
*
|
|
170
|
+
* A row a legacy v1 tx planted at the key (`isV1EvidenceRow`: a v1 join / leave / deposit / claim record) is not an
|
|
171
|
+
* index entry, blocks nobody and is overwritten by the next `create_rollup` (index squatting, #1505 L2, #1680). With
|
|
172
|
+
* `kind`, any other row that is not a genuine index entry of that kind blocks (fail closed, #1680): it is never
|
|
173
|
+
* overwritten.
|
|
149
174
|
*/
|
|
150
175
|
const indexBlocks = (entry, txSec, kind) => {
|
|
151
|
-
if (!entry) return false;
|
|
152
|
-
if (kind && !isBridgeIndex(entry, kind)) return
|
|
176
|
+
if (!entry || isV1EvidenceRow(entry)) return false;
|
|
177
|
+
if (kind && !isBridgeIndex(entry, kind)) return true;
|
|
153
178
|
const finalAt = entry.data?.value?.finalAt;
|
|
154
179
|
return !(typeof finalAt === "number" && finalAt <= txSec);
|
|
155
180
|
};
|
|
@@ -216,4 +241,4 @@ const rejectBridgeV2 = (txName) => function RejectBridgeV2(context, next) {
|
|
|
216
241
|
};
|
|
217
242
|
|
|
218
243
|
//#endregion
|
|
219
|
-
export { BRIDGE_MEMBERSHIP_ACTION, VerifyBridgeAuthority, bridgeUpdates, createIndexEvidence, gatewayIndexKey, ifV1, ifV2, indexBlocks, indexData, isBridgeIndex, isEthereumDid, isRollupV1Enabled, loadBridge, membershipDigest, membershipTombstoneKey, peekBridge, readItxData, recoverAll, rejectBridgeV2, rejectRollupV1IfDisabled, reserveIndexKey, toHexDigest, tokenIndexKey, txSecOf, upsertIndexEvidence };
|
|
244
|
+
export { BRIDGE_MEMBERSHIP_ACTION, VerifyBridgeAuthority, bridgeUpdates, createIndexEvidence, gatewayIndexKey, ifV1, ifV2, indexBlocks, indexData, isBridgeIndex, isEthereumDid, isRollupV1Enabled, isV1EvidenceRow, loadBridge, membershipDigest, membershipTombstoneKey, peekBridge, peekBridgeFailClosed, readItxData, recoverAll, rejectBridgeV2, rejectRollupV1IfDisabled, reserveIndexKey, toHexDigest, tokenIndexKey, txSecOf, upsertIndexEvidence };
|