@ocap/tx-pipeline 1.31.9 → 1.32.1

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.
@@ -20,6 +20,11 @@ declare const BRIDGE_RELEASE_KINDS: readonly number[];
20
20
  * It passes the config key pattern `fg:t:[_a-z0-9]+`.
21
21
  */
22
22
  declare const BRIDGE_RELEASE_V2_RESOURCE_KEY = "fg:t:deposit_token_v2_bridge";
23
+ /**
24
+ * maxTxSize / maxGasOps key of a v2 bridge `update_rollup` (typed patch, `evmGovernanceSync`, or `govProposalVote`, #1880).
25
+ * Keeps legacy v1 `fg:t:update_rollup` (`1691` bytes) untouched and survives per-node overrides of v1 `maxTxSize` keys.
26
+ */
27
+ declare const BRIDGE_UPDATE_V2_RESOURCE_KEY = "fg:t:update_rollup_bridge";
23
28
  /**
24
29
  * Tx types that may DEBIT a reserve (R1), besides a bridge release (`isNamedBridgeRelease`, which may only debit the
25
30
  * reserve of its own bridge, or of the `migratedTo` chain of a migrated bridge): `migrate_rollup` moves a whole reserve
@@ -50,9 +55,14 @@ declare function isBridgeRelease(txType: unknown, itx: unknown): boolean;
50
55
  * nothing in the release key space and may debit no reserve.
51
56
  */
52
57
  declare function isNamedBridgeRelease(txType: unknown, itx: unknown): boolean;
58
+ /**
59
+ * Whether `txType` / `itx` is a v2 bridge `update_rollup` (zero v1 rollup fields and non-empty `itx.data`).
60
+ */
61
+ declare function isBridgeUpdateV2(txType: unknown, itx: unknown): boolean;
53
62
  /**
54
63
  * The `transaction.maxTxSize` / `maxGasOps` key a tx is measured by: `fg:t:deposit_token_v2_bridge` for a bridge release,
55
- * the tx type itself otherwise (so every other tx, and every v1 deposit, keeps its key and limit).
64
+ * `fg:t:update_rollup_bridge` for a v2 bridge `update_rollup`, and the tx type itself otherwise (so every other tx,
65
+ * and every v1 deposit/rollup update, keeps its key and limit).
56
66
  */
57
67
  declare function txResourceKey(txType: string, itx: unknown): string;
58
68
  /** Strip a `did:abt:` prefix and whitespace: the form used in the evidence index and in rows. */
@@ -72,6 +82,14 @@ interface ResolvedBridge {
72
82
  body: rollup.BridgeBodyV2;
73
83
  /** the OCAP token of the bridge (the only token its reserve may hold) */
74
84
  token: string;
85
+ /** lowercase bare `0x` Ethereum gateway address (`''` when absent) */
86
+ ethGateway: string;
87
+ /** lowercase bare `0x` Ethereum token contract address (`''` when absent) */
88
+ ethToken: string;
89
+ /** lowercase bare `0x` current Ethereum Vault address (`''` when absent) */
90
+ ethVault: string;
91
+ /** lowercase bare `0x` historical Ethereum Vault addresses */
92
+ ethVaultHistory: string[];
75
93
  /** `txTime` in seconds the flags below were computed at */
76
94
  txSec: number;
77
95
  /** effective pause (a lone pause expires by itself): `isBridgePausedAt` */
@@ -143,4 +161,4 @@ interface BridgeReserveResolution {
143
161
  */
144
162
  declare function prepareBridgeReserveGate(context: Ctx): Promise<void>;
145
163
  //#endregion
146
- export { BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RELEASE_KINDS, BRIDGE_RELEASE_V2_RESOURCE_KEY, BRIDGE_RELEASE_V2_TX_TYPE, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BRIDGE_WITHDRAW_V2_TX_TYPE, BridgeReserveResolution, ReleaseResolution, ResolvedBridge, bareAddress, describeBridge, isBridgeRelease, isBridgeReserveRole, isNamedBridgeRelease, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, stripTxTypePrefix, txResourceKey };
164
+ export { BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RELEASE_KINDS, BRIDGE_RELEASE_V2_RESOURCE_KEY, BRIDGE_RELEASE_V2_TX_TYPE, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BRIDGE_UPDATE_V2_RESOURCE_KEY, BRIDGE_WITHDRAW_V2_TX_TYPE, BridgeReserveResolution, ReleaseResolution, ResolvedBridge, bareAddress, describeBridge, isBridgeRelease, isBridgeReserveRole, isBridgeUpdateV2, isNamedBridgeRelease, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, stripTxTypePrefix, txResourceKey };
@@ -42,6 +42,11 @@ const BRIDGE_RELEASE_KINDS = [
42
42
  */
43
43
  const BRIDGE_RELEASE_V2_RESOURCE_KEY = "fg:t:deposit_token_v2_bridge";
44
44
  /**
45
+ * maxTxSize / maxGasOps key of a v2 bridge `update_rollup` (typed patch, `evmGovernanceSync`, or `govProposalVote`, #1880).
46
+ * Keeps legacy v1 `fg:t:update_rollup` (`1691` bytes) untouched and survives per-node overrides of v1 `maxTxSize` keys.
47
+ */
48
+ const BRIDGE_UPDATE_V2_RESOURCE_KEY = "fg:t:update_rollup_bridge";
49
+ /**
45
50
  * Tx types that may DEBIT a reserve (R1), besides a bridge release (`isNamedBridgeRelease`, which may only debit the
46
51
  * reserve of its own bridge, or of the `migratedTo` chain of a migrated bridge): `migrate_rollup` moves a whole reserve
47
52
  * to its successor's.
@@ -83,11 +88,29 @@ function isNamedBridgeRelease(txType, itx) {
83
88
  return isBridgeRelease(txType, itx) && typeof rollupField === "string" && rollupField.length > 0;
84
89
  }
85
90
  /**
91
+ * Whether `txType` / `itx` is a v2 bridge `update_rollup` (zero v1 rollup fields and non-empty `itx.data`).
92
+ */
93
+ function isBridgeUpdateV2(txType, itx) {
94
+ if (stripTxTypePrefix(txType) !== "update_rollup") return false;
95
+ if (!itx || typeof itx !== "object") return false;
96
+ const rec = itx;
97
+ if (!rec.data) return false;
98
+ try {
99
+ rollup.assertV1FieldsUnused(rec, "INVALID_ROLLUP_UPDATE");
100
+ return true;
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+ /**
86
106
  * The `transaction.maxTxSize` / `maxGasOps` key a tx is measured by: `fg:t:deposit_token_v2_bridge` for a bridge release,
87
- * the tx type itself otherwise (so every other tx, and every v1 deposit, keeps its key and limit).
107
+ * `fg:t:update_rollup_bridge` for a v2 bridge `update_rollup`, and the tx type itself otherwise (so every other tx,
108
+ * and every v1 deposit/rollup update, keeps its key and limit).
88
109
  */
89
110
  function txResourceKey(txType, itx) {
90
- return isBridgeRelease(txType, itx) ? BRIDGE_RELEASE_V2_RESOURCE_KEY : txType;
111
+ if (isBridgeRelease(txType, itx)) return BRIDGE_RELEASE_V2_RESOURCE_KEY;
112
+ if (isBridgeUpdateV2(txType, itx)) return BRIDGE_UPDATE_V2_RESOURCE_KEY;
113
+ return txType;
91
114
  }
92
115
  /** Strip a `did:abt:` prefix and whitespace: the form used in the evidence index and in rows. */
93
116
  const bareAddress = (address) => String(address ?? "").trim().replace(/^did:abt:/, "");
@@ -131,12 +154,20 @@ function describeBridge(row, txSec) {
131
154
  const final = rollup.isBridgeFinalAt(body, txSec);
132
155
  const paused = rollup.isBridgePausedAt(row, txSec);
133
156
  const migrated = typeof body.migratedTo === "string" && body.migratedTo.length > 0;
157
+ const ethGateway = rollup.bareEthAddress(body.gateway);
158
+ const ethToken = rollup.bareEthAddress(row.contractAddress);
159
+ const ethVault = rollup.bareEthAddress(row.vaultAddress);
160
+ const ethVaultHistory = Array.isArray(row.vaultHistory) ? row.vaultHistory.map((v) => rollup.bareEthAddress(v)).filter(Boolean) : [];
134
161
  return {
135
162
  address: row.address,
136
163
  reserve: toBridgeReserveAddress(row.address),
137
164
  state: row,
138
165
  body,
139
166
  token: String(row.tokenAddress || ""),
167
+ ethGateway,
168
+ ethToken,
169
+ ethVault,
170
+ ethVaultHistory,
140
171
  txSec,
141
172
  paused,
142
173
  closing,
@@ -289,4 +320,4 @@ async function prepareBridgeReserveGate(context) {
289
320
  }
290
321
 
291
322
  //#endregion
292
- export { BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RELEASE_KINDS, BRIDGE_RELEASE_V2_RESOURCE_KEY, BRIDGE_RELEASE_V2_TX_TYPE, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BRIDGE_WITHDRAW_V2_TX_TYPE, bareAddress, describeBridge, isBridgeRelease, isBridgeReserveRole, isNamedBridgeRelease, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, stripTxTypePrefix, txResourceKey };
323
+ export { BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RELEASE_KINDS, BRIDGE_RELEASE_V2_RESOURCE_KEY, BRIDGE_RELEASE_V2_TX_TYPE, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, BRIDGE_UPDATE_V2_RESOURCE_KEY, BRIDGE_WITHDRAW_V2_TX_TYPE, bareAddress, describeBridge, isBridgeRelease, isBridgeReserveRole, isBridgeUpdateV2, isNamedBridgeRelease, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, stripTxTypePrefix, txResourceKey };
@@ -77,6 +77,8 @@ function checkBridgeWithdrawV2(context, bridge) {
77
77
  if (typeof token.value !== "string" || !DECIMAL.test(token.value)) return fail(BRIDGE_WITHDRAW_AMOUNT, "Bridge withdraw amount must be a decimal string");
78
78
  const parsed = parseStrictEthAddress(itx.to);
79
79
  if (!parsed.ok) return fail(BRIDGE_WITHDRAW_RECIPIENT, `Bridge withdraw recipient is not a valid Ethereum address (${parsed.reason})`);
80
+ const recipient = parsed.lowercase;
81
+ if (recipient === "0x0000000000000000000000000000000000000000" || bridge.ethGateway && recipient === bridge.ethGateway || bridge.ethToken && recipient === bridge.ethToken || bridge.ethVault && recipient === bridge.ethVault || bridge.ethVaultHistory.includes(recipient)) return fail(BRIDGE_WITHDRAW_RECIPIENT, "Bridge withdraw recipient cannot be the zero address, gateway, token contract, or bridge vault");
80
82
  if (itx.proposer !== void 0 && itx.proposer !== null && itx.proposer !== "") return fail(BRIDGE_WITHDRAW_FEE, "Bridge withdraw has no proposer");
81
83
  if (!isNoFee(itx.maxFee) || !isNoFee(itx.actualFee)) return fail(BRIDGE_WITHDRAW_FEE, "Bridge withdraw carries no maxFee or actualFee");
82
84
  if (!isEmptyData(itx.data)) return fail(BRIDGE_WITHDRAW_RECIPIENT, "Bridge withdraw carries no itx.data: the recipient is itx.to");
package/esm/index.d.mts CHANGED
@@ -32,6 +32,7 @@ import VerifyTx from "./pipes/verify-tx.mjs";
32
32
  import CreateVerifyTxInputPipe from "./pipes/verify-tx-input.mjs";
33
33
  import VerifyTxSize from "./pipes/verify-tx-size.mjs";
34
34
  import CreateVerifyUpdaterPipe from "./pipes/verify-updater.mjs";
35
+ import { inBridgeGovKeySpace } from "./pipes/bridge-release-gate.mjs";
35
36
  import { IAccountUpdate, IBaseContext, IDecodedContext, IDecodedTransaction, IExecutedContext, IGasContext, IReadyContext, ITxOnlyContext, IWithAsset, IWithAssets, IWithDelegation, IWithDelegator, IWithEvidence, IWithFactory, IWithLocked, IWithOwner, IWithReceiver, IWithRollup, IWithRollupBlock, IWithSender, IWithStake, IWithStakes, IWithToken, IWithTokenFactory, IWithTokens, TTransactionReceipt } from "@ocap/types";
36
37
 
37
38
  //#region src/index.d.ts
@@ -101,4 +102,4 @@ declare const _default: {
101
102
  };
102
103
  };
103
104
  //#endregion
104
- export { CreateAntiLandAttackPipe as AntiLandAttack, BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, type BridgeReserveResolution, DecodeItx, DecodeTx, ENCRYPTED_NFT_SCHEMA_VERSION, type EncryptedAssetEnvelope, type EncryptedNftAlgorithm, type EncryptedNftOwnerCipherEnvelope, type EncryptedNftPrivateMetadata, type EncryptedNftPublicDiscoveryHeader, type ErrorPipeFunction, CreateExtractReceiverPipe as ExtractReceiver, CreateExtractSignerPipe as ExtractSigner, CreateExtractStatePipe as ExtractState, type IAccountUpdate, type IBaseContext, type IDecodedContext, type IDecodedTransaction, type IExecutedContext, type IGasContext, type IReadyContext, type IStateWriteTracker, type ITxOnlyContext, type IWithAsset, type IWithAssets, type IWithDelegation, type IWithDelegator, type IWithEvidence, type IWithFactory, type IWithLocked, type IWithOwner, type IWithReceiver, type IWithRollup, type IWithRollupBlock, type IWithSender, type IWithStake, type IWithStakes, type IWithToken, type IWithTokenFactory, type IWithTokens, MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_ENCRYPTED_NFT_CATEGORY_LENGTH, MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS, MAX_ENCRYPTED_NFT_SUMMARY_LENGTH, MAX_ENCRYPTED_NFT_TAGS, MAX_ENCRYPTED_NFT_TAG_LENGTH, MAX_ENCRYPTED_NFT_URI_LENGTH, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, type OpenEncryptedNftAsOwnerInput, type OpenEncryptedNftAsOwnerResult, type PipeFunction, type PipeNext, type PipeOptions, CreatePostExecutionInvariantGatePipe as PostExecutionInvariantGate, PreFlightWaf, RELEASE_RING_SLOTS, type ReleaseResolution, type ReleaseRing, type ResolvedBridge, type RewrapEncryptedNftForNewOwnerInput, PipelineRunner as Runner, type SealEncryptedNftForOwnerInput, TRACKED_STATE_TABLES, type TTransactionReceipt, CreateTakeStateSnapshotPipe as TakeStateSnapshot, type TrackedStateTable, CreateUpdateOwnerPipe as UpdateOwner, V1_EVIDENCE_DATA, VALID_ENCRYPTED_NFT_ALGORITHMS, CreateVerifyAccountMigrationPipe as VerifyAccountMigration, CreatedVerifyBlockedPipe as VerifyBlocked, CreateVerifyDelegationPipe as VerifyDelegation, type VerifyEncryptedNftHandoverInput, CreateVerifyInfoPipe as VerifyInfo, CreateVerifyListSizePipe as VerifyListSize, CreateVerifyMultiSigPipe as VerifyMultiSig, CreateVerifyMultiSigV2Pipe as VerifyMultiSigV2, CreateVerifySenderPipe as VerifySender, VerifyServiceFee, VerifySignature, CreateVerifySignerPipe as VerifySigner, CreateVerifyStateDiffPipe as VerifyStateDiff, CreateVerifyTokenBalancePipe as VerifyTokenBalance, CreateVerifyTransferrablePipe as VerifyTransferrable, VerifyTx, CreateVerifyTxInputPipe as VerifyTxInput, VerifyTxSize, CreateVerifyUpdaterPipe as VerifyUpdater, assertKnownItxFields, assertRawWireEnvelope, canonicalizeEncryptedNftMetadata, computeEncryptedNftCekCommitmentHash, computeEncryptedNftPlaintextHash, computeEncryptedNftPublicHeaderAad, _default as default, deriveOwnerPublicKeyHexFromSecretKey, describeBridge, formatBucketData, getReleaseBucketKey, getReleaseTombstoneKey, groupStatesByAddress, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, isBridgeReserveRole, isCanonicalPasskeyExtra, isDelegationSufficient, isV1EvidenceRow, normalizeEntityKey, openEncryptedNftAsOwner, parseBucketData, parseNonceBn, pipes, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, rewrapEncryptedNftForNewOwner, rollbackTrackedStateWrites, scanItxPayloadAnomalies, sealEncryptedNftForOwner, validateEncryptedAssetEnvelope, verifyAssetHierarchy, verifyEncryptedNftHandover, verifyImplicitAssetOwnership, CreateVerifyTokenAccessPipe as verifyTokenAccess };
105
+ export { CreateAntiLandAttackPipe as AntiLandAttack, BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, type BridgeReserveResolution, DecodeItx, DecodeTx, ENCRYPTED_NFT_SCHEMA_VERSION, type EncryptedAssetEnvelope, type EncryptedNftAlgorithm, type EncryptedNftOwnerCipherEnvelope, type EncryptedNftPrivateMetadata, type EncryptedNftPublicDiscoveryHeader, type ErrorPipeFunction, CreateExtractReceiverPipe as ExtractReceiver, CreateExtractSignerPipe as ExtractSigner, CreateExtractStatePipe as ExtractState, type IAccountUpdate, type IBaseContext, type IDecodedContext, type IDecodedTransaction, type IExecutedContext, type IGasContext, type IReadyContext, type IStateWriteTracker, type ITxOnlyContext, type IWithAsset, type IWithAssets, type IWithDelegation, type IWithDelegator, type IWithEvidence, type IWithFactory, type IWithLocked, type IWithOwner, type IWithReceiver, type IWithRollup, type IWithRollupBlock, type IWithSender, type IWithStake, type IWithStakes, type IWithToken, type IWithTokenFactory, type IWithTokens, MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_ENCRYPTED_NFT_CATEGORY_LENGTH, MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS, MAX_ENCRYPTED_NFT_SUMMARY_LENGTH, MAX_ENCRYPTED_NFT_TAGS, MAX_ENCRYPTED_NFT_TAG_LENGTH, MAX_ENCRYPTED_NFT_URI_LENGTH, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, type OpenEncryptedNftAsOwnerInput, type OpenEncryptedNftAsOwnerResult, type PipeFunction, type PipeNext, type PipeOptions, CreatePostExecutionInvariantGatePipe as PostExecutionInvariantGate, PreFlightWaf, RELEASE_RING_SLOTS, type ReleaseResolution, type ReleaseRing, type ResolvedBridge, type RewrapEncryptedNftForNewOwnerInput, PipelineRunner as Runner, type SealEncryptedNftForOwnerInput, TRACKED_STATE_TABLES, type TTransactionReceipt, CreateTakeStateSnapshotPipe as TakeStateSnapshot, type TrackedStateTable, CreateUpdateOwnerPipe as UpdateOwner, V1_EVIDENCE_DATA, VALID_ENCRYPTED_NFT_ALGORITHMS, CreateVerifyAccountMigrationPipe as VerifyAccountMigration, CreatedVerifyBlockedPipe as VerifyBlocked, CreateVerifyDelegationPipe as VerifyDelegation, type VerifyEncryptedNftHandoverInput, CreateVerifyInfoPipe as VerifyInfo, CreateVerifyListSizePipe as VerifyListSize, CreateVerifyMultiSigPipe as VerifyMultiSig, CreateVerifyMultiSigV2Pipe as VerifyMultiSigV2, CreateVerifySenderPipe as VerifySender, VerifyServiceFee, VerifySignature, CreateVerifySignerPipe as VerifySigner, CreateVerifyStateDiffPipe as VerifyStateDiff, CreateVerifyTokenBalancePipe as VerifyTokenBalance, CreateVerifyTransferrablePipe as VerifyTransferrable, VerifyTx, CreateVerifyTxInputPipe as VerifyTxInput, VerifyTxSize, CreateVerifyUpdaterPipe as VerifyUpdater, assertKnownItxFields, assertRawWireEnvelope, canonicalizeEncryptedNftMetadata, computeEncryptedNftCekCommitmentHash, computeEncryptedNftPlaintextHash, computeEncryptedNftPublicHeaderAad, _default as default, deriveOwnerPublicKeyHexFromSecretKey, describeBridge, formatBucketData, getReleaseBucketKey, getReleaseTombstoneKey, groupStatesByAddress, inBridgeGovKeySpace, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, isBridgeReserveRole, isCanonicalPasskeyExtra, isDelegationSufficient, isV1EvidenceRow, normalizeEntityKey, openEncryptedNftAsOwner, parseBucketData, parseNonceBn, pipes, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, rewrapEncryptedNftForNewOwner, rollbackTrackedStateWrites, scanItxPayloadAnomalies, sealEncryptedNftForOwner, validateEncryptedAssetEnvelope, verifyAssetHierarchy, verifyEncryptedNftHandover, verifyImplicitAssetOwnership, CreateVerifyTokenAccessPipe as verifyTokenAccess };
package/esm/index.mjs CHANGED
@@ -15,6 +15,7 @@ import DecodeTx from "./pipes/decode-tx.mjs";
15
15
  import CreateExtractReceiverPipe from "./pipes/extract-receiver.mjs";
16
16
  import CreateExtractSignerPipe from "./pipes/extract-signer.mjs";
17
17
  import CreateExtractStatePipe from "./pipes/extract-state.mjs";
18
+ import { inBridgeGovKeySpace } from "./pipes/bridge-release-gate.mjs";
18
19
  import post_execution_invariant_gate_default, { MAX_POST_EXECUTION_WRITE_SET_ENTRIES, TRACKED_STATE_TABLES, inspectPostExecutionInvariants, installStateWriteInterceptor, normalizeEntityKey, rollbackTrackedStateWrites } from "./pipes/post-execution-invariant-gate.mjs";
19
20
  import CreateVerifyStateDiffPipe, { groupStatesByAddress } from "./pipes/verify-state-diff.mjs";
20
21
  import CreateTakeStateSnapshotPipe from "./pipes/take-state-snapshot.mjs";
@@ -71,4 +72,4 @@ var src_default = {
71
72
  };
72
73
 
73
74
  //#endregion
74
- export { CreateAntiLandAttackPipe as AntiLandAttack, BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, DecodeItx, DecodeTx, ENCRYPTED_NFT_SCHEMA_VERSION, CreateExtractReceiverPipe as ExtractReceiver, CreateExtractSignerPipe as ExtractSigner, CreateExtractStatePipe as ExtractState, MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_ENCRYPTED_NFT_CATEGORY_LENGTH, MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS, MAX_ENCRYPTED_NFT_SUMMARY_LENGTH, MAX_ENCRYPTED_NFT_TAGS, MAX_ENCRYPTED_NFT_TAG_LENGTH, MAX_ENCRYPTED_NFT_URI_LENGTH, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, post_execution_invariant_gate_default as PostExecutionInvariantGate, PreFlightWaf, RELEASE_RING_SLOTS, runner_default as Runner, TRACKED_STATE_TABLES, CreateTakeStateSnapshotPipe as TakeStateSnapshot, CreateUpdateOwnerPipe as UpdateOwner, V1_EVIDENCE_DATA, VALID_ENCRYPTED_NFT_ALGORITHMS, CreateVerifyAccountMigrationPipe as VerifyAccountMigration, CreatedVerifyBlockedPipe as VerifyBlocked, CreateVerifyDelegationPipe as VerifyDelegation, CreateVerifyInfoPipe as VerifyInfo, CreateVerifyListSizePipe as VerifyListSize, CreateVerifyMultiSigPipe as VerifyMultiSig, CreateVerifyMultiSigV2Pipe as VerifyMultiSigV2, CreateVerifySenderPipe as VerifySender, VerifyServiceFee, VerifySignature, CreateVerifySignerPipe as VerifySigner, CreateVerifyStateDiffPipe as VerifyStateDiff, CreateVerifyTokenBalancePipe as VerifyTokenBalance, CreateVerifyTransferrablePipe as VerifyTransferrable, VerifyTx, CreateVerifyTxInputPipe as VerifyTxInput, VerifyTxSize, CreateVerifyUpdaterPipe as VerifyUpdater, assertKnownItxFields, assertRawWireEnvelope, canonicalizeEncryptedNftMetadata, computeEncryptedNftCekCommitmentHash, computeEncryptedNftPlaintextHash, computeEncryptedNftPublicHeaderAad, src_default as default, deriveOwnerPublicKeyHexFromSecretKey, describeBridge, formatBucketData, getReleaseBucketKey, getReleaseTombstoneKey, groupStatesByAddress, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, isBridgeReserveRole, isCanonicalPasskeyExtra, isDelegationSufficient, isV1EvidenceRow, normalizeEntityKey, openEncryptedNftAsOwner, parseBucketData, parseNonceBn, pipes, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, rewrapEncryptedNftForNewOwner, rollbackTrackedStateWrites, scanItxPayloadAnomalies, sealEncryptedNftForOwner, validateEncryptedAssetEnvelope, verifyAssetHierarchy, verifyEncryptedNftHandover, verifyImplicitAssetOwnership, CreateVerifyTokenAccessPipe as verifyTokenAccess };
75
+ export { CreateAntiLandAttackPipe as AntiLandAttack, BRIDGE_MAX_MIGRATION_HOPS, BRIDGE_RECONCILE_TX_TYPES, BRIDGE_RESERVE_CREDIT_TX_TYPES, BRIDGE_RESERVE_DEBIT_TX_TYPES, DecodeItx, DecodeTx, ENCRYPTED_NFT_SCHEMA_VERSION, CreateExtractReceiverPipe as ExtractReceiver, CreateExtractSignerPipe as ExtractSigner, CreateExtractStatePipe as ExtractState, MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_ENCRYPTED_NFT_CATEGORY_LENGTH, MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS, MAX_ENCRYPTED_NFT_SUMMARY_LENGTH, MAX_ENCRYPTED_NFT_TAGS, MAX_ENCRYPTED_NFT_TAG_LENGTH, MAX_ENCRYPTED_NFT_URI_LENGTH, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, post_execution_invariant_gate_default as PostExecutionInvariantGate, PreFlightWaf, RELEASE_RING_SLOTS, runner_default as Runner, TRACKED_STATE_TABLES, CreateTakeStateSnapshotPipe as TakeStateSnapshot, CreateUpdateOwnerPipe as UpdateOwner, V1_EVIDENCE_DATA, VALID_ENCRYPTED_NFT_ALGORITHMS, CreateVerifyAccountMigrationPipe as VerifyAccountMigration, CreatedVerifyBlockedPipe as VerifyBlocked, CreateVerifyDelegationPipe as VerifyDelegation, CreateVerifyInfoPipe as VerifyInfo, CreateVerifyListSizePipe as VerifyListSize, CreateVerifyMultiSigPipe as VerifyMultiSig, CreateVerifyMultiSigV2Pipe as VerifyMultiSigV2, CreateVerifySenderPipe as VerifySender, VerifyServiceFee, VerifySignature, CreateVerifySignerPipe as VerifySigner, CreateVerifyStateDiffPipe as VerifyStateDiff, CreateVerifyTokenBalancePipe as VerifyTokenBalance, CreateVerifyTransferrablePipe as VerifyTransferrable, VerifyTx, CreateVerifyTxInputPipe as VerifyTxInput, VerifyTxSize, CreateVerifyUpdaterPipe as VerifyUpdater, assertKnownItxFields, assertRawWireEnvelope, canonicalizeEncryptedNftMetadata, computeEncryptedNftCekCommitmentHash, computeEncryptedNftPlaintextHash, computeEncryptedNftPublicHeaderAad, src_default as default, deriveOwnerPublicKeyHexFromSecretKey, describeBridge, formatBucketData, getReleaseBucketKey, getReleaseTombstoneKey, groupStatesByAddress, inBridgeGovKeySpace, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, isBridgeReserveRole, isCanonicalPasskeyExtra, isDelegationSufficient, isV1EvidenceRow, normalizeEntityKey, openEncryptedNftAsOwner, parseBucketData, parseNonceBn, pipes, prepareBridgeReserveGate, reserveIndexKey, resolveBridge, resolveBridgeForRelease, resolveBridgeForReserve, rewrapEncryptedNftForNewOwner, rollbackTrackedStateWrites, scanItxPayloadAnomalies, sealEncryptedNftForOwner, validateEncryptedAssetEnvelope, verifyAssetHierarchy, verifyEncryptedNftHandover, verifyImplicitAssetOwnership, CreateVerifyTokenAccessPipe as verifyTokenAccess };
@@ -1,7 +1,9 @@
1
1
  import { BridgeReserveResolution } from "../bridge-reserves.mjs";
2
+ import { inBridgeGovKeySpace } from "@ocap/mcrypto";
2
3
  import { BN } from "@ocap/util";
3
4
 
4
5
  //#region src/pipes/bridge-release-gate.d.ts
6
+
5
7
  type Rec = Record<string, unknown>;
6
8
  type Bn = InstanceType<typeof BN>;
7
9
  interface BridgeReleaseGateInput {
@@ -28,4 +30,4 @@ interface BridgeReleaseGateInput {
28
30
  declare const bridgeRecordKind: (row: Rec | null | undefined) => string | null;
29
31
  declare function assertBridgeReleaseProtected(input: BridgeReleaseGateInput): void;
30
32
  //#endregion
31
- export { BridgeReleaseGateInput, assertBridgeReleaseProtected, bridgeRecordKind };
33
+ export { BridgeReleaseGateInput, assertBridgeReleaseProtected, bridgeRecordKind, inBridgeGovKeySpace };
@@ -1,7 +1,9 @@
1
1
  import { getReleaseTombstoneKey, identifyBucketRow, isV1EvidenceRow } from "../bridge-release-keys.mjs";
2
2
  import { bareAddress, isNamedBridgeRelease } from "../bridge-reserves.mjs";
3
- import { inBridgeReleaseKeySpace } from "@ocap/mcrypto";
3
+ import { bridgeGovDocKey, bridgeGovIndexKey, coerceEvmProposal, coerceOcapProposal, computeEvmProposalHash, computeOcapProposalId, inBridgeGovKeySpace, inBridgeReleaseKeySpace, isBridgeGovKey } from "@ocap/mcrypto";
4
4
  import { BN } from "@ocap/util";
5
+ import { rollup } from "@ocap/state";
6
+ import { decodeAny } from "@ocap/message";
5
7
  import isEqual from "lodash/isEqual.js";
6
8
 
7
9
  //#region src/pipes/bridge-release-gate.ts
@@ -39,14 +41,14 @@ const CANONICAL_UINT = /^(?:0|[1-9]\d*)$/;
39
41
  const isReleaseForm = (txType, itx) => isNamedBridgeRelease(txType, itx);
40
42
  /** The release fields: the deposit fields, reused (`rollup`, `token.value`, `evidence.hash`, `token.address`). */
41
43
  const releaseFieldsOf = (itx) => {
42
- const token = itx.token ?? {};
44
+ const token$1 = itx.token ?? {};
43
45
  const evidence = itx.evidence ?? {};
44
46
  return {
45
47
  label: "deposit_token_v2 (bridge release)",
46
48
  bridge: itx.rollup,
47
- amount: token.value,
49
+ amount: token$1.value,
48
50
  evidence: evidence.hash,
49
- token: token.address
51
+ token: token$1.address
50
52
  };
51
53
  };
52
54
  /** owners of the hex-keyed bridge records, by `data.value.kind` (#1505 L2 rows, membership tombstones) */
@@ -69,10 +71,131 @@ const bodyOf = (row) => {
69
71
  const v = (row?.data)?.value;
70
72
  return v && typeof v === "object" ? v : null;
71
73
  };
74
+ const GOV_RECORD_KINDS = new Set(["bridge-gov-index", "bridge-gov-doc"]);
75
+ const govBodyOf = (row) => {
76
+ const raw = row?.data;
77
+ if (typeof raw === "string") try {
78
+ const parsed = JSON.parse(raw);
79
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ const d = raw;
84
+ if (d && typeof d === "object" && d.type === "json" && d.value && typeof d.value === "object" && !Array.isArray(d.value)) return d.value;
85
+ return null;
86
+ };
87
+ const identifyGovRow = (row) => {
88
+ const kind = govBodyOf(row)?.kind;
89
+ return typeof kind === "string" && GOV_RECORD_KINDS.has(kind) ? kind : null;
90
+ };
91
+ const readItxJsonValue = (rawData) => {
92
+ if (!rawData || typeof rawData !== "object") return null;
93
+ const r = rawData;
94
+ if (r.type === "json" && r.value && typeof r.value === "object" && !Array.isArray(r.value)) return r.value;
95
+ try {
96
+ const decoded = decodeAny(rawData);
97
+ if (decoded?.type === "json" && decoded.value && typeof decoded.value === "object" && !Array.isArray(decoded.value)) return decoded.value;
98
+ } catch {
99
+ return null;
100
+ }
101
+ return null;
102
+ };
103
+ const findPreRollupRow = (input, bridge) => {
104
+ if (typeof bridge !== "string" || !bridge) return null;
105
+ const target = bareAddress(bridge);
106
+ if (!target) return null;
107
+ return [...input.before.get("rollup")?.entries() ?? []].find(([k]) => bareAddress(k) === target)?.[1] ?? null;
108
+ };
109
+ function assertBridgeGovVoteIsolated(input, govVoteRaw, writtenEvidence, violation) {
110
+ const label = "update_rollup (govProposalVote)";
111
+ const G = (msg) => violation("BRIDGE_GOV_VOTE_ISOLATION_VIOLATION", msg);
112
+ const bridgeRaw = input.itx.rollup;
113
+ if (typeof bridgeRaw !== "string" || !bridgeRaw || bridgeRaw !== bareAddress(bridgeRaw)) throw G(`${label} must name a bare v2 bridge DID in itx.rollup`);
114
+ if (!govVoteRaw || typeof govVoteRaw !== "object" || Array.isArray(govVoteRaw)) throw G(`${label} payload must be a plain object`);
115
+ const govVote = govVoteRaw;
116
+ let proposalId = "";
117
+ try {
118
+ if (govVote.proposal && typeof govVote.proposal === "object" && !Array.isArray(govVote.proposal)) {
119
+ const p = govVote.proposal;
120
+ if (p.plane === "ethereum") proposalId = computeEvmProposalHash(coerceEvmProposal(p));
121
+ else if (p.plane === "ocap") proposalId = computeOcapProposalId(coerceOcapProposal(p));
122
+ else throw new Error("unknown proposal plane");
123
+ if (govVote.proposalId !== void 0 && (typeof govVote.proposalId !== "string" || govVote.proposalId.toLowerCase() !== proposalId.toLowerCase())) throw new Error("proposalId mismatch");
124
+ } else if (typeof govVote.proposalId === "string" && /^0x[0-9a-f]{64}$/i.test(govVote.proposalId)) proposalId = govVote.proposalId.toLowerCase();
125
+ else throw new Error("missing proposal");
126
+ } catch (err) {
127
+ throw G(`${label} carries an invalid proposal or proposalId: ${err.message}`);
128
+ }
129
+ let expectedIndexKey = "";
130
+ let expectedDocKey = "";
131
+ try {
132
+ expectedIndexKey = bridgeGovIndexKey(bridgeRaw);
133
+ expectedDocKey = bridgeGovDocKey(bridgeRaw, proposalId);
134
+ } catch (err) {
135
+ throw G(`${label} cannot derive governance evidence keys: ${err.message}`);
136
+ }
137
+ if (writtenEvidence.size === 0 || !writtenEvidence.has(expectedDocKey) || [...writtenEvidence].some((k) => k !== expectedIndexKey && k !== expectedDocKey)) throw G(`${label} may write only ${expectedIndexKey} and ${expectedDocKey}`);
138
+ for (const k of writtenEvidence) {
139
+ if (!isBridgeGovKey(k)) throw G(`${label} wrote non-canonical governance key ${k}`);
140
+ const afterRow = input.after.get("evidence")?.get(k);
141
+ const val = govBodyOf(afterRow);
142
+ if (!afterRow || !val) throw G(`${label} must write typed JSON evidence at ${k}`);
143
+ if (k === expectedDocKey) {
144
+ if (val.kind !== "bridge-gov-doc" || val.bridge !== bridgeRaw || typeof val.proposalId !== "string" || val.proposalId.toLowerCase() !== proposalId.toLowerCase()) throw G(`${label} doc ${k} does not match bridge ${bridgeRaw} and proposalId ${proposalId}`);
145
+ } else if (val.kind !== "bridge-gov-index" || val.bridge !== bridgeRaw) throw G(`${label} index ${k} does not match bridge ${bridgeRaw}`);
146
+ }
147
+ for (const table of [
148
+ "rollup",
149
+ "stake",
150
+ "token",
151
+ "tokenFactory",
152
+ "asset",
153
+ "factory",
154
+ "delegation",
155
+ "rollupBlock"
156
+ ]) if ((input.written(table)?.size || 0) > 0) throw G(`${label} must not write ${table} records`);
157
+ if (input.directBalanceWrites.length > 0 || (input.written("balance")?.size || 0) > 0) throw G(`${label} must not write the balance table directly`);
158
+ for (const accKey of input.written("account") ?? []) {
159
+ const nk = input.norm(accKey);
160
+ if (nk !== input.payer && !input.vaults.has(nk)) throw G(`${label} must not write non-gas account ${accKey}`);
161
+ }
162
+ const officialKey = input.officialToken;
163
+ const beforeAccounts = input.before.get("account") ?? /* @__PURE__ */ new Map();
164
+ const afterAccounts = input.after.get("account") ?? /* @__PURE__ */ new Map();
165
+ const actual = /* @__PURE__ */ new Map();
166
+ for (const [addr, afterAcc] of afterAccounts.entries()) {
167
+ const pre = input.tokenBalances(beforeAccounts.get(addr)?.tokens, `beforeAccount[${addr}].tokens`);
168
+ const post = input.tokenBalances(afterAcc.tokens, `afterAccount[${addr}].tokens`);
169
+ for (const tok of new Set([...Object.keys(pre), ...Object.keys(post)])) {
170
+ const d = (post[tok] || ZERO).sub(pre[tok] || ZERO);
171
+ if (d.isZero()) continue;
172
+ if (!actual.has(addr)) actual.set(addr, /* @__PURE__ */ new Map());
173
+ actual.get(addr)?.set(tok, d);
174
+ }
175
+ }
176
+ let gas = ZERO;
177
+ for (const vault of input.vaults) for (const [tok, d] of actual.get(vault) ?? []) {
178
+ if (tok !== officialKey || d.isNeg()) throw G(`${label} may only credit vault ${vault} with official-token gas`);
179
+ gas = gas.add(d);
180
+ }
181
+ for (const [addr, deltas] of actual.entries()) {
182
+ if (input.vaults.has(addr)) continue;
183
+ for (const [tok, d] of deltas.entries()) {
184
+ const want = addr === input.payer && tok === officialKey ? gas.neg() : ZERO;
185
+ if (!d.eq(want)) throw G(`${label} moved ${d.toString(10)} of ${tok} for ${addr}, expected ${want.toString(10)} (gas only)`);
186
+ }
187
+ }
188
+ }
72
189
  function assertBridgeReleaseProtected(input) {
73
190
  const { txType, itx, norm, createGateError } = input;
74
191
  const violation = (code, message) => createGateError(code, `Post-Execution Invariant Gate: ${message}`);
75
192
  const writtenEvidence = input.written("evidence") ?? /* @__PURE__ */ new Set();
193
+ const itxJson = txType === "update_rollup" ? readItxJsonValue(itx.data) : null;
194
+ const hasGovVoteField = !!itxJson && Object.prototype.hasOwnProperty.call(itxJson, "govProposalVote");
195
+ const preRollup = txType === "update_rollup" ? findPreRollupRow(input, itx.rollup) : null;
196
+ const isV2Bridge = !!preRollup && rollup.isBridgeV2(preRollup);
197
+ if (isV2Bridge && hasGovVoteField && Object.keys(itxJson).length !== 1) throw violation("BRIDGE_GOV_VOTE_ISOLATION_VIOLATION", "update_rollup (govProposalVote) must not combine govProposalVote with rollup patch fields");
198
+ const isV2GovVote = isV2Bridge && hasGovVoteField && Object.keys(itxJson).length === 1;
76
199
  for (const key of writtenEvidence) {
77
200
  const row = input.after.get("evidence")?.get(key) ?? input.before.get("evidence")?.get(key) ?? null;
78
201
  const prior = input.before.get("evidence")?.get(key) ?? null;
@@ -83,10 +206,16 @@ function assertBridgeReleaseProtected(input) {
83
206
  if (rowKind && prior) {
84
207
  if (!(priorKind === rowKind && !MEMBERSHIP_KINDS.has(rowKind)) && !isV1EvidenceRow(prior)) throw violation("BRIDGE_RECORD_FORBIDDEN", `a ${rowKind} record may not replace the existing evidence row ${key} (only a v1-planted row or a ${rowKind} index entry)`);
85
208
  }
209
+ const govKind = identifyGovRow(row) ?? identifyGovRow(prior);
210
+ if (!isV2GovVote && (inBridgeGovKeySpace(key) || govKind !== null)) throw violation("BRIDGE_GOV_EVIDENCE_FORBIDDEN", `governance evidence ${key} may only be written by a v2 bridge update_rollup(govProposalVote), not a ${txType || "unknown"} tx`);
86
211
  if (isReleaseForm(txType, itx)) continue;
87
212
  if (identifyBucketRow(row) || identifyBucketRow(prior) || /^rb:/i.test(String(key).trim())) throw violation("BRIDGE_RELEASE_BUCKET_FORBIDDEN", `release-window bucket ${key} may only be written by a deposit_token_v2 bridge release, not a ${txType || "unknown"} tx`);
88
213
  if (inBridgeReleaseKeySpace(key)) throw violation("BRIDGE_RELEASE_TOMBSTONE_FORBIDDEN", `release tombstone ${key} may only be written by a deposit_token_v2 bridge release, not a ${txType || "unknown"} tx`);
89
214
  }
215
+ if (isV2GovVote) {
216
+ assertBridgeGovVoteIsolated(input, itxJson.govProposalVote, writtenEvidence, violation);
217
+ return;
218
+ }
90
219
  if (!isReleaseForm(txType, itx)) return;
91
220
  const R4 = (message) => violation("BRIDGE_RELEASE_ACCOUNTING_VIOLATION", message);
92
221
  const fields = releaseFieldsOf(itx);
@@ -195,4 +324,4 @@ function assertBridgeReleaseProtected(input) {
195
324
  }
196
325
 
197
326
  //#endregion
198
- export { assertBridgeReleaseProtected, bridgeRecordKind };
327
+ export { assertBridgeReleaseProtected, bridgeRecordKind, inBridgeGovKeySpace };
@@ -26,7 +26,8 @@ declare function estimateBase64WireBytes(trimmed: string): number;
26
26
  */
27
27
  declare function assertWireByteCeiling(txBase64: string, config?: IChainConfig, messagePrefix?: string): string;
28
28
  /**
29
- * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
29
+ * Fast O(1) wire-size and canonical base64/base64url validation before allocating buffers or decoding.
30
+ * Accepts ONLY canonical `{stdPadded, stdUnpadded, urlPadded, urlUnpadded}` encodings (#1493).
30
31
  */
31
32
  declare function assertRawWireEnvelope(txBase64: string, config?: IChainConfig): void;
32
33
  /**
@@ -63,6 +64,12 @@ interface IPreFlightVerifiedSnapshot {
63
64
  txExtraSerialized: string;
64
65
  gasStakeHeadersSerialized: string;
65
66
  coSignatureSerialized: string;
67
+ gasPassSerialized: string;
68
+ verifiedCoSignature?: {
69
+ pk: string;
70
+ signature: string;
71
+ extra?: string;
72
+ };
66
73
  tx: IDecodedTransaction;
67
74
  txEncoding: 'cbor' | 'protobuf';
68
75
  txSize: number;
@@ -70,6 +77,7 @@ interface IPreFlightVerifiedSnapshot {
70
77
  extraSizeCounted: boolean;
71
78
  txHash: string;
72
79
  unsignedTxHash: string;
80
+ txTime?: string;
73
81
  txBaseGas: boolean;
74
82
  itx: Record<string, unknown>;
75
83
  txType: string;
@@ -163,14 +163,31 @@ function assertWireByteCeiling(txBase64, config, messagePrefix = "Raw transactio
163
163
  if (estimatedWireBytes > maxConfiguredTxBytes) throw new CustomError("INVALID_TX_SIZE", `${messagePrefix} (${estimatedWireBytes} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
164
164
  return trimmed;
165
165
  }
166
+ function decodeBase64Sextet(code) {
167
+ if (code >= 65 && code <= 90) return code - 65;
168
+ if (code >= 97 && code <= 122) return code - 71;
169
+ if (code >= 48 && code <= 57) return code + 4;
170
+ if (code === 43 || code === 45) return 62;
171
+ if (code === 47 || code === 95) return 63;
172
+ return -1;
173
+ }
166
174
  /**
167
- * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
175
+ * Fast O(1) wire-size and canonical base64/base64url validation before allocating buffers or decoding.
176
+ * Accepts ONLY canonical `{stdPadded, stdUnpadded, urlPadded, urlUnpadded}` encodings (#1493).
168
177
  */
169
178
  function assertRawWireEnvelope(txBase64, config) {
170
179
  if (!txBase64 || typeof txBase64 !== "string" || txBase64.length < 20) throw new CustomError("INVALID_TX", "Transaction data is empty or too short");
171
180
  const trimmed = assertWireByteCeiling(txBase64, config, "Pre-Flight WAF: raw transaction wire size");
172
181
  if (trimmed.length < 20) throw new CustomError("INVALID_TX", "Transaction data is empty or too short");
173
182
  if (txBase64 !== trimmed || !BASE64_WIRE_PATTERN.test(trimmed)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains invalid non-base64 characters");
183
+ const padCount = trimmed.endsWith("==") ? 2 : trimmed.endsWith("=") ? 1 : 0;
184
+ const dataLen = trimmed.length - padCount;
185
+ const rem = dataLen & 3;
186
+ if (rem === 1 || padCount > 0 && (dataLen + padCount & 3) !== 0) throw new CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data is not canonical base64 or base64url");
187
+ if (rem === 2 || rem === 3) {
188
+ const lastSextet = decodeBase64Sextet(trimmed.charCodeAt(dataLen - 1));
189
+ if (lastSextet < 0 || (lastSextet & (rem === 2 ? 15 : 3)) !== 0) throw new CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains non-canonical trailing base64 pad bits");
190
+ }
174
191
  }
175
192
  /**
176
193
  * Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
@@ -591,6 +608,7 @@ function tryApplyPreFlightVerifiedSnapshot(context) {
591
608
  context._preFlightWafScanned = false;
592
609
  context._preFlightVerified = false;
593
610
  context._preFlightSnapshotApplied = false;
611
+ context._verifiedCoSignature = void 0;
594
612
  const snap = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
595
613
  if (!snap || typeof context.txBase64 !== "string" || snap.txBase64 !== context.txBase64) return false;
596
614
  const config = context.config;
@@ -608,10 +626,10 @@ function tryApplyPreFlightVerifiedSnapshot(context) {
608
626
  txResourceKey(snap.txType, snap.itx)
609
627
  ], defaultSizeLimit) : defaultSizeLimit) || snap.maxExtraSize !== get(config, "transaction.maxExtraSize") || snap.maxMultisig !== get(config, "transaction.maxMultisig") || snap.maxListSize !== get(config, "transaction.maxListSize") || snap.maxAssetSize !== get(config, "transaction.maxAssetSize") || snap.isSupportedTx !== Boolean(Array.isArray(supportedTxs) && supportedTxs.includes(snap.txType)) || snap.isMultiSignV2Tx !== Boolean(Array.isArray(multiSignV2Txs) && multiSignV2Txs.includes(snap.txType))) return false;
610
628
  const extra = context.extra;
611
- if (snap.txExtraSerialized !== serializeExtraField(extra?.txExtra) || snap.gasStakeHeadersSerialized !== serializeExtraField(extra?.gasStakeHeaders) || snap.coSignatureSerialized !== serializeExtraField(extra?.coSignature)) return false;
629
+ if (snap.txExtraSerialized !== serializeExtraField(extra?.txExtra) || snap.gasStakeHeadersSerialized !== serializeExtraField(extra?.gasStakeHeaders) || snap.coSignatureSerialized !== serializeExtraField(extra?.coSignature) || snap.gasPassSerialized !== serializeExtraField(extra?.gasPass)) return false;
612
630
  const pinned = extra?.txTime;
613
631
  const pinnedMs = pinned === void 0 || pinned === null || pinned === "" ? NaN : new Date(pinned).getTime();
614
- const resolvedTxTime = Number.isFinite(pinnedMs) ? new Date(pinnedMs).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
632
+ const resolvedTxTime = Number.isFinite(pinnedMs) ? new Date(pinnedMs).toISOString() : snap.txTime || (/* @__PURE__ */ new Date()).toISOString();
615
633
  Object.defineProperty(context, "tx", {
616
634
  value: cloneDeep(snap.tx),
617
635
  enumerable: true,
@@ -669,6 +687,7 @@ function tryApplyPreFlightVerifiedSnapshot(context) {
669
687
  context._baseTxSize = snap.baseTxSize;
670
688
  context._extraSizeCounted = snap.extraSizeCounted;
671
689
  context._rawTxItxBeforeNormalize = snap.rawTxItxBeforeNormalize;
690
+ context._verifiedCoSignature = snap.verifiedCoSignature ? { ...snap.verifiedCoSignature } : void 0;
672
691
  context._preFlightWafScanned = true;
673
692
  context._preFlightVerified = true;
674
693
  return true;
@@ -737,9 +756,11 @@ async function inspectTransactionPreFlight(context) {
737
756
  const baseTxSize = preFlightCtx._baseTxSize ?? preFlightCtx.txSize;
738
757
  const extraSizeCounted = Boolean(preFlightCtx._extraSizeCounted);
739
758
  const rawTxItxBeforeNormalize = preFlightCtx._rawTxItxBeforeNormalize;
759
+ const verifiedCoSignature = preFlightCtx._verifiedCoSignature;
740
760
  context._baseTxSize = baseTxSize;
741
761
  context._extraSizeCounted = extraSizeCounted;
742
762
  context._rawTxItxBeforeNormalize = rawTxItxBeforeNormalize;
763
+ context._verifiedCoSignature = verifiedCoSignature ? { ...verifiedCoSignature } : void 0;
743
764
  context._preFlightWafScanned = true;
744
765
  context._preFlightVerified = true;
745
766
  if (typeof context.txBase64 === "string" && preFlightCtx.tx && preFlightCtx.itx && preFlightCtx.txType) {
@@ -772,6 +793,8 @@ async function inspectTransactionPreFlight(context) {
772
793
  txExtraSerialized: serializeExtraField(extra?.txExtra),
773
794
  gasStakeHeadersSerialized: serializeExtraField(extra?.gasStakeHeaders),
774
795
  coSignatureSerialized: serializeExtraField(extra?.coSignature),
796
+ gasPassSerialized: serializeExtraField(extra?.gasPass),
797
+ verifiedCoSignature: verifiedCoSignature ? { ...verifiedCoSignature } : void 0,
775
798
  tx: cloneDeep(preFlightCtx.tx),
776
799
  txEncoding: preFlightCtx.txEncoding,
777
800
  txSize: preFlightCtx.txSize,
@@ -779,6 +802,7 @@ async function inspectTransactionPreFlight(context) {
779
802
  extraSizeCounted,
780
803
  txHash: preFlightCtx.txHash,
781
804
  unsignedTxHash: preFlightCtx.unsignedTxHash,
805
+ txTime: typeof preFlightCtx.txTime === "string" && preFlightCtx.txTime ? preFlightCtx.txTime : void 0,
782
806
  txBaseGas: Boolean(preFlightCtx.txBaseGas),
783
807
  itx: cloneDeep(preFlightCtx.itx),
784
808
  txType: preFlightCtx.txType,
@@ -368,21 +368,28 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
368
368
  }
369
369
  for (const payload of candidatePayloads) {
370
370
  try {
371
- if (await wallet.verify(payload, rawCoSig.signature, false, coSigExtra)) return true;
371
+ if (await wallet.verify(payload, rawCoSig.signature, false, coSigExtra)) {
372
+ if (parsedFromDirect) context._verifiedCoSignature = parsedFromDirect;
373
+ return true;
374
+ }
372
375
  } catch {}
373
376
  try {
374
- if (await wallet.verify(payload, rawCoSig.signature, true, coSigExtra)) return true;
377
+ if (await wallet.verify(payload, rawCoSig.signature, true, coSigExtra)) {
378
+ if (parsedFromDirect) context._verifiedCoSignature = parsedFromDirect;
379
+ return true;
380
+ }
375
381
  } catch {}
376
382
  }
377
383
  return false;
378
384
  };
379
385
  const getTxTimestampSeconds = () => {
380
- const txTime = context.txTime;
386
+ const ctxWithTime = context;
387
+ const txTime = ctxWithTime.txTime !== void 0 && ctxWithTime.txTime !== null && ctxWithTime.txTime !== "" ? ctxWithTime.txTime : ctxWithTime.extra?.txTime;
381
388
  if (txTime !== void 0 && txTime !== null && txTime !== "") if (typeof txTime === "number") {
382
- if (Number.isFinite(txTime) && txTime > 0) return txTime > 1e11 ? Math.floor(txTime / 1e3) : Math.floor(txTime);
389
+ if (Number.isFinite(txTime) && txTime >= 0) return txTime > 1e11 ? Math.floor(txTime / 1e3) : Math.floor(txTime);
383
390
  } else {
384
391
  const parsedMs = new Date(txTime).getTime();
385
- if (Number.isFinite(parsedMs) && parsedMs > 0) return Math.floor(parsedMs / 1e3);
392
+ if (Number.isFinite(parsedMs) && parsedMs >= 0) return Math.floor(parsedMs / 1e3);
386
393
  }
387
394
  return Math.floor(Date.now() / 1e3);
388
395
  };
@@ -152,6 +152,10 @@ async function VerifySignature(context, next) {
152
152
  const ctxTxHash = context.txHash;
153
153
  const ctxUnsignedTxHash = context.unsignedTxHash || toTxHash(txBytes);
154
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"));
155
+ if (parsedFromDirect && context.extra && typeof context.extra === "object") {
156
+ context.extra.coSignature = parsedFromDirect;
157
+ context._verifiedCoSignature = parsedFromDirect;
158
+ }
155
159
  }
156
160
  }
157
161
  const extra = isPasskey ? rawTxExtra : isWalletEnvelope ? rawTxExtra : "";
@@ -6,32 +6,62 @@ import { toTypeUrl } from "@ocap/message";
6
6
  //#region src/pipes/verify-tx-size.ts
7
7
  const DEFAULT_MAX_EXTRA_SIZE = 8 * 1024;
8
8
  const MAX_GAS_STAKE_HEADERS_SIZE = 8 * 1024;
9
+ const MAX_GAS_STAKE_TOKEN_BYTES = 4 * 1024;
10
+ const MAX_GAS_STAKE_PK_BYTES = 512;
9
11
  const MAX_CO_SIGNATURE_SIZE = 4 * 1024;
12
+ const MAX_GAS_PASS_SIZE = 2 * 1024;
13
+ const ALLOWED_GAS_STAKE_HEADER_KEYS = new Set(["token", "pk"]);
10
14
  const getFieldByteSize = (val) => {
11
15
  if (val === void 0 || val === null || val === "") return 0;
12
- return Buffer.byteLength(typeof val === "string" ? val : JSON.stringify(val), "utf8");
16
+ if (typeof val === "string") return Buffer.byteLength(val, "utf8");
17
+ try {
18
+ const serialized = JSON.stringify(val);
19
+ if (typeof serialized !== "string") return Number.POSITIVE_INFINITY;
20
+ return Buffer.byteLength(serialized, "utf8");
21
+ } catch {
22
+ return Number.POSITIVE_INFINITY;
23
+ }
24
+ };
25
+ const isInvalidGasStakeHeadersEnvelope = (raw) => {
26
+ if (raw === void 0 || raw === null || raw === "") return false;
27
+ if (typeof raw !== "object" || Array.isArray(raw)) return true;
28
+ const proto = Object.getPrototypeOf(raw);
29
+ if (proto !== Object.prototype && proto !== null) return true;
30
+ const obj = raw;
31
+ for (const key of Object.keys(obj)) if (!ALLOWED_GAS_STAKE_HEADER_KEYS.has(key)) return true;
32
+ if (obj.token !== void 0 && typeof obj.token !== "string") return true;
33
+ if (obj.pk !== void 0 && typeof obj.pk !== "string") return true;
34
+ const tokenBytes = typeof obj.token === "string" ? Buffer.byteLength(obj.token, "utf8") : 0;
35
+ const pkBytes = typeof obj.pk === "string" ? Buffer.byteLength(obj.pk, "utf8") : 0;
36
+ return tokenBytes > MAX_GAS_STAKE_TOKEN_BYTES || pkBytes > MAX_GAS_STAKE_PK_BYTES;
13
37
  };
14
38
  const getExtraByteSizes = (extra) => {
15
39
  if (!extra || typeof extra !== "object") return {
16
40
  txExtraBytes: 0,
17
41
  gasStakeHeadersBytes: 0,
18
42
  coSignatureBytes: 0,
19
- totalExtraBytes: 0
43
+ gasPassBytes: 0,
44
+ totalExtraBytes: 0,
45
+ invalidGasHeaders: false
20
46
  };
21
- const { txExtra, gasStakeHeaders, coSignature } = extra;
47
+ const { txExtra, gasStakeHeaders, coSignature, gasPass } = extra;
48
+ const invalidGasHeaders = isInvalidGasStakeHeadersEnvelope(gasStakeHeaders);
22
49
  const txExtraBytes = getFieldByteSize(txExtra);
23
- const gasStakeHeadersBytes = getFieldByteSize(gasStakeHeaders);
50
+ const gasStakeHeadersBytes = invalidGasHeaders ? 0 : getFieldByteSize(gasStakeHeaders);
24
51
  const coSignatureBytes = getFieldByteSize(coSignature);
52
+ const gasPassBytes = getFieldByteSize(gasPass);
25
53
  return {
26
54
  txExtraBytes,
27
55
  gasStakeHeadersBytes,
28
56
  coSignatureBytes,
29
- totalExtraBytes: txExtraBytes + gasStakeHeadersBytes + coSignatureBytes
57
+ gasPassBytes,
58
+ totalExtraBytes: txExtraBytes + gasStakeHeadersBytes + coSignatureBytes + gasPassBytes,
59
+ invalidGasHeaders
30
60
  };
31
61
  };
32
62
  function VerifyTxSize(context, next) {
33
63
  const { txSize, txType, tx, config } = context;
34
- const { txExtraBytes, gasStakeHeadersBytes, coSignatureBytes, totalExtraBytes } = getExtraByteSizes(context.extra);
64
+ const { txExtraBytes, gasStakeHeadersBytes, coSignatureBytes, gasPassBytes, totalExtraBytes, invalidGasHeaders } = getExtraByteSizes(context.extra);
35
65
  const alreadyCounted = Boolean(context._extraSizeCounted);
36
66
  const baseTxSize = alreadyCounted ? Math.max(0, (txSize || 0) - txExtraBytes) : txSize || 0;
37
67
  context._baseTxSize = baseTxSize;
@@ -45,7 +75,7 @@ function VerifyTxSize(context, next) {
45
75
  ], defaultSizeLimit);
46
76
  if (baseTxSize > sizeLimit) return next(new CustomError("INVALID_TX_SIZE", `Transaction size too large for ${txType}: expect ${sizeLimit}, got ${baseTxSize}`));
47
77
  const maxExtraSize = get(config, "transaction.maxExtraSize", DEFAULT_MAX_EXTRA_SIZE);
48
- if (totalExtraBytes > maxExtraSize || gasStakeHeadersBytes > MAX_GAS_STAKE_HEADERS_SIZE || coSignatureBytes > MAX_CO_SIGNATURE_SIZE) {
78
+ if (invalidGasHeaders || totalExtraBytes > maxExtraSize || gasStakeHeadersBytes > MAX_GAS_STAKE_HEADERS_SIZE || coSignatureBytes > MAX_CO_SIGNATURE_SIZE || gasPassBytes > MAX_GAS_PASS_SIZE) {
49
79
  const extraErr = new CustomError("INVALID_TX_SIZE", `Transaction extra size too large for ${txType}: expect <= ${maxExtraSize}, got ${totalExtraBytes}`);
50
80
  extraErr._unauthenticatedExtraFailure = true;
51
81
  return next(extraErr);