@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,16 +1,16 @@
1
1
  import { ENCRYPTED_NFT_SCHEMA_VERSION, validateEncryptedAssetEnvelope } from "../encrypted-nft-envelope.mjs";
2
2
  import DecodeItx from "./decode-itx.mjs";
3
- import DecodeTx from "./decode-tx.mjs";
4
3
  import runner_default from "../runner.mjs";
5
4
  import CreatedVerifyBlockedPipe from "./verify-blocked.mjs";
6
5
  import VerifyServiceFee from "./verify-service-fee.mjs";
7
6
  import VerifySignature from "./verify-signature.mjs";
8
7
  import VerifyTx from "./verify-tx.mjs";
9
8
  import VerifyTxSize from "./verify-tx-size.mjs";
9
+ import DecodeTx from "./decode-tx.mjs";
10
10
  import { CustomError } from "@ocap/util/lib/error";
11
- import get from "lodash/get.js";
12
11
  import { createMessage, decodeAny, encodeAny, fromTypeUrl, toTypeUrl } from "@ocap/message";
13
12
  import { getListField } from "@ocap/util/lib/get-list-field";
13
+ import get from "lodash/get.js";
14
14
  import cloneDeep from "lodash/cloneDeep.js";
15
15
 
16
16
  //#region src/pipes/pre-flight-waf.ts
@@ -30,7 +30,7 @@ const FORBIDDEN_STORAGE_DATA_URI_PATTERN = /^\s*data\s*:\s*(?:image\/|audio\/|vi
30
30
  const FORBIDDEN_BINARY_MAGIC_BASE64_PATTERN = /^(?:AGFzbQ|f0VMRg|JVBERi0|UEsDB|H4sIA|iVBORw0KGgo|(?:\/9j\/|_9j_)4AAQ|R0lGOD(?:lh|dh))/;
31
31
  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)/;
32
32
  const FORBIDDEN_CONTROL_CHAR_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
33
- const BASE64_WIRE_PATTERN = /^[A-Za-z0-9+/=_-]+$/;
33
+ const BASE64_WIRE_PATTERN = /^(?:[A-Za-z0-9+/]+={0,2}|[A-Za-z0-9_-]+={0,2})$/;
34
34
  const STANDARD_BOUNDED_LIST_KEYS = [
35
35
  "inputs",
36
36
  "outputs",
@@ -121,20 +121,55 @@ function getAllowedTopLevelItxKeys(typeUrl) {
121
121
  return null;
122
122
  }
123
123
  }
124
+ const MAX_WIRE_WHITESPACE_SLACK = 64;
125
+ /**
126
+ * Compute the maximum allowed raw transaction wire size in bytes for a given chain config (#1336, #1516).
127
+ * Shared between `PreFlightWaf` and `DecodeTx` so callers that invoke `DecodeTx` without `PreFlightWaf`
128
+ * (e.g. `decodeOcapWireTx` on Cloudflare Durable Objects) enforce the exact same ceiling before `fromBase64`.
129
+ */
130
+ function computeMaxWireEnvelopeBytes(config) {
131
+ const maxTxSizeMap = get(config, "transaction.maxTxSize");
132
+ const configuredLimits = maxTxSizeMap && typeof maxTxSizeMap === "object" ? Object.values(maxTxSizeMap).filter((v) => typeof v === "number" && Number.isFinite(v) && v > 0) : [];
133
+ if (configuredLimits.length === 0) return MAX_PREFLIGHT_WIRE_BYTES_FALLBACK;
134
+ const rawMaxAssetSize = get(config, "transaction.maxAssetSize");
135
+ const maxAssetSize = typeof rawMaxAssetSize === "number" && Number.isFinite(rawMaxAssetSize) && rawMaxAssetSize > 0 ? rawMaxAssetSize : 65536;
136
+ const rawMaxExtraSize = get(config, "transaction.maxExtraSize");
137
+ const maxExtraSize = typeof rawMaxExtraSize === "number" && Number.isFinite(rawMaxExtraSize) && rawMaxExtraSize >= 0 ? rawMaxExtraSize : 8192;
138
+ return Math.max(...configuredLimits, maxAssetSize) + maxExtraSize;
139
+ }
140
+ /**
141
+ * Upper-bound decoded byte length of a trimmed base64 / base64url string.
142
+ * Exact for all canonical base64 / base64url payloads (`0`, `1`, or `2` mod 3 bytes) and
143
+ * never under-estimates `Buffer.from(base64.unescape(trimmed), 'base64').byteLength` on malformed input.
144
+ */
145
+ function estimateBase64WireBytes(trimmed) {
146
+ const len = trimmed.length;
147
+ const pad = len >= 4 && len % 4 === 0 ? trimmed.endsWith("==") ? 2 : trimmed.endsWith("=") ? 1 : 0 : 0;
148
+ return Math.max(0, Math.floor(len * 3 / 4) - pad);
149
+ }
150
+ /**
151
+ * Enforce the raw wire byte ceiling in O(1) before `.trim()`, regex scanning, or base64 decoding (#1516).
152
+ * Returns the ASCII-trimmed string when within the configured ceiling.
153
+ */
154
+ function assertWireByteCeiling(txBase64, config, messagePrefix = "Raw transaction wire size") {
155
+ const maxConfiguredTxBytes = computeMaxWireEnvelopeBytes(config);
156
+ const maxBase64Chars = Math.ceil(maxConfiguredTxBytes * 4 / 3) + 4;
157
+ if (txBase64.length > maxBase64Chars + MAX_WIRE_WHITESPACE_SLACK) throw new CustomError("INVALID_TX_SIZE", `${messagePrefix} (${Math.floor(txBase64.length * 3 / 4)} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
158
+ const utf8ByteLen = Buffer.byteLength(txBase64, "utf8");
159
+ if (utf8ByteLen > maxBase64Chars + MAX_WIRE_WHITESPACE_SLACK) throw new CustomError("INVALID_TX_SIZE", `${messagePrefix} (${Math.floor(utf8ByteLen * 3 / 4)} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
160
+ const trimmed = txBase64.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
161
+ const estimatedWireBytes = estimateBase64WireBytes(trimmed);
162
+ if (estimatedWireBytes > maxConfiguredTxBytes) throw new CustomError("INVALID_TX_SIZE", `${messagePrefix} (${estimatedWireBytes} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
163
+ return trimmed;
164
+ }
124
165
  /**
125
166
  * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
126
167
  */
127
168
  function assertRawWireEnvelope(txBase64, config) {
128
169
  if (!txBase64 || typeof txBase64 !== "string" || txBase64.length < 20) throw new CustomError("INVALID_TX", "Transaction data is empty or too short");
129
- const trimmed = txBase64.trim();
130
- if (!BASE64_WIRE_PATTERN.test(trimmed)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains invalid non-base64 characters");
131
- const maxTxSizeMap = get(config, "transaction.maxTxSize") || {};
132
- const configuredLimits = Object.values(maxTxSizeMap).filter((v) => typeof v === "number" && v > 0);
133
- const maxAssetSize = get(config, "transaction.maxAssetSize", 65536) || 65536;
134
- const maxExtraSize = get(config, "transaction.maxExtraSize", 8192) || 8192;
135
- const maxConfiguredTxBytes = configuredLimits.length > 0 ? Math.max(...configuredLimits, maxAssetSize) + maxExtraSize : MAX_PREFLIGHT_WIRE_BYTES_FALLBACK;
136
- const estimatedWireBytes = Math.floor(trimmed.length * 3 / 4);
137
- if (estimatedWireBytes > maxConfiguredTxBytes) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: raw transaction wire size (${estimatedWireBytes} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
170
+ const trimmed = assertWireByteCeiling(txBase64, config, "Pre-Flight WAF: raw transaction wire size");
171
+ if (trimmed.length < 20) throw new CustomError("INVALID_TX", "Transaction data is empty or too short");
172
+ if (txBase64 !== trimmed || !BASE64_WIRE_PATTERN.test(trimmed)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains invalid non-base64 characters");
138
173
  }
139
174
  /**
140
175
  * Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
@@ -753,4 +788,4 @@ async function inspectTransactionPreFlight(context) {
753
788
  }
754
789
 
755
790
  //#endregion
756
- 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, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, assertKnownItxFields, assertRawWireEnvelope, PreFlightWaf as default, inspectTransactionPreFlight, scanItxPayloadAnomalies, tryApplyPreFlightVerifiedSnapshot };
791
+ 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, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, assertKnownItxFields, assertRawWireEnvelope, assertWireByteCeiling, computeMaxWireEnvelopeBytes, PreFlightWaf as default, estimateBase64WireBytes, inspectTransactionPreFlight, scanItxPayloadAnomalies, tryApplyPreFlightVerifiedSnapshot };
@@ -2,10 +2,10 @@ import { name } from "../package.mjs";
2
2
  import { types } from "@ocap/mcrypto";
3
3
  import { isSameDid } from "@ocap/util";
4
4
  import { CustomError } from "@ocap/util/lib/error";
5
+ import { toTypeInfo } from "@arcblock/did";
5
6
  import get from "lodash/get.js";
6
7
  import Debug from "debug";
7
8
  import set from "lodash/set.js";
8
- import { toTypeInfo } from "@arcblock/did";
9
9
 
10
10
  //#region src/pipes/update-owner.ts
11
11
  const debug = Debug(`${name}:pipe:update-owner`);
@@ -1,6 +1,6 @@
1
1
  import { CustomError } from "@ocap/util/lib/error";
2
- import get from "lodash/get.js";
3
2
  import { getListField } from "@ocap/util/lib/get-list-field";
3
+ import get from "lodash/get.js";
4
4
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
5
5
 
6
6
  //#region src/pipes/verify-account-migration.ts
@@ -1,14 +1,15 @@
1
+ import { parseCanonicalCoSignatureTxExtra } from "./verify-signature.mjs";
1
2
  import { types } from "@ocap/mcrypto";
2
3
  import { isSameDid, scopeMatch, scopeMatchAny, toBN } from "@ocap/util";
3
4
  import { CustomError } from "@ocap/util/lib/error";
4
- import get from "lodash/get.js";
5
- import { getListField } from "@ocap/util/lib/get-list-field";
6
- import set from "lodash/set.js";
7
5
  import { isFromPublicKey, normalizePublicKeyHex, toTypeInfo } from "@arcblock/did";
6
+ import { toDelegateAddress } from "@arcblock/did-util";
7
+ import { getListField } from "@ocap/util/lib/get-list-field";
8
+ import get from "lodash/get.js";
8
9
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
9
- import isEmpty from "lodash/isEmpty.js";
10
10
  import { fromPublicKey } from "@ocap/wallet";
11
- import { toDelegateAddress } from "@arcblock/did-util";
11
+ import isEmpty from "lodash/isEmpty.js";
12
+ import set from "lodash/set.js";
12
13
 
13
14
  //#region src/pipes/verify-delegation.ts
14
15
  const ZERO = toBN(0);
@@ -321,22 +322,31 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
321
322
  }
322
323
  return null;
323
324
  };
325
+ const hasExplicitCoSignatureInput = () => {
326
+ const explicitCoSig = get(context, "extra.coSignature");
327
+ if (explicitCoSig !== void 0 && explicitCoSig !== null) return true;
328
+ const rawTxExtra = get(context, "extra.txExtra");
329
+ if (typeof rawTxExtra === "string" && rawTxExtra.trim().startsWith("{")) try {
330
+ const parsed = JSON.parse(rawTxExtra);
331
+ return Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && "coSignature" in parsed);
332
+ } catch {
333
+ return false;
334
+ }
335
+ if (rawTxExtra && typeof rawTxExtra === "object" && !Array.isArray(rawTxExtra)) return "coSignature" in rawTxExtra;
336
+ return false;
337
+ };
324
338
  const verifyOwnerCoSignature = async (signerState, delegateePk) => {
325
339
  if (!signerState?.address) return false;
326
340
  if (Array.isArray(signerState.migratedTo) && signerState.migratedTo.length > 0) return false;
327
- let rawCoSig = get(context, "extra.coSignature");
328
- if (!rawCoSig) {
329
- const rawTxExtra = get(context, "extra.txExtra");
330
- if (typeof rawTxExtra === "string" && rawTxExtra.trim().startsWith("{")) try {
331
- const parsed = JSON.parse(rawTxExtra);
332
- if (parsed?.coSignature && typeof parsed.coSignature === "object") rawCoSig = parsed.coSignature;
333
- } catch {}
334
- else if (rawTxExtra && typeof rawTxExtra === "object") {
335
- const maybeCoSig = rawTxExtra.coSignature;
336
- if (maybeCoSig && typeof maybeCoSig === "object") rawCoSig = maybeCoSig;
337
- }
338
- }
339
- if (!rawCoSig || typeof rawCoSig.pk !== "string" || typeof rawCoSig.signature !== "string") return false;
341
+ const rawDirectCoSig = get(context, "extra.coSignature");
342
+ const hasDirectCoSig = rawDirectCoSig !== void 0 && rawDirectCoSig !== null;
343
+ const rawTxExtra = get(context, "extra.txExtra");
344
+ const parsedFromDirect = hasDirectCoSig ? parseCanonicalCoSignatureTxExtra({ coSignature: rawDirectCoSig }) : null;
345
+ const parsedFromTxExtra = rawTxExtra !== void 0 && rawTxExtra !== null ? parseCanonicalCoSignatureTxExtra(rawTxExtra) : null;
346
+ if (hasDirectCoSig && !parsedFromDirect) return false;
347
+ if (parsedFromDirect && parsedFromTxExtra && (parsedFromDirect.pk !== parsedFromTxExtra.pk || parsedFromDirect.signature !== parsedFromTxExtra.signature || (parsedFromDirect.extra || "") !== (parsedFromTxExtra.extra || ""))) return false;
348
+ const rawCoSig = parsedFromDirect || parsedFromTxExtra;
349
+ if (!rawCoSig) return false;
340
350
  const candidatePayloads = [context.txHash, context.unsignedTxHash].filter((x) => typeof x === "string" && x.length > 0);
341
351
  if (candidatePayloads.length === 0) return false;
342
352
  const ownerAddr = signerState.address;
@@ -345,15 +355,25 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
345
355
  const forbiddenPkHex = forbiddenPk ? normalizePublicKeyHex(forbiddenPk) : "";
346
356
  if (!coSigPkHex || forbiddenPkHex && coSigPkHex === forbiddenPkHex) return false;
347
357
  if (!isFromPublicKey(ownerAddr, rawCoSig.pk)) return false;
358
+ const ownerType = toTypeInfo(ownerAddr);
359
+ const isOwnerPasskey = ownerType.role === types.RoleType.ROLE_PASSKEY || ownerType.pk === types.KeyType.PASSKEY;
360
+ const coSigExtra = rawCoSig.extra || "";
361
+ if (isOwnerPasskey && !coSigExtra) return false;
362
+ if (!isOwnerPasskey && coSigExtra) return false;
363
+ let wallet;
348
364
  try {
349
- const wallet = fromPublicKey(rawCoSig.pk, toTypeInfo(ownerAddr));
350
- for (const payload of candidatePayloads) {
351
- if (await wallet.verify(payload, rawCoSig.signature, false)) return true;
352
- if (await wallet.verify(payload, rawCoSig.signature, true)) return true;
353
- }
365
+ wallet = fromPublicKey(rawCoSig.pk, ownerType);
354
366
  } catch {
355
367
  return false;
356
368
  }
369
+ for (const payload of candidatePayloads) {
370
+ try {
371
+ if (await wallet.verify(payload, rawCoSig.signature, false, coSigExtra)) return true;
372
+ } catch {}
373
+ try {
374
+ if (await wallet.verify(payload, rawCoSig.signature, true, coSigExtra)) return true;
375
+ } catch {}
376
+ }
357
377
  return false;
358
378
  };
359
379
  const getTxTimestampSeconds = () => {
@@ -424,6 +444,7 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
424
444
  const signerAddress = signerState?.address || tx?.from;
425
445
  if (delegatorState && (tx?.delegator && !isSameDid(delegatorState.address, tx.delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new CustomError("ACCOUNT_MIGRATED", `Delegator account ${tx?.delegator} is migrated`, { persist: false }));
426
446
  if (signerAddress && toTypeInfo(signerAddress).role === types.RoleType.ROLE_ASSET) {
447
+ if (hasExplicitCoSignatureInput()) return next(new CustomError("INVALID_SIGNATURE", "Unexpected owner coSignature on implicit asset delegation", { persist: false }));
427
448
  try {
428
449
  if (await verifyImplicitAssetOwnership(signerAddress, delegatorState || (tx?.delegator ? { address: tx.delegator } : null), context, tx?.delegator)) {
429
450
  set(context, "isImplicitDelegation", true);
@@ -446,6 +467,8 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
446
467
  const coSignedByOwner = await verifyOwnerCoSignature(signerState);
447
468
  const result = checkDelegation(delegationState, requirements, coSignedByOwner);
448
469
  if (result.code) return next(new CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: false }));
470
+ const hasDelegatedMultiSig = getListField(tx, "signatures").some((x) => Boolean(x?.delegator));
471
+ if (hasExplicitCoSignatureInput() && !coSignedByOwner && !hasDelegatedMultiSig) return next(new CustomError("INVALID_SIGNATURE", "Invalid owner coSignature", { persist: false }));
449
472
  if (coSignedByOwner) set(context, "coSignedByOwner", true);
450
473
  set(context, delegationKey, delegationState);
451
474
  set(context, "isDelegationChanged", true);
@@ -468,8 +491,8 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
468
491
  const { signer, delegator } = signature;
469
492
  const sigRequirements = typeof getRequirements === "function" ? getRequirements(context, index, signature) || [] : [];
470
493
  allRequirements.push(...sigRequirements);
471
- const signerState = signerStates?.find((x) => signer && isSameDid(x.address, signer));
472
- const delegatorState = delegatorStates?.find((x) => delegator && getRelatedAddresses(x).some((addr) => isSameDid(addr, delegator)));
494
+ const signerState = signerStates?.find((x) => Boolean(x && signer && getRelatedAddresses(x).some((addr) => isSameDid(addr, signer))));
495
+ const delegatorState = delegatorStates?.find((x) => Boolean(x && delegator && getRelatedAddresses(x).some((addr) => isSameDid(addr, delegator))));
473
496
  if (delegatorState && (delegator && !isSameDid(delegatorState.address, delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegator} is migrated`, { persist: false }));
474
497
  const signerAddress = signerState?.address || signer;
475
498
  if (signerAddress && toTypeInfo(signerAddress).role === types.RoleType.ROLE_ASSET) {
@@ -498,6 +521,7 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
498
521
  if (coSignedByOwner) set(context, "coSignedByOwner", true);
499
522
  if (!delegationStates.some((d) => isSameDid(d.address, delegationState.address))) delegationStates.push(delegationState);
500
523
  }
524
+ if (hasExplicitCoSignatureInput() && !get(context, "coSignedByOwner")) return next(new CustomError("INVALID_SIGNATURE", "Invalid owner coSignature", { persist: false }));
501
525
  set(context, requirementsKey, allRequirements);
502
526
  set(context, delegationKey, delegationStates);
503
527
  set(context, "isMultiSigDelegationVerified", true);
@@ -1,16 +1,16 @@
1
- import { assertEnvelopeMatchesTxContext, isCanonicalPasskeyExtra, isCanonicalWalletEnvelopeExtra } from "../helpers/replay-guard.mjs";
1
+ import { assertEnvelopeMatchesTxContext, getBridgeWithdrawEnvelopeContext, isCanonicalPasskeyExtra, isCanonicalWalletEnvelopeExtra } from "../helpers/replay-guard.mjs";
2
2
  import { name } from "../package.mjs";
3
3
  import { unwrapOpaqueAnyData } from "../helpers/unwrap-opaque-any.mjs";
4
4
  import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
5
5
  import { types } from "@ocap/mcrypto";
6
6
  import { CustomError } from "@ocap/util/lib/error";
7
- import get from "lodash/get.js";
7
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
8
8
  import { decodeAny } from "@ocap/message";
9
9
  import { getListField, setListField } from "@ocap/util/lib/get-list-field";
10
+ import get from "lodash/get.js";
10
11
  import cloneDeep from "lodash/cloneDeep.js";
11
12
  import omit from "lodash/omit.js";
12
13
  import Debug from "debug";
13
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
14
14
  import { fromPublicKey } from "@ocap/wallet";
15
15
 
16
16
  //#region src/pipes/verify-multisig-v2.ts
@@ -66,7 +66,8 @@ function CreateVerifyMultiSigV2Pipe({ signersKey }) {
66
66
  signer: address,
67
67
  from: signer,
68
68
  nonce: tx.nonce,
69
- action: context.txType
69
+ action: context.txType,
70
+ withdraw: await getBridgeWithdrawEnvelopeContext(context)
70
71
  });
71
72
  if (await wallet.verify(txBytes, signature, true, verifiedExtra) === false) return next(new CustomError("INVALID_SIGNATURE", `Signature for ${address} is not valid`));
72
73
  } catch (err) {
@@ -1,13 +1,13 @@
1
- import { assertEnvelopeMatchesTxContext, isCanonicalPasskeyExtra, isCanonicalWalletEnvelopeExtra } from "../helpers/replay-guard.mjs";
1
+ import { assertEnvelopeMatchesTxContext, getBridgeWithdrawEnvelopeContext, isCanonicalPasskeyExtra, isCanonicalWalletEnvelopeExtra } from "../helpers/replay-guard.mjs";
2
2
  import { unwrapOpaqueAnyData } from "../helpers/unwrap-opaque-any.mjs";
3
3
  import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
4
4
  import { types } from "@ocap/mcrypto";
5
5
  import { CustomError } from "@ocap/util/lib/error";
6
- import get from "lodash/get.js";
6
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
7
7
  import { decodeAny } from "@ocap/message";
8
8
  import { deleteListField, getListField, setListField } from "@ocap/util/lib/get-list-field";
9
+ import get from "lodash/get.js";
9
10
  import cloneDeep from "lodash/cloneDeep.js";
10
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
11
11
  import { fromPublicKey } from "@ocap/wallet";
12
12
 
13
13
  //#region src/pipes/verify-multisig.ts
@@ -45,7 +45,8 @@ function CreateVerifyMultiSigPipe(numSigs = 0) {
45
45
  signer: address,
46
46
  from: signer,
47
47
  nonce: tx.nonce,
48
- action: context.txType
48
+ action: context.txType,
49
+ withdraw: await getBridgeWithdrawEnvelopeContext(context)
49
50
  });
50
51
  if (await wallet.verify(txBytes, signature, true, extra) === false) return next(new CustomError("INVALID_SIGNATURE", `Multi signature for ${address} is not valid`));
51
52
  } catch (err) {
@@ -2,6 +2,12 @@ import { CustomError } from "@ocap/util/lib/error";
2
2
  import { IDecodedContext } from "@ocap/types";
3
3
 
4
4
  //#region src/pipes/verify-signature.d.ts
5
+ interface ParsedCoSignature {
6
+ pk: string;
7
+ signature: string;
8
+ extra?: string;
9
+ }
10
+ declare function parseCanonicalCoSignatureTxExtra(rawTxExtra: unknown): ParsedCoSignature | null;
5
11
  declare function VerifySignature(context: IDecodedContext, next: (err?: CustomError) => void): Promise<void>;
6
12
  //#endregion
7
- export { VerifySignature as default };
13
+ export { ParsedCoSignature, VerifySignature as default, parseCanonicalCoSignatureTxExtra };
@@ -1,11 +1,11 @@
1
- import { assertEnvelopeMatchesTxContext, isCanonicalPasskeyExtra, isCanonicalWalletEnvelopeExtra } from "../helpers/replay-guard.mjs";
1
+ import { assertEnvelopeMatchesTxContext, getBridgeWithdrawEnvelopeContext, isCanonicalPasskeyExtra, isCanonicalWalletEnvelopeExtra } from "../helpers/replay-guard.mjs";
2
2
  import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
3
- import { types } from "@ocap/mcrypto";
3
+ import { toTxHash, types } from "@ocap/mcrypto";
4
4
  import { CustomError } from "@ocap/util/lib/error";
5
- import get from "lodash/get.js";
5
+ import { isFromPublicKey, normalizePublicKeyHex, toTypeInfo } from "@arcblock/did";
6
6
  import { deleteListField, getListField } from "@ocap/util/lib/get-list-field";
7
+ import get from "lodash/get.js";
7
8
  import cloneDeep from "lodash/cloneDeep.js";
8
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
9
9
  import { fromPublicKey } from "@ocap/wallet";
10
10
 
11
11
  //#region src/pipes/verify-signature.ts
@@ -14,6 +14,94 @@ const V1_MULTISIG_TX_TYPES = new Set([
14
14
  "fg:t:exchange_v2",
15
15
  "fg:t:account_migrate"
16
16
  ]);
17
+ const ALLOWED_COSIG_KEYS = new Set([
18
+ "pk",
19
+ "signature",
20
+ "extra"
21
+ ]);
22
+ const ALLOWED_PASSKEY_COSIG_EXTRA_KEYS = new Set(["authenticatorData", "clientDataJSON"]);
23
+ const MAX_CO_SIGNATURE_TX_EXTRA_CHARS = 4096;
24
+ const MAX_CO_SIGNATURE_PASSKEY_EXTRA_CHARS = 2048;
25
+ function isCanonicalPasskeyCoSigExtra(extra) {
26
+ if (typeof extra !== "string" || extra.length === 0 || extra.length > MAX_CO_SIGNATURE_PASSKEY_EXTRA_CHARS || !isCanonicalPasskeyExtra(extra)) return false;
27
+ try {
28
+ const parsed = JSON.parse(extra);
29
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || JSON.stringify(parsed) !== extra) return false;
30
+ if (Object.keys(parsed).some((k) => !ALLOWED_PASSKEY_COSIG_EXTRA_KEYS.has(k))) return false;
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+ function parseCanonicalCoSignatureTxExtra(rawTxExtra) {
37
+ try {
38
+ let parsed = null;
39
+ if (typeof rawTxExtra === "string") {
40
+ if (rawTxExtra.length > MAX_CO_SIGNATURE_TX_EXTRA_CHARS || !rawTxExtra.startsWith("{")) return null;
41
+ parsed = JSON.parse(rawTxExtra);
42
+ if (JSON.stringify(parsed) !== rawTxExtra) return null;
43
+ } else if (rawTxExtra && typeof rawTxExtra === "object" && !Array.isArray(rawTxExtra)) {
44
+ const serialized = JSON.stringify(rawTxExtra);
45
+ if (!serialized || serialized.length > MAX_CO_SIGNATURE_TX_EXTRA_CHARS) return null;
46
+ parsed = rawTxExtra;
47
+ } else return null;
48
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
49
+ const topKeys = Object.keys(parsed);
50
+ if (topKeys.length !== 1 || topKeys[0] !== "coSignature") return null;
51
+ const coSig = parsed.coSignature;
52
+ if (!coSig || typeof coSig !== "object" || Array.isArray(coSig)) return null;
53
+ const coSigKeys = Object.keys(coSig);
54
+ if (coSigKeys.length < 2 || coSigKeys.length > 3 || coSigKeys.some((k) => !ALLOWED_COSIG_KEYS.has(k))) return null;
55
+ const { pk, signature, extra } = coSig;
56
+ if (typeof pk !== "string" || pk.trim().length === 0 || pk.length > 256) return null;
57
+ if (typeof signature !== "string" || signature.trim().length === 0 || signature.length > 512) return null;
58
+ if (extra !== void 0 && extra !== "") {
59
+ if (typeof extra !== "string" || !isCanonicalPasskeyCoSigExtra(extra)) return null;
60
+ return {
61
+ pk,
62
+ signature,
63
+ extra
64
+ };
65
+ }
66
+ return {
67
+ pk,
68
+ signature
69
+ };
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+ async function verifyStatelessCoSignature(coSig, candidates, candidatePayloads) {
75
+ if (candidates.length === 0 || candidatePayloads.length === 0) return false;
76
+ const coSigPkHex = normalizePublicKeyHex(coSig.pk);
77
+ if (!coSigPkHex) return false;
78
+ for (const { ownerAddr, delegateePk } of candidates) {
79
+ if (!ownerAddr) continue;
80
+ const forbiddenPkHex = delegateePk ? normalizePublicKeyHex(delegateePk) : "";
81
+ if (forbiddenPkHex && coSigPkHex === forbiddenPkHex) continue;
82
+ if (!isFromPublicKey(ownerAddr, coSig.pk)) continue;
83
+ const ownerType = toTypeInfo(ownerAddr);
84
+ const isOwnerPasskey = ownerType.role === types.RoleType.ROLE_PASSKEY || ownerType.pk === types.KeyType.PASSKEY;
85
+ const coSigExtra = coSig.extra || "";
86
+ if (isOwnerPasskey && !coSigExtra) continue;
87
+ if (!isOwnerPasskey && coSigExtra) continue;
88
+ let wallet;
89
+ try {
90
+ wallet = fromPublicKey(coSig.pk, ownerType);
91
+ } catch {
92
+ continue;
93
+ }
94
+ for (const payload of candidatePayloads) {
95
+ try {
96
+ if (await wallet.verify(payload, coSig.signature, false, coSigExtra)) return true;
97
+ } catch {}
98
+ try {
99
+ if (await wallet.verify(payload, coSig.signature, true, coSigExtra)) return true;
100
+ } catch {}
101
+ }
102
+ }
103
+ return false;
104
+ }
17
105
  async function VerifySignature(context, next) {
18
106
  const tx = cloneDeep(context.tx);
19
107
  const { signature } = tx;
@@ -35,22 +123,36 @@ async function VerifySignature(context, next) {
35
123
  const type = toTypeInfo(signer);
36
124
  const wallet = fromPublicKey(pk, type);
37
125
  const rawTxExtra = get(context, "extra.txExtra");
126
+ const rawDirectCoSig = get(context, "extra.coSignature");
127
+ const hasDirectCoSig = rawDirectCoSig !== void 0 && rawDirectCoSig !== null;
38
128
  const isPasskey = type.role === types.RoleType.ROLE_PASSKEY || type.pk === types.KeyType.PASSKEY;
39
129
  if (isPasskey && (typeof rawTxExtra !== "string" || !isCanonicalPasskeyExtra(rawTxExtra))) return next(new CustomError("INVALID_SIGNATURE", "Non-canonical extra data for passkey signer"));
40
130
  const isWalletEnvelope = !isPasskey && typeof rawTxExtra === "string" && isCanonicalWalletEnvelopeExtra(rawTxExtra, type.pk);
41
- if (!isPasskey && !isWalletEnvelope && rawTxExtra) {
131
+ if (!isPasskey && !isWalletEnvelope && rawTxExtra || hasDirectCoSig) {
42
132
  const v1Sigs = getListField(context.tx, "signatures");
43
133
  const v1Counterparty = v1Sigs[0]?.delegator || v1Sigs[0]?.signer;
44
- const isV1CounterpartyPasskey = Boolean(txType && V1_MULTISIG_TX_TYPES.has(txType) && v1Counterparty && (toTypeInfo(v1Counterparty).role === types.RoleType.ROLE_PASSKEY || toTypeInfo(v1Counterparty).pk === types.KeyType.PASSKEY) && typeof rawTxExtra === "string" && isCanonicalPasskeyExtra(rawTxExtra));
45
- const hasDelegator = Boolean(tx.delegator) || v1Sigs.some((s) => Boolean(s?.delegator));
46
- let isTier3CoSignatureExtra = false;
47
- if (hasDelegator) try {
48
- const parsed = typeof rawTxExtra === "string" ? rawTxExtra.trim().startsWith("{") ? JSON.parse(rawTxExtra) : null : rawTxExtra;
49
- isTier3CoSignatureExtra = Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && parsed.coSignature && typeof parsed.coSignature === "object" && typeof parsed.coSignature.pk === "string" && typeof parsed.coSignature.signature === "string");
50
- } catch {
51
- isTier3CoSignatureExtra = false;
134
+ if (!Boolean(!hasDirectCoSig && txType && V1_MULTISIG_TX_TYPES.has(txType) && v1Counterparty && (toTypeInfo(v1Counterparty).role === types.RoleType.ROLE_PASSKEY || toTypeInfo(v1Counterparty).pk === types.KeyType.PASSKEY) && typeof rawTxExtra === "string" && isCanonicalPasskeyExtra(rawTxExtra))) {
135
+ const hasDelegator = Boolean(tx.delegator) || v1Sigs.some((s) => Boolean(s?.delegator));
136
+ const parsedFromTxExtra = !isPasskey && !isWalletEnvelope && rawTxExtra ? parseCanonicalCoSignatureTxExtra(rawTxExtra) : null;
137
+ const parsedFromDirect = hasDirectCoSig ? parseCanonicalCoSignatureTxExtra({ coSignature: rawDirectCoSig }) : null;
138
+ if (hasDirectCoSig && !parsedFromDirect) return next(new CustomError("INVALID_SIGNATURE", "Invalid owner coSignature"));
139
+ if (!isPasskey && !isWalletEnvelope && rawTxExtra && !parsedFromTxExtra) return next(new CustomError("INVALID_SIGNATURE", `Unexpected extra data for non-passkey signer ${signer}`));
140
+ if (parsedFromTxExtra && parsedFromDirect && (parsedFromTxExtra.pk !== parsedFromDirect.pk || parsedFromTxExtra.signature !== parsedFromDirect.signature || (parsedFromTxExtra.extra || "") !== (parsedFromDirect.extra || ""))) return next(new CustomError("INVALID_SIGNATURE", "Conflicting owner coSignature inputs"));
141
+ const parsedCoSig = parsedFromTxExtra || parsedFromDirect;
142
+ if (!hasDelegator || !parsedCoSig) return next(new CustomError("INVALID_SIGNATURE", `Unexpected extra data for non-passkey signer ${signer}`));
143
+ const coSigCandidates = [];
144
+ if (tx.delegator && tx.from) coSigCandidates.push({
145
+ ownerAddr: tx.from,
146
+ delegateePk: tx.pk
147
+ });
148
+ for (const s of v1Sigs) if (s?.delegator && s?.signer) coSigCandidates.push({
149
+ ownerAddr: s.signer,
150
+ delegateePk: s.pk
151
+ });
152
+ const ctxTxHash = context.txHash;
153
+ const ctxUnsignedTxHash = context.unsignedTxHash || toTxHash(txBytes);
154
+ if (!await verifyStatelessCoSignature(parsedCoSig, coSigCandidates, Array.from(new Set([ctxTxHash, ctxUnsignedTxHash].filter((x) => typeof x === "string" && x.length > 0))))) return next(new CustomError("INVALID_SIGNATURE", "Invalid owner coSignature"));
52
155
  }
53
- if (!isV1CounterpartyPasskey && !isTier3CoSignatureExtra) return next(new CustomError("INVALID_SIGNATURE", `Unexpected extra data for non-passkey signer ${signer}`));
54
156
  }
55
157
  const extra = isPasskey ? rawTxExtra : isWalletEnvelope ? rawTxExtra : "";
56
158
  try {
@@ -59,7 +161,8 @@ async function VerifySignature(context, next) {
59
161
  signer,
60
162
  from: tx.from,
61
163
  nonce: tx.nonce,
62
- action: txType
164
+ action: txType,
165
+ withdraw: await getBridgeWithdrawEnvelopeContext(context)
63
166
  });
64
167
  if (!signature || await wallet.verify(txBytes, signature, true, extra || "") === false) return next(new CustomError("INVALID_SIGNATURE", "tx.signature is invalid"));
65
168
  } catch (err) {
@@ -71,4 +174,4 @@ async function VerifySignature(context, next) {
71
174
  }
72
175
 
73
176
  //#endregion
74
- export { VerifySignature as default };
177
+ export { VerifySignature as default, parseCanonicalCoSignatureTxExtra };
@@ -1,10 +1,10 @@
1
1
  import { name } from "../package.mjs";
2
2
  import { types } from "@ocap/mcrypto";
3
3
  import { CustomError } from "@ocap/util/lib/error";
4
- import get from "lodash/get.js";
4
+ import { toTypeInfo } from "@arcblock/did";
5
5
  import { getListField } from "@ocap/util/lib/get-list-field";
6
+ import get from "lodash/get.js";
6
7
  import Debug from "debug";
7
- import { toTypeInfo } from "@arcblock/did";
8
8
 
9
9
  //#region src/pipes/verify-signer.ts
10
10
  const debug = Debug(`${name}:pipe:verify-signer`);
@@ -1,7 +1,7 @@
1
1
  import { toAddress } from "@ocap/util";
2
2
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
3
  import { getListField } from "@ocap/util/lib/get-list-field";
4
+ import get from "lodash/get.js";
5
5
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
6
6
  import isEmpty from "lodash/isEmpty.js";
7
7
 
@@ -1,7 +1,7 @@
1
1
  import { BN, isSameDid } from "@ocap/util";
2
2
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
3
  import { getListField } from "@ocap/util/lib/get-list-field";
4
+ import get from "lodash/get.js";
5
5
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
6
6
  import isEmpty from "lodash/isEmpty.js";
7
7
 
@@ -1,7 +1,7 @@
1
1
  import { BN } from "@ocap/util";
2
2
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
3
  import { getListField } from "@ocap/util/lib/get-list-field";
4
+ import get from "lodash/get.js";
5
5
  import isEmpty from "lodash/isEmpty.js";
6
6
  import { createSortedList } from "@ocap/util/lib/create-sorted-list";
7
7
 
@@ -1,6 +1,6 @@
1
1
  import { CustomError } from "@ocap/util/lib/error";
2
- import get from "lodash/get.js";
3
2
  import { toTypeUrl } from "@ocap/message";
3
+ import get from "lodash/get.js";
4
4
 
5
5
  //#region src/pipes/verify-tx-size.ts
6
6
  const DEFAULT_MAX_EXTRA_SIZE = 8 * 1024;
@@ -1,11 +1,12 @@
1
- import { parseNonceBn } from "../helpers/replay-guard.mjs";
1
+ import { parseNonceBn as parseNonceBn$1 } from "../helpers/replay-guard.mjs";
2
2
  import { types } from "@ocap/mcrypto";
3
3
  import { BN } from "@ocap/util";
4
4
  import { CustomError } from "@ocap/util/lib/error";
5
- import get from "lodash/get.js";
5
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
6
+ import { account } from "@ocap/state";
6
7
  import { toTypeUrl } from "@ocap/message";
7
8
  import { getListField } from "@ocap/util/lib/get-list-field";
8
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
9
+ import get from "lodash/get.js";
9
10
  import isEmpty from "lodash/isEmpty.js";
10
11
 
11
12
  //#region src/pipes/verify-tx.ts
@@ -20,11 +21,17 @@ async function VerifyTx(context, next) {
20
21
  const { itx, chainId, nonce, pk, from, delegator } = context.tx;
21
22
  const expected = get(context, "config.chainId");
22
23
  if (chainId !== expected) return next(new CustomError("INVALID_CHAIN_ID", `Invalid chain id: expected ${expected}, got ${chainId}`));
23
- const nonceBn = parseNonceBn(nonce);
24
+ const nonceBn = parseNonceBn$1(nonce);
24
25
  if (!nonceBn || nonceBn.lte(new BN(0))) return next(new CustomError("INVALID_NONCE", "tx.nonce should be a positive integer"));
25
- const { supportedTxs, maxMultisig } = get(context, "config.transaction");
26
26
  const rawItx = itx;
27
27
  const itxTypeUrl = rawItx.typeUrl || (rawItx.type ? toTypeUrl(rawItx.type) : void 0);
28
+ const isExchangeV2 = itxTypeUrl === "fg:t:exchange_v2" || context.txType === "fg:t:exchange_v2";
29
+ if (!isEmpty(delegator) || isExchangeV2) {
30
+ const txTimeMs = context.txTime ? new Date(context.txTime).getTime() : NaN;
31
+ const maxNonce = (Number.isFinite(txTimeMs) ? txTimeMs : Date.now()) + account.DELEGATED_NONCE_MAX_FUTURE_MS;
32
+ if (nonceBn.gt(new BN(String(maxNonce), 10))) return next(new CustomError("INVALID_NONCE", `tx.nonce of a ${!isEmpty(delegator) ? "delegated" : "exchange_v2"} tx should not exceed the tx time in milliseconds plus 24 hours (max ${maxNonce}, got ${nonceBn.toString(10)})`));
33
+ }
34
+ const { supportedTxs, maxMultisig } = get(context, "config.transaction");
28
35
  if (!itxTypeUrl || supportedTxs.includes(itxTypeUrl) === false) return next(new CustomError("UNSUPPORTED_TX", `Transaction ${itxTypeUrl} is not supported`));
29
36
  if (getListField(context, "tx.signatures").length > maxMultisig) return next(new CustomError("INVALID_TX", "Too many multisig signatures"));
30
37
  if (toTypeInfo(from).role === types.RoleType.ROLE_ASSET && isEmpty(delegator)) return next(new CustomError("INVALID_TX", "Asset sender requires a delegator"));