@ocap/resolver 1.31.8 → 1.32.0

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.
Files changed (42) hide show
  1. package/esm/_virtual/rolldown_runtime.mjs +7 -0
  2. package/esm/api.d.mts +33 -5
  3. package/esm/api.mjs +939 -53
  4. package/esm/dashboard.d.mts +199 -0
  5. package/esm/dashboard.mjs +2481 -0
  6. package/esm/explorer.d.mts +29 -0
  7. package/esm/explorer.mjs +227 -0
  8. package/esm/follower.d.mts +277 -0
  9. package/esm/follower.mjs +2428 -0
  10. package/esm/hooks.mjs +1 -1
  11. package/esm/hotstuff-runtime.d.mts +271 -0
  12. package/esm/hotstuff-runtime.mjs +2668 -0
  13. package/esm/index.d.mts +87 -4
  14. package/esm/index.mjs +937 -177
  15. package/esm/node-preferences.d.mts +203 -0
  16. package/esm/node-preferences.mjs +1021 -0
  17. package/esm/replayer.d.mts +74 -0
  18. package/esm/replayer.mjs +394 -0
  19. package/esm/token-distribution.mjs +2 -2
  20. package/esm/token-flow.mjs +1 -1
  21. package/esm/types.d.mts +25 -2
  22. package/lib/api.cjs +941 -52
  23. package/lib/api.d.cts +33 -5
  24. package/lib/dashboard.cjs +2491 -0
  25. package/lib/dashboard.d.cts +199 -0
  26. package/lib/explorer.cjs +227 -0
  27. package/lib/explorer.d.cts +29 -0
  28. package/lib/follower.cjs +2434 -0
  29. package/lib/follower.d.cts +277 -0
  30. package/lib/hooks.cjs +1 -1
  31. package/lib/hotstuff-runtime.cjs +2671 -0
  32. package/lib/hotstuff-runtime.d.cts +271 -0
  33. package/lib/index.cjs +972 -177
  34. package/lib/index.d.cts +87 -4
  35. package/lib/node-preferences.cjs +1043 -0
  36. package/lib/node-preferences.d.cts +203 -0
  37. package/lib/replayer.cjs +395 -0
  38. package/lib/replayer.d.cts +74 -0
  39. package/lib/token-distribution.cjs +2 -2
  40. package/lib/token-flow.cjs +1 -1
  41. package/lib/types.d.cts +25 -2
  42. package/package.json +20 -14
package/esm/index.mjs CHANGED
@@ -1,26 +1,33 @@
1
+ import { MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, NodePreferencesError, NodePreferencesManager, applyBootRuntimePreferences, createAdminAuthGuard, createFollowerPeerFetchGuard, isPrivateOrReservedIpAddress, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls } from "./node-preferences.mjs";
2
+ import { UNIFIED_CONSOLE_APP_JS, buildUnifiedConsoleHtml, collectLedgerHealthSummary, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, isDashboardEnabled } from "./dashboard.mjs";
3
+ import { createExplorerMiddleware, isExplorerEnabled } from "./explorer.mjs";
4
+ import { LedgerEntryReplayer } from "./replayer.mjs";
5
+ import { DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, isTransientSqliteLockError } from "./follower.mjs";
1
6
  import { name } from "./package.mjs";
2
7
  import { onCreateRollup, onCreateRollupBlock, onCreateTx, onUpdateToken } from "./hooks.mjs";
8
+ import { ConsensusAbortError, HotStuffNodeRuntime } from "./hotstuff-runtime.mjs";
3
9
  import { MigrationChainManager } from "./migration-chain.mjs";
4
10
  import { getInstance } from "./token-cache.mjs";
5
11
  import { TokenDistributionManager } from "./token-distribution.mjs";
6
12
  import { listTokenFlows, verifyAccountRisk } from "./token-flow.mjs";
7
- import { toStakeAddress } from "@arcblock/did-util";
13
+ import { computeForwardReceiptDigest } from "@arcblock/ledger-core";
14
+ import { types } from "@ocap/mcrypto";
15
+ import { TxTimer, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, createExecutor, getTxSecurityWarningByHash, inspectTransactionPreFlight, recordActorSecurityStrike, resolveVerifiedStrikeActors, setTxSecurityWarningForHash } from "@ocap/tx-protocols";
16
+ import { randomUUID } from "node:crypto";
17
+ import { fromPublicKey, isValid, toTypeInfo } from "@arcblock/did";
8
18
  import { BN, fromTokenToUnit, toAddress, toBN } from "@ocap/util";
19
+ import { CustomError } from "@ocap/util/lib/error";
20
+ import * as states from "@ocap/state";
21
+ import { toStakeAddress } from "@arcblock/did-util";
9
22
  import createDebug from "debug";
10
23
  import pick from "lodash/pick.js";
11
- import { randomUUID } from "node:crypto";
12
- import { fromPublicKey, isValid, toTypeInfo } from "@arcblock/did";
13
24
  import { patterns, v, vDID, vValidate } from "@arcblock/validator";
14
25
  import * as Config from "@ocap/config";
15
26
  import { formatSearchResult, rebuildIndexFromState } from "@ocap/indexdb";
16
- import { types } from "@ocap/mcrypto";
17
27
  import { fromTypeUrl } from "@ocap/message";
18
- import * as states from "@ocap/state";
19
- import { TxTimer, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, createExecutor, getTxSecurityWarningByHash, inspectTransactionPreFlight, recordActorSecurityStrike, resolveVerifiedStrikeActors, setTxSecurityWarningForHash } from "@ocap/tx-protocols";
20
28
  import { decodeAnySafe } from "@ocap/tx-protocols/lib/util";
21
29
  import { DEFAULT_TOKEN_DECIMAL } from "@ocap/util/lib/constant";
22
30
  import { stripDefaultDepositV2BridgeFields } from "@ocap/util/lib/deposit-v2-bridge-fields";
23
- import { CustomError } from "@ocap/util/lib/error";
24
31
  import { md5 } from "@ocap/util/lib/md5";
25
32
  import cloneDeep from "lodash/cloneDeep.js";
26
33
  import get from "lodash/get.js";
@@ -31,13 +38,16 @@ import set from "lodash/set.js";
31
38
  import uniqBy from "lodash/unionBy.js";
32
39
  import uniq from "lodash/uniq.js";
33
40
  import Queue from "queue";
34
- import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
41
+ import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatTxBeforeInsert, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
35
42
  import { attachPaidTxGas, getTxReceipts, getTxReceiver, getTxSender, mergeTxReceipts } from "@ocap/state/lib/states/tx";
36
43
 
37
44
  //#region src/index.ts
38
45
  const debug = createDebug(name);
39
46
  const noop = (x) => x;
40
47
  const CHAIN_ADDR = md5("OCAP_CHAIN_ADDR");
48
+ function getNormalizedEnvLower(key) {
49
+ return String(process.env[key] ?? "").trim().toLowerCase();
50
+ }
41
51
  const maxGasOps = {
42
52
  "fg:t:account_migrate": {
43
53
  create: 2,
@@ -244,6 +254,34 @@ const extractTokenMeta = (address, tokenStates) => {
244
254
  foreignToken: tokenState.foreignToken
245
255
  };
246
256
  };
257
+ /**
258
+ * Index `tx` columns a GraphQL `IndexedTransaction` read needs (#1872): the type's fields (hash sender receiver time
259
+ * type tx valid code receipts gasPayer; `tokenSymbols` is always recomputed by _formatTx) plus every input of
260
+ * _formatTx / getTxReceipts / getTxSender / deriveTxGasPayer / isDefaultTokenChanged / attachPaidTxGas, which only
261
+ * read these. Used only when the caller sets `ctx.graphqlTxProjection` (@ocap/gql does, for listTransactions and
262
+ * listAssetTransactions); every other caller keeps receiving every column.
263
+ */
264
+ const GRAPHQL_INDEXED_TX_COLUMNS = [
265
+ "hash",
266
+ "code",
267
+ "receipts",
268
+ "receiver",
269
+ "sender",
270
+ "gasPayer",
271
+ "time",
272
+ "tx",
273
+ "type",
274
+ "valid"
275
+ ];
276
+ const withTxProjection = (args, ctx) => ctx?.graphqlTxProjection === true ? {
277
+ ...args,
278
+ columns: GRAPHQL_INDEXED_TX_COLUMNS
279
+ } : args;
280
+ const assertResolverNotHaltedForDataRead = (self) => {
281
+ const runtime = self?.nodeRuntime;
282
+ if (runtime?.isHalted?.() === true) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
283
+ if (runtime?.isReconciling?.() === true) throw new CustomError("FOLLOWER_RECONCILING", "Follower is reconciling local statedb with imported ledger segment");
284
+ };
247
285
  var OCAPResolver = class {
248
286
  /**
249
287
  * Creates an instance of OCAPResolver.
@@ -255,24 +293,44 @@ var OCAPResolver = class {
255
293
  * @param params.filter bloom filter to do anti-replay check
256
294
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
257
295
  */
258
- constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
296
+ constructor({ statedb, indexdb, ledger, config, filter, admissionBlockedCheck, admissionReservedSymbolCheck, validateTokenConfig = true, skipInitializeStateDB = false, deferInitialize = false, consensusMode, txQueueConfig, now, nodeRuntime, logger }) {
259
297
  this.inFlightPreFlights = 0;
298
+ this.initializationPromise = null;
299
+ this.shutdownPromise = null;
300
+ this.isShuttingDown = false;
301
+ this.preFlightDrainWaiters = [];
302
+ this.pendingIndexWrites = /* @__PURE__ */ new Set();
303
+ this.txAcceptedTotal = 0;
304
+ this.txPersistedFailedTotal = 0;
305
+ this.txPreFlightRejectedTotal = 0;
306
+ this.txForwardedTotal = 0;
307
+ this.txBucketsSec = new Int32Array(60);
308
+ this.txBucketCounts = new Int32Array(60);
260
309
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
261
310
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
262
311
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
263
312
  this.logger = logger || console;
313
+ this.now = typeof now === "function" ? now : () => Date.now();
314
+ this.deferInitialize = Boolean(deferInitialize);
315
+ this.explicitConsensusMode = consensusMode;
264
316
  this.statedb = statedb;
265
317
  this.indexdb = indexdb;
266
318
  this.ledger = ledger;
267
319
  this.filter = filter;
320
+ this.admissionBlockedCheck = admissionBlockedCheck;
321
+ this.admissionReservedSymbolCheck = admissionReservedSymbolCheck;
322
+ this.skipInitializeStateDB = Boolean(skipInitializeStateDB);
323
+ this.nodeRuntime = nodeRuntime;
268
324
  this.config = Object.freeze(Config.validate(config));
269
325
  this.chainAddr = md5(config.chainId);
270
326
  this.tokenItx = Config.genTokenItx(this.config);
271
327
  this.consensus = `${statedb.name} v${statedb.version}`;
328
+ const isHotStuffMode = consensusMode === "hotstuff" || !consensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(nodeRuntime?.getConsensusCommitter?.());
329
+ if (txQueueConfig?.maxRequest !== void 0) this.setMaxTxRequest(txQueueConfig.maxRequest);
272
330
  this.queue = new Queue({
273
331
  autostart: true,
274
- concurrency: txRequestConfig.concurrent,
275
- timeout: txRequestConfig.timeout
332
+ concurrency: isHotStuffMode ? 1 : txQueueConfig?.concurrent ?? txRequestConfig.concurrent,
333
+ timeout: txQueueConfig?.timeoutMs ?? txRequestConfig.timeout
276
334
  });
277
335
  if (indexdb) {
278
336
  this.tokenCache = getInstance(indexdb.token);
@@ -287,28 +345,387 @@ var OCAPResolver = class {
287
345
  runAsLambda: typeof statedb.runAsLambda === "function" ? statedb.runAsLambda.bind(statedb) : void 0
288
346
  });
289
347
  this.formatTx = this._formatTx.bind(this);
290
- if (validateTokenConfig) this.validateTokenConfig();
348
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
349
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
350
+ const isReadonlyStartRole = Boolean(skipInitializeStateDB) || nodeRuntime && nodeRuntime.role !== "validator" || normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
351
+ if (validateTokenConfig && !isReadonlyStartRole) this.validateTokenConfig();
291
352
  this.connectIndexDB();
292
- this.initializationPromise = this.initializeStateDB().catch((err) => {
353
+ if (!this.deferInitialize) this.initializationPromise = this.initializeStateDB().catch((err) => {
293
354
  this.logger.error("Failed to initialize statedb:", err.message);
294
355
  process.exit(1);
295
356
  });
296
357
  }
358
+ initialize() {
359
+ if (!this.initializationPromise) this.initializationPromise = this.initializeStateDB();
360
+ return this.initializationPromise;
361
+ }
362
+ setNodeRuntime(runtime) {
363
+ this.nodeRuntime = runtime;
364
+ if (runtime?.getConsensusCommitter?.()) this.queue.concurrency = 1;
365
+ }
366
+ getNodeRuntime() {
367
+ return this.nodeRuntime;
368
+ }
369
+ setAdmissionBlockedCheck(fn) {
370
+ this.admissionBlockedCheck = fn;
371
+ }
372
+ setAdmissionReservedSymbolCheck(fn) {
373
+ this.admissionReservedSymbolCheck = fn;
374
+ }
375
+ getMaxTxRequest() {
376
+ if (this.maxTxRequestOverride !== void 0) return this.maxTxRequestOverride;
377
+ return Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
378
+ }
379
+ setMaxTxRequest(maxRequest) {
380
+ if (maxRequest === void 0) {
381
+ this.maxTxRequestOverride = void 0;
382
+ return;
383
+ }
384
+ if (!Number.isSafeInteger(maxRequest) || maxRequest < 1 || maxRequest > 1e4) throw new CustomError("INVALID_CONFIG", "txMaxRequest must be an integer between 1 and 10000");
385
+ this.maxTxRequestOverride = maxRequest;
386
+ }
387
+ recordCommittedTxSample(nowMs = Date.now()) {
388
+ const sec = Math.floor(nowMs / 1e3);
389
+ const slot = (sec % 60 + 60) % 60;
390
+ if (this.txBucketsSec[slot] !== sec) {
391
+ this.txBucketsSec[slot] = sec;
392
+ this.txBucketCounts[slot] = 1;
393
+ } else this.txBucketCounts[slot] += 1;
394
+ }
395
+ getPipelineTelemetry(nowMs = Date.now()) {
396
+ const nowSec = Math.floor(nowMs / 1e3);
397
+ let sum10 = 0;
398
+ let sum60 = 0;
399
+ for (let i = 0; i < 60; i++) {
400
+ const bucketSec = this.txBucketsSec[i];
401
+ if (bucketSec <= 0) continue;
402
+ const age = nowSec - bucketSec;
403
+ if (age >= 0 && age < 60) {
404
+ sum60 += this.txBucketCounts[i];
405
+ if (age < 10) sum10 += this.txBucketCounts[i];
406
+ }
407
+ }
408
+ return {
409
+ queueDepth: this.queue.length,
410
+ inFlightPreFlights: this.inFlightPreFlights,
411
+ maxTxRequest: this.getMaxTxRequest(),
412
+ concurrency: this.queue.concurrency,
413
+ acceptedTotal: this.txAcceptedTotal,
414
+ persistedFailedTotal: this.txPersistedFailedTotal,
415
+ preFlightRejectedTotal: this.txPreFlightRejectedTotal,
416
+ forwardedTotal: this.txForwardedTotal,
417
+ tps10s: Number((sum10 / 10).toFixed(2)),
418
+ tps60s: Number((sum60 / 60).toFixed(2))
419
+ };
420
+ }
421
+ async assertNotBlockedAtAdmission(context) {
422
+ const hasBlockedCheck = typeof this.admissionBlockedCheck === "function";
423
+ const hasReservedCheck = typeof this.admissionReservedSymbolCheck === "function";
424
+ if (!hasBlockedCheck && !hasReservedCheck) return;
425
+ const txObj = context.tx && typeof context.tx === "object" ? context.tx : {};
426
+ const itxObj = context.itxJson && typeof context.itxJson === "object" ? context.itxJson : context.itx && typeof context.itx === "object" ? context.itx : {};
427
+ const txType = String(context.txType || txObj.itx?.type || "");
428
+ if (hasReservedCheck) {
429
+ if (txType === "fg:t:create_token_factory" || txType === "CreateTokenFactoryTx" || txType === "fg:t:create_token" || txType === "CreateTokenTx") {
430
+ const tokenNested = itxObj.token && typeof itxObj.token === "object" ? itxObj.token : null;
431
+ const normalizedSym = (typeof tokenNested?.symbol === "string" ? tokenNested.symbol : typeof itxObj.symbol === "string" ? itxObj.symbol : "").trim().toUpperCase();
432
+ if (normalizedSym && await Promise.resolve(this.admissionReservedSymbolCheck(normalizedSym))) {
433
+ const symErr = new CustomError("INVALID_SYMBOL", `Token symbol "${normalizedSym}" is reserved by node admission policy`);
434
+ symErr._strikeRecorded = true;
435
+ throw symErr;
436
+ }
437
+ }
438
+ }
439
+ if (!hasBlockedCheck) return;
440
+ const sigs = Array.isArray(txObj.signaturesList) ? txObj.signaturesList : Array.isArray(txObj.signatures) ? txObj.signatures : [];
441
+ const inputs = Array.isArray(itxObj.inputs) ? itxObj.inputs : Array.isArray(itxObj.inputsList) ? itxObj.inputsList : [];
442
+ const outputs = Array.isArray(itxObj.outputs) ? itxObj.outputs : Array.isArray(itxObj.outputsList) ? itxObj.outputsList : [];
443
+ const trustedIssuers = Array.isArray(itxObj.trustedIssuers) ? itxObj.trustedIssuers : Array.isArray(itxObj.trustedIssuersList) ? itxObj.trustedIssuersList : [];
444
+ const issuerField = itxObj.issuer;
445
+ const issuerCandidates = typeof issuerField === "string" ? [issuerField] : issuerField && typeof issuerField === "object" ? [issuerField.id, issuerField.address] : [];
446
+ const candidateActors = /* @__PURE__ */ new Set();
447
+ const addCandidate = (raw) => {
448
+ if (typeof raw === "string") {
449
+ const trimmed = raw.trim();
450
+ if (trimmed) candidateActors.add(trimmed);
451
+ }
452
+ };
453
+ const isRevokeDelegate = txType === "fg:t:revoke_delegate" || txType === "RevokeDelegateTx";
454
+ for (const candidate of [
455
+ txObj.from,
456
+ txObj.delegator,
457
+ ...isRevokeDelegate ? [] : [itxObj.to],
458
+ itxObj.receiver,
459
+ itxObj.owner,
460
+ itxObj.delegatee,
461
+ ...txType === "fg:t:account_migrate" || txType === "AccountMigrateTx" ? [itxObj.address] : [],
462
+ ...issuerCandidates,
463
+ ...trustedIssuers,
464
+ ...sigs.flatMap((s) => [s?.signer, s?.delegator]),
465
+ ...inputs.flatMap((inp) => [inp?.owner, inp?.address]),
466
+ ...outputs.flatMap((out) => [out?.owner, out?.address])
467
+ ]) addCandidate(candidate);
468
+ if (this.statedb) {
469
+ if (txType === "fg:t:claim_stake" || txType === "ClaimStakeTx") {
470
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
471
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
472
+ const evidenceHash = itxObj.evidence && typeof itxObj.evidence === "object" ? itxObj.evidence.hash : void 0;
473
+ if (typeof evidenceHash === "string" && evidenceHash.trim() && typeof this.statedb.tx?.get === "function") {
474
+ const evTxState = await this.statedb.tx.get(evidenceHash.trim()).catch(() => null);
475
+ const evItx = evTxState?.tx?.itxJson && typeof evTxState.tx.itxJson === "object" ? evTxState.tx.itxJson : (evTxState?.tx)?.itx && typeof (evTxState?.tx).itx === "object" ? (evTxState?.tx).itx : {};
476
+ const evOutputs = Array.isArray(evItx.outputs) ? evItx.outputs : Array.isArray(evItx.outputsList) ? evItx.outputsList : [];
477
+ for (const out of evOutputs) {
478
+ addCandidate(out?.owner);
479
+ addCandidate(out?.address);
480
+ }
481
+ }
482
+ } else if (txType === "fg:t:revoke_stake" || txType === "RevokeStakeTx") {
483
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
484
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
485
+ }
486
+ const isAcquireAsset = txType === "fg:t:acquire_asset_v2" || txType === "AcquireAssetV2Tx" || txType === "fg:t:acquire_asset_v3" || txType === "AcquireAssetV3Tx";
487
+ if (isAcquireAsset || txType === "fg:t:mint_asset" || txType === "MintAssetTx") {
488
+ const factoryAddr = typeof itxObj.factory === "string" ? itxObj.factory.trim() : "";
489
+ if (factoryAddr && typeof this.statedb.factory?.get === "function") {
490
+ const factoryState = await this.statedb.factory.get(factoryAddr).catch(() => null);
491
+ addCandidate(factoryState?.owner);
492
+ if (Array.isArray(factoryState?.trustedIssuers)) for (const ti of factoryState.trustedIssuers) addCandidate(ti);
493
+ if (isAcquireAsset && factoryState?.settlement === "instant" && Array.isArray(factoryState?.hooks)) {
494
+ for (const hook of factoryState.hooks) if (hook?.name === "mint" && hook?.type === "contract" && Array.isArray(hook?.compiled)) for (const cmd of hook.compiled) addCandidate(cmd?.args?.to);
495
+ }
496
+ }
497
+ }
498
+ if (txType === "fg:t:update_asset" || txType === "UpdateAssetTx" || txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") {
499
+ const assetAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
500
+ if (assetAddr && typeof this.statedb.asset?.get === "function") {
501
+ const assetState = await this.statedb.asset.get(assetAddr).catch(() => null);
502
+ addCandidate(assetState?.issuer);
503
+ if (txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") addCandidate(assetState?.owner);
504
+ }
505
+ }
506
+ }
507
+ const findBlockedInLineage = async (seedActor) => {
508
+ const visited = /* @__PURE__ */ new Set();
509
+ const queue = [seedActor];
510
+ const MAX_LINEAGE_EXPAND = 32;
511
+ while (queue.length > 0 && visited.size < MAX_LINEAGE_EXPAND) {
512
+ const rawCurr = queue.shift();
513
+ if (!rawCurr) continue;
514
+ const bareCurr = toAddress(rawCurr).trim();
515
+ const keyCurr = bareCurr || rawCurr;
516
+ if (visited.has(keyCurr)) continue;
517
+ visited.add(keyCurr);
518
+ if (await Promise.resolve(this.admissionBlockedCheck(rawCurr))) return rawCurr;
519
+ if (bareCurr && bareCurr !== rawCurr && await Promise.resolve(this.admissionBlockedCheck(bareCurr))) return bareCurr;
520
+ if (isValid(keyCurr) && typeof this.statedb?.account?.get === "function") {
521
+ const accState = await this.statedb.account.get(keyCurr, { traceMigration: false }).catch(() => null);
522
+ if (accState) {
523
+ if (typeof accState.address === "string" && accState.address.trim()) {
524
+ const nextKey = toAddress(accState.address.trim()).trim();
525
+ if (nextKey && !visited.has(nextKey)) queue.push(nextKey);
526
+ }
527
+ if (Array.isArray(accState.migratedFrom)) {
528
+ for (const prev of accState.migratedFrom) if (typeof prev === "string" && prev.trim()) {
529
+ const prevKey = toAddress(prev.trim()).trim();
530
+ if (prevKey && !visited.has(prevKey)) queue.push(prevKey);
531
+ }
532
+ }
533
+ if (Array.isArray(accState.migratedTo)) {
534
+ for (const nextAddr of accState.migratedTo) if (typeof nextAddr === "string" && nextAddr.trim()) {
535
+ const toKey = toAddress(nextAddr.trim()).trim();
536
+ if (toKey && !visited.has(toKey)) queue.push(toKey);
537
+ }
538
+ }
539
+ }
540
+ }
541
+ }
542
+ return null;
543
+ };
544
+ for (const actor of candidateActors) {
545
+ const blockedMatch = await findBlockedInLineage(actor);
546
+ if (blockedMatch) {
547
+ const blockErr = new CustomError("FORBIDDEN", `Account ${blockedMatch} is blocked by node admission policy`);
548
+ blockErr._strikeRecorded = true;
549
+ throw blockErr;
550
+ }
551
+ }
552
+ const extraObj = context.extra && typeof context.extra === "object" ? context.extra : {};
553
+ const rawTxExtra = extraObj.txExtra && typeof extraObj.txExtra === "object" ? extraObj.txExtra : void 0;
554
+ for (const candidateHeaders of [extraObj.gasStakeHeaders, rawTxExtra?.gasStakeHeaders]) {
555
+ const gasHeaders = candidateHeaders;
556
+ if (typeof gasHeaders?.token === "string" && gasHeaders.token.includes(".")) try {
557
+ const parts = gasHeaders.token.split(".");
558
+ if (parts.length === 3 && parts[1].length <= 16384) {
559
+ const payloadJson = Buffer.from(parts[1], "base64url").toString("utf8");
560
+ const decoded = JSON.parse(payloadJson);
561
+ if (typeof decoded?.iss === "string" && decoded.iss.trim()) {
562
+ const blockedSponsor = await findBlockedInLineage(decoded.iss.trim());
563
+ if (blockedSponsor) {
564
+ const sponsorErr = new CustomError("FORBIDDEN", `Gas sponsor ${blockedSponsor} is blocked by node admission policy`);
565
+ sponsorErr._unauthenticatedExtraFailure = true;
566
+ sponsorErr._strikeRecorded = true;
567
+ throw sponsorErr;
568
+ }
569
+ }
570
+ }
571
+ } catch (err) {
572
+ if (err?.code === "FORBIDDEN") throw err;
573
+ }
574
+ }
575
+ for (const candidatePass of [extraObj.gasPass, rawTxExtra?.gasPass]) {
576
+ const gasPass = candidatePass;
577
+ if (typeof gasPass?.stakeId === "string" && gasPass.stakeId.trim() && typeof this.statedb?.stake?.get === "function") {
578
+ const stakeState = await this.statedb.stake.get(gasPass.stakeId.trim()).catch(() => null);
579
+ for (const passActor of [stakeState?.sender, stakeState?.owner]) if (typeof passActor === "string" && passActor.trim()) {
580
+ const blockedPassActor = await findBlockedInLineage(passActor.trim());
581
+ if (blockedPassActor) {
582
+ const passErr = new CustomError("FORBIDDEN", `Gas pass sponsor ${blockedPassActor} is blocked by node admission policy`);
583
+ passErr._unauthenticatedExtraFailure = true;
584
+ passErr._strikeRecorded = true;
585
+ throw passErr;
586
+ }
587
+ }
588
+ }
589
+ }
590
+ }
591
+ async getFollowerStatus() {
592
+ if (this.nodeRuntime && typeof this.nodeRuntime.getFollowerStatus === "function") return this.nodeRuntime.getFollowerStatus();
593
+ return null;
594
+ }
595
+ async signForwardedSendTxReceipt(txHash) {
596
+ if (this.readonly || this.nodeRuntime && this.nodeRuntime.role !== "validator") return null;
597
+ const normalizedTxHash = txHash ? txHash.replace(/^0x/i, "").toUpperCase() : "";
598
+ const localEntry = txHash && typeof this.ledger?.get === "function" ? await this.ledger.get(txHash) || (normalizedTxHash && normalizedTxHash !== txHash ? await this.ledger.get(normalizedTxHash) : null) : null;
599
+ if (typeof this.nodeRuntime?.shouldHandleWriteLocally === "function" && !this.nodeRuntime.shouldHandleWriteLocally() && !localEntry) return null;
600
+ const proposer = this.ledger?.getProposer?.() || null;
601
+ if (!proposer || typeof this.ledger?.signConsensusDigest !== "function") return null;
602
+ const digest = computeForwardReceiptDigest({
603
+ chainId: this.config?.chainId || this.ledger.chainId,
604
+ txHash,
605
+ proposer
606
+ });
607
+ const signature = await this.ledger.signConsensusDigest(digest);
608
+ if (!signature) return null;
609
+ let commitProof;
610
+ if (localEntry && typeof this.ledger?.getCheckpointForSequence === "function" && typeof this.ledger?.getMerkleProof === "function") {
611
+ const [checkpoint, merkleProof] = await Promise.all([this.ledger.getCheckpointForSequence(localEntry.sequence).catch(() => null), this.ledger.getMerkleProof(localEntry.sequence).catch(() => null)]);
612
+ if (checkpoint?.qc && merkleProof) commitProof = Buffer.from(JSON.stringify({
613
+ sequence: localEntry.sequence,
614
+ entryHash: localEntry.entryHash,
615
+ stateCommitHash: localEntry.stateCommitHash ?? "",
616
+ proof: merkleProof,
617
+ checkpoint
618
+ }), "utf8").toString("base64");
619
+ }
620
+ return {
621
+ proposer,
622
+ signature,
623
+ ...commitProof ? { commitProof } : {}
624
+ };
625
+ }
626
+ trackIndexWrite(promise) {
627
+ const settled = promise.then(() => void 0, () => void 0);
628
+ this.pendingIndexWrites.add(settled);
629
+ settled.finally(() => {
630
+ this.pendingIndexWrites.delete(settled);
631
+ });
632
+ }
633
+ async flushIndexWrites() {
634
+ while (this.pendingIndexWrites.size > 0) await Promise.allSettled([...this.pendingIndexWrites]);
635
+ }
297
636
  sendTx({ tx: txBase64, extra }, ctx = {}) {
298
637
  debug("sendTx", {
299
638
  txBase64,
300
639
  request: ctx.request
301
640
  });
302
- if (process.env.CHAIN_MODE === "readonly") throw new CustomError("FORBIDDEN", "This chain node is running in readonly mode");
303
- const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
304
- if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new CustomError("FORBIDDEN", "Chain is busy");
641
+ if (this.isShuttingDown) throw new CustomError("SERVICE_UNAVAILABLE", "Resolver is shutting down");
642
+ const runtime = this.nodeRuntime;
643
+ if (runtime?.isHalted?.()) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
644
+ if (runtime ? runtime.role !== "validator" : (() => {
645
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
646
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
647
+ return normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
648
+ })()) {
649
+ if ((runtime ? runtime.writePolicy : getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject") !== "forward" || typeof runtime?.forwardSendTx !== "function") throw new CustomError("FORBIDDEN", "This chain node is running in readonly mode (FOLLOWER_READ_ONLY)");
650
+ assertRawWireEnvelope(txBase64, this.config);
651
+ if (ctx.forwardedHop !== void 0) throw new CustomError("FORWARD_LOOP_DETECTED", "Refusing to forward sendTx: request already carries X-Ocap-Forwarded-Hop header");
652
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
653
+ return (async () => {
654
+ await this.initialize();
655
+ if (runtime?.isHalted?.()) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
656
+ const forwardContext = {
657
+ txBase64,
658
+ statedb: this.statedb,
659
+ indexdb: this.indexdb,
660
+ ledger: this.ledger,
661
+ config: this.config,
662
+ filter: this.filter,
663
+ logger: this.logger,
664
+ extra: {
665
+ ...ctx,
666
+ txTime: pinnedTxTime$1,
667
+ txExtra: extra
668
+ }
669
+ };
670
+ await inspectTransactionPreFlight(forwardContext);
671
+ await assertStatelessTxRules(forwardContext);
672
+ await this.assertNotBlockedAtAdmission(forwardContext);
673
+ const forwarded = await runtime.forwardSendTx({
674
+ tx: txBase64,
675
+ extra
676
+ }, ctx);
677
+ this.txForwardedTotal += 1;
678
+ if (forwarded?.hash && forwarded?.warning !== void 0) setTxSecurityWarningForHash(forwarded.hash, forwarded.warning, this.statedb);
679
+ return forwarded.hash;
680
+ })();
681
+ }
682
+ if (runtime?.role === "validator" && typeof runtime.shouldHandleWriteLocally === "function" && !runtime.shouldHandleWriteLocally()) {
683
+ if (ctx.forwardedHop !== void 0) throw new CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader for forwarded sendTx");
684
+ if (runtime.writePolicy !== "forward" || typeof runtime.forwardSendTx !== "function") throw new CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader");
685
+ assertRawWireEnvelope(txBase64, this.config);
686
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
687
+ return (async () => {
688
+ await this.initialize();
689
+ if (runtime.isHalted()) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
690
+ const forwardContext = {
691
+ txBase64,
692
+ statedb: this.statedb,
693
+ indexdb: this.indexdb,
694
+ ledger: this.ledger,
695
+ config: this.config,
696
+ filter: this.filter,
697
+ logger: this.logger,
698
+ extra: {
699
+ ...ctx,
700
+ txTime: pinnedTxTime$1,
701
+ txExtra: extra
702
+ }
703
+ };
704
+ await inspectTransactionPreFlight(forwardContext);
705
+ await assertStatelessTxRules(forwardContext);
706
+ await this.assertNotBlockedAtAdmission(forwardContext);
707
+ const forwarded = await runtime.forwardSendTx({
708
+ tx: txBase64,
709
+ extra
710
+ }, ctx);
711
+ this.txForwardedTotal += 1;
712
+ if (forwarded?.hash && forwarded?.warning !== void 0) setTxSecurityWarningForHash(forwarded.hash, forwarded.warning, this.statedb);
713
+ return forwarded.hash;
714
+ })();
715
+ }
716
+ const maxRequest = this.getMaxTxRequest();
717
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) {
718
+ this.txPreFlightRejectedTotal += 1;
719
+ throw new CustomError("FORBIDDEN", "Chain is busy");
720
+ }
305
721
  assertRawWireEnvelope(txBase64, this.config);
306
722
  const timer = new TxTimer();
307
723
  timer.setQueueState({
308
724
  waitingAtEnqueue: Math.max(0, this.queue.length - (this.queue.pending ?? 0)),
309
725
  runningAtEnqueue: this.queue.pending ?? 0,
310
- concurrencyConfig: txRequestConfig.concurrent
726
+ concurrencyConfig: this.queue.concurrency ?? txRequestConfig.concurrent
311
727
  });
728
+ const pinnedTxTime = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
312
729
  const context = {
313
730
  txBase64,
314
731
  statedb: this.statedb,
@@ -318,8 +735,10 @@ var OCAPResolver = class {
318
735
  filter: this.filter,
319
736
  logger: this.logger,
320
737
  timer,
738
+ ...runtime?.getConsensusCommitter ? { consensusCommitter: runtime.getConsensusCommitter() } : {},
321
739
  extra: {
322
740
  ...ctx,
741
+ txTime: pinnedTxTime,
323
742
  txExtra: extra
324
743
  }
325
744
  };
@@ -330,13 +749,18 @@ var OCAPResolver = class {
330
749
  if (!preFlightSlotReleased) {
331
750
  preFlightSlotReleased = true;
332
751
  this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
752
+ if (this.inFlightPreFlights === 0 && this.preFlightDrainWaiters.length > 0) {
753
+ const waiters = this.preFlightDrainWaiters.splice(0, this.preFlightDrainWaiters.length);
754
+ for (const notify of waiters) notify();
755
+ }
333
756
  }
334
757
  };
335
758
  const enqueueAfterPreFlight = async () => {
336
759
  try {
337
- await this.initializationPromise;
760
+ await this.initialize();
338
761
  await inspectTransactionPreFlight(context);
339
762
  await assertStatelessTxRules(context);
763
+ await this.assertNotBlockedAtAdmission(context);
340
764
  const preTx = context.tx;
341
765
  const preTxHash = context.txHash;
342
766
  if (preTx) await assertTxAdmission({
@@ -370,27 +794,54 @@ var OCAPResolver = class {
370
794
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
371
795
  }
372
796
  releasePreFlightSlot();
797
+ this.txPreFlightRejectedTotal += 1;
373
798
  reject(preFlightErr);
374
799
  return;
375
800
  }
376
- releasePreFlightSlot();
377
- const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
801
+ const currentMaxRequest = this.getMaxTxRequest();
378
802
  if (this.queue.length >= currentMaxRequest) {
803
+ releasePreFlightSlot();
804
+ this.txPreFlightRejectedTotal += 1;
379
805
  reject(new CustomError("FORBIDDEN", "Chain is busy"));
380
806
  return;
381
807
  }
382
808
  const task = async () => {
383
809
  timer.mark("queueWait");
384
810
  try {
385
- const result = await this.executor.execute(context);
811
+ const activeRuntime = this.nodeRuntime;
812
+ if (activeRuntime?.getConsensusCommitter && !("consensusCommitter" in context)) context.consensusCommitter = activeRuntime.getConsensusCommitter();
813
+ const result = typeof activeRuntime?.executeWithConsensusLock === "function" ? await activeRuntime.executeWithConsensusLock(() => this.executor.execute(context)) : await this.executor.execute(context);
386
814
  if (result?.txHash && result?.securityWarning) setTxSecurityWarningForHash(result.txHash, result.securityWarning, this.statedb);
815
+ this.txAcceptedTotal += 1;
816
+ this.recordCommittedTxSample();
387
817
  resolve(result.txHash);
388
818
  } catch (err) {
819
+ if (err?.isConsensusAbort === true) {
820
+ const activeRuntime = this.nodeRuntime;
821
+ if (ctx.forwardedHop === void 0 && activeRuntime?.writePolicy === "forward" && typeof activeRuntime.forwardSendTx === "function") try {
822
+ const forwarded = await activeRuntime.forwardSendTx({
823
+ tx: txBase64,
824
+ extra
825
+ }, ctx);
826
+ if (forwarded?.hash && forwarded?.warning !== void 0) setTxSecurityWarningForHash(forwarded.hash, forwarded.warning, this.statedb);
827
+ this.txForwardedTotal += 1;
828
+ resolve(forwarded.hash);
829
+ return;
830
+ } catch (forwardErr) {
831
+ reject(forwardErr);
832
+ return;
833
+ }
834
+ reject(err);
835
+ return;
836
+ }
837
+ if (Number(context.ledgerSequence ?? 0) > 0) this.txPersistedFailedTotal += 1;
838
+ else this.txPreFlightRejectedTotal += 1;
389
839
  await this._indexRejectedLedgerTx(context, err);
390
840
  reject(err);
391
841
  }
392
842
  };
393
843
  this.queue.push(task);
844
+ releasePreFlightSlot();
394
845
  };
395
846
  enqueueAfterPreFlight().catch((err) => {
396
847
  releasePreFlightSlot();
@@ -497,6 +948,7 @@ var OCAPResolver = class {
497
948
  return getTxSecurityWarningByHash(txHash, this.statedb);
498
949
  }
499
950
  async getTx({ hash }, ctx) {
951
+ assertResolverNotHaltedForDataRead(this);
500
952
  if (patterns.txHash.test(hash)) {
501
953
  const normalizedHash = hash.toUpperCase();
502
954
  const stateTx = await this._getState({
@@ -516,18 +968,60 @@ var OCAPResolver = class {
516
968
  return null;
517
969
  }
518
970
  getBlock() {
971
+ assertResolverNotHaltedForDataRead(this);
519
972
  return null;
520
973
  }
521
974
  getBlocks() {
975
+ assertResolverNotHaltedForDataRead(this);
522
976
  return [];
523
977
  }
524
978
  getUnconfirmedTxs() {
979
+ assertResolverNotHaltedForDataRead(this);
525
980
  return [];
526
981
  }
982
+ async resolveNodeSyncMetadata() {
983
+ if (this.nodeRuntime) {
984
+ const reconciling = Boolean(this.nodeRuntime.isReconciling?.());
985
+ if (typeof this.nodeRuntime.getFollowerStatus === "function") {
986
+ const status = await this.nodeRuntime.getFollowerStatus();
987
+ return {
988
+ synced: status.synced && !status.halted && !reconciling,
989
+ nodeRole: status.nodeRole,
990
+ writePolicy: status.writePolicy,
991
+ syncLagEntries: status.syncLagEntries,
992
+ verifiedCheckpointHeight: status.verifiedCheckpointHeight,
993
+ halted: status.halted
994
+ };
995
+ }
996
+ const [synced, latestCp$1] = await Promise.all([Promise.resolve(this.nodeRuntime.isSynced()), this.ledger?.getCheckpoint ? this.ledger.getCheckpoint().catch(() => null) : Promise.resolve(null)]);
997
+ const halted = this.nodeRuntime.isHalted();
998
+ return {
999
+ synced: synced && !halted && !reconciling,
1000
+ nodeRole: this.nodeRuntime.role,
1001
+ writePolicy: this.nodeRuntime.writePolicy,
1002
+ syncLagEntries: null,
1003
+ verifiedCheckpointHeight: latestCp$1?.height ?? 0,
1004
+ halted
1005
+ };
1006
+ }
1007
+ const latestCp = this.ledger?.getCheckpoint ? await this.ledger.getCheckpoint().catch(() => null) : null;
1008
+ const rawRole = getNormalizedEnvLower("CHAIN_ROLE");
1009
+ const rawMode = getNormalizedEnvLower("CHAIN_MODE");
1010
+ const nodeRole = rawRole === "follower" || rawRole === "standby" ? rawRole : rawMode === "readonly" ? "follower" : "validator";
1011
+ return {
1012
+ synced: true,
1013
+ nodeRole,
1014
+ writePolicy: getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject",
1015
+ syncLagEntries: nodeRole === "validator" ? 0 : null,
1016
+ verifiedCheckpointHeight: latestCp?.height ?? 0,
1017
+ halted: false
1018
+ };
1019
+ }
527
1020
  async getChainInfo() {
1021
+ const [totalTxs, syncMeta] = await Promise.all([this.indexdb.tx.count(), this.resolveNodeSyncMetadata()]);
528
1022
  return {
529
1023
  id: this.chainAddr,
530
- totalTxs: await this.indexdb.tx.count(),
1024
+ totalTxs,
531
1025
  blockHash: md5(""),
532
1026
  blockHeight: 0,
533
1027
  blockTime: "",
@@ -539,12 +1033,18 @@ var OCAPResolver = class {
539
1033
  moniker: this.config.chainId,
540
1034
  network: this.config.chainId,
541
1035
  supportedTxs: this.config.transaction.supportedTxs,
542
- synced: true,
543
- votingPower: "10"
1036
+ synced: syncMeta.synced,
1037
+ nodeRole: syncMeta.nodeRole,
1038
+ writePolicy: syncMeta.writePolicy,
1039
+ syncLagEntries: syncMeta.syncLagEntries,
1040
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1041
+ halted: syncMeta.halted,
1042
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
544
1043
  };
545
1044
  }
546
- getNodeInfo() {
547
- return Promise.resolve({
1045
+ async getNodeInfo() {
1046
+ const syncMeta = await this.resolveNodeSyncMetadata();
1047
+ return {
548
1048
  address: this.chainAddr,
549
1049
  appHash: md5((/* @__PURE__ */ new Date()).toISOString()),
550
1050
  consensusVersion: this.consensus,
@@ -561,53 +1061,166 @@ var OCAPResolver = class {
561
1061
  network: this.config.chainId,
562
1062
  p2pAddress: "",
563
1063
  supportedTxs: this.config.transaction.supportedTxs,
564
- synced: true,
565
- votingPower: "10"
566
- });
1064
+ synced: syncMeta.synced,
1065
+ nodeRole: syncMeta.nodeRole,
1066
+ writePolicy: syncMeta.writePolicy,
1067
+ syncLagEntries: syncMeta.syncLagEntries,
1068
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1069
+ halted: syncMeta.halted,
1070
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
1071
+ };
567
1072
  }
568
- getNetInfo() {
569
- return Promise.resolve({
1073
+ async getNetInfo() {
1074
+ if (!this.nodeRuntime || typeof this.nodeRuntime.getRuntimeDiagnostics !== "function") return {
570
1075
  listeners: [],
571
1076
  listening: true,
572
1077
  nPeers: 0,
573
1078
  peers: []
574
- });
1079
+ };
1080
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1081
+ const listening = !this.nodeRuntime.isHalted();
1082
+ const defaultGeo = {
1083
+ city: "Unknown",
1084
+ country: "Unknown",
1085
+ latitude: 0,
1086
+ longitude: 0
1087
+ };
1088
+ if (diag.mode === "hotstuff" && Array.isArray(diag.validators)) {
1089
+ const peerValidators = diag.validators.filter((v$1) => !v$1.isSelf && v$1.reachable && typeof v$1.did === "string");
1090
+ return {
1091
+ listeners: [],
1092
+ listening,
1093
+ nPeers: peerValidators.length,
1094
+ peers: peerValidators.map((peer) => ({
1095
+ id: peer.did,
1096
+ moniker: peer.did,
1097
+ network: this.config.chainId,
1098
+ consensusVersion: this.consensus,
1099
+ ip: "",
1100
+ geoInfo: defaultGeo
1101
+ }))
1102
+ };
1103
+ }
1104
+ if (diag.mode === "follower") {
1105
+ const leaderRouter = diag.leaderRouter;
1106
+ const candidates = Array.isArray(leaderRouter?.candidates) ? leaderRouter.candidates : [];
1107
+ const activePeers = candidates.length > 0 ? candidates.filter((c) => c.reachable) : Number(diag.peerCount ?? 0) > 0 && Boolean(diag.hasActiveLeader) ? [{
1108
+ id: "upstream-peer-1",
1109
+ reachable: true
1110
+ }] : [];
1111
+ return {
1112
+ listeners: [],
1113
+ listening,
1114
+ nPeers: activePeers.length,
1115
+ peers: activePeers.map((c, idx) => ({
1116
+ id: c.id || `upstream-peer-${idx + 1}`,
1117
+ moniker: c.id || `upstream-peer-${idx + 1}`,
1118
+ network: this.config.chainId,
1119
+ consensusVersion: this.consensus,
1120
+ ip: "",
1121
+ geoInfo: defaultGeo
1122
+ }))
1123
+ };
1124
+ }
1125
+ return {
1126
+ listeners: [],
1127
+ listening,
1128
+ nPeers: 0,
1129
+ peers: []
1130
+ };
575
1131
  }
576
- getValidatorsInfo() {
577
- return Promise.resolve({
1132
+ async getValidatorsInfo() {
1133
+ assertResolverNotHaltedForDataRead(this);
1134
+ const formatPubKey = (rawPk) => {
1135
+ const cleanPkHex = rawPk ? rawPk.replace(/^0x/i, "") : "";
1136
+ if (!cleanPkHex || !/^[0-9a-fA-F]+$/.test(cleanPkHex)) return;
1137
+ return {
1138
+ type: cleanPkHex.length === 64 ? "ed25519" : "secp256k1",
1139
+ data: cleanPkHex
1140
+ };
1141
+ };
1142
+ if (this.nodeRuntime && this.nodeRuntime.getConsensusMode?.() === "hotstuff" && typeof this.nodeRuntime.getRuntimeDiagnostics === "function") {
1143
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1144
+ if (Array.isArray(diag.validators) && diag.validators.length > 0) {
1145
+ const leaderDid = typeof diag.currentLeaderDid === "string" ? diag.currentLeaderDid : "";
1146
+ return {
1147
+ blockHeight: 0,
1148
+ validators: diag.validators.map((v$1) => {
1149
+ const pk$1 = formatPubKey(v$1.publicKey);
1150
+ return {
1151
+ address: v$1.did,
1152
+ ...pk$1 ? { pubKey: pk$1 } : {},
1153
+ name: "",
1154
+ proposerPriority: v$1.isCurrentViewLeader || v$1.did === leaderDid ? "1" : "0",
1155
+ votingPower: "10"
1156
+ };
1157
+ })
1158
+ };
1159
+ }
1160
+ }
1161
+ const activeProposer = this.ledger?.getProposer?.() || this.config?.moderator?.address || fromPublicKey(this.chainAddr);
1162
+ const pk = formatPubKey(this.ledger?.getProposerPublicKey?.());
1163
+ return {
578
1164
  blockHeight: 0,
579
1165
  validators: [{
580
- address: this.config?.moderator?.address || fromPublicKey(this.chainAddr),
1166
+ address: activeProposer,
1167
+ ...pk ? { pubKey: pk } : {},
581
1168
  name: "",
582
1169
  proposerPriority: "0",
583
1170
  votingPower: "10"
584
1171
  }]
585
- });
1172
+ };
1173
+ }
1174
+ async getLedgerInfo() {
1175
+ assertResolverNotHaltedForDataRead(this);
1176
+ if (!this.ledger) return null;
1177
+ const latestSequence = await this.ledger.getLatestSequence();
1178
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1179
+ const entryHashV2From = rawV2From === void 0 ? null : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
1180
+ const proposer = this.ledger.getProposer?.() || this.config?.moderator?.address || null;
1181
+ const proposerPublicKey = this.ledger.getProposerPublicKey?.() || null;
1182
+ const checkpointSigningEnabled = typeof this.ledger.isCheckpointSigningEnabled === "function" ? this.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
1183
+ return {
1184
+ chainId: this.config?.chainId || this.ledger.chainId,
1185
+ latestSequence,
1186
+ entryHashV2From,
1187
+ proposer,
1188
+ proposerPublicKey,
1189
+ checkpointSigningEnabled
1190
+ };
586
1191
  }
587
1192
  async getLatestCheckpoint({ height } = {}) {
1193
+ assertResolverNotHaltedForDataRead(this);
588
1194
  if (!this.ledger) return null;
589
1195
  const targetHeight = height !== void 0 && height !== null ? Number(height) : void 0;
590
1196
  return this.ledger.getCheckpoint(targetHeight);
591
1197
  }
592
1198
  async getLedgerEntry({ hash, sequence } = {}) {
1199
+ assertResolverNotHaltedForDataRead(this);
593
1200
  if (!this.ledger) return null;
594
1201
  if (sequence !== void 0 && sequence !== null) return this.ledger.getBySequence(Number(sequence));
595
1202
  if (hash) return this.ledger.get(String(hash));
596
1203
  return null;
597
1204
  }
598
1205
  async getMerkleProof({ sequence }) {
1206
+ assertResolverNotHaltedForDataRead(this);
599
1207
  if (!this.ledger || sequence === void 0 || sequence === null) return null;
600
1208
  const seq = Number(sequence);
601
1209
  const [proof, checkpoint] = await Promise.all([this.ledger.getMerkleProof(seq), this.ledger.getCheckpointForSequence(seq)]);
1210
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1211
+ const entryHashV2From = rawV2From === void 0 ? void 0 : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
602
1212
  return {
603
1213
  proof,
604
- checkpoint
1214
+ checkpoint,
1215
+ ...entryHashV2From !== void 0 ? { entryHashV2From } : {}
605
1216
  };
606
1217
  }
607
1218
  getConfig() {
1219
+ assertResolverNotHaltedForDataRead(this);
608
1220
  return JSON.stringify(this.config);
609
1221
  }
610
1222
  getAccountState({ address, traceMigration = true, expandContext = true }, ctx) {
1223
+ assertResolverNotHaltedForDataRead(this);
611
1224
  return this._getState({
612
1225
  table: "account",
613
1226
  id: address,
@@ -624,6 +1237,7 @@ var OCAPResolver = class {
624
1237
  });
625
1238
  }
626
1239
  getStakeState({ address }, ctx) {
1240
+ assertResolverNotHaltedForDataRead(this);
627
1241
  return this._getState({
628
1242
  table: "stake",
629
1243
  id: address,
@@ -639,6 +1253,7 @@ var OCAPResolver = class {
639
1253
  });
640
1254
  }
641
1255
  async getRollupState({ address }, ctx) {
1256
+ assertResolverNotHaltedForDataRead(this);
642
1257
  const rollup = await this._getState({
643
1258
  table: "rollup",
644
1259
  id: address,
@@ -661,6 +1276,7 @@ var OCAPResolver = class {
661
1276
  return rollup;
662
1277
  }
663
1278
  async getRollupBlock({ hash, height, rollupAddress }, ctx) {
1279
+ assertResolverNotHaltedForDataRead(this);
664
1280
  if (hash) return this._getState({
665
1281
  table: "rollupBlock",
666
1282
  id: hash,
@@ -684,6 +1300,7 @@ var OCAPResolver = class {
684
1300
  throw new Error("Can not get rollup block without hash or height + rollup");
685
1301
  }
686
1302
  getAssetState({ address }, ctx) {
1303
+ assertResolverNotHaltedForDataRead(this);
687
1304
  return this._getState({
688
1305
  table: "asset",
689
1306
  id: address,
@@ -696,6 +1313,7 @@ var OCAPResolver = class {
696
1313
  });
697
1314
  }
698
1315
  getEvidenceState({ hash }, ctx) {
1316
+ assertResolverNotHaltedForDataRead(this);
699
1317
  return this._getState({
700
1318
  table: "evidence",
701
1319
  id: hash,
@@ -704,6 +1322,7 @@ var OCAPResolver = class {
704
1322
  });
705
1323
  }
706
1324
  getFactoryState({ address }, ctx) {
1325
+ assertResolverNotHaltedForDataRead(this);
707
1326
  return this._getState({
708
1327
  table: "factory",
709
1328
  id: address,
@@ -722,6 +1341,7 @@ var OCAPResolver = class {
722
1341
  });
723
1342
  }
724
1343
  async getTokenState({ address }, ctx) {
1344
+ assertResolverNotHaltedForDataRead(this);
725
1345
  const state = await this._getState({
726
1346
  table: "token",
727
1347
  id: address,
@@ -735,6 +1355,7 @@ var OCAPResolver = class {
735
1355
  return state;
736
1356
  }
737
1357
  getTokenFactoryState(args, ctx) {
1358
+ assertResolverNotHaltedForDataRead(this);
738
1359
  return this._getState({
739
1360
  table: "tokenFactory",
740
1361
  id: args.address,
@@ -757,6 +1378,7 @@ var OCAPResolver = class {
757
1378
  });
758
1379
  }
759
1380
  getDelegateState({ address }, ctx) {
1381
+ assertResolverNotHaltedForDataRead(this);
760
1382
  return this._getState({
761
1383
  table: "delegation",
762
1384
  id: address,
@@ -772,6 +1394,7 @@ var OCAPResolver = class {
772
1394
  });
773
1395
  }
774
1396
  async getAccountTokens({ address, token }, ctx) {
1397
+ assertResolverNotHaltedForDataRead(this);
775
1398
  if (!address) return [];
776
1399
  let state = null;
777
1400
  if (toTypeInfo(address).role === types.RoleType.ROLE_ASSET) state = await this._getState({
@@ -813,6 +1436,7 @@ var OCAPResolver = class {
813
1436
  }));
814
1437
  }
815
1438
  getForgeState() {
1439
+ assertResolverNotHaltedForDataRead(this);
816
1440
  const { accounts, token, transaction, vaults } = this.config;
817
1441
  return Promise.resolve({
818
1442
  accountConfig: accounts,
@@ -851,6 +1475,7 @@ var OCAPResolver = class {
851
1475
  });
852
1476
  }
853
1477
  async getForgeStats() {
1478
+ assertResolverNotHaltedForDataRead(this);
854
1479
  const [accountCount, assetCount, txCount] = await Promise.all([
855
1480
  this.indexdb.account.count(),
856
1481
  this.indexdb.asset.count(),
@@ -880,19 +1505,23 @@ var OCAPResolver = class {
880
1505
  };
881
1506
  }
882
1507
  async listTransactions(args = {}, ctx) {
883
- return await this._doPaginatedSearch("listTransactions", args, "transactions", "tx.itxJson.data", ctx);
1508
+ assertResolverNotHaltedForDataRead(this);
1509
+ return await this._doPaginatedSearch("listTransactions", withTxProjection(args, ctx), "transactions", "tx.itxJson.data", ctx);
884
1510
  }
885
1511
  listAssets(args = {}, ctx) {
1512
+ assertResolverNotHaltedForDataRead(this);
886
1513
  return this._doPaginatedSearch("listAssets", args, "assets", "data", ctx);
887
1514
  }
888
1515
  listAssetTransactions(args = {}, ctx = {}) {
1516
+ assertResolverNotHaltedForDataRead(this);
889
1517
  if (!args.address) return Promise.resolve({ transactions: [] });
890
- return this._doPaginatedSearch("listTransactions", {
1518
+ return this._doPaginatedSearch("listTransactions", withTxProjection({
891
1519
  ...args,
892
1520
  assetFilter: { assets: [args.address] }
893
- }, "transactions", "tx.itxJson.data", ctx);
1521
+ }, ctx), "transactions", "tx.itxJson.data", ctx);
894
1522
  }
895
1523
  async listFactories(args = {}, ctx) {
1524
+ assertResolverNotHaltedForDataRead(this);
896
1525
  const result = await this._doPaginatedSearch("listFactories", args, "factories", "data", ctx);
897
1526
  result.factories = result.factories.map((x) => {
898
1527
  const output = x.output;
@@ -902,24 +1531,31 @@ var OCAPResolver = class {
902
1531
  return result;
903
1532
  }
904
1533
  listTopAccounts(args = {}) {
1534
+ assertResolverNotHaltedForDataRead(this);
905
1535
  return this._doPaginatedSearch("listTopAccounts", args, "accounts");
906
1536
  }
907
1537
  listTokens(args = {}, ctx) {
1538
+ assertResolverNotHaltedForDataRead(this);
908
1539
  return this._doPaginatedSearch("listTokens", args, "tokens", ["data", "metadata"], ctx);
909
1540
  }
910
1541
  listTokenFactories(args = {}, ctx) {
1542
+ assertResolverNotHaltedForDataRead(this);
911
1543
  return this._doPaginatedSearch("listTokenFactories", args, "tokenFactories", "data", ctx);
912
1544
  }
913
1545
  listStakes(args = {}, ctx) {
1546
+ assertResolverNotHaltedForDataRead(this);
914
1547
  return this._doPaginatedSearch("listStakes", args, "stakes", "data", ctx);
915
1548
  }
916
1549
  listRollups(args = {}, ctx) {
1550
+ assertResolverNotHaltedForDataRead(this);
917
1551
  return this._doPaginatedSearch("listRollups", args, "rollups", "data", ctx);
918
1552
  }
919
1553
  listRollupBlocks(args = {}, ctx) {
1554
+ assertResolverNotHaltedForDataRead(this);
920
1555
  return this._doPaginatedSearch("listRollupBlocks", args, "blocks", "data", ctx);
921
1556
  }
922
1557
  async listRollupValidators(args = {}, ctx) {
1558
+ assertResolverNotHaltedForDataRead(this);
923
1559
  if (!args.rollupAddress) return { validators: [] };
924
1560
  const rollup = await this.statedb.rollup.get(args.rollupAddress);
925
1561
  if (!rollup) return { validators: [] };
@@ -936,9 +1572,11 @@ var OCAPResolver = class {
936
1572
  return result;
937
1573
  }
938
1574
  listDelegations(args = {}, ctx) {
1575
+ assertResolverNotHaltedForDataRead(this);
939
1576
  return this._doPaginatedSearch("listDelegations", args, "delegations", "data", ctx);
940
1577
  }
941
1578
  verifyAccountRisk(args = {}, ctx) {
1579
+ assertResolverNotHaltedForDataRead(this);
942
1580
  if (process.env.TOKEN_FLOW_ENABLED === "true") return verifyAccountRisk({
943
1581
  ...args,
944
1582
  tokenAddress: toAddress(args.tokenAddress || this.config.token.address),
@@ -950,10 +1588,12 @@ var OCAPResolver = class {
950
1588
  return null;
951
1589
  }
952
1590
  listTokenFlows(args = {}, ctx) {
1591
+ assertResolverNotHaltedForDataRead(this);
953
1592
  if (process.env.TOKEN_FLOW_ENABLED === "true") return listTokenFlows(args, this, ctx);
954
1593
  return [];
955
1594
  }
956
1595
  async search(args) {
1596
+ assertResolverNotHaltedForDataRead(this);
957
1597
  if (!args.keyword) return { results: [] };
958
1598
  const doSearch = async (type, keyword) => {
959
1599
  const result = await this.indexdb[type].get(keyword);
@@ -979,6 +1619,7 @@ var OCAPResolver = class {
979
1619
  return { results: [] };
980
1620
  }
981
1621
  estimateGas(args = {}) {
1622
+ assertResolverNotHaltedForDataRead(this);
982
1623
  const { typeUrl = "" } = args;
983
1624
  if (!typeUrl || !maxGasOps[typeUrl]) throw new CustomError("INVALID_REQUEST", "Unknown tx typeUrl");
984
1625
  const { txGas, maxTxSize } = this.config.transaction;
@@ -988,15 +1629,25 @@ var OCAPResolver = class {
988
1629
  totalGas = totalGas.add(new BN(txGas.price).mul(new BN(txGas.updateState)).mul(new BN(estimate.update)));
989
1630
  return { estimate: { max: totalGas.toString(10) } };
990
1631
  }
991
- async shutdown() {
992
- if (this.queue) {
993
- this.queue.autostart = false;
994
- if (this.queue.length > 0) await new Promise((resolve) => {
995
- this.queue.on("end", resolve);
1632
+ shutdown() {
1633
+ this.isShuttingDown = true;
1634
+ if (!this.shutdownPromise) this.shutdownPromise = (async () => {
1635
+ if (this.inFlightPreFlights > 0) await new Promise((resolve) => {
1636
+ if (this.inFlightPreFlights === 0) resolve();
1637
+ else this.preFlightDrainWaiters.push(resolve);
996
1638
  });
997
- }
1639
+ if (this.queue) {
1640
+ this.queue.autostart = false;
1641
+ if (this.queue.length > 0) await new Promise((resolve) => {
1642
+ this.queue.once("end", () => resolve());
1643
+ });
1644
+ }
1645
+ await this.flushIndexWrites();
1646
+ })();
1647
+ return this.shutdownPromise;
998
1648
  }
999
1649
  listBlocks() {
1650
+ assertResolverNotHaltedForDataRead(this);
1000
1651
  return { blocks: [] };
1001
1652
  }
1002
1653
  validateTokenConfig() {
@@ -1016,17 +1667,91 @@ var OCAPResolver = class {
1016
1667
  async getToken(id) {
1017
1668
  return this.statedb.token.get(id);
1018
1669
  }
1019
- async initializeStateDB() {
1670
+ async initializeStateDB(options = {}) {
1671
+ if (this.skipInitializeStateDB || this.nodeRuntime && this.nodeRuntime.role !== "validator") return;
1020
1672
  const { accounts, token } = this.config;
1021
1673
  const { account: accountDB, chain: chainDB, token: tokenDB } = this.statedb;
1022
1674
  const { account: accountState, chain: chainState, token: tokenState } = states;
1675
+ const rawTime = options.txTime ?? this.config.genesisTime ?? (process.env.CHAIN_GENESIS_TIME || "").trim();
1676
+ const parsedMs = rawTime === void 0 || rawTime === null || rawTime === "" ? NaN : new Date(rawTime).getTime();
1677
+ const isHotStuffBootstrap = this.explicitConsensusMode === "hotstuff" || !this.explicitConsensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(this.nodeRuntime?.getConsensusCommitter?.());
1023
1678
  const context = {
1024
- txTime: (/* @__PURE__ */ new Date()).toISOString(),
1679
+ txTime: Number.isFinite(parsedMs) ? new Date(parsedMs).toISOString() : typeof rawTime === "string" && rawTime.trim() ? rawTime.trim() : isHotStuffBootstrap ? "1970-01-01T00:00:00.000Z" : new Date(typeof this.now === "function" ? this.now() : Date.now()).toISOString(),
1025
1680
  txHash: ""
1026
1681
  };
1027
- await this.runAsLambda(async (txn) => {
1682
+ const config = omit(this.config, ["reservedSymbols"]);
1683
+ const role = String(this.config.role || process.env.CHAIN_ROLE || "").trim().toLowerCase();
1684
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
1685
+ const isReadOnlyMode = options.readonly === true || normalizedMode === "readonly" || role === "follower" || role === "standby";
1686
+ const commitGetter = this.statedb.getCommitHash;
1687
+ const hasCommitTracking = typeof commitGetter === "function";
1688
+ if (isReadOnlyMode) {
1689
+ const existingChain$1 = await this.statedb.chain.get(CHAIN_ADDR);
1690
+ if (!existingChain$1) {
1691
+ if (hasCommitTracking) throw new CustomError("FORBIDDEN", "Read-only/follower StateDB is uninitialized (missing chain state)");
1692
+ return;
1693
+ }
1694
+ if (hasCommitTracking) {
1695
+ const roCommit = await commitGetter.call(this.statedb);
1696
+ const roSeq = Number(roCommit?.seq || 0);
1697
+ if (this.tokenItx) {
1698
+ if (!await this.statedb.token.get(this.tokenItx.address) || roCommit?.msg === "initialize chain") throw new CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing official token state)");
1699
+ if (accounts.length > 0 && roSeq <= 2 && roCommit?.msg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing initial accounts)");
1700
+ }
1701
+ }
1702
+ chainState.update(existingChain$1, {
1703
+ ...config,
1704
+ context
1705
+ });
1706
+ return;
1707
+ }
1708
+ let stateCommitSeq = 0;
1709
+ let stateCommitMsg = "";
1710
+ let stateCommitCurrentHash = "GENESIS";
1711
+ if (hasCommitTracking) {
1712
+ const commitInfo = await commitGetter.call(this.statedb);
1713
+ stateCommitSeq = Number(commitInfo?.seq || 0);
1714
+ stateCommitMsg = String(commitInfo?.msg || "");
1715
+ stateCommitCurrentHash = String(commitInfo?.currentHash || "GENESIS");
1716
+ }
1717
+ const isLedgerAnchoredRestart = hasCommitTracking && (stateCommitSeq > 0 || Boolean(stateCommitCurrentHash) && stateCommitCurrentHash !== "GENESIS");
1718
+ if (isLedgerAnchoredRestart && this.tokenItx) {
1719
+ if (stateCommitMsg === "initialize chain") throw new CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after chain initialization before official token state was committed");
1720
+ if (accounts.length > 0 && stateCommitSeq <= 2 && stateCommitMsg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after official token initialization before initial accounts were committed");
1721
+ }
1722
+ const existingChain = await this.statedb.chain.get(CHAIN_ADDR);
1723
+ const normalizeComparable = (val) => {
1724
+ if (val === void 0 || val === null) return null;
1725
+ if (Array.isArray(val)) return val.map(normalizeComparable);
1726
+ if (typeof val === "object") {
1727
+ const out = {};
1728
+ for (const [k, v$1] of Object.entries(val)) if (v$1 !== void 0) out[k] = normalizeComparable(v$1);
1729
+ return out;
1730
+ }
1731
+ return val;
1732
+ };
1733
+ const persistedChainKeys = [
1734
+ "chainId",
1735
+ "version",
1736
+ "transaction",
1737
+ "moderator",
1738
+ "accounts",
1739
+ "token",
1740
+ "vaults"
1741
+ ];
1742
+ const expectedConfig = normalizeComparable(pick(this.config, persistedChainKeys));
1743
+ const needsChainWrite = !existingChain || isEqual(normalizeComparable(pick(existingChain, persistedChainKeys)), expectedConfig) === false;
1744
+ if (isLedgerAnchoredRestart) {
1745
+ if (!existingChain) throw new CustomError("INTERNAL", "Incomplete genesis StateDB: missing chain state while _state_commit.seq > 0");
1746
+ if (needsChainWrite) {
1747
+ chainState.update(existingChain, {
1748
+ ...config,
1749
+ context
1750
+ });
1751
+ this.logger.info("skipping out-of-band chain state update on ledger-anchored restart to preserve _state_commit parity", { stateCommitSeq });
1752
+ }
1753
+ } else if (needsChainWrite) await this.runAsLambda(async (txn) => {
1028
1754
  const info = await this.statedb.chain.get(CHAIN_ADDR, { txn });
1029
- const config = omit(this.config, ["reservedSymbols"]);
1030
1755
  if (!info) {
1031
1756
  const state = chainState.create({
1032
1757
  ...config,
@@ -1035,7 +1760,7 @@ var OCAPResolver = class {
1035
1760
  });
1036
1761
  const result = await chainDB.create(CHAIN_ADDR, state, { txn });
1037
1762
  this.logger.debug("create chain state", { result });
1038
- } else if (isEqual(pick(info, Object.keys(config)), config) === false) {
1763
+ } else if (isEqual(normalizeComparable(pick(info, persistedChainKeys)), normalizeComparable(pick(config, persistedChainKeys))) === false) {
1039
1764
  const state = chainState.update(info, {
1040
1765
  ...config,
1041
1766
  context
@@ -1045,50 +1770,73 @@ var OCAPResolver = class {
1045
1770
  }
1046
1771
  }, { commitMessage: "initialize chain" });
1047
1772
  if (this.tokenItx) {
1048
- await this.runAsLambda(async (txn) => {
1773
+ const changedKeys = [
1774
+ "icon",
1775
+ "website",
1776
+ "metadata"
1777
+ ];
1778
+ const normalizeTokenMutable = (obj) => ({
1779
+ icon: obj?.icon ? String(obj.icon) : "",
1780
+ website: obj?.website ? String(obj.website) : "",
1781
+ metadata: obj?.metadata === void 0 || obj?.metadata === null ? null : normalizeComparable(obj.metadata)
1782
+ });
1783
+ const expectedTokenShape = tokenState.create(this.tokenItx, context);
1784
+ const preExistToken = await this.statedb.token.get(this.tokenItx.address);
1785
+ const needsTokenWrite = !preExistToken || !isEqual(normalizeTokenMutable(preExistToken), normalizeTokenMutable(expectedTokenShape));
1786
+ if (isLedgerAnchoredRestart) {
1787
+ if (!preExistToken) throw new CustomError("INTERNAL", `Incomplete genesis StateDB: missing official token state (${this.tokenItx.address}) while _state_commit.seq > 0`);
1788
+ if (needsTokenWrite) {
1789
+ tokenState.update(preExistToken, pick(this.tokenItx, changedKeys));
1790
+ this.logger.info("skipping out-of-band token metadata update on ledger-anchored restart to preserve _state_commit parity", {
1791
+ address: this.tokenItx.address,
1792
+ stateCommitSeq
1793
+ });
1794
+ }
1795
+ } else if (needsTokenWrite) await this.runAsLambda(async (txn) => {
1049
1796
  const existToken = await this.statedb.token.get(this.tokenItx.address, { txn });
1050
1797
  if (!existToken) {
1051
1798
  const state = tokenState.create(this.tokenItx, context);
1052
1799
  const result = await tokenDB.create(this.tokenItx.address, state, { txn });
1053
1800
  tokenDB.emit("create", result, { txn });
1054
1801
  this.logger.debug("create token state", { address: result?.address });
1055
- } else {
1056
- const changedKeys = [
1057
- "icon",
1058
- "website",
1059
- "metadata"
1060
- ];
1061
- const pickStateToken = pick(existToken, changedKeys);
1062
- const pickConfigToken = pick(this.tokenItx, changedKeys);
1063
- if (!isEqual(pickStateToken, pickConfigToken)) {
1064
- const state = tokenState.update(existToken, pickConfigToken);
1065
- const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1066
- tokenDB.emit("update", result, { txn });
1067
- this.logger.info("update token state", { result });
1068
- }
1802
+ } else if (!isEqual(normalizeTokenMutable(existToken), normalizeTokenMutable(expectedTokenShape))) {
1803
+ const state = tokenState.update(existToken, pick(this.tokenItx, changedKeys));
1804
+ const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1805
+ tokenDB.emit("update", result, { txn });
1806
+ this.logger.info("update token state", { result });
1069
1807
  }
1070
1808
  }, { commitMessage: "initialize token" });
1071
- await this.runAsLambda(async (txn) => {
1072
- for (let i = 0; i < accounts.length; i++) {
1073
- const { address, balance, moniker, pk } = accounts[i];
1074
- try {
1075
- if (!await accountDB.get(address, { txn })) {
1076
- const balanceStr = fromTokenToUnit(balance ?? 0, token.decimal ?? 18).toString(10);
1077
- const state = accountState.create({
1078
- address,
1079
- tokens: { [this.tokenItx.address]: balanceStr },
1080
- moniker: moniker || "token-holder",
1081
- pk
1082
- }, context);
1083
- const result = await accountDB.create(address, state, { txn });
1084
- accountDB.emit("create", result, { txn });
1085
- this.logger.info("create account done", { address });
1809
+ if (!isLedgerAnchoredRestart) {
1810
+ let needsAccountsWrite = false;
1811
+ if (accounts.length > 0) {
1812
+ for (let i = 0; i < accounts.length; i++) if (!await accountDB.get(accounts[i].address)) {
1813
+ needsAccountsWrite = true;
1814
+ break;
1815
+ }
1816
+ } else if (!existingChain) needsAccountsWrite = true;
1817
+ if (needsAccountsWrite) await this.runAsLambda(async (txn) => {
1818
+ for (let i = 0; i < accounts.length; i++) {
1819
+ const { address, balance, moniker, pk } = accounts[i];
1820
+ try {
1821
+ if (!await accountDB.get(address, { txn })) {
1822
+ const balanceStr = fromTokenToUnit(balance ?? 0, token.decimal ?? 18).toString(10);
1823
+ const state = accountState.create({
1824
+ address,
1825
+ tokens: { [this.tokenItx.address]: balanceStr },
1826
+ moniker: moniker || "token-holder",
1827
+ pk
1828
+ }, context);
1829
+ const result = await accountDB.create(address, state, { txn });
1830
+ accountDB.emit("create", result, { txn });
1831
+ this.logger.info("create account done", { address });
1832
+ }
1833
+ } catch (err) {
1834
+ this.logger.error("Failed to initialize initial token holders", err);
1835
+ if (hasCommitTracking) throw err;
1086
1836
  }
1087
- } catch (err) {
1088
- this.logger.error("Failed to initialize initial token holders", err);
1089
1837
  }
1090
- }
1091
- }, { commitMessage: "initialize accounts" });
1838
+ }, { commitMessage: "initialize accounts" });
1839
+ }
1092
1840
  }
1093
1841
  }
1094
1842
  /**
@@ -1129,59 +1877,65 @@ var OCAPResolver = class {
1129
1877
  }
1130
1878
  connectIndexDB() {
1131
1879
  const getToken = this.getToken.bind(this);
1132
- this.statedb.tx.on("create", async (x, ctx) => {
1880
+ this.statedb.tx.on("create", (x, ctx) => {
1133
1881
  if (!ctx) return;
1134
- try {
1135
- const tx = await createIndexedTransaction(x, ctx, this.indexdb);
1136
- await this.indexdb.tx.insert(tx);
1137
- if (typeof onCreateTx === "function") await onCreateTx(tx, ctx, this);
1138
- } catch (error) {
1139
- this.logger.error("create tx index failed", {
1140
- account: x,
1141
- error
1142
- });
1143
- await this.recordIndexFailure({
1144
- table: "tx",
1145
- event: "create",
1146
- entityId: x?.hash,
1147
- payload: x,
1148
- error
1149
- });
1150
- }
1882
+ this.trackIndexWrite((async () => {
1883
+ try {
1884
+ const tx = await createIndexedTransaction(x, ctx, this.indexdb);
1885
+ await this.indexdb.tx.insert(tx);
1886
+ if (typeof onCreateTx === "function") await onCreateTx(tx, ctx, this);
1887
+ } catch (error) {
1888
+ this.logger.error("create tx index failed", {
1889
+ account: x,
1890
+ error
1891
+ });
1892
+ await this.recordIndexFailure({
1893
+ table: "tx",
1894
+ event: "create",
1895
+ entityId: x?.hash,
1896
+ payload: x,
1897
+ error
1898
+ });
1899
+ }
1900
+ })());
1151
1901
  });
1152
- this.statedb.account.on("create", async (x) => {
1153
- try {
1154
- await this.indexdb.account.insert(await createIndexedAccount(x, getToken));
1155
- } catch (error) {
1156
- this.logger.error("create account index failed", {
1157
- account: x,
1158
- error
1159
- });
1160
- await this.recordIndexFailure({
1161
- table: "account",
1162
- event: "create",
1163
- entityId: x?.address,
1164
- payload: x,
1165
- error
1166
- });
1167
- }
1902
+ this.statedb.account.on("create", (x) => {
1903
+ this.trackIndexWrite((async () => {
1904
+ try {
1905
+ await this.indexdb.account.insert(await createIndexedAccount(x, getToken));
1906
+ } catch (error) {
1907
+ this.logger.error("create account index failed", {
1908
+ account: x,
1909
+ error
1910
+ });
1911
+ await this.recordIndexFailure({
1912
+ table: "account",
1913
+ event: "create",
1914
+ entityId: x?.address,
1915
+ payload: x,
1916
+ error
1917
+ });
1918
+ }
1919
+ })());
1168
1920
  });
1169
- this.statedb.account.on("update", async (x) => {
1170
- try {
1171
- await this.indexdb.account.update(x.address, await createIndexedAccount(x, getToken));
1172
- } catch (error) {
1173
- this.logger.error("update account index failed", {
1174
- account: x,
1175
- error
1176
- });
1177
- await this.recordIndexFailure({
1178
- table: "account",
1179
- event: "update",
1180
- entityId: x?.address,
1181
- payload: x,
1182
- error
1183
- });
1184
- }
1921
+ this.statedb.account.on("update", (x) => {
1922
+ this.trackIndexWrite((async () => {
1923
+ try {
1924
+ await this.indexdb.account.update(x.address, await createIndexedAccount(x, getToken));
1925
+ } catch (error) {
1926
+ this.logger.error("update account index failed", {
1927
+ account: x,
1928
+ error
1929
+ });
1930
+ await this.recordIndexFailure({
1931
+ table: "account",
1932
+ event: "update",
1933
+ entityId: x?.address,
1934
+ payload: x,
1935
+ error
1936
+ });
1937
+ }
1938
+ })());
1185
1939
  });
1186
1940
  const mapping = {
1187
1941
  asset: [
@@ -1235,45 +1989,49 @@ var OCAPResolver = class {
1235
1989
  };
1236
1990
  Object.keys(mapping).forEach((table) => {
1237
1991
  const [fn, key, onCreate, onUpdate] = mapping[table];
1238
- this.statedb[table].on("create", async (x, _ctx) => {
1239
- try {
1240
- const ctx = this.enrichIndexContext(_ctx);
1241
- const doc = await fn(x, ctx, this.indexdb);
1242
- await this.indexdb[table].insert(doc);
1243
- if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
1244
- } catch (error) {
1245
- this.logger.error(`create ${table} index failed`, {
1246
- [table]: x,
1247
- error
1248
- });
1249
- await this.recordIndexFailure({
1250
- table,
1251
- event: "create",
1252
- entityId: x?.[key],
1253
- payload: x,
1254
- error
1255
- });
1256
- }
1992
+ this.statedb[table].on("create", (x, _ctx) => {
1993
+ this.trackIndexWrite((async () => {
1994
+ try {
1995
+ const ctx = this.enrichIndexContext(_ctx);
1996
+ const doc = await fn(x, ctx, this.indexdb);
1997
+ await this.indexdb[table].insert(doc);
1998
+ if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
1999
+ } catch (error) {
2000
+ this.logger.error(`create ${table} index failed`, {
2001
+ [table]: x,
2002
+ error
2003
+ });
2004
+ await this.recordIndexFailure({
2005
+ table,
2006
+ event: "create",
2007
+ entityId: x?.[key],
2008
+ payload: x,
2009
+ error
2010
+ });
2011
+ }
2012
+ })());
1257
2013
  });
1258
- this.statedb[table].on("update", async (x, _ctx) => {
1259
- try {
1260
- const ctx = this.enrichIndexContext(_ctx);
1261
- const doc = await fn(x, ctx, this.indexdb);
1262
- await this.indexdb[table].update(doc[key], doc);
1263
- if (typeof onUpdate === "function") onUpdate(doc, ctx, this.indexdb, this);
1264
- } catch (error) {
1265
- this.logger.error(`update ${table} index failed`, {
1266
- [table]: x,
1267
- error
1268
- });
1269
- await this.recordIndexFailure({
1270
- table,
1271
- event: "update",
1272
- entityId: x?.[key],
1273
- payload: x,
1274
- error
1275
- });
1276
- }
2014
+ this.statedb[table].on("update", (x, _ctx) => {
2015
+ this.trackIndexWrite((async () => {
2016
+ try {
2017
+ const ctx = this.enrichIndexContext(_ctx);
2018
+ const doc = await fn(x, ctx, this.indexdb);
2019
+ await this.indexdb[table].update(doc[key], doc);
2020
+ if (typeof onUpdate === "function") await onUpdate(doc, ctx, this.indexdb, this);
2021
+ } catch (error) {
2022
+ this.logger.error(`update ${table} index failed`, {
2023
+ [table]: x,
2024
+ error
2025
+ });
2026
+ await this.recordIndexFailure({
2027
+ table,
2028
+ event: "update",
2029
+ entityId: x?.[key],
2030
+ payload: x,
2031
+ error
2032
+ });
2033
+ }
2034
+ })());
1277
2035
  });
1278
2036
  });
1279
2037
  }
@@ -1318,7 +2076,8 @@ var OCAPResolver = class {
1318
2076
  async getReplayTxRollupContext(state) {
1319
2077
  const type = typeof state?.type === "string" ? state.type : "";
1320
2078
  const txType = type ? `fg:t:${type}` : "";
1321
- const address = state?.tx?.itxJson?.rollup;
2079
+ const itxJson = state?.tx?.itxJson;
2080
+ const address = itxJson?.rollup || (type === "create_rollup" ? itxJson?.address : void 0);
1322
2081
  if (typeof address !== "string" || !address) return txType ? { txType } : {};
1323
2082
  const row = await this.statedb.rollup.get(address);
1324
2083
  if (!row) return txType ? { txType } : {};
@@ -1362,9 +2121,9 @@ var OCAPResolver = class {
1362
2121
  };
1363
2122
  const doc$1 = state?.tx && state?.hash && typeof state?.Valid !== "undefined" ? state : await createIndexedTransaction(state, ctx$1, this.indexdb);
1364
2123
  const existing$1 = await this.indexdb.tx.get(doc$1.hash);
1365
- if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, doc$1);
2124
+ if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, formatTxBeforeInsert(doc$1));
1366
2125
  else if (!existing$1) await this.indexdb.tx.insert(doc$1);
1367
- else await this.indexdb.tx.update(doc$1.hash, doc$1);
2126
+ else await this.indexdb.tx.update(doc$1.hash, formatTxBeforeInsert(doc$1));
1368
2127
  if (event === "create" && !existing$1 && typeof onCreateTx === "function") await onCreateTx(doc$1, ctx$1, this);
1369
2128
  return;
1370
2129
  }
@@ -1806,6 +2565,7 @@ var OCAPResolver = class {
1806
2565
  return await this.tokenDistribution.updateByToken(tokenAddress, force);
1807
2566
  }
1808
2567
  async getTokenDistribution(args = {}) {
2568
+ assertResolverNotHaltedForDataRead(this);
1809
2569
  const { tokenAddress = this.config.token.address } = args;
1810
2570
  return await this.tokenDistribution.getDistribution(tokenAddress);
1811
2571
  }
@@ -1893,4 +2653,4 @@ var OCAPResolver = class {
1893
2653
  };
1894
2654
 
1895
2655
  //#endregion
1896
- export { OCAPResolver as default, formatData, formatDelegationOps };
2656
+ export { ConsensusAbortError, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, GRAPHQL_INDEXED_TX_COLUMNS, HotStuffNodeRuntime, LedgerEntryReplayer, MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, NodePreferencesError, NodePreferencesManager, UNIFIED_CONSOLE_APP_JS, applyBootRuntimePreferences, buildUnifiedConsoleHtml, collectLedgerHealthSummary, createAdminAuthGuard, createExplorerMiddleware, createFollowerPeerFetchGuard, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, OCAPResolver as default, formatData, formatDelegationOps, isDashboardEnabled, isExplorerEnabled, isPrivateOrReservedIpAddress, isTransientSqliteLockError, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls };