@ocap/tx-pipeline 1.31.9 → 1.32.0

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.
@@ -43,6 +43,11 @@ const BRIDGE_RELEASE_KINDS = [
43
43
  */
44
44
  const BRIDGE_RELEASE_V2_RESOURCE_KEY = "fg:t:deposit_token_v2_bridge";
45
45
  /**
46
+ * maxTxSize / maxGasOps key of a v2 bridge `update_rollup` (typed patch, `evmGovernanceSync`, or `govProposalVote`, #1880).
47
+ * Keeps legacy v1 `fg:t:update_rollup` (`1691` bytes) untouched and survives per-node overrides of v1 `maxTxSize` keys.
48
+ */
49
+ const BRIDGE_UPDATE_V2_RESOURCE_KEY = "fg:t:update_rollup_bridge";
50
+ /**
46
51
  * Tx types that may DEBIT a reserve (R1), besides a bridge release (`isNamedBridgeRelease`, which may only debit the
47
52
  * reserve of its own bridge, or of the `migratedTo` chain of a migrated bridge): `migrate_rollup` moves a whole reserve
48
53
  * to its successor's.
@@ -84,11 +89,29 @@ function isNamedBridgeRelease(txType, itx) {
84
89
  return isBridgeRelease(txType, itx) && typeof rollupField === "string" && rollupField.length > 0;
85
90
  }
86
91
  /**
92
+ * Whether `txType` / `itx` is a v2 bridge `update_rollup` (zero v1 rollup fields and non-empty `itx.data`).
93
+ */
94
+ function isBridgeUpdateV2(txType, itx) {
95
+ if (stripTxTypePrefix(txType) !== "update_rollup") return false;
96
+ if (!itx || typeof itx !== "object") return false;
97
+ const rec = itx;
98
+ if (!rec.data) return false;
99
+ try {
100
+ _ocap_state.rollup.assertV1FieldsUnused(rec, "INVALID_ROLLUP_UPDATE");
101
+ return true;
102
+ } catch {
103
+ return false;
104
+ }
105
+ }
106
+ /**
87
107
  * The `transaction.maxTxSize` / `maxGasOps` key a tx is measured by: `fg:t:deposit_token_v2_bridge` for a bridge release,
88
- * the tx type itself otherwise (so every other tx, and every v1 deposit, keeps its key and limit).
108
+ * `fg:t:update_rollup_bridge` for a v2 bridge `update_rollup`, and the tx type itself otherwise (so every other tx,
109
+ * and every v1 deposit/rollup update, keeps its key and limit).
89
110
  */
90
111
  function txResourceKey(txType, itx) {
91
- return isBridgeRelease(txType, itx) ? BRIDGE_RELEASE_V2_RESOURCE_KEY : txType;
112
+ if (isBridgeRelease(txType, itx)) return BRIDGE_RELEASE_V2_RESOURCE_KEY;
113
+ if (isBridgeUpdateV2(txType, itx)) return BRIDGE_UPDATE_V2_RESOURCE_KEY;
114
+ return txType;
92
115
  }
93
116
  /** Strip a `did:abt:` prefix and whitespace: the form used in the evidence index and in rows. */
94
117
  const bareAddress = (address) => String(address ?? "").trim().replace(/^did:abt:/, "");
@@ -132,12 +155,20 @@ function describeBridge(row, txSec) {
132
155
  const final = _ocap_state.rollup.isBridgeFinalAt(body, txSec);
133
156
  const paused = _ocap_state.rollup.isBridgePausedAt(row, txSec);
134
157
  const migrated = typeof body.migratedTo === "string" && body.migratedTo.length > 0;
158
+ const ethGateway = _ocap_state.rollup.bareEthAddress(body.gateway);
159
+ const ethToken = _ocap_state.rollup.bareEthAddress(row.contractAddress);
160
+ const ethVault = _ocap_state.rollup.bareEthAddress(row.vaultAddress);
161
+ const ethVaultHistory = Array.isArray(row.vaultHistory) ? row.vaultHistory.map((v) => _ocap_state.rollup.bareEthAddress(v)).filter(Boolean) : [];
135
162
  return {
136
163
  address: row.address,
137
164
  reserve: (0, _arcblock_did_util.toBridgeReserveAddress)(row.address),
138
165
  state: row,
139
166
  body,
140
167
  token: String(row.tokenAddress || ""),
168
+ ethGateway,
169
+ ethToken,
170
+ ethVault,
171
+ ethVaultHistory,
141
172
  txSec,
142
173
  paused,
143
174
  closing,
@@ -297,11 +328,13 @@ exports.BRIDGE_RELEASE_V2_RESOURCE_KEY = BRIDGE_RELEASE_V2_RESOURCE_KEY;
297
328
  exports.BRIDGE_RELEASE_V2_TX_TYPE = BRIDGE_RELEASE_V2_TX_TYPE;
298
329
  exports.BRIDGE_RESERVE_CREDIT_TX_TYPES = BRIDGE_RESERVE_CREDIT_TX_TYPES;
299
330
  exports.BRIDGE_RESERVE_DEBIT_TX_TYPES = BRIDGE_RESERVE_DEBIT_TX_TYPES;
331
+ exports.BRIDGE_UPDATE_V2_RESOURCE_KEY = BRIDGE_UPDATE_V2_RESOURCE_KEY;
300
332
  exports.BRIDGE_WITHDRAW_V2_TX_TYPE = BRIDGE_WITHDRAW_V2_TX_TYPE;
301
333
  exports.bareAddress = bareAddress;
302
334
  exports.describeBridge = describeBridge;
303
335
  exports.isBridgeRelease = isBridgeRelease;
304
336
  exports.isBridgeReserveRole = isBridgeReserveRole;
337
+ exports.isBridgeUpdateV2 = isBridgeUpdateV2;
305
338
  exports.isNamedBridgeRelease = isNamedBridgeRelease;
306
339
  exports.prepareBridgeReserveGate = prepareBridgeReserveGate;
307
340
  exports.reserveIndexKey = reserveIndexKey;
@@ -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 };
@@ -78,6 +78,8 @@ function checkBridgeWithdrawV2(context, bridge) {
78
78
  if (typeof token.value !== "string" || !DECIMAL.test(token.value)) return fail(BRIDGE_WITHDRAW_AMOUNT, "Bridge withdraw amount must be a decimal string");
79
79
  const parsed = (0, _ocap_mcrypto.parseStrictEthAddress)(itx.to);
80
80
  if (!parsed.ok) return fail(BRIDGE_WITHDRAW_RECIPIENT, `Bridge withdraw recipient is not a valid Ethereum address (${parsed.reason})`);
81
+ const recipient = parsed.lowercase;
82
+ 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");
81
83
  if (itx.proposer !== void 0 && itx.proposer !== null && itx.proposer !== "") return fail(BRIDGE_WITHDRAW_FEE, "Bridge withdraw has no proposer");
82
84
  if (!isNoFee(itx.maxFee) || !isNoFee(itx.actualFee)) return fail(BRIDGE_WITHDRAW_FEE, "Bridge withdraw carries no maxFee or actualFee");
83
85
  if (!isEmptyData(itx.data)) return fail(BRIDGE_WITHDRAW_RECIPIENT, "Bridge withdraw carries no itx.data: the recipient is itx.to");
package/lib/index.cjs CHANGED
@@ -17,6 +17,7 @@ const require_pipes_decode_tx = require('./pipes/decode-tx.cjs');
17
17
  const require_pipes_extract_receiver = require('./pipes/extract-receiver.cjs');
18
18
  const require_pipes_extract_signer = require('./pipes/extract-signer.cjs');
19
19
  const require_pipes_extract_state = require('./pipes/extract-state.cjs');
20
+ require('./pipes/bridge-release-gate.cjs');
20
21
  const require_pipes_post_execution_invariant_gate = require('./pipes/post-execution-invariant-gate.cjs');
21
22
  const require_pipes_verify_state_diff = require('./pipes/verify-state-diff.cjs');
22
23
  const require_pipes_take_state_snapshot = require('./pipes/take-state-snapshot.cjs');
@@ -35,6 +36,7 @@ const require_pipes_verify_transferrable = require('./pipes/verify-transferrable
35
36
  const require_pipes_verify_tx_input = require('./pipes/verify-tx-input.cjs');
36
37
  const require_pipes_verify_updater = require('./pipes/verify-updater.cjs');
37
38
  let _ocap_state = require("@ocap/state");
39
+ let _ocap_mcrypto = require("@ocap/mcrypto");
38
40
 
39
41
  //#region src/index.ts
40
42
  const pipes = {
@@ -138,6 +140,7 @@ exports.formatBucketData = require_bridge_release_keys.formatBucketData;
138
140
  exports.getReleaseBucketKey = require_bridge_release_keys.getReleaseBucketKey;
139
141
  exports.getReleaseTombstoneKey = require_bridge_release_keys.getReleaseTombstoneKey;
140
142
  exports.groupStatesByAddress = require_pipes_verify_state_diff.groupStatesByAddress;
143
+ exports.inBridgeGovKeySpace = _ocap_mcrypto.inBridgeGovKeySpace;
141
144
  exports.inspectPostExecutionInvariants = require_pipes_post_execution_invariant_gate.inspectPostExecutionInvariants;
142
145
  exports.inspectTransactionPreFlight = require_pipes_pre_flight_waf.inspectTransactionPreFlight;
143
146
  exports.installStateWriteInterceptor = require_pipes_post_execution_invariant_gate.installStateWriteInterceptor;
package/lib/index.d.cts CHANGED
@@ -32,6 +32,7 @@ import VerifyTx from "./pipes/verify-tx.cjs";
32
32
  import CreateVerifyTxInputPipe from "./pipes/verify-tx-input.cjs";
33
33
  import VerifyTxSize from "./pipes/verify-tx-size.cjs";
34
34
  import CreateVerifyUpdaterPipe from "./pipes/verify-updater.cjs";
35
+ import { inBridgeGovKeySpace } from "./pipes/bridge-release-gate.cjs";
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 };
@@ -3,6 +3,8 @@ const require_bridge_release_keys = require('../bridge-release-keys.cjs');
3
3
  const require_bridge_reserves = require('../bridge-reserves.cjs');
4
4
  let _ocap_mcrypto = require("@ocap/mcrypto");
5
5
  let _ocap_util = require("@ocap/util");
6
+ let _ocap_state = require("@ocap/state");
7
+ let _ocap_message = require("@ocap/message");
6
8
  let lodash_isEqual = require("lodash/isEqual");
7
9
  lodash_isEqual = require_rolldown_runtime.__toESM(lodash_isEqual);
8
10
 
@@ -71,10 +73,131 @@ const bodyOf = (row) => {
71
73
  const v = (row?.data)?.value;
72
74
  return v && typeof v === "object" ? v : null;
73
75
  };
76
+ const GOV_RECORD_KINDS = new Set(["bridge-gov-index", "bridge-gov-doc"]);
77
+ const govBodyOf = (row) => {
78
+ const raw = row?.data;
79
+ if (typeof raw === "string") try {
80
+ const parsed = JSON.parse(raw);
81
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
82
+ } catch {
83
+ return null;
84
+ }
85
+ const d = raw;
86
+ if (d && typeof d === "object" && d.type === "json" && d.value && typeof d.value === "object" && !Array.isArray(d.value)) return d.value;
87
+ return null;
88
+ };
89
+ const identifyGovRow = (row) => {
90
+ const kind = govBodyOf(row)?.kind;
91
+ return typeof kind === "string" && GOV_RECORD_KINDS.has(kind) ? kind : null;
92
+ };
93
+ const readItxJsonValue = (rawData) => {
94
+ if (!rawData || typeof rawData !== "object") return null;
95
+ const r = rawData;
96
+ if (r.type === "json" && r.value && typeof r.value === "object" && !Array.isArray(r.value)) return r.value;
97
+ try {
98
+ const decoded = (0, _ocap_message.decodeAny)(rawData);
99
+ if (decoded?.type === "json" && decoded.value && typeof decoded.value === "object" && !Array.isArray(decoded.value)) return decoded.value;
100
+ } catch {
101
+ return null;
102
+ }
103
+ return null;
104
+ };
105
+ const findPreRollupRow = (input, bridge) => {
106
+ if (typeof bridge !== "string" || !bridge) return null;
107
+ const target = require_bridge_reserves.bareAddress(bridge);
108
+ if (!target) return null;
109
+ return [...input.before.get("rollup")?.entries() ?? []].find(([k]) => require_bridge_reserves.bareAddress(k) === target)?.[1] ?? null;
110
+ };
111
+ function assertBridgeGovVoteIsolated(input, govVoteRaw, writtenEvidence, violation) {
112
+ const label = "update_rollup (govProposalVote)";
113
+ const G = (msg) => violation("BRIDGE_GOV_VOTE_ISOLATION_VIOLATION", msg);
114
+ const bridgeRaw = input.itx.rollup;
115
+ if (typeof bridgeRaw !== "string" || !bridgeRaw || bridgeRaw !== require_bridge_reserves.bareAddress(bridgeRaw)) throw G(`${label} must name a bare v2 bridge DID in itx.rollup`);
116
+ if (!govVoteRaw || typeof govVoteRaw !== "object" || Array.isArray(govVoteRaw)) throw G(`${label} payload must be a plain object`);
117
+ const govVote = govVoteRaw;
118
+ let proposalId = "";
119
+ try {
120
+ if (govVote.proposal && typeof govVote.proposal === "object" && !Array.isArray(govVote.proposal)) {
121
+ const p = govVote.proposal;
122
+ if (p.plane === "ethereum") proposalId = (0, _ocap_mcrypto.computeEvmProposalHash)((0, _ocap_mcrypto.coerceEvmProposal)(p));
123
+ else if (p.plane === "ocap") proposalId = (0, _ocap_mcrypto.computeOcapProposalId)((0, _ocap_mcrypto.coerceOcapProposal)(p));
124
+ else throw new Error("unknown proposal plane");
125
+ if (govVote.proposalId !== void 0 && (typeof govVote.proposalId !== "string" || govVote.proposalId.toLowerCase() !== proposalId.toLowerCase())) throw new Error("proposalId mismatch");
126
+ } else if (typeof govVote.proposalId === "string" && /^0x[0-9a-f]{64}$/i.test(govVote.proposalId)) proposalId = govVote.proposalId.toLowerCase();
127
+ else throw new Error("missing proposal");
128
+ } catch (err) {
129
+ throw G(`${label} carries an invalid proposal or proposalId: ${err.message}`);
130
+ }
131
+ let expectedIndexKey = "";
132
+ let expectedDocKey = "";
133
+ try {
134
+ expectedIndexKey = (0, _ocap_mcrypto.bridgeGovIndexKey)(bridgeRaw);
135
+ expectedDocKey = (0, _ocap_mcrypto.bridgeGovDocKey)(bridgeRaw, proposalId);
136
+ } catch (err) {
137
+ throw G(`${label} cannot derive governance evidence keys: ${err.message}`);
138
+ }
139
+ if (writtenEvidence.size === 0 || !writtenEvidence.has(expectedDocKey) || [...writtenEvidence].some((k) => k !== expectedIndexKey && k !== expectedDocKey)) throw G(`${label} may write only ${expectedIndexKey} and ${expectedDocKey}`);
140
+ for (const k of writtenEvidence) {
141
+ if (!(0, _ocap_mcrypto.isBridgeGovKey)(k)) throw G(`${label} wrote non-canonical governance key ${k}`);
142
+ const afterRow = input.after.get("evidence")?.get(k);
143
+ const val = govBodyOf(afterRow);
144
+ if (!afterRow || !val) throw G(`${label} must write typed JSON evidence at ${k}`);
145
+ if (k === expectedDocKey) {
146
+ 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}`);
147
+ } else if (val.kind !== "bridge-gov-index" || val.bridge !== bridgeRaw) throw G(`${label} index ${k} does not match bridge ${bridgeRaw}`);
148
+ }
149
+ for (const table of [
150
+ "rollup",
151
+ "stake",
152
+ "token",
153
+ "tokenFactory",
154
+ "asset",
155
+ "factory",
156
+ "delegation",
157
+ "rollupBlock"
158
+ ]) if ((input.written(table)?.size || 0) > 0) throw G(`${label} must not write ${table} records`);
159
+ if (input.directBalanceWrites.length > 0 || (input.written("balance")?.size || 0) > 0) throw G(`${label} must not write the balance table directly`);
160
+ for (const accKey of input.written("account") ?? []) {
161
+ const nk = input.norm(accKey);
162
+ if (nk !== input.payer && !input.vaults.has(nk)) throw G(`${label} must not write non-gas account ${accKey}`);
163
+ }
164
+ const officialKey = input.officialToken;
165
+ const beforeAccounts = input.before.get("account") ?? /* @__PURE__ */ new Map();
166
+ const afterAccounts = input.after.get("account") ?? /* @__PURE__ */ new Map();
167
+ const actual = /* @__PURE__ */ new Map();
168
+ for (const [addr, afterAcc] of afterAccounts.entries()) {
169
+ const pre = input.tokenBalances(beforeAccounts.get(addr)?.tokens, `beforeAccount[${addr}].tokens`);
170
+ const post = input.tokenBalances(afterAcc.tokens, `afterAccount[${addr}].tokens`);
171
+ for (const tok of new Set([...Object.keys(pre), ...Object.keys(post)])) {
172
+ const d = (post[tok] || ZERO).sub(pre[tok] || ZERO);
173
+ if (d.isZero()) continue;
174
+ if (!actual.has(addr)) actual.set(addr, /* @__PURE__ */ new Map());
175
+ actual.get(addr)?.set(tok, d);
176
+ }
177
+ }
178
+ let gas = ZERO;
179
+ for (const vault of input.vaults) for (const [tok, d] of actual.get(vault) ?? []) {
180
+ if (tok !== officialKey || d.isNeg()) throw G(`${label} may only credit vault ${vault} with official-token gas`);
181
+ gas = gas.add(d);
182
+ }
183
+ for (const [addr, deltas] of actual.entries()) {
184
+ if (input.vaults.has(addr)) continue;
185
+ for (const [tok, d] of deltas.entries()) {
186
+ const want = addr === input.payer && tok === officialKey ? gas.neg() : ZERO;
187
+ if (!d.eq(want)) throw G(`${label} moved ${d.toString(10)} of ${tok} for ${addr}, expected ${want.toString(10)} (gas only)`);
188
+ }
189
+ }
190
+ }
74
191
  function assertBridgeReleaseProtected(input) {
75
192
  const { txType, itx, norm, createGateError } = input;
76
193
  const violation = (code, message) => createGateError(code, `Post-Execution Invariant Gate: ${message}`);
77
194
  const writtenEvidence = input.written("evidence") ?? /* @__PURE__ */ new Set();
195
+ const itxJson = txType === "update_rollup" ? readItxJsonValue(itx.data) : null;
196
+ const hasGovVoteField = !!itxJson && Object.prototype.hasOwnProperty.call(itxJson, "govProposalVote");
197
+ const preRollup = txType === "update_rollup" ? findPreRollupRow(input, itx.rollup) : null;
198
+ const isV2Bridge = !!preRollup && _ocap_state.rollup.isBridgeV2(preRollup);
199
+ 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");
200
+ const isV2GovVote = isV2Bridge && hasGovVoteField && Object.keys(itxJson).length === 1;
78
201
  for (const key of writtenEvidence) {
79
202
  const row = input.after.get("evidence")?.get(key) ?? input.before.get("evidence")?.get(key) ?? null;
80
203
  const prior = input.before.get("evidence")?.get(key) ?? null;
@@ -85,10 +208,16 @@ function assertBridgeReleaseProtected(input) {
85
208
  if (rowKind && prior) {
86
209
  if (!(priorKind === rowKind && !MEMBERSHIP_KINDS.has(rowKind)) && !require_bridge_release_keys.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)`);
87
210
  }
211
+ const govKind = identifyGovRow(row) ?? identifyGovRow(prior);
212
+ if (!isV2GovVote && ((0, _ocap_mcrypto.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`);
88
213
  if (isReleaseForm(txType, itx)) continue;
89
214
  if (require_bridge_release_keys.identifyBucketRow(row) || require_bridge_release_keys.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`);
90
215
  if ((0, _ocap_mcrypto.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`);
91
216
  }
217
+ if (isV2GovVote) {
218
+ assertBridgeGovVoteIsolated(input, itxJson.govProposalVote, writtenEvidence, violation);
219
+ return;
220
+ }
92
221
  if (!isReleaseForm(txType, itx)) return;
93
222
  const R4 = (message) => violation("BRIDGE_RELEASE_ACCOUNTING_VIOLATION", message);
94
223
  const fields = releaseFieldsOf(itx);
@@ -198,4 +327,5 @@ function assertBridgeReleaseProtected(input) {
198
327
 
199
328
  //#endregion
200
329
  exports.assertBridgeReleaseProtected = assertBridgeReleaseProtected;
201
- exports.bridgeRecordKind = bridgeRecordKind;
330
+ exports.bridgeRecordKind = bridgeRecordKind;
331
+ exports.inBridgeGovKeySpace = _ocap_mcrypto.inBridgeGovKeySpace;
@@ -1,7 +1,9 @@
1
1
  import { BridgeReserveResolution } from "../bridge-reserves.cjs";
2
2
  import { BN } from "@ocap/util";
3
+ import { inBridgeGovKeySpace } from "@ocap/mcrypto";
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 };
@@ -167,14 +167,31 @@ function assertWireByteCeiling(txBase64, config, messagePrefix = "Raw transactio
167
167
  if (estimatedWireBytes > maxConfiguredTxBytes) throw new _ocap_util_lib_error.CustomError("INVALID_TX_SIZE", `${messagePrefix} (${estimatedWireBytes} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
168
168
  return trimmed;
169
169
  }
170
+ function decodeBase64Sextet(code) {
171
+ if (code >= 65 && code <= 90) return code - 65;
172
+ if (code >= 97 && code <= 122) return code - 71;
173
+ if (code >= 48 && code <= 57) return code + 4;
174
+ if (code === 43 || code === 45) return 62;
175
+ if (code === 47 || code === 95) return 63;
176
+ return -1;
177
+ }
170
178
  /**
171
- * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
179
+ * Fast O(1) wire-size and canonical base64/base64url validation before allocating buffers or decoding.
180
+ * Accepts ONLY canonical `{stdPadded, stdUnpadded, urlPadded, urlUnpadded}` encodings (#1493).
172
181
  */
173
182
  function assertRawWireEnvelope(txBase64, config) {
174
183
  if (!txBase64 || typeof txBase64 !== "string" || txBase64.length < 20) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Transaction data is empty or too short");
175
184
  const trimmed = assertWireByteCeiling(txBase64, config, "Pre-Flight WAF: raw transaction wire size");
176
185
  if (trimmed.length < 20) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Transaction data is empty or too short");
177
186
  if (txBase64 !== trimmed || !BASE64_WIRE_PATTERN.test(trimmed)) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains invalid non-base64 characters");
187
+ const padCount = trimmed.endsWith("==") ? 2 : trimmed.endsWith("=") ? 1 : 0;
188
+ const dataLen = trimmed.length - padCount;
189
+ const rem = dataLen & 3;
190
+ if (rem === 1 || padCount > 0 && (dataLen + padCount & 3) !== 0) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data is not canonical base64 or base64url");
191
+ if (rem === 2 || rem === 3) {
192
+ const lastSextet = decodeBase64Sextet(trimmed.charCodeAt(dataLen - 1));
193
+ if (lastSextet < 0 || (lastSextet & (rem === 2 ? 15 : 3)) !== 0) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains non-canonical trailing base64 pad bits");
194
+ }
178
195
  }
179
196
  /**
180
197
  * Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
@@ -595,6 +612,7 @@ function tryApplyPreFlightVerifiedSnapshot(context) {
595
612
  context._preFlightWafScanned = false;
596
613
  context._preFlightVerified = false;
597
614
  context._preFlightSnapshotApplied = false;
615
+ context._verifiedCoSignature = void 0;
598
616
  const snap = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
599
617
  if (!snap || typeof context.txBase64 !== "string" || snap.txBase64 !== context.txBase64) return false;
600
618
  const config = context.config;
@@ -612,10 +630,10 @@ function tryApplyPreFlightVerifiedSnapshot(context) {
612
630
  require_bridge_reserves.txResourceKey(snap.txType, snap.itx)
613
631
  ], defaultSizeLimit) : defaultSizeLimit) || snap.maxExtraSize !== (0, lodash_get.default)(config, "transaction.maxExtraSize") || snap.maxMultisig !== (0, lodash_get.default)(config, "transaction.maxMultisig") || snap.maxListSize !== (0, lodash_get.default)(config, "transaction.maxListSize") || snap.maxAssetSize !== (0, lodash_get.default)(config, "transaction.maxAssetSize") || snap.isSupportedTx !== Boolean(Array.isArray(supportedTxs) && supportedTxs.includes(snap.txType)) || snap.isMultiSignV2Tx !== Boolean(Array.isArray(multiSignV2Txs) && multiSignV2Txs.includes(snap.txType))) return false;
614
632
  const extra = context.extra;
615
- if (snap.txExtraSerialized !== serializeExtraField(extra?.txExtra) || snap.gasStakeHeadersSerialized !== serializeExtraField(extra?.gasStakeHeaders) || snap.coSignatureSerialized !== serializeExtraField(extra?.coSignature)) return false;
633
+ if (snap.txExtraSerialized !== serializeExtraField(extra?.txExtra) || snap.gasStakeHeadersSerialized !== serializeExtraField(extra?.gasStakeHeaders) || snap.coSignatureSerialized !== serializeExtraField(extra?.coSignature) || snap.gasPassSerialized !== serializeExtraField(extra?.gasPass)) return false;
616
634
  const pinned = extra?.txTime;
617
635
  const pinnedMs = pinned === void 0 || pinned === null || pinned === "" ? NaN : new Date(pinned).getTime();
618
- const resolvedTxTime = Number.isFinite(pinnedMs) ? new Date(pinnedMs).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
636
+ const resolvedTxTime = Number.isFinite(pinnedMs) ? new Date(pinnedMs).toISOString() : snap.txTime || (/* @__PURE__ */ new Date()).toISOString();
619
637
  Object.defineProperty(context, "tx", {
620
638
  value: (0, lodash_cloneDeep.default)(snap.tx),
621
639
  enumerable: true,
@@ -673,6 +691,7 @@ function tryApplyPreFlightVerifiedSnapshot(context) {
673
691
  context._baseTxSize = snap.baseTxSize;
674
692
  context._extraSizeCounted = snap.extraSizeCounted;
675
693
  context._rawTxItxBeforeNormalize = snap.rawTxItxBeforeNormalize;
694
+ context._verifiedCoSignature = snap.verifiedCoSignature ? { ...snap.verifiedCoSignature } : void 0;
676
695
  context._preFlightWafScanned = true;
677
696
  context._preFlightVerified = true;
678
697
  return true;
@@ -741,9 +760,11 @@ async function inspectTransactionPreFlight(context) {
741
760
  const baseTxSize = preFlightCtx._baseTxSize ?? preFlightCtx.txSize;
742
761
  const extraSizeCounted = Boolean(preFlightCtx._extraSizeCounted);
743
762
  const rawTxItxBeforeNormalize = preFlightCtx._rawTxItxBeforeNormalize;
763
+ const verifiedCoSignature = preFlightCtx._verifiedCoSignature;
744
764
  context._baseTxSize = baseTxSize;
745
765
  context._extraSizeCounted = extraSizeCounted;
746
766
  context._rawTxItxBeforeNormalize = rawTxItxBeforeNormalize;
767
+ context._verifiedCoSignature = verifiedCoSignature ? { ...verifiedCoSignature } : void 0;
747
768
  context._preFlightWafScanned = true;
748
769
  context._preFlightVerified = true;
749
770
  if (typeof context.txBase64 === "string" && preFlightCtx.tx && preFlightCtx.itx && preFlightCtx.txType) {
@@ -776,6 +797,8 @@ async function inspectTransactionPreFlight(context) {
776
797
  txExtraSerialized: serializeExtraField(extra?.txExtra),
777
798
  gasStakeHeadersSerialized: serializeExtraField(extra?.gasStakeHeaders),
778
799
  coSignatureSerialized: serializeExtraField(extra?.coSignature),
800
+ gasPassSerialized: serializeExtraField(extra?.gasPass),
801
+ verifiedCoSignature: verifiedCoSignature ? { ...verifiedCoSignature } : void 0,
779
802
  tx: (0, lodash_cloneDeep.default)(preFlightCtx.tx),
780
803
  txEncoding: preFlightCtx.txEncoding,
781
804
  txSize: preFlightCtx.txSize,
@@ -783,6 +806,7 @@ async function inspectTransactionPreFlight(context) {
783
806
  extraSizeCounted,
784
807
  txHash: preFlightCtx.txHash,
785
808
  unsignedTxHash: preFlightCtx.unsignedTxHash,
809
+ txTime: typeof preFlightCtx.txTime === "string" && preFlightCtx.txTime ? preFlightCtx.txTime : void 0,
786
810
  txBaseGas: Boolean(preFlightCtx.txBaseGas),
787
811
  itx: (0, lodash_cloneDeep.default)(preFlightCtx.itx),
788
812
  txType: preFlightCtx.txType,
@@ -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;
@@ -373,21 +373,28 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
373
373
  }
374
374
  for (const payload of candidatePayloads) {
375
375
  try {
376
- if (await wallet.verify(payload, rawCoSig.signature, false, coSigExtra)) return true;
376
+ if (await wallet.verify(payload, rawCoSig.signature, false, coSigExtra)) {
377
+ if (parsedFromDirect) context._verifiedCoSignature = parsedFromDirect;
378
+ return true;
379
+ }
377
380
  } catch {}
378
381
  try {
379
- if (await wallet.verify(payload, rawCoSig.signature, true, coSigExtra)) return true;
382
+ if (await wallet.verify(payload, rawCoSig.signature, true, coSigExtra)) {
383
+ if (parsedFromDirect) context._verifiedCoSignature = parsedFromDirect;
384
+ return true;
385
+ }
380
386
  } catch {}
381
387
  }
382
388
  return false;
383
389
  };
384
390
  const getTxTimestampSeconds = () => {
385
- const txTime = context.txTime;
391
+ const ctxWithTime = context;
392
+ const txTime = ctxWithTime.txTime !== void 0 && ctxWithTime.txTime !== null && ctxWithTime.txTime !== "" ? ctxWithTime.txTime : ctxWithTime.extra?.txTime;
386
393
  if (txTime !== void 0 && txTime !== null && txTime !== "") if (typeof txTime === "number") {
387
- if (Number.isFinite(txTime) && txTime > 0) return txTime > 1e11 ? Math.floor(txTime / 1e3) : Math.floor(txTime);
394
+ if (Number.isFinite(txTime) && txTime >= 0) return txTime > 1e11 ? Math.floor(txTime / 1e3) : Math.floor(txTime);
388
395
  } else {
389
396
  const parsedMs = new Date(txTime).getTime();
390
- if (Number.isFinite(parsedMs) && parsedMs > 0) return Math.floor(parsedMs / 1e3);
397
+ if (Number.isFinite(parsedMs) && parsedMs >= 0) return Math.floor(parsedMs / 1e3);
391
398
  }
392
399
  return Math.floor(Date.now() / 1e3);
393
400
  };
@@ -156,6 +156,10 @@ async function VerifySignature(context, next) {
156
156
  const ctxTxHash = context.txHash;
157
157
  const ctxUnsignedTxHash = context.unsignedTxHash || (0, _ocap_mcrypto.toTxHash)(txBytes);
158
158
  if (!await verifyStatelessCoSignature(parsedCoSig, coSigCandidates, Array.from(new Set([ctxTxHash, ctxUnsignedTxHash].filter((x) => typeof x === "string" && x.length > 0))))) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", "Invalid owner coSignature"));
159
+ if (parsedFromDirect && context.extra && typeof context.extra === "object") {
160
+ context.extra.coSignature = parsedFromDirect;
161
+ context._verifiedCoSignature = parsedFromDirect;
162
+ }
159
163
  }
160
164
  }
161
165
  const extra = isPasskey ? rawTxExtra : isWalletEnvelope ? rawTxExtra : "";
@@ -9,32 +9,62 @@ let _ocap_message = require("@ocap/message");
9
9
  //#region src/pipes/verify-tx-size.ts
10
10
  const DEFAULT_MAX_EXTRA_SIZE = 8 * 1024;
11
11
  const MAX_GAS_STAKE_HEADERS_SIZE = 8 * 1024;
12
+ const MAX_GAS_STAKE_TOKEN_BYTES = 4 * 1024;
13
+ const MAX_GAS_STAKE_PK_BYTES = 512;
12
14
  const MAX_CO_SIGNATURE_SIZE = 4 * 1024;
15
+ const MAX_GAS_PASS_SIZE = 2 * 1024;
16
+ const ALLOWED_GAS_STAKE_HEADER_KEYS = new Set(["token", "pk"]);
13
17
  const getFieldByteSize = (val) => {
14
18
  if (val === void 0 || val === null || val === "") return 0;
15
- return Buffer.byteLength(typeof val === "string" ? val : JSON.stringify(val), "utf8");
19
+ if (typeof val === "string") return Buffer.byteLength(val, "utf8");
20
+ try {
21
+ const serialized = JSON.stringify(val);
22
+ if (typeof serialized !== "string") return Number.POSITIVE_INFINITY;
23
+ return Buffer.byteLength(serialized, "utf8");
24
+ } catch {
25
+ return Number.POSITIVE_INFINITY;
26
+ }
27
+ };
28
+ const isInvalidGasStakeHeadersEnvelope = (raw) => {
29
+ if (raw === void 0 || raw === null || raw === "") return false;
30
+ if (typeof raw !== "object" || Array.isArray(raw)) return true;
31
+ const proto = Object.getPrototypeOf(raw);
32
+ if (proto !== Object.prototype && proto !== null) return true;
33
+ const obj = raw;
34
+ for (const key of Object.keys(obj)) if (!ALLOWED_GAS_STAKE_HEADER_KEYS.has(key)) return true;
35
+ if (obj.token !== void 0 && typeof obj.token !== "string") return true;
36
+ if (obj.pk !== void 0 && typeof obj.pk !== "string") return true;
37
+ const tokenBytes = typeof obj.token === "string" ? Buffer.byteLength(obj.token, "utf8") : 0;
38
+ const pkBytes = typeof obj.pk === "string" ? Buffer.byteLength(obj.pk, "utf8") : 0;
39
+ return tokenBytes > MAX_GAS_STAKE_TOKEN_BYTES || pkBytes > MAX_GAS_STAKE_PK_BYTES;
16
40
  };
17
41
  const getExtraByteSizes = (extra) => {
18
42
  if (!extra || typeof extra !== "object") return {
19
43
  txExtraBytes: 0,
20
44
  gasStakeHeadersBytes: 0,
21
45
  coSignatureBytes: 0,
22
- totalExtraBytes: 0
46
+ gasPassBytes: 0,
47
+ totalExtraBytes: 0,
48
+ invalidGasHeaders: false
23
49
  };
24
- const { txExtra, gasStakeHeaders, coSignature } = extra;
50
+ const { txExtra, gasStakeHeaders, coSignature, gasPass } = extra;
51
+ const invalidGasHeaders = isInvalidGasStakeHeadersEnvelope(gasStakeHeaders);
25
52
  const txExtraBytes = getFieldByteSize(txExtra);
26
- const gasStakeHeadersBytes = getFieldByteSize(gasStakeHeaders);
53
+ const gasStakeHeadersBytes = invalidGasHeaders ? 0 : getFieldByteSize(gasStakeHeaders);
27
54
  const coSignatureBytes = getFieldByteSize(coSignature);
55
+ const gasPassBytes = getFieldByteSize(gasPass);
28
56
  return {
29
57
  txExtraBytes,
30
58
  gasStakeHeadersBytes,
31
59
  coSignatureBytes,
32
- totalExtraBytes: txExtraBytes + gasStakeHeadersBytes + coSignatureBytes
60
+ gasPassBytes,
61
+ totalExtraBytes: txExtraBytes + gasStakeHeadersBytes + coSignatureBytes + gasPassBytes,
62
+ invalidGasHeaders
33
63
  };
34
64
  };
35
65
  function VerifyTxSize(context, next) {
36
66
  const { txSize, txType, tx, config } = context;
37
- const { txExtraBytes, gasStakeHeadersBytes, coSignatureBytes, totalExtraBytes } = getExtraByteSizes(context.extra);
67
+ const { txExtraBytes, gasStakeHeadersBytes, coSignatureBytes, gasPassBytes, totalExtraBytes, invalidGasHeaders } = getExtraByteSizes(context.extra);
38
68
  const alreadyCounted = Boolean(context._extraSizeCounted);
39
69
  const baseTxSize = alreadyCounted ? Math.max(0, (txSize || 0) - txExtraBytes) : txSize || 0;
40
70
  context._baseTxSize = baseTxSize;
@@ -48,7 +78,7 @@ function VerifyTxSize(context, next) {
48
78
  ], defaultSizeLimit);
49
79
  if (baseTxSize > sizeLimit) return next(new _ocap_util_lib_error.CustomError("INVALID_TX_SIZE", `Transaction size too large for ${txType}: expect ${sizeLimit}, got ${baseTxSize}`));
50
80
  const maxExtraSize = (0, lodash_get.default)(config, "transaction.maxExtraSize", DEFAULT_MAX_EXTRA_SIZE);
51
- if (totalExtraBytes > maxExtraSize || gasStakeHeadersBytes > MAX_GAS_STAKE_HEADERS_SIZE || coSignatureBytes > MAX_CO_SIGNATURE_SIZE) {
81
+ if (invalidGasHeaders || totalExtraBytes > maxExtraSize || gasStakeHeadersBytes > MAX_GAS_STAKE_HEADERS_SIZE || coSignatureBytes > MAX_CO_SIGNATURE_SIZE || gasPassBytes > MAX_GAS_PASS_SIZE) {
52
82
  const extraErr = new _ocap_util_lib_error.CustomError("INVALID_TX_SIZE", `Transaction extra size too large for ${txType}: expect <= ${maxExtraSize}, got ${totalExtraBytes}`);
53
83
  extraErr._unauthenticatedExtraFailure = true;
54
84
  return next(extraErr);