@ocap/tx-pipeline 1.31.1 → 1.31.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/esm/bridge-release-keys.d.mts +33 -0
  2. package/esm/bridge-release-keys.mjs +81 -0
  3. package/esm/bridge-reserves.d.mts +107 -0
  4. package/esm/bridge-reserves.mjs +242 -0
  5. package/esm/helpers/bridge-withdraw.d.mts +86 -0
  6. package/esm/helpers/bridge-withdraw.mjs +123 -0
  7. package/esm/helpers/replay-guard.d.mts +19 -1
  8. package/esm/helpers/replay-guard.mjs +39 -1
  9. package/esm/index.d.mts +3 -1
  10. package/esm/index.mjs +8 -6
  11. package/esm/legacy-protocol-sunset.d.mts +2 -2
  12. package/esm/legacy-protocol-sunset.mjs +5 -5
  13. package/esm/legacy-rollup-archive.d.mts +67 -0
  14. package/esm/legacy-rollup-archive.mjs +199 -0
  15. package/esm/library.d.mts +4 -4
  16. package/esm/library.mjs +3 -3
  17. package/esm/native-abt-exchange.d.mts +3 -0
  18. package/esm/native-abt-exchange.mjs +93 -46
  19. package/esm/pipes/bridge-release-gate.d.mts +30 -0
  20. package/esm/pipes/bridge-release-gate.mjs +143 -0
  21. package/esm/pipes/bridge-reserve-v2-gate.d.mts +53 -0
  22. package/esm/pipes/bridge-reserve-v2-gate.mjs +264 -0
  23. package/esm/pipes/decode-tx.mjs +29 -4
  24. package/esm/pipes/extract-signer.mjs +1 -1
  25. package/esm/pipes/extract-state.mjs +2 -2
  26. package/esm/pipes/post-execution-invariant-gate.d.mts +19 -2
  27. package/esm/pipes/post-execution-invariant-gate.mjs +121 -6
  28. package/esm/pipes/pre-flight-waf.d.mts +18 -1
  29. package/esm/pipes/pre-flight-waf.mjs +48 -13
  30. package/esm/pipes/update-owner.mjs +1 -1
  31. package/esm/pipes/verify-account-migration.mjs +1 -1
  32. package/esm/pipes/verify-delegation.mjs +49 -25
  33. package/esm/pipes/verify-multisig-v2.mjs +5 -4
  34. package/esm/pipes/verify-multisig.mjs +5 -4
  35. package/esm/pipes/verify-signature.d.mts +7 -1
  36. package/esm/pipes/verify-signature.mjs +119 -16
  37. package/esm/pipes/verify-signer.mjs +2 -2
  38. package/esm/pipes/verify-token-access.mjs +1 -1
  39. package/esm/pipes/verify-token-balance.mjs +1 -1
  40. package/esm/pipes/verify-tx-input.mjs +1 -1
  41. package/esm/pipes/verify-tx-size.mjs +1 -1
  42. package/esm/pipes/verify-tx.mjs +12 -5
  43. package/esm/super-suites-foundation.mjs +6 -6
  44. package/esm/transaction-block.d.mts +6 -2
  45. package/esm/transaction-block.mjs +282 -40
  46. package/esm/uniswap-router.d.mts +247 -1
  47. package/esm/uniswap-router.mjs +573 -2
  48. package/lib/bridge-release-keys.cjs +88 -0
  49. package/lib/bridge-release-keys.d.cts +33 -0
  50. package/lib/bridge-reserves.cjs +257 -0
  51. package/lib/bridge-reserves.d.cts +107 -0
  52. package/lib/helpers/bridge-withdraw.cjs +136 -0
  53. package/lib/helpers/bridge-withdraw.d.cts +86 -0
  54. package/lib/helpers/replay-guard.cjs +39 -0
  55. package/lib/helpers/replay-guard.d.cts +20 -2
  56. package/lib/index.cjs +25 -5
  57. package/lib/index.d.cts +3 -1
  58. package/lib/legacy-protocol-sunset.cjs +7 -7
  59. package/lib/legacy-protocol-sunset.d.cts +2 -2
  60. package/lib/legacy-rollup-archive.cjs +208 -0
  61. package/lib/legacy-rollup-archive.d.cts +67 -0
  62. package/lib/library.cjs +14 -68
  63. package/lib/library.d.cts +4 -4
  64. package/lib/native-abt-exchange.cjs +93 -46
  65. package/lib/native-abt-exchange.d.cts +3 -0
  66. package/lib/pipes/bridge-release-gate.cjs +145 -0
  67. package/lib/pipes/bridge-release-gate.d.cts +30 -0
  68. package/lib/pipes/bridge-reserve-v2-gate.cjs +273 -0
  69. package/lib/pipes/bridge-reserve-v2-gate.d.cts +53 -0
  70. package/lib/pipes/decode-itx.d.cts +1 -1
  71. package/lib/pipes/decode-tx.cjs +28 -3
  72. package/lib/pipes/decode-tx.d.cts +1 -1
  73. package/lib/pipes/extract-signer.cjs +1 -1
  74. package/lib/pipes/extract-state.cjs +3 -3
  75. package/lib/pipes/post-execution-invariant-gate.cjs +121 -4
  76. package/lib/pipes/post-execution-invariant-gate.d.cts +19 -2
  77. package/lib/pipes/pre-flight-waf.cjs +51 -13
  78. package/lib/pipes/pre-flight-waf.d.cts +19 -2
  79. package/lib/pipes/update-owner.cjs +1 -1
  80. package/lib/pipes/update-owner.d.cts +1 -1
  81. package/lib/pipes/verify-account-migration.cjs +1 -1
  82. package/lib/pipes/verify-delegation.cjs +50 -26
  83. package/lib/pipes/verify-multisig-v2.cjs +5 -4
  84. package/lib/pipes/verify-multisig.cjs +5 -4
  85. package/lib/pipes/verify-service-fee.d.cts +1 -1
  86. package/lib/pipes/verify-signature.cjs +118 -14
  87. package/lib/pipes/verify-signature.d.cts +8 -2
  88. package/lib/pipes/verify-signer.cjs +2 -2
  89. package/lib/pipes/verify-token-access.cjs +1 -1
  90. package/lib/pipes/verify-token-balance.cjs +1 -1
  91. package/lib/pipes/verify-tx-input.cjs +1 -1
  92. package/lib/pipes/verify-tx-size.cjs +1 -1
  93. package/lib/pipes/verify-tx-size.d.cts +1 -1
  94. package/lib/pipes/verify-tx.cjs +11 -5
  95. package/lib/pipes/verify-tx.d.cts +1 -1
  96. package/lib/super-suites-foundation.cjs +6 -6
  97. package/lib/transaction-block.cjs +282 -40
  98. package/lib/transaction-block.d.cts +6 -2
  99. package/lib/uniswap-router.cjs +576 -1
  100. package/lib/uniswap-router.d.cts +247 -1
  101. package/package.json +10 -10
  102. package/esm/evm-simplified-bridge.d.mts +0 -1370
  103. package/esm/evm-simplified-bridge.mjs +0 -3875
  104. package/lib/evm-simplified-bridge.cjs +0 -3943
  105. 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
- if (afterStake.revocable !== false && !isAllowedRollupCloseUnlock) throw createInvariantError("STAKE_PROTECTION_VIOLATION", `Post-Execution Invariant Gate: permanently locked stake ${stakeAddr} (revocable=false) cannot be unlocked`);
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,18 @@ 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
17
  let lodash_cloneDeep = require("lodash/cloneDeep");
18
18
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
19
19
 
@@ -34,7 +34,7 @@ const FORBIDDEN_STORAGE_DATA_URI_PATTERN = /^\s*data\s*:\s*(?:image\/|audio\/|vi
34
34
  const FORBIDDEN_BINARY_MAGIC_BASE64_PATTERN = /^(?:AGFzbQ|f0VMRg|JVBERi0|UEsDB|H4sIA|iVBORw0KGgo|(?:\/9j\/|_9j_)4AAQ|R0lGOD(?:lh|dh))/;
35
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)/;
36
36
  const FORBIDDEN_CONTROL_CHAR_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
37
- 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})$/;
38
38
  const STANDARD_BOUNDED_LIST_KEYS = [
39
39
  "inputs",
40
40
  "outputs",
@@ -125,20 +125,55 @@ function getAllowedTopLevelItxKeys(typeUrl) {
125
125
  return null;
126
126
  }
127
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
+ }
128
169
  /**
129
170
  * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
130
171
  */
131
172
  function assertRawWireEnvelope(txBase64, config) {
132
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");
133
- const trimmed = txBase64.trim();
134
- if (!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");
135
- const maxTxSizeMap = (0, lodash_get.default)(config, "transaction.maxTxSize") || {};
136
- const configuredLimits = Object.values(maxTxSizeMap).filter((v) => typeof v === "number" && v > 0);
137
- const maxAssetSize = (0, lodash_get.default)(config, "transaction.maxAssetSize", 65536) || 65536;
138
- const maxExtraSize = (0, lodash_get.default)(config, "transaction.maxExtraSize", 8192) || 8192;
139
- const maxConfiguredTxBytes = configuredLimits.length > 0 ? Math.max(...configuredLimits, maxAssetSize) + maxExtraSize : MAX_PREFLIGHT_WIRE_BYTES_FALLBACK;
140
- const estimatedWireBytes = Math.floor(trimmed.length * 3 / 4);
141
- 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");
142
177
  }
143
178
  /**
144
179
  * Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
@@ -766,7 +801,10 @@ exports.MAX_ROLLUP_TXS_LIST_SIZE = MAX_ROLLUP_TXS_LIST_SIZE;
766
801
  exports.PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL;
767
802
  exports.assertKnownItxFields = assertKnownItxFields;
768
803
  exports.assertRawWireEnvelope = assertRawWireEnvelope;
804
+ exports.assertWireByteCeiling = assertWireByteCeiling;
805
+ exports.computeMaxWireEnvelopeBytes = computeMaxWireEnvelopeBytes;
769
806
  exports.default = PreFlightWaf;
807
+ exports.estimateBase64WireBytes = estimateBase64WireBytes;
770
808
  exports.inspectTransactionPreFlight = inspectTransactionPreFlight;
771
809
  exports.scanItxPayloadAnomalies = scanItxPayloadAnomalies;
772
810
  exports.tryApplyPreFlightVerifiedSnapshot = tryApplyPreFlightVerifiedSnapshot;
@@ -1,5 +1,5 @@
1
- import { CustomError } from "@ocap/util/lib/error";
2
1
  import { IBaseContext, IChainConfig, IDecodedContext, IDecodedTransaction } from "@ocap/types";
2
+ import { CustomError } from "@ocap/util/lib/error";
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
  */
@@ -70,4 +87,4 @@ declare function tryApplyPreFlightVerifiedSnapshot(context: IBaseContext): boole
70
87
  */
71
88
  declare function inspectTransactionPreFlight(context: IBaseContext): Promise<IDecodedContext>;
72
89
  //#endregion
73
- 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, PreFlightWaf as default, inspectTransactionPreFlight, scanItxPayloadAnomalies, tryApplyPreFlightVerifiedSnapshot };
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
@@ -1,19 +1,20 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
+ const require_pipes_verify_signature = require('./verify-signature.cjs');
3
4
  let _ocap_mcrypto = require("@ocap/mcrypto");
4
5
  let _ocap_util = require("@ocap/util");
5
6
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
+ let _arcblock_did = require("@arcblock/did");
8
+ let _arcblock_did_util = require("@arcblock/did-util");
9
+ let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
6
10
  let lodash_get = require("lodash/get");
7
11
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
8
- let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
9
- let lodash_set = require("lodash/set");
10
- lodash_set = require_rolldown_runtime.__toESM(lodash_set);
11
- let _arcblock_did = require("@arcblock/did");
12
12
  let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
13
+ let _ocap_wallet = require("@ocap/wallet");
13
14
  let lodash_isEmpty = require("lodash/isEmpty");
14
15
  lodash_isEmpty = require_rolldown_runtime.__toESM(lodash_isEmpty);
15
- let _ocap_wallet = require("@ocap/wallet");
16
- let _arcblock_did_util = require("@arcblock/did-util");
16
+ let lodash_set = require("lodash/set");
17
+ lodash_set = require_rolldown_runtime.__toESM(lodash_set);
17
18
 
18
19
  //#region src/pipes/verify-delegation.ts
19
20
  const ZERO = (0, _ocap_util.toBN)(0);
@@ -326,22 +327,31 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
326
327
  }
327
328
  return null;
328
329
  };
330
+ const hasExplicitCoSignatureInput = () => {
331
+ const explicitCoSig = (0, lodash_get.default)(context, "extra.coSignature");
332
+ if (explicitCoSig !== void 0 && explicitCoSig !== null) return true;
333
+ const rawTxExtra = (0, lodash_get.default)(context, "extra.txExtra");
334
+ if (typeof rawTxExtra === "string" && rawTxExtra.trim().startsWith("{")) try {
335
+ const parsed = JSON.parse(rawTxExtra);
336
+ return Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && "coSignature" in parsed);
337
+ } catch {
338
+ return false;
339
+ }
340
+ if (rawTxExtra && typeof rawTxExtra === "object" && !Array.isArray(rawTxExtra)) return "coSignature" in rawTxExtra;
341
+ return false;
342
+ };
329
343
  const verifyOwnerCoSignature = async (signerState, delegateePk) => {
330
344
  if (!signerState?.address) return false;
331
345
  if (Array.isArray(signerState.migratedTo) && signerState.migratedTo.length > 0) return false;
332
- let rawCoSig = (0, lodash_get.default)(context, "extra.coSignature");
333
- if (!rawCoSig) {
334
- const rawTxExtra = (0, lodash_get.default)(context, "extra.txExtra");
335
- if (typeof rawTxExtra === "string" && rawTxExtra.trim().startsWith("{")) try {
336
- const parsed = JSON.parse(rawTxExtra);
337
- if (parsed?.coSignature && typeof parsed.coSignature === "object") rawCoSig = parsed.coSignature;
338
- } catch {}
339
- else if (rawTxExtra && typeof rawTxExtra === "object") {
340
- const maybeCoSig = rawTxExtra.coSignature;
341
- if (maybeCoSig && typeof maybeCoSig === "object") rawCoSig = maybeCoSig;
342
- }
343
- }
344
- if (!rawCoSig || typeof rawCoSig.pk !== "string" || typeof rawCoSig.signature !== "string") return false;
346
+ const rawDirectCoSig = (0, lodash_get.default)(context, "extra.coSignature");
347
+ const hasDirectCoSig = rawDirectCoSig !== void 0 && rawDirectCoSig !== null;
348
+ const rawTxExtra = (0, lodash_get.default)(context, "extra.txExtra");
349
+ const parsedFromDirect = hasDirectCoSig ? require_pipes_verify_signature.parseCanonicalCoSignatureTxExtra({ coSignature: rawDirectCoSig }) : null;
350
+ const parsedFromTxExtra = rawTxExtra !== void 0 && rawTxExtra !== null ? require_pipes_verify_signature.parseCanonicalCoSignatureTxExtra(rawTxExtra) : null;
351
+ if (hasDirectCoSig && !parsedFromDirect) return false;
352
+ if (parsedFromDirect && parsedFromTxExtra && (parsedFromDirect.pk !== parsedFromTxExtra.pk || parsedFromDirect.signature !== parsedFromTxExtra.signature || (parsedFromDirect.extra || "") !== (parsedFromTxExtra.extra || ""))) return false;
353
+ const rawCoSig = parsedFromDirect || parsedFromTxExtra;
354
+ if (!rawCoSig) return false;
345
355
  const candidatePayloads = [context.txHash, context.unsignedTxHash].filter((x) => typeof x === "string" && x.length > 0);
346
356
  if (candidatePayloads.length === 0) return false;
347
357
  const ownerAddr = signerState.address;
@@ -350,15 +360,25 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
350
360
  const forbiddenPkHex = forbiddenPk ? (0, _arcblock_did.normalizePublicKeyHex)(forbiddenPk) : "";
351
361
  if (!coSigPkHex || forbiddenPkHex && coSigPkHex === forbiddenPkHex) return false;
352
362
  if (!(0, _arcblock_did.isFromPublicKey)(ownerAddr, rawCoSig.pk)) return false;
363
+ const ownerType = (0, _arcblock_did.toTypeInfo)(ownerAddr);
364
+ const isOwnerPasskey = ownerType.role === _ocap_mcrypto.types.RoleType.ROLE_PASSKEY || ownerType.pk === _ocap_mcrypto.types.KeyType.PASSKEY;
365
+ const coSigExtra = rawCoSig.extra || "";
366
+ if (isOwnerPasskey && !coSigExtra) return false;
367
+ if (!isOwnerPasskey && coSigExtra) return false;
368
+ let wallet;
353
369
  try {
354
- const wallet = (0, _ocap_wallet.fromPublicKey)(rawCoSig.pk, (0, _arcblock_did.toTypeInfo)(ownerAddr));
355
- for (const payload of candidatePayloads) {
356
- if (await wallet.verify(payload, rawCoSig.signature, false)) return true;
357
- if (await wallet.verify(payload, rawCoSig.signature, true)) return true;
358
- }
370
+ wallet = (0, _ocap_wallet.fromPublicKey)(rawCoSig.pk, ownerType);
359
371
  } catch {
360
372
  return false;
361
373
  }
374
+ for (const payload of candidatePayloads) {
375
+ try {
376
+ if (await wallet.verify(payload, rawCoSig.signature, false, coSigExtra)) return true;
377
+ } catch {}
378
+ try {
379
+ if (await wallet.verify(payload, rawCoSig.signature, true, coSigExtra)) return true;
380
+ } catch {}
381
+ }
362
382
  return false;
363
383
  };
364
384
  const getTxTimestampSeconds = () => {
@@ -429,6 +449,7 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
429
449
  const signerAddress = signerState?.address || tx?.from;
430
450
  if (delegatorState && (tx?.delegator && !(0, _ocap_util.isSameDid)(delegatorState.address, tx.delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${tx?.delegator} is migrated`, { persist: false }));
431
451
  if (signerAddress && (0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
452
+ if (hasExplicitCoSignatureInput()) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", "Unexpected owner coSignature on implicit asset delegation", { persist: false }));
432
453
  try {
433
454
  if (await verifyImplicitAssetOwnership(signerAddress, delegatorState || (tx?.delegator ? { address: tx.delegator } : null), context, tx?.delegator)) {
434
455
  (0, lodash_set.default)(context, "isImplicitDelegation", true);
@@ -451,6 +472,8 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
451
472
  const coSignedByOwner = await verifyOwnerCoSignature(signerState);
452
473
  const result = checkDelegation(delegationState, requirements, coSignedByOwner);
453
474
  if (result.code) return next(new _ocap_util_lib_error.CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: false }));
475
+ const hasDelegatedMultiSig = (0, _ocap_util_lib_get_list_field.getListField)(tx, "signatures").some((x) => Boolean(x?.delegator));
476
+ if (hasExplicitCoSignatureInput() && !coSignedByOwner && !hasDelegatedMultiSig) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", "Invalid owner coSignature", { persist: false }));
454
477
  if (coSignedByOwner) (0, lodash_set.default)(context, "coSignedByOwner", true);
455
478
  (0, lodash_set.default)(context, delegationKey, delegationState);
456
479
  (0, lodash_set.default)(context, "isDelegationChanged", true);
@@ -473,8 +496,8 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
473
496
  const { signer, delegator } = signature;
474
497
  const sigRequirements = typeof getRequirements === "function" ? getRequirements(context, index, signature) || [] : [];
475
498
  allRequirements.push(...sigRequirements);
476
- const signerState = signerStates?.find((x) => signer && (0, _ocap_util.isSameDid)(x.address, signer));
477
- const delegatorState = delegatorStates?.find((x) => delegator && (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(x).some((addr) => (0, _ocap_util.isSameDid)(addr, delegator)));
499
+ const signerState = signerStates?.find((x) => Boolean(x && signer && (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(x).some((addr) => (0, _ocap_util.isSameDid)(addr, signer))));
500
+ const delegatorState = delegatorStates?.find((x) => Boolean(x && delegator && (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(x).some((addr) => (0, _ocap_util.isSameDid)(addr, delegator))));
478
501
  if (delegatorState && (delegator && !(0, _ocap_util.isSameDid)(delegatorState.address, delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegator} is migrated`, { persist: false }));
479
502
  const signerAddress = signerState?.address || signer;
480
503
  if (signerAddress && (0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
@@ -503,6 +526,7 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
503
526
  if (coSignedByOwner) (0, lodash_set.default)(context, "coSignedByOwner", true);
504
527
  if (!delegationStates.some((d) => (0, _ocap_util.isSameDid)(d.address, delegationState.address))) delegationStates.push(delegationState);
505
528
  }
529
+ if (hasExplicitCoSignatureInput() && !(0, lodash_get.default)(context, "coSignedByOwner")) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", "Invalid owner coSignature", { persist: false }));
506
530
  (0, lodash_set.default)(context, requirementsKey, allRequirements);
507
531
  (0, lodash_set.default)(context, delegationKey, delegationStates);
508
532
  (0, lodash_set.default)(context, "isMultiSigDelegationVerified", true);
@@ -6,17 +6,17 @@ const require_helpers_unwrap_opaque_any = require('../helpers/unwrap-opaque-any.
6
6
  const require_helpers_encode_tx_by_context = require('../helpers/encode-tx-by-context.cjs');
7
7
  let _ocap_mcrypto = require("@ocap/mcrypto");
8
8
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
9
- let lodash_get = require("lodash/get");
10
- lodash_get = require_rolldown_runtime.__toESM(lodash_get);
9
+ let _arcblock_did = require("@arcblock/did");
11
10
  let _ocap_message = require("@ocap/message");
12
11
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
12
+ let lodash_get = require("lodash/get");
13
+ lodash_get = require_rolldown_runtime.__toESM(lodash_get);
13
14
  let lodash_cloneDeep = require("lodash/cloneDeep");
14
15
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
15
16
  let lodash_omit = require("lodash/omit");
16
17
  lodash_omit = require_rolldown_runtime.__toESM(lodash_omit);
17
18
  let debug = require("debug");
18
19
  debug = require_rolldown_runtime.__toESM(debug);
19
- let _arcblock_did = require("@arcblock/did");
20
20
  let _ocap_wallet = require("@ocap/wallet");
21
21
 
22
22
  //#region src/pipes/verify-multisig-v2.ts
@@ -72,7 +72,8 @@ function CreateVerifyMultiSigV2Pipe({ signersKey }) {
72
72
  signer: address,
73
73
  from: signer,
74
74
  nonce: tx.nonce,
75
- action: context.txType
75
+ action: context.txType,
76
+ withdraw: await require_helpers_replay_guard.getBridgeWithdrawEnvelopeContext(context)
76
77
  });
77
78
  if (await wallet.verify(txBytes, signature, true, verifiedExtra) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Signature for ${address} is not valid`));
78
79
  } catch (err) {
@@ -5,13 +5,13 @@ const require_helpers_unwrap_opaque_any = require('../helpers/unwrap-opaque-any.
5
5
  const require_helpers_encode_tx_by_context = require('../helpers/encode-tx-by-context.cjs');
6
6
  let _ocap_mcrypto = require("@ocap/mcrypto");
7
7
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
8
- let lodash_get = require("lodash/get");
9
- lodash_get = require_rolldown_runtime.__toESM(lodash_get);
8
+ let _arcblock_did = require("@arcblock/did");
10
9
  let _ocap_message = require("@ocap/message");
11
10
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
11
+ let lodash_get = require("lodash/get");
12
+ lodash_get = require_rolldown_runtime.__toESM(lodash_get);
12
13
  let lodash_cloneDeep = require("lodash/cloneDeep");
13
14
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
14
- let _arcblock_did = require("@arcblock/did");
15
15
  let _ocap_wallet = require("@ocap/wallet");
16
16
 
17
17
  //#region src/pipes/verify-multisig.ts
@@ -49,7 +49,8 @@ function CreateVerifyMultiSigPipe(numSigs = 0) {
49
49
  signer: address,
50
50
  from: signer,
51
51
  nonce: tx.nonce,
52
- action: context.txType
52
+ action: context.txType,
53
+ withdraw: await require_helpers_replay_guard.getBridgeWithdrawEnvelopeContext(context)
53
54
  });
54
55
  if (await wallet.verify(txBytes, signature, true, extra) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Multi signature for ${address} is not valid`));
55
56
  } catch (err) {