@ocap/tx-protocols 1.30.26 → 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 +11 -2
- package/esm/execute.mjs +724 -80
- package/esm/gas-security-guard.d.mts +375 -0
- package/esm/gas-security-guard.mjs +1103 -0
- package/esm/index.d.mts +36 -6
- package/esm/index.mjs +4 -2
- package/esm/pipes/ensure-cost.mjs +335 -59
- package/esm/protocols/account/delegate.mjs +64 -16
- package/esm/protocols/account/migrate.d.mts +3 -0
- package/esm/protocols/account/migrate.mjs +235 -35
- package/esm/protocols/account/revoke-delegate.d.mts +3 -3
- package/esm/protocols/account/revoke-delegate.mjs +70 -38
- package/esm/protocols/asset/acquire-v2.mjs +29 -12
- package/esm/protocols/asset/acquire-v3.mjs +78 -22
- package/esm/protocols/asset/calls/transfer-token.mjs +2 -1
- package/esm/protocols/asset/calls/transfer.mjs +1 -0
- package/esm/protocols/asset/consume.mjs +12 -4
- package/esm/protocols/asset/create.mjs +18 -5
- package/esm/protocols/asset/mint.mjs +23 -1
- package/esm/protocols/asset/pipes/exec-mint-hook.d.mts +21 -1
- package/esm/protocols/asset/pipes/exec-mint-hook.mjs +115 -1
- package/esm/protocols/asset/pipes/extract-factory-tokens.mjs +14 -8
- package/esm/protocols/asset/pipes/verify-itx-address.mjs +9 -0
- package/esm/protocols/asset/pipes/verify-itx-assets.mjs +21 -5
- package/esm/protocols/asset/update.d.mts +13 -2
- package/esm/protocols/asset/update.mjs +133 -14
- package/esm/protocols/factory/create.mjs +14 -6
- package/esm/protocols/governance/claim-stake.mjs +115 -11
- package/esm/protocols/governance/return-stake.mjs +44 -12
- package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
- package/esm/protocols/governance/revoke-ledger.mjs +179 -0
- package/esm/protocols/governance/revoke-stake.mjs +25 -5
- package/esm/protocols/governance/slash-stake.mjs +72 -25
- package/esm/protocols/governance/stake.mjs +63 -13
- package/esm/protocols/rollup/claim-reward.mjs +39 -20
- package/esm/protocols/rollup/close.mjs +1 -1
- package/esm/protocols/rollup/create-block.mjs +8 -7
- package/esm/protocols/rollup/create.mjs +17 -6
- package/esm/protocols/rollup/join.mjs +3 -3
- package/esm/protocols/rollup/leave.mjs +1 -1
- package/esm/protocols/rollup/migrate.mjs +7 -4
- package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
- package/esm/protocols/rollup/update.mjs +6 -1
- package/esm/protocols/token/create.mjs +23 -12
- package/esm/protocols/token/deposit-v2.d.mts +5 -1
- package/esm/protocols/token/deposit-v2.mjs +81 -29
- package/esm/protocols/token/withdraw-v2.mjs +33 -16
- package/esm/protocols/token-factory/burn.mjs +43 -10
- package/esm/protocols/token-factory/create.mjs +23 -14
- package/esm/protocols/token-factory/mint.mjs +54 -21
- package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
- package/esm/protocols/token-factory/update.mjs +16 -6
- package/esm/protocols/trade/exchange-v2.d.mts +4 -0
- package/esm/protocols/trade/exchange-v2.mjs +78 -22
- package/esm/protocols/trade/transfer-v2.mjs +44 -13
- package/esm/protocols/trade/transfer-v3.mjs +72 -31
- package/esm/util.d.mts +3 -1
- package/esm/util.mjs +26 -17
- package/lib/execute.cjs +724 -76
- package/lib/execute.d.cts +11 -2
- package/lib/gas-security-guard.cjs +1142 -0
- package/lib/gas-security-guard.d.cts +375 -0
- package/lib/index.cjs +124 -1
- package/lib/index.d.cts +37 -7
- package/lib/pipes/ensure-cost.cjs +334 -58
- package/lib/protocols/account/delegate.cjs +64 -16
- package/lib/protocols/account/migrate.cjs +235 -35
- package/lib/protocols/account/migrate.d.cts +3 -0
- package/lib/protocols/account/revoke-delegate.cjs +71 -39
- package/lib/protocols/account/revoke-delegate.d.cts +3 -3
- package/lib/protocols/asset/acquire-v2.cjs +28 -11
- package/lib/protocols/asset/acquire-v3.cjs +77 -20
- package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
- package/lib/protocols/asset/calls/transfer.cjs +1 -0
- package/lib/protocols/asset/consume.cjs +11 -3
- package/lib/protocols/asset/create.cjs +19 -6
- package/lib/protocols/asset/mint.cjs +23 -1
- package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
- package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
- package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
- package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
- package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
- package/lib/protocols/asset/update.cjs +131 -12
- package/lib/protocols/asset/update.d.cts +13 -2
- package/lib/protocols/factory/create.cjs +14 -6
- package/lib/protocols/governance/claim-stake.cjs +115 -10
- package/lib/protocols/governance/claim-stake.d.cts +1 -1
- package/lib/protocols/governance/return-stake.cjs +44 -11
- package/lib/protocols/governance/return-stake.d.cts +1 -1
- package/lib/protocols/governance/revoke-ledger.cjs +184 -0
- package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
- package/lib/protocols/governance/revoke-stake.cjs +25 -5
- package/lib/protocols/governance/revoke-stake.d.cts +1 -1
- package/lib/protocols/governance/slash-stake.cjs +72 -24
- package/lib/protocols/governance/slash-stake.d.cts +1 -1
- package/lib/protocols/governance/stake.cjs +65 -14
- package/lib/protocols/rollup/claim-reward.cjs +39 -20
- package/lib/protocols/rollup/close.cjs +1 -1
- package/lib/protocols/rollup/create-block.cjs +9 -8
- package/lib/protocols/rollup/create-block.d.cts +1 -1
- package/lib/protocols/rollup/create.cjs +18 -7
- package/lib/protocols/rollup/join.cjs +3 -3
- package/lib/protocols/rollup/leave.cjs +1 -1
- package/lib/protocols/rollup/migrate.cjs +7 -4
- package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
- package/lib/protocols/rollup/update.cjs +6 -1
- package/lib/protocols/token/create.cjs +24 -13
- package/lib/protocols/token/deposit-v2.cjs +80 -28
- package/lib/protocols/token/deposit-v2.d.cts +5 -1
- package/lib/protocols/token/withdraw-v2.cjs +32 -15
- package/lib/protocols/token-factory/burn.cjs +42 -9
- package/lib/protocols/token-factory/create.cjs +24 -15
- package/lib/protocols/token-factory/mint.cjs +53 -20
- package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
- package/lib/protocols/token-factory/update.cjs +16 -6
- package/lib/protocols/trade/exchange-v2.cjs +76 -20
- package/lib/protocols/trade/exchange-v2.d.cts +4 -0
- package/lib/protocols/trade/transfer-v2.cjs +45 -14
- package/lib/protocols/trade/transfer-v3.cjs +72 -30
- package/lib/util.cjs +26 -17
- package/lib/util.d.cts +4 -2
- package/package.json +16 -16
package/esm/execute.mjs
CHANGED
|
@@ -1,18 +1,40 @@
|
|
|
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";
|
|
1
3
|
import ensure_cost_default from "./pipes/ensure-cost.mjs";
|
|
2
4
|
import ensure_gas_default from "./pipes/ensure-gas.mjs";
|
|
3
5
|
import { WriteLedger } from "./pipes/write-ledger.mjs";
|
|
4
6
|
import { TxTimer } from "./tx-timer.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import
|
|
8
|
-
import {
|
|
7
|
+
import { isFromPublicKey, toAddress, toTypeInfo } from "@arcblock/did";
|
|
8
|
+
import { toDelegateAddress, toStakeAddress } from "@arcblock/did-util";
|
|
9
|
+
import * as JWT from "@arcblock/jwt";
|
|
10
|
+
import { toTxHash, types } from "@ocap/mcrypto";
|
|
11
|
+
import { account, evidence, parseNonceBn } from "@ocap/state";
|
|
12
|
+
import { Runner, inspectPostExecutionInvariants, installStateWriteInterceptor, pipes, rollbackTrackedStateWrites, verifyImplicitAssetOwnership } from "@ocap/tx-pipeline";
|
|
13
|
+
import { BN, fromTokenToUnit, isSameDid, toBase58, toBase64, toBuffer } from "@ocap/util";
|
|
9
14
|
import { CustomError } from "@ocap/util/lib/error";
|
|
15
|
+
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
16
|
+
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
10
17
|
import camelCase from "lodash/camelCase.js";
|
|
18
|
+
import cloneDeep from "lodash/cloneDeep.js";
|
|
11
19
|
import get from "lodash/get.js";
|
|
12
20
|
import merge from "lodash/merge.js";
|
|
13
21
|
import pick from "lodash/pick.js";
|
|
14
22
|
|
|
15
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
|
+
}
|
|
16
38
|
const ensureTxGas = ensure_gas_default(() => ({
|
|
17
39
|
create: 0,
|
|
18
40
|
update: 2
|
|
@@ -39,7 +61,56 @@ const flushEvents = (context, extra = {}) => {
|
|
|
39
61
|
});
|
|
40
62
|
context.events = [];
|
|
41
63
|
};
|
|
42
|
-
const
|
|
64
|
+
const SINGLE_SIG_DELEGATION_TX_TYPES = new Set([
|
|
65
|
+
"fg:t:acquire_asset_v2",
|
|
66
|
+
"fg:t:acquire_asset_v3",
|
|
67
|
+
"fg:t:create_asset",
|
|
68
|
+
"fg:t:update_asset",
|
|
69
|
+
"fg:t:create_factory",
|
|
70
|
+
"fg:t:create_rollup",
|
|
71
|
+
"fg:t:create_token_factory",
|
|
72
|
+
"fg:t:update_token_factory",
|
|
73
|
+
"fg:t:create_token",
|
|
74
|
+
"fg:t:exchange_v2",
|
|
75
|
+
"fg:t:transfer",
|
|
76
|
+
"fg:t:transfer_v2",
|
|
77
|
+
"fg:t:transfer_v3"
|
|
78
|
+
]);
|
|
79
|
+
const MULTISIG_DELEGATION_TX_TYPES = new Set([
|
|
80
|
+
"fg:t:acquire_asset_v3",
|
|
81
|
+
"fg:t:exchange_v2",
|
|
82
|
+
"fg:t:transfer_v3"
|
|
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
|
+
]);
|
|
107
|
+
const shouldPersistTx = (err, context) => {
|
|
108
|
+
if (!err) return true;
|
|
109
|
+
if (!get(err, "props.persist")) return false;
|
|
110
|
+
if (context?.tx?.delegator && !context.delegationState && !context.isImplicitDelegation) return false;
|
|
111
|
+
if ((getListField(context?.tx, "signatures") || []).some((s) => Boolean(s?.delegator)) && !context.isMultiSigDelegationVerified && !context.delegationStates) return false;
|
|
112
|
+
return true;
|
|
113
|
+
};
|
|
43
114
|
const toUnsignedEvidenceKey = (unsignedTxHash) => toTxHash(Buffer.from(`unsigned-tx:${unsignedTxHash}`));
|
|
44
115
|
const UNSIGNED_TX_EVIDENCE_DATA_PREFIX = "unsigned-tx:";
|
|
45
116
|
const hasEvidenceStore = (statedb) => Boolean(statedb && typeof statedb.evidence?.get === "function" && typeof statedb.evidence?.create === "function");
|
|
@@ -56,18 +127,11 @@ const getOrCreateSyncState = (target) => {
|
|
|
56
127
|
}
|
|
57
128
|
return state;
|
|
58
129
|
};
|
|
59
|
-
/**
|
|
60
|
-
* Determine whether `unsignedTxHash` deduplication in `statedb.evidence` is active
|
|
61
|
-
* for the current execution context.
|
|
62
|
-
*/
|
|
63
|
-
const isUnsignedDedupActive = async (context) => {
|
|
64
|
-
if (!context.unsignedTxHash) return false;
|
|
65
|
-
return isDedupHeightActive(context);
|
|
66
|
-
};
|
|
67
130
|
const createExecute = ({ filter, runAsLambda }) => {
|
|
68
131
|
const fallbackSyncTarget = {};
|
|
69
132
|
const getSyncState = (context) => {
|
|
70
|
-
|
|
133
|
+
const rawDb = (context?.statedb)?._underlyingStateDb || context?.statedb;
|
|
134
|
+
return getOrCreateSyncState((rawDb && typeof rawDb === "object" ? rawDb : null) || (context?.ledger && typeof context.ledger === "object" ? context.ledger : null) || fallbackSyncTarget);
|
|
71
135
|
};
|
|
72
136
|
const withPreWriteLock = async (context, fn) => {
|
|
73
137
|
const syncState = getSyncState(context);
|
|
@@ -104,7 +168,6 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
104
168
|
};
|
|
105
169
|
const recordUnsignedTxInStateDb = async (context, txHash) => {
|
|
106
170
|
if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return;
|
|
107
|
-
if (!await isUnsignedDedupActive(context)) return;
|
|
108
171
|
const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
|
|
109
172
|
if (!await context.statedb.evidence.get(unsignedKey, { txn: context.txn })) {
|
|
110
173
|
const evState = evidence.create({
|
|
@@ -118,9 +181,9 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
118
181
|
}
|
|
119
182
|
};
|
|
120
183
|
/**
|
|
121
|
-
*
|
|
184
|
+
* Sender nonce precheck, run under the pre-write lock BEFORE WriteLedger.
|
|
122
185
|
*
|
|
123
|
-
* Every persisted pre
|
|
186
|
+
* Every persisted pre-#1127 tx has `nonce <= sender.nonce` once the offline migration
|
|
124
187
|
* restored each account's max historical nonce. Rejecting stale nonces here (instead of
|
|
125
188
|
* relying on each protocol's `account.update` after WriteLedger) means a signature-malleated
|
|
126
189
|
* twin of ANY historical tx is refused without appending a ledger row and without depending
|
|
@@ -131,36 +194,534 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
131
194
|
* decides as before.
|
|
132
195
|
* - Sender migrated (statedb resolves `tx.from` to its successor): reject like
|
|
133
196
|
* VerifyAccountMigration, but before the ledger write.
|
|
197
|
+
*/
|
|
198
|
+
/**
|
|
199
|
+
* Pre-ledger admission check for non-existent senders (#1359).
|
|
134
200
|
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
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.
|
|
138
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
|
+
};
|
|
139
622
|
const assertSenderNonceFresh = async (context) => {
|
|
140
623
|
const from = context.tx?.from;
|
|
141
624
|
const accountStore = context.statedb?.account;
|
|
142
|
-
if (!from || typeof accountStore?.get !== "function") return;
|
|
625
|
+
if (!from || typeof accountStore?.get !== "function") return null;
|
|
143
626
|
const senderState = await accountStore.get(from, context);
|
|
144
|
-
if (!senderState) return;
|
|
627
|
+
if (!senderState) return null;
|
|
145
628
|
if (senderState.address !== from && senderState.address !== account.ensureChecksumAddress(from)) throw new CustomError("ACCOUNT_MIGRATED", `account ${from} is migrated`);
|
|
146
629
|
const incomingNonceBn = parseNonceBn(context.tx?.nonce);
|
|
147
630
|
const currentNonceBn = parseNonceBn(senderState.nonce) ?? new BN(0);
|
|
148
631
|
if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn)) throw new CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
|
|
632
|
+
return senderState;
|
|
633
|
+
};
|
|
634
|
+
/**
|
|
635
|
+
* Pre-ledger delegation authorization check, run under the pre-write lock BEFORE WriteLedger.
|
|
636
|
+
*
|
|
637
|
+
* Unauthenticated delegated transactions (`tx.delegator` or multisig `signatures[].delegator`
|
|
638
|
+
* without valid on-chain delegation or implicit asset ownership) are rejected with
|
|
639
|
+
* `persist: false` so they cannot charge gas or advance nonces on the target account.
|
|
640
|
+
* Rejecting them before `WriteLedger` prevents unauthenticated actors from appending
|
|
641
|
+
* orphaned, unpersisted entries to the immutable ledger.
|
|
642
|
+
*/
|
|
643
|
+
const assertDelegatorPairAuthorized = async (context, signerAddress, delegatorAddress, noDelegationMsg) => {
|
|
644
|
+
if (!signerAddress || !delegatorAddress) return;
|
|
645
|
+
const statedb = context.statedb;
|
|
646
|
+
const accountStore = statedb?.account;
|
|
647
|
+
if (typeof accountStore?.get !== "function") return;
|
|
648
|
+
const delegatorState = await accountStore.get(delegatorAddress, context);
|
|
649
|
+
if (delegatorState && (!isSameDid(delegatorState.address, delegatorAddress) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) throw new CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegatorAddress} is migrated`, { persist: false });
|
|
650
|
+
if (toTypeInfo(signerAddress).role === types.RoleType.ROLE_ASSET) {
|
|
651
|
+
if (typeof statedb?.asset?.get !== "function") return;
|
|
652
|
+
let isOwner = false;
|
|
653
|
+
try {
|
|
654
|
+
isOwner = await verifyImplicitAssetOwnership(signerAddress, delegatorState || { address: delegatorAddress }, context, delegatorAddress);
|
|
655
|
+
} catch (err) {
|
|
656
|
+
if (err && typeof err === "object") err.props = {
|
|
657
|
+
...err.props || {},
|
|
658
|
+
persist: false
|
|
659
|
+
};
|
|
660
|
+
throw err;
|
|
661
|
+
}
|
|
662
|
+
if (!isOwner) throw new CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || delegatorAddress} is not the owner of asset ${signerAddress}`, { persist: false });
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
if (typeof statedb?.delegation?.get !== "function") return;
|
|
666
|
+
const signerState = await accountStore.get(signerAddress, context);
|
|
667
|
+
if (signerState && (!isSameDid(signerState.address, signerAddress) || Array.isArray(signerState.migratedTo) && signerState.migratedTo.length > 0)) throw new CustomError("ACCOUNT_MIGRATED", `account ${signerAddress} is migrated`, { persist: false });
|
|
668
|
+
if (!signerState || !delegatorState) throw new CustomError("INVALID_DELEGATION", noDelegationMsg, { persist: false });
|
|
669
|
+
const related = getRelatedAddresses(delegatorState);
|
|
670
|
+
if (!(await Promise.all(related.map((x) => statedb.delegation.get(toDelegateAddress(signerState.address, x), context)))).some(Boolean)) throw new CustomError("INVALID_DELEGATION", noDelegationMsg, { persist: false });
|
|
671
|
+
};
|
|
672
|
+
const assertDelegationAuthorized = async (context) => {
|
|
673
|
+
const tx$1 = context.tx;
|
|
674
|
+
if (tx$1?.delegator) {
|
|
675
|
+
if (context.txType && !SINGLE_SIG_DELEGATION_TX_TYPES.has(context.txType)) throw new CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false });
|
|
676
|
+
await assertDelegatorPairAuthorized(context, tx$1.from, tx$1.delegator, "No delegation found between sender and delegator");
|
|
677
|
+
}
|
|
678
|
+
const signatures = getListField(tx$1, "signatures") || [];
|
|
679
|
+
for (const sig of signatures) if (sig?.delegator) {
|
|
680
|
+
if (context.txType && !MULTISIG_DELEGATION_TX_TYPES.has(context.txType)) throw new CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false });
|
|
681
|
+
await assertDelegatorPairAuthorized(context, sig.signer, sig.delegator, "No delegation found between signer and delegator");
|
|
682
|
+
}
|
|
149
683
|
};
|
|
150
684
|
const pre = new Runner("pre-execute");
|
|
151
|
-
pre.use(
|
|
152
|
-
|
|
153
|
-
if (
|
|
154
|
-
|
|
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);
|
|
155
692
|
});
|
|
156
|
-
pre.use(pipes.DecodeTx);
|
|
157
693
|
pre.use(pipes.VerifyBlocked({
|
|
158
694
|
filter,
|
|
159
695
|
stateKeys: ["tx.from"]
|
|
160
696
|
}));
|
|
161
|
-
pre.use(
|
|
162
|
-
|
|
163
|
-
|
|
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
|
+
});
|
|
164
725
|
pre.use(async (context, next) => {
|
|
165
726
|
const syncState = getSyncState(context);
|
|
166
727
|
const execId = context.executionId;
|
|
@@ -169,57 +730,53 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
169
730
|
if (filter.has(context.txHash)) {
|
|
170
731
|
if (await context.statedb.tx.get(context.txHash, context)) return next(new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
|
|
171
732
|
}
|
|
172
|
-
if (
|
|
173
|
-
const inFlightUnsignedOwner =
|
|
733
|
+
if (context.unsignedTxHash) {
|
|
734
|
+
const inFlightUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
|
|
174
735
|
if (inFlightUnsignedOwner && inFlightUnsignedOwner !== execId || await hasCommittedUnsignedTx(context)) return next(new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
|
|
175
736
|
}
|
|
176
737
|
filter.add(context.txHash);
|
|
177
738
|
return next();
|
|
178
739
|
});
|
|
179
|
-
pre.use(
|
|
180
|
-
|
|
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
|
+
});
|
|
755
|
+
pre.use((context, next) => {
|
|
756
|
+
context.isSignatureVerified = true;
|
|
757
|
+
return next();
|
|
758
|
+
});
|
|
181
759
|
pre.use(async (context, next) => {
|
|
182
760
|
try {
|
|
183
761
|
await withPreWriteLock(context, async () => {
|
|
184
762
|
const syncState = getSyncState(context);
|
|
185
|
-
if (context.height === void 0 && !context.ledgerSequence) {
|
|
186
|
-
delete context.expectedLedgerSequence;
|
|
187
|
-
delete context.dedupActive;
|
|
188
|
-
const dedupHeight = resolveDedupActivationHeight(context);
|
|
189
|
-
if (dedupHeight > 0 && dedupHeight < PENDING_DEDUP_ACTIVATION_HEIGHT) await resolveEffectiveHeight(context);
|
|
190
|
-
}
|
|
191
|
-
const isActiveNow = await isUnsignedDedupActive(context);
|
|
192
|
-
context.dedupActive = isActiveNow;
|
|
193
763
|
const execId = context.executionId || Symbol("tx-exec");
|
|
194
764
|
context.executionId = execId;
|
|
195
765
|
if (context.txHash) {
|
|
196
766
|
const existingTxOwner = syncState.inFlightTxHashes.get(context.txHash);
|
|
197
767
|
if (existingTxOwner && existingTxOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
198
768
|
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if (context.unsignedTxHash) {
|
|
205
|
-
const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
|
|
206
|
-
if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
207
|
-
}
|
|
208
|
-
if (await hasCommittedUnsignedTx(context)) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
769
|
+
const senderState = await assertSenderNonceFresh(context);
|
|
770
|
+
await assertDelegationAuthorized(context);
|
|
771
|
+
if (context.unsignedTxHash) {
|
|
772
|
+
const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
|
|
773
|
+
if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
209
774
|
}
|
|
775
|
+
if (await hasCommittedUnsignedTx(context)) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
776
|
+
if (!senderState) await assertNonExistentSenderAdmissible(context);
|
|
210
777
|
if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
|
|
211
|
-
if (
|
|
778
|
+
if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
|
|
212
779
|
await runSinglePipe(WriteLedger, context);
|
|
213
|
-
delete context.dedupActive;
|
|
214
|
-
const isActiveAfterWrite = await isUnsignedDedupActive(context);
|
|
215
|
-
context.dedupActive = isActiveAfterWrite;
|
|
216
|
-
if (isActiveAfterWrite) {
|
|
217
|
-
if (!isActiveNow) assertCanonicalActiveTx(context);
|
|
218
|
-
const nonceBn = parseNonceBn(context.tx?.nonce);
|
|
219
|
-
if (!nonceBn || nonceBn.lte(new BN(0))) throw new CustomError("INVALID_NONCE", "tx.nonce should be a positive integer");
|
|
220
|
-
if (await hasCommittedUnsignedTx(context)) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
221
|
-
if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
|
|
222
|
-
}
|
|
223
780
|
});
|
|
224
781
|
return next();
|
|
225
782
|
} catch (err) {
|
|
@@ -228,20 +785,40 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
228
785
|
});
|
|
229
786
|
const ensureGasFeePaid = (context) => {
|
|
230
787
|
const gasRunner = new Runner("ensure-gas-fee-paid");
|
|
788
|
+
gasRunner.use(async (ctx, next) => {
|
|
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
|
+
};
|
|
798
|
+
ctx.isFailedTxGasCharge = true;
|
|
799
|
+
ctx.gasPaid = false;
|
|
800
|
+
ctx.senderUpdates = {};
|
|
801
|
+
ctx.senderChange = void 0;
|
|
802
|
+
ctx.updatedAccounts = [];
|
|
803
|
+
ctx.feeVaultChange = void 0;
|
|
804
|
+
ctx.gasVaultChange = void 0;
|
|
805
|
+
return next();
|
|
806
|
+
});
|
|
231
807
|
gasRunner.use(ensureTxGas);
|
|
232
808
|
gasRunner.use(ensureTxCost);
|
|
233
809
|
gasRunner.use(async (ctx, next) => {
|
|
234
810
|
const { tx: tx$1, statedb, senderUpdates, updateVaults } = ctx;
|
|
235
811
|
if (ctx.senderState && ctx.states && tx$1) {
|
|
236
|
-
|
|
812
|
+
if (tx$1.delegator && !ctx.delegationState && !ctx.isImplicitDelegation) return next(new CustomError("INVALID_DELEGATION", "Cannot charge gas to sender without verified delegation"));
|
|
813
|
+
const senderState = ctx.senderState;
|
|
237
814
|
const updates = ctx.states.account.update(senderState, {
|
|
238
815
|
nonce: tx$1.nonce,
|
|
239
|
-
pk: tx$1.pk,
|
|
816
|
+
pk: tx$1.delegator ? senderState.pk : tx$1.pk,
|
|
240
817
|
...senderUpdates
|
|
241
818
|
}, ctx);
|
|
242
|
-
await statedb.account.update(senderState.address, updates, ctx);
|
|
819
|
+
ctx.senderState = await statedb.account.update(senderState.address, updates, ctx) || senderState;
|
|
243
820
|
if (updateVaults) await updateVaults();
|
|
244
|
-
}
|
|
821
|
+
} else if (updateVaults) await updateVaults();
|
|
245
822
|
return next();
|
|
246
823
|
});
|
|
247
824
|
return new Promise((resolve, reject) => {
|
|
@@ -260,9 +837,41 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
260
837
|
});
|
|
261
838
|
});
|
|
262
839
|
};
|
|
840
|
+
const attachSecurityStrikeToError = async (err, ctx) => {
|
|
841
|
+
if (!err || err._strikeRecorded || err._unauthenticatedExtraFailure === true) return;
|
|
842
|
+
const classified = classifyErrorStrikeCategory(err);
|
|
843
|
+
if (!classified.shouldRecordStrike) return;
|
|
844
|
+
const secCfg = ctx.config?.transaction?.security;
|
|
845
|
+
const strikeOnAllErrors = secCfg?.strikeOnAllErrors === true;
|
|
846
|
+
if (!(classified.category === "WAF_REJECT" || classified.category === "INVARIANT_VIOLATION" || classified.category === "PAYMASTER_VIOLATION" || strikeOnAllErrors)) return;
|
|
847
|
+
const actors = await resolveVerifiedStrikeActors(ctx);
|
|
848
|
+
if (actors.length === 0) return;
|
|
849
|
+
err._strikeRecorded = true;
|
|
850
|
+
const fishermanAddress = secCfg?.fishermanAddress;
|
|
851
|
+
const nowMs = ctx.txTime ? +new Date(ctx.txTime) : Date.now();
|
|
852
|
+
const { primaryWarning, slashEvidence } = await recordActorSecurityStrike({
|
|
853
|
+
actors,
|
|
854
|
+
category: classified.category,
|
|
855
|
+
reasonCode: classified.code,
|
|
856
|
+
txHash: ctx.txHash,
|
|
857
|
+
config: ctx.config,
|
|
858
|
+
statedb: ctx.statedb,
|
|
859
|
+
txn: ctx.txn,
|
|
860
|
+
fishermanAddress,
|
|
861
|
+
nowMs,
|
|
862
|
+
telemetry: ctx.gasQuotaTelemetry
|
|
863
|
+
});
|
|
864
|
+
if (primaryWarning && !err.warning) {
|
|
865
|
+
err.warning = primaryWarning;
|
|
866
|
+
ctx.securityWarning = primaryWarning;
|
|
867
|
+
}
|
|
868
|
+
if (slashEvidence && !err.slashEvidence) err.slashEvidence = slashEvidence;
|
|
869
|
+
};
|
|
263
870
|
const execute = async (context, protocols, isRetrySupported = false) => new Promise((resolve, reject) => {
|
|
264
|
-
|
|
871
|
+
context._protocols = protocols;
|
|
872
|
+
pre.run(context, async (err) => {
|
|
265
873
|
if (err) {
|
|
874
|
+
if (!isRetrySupported) await attachSecurityStrikeToError(err, context);
|
|
266
875
|
context.logger?.error("Failed to prepare transaction", {
|
|
267
876
|
error: err,
|
|
268
877
|
txHash: context.txHash,
|
|
@@ -272,16 +881,30 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
272
881
|
}
|
|
273
882
|
const protocol = protocols[getTxName(context.txType)];
|
|
274
883
|
if (!protocol) return reject(new CustomError("UNSUPPORTED_TX", `Unsupported tx type ${context.txType}`));
|
|
275
|
-
|
|
884
|
+
installStateWriteInterceptor(context);
|
|
885
|
+
protocol.run(context, async (rawError) => {
|
|
886
|
+
const underlyingDb = context.statedb?._underlyingStateDb;
|
|
887
|
+
if (underlyingDb) context.statedb = underlyingDb;
|
|
888
|
+
let error = rawError;
|
|
276
889
|
context.timer?.mark("protocol");
|
|
890
|
+
if (!error) try {
|
|
891
|
+
inspectPostExecutionInvariants(context);
|
|
892
|
+
} catch (invariantErr) {
|
|
893
|
+
error = invariantErr;
|
|
894
|
+
}
|
|
277
895
|
if (isRetrySupported) {
|
|
278
896
|
if (error) return reject(error);
|
|
279
897
|
return resolve(context);
|
|
280
898
|
}
|
|
899
|
+
if (error) {
|
|
900
|
+
await rollbackTrackedStateWrites(context);
|
|
901
|
+
context.events = [];
|
|
902
|
+
await attachSecurityStrikeToError(error, context);
|
|
903
|
+
}
|
|
281
904
|
const txStatus = error ? error.code || "INTERNAL" : "OK";
|
|
282
905
|
const states = getStates(context);
|
|
283
906
|
let txState = states.tx.create(context, txStatus);
|
|
284
|
-
if (shouldPersistTx(error)) try {
|
|
907
|
+
if (shouldPersistTx(error, context)) try {
|
|
285
908
|
if (error) {
|
|
286
909
|
await ensureGasFeePaid(context);
|
|
287
910
|
txState = states.tx.create(context, txStatus);
|
|
@@ -306,7 +929,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
306
929
|
txSize: context.txSize,
|
|
307
930
|
senderAddr: context.tx?.from,
|
|
308
931
|
ledgerSequence: context.ledgerSequence,
|
|
309
|
-
status: error ? shouldPersistTx(error) ? "PERSISTED_FAILED" : "FAILED" : "OK",
|
|
932
|
+
status: error ? shouldPersistTx(error, context) ? "PERSISTED_FAILED" : "FAILED" : "OK",
|
|
310
933
|
errorCode: error ? error.code || "INTERNAL" : null,
|
|
311
934
|
retried: Boolean(error)
|
|
312
935
|
});
|
|
@@ -344,10 +967,11 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
344
967
|
"extra",
|
|
345
968
|
"logger",
|
|
346
969
|
"ledgerSequence",
|
|
347
|
-
"height",
|
|
348
970
|
"timer",
|
|
349
971
|
"executionId"
|
|
350
972
|
]);
|
|
973
|
+
const preFlightSnapshot = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
|
|
974
|
+
if (preFlightSnapshot !== void 0) ctx[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL] = preFlightSnapshot;
|
|
351
975
|
ctx.txn = txn;
|
|
352
976
|
if (savedLedgerSequence !== void 0) ctx.ledgerSequence = savedLedgerSequence;
|
|
353
977
|
ctx.timer?.mark("lockWait");
|
|
@@ -419,7 +1043,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
419
1043
|
txState,
|
|
420
1044
|
request: context.extra?.request
|
|
421
1045
|
});
|
|
422
|
-
if (txState && shouldPersistTx(err)) {
|
|
1046
|
+
if (txState && shouldPersistTx(err, ctx)) {
|
|
423
1047
|
ctx.events = [];
|
|
424
1048
|
try {
|
|
425
1049
|
txState = await runAsLambda(async (txn) => {
|
|
@@ -428,12 +1052,30 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
428
1052
|
cacheStates: null
|
|
429
1053
|
});
|
|
430
1054
|
ctx.timer?.mark("lockWait");
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
1055
|
+
const strikeSnapshot = snapshotActorSecurityRecords([
|
|
1056
|
+
ctx.tx?.delegator || "",
|
|
1057
|
+
ctx.tx?.from || "",
|
|
1058
|
+
ctx.gasStake?.sponsorAddress || ""
|
|
1059
|
+
].filter(Boolean), ctx.statedb, ctx.txHash);
|
|
1060
|
+
const hadStrikeBefore = Boolean(err._strikeRecorded);
|
|
1061
|
+
const prevWarning = err.warning;
|
|
1062
|
+
const prevSlashEvidence = err.slashEvidence;
|
|
1063
|
+
try {
|
|
1064
|
+
await ensureGasFeePaid(ctx);
|
|
1065
|
+
await attachSecurityStrikeToError(err, ctx);
|
|
1066
|
+
const state = getStates(context).tx.create(ctx, txStatus);
|
|
1067
|
+
await ctx.statedb.tx.create(state.hash, state, ctx);
|
|
1068
|
+
await recordUnsignedTxInStateDb(ctx, state.hash);
|
|
1069
|
+
ctx.timer?.mark("txstate");
|
|
1070
|
+
return state;
|
|
1071
|
+
} catch (lambdaErr) {
|
|
1072
|
+
restoreActorSecurityRecords(strikeSnapshot, ctx.statedb);
|
|
1073
|
+
err._strikeRecorded = hadStrikeBefore;
|
|
1074
|
+
err.warning = prevWarning;
|
|
1075
|
+
err.slashEvidence = prevSlashEvidence;
|
|
1076
|
+
ctx.securityWarning = prevWarning;
|
|
1077
|
+
throw lambdaErr;
|
|
1078
|
+
}
|
|
437
1079
|
}, {
|
|
438
1080
|
cleanWorkingSet: true,
|
|
439
1081
|
verifyHash: true,
|
|
@@ -481,6 +1123,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
481
1123
|
perf: ctx.timer?.summaryV2()
|
|
482
1124
|
});
|
|
483
1125
|
} catch (innerErr) {
|
|
1126
|
+
await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
|
|
484
1127
|
ctx.logger?.error("Failed to save invalid transaction to statedb", {
|
|
485
1128
|
error: innerErr,
|
|
486
1129
|
txError: error,
|
|
@@ -491,6 +1134,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
491
1134
|
throw error;
|
|
492
1135
|
}
|
|
493
1136
|
} else {
|
|
1137
|
+
await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
|
|
494
1138
|
ctx.timer?.setMeta({
|
|
495
1139
|
txType: ctx.txType,
|
|
496
1140
|
txSize: ctx.txSize,
|
|
@@ -561,4 +1205,4 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
561
1205
|
var execute_default = createExecute;
|
|
562
1206
|
|
|
563
1207
|
//#endregion
|
|
564
|
-
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 };
|