@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/lib/execute.cjs
CHANGED
|
@@ -1,16 +1,26 @@
|
|
|
1
1
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
2
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
3
|
+
const require_gas_security_guard = require('./gas-security-guard.cjs');
|
|
4
|
+
const require_util = require('./util.cjs');
|
|
3
5
|
const require_pipes_ensure_cost = require('./pipes/ensure-cost.cjs');
|
|
4
6
|
const require_pipes_ensure_gas = require('./pipes/ensure-gas.cjs');
|
|
5
7
|
const require_pipes_write_ledger = require('./pipes/write-ledger.cjs');
|
|
6
8
|
const require_tx_timer = require('./tx-timer.cjs');
|
|
9
|
+
let _arcblock_did = require("@arcblock/did");
|
|
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);
|
|
7
13
|
let _ocap_mcrypto = require("@ocap/mcrypto");
|
|
8
14
|
let _ocap_state = require("@ocap/state");
|
|
9
15
|
let _ocap_tx_pipeline = require("@ocap/tx-pipeline");
|
|
10
16
|
let _ocap_util = require("@ocap/util");
|
|
11
17
|
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
18
|
+
let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
|
|
19
|
+
let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
|
|
12
20
|
let lodash_camelCase = require("lodash/camelCase");
|
|
13
21
|
lodash_camelCase = require_rolldown_runtime.__toESM(lodash_camelCase);
|
|
22
|
+
let lodash_cloneDeep = require("lodash/cloneDeep");
|
|
23
|
+
lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
|
|
14
24
|
let lodash_get = require("lodash/get");
|
|
15
25
|
lodash_get = require_rolldown_runtime.__toESM(lodash_get);
|
|
16
26
|
let lodash_merge = require("lodash/merge");
|
|
@@ -19,6 +29,20 @@ let lodash_pick = require("lodash/pick");
|
|
|
19
29
|
lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
|
|
20
30
|
|
|
21
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
|
+
}
|
|
22
46
|
const ensureTxGas = require_pipes_ensure_gas.default(() => ({
|
|
23
47
|
create: 0,
|
|
24
48
|
update: 2
|
|
@@ -45,7 +69,56 @@ const flushEvents = (context, extra = {}) => {
|
|
|
45
69
|
});
|
|
46
70
|
context.events = [];
|
|
47
71
|
};
|
|
48
|
-
const
|
|
72
|
+
const SINGLE_SIG_DELEGATION_TX_TYPES = new Set([
|
|
73
|
+
"fg:t:acquire_asset_v2",
|
|
74
|
+
"fg:t:acquire_asset_v3",
|
|
75
|
+
"fg:t:create_asset",
|
|
76
|
+
"fg:t:update_asset",
|
|
77
|
+
"fg:t:create_factory",
|
|
78
|
+
"fg:t:create_rollup",
|
|
79
|
+
"fg:t:create_token_factory",
|
|
80
|
+
"fg:t:update_token_factory",
|
|
81
|
+
"fg:t:create_token",
|
|
82
|
+
"fg:t:exchange_v2",
|
|
83
|
+
"fg:t:transfer",
|
|
84
|
+
"fg:t:transfer_v2",
|
|
85
|
+
"fg:t:transfer_v3"
|
|
86
|
+
]);
|
|
87
|
+
const MULTISIG_DELEGATION_TX_TYPES = new Set([
|
|
88
|
+
"fg:t:acquire_asset_v3",
|
|
89
|
+
"fg:t:exchange_v2",
|
|
90
|
+
"fg:t:transfer_v3"
|
|
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
|
+
]);
|
|
115
|
+
const shouldPersistTx = (err, context) => {
|
|
116
|
+
if (!err) return true;
|
|
117
|
+
if (!(0, lodash_get.default)(err, "props.persist")) return false;
|
|
118
|
+
if (context?.tx?.delegator && !context.delegationState && !context.isImplicitDelegation) return false;
|
|
119
|
+
if (((0, _ocap_util_lib_get_list_field.getListField)(context?.tx, "signatures") || []).some((s) => Boolean(s?.delegator)) && !context.isMultiSigDelegationVerified && !context.delegationStates) return false;
|
|
120
|
+
return true;
|
|
121
|
+
};
|
|
49
122
|
const toUnsignedEvidenceKey = (unsignedTxHash) => (0, _ocap_mcrypto.toTxHash)(Buffer.from(`unsigned-tx:${unsignedTxHash}`));
|
|
50
123
|
const UNSIGNED_TX_EVIDENCE_DATA_PREFIX = "unsigned-tx:";
|
|
51
124
|
const hasEvidenceStore = (statedb) => Boolean(statedb && typeof statedb.evidence?.get === "function" && typeof statedb.evidence?.create === "function");
|
|
@@ -62,18 +135,11 @@ const getOrCreateSyncState = (target) => {
|
|
|
62
135
|
}
|
|
63
136
|
return state;
|
|
64
137
|
};
|
|
65
|
-
/**
|
|
66
|
-
* Determine whether `unsignedTxHash` deduplication in `statedb.evidence` is active
|
|
67
|
-
* for the current execution context.
|
|
68
|
-
*/
|
|
69
|
-
const isUnsignedDedupActive = async (context) => {
|
|
70
|
-
if (!context.unsignedTxHash) return false;
|
|
71
|
-
return (0, _ocap_tx_pipeline.isDedupHeightActive)(context);
|
|
72
|
-
};
|
|
73
138
|
const createExecute = ({ filter, runAsLambda }) => {
|
|
74
139
|
const fallbackSyncTarget = {};
|
|
75
140
|
const getSyncState = (context) => {
|
|
76
|
-
|
|
141
|
+
const rawDb = (context?.statedb)?._underlyingStateDb || context?.statedb;
|
|
142
|
+
return getOrCreateSyncState((rawDb && typeof rawDb === "object" ? rawDb : null) || (context?.ledger && typeof context.ledger === "object" ? context.ledger : null) || fallbackSyncTarget);
|
|
77
143
|
};
|
|
78
144
|
const withPreWriteLock = async (context, fn) => {
|
|
79
145
|
const syncState = getSyncState(context);
|
|
@@ -110,7 +176,6 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
110
176
|
};
|
|
111
177
|
const recordUnsignedTxInStateDb = async (context, txHash) => {
|
|
112
178
|
if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return;
|
|
113
|
-
if (!await isUnsignedDedupActive(context)) return;
|
|
114
179
|
const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
|
|
115
180
|
if (!await context.statedb.evidence.get(unsignedKey, { txn: context.txn })) {
|
|
116
181
|
const evState = _ocap_state.evidence.create({
|
|
@@ -124,9 +189,9 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
124
189
|
}
|
|
125
190
|
};
|
|
126
191
|
/**
|
|
127
|
-
*
|
|
192
|
+
* Sender nonce precheck, run under the pre-write lock BEFORE WriteLedger.
|
|
128
193
|
*
|
|
129
|
-
* Every persisted pre
|
|
194
|
+
* Every persisted pre-#1127 tx has `nonce <= sender.nonce` once the offline migration
|
|
130
195
|
* restored each account's max historical nonce. Rejecting stale nonces here (instead of
|
|
131
196
|
* relying on each protocol's `account.update` after WriteLedger) means a signature-malleated
|
|
132
197
|
* twin of ANY historical tx is refused without appending a ledger row and without depending
|
|
@@ -137,36 +202,534 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
137
202
|
* decides as before.
|
|
138
203
|
* - Sender migrated (statedb resolves `tx.from` to its successor): reject like
|
|
139
204
|
* VerifyAccountMigration, but before the ledger write.
|
|
205
|
+
*/
|
|
206
|
+
/**
|
|
207
|
+
* Pre-ledger admission check for non-existent senders (#1359).
|
|
140
208
|
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
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.
|
|
144
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
|
+
};
|
|
145
630
|
const assertSenderNonceFresh = async (context) => {
|
|
146
631
|
const from = context.tx?.from;
|
|
147
632
|
const accountStore = context.statedb?.account;
|
|
148
|
-
if (!from || typeof accountStore?.get !== "function") return;
|
|
633
|
+
if (!from || typeof accountStore?.get !== "function") return null;
|
|
149
634
|
const senderState = await accountStore.get(from, context);
|
|
150
|
-
if (!senderState) return;
|
|
635
|
+
if (!senderState) return null;
|
|
151
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`);
|
|
152
637
|
const incomingNonceBn = (0, _ocap_state.parseNonceBn)(context.tx?.nonce);
|
|
153
638
|
const currentNonceBn = (0, _ocap_state.parseNonceBn)(senderState.nonce) ?? new _ocap_util.BN(0);
|
|
154
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;
|
|
641
|
+
};
|
|
642
|
+
/**
|
|
643
|
+
* Pre-ledger delegation authorization check, run under the pre-write lock BEFORE WriteLedger.
|
|
644
|
+
*
|
|
645
|
+
* Unauthenticated delegated transactions (`tx.delegator` or multisig `signatures[].delegator`
|
|
646
|
+
* without valid on-chain delegation or implicit asset ownership) are rejected with
|
|
647
|
+
* `persist: false` so they cannot charge gas or advance nonces on the target account.
|
|
648
|
+
* Rejecting them before `WriteLedger` prevents unauthenticated actors from appending
|
|
649
|
+
* orphaned, unpersisted entries to the immutable ledger.
|
|
650
|
+
*/
|
|
651
|
+
const assertDelegatorPairAuthorized = async (context, signerAddress, delegatorAddress, noDelegationMsg) => {
|
|
652
|
+
if (!signerAddress || !delegatorAddress) return;
|
|
653
|
+
const statedb = context.statedb;
|
|
654
|
+
const accountStore = statedb?.account;
|
|
655
|
+
if (typeof accountStore?.get !== "function") return;
|
|
656
|
+
const delegatorState = await accountStore.get(delegatorAddress, context);
|
|
657
|
+
if (delegatorState && (!(0, _ocap_util.isSameDid)(delegatorState.address, delegatorAddress) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegatorAddress} is migrated`, { persist: false });
|
|
658
|
+
if ((0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
|
|
659
|
+
if (typeof statedb?.asset?.get !== "function") return;
|
|
660
|
+
let isOwner = false;
|
|
661
|
+
try {
|
|
662
|
+
isOwner = await (0, _ocap_tx_pipeline.verifyImplicitAssetOwnership)(signerAddress, delegatorState || { address: delegatorAddress }, context, delegatorAddress);
|
|
663
|
+
} catch (err) {
|
|
664
|
+
if (err && typeof err === "object") err.props = {
|
|
665
|
+
...err.props || {},
|
|
666
|
+
persist: false
|
|
667
|
+
};
|
|
668
|
+
throw err;
|
|
669
|
+
}
|
|
670
|
+
if (!isOwner) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || delegatorAddress} is not the owner of asset ${signerAddress}`, { persist: false });
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
if (typeof statedb?.delegation?.get !== "function") return;
|
|
674
|
+
const signerState = await accountStore.get(signerAddress, context);
|
|
675
|
+
if (signerState && (!(0, _ocap_util.isSameDid)(signerState.address, signerAddress) || Array.isArray(signerState.migratedTo) && signerState.migratedTo.length > 0)) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `account ${signerAddress} is migrated`, { persist: false });
|
|
676
|
+
if (!signerState || !delegatorState) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", noDelegationMsg, { persist: false });
|
|
677
|
+
const related = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(delegatorState);
|
|
678
|
+
if (!(await Promise.all(related.map((x) => statedb.delegation.get((0, _arcblock_did_util.toDelegateAddress)(signerState.address, x), context)))).some(Boolean)) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", noDelegationMsg, { persist: false });
|
|
679
|
+
};
|
|
680
|
+
const assertDelegationAuthorized = async (context) => {
|
|
681
|
+
const tx = context.tx;
|
|
682
|
+
if (tx?.delegator) {
|
|
683
|
+
if (context.txType && !SINGLE_SIG_DELEGATION_TX_TYPES.has(context.txType)) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false });
|
|
684
|
+
await assertDelegatorPairAuthorized(context, tx.from, tx.delegator, "No delegation found between sender and delegator");
|
|
685
|
+
}
|
|
686
|
+
const signatures = (0, _ocap_util_lib_get_list_field.getListField)(tx, "signatures") || [];
|
|
687
|
+
for (const sig of signatures) if (sig?.delegator) {
|
|
688
|
+
if (context.txType && !MULTISIG_DELEGATION_TX_TYPES.has(context.txType)) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false });
|
|
689
|
+
await assertDelegatorPairAuthorized(context, sig.signer, sig.delegator, "No delegation found between signer and delegator");
|
|
690
|
+
}
|
|
155
691
|
};
|
|
156
692
|
const pre = new _ocap_tx_pipeline.Runner("pre-execute");
|
|
157
|
-
pre.use(
|
|
158
|
-
|
|
159
|
-
if (
|
|
160
|
-
|
|
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);
|
|
161
700
|
});
|
|
162
|
-
pre.use(_ocap_tx_pipeline.pipes.DecodeTx);
|
|
163
701
|
pre.use(_ocap_tx_pipeline.pipes.VerifyBlocked({
|
|
164
702
|
filter,
|
|
165
703
|
stateKeys: ["tx.from"]
|
|
166
704
|
}));
|
|
167
|
-
pre.use(
|
|
168
|
-
|
|
169
|
-
|
|
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
|
+
});
|
|
170
733
|
pre.use(async (context, next) => {
|
|
171
734
|
const syncState = getSyncState(context);
|
|
172
735
|
const execId = context.executionId;
|
|
@@ -175,57 +738,53 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
175
738
|
if (filter.has(context.txHash)) {
|
|
176
739
|
if (await context.statedb.tx.get(context.txHash, context)) return next(new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
|
|
177
740
|
}
|
|
178
|
-
if (
|
|
179
|
-
const inFlightUnsignedOwner =
|
|
741
|
+
if (context.unsignedTxHash) {
|
|
742
|
+
const inFlightUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
|
|
180
743
|
if (inFlightUnsignedOwner && inFlightUnsignedOwner !== execId || await hasCommittedUnsignedTx(context)) return next(new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
|
|
181
744
|
}
|
|
182
745
|
filter.add(context.txHash);
|
|
183
746
|
return next();
|
|
184
747
|
});
|
|
185
|
-
pre.use(
|
|
186
|
-
|
|
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
|
+
});
|
|
763
|
+
pre.use((context, next) => {
|
|
764
|
+
context.isSignatureVerified = true;
|
|
765
|
+
return next();
|
|
766
|
+
});
|
|
187
767
|
pre.use(async (context, next) => {
|
|
188
768
|
try {
|
|
189
769
|
await withPreWriteLock(context, async () => {
|
|
190
770
|
const syncState = getSyncState(context);
|
|
191
|
-
if (context.height === void 0 && !context.ledgerSequence) {
|
|
192
|
-
delete context.expectedLedgerSequence;
|
|
193
|
-
delete context.dedupActive;
|
|
194
|
-
const dedupHeight = (0, _ocap_state.resolveDedupActivationHeight)(context);
|
|
195
|
-
if (dedupHeight > 0 && dedupHeight < _ocap_state.PENDING_DEDUP_ACTIVATION_HEIGHT) await (0, _ocap_tx_pipeline.resolveEffectiveHeight)(context);
|
|
196
|
-
}
|
|
197
|
-
const isActiveNow = await isUnsignedDedupActive(context);
|
|
198
|
-
context.dedupActive = isActiveNow;
|
|
199
771
|
const execId = context.executionId || Symbol("tx-exec");
|
|
200
772
|
context.executionId = execId;
|
|
201
773
|
if (context.txHash) {
|
|
202
774
|
const existingTxOwner = syncState.inFlightTxHashes.get(context.txHash);
|
|
203
775
|
if (existingTxOwner && existingTxOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
204
776
|
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
if (context.unsignedTxHash) {
|
|
211
|
-
const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
|
|
212
|
-
if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
213
|
-
}
|
|
214
|
-
if (await hasCommittedUnsignedTx(context)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
777
|
+
const senderState = await assertSenderNonceFresh(context);
|
|
778
|
+
await assertDelegationAuthorized(context);
|
|
779
|
+
if (context.unsignedTxHash) {
|
|
780
|
+
const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
|
|
781
|
+
if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
215
782
|
}
|
|
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);
|
|
216
785
|
if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
|
|
217
|
-
if (
|
|
786
|
+
if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
|
|
218
787
|
await runSinglePipe(require_pipes_write_ledger.WriteLedger, context);
|
|
219
|
-
delete context.dedupActive;
|
|
220
|
-
const isActiveAfterWrite = await isUnsignedDedupActive(context);
|
|
221
|
-
context.dedupActive = isActiveAfterWrite;
|
|
222
|
-
if (isActiveAfterWrite) {
|
|
223
|
-
if (!isActiveNow) (0, _ocap_tx_pipeline.assertCanonicalActiveTx)(context);
|
|
224
|
-
const nonceBn = (0, _ocap_state.parseNonceBn)(context.tx?.nonce);
|
|
225
|
-
if (!nonceBn || nonceBn.lte(new _ocap_util.BN(0))) throw new _ocap_util_lib_error.CustomError("INVALID_NONCE", "tx.nonce should be a positive integer");
|
|
226
|
-
if (await hasCommittedUnsignedTx(context)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
227
|
-
if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
|
|
228
|
-
}
|
|
229
788
|
});
|
|
230
789
|
return next();
|
|
231
790
|
} catch (err) {
|
|
@@ -234,20 +793,40 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
234
793
|
});
|
|
235
794
|
const ensureGasFeePaid = (context) => {
|
|
236
795
|
const gasRunner = new _ocap_tx_pipeline.Runner("ensure-gas-fee-paid");
|
|
796
|
+
gasRunner.use(async (ctx, next) => {
|
|
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
|
+
};
|
|
806
|
+
ctx.isFailedTxGasCharge = true;
|
|
807
|
+
ctx.gasPaid = false;
|
|
808
|
+
ctx.senderUpdates = {};
|
|
809
|
+
ctx.senderChange = void 0;
|
|
810
|
+
ctx.updatedAccounts = [];
|
|
811
|
+
ctx.feeVaultChange = void 0;
|
|
812
|
+
ctx.gasVaultChange = void 0;
|
|
813
|
+
return next();
|
|
814
|
+
});
|
|
237
815
|
gasRunner.use(ensureTxGas);
|
|
238
816
|
gasRunner.use(ensureTxCost);
|
|
239
817
|
gasRunner.use(async (ctx, next) => {
|
|
240
818
|
const { tx, statedb, senderUpdates, updateVaults } = ctx;
|
|
241
819
|
if (ctx.senderState && ctx.states && tx) {
|
|
242
|
-
|
|
820
|
+
if (tx.delegator && !ctx.delegationState && !ctx.isImplicitDelegation) return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Cannot charge gas to sender without verified delegation"));
|
|
821
|
+
const senderState = ctx.senderState;
|
|
243
822
|
const updates = ctx.states.account.update(senderState, {
|
|
244
823
|
nonce: tx.nonce,
|
|
245
|
-
pk: tx.pk,
|
|
824
|
+
pk: tx.delegator ? senderState.pk : tx.pk,
|
|
246
825
|
...senderUpdates
|
|
247
826
|
}, ctx);
|
|
248
|
-
await statedb.account.update(senderState.address, updates, ctx);
|
|
827
|
+
ctx.senderState = await statedb.account.update(senderState.address, updates, ctx) || senderState;
|
|
249
828
|
if (updateVaults) await updateVaults();
|
|
250
|
-
}
|
|
829
|
+
} else if (updateVaults) await updateVaults();
|
|
251
830
|
return next();
|
|
252
831
|
});
|
|
253
832
|
return new Promise((resolve, reject) => {
|
|
@@ -266,9 +845,41 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
266
845
|
});
|
|
267
846
|
});
|
|
268
847
|
};
|
|
848
|
+
const attachSecurityStrikeToError = async (err, ctx) => {
|
|
849
|
+
if (!err || err._strikeRecorded || err._unauthenticatedExtraFailure === true) return;
|
|
850
|
+
const classified = require_gas_security_guard.classifyErrorStrikeCategory(err);
|
|
851
|
+
if (!classified.shouldRecordStrike) return;
|
|
852
|
+
const secCfg = ctx.config?.transaction?.security;
|
|
853
|
+
const strikeOnAllErrors = secCfg?.strikeOnAllErrors === true;
|
|
854
|
+
if (!(classified.category === "WAF_REJECT" || classified.category === "INVARIANT_VIOLATION" || classified.category === "PAYMASTER_VIOLATION" || strikeOnAllErrors)) return;
|
|
855
|
+
const actors = await require_gas_security_guard.resolveVerifiedStrikeActors(ctx);
|
|
856
|
+
if (actors.length === 0) return;
|
|
857
|
+
err._strikeRecorded = true;
|
|
858
|
+
const fishermanAddress = secCfg?.fishermanAddress;
|
|
859
|
+
const nowMs = ctx.txTime ? +new Date(ctx.txTime) : Date.now();
|
|
860
|
+
const { primaryWarning, slashEvidence } = await require_gas_security_guard.recordActorSecurityStrike({
|
|
861
|
+
actors,
|
|
862
|
+
category: classified.category,
|
|
863
|
+
reasonCode: classified.code,
|
|
864
|
+
txHash: ctx.txHash,
|
|
865
|
+
config: ctx.config,
|
|
866
|
+
statedb: ctx.statedb,
|
|
867
|
+
txn: ctx.txn,
|
|
868
|
+
fishermanAddress,
|
|
869
|
+
nowMs,
|
|
870
|
+
telemetry: ctx.gasQuotaTelemetry
|
|
871
|
+
});
|
|
872
|
+
if (primaryWarning && !err.warning) {
|
|
873
|
+
err.warning = primaryWarning;
|
|
874
|
+
ctx.securityWarning = primaryWarning;
|
|
875
|
+
}
|
|
876
|
+
if (slashEvidence && !err.slashEvidence) err.slashEvidence = slashEvidence;
|
|
877
|
+
};
|
|
269
878
|
const execute = async (context, protocols, isRetrySupported = false) => new Promise((resolve, reject) => {
|
|
270
|
-
|
|
879
|
+
context._protocols = protocols;
|
|
880
|
+
pre.run(context, async (err) => {
|
|
271
881
|
if (err) {
|
|
882
|
+
if (!isRetrySupported) await attachSecurityStrikeToError(err, context);
|
|
272
883
|
context.logger?.error("Failed to prepare transaction", {
|
|
273
884
|
error: err,
|
|
274
885
|
txHash: context.txHash,
|
|
@@ -278,16 +889,30 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
278
889
|
}
|
|
279
890
|
const protocol = protocols[getTxName(context.txType)];
|
|
280
891
|
if (!protocol) return reject(new _ocap_util_lib_error.CustomError("UNSUPPORTED_TX", `Unsupported tx type ${context.txType}`));
|
|
281
|
-
|
|
892
|
+
(0, _ocap_tx_pipeline.installStateWriteInterceptor)(context);
|
|
893
|
+
protocol.run(context, async (rawError) => {
|
|
894
|
+
const underlyingDb = context.statedb?._underlyingStateDb;
|
|
895
|
+
if (underlyingDb) context.statedb = underlyingDb;
|
|
896
|
+
let error = rawError;
|
|
282
897
|
context.timer?.mark("protocol");
|
|
898
|
+
if (!error) try {
|
|
899
|
+
(0, _ocap_tx_pipeline.inspectPostExecutionInvariants)(context);
|
|
900
|
+
} catch (invariantErr) {
|
|
901
|
+
error = invariantErr;
|
|
902
|
+
}
|
|
283
903
|
if (isRetrySupported) {
|
|
284
904
|
if (error) return reject(error);
|
|
285
905
|
return resolve(context);
|
|
286
906
|
}
|
|
907
|
+
if (error) {
|
|
908
|
+
await (0, _ocap_tx_pipeline.rollbackTrackedStateWrites)(context);
|
|
909
|
+
context.events = [];
|
|
910
|
+
await attachSecurityStrikeToError(error, context);
|
|
911
|
+
}
|
|
287
912
|
const txStatus = error ? error.code || "INTERNAL" : "OK";
|
|
288
913
|
const states = getStates(context);
|
|
289
914
|
let txState = states.tx.create(context, txStatus);
|
|
290
|
-
if (shouldPersistTx(error)) try {
|
|
915
|
+
if (shouldPersistTx(error, context)) try {
|
|
291
916
|
if (error) {
|
|
292
917
|
await ensureGasFeePaid(context);
|
|
293
918
|
txState = states.tx.create(context, txStatus);
|
|
@@ -312,7 +937,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
312
937
|
txSize: context.txSize,
|
|
313
938
|
senderAddr: context.tx?.from,
|
|
314
939
|
ledgerSequence: context.ledgerSequence,
|
|
315
|
-
status: error ? shouldPersistTx(error) ? "PERSISTED_FAILED" : "FAILED" : "OK",
|
|
940
|
+
status: error ? shouldPersistTx(error, context) ? "PERSISTED_FAILED" : "FAILED" : "OK",
|
|
316
941
|
errorCode: error ? error.code || "INTERNAL" : null,
|
|
317
942
|
retried: Boolean(error)
|
|
318
943
|
});
|
|
@@ -350,10 +975,11 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
350
975
|
"extra",
|
|
351
976
|
"logger",
|
|
352
977
|
"ledgerSequence",
|
|
353
|
-
"height",
|
|
354
978
|
"timer",
|
|
355
979
|
"executionId"
|
|
356
980
|
]);
|
|
981
|
+
const preFlightSnapshot = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
|
|
982
|
+
if (preFlightSnapshot !== void 0) ctx[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL] = preFlightSnapshot;
|
|
357
983
|
ctx.txn = txn;
|
|
358
984
|
if (savedLedgerSequence !== void 0) ctx.ledgerSequence = savedLedgerSequence;
|
|
359
985
|
ctx.timer?.mark("lockWait");
|
|
@@ -425,7 +1051,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
425
1051
|
txState,
|
|
426
1052
|
request: context.extra?.request
|
|
427
1053
|
});
|
|
428
|
-
if (txState && shouldPersistTx(err)) {
|
|
1054
|
+
if (txState && shouldPersistTx(err, ctx)) {
|
|
429
1055
|
ctx.events = [];
|
|
430
1056
|
try {
|
|
431
1057
|
txState = await runAsLambda(async (txn) => {
|
|
@@ -434,12 +1060,30 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
434
1060
|
cacheStates: null
|
|
435
1061
|
});
|
|
436
1062
|
ctx.timer?.mark("lockWait");
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
1063
|
+
const strikeSnapshot = require_gas_security_guard.snapshotActorSecurityRecords([
|
|
1064
|
+
ctx.tx?.delegator || "",
|
|
1065
|
+
ctx.tx?.from || "",
|
|
1066
|
+
ctx.gasStake?.sponsorAddress || ""
|
|
1067
|
+
].filter(Boolean), ctx.statedb, ctx.txHash);
|
|
1068
|
+
const hadStrikeBefore = Boolean(err._strikeRecorded);
|
|
1069
|
+
const prevWarning = err.warning;
|
|
1070
|
+
const prevSlashEvidence = err.slashEvidence;
|
|
1071
|
+
try {
|
|
1072
|
+
await ensureGasFeePaid(ctx);
|
|
1073
|
+
await attachSecurityStrikeToError(err, ctx);
|
|
1074
|
+
const state = getStates(context).tx.create(ctx, txStatus);
|
|
1075
|
+
await ctx.statedb.tx.create(state.hash, state, ctx);
|
|
1076
|
+
await recordUnsignedTxInStateDb(ctx, state.hash);
|
|
1077
|
+
ctx.timer?.mark("txstate");
|
|
1078
|
+
return state;
|
|
1079
|
+
} catch (lambdaErr) {
|
|
1080
|
+
require_gas_security_guard.restoreActorSecurityRecords(strikeSnapshot, ctx.statedb);
|
|
1081
|
+
err._strikeRecorded = hadStrikeBefore;
|
|
1082
|
+
err.warning = prevWarning;
|
|
1083
|
+
err.slashEvidence = prevSlashEvidence;
|
|
1084
|
+
ctx.securityWarning = prevWarning;
|
|
1085
|
+
throw lambdaErr;
|
|
1086
|
+
}
|
|
443
1087
|
}, {
|
|
444
1088
|
cleanWorkingSet: true,
|
|
445
1089
|
verifyHash: true,
|
|
@@ -487,6 +1131,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
487
1131
|
perf: ctx.timer?.summaryV2()
|
|
488
1132
|
});
|
|
489
1133
|
} catch (innerErr) {
|
|
1134
|
+
await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
|
|
490
1135
|
ctx.logger?.error("Failed to save invalid transaction to statedb", {
|
|
491
1136
|
error: innerErr,
|
|
492
1137
|
txError: error,
|
|
@@ -497,6 +1142,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
497
1142
|
throw error;
|
|
498
1143
|
}
|
|
499
1144
|
} else {
|
|
1145
|
+
await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
|
|
500
1146
|
ctx.timer?.setMeta({
|
|
501
1147
|
txType: ctx.txType,
|
|
502
1148
|
txSize: ctx.txSize,
|
|
@@ -567,6 +1213,8 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
567
1213
|
var execute_default = createExecute;
|
|
568
1214
|
|
|
569
1215
|
//#endregion
|
|
1216
|
+
exports.PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL;
|
|
570
1217
|
exports.UNSIGNED_TX_EVIDENCE_DATA_PREFIX = UNSIGNED_TX_EVIDENCE_DATA_PREFIX;
|
|
571
1218
|
exports.default = execute_default;
|
|
572
|
-
exports.toUnsignedEvidenceKey = toUnsignedEvidenceKey;
|
|
1219
|
+
exports.toUnsignedEvidenceKey = toUnsignedEvidenceKey;
|
|
1220
|
+
exports.tryApplyPreFlightVerifiedSnapshot = tryApplyPreFlightVerifiedSnapshot;
|