@ocap/tx-protocols 1.31.8 → 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.
Files changed (37) hide show
  1. package/esm/execute.d.mts +6 -1
  2. package/esm/execute.mjs +151 -9
  3. package/esm/gas-security-guard.d.mts +19 -1
  4. package/esm/gas-security-guard.mjs +44 -1
  5. package/esm/index.d.mts +8 -2
  6. package/esm/index.mjs +2 -2
  7. package/esm/pipes/ensure-cost.mjs +39 -2
  8. package/esm/pipes/write-ledger.mjs +18 -3
  9. package/esm/protocols/rollup/bridge-create.mjs +8 -3
  10. package/esm/protocols/rollup/bridge-governance-tx-binding.d.mts +7 -0
  11. package/esm/protocols/rollup/bridge-governance-tx-binding.mjs +212 -0
  12. package/esm/protocols/rollup/bridge-governance-vote.d.mts +49 -0
  13. package/esm/protocols/rollup/bridge-governance-vote.mjs +564 -0
  14. package/esm/protocols/rollup/bridge-migrate.mjs +6 -3
  15. package/esm/protocols/rollup/bridge-v2.d.mts +6 -0
  16. package/esm/protocols/rollup/bridge-v2.mjs +5 -0
  17. package/esm/protocols/rollup/update.d.mts +2 -0
  18. package/esm/protocols/rollup/update.mjs +28 -6
  19. package/lib/execute.cjs +151 -9
  20. package/lib/execute.d.cts +6 -1
  21. package/lib/gas-security-guard.cjs +44 -0
  22. package/lib/gas-security-guard.d.cts +19 -1
  23. package/lib/index.cjs +1 -0
  24. package/lib/index.d.cts +8 -2
  25. package/lib/pipes/ensure-cost.cjs +39 -2
  26. package/lib/pipes/write-ledger.cjs +18 -3
  27. package/lib/protocols/rollup/bridge-create.cjs +8 -3
  28. package/lib/protocols/rollup/bridge-governance-tx-binding.cjs +213 -0
  29. package/lib/protocols/rollup/bridge-governance-tx-binding.d.cts +7 -0
  30. package/lib/protocols/rollup/bridge-governance-vote.cjs +573 -0
  31. package/lib/protocols/rollup/bridge-governance-vote.d.cts +49 -0
  32. package/lib/protocols/rollup/bridge-migrate.cjs +6 -3
  33. package/lib/protocols/rollup/bridge-v2.cjs +5 -0
  34. package/lib/protocols/rollup/bridge-v2.d.cts +6 -0
  35. package/lib/protocols/rollup/update.cjs +28 -6
  36. package/lib/protocols/rollup/update.d.cts +2 -0
  37. package/package.json +16 -16
package/esm/execute.d.mts CHANGED
@@ -2,7 +2,7 @@ import { ITxGasQuotaTelemetry, ITxSecurityWarning } from "./gas-security-guard.m
2
2
  import { TxTimer } from "./tx-timer.mjs";
3
3
  import { CustomError } from "@ocap/util/lib/error";
4
4
  import { Blacklist } from "@ocap/state";
5
- import { IAccountState, IBaseContext, IGasContext } from "@ocap/types";
5
+ import { IAccountState, IBaseContext, IConsensusCommitter, IGasContext } from "@ocap/types";
6
6
 
7
7
  //#region src/execute.d.ts
8
8
  declare const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL: symbol;
@@ -45,6 +45,8 @@ interface IExecutionContext extends IGasContext {
45
45
  gasQuotaTelemetry?: ITxGasQuotaTelemetry;
46
46
  /** Structured progressive strike warning */
47
47
  securityWarning?: ITxSecurityWarning;
48
+ /** Optional BFT consensus committer (#1712) */
49
+ consensusCommitter?: IConsensusCommitter;
48
50
  }
49
51
  /** Protocol runner interface */
50
52
  interface IProtocolRunner {
@@ -59,6 +61,9 @@ interface IExecuteOptions {
59
61
  cleanWorkingSet: boolean;
60
62
  verifyHash: boolean;
61
63
  context: IExecutionContext;
64
+ beforeCommit?: (params: {
65
+ commitHash: string;
66
+ }) => void | Promise<void>;
62
67
  onCommit?: (commitHash?: string) => void | Promise<void>;
63
68
  }) => Promise<T>;
64
69
  }
package/esm/execute.mjs CHANGED
@@ -53,6 +53,7 @@ const getStates = (context) => {
53
53
  return context.states;
54
54
  };
55
55
  const flushEvents = (context, extra = {}) => {
56
+ if (context.extra?._dryRun === true) return;
56
57
  const events = context.events || [];
57
58
  if (events.length) context.timer?.incrCounter("indexEvents", events.length);
58
59
  events.forEach((e) => {
@@ -419,9 +420,8 @@ const createExecute = ({ filter, runAsLambda }) => {
419
420
  }
420
421
  }
421
422
  const extra = context.extra || {};
422
- const txExtra = extra.txExtra && typeof extra.txExtra === "object" ? extra.txExtra : void 0;
423
423
  const { token: token$1, pk } = extra.gasStakeHeaders || {};
424
- const rawGasPass = extra.gasPass || txExtra?.gasPass;
424
+ const rawGasPass = extra.gasPass;
425
425
  const txHash = context.txHash || "";
426
426
  const txTime = context.txTime;
427
427
  const nowMs = txTime ? +new Date(txTime) : Date.now();
@@ -746,7 +746,10 @@ const createExecute = ({ filter, runAsLambda }) => {
746
746
  return pipes.DecodeItx(context, next);
747
747
  });
748
748
  pre.use((context, next) => {
749
- if (context._preFlightSnapshotApplied) return next();
749
+ if (context._preFlightSnapshotApplied) {
750
+ if (context.extra?.txTime !== void 0 && (Boolean(context.tx?.delegator) || context.txType === "fg:t:exchange_v2")) return pipes.VerifyTx(context, next);
751
+ return next();
752
+ }
750
753
  return pipes.VerifyTx(context, next);
751
754
  });
752
755
  pre.use((context, next) => {
@@ -890,6 +893,7 @@ const createExecute = ({ filter, runAsLambda }) => {
890
893
  };
891
894
  const attachSecurityStrikeToError = async (err, ctx) => {
892
895
  if (!err || err._strikeRecorded || err._unauthenticatedExtraFailure === true) return;
896
+ if (ctx.extra?._isReplay === true) return;
893
897
  const classified = classifyErrorStrikeCategory(err);
894
898
  if (!classified.shouldRecordStrike) return;
895
899
  const secCfg = ctx.config?.transaction?.security;
@@ -900,6 +904,7 @@ const createExecute = ({ filter, runAsLambda }) => {
900
904
  err._strikeRecorded = true;
901
905
  const fishermanAddress = secCfg?.fishermanAddress;
902
906
  const nowMs = ctx.txTime ? +new Date(ctx.txTime) : Date.now();
907
+ const allowStateDbAutoSlash = !ctx.consensusCommitter && ctx.extra?.txTime === void 0;
903
908
  const { primaryWarning, slashEvidence } = await recordActorSecurityStrike({
904
909
  actors,
905
910
  category: classified.category,
@@ -907,7 +912,7 @@ const createExecute = ({ filter, runAsLambda }) => {
907
912
  txHash: ctx.txHash,
908
913
  config: ctx.config,
909
914
  statedb: ctx.statedb,
910
- txn: ctx.txn,
915
+ txn: allowStateDbAutoSlash ? ctx.txn : void 0,
911
916
  fishermanAddress,
912
917
  nowMs,
913
918
  telemetry: ctx.gasQuotaTelemetry
@@ -1013,20 +1018,58 @@ const createExecute = ({ filter, runAsLambda }) => {
1013
1018
  });
1014
1019
  });
1015
1020
  });
1021
+ const createStagingLedgerProxy = (baseLedger, slot, onStage) => {
1022
+ const proxy = Object.create(baseLedger || Object.prototype);
1023
+ proxy.append = async (txInput) => {
1024
+ const normalizedInput = {
1025
+ ...txInput,
1026
+ timestamp: slot.timestampMs
1027
+ };
1028
+ onStage({
1029
+ txInput: normalizedInput,
1030
+ sequence: slot.sequence
1031
+ });
1032
+ return {
1033
+ sequence: slot.sequence,
1034
+ hash: normalizedInput.txHash,
1035
+ tx: normalizedInput.tx,
1036
+ txRaw: normalizedInput.txRaw,
1037
+ txType: normalizedInput.txType,
1038
+ from: normalizedInput.from,
1039
+ nonce: normalizedInput.nonce,
1040
+ pk: normalizedInput.pk,
1041
+ signature: normalizedInput.signature,
1042
+ chainId: normalizedInput.chainId,
1043
+ timestamp: slot.timestampMs,
1044
+ txExtra: normalizedInput.txExtra,
1045
+ entryHash: "",
1046
+ finalized: false
1047
+ };
1048
+ };
1049
+ return proxy;
1050
+ };
1016
1051
  if (typeof runAsLambda === "function") return async (context, protocols) => {
1017
1052
  const executionId = Symbol("tx-exec");
1018
1053
  context.executionId = executionId;
1019
1054
  let ctx = context;
1020
1055
  context.timer = context.timer || new TxTimer();
1056
+ const consensusCommitter = context.consensusCommitter;
1057
+ let proposalSlot = null;
1058
+ let stagedCapture = null;
1059
+ let committedConsensusEntry = null;
1021
1060
  let entryFinalized = false;
1022
1061
  let savedLedgerSequence;
1023
1062
  try {
1063
+ if (consensusCommitter) proposalSlot = await consensusCommitter.prepareProposalSlot();
1024
1064
  const txState = await runAsLambda(async (txn) => {
1065
+ stagedCapture = null;
1066
+ committedConsensusEntry = null;
1025
1067
  ctx = pick(context, [
1026
1068
  "txBase64",
1027
1069
  "statedb",
1028
1070
  "indexdb",
1029
1071
  "ledger",
1072
+ "consensusCommitter",
1030
1073
  "config",
1031
1074
  "states",
1032
1075
  "filter",
@@ -1036,20 +1079,33 @@ const createExecute = ({ filter, runAsLambda }) => {
1036
1079
  "timer",
1037
1080
  "executionId"
1038
1081
  ]);
1082
+ if (consensusCommitter && proposalSlot) {
1083
+ ctx.extra = {
1084
+ ...context.extra || {},
1085
+ txTime: proposalSlot.timestampMs
1086
+ };
1087
+ ctx.ledger = createStagingLedgerProxy(context.ledger, proposalSlot, (staged) => {
1088
+ stagedCapture = staged;
1089
+ });
1090
+ }
1039
1091
  const preFlightSnapshot = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
1040
1092
  if (preFlightSnapshot !== void 0) ctx[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL] = preFlightSnapshot;
1041
1093
  ctx.txn = txn;
1042
- if (savedLedgerSequence !== void 0) ctx.ledgerSequence = savedLedgerSequence;
1094
+ if (savedLedgerSequence !== void 0 && !consensusCommitter) ctx.ledgerSequence = savedLedgerSequence;
1043
1095
  ctx.timer?.mark("lockWait");
1044
1096
  try {
1045
1097
  await execute(ctx, protocols, true);
1046
1098
  await appendLedgerEntry(ctx);
1047
1099
  } finally {
1048
- if (ctx.ledgerSequence && !savedLedgerSequence) {
1100
+ if (ctx.ledgerSequence && !savedLedgerSequence && !consensusCommitter) {
1049
1101
  savedLedgerSequence = ctx.ledgerSequence;
1050
1102
  context.ledgerSequence = ctx.ledgerSequence;
1051
1103
  }
1052
1104
  }
1105
+ if (consensusCommitter && ctx.ledgerSequence) {
1106
+ savedLedgerSequence = ctx.ledgerSequence;
1107
+ context.ledgerSequence = ctx.ledgerSequence;
1108
+ }
1053
1109
  const state = getStates(context).tx.create(ctx, "OK");
1054
1110
  await context.statedb.tx.create(state.hash, state, ctx);
1055
1111
  await recordUnsignedTxInStateDb(ctx, state.hash);
@@ -1059,7 +1115,27 @@ const createExecute = ({ filter, runAsLambda }) => {
1059
1115
  cleanWorkingSet: true,
1060
1116
  verifyHash: true,
1061
1117
  context: ctx,
1118
+ ...consensusCommitter && proposalSlot ? { beforeCommit: async ({ commitHash }) => {
1119
+ if (!stagedCapture || !proposalSlot) {
1120
+ const abortErr = new CustomError("CONSENSUS_ABORTED", "Missing staged ledger entry before consensus commit");
1121
+ abortErr.isConsensusAbort = true;
1122
+ throw abortErr;
1123
+ }
1124
+ committedConsensusEntry = await consensusCommitter.commitStagedEntry({
1125
+ txInput: stagedCapture.txInput,
1126
+ sequence: stagedCapture.sequence,
1127
+ stateCommitHash: commitHash || "",
1128
+ timestampMs: proposalSlot.timestampMs
1129
+ });
1130
+ ctx.stateCommitHash = commitHash || "";
1131
+ entryFinalized = true;
1132
+ } } : {},
1062
1133
  onCommit: async (stateCommitHash) => {
1134
+ if (consensusCommitter) {
1135
+ ctx.stateCommitHash = stateCommitHash || "";
1136
+ entryFinalized = true;
1137
+ return;
1138
+ }
1063
1139
  if (ctx.txHash && ctx.ledger && ctx.ledgerSequence && ctx.txBase64) try {
1064
1140
  await ctx.ledger.finalizeEntry(ctx.txHash, stateCommitHash || "", ctx.ledgerSequence, ctx.txBase64);
1065
1141
  ctx.stateCommitHash = stateCommitHash || "";
@@ -1074,10 +1150,13 @@ const createExecute = ({ filter, runAsLambda }) => {
1074
1150
  }
1075
1151
  }
1076
1152
  });
1153
+ if (consensusCommitter) ctx.ledger = context.ledger;
1077
1154
  ctx.timer?.mark("commit");
1078
1155
  flushEvents(ctx, { txState });
1079
1156
  ctx.timer?.mark("indexdb");
1080
- ctx.ledger?.createCheckpointIfNeeded()?.catch((err) => {
1157
+ if (consensusCommitter) {
1158
+ if (committedConsensusEntry && typeof consensusCommitter.afterStateCommitted === "function") await consensusCommitter.afterStateCommitted(committedConsensusEntry);
1159
+ } else ctx.ledger?.createCheckpointIfNeeded()?.catch((err) => {
1081
1160
  ctx.logger?.error("Background checkpoint creation failed", {
1082
1161
  txHash: ctx.txHash,
1083
1162
  error: err
@@ -1102,6 +1181,18 @@ const createExecute = ({ filter, runAsLambda }) => {
1102
1181
  });
1103
1182
  } catch (error) {
1104
1183
  const err = error;
1184
+ if (consensusCommitter && !entryFinalized) {
1185
+ ctx.ledger = context.ledger;
1186
+ ctx.ledgerSequence = void 0;
1187
+ savedLedgerSequence = void 0;
1188
+ context.ledgerSequence = void 0;
1189
+ }
1190
+ if (err?.isConsensusAbort === true) {
1191
+ ctx.ledgerSequence = void 0;
1192
+ savedLedgerSequence = void 0;
1193
+ context.ledgerSequence = void 0;
1194
+ throw error;
1195
+ }
1105
1196
  const txStatus = err.code || "INTERNAL";
1106
1197
  let txState = ctx.tx ? getStates(context).tx.create(ctx, txStatus, false) : null;
1107
1198
  ctx.logger?.error("Failed to execute transaction", {
@@ -1114,10 +1205,22 @@ const createExecute = ({ filter, runAsLambda }) => {
1114
1205
  ctx.events = [];
1115
1206
  try {
1116
1207
  txState = await runAsLambda(async (txn) => {
1208
+ stagedCapture = null;
1209
+ committedConsensusEntry = null;
1117
1210
  ctx = Object.assign({}, ctx, {
1118
1211
  txn,
1119
1212
  cacheStates: null
1120
1213
  });
1214
+ if (consensusCommitter && proposalSlot) {
1215
+ ctx.ledgerSequence = void 0;
1216
+ ctx.extra = {
1217
+ ...ctx.extra || {},
1218
+ txTime: proposalSlot.timestampMs
1219
+ };
1220
+ ctx.ledger = createStagingLedgerProxy(context.ledger, proposalSlot, (staged) => {
1221
+ stagedCapture = staged;
1222
+ });
1223
+ }
1121
1224
  ctx.timer?.mark("lockWait");
1122
1225
  const strikeSnapshot = snapshotActorSecurityRecords([
1123
1226
  ctx.tx?.delegator || "",
@@ -1152,7 +1255,27 @@ const createExecute = ({ filter, runAsLambda }) => {
1152
1255
  cleanWorkingSet: true,
1153
1256
  verifyHash: true,
1154
1257
  context: ctx,
1258
+ ...consensusCommitter && proposalSlot ? { beforeCommit: async ({ commitHash }) => {
1259
+ if (!stagedCapture || !proposalSlot) {
1260
+ const abortErr = new CustomError("CONSENSUS_ABORTED", "Missing staged ledger entry before failed-tx consensus commit");
1261
+ abortErr.isConsensusAbort = true;
1262
+ throw abortErr;
1263
+ }
1264
+ committedConsensusEntry = await consensusCommitter.commitStagedEntry({
1265
+ txInput: stagedCapture.txInput,
1266
+ sequence: stagedCapture.sequence,
1267
+ stateCommitHash: commitHash || "",
1268
+ timestampMs: proposalSlot.timestampMs
1269
+ });
1270
+ ctx.stateCommitHash = commitHash || "";
1271
+ entryFinalized = true;
1272
+ } } : {},
1155
1273
  onCommit: async (stateCommitHash) => {
1274
+ if (consensusCommitter) {
1275
+ ctx.stateCommitHash = stateCommitHash || "";
1276
+ entryFinalized = true;
1277
+ return;
1278
+ }
1156
1279
  if (ctx.txHash && ctx.ledger && ctx.ledgerSequence && ctx.txBase64) try {
1157
1280
  await ctx.ledger.finalizeEntry(ctx.txHash, stateCommitHash || "", ctx.ledgerSequence, ctx.txBase64);
1158
1281
  ctx.stateCommitHash = stateCommitHash || "";
@@ -1167,10 +1290,13 @@ const createExecute = ({ filter, runAsLambda }) => {
1167
1290
  }
1168
1291
  }
1169
1292
  });
1293
+ if (consensusCommitter) ctx.ledger = context.ledger;
1170
1294
  ctx.timer?.mark("commit");
1171
1295
  flushEvents(ctx, { txState });
1172
1296
  ctx.timer?.mark("indexdb");
1173
- ctx.ledger?.createCheckpointIfNeeded()?.catch((err$1) => {
1297
+ if (consensusCommitter) {
1298
+ if (committedConsensusEntry && typeof consensusCommitter.afterStateCommitted === "function") await consensusCommitter.afterStateCommitted(committedConsensusEntry);
1299
+ } else ctx.ledger?.createCheckpointIfNeeded()?.catch((err$1) => {
1174
1300
  ctx.logger?.error("Background checkpoint creation failed", {
1175
1301
  txHash: ctx.txHash,
1176
1302
  error: err$1
@@ -1195,6 +1321,20 @@ const createExecute = ({ filter, runAsLambda }) => {
1195
1321
  perf: ctx.timer?.summaryV2()
1196
1322
  });
1197
1323
  } catch (innerErr) {
1324
+ if (consensusCommitter) {
1325
+ ctx.ledger = context.ledger;
1326
+ if (!entryFinalized) {
1327
+ ctx.ledgerSequence = void 0;
1328
+ savedLedgerSequence = void 0;
1329
+ context.ledgerSequence = void 0;
1330
+ }
1331
+ }
1332
+ if (innerErr?.isConsensusAbort === true) {
1333
+ ctx.ledgerSequence = void 0;
1334
+ savedLedgerSequence = void 0;
1335
+ context.ledgerSequence = void 0;
1336
+ throw innerErr;
1337
+ }
1198
1338
  await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
1199
1339
  ctx.logger?.error("Failed to save invalid transaction to statedb", {
1200
1340
  error: innerErr,
@@ -1206,6 +1346,7 @@ const createExecute = ({ filter, runAsLambda }) => {
1206
1346
  throw error;
1207
1347
  }
1208
1348
  } else {
1349
+ if (consensusCommitter) ctx.ledger = context.ledger;
1209
1350
  await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
1210
1351
  ctx.timer?.setMeta({
1211
1352
  txType: ctx.txType,
@@ -1227,7 +1368,8 @@ const createExecute = ({ filter, runAsLambda }) => {
1227
1368
  }
1228
1369
  throw error;
1229
1370
  } finally {
1230
- if (!entryFinalized) {
1371
+ if (consensusCommitter) ctx.ledger = context.ledger;
1372
+ if (!entryFinalized && !consensusCommitter) {
1231
1373
  const ledger = ctx.ledger || context.ledger;
1232
1374
  const txHash = ctx.txHash || context.txHash;
1233
1375
  const txBase64 = ctx.txBase64 || context.txBase64;
@@ -369,5 +369,23 @@ declare function assertTxAdmission(params: {
369
369
  }>;
370
370
  declare function getTxSecurityWarningByHash(txHash: string, statedb?: unknown): ITxSecurityWarning | undefined;
371
371
  declare function setTxSecurityWarningForHash(txHash: string, warning: ITxSecurityWarning, statedb?: unknown): void;
372
+ interface IGasSecuritySummary {
373
+ enabled: boolean;
374
+ trackedActors: number;
375
+ warningActors: number;
376
+ throttledActors: number;
377
+ slashTriggeredActors: number;
378
+ activeBurstsInWindow: number;
379
+ strikeWindowMs: number;
380
+ burstWindowMs: number;
381
+ }
382
+ /**
383
+ * Pure, side-effect-free read-only telemetry summary of process-local gas security counters (#1756).
384
+ *
385
+ * INVARIANT (`AGENTS.md` Axiom #4): Never mutates registry maps, LRU order, burst windows, or strike
386
+ * records, never returns individual actor DIDs on public endpoints, and MUST NEVER be called inside
387
+ * `execute` or transaction pipeline stages.
388
+ */
389
+ declare function getGasSecuritySummary(statedb?: unknown, config?: Partial<IChainConfig>, nowMs?: number): IGasSecuritySummary;
372
390
  //#endregion
373
- export { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_DELEGATED_BURST_MULTIPLE, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, IAbuseSlashEvidence, IActorSecuritySnapshot, IGasSecurityConfig, IPaymasterDecodedClaims, IStakeForGasEligibilityResult, ITxGasQuotaTelemetry, ITxSecurityWarning, IUnlinkableGasPass, SecurityStrikeTier, StrikeReasonCategory, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, setTxSecurityWarningForHash, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
391
+ export { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_DELEGATED_BURST_MULTIPLE, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, IAbuseSlashEvidence, IActorSecuritySnapshot, IGasSecurityConfig, IGasSecuritySummary, IPaymasterDecodedClaims, IStakeForGasEligibilityResult, ITxGasQuotaTelemetry, ITxSecurityWarning, IUnlinkableGasPass, SecurityStrikeTier, StrikeReasonCategory, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getGasSecuritySummary, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, setTxSecurityWarningForHash, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
@@ -1120,6 +1120,49 @@ function setTxSecurityWarningForHash(txHash, warning, statedb) {
1120
1120
  }
1121
1121
  reg.txWarningsByHash.set(normKey, warning);
1122
1122
  }
1123
+ /**
1124
+ * Pure, side-effect-free read-only telemetry summary of process-local gas security counters (#1756).
1125
+ *
1126
+ * INVARIANT (`AGENTS.md` Axiom #4): Never mutates registry maps, LRU order, burst windows, or strike
1127
+ * records, never returns individual actor DIDs on public endpoints, and MUST NEVER be called inside
1128
+ * `execute` or transaction pipeline stages.
1129
+ */
1130
+ function getGasSecuritySummary(statedb, config, nowMs = Date.now()) {
1131
+ const cfg = resolveGasSecurityConfig(config);
1132
+ const reg = getGasSecurityRegistry(statedb);
1133
+ const strikeCutoff = nowMs - cfg.strikeWindowMs;
1134
+ const burstCutoff = nowMs - cfg.burstWindowMs;
1135
+ let trackedActors = 0;
1136
+ let warningActors = 0;
1137
+ let throttledActors = 0;
1138
+ let slashTriggeredActors = 0;
1139
+ let activeBurstsInWindow = 0;
1140
+ for (const [key, rec] of reg.actors.entries()) {
1141
+ if (key.endsWith(">*")) continue;
1142
+ trackedActors += 1;
1143
+ let activeBursts = 0;
1144
+ for (const b of rec.bursts) if (b.t >= burstCutoff) activeBursts += 1;
1145
+ activeBurstsInWindow += activeBursts;
1146
+ if (!cfg.enabled) continue;
1147
+ let strikeCount = 0;
1148
+ for (const s of rec.strikes) if (s.timestampMs >= strikeCutoff) strikeCount += s.weight;
1149
+ const isCoolingDown = cfg.throttle && rec.cooldownUntilMs > nowMs;
1150
+ const tier = computeActorTier(strikeCount, isCoolingDown, cfg);
1151
+ if (tier === "WARNING") warningActors += 1;
1152
+ else if (tier === "THROTTLED") throttledActors += 1;
1153
+ else if (tier === "SLASH_TRIGGERED") slashTriggeredActors += 1;
1154
+ }
1155
+ return {
1156
+ enabled: cfg.enabled,
1157
+ trackedActors,
1158
+ warningActors,
1159
+ throttledActors,
1160
+ slashTriggeredActors,
1161
+ activeBurstsInWindow,
1162
+ strikeWindowMs: cfg.strikeWindowMs,
1163
+ burstWindowMs: cfg.burstWindowMs
1164
+ };
1165
+ }
1123
1166
 
1124
1167
  //#endregion
1125
- export { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_DELEGATED_BURST_MULTIPLE, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, setTxSecurityWarningForHash, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
1168
+ export { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_DELEGATED_BURST_MULTIPLE, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getGasSecuritySummary, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, setTxSecurityWarningForHash, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
package/esm/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, IAbuseSlashEvidence, IGasSecurityConfig, IPaymasterDecodedClaims, IStakeForGasEligibilityResult, ITxGasQuotaTelemetry, ITxSecurityWarning, IUnlinkableGasPass, SecurityStrikeTier, StrikeReasonCategory, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, setTxSecurityWarningForHash, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
1
+ import { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, IAbuseSlashEvidence, IGasSecurityConfig, IGasSecuritySummary, IPaymasterDecodedClaims, IStakeForGasEligibilityResult, ITxGasQuotaTelemetry, ITxSecurityWarning, IUnlinkableGasPass, SecurityStrikeTier, StrikeReasonCategory, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getGasSecuritySummary, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, setTxSecurityWarningForHash, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
2
2
  import { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 } from "./tx-timer.mjs";
3
3
  import { PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot } from "./execute.mjs";
4
4
  import { TokenInput } from "./protocols/trade/transfer-v2.mjs";
@@ -18,6 +18,7 @@ import { MultiOutput as MultiOutput$1, TokenCondition as TokenCondition$1, Token
18
18
  import { MultiOutput as MultiOutput$2 } from "./protocols/governance/slash-stake.mjs";
19
19
  import { MultiInput as MultiInput$5, TokenCondition as TokenCondition$2 } from "./protocols/governance/return-stake.mjs";
20
20
  import { BridgeCtxMixin } from "./protocols/rollup/bridge-v2.mjs";
21
+ import { BridgeGovVotePlan } from "./protocols/rollup/bridge-governance-vote.mjs";
21
22
  import { TokenChange as TokenChange$1 } from "./protocols/rollup/create-block.mjs";
22
23
  import { TokenChange as TokenChange$2 } from "./protocols/rollup/claim-reward.mjs";
23
24
  import { WriteLedger } from "./pipes/write-ledger.mjs";
@@ -36,6 +37,9 @@ interface ICreateExecutorOptions {
36
37
  cleanWorkingSet: boolean;
37
38
  verifyHash: boolean;
38
39
  context: unknown;
40
+ beforeCommit?: (params: {
41
+ commitHash: string;
42
+ }) => void | Promise<void>;
39
43
  onCommit?: (commitHash: string) => void | Promise<void>;
40
44
  }) => Promise<T>;
41
45
  }
@@ -373,6 +377,7 @@ declare const createExecutor: ({
373
377
  }>;
374
378
  updateRollup: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TUpdateRollupTx> & _ocap_types0.IWithRollup & _ocap_types0.IWithSender & _ocap_types0.IWithSigners & BridgeCtxMixin & {
375
379
  bridgePlan?: states.rollup.BridgePatchPlan;
380
+ govVotePlan?: BridgeGovVotePlan;
376
381
  }>;
377
382
  joinRollup: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TJoinRollupTx> & _ocap_types0.IWithRollup & _ocap_types0.IWithSender & _ocap_types0.IWithSigners & _ocap_types0.IWithStake & BridgeCtxMixin & {
378
383
  evidenceState?: _ocap_types0.IEvidenceState | null;
@@ -772,6 +777,7 @@ declare const defaultExecutor: {
772
777
  }>;
773
778
  updateRollup: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TUpdateRollupTx> & _ocap_types0.IWithRollup & _ocap_types0.IWithSender & _ocap_types0.IWithSigners & BridgeCtxMixin & {
774
779
  bridgePlan?: states.rollup.BridgePatchPlan;
780
+ govVotePlan?: BridgeGovVotePlan;
775
781
  }>;
776
782
  joinRollup: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TJoinRollupTx> & _ocap_types0.IWithRollup & _ocap_types0.IWithSender & _ocap_types0.IWithSigners & _ocap_types0.IWithStake & BridgeCtxMixin & {
777
783
  evidenceState?: _ocap_types0.IEvidenceState | null;
@@ -842,4 +848,4 @@ declare const defaultExecutor: {
842
848
  };
843
849
  declare const execute: (context: unknown, done?: (err: Error | null, res?: unknown) => void) => any;
844
850
  //#endregion
845
- export { COUNTER_NAMES, type CounterName, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, type IAbuseSlashEvidence, type IGasSecurityConfig, type IPaymasterDecodedClaims, type IStakeForGasEligibilityResult, type ITxGasQuotaTelemetry, type ITxSecurityWarning, type IUnlinkableGasPass, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, PostExecutionInvariantGate, PreFlightWaf, type QueueState, STAGE_LABELS, type SecurityStrikeTier, type StageLabel, type StrikeReasonCategory, TRACKED_STATE_TABLES, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, defaultExecutor as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getStatelessPrefixLength, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, markStatelessPrefix, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
851
+ export { COUNTER_NAMES, type CounterName, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, type IAbuseSlashEvidence, type IGasSecurityConfig, type IGasSecuritySummary, type IPaymasterDecodedClaims, type IStakeForGasEligibilityResult, type ITxGasQuotaTelemetry, type ITxSecurityWarning, type IUnlinkableGasPass, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, PostExecutionInvariantGate, PreFlightWaf, type QueueState, STAGE_LABELS, type SecurityStrikeTier, type StageLabel, type StrikeReasonCategory, TRACKED_STATE_TABLES, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, defaultExecutor as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getGasSecuritySummary, getStatelessPrefixLength, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, markStatelessPrefix, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
package/esm/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, setTxSecurityWarningForHash, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
1
+ import { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getGasSecuritySummary, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, setTxSecurityWarningForHash, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
2
2
  import { WriteLedger } from "./pipes/write-ledger.mjs";
3
3
  import { assertStatelessTxRules, getStatelessPrefixLength, markStatelessPrefix, setDefaultStatelessProtocols } from "./stateless-prefix.mjs";
4
4
  import { COUNTER_NAMES, STAGE_LABELS, TxTimer } from "./tx-timer.mjs";
@@ -103,4 +103,4 @@ const { execute } = defaultExecutor;
103
103
  var src_default = defaultExecutor;
104
104
 
105
105
  //#endregion
106
- export { COUNTER_NAMES, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, PostExecutionInvariantGate, PreFlightWaf, STAGE_LABELS, TRACKED_STATE_TABLES, TxTimer, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, src_default as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getStatelessPrefixLength, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, markStatelessPrefix, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
106
+ export { COUNTER_NAMES, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, PostExecutionInvariantGate, PreFlightWaf, STAGE_LABELS, TRACKED_STATE_TABLES, TxTimer, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, src_default as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getGasSecuritySummary, getStatelessPrefixLength, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, markStatelessPrefix, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
@@ -27,12 +27,18 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
27
27
  const { statedb, txType, senderState, gasEstimate, totalGas } = context;
28
28
  const { config } = context;
29
29
  const { tx: tx$1, extra = {}, txHash = "", txTime } = context;
30
+ const verifiedLedgerExtraCtx = context;
30
31
  const isFailedTxGasCharge = Boolean(context.isFailedTxGasCharge);
31
32
  const canChargeSenderDirectly = Boolean(senderState);
33
+ verifiedLedgerExtraCtx._ensureTxCostEvaluated = true;
34
+ if (!isFailedTxGasCharge || !canChargeSenderDirectly) {
35
+ verifiedLedgerExtraCtx._verifiedGasPass = void 0;
36
+ verifiedLedgerExtraCtx._verifiedGasStakeHeaders = void 0;
37
+ }
32
38
  const txSize = context._baseTxSize ?? context.txSize;
33
39
  const nowMs = txTime ? +new Date(txTime) : Date.now();
34
40
  const { token: token$1, pk } = extra.gasStakeHeaders || {};
35
- const rawGasPass = extra.gasPass || extra.txExtra?.gasPass;
41
+ const rawGasPass = extra.gasPass;
36
42
  const gasStake = {};
37
43
  let isThirdPartySponsor = false;
38
44
  let enforceSponsor3DEligibility = false;
@@ -105,6 +111,15 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
105
111
  gasStake.owner = passOwner;
106
112
  gasStake.stakeId = passResult.stakeId;
107
113
  gasStake.state = passStakeState;
114
+ verifiedLedgerExtraCtx._verifiedGasPass = {
115
+ stakeId: passResult.stakeId,
116
+ epoch: Number(rawGasPass.epoch),
117
+ nullifier: String(rawGasPass.nullifier).trim(),
118
+ commitment: String(rawGasPass.commitment).trim().toLowerCase(),
119
+ ...typeof rawGasPass.passSecret === "string" && rawGasPass.passSecret ? { passSecret: rawGasPass.passSecret } : {},
120
+ ...typeof rawGasPass.pk === "string" && rawGasPass.pk ? { pk: rawGasPass.pk } : {},
121
+ ...typeof rawGasPass.signature === "string" && rawGasPass.signature ? { signature: rawGasPass.signature } : {}
122
+ };
108
123
  }
109
124
  } else if ((!isFailedTxGasCharge || !canChargeSenderDirectly) && token$1 && pk) {
110
125
  const decoded = JWT.decode(token$1) || {};
@@ -214,6 +229,10 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
214
229
  gasStake.owner = sponsorAddress;
215
230
  gasStake.stakeId = sponsorStakeId;
216
231
  if (sponsorStakeState) gasStake.state = sponsorStakeState;
232
+ if (sponsorIsBacked && typeof token$1 === "string" && token$1.length > 0 && Buffer.byteLength(token$1, "utf8") <= 4 * 1024 && typeof pk === "string" && pk.length > 0 && Buffer.byteLength(pk, "utf8") <= 512) verifiedLedgerExtraCtx._verifiedGasStakeHeaders = {
233
+ token: token$1,
234
+ pk
235
+ };
217
236
  }
218
237
  }
219
238
  } else console.warn(`Invalid gas payer header for: ${txHash}`);
@@ -340,7 +359,25 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
340
359
  };
341
360
  }
342
361
  const nextSponsorState = await statedb.account.update(latestSponsor.address, updatedSponsorPayload, context);
343
- if (nextSponsorState && typeof nextSponsorState === "object") nextSponsorState._retrievedAt = Date.now() + 1;
362
+ if (nextSponsorState && typeof nextSponsorState === "object") {
363
+ const prevSponsorTick = latestSponsor?._retrievedAt;
364
+ const curSponsorTick = nextSponsorState._retrievedAt;
365
+ if (!(typeof curSponsorTick === "bigint" && (typeof prevSponsorTick !== "bigint" || curSponsorTick > prevSponsorTick))) {
366
+ let nextTick;
367
+ if (typeof prevSponsorTick === "bigint" || typeof curSponsorTick === "bigint") nextTick = [prevSponsorTick, curSponsorTick].filter((v) => typeof v === "bigint").reduce((acc, v) => v > acc ? v : acc, 0n) + 1n;
368
+ else {
369
+ const prevNum = typeof prevSponsorTick === "number" ? prevSponsorTick : 0;
370
+ const curNum = typeof curSponsorTick === "number" ? curSponsorTick : 0;
371
+ nextTick = Math.max(prevNum, curNum) + 1;
372
+ }
373
+ Object.defineProperty(nextSponsorState, "_retrievedAt", {
374
+ value: nextTick,
375
+ enumerable: false,
376
+ writable: true,
377
+ configurable: true
378
+ });
379
+ }
380
+ }
344
381
  context.sponsorState = nextSponsorState;
345
382
  }
346
383
  let feeVaultState = null;
@@ -61,11 +61,26 @@ const WriteLedger = async (context, next) => {
61
61
  return next();
62
62
  }
63
63
  try {
64
+ const verifiedCtx = context;
65
+ const evaluatedByPipeline = verifiedCtx._ensureTxCostEvaluated === true;
66
+ let canonicalGasHeaders;
67
+ if (evaluatedByPipeline) canonicalGasHeaders = verifiedCtx._verifiedGasStakeHeaders;
68
+ else if (extra?.gasStakeHeaders && typeof extra.gasStakeHeaders === "object" && !Array.isArray(extra.gasStakeHeaders)) {
69
+ const hdr = extra.gasStakeHeaders;
70
+ if (typeof hdr.token === "string" && hdr.token.length > 0 && typeof hdr.pk === "string" && hdr.pk.length > 0) canonicalGasHeaders = {
71
+ token: hdr.token,
72
+ pk: hdr.pk
73
+ };
74
+ }
75
+ const canonicalCoSig = evaluatedByPipeline ? verifiedCtx._verifiedCoSignature : extra?.coSignature && typeof extra.coSignature === "object" && !Array.isArray(extra.coSignature) ? extra.coSignature : void 0;
76
+ const canonicalGasPass = evaluatedByPipeline ? verifiedCtx._verifiedGasPass : extra?.gasPass && typeof extra.gasPass === "object" && !Array.isArray(extra.gasPass) ? extra.gasPass : void 0;
64
77
  let txExtra;
65
- if (extra?.txExtra || extra?.gasStakeHeaders) {
78
+ if (extra?.txExtra || canonicalGasHeaders || canonicalCoSig || canonicalGasPass) {
66
79
  txExtra = {};
67
- if (extra.txExtra) txExtra.txExtra = extra.txExtra;
68
- if (extra.gasStakeHeaders) txExtra.gasStakeHeaders = extra.gasStakeHeaders;
80
+ if (extra?.txExtra) txExtra.txExtra = extra.txExtra;
81
+ if (canonicalGasHeaders) txExtra.gasStakeHeaders = canonicalGasHeaders;
82
+ if (canonicalCoSig) txExtra.coSignature = canonicalCoSig;
83
+ if (canonicalGasPass) txExtra.gasPass = canonicalGasPass;
69
84
  }
70
85
  const formattedTx = stripDefaultDepositV2BridgeFieldsInTx(formatMessage("Transaction", tx));
71
86
  const txInput = {
@@ -10,6 +10,7 @@ import { BN, isSameDid } from "@ocap/util";
10
10
  /**
11
11
  * `create_rollup` for a v2 bridge (bridge/docs/ocap-protocols.md §v2.2, row `create_rollup`).
12
12
  */
13
+ const ZERO_ETH_ADDRESS = "0x0000000000000000000000000000000000000000";
13
14
  const isHttpUrl = (s) => {
14
15
  try {
15
16
  return typeof s === "string" && ["http:", "https:"].includes(new URL(s).protocol);
@@ -32,11 +33,15 @@ async function verifyBridgeCreate(context, next) {
32
33
  if (!isEthereumDid(owner)) return next(new CustomError("INVALID_TX", "The bridge owner must use an ethereum compatible address"));
33
34
  const seeds = context.seedValidators;
34
35
  if (!seeds || seeds.length !== 1 || !rollup.sameAddress(seeds[0], owner)) return next(new CustomError("INVALID_TX", "seed_validators of a v2 bridge must be the bridge owner alone"));
35
- if (!rollup.isValidRollupContractAddress(itx.contractAddress, "EVM")) return next(new CustomError("INVALID_TX", "contractAddress must be an ethereum token address"));
36
- if (itx.vaultAddress && !rollup.isValidRollupVaultAddress(itx.vaultAddress, "EVM")) return next(new CustomError("INVALID_TX", "vaultAddress must be an ethereum address"));
36
+ if (typeof itx.contractAddress !== "string" || itx.contractAddress !== itx.contractAddress.trim() || !rollup.isValidRollupContractAddress(itx.contractAddress, "EVM")) return next(new CustomError("INVALID_TX", "contractAddress must be an ethereum token address"));
37
+ if (!itx.vaultAddress || typeof itx.vaultAddress !== "string" || itx.vaultAddress !== itx.vaultAddress.trim() || !rollup.isValidRollupVaultAddress(itx.vaultAddress, "EVM")) return next(new CustomError("INVALID_TX", "vaultAddress must be an ethereum address"));
37
38
  if (!(itx.minBlockConfirmation >= 1 && itx.minBlockConfirmation <= 100)) return next(new CustomError("INVALID_TX", "minBlockConfirmation must be between 1 and 100"));
38
- const ethToken = String(itx.contractAddress).toLowerCase();
39
39
  const { body } = input;
40
+ const ethToken = rollup.bareEthAddress(itx.contractAddress);
41
+ const ethVault = rollup.bareEthAddress(itx.vaultAddress);
42
+ const ethGateway = rollup.bareEthAddress(body.gateway);
43
+ if (ethToken === ZERO_ETH_ADDRESS || ethToken === ethGateway) return next(new CustomError("INVALID_TX", "contractAddress must be a non-zero ethereum token address distinct from gateway"));
44
+ if (ethVault === ZERO_ETH_ADDRESS || ethVault === ethToken || ethVault === ethGateway) return next(new CustomError("INVALID_TX", "vaultAddress must be a non-zero ethereum address distinct from contractAddress and gateway"));
40
45
  const epoch1 = body.epochs[0];
41
46
  const consents = input.consents;
42
47
  if (consents.length !== epoch1.validators.length) return next(new CustomError("INVALID_SIGNATURE", "Every initial validator must sign a BridgeMembership consent"));
@@ -0,0 +1,7 @@
1
+ import { OcapGovernanceProposal } from "@ocap/mcrypto";
2
+
3
+ //#region src/protocols/rollup/bridge-governance-tx-binding.d.ts
4
+ type Ctx = any;
5
+ declare function verifyOcapProposalTxBinding(context: Ctx, proposal: OcapGovernanceProposal): Promise<void>;
6
+ //#endregion
7
+ export { verifyOcapProposalTxBinding };