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