@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
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
|
|
2
|
+
import { toStakeAddress } from "@arcblock/did-util";
|
|
3
|
+
import { getHasher, getSigner } from "@ocap/mcrypto";
|
|
4
|
+
import { account, evidence, parseNonceBn, stake } from "@ocap/state";
|
|
5
|
+
import { pipes } from "@ocap/tx-pipeline";
|
|
6
|
+
import { BN, fromTokenToUnit, isSameDid, toAddress as toAddress$1 } from "@ocap/util";
|
|
7
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
8
|
+
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
9
|
+
import cloneDeep from "lodash/cloneDeep.js";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { fromPublicKey as fromPublicKey$1 } from "@ocap/wallet";
|
|
12
|
+
|
|
13
|
+
//#region src/gas-security-guard.ts
|
|
14
|
+
const ZERO = new BN(0);
|
|
15
|
+
const BPS_DENOMINATOR = new BN(1e4);
|
|
16
|
+
const DEFAULT_MAX_FREE_GAS_TX_SIZE = 4096;
|
|
17
|
+
const DEFAULT_MAX_FREE_GAS_STATE_OPS = 6;
|
|
18
|
+
const DEFAULT_BURST_WINDOW_MS = 6e4;
|
|
19
|
+
const DEFAULT_BASE_BURST_ALLOWANCE = 10;
|
|
20
|
+
const DEFAULT_BURST_REJECT_MULTIPLE = 100;
|
|
21
|
+
const DEFAULT_DELEGATED_BURST_MULTIPLE = 20;
|
|
22
|
+
const DEFAULT_STRIKE_WINDOW_MS = 6e5;
|
|
23
|
+
const DEFAULT_WARNING_STRIKE_THRESHOLD = 2;
|
|
24
|
+
const DEFAULT_THROTTLE_STRIKE_THRESHOLD = 5;
|
|
25
|
+
const DEFAULT_SLASH_STRIKE_THRESHOLD = 10;
|
|
26
|
+
const DEFAULT_THROTTLE_COOLDOWN_MS = 15e3;
|
|
27
|
+
const DEFAULT_GAS_PASS_EPOCH_SECONDS = 60;
|
|
28
|
+
const DEFAULT_FISHERMAN_BOUNTY_BPS = 1e3;
|
|
29
|
+
const MAX_TRACKED_ACTORS = 1e4;
|
|
30
|
+
const MAX_NULLIFIERS_PER_STAKE = 5e3;
|
|
31
|
+
const MAX_FREE_VARIANTS = 2;
|
|
32
|
+
/**
|
|
33
|
+
* High-overhead creator, factory, token-issuance, rollup, and batch transaction types
|
|
34
|
+
* that ALWAYS require direct gas payment (`requiresDirectGas: true`) and cannot waive
|
|
35
|
+
* gas via self-staked `Stake-for-Gas` or Unlinkable Gas Pass.
|
|
36
|
+
*/
|
|
37
|
+
const DIRECT_GAS_REQUIRED_TX_TYPES = new Set([
|
|
38
|
+
"create_token",
|
|
39
|
+
"create_token_factory",
|
|
40
|
+
"update_token_factory",
|
|
41
|
+
"create_factory",
|
|
42
|
+
"create_asset",
|
|
43
|
+
"mint_asset",
|
|
44
|
+
"update_asset",
|
|
45
|
+
"create_rollup",
|
|
46
|
+
"update_rollup",
|
|
47
|
+
"create_rollup_block",
|
|
48
|
+
"join_rollup",
|
|
49
|
+
"leave_rollup",
|
|
50
|
+
"pause_rollup",
|
|
51
|
+
"resume_rollup",
|
|
52
|
+
"close_rollup",
|
|
53
|
+
"migrate_rollup",
|
|
54
|
+
"claim_block_reward",
|
|
55
|
+
"slash_stake",
|
|
56
|
+
"return_stake",
|
|
57
|
+
"execute_transaction_block"
|
|
58
|
+
]);
|
|
59
|
+
/**
|
|
60
|
+
* Everyday end-user transaction types eligible for `Stake-for-Gas` free gas waiver
|
|
61
|
+
* when within the 3D envelope (`txType` allowlist + `txSize <= 4096` + `stateOps <= 6`).
|
|
62
|
+
*/
|
|
63
|
+
const FREE_GAS_ELIGIBLE_TX_TYPES = new Set([
|
|
64
|
+
"transfer",
|
|
65
|
+
"transfer_v2",
|
|
66
|
+
"transfer_v3",
|
|
67
|
+
"exchange",
|
|
68
|
+
"exchange_v2",
|
|
69
|
+
"declare",
|
|
70
|
+
"account_migrate",
|
|
71
|
+
"delegate",
|
|
72
|
+
"revoke_delegate",
|
|
73
|
+
"stake",
|
|
74
|
+
"revoke_stake",
|
|
75
|
+
"claim_stake",
|
|
76
|
+
"consume_asset",
|
|
77
|
+
"acquire_asset_v2",
|
|
78
|
+
"acquire_asset_v3",
|
|
79
|
+
"mint_token",
|
|
80
|
+
"burn_token",
|
|
81
|
+
"deposit_token_v2",
|
|
82
|
+
"withdraw_token_v2",
|
|
83
|
+
"poke"
|
|
84
|
+
]);
|
|
85
|
+
const registryByStateDb = /* @__PURE__ */ new WeakMap();
|
|
86
|
+
let defaultGlobalRegistry = createEmptyRegistry();
|
|
87
|
+
function createEmptyRegistry() {
|
|
88
|
+
return {
|
|
89
|
+
actors: /* @__PURE__ */ new Map(),
|
|
90
|
+
consumedNullifiers: /* @__PURE__ */ new Map(),
|
|
91
|
+
txWarningsByHash: /* @__PURE__ */ new Map()
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function getUnderlyingTarget(statedb) {
|
|
95
|
+
if (!statedb || typeof statedb !== "object") return null;
|
|
96
|
+
const raw = statedb._underlyingStateDb || statedb;
|
|
97
|
+
const accountTable = raw.account;
|
|
98
|
+
if (accountTable && typeof accountTable === "object") return accountTable;
|
|
99
|
+
return raw;
|
|
100
|
+
}
|
|
101
|
+
function getGasSecurityRegistry(statedb) {
|
|
102
|
+
const target = getUnderlyingTarget(statedb);
|
|
103
|
+
if (!target) return defaultGlobalRegistry;
|
|
104
|
+
let reg = registryByStateDb.get(target);
|
|
105
|
+
if (!reg) {
|
|
106
|
+
reg = createEmptyRegistry();
|
|
107
|
+
registryByStateDb.set(target, reg);
|
|
108
|
+
}
|
|
109
|
+
return reg;
|
|
110
|
+
}
|
|
111
|
+
function resetGasSecurityState(statedb) {
|
|
112
|
+
const target = getUnderlyingTarget(statedb);
|
|
113
|
+
if (target) registryByStateDb.set(target, createEmptyRegistry());
|
|
114
|
+
defaultGlobalRegistry = createEmptyRegistry();
|
|
115
|
+
}
|
|
116
|
+
function normalizeActorAddress(raw) {
|
|
117
|
+
if (typeof raw !== "string") return "";
|
|
118
|
+
const trimmed = raw.trim();
|
|
119
|
+
if (!trimmed) return "";
|
|
120
|
+
const stripped = trimmed.startsWith("did:abt:") ? toAddress$1(trimmed) : trimmed;
|
|
121
|
+
if (/^0x[0-9a-fA-F]{40}$/.test(stripped)) return account.ensureChecksumAddress(stripped.toLowerCase());
|
|
122
|
+
return account.ensureChecksumAddress(stripped);
|
|
123
|
+
}
|
|
124
|
+
function normalizeShortTxType(txType) {
|
|
125
|
+
if (typeof txType !== "string" || !txType.trim()) return "";
|
|
126
|
+
const parts = txType.trim().split(":");
|
|
127
|
+
return parts[parts.length - 1] || "";
|
|
128
|
+
}
|
|
129
|
+
function resolveGasSecurityConfig(config) {
|
|
130
|
+
const txGas = config?.transaction?.txGas || {};
|
|
131
|
+
const sec = (config?.transaction)?.security || {};
|
|
132
|
+
const numOr = (val, fallback) => typeof val === "number" && Number.isFinite(val) && val > 0 ? val : fallback;
|
|
133
|
+
const boolOr = (val, fallback) => typeof val === "boolean" ? val : fallback;
|
|
134
|
+
return {
|
|
135
|
+
enabled: boolOr(sec.enabled, true),
|
|
136
|
+
throttle: boolOr(sec.throttle, true),
|
|
137
|
+
burstEscalation: boolOr(sec.burstEscalation, true),
|
|
138
|
+
autoSlash: boolOr(sec.autoSlash, false),
|
|
139
|
+
gasPassNullifierCheck: boolOr(sec.gasPassNullifierCheck, false),
|
|
140
|
+
burstRejectMultiple: numOr(sec.burstRejectMultiple, DEFAULT_BURST_REJECT_MULTIPLE),
|
|
141
|
+
exemptActors: Array.isArray(sec.exemptActors) ? sec.exemptActors.map((a) => normalizeActorAddress(a)).filter(Boolean) : [],
|
|
142
|
+
delegatedBurstMultiple: numOr(sec.delegatedBurstMultiple, DEFAULT_DELEGATED_BURST_MULTIPLE),
|
|
143
|
+
maxFreeGasTxSize: numOr(txGas.maxFreeGasTxSize, DEFAULT_MAX_FREE_GAS_TX_SIZE),
|
|
144
|
+
maxFreeGasStateOps: numOr(txGas.maxFreeGasStateOps, DEFAULT_MAX_FREE_GAS_STATE_OPS),
|
|
145
|
+
burstWindowMs: numOr(txGas.burstWindowMs, DEFAULT_BURST_WINDOW_MS),
|
|
146
|
+
baseBurstAllowance: numOr(txGas.baseBurstAllowance, DEFAULT_BASE_BURST_ALLOWANCE),
|
|
147
|
+
strikeWindowMs: numOr(sec.strikeWindowMs, DEFAULT_STRIKE_WINDOW_MS),
|
|
148
|
+
warningThreshold: numOr(sec.warningThreshold, DEFAULT_WARNING_STRIKE_THRESHOLD),
|
|
149
|
+
throttleThreshold: numOr(sec.throttleThreshold, DEFAULT_THROTTLE_STRIKE_THRESHOLD),
|
|
150
|
+
slashThreshold: numOr(sec.slashThreshold, DEFAULT_SLASH_STRIKE_THRESHOLD),
|
|
151
|
+
throttleCooldownMs: numOr(sec.throttleCooldownMs, DEFAULT_THROTTLE_COOLDOWN_MS),
|
|
152
|
+
gasPassEpochSeconds: numOr(sec.gasPassEpochSeconds, DEFAULT_GAS_PASS_EPOCH_SECONDS),
|
|
153
|
+
fishermanBountyBps: typeof sec.fishermanBountyBps === "number" && Number.isFinite(sec.fishermanBountyBps) && sec.fishermanBountyBps >= 0 && sec.fishermanBountyBps <= 5e3 ? Math.floor(sec.fishermanBountyBps) : DEFAULT_FISHERMAN_BOUNTY_BPS
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** Actor keys are addresses, or `signer>principal` pairs for delegated-tx burst windows. */
|
|
157
|
+
function normalizeActorKey(raw) {
|
|
158
|
+
return raw.includes(">") ? raw.split(">").map((part) => part === "*" ? part : normalizeActorAddress(part)).join(">") : normalizeActorAddress(raw);
|
|
159
|
+
}
|
|
160
|
+
function getOrCreateActorRecord(reg, rawActor, nowMs, cfg) {
|
|
161
|
+
const actor = normalizeActorKey(rawActor);
|
|
162
|
+
let rec = reg.actors.get(actor);
|
|
163
|
+
if (rec) {
|
|
164
|
+
reg.actors.delete(actor);
|
|
165
|
+
reg.actors.set(actor, rec);
|
|
166
|
+
} else {
|
|
167
|
+
if (reg.actors.size >= MAX_TRACKED_ACTORS) {
|
|
168
|
+
let victim;
|
|
169
|
+
for (const [key, candidate] of reg.actors) if (candidate.cooldownUntilMs <= nowMs) {
|
|
170
|
+
victim = key;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
victim = victim ?? reg.actors.keys().next().value;
|
|
174
|
+
if (victim) reg.actors.delete(victim);
|
|
175
|
+
}
|
|
176
|
+
rec = {
|
|
177
|
+
actor,
|
|
178
|
+
bursts: [],
|
|
179
|
+
strikes: [],
|
|
180
|
+
cooldownUntilMs: 0
|
|
181
|
+
};
|
|
182
|
+
reg.actors.set(actor, rec);
|
|
183
|
+
}
|
|
184
|
+
const burstCutoff = nowMs - cfg.burstWindowMs;
|
|
185
|
+
rec.bursts = rec.bursts.filter((b) => b.t > burstCutoff);
|
|
186
|
+
const strikeCutoff = nowMs - cfg.strikeWindowMs;
|
|
187
|
+
rec.strikes = rec.strikes.filter((s) => s.timestampMs > strikeCutoff);
|
|
188
|
+
return rec;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* 3D `Stake-for-Gas` Eligibility Gate:
|
|
192
|
+
* 1. `txType` must be in `FREE_GAS_ELIGIBLE_TX_TYPES` (everyday user actions only).
|
|
193
|
+
* 2. `txSize` must be <= `maxFreeGasTxSize` (default 4096 bytes).
|
|
194
|
+
* 3. `stateOps` (`estimate.create + estimate.update`) must be <= `maxFreeGasStateOps` (default 6).
|
|
195
|
+
* 4. Failed transactions (`isFailedTxGasCharge === true`) NEVER waive gas.
|
|
196
|
+
*/
|
|
197
|
+
function evaluateStakeForGasEligibility(params) {
|
|
198
|
+
const cfg = resolveGasSecurityConfig(params.config);
|
|
199
|
+
if (params.isFailedTxGasCharge) return {
|
|
200
|
+
eligible: false,
|
|
201
|
+
reason: "FAILED_TX_REQUIRES_DIRECT_GAS"
|
|
202
|
+
};
|
|
203
|
+
const shortType = normalizeShortTxType(params.txType);
|
|
204
|
+
const customAllowlist = (params.config?.transaction?.txGas)?.freeGasAllowedTxTypes;
|
|
205
|
+
if ((!params.isThirdPartySponsor || params.enforceSponsor3DEligibility === true) && shortType) {
|
|
206
|
+
if (Array.isArray(customAllowlist) && customAllowlist.length > 0) {
|
|
207
|
+
if (!customAllowlist.some((t) => normalizeShortTxType(t) === shortType || t === params.txType)) return {
|
|
208
|
+
eligible: false,
|
|
209
|
+
reason: "TX_TYPE_REQUIRES_DIRECT_GAS"
|
|
210
|
+
};
|
|
211
|
+
} else if (DIRECT_GAS_REQUIRED_TX_TYPES.has(shortType) || typeof params.txType === "string" && params.txType.startsWith("fg:t:") && !FREE_GAS_ELIGIBLE_TX_TYPES.has(shortType)) return {
|
|
212
|
+
eligible: false,
|
|
213
|
+
reason: "TX_TYPE_REQUIRES_DIRECT_GAS"
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
if ((typeof params.txSize === "number" ? params.txSize : 0) > cfg.maxFreeGasTxSize) return {
|
|
217
|
+
eligible: false,
|
|
218
|
+
reason: "TX_SIZE_EXCEEDS_FREE_GAS_CEILING"
|
|
219
|
+
};
|
|
220
|
+
if ((params.gasEstimate?.create || 0) + (params.gasEstimate?.update || 0) > cfg.maxFreeGasStateOps) return {
|
|
221
|
+
eligible: false,
|
|
222
|
+
reason: "STATE_OPS_EXCEED_FREE_GAS_CEILING"
|
|
223
|
+
};
|
|
224
|
+
return { eligible: true };
|
|
225
|
+
}
|
|
226
|
+
const CREATION_TARGET_TX_TYPES = new Set([
|
|
227
|
+
"create_asset",
|
|
228
|
+
"acquire_asset",
|
|
229
|
+
"acquire_asset_v2",
|
|
230
|
+
"acquire_asset_v3",
|
|
231
|
+
"create_factory",
|
|
232
|
+
"create_token",
|
|
233
|
+
"create_token_factory"
|
|
234
|
+
]);
|
|
235
|
+
/**
|
|
236
|
+
* Extracts all target DIDs referenced by a transaction (`itx.to`, `itx.factory`, `itx.tokenFactory`,
|
|
237
|
+
* `itx.address`, `itx.assets`, `itx.inputs`, `itx.outputs`, `itx.sender`, `itx.receiver`) for
|
|
238
|
+
* Paymaster `allowedTargets` scoping.
|
|
239
|
+
*/
|
|
240
|
+
function extractTransactionTargets(tx$1, decodedItx, txType) {
|
|
241
|
+
if ((!tx$1 || typeof tx$1 !== "object") && (!decodedItx || typeof decodedItx !== "object")) return [];
|
|
242
|
+
const targets = /* @__PURE__ */ new Set();
|
|
243
|
+
const addTarget = (candidate) => {
|
|
244
|
+
const norm = normalizeActorAddress(candidate);
|
|
245
|
+
if (norm) targets.add(norm);
|
|
246
|
+
};
|
|
247
|
+
const shortType = normalizeShortTxType(txType || (tx$1?.itx)?.typeUrl);
|
|
248
|
+
const rawItx = decodedItx || tx$1?.itxJson || tx$1?.itx;
|
|
249
|
+
const itx = rawItx && typeof rawItx === "object" && !Buffer.isBuffer(rawItx) && typeof rawItx.value !== "string" ? rawItx : decodedItx;
|
|
250
|
+
if (itx && typeof itx === "object") {
|
|
251
|
+
const scalarFields = [
|
|
252
|
+
"to",
|
|
253
|
+
"factory",
|
|
254
|
+
"receiver",
|
|
255
|
+
"rollup",
|
|
256
|
+
"tokenAddress",
|
|
257
|
+
"factoryAddress",
|
|
258
|
+
"tokenFactory",
|
|
259
|
+
"owner",
|
|
260
|
+
"parent",
|
|
261
|
+
"issuer",
|
|
262
|
+
"validator",
|
|
263
|
+
"contract",
|
|
264
|
+
"delegatee"
|
|
265
|
+
];
|
|
266
|
+
if (!CREATION_TARGET_TX_TYPES.has(shortType)) scalarFields.push("address");
|
|
267
|
+
for (const field of scalarFields) if (typeof itx[field] === "string" && itx[field]) addTarget(itx[field]);
|
|
268
|
+
const extractPartySubTargets = (party) => {
|
|
269
|
+
if (!party || typeof party !== "object") return;
|
|
270
|
+
const p = party;
|
|
271
|
+
addTarget(p.address);
|
|
272
|
+
addTarget(p.owner);
|
|
273
|
+
addTarget(p.to);
|
|
274
|
+
const pAssets = getListField(p, "assets");
|
|
275
|
+
if (Array.isArray(pAssets)) for (const a of pAssets) addTarget(a);
|
|
276
|
+
const pTokens = getListField(p, "tokens");
|
|
277
|
+
if (Array.isArray(pTokens)) {
|
|
278
|
+
for (const tok of pTokens) if (tok && typeof tok === "object") addTarget(tok.address);
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
if (itx.sender && typeof itx.sender === "object") extractPartySubTargets(itx.sender);
|
|
282
|
+
if (itx.receiver && typeof itx.receiver === "object") extractPartySubTargets(itx.receiver);
|
|
283
|
+
const assets = getListField(itx, "assets");
|
|
284
|
+
if (Array.isArray(assets)) for (const a of assets) addTarget(a);
|
|
285
|
+
const inputs = getListField(itx, "inputs");
|
|
286
|
+
if (Array.isArray(inputs)) for (const inp of inputs) extractPartySubTargets(inp);
|
|
287
|
+
const outputs = getListField(itx, "outputs");
|
|
288
|
+
if (Array.isArray(outputs)) for (const out of outputs) extractPartySubTargets(out);
|
|
289
|
+
}
|
|
290
|
+
return Array.from(targets);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Verifies Merchant / DApp Paymaster (`extra.gasStakeHeaders` JWT) scope constraints:
|
|
294
|
+
* - `allowedTxTypes`: if present, transaction type must be in `allowedTxTypes`.
|
|
295
|
+
* - `allowedTargets`: if present, transaction must touch at least one target and EVERY target
|
|
296
|
+
* touched by the transaction (excluding the sender `tx.from` itself in multi-input change)
|
|
297
|
+
* must be in `allowedTargets`.
|
|
298
|
+
* - `maxGasPerTx`: if present, `totalGas` must not exceed `maxGasPerTx`.
|
|
299
|
+
*/
|
|
300
|
+
function verifyPaymasterConstraints(params) {
|
|
301
|
+
const { decoded, tx: tx$1, itx, txType, totalGas } = params;
|
|
302
|
+
const isPaymasterDirectCharge = decoded.mode === "paymaster" || decoded.chargeSponsorBalance === true;
|
|
303
|
+
if (Array.isArray(decoded.allowedTxTypes)) {
|
|
304
|
+
if (decoded.allowedTxTypes.length === 0) return {
|
|
305
|
+
valid: false,
|
|
306
|
+
reason: "PAYMASTER_TX_TYPE_FORBIDDEN",
|
|
307
|
+
isPaymasterDirectCharge
|
|
308
|
+
};
|
|
309
|
+
const shortType = normalizeShortTxType(txType);
|
|
310
|
+
if (!decoded.allowedTxTypes.some((allowed) => allowed === txType || normalizeShortTxType(allowed) === shortType)) return {
|
|
311
|
+
valid: false,
|
|
312
|
+
reason: "PAYMASTER_TX_TYPE_FORBIDDEN",
|
|
313
|
+
isPaymasterDirectCharge
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
if (Array.isArray(decoded.allowedTargets)) {
|
|
317
|
+
const normalizedAllowed = decoded.allowedTargets.map((t) => normalizeActorAddress(t)).filter(Boolean);
|
|
318
|
+
if (normalizedAllowed.length === 0) return {
|
|
319
|
+
valid: false,
|
|
320
|
+
reason: "PAYMASTER_TARGET_FORBIDDEN",
|
|
321
|
+
isPaymasterDirectCharge
|
|
322
|
+
};
|
|
323
|
+
const txFrom = normalizeActorAddress(tx$1?.from);
|
|
324
|
+
const allTargets = extractTransactionTargets(tx$1, itx, txType).filter((t) => t !== txFrom);
|
|
325
|
+
if (allTargets.length === 0) return {
|
|
326
|
+
valid: false,
|
|
327
|
+
reason: "PAYMASTER_TARGET_FORBIDDEN",
|
|
328
|
+
isPaymasterDirectCharge
|
|
329
|
+
};
|
|
330
|
+
if (!allTargets.every((target) => normalizedAllowed.some((allowed) => isSameDid(target, allowed) || target === allowed))) return {
|
|
331
|
+
valid: false,
|
|
332
|
+
reason: "PAYMASTER_TARGET_FORBIDDEN",
|
|
333
|
+
isPaymasterDirectCharge
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
if (decoded.maxGasPerTx !== void 0 && decoded.maxGasPerTx !== null && decoded.maxGasPerTx !== "") {
|
|
337
|
+
const capStr = String(decoded.maxGasPerTx).trim();
|
|
338
|
+
if (!/^(0|[1-9]\d*)$/.test(capStr)) return {
|
|
339
|
+
valid: false,
|
|
340
|
+
reason: "PAYMASTER_MAX_GAS_EXCEEDED",
|
|
341
|
+
isPaymasterDirectCharge
|
|
342
|
+
};
|
|
343
|
+
const capBN = new BN(capStr, 10);
|
|
344
|
+
if ((totalGas ?? ZERO).gt(capBN)) return {
|
|
345
|
+
valid: false,
|
|
346
|
+
reason: "PAYMASTER_MAX_GAS_EXCEEDED",
|
|
347
|
+
isPaymasterDirectCharge
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
valid: true,
|
|
352
|
+
isPaymasterDirectCharge
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Computes the SHA-256 hash of a stake owner's secret for Unlinkable Gas Pass verification:
|
|
357
|
+
* `SHA256("ocap:gas-pass-secret:v1:" + passSecret)`
|
|
358
|
+
*/
|
|
359
|
+
function computeUnlinkableGasPassSecretHash(passSecret) {
|
|
360
|
+
return createHash("sha256").update(`ocap:gas-pass-secret:v1:${passSecret}`).digest("hex").toLowerCase();
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Computes the deterministic commitment for a Consumer Self-Use Unlinkable Gas Pass:
|
|
364
|
+
* `SHA256("ocap:gas-pass:v1:" + normalizeActorAddress(stakeId) + ":" + epoch + ":" + nullifier + ":" + txHash)`
|
|
365
|
+
*/
|
|
366
|
+
function computeUnlinkableGasPassCommitment(params) {
|
|
367
|
+
const normStakeId = normalizeActorAddress(params.stakeId);
|
|
368
|
+
return createHash("sha256").update(`ocap:gas-pass:v1:${normStakeId}:${params.epoch}:${params.nullifier}:${params.txHash}`).digest("hex");
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Verifies and consumes a Consumer Self-Use Unlinkable Gas Pass (`extra.gasPass`),
|
|
372
|
+
* allowing a user who staked ABT on their main DID to pay/waive gas from a fresh
|
|
373
|
+
* unlinked sub-DID without revealing their main DID on-chain in `tx.from`, while
|
|
374
|
+
* strictly enforcing cryptographic authorization (`passSecret` matching `stakeState.gasPassSecretHash`
|
|
375
|
+
* or `pk`+`signature` signed by `stakeState.sender`), `nullifier` single-use per epoch, and
|
|
376
|
+
* stake-proportional quota.
|
|
377
|
+
*/
|
|
378
|
+
function verifyAndConsumeUnlinkableGasPass(params) {
|
|
379
|
+
const { gasPass, stakeState, txHash, config, statedb } = params;
|
|
380
|
+
if (!gasPass || typeof gasPass !== "object") return {
|
|
381
|
+
valid: false,
|
|
382
|
+
reason: "INVALID_GAS_PASS"
|
|
383
|
+
};
|
|
384
|
+
const stakeId = normalizeActorAddress(gasPass.stakeId);
|
|
385
|
+
const nullifier = typeof gasPass.nullifier === "string" ? gasPass.nullifier.trim() : "";
|
|
386
|
+
const commitment = typeof gasPass.commitment === "string" ? gasPass.commitment.trim().toLowerCase() : "";
|
|
387
|
+
const epoch = typeof gasPass.epoch === "number" && Number.isInteger(gasPass.epoch) ? gasPass.epoch : -1;
|
|
388
|
+
if (!stakeId || !nullifier || nullifier.length < 16 || nullifier.length > 256 || !commitment || epoch < 0) return {
|
|
389
|
+
valid: false,
|
|
390
|
+
reason: "INVALID_GAS_PASS_FORMAT"
|
|
391
|
+
};
|
|
392
|
+
if (!stakeState || normalizeActorAddress(stakeState.address) !== stakeId) return {
|
|
393
|
+
valid: false,
|
|
394
|
+
reason: "GAS_PASS_STAKE_NOT_FOUND"
|
|
395
|
+
};
|
|
396
|
+
const stakeSender = normalizeActorAddress(stakeState.sender);
|
|
397
|
+
const stakeReceiver = normalizeActorAddress(stakeState.receiver);
|
|
398
|
+
if (!stakeSender || stakeSender !== stakeReceiver || toStakeAddress(stakeSender, stakeSender) !== stakeId) return {
|
|
399
|
+
valid: false,
|
|
400
|
+
reason: "GAS_PASS_NOT_SELF_STAKE"
|
|
401
|
+
};
|
|
402
|
+
const minStakeUnit = fromTokenToUnit(config.transaction.txGas.minStake, config.token.decimal);
|
|
403
|
+
if (new BN(stakeState.tokens?.[config.token.address] || 0).lt(minStakeUnit)) return {
|
|
404
|
+
valid: false,
|
|
405
|
+
reason: "GAS_PASS_INSUFFICIENT_STAKE"
|
|
406
|
+
};
|
|
407
|
+
const cfg = resolveGasSecurityConfig(config);
|
|
408
|
+
const nowSec = Math.floor((params.nowMs ?? Date.now()) / 1e3);
|
|
409
|
+
const currentEpoch = Math.floor(nowSec / cfg.gasPassEpochSeconds);
|
|
410
|
+
if (Math.abs(epoch - currentEpoch) > 1) return {
|
|
411
|
+
valid: false,
|
|
412
|
+
reason: "GAS_PASS_EPOCH_EXPIRED"
|
|
413
|
+
};
|
|
414
|
+
const expectedCommitment = computeUnlinkableGasPassCommitment({
|
|
415
|
+
stakeId,
|
|
416
|
+
epoch,
|
|
417
|
+
nullifier,
|
|
418
|
+
txHash
|
|
419
|
+
}).toLowerCase();
|
|
420
|
+
if (commitment !== expectedCommitment) return {
|
|
421
|
+
valid: false,
|
|
422
|
+
reason: "GAS_PASS_COMMITMENT_MISMATCH"
|
|
423
|
+
};
|
|
424
|
+
const stakeRecord = stakeState;
|
|
425
|
+
const stakeData = stakeRecord.data;
|
|
426
|
+
const rawSecretHash = stakeRecord.gasPassSecretHash || stakeData?.gasPassSecretHash;
|
|
427
|
+
let isAuthorized = false;
|
|
428
|
+
if (typeof gasPass.passSecret === "string" && gasPass.passSecret.length > 0 && typeof rawSecretHash === "string" && rawSecretHash.length > 0) {
|
|
429
|
+
if (computeUnlinkableGasPassSecretHash(gasPass.passSecret) === rawSecretHash.trim().toLowerCase()) isAuthorized = true;
|
|
430
|
+
}
|
|
431
|
+
if (!isAuthorized && typeof gasPass.pk === "string" && gasPass.pk && typeof gasPass.signature === "string" && gasPass.signature) try {
|
|
432
|
+
const didType = toTypeInfo(stakeSender);
|
|
433
|
+
if (normalizeActorAddress(fromPublicKey$1(gasPass.pk, didType).address) === stakeSender || isFromPublicKey(stakeSender, gasPass.pk)) {
|
|
434
|
+
const signer = getSigner(didType.pk);
|
|
435
|
+
const hashedMsg = getHasher(didType.hash)(expectedCommitment, 1);
|
|
436
|
+
if (signer.verify(hashedMsg, gasPass.signature, gasPass.pk) || signer.verify(expectedCommitment, gasPass.signature, gasPass.pk)) isAuthorized = true;
|
|
437
|
+
}
|
|
438
|
+
} catch {
|
|
439
|
+
isAuthorized = false;
|
|
440
|
+
}
|
|
441
|
+
if (!isAuthorized) return {
|
|
442
|
+
valid: false,
|
|
443
|
+
reason: "GAS_PASS_UNAUTHORIZED"
|
|
444
|
+
};
|
|
445
|
+
if (!cfg.gasPassNullifierCheck) return {
|
|
446
|
+
valid: true,
|
|
447
|
+
stakeId
|
|
448
|
+
};
|
|
449
|
+
const reg = getGasSecurityRegistry(statedb);
|
|
450
|
+
let nullifierMap = reg.consumedNullifiers.get(stakeId);
|
|
451
|
+
if (!nullifierMap) {
|
|
452
|
+
nullifierMap = /* @__PURE__ */ new Map();
|
|
453
|
+
reg.consumedNullifiers.set(stakeId, nullifierMap);
|
|
454
|
+
}
|
|
455
|
+
for (const [k, entry] of nullifierMap.entries()) if (entry.epoch < currentEpoch - 2) nullifierMap.delete(k);
|
|
456
|
+
const existingNullifier = nullifierMap.get(nullifier);
|
|
457
|
+
if (existingNullifier) {
|
|
458
|
+
if (existingNullifier.txHash && txHash && existingNullifier.txHash === txHash) return {
|
|
459
|
+
valid: true,
|
|
460
|
+
stakeId
|
|
461
|
+
};
|
|
462
|
+
return {
|
|
463
|
+
valid: false,
|
|
464
|
+
reason: "GAS_PASS_NULLIFIER_ALREADY_SPENT"
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
if (params.consumeNullifier !== false) {
|
|
468
|
+
if (nullifierMap.size >= MAX_NULLIFIERS_PER_STAKE) {
|
|
469
|
+
const oldest = nullifierMap.keys().next().value;
|
|
470
|
+
if (oldest) nullifierMap.delete(oldest);
|
|
471
|
+
}
|
|
472
|
+
nullifierMap.set(nullifier, {
|
|
473
|
+
epoch,
|
|
474
|
+
txHash
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
return {
|
|
478
|
+
valid: true,
|
|
479
|
+
stakeId
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function computeStakeMultiple(config, stakeState) {
|
|
483
|
+
const minStakeUnit = fromTokenToUnit(config.transaction.txGas.minStake || 1, config.token.decimal);
|
|
484
|
+
const maxStakeUnit = fromTokenToUnit(config.transaction.txGas.maxStake || 1e4, config.token.decimal);
|
|
485
|
+
const stakedUnit = new BN(stakeState?.tokens?.[config.token.address] || 0);
|
|
486
|
+
if (minStakeUnit.gt(ZERO) && stakedUnit.gte(minStakeUnit)) {
|
|
487
|
+
const cappedStake = stakedUnit.gt(maxStakeUnit) && maxStakeUnit.gt(ZERO) ? maxStakeUnit : stakedUnit;
|
|
488
|
+
return Math.max(1, Math.min(1e4, cappedStake.div(minStakeUnit).toNumber()));
|
|
489
|
+
}
|
|
490
|
+
return 1;
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Stake-scaled per-sender burst quota (`rho = n_burst / B_normal(S)`) with machine-readable telemetry.
|
|
494
|
+
*
|
|
495
|
+
* RELIABILITY CONTRACT: the counter is process-local, so it is used for ADMISSION only (reject before the
|
|
496
|
+
* single-writer queue). It never reprices gas, never changes a waiver and never touches receipts; the executed
|
|
497
|
+
* outcome of a tx is a pure function of (tx, on-chain state). A request is rejected only above
|
|
498
|
+
* `baseBurstAllowance * stakeMultiple * burstRejectMultiple` (`hardLimitExceeded`); between 1x and the hard limit
|
|
499
|
+
* it is admitted and only advisory telemetry is returned (`quotaExceeded`).
|
|
500
|
+
*/
|
|
501
|
+
function evaluateBurstQuota(params) {
|
|
502
|
+
const { config, statedb } = params;
|
|
503
|
+
const baseGas = params.baseGas ?? ZERO;
|
|
504
|
+
const cfg = resolveGasSecurityConfig(config);
|
|
505
|
+
const nowMs = params.nowMs ?? Date.now();
|
|
506
|
+
const rec = getOrCreateActorRecord(getGasSecurityRegistry(statedb), normalizeActorKey(params.actor || "anonymous"), nowMs, cfg);
|
|
507
|
+
const normHash = params.txHash ? params.txHash.trim().toUpperCase() : void 0;
|
|
508
|
+
const variantHash = params.variantHash ? params.variantHash.trim().toUpperCase() : void 0;
|
|
509
|
+
const existing = normHash ? rec.bursts.find((b) => b.h === normHash) : void 0;
|
|
510
|
+
let alreadyCounted = false;
|
|
511
|
+
if (existing) {
|
|
512
|
+
if (!variantHash || (existing.variants || []).includes(variantHash)) alreadyCounted = true;
|
|
513
|
+
else if ((existing.variants || []).length < MAX_FREE_VARIANTS) {
|
|
514
|
+
alreadyCounted = true;
|
|
515
|
+
if (params.recordBurst !== false) existing.variants = [...existing.variants || [], variantHash];
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const burstCount = Math.max(1, rec.bursts.length + (alreadyCounted ? 0 : 1));
|
|
519
|
+
const stakeMultiple = computeStakeMultiple(config, params.stakeState);
|
|
520
|
+
const minStakeUnit = fromTokenToUnit(config.transaction.txGas.minStake || 1, config.token.decimal);
|
|
521
|
+
const normalAllowance = cfg.baseBurstAllowance * stakeMultiple;
|
|
522
|
+
const hardLimit = Math.ceil(normalAllowance * (params.rejectMultiple ?? cfg.burstRejectMultiple));
|
|
523
|
+
const rawRho = burstCount / normalAllowance;
|
|
524
|
+
const loadRatio = Number(rawRho.toFixed(4));
|
|
525
|
+
const quotaExceeded = rawRho > 1;
|
|
526
|
+
const hardLimitExceeded = burstCount > hardLimit;
|
|
527
|
+
if (params.recordBurst !== false && !alreadyCounted && !hardLimitExceeded) rec.bursts.push({
|
|
528
|
+
t: nowMs,
|
|
529
|
+
h: existing && variantHash ? `${normHash}#${variantHash}` : normHash,
|
|
530
|
+
variants: variantHash ? [variantHash] : void 0
|
|
531
|
+
});
|
|
532
|
+
const recommendedBackoffMs = rawRho <= 1 ? 0 : Math.min(cfg.burstWindowMs, Math.ceil((rawRho - 1) * (cfg.burstWindowMs / 2)));
|
|
533
|
+
const requiredMultiplesFor1x = Math.max(1, Math.ceil(burstCount / cfg.baseBurstAllowance));
|
|
534
|
+
return {
|
|
535
|
+
burstCount,
|
|
536
|
+
normalAllowance,
|
|
537
|
+
hardLimit,
|
|
538
|
+
loadRatio,
|
|
539
|
+
quotaExceeded,
|
|
540
|
+
hardLimitExceeded,
|
|
541
|
+
telemetry: {
|
|
542
|
+
loadRatio,
|
|
543
|
+
remainingNormalQuota: Math.max(0, normalAllowance - burstCount),
|
|
544
|
+
currentGasMultiplier: 1,
|
|
545
|
+
nextTxEstimatedGas: baseGas.toString(10),
|
|
546
|
+
recommendedBackoffMs,
|
|
547
|
+
stakeRequiredFor1x: minStakeUnit.mul(new BN(requiredMultiplesFor1x)).toString(10)
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
function getStrikeWeight(category) {
|
|
552
|
+
switch (category) {
|
|
553
|
+
case "INVARIANT_VIOLATION": return 3;
|
|
554
|
+
case "WAF_REJECT":
|
|
555
|
+
case "PAYMASTER_VIOLATION": return 2;
|
|
556
|
+
case "BENIGN_REJECT":
|
|
557
|
+
case "QUOTA_EXCEEDED": return 0;
|
|
558
|
+
default: return 1;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const BENIGN_REJECT_CODES = new Set([
|
|
562
|
+
"INVALID_NONCE",
|
|
563
|
+
"DUPLICATE_TX",
|
|
564
|
+
"ACCOUNT_MIGRATED",
|
|
565
|
+
"INVALID_TX_TIME",
|
|
566
|
+
"EXPIRED",
|
|
567
|
+
"TX_EXPIRED",
|
|
568
|
+
"NOT_FOUND",
|
|
569
|
+
"STAKE_NOT_FOUND",
|
|
570
|
+
"INVALID_LOCK_STATUS",
|
|
571
|
+
"ACCOUNT_NOT_FOUND"
|
|
572
|
+
]);
|
|
573
|
+
function classifyErrorStrikeCategory(err) {
|
|
574
|
+
const code = err?.code || "INTERNAL";
|
|
575
|
+
const msg = err?.message || "";
|
|
576
|
+
if (code.startsWith("WAF_") || /Pre-Flight WAF/i.test(msg)) return {
|
|
577
|
+
shouldRecordStrike: true,
|
|
578
|
+
category: "WAF_REJECT",
|
|
579
|
+
code
|
|
580
|
+
};
|
|
581
|
+
if (code.endsWith("_VIOLATION") || code === "STATE_DELETION_FORBIDDEN" || code === "RW_SET_CEILING_EXCEEDED" || /Post-Execution Invariant Gate/i.test(msg)) return {
|
|
582
|
+
shouldRecordStrike: true,
|
|
583
|
+
category: "INVARIANT_VIOLATION",
|
|
584
|
+
code
|
|
585
|
+
};
|
|
586
|
+
if (code.startsWith("PAYMASTER_") || code.startsWith("GAS_PASS_")) return {
|
|
587
|
+
shouldRecordStrike: true,
|
|
588
|
+
category: "PAYMASTER_VIOLATION",
|
|
589
|
+
code
|
|
590
|
+
};
|
|
591
|
+
if (code === "TOO_MANY_TXS" || code === "ABUSE_SLASH_TRIGGERED") return {
|
|
592
|
+
shouldRecordStrike: false,
|
|
593
|
+
category: "QUOTA_EXCEEDED",
|
|
594
|
+
code
|
|
595
|
+
};
|
|
596
|
+
if (code.startsWith("INSUFFICIENT_") || BENIGN_REJECT_CODES.has(code)) return {
|
|
597
|
+
shouldRecordStrike: false,
|
|
598
|
+
category: "BENIGN_REJECT",
|
|
599
|
+
code
|
|
600
|
+
};
|
|
601
|
+
return {
|
|
602
|
+
shouldRecordStrike: true,
|
|
603
|
+
category: "PROTOCOL_REJECT",
|
|
604
|
+
code
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function computeActorTier(strikeCount, cfg) {
|
|
608
|
+
if (strikeCount >= cfg.slashThreshold) return "SLASH_TRIGGERED";
|
|
609
|
+
if (strikeCount >= cfg.throttleThreshold) return "THROTTLED";
|
|
610
|
+
if (strikeCount >= cfg.warningThreshold) return "WARNING";
|
|
611
|
+
return "NORMAL";
|
|
612
|
+
}
|
|
613
|
+
function getActorSecurityStatus(params) {
|
|
614
|
+
const cfg = resolveGasSecurityConfig(params.config);
|
|
615
|
+
const nowMs = params.nowMs ?? Date.now();
|
|
616
|
+
const reg = getGasSecurityRegistry(params.statedb);
|
|
617
|
+
const actor = normalizeActorAddress(params.actor);
|
|
618
|
+
if (!actor) return {
|
|
619
|
+
strikeCount: 0,
|
|
620
|
+
tier: "NORMAL",
|
|
621
|
+
cooldownUntilMs: 0
|
|
622
|
+
};
|
|
623
|
+
const rec = getOrCreateActorRecord(reg, actor, nowMs, cfg);
|
|
624
|
+
const strikeCount = rec.strikes.reduce((acc, s) => acc + s.weight, 0);
|
|
625
|
+
const tier = computeActorTier(strikeCount, cfg);
|
|
626
|
+
const defaultTelemetry = params.telemetry || {
|
|
627
|
+
loadRatio: 0,
|
|
628
|
+
remainingNormalQuota: cfg.baseBurstAllowance,
|
|
629
|
+
currentGasMultiplier: 1,
|
|
630
|
+
nextTxEstimatedGas: "0",
|
|
631
|
+
recommendedBackoffMs: 0,
|
|
632
|
+
stakeRequiredFor1x: "0"
|
|
633
|
+
};
|
|
634
|
+
let warning;
|
|
635
|
+
if (tier !== "NORMAL" || defaultTelemetry.loadRatio >= .8) {
|
|
636
|
+
warning = {
|
|
637
|
+
tier,
|
|
638
|
+
code: tier === "SLASH_TRIGGERED" ? "ABUSE_SLASH_TRIGGERED" : tier === "THROTTLED" ? "ACTOR_THROTTLED" : tier === "WARNING" ? "SECURITY_STRIKE_WARNING" : "GAS_QUOTA_ADVISORY",
|
|
639
|
+
message: tier === "SLASH_TRIGGERED" ? `Actor ${actor} reached slash threshold (${strikeCount}/${cfg.slashThreshold}); new submissions are rejected during the cooldown${cfg.autoSlash ? " and Stake-for-Gas is subject to automatic slashing" : ""}.` : tier === "THROTTLED" ? `Actor ${actor} is throttled (${strikeCount}/${cfg.throttleThreshold} strikes); new submissions are rejected during the cooldown.` : tier === "WARNING" ? `Actor ${actor} accumulated ${strikeCount} security strikes (throttle at ${cfg.throttleThreshold}, slash at ${cfg.slashThreshold}).` : `Actor ${actor} burst gas load ratio is ${defaultTelemetry.loadRatio} (remaining normal quota: ${defaultTelemetry.remainingNormalQuota}).`,
|
|
640
|
+
actor,
|
|
641
|
+
strikeCount,
|
|
642
|
+
warningThreshold: cfg.warningThreshold,
|
|
643
|
+
throttleThreshold: cfg.throttleThreshold,
|
|
644
|
+
slashThreshold: cfg.slashThreshold,
|
|
645
|
+
gasStakeQuotaRemaining: defaultTelemetry.remainingNormalQuota,
|
|
646
|
+
cooldownUntilMs: rec.cooldownUntilMs,
|
|
647
|
+
telemetry: defaultTelemetry
|
|
648
|
+
};
|
|
649
|
+
rec.lastWarning = warning;
|
|
650
|
+
}
|
|
651
|
+
return {
|
|
652
|
+
strikeCount,
|
|
653
|
+
tier,
|
|
654
|
+
cooldownUntilMs: rec.cooldownUntilMs,
|
|
655
|
+
lastSlashEvidence: rec.lastSlashEvidence,
|
|
656
|
+
warning
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Resolves the list of cryptographically verified actor addresses that may be penalized
|
|
661
|
+
* with a security strike for a failed or rejected transaction:
|
|
662
|
+
* - Never attributes strikes to `tx.from` or `tx.delegator` unless `VerifySignature` has
|
|
663
|
+
* cryptographically verified the transaction signature (`CRITICAL-2` protection).
|
|
664
|
+
* - When `tx.delegator` is present, attributes strikes ONLY to `tx.delegator` (the verified signer / delegatee),
|
|
665
|
+
* never to the principal `tx.from`, whether or not the delegation verified.
|
|
666
|
+
* - Never attributes sender-induced strikes to a third-party `gasStake.owner` (`CRITICAL-3`).
|
|
667
|
+
*/
|
|
668
|
+
async function resolveVerifiedStrikeActors(ctx) {
|
|
669
|
+
if (!ctx || typeof ctx !== "object") return [];
|
|
670
|
+
const tx$1 = ctx.tx;
|
|
671
|
+
if (!tx$1 || typeof tx$1 !== "object") return [];
|
|
672
|
+
const signer = tx$1.delegator || tx$1.from;
|
|
673
|
+
if (!signer || !tx$1.pk || !tx$1.signature) return [];
|
|
674
|
+
let sigVerified = ctx.isSignatureVerified === true || ctx._preFlightVerified === true;
|
|
675
|
+
if (!sigVerified) try {
|
|
676
|
+
if (!isFromPublicKey(signer, tx$1.pk)) return [];
|
|
677
|
+
await new Promise((resolve, reject) => {
|
|
678
|
+
const verifyFn = pipes.VerifySignature;
|
|
679
|
+
Promise.resolve(verifyFn(ctx, (err) => err ? reject(err) : resolve())).catch(reject);
|
|
680
|
+
});
|
|
681
|
+
ctx.isSignatureVerified = true;
|
|
682
|
+
sigVerified = true;
|
|
683
|
+
} catch {
|
|
684
|
+
return [];
|
|
685
|
+
}
|
|
686
|
+
if (!sigVerified) return [];
|
|
687
|
+
const normSigner = normalizeActorAddress(signer);
|
|
688
|
+
if (!normSigner) return [];
|
|
689
|
+
return [normSigner];
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Records a weighted security strike against one or more verified actor addresses,
|
|
693
|
+
* updates their tier (`NORMAL` -> `WARNING` -> `THROTTLED` -> `SLASH_TRIGGERED`), and if `SLASH_TRIGGERED` is reached,
|
|
694
|
+
* executes automatic `Stake-for-Gas` slashing into `config.vaults.slashedStake` (with optional Fisherman bounty split
|
|
695
|
+
* and 0% token burn per Axiom #3).
|
|
696
|
+
*/
|
|
697
|
+
async function recordActorSecurityStrike(params) {
|
|
698
|
+
const cfg = resolveGasSecurityConfig(params.config);
|
|
699
|
+
if (!cfg.enabled) return {};
|
|
700
|
+
const nowMs = params.nowMs ?? Date.now();
|
|
701
|
+
const reg = getGasSecurityRegistry(params.statedb);
|
|
702
|
+
const weight = getStrikeWeight(params.category);
|
|
703
|
+
if (weight <= 0) return {};
|
|
704
|
+
const normTxHash = params.txHash ? params.txHash.trim().toUpperCase() : void 0;
|
|
705
|
+
const uniqueActors = Array.from(new Set(params.actors.map((a) => normalizeActorAddress(a)).filter(Boolean))).filter((a) => !cfg.exemptActors.includes(a));
|
|
706
|
+
let primaryWarning;
|
|
707
|
+
let slashEvidence;
|
|
708
|
+
for (const actor of uniqueActors) {
|
|
709
|
+
const rec = getOrCreateActorRecord(reg, actor, nowMs, cfg);
|
|
710
|
+
const prevStrikes = rec.strikes.map((s) => ({ ...s }));
|
|
711
|
+
const prevCooldown = rec.cooldownUntilMs;
|
|
712
|
+
const prevSlashEvidence = rec.lastSlashEvidence;
|
|
713
|
+
const prevWarning = rec.lastWarning;
|
|
714
|
+
if (!(normTxHash ? rec.strikes.some((s) => s.txHash === normTxHash) : false)) rec.strikes.push({
|
|
715
|
+
timestampMs: nowMs,
|
|
716
|
+
weight,
|
|
717
|
+
code: params.reasonCode,
|
|
718
|
+
txHash: normTxHash
|
|
719
|
+
});
|
|
720
|
+
const strikeCount = rec.strikes.reduce((acc, s) => acc + s.weight, 0);
|
|
721
|
+
const tier = computeActorTier(strikeCount, cfg);
|
|
722
|
+
if (tier === "THROTTLED" || tier === "SLASH_TRIGGERED") rec.cooldownUntilMs = Math.max(rec.cooldownUntilMs, nowMs + cfg.throttleCooldownMs);
|
|
723
|
+
const status = getActorSecurityStatus({
|
|
724
|
+
actor,
|
|
725
|
+
config: params.config,
|
|
726
|
+
statedb: params.statedb,
|
|
727
|
+
nowMs,
|
|
728
|
+
telemetry: params.telemetry
|
|
729
|
+
});
|
|
730
|
+
if (status.warning && !primaryWarning) primaryWarning = status.warning;
|
|
731
|
+
if (tier === "SLASH_TRIGGERED" && cfg.autoSlash && params.txn) try {
|
|
732
|
+
const evidence$1 = await executeAutoGasStakeSlash({
|
|
733
|
+
offender: actor,
|
|
734
|
+
strikeCount,
|
|
735
|
+
strikes: rec.strikes,
|
|
736
|
+
config: params.config,
|
|
737
|
+
statedb: params.statedb,
|
|
738
|
+
txn: params.txn,
|
|
739
|
+
fishermanAddress: params.fishermanAddress,
|
|
740
|
+
nowMs
|
|
741
|
+
});
|
|
742
|
+
if (evidence$1) {
|
|
743
|
+
slashEvidence = evidence$1;
|
|
744
|
+
rec.lastSlashEvidence = evidence$1;
|
|
745
|
+
rec.strikes = [];
|
|
746
|
+
}
|
|
747
|
+
} catch (slashErr) {
|
|
748
|
+
rec.strikes = prevStrikes;
|
|
749
|
+
rec.cooldownUntilMs = prevCooldown;
|
|
750
|
+
rec.lastSlashEvidence = prevSlashEvidence;
|
|
751
|
+
rec.lastWarning = prevWarning;
|
|
752
|
+
throw slashErr;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
if (params.txHash && primaryWarning) setTxSecurityWarningForHash(params.txHash, primaryWarning, params.statedb);
|
|
756
|
+
return {
|
|
757
|
+
primaryWarning,
|
|
758
|
+
slashEvidence
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
function snapshotActorSecurityRecords(actors, statedb, txHash) {
|
|
762
|
+
const reg = getGasSecurityRegistry(statedb);
|
|
763
|
+
const map = /* @__PURE__ */ new Map();
|
|
764
|
+
for (const raw of actors) {
|
|
765
|
+
const actor = normalizeActorAddress(raw);
|
|
766
|
+
if (!actor) continue;
|
|
767
|
+
const existing = reg.actors.get(actor);
|
|
768
|
+
map.set(actor, existing ? cloneDeep(existing) : null);
|
|
769
|
+
}
|
|
770
|
+
const normHash = txHash ? txHash.trim().toUpperCase() : void 0;
|
|
771
|
+
return {
|
|
772
|
+
actors: map,
|
|
773
|
+
txWarningExisted: normHash ? reg.txWarningsByHash.has(normHash) : false,
|
|
774
|
+
prevTxWarning: normHash ? reg.txWarningsByHash.get(normHash) : void 0,
|
|
775
|
+
txHash: normHash
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
function restoreActorSecurityRecords(snapshot, statedb) {
|
|
779
|
+
const reg = getGasSecurityRegistry(statedb);
|
|
780
|
+
for (const [actor, record] of snapshot.actors.entries()) if (record) reg.actors.set(actor, cloneDeep(record));
|
|
781
|
+
else reg.actors.delete(actor);
|
|
782
|
+
if (snapshot.txHash) if (snapshot.txWarningExisted && snapshot.prevTxWarning) reg.txWarningsByHash.set(snapshot.txHash, snapshot.prevTxWarning);
|
|
783
|
+
else reg.txWarningsByHash.delete(snapshot.txHash);
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Executes automatic `Stake-for-Gas` slashing when an actor crosses `slashThreshold` (opt-in via
|
|
787
|
+
* `transaction.security.autoSlash`; ONLY inside the enclosing queued tx's own write set, `params.txn` is required):
|
|
788
|
+
* - Transfers 100% of the offender's staked official tokens out of `toStakeAddress(offender, offender)`:
|
|
789
|
+
* - `fishermanBountyBps` (default 10%) to `fishermanAddress` (if provided and distinct from `offender`).
|
|
790
|
+
* - Remaining 90% (or 100% if no fisherman) to `config.vaults.slashedStake` (or `config.vaults.txGas[0]` / `config.vaults.txFee`).
|
|
791
|
+
* - ZERO official tokens are ever burned (Axiom #3).
|
|
792
|
+
* - Creates and persists a deterministic `IAbuseSlashEvidence` record in `statedb.evidence`.
|
|
793
|
+
*/
|
|
794
|
+
async function executeAutoGasStakeSlash(params) {
|
|
795
|
+
if (!params.txn) return null;
|
|
796
|
+
const offender = normalizeActorAddress(params.offender);
|
|
797
|
+
const stakeAddress = toStakeAddress(offender, offender);
|
|
798
|
+
const cfg = resolveGasSecurityConfig(params.config);
|
|
799
|
+
const nowIso = new Date(params.nowMs ?? Date.now()).toISOString();
|
|
800
|
+
const officialToken = params.config?.token?.address || "";
|
|
801
|
+
const vaults = params.config?.vaults || {};
|
|
802
|
+
const txGasVaults = Array.isArray(vaults.txGas) ? vaults.txGas : [];
|
|
803
|
+
const configuredVault = normalizeActorAddress(vaults.slashedStake || txGasVaults[0] || vaults.txFee || "");
|
|
804
|
+
const fallbackVaultSink = toStakeAddress(officialToken || stakeAddress, "slashed-stake-vault");
|
|
805
|
+
const vaultDestination = configuredVault && configuredVault !== offender ? configuredVault : fallbackVaultSink;
|
|
806
|
+
const fisherman = normalizeActorAddress(params.fishermanAddress);
|
|
807
|
+
const validFisherman = fisherman && fisherman !== offender && fisherman !== vaultDestination ? fisherman : void 0;
|
|
808
|
+
const reasonCodes = Array.from(new Set(params.strikes.map((s) => s.code)));
|
|
809
|
+
const recentTxHashes = Array.from(new Set(params.strikes.map((s) => s.txHash).filter(Boolean))).slice(-10);
|
|
810
|
+
let fishermanBountyBN = ZERO;
|
|
811
|
+
let vaultAmountBN = ZERO;
|
|
812
|
+
const slashedTokens = {};
|
|
813
|
+
const rawDb = params.statedb?._underlyingStateDb || params.statedb;
|
|
814
|
+
const stakeTable = rawDb?.stake;
|
|
815
|
+
const accountTable = rawDb?.account;
|
|
816
|
+
const evidenceTable = rawDb?.evidence;
|
|
817
|
+
const stateCtx = {
|
|
818
|
+
txHash: recentTxHashes.find((h) => /^[0-9a-fA-F]{64}$/.test(h)) || "",
|
|
819
|
+
txTime: nowIso,
|
|
820
|
+
txn: params.txn
|
|
821
|
+
};
|
|
822
|
+
if (stakeTable && typeof stakeTable.get === "function" && typeof stakeTable.update === "function" && officialToken) {
|
|
823
|
+
const performSlashMutations = async (activeCtx) => {
|
|
824
|
+
const stakeState = await stakeTable.get(stakeAddress, activeCtx);
|
|
825
|
+
const currentStaked = new BN(stakeState?.tokens?.[officialToken] || 0);
|
|
826
|
+
if (!stakeState || currentStaked.lte(ZERO)) return;
|
|
827
|
+
const originalStakeSnapshot = cloneDeep(stakeState);
|
|
828
|
+
const existingVaultSnapshot = accountTable && typeof accountTable.get === "function" ? cloneDeep(await accountTable.get(vaultDestination, activeCtx)) : null;
|
|
829
|
+
slashedTokens[officialToken] = currentStaked.toString(10);
|
|
830
|
+
if (validFisherman && cfg.fishermanBountyBps > 0) fishermanBountyBN = currentStaked.mul(new BN(cfg.fishermanBountyBps)).div(BPS_DENOMINATOR);
|
|
831
|
+
vaultAmountBN = currentStaked.sub(fishermanBountyBN);
|
|
832
|
+
const updatedStakeTokens = {
|
|
833
|
+
...stakeState.tokens || {},
|
|
834
|
+
[officialToken]: "0"
|
|
835
|
+
};
|
|
836
|
+
const defaultGenesisCtx = {
|
|
837
|
+
genesisTime: nowIso,
|
|
838
|
+
genesisTx: "",
|
|
839
|
+
renaissanceTime: nowIso,
|
|
840
|
+
renaissanceTx: ""
|
|
841
|
+
};
|
|
842
|
+
let updatedStake;
|
|
843
|
+
try {
|
|
844
|
+
updatedStake = stake.update({
|
|
845
|
+
context: defaultGenesisCtx,
|
|
846
|
+
...cloneDeep(stakeState)
|
|
847
|
+
}, {
|
|
848
|
+
tokens: updatedStakeTokens,
|
|
849
|
+
message: "auto-slashed:abuse-strike-threshold"
|
|
850
|
+
}, activeCtx);
|
|
851
|
+
} catch {
|
|
852
|
+
updatedStake = {
|
|
853
|
+
...cloneDeep(stakeState),
|
|
854
|
+
tokens: updatedStakeTokens,
|
|
855
|
+
message: "auto-slashed:abuse-strike-threshold"
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
let stakeDebited = false;
|
|
859
|
+
let vaultCredited = false;
|
|
860
|
+
try {
|
|
861
|
+
await stakeTable.update(stakeAddress, updatedStake, activeCtx);
|
|
862
|
+
stakeDebited = true;
|
|
863
|
+
const creditAccount = async (targetAddr, deltaBN) => {
|
|
864
|
+
if (!targetAddr || deltaBN.lte(ZERO) || !accountTable || typeof accountTable.get !== "function") return;
|
|
865
|
+
const existing = await accountTable.get(targetAddr, activeCtx);
|
|
866
|
+
const prevBal = new BN(existing?.tokens?.[officialToken] || 0);
|
|
867
|
+
const nextTokens = {
|
|
868
|
+
...existing?.tokens || {},
|
|
869
|
+
[officialToken]: prevBal.add(deltaBN).toString(10)
|
|
870
|
+
};
|
|
871
|
+
if (existing && typeof accountTable.update === "function") {
|
|
872
|
+
let nextAcc;
|
|
873
|
+
try {
|
|
874
|
+
nextAcc = account.update({
|
|
875
|
+
context: defaultGenesisCtx,
|
|
876
|
+
...cloneDeep(existing)
|
|
877
|
+
}, { tokens: nextTokens }, activeCtx);
|
|
878
|
+
} catch {
|
|
879
|
+
nextAcc = {
|
|
880
|
+
...cloneDeep(existing),
|
|
881
|
+
tokens: nextTokens
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
await accountTable.update(targetAddr, nextAcc, activeCtx);
|
|
885
|
+
} else if (typeof accountTable.updateOrCreate === "function") {
|
|
886
|
+
const nextAcc = account.updateOrCreate(existing ?? null, {
|
|
887
|
+
address: targetAddr,
|
|
888
|
+
tokens: nextTokens
|
|
889
|
+
}, activeCtx);
|
|
890
|
+
await accountTable.updateOrCreate(existing ?? null, nextAcc, activeCtx);
|
|
891
|
+
} else if (typeof accountTable.create === "function") {
|
|
892
|
+
const nextAcc = account.create({
|
|
893
|
+
address: targetAddr,
|
|
894
|
+
tokens: nextTokens
|
|
895
|
+
}, activeCtx);
|
|
896
|
+
await accountTable.create(targetAddr, nextAcc, activeCtx);
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
await creditAccount(vaultDestination, vaultAmountBN);
|
|
900
|
+
vaultCredited = true;
|
|
901
|
+
if (validFisherman && fishermanBountyBN.gt(ZERO)) await creditAccount(validFisherman, fishermanBountyBN);
|
|
902
|
+
} catch (slashWriteErr) {
|
|
903
|
+
delete slashedTokens[officialToken];
|
|
904
|
+
vaultAmountBN = ZERO;
|
|
905
|
+
fishermanBountyBN = ZERO;
|
|
906
|
+
if (stakeDebited) try {
|
|
907
|
+
await stakeTable.update(stakeAddress, originalStakeSnapshot, activeCtx);
|
|
908
|
+
} catch {}
|
|
909
|
+
if (vaultCredited && existingVaultSnapshot && accountTable && typeof accountTable.update === "function") try {
|
|
910
|
+
await accountTable.update(vaultDestination, existingVaultSnapshot, activeCtx);
|
|
911
|
+
} catch {}
|
|
912
|
+
throw slashWriteErr;
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
await performSlashMutations(stateCtx);
|
|
916
|
+
}
|
|
917
|
+
if (Object.keys(slashedTokens).length === 0) return null;
|
|
918
|
+
const evidencePayload = {
|
|
919
|
+
type: "AbuseSlashEvidence",
|
|
920
|
+
offender,
|
|
921
|
+
stakeAddress,
|
|
922
|
+
strikeCount: params.strikeCount,
|
|
923
|
+
reasonCodes,
|
|
924
|
+
recentTxHashes,
|
|
925
|
+
slashedTokens,
|
|
926
|
+
fishermanAddress: validFisherman,
|
|
927
|
+
fishermanBounty: fishermanBountyBN.toString(10),
|
|
928
|
+
vaultDestination,
|
|
929
|
+
vaultAmount: vaultAmountBN.toString(10),
|
|
930
|
+
timestamp: nowIso
|
|
931
|
+
};
|
|
932
|
+
const evidenceHash = createHash("sha256").update(`ocap:abuse-slash:v1:${JSON.stringify(evidencePayload)}`).digest("hex").toUpperCase();
|
|
933
|
+
const evidenceRecord = {
|
|
934
|
+
evidenceHash,
|
|
935
|
+
...evidencePayload
|
|
936
|
+
};
|
|
937
|
+
if (evidenceTable && typeof evidenceTable.create === "function") try {
|
|
938
|
+
if (!(typeof evidenceTable.get === "function" ? await evidenceTable.get(evidenceHash, stateCtx) : null)) {
|
|
939
|
+
const evState = evidence.create({
|
|
940
|
+
hash: evidenceHash,
|
|
941
|
+
data: JSON.stringify(evidenceRecord)
|
|
942
|
+
}, {
|
|
943
|
+
txHash: evidenceHash,
|
|
944
|
+
txTime: nowIso
|
|
945
|
+
});
|
|
946
|
+
await evidenceTable.create(evidenceHash, evState, stateCtx);
|
|
947
|
+
}
|
|
948
|
+
} catch {}
|
|
949
|
+
return evidenceRecord;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Pre-queue ADMISSION control. This is the only consumer of the process-local strike / burst counters:
|
|
953
|
+
* it decides whether a request is accepted into the single-writer queue at all. It never changes the gas,
|
|
954
|
+
* waiver or receipts of a tx that is admitted, so executed outcomes stay a pure function of (tx, chain state)
|
|
955
|
+
* and cannot diverge between the two OS processes on main or across restarts.
|
|
956
|
+
*
|
|
957
|
+
* - `throttle`: the verified signer (`tx.delegator || tx.from`, i.e. the delegatee for delegated txs) is rejected
|
|
958
|
+
* with `TOO_MANY_TXS` while its strike-driven cooldown is active. Cooldowns always expire; actors without any
|
|
959
|
+
* strikes (and actors without stake) are never locked.
|
|
960
|
+
* - `burstEscalation`: the per-sender sliding-window quota rejects with `TOO_MANY_TXS` only above
|
|
961
|
+
* `baseBurstAllowance * stakeMultiple * burstRejectMultiple`. Keyed by the sender, never by the gas sponsor, so a
|
|
962
|
+
* sponsoring app is not capped across all of its users.
|
|
963
|
+
*/
|
|
964
|
+
async function assertTxAdmission(params) {
|
|
965
|
+
const cfg = resolveGasSecurityConfig(params.config);
|
|
966
|
+
if (!cfg.enabled) return {};
|
|
967
|
+
const nowMs = params.nowMs ?? Date.now();
|
|
968
|
+
const signer = normalizeActorAddress(params.tx?.delegator || params.tx?.from || "");
|
|
969
|
+
const principal = normalizeActorAddress(params.tx?.from || signer);
|
|
970
|
+
if (!signer || cfg.exemptActors.includes(signer)) return {};
|
|
971
|
+
const dbTx = params.statedb?.tx;
|
|
972
|
+
if (params.txHash && typeof dbTx?.get === "function") {
|
|
973
|
+
let committed = null;
|
|
974
|
+
try {
|
|
975
|
+
committed = await dbTx.get(params.txHash);
|
|
976
|
+
} catch {
|
|
977
|
+
committed = null;
|
|
978
|
+
}
|
|
979
|
+
if (committed) {
|
|
980
|
+
const dup = new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
981
|
+
dup._strikeRecorded = true;
|
|
982
|
+
throw dup;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
const dbAccount = params.statedb?.account;
|
|
986
|
+
if (!params.tx?.delegator && params.tx?.from && typeof dbAccount?.get === "function") try {
|
|
987
|
+
const senderState = await dbAccount.get(params.tx.from);
|
|
988
|
+
const incoming = parseNonceBn(params.tx.nonce);
|
|
989
|
+
if (senderState && incoming && incoming.lte(parseNonceBn(senderState.nonce) ?? new BN(0))) {
|
|
990
|
+
const stale = new CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
|
|
991
|
+
stale._strikeRecorded = true;
|
|
992
|
+
throw stale;
|
|
993
|
+
}
|
|
994
|
+
} catch (e) {
|
|
995
|
+
if (e?.code === "INVALID_NONCE") throw e;
|
|
996
|
+
}
|
|
997
|
+
const countedHash = params.unsignedTxHash || params.txHash;
|
|
998
|
+
const burstKey = principal && principal !== signer ? `${signer}>${principal}` : signer;
|
|
999
|
+
if (cfg.throttle) {
|
|
1000
|
+
const status = getActorSecurityStatus({
|
|
1001
|
+
actor: signer,
|
|
1002
|
+
config: params.config,
|
|
1003
|
+
statedb: params.statedb,
|
|
1004
|
+
nowMs
|
|
1005
|
+
});
|
|
1006
|
+
if (status.tier !== "NORMAL" && status.tier !== "WARNING" && status.cooldownUntilMs > nowMs) {
|
|
1007
|
+
const err = new CustomError("TOO_MANY_TXS", status.warning?.message || `Actor ${signer} is throttled; retry after ${status.cooldownUntilMs - nowMs}ms cooldown`);
|
|
1008
|
+
err.warning = status.warning;
|
|
1009
|
+
throw err;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
let telemetry;
|
|
1013
|
+
if (cfg.burstEscalation && params.config?.transaction?.txGas && params.config?.token) {
|
|
1014
|
+
const config = params.config;
|
|
1015
|
+
let stakeState = null;
|
|
1016
|
+
try {
|
|
1017
|
+
const stakeId = toStakeAddress(signer, signer);
|
|
1018
|
+
stakeState = await params.statedb?.stake?.get?.(stakeId) || null;
|
|
1019
|
+
} catch {
|
|
1020
|
+
stakeState = null;
|
|
1021
|
+
}
|
|
1022
|
+
if (burstKey !== signer) {
|
|
1023
|
+
const agg = evaluateBurstQuota({
|
|
1024
|
+
actor: `${signer}>*`,
|
|
1025
|
+
stakeState,
|
|
1026
|
+
config,
|
|
1027
|
+
statedb: params.statedb,
|
|
1028
|
+
nowMs,
|
|
1029
|
+
txHash: countedHash,
|
|
1030
|
+
variantHash: params.txHash,
|
|
1031
|
+
recordBurst: false,
|
|
1032
|
+
rejectMultiple: cfg.burstRejectMultiple * cfg.delegatedBurstMultiple
|
|
1033
|
+
});
|
|
1034
|
+
if (agg.hardLimitExceeded) throw new CustomError("TOO_MANY_TXS", `Delegatee ${signer} exceeded the aggregate delegated burst limit (${agg.burstCount} > ${agg.hardLimit} per ${cfg.burstWindowMs}ms)`);
|
|
1035
|
+
}
|
|
1036
|
+
const evalRes = evaluateBurstQuota({
|
|
1037
|
+
actor: burstKey,
|
|
1038
|
+
stakeState,
|
|
1039
|
+
config,
|
|
1040
|
+
statedb: params.statedb,
|
|
1041
|
+
nowMs,
|
|
1042
|
+
txHash: countedHash,
|
|
1043
|
+
variantHash: params.txHash,
|
|
1044
|
+
recordBurst: false
|
|
1045
|
+
});
|
|
1046
|
+
telemetry = evalRes.telemetry;
|
|
1047
|
+
if (evalRes.hardLimitExceeded) {
|
|
1048
|
+
const status = getActorSecurityStatus({
|
|
1049
|
+
actor: signer,
|
|
1050
|
+
config: params.config,
|
|
1051
|
+
statedb: params.statedb,
|
|
1052
|
+
nowMs,
|
|
1053
|
+
telemetry
|
|
1054
|
+
});
|
|
1055
|
+
const err = new CustomError("TOO_MANY_TXS", `Actor ${signer} exceeded the burst limit (${evalRes.burstCount} > ${evalRes.hardLimit} per ${cfg.burstWindowMs}ms); retry after ${telemetry.recommendedBackoffMs}ms or stake more for a larger quota`);
|
|
1056
|
+
err.warning = status.warning || {
|
|
1057
|
+
tier: "NORMAL",
|
|
1058
|
+
code: "GAS_QUOTA_ADVISORY",
|
|
1059
|
+
message: `Actor ${signer} burst gas load ratio is ${telemetry.loadRatio}`,
|
|
1060
|
+
actor: signer,
|
|
1061
|
+
strikeCount: 0,
|
|
1062
|
+
warningThreshold: cfg.warningThreshold,
|
|
1063
|
+
throttleThreshold: cfg.throttleThreshold,
|
|
1064
|
+
slashThreshold: cfg.slashThreshold,
|
|
1065
|
+
gasStakeQuotaRemaining: 0,
|
|
1066
|
+
cooldownUntilMs: 0,
|
|
1067
|
+
telemetry
|
|
1068
|
+
};
|
|
1069
|
+
throw err;
|
|
1070
|
+
}
|
|
1071
|
+
const record = (actor, rejectMultiple) => evaluateBurstQuota({
|
|
1072
|
+
actor,
|
|
1073
|
+
stakeState,
|
|
1074
|
+
config,
|
|
1075
|
+
statedb: params.statedb,
|
|
1076
|
+
nowMs,
|
|
1077
|
+
txHash: countedHash,
|
|
1078
|
+
variantHash: params.txHash,
|
|
1079
|
+
rejectMultiple
|
|
1080
|
+
});
|
|
1081
|
+
if (burstKey !== signer) record(`${signer}>*`, cfg.burstRejectMultiple * cfg.delegatedBurstMultiple);
|
|
1082
|
+
record(burstKey);
|
|
1083
|
+
}
|
|
1084
|
+
return { telemetry };
|
|
1085
|
+
}
|
|
1086
|
+
function getTxSecurityWarningByHash(txHash, statedb) {
|
|
1087
|
+
if (!txHash || typeof txHash !== "string") return void 0;
|
|
1088
|
+
return getGasSecurityRegistry(statedb).txWarningsByHash.get(txHash.trim().toUpperCase());
|
|
1089
|
+
}
|
|
1090
|
+
function setTxSecurityWarningForHash(txHash, warning, statedb) {
|
|
1091
|
+
if (!txHash || typeof txHash !== "string" || !warning) return;
|
|
1092
|
+
const normKey = txHash.trim().toUpperCase();
|
|
1093
|
+
if (!normKey) return;
|
|
1094
|
+
const reg = getGasSecurityRegistry(statedb);
|
|
1095
|
+
if (!reg.txWarningsByHash.has(normKey) && reg.txWarningsByHash.size >= MAX_TRACKED_ACTORS) {
|
|
1096
|
+
const oldest = reg.txWarningsByHash.keys().next().value;
|
|
1097
|
+
if (oldest) reg.txWarningsByHash.delete(oldest);
|
|
1098
|
+
}
|
|
1099
|
+
reg.txWarningsByHash.set(normKey, warning);
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
//#endregion
|
|
1103
|
+
export { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_DELEGATED_BURST_MULTIPLE, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, setTxSecurityWarningForHash, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
|