@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
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
2
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
3
|
+
const require_bridge_reserves = require('../bridge-reserves.cjs');
|
|
4
|
+
const require_helpers_bridge_withdraw = require('../helpers/bridge-withdraw.cjs');
|
|
5
|
+
const require_pipes_bridge_release_gate = require('./bridge-release-gate.cjs');
|
|
6
|
+
const require_pipes_bridge_reserve_v2_gate = require('./bridge-reserve-v2-gate.cjs');
|
|
3
7
|
let _ocap_mcrypto = require("@ocap/mcrypto");
|
|
4
8
|
let _ocap_util = require("@ocap/util");
|
|
5
9
|
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
10
|
+
let _arcblock_did = require("@arcblock/did");
|
|
11
|
+
let _arcblock_did_util = require("@arcblock/did-util");
|
|
6
12
|
let _ocap_state = require("@ocap/state");
|
|
7
13
|
let lodash_cloneDeep = require("lodash/cloneDeep");
|
|
8
14
|
lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
|
|
9
|
-
let _arcblock_did = require("@arcblock/did");
|
|
10
15
|
let lodash_isEqual = require("lodash/isEqual");
|
|
11
16
|
lodash_isEqual = require_rolldown_runtime.__toESM(lodash_isEqual);
|
|
12
17
|
|
|
@@ -28,6 +33,37 @@ const TRACKED_STATE_TABLES = [
|
|
|
28
33
|
"evidence",
|
|
29
34
|
"balance"
|
|
30
35
|
];
|
|
36
|
+
const isZeroAmount = (value) => {
|
|
37
|
+
const str = String(value ?? "0");
|
|
38
|
+
return CANONICAL_UINT_STRING_PATTERN.test(str) && new _ocap_util.BN(str, 10).isZero();
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Whether `stake` is a Stake-for-Token of `token`: staked on the official token under the token's symbol as nonce
|
|
42
|
+
* (`toStakeAddress(sender, config.token.address, symbol)`, see `create_token_factory`). Any account can hold such a
|
|
43
|
+
* stake for a symbol; who may use it is decided by the caller (#1422).
|
|
44
|
+
*/
|
|
45
|
+
function isTokenIssuanceStakeOf(stake, token, officialTokenAddress) {
|
|
46
|
+
const nonce = stake?.nonce;
|
|
47
|
+
if (!stake?.address || !stake.sender || !stake.receiver || typeof nonce !== "string" || !nonce) return false;
|
|
48
|
+
if (!token?.address || !token.symbol || !token.tokenFactoryAddress) return false;
|
|
49
|
+
if (!officialTokenAddress || !(0, _ocap_util.isSameDid)(stake.receiver, officialTokenAddress)) return false;
|
|
50
|
+
if ((0, _ocap_util.isSameDid)(token.address, officialTokenAddress)) return false;
|
|
51
|
+
if (nonce.toUpperCase() !== String(token.symbol).toUpperCase()) return false;
|
|
52
|
+
try {
|
|
53
|
+
return (0, _ocap_util.isSameDid)((0, _arcblock_did_util.toStakeAddress)(stake.sender, stake.receiver, nonce), stake.address);
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Whether the token behind `factory` has been 100% redeemed: token and factory point at each other, nothing is in
|
|
60
|
+
* circulation (`totalSupply`, `currentSupply`) and no reserve is left in the curve (`reserveBalance`).
|
|
61
|
+
*/
|
|
62
|
+
function isTokenFullyRedeemed(token, factory) {
|
|
63
|
+
if (!token?.address || !factory?.address || !factory.tokenAddress || !token.tokenFactoryAddress) return false;
|
|
64
|
+
if (!(0, _ocap_util.isSameDid)(factory.tokenAddress, token.address) || !(0, _ocap_util.isSameDid)(token.tokenFactoryAddress, factory.address)) return false;
|
|
65
|
+
return isZeroAmount(token.totalSupply) && isZeroAmount(factory.currentSupply) && isZeroAmount(factory.reserveBalance);
|
|
66
|
+
}
|
|
31
67
|
const TX_TYPES_ALLOWED_TO_CREATE_ASSET = new Set([
|
|
32
68
|
"fg:t:create_asset",
|
|
33
69
|
"create_asset",
|
|
@@ -98,7 +134,8 @@ function createEmptyTracker() {
|
|
|
98
134
|
writtenKeys,
|
|
99
135
|
addressAliases: /* @__PURE__ */ new Map(),
|
|
100
136
|
totalWriteOps: 0,
|
|
101
|
-
unauthorizedDeletions: 0
|
|
137
|
+
unauthorizedDeletions: 0,
|
|
138
|
+
directBalanceWrites: []
|
|
102
139
|
};
|
|
103
140
|
}
|
|
104
141
|
function getEntityKey(table, rawKey, stateObj) {
|
|
@@ -258,6 +295,12 @@ function installStateWriteInterceptor(context) {
|
|
|
258
295
|
}
|
|
259
296
|
return res;
|
|
260
297
|
};
|
|
298
|
+
if (tableName === "balance" && prop === "updateBalance") return async function interceptedUpdateBalance(params, ...rest) {
|
|
299
|
+
const addr = normalizeEntityKey(params?.address);
|
|
300
|
+
if (addr) tracker.directBalanceWrites.push(addr);
|
|
301
|
+
tracker.totalWriteOps += 1;
|
|
302
|
+
return origVal.apply(origTable, [params, ...rest]);
|
|
303
|
+
};
|
|
261
304
|
if (prop === "remove" || prop === "delete" || prop === "destroy" || prop === "clear") return async function interceptedDelete(...args) {
|
|
262
305
|
tracker.unauthorizedDeletions += 1;
|
|
263
306
|
tracker.totalWriteOps += 1;
|
|
@@ -478,6 +521,51 @@ function inspectPostExecutionInvariants(context) {
|
|
|
478
521
|
const tracker = context._stateWriteTracker;
|
|
479
522
|
if (tracker && tracker.unauthorizedDeletions > 0) throw createInvariantError("STATE_DELETION_FORBIDDEN", `Post-Execution Invariant Gate: unauthorized state deletion detected (${tracker.unauthorizedDeletions} delete operation(s))`);
|
|
480
523
|
const { beforeByTable, afterByTable, writtenCount } = collectUnifiedBeforeAndAfterStates(context);
|
|
524
|
+
require_pipes_bridge_reserve_v2_gate.assertBridgeReservesV2Protected({
|
|
525
|
+
txType: require_bridge_reserves.stripTxTypePrefix(txType),
|
|
526
|
+
isReserveAddress: (key) => getDidRoleSafe(key) === RoleType.ROLE_BRIDGE_RESERVE,
|
|
527
|
+
norm: normalizeEntityKey,
|
|
528
|
+
createGateError: createInvariantError,
|
|
529
|
+
tokenBalances: (tokens, label) => normalizeTokenBalanceRecord(tokens, label),
|
|
530
|
+
before: beforeByTable,
|
|
531
|
+
after: afterByTable,
|
|
532
|
+
directBalanceWrites: tracker?.directBalanceWrites ?? [],
|
|
533
|
+
writtenBalanceKeys: tracker?.writtenKeys.get("balance"),
|
|
534
|
+
enabled: !!(context.config?.transaction)?.bridge?.enabled,
|
|
535
|
+
resolution: context._bridgeReserveGate ?? null,
|
|
536
|
+
releaseKind: context.itx?.kind,
|
|
537
|
+
checkWithdraw: (bridge, credited) => {
|
|
538
|
+
const withdraw = require_helpers_bridge_withdraw.checkBridgeWithdraw(context, bridge);
|
|
539
|
+
if (require_helpers_bridge_withdraw.isBridgeWithdrawFailure(withdraw)) return `${withdraw.code}: ${withdraw.message}`;
|
|
540
|
+
if (!credited.eq(new _ocap_util.BN(withdraw.amount))) return `the reserve grew by ${credited.toString(10)}, not by the withdrawn amount ${withdraw.amount}`;
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
{
|
|
545
|
+
const cfgVaults = context.config?.vaults || {};
|
|
546
|
+
const asList = (x) => Array.isArray(x) ? x : [];
|
|
547
|
+
require_pipes_bridge_release_gate.assertBridgeReleaseProtected({
|
|
548
|
+
txType: require_bridge_reserves.stripTxTypePrefix(txType),
|
|
549
|
+
itx: context.itx ?? {},
|
|
550
|
+
payer: normalizeEntityKey(context.tx?.from),
|
|
551
|
+
norm: normalizeEntityKey,
|
|
552
|
+
isReserveAddress: (key) => getDidRoleSafe(key) === RoleType.ROLE_BRIDGE_RESERVE,
|
|
553
|
+
createGateError: createInvariantError,
|
|
554
|
+
tokenBalances: (tokens, label) => normalizeTokenBalanceRecord(tokens, label),
|
|
555
|
+
before: beforeByTable,
|
|
556
|
+
after: afterByTable,
|
|
557
|
+
written: (table) => tracker?.writtenKeys.get(table),
|
|
558
|
+
directBalanceWrites: tracker?.directBalanceWrites ?? [],
|
|
559
|
+
officialToken: normalizeEntityKey(context.config?.token?.address || ""),
|
|
560
|
+
vaults: new Set([
|
|
561
|
+
cfgVaults.slashedStake,
|
|
562
|
+
cfgVaults.txFee,
|
|
563
|
+
...asList(cfgVaults.txFees),
|
|
564
|
+
...asList(cfgVaults.txGas)
|
|
565
|
+
].filter((x) => typeof x === "string" && !!x).map((x) => normalizeEntityKey(x))),
|
|
566
|
+
resolution: context._bridgeReserveGate ?? null
|
|
567
|
+
});
|
|
568
|
+
}
|
|
481
569
|
if (writtenCount > maxWriteSetEntries) throw createInvariantError("RW_SET_LIMIT_EXCEEDED", `Post-Execution Invariant Gate: transaction modified ${writtenCount} state entries, exceeding ceiling ${maxWriteSetEntries}`);
|
|
482
570
|
const beforeAccounts = beforeByTable.get("account");
|
|
483
571
|
const afterAccounts = afterByTable.get("account");
|
|
@@ -572,6 +660,7 @@ function inspectPostExecutionInvariants(context) {
|
|
|
572
660
|
} else if (!afterSupply.isZero()) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: create_token_factory must initialize token ${tokAddr} with totalSupply = 0`);
|
|
573
661
|
}
|
|
574
662
|
}
|
|
663
|
+
const isRevokeStakeTx = txType === "fg:t:revoke_stake" || txType === "revoke_stake";
|
|
575
664
|
const factoryByTokenAddr = /* @__PURE__ */ new Map();
|
|
576
665
|
for (const [factoryAddr, afterFac] of afterFactories.entries()) {
|
|
577
666
|
const beforeFac = beforeFactories.get(factoryAddr) ?? null;
|
|
@@ -586,6 +675,16 @@ function inspectPostExecutionInvariants(context) {
|
|
|
586
675
|
if (beforeTokenAddr && facTokenAddr !== beforeTokenAddr) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: tokenFactory ${factoryAddr} tokenAddress is immutable`);
|
|
587
676
|
if (beforeReserveAddr && facReserveAddr !== beforeReserveAddr) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: tokenFactory ${factoryAddr} reserveAddress is immutable`);
|
|
588
677
|
}
|
|
678
|
+
const afterFacStatus = afterFac.status;
|
|
679
|
+
const beforeFacStatus = beforeFac ? beforeFac.status : void 0;
|
|
680
|
+
if (beforeFacStatus === "RETIRED" && afterFacStatus !== "RETIRED") throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: retired tokenFactory ${factoryAddr} cannot be reactivated`);
|
|
681
|
+
if (afterFacStatus === "RETIRED") {
|
|
682
|
+
const facToken = afterTokens.get(facTokenAddr) ?? beforeTokens.get(facTokenAddr) ?? null;
|
|
683
|
+
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`);
|
|
684
|
+
if (beforeFacStatus !== "RETIRED") {
|
|
685
|
+
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`);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
589
688
|
if (facTokenAddr) {
|
|
590
689
|
if (factoryByTokenAddr.has(facTokenAddr) && factoryByTokenAddr.get(facTokenAddr) !== factoryAddr) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", `Post-Execution Invariant Gate: multiple tokenFactories referencing token ${facTokenAddr}`);
|
|
591
690
|
factoryByTokenAddr.set(facTokenAddr, factoryAddr);
|
|
@@ -600,7 +699,13 @@ function inspectPostExecutionInvariants(context) {
|
|
|
600
699
|
}
|
|
601
700
|
const isCreateRollupBlockTx = txType === "fg:t:create_rollup_block" || txType === "create_rollup_block";
|
|
602
701
|
if (isCreateRollupBlockTx) {
|
|
702
|
+
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");
|
|
603
703
|
const rollupState = context.rollupState;
|
|
704
|
+
if ([
|
|
705
|
+
rollupState,
|
|
706
|
+
...Array.from(beforeByTable.get("rollup")?.values() ?? []),
|
|
707
|
+
...Array.from(afterByTable.get("rollup")?.values() ?? [])
|
|
708
|
+
].some((row) => row && _ocap_state.rollup.isBridgeV2(row))) throw createInvariantError("TOKEN_CONSERVATION_VIOLATION", "Post-Execution Invariant Gate: create_rollup_block supply exemption is forbidden for v2 bridges");
|
|
604
709
|
const defaultRollupToken = normalizeEntityKey(rollupState?.tokenAddress || officialTokenAddress);
|
|
605
710
|
const txStates = context.txStates || [];
|
|
606
711
|
const seenRollupTxHashes = /* @__PURE__ */ new Set();
|
|
@@ -710,6 +815,15 @@ function inspectPostExecutionInvariants(context) {
|
|
|
710
815
|
const isSlashStakeTx = txType === "fg:t:slash_stake" || txType === "slash_stake";
|
|
711
816
|
const isRollupDepositTx = txType === "fg:t:deposit_token_v2" || txType === "deposit_token_v2";
|
|
712
817
|
const isClaimBlockRewardTx = txType === "fg:t:claim_block_reward" || txType === "claim_block_reward";
|
|
818
|
+
const isStakeOfRetiredToken = (stakeRec) => {
|
|
819
|
+
for (const afterFac of afterFactories.values()) {
|
|
820
|
+
const fac = afterFac;
|
|
821
|
+
if (fac.status !== "RETIRED") continue;
|
|
822
|
+
const tok = afterTokens.get(normalizeEntityKey(fac.tokenAddress)) ?? null;
|
|
823
|
+
if (isTokenIssuanceStakeOf(stakeRec, tok, officialTokenAddress) && isTokenFullyRedeemed(tok, fac)) return true;
|
|
824
|
+
}
|
|
825
|
+
return false;
|
|
826
|
+
};
|
|
713
827
|
for (const [stakeAddr, afterStakeRec] of afterStakes.entries()) {
|
|
714
828
|
const beforeStakeRec = beforeStakes.get(stakeAddr) ?? null;
|
|
715
829
|
const afterStake = afterStakeRec;
|
|
@@ -747,8 +861,9 @@ function inspectPostExecutionInvariants(context) {
|
|
|
747
861
|
const isRollupStake = receiverRole === RoleType.ROLE_ROLLUP && !isProtocolTokenOrAssetStake;
|
|
748
862
|
if (beforeStake.revocable === false) {
|
|
749
863
|
const isAllowedRollupCloseUnlock = (isCloseRollupTx || isLeaveRollupTx) && isRollupStake;
|
|
750
|
-
|
|
751
|
-
if (!isAllowedRollupCloseUnlock) {
|
|
864
|
+
const isAllowedRetiredTokenUnlock = isRevokeStakeTx && isStakeOfRetiredToken(beforeStake);
|
|
865
|
+
if (afterStake.revocable !== false && !isAllowedRollupCloseUnlock && !isAllowedRetiredTokenUnlock) throw createInvariantError("STAKE_PROTECTION_VIOLATION", `Post-Execution Invariant Gate: permanently locked stake ${stakeAddr} (revocable=false) cannot be unlocked`);
|
|
866
|
+
if (!isAllowedRollupCloseUnlock && !isAllowedRetiredTokenUnlock) {
|
|
752
867
|
const hasConfiguredSlashers = Array.isArray(beforeStake.slashers) && beforeStake.slashers.length > 0;
|
|
753
868
|
const isAllowedLockedStakeSlash = isSlashStakeTx && !isProtocolTokenOrAssetStake && hasConfiguredSlashers;
|
|
754
869
|
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}`);
|
|
@@ -796,5 +911,7 @@ exports.TRACKED_STATE_TABLES = TRACKED_STATE_TABLES;
|
|
|
796
911
|
exports.default = post_execution_invariant_gate_default;
|
|
797
912
|
exports.inspectPostExecutionInvariants = inspectPostExecutionInvariants;
|
|
798
913
|
exports.installStateWriteInterceptor = installStateWriteInterceptor;
|
|
914
|
+
exports.isTokenFullyRedeemed = isTokenFullyRedeemed;
|
|
915
|
+
exports.isTokenIssuanceStakeOf = isTokenIssuanceStakeOf;
|
|
799
916
|
exports.normalizeEntityKey = normalizeEntityKey;
|
|
800
917
|
exports.rollbackTrackedStateWrites = rollbackTrackedStateWrites;
|
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
import { PipeFunction } from "../runner.cjs";
|
|
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 };
|
|
@@ -2,18 +2,20 @@ Object.defineProperty(exports, '__esModule', { value: true });
|
|
|
2
2
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
3
3
|
const require_encrypted_nft_envelope = require('../encrypted-nft-envelope.cjs');
|
|
4
4
|
const require_pipes_decode_itx = require('./decode-itx.cjs');
|
|
5
|
-
const require_pipes_decode_tx = require('./decode-tx.cjs');
|
|
6
5
|
const require_runner = require('../runner.cjs');
|
|
7
6
|
const require_pipes_verify_blocked = require('./verify-blocked.cjs');
|
|
8
7
|
const require_pipes_verify_service_fee = require('./verify-service-fee.cjs');
|
|
9
8
|
const require_pipes_verify_signature = require('./verify-signature.cjs');
|
|
10
9
|
const require_pipes_verify_tx = require('./verify-tx.cjs');
|
|
11
10
|
const require_pipes_verify_tx_size = require('./verify-tx-size.cjs');
|
|
11
|
+
const require_pipes_decode_tx = require('./decode-tx.cjs');
|
|
12
12
|
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
13
|
-
let lodash_get = require("lodash/get");
|
|
14
|
-
lodash_get = require_rolldown_runtime.__toESM(lodash_get);
|
|
15
13
|
let _ocap_message = require("@ocap/message");
|
|
16
14
|
let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
|
|
15
|
+
let lodash_get = require("lodash/get");
|
|
16
|
+
lodash_get = require_rolldown_runtime.__toESM(lodash_get);
|
|
17
|
+
let lodash_cloneDeep = require("lodash/cloneDeep");
|
|
18
|
+
lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
|
|
17
19
|
|
|
18
20
|
//#region src/pipes/pre-flight-waf.ts
|
|
19
21
|
const MAX_PREFLIGHT_JSON_DEPTH = 16;
|
|
@@ -32,7 +34,7 @@ const FORBIDDEN_STORAGE_DATA_URI_PATTERN = /^\s*data\s*:\s*(?:image\/|audio\/|vi
|
|
|
32
34
|
const FORBIDDEN_BINARY_MAGIC_BASE64_PATTERN = /^(?:AGFzbQ|f0VMRg|JVBERi0|UEsDB|H4sIA|iVBORw0KGgo|(?:\/9j\/|_9j_)4AAQ|R0lGOD(?:lh|dh))/;
|
|
33
35
|
const FORBIDDEN_BINARY_MAGIC_RAW_PATTERN = /^(?:\x00asm|\x7fELF|%PDF-|PK\x03\x04|\x1f\x8b\x08[\x00-\x1f]|\x89PNG\r\n\x1a\n|\xff\xd8\xff[\xdb\xe0\xe1\xe2\xee]|GIF8[79]a)/;
|
|
34
36
|
const FORBIDDEN_CONTROL_CHAR_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
|
|
35
|
-
const BASE64_WIRE_PATTERN = /^[A-Za-z0-9
|
|
37
|
+
const BASE64_WIRE_PATTERN = /^(?:[A-Za-z0-9+/]+={0,2}|[A-Za-z0-9_-]+={0,2})$/;
|
|
36
38
|
const STANDARD_BOUNDED_LIST_KEYS = [
|
|
37
39
|
"inputs",
|
|
38
40
|
"outputs",
|
|
@@ -123,20 +125,55 @@ function getAllowedTopLevelItxKeys(typeUrl) {
|
|
|
123
125
|
return null;
|
|
124
126
|
}
|
|
125
127
|
}
|
|
128
|
+
const MAX_WIRE_WHITESPACE_SLACK = 64;
|
|
129
|
+
/**
|
|
130
|
+
* Compute the maximum allowed raw transaction wire size in bytes for a given chain config (#1336, #1516).
|
|
131
|
+
* Shared between `PreFlightWaf` and `DecodeTx` so callers that invoke `DecodeTx` without `PreFlightWaf`
|
|
132
|
+
* (e.g. `decodeOcapWireTx` on Cloudflare Durable Objects) enforce the exact same ceiling before `fromBase64`.
|
|
133
|
+
*/
|
|
134
|
+
function computeMaxWireEnvelopeBytes(config) {
|
|
135
|
+
const maxTxSizeMap = (0, lodash_get.default)(config, "transaction.maxTxSize");
|
|
136
|
+
const configuredLimits = maxTxSizeMap && typeof maxTxSizeMap === "object" ? Object.values(maxTxSizeMap).filter((v) => typeof v === "number" && Number.isFinite(v) && v > 0) : [];
|
|
137
|
+
if (configuredLimits.length === 0) return MAX_PREFLIGHT_WIRE_BYTES_FALLBACK;
|
|
138
|
+
const rawMaxAssetSize = (0, lodash_get.default)(config, "transaction.maxAssetSize");
|
|
139
|
+
const maxAssetSize = typeof rawMaxAssetSize === "number" && Number.isFinite(rawMaxAssetSize) && rawMaxAssetSize > 0 ? rawMaxAssetSize : 65536;
|
|
140
|
+
const rawMaxExtraSize = (0, lodash_get.default)(config, "transaction.maxExtraSize");
|
|
141
|
+
const maxExtraSize = typeof rawMaxExtraSize === "number" && Number.isFinite(rawMaxExtraSize) && rawMaxExtraSize >= 0 ? rawMaxExtraSize : 8192;
|
|
142
|
+
return Math.max(...configuredLimits, maxAssetSize) + maxExtraSize;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Upper-bound decoded byte length of a trimmed base64 / base64url string.
|
|
146
|
+
* Exact for all canonical base64 / base64url payloads (`0`, `1`, or `2` mod 3 bytes) and
|
|
147
|
+
* never under-estimates `Buffer.from(base64.unescape(trimmed), 'base64').byteLength` on malformed input.
|
|
148
|
+
*/
|
|
149
|
+
function estimateBase64WireBytes(trimmed) {
|
|
150
|
+
const len = trimmed.length;
|
|
151
|
+
const pad = len >= 4 && len % 4 === 0 ? trimmed.endsWith("==") ? 2 : trimmed.endsWith("=") ? 1 : 0 : 0;
|
|
152
|
+
return Math.max(0, Math.floor(len * 3 / 4) - pad);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Enforce the raw wire byte ceiling in O(1) before `.trim()`, regex scanning, or base64 decoding (#1516).
|
|
156
|
+
* Returns the ASCII-trimmed string when within the configured ceiling.
|
|
157
|
+
*/
|
|
158
|
+
function assertWireByteCeiling(txBase64, config, messagePrefix = "Raw transaction wire size") {
|
|
159
|
+
const maxConfiguredTxBytes = computeMaxWireEnvelopeBytes(config);
|
|
160
|
+
const maxBase64Chars = Math.ceil(maxConfiguredTxBytes * 4 / 3) + 4;
|
|
161
|
+
if (txBase64.length > maxBase64Chars + MAX_WIRE_WHITESPACE_SLACK) throw new _ocap_util_lib_error.CustomError("INVALID_TX_SIZE", `${messagePrefix} (${Math.floor(txBase64.length * 3 / 4)} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
|
|
162
|
+
const utf8ByteLen = Buffer.byteLength(txBase64, "utf8");
|
|
163
|
+
if (utf8ByteLen > maxBase64Chars + MAX_WIRE_WHITESPACE_SLACK) throw new _ocap_util_lib_error.CustomError("INVALID_TX_SIZE", `${messagePrefix} (${Math.floor(utf8ByteLen * 3 / 4)} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
|
|
164
|
+
const trimmed = txBase64.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
|
|
165
|
+
const estimatedWireBytes = estimateBase64WireBytes(trimmed);
|
|
166
|
+
if (estimatedWireBytes > maxConfiguredTxBytes) throw new _ocap_util_lib_error.CustomError("INVALID_TX_SIZE", `${messagePrefix} (${estimatedWireBytes} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
|
|
167
|
+
return trimmed;
|
|
168
|
+
}
|
|
126
169
|
/**
|
|
127
170
|
* Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
|
|
128
171
|
*/
|
|
129
172
|
function assertRawWireEnvelope(txBase64, config) {
|
|
130
173
|
if (!txBase64 || typeof txBase64 !== "string" || txBase64.length < 20) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Transaction data is empty or too short");
|
|
131
|
-
const trimmed = txBase64
|
|
132
|
-
if (
|
|
133
|
-
|
|
134
|
-
const configuredLimits = Object.values(maxTxSizeMap).filter((v) => typeof v === "number" && v > 0);
|
|
135
|
-
const maxAssetSize = (0, lodash_get.default)(config, "transaction.maxAssetSize", 65536) || 65536;
|
|
136
|
-
const maxExtraSize = (0, lodash_get.default)(config, "transaction.maxExtraSize", 8192) || 8192;
|
|
137
|
-
const maxConfiguredTxBytes = configuredLimits.length > 0 ? Math.max(...configuredLimits, maxAssetSize) + maxExtraSize : MAX_PREFLIGHT_WIRE_BYTES_FALLBACK;
|
|
138
|
-
const estimatedWireBytes = Math.floor(trimmed.length * 3 / 4);
|
|
139
|
-
if (estimatedWireBytes > maxConfiguredTxBytes) throw new _ocap_util_lib_error.CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: raw transaction wire size (${estimatedWireBytes} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
|
|
174
|
+
const trimmed = assertWireByteCeiling(txBase64, config, "Pre-Flight WAF: raw transaction wire size");
|
|
175
|
+
if (trimmed.length < 20) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Transaction data is empty or too short");
|
|
176
|
+
if (txBase64 !== trimmed || !BASE64_WIRE_PATTERN.test(trimmed)) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains invalid non-base64 characters");
|
|
140
177
|
}
|
|
141
178
|
/**
|
|
142
179
|
* Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
|
|
@@ -535,6 +572,110 @@ function PreFlightWaf(context, next) {
|
|
|
535
572
|
return next(err);
|
|
536
573
|
}
|
|
537
574
|
}
|
|
575
|
+
const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = Symbol.for("@ocap/tx-pipeline/preFlightVerifiedSnapshot");
|
|
576
|
+
function serializeExtraField(val) {
|
|
577
|
+
if (val === void 0) return "u";
|
|
578
|
+
if (val === null) return "n";
|
|
579
|
+
if (typeof val === "string") return `s:${val}`;
|
|
580
|
+
try {
|
|
581
|
+
return `j:${JSON.stringify(val)}`;
|
|
582
|
+
} catch {
|
|
583
|
+
return "invalid";
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Apply the verified pre-flight snapshot onto `context` if and only if all verified inputs
|
|
588
|
+
* (`txBase64`, `config` invariants, and `extra.{txExtra,gasStakeHeaders,coSignature}`) are
|
|
589
|
+
* unchanged since `inspectTransactionPreFlight(context)` succeeded.
|
|
590
|
+
*/
|
|
591
|
+
function tryApplyPreFlightVerifiedSnapshot(context) {
|
|
592
|
+
context._preFlightWafScanned = false;
|
|
593
|
+
context._preFlightVerified = false;
|
|
594
|
+
context._preFlightSnapshotApplied = false;
|
|
595
|
+
const snap = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
|
|
596
|
+
if (!snap || typeof context.txBase64 !== "string" || snap.txBase64 !== context.txBase64) return false;
|
|
597
|
+
const config = context.config;
|
|
598
|
+
if (snap.configRef !== config) return false;
|
|
599
|
+
const supportedTxs = (0, lodash_get.default)(config, "transaction.supportedTxs");
|
|
600
|
+
const multiSignV2Txs = (0, lodash_get.default)(config, "transaction.multiSignV2Txs");
|
|
601
|
+
const defaultSizeLimit = (0, lodash_get.default)(config, "transaction.maxTxSize.default");
|
|
602
|
+
if (snap.chainId !== (0, lodash_get.default)(config, "chainId") || snap.tokenDecimal !== (0, lodash_get.default)(config, "token.decimal") || snap.txFeeForType !== (snap.txType ? (0, lodash_get.default)(config, [
|
|
603
|
+
"transaction",
|
|
604
|
+
"txFee",
|
|
605
|
+
snap.txType
|
|
606
|
+
]) : void 0) || snap.maxTxSizeForType !== (snap.txType ? (0, lodash_get.default)(config, [
|
|
607
|
+
"transaction",
|
|
608
|
+
"maxTxSize",
|
|
609
|
+
snap.txType
|
|
610
|
+
], defaultSizeLimit) : defaultSizeLimit) || snap.maxExtraSize !== (0, lodash_get.default)(config, "transaction.maxExtraSize") || snap.maxMultisig !== (0, lodash_get.default)(config, "transaction.maxMultisig") || snap.maxListSize !== (0, lodash_get.default)(config, "transaction.maxListSize") || snap.maxAssetSize !== (0, lodash_get.default)(config, "transaction.maxAssetSize") || snap.isSupportedTx !== Boolean(Array.isArray(supportedTxs) && supportedTxs.includes(snap.txType)) || snap.isMultiSignV2Tx !== Boolean(Array.isArray(multiSignV2Txs) && multiSignV2Txs.includes(snap.txType))) return false;
|
|
611
|
+
const extra = context.extra;
|
|
612
|
+
if (snap.txExtraSerialized !== serializeExtraField(extra?.txExtra) || snap.gasStakeHeadersSerialized !== serializeExtraField(extra?.gasStakeHeaders) || snap.coSignatureSerialized !== serializeExtraField(extra?.coSignature)) return false;
|
|
613
|
+
const pinned = extra?.txTime;
|
|
614
|
+
const pinnedMs = pinned === void 0 || pinned === null || pinned === "" ? NaN : new Date(pinned).getTime();
|
|
615
|
+
const resolvedTxTime = Number.isFinite(pinnedMs) ? new Date(pinnedMs).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
|
|
616
|
+
Object.defineProperty(context, "tx", {
|
|
617
|
+
value: (0, lodash_cloneDeep.default)(snap.tx),
|
|
618
|
+
enumerable: true,
|
|
619
|
+
configurable: true,
|
|
620
|
+
writable: true
|
|
621
|
+
});
|
|
622
|
+
Object.defineProperty(context, "txEncoding", {
|
|
623
|
+
value: snap.txEncoding,
|
|
624
|
+
enumerable: true,
|
|
625
|
+
configurable: true,
|
|
626
|
+
writable: true
|
|
627
|
+
});
|
|
628
|
+
Object.defineProperty(context, "txSize", {
|
|
629
|
+
value: snap.txSize,
|
|
630
|
+
enumerable: true,
|
|
631
|
+
configurable: true,
|
|
632
|
+
writable: true
|
|
633
|
+
});
|
|
634
|
+
Object.defineProperty(context, "txHash", {
|
|
635
|
+
value: snap.txHash,
|
|
636
|
+
enumerable: true,
|
|
637
|
+
configurable: true,
|
|
638
|
+
writable: true
|
|
639
|
+
});
|
|
640
|
+
Object.defineProperty(context, "unsignedTxHash", {
|
|
641
|
+
value: snap.unsignedTxHash,
|
|
642
|
+
enumerable: true,
|
|
643
|
+
configurable: true,
|
|
644
|
+
writable: true
|
|
645
|
+
});
|
|
646
|
+
Object.defineProperty(context, "txTime", {
|
|
647
|
+
value: resolvedTxTime,
|
|
648
|
+
enumerable: true,
|
|
649
|
+
configurable: true,
|
|
650
|
+
writable: true
|
|
651
|
+
});
|
|
652
|
+
Object.defineProperty(context, "txBaseGas", {
|
|
653
|
+
value: snap.txBaseGas,
|
|
654
|
+
enumerable: true,
|
|
655
|
+
configurable: true,
|
|
656
|
+
writable: true
|
|
657
|
+
});
|
|
658
|
+
Object.defineProperty(context, "itx", {
|
|
659
|
+
value: (0, lodash_cloneDeep.default)(snap.itx),
|
|
660
|
+
enumerable: true,
|
|
661
|
+
configurable: true,
|
|
662
|
+
writable: true
|
|
663
|
+
});
|
|
664
|
+
Object.defineProperty(context, "txType", {
|
|
665
|
+
value: snap.txType,
|
|
666
|
+
enumerable: true,
|
|
667
|
+
configurable: true,
|
|
668
|
+
writable: true
|
|
669
|
+
});
|
|
670
|
+
context._baseTxSize = snap.baseTxSize;
|
|
671
|
+
context._extraSizeCounted = snap.extraSizeCounted;
|
|
672
|
+
context._rawTxItxBeforeNormalize = snap.rawTxItxBeforeNormalize;
|
|
673
|
+
context._preFlightWafScanned = true;
|
|
674
|
+
context._preFlightVerified = true;
|
|
675
|
+
return true;
|
|
676
|
+
}
|
|
677
|
+
PreFlightWaf.SNAPSHOT_SYMBOL = PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL;
|
|
678
|
+
PreFlightWaf.tryApplyVerifiedSnapshot = tryApplyPreFlightVerifiedSnapshot;
|
|
538
679
|
/**
|
|
539
680
|
* Stateless, zero-DB-I/O Pre-Flight inspection runner for `OCAPResolver.sendTx`
|
|
540
681
|
* BEFORE enqueuing into the single-writer queue (`this.queue`) or acquiring the SQLite write lock.
|
|
@@ -594,9 +735,57 @@ async function inspectTransactionPreFlight(context) {
|
|
|
594
735
|
configurable: true,
|
|
595
736
|
writable: true
|
|
596
737
|
});
|
|
597
|
-
|
|
738
|
+
const baseTxSize = preFlightCtx._baseTxSize ?? preFlightCtx.txSize;
|
|
739
|
+
const extraSizeCounted = Boolean(preFlightCtx._extraSizeCounted);
|
|
740
|
+
const rawTxItxBeforeNormalize = preFlightCtx._rawTxItxBeforeNormalize;
|
|
741
|
+
context._baseTxSize = baseTxSize;
|
|
742
|
+
context._extraSizeCounted = extraSizeCounted;
|
|
743
|
+
context._rawTxItxBeforeNormalize = rawTxItxBeforeNormalize;
|
|
598
744
|
context._preFlightWafScanned = true;
|
|
599
745
|
context._preFlightVerified = true;
|
|
746
|
+
if (typeof context.txBase64 === "string" && preFlightCtx.tx && preFlightCtx.itx && preFlightCtx.txType) {
|
|
747
|
+
const config = context.config;
|
|
748
|
+
const supportedTxs = (0, lodash_get.default)(config, "transaction.supportedTxs");
|
|
749
|
+
const multiSignV2Txs = (0, lodash_get.default)(config, "transaction.multiSignV2Txs");
|
|
750
|
+
const defaultSizeLimit = (0, lodash_get.default)(config, "transaction.maxTxSize.default");
|
|
751
|
+
const extra = context.extra;
|
|
752
|
+
context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL] = {
|
|
753
|
+
txBase64: context.txBase64,
|
|
754
|
+
configRef: config,
|
|
755
|
+
chainId: (0, lodash_get.default)(config, "chainId"),
|
|
756
|
+
tokenDecimal: (0, lodash_get.default)(config, "token.decimal"),
|
|
757
|
+
txFeeForType: (0, lodash_get.default)(config, [
|
|
758
|
+
"transaction",
|
|
759
|
+
"txFee",
|
|
760
|
+
preFlightCtx.txType
|
|
761
|
+
]),
|
|
762
|
+
maxTxSizeForType: (0, lodash_get.default)(config, [
|
|
763
|
+
"transaction",
|
|
764
|
+
"maxTxSize",
|
|
765
|
+
preFlightCtx.txType
|
|
766
|
+
], defaultSizeLimit),
|
|
767
|
+
maxExtraSize: (0, lodash_get.default)(config, "transaction.maxExtraSize"),
|
|
768
|
+
maxMultisig: (0, lodash_get.default)(config, "transaction.maxMultisig"),
|
|
769
|
+
maxListSize: (0, lodash_get.default)(config, "transaction.maxListSize"),
|
|
770
|
+
maxAssetSize: (0, lodash_get.default)(config, "transaction.maxAssetSize"),
|
|
771
|
+
isSupportedTx: Boolean(Array.isArray(supportedTxs) && supportedTxs.includes(preFlightCtx.txType)),
|
|
772
|
+
isMultiSignV2Tx: Boolean(Array.isArray(multiSignV2Txs) && multiSignV2Txs.includes(preFlightCtx.txType)),
|
|
773
|
+
txExtraSerialized: serializeExtraField(extra?.txExtra),
|
|
774
|
+
gasStakeHeadersSerialized: serializeExtraField(extra?.gasStakeHeaders),
|
|
775
|
+
coSignatureSerialized: serializeExtraField(extra?.coSignature),
|
|
776
|
+
tx: (0, lodash_cloneDeep.default)(preFlightCtx.tx),
|
|
777
|
+
txEncoding: preFlightCtx.txEncoding,
|
|
778
|
+
txSize: preFlightCtx.txSize,
|
|
779
|
+
baseTxSize,
|
|
780
|
+
extraSizeCounted,
|
|
781
|
+
txHash: preFlightCtx.txHash,
|
|
782
|
+
unsignedTxHash: preFlightCtx.unsignedTxHash,
|
|
783
|
+
txBaseGas: Boolean(preFlightCtx.txBaseGas),
|
|
784
|
+
itx: (0, lodash_cloneDeep.default)(preFlightCtx.itx),
|
|
785
|
+
txType: preFlightCtx.txType,
|
|
786
|
+
rawTxItxBeforeNormalize
|
|
787
|
+
};
|
|
788
|
+
}
|
|
600
789
|
resolve(context);
|
|
601
790
|
});
|
|
602
791
|
});
|
|
@@ -609,8 +798,13 @@ exports.MAX_PREFLIGHT_JSON_KEYS = MAX_PREFLIGHT_JSON_KEYS;
|
|
|
609
798
|
exports.MAX_PREFLIGHT_STRING_FIELD_BYTES = MAX_PREFLIGHT_STRING_FIELD_BYTES;
|
|
610
799
|
exports.MAX_PREFLIGHT_WIRE_BYTES_FALLBACK = MAX_PREFLIGHT_WIRE_BYTES_FALLBACK;
|
|
611
800
|
exports.MAX_ROLLUP_TXS_LIST_SIZE = MAX_ROLLUP_TXS_LIST_SIZE;
|
|
801
|
+
exports.PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL;
|
|
612
802
|
exports.assertKnownItxFields = assertKnownItxFields;
|
|
613
803
|
exports.assertRawWireEnvelope = assertRawWireEnvelope;
|
|
804
|
+
exports.assertWireByteCeiling = assertWireByteCeiling;
|
|
805
|
+
exports.computeMaxWireEnvelopeBytes = computeMaxWireEnvelopeBytes;
|
|
614
806
|
exports.default = PreFlightWaf;
|
|
807
|
+
exports.estimateBase64WireBytes = estimateBase64WireBytes;
|
|
615
808
|
exports.inspectTransactionPreFlight = inspectTransactionPreFlight;
|
|
616
|
-
exports.scanItxPayloadAnomalies = scanItxPayloadAnomalies;
|
|
809
|
+
exports.scanItxPayloadAnomalies = scanItxPayloadAnomalies;
|
|
810
|
+
exports.tryApplyPreFlightVerifiedSnapshot = tryApplyPreFlightVerifiedSnapshot;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { IBaseContext, IChainConfig, IDecodedContext, IDecodedTransaction } from "@ocap/types";
|
|
1
2
|
import { CustomError } from "@ocap/util/lib/error";
|
|
2
|
-
import { IBaseContext, IChainConfig, IDecodedContext } from "@ocap/types";
|
|
3
3
|
|
|
4
4
|
//#region src/pipes/pre-flight-waf.d.ts
|
|
5
5
|
declare const MAX_PREFLIGHT_JSON_DEPTH = 16;
|
|
@@ -8,6 +8,23 @@ declare const MAX_PREFLIGHT_STRING_FIELD_BYTES: number;
|
|
|
8
8
|
declare const MAX_PREFLIGHT_WIRE_BYTES_FALLBACK: number;
|
|
9
9
|
declare const MAX_ROLLUP_TXS_LIST_SIZE = 512;
|
|
10
10
|
declare const MAX_DELEGATE_TYPE_URLS_LIST_SIZE = 128;
|
|
11
|
+
/**
|
|
12
|
+
* Compute the maximum allowed raw transaction wire size in bytes for a given chain config (#1336, #1516).
|
|
13
|
+
* Shared between `PreFlightWaf` and `DecodeTx` so callers that invoke `DecodeTx` without `PreFlightWaf`
|
|
14
|
+
* (e.g. `decodeOcapWireTx` on Cloudflare Durable Objects) enforce the exact same ceiling before `fromBase64`.
|
|
15
|
+
*/
|
|
16
|
+
declare function computeMaxWireEnvelopeBytes(config?: IChainConfig): number;
|
|
17
|
+
/**
|
|
18
|
+
* Upper-bound decoded byte length of a trimmed base64 / base64url string.
|
|
19
|
+
* Exact for all canonical base64 / base64url payloads (`0`, `1`, or `2` mod 3 bytes) and
|
|
20
|
+
* never under-estimates `Buffer.from(base64.unescape(trimmed), 'base64').byteLength` on malformed input.
|
|
21
|
+
*/
|
|
22
|
+
declare function estimateBase64WireBytes(trimmed: string): number;
|
|
23
|
+
/**
|
|
24
|
+
* Enforce the raw wire byte ceiling in O(1) before `.trim()`, regex scanning, or base64 decoding (#1516).
|
|
25
|
+
* Returns the ASCII-trimmed string when within the configured ceiling.
|
|
26
|
+
*/
|
|
27
|
+
declare function assertWireByteCeiling(txBase64: string, config?: IChainConfig, messagePrefix?: string): string;
|
|
11
28
|
/**
|
|
12
29
|
* Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
|
|
13
30
|
*/
|
|
@@ -25,10 +42,49 @@ declare function scanItxPayloadAnomalies(itx: unknown, txType: string | undefine
|
|
|
25
42
|
* Pipeline pipe that runs the Pre-Flight WAF structural & anomaly checks.
|
|
26
43
|
*/
|
|
27
44
|
declare function PreFlightWaf(context: IDecodedContext, next: (err?: CustomError) => void): void;
|
|
45
|
+
declare namespace PreFlightWaf {
|
|
46
|
+
var SNAPSHOT_SYMBOL: typeof PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL;
|
|
47
|
+
var tryApplyVerifiedSnapshot: typeof tryApplyPreFlightVerifiedSnapshot;
|
|
48
|
+
}
|
|
49
|
+
declare const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL: unique symbol;
|
|
50
|
+
interface IPreFlightVerifiedSnapshot {
|
|
51
|
+
txBase64: string;
|
|
52
|
+
configRef: IChainConfig | undefined;
|
|
53
|
+
chainId: unknown;
|
|
54
|
+
tokenDecimal: unknown;
|
|
55
|
+
txFeeForType: unknown;
|
|
56
|
+
maxTxSizeForType: unknown;
|
|
57
|
+
maxExtraSize: unknown;
|
|
58
|
+
maxMultisig: unknown;
|
|
59
|
+
maxListSize: unknown;
|
|
60
|
+
maxAssetSize: unknown;
|
|
61
|
+
isSupportedTx: boolean;
|
|
62
|
+
isMultiSignV2Tx: boolean;
|
|
63
|
+
txExtraSerialized: string;
|
|
64
|
+
gasStakeHeadersSerialized: string;
|
|
65
|
+
coSignatureSerialized: string;
|
|
66
|
+
tx: IDecodedTransaction;
|
|
67
|
+
txEncoding: 'cbor' | 'protobuf';
|
|
68
|
+
txSize: number;
|
|
69
|
+
baseTxSize: number;
|
|
70
|
+
extraSizeCounted: boolean;
|
|
71
|
+
txHash: string;
|
|
72
|
+
unsignedTxHash: string;
|
|
73
|
+
txBaseGas: boolean;
|
|
74
|
+
itx: Record<string, unknown>;
|
|
75
|
+
txType: string;
|
|
76
|
+
rawTxItxBeforeNormalize: unknown;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Apply the verified pre-flight snapshot onto `context` if and only if all verified inputs
|
|
80
|
+
* (`txBase64`, `config` invariants, and `extra.{txExtra,gasStakeHeaders,coSignature}`) are
|
|
81
|
+
* unchanged since `inspectTransactionPreFlight(context)` succeeded.
|
|
82
|
+
*/
|
|
83
|
+
declare function tryApplyPreFlightVerifiedSnapshot(context: IBaseContext): boolean;
|
|
28
84
|
/**
|
|
29
85
|
* Stateless, zero-DB-I/O Pre-Flight inspection runner for `OCAPResolver.sendTx`
|
|
30
86
|
* BEFORE enqueuing into the single-writer queue (`this.queue`) or acquiring the SQLite write lock.
|
|
31
87
|
*/
|
|
32
88
|
declare function inspectTransactionPreFlight(context: IBaseContext): Promise<IDecodedContext>;
|
|
33
89
|
//#endregion
|
|
34
|
-
export { MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, assertKnownItxFields, assertRawWireEnvelope, PreFlightWaf as default, inspectTransactionPreFlight, scanItxPayloadAnomalies };
|
|
90
|
+
export { IPreFlightVerifiedSnapshot, MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, assertKnownItxFields, assertRawWireEnvelope, assertWireByteCeiling, computeMaxWireEnvelopeBytes, PreFlightWaf as default, estimateBase64WireBytes, inspectTransactionPreFlight, scanItxPayloadAnomalies, tryApplyPreFlightVerifiedSnapshot };
|
|
@@ -4,13 +4,13 @@ const require_package = require('../package.cjs');
|
|
|
4
4
|
let _ocap_mcrypto = require("@ocap/mcrypto");
|
|
5
5
|
let _ocap_util = require("@ocap/util");
|
|
6
6
|
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
7
|
+
let _arcblock_did = require("@arcblock/did");
|
|
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
12
|
let lodash_set = require("lodash/set");
|
|
12
13
|
lodash_set = require_rolldown_runtime.__toESM(lodash_set);
|
|
13
|
-
let _arcblock_did = require("@arcblock/did");
|
|
14
14
|
|
|
15
15
|
//#region src/pipes/update-owner.ts
|
|
16
16
|
const debug$1 = (0, debug.default)(`${require_package.name}:pipe:update-owner`);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PipeFunction } from "../runner.cjs";
|
|
2
|
-
import { CustomError } from "@ocap/util/lib/error";
|
|
3
2
|
import { IBaseContext } from "@ocap/types";
|
|
3
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
4
4
|
|
|
5
5
|
//#region src/pipes/update-owner.d.ts
|
|
6
6
|
declare function verifyAssetHierarchy(assetAddresses: string[], newOwnerAddress: string | undefined, context: IBaseContext, pendingOwners?: Record<string, string>, pendingConsumed?: string[]): Promise<CustomError | null>;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
2
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
3
3
|
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
4
|
+
let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
|
|
4
5
|
let lodash_get = require("lodash/get");
|
|
5
6
|
lodash_get = require_rolldown_runtime.__toESM(lodash_get);
|
|
6
|
-
let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
|
|
7
7
|
let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
|
|
8
8
|
|
|
9
9
|
//#region src/pipes/verify-account-migration.ts
|