@ocap/resolver 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/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { IAddressArgs, IAssetState, IChainConfig, IChunkIterator, IDataObject, IDelegateState, IEvidenceState, IFilter, IGetAccountStateArgs, IGetAccountTokensArgs, IGetStateParams, IIndexDB as IIndexDB$1, IListChunksParams, IPaginatedResult, IPipelineLogger as IPipelineLogger$1, IResolver, IResolverAccountState, IResolverChainInfo, IResolverContext as IResolverContext$1, IResolverFactoryState, IResolverForgeStats, IResolverListAccountsResult, IResolverListAssetsResult, IResolverListDelegationsResult, IResolverListFactoriesResult, IResolverListRollupBlocksResult, IResolverListRollupValidatorsResult, IResolverListRollupsResult, IResolverListStakesResult, IResolverListTokenFactoriesResult, IResolverListTokensResult, IResolverListTransactionsResult, IResolverNetInfo, IResolverNodeInfo, IResolverPaging, IResolverParams, IResolverRollupState, IResolverStakeState, IResolverTransaction, IResolverValidatorsInfo, IRollupBlock, IStateDB as IStateDB$1, ITokenCache, ITokenFactoryState, ITokenFlowsResult, ITokenInfo, ITokenState, TIndexedTokenState as TIndexedTokenState$1, TRequestEstimateGas, TRequestGetEvidenceState, TRequestGetRollupBlock, TRequestGetTokenDistribution, TRequestGetTx, TRequestListAssetTransactions, TRequestListAssets, TRequestListDelegations, TRequestListFactories, TRequestListRollupBlocks, TRequestListRollupValidators, TRequestListRollups, TRequestListStakes, TRequestListTokenFactories, TRequestListTokenFlows, TRequestListTokens, TRequestListTopAccounts, TRequestListTransactions, TRequestSearch, TRequestVerifyAccountRisk, TSearchResult, TTokenDistribution, TVerifyAccountRiskResult } from "./types.mjs";
2
2
  import { MigrationChainManager } from "./migration-chain.mjs";
3
3
  import { TokenDistributionManager } from "./token-distribution.mjs";
4
- import { createExecutor } from "@ocap/tx-protocols";
4
+ import { ITxSecurityWarning, createExecutor } from "@ocap/tx-protocols";
5
5
  import Queue from "queue";
6
6
  import { ILedger } from "@ocap/types";
7
7
 
@@ -24,6 +24,7 @@ declare class OCAPResolver implements IResolver {
24
24
  logger: IPipelineLogger$1;
25
25
  migrationChain?: MigrationChainManager;
26
26
  formatTx: (tx: IResolverTransaction | null, ctx?: IResolverContext$1) => Promise<IResolverTransaction | null>;
27
+ inFlightPreFlights: number;
27
28
  private initializationPromise;
28
29
  /**
29
30
  * Creates an instance of OCAPResolver.
@@ -51,6 +52,8 @@ declare class OCAPResolver implements IResolver {
51
52
  tx: string;
52
53
  extra?: Record<string, unknown>;
53
54
  }, ctx?: IResolverContext$1): Promise<string>;
55
+ _indexRejectedLedgerTx(ctx: Record<string, unknown>, err: unknown): Promise<void>;
56
+ getTxSecurityWarning(txHash: string): ITxSecurityWarning | undefined;
54
57
  getTx({
55
58
  hash
56
59
  }: TRequestGetTx, ctx?: IResolverContext$1): Promise<IResolverTransaction | null>;
package/esm/index.mjs CHANGED
@@ -16,7 +16,7 @@ import { formatSearchResult, rebuildIndexFromState } from "@ocap/indexdb";
16
16
  import { types } from "@ocap/mcrypto";
17
17
  import { fromTypeUrl } from "@ocap/message";
18
18
  import * as states from "@ocap/state";
19
- import { TxTimer, createExecutor } from "@ocap/tx-protocols";
19
+ import { TxTimer, assertRawWireEnvelope, assertTxAdmission, classifyErrorStrikeCategory, createExecutor, getTxSecurityWarningByHash, inspectTransactionPreFlight, recordActorSecurityStrike, resolveVerifiedStrikeActors, setTxSecurityWarningForHash } from "@ocap/tx-protocols";
20
20
  import { decodeAnySafe } from "@ocap/tx-protocols/lib/util";
21
21
  import { DEFAULT_TOKEN_DECIMAL } from "@ocap/util/lib/constant";
22
22
  import { CustomError } from "@ocap/util/lib/error";
@@ -29,7 +29,7 @@ import set from "lodash/set.js";
29
29
  import uniqBy from "lodash/unionBy.js";
30
30
  import uniq from "lodash/uniq.js";
31
31
  import Queue from "queue";
32
- import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
32
+ import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
33
33
  import { attachPaidTxGas, getTxReceipts, getTxReceiver, getTxSender, mergeTxReceipts } from "@ocap/state/lib/states/tx";
34
34
 
35
35
  //#region src/index.ts
@@ -250,6 +250,7 @@ var OCAPResolver = class {
250
250
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
251
251
  */
252
252
  constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
253
+ this.inFlightPreFlights = 0;
253
254
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
254
255
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
255
256
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
@@ -293,8 +294,9 @@ var OCAPResolver = class {
293
294
  request: ctx.request
294
295
  });
295
296
  if (process.env.CHAIN_MODE === "readonly") throw new CustomError("FORBIDDEN", "This chain node is running in readonly mode");
296
- if (this.queue.length >= txRequestConfig.maxRequest) throw new CustomError("FORBIDDEN", "Chain is busy");
297
- if (!txBase64 || typeof txBase64 !== "string" || txBase64.length < 20) throw new CustomError("INVALID_TX", "Transaction data is empty or too short");
297
+ const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
298
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new CustomError("FORBIDDEN", "Chain is busy");
299
+ assertRawWireEnvelope(txBase64, this.config);
298
300
  const timer = new TxTimer();
299
301
  timer.setQueueState({
300
302
  waitingAtEnqueue: Math.max(0, this.queue.length - (this.queue.pending ?? 0)),
@@ -316,28 +318,195 @@ var OCAPResolver = class {
316
318
  }
317
319
  };
318
320
  return new Promise((resolve, reject) => {
319
- const task = async () => {
320
- timer.mark("queueWait");
321
+ this.inFlightPreFlights += 1;
322
+ let preFlightSlotReleased = false;
323
+ const releasePreFlightSlot = () => {
324
+ if (!preFlightSlotReleased) {
325
+ preFlightSlotReleased = true;
326
+ this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
327
+ }
328
+ };
329
+ const enqueueAfterPreFlight = async () => {
321
330
  try {
322
331
  await this.initializationPromise;
323
- resolve((await this.executor.execute(context)).txHash);
324
- } catch (err) {
325
- reject(err);
332
+ await inspectTransactionPreFlight(context);
333
+ const preTx = context.tx;
334
+ const preTxHash = context.txHash;
335
+ if (preTx) await assertTxAdmission({
336
+ tx: preTx,
337
+ txHash: preTxHash,
338
+ unsignedTxHash: context.unsignedTxHash,
339
+ config: this.config,
340
+ statedb: this.statedb
341
+ });
342
+ } catch (preFlightErr) {
343
+ const errObj = preFlightErr;
344
+ const strikeCtx = errObj._preFlightCtx || context;
345
+ const txHash = strikeCtx.txHash || context.txHash;
346
+ const classified = classifyErrorStrikeCategory(errObj);
347
+ if (classified.shouldRecordStrike && !errObj._strikeRecorded && errObj._unauthenticatedExtraFailure !== true) try {
348
+ const actors = await resolveVerifiedStrikeActors(strikeCtx);
349
+ if (actors.length > 0) {
350
+ errObj._strikeRecorded = true;
351
+ const { primaryWarning, slashEvidence } = await recordActorSecurityStrike({
352
+ actors,
353
+ category: classified.category,
354
+ reasonCode: classified.code,
355
+ txHash,
356
+ config: this.config,
357
+ statedb: this.statedb
358
+ });
359
+ if (primaryWarning && !errObj.warning) errObj.warning = primaryWarning;
360
+ if (slashEvidence && !errObj.slashEvidence) errObj.slashEvidence = slashEvidence;
361
+ }
362
+ } catch (strikeErr) {
363
+ this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
364
+ }
365
+ releasePreFlightSlot();
366
+ reject(preFlightErr);
367
+ return;
368
+ }
369
+ releasePreFlightSlot();
370
+ const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
371
+ if (this.queue.length >= currentMaxRequest) {
372
+ reject(new CustomError("FORBIDDEN", "Chain is busy"));
373
+ return;
326
374
  }
375
+ const task = async () => {
376
+ timer.mark("queueWait");
377
+ try {
378
+ const result = await this.executor.execute(context);
379
+ if (result?.txHash && result?.securityWarning) setTxSecurityWarningForHash(result.txHash, result.securityWarning, this.statedb);
380
+ resolve(result.txHash);
381
+ } catch (err) {
382
+ await this._indexRejectedLedgerTx(context, err);
383
+ reject(err);
384
+ }
385
+ };
386
+ this.queue.push(task);
327
387
  };
328
- this.queue.push(task);
388
+ enqueueAfterPreFlight().catch((err) => {
389
+ releasePreFlightSlot();
390
+ reject(err);
391
+ });
329
392
  });
330
393
  }
331
- getTx({ hash }, ctx) {
332
- if (patterns.txHash.test(hash)) return this._getState({
333
- table: "tx",
334
- id: hash.toUpperCase(),
335
- dataKey: "tx.itxJson.data",
336
- onRead: (tx) => this.formatTx(tx, ctx),
337
- expandContext: false,
338
- ctx
339
- });
340
- return Promise.resolve(null);
394
+ async _indexRejectedLedgerTx(ctx, err) {
395
+ if (!this.indexdb?.tx?.insert) return;
396
+ const ledgerSequence = Number(ctx.ledgerSequence ?? 0);
397
+ const rawTxHash = typeof ctx.txHash === "string" ? ctx.txHash.trim() : "";
398
+ if (!(ledgerSequence > 0) || !rawTxHash) return;
399
+ const txHash = rawTxHash.toUpperCase();
400
+ let rejectedRow;
401
+ try {
402
+ if (await Promise.resolve(this.statedb?.tx?.get?.(txHash)).catch(() => null)) return;
403
+ if (await Promise.resolve(this.indexdb.tx.get?.(txHash)).catch(() => null)) return;
404
+ const txType = typeof ctx.txType === "string" ? ctx.txType : "";
405
+ const type = txType ? txType.split(":").pop() || "" : "";
406
+ let typeName = "";
407
+ if (txType) try {
408
+ typeName = fromTypeUrl(txType);
409
+ } catch {
410
+ typeName = "";
411
+ }
412
+ const txObj = ctx.tx && typeof ctx.tx === "object" ? ctx.tx : {};
413
+ const from = typeof txObj.from === "string" ? txObj.from : "";
414
+ const delegator = typeof txObj.delegator === "string" ? txObj.delegator : "";
415
+ const toStrOrBase64 = (val) => {
416
+ if (typeof val === "string") return val;
417
+ if (val instanceof Uint8Array || Buffer.isBuffer(val)) return Buffer.from(val).toString("base64");
418
+ return "";
419
+ };
420
+ const sourceItx = ctx.itxJson && typeof ctx.itxJson === "object" ? ctx.itxJson : ctx.itx && typeof ctx.itx === "object" ? ctx.itx : null;
421
+ const itxJson = sourceItx ? { ...sourceItx } : {
422
+ ...typeName ? { _type: typeName } : {},
423
+ type_url: txType
424
+ };
425
+ if (!itxJson.type_url && txType) itxJson.type_url = txType;
426
+ if (!itxJson._type && typeName) itxJson._type = typeName;
427
+ const syntheticTx = {
428
+ valid: false,
429
+ code: String(err?.code || "INTERNAL"),
430
+ tx: {
431
+ from,
432
+ delegator,
433
+ itxJson
434
+ }
435
+ };
436
+ const sender = deriveTxSender(syntheticTx, ctx);
437
+ const gasPayer = "";
438
+ const time = typeof ctx.txTime === "string" && ctx.txTime || (/* @__PURE__ */ new Date()).toISOString();
439
+ const code = syntheticTx.code;
440
+ const accounts = uniq([
441
+ from,
442
+ delegator,
443
+ sender
444
+ ].filter(Boolean));
445
+ rejectedRow = {
446
+ hash: txHash,
447
+ type,
448
+ code,
449
+ valid: false,
450
+ time,
451
+ sender,
452
+ receiver: "",
453
+ gasPayer,
454
+ gasUsed: "0",
455
+ tx: {
456
+ chainId: String(txObj.chainId || this.config?.chainId || ""),
457
+ from,
458
+ delegator,
459
+ nonce: txObj.nonce ?? 0,
460
+ pk: toStrOrBase64(txObj.pk),
461
+ signature: toStrOrBase64(txObj.signature),
462
+ signaturesList: Array.isArray(txObj.signaturesList) ? txObj.signaturesList : [],
463
+ signatures: Array.isArray(txObj.signatures) ? txObj.signatures : [],
464
+ serviceFee: "0",
465
+ gasFee: "0",
466
+ gasPaid: "0",
467
+ gasPayer,
468
+ itx: {
469
+ typeUrl: txType,
470
+ ...typeName ? { __typename: typeName } : {}
471
+ },
472
+ itxJson
473
+ },
474
+ receipts: [],
475
+ tokenSymbols: [],
476
+ accounts
477
+ };
478
+ await this.indexdb.tx.insert(rejectedRow);
479
+ } catch (indexErr) {
480
+ await this.recordIndexFailure({
481
+ table: "tx",
482
+ event: "create",
483
+ entityId: txHash,
484
+ payload: rejectedRow ?? { hash: txHash },
485
+ error: indexErr
486
+ });
487
+ }
488
+ }
489
+ getTxSecurityWarning(txHash) {
490
+ return getTxSecurityWarningByHash(txHash, this.statedb);
491
+ }
492
+ async getTx({ hash }, ctx) {
493
+ if (patterns.txHash.test(hash)) {
494
+ const normalizedHash = hash.toUpperCase();
495
+ const stateTx = await this._getState({
496
+ table: "tx",
497
+ id: normalizedHash,
498
+ dataKey: "tx.itxJson.data",
499
+ onRead: (tx) => this.formatTx(tx, ctx),
500
+ expandContext: false,
501
+ ctx
502
+ });
503
+ if (stateTx) return stateTx;
504
+ if (this.indexdb?.tx?.get) {
505
+ const indexedTx = await Promise.resolve(this.indexdb.tx.get(normalizedHash)).catch(() => null);
506
+ if (indexedTx && (indexedTx.valid === false || indexedTx.valid === 0 || indexedTx.code !== "OK")) return this.formatTx(indexedTx, ctx);
507
+ }
508
+ }
509
+ return null;
341
510
  }
342
511
  getBlock() {
343
512
  return null;
@@ -1365,18 +1534,28 @@ var OCAPResolver = class {
1365
1534
  async _formatTx(tx, ctx) {
1366
1535
  if (!tx) return tx;
1367
1536
  if (!tx.sender && !tx.receiver) {
1368
- const typeUrl$1 = fromTypeUrl(tx.tx.itx.typeUrl);
1369
- tx.sender = getTxSender({
1370
- tx: tx.tx,
1371
- itx: tx.tx.itxJson,
1372
- typeUrl: typeUrl$1
1373
- });
1374
- tx.receiver = getTxReceiver({
1375
- tx: tx.tx,
1376
- itx: tx.tx.itxJson,
1377
- typeUrl: typeUrl$1
1378
- });
1537
+ const rawTypeUrl = tx.tx?.itx?.typeUrl || (tx.tx?.itx)?.__typename || tx.tx?.itxJson?.type_url || (tx.tx?.itxJson)?._type || "";
1538
+ let parsedTypeUrl = rawTypeUrl;
1539
+ if (rawTypeUrl.startsWith("fg:t:")) try {
1540
+ parsedTypeUrl = fromTypeUrl(rawTypeUrl);
1541
+ } catch {
1542
+ parsedTypeUrl = rawTypeUrl;
1543
+ }
1544
+ if (parsedTypeUrl) {
1545
+ tx.sender = getTxSender({
1546
+ tx: tx.tx,
1547
+ itx: tx.tx?.itxJson || {},
1548
+ typeUrl: parsedTypeUrl
1549
+ });
1550
+ tx.receiver = getTxReceiver({
1551
+ tx: tx.tx,
1552
+ itx: tx.tx?.itxJson || {},
1553
+ typeUrl: parsedTypeUrl
1554
+ });
1555
+ }
1556
+ if (!tx.sender && tx.valid === false) tx.sender = deriveTxSender(tx);
1379
1557
  }
1558
+ if (!tx.gasPayer) tx.gasPayer = deriveTxGasPayer(tx);
1380
1559
  if (!tx.receipts) tx.receipts = getTxReceipts(tx, { config: this.config });
1381
1560
  const typeUrl = get(tx, "tx.itxJson.type_url");
1382
1561
  if (typeUrl === "fg:t:revoke_withdraw" || typeUrl === "fg:t:approve_withdraw") {
@@ -1451,7 +1630,7 @@ var OCAPResolver = class {
1451
1630
  }));
1452
1631
  }
1453
1632
  async getTxTokenSymbols(tx) {
1454
- if (!tx) return [];
1633
+ if (!tx || !tx.tx?.itxJson) return [];
1455
1634
  const rollupTxs = [
1456
1635
  "DepositTokenV2Tx",
1457
1636
  "WithdrawTokenV2Tx",
@@ -1460,43 +1639,56 @@ var OCAPResolver = class {
1460
1639
  "CreateRollupBlockTx",
1461
1640
  "ClaimBlockRewardTx"
1462
1641
  ];
1463
- const typeUrl = tx.tx.itxJson._type || "";
1642
+ const itxJson = tx.tx.itxJson;
1643
+ const typeUrl = itxJson._type || "";
1464
1644
  const tokens = [];
1465
1645
  if (isDefaultTokenChanged(tx, this.config.token)) tokens.push(this.tokenItx);
1466
1646
  if (typeUrl === "AcquireAssetV2Tx") {
1467
- const factoryInput = (await this.indexdb.factory.get(tx.tx.itxJson.factory))?.input;
1468
- if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1647
+ if (typeof itxJson.factory === "string" && itxJson.factory) {
1648
+ const factoryInput = (await this.indexdb.factory.get(itxJson.factory))?.input;
1649
+ if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1650
+ }
1469
1651
  } else if (typeUrl === "ExchangeV2Tx") {
1470
- tokens.push(...tx.tx.itxJson.sender?.tokens || []);
1471
- tokens.push(...tx.tx.itxJson.receiver?.tokens || []);
1472
- } else if (typeUrl === "TransferV2Tx") tokens.push(...tx.tx.itxJson.tokens || []);
1652
+ tokens.push(...itxJson.sender?.tokens || []);
1653
+ tokens.push(...itxJson.receiver?.tokens || []);
1654
+ } else if (typeUrl === "TransferV2Tx") tokens.push(...itxJson.tokens || []);
1473
1655
  else if ([
1474
1656
  "TransferV3Tx",
1475
1657
  "AcquireAssetV3Tx",
1476
1658
  "StakeTx"
1477
- ].includes(typeUrl)) tokens.push(...uniqBy((tx.tx.itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1659
+ ].includes(typeUrl)) tokens.push(...uniqBy((itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1478
1660
  else if ([
1479
1661
  "RevokeStakeTx",
1480
1662
  "SlashStakeTx",
1481
1663
  "ReturnStakeTx"
1482
- ].includes(typeUrl)) tokens.push(...uniqBy((tx.tx.itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1664
+ ].includes(typeUrl)) tokens.push(...uniqBy((itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1483
1665
  else if (typeUrl === "ClaimStakeTx") {
1484
- const revokeTx = await this.indexdb.tx.get(tx.tx.itxJson.evidence.hash);
1666
+ const evidenceHash = itxJson.evidence?.hash;
1667
+ const revokeTx = typeof evidenceHash === "string" && evidenceHash ? await this.indexdb.tx.get(evidenceHash) : null;
1485
1668
  if (revokeTx) {
1486
1669
  const revokeTxAny = revokeTx;
1487
1670
  tokens.push(...uniqBy((revokeTxAny.tx?.itxJson?.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1488
1671
  } else this.logger.warn("Revoke stake tx not found", { tx });
1489
1672
  } else if (rollupTxs.includes(typeUrl)) {
1490
- const rollup = await this.indexdb.rollup.get(tx.tx.itxJson.rollup);
1491
- if (rollup) tokens.push({
1492
- address: rollup.tokenAddress,
1493
- value: "0"
1494
- });
1495
- } else if (typeUrl === "CreateTokenTx") return [extractTokenMeta(tx.tx.itxJson.address, [tx.tx.itxJson])];
1496
- else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1497
- const token = await this.indexdb.tokenFactory.get(tx.tx.itxJson.tokenFactory);
1498
- if (token) tokens.push({ address: token.tokenAddress });
1499
- } else if (typeUrl === "CreateTokenFactoryTx") tokens.push({ address: tx.tx.itxJson.token.address });
1673
+ if (typeof itxJson.rollup === "string" && itxJson.rollup) {
1674
+ const rollup = await this.indexdb.rollup.get(itxJson.rollup);
1675
+ if (rollup) tokens.push({
1676
+ address: rollup.tokenAddress,
1677
+ value: "0"
1678
+ });
1679
+ }
1680
+ } else if (typeUrl === "CreateTokenTx") {
1681
+ if (typeof itxJson.address === "string" && itxJson.address) return [extractTokenMeta(itxJson.address, [itxJson])];
1682
+ return [];
1683
+ } else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1684
+ if (typeof itxJson.tokenFactory === "string" && itxJson.tokenFactory) {
1685
+ const token = await this.indexdb.tokenFactory.get(itxJson.tokenFactory);
1686
+ if (token) tokens.push({ address: token.tokenAddress });
1687
+ }
1688
+ } else if (typeUrl === "CreateTokenFactoryTx") {
1689
+ const tokenAddr = itxJson.token?.address;
1690
+ if (typeof tokenAddr === "string" && tokenAddr) tokens.push({ address: tokenAddr });
1691
+ }
1500
1692
  if (tokens.length > 0) return this.formatTokenArray(tokens);
1501
1693
  return [];
1502
1694
  }
package/lib/index.cjs CHANGED
@@ -264,6 +264,7 @@ var OCAPResolver = class {
264
264
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
265
265
  */
266
266
  constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
267
+ this.inFlightPreFlights = 0;
267
268
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
268
269
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
269
270
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
@@ -307,8 +308,9 @@ var OCAPResolver = class {
307
308
  request: ctx.request
308
309
  });
309
310
  if (process.env.CHAIN_MODE === "readonly") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "This chain node is running in readonly mode");
310
- if (this.queue.length >= txRequestConfig.maxRequest) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
311
- if (!txBase64 || typeof txBase64 !== "string" || txBase64.length < 20) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Transaction data is empty or too short");
311
+ const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
312
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
313
+ (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
312
314
  const timer = new _ocap_tx_protocols.TxTimer();
313
315
  timer.setQueueState({
314
316
  waitingAtEnqueue: Math.max(0, this.queue.length - (this.queue.pending ?? 0)),
@@ -330,28 +332,195 @@ var OCAPResolver = class {
330
332
  }
331
333
  };
332
334
  return new Promise((resolve, reject) => {
333
- const task = async () => {
334
- timer.mark("queueWait");
335
+ this.inFlightPreFlights += 1;
336
+ let preFlightSlotReleased = false;
337
+ const releasePreFlightSlot = () => {
338
+ if (!preFlightSlotReleased) {
339
+ preFlightSlotReleased = true;
340
+ this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
341
+ }
342
+ };
343
+ const enqueueAfterPreFlight = async () => {
335
344
  try {
336
345
  await this.initializationPromise;
337
- resolve((await this.executor.execute(context)).txHash);
338
- } catch (err) {
339
- reject(err);
346
+ await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(context);
347
+ const preTx = context.tx;
348
+ const preTxHash = context.txHash;
349
+ if (preTx) await (0, _ocap_tx_protocols.assertTxAdmission)({
350
+ tx: preTx,
351
+ txHash: preTxHash,
352
+ unsignedTxHash: context.unsignedTxHash,
353
+ config: this.config,
354
+ statedb: this.statedb
355
+ });
356
+ } catch (preFlightErr) {
357
+ const errObj = preFlightErr;
358
+ const strikeCtx = errObj._preFlightCtx || context;
359
+ const txHash = strikeCtx.txHash || context.txHash;
360
+ const classified = (0, _ocap_tx_protocols.classifyErrorStrikeCategory)(errObj);
361
+ if (classified.shouldRecordStrike && !errObj._strikeRecorded && errObj._unauthenticatedExtraFailure !== true) try {
362
+ const actors = await (0, _ocap_tx_protocols.resolveVerifiedStrikeActors)(strikeCtx);
363
+ if (actors.length > 0) {
364
+ errObj._strikeRecorded = true;
365
+ const { primaryWarning, slashEvidence } = await (0, _ocap_tx_protocols.recordActorSecurityStrike)({
366
+ actors,
367
+ category: classified.category,
368
+ reasonCode: classified.code,
369
+ txHash,
370
+ config: this.config,
371
+ statedb: this.statedb
372
+ });
373
+ if (primaryWarning && !errObj.warning) errObj.warning = primaryWarning;
374
+ if (slashEvidence && !errObj.slashEvidence) errObj.slashEvidence = slashEvidence;
375
+ }
376
+ } catch (strikeErr) {
377
+ this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
378
+ }
379
+ releasePreFlightSlot();
380
+ reject(preFlightErr);
381
+ return;
382
+ }
383
+ releasePreFlightSlot();
384
+ const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
385
+ if (this.queue.length >= currentMaxRequest) {
386
+ reject(new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy"));
387
+ return;
340
388
  }
389
+ const task = async () => {
390
+ timer.mark("queueWait");
391
+ try {
392
+ const result = await this.executor.execute(context);
393
+ if (result?.txHash && result?.securityWarning) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(result.txHash, result.securityWarning, this.statedb);
394
+ resolve(result.txHash);
395
+ } catch (err) {
396
+ await this._indexRejectedLedgerTx(context, err);
397
+ reject(err);
398
+ }
399
+ };
400
+ this.queue.push(task);
341
401
  };
342
- this.queue.push(task);
402
+ enqueueAfterPreFlight().catch((err) => {
403
+ releasePreFlightSlot();
404
+ reject(err);
405
+ });
343
406
  });
344
407
  }
345
- getTx({ hash }, ctx) {
346
- if (_arcblock_validator.patterns.txHash.test(hash)) return this._getState({
347
- table: "tx",
348
- id: hash.toUpperCase(),
349
- dataKey: "tx.itxJson.data",
350
- onRead: (tx) => this.formatTx(tx, ctx),
351
- expandContext: false,
352
- ctx
353
- });
354
- return Promise.resolve(null);
408
+ async _indexRejectedLedgerTx(ctx, err) {
409
+ if (!this.indexdb?.tx?.insert) return;
410
+ const ledgerSequence = Number(ctx.ledgerSequence ?? 0);
411
+ const rawTxHash = typeof ctx.txHash === "string" ? ctx.txHash.trim() : "";
412
+ if (!(ledgerSequence > 0) || !rawTxHash) return;
413
+ const txHash = rawTxHash.toUpperCase();
414
+ let rejectedRow;
415
+ try {
416
+ if (await Promise.resolve(this.statedb?.tx?.get?.(txHash)).catch(() => null)) return;
417
+ if (await Promise.resolve(this.indexdb.tx.get?.(txHash)).catch(() => null)) return;
418
+ const txType = typeof ctx.txType === "string" ? ctx.txType : "";
419
+ const type = txType ? txType.split(":").pop() || "" : "";
420
+ let typeName = "";
421
+ if (txType) try {
422
+ typeName = (0, _ocap_message.fromTypeUrl)(txType);
423
+ } catch {
424
+ typeName = "";
425
+ }
426
+ const txObj = ctx.tx && typeof ctx.tx === "object" ? ctx.tx : {};
427
+ const from = typeof txObj.from === "string" ? txObj.from : "";
428
+ const delegator = typeof txObj.delegator === "string" ? txObj.delegator : "";
429
+ const toStrOrBase64 = (val) => {
430
+ if (typeof val === "string") return val;
431
+ if (val instanceof Uint8Array || Buffer.isBuffer(val)) return Buffer.from(val).toString("base64");
432
+ return "";
433
+ };
434
+ const sourceItx = ctx.itxJson && typeof ctx.itxJson === "object" ? ctx.itxJson : ctx.itx && typeof ctx.itx === "object" ? ctx.itx : null;
435
+ const itxJson = sourceItx ? { ...sourceItx } : {
436
+ ...typeName ? { _type: typeName } : {},
437
+ type_url: txType
438
+ };
439
+ if (!itxJson.type_url && txType) itxJson.type_url = txType;
440
+ if (!itxJson._type && typeName) itxJson._type = typeName;
441
+ const syntheticTx = {
442
+ valid: false,
443
+ code: String(err?.code || "INTERNAL"),
444
+ tx: {
445
+ from,
446
+ delegator,
447
+ itxJson
448
+ }
449
+ };
450
+ const sender = (0, _ocap_indexdb_lib_util.deriveTxSender)(syntheticTx, ctx);
451
+ const gasPayer = "";
452
+ const time = typeof ctx.txTime === "string" && ctx.txTime || (/* @__PURE__ */ new Date()).toISOString();
453
+ const code = syntheticTx.code;
454
+ const accounts = (0, lodash_uniq.default)([
455
+ from,
456
+ delegator,
457
+ sender
458
+ ].filter(Boolean));
459
+ rejectedRow = {
460
+ hash: txHash,
461
+ type,
462
+ code,
463
+ valid: false,
464
+ time,
465
+ sender,
466
+ receiver: "",
467
+ gasPayer,
468
+ gasUsed: "0",
469
+ tx: {
470
+ chainId: String(txObj.chainId || this.config?.chainId || ""),
471
+ from,
472
+ delegator,
473
+ nonce: txObj.nonce ?? 0,
474
+ pk: toStrOrBase64(txObj.pk),
475
+ signature: toStrOrBase64(txObj.signature),
476
+ signaturesList: Array.isArray(txObj.signaturesList) ? txObj.signaturesList : [],
477
+ signatures: Array.isArray(txObj.signatures) ? txObj.signatures : [],
478
+ serviceFee: "0",
479
+ gasFee: "0",
480
+ gasPaid: "0",
481
+ gasPayer,
482
+ itx: {
483
+ typeUrl: txType,
484
+ ...typeName ? { __typename: typeName } : {}
485
+ },
486
+ itxJson
487
+ },
488
+ receipts: [],
489
+ tokenSymbols: [],
490
+ accounts
491
+ };
492
+ await this.indexdb.tx.insert(rejectedRow);
493
+ } catch (indexErr) {
494
+ await this.recordIndexFailure({
495
+ table: "tx",
496
+ event: "create",
497
+ entityId: txHash,
498
+ payload: rejectedRow ?? { hash: txHash },
499
+ error: indexErr
500
+ });
501
+ }
502
+ }
503
+ getTxSecurityWarning(txHash) {
504
+ return (0, _ocap_tx_protocols.getTxSecurityWarningByHash)(txHash, this.statedb);
505
+ }
506
+ async getTx({ hash }, ctx) {
507
+ if (_arcblock_validator.patterns.txHash.test(hash)) {
508
+ const normalizedHash = hash.toUpperCase();
509
+ const stateTx = await this._getState({
510
+ table: "tx",
511
+ id: normalizedHash,
512
+ dataKey: "tx.itxJson.data",
513
+ onRead: (tx) => this.formatTx(tx, ctx),
514
+ expandContext: false,
515
+ ctx
516
+ });
517
+ if (stateTx) return stateTx;
518
+ if (this.indexdb?.tx?.get) {
519
+ const indexedTx = await Promise.resolve(this.indexdb.tx.get(normalizedHash)).catch(() => null);
520
+ if (indexedTx && (indexedTx.valid === false || indexedTx.valid === 0 || indexedTx.code !== "OK")) return this.formatTx(indexedTx, ctx);
521
+ }
522
+ }
523
+ return null;
355
524
  }
356
525
  getBlock() {
357
526
  return null;
@@ -1379,18 +1548,28 @@ var OCAPResolver = class {
1379
1548
  async _formatTx(tx, ctx) {
1380
1549
  if (!tx) return tx;
1381
1550
  if (!tx.sender && !tx.receiver) {
1382
- const typeUrl$1 = (0, _ocap_message.fromTypeUrl)(tx.tx.itx.typeUrl);
1383
- tx.sender = (0, _ocap_state_lib_states_tx.getTxSender)({
1384
- tx: tx.tx,
1385
- itx: tx.tx.itxJson,
1386
- typeUrl: typeUrl$1
1387
- });
1388
- tx.receiver = (0, _ocap_state_lib_states_tx.getTxReceiver)({
1389
- tx: tx.tx,
1390
- itx: tx.tx.itxJson,
1391
- typeUrl: typeUrl$1
1392
- });
1551
+ const rawTypeUrl = tx.tx?.itx?.typeUrl || (tx.tx?.itx)?.__typename || tx.tx?.itxJson?.type_url || (tx.tx?.itxJson)?._type || "";
1552
+ let parsedTypeUrl = rawTypeUrl;
1553
+ if (rawTypeUrl.startsWith("fg:t:")) try {
1554
+ parsedTypeUrl = (0, _ocap_message.fromTypeUrl)(rawTypeUrl);
1555
+ } catch {
1556
+ parsedTypeUrl = rawTypeUrl;
1557
+ }
1558
+ if (parsedTypeUrl) {
1559
+ tx.sender = (0, _ocap_state_lib_states_tx.getTxSender)({
1560
+ tx: tx.tx,
1561
+ itx: tx.tx?.itxJson || {},
1562
+ typeUrl: parsedTypeUrl
1563
+ });
1564
+ tx.receiver = (0, _ocap_state_lib_states_tx.getTxReceiver)({
1565
+ tx: tx.tx,
1566
+ itx: tx.tx?.itxJson || {},
1567
+ typeUrl: parsedTypeUrl
1568
+ });
1569
+ }
1570
+ if (!tx.sender && tx.valid === false) tx.sender = (0, _ocap_indexdb_lib_util.deriveTxSender)(tx);
1393
1571
  }
1572
+ if (!tx.gasPayer) tx.gasPayer = (0, _ocap_indexdb_lib_util.deriveTxGasPayer)(tx);
1394
1573
  if (!tx.receipts) tx.receipts = (0, _ocap_state_lib_states_tx.getTxReceipts)(tx, { config: this.config });
1395
1574
  const typeUrl = (0, lodash_get.default)(tx, "tx.itxJson.type_url");
1396
1575
  if (typeUrl === "fg:t:revoke_withdraw" || typeUrl === "fg:t:approve_withdraw") {
@@ -1465,7 +1644,7 @@ var OCAPResolver = class {
1465
1644
  }));
1466
1645
  }
1467
1646
  async getTxTokenSymbols(tx) {
1468
- if (!tx) return [];
1647
+ if (!tx || !tx.tx?.itxJson) return [];
1469
1648
  const rollupTxs = [
1470
1649
  "DepositTokenV2Tx",
1471
1650
  "WithdrawTokenV2Tx",
@@ -1474,43 +1653,56 @@ var OCAPResolver = class {
1474
1653
  "CreateRollupBlockTx",
1475
1654
  "ClaimBlockRewardTx"
1476
1655
  ];
1477
- const typeUrl = tx.tx.itxJson._type || "";
1656
+ const itxJson = tx.tx.itxJson;
1657
+ const typeUrl = itxJson._type || "";
1478
1658
  const tokens = [];
1479
1659
  if ((0, _ocap_indexdb_lib_util.isDefaultTokenChanged)(tx, this.config.token)) tokens.push(this.tokenItx);
1480
1660
  if (typeUrl === "AcquireAssetV2Tx") {
1481
- const factoryInput = (await this.indexdb.factory.get(tx.tx.itxJson.factory))?.input;
1482
- if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1661
+ if (typeof itxJson.factory === "string" && itxJson.factory) {
1662
+ const factoryInput = (await this.indexdb.factory.get(itxJson.factory))?.input;
1663
+ if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1664
+ }
1483
1665
  } else if (typeUrl === "ExchangeV2Tx") {
1484
- tokens.push(...tx.tx.itxJson.sender?.tokens || []);
1485
- tokens.push(...tx.tx.itxJson.receiver?.tokens || []);
1486
- } else if (typeUrl === "TransferV2Tx") tokens.push(...tx.tx.itxJson.tokens || []);
1666
+ tokens.push(...itxJson.sender?.tokens || []);
1667
+ tokens.push(...itxJson.receiver?.tokens || []);
1668
+ } else if (typeUrl === "TransferV2Tx") tokens.push(...itxJson.tokens || []);
1487
1669
  else if ([
1488
1670
  "TransferV3Tx",
1489
1671
  "AcquireAssetV3Tx",
1490
1672
  "StakeTx"
1491
- ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((tx.tx.itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1673
+ ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1492
1674
  else if ([
1493
1675
  "RevokeStakeTx",
1494
1676
  "SlashStakeTx",
1495
1677
  "ReturnStakeTx"
1496
- ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((tx.tx.itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1678
+ ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1497
1679
  else if (typeUrl === "ClaimStakeTx") {
1498
- const revokeTx = await this.indexdb.tx.get(tx.tx.itxJson.evidence.hash);
1680
+ const evidenceHash = itxJson.evidence?.hash;
1681
+ const revokeTx = typeof evidenceHash === "string" && evidenceHash ? await this.indexdb.tx.get(evidenceHash) : null;
1499
1682
  if (revokeTx) {
1500
1683
  const revokeTxAny = revokeTx;
1501
1684
  tokens.push(...(0, lodash_unionBy.default)((revokeTxAny.tx?.itxJson?.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1502
1685
  } else this.logger.warn("Revoke stake tx not found", { tx });
1503
1686
  } else if (rollupTxs.includes(typeUrl)) {
1504
- const rollup = await this.indexdb.rollup.get(tx.tx.itxJson.rollup);
1505
- if (rollup) tokens.push({
1506
- address: rollup.tokenAddress,
1507
- value: "0"
1508
- });
1509
- } else if (typeUrl === "CreateTokenTx") return [extractTokenMeta(tx.tx.itxJson.address, [tx.tx.itxJson])];
1510
- else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1511
- const token = await this.indexdb.tokenFactory.get(tx.tx.itxJson.tokenFactory);
1512
- if (token) tokens.push({ address: token.tokenAddress });
1513
- } else if (typeUrl === "CreateTokenFactoryTx") tokens.push({ address: tx.tx.itxJson.token.address });
1687
+ if (typeof itxJson.rollup === "string" && itxJson.rollup) {
1688
+ const rollup = await this.indexdb.rollup.get(itxJson.rollup);
1689
+ if (rollup) tokens.push({
1690
+ address: rollup.tokenAddress,
1691
+ value: "0"
1692
+ });
1693
+ }
1694
+ } else if (typeUrl === "CreateTokenTx") {
1695
+ if (typeof itxJson.address === "string" && itxJson.address) return [extractTokenMeta(itxJson.address, [itxJson])];
1696
+ return [];
1697
+ } else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1698
+ if (typeof itxJson.tokenFactory === "string" && itxJson.tokenFactory) {
1699
+ const token = await this.indexdb.tokenFactory.get(itxJson.tokenFactory);
1700
+ if (token) tokens.push({ address: token.tokenAddress });
1701
+ }
1702
+ } else if (typeUrl === "CreateTokenFactoryTx") {
1703
+ const tokenAddr = itxJson.token?.address;
1704
+ if (typeof tokenAddr === "string" && tokenAddr) tokens.push({ address: tokenAddr });
1705
+ }
1514
1706
  if (tokens.length > 0) return this.formatTokenArray(tokens);
1515
1707
  return [];
1516
1708
  }
package/lib/index.d.cts CHANGED
@@ -2,7 +2,7 @@ import { IAddressArgs, IAssetState, IChainConfig, IChunkIterator, IDataObject, I
2
2
  import { MigrationChainManager } from "./migration-chain.cjs";
3
3
  import { TokenDistributionManager } from "./token-distribution.cjs";
4
4
  import { ILedger } from "@ocap/types";
5
- import { createExecutor } from "@ocap/tx-protocols";
5
+ import { ITxSecurityWarning, createExecutor } from "@ocap/tx-protocols";
6
6
  import Queue from "queue";
7
7
 
8
8
  //#region src/index.d.ts
@@ -24,6 +24,7 @@ declare class OCAPResolver implements IResolver {
24
24
  logger: IPipelineLogger$1;
25
25
  migrationChain?: MigrationChainManager;
26
26
  formatTx: (tx: IResolverTransaction | null, ctx?: IResolverContext$1) => Promise<IResolverTransaction | null>;
27
+ inFlightPreFlights: number;
27
28
  private initializationPromise;
28
29
  /**
29
30
  * Creates an instance of OCAPResolver.
@@ -51,6 +52,8 @@ declare class OCAPResolver implements IResolver {
51
52
  tx: string;
52
53
  extra?: Record<string, unknown>;
53
54
  }, ctx?: IResolverContext$1): Promise<string>;
55
+ _indexRejectedLedgerTx(ctx: Record<string, unknown>, err: unknown): Promise<void>;
56
+ getTxSecurityWarning(txHash: string): ITxSecurityWarning | undefined;
54
57
  getTx({
55
58
  hash
56
59
  }: TRequestGetTx, ctx?: IResolverContext$1): Promise<IResolverTransaction | null>;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.30.26",
6
+ "version": "1.31.1",
7
7
  "description": "GraphQL resolver built upon ocap statedb and GQL layer",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -49,20 +49,20 @@
49
49
  "tsdown": "^0.18.4"
50
50
  },
51
51
  "dependencies": {
52
- "@arcblock/did": "1.30.26",
53
- "@arcblock/did-ext": "1.30.26",
54
- "@arcblock/did-util": "1.30.26",
52
+ "@arcblock/did": "1.31.1",
53
+ "@arcblock/did-ext": "1.31.1",
54
+ "@arcblock/did-util": "1.31.1",
55
55
  "@arcblock/nft-display": "^3.2.3",
56
- "@arcblock/validator": "1.30.26",
57
- "@ocap/config": "1.30.26",
58
- "@ocap/indexdb": "1.30.26",
59
- "@ocap/mcrypto": "1.30.26",
60
- "@ocap/message": "1.30.26",
61
- "@ocap/state": "1.30.26",
62
- "@ocap/tx-protocols": "1.30.26",
63
- "@ocap/types": "1.30.26",
64
- "@ocap/util": "1.30.26",
65
- "@ocap/wallet": "1.30.26",
56
+ "@arcblock/validator": "1.31.1",
57
+ "@ocap/config": "1.31.1",
58
+ "@ocap/indexdb": "1.31.1",
59
+ "@ocap/mcrypto": "1.31.1",
60
+ "@ocap/message": "1.31.1",
61
+ "@ocap/state": "1.31.1",
62
+ "@ocap/tx-protocols": "1.31.1",
63
+ "@ocap/types": "1.31.1",
64
+ "@ocap/util": "1.31.1",
65
+ "@ocap/wallet": "1.31.1",
66
66
  "debug": "^4.4.3",
67
67
  "express": "^4.22.1",
68
68
  "lodash": "^4.17.23",