@ocap/tx-protocols 1.31.0 → 1.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/execute.d.mts CHANGED
@@ -2,9 +2,11 @@ import { ITxGasQuotaTelemetry, ITxSecurityWarning } from "./gas-security-guard.m
2
2
  import { TxTimer } from "./tx-timer.mjs";
3
3
  import { Blacklist } from "@ocap/state";
4
4
  import { CustomError } from "@ocap/util/lib/error";
5
- import { IAccountState, IGasContext } from "@ocap/types";
5
+ import { IAccountState, IBaseContext, IGasContext } from "@ocap/types";
6
6
 
7
7
  //#region src/execute.d.ts
8
+ declare const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL: symbol;
9
+ declare const tryApplyPreFlightVerifiedSnapshot: (context: IBaseContext) => boolean;
8
10
  /** State helpers interface */
9
11
  interface IStateHelpers {
10
12
  tx: {
@@ -69,4 +71,4 @@ declare const createExecute: ({
69
71
  runAsLambda
70
72
  }: IExecuteOptions) => ExecuteFn;
71
73
  //#endregion
72
- export { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, createExecute as default, toUnsignedEvidenceKey };
74
+ export { PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, createExecute as default, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot };
package/esm/execute.mjs CHANGED
@@ -1,14 +1,16 @@
1
- import { classifyErrorStrikeCategory, recordActorSecurityStrike, resolveVerifiedStrikeActors, restoreActorSecurityRecords, snapshotActorSecurityRecords } from "./gas-security-guard.mjs";
1
+ import { classifyErrorStrikeCategory, evaluateStakeForGasEligibility, extractTransactionTargets, normalizeShortTxType, recordActorSecurityStrike, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
2
+ import { getRewardLocker, isGasStakeAddress, isGasStakeInput, isGasStakeValid } from "./util.mjs";
2
3
  import ensure_cost_default from "./pipes/ensure-cost.mjs";
3
4
  import ensure_gas_default from "./pipes/ensure-gas.mjs";
4
5
  import { WriteLedger } from "./pipes/write-ledger.mjs";
5
6
  import { TxTimer } from "./tx-timer.mjs";
6
- import { toTypeInfo } from "@arcblock/did";
7
- import { toDelegateAddress } from "@arcblock/did-util";
7
+ import { isFromPublicKey, toAddress, toTypeInfo } from "@arcblock/did";
8
+ import { toDelegateAddress, toStakeAddress } from "@arcblock/did-util";
9
+ import * as JWT from "@arcblock/jwt";
8
10
  import { toTxHash, types } from "@ocap/mcrypto";
9
11
  import { account, evidence, parseNonceBn } from "@ocap/state";
10
12
  import { Runner, inspectPostExecutionInvariants, installStateWriteInterceptor, pipes, rollbackTrackedStateWrites, verifyImplicitAssetOwnership } from "@ocap/tx-pipeline";
11
- import { BN, isSameDid } from "@ocap/util";
13
+ import { BN, fromTokenToUnit, isSameDid, toBase58, toBase64, toBuffer } from "@ocap/util";
12
14
  import { CustomError } from "@ocap/util/lib/error";
13
15
  import { getListField } from "@ocap/util/lib/get-list-field";
14
16
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
@@ -19,6 +21,20 @@ import merge from "lodash/merge.js";
19
21
  import pick from "lodash/pick.js";
20
22
 
21
23
  //#region src/execute.ts
24
+ const ZERO = new BN(0);
25
+ const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = pipes.PreFlightWaf.SNAPSHOT_SYMBOL || Symbol.for("@ocap/tx-pipeline/preFlightVerifiedSnapshot");
26
+ const tryApplyPreFlightVerifiedSnapshot = (context) => {
27
+ const fn = pipes.PreFlightWaf.tryApplyVerifiedSnapshot;
28
+ return typeof fn === "function" ? fn(context) : false;
29
+ };
30
+ function isMatchingAccountPublicKey(onChainPk, headerPk) {
31
+ if (onChainPk === headerPk) return true;
32
+ try {
33
+ const headerBuf = toBuffer(headerPk);
34
+ if (toBase58(headerBuf) === onChainPk || toBase64(headerBuf) === onChainPk) return true;
35
+ } catch {}
36
+ return false;
37
+ }
22
38
  const ensureTxGas = ensure_gas_default(() => ({
23
39
  create: 0,
24
40
  update: 2
@@ -65,6 +81,29 @@ const MULTISIG_DELEGATION_TX_TYPES = new Set([
65
81
  "fg:t:exchange_v2",
66
82
  "fg:t:transfer_v3"
67
83
  ]);
84
+ /** Zero-stake onboarding transaction types permitted from a non-existent sender within free-gas size ceilings. */
85
+ const ONBOARDING_FREE_TX_TYPES = new Set([
86
+ "declare",
87
+ "poke",
88
+ "faucet"
89
+ ]);
90
+ /**
91
+ * Transaction types whose protocol pipeline uses `status: 'OK'` on `ExtractState({ from: 'tx.from', to: 'senderState' })`
92
+ * and can therefore execute when `tx.from` has no `statedb.account` row (and is not an existing `ROLE_ASSET`).
93
+ */
94
+ const NON_EXISTENT_SENDER_CAPABLE_TX_TYPES = new Set([
95
+ "declare",
96
+ "poke",
97
+ "faucet",
98
+ "delegate",
99
+ "account_migrate",
100
+ "acquire_asset_v3",
101
+ "stake",
102
+ "burn_token",
103
+ "mint_token",
104
+ "deposit_token_v2",
105
+ "transfer_v3"
106
+ ]);
68
107
  const shouldPersistTx = (err, context) => {
69
108
  if (!err) return true;
70
109
  if (!get(err, "props.persist")) return false;
@@ -156,16 +195,441 @@ const createExecute = ({ filter, runAsLambda }) => {
156
195
  * - Sender migrated (statedb resolves `tx.from` to its successor): reject like
157
196
  * VerifyAccountMigration, but before the ledger write.
158
197
  */
198
+ /**
199
+ * Pre-ledger admission check for non-existent senders (#1359).
200
+ *
201
+ * When `tx.from` has no account in `statedb.account`, it cannot pay direct gas or service fees
202
+ * from `senderState`. Rejecting unpaid or unexecutable transactions from non-existent senders before
203
+ * `WriteLedger` prevents unauthenticated actors from appending uncompensated entries to the immutable
204
+ * ledger for free.
205
+ */
206
+ const estimatePreLedgerGasOps = async (context, shortTxType, from, statedb, isExistingAssetSender) => {
207
+ const itx = context.itx || {};
208
+ const accountStore = statedb?.account;
209
+ const inputs = getListField(itx, "inputs") || [];
210
+ const uniqueInputOwners = Array.from(new Set(inputs.map((inp) => typeof inp?.owner === "string" ? inp.owner : "").filter(Boolean)));
211
+ const uniqueInputAssets = Array.from(new Set(inputs.flatMap((inp) => getListField(inp, "assets") || []).filter((a) => typeof a === "string" && a.length > 0)));
212
+ switch (shortTxType) {
213
+ case "declare": return {
214
+ create: 1,
215
+ update: 0,
216
+ isGasSelfStakeTx: false
217
+ };
218
+ case "poke": return {
219
+ create: 1,
220
+ update: 1,
221
+ isGasSelfStakeTx: false
222
+ };
223
+ case "faucet": return {
224
+ create: 0,
225
+ update: 1,
226
+ isGasSelfStakeTx: false
227
+ };
228
+ case "account_migrate": return {
229
+ create: 2,
230
+ update: 0,
231
+ isGasSelfStakeTx: false
232
+ };
233
+ case "delegate": {
234
+ const result = {
235
+ create: 0,
236
+ update: 1,
237
+ isGasSelfStakeTx: false
238
+ };
239
+ const toAddr = typeof itx.to === "string" ? itx.to : "";
240
+ if (Boolean(toAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context))) result.update += 1;
241
+ else result.create += 1;
242
+ const delAddr = typeof itx.address === "string" ? itx.address : "";
243
+ if (Boolean(delAddr) && typeof statedb?.delegation?.get === "function" && Boolean(await statedb.delegation.get(delAddr, context))) result.update += 1;
244
+ else result.create += 1;
245
+ return result;
246
+ }
247
+ case "deposit_token_v2": {
248
+ const result = {
249
+ create: 2,
250
+ update: 1,
251
+ isGasSelfStakeTx: false
252
+ };
253
+ const proposer = typeof itx.proposer === "string" ? itx.proposer : "";
254
+ const toAddr = typeof itx.to === "string" ? itx.to : "";
255
+ if (proposer === from && toAddr && toAddr !== from) if (typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context))) result.update += 1;
256
+ else result.create += 1;
257
+ const rollupAddr = typeof itx.rollup === "string" ? itx.rollup : "";
258
+ if (Boolean(rollupAddr) && typeof statedb?.stake?.get === "function" && Boolean(await statedb.stake.get(getRewardLocker(rollupAddr), context))) result.update += 1;
259
+ else result.create += 1;
260
+ return result;
261
+ }
262
+ case "acquire_asset_v3": {
263
+ const result = {
264
+ create: 1,
265
+ update: 2 + uniqueInputOwners.length + uniqueInputAssets.length,
266
+ isGasSelfStakeTx: false
267
+ };
268
+ const ownerAddr = typeof itx.owner === "string" ? itx.owner : "";
269
+ if (!(Boolean(ownerAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(ownerAddr, context)))) result.create += 1;
270
+ return result;
271
+ }
272
+ case "transfer_v3": {
273
+ const result = {
274
+ create: 1,
275
+ update: uniqueInputOwners.length + uniqueInputAssets.length,
276
+ isGasSelfStakeTx: false
277
+ };
278
+ const outputs = getListField(itx, "outputs") || [];
279
+ const uniqueReceivers = Array.from(new Set(outputs.map((out) => typeof out?.owner === "string" ? out.owner : "").filter(Boolean)));
280
+ for (const r of uniqueReceivers) if (typeof accountStore?.get === "function" && Boolean(await accountStore.get(r, context))) result.update += 1;
281
+ else result.create += 1;
282
+ return result;
283
+ }
284
+ case "mint_token":
285
+ case "burn_token": {
286
+ const result = {
287
+ create: 1,
288
+ update: 2 + uniqueInputOwners.length,
289
+ isGasSelfStakeTx: false
290
+ };
291
+ const receiverAddr = typeof itx.receiver === "string" ? itx.receiver : "";
292
+ if (Boolean(receiverAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(receiverAddr, context))) result.update += 1;
293
+ else result.create += 1;
294
+ if (itx.reserveFee && /^\d+$/.test(String(itx.reserveFee)) && new BN(String(itx.reserveFee)).gt(ZERO)) result.update += 1;
295
+ return result;
296
+ }
297
+ case "stake": {
298
+ const stakeAddr = typeof itx.address === "string" ? itx.address : "";
299
+ const normalizedInputs = inputs.map((inp) => ({
300
+ assetsList: getListField(inp, "assets") || [],
301
+ tokensList: getListField(inp, "tokens") || []
302
+ }));
303
+ const officialTok = context.config?.token?.address || "";
304
+ if (stakeAddr && officialTok && isGasStakeAddress(from, stakeAddr) && isGasStakeInput(normalizedInputs, officialTok)) return {
305
+ create: 0,
306
+ update: 0,
307
+ isGasSelfStakeTx: true
308
+ };
309
+ const result = {
310
+ create: 1,
311
+ update: uniqueInputOwners.length + uniqueInputAssets.length,
312
+ isGasSelfStakeTx: false
313
+ };
314
+ if (Boolean(stakeAddr) && typeof statedb?.stake?.get === "function" && Boolean(await statedb.stake.get(stakeAddr, context))) result.update += 1;
315
+ else result.create += 1;
316
+ return result;
317
+ }
318
+ default:
319
+ if (shortTxType === "create_asset" || shortTxType === "create_factory" || shortTxType === "create_token" || shortTxType === "create_token_factory" || shortTxType === "create_rollup") return {
320
+ create: 1,
321
+ update: 2,
322
+ isGasSelfStakeTx: false
323
+ };
324
+ if (shortTxType === "transfer_v2" || shortTxType === "transfer") {
325
+ const toAddr = typeof itx.to === "string" ? itx.to : "";
326
+ const hasReceiver = Boolean(toAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context));
327
+ const assetsList = getListField(itx, "assets") || [];
328
+ return {
329
+ create: hasReceiver ? 0 : 1,
330
+ update: (isExistingAssetSender ? 1 : 0) + (hasReceiver ? 1 : 0) + assetsList.length,
331
+ isGasSelfStakeTx: false
332
+ };
333
+ }
334
+ return {
335
+ create: 0,
336
+ update: 2,
337
+ isGasSelfStakeTx: false
338
+ };
339
+ }
340
+ };
341
+ const assertNonExistentSenderAdmissible = async (context) => {
342
+ const from = context.tx?.from;
343
+ const statedb = context.statedb;
344
+ const accountStore = statedb?.account;
345
+ if (!from || !context.ledger || typeof accountStore?.get !== "function") return;
346
+ if (context.tx?.delegator) {
347
+ if (!await accountStore.get(context.tx.delegator, context)) throw new CustomError("INVALID_DELEGATION", "No delegation found between sender and delegator", { persist: false });
348
+ }
349
+ const isExistingAssetSender = toTypeInfo(from).role === types.RoleType.ROLE_ASSET && typeof statedb?.asset?.get === "function" && Boolean(await statedb.asset.get(from, context));
350
+ const config = context.config;
351
+ const txType = context.txType;
352
+ const shortTxType = normalizeShortTxType(txType);
353
+ const assertProtocolAdmissibleWithoutSenderState = async () => {
354
+ if (!isExistingAssetSender && !NON_EXISTENT_SENDER_CAPABLE_TX_TYPES.has(shortTxType)) throw new CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
355
+ if (shortTxType === "transfer_v3" || shortTxType === "stake" || shortTxType === "burn_token" || shortTxType === "mint_token" || shortTxType === "acquire_asset_v3") {
356
+ const inputs = getListField(context.itx, "inputs") || [];
357
+ if ((shortTxType === "transfer_v3" || shortTxType === "stake" || shortTxType === "burn_token") && inputs.length === 0) throw new CustomError("INVALID_TX", "Invalid itx: inputs must not be empty", { persist: false });
358
+ for (const inp of inputs) {
359
+ if (!inp?.owner) throw new CustomError("INVALID_TX", "Invalid itx: input owner is required", { persist: false });
360
+ if (!(Boolean(await accountStore.get(inp.owner, context)) || toTypeInfo(inp.owner).role === types.RoleType.ROLE_ASSET && typeof statedb?.asset?.get === "function" && Boolean(await statedb.asset.get(inp.owner, context)))) throw new CustomError("INVALID_SIGNER_STATE", `Invalid state extracted for ACCOUNT: ${inp.owner}`, { persist: false });
361
+ }
362
+ } else if (shortTxType === "deposit_token_v2") {
363
+ const signatures = getListField(context.tx, "signatures") || [];
364
+ if (signatures.length === 0) throw new CustomError("INVALID_TX", "itx.proposer must exist in signatures", { persist: false });
365
+ for (const sig of signatures) if (!sig?.signer || !await accountStore.get(sig.signer, context)) throw new CustomError("INVALID_SIGNER_STATE", `Invalid state extracted for ACCOUNT: ${sig?.signer || ""}`, { persist: false });
366
+ }
367
+ };
368
+ const txFeeMap = config?.transaction?.txFee || {};
369
+ const rawTxFee = txType ? txFeeMap[txType] : void 0;
370
+ const feeCost = typeof rawTxFee === "number" && rawTxFee > 0 && Boolean(config?.token?.decimal) ? fromTokenToUnit(rawTxFee, config.token.decimal) : ZERO;
371
+ const txGasCfg = config?.transaction?.txGas;
372
+ const gasPriceRaw = txGasCfg?.price;
373
+ const gasPrice = txGasCfg?.enabled !== false && gasPriceRaw !== void 0 && gasPriceRaw !== null && /^\d+$/.test(String(gasPriceRaw)) ? new BN(String(gasPriceRaw)) : ZERO;
374
+ const estimatedOps = await estimatePreLedgerGasOps(context, shortTxType, from, statedb, isExistingAssetSender);
375
+ const gasEstimate = {
376
+ create: estimatedOps.create,
377
+ update: estimatedOps.update
378
+ };
379
+ const estimatedTotalGas = Boolean(context.txBaseGas) && !estimatedOps.isGasSelfStakeTx && gasPrice.gt(ZERO) ? gasPrice.mul(new BN(txGasCfg?.dataStorage || 0)).mul(new BN(context.txSize || 0)).add(gasPrice.mul(new BN(txGasCfg?.createState || 0)).mul(new BN(estimatedOps.create + 1))).add(gasPrice.mul(new BN(txGasCfg?.updateState || 0)).mul(new BN(estimatedOps.update))) : ZERO;
380
+ const requiresGasPayment = estimatedTotalGas.gt(ZERO);
381
+ const txSize = context._baseTxSize ?? context.txSize;
382
+ const secCfg = resolveGasSecurityConfig(config);
383
+ if (feeCost.lte(ZERO)) {
384
+ if (!requiresGasPayment) {
385
+ await assertProtocolAdmissibleWithoutSenderState();
386
+ return;
387
+ }
388
+ if (ONBOARDING_FREE_TX_TYPES.has(shortTxType) && (txSize || 0) <= secCfg.maxFreeGasTxSize) {
389
+ await assertProtocolAdmissibleWithoutSenderState();
390
+ return;
391
+ }
392
+ }
393
+ const extra = context.extra || {};
394
+ const txExtra = extra.txExtra && typeof extra.txExtra === "object" ? extra.txExtra : void 0;
395
+ const { token: token$1, pk } = extra.gasStakeHeaders || {};
396
+ const rawGasPass = extra.gasPass || txExtra?.gasPass;
397
+ const txHash = context.txHash || "";
398
+ const txTime = context.txTime;
399
+ const nowMs = txTime ? +new Date(txTime) : Date.now();
400
+ const officialTok = config?.token?.address || "";
401
+ const resolveSelfGasStake = async () => {
402
+ if (!officialTok || typeof statedb?.stake?.get !== "function") return {
403
+ hasSelfStake: false,
404
+ state: null,
405
+ valid: false
406
+ };
407
+ const candidates = Array.from(new Set([from, context.tx?.delegator].filter(Boolean)));
408
+ for (const candidate of candidates) {
409
+ const stakeId = toStakeAddress(candidate, candidate);
410
+ const selfStake = await statedb.stake.get(stakeId, context);
411
+ if (new BN(selfStake?.tokens?.[officialTok] || 0).gt(ZERO)) return {
412
+ hasSelfStake: true,
413
+ state: selfStake,
414
+ valid: isGasStakeValid(selfStake, config)
415
+ };
416
+ }
417
+ return {
418
+ hasSelfStake: false,
419
+ state: null,
420
+ valid: false
421
+ };
422
+ };
423
+ if (feeCost.lte(ZERO)) {
424
+ if (rawGasPass) {
425
+ const passStakeState = rawGasPass.stakeId && typeof statedb?.stake?.get === "function" ? await statedb.stake.get(rawGasPass.stakeId, context) : null;
426
+ const passResult = verifyAndConsumeUnlinkableGasPass({
427
+ gasPass: rawGasPass,
428
+ stakeState: passStakeState,
429
+ txHash,
430
+ nowMs,
431
+ config,
432
+ statedb,
433
+ consumeNullifier: false
434
+ });
435
+ if (!passResult.valid) {
436
+ const passErr = new CustomError(passResult.reason || "INVALID_GAS_PASS", `Invalid unlinkable gas pass: ${passResult.reason}`, { persist: false });
437
+ passErr._unauthenticatedExtraFailure = true;
438
+ throw passErr;
439
+ }
440
+ const passOwner = passStakeState?.sender || rawGasPass.stakeId;
441
+ const isThirdPartyGasPass = Boolean(passOwner && !isSameDid(passOwner, from) && (!context.tx?.delegator || !isSameDid(passOwner, context.tx.delegator)));
442
+ const selfStakeInfo = isThirdPartyGasPass ? await resolveSelfGasStake() : null;
443
+ const selfStakeEligible = Boolean(selfStakeInfo?.valid) && evaluateStakeForGasEligibility({
444
+ txType,
445
+ txSize,
446
+ gasEstimate,
447
+ isFailedTxGasCharge: false,
448
+ isThirdPartySponsor: false,
449
+ enforceSponsor3DEligibility: false,
450
+ config
451
+ }).eligible;
452
+ const effectiveStakeState = selfStakeInfo?.valid && selfStakeEligible ? selfStakeInfo.state : passStakeState;
453
+ const eligibility = evaluateStakeForGasEligibility({
454
+ txType,
455
+ txSize,
456
+ gasEstimate,
457
+ isFailedTxGasCharge: false,
458
+ isThirdPartySponsor: selfStakeInfo?.valid && selfStakeEligible ? false : isThirdPartyGasPass,
459
+ enforceSponsor3DEligibility: false,
460
+ config
461
+ });
462
+ if (isGasStakeValid(effectiveStakeState, config) && eligibility.eligible) {
463
+ await assertProtocolAdmissibleWithoutSenderState();
464
+ return;
465
+ }
466
+ } else if (token$1 && pk) {
467
+ let decoded = {};
468
+ let sponsorAddress = "";
469
+ let issuerMatchesPk = false;
470
+ try {
471
+ if (typeof token$1 === "string" && typeof pk === "string") {
472
+ decoded = JWT.decode(token$1) || {};
473
+ sponsorAddress = toAddress(decoded.iss || "");
474
+ issuerMatchesPk = Boolean(sponsorAddress && isFromPublicKey(sponsorAddress, pk));
475
+ }
476
+ } catch {
477
+ issuerMatchesPk = false;
478
+ }
479
+ if (!issuerMatchesPk) {
480
+ const hdrErr = new CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT issuer does not match signer public key", { persist: false });
481
+ hdrErr._unauthenticatedExtraFailure = true;
482
+ throw hdrErr;
483
+ }
484
+ let jwtVerified = false;
485
+ try {
486
+ jwtVerified = Boolean(await JWT.verify(token$1, pk, {
487
+ enforceTimestamp: !txTime,
488
+ tolerance: 5
489
+ }));
490
+ } catch {
491
+ jwtVerified = false;
492
+ }
493
+ if (jwtVerified) {
494
+ const toleranceSec = 5;
495
+ const nowSec = txTime ? Math.floor(+new Date(txTime) / 1e3) : Math.floor(Date.now() / 1e3);
496
+ const expNum = decoded?.exp != null && decoded.exp !== "" ? Number(decoded.exp) : NaN;
497
+ const expValid = Number.isFinite(expNum) && expNum > 0 && expNum + toleranceSec >= nowSec;
498
+ const nbfNum = decoded?.nbf != null && decoded.nbf !== "" ? Number(decoded.nbf) : NaN;
499
+ const nbfValid = decoded?.nbf == null || decoded.nbf === "" || Number.isFinite(nbfNum) && nbfNum - toleranceSec <= nowSec;
500
+ const iatNum = decoded?.iat != null && decoded.iat !== "" ? Number(decoded.iat) : NaN;
501
+ const iatValid = decoded?.iat == null || decoded.iat === "" || Number.isFinite(iatNum) && iatNum - toleranceSec <= nowSec;
502
+ const txHashes = (decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean);
503
+ if (expValid && nbfValid && iatValid && txHashes.includes(txHash)) {
504
+ const sponsorState = await accountStore.get(sponsorAddress, {
505
+ ...context,
506
+ traceMigration: false
507
+ });
508
+ if (sponsorState?.pk && !isMatchingAccountPublicKey(sponsorState.pk, pk)) {
509
+ const pkErr = new CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT signer public key does not match on-chain sponsor account", { persist: false });
510
+ pkErr._unauthenticatedExtraFailure = true;
511
+ throw pkErr;
512
+ }
513
+ const isSponsorMigrated = Array.isArray(sponsorState?.migratedTo) && sponsorState.migratedTo.length > 0;
514
+ const sponsorAddresses = getRelatedAddresses(sponsorState || { address: sponsorAddress });
515
+ const checkBlocked = async (checker, addr) => {
516
+ if (typeof checker?.isBlocked !== "function") return false;
517
+ if (await Promise.resolve(checker.isBlocked(addr))) return true;
518
+ return Boolean(await Promise.resolve(checker.isBlocked([addr])));
519
+ };
520
+ let isSponsorBlocked = false;
521
+ for (const addr of sponsorAddresses) if (await checkBlocked(filter, addr) || await checkBlocked(statedb?.blacklist, addr)) {
522
+ isSponsorBlocked = true;
523
+ break;
524
+ }
525
+ if (!isSponsorMigrated && !isSponsorBlocked) {
526
+ const sponsorStakeId = toStakeAddress(sponsorAddress, sponsorAddress);
527
+ const isDirectMode = decoded.mode === "paymaster" || decoded.chargeSponsorBalance === true;
528
+ const sponsorStakeState = !isDirectMode && typeof statedb?.stake?.get === "function" ? await statedb.stake.get(sponsorStakeId, context) : null;
529
+ const minSponsorBalance = estimatedTotalGas.gt(ZERO) ? estimatedTotalGas : new BN(1);
530
+ const sponsorIsBacked = isDirectMode ? Boolean(sponsorState && officialTok && new BN(sponsorState.tokens?.[officialTok] || 0).gte(minSponsorBalance)) : isGasStakeValid(sponsorStakeState, config);
531
+ const paymasterCheck = verifyPaymasterConstraints({
532
+ decoded,
533
+ tx: context.tx,
534
+ itx: context.itx,
535
+ txType,
536
+ totalGas: estimatedTotalGas
537
+ });
538
+ if (!paymasterCheck.valid) {
539
+ const pmErr = new CustomError(paymasterCheck.reason || "PAYMASTER_VIOLATION", `Paymaster sponsorship constraint violated: ${paymasterCheck.reason}`, { persist: false });
540
+ pmErr._strikeRecorded = true;
541
+ pmErr._unauthenticatedExtraFailure = true;
542
+ throw pmErr;
543
+ }
544
+ if (paymasterCheck.isPaymasterDirectCharge) {
545
+ const txTargets = extractTransactionTargets(context.tx, context.itx, txType);
546
+ if ([
547
+ from,
548
+ context.tx?.delegator,
549
+ context.gasVault,
550
+ context.feeVault,
551
+ config?.vaults?.txFee,
552
+ ...Array.isArray(config?.vaults?.txGas) ? config.vaults.txGas : [],
553
+ ...Array.isArray(config?.vaults?.txFees) ? config.vaults.txFees : [],
554
+ ...txTargets
555
+ ].filter(Boolean).some((candidate) => isSameDid(sponsorAddress, candidate) || sponsorAddress === candidate)) {
556
+ const aliasErr = new CustomError("PAYMASTER_SPONSOR_ALIAS_FORBIDDEN", "Paymaster direct-charge sponsor cannot alias transaction sender, delegator, target, or vault", { persist: false });
557
+ aliasErr._unauthenticatedExtraFailure = true;
558
+ throw aliasErr;
559
+ }
560
+ }
561
+ const selfStakeInfo = await resolveSelfGasStake();
562
+ const selfStakeEligible = Boolean(selfStakeInfo.valid) && evaluateStakeForGasEligibility({
563
+ txType,
564
+ txSize,
565
+ gasEstimate,
566
+ isFailedTxGasCharge: false,
567
+ isThirdPartySponsor: false,
568
+ enforceSponsor3DEligibility: false,
569
+ config
570
+ }).eligible;
571
+ if (selfStakeInfo.valid && selfStakeEligible) {
572
+ await assertProtocolAdmissibleWithoutSenderState();
573
+ return;
574
+ }
575
+ if (!sponsorIsBacked && selfStakeInfo.hasSelfStake) {} else if (paymasterCheck.isPaymasterDirectCharge) {
576
+ if (sponsorIsBacked) {
577
+ await assertProtocolAdmissibleWithoutSenderState();
578
+ return;
579
+ }
580
+ } else {
581
+ const eligibility = evaluateStakeForGasEligibility({
582
+ txType,
583
+ txSize,
584
+ gasEstimate,
585
+ isFailedTxGasCharge: false,
586
+ isThirdPartySponsor: true,
587
+ enforceSponsor3DEligibility: decoded.enforce3DEligibility === true || (config?.transaction?.txGas)?.enforceSponsor3DEligibility === true,
588
+ config
589
+ });
590
+ if (isGasStakeValid(sponsorStakeState, config) && eligibility.eligible) {
591
+ await assertProtocolAdmissibleWithoutSenderState();
592
+ return;
593
+ }
594
+ }
595
+ }
596
+ }
597
+ }
598
+ }
599
+ if (officialTok && typeof statedb?.stake?.get === "function") {
600
+ const directStakeId = toStakeAddress(from, from);
601
+ if (isGasStakeValid(await statedb.stake.get(directStakeId, context), config)) {
602
+ if (evaluateStakeForGasEligibility({
603
+ txType,
604
+ txSize,
605
+ gasEstimate,
606
+ isFailedTxGasCharge: false,
607
+ isThirdPartySponsor: false,
608
+ enforceSponsor3DEligibility: false,
609
+ config
610
+ }).eligible) {
611
+ await assertProtocolAdmissibleWithoutSenderState();
612
+ return;
613
+ }
614
+ }
615
+ }
616
+ }
617
+ if (isExistingAssetSender) throw new CustomError("INSUFFICIENT_FUND", `Insufficient fund to pay for tx cost from ${from}`, { persist: false });
618
+ if (txType === "fg:t:account_migrate" || Boolean(token$1 || pk) || Boolean(rawGasPass)) throw new CustomError("INVALID_GAS_PAYER", `Gas payer ${from} does not exist on chain`, { persist: false });
619
+ if (!NON_EXISTENT_SENDER_CAPABLE_TX_TYPES.has(shortTxType)) throw new CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
620
+ throw new CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
621
+ };
159
622
  const assertSenderNonceFresh = async (context) => {
160
623
  const from = context.tx?.from;
161
624
  const accountStore = context.statedb?.account;
162
- if (!from || typeof accountStore?.get !== "function") return;
625
+ if (!from || typeof accountStore?.get !== "function") return null;
163
626
  const senderState = await accountStore.get(from, context);
164
- if (!senderState) return;
627
+ if (!senderState) return null;
165
628
  if (senderState.address !== from && senderState.address !== account.ensureChecksumAddress(from)) throw new CustomError("ACCOUNT_MIGRATED", `account ${from} is migrated`);
166
629
  const incomingNonceBn = parseNonceBn(context.tx?.nonce);
167
630
  const currentNonceBn = parseNonceBn(senderState.nonce) ?? new BN(0);
168
631
  if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn)) throw new CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
632
+ return senderState;
169
633
  };
170
634
  /**
171
635
  * Pre-ledger delegation authorization check, run under the pre-write lock BEFORE WriteLedger.
@@ -218,14 +682,46 @@ const createExecute = ({ filter, runAsLambda }) => {
218
682
  }
219
683
  };
220
684
  const pre = new Runner("pre-execute");
221
- pre.use(pipes.DecodeTx);
685
+ pre.use((context, next) => {
686
+ context._preFlightSnapshotApplied = false;
687
+ if (tryApplyPreFlightVerifiedSnapshot(context)) {
688
+ context._preFlightSnapshotApplied = true;
689
+ return next();
690
+ }
691
+ return pipes.DecodeTx(context, next);
692
+ });
222
693
  pre.use(pipes.VerifyBlocked({
223
694
  filter,
224
695
  stateKeys: ["tx.from"]
225
696
  }));
226
- pre.use(pipes.DecodeItx);
227
- pre.use(pipes.VerifyTx);
228
- pre.use(pipes.VerifyServiceFee);
697
+ pre.use((context, next) => {
698
+ if (context._preFlightSnapshotApplied) {
699
+ context.logger?.info("Tx decoded", {
700
+ txBase64: context.txBase64,
701
+ txHash: context.txHash,
702
+ txTime: context.txTime,
703
+ txSize: context.txSize,
704
+ txType: context.txType,
705
+ request: context.extra?.request
706
+ });
707
+ context.timer?.mark?.("decode");
708
+ return next();
709
+ }
710
+ return pipes.DecodeItx(context, next);
711
+ });
712
+ pre.use((context, next) => {
713
+ if (context._preFlightSnapshotApplied) return next();
714
+ return pipes.VerifyTx(context, next);
715
+ });
716
+ pre.use((context, next) => {
717
+ const protocolsMap = context._protocols;
718
+ if (protocolsMap && context.txType && !protocolsMap[getTxName(context.txType)]) return next(new CustomError("UNSUPPORTED_TX", `Unsupported tx type ${context.txType}`, { persist: false }));
719
+ return next();
720
+ });
721
+ pre.use((context, next) => {
722
+ if (context._preFlightSnapshotApplied) return next();
723
+ return pipes.VerifyServiceFee(context, next);
724
+ });
229
725
  pre.use(async (context, next) => {
230
726
  const syncState = getSyncState(context);
231
727
  const execId = context.executionId;
@@ -241,9 +737,21 @@ const createExecute = ({ filter, runAsLambda }) => {
241
737
  filter.add(context.txHash);
242
738
  return next();
243
739
  });
244
- pre.use(pipes.VerifyTxSize);
245
- pre.use(pipes.PreFlightWaf);
246
- pre.use(pipes.VerifySignature);
740
+ pre.use((context, next) => {
741
+ if (context._preFlightSnapshotApplied) return next();
742
+ return pipes.VerifyTxSize(context, next);
743
+ });
744
+ pre.use((context, next) => {
745
+ if (context._preFlightSnapshotApplied) return next();
746
+ return pipes.PreFlightWaf(context, next);
747
+ });
748
+ pre.use((context, next) => {
749
+ if (context._preFlightSnapshotApplied) {
750
+ context.timer?.mark?.("verify");
751
+ return next();
752
+ }
753
+ return pipes.VerifySignature(context, next);
754
+ });
247
755
  pre.use((context, next) => {
248
756
  context.isSignatureVerified = true;
249
757
  return next();
@@ -258,13 +766,14 @@ const createExecute = ({ filter, runAsLambda }) => {
258
766
  const existingTxOwner = syncState.inFlightTxHashes.get(context.txHash);
259
767
  if (existingTxOwner && existingTxOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
260
768
  }
261
- await assertSenderNonceFresh(context);
769
+ const senderState = await assertSenderNonceFresh(context);
262
770
  await assertDelegationAuthorized(context);
263
771
  if (context.unsignedTxHash) {
264
772
  const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
265
773
  if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
266
774
  }
267
775
  if (await hasCommittedUnsignedTx(context)) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
776
+ if (!senderState) await assertNonExistentSenderAdmissible(context);
268
777
  if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
269
778
  if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
270
779
  await runSinglePipe(WriteLedger, context);
@@ -276,8 +785,16 @@ const createExecute = ({ filter, runAsLambda }) => {
276
785
  });
277
786
  const ensureGasFeePaid = (context) => {
278
787
  const gasRunner = new Runner("ensure-gas-fee-paid");
279
- gasRunner.use((ctx, next) => {
788
+ gasRunner.use(async (ctx, next) => {
280
789
  if (ctx.senderState?.address && ctx.stateSnapshot?.[ctx.senderState.address]) ctx.senderState = cloneDeep(ctx.stateSnapshot[ctx.senderState.address]);
790
+ else if (!ctx.senderState && ctx.tx?.from && typeof ctx.statedb?.account?.get === "function") {
791
+ const fetched = await ctx.statedb.account.get(ctx.tx.from, ctx);
792
+ if (fetched && (fetched.address === ctx.tx.from || isSameDid(fetched.address, ctx.tx.from)) && !(Array.isArray(fetched.migratedTo) && fetched.migratedTo.length > 0)) ctx.senderState = fetched;
793
+ }
794
+ if (ctx.senderState?.address && !ctx.stateSnapshot?.[ctx.senderState.address]) ctx.stateSnapshot = {
795
+ ...ctx.stateSnapshot || {},
796
+ [ctx.senderState.address]: cloneDeep(ctx.senderState)
797
+ };
281
798
  ctx.isFailedTxGasCharge = true;
282
799
  ctx.gasPaid = false;
283
800
  ctx.senderUpdates = {};
@@ -301,7 +818,7 @@ const createExecute = ({ filter, runAsLambda }) => {
301
818
  }, ctx);
302
819
  ctx.senderState = await statedb.account.update(senderState.address, updates, ctx) || senderState;
303
820
  if (updateVaults) await updateVaults();
304
- }
821
+ } else if (updateVaults) await updateVaults();
305
822
  return next();
306
823
  });
307
824
  return new Promise((resolve, reject) => {
@@ -351,6 +868,7 @@ const createExecute = ({ filter, runAsLambda }) => {
351
868
  if (slashEvidence && !err.slashEvidence) err.slashEvidence = slashEvidence;
352
869
  };
353
870
  const execute = async (context, protocols, isRetrySupported = false) => new Promise((resolve, reject) => {
871
+ context._protocols = protocols;
354
872
  pre.run(context, async (err) => {
355
873
  if (err) {
356
874
  if (!isRetrySupported) await attachSecurityStrikeToError(err, context);
@@ -449,10 +967,11 @@ const createExecute = ({ filter, runAsLambda }) => {
449
967
  "extra",
450
968
  "logger",
451
969
  "ledgerSequence",
452
- "height",
453
970
  "timer",
454
971
  "executionId"
455
972
  ]);
973
+ const preFlightSnapshot = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
974
+ if (preFlightSnapshot !== void 0) ctx[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL] = preFlightSnapshot;
456
975
  ctx.txn = txn;
457
976
  if (savedLedgerSequence !== void 0) ctx.ledgerSequence = savedLedgerSequence;
458
977
  ctx.timer?.mark("lockWait");
@@ -686,4 +1205,4 @@ const createExecute = ({ filter, runAsLambda }) => {
686
1205
  var execute_default = createExecute;
687
1206
 
688
1207
  //#endregion
689
- export { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, execute_default as default, toUnsignedEvidenceKey };
1208
+ export { PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, execute_default as default, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot };