@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/lib/index.cjs CHANGED
@@ -1,32 +1,39 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
3
+ const require_node_preferences = require('./node-preferences.cjs');
4
+ const require_dashboard = require('./dashboard.cjs');
5
+ const require_explorer = require('./explorer.cjs');
6
+ const require_replayer = require('./replayer.cjs');
7
+ const require_follower = require('./follower.cjs');
3
8
  const require_package = require('./package.cjs');
4
9
  const require_hooks = require('./hooks.cjs');
10
+ const require_hotstuff_runtime = require('./hotstuff-runtime.cjs');
5
11
  const require_migration_chain = require('./migration-chain.cjs');
6
12
  const require_token_cache = require('./token-cache.cjs');
7
13
  const require_token_distribution = require('./token-distribution.cjs');
8
14
  const require_token_flow = require('./token-flow.cjs');
9
- let _arcblock_did_util = require("@arcblock/did-util");
15
+ let _arcblock_ledger_core = require("@arcblock/ledger-core");
16
+ let _ocap_mcrypto = require("@ocap/mcrypto");
17
+ let _ocap_tx_protocols = require("@ocap/tx-protocols");
18
+ let node_crypto = require("node:crypto");
19
+ let _arcblock_did = require("@arcblock/did");
10
20
  let _ocap_util = require("@ocap/util");
21
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
22
+ let _ocap_state = require("@ocap/state");
23
+ _ocap_state = require_rolldown_runtime.__toESM(_ocap_state);
24
+ let _arcblock_did_util = require("@arcblock/did-util");
11
25
  let debug = require("debug");
12
26
  debug = require_rolldown_runtime.__toESM(debug);
13
27
  let lodash_pick = require("lodash/pick");
14
28
  lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
15
- let node_crypto = require("node:crypto");
16
- let _arcblock_did = require("@arcblock/did");
17
29
  let _arcblock_validator = require("@arcblock/validator");
18
30
  let _ocap_config = require("@ocap/config");
19
31
  _ocap_config = require_rolldown_runtime.__toESM(_ocap_config);
20
32
  let _ocap_indexdb = require("@ocap/indexdb");
21
- let _ocap_mcrypto = require("@ocap/mcrypto");
22
33
  let _ocap_message = require("@ocap/message");
23
- let _ocap_state = require("@ocap/state");
24
- _ocap_state = require_rolldown_runtime.__toESM(_ocap_state);
25
- let _ocap_tx_protocols = require("@ocap/tx-protocols");
26
34
  let _ocap_tx_protocols_lib_util = require("@ocap/tx-protocols/lib/util");
27
35
  let _ocap_util_lib_constant = require("@ocap/util/lib/constant");
28
36
  let _ocap_util_lib_deposit_v2_bridge_fields = require("@ocap/util/lib/deposit-v2-bridge-fields");
29
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
30
37
  let _ocap_util_lib_md5 = require("@ocap/util/lib/md5");
31
38
  let lodash_cloneDeep = require("lodash/cloneDeep");
32
39
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
@@ -53,6 +60,9 @@ let _ocap_state_lib_states_tx = require("@ocap/state/lib/states/tx");
53
60
  const debug$1 = (0, debug.default)(require_package.name);
54
61
  const noop = (x) => x;
55
62
  const CHAIN_ADDR = (0, _ocap_util_lib_md5.md5)("OCAP_CHAIN_ADDR");
63
+ function getNormalizedEnvLower(key) {
64
+ return String(process.env[key] ?? "").trim().toLowerCase();
65
+ }
56
66
  const maxGasOps = {
57
67
  "fg:t:account_migrate": {
58
68
  create: 2,
@@ -259,6 +269,34 @@ const extractTokenMeta = (address, tokenStates) => {
259
269
  foreignToken: tokenState.foreignToken
260
270
  };
261
271
  };
272
+ /**
273
+ * Index `tx` columns a GraphQL `IndexedTransaction` read needs (#1872): the type's fields (hash sender receiver time
274
+ * type tx valid code receipts gasPayer; `tokenSymbols` is always recomputed by _formatTx) plus every input of
275
+ * _formatTx / getTxReceipts / getTxSender / deriveTxGasPayer / isDefaultTokenChanged / attachPaidTxGas, which only
276
+ * read these. Used only when the caller sets `ctx.graphqlTxProjection` (@ocap/gql does, for listTransactions and
277
+ * listAssetTransactions); every other caller keeps receiving every column.
278
+ */
279
+ const GRAPHQL_INDEXED_TX_COLUMNS = [
280
+ "hash",
281
+ "code",
282
+ "receipts",
283
+ "receiver",
284
+ "sender",
285
+ "gasPayer",
286
+ "time",
287
+ "tx",
288
+ "type",
289
+ "valid"
290
+ ];
291
+ const withTxProjection = (args, ctx) => ctx?.graphqlTxProjection === true ? {
292
+ ...args,
293
+ columns: GRAPHQL_INDEXED_TX_COLUMNS
294
+ } : args;
295
+ const assertResolverNotHaltedForDataRead = (self) => {
296
+ const runtime = self?.nodeRuntime;
297
+ if (runtime?.isHalted?.() === true) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
298
+ if (runtime?.isReconciling?.() === true) throw new _ocap_util_lib_error.CustomError("FOLLOWER_RECONCILING", "Follower is reconciling local statedb with imported ledger segment");
299
+ };
262
300
  var OCAPResolver = class {
263
301
  /**
264
302
  * Creates an instance of OCAPResolver.
@@ -270,24 +308,44 @@ var OCAPResolver = class {
270
308
  * @param params.filter bloom filter to do anti-replay check
271
309
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
272
310
  */
273
- constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
311
+ constructor({ statedb, indexdb, ledger, config, filter, admissionBlockedCheck, admissionReservedSymbolCheck, validateTokenConfig = true, skipInitializeStateDB = false, deferInitialize = false, consensusMode, txQueueConfig, now, nodeRuntime, logger }) {
274
312
  this.inFlightPreFlights = 0;
313
+ this.initializationPromise = null;
314
+ this.shutdownPromise = null;
315
+ this.isShuttingDown = false;
316
+ this.preFlightDrainWaiters = [];
317
+ this.pendingIndexWrites = /* @__PURE__ */ new Set();
318
+ this.txAcceptedTotal = 0;
319
+ this.txPersistedFailedTotal = 0;
320
+ this.txPreFlightRejectedTotal = 0;
321
+ this.txForwardedTotal = 0;
322
+ this.txBucketsSec = new Int32Array(60);
323
+ this.txBucketCounts = new Int32Array(60);
275
324
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
276
325
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
277
326
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
278
327
  this.logger = logger || console;
328
+ this.now = typeof now === "function" ? now : () => Date.now();
329
+ this.deferInitialize = Boolean(deferInitialize);
330
+ this.explicitConsensusMode = consensusMode;
279
331
  this.statedb = statedb;
280
332
  this.indexdb = indexdb;
281
333
  this.ledger = ledger;
282
334
  this.filter = filter;
335
+ this.admissionBlockedCheck = admissionBlockedCheck;
336
+ this.admissionReservedSymbolCheck = admissionReservedSymbolCheck;
337
+ this.skipInitializeStateDB = Boolean(skipInitializeStateDB);
338
+ this.nodeRuntime = nodeRuntime;
283
339
  this.config = Object.freeze(_ocap_config.validate(config));
284
340
  this.chainAddr = (0, _ocap_util_lib_md5.md5)(config.chainId);
285
341
  this.tokenItx = _ocap_config.genTokenItx(this.config);
286
342
  this.consensus = `${statedb.name} v${statedb.version}`;
343
+ const isHotStuffMode = consensusMode === "hotstuff" || !consensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(nodeRuntime?.getConsensusCommitter?.());
344
+ if (txQueueConfig?.maxRequest !== void 0) this.setMaxTxRequest(txQueueConfig.maxRequest);
287
345
  this.queue = new queue.default({
288
346
  autostart: true,
289
- concurrency: txRequestConfig.concurrent,
290
- timeout: txRequestConfig.timeout
347
+ concurrency: isHotStuffMode ? 1 : txQueueConfig?.concurrent ?? txRequestConfig.concurrent,
348
+ timeout: txQueueConfig?.timeoutMs ?? txRequestConfig.timeout
291
349
  });
292
350
  if (indexdb) {
293
351
  this.tokenCache = require_token_cache.getInstance(indexdb.token);
@@ -302,28 +360,387 @@ var OCAPResolver = class {
302
360
  runAsLambda: typeof statedb.runAsLambda === "function" ? statedb.runAsLambda.bind(statedb) : void 0
303
361
  });
304
362
  this.formatTx = this._formatTx.bind(this);
305
- if (validateTokenConfig) this.validateTokenConfig();
363
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
364
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
365
+ const isReadonlyStartRole = Boolean(skipInitializeStateDB) || nodeRuntime && nodeRuntime.role !== "validator" || normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
366
+ if (validateTokenConfig && !isReadonlyStartRole) this.validateTokenConfig();
306
367
  this.connectIndexDB();
307
- this.initializationPromise = this.initializeStateDB().catch((err) => {
368
+ if (!this.deferInitialize) this.initializationPromise = this.initializeStateDB().catch((err) => {
308
369
  this.logger.error("Failed to initialize statedb:", err.message);
309
370
  process.exit(1);
310
371
  });
311
372
  }
373
+ initialize() {
374
+ if (!this.initializationPromise) this.initializationPromise = this.initializeStateDB();
375
+ return this.initializationPromise;
376
+ }
377
+ setNodeRuntime(runtime) {
378
+ this.nodeRuntime = runtime;
379
+ if (runtime?.getConsensusCommitter?.()) this.queue.concurrency = 1;
380
+ }
381
+ getNodeRuntime() {
382
+ return this.nodeRuntime;
383
+ }
384
+ setAdmissionBlockedCheck(fn) {
385
+ this.admissionBlockedCheck = fn;
386
+ }
387
+ setAdmissionReservedSymbolCheck(fn) {
388
+ this.admissionReservedSymbolCheck = fn;
389
+ }
390
+ getMaxTxRequest() {
391
+ if (this.maxTxRequestOverride !== void 0) return this.maxTxRequestOverride;
392
+ return Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
393
+ }
394
+ setMaxTxRequest(maxRequest) {
395
+ if (maxRequest === void 0) {
396
+ this.maxTxRequestOverride = void 0;
397
+ return;
398
+ }
399
+ if (!Number.isSafeInteger(maxRequest) || maxRequest < 1 || maxRequest > 1e4) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "txMaxRequest must be an integer between 1 and 10000");
400
+ this.maxTxRequestOverride = maxRequest;
401
+ }
402
+ recordCommittedTxSample(nowMs = Date.now()) {
403
+ const sec = Math.floor(nowMs / 1e3);
404
+ const slot = (sec % 60 + 60) % 60;
405
+ if (this.txBucketsSec[slot] !== sec) {
406
+ this.txBucketsSec[slot] = sec;
407
+ this.txBucketCounts[slot] = 1;
408
+ } else this.txBucketCounts[slot] += 1;
409
+ }
410
+ getPipelineTelemetry(nowMs = Date.now()) {
411
+ const nowSec = Math.floor(nowMs / 1e3);
412
+ let sum10 = 0;
413
+ let sum60 = 0;
414
+ for (let i = 0; i < 60; i++) {
415
+ const bucketSec = this.txBucketsSec[i];
416
+ if (bucketSec <= 0) continue;
417
+ const age = nowSec - bucketSec;
418
+ if (age >= 0 && age < 60) {
419
+ sum60 += this.txBucketCounts[i];
420
+ if (age < 10) sum10 += this.txBucketCounts[i];
421
+ }
422
+ }
423
+ return {
424
+ queueDepth: this.queue.length,
425
+ inFlightPreFlights: this.inFlightPreFlights,
426
+ maxTxRequest: this.getMaxTxRequest(),
427
+ concurrency: this.queue.concurrency,
428
+ acceptedTotal: this.txAcceptedTotal,
429
+ persistedFailedTotal: this.txPersistedFailedTotal,
430
+ preFlightRejectedTotal: this.txPreFlightRejectedTotal,
431
+ forwardedTotal: this.txForwardedTotal,
432
+ tps10s: Number((sum10 / 10).toFixed(2)),
433
+ tps60s: Number((sum60 / 60).toFixed(2))
434
+ };
435
+ }
436
+ async assertNotBlockedAtAdmission(context) {
437
+ const hasBlockedCheck = typeof this.admissionBlockedCheck === "function";
438
+ const hasReservedCheck = typeof this.admissionReservedSymbolCheck === "function";
439
+ if (!hasBlockedCheck && !hasReservedCheck) return;
440
+ const txObj = context.tx && typeof context.tx === "object" ? context.tx : {};
441
+ const itxObj = context.itxJson && typeof context.itxJson === "object" ? context.itxJson : context.itx && typeof context.itx === "object" ? context.itx : {};
442
+ const txType = String(context.txType || txObj.itx?.type || "");
443
+ if (hasReservedCheck) {
444
+ if (txType === "fg:t:create_token_factory" || txType === "CreateTokenFactoryTx" || txType === "fg:t:create_token" || txType === "CreateTokenTx") {
445
+ const tokenNested = itxObj.token && typeof itxObj.token === "object" ? itxObj.token : null;
446
+ const normalizedSym = (typeof tokenNested?.symbol === "string" ? tokenNested.symbol : typeof itxObj.symbol === "string" ? itxObj.symbol : "").trim().toUpperCase();
447
+ if (normalizedSym && await Promise.resolve(this.admissionReservedSymbolCheck(normalizedSym))) {
448
+ const symErr = new _ocap_util_lib_error.CustomError("INVALID_SYMBOL", `Token symbol "${normalizedSym}" is reserved by node admission policy`);
449
+ symErr._strikeRecorded = true;
450
+ throw symErr;
451
+ }
452
+ }
453
+ }
454
+ if (!hasBlockedCheck) return;
455
+ const sigs = Array.isArray(txObj.signaturesList) ? txObj.signaturesList : Array.isArray(txObj.signatures) ? txObj.signatures : [];
456
+ const inputs = Array.isArray(itxObj.inputs) ? itxObj.inputs : Array.isArray(itxObj.inputsList) ? itxObj.inputsList : [];
457
+ const outputs = Array.isArray(itxObj.outputs) ? itxObj.outputs : Array.isArray(itxObj.outputsList) ? itxObj.outputsList : [];
458
+ const trustedIssuers = Array.isArray(itxObj.trustedIssuers) ? itxObj.trustedIssuers : Array.isArray(itxObj.trustedIssuersList) ? itxObj.trustedIssuersList : [];
459
+ const issuerField = itxObj.issuer;
460
+ const issuerCandidates = typeof issuerField === "string" ? [issuerField] : issuerField && typeof issuerField === "object" ? [issuerField.id, issuerField.address] : [];
461
+ const candidateActors = /* @__PURE__ */ new Set();
462
+ const addCandidate = (raw) => {
463
+ if (typeof raw === "string") {
464
+ const trimmed = raw.trim();
465
+ if (trimmed) candidateActors.add(trimmed);
466
+ }
467
+ };
468
+ const isRevokeDelegate = txType === "fg:t:revoke_delegate" || txType === "RevokeDelegateTx";
469
+ for (const candidate of [
470
+ txObj.from,
471
+ txObj.delegator,
472
+ ...isRevokeDelegate ? [] : [itxObj.to],
473
+ itxObj.receiver,
474
+ itxObj.owner,
475
+ itxObj.delegatee,
476
+ ...txType === "fg:t:account_migrate" || txType === "AccountMigrateTx" ? [itxObj.address] : [],
477
+ ...issuerCandidates,
478
+ ...trustedIssuers,
479
+ ...sigs.flatMap((s) => [s?.signer, s?.delegator]),
480
+ ...inputs.flatMap((inp) => [inp?.owner, inp?.address]),
481
+ ...outputs.flatMap((out) => [out?.owner, out?.address])
482
+ ]) addCandidate(candidate);
483
+ if (this.statedb) {
484
+ if (txType === "fg:t:claim_stake" || txType === "ClaimStakeTx") {
485
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
486
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
487
+ const evidenceHash = itxObj.evidence && typeof itxObj.evidence === "object" ? itxObj.evidence.hash : void 0;
488
+ if (typeof evidenceHash === "string" && evidenceHash.trim() && typeof this.statedb.tx?.get === "function") {
489
+ const evTxState = await this.statedb.tx.get(evidenceHash.trim()).catch(() => null);
490
+ const evItx = evTxState?.tx?.itxJson && typeof evTxState.tx.itxJson === "object" ? evTxState.tx.itxJson : (evTxState?.tx)?.itx && typeof (evTxState?.tx).itx === "object" ? (evTxState?.tx).itx : {};
491
+ const evOutputs = Array.isArray(evItx.outputs) ? evItx.outputs : Array.isArray(evItx.outputsList) ? evItx.outputsList : [];
492
+ for (const out of evOutputs) {
493
+ addCandidate(out?.owner);
494
+ addCandidate(out?.address);
495
+ }
496
+ }
497
+ } else if (txType === "fg:t:revoke_stake" || txType === "RevokeStakeTx") {
498
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
499
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
500
+ }
501
+ const isAcquireAsset = txType === "fg:t:acquire_asset_v2" || txType === "AcquireAssetV2Tx" || txType === "fg:t:acquire_asset_v3" || txType === "AcquireAssetV3Tx";
502
+ if (isAcquireAsset || txType === "fg:t:mint_asset" || txType === "MintAssetTx") {
503
+ const factoryAddr = typeof itxObj.factory === "string" ? itxObj.factory.trim() : "";
504
+ if (factoryAddr && typeof this.statedb.factory?.get === "function") {
505
+ const factoryState = await this.statedb.factory.get(factoryAddr).catch(() => null);
506
+ addCandidate(factoryState?.owner);
507
+ if (Array.isArray(factoryState?.trustedIssuers)) for (const ti of factoryState.trustedIssuers) addCandidate(ti);
508
+ if (isAcquireAsset && factoryState?.settlement === "instant" && Array.isArray(factoryState?.hooks)) {
509
+ 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);
510
+ }
511
+ }
512
+ }
513
+ if (txType === "fg:t:update_asset" || txType === "UpdateAssetTx" || txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") {
514
+ const assetAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
515
+ if (assetAddr && typeof this.statedb.asset?.get === "function") {
516
+ const assetState = await this.statedb.asset.get(assetAddr).catch(() => null);
517
+ addCandidate(assetState?.issuer);
518
+ if (txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") addCandidate(assetState?.owner);
519
+ }
520
+ }
521
+ }
522
+ const findBlockedInLineage = async (seedActor) => {
523
+ const visited = /* @__PURE__ */ new Set();
524
+ const queue$1 = [seedActor];
525
+ const MAX_LINEAGE_EXPAND = 32;
526
+ while (queue$1.length > 0 && visited.size < MAX_LINEAGE_EXPAND) {
527
+ const rawCurr = queue$1.shift();
528
+ if (!rawCurr) continue;
529
+ const bareCurr = (0, _ocap_util.toAddress)(rawCurr).trim();
530
+ const keyCurr = bareCurr || rawCurr;
531
+ if (visited.has(keyCurr)) continue;
532
+ visited.add(keyCurr);
533
+ if (await Promise.resolve(this.admissionBlockedCheck(rawCurr))) return rawCurr;
534
+ if (bareCurr && bareCurr !== rawCurr && await Promise.resolve(this.admissionBlockedCheck(bareCurr))) return bareCurr;
535
+ if ((0, _arcblock_did.isValid)(keyCurr) && typeof this.statedb?.account?.get === "function") {
536
+ const accState = await this.statedb.account.get(keyCurr, { traceMigration: false }).catch(() => null);
537
+ if (accState) {
538
+ if (typeof accState.address === "string" && accState.address.trim()) {
539
+ const nextKey = (0, _ocap_util.toAddress)(accState.address.trim()).trim();
540
+ if (nextKey && !visited.has(nextKey)) queue$1.push(nextKey);
541
+ }
542
+ if (Array.isArray(accState.migratedFrom)) {
543
+ for (const prev of accState.migratedFrom) if (typeof prev === "string" && prev.trim()) {
544
+ const prevKey = (0, _ocap_util.toAddress)(prev.trim()).trim();
545
+ if (prevKey && !visited.has(prevKey)) queue$1.push(prevKey);
546
+ }
547
+ }
548
+ if (Array.isArray(accState.migratedTo)) {
549
+ for (const nextAddr of accState.migratedTo) if (typeof nextAddr === "string" && nextAddr.trim()) {
550
+ const toKey = (0, _ocap_util.toAddress)(nextAddr.trim()).trim();
551
+ if (toKey && !visited.has(toKey)) queue$1.push(toKey);
552
+ }
553
+ }
554
+ }
555
+ }
556
+ }
557
+ return null;
558
+ };
559
+ for (const actor of candidateActors) {
560
+ const blockedMatch = await findBlockedInLineage(actor);
561
+ if (blockedMatch) {
562
+ const blockErr = new _ocap_util_lib_error.CustomError("FORBIDDEN", `Account ${blockedMatch} is blocked by node admission policy`);
563
+ blockErr._strikeRecorded = true;
564
+ throw blockErr;
565
+ }
566
+ }
567
+ const extraObj = context.extra && typeof context.extra === "object" ? context.extra : {};
568
+ const rawTxExtra = extraObj.txExtra && typeof extraObj.txExtra === "object" ? extraObj.txExtra : void 0;
569
+ for (const candidateHeaders of [extraObj.gasStakeHeaders, rawTxExtra?.gasStakeHeaders]) {
570
+ const gasHeaders = candidateHeaders;
571
+ if (typeof gasHeaders?.token === "string" && gasHeaders.token.includes(".")) try {
572
+ const parts = gasHeaders.token.split(".");
573
+ if (parts.length === 3 && parts[1].length <= 16384) {
574
+ const payloadJson = Buffer.from(parts[1], "base64url").toString("utf8");
575
+ const decoded = JSON.parse(payloadJson);
576
+ if (typeof decoded?.iss === "string" && decoded.iss.trim()) {
577
+ const blockedSponsor = await findBlockedInLineage(decoded.iss.trim());
578
+ if (blockedSponsor) {
579
+ const sponsorErr = new _ocap_util_lib_error.CustomError("FORBIDDEN", `Gas sponsor ${blockedSponsor} is blocked by node admission policy`);
580
+ sponsorErr._unauthenticatedExtraFailure = true;
581
+ sponsorErr._strikeRecorded = true;
582
+ throw sponsorErr;
583
+ }
584
+ }
585
+ }
586
+ } catch (err) {
587
+ if (err?.code === "FORBIDDEN") throw err;
588
+ }
589
+ }
590
+ for (const candidatePass of [extraObj.gasPass, rawTxExtra?.gasPass]) {
591
+ const gasPass = candidatePass;
592
+ if (typeof gasPass?.stakeId === "string" && gasPass.stakeId.trim() && typeof this.statedb?.stake?.get === "function") {
593
+ const stakeState = await this.statedb.stake.get(gasPass.stakeId.trim()).catch(() => null);
594
+ for (const passActor of [stakeState?.sender, stakeState?.owner]) if (typeof passActor === "string" && passActor.trim()) {
595
+ const blockedPassActor = await findBlockedInLineage(passActor.trim());
596
+ if (blockedPassActor) {
597
+ const passErr = new _ocap_util_lib_error.CustomError("FORBIDDEN", `Gas pass sponsor ${blockedPassActor} is blocked by node admission policy`);
598
+ passErr._unauthenticatedExtraFailure = true;
599
+ passErr._strikeRecorded = true;
600
+ throw passErr;
601
+ }
602
+ }
603
+ }
604
+ }
605
+ }
606
+ async getFollowerStatus() {
607
+ if (this.nodeRuntime && typeof this.nodeRuntime.getFollowerStatus === "function") return this.nodeRuntime.getFollowerStatus();
608
+ return null;
609
+ }
610
+ async signForwardedSendTxReceipt(txHash) {
611
+ if (this.readonly || this.nodeRuntime && this.nodeRuntime.role !== "validator") return null;
612
+ const normalizedTxHash = txHash ? txHash.replace(/^0x/i, "").toUpperCase() : "";
613
+ const localEntry = txHash && typeof this.ledger?.get === "function" ? await this.ledger.get(txHash) || (normalizedTxHash && normalizedTxHash !== txHash ? await this.ledger.get(normalizedTxHash) : null) : null;
614
+ if (typeof this.nodeRuntime?.shouldHandleWriteLocally === "function" && !this.nodeRuntime.shouldHandleWriteLocally() && !localEntry) return null;
615
+ const proposer = this.ledger?.getProposer?.() || null;
616
+ if (!proposer || typeof this.ledger?.signConsensusDigest !== "function") return null;
617
+ const digest = (0, _arcblock_ledger_core.computeForwardReceiptDigest)({
618
+ chainId: this.config?.chainId || this.ledger.chainId,
619
+ txHash,
620
+ proposer
621
+ });
622
+ const signature = await this.ledger.signConsensusDigest(digest);
623
+ if (!signature) return null;
624
+ let commitProof;
625
+ if (localEntry && typeof this.ledger?.getCheckpointForSequence === "function" && typeof this.ledger?.getMerkleProof === "function") {
626
+ const [checkpoint, merkleProof] = await Promise.all([this.ledger.getCheckpointForSequence(localEntry.sequence).catch(() => null), this.ledger.getMerkleProof(localEntry.sequence).catch(() => null)]);
627
+ if (checkpoint?.qc && merkleProof) commitProof = Buffer.from(JSON.stringify({
628
+ sequence: localEntry.sequence,
629
+ entryHash: localEntry.entryHash,
630
+ stateCommitHash: localEntry.stateCommitHash ?? "",
631
+ proof: merkleProof,
632
+ checkpoint
633
+ }), "utf8").toString("base64");
634
+ }
635
+ return {
636
+ proposer,
637
+ signature,
638
+ ...commitProof ? { commitProof } : {}
639
+ };
640
+ }
641
+ trackIndexWrite(promise) {
642
+ const settled = promise.then(() => void 0, () => void 0);
643
+ this.pendingIndexWrites.add(settled);
644
+ settled.finally(() => {
645
+ this.pendingIndexWrites.delete(settled);
646
+ });
647
+ }
648
+ async flushIndexWrites() {
649
+ while (this.pendingIndexWrites.size > 0) await Promise.allSettled([...this.pendingIndexWrites]);
650
+ }
312
651
  sendTx({ tx: txBase64, extra }, ctx = {}) {
313
652
  debug$1("sendTx", {
314
653
  txBase64,
315
654
  request: ctx.request
316
655
  });
317
- if (process.env.CHAIN_MODE === "readonly") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "This chain node is running in readonly mode");
318
- const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
319
- if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
656
+ if (this.isShuttingDown) throw new _ocap_util_lib_error.CustomError("SERVICE_UNAVAILABLE", "Resolver is shutting down");
657
+ const runtime = this.nodeRuntime;
658
+ if (runtime?.isHalted?.()) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
659
+ if (runtime ? runtime.role !== "validator" : (() => {
660
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
661
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
662
+ return normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
663
+ })()) {
664
+ if ((runtime ? runtime.writePolicy : getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject") !== "forward" || typeof runtime?.forwardSendTx !== "function") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "This chain node is running in readonly mode (FOLLOWER_READ_ONLY)");
665
+ (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
666
+ if (ctx.forwardedHop !== void 0) throw new _ocap_util_lib_error.CustomError("FORWARD_LOOP_DETECTED", "Refusing to forward sendTx: request already carries X-Ocap-Forwarded-Hop header");
667
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
668
+ return (async () => {
669
+ await this.initialize();
670
+ if (runtime?.isHalted?.()) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
671
+ const forwardContext = {
672
+ txBase64,
673
+ statedb: this.statedb,
674
+ indexdb: this.indexdb,
675
+ ledger: this.ledger,
676
+ config: this.config,
677
+ filter: this.filter,
678
+ logger: this.logger,
679
+ extra: {
680
+ ...ctx,
681
+ txTime: pinnedTxTime$1,
682
+ txExtra: extra
683
+ }
684
+ };
685
+ await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(forwardContext);
686
+ await (0, _ocap_tx_protocols.assertStatelessTxRules)(forwardContext);
687
+ await this.assertNotBlockedAtAdmission(forwardContext);
688
+ const forwarded = await runtime.forwardSendTx({
689
+ tx: txBase64,
690
+ extra
691
+ }, ctx);
692
+ this.txForwardedTotal += 1;
693
+ if (forwarded?.hash && forwarded?.warning !== void 0) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(forwarded.hash, forwarded.warning, this.statedb);
694
+ return forwarded.hash;
695
+ })();
696
+ }
697
+ if (runtime?.role === "validator" && typeof runtime.shouldHandleWriteLocally === "function" && !runtime.shouldHandleWriteLocally()) {
698
+ if (ctx.forwardedHop !== void 0) throw new _ocap_util_lib_error.CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader for forwarded sendTx");
699
+ if (runtime.writePolicy !== "forward" || typeof runtime.forwardSendTx !== "function") throw new _ocap_util_lib_error.CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader");
700
+ (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
701
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
702
+ return (async () => {
703
+ await this.initialize();
704
+ if (runtime.isHalted()) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
705
+ const forwardContext = {
706
+ txBase64,
707
+ statedb: this.statedb,
708
+ indexdb: this.indexdb,
709
+ ledger: this.ledger,
710
+ config: this.config,
711
+ filter: this.filter,
712
+ logger: this.logger,
713
+ extra: {
714
+ ...ctx,
715
+ txTime: pinnedTxTime$1,
716
+ txExtra: extra
717
+ }
718
+ };
719
+ await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(forwardContext);
720
+ await (0, _ocap_tx_protocols.assertStatelessTxRules)(forwardContext);
721
+ await this.assertNotBlockedAtAdmission(forwardContext);
722
+ const forwarded = await runtime.forwardSendTx({
723
+ tx: txBase64,
724
+ extra
725
+ }, ctx);
726
+ this.txForwardedTotal += 1;
727
+ if (forwarded?.hash && forwarded?.warning !== void 0) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(forwarded.hash, forwarded.warning, this.statedb);
728
+ return forwarded.hash;
729
+ })();
730
+ }
731
+ const maxRequest = this.getMaxTxRequest();
732
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) {
733
+ this.txPreFlightRejectedTotal += 1;
734
+ throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
735
+ }
320
736
  (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
321
737
  const timer = new _ocap_tx_protocols.TxTimer();
322
738
  timer.setQueueState({
323
739
  waitingAtEnqueue: Math.max(0, this.queue.length - (this.queue.pending ?? 0)),
324
740
  runningAtEnqueue: this.queue.pending ?? 0,
325
- concurrencyConfig: txRequestConfig.concurrent
741
+ concurrencyConfig: this.queue.concurrency ?? txRequestConfig.concurrent
326
742
  });
743
+ const pinnedTxTime = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
327
744
  const context = {
328
745
  txBase64,
329
746
  statedb: this.statedb,
@@ -333,8 +750,10 @@ var OCAPResolver = class {
333
750
  filter: this.filter,
334
751
  logger: this.logger,
335
752
  timer,
753
+ ...runtime?.getConsensusCommitter ? { consensusCommitter: runtime.getConsensusCommitter() } : {},
336
754
  extra: {
337
755
  ...ctx,
756
+ txTime: pinnedTxTime,
338
757
  txExtra: extra
339
758
  }
340
759
  };
@@ -345,13 +764,18 @@ var OCAPResolver = class {
345
764
  if (!preFlightSlotReleased) {
346
765
  preFlightSlotReleased = true;
347
766
  this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
767
+ if (this.inFlightPreFlights === 0 && this.preFlightDrainWaiters.length > 0) {
768
+ const waiters = this.preFlightDrainWaiters.splice(0, this.preFlightDrainWaiters.length);
769
+ for (const notify of waiters) notify();
770
+ }
348
771
  }
349
772
  };
350
773
  const enqueueAfterPreFlight = async () => {
351
774
  try {
352
- await this.initializationPromise;
775
+ await this.initialize();
353
776
  await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(context);
354
777
  await (0, _ocap_tx_protocols.assertStatelessTxRules)(context);
778
+ await this.assertNotBlockedAtAdmission(context);
355
779
  const preTx = context.tx;
356
780
  const preTxHash = context.txHash;
357
781
  if (preTx) await (0, _ocap_tx_protocols.assertTxAdmission)({
@@ -385,27 +809,54 @@ var OCAPResolver = class {
385
809
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
386
810
  }
387
811
  releasePreFlightSlot();
812
+ this.txPreFlightRejectedTotal += 1;
388
813
  reject(preFlightErr);
389
814
  return;
390
815
  }
391
- releasePreFlightSlot();
392
- const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
816
+ const currentMaxRequest = this.getMaxTxRequest();
393
817
  if (this.queue.length >= currentMaxRequest) {
818
+ releasePreFlightSlot();
819
+ this.txPreFlightRejectedTotal += 1;
394
820
  reject(new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy"));
395
821
  return;
396
822
  }
397
823
  const task = async () => {
398
824
  timer.mark("queueWait");
399
825
  try {
400
- const result = await this.executor.execute(context);
826
+ const activeRuntime = this.nodeRuntime;
827
+ if (activeRuntime?.getConsensusCommitter && !("consensusCommitter" in context)) context.consensusCommitter = activeRuntime.getConsensusCommitter();
828
+ const result = typeof activeRuntime?.executeWithConsensusLock === "function" ? await activeRuntime.executeWithConsensusLock(() => this.executor.execute(context)) : await this.executor.execute(context);
401
829
  if (result?.txHash && result?.securityWarning) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(result.txHash, result.securityWarning, this.statedb);
830
+ this.txAcceptedTotal += 1;
831
+ this.recordCommittedTxSample();
402
832
  resolve(result.txHash);
403
833
  } catch (err) {
834
+ if (err?.isConsensusAbort === true) {
835
+ const activeRuntime = this.nodeRuntime;
836
+ if (ctx.forwardedHop === void 0 && activeRuntime?.writePolicy === "forward" && typeof activeRuntime.forwardSendTx === "function") try {
837
+ const forwarded = await activeRuntime.forwardSendTx({
838
+ tx: txBase64,
839
+ extra
840
+ }, ctx);
841
+ if (forwarded?.hash && forwarded?.warning !== void 0) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(forwarded.hash, forwarded.warning, this.statedb);
842
+ this.txForwardedTotal += 1;
843
+ resolve(forwarded.hash);
844
+ return;
845
+ } catch (forwardErr) {
846
+ reject(forwardErr);
847
+ return;
848
+ }
849
+ reject(err);
850
+ return;
851
+ }
852
+ if (Number(context.ledgerSequence ?? 0) > 0) this.txPersistedFailedTotal += 1;
853
+ else this.txPreFlightRejectedTotal += 1;
404
854
  await this._indexRejectedLedgerTx(context, err);
405
855
  reject(err);
406
856
  }
407
857
  };
408
858
  this.queue.push(task);
859
+ releasePreFlightSlot();
409
860
  };
410
861
  enqueueAfterPreFlight().catch((err) => {
411
862
  releasePreFlightSlot();
@@ -512,6 +963,7 @@ var OCAPResolver = class {
512
963
  return (0, _ocap_tx_protocols.getTxSecurityWarningByHash)(txHash, this.statedb);
513
964
  }
514
965
  async getTx({ hash }, ctx) {
966
+ assertResolverNotHaltedForDataRead(this);
515
967
  if (_arcblock_validator.patterns.txHash.test(hash)) {
516
968
  const normalizedHash = hash.toUpperCase();
517
969
  const stateTx = await this._getState({
@@ -531,18 +983,60 @@ var OCAPResolver = class {
531
983
  return null;
532
984
  }
533
985
  getBlock() {
986
+ assertResolverNotHaltedForDataRead(this);
534
987
  return null;
535
988
  }
536
989
  getBlocks() {
990
+ assertResolverNotHaltedForDataRead(this);
537
991
  return [];
538
992
  }
539
993
  getUnconfirmedTxs() {
994
+ assertResolverNotHaltedForDataRead(this);
540
995
  return [];
541
996
  }
997
+ async resolveNodeSyncMetadata() {
998
+ if (this.nodeRuntime) {
999
+ const reconciling = Boolean(this.nodeRuntime.isReconciling?.());
1000
+ if (typeof this.nodeRuntime.getFollowerStatus === "function") {
1001
+ const status = await this.nodeRuntime.getFollowerStatus();
1002
+ return {
1003
+ synced: status.synced && !status.halted && !reconciling,
1004
+ nodeRole: status.nodeRole,
1005
+ writePolicy: status.writePolicy,
1006
+ syncLagEntries: status.syncLagEntries,
1007
+ verifiedCheckpointHeight: status.verifiedCheckpointHeight,
1008
+ halted: status.halted
1009
+ };
1010
+ }
1011
+ const [synced, latestCp$1] = await Promise.all([Promise.resolve(this.nodeRuntime.isSynced()), this.ledger?.getCheckpoint ? this.ledger.getCheckpoint().catch(() => null) : Promise.resolve(null)]);
1012
+ const halted = this.nodeRuntime.isHalted();
1013
+ return {
1014
+ synced: synced && !halted && !reconciling,
1015
+ nodeRole: this.nodeRuntime.role,
1016
+ writePolicy: this.nodeRuntime.writePolicy,
1017
+ syncLagEntries: null,
1018
+ verifiedCheckpointHeight: latestCp$1?.height ?? 0,
1019
+ halted
1020
+ };
1021
+ }
1022
+ const latestCp = this.ledger?.getCheckpoint ? await this.ledger.getCheckpoint().catch(() => null) : null;
1023
+ const rawRole = getNormalizedEnvLower("CHAIN_ROLE");
1024
+ const rawMode = getNormalizedEnvLower("CHAIN_MODE");
1025
+ const nodeRole = rawRole === "follower" || rawRole === "standby" ? rawRole : rawMode === "readonly" ? "follower" : "validator";
1026
+ return {
1027
+ synced: true,
1028
+ nodeRole,
1029
+ writePolicy: getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject",
1030
+ syncLagEntries: nodeRole === "validator" ? 0 : null,
1031
+ verifiedCheckpointHeight: latestCp?.height ?? 0,
1032
+ halted: false
1033
+ };
1034
+ }
542
1035
  async getChainInfo() {
1036
+ const [totalTxs, syncMeta] = await Promise.all([this.indexdb.tx.count(), this.resolveNodeSyncMetadata()]);
543
1037
  return {
544
1038
  id: this.chainAddr,
545
- totalTxs: await this.indexdb.tx.count(),
1039
+ totalTxs,
546
1040
  blockHash: (0, _ocap_util_lib_md5.md5)(""),
547
1041
  blockHeight: 0,
548
1042
  blockTime: "",
@@ -554,12 +1048,18 @@ var OCAPResolver = class {
554
1048
  moniker: this.config.chainId,
555
1049
  network: this.config.chainId,
556
1050
  supportedTxs: this.config.transaction.supportedTxs,
557
- synced: true,
558
- votingPower: "10"
1051
+ synced: syncMeta.synced,
1052
+ nodeRole: syncMeta.nodeRole,
1053
+ writePolicy: syncMeta.writePolicy,
1054
+ syncLagEntries: syncMeta.syncLagEntries,
1055
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1056
+ halted: syncMeta.halted,
1057
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
559
1058
  };
560
1059
  }
561
- getNodeInfo() {
562
- return Promise.resolve({
1060
+ async getNodeInfo() {
1061
+ const syncMeta = await this.resolveNodeSyncMetadata();
1062
+ return {
563
1063
  address: this.chainAddr,
564
1064
  appHash: (0, _ocap_util_lib_md5.md5)((/* @__PURE__ */ new Date()).toISOString()),
565
1065
  consensusVersion: this.consensus,
@@ -576,53 +1076,166 @@ var OCAPResolver = class {
576
1076
  network: this.config.chainId,
577
1077
  p2pAddress: "",
578
1078
  supportedTxs: this.config.transaction.supportedTxs,
579
- synced: true,
580
- votingPower: "10"
581
- });
1079
+ synced: syncMeta.synced,
1080
+ nodeRole: syncMeta.nodeRole,
1081
+ writePolicy: syncMeta.writePolicy,
1082
+ syncLagEntries: syncMeta.syncLagEntries,
1083
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1084
+ halted: syncMeta.halted,
1085
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
1086
+ };
582
1087
  }
583
- getNetInfo() {
584
- return Promise.resolve({
1088
+ async getNetInfo() {
1089
+ if (!this.nodeRuntime || typeof this.nodeRuntime.getRuntimeDiagnostics !== "function") return {
585
1090
  listeners: [],
586
1091
  listening: true,
587
1092
  nPeers: 0,
588
1093
  peers: []
589
- });
1094
+ };
1095
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1096
+ const listening = !this.nodeRuntime.isHalted();
1097
+ const defaultGeo = {
1098
+ city: "Unknown",
1099
+ country: "Unknown",
1100
+ latitude: 0,
1101
+ longitude: 0
1102
+ };
1103
+ if (diag.mode === "hotstuff" && Array.isArray(diag.validators)) {
1104
+ const peerValidators = diag.validators.filter((v$1) => !v$1.isSelf && v$1.reachable && typeof v$1.did === "string");
1105
+ return {
1106
+ listeners: [],
1107
+ listening,
1108
+ nPeers: peerValidators.length,
1109
+ peers: peerValidators.map((peer) => ({
1110
+ id: peer.did,
1111
+ moniker: peer.did,
1112
+ network: this.config.chainId,
1113
+ consensusVersion: this.consensus,
1114
+ ip: "",
1115
+ geoInfo: defaultGeo
1116
+ }))
1117
+ };
1118
+ }
1119
+ if (diag.mode === "follower") {
1120
+ const leaderRouter = diag.leaderRouter;
1121
+ const candidates = Array.isArray(leaderRouter?.candidates) ? leaderRouter.candidates : [];
1122
+ const activePeers = candidates.length > 0 ? candidates.filter((c) => c.reachable) : Number(diag.peerCount ?? 0) > 0 && Boolean(diag.hasActiveLeader) ? [{
1123
+ id: "upstream-peer-1",
1124
+ reachable: true
1125
+ }] : [];
1126
+ return {
1127
+ listeners: [],
1128
+ listening,
1129
+ nPeers: activePeers.length,
1130
+ peers: activePeers.map((c, idx) => ({
1131
+ id: c.id || `upstream-peer-${idx + 1}`,
1132
+ moniker: c.id || `upstream-peer-${idx + 1}`,
1133
+ network: this.config.chainId,
1134
+ consensusVersion: this.consensus,
1135
+ ip: "",
1136
+ geoInfo: defaultGeo
1137
+ }))
1138
+ };
1139
+ }
1140
+ return {
1141
+ listeners: [],
1142
+ listening,
1143
+ nPeers: 0,
1144
+ peers: []
1145
+ };
590
1146
  }
591
- getValidatorsInfo() {
592
- return Promise.resolve({
1147
+ async getValidatorsInfo() {
1148
+ assertResolverNotHaltedForDataRead(this);
1149
+ const formatPubKey = (rawPk) => {
1150
+ const cleanPkHex = rawPk ? rawPk.replace(/^0x/i, "") : "";
1151
+ if (!cleanPkHex || !/^[0-9a-fA-F]+$/.test(cleanPkHex)) return;
1152
+ return {
1153
+ type: cleanPkHex.length === 64 ? "ed25519" : "secp256k1",
1154
+ data: cleanPkHex
1155
+ };
1156
+ };
1157
+ if (this.nodeRuntime && this.nodeRuntime.getConsensusMode?.() === "hotstuff" && typeof this.nodeRuntime.getRuntimeDiagnostics === "function") {
1158
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1159
+ if (Array.isArray(diag.validators) && diag.validators.length > 0) {
1160
+ const leaderDid = typeof diag.currentLeaderDid === "string" ? diag.currentLeaderDid : "";
1161
+ return {
1162
+ blockHeight: 0,
1163
+ validators: diag.validators.map((v$1) => {
1164
+ const pk$1 = formatPubKey(v$1.publicKey);
1165
+ return {
1166
+ address: v$1.did,
1167
+ ...pk$1 ? { pubKey: pk$1 } : {},
1168
+ name: "",
1169
+ proposerPriority: v$1.isCurrentViewLeader || v$1.did === leaderDid ? "1" : "0",
1170
+ votingPower: "10"
1171
+ };
1172
+ })
1173
+ };
1174
+ }
1175
+ }
1176
+ const activeProposer = this.ledger?.getProposer?.() || this.config?.moderator?.address || (0, _arcblock_did.fromPublicKey)(this.chainAddr);
1177
+ const pk = formatPubKey(this.ledger?.getProposerPublicKey?.());
1178
+ return {
593
1179
  blockHeight: 0,
594
1180
  validators: [{
595
- address: this.config?.moderator?.address || (0, _arcblock_did.fromPublicKey)(this.chainAddr),
1181
+ address: activeProposer,
1182
+ ...pk ? { pubKey: pk } : {},
596
1183
  name: "",
597
1184
  proposerPriority: "0",
598
1185
  votingPower: "10"
599
1186
  }]
600
- });
1187
+ };
1188
+ }
1189
+ async getLedgerInfo() {
1190
+ assertResolverNotHaltedForDataRead(this);
1191
+ if (!this.ledger) return null;
1192
+ const latestSequence = await this.ledger.getLatestSequence();
1193
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1194
+ const entryHashV2From = rawV2From === void 0 ? null : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
1195
+ const proposer = this.ledger.getProposer?.() || this.config?.moderator?.address || null;
1196
+ const proposerPublicKey = this.ledger.getProposerPublicKey?.() || null;
1197
+ const checkpointSigningEnabled = typeof this.ledger.isCheckpointSigningEnabled === "function" ? this.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
1198
+ return {
1199
+ chainId: this.config?.chainId || this.ledger.chainId,
1200
+ latestSequence,
1201
+ entryHashV2From,
1202
+ proposer,
1203
+ proposerPublicKey,
1204
+ checkpointSigningEnabled
1205
+ };
601
1206
  }
602
1207
  async getLatestCheckpoint({ height } = {}) {
1208
+ assertResolverNotHaltedForDataRead(this);
603
1209
  if (!this.ledger) return null;
604
1210
  const targetHeight = height !== void 0 && height !== null ? Number(height) : void 0;
605
1211
  return this.ledger.getCheckpoint(targetHeight);
606
1212
  }
607
1213
  async getLedgerEntry({ hash, sequence } = {}) {
1214
+ assertResolverNotHaltedForDataRead(this);
608
1215
  if (!this.ledger) return null;
609
1216
  if (sequence !== void 0 && sequence !== null) return this.ledger.getBySequence(Number(sequence));
610
1217
  if (hash) return this.ledger.get(String(hash));
611
1218
  return null;
612
1219
  }
613
1220
  async getMerkleProof({ sequence }) {
1221
+ assertResolverNotHaltedForDataRead(this);
614
1222
  if (!this.ledger || sequence === void 0 || sequence === null) return null;
615
1223
  const seq = Number(sequence);
616
1224
  const [proof, checkpoint] = await Promise.all([this.ledger.getMerkleProof(seq), this.ledger.getCheckpointForSequence(seq)]);
1225
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1226
+ const entryHashV2From = rawV2From === void 0 ? void 0 : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
617
1227
  return {
618
1228
  proof,
619
- checkpoint
1229
+ checkpoint,
1230
+ ...entryHashV2From !== void 0 ? { entryHashV2From } : {}
620
1231
  };
621
1232
  }
622
1233
  getConfig() {
1234
+ assertResolverNotHaltedForDataRead(this);
623
1235
  return JSON.stringify(this.config);
624
1236
  }
625
1237
  getAccountState({ address, traceMigration = true, expandContext = true }, ctx) {
1238
+ assertResolverNotHaltedForDataRead(this);
626
1239
  return this._getState({
627
1240
  table: "account",
628
1241
  id: address,
@@ -639,6 +1252,7 @@ var OCAPResolver = class {
639
1252
  });
640
1253
  }
641
1254
  getStakeState({ address }, ctx) {
1255
+ assertResolverNotHaltedForDataRead(this);
642
1256
  return this._getState({
643
1257
  table: "stake",
644
1258
  id: address,
@@ -654,6 +1268,7 @@ var OCAPResolver = class {
654
1268
  });
655
1269
  }
656
1270
  async getRollupState({ address }, ctx) {
1271
+ assertResolverNotHaltedForDataRead(this);
657
1272
  const rollup = await this._getState({
658
1273
  table: "rollup",
659
1274
  id: address,
@@ -676,6 +1291,7 @@ var OCAPResolver = class {
676
1291
  return rollup;
677
1292
  }
678
1293
  async getRollupBlock({ hash, height, rollupAddress }, ctx) {
1294
+ assertResolverNotHaltedForDataRead(this);
679
1295
  if (hash) return this._getState({
680
1296
  table: "rollupBlock",
681
1297
  id: hash,
@@ -699,6 +1315,7 @@ var OCAPResolver = class {
699
1315
  throw new Error("Can not get rollup block without hash or height + rollup");
700
1316
  }
701
1317
  getAssetState({ address }, ctx) {
1318
+ assertResolverNotHaltedForDataRead(this);
702
1319
  return this._getState({
703
1320
  table: "asset",
704
1321
  id: address,
@@ -711,6 +1328,7 @@ var OCAPResolver = class {
711
1328
  });
712
1329
  }
713
1330
  getEvidenceState({ hash }, ctx) {
1331
+ assertResolverNotHaltedForDataRead(this);
714
1332
  return this._getState({
715
1333
  table: "evidence",
716
1334
  id: hash,
@@ -719,6 +1337,7 @@ var OCAPResolver = class {
719
1337
  });
720
1338
  }
721
1339
  getFactoryState({ address }, ctx) {
1340
+ assertResolverNotHaltedForDataRead(this);
722
1341
  return this._getState({
723
1342
  table: "factory",
724
1343
  id: address,
@@ -737,6 +1356,7 @@ var OCAPResolver = class {
737
1356
  });
738
1357
  }
739
1358
  async getTokenState({ address }, ctx) {
1359
+ assertResolverNotHaltedForDataRead(this);
740
1360
  const state = await this._getState({
741
1361
  table: "token",
742
1362
  id: address,
@@ -750,6 +1370,7 @@ var OCAPResolver = class {
750
1370
  return state;
751
1371
  }
752
1372
  getTokenFactoryState(args, ctx) {
1373
+ assertResolverNotHaltedForDataRead(this);
753
1374
  return this._getState({
754
1375
  table: "tokenFactory",
755
1376
  id: args.address,
@@ -772,6 +1393,7 @@ var OCAPResolver = class {
772
1393
  });
773
1394
  }
774
1395
  getDelegateState({ address }, ctx) {
1396
+ assertResolverNotHaltedForDataRead(this);
775
1397
  return this._getState({
776
1398
  table: "delegation",
777
1399
  id: address,
@@ -787,6 +1409,7 @@ var OCAPResolver = class {
787
1409
  });
788
1410
  }
789
1411
  async getAccountTokens({ address, token }, ctx) {
1412
+ assertResolverNotHaltedForDataRead(this);
790
1413
  if (!address) return [];
791
1414
  let state = null;
792
1415
  if ((0, _arcblock_did.toTypeInfo)(address).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) state = await this._getState({
@@ -828,6 +1451,7 @@ var OCAPResolver = class {
828
1451
  }));
829
1452
  }
830
1453
  getForgeState() {
1454
+ assertResolverNotHaltedForDataRead(this);
831
1455
  const { accounts, token, transaction, vaults } = this.config;
832
1456
  return Promise.resolve({
833
1457
  accountConfig: accounts,
@@ -866,6 +1490,7 @@ var OCAPResolver = class {
866
1490
  });
867
1491
  }
868
1492
  async getForgeStats() {
1493
+ assertResolverNotHaltedForDataRead(this);
869
1494
  const [accountCount, assetCount, txCount] = await Promise.all([
870
1495
  this.indexdb.account.count(),
871
1496
  this.indexdb.asset.count(),
@@ -895,19 +1520,23 @@ var OCAPResolver = class {
895
1520
  };
896
1521
  }
897
1522
  async listTransactions(args = {}, ctx) {
898
- return await this._doPaginatedSearch("listTransactions", args, "transactions", "tx.itxJson.data", ctx);
1523
+ assertResolverNotHaltedForDataRead(this);
1524
+ return await this._doPaginatedSearch("listTransactions", withTxProjection(args, ctx), "transactions", "tx.itxJson.data", ctx);
899
1525
  }
900
1526
  listAssets(args = {}, ctx) {
1527
+ assertResolverNotHaltedForDataRead(this);
901
1528
  return this._doPaginatedSearch("listAssets", args, "assets", "data", ctx);
902
1529
  }
903
1530
  listAssetTransactions(args = {}, ctx = {}) {
1531
+ assertResolverNotHaltedForDataRead(this);
904
1532
  if (!args.address) return Promise.resolve({ transactions: [] });
905
- return this._doPaginatedSearch("listTransactions", {
1533
+ return this._doPaginatedSearch("listTransactions", withTxProjection({
906
1534
  ...args,
907
1535
  assetFilter: { assets: [args.address] }
908
- }, "transactions", "tx.itxJson.data", ctx);
1536
+ }, ctx), "transactions", "tx.itxJson.data", ctx);
909
1537
  }
910
1538
  async listFactories(args = {}, ctx) {
1539
+ assertResolverNotHaltedForDataRead(this);
911
1540
  const result = await this._doPaginatedSearch("listFactories", args, "factories", "data", ctx);
912
1541
  result.factories = result.factories.map((x) => {
913
1542
  const output = x.output;
@@ -917,24 +1546,31 @@ var OCAPResolver = class {
917
1546
  return result;
918
1547
  }
919
1548
  listTopAccounts(args = {}) {
1549
+ assertResolverNotHaltedForDataRead(this);
920
1550
  return this._doPaginatedSearch("listTopAccounts", args, "accounts");
921
1551
  }
922
1552
  listTokens(args = {}, ctx) {
1553
+ assertResolverNotHaltedForDataRead(this);
923
1554
  return this._doPaginatedSearch("listTokens", args, "tokens", ["data", "metadata"], ctx);
924
1555
  }
925
1556
  listTokenFactories(args = {}, ctx) {
1557
+ assertResolverNotHaltedForDataRead(this);
926
1558
  return this._doPaginatedSearch("listTokenFactories", args, "tokenFactories", "data", ctx);
927
1559
  }
928
1560
  listStakes(args = {}, ctx) {
1561
+ assertResolverNotHaltedForDataRead(this);
929
1562
  return this._doPaginatedSearch("listStakes", args, "stakes", "data", ctx);
930
1563
  }
931
1564
  listRollups(args = {}, ctx) {
1565
+ assertResolverNotHaltedForDataRead(this);
932
1566
  return this._doPaginatedSearch("listRollups", args, "rollups", "data", ctx);
933
1567
  }
934
1568
  listRollupBlocks(args = {}, ctx) {
1569
+ assertResolverNotHaltedForDataRead(this);
935
1570
  return this._doPaginatedSearch("listRollupBlocks", args, "blocks", "data", ctx);
936
1571
  }
937
1572
  async listRollupValidators(args = {}, ctx) {
1573
+ assertResolverNotHaltedForDataRead(this);
938
1574
  if (!args.rollupAddress) return { validators: [] };
939
1575
  const rollup = await this.statedb.rollup.get(args.rollupAddress);
940
1576
  if (!rollup) return { validators: [] };
@@ -951,9 +1587,11 @@ var OCAPResolver = class {
951
1587
  return result;
952
1588
  }
953
1589
  listDelegations(args = {}, ctx) {
1590
+ assertResolverNotHaltedForDataRead(this);
954
1591
  return this._doPaginatedSearch("listDelegations", args, "delegations", "data", ctx);
955
1592
  }
956
1593
  verifyAccountRisk(args = {}, ctx) {
1594
+ assertResolverNotHaltedForDataRead(this);
957
1595
  if (process.env.TOKEN_FLOW_ENABLED === "true") return require_token_flow.verifyAccountRisk({
958
1596
  ...args,
959
1597
  tokenAddress: (0, _ocap_util.toAddress)(args.tokenAddress || this.config.token.address),
@@ -965,10 +1603,12 @@ var OCAPResolver = class {
965
1603
  return null;
966
1604
  }
967
1605
  listTokenFlows(args = {}, ctx) {
1606
+ assertResolverNotHaltedForDataRead(this);
968
1607
  if (process.env.TOKEN_FLOW_ENABLED === "true") return require_token_flow.listTokenFlows(args, this, ctx);
969
1608
  return [];
970
1609
  }
971
1610
  async search(args) {
1611
+ assertResolverNotHaltedForDataRead(this);
972
1612
  if (!args.keyword) return { results: [] };
973
1613
  const doSearch = async (type, keyword) => {
974
1614
  const result = await this.indexdb[type].get(keyword);
@@ -994,6 +1634,7 @@ var OCAPResolver = class {
994
1634
  return { results: [] };
995
1635
  }
996
1636
  estimateGas(args = {}) {
1637
+ assertResolverNotHaltedForDataRead(this);
997
1638
  const { typeUrl = "" } = args;
998
1639
  if (!typeUrl || !maxGasOps[typeUrl]) throw new _ocap_util_lib_error.CustomError("INVALID_REQUEST", "Unknown tx typeUrl");
999
1640
  const { txGas, maxTxSize } = this.config.transaction;
@@ -1003,15 +1644,25 @@ var OCAPResolver = class {
1003
1644
  totalGas = totalGas.add(new _ocap_util.BN(txGas.price).mul(new _ocap_util.BN(txGas.updateState)).mul(new _ocap_util.BN(estimate.update)));
1004
1645
  return { estimate: { max: totalGas.toString(10) } };
1005
1646
  }
1006
- async shutdown() {
1007
- if (this.queue) {
1008
- this.queue.autostart = false;
1009
- if (this.queue.length > 0) await new Promise((resolve) => {
1010
- this.queue.on("end", resolve);
1647
+ shutdown() {
1648
+ this.isShuttingDown = true;
1649
+ if (!this.shutdownPromise) this.shutdownPromise = (async () => {
1650
+ if (this.inFlightPreFlights > 0) await new Promise((resolve) => {
1651
+ if (this.inFlightPreFlights === 0) resolve();
1652
+ else this.preFlightDrainWaiters.push(resolve);
1011
1653
  });
1012
- }
1654
+ if (this.queue) {
1655
+ this.queue.autostart = false;
1656
+ if (this.queue.length > 0) await new Promise((resolve) => {
1657
+ this.queue.once("end", () => resolve());
1658
+ });
1659
+ }
1660
+ await this.flushIndexWrites();
1661
+ })();
1662
+ return this.shutdownPromise;
1013
1663
  }
1014
1664
  listBlocks() {
1665
+ assertResolverNotHaltedForDataRead(this);
1015
1666
  return { blocks: [] };
1016
1667
  }
1017
1668
  validateTokenConfig() {
@@ -1031,17 +1682,91 @@ var OCAPResolver = class {
1031
1682
  async getToken(id) {
1032
1683
  return this.statedb.token.get(id);
1033
1684
  }
1034
- async initializeStateDB() {
1685
+ async initializeStateDB(options = {}) {
1686
+ if (this.skipInitializeStateDB || this.nodeRuntime && this.nodeRuntime.role !== "validator") return;
1035
1687
  const { accounts, token } = this.config;
1036
1688
  const { account: accountDB, chain: chainDB, token: tokenDB } = this.statedb;
1037
1689
  const { account: accountState, chain: chainState, token: tokenState } = _ocap_state;
1690
+ const rawTime = options.txTime ?? this.config.genesisTime ?? (process.env.CHAIN_GENESIS_TIME || "").trim();
1691
+ const parsedMs = rawTime === void 0 || rawTime === null || rawTime === "" ? NaN : new Date(rawTime).getTime();
1692
+ const isHotStuffBootstrap = this.explicitConsensusMode === "hotstuff" || !this.explicitConsensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(this.nodeRuntime?.getConsensusCommitter?.());
1038
1693
  const context = {
1039
- txTime: (/* @__PURE__ */ new Date()).toISOString(),
1694
+ 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(),
1040
1695
  txHash: ""
1041
1696
  };
1042
- await this.runAsLambda(async (txn) => {
1697
+ const config = (0, lodash_omit.default)(this.config, ["reservedSymbols"]);
1698
+ const role = String(this.config.role || process.env.CHAIN_ROLE || "").trim().toLowerCase();
1699
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
1700
+ const isReadOnlyMode = options.readonly === true || normalizedMode === "readonly" || role === "follower" || role === "standby";
1701
+ const commitGetter = this.statedb.getCommitHash;
1702
+ const hasCommitTracking = typeof commitGetter === "function";
1703
+ if (isReadOnlyMode) {
1704
+ const existingChain$1 = await this.statedb.chain.get(CHAIN_ADDR);
1705
+ if (!existingChain$1) {
1706
+ if (hasCommitTracking) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Read-only/follower StateDB is uninitialized (missing chain state)");
1707
+ return;
1708
+ }
1709
+ if (hasCommitTracking) {
1710
+ const roCommit = await commitGetter.call(this.statedb);
1711
+ const roSeq = Number(roCommit?.seq || 0);
1712
+ if (this.tokenItx) {
1713
+ if (!await this.statedb.token.get(this.tokenItx.address) || roCommit?.msg === "initialize chain") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing official token state)");
1714
+ if (accounts.length > 0 && roSeq <= 2 && roCommit?.msg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing initial accounts)");
1715
+ }
1716
+ }
1717
+ chainState.update(existingChain$1, {
1718
+ ...config,
1719
+ context
1720
+ });
1721
+ return;
1722
+ }
1723
+ let stateCommitSeq = 0;
1724
+ let stateCommitMsg = "";
1725
+ let stateCommitCurrentHash = "GENESIS";
1726
+ if (hasCommitTracking) {
1727
+ const commitInfo = await commitGetter.call(this.statedb);
1728
+ stateCommitSeq = Number(commitInfo?.seq || 0);
1729
+ stateCommitMsg = String(commitInfo?.msg || "");
1730
+ stateCommitCurrentHash = String(commitInfo?.currentHash || "GENESIS");
1731
+ }
1732
+ const isLedgerAnchoredRestart = hasCommitTracking && (stateCommitSeq > 0 || Boolean(stateCommitCurrentHash) && stateCommitCurrentHash !== "GENESIS");
1733
+ if (isLedgerAnchoredRestart && this.tokenItx) {
1734
+ if (stateCommitMsg === "initialize chain") throw new _ocap_util_lib_error.CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after chain initialization before official token state was committed");
1735
+ if (accounts.length > 0 && stateCommitSeq <= 2 && stateCommitMsg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new _ocap_util_lib_error.CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after official token initialization before initial accounts were committed");
1736
+ }
1737
+ const existingChain = await this.statedb.chain.get(CHAIN_ADDR);
1738
+ const normalizeComparable = (val) => {
1739
+ if (val === void 0 || val === null) return null;
1740
+ if (Array.isArray(val)) return val.map(normalizeComparable);
1741
+ if (typeof val === "object") {
1742
+ const out = {};
1743
+ for (const [k, v$1] of Object.entries(val)) if (v$1 !== void 0) out[k] = normalizeComparable(v$1);
1744
+ return out;
1745
+ }
1746
+ return val;
1747
+ };
1748
+ const persistedChainKeys = [
1749
+ "chainId",
1750
+ "version",
1751
+ "transaction",
1752
+ "moderator",
1753
+ "accounts",
1754
+ "token",
1755
+ "vaults"
1756
+ ];
1757
+ const expectedConfig = normalizeComparable((0, lodash_pick.default)(this.config, persistedChainKeys));
1758
+ const needsChainWrite = !existingChain || (0, lodash_isEqual.default)(normalizeComparable((0, lodash_pick.default)(existingChain, persistedChainKeys)), expectedConfig) === false;
1759
+ if (isLedgerAnchoredRestart) {
1760
+ if (!existingChain) throw new _ocap_util_lib_error.CustomError("INTERNAL", "Incomplete genesis StateDB: missing chain state while _state_commit.seq > 0");
1761
+ if (needsChainWrite) {
1762
+ chainState.update(existingChain, {
1763
+ ...config,
1764
+ context
1765
+ });
1766
+ this.logger.info("skipping out-of-band chain state update on ledger-anchored restart to preserve _state_commit parity", { stateCommitSeq });
1767
+ }
1768
+ } else if (needsChainWrite) await this.runAsLambda(async (txn) => {
1043
1769
  const info = await this.statedb.chain.get(CHAIN_ADDR, { txn });
1044
- const config = (0, lodash_omit.default)(this.config, ["reservedSymbols"]);
1045
1770
  if (!info) {
1046
1771
  const state = chainState.create({
1047
1772
  ...config,
@@ -1050,7 +1775,7 @@ var OCAPResolver = class {
1050
1775
  });
1051
1776
  const result = await chainDB.create(CHAIN_ADDR, state, { txn });
1052
1777
  this.logger.debug("create chain state", { result });
1053
- } else if ((0, lodash_isEqual.default)((0, lodash_pick.default)(info, Object.keys(config)), config) === false) {
1778
+ } else if ((0, lodash_isEqual.default)(normalizeComparable((0, lodash_pick.default)(info, persistedChainKeys)), normalizeComparable((0, lodash_pick.default)(config, persistedChainKeys))) === false) {
1054
1779
  const state = chainState.update(info, {
1055
1780
  ...config,
1056
1781
  context
@@ -1060,50 +1785,73 @@ var OCAPResolver = class {
1060
1785
  }
1061
1786
  }, { commitMessage: "initialize chain" });
1062
1787
  if (this.tokenItx) {
1063
- await this.runAsLambda(async (txn) => {
1788
+ const changedKeys = [
1789
+ "icon",
1790
+ "website",
1791
+ "metadata"
1792
+ ];
1793
+ const normalizeTokenMutable = (obj) => ({
1794
+ icon: obj?.icon ? String(obj.icon) : "",
1795
+ website: obj?.website ? String(obj.website) : "",
1796
+ metadata: obj?.metadata === void 0 || obj?.metadata === null ? null : normalizeComparable(obj.metadata)
1797
+ });
1798
+ const expectedTokenShape = tokenState.create(this.tokenItx, context);
1799
+ const preExistToken = await this.statedb.token.get(this.tokenItx.address);
1800
+ const needsTokenWrite = !preExistToken || !(0, lodash_isEqual.default)(normalizeTokenMutable(preExistToken), normalizeTokenMutable(expectedTokenShape));
1801
+ if (isLedgerAnchoredRestart) {
1802
+ if (!preExistToken) throw new _ocap_util_lib_error.CustomError("INTERNAL", `Incomplete genesis StateDB: missing official token state (${this.tokenItx.address}) while _state_commit.seq > 0`);
1803
+ if (needsTokenWrite) {
1804
+ tokenState.update(preExistToken, (0, lodash_pick.default)(this.tokenItx, changedKeys));
1805
+ this.logger.info("skipping out-of-band token metadata update on ledger-anchored restart to preserve _state_commit parity", {
1806
+ address: this.tokenItx.address,
1807
+ stateCommitSeq
1808
+ });
1809
+ }
1810
+ } else if (needsTokenWrite) await this.runAsLambda(async (txn) => {
1064
1811
  const existToken = await this.statedb.token.get(this.tokenItx.address, { txn });
1065
1812
  if (!existToken) {
1066
1813
  const state = tokenState.create(this.tokenItx, context);
1067
1814
  const result = await tokenDB.create(this.tokenItx.address, state, { txn });
1068
1815
  tokenDB.emit("create", result, { txn });
1069
1816
  this.logger.debug("create token state", { address: result?.address });
1070
- } else {
1071
- const changedKeys = [
1072
- "icon",
1073
- "website",
1074
- "metadata"
1075
- ];
1076
- const pickStateToken = (0, lodash_pick.default)(existToken, changedKeys);
1077
- const pickConfigToken = (0, lodash_pick.default)(this.tokenItx, changedKeys);
1078
- if (!(0, lodash_isEqual.default)(pickStateToken, pickConfigToken)) {
1079
- const state = tokenState.update(existToken, pickConfigToken);
1080
- const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1081
- tokenDB.emit("update", result, { txn });
1082
- this.logger.info("update token state", { result });
1083
- }
1817
+ } else if (!(0, lodash_isEqual.default)(normalizeTokenMutable(existToken), normalizeTokenMutable(expectedTokenShape))) {
1818
+ const state = tokenState.update(existToken, (0, lodash_pick.default)(this.tokenItx, changedKeys));
1819
+ const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1820
+ tokenDB.emit("update", result, { txn });
1821
+ this.logger.info("update token state", { result });
1084
1822
  }
1085
1823
  }, { commitMessage: "initialize token" });
1086
- await this.runAsLambda(async (txn) => {
1087
- for (let i = 0; i < accounts.length; i++) {
1088
- const { address, balance, moniker, pk } = accounts[i];
1089
- try {
1090
- if (!await accountDB.get(address, { txn })) {
1091
- const balanceStr = (0, _ocap_util.fromTokenToUnit)(balance ?? 0, token.decimal ?? 18).toString(10);
1092
- const state = accountState.create({
1093
- address,
1094
- tokens: { [this.tokenItx.address]: balanceStr },
1095
- moniker: moniker || "token-holder",
1096
- pk
1097
- }, context);
1098
- const result = await accountDB.create(address, state, { txn });
1099
- accountDB.emit("create", result, { txn });
1100
- this.logger.info("create account done", { address });
1824
+ if (!isLedgerAnchoredRestart) {
1825
+ let needsAccountsWrite = false;
1826
+ if (accounts.length > 0) {
1827
+ for (let i = 0; i < accounts.length; i++) if (!await accountDB.get(accounts[i].address)) {
1828
+ needsAccountsWrite = true;
1829
+ break;
1830
+ }
1831
+ } else if (!existingChain) needsAccountsWrite = true;
1832
+ if (needsAccountsWrite) await this.runAsLambda(async (txn) => {
1833
+ for (let i = 0; i < accounts.length; i++) {
1834
+ const { address, balance, moniker, pk } = accounts[i];
1835
+ try {
1836
+ if (!await accountDB.get(address, { txn })) {
1837
+ const balanceStr = (0, _ocap_util.fromTokenToUnit)(balance ?? 0, token.decimal ?? 18).toString(10);
1838
+ const state = accountState.create({
1839
+ address,
1840
+ tokens: { [this.tokenItx.address]: balanceStr },
1841
+ moniker: moniker || "token-holder",
1842
+ pk
1843
+ }, context);
1844
+ const result = await accountDB.create(address, state, { txn });
1845
+ accountDB.emit("create", result, { txn });
1846
+ this.logger.info("create account done", { address });
1847
+ }
1848
+ } catch (err) {
1849
+ this.logger.error("Failed to initialize initial token holders", err);
1850
+ if (hasCommitTracking) throw err;
1101
1851
  }
1102
- } catch (err) {
1103
- this.logger.error("Failed to initialize initial token holders", err);
1104
1852
  }
1105
- }
1106
- }, { commitMessage: "initialize accounts" });
1853
+ }, { commitMessage: "initialize accounts" });
1854
+ }
1107
1855
  }
1108
1856
  }
1109
1857
  /**
@@ -1144,59 +1892,65 @@ var OCAPResolver = class {
1144
1892
  }
1145
1893
  connectIndexDB() {
1146
1894
  const getToken = this.getToken.bind(this);
1147
- this.statedb.tx.on("create", async (x, ctx) => {
1895
+ this.statedb.tx.on("create", (x, ctx) => {
1148
1896
  if (!ctx) return;
1149
- try {
1150
- const tx = await (0, _ocap_indexdb_lib_util.createIndexedTransaction)(x, ctx, this.indexdb);
1151
- await this.indexdb.tx.insert(tx);
1152
- if (typeof require_hooks.onCreateTx === "function") await require_hooks.onCreateTx(tx, ctx, this);
1153
- } catch (error) {
1154
- this.logger.error("create tx index failed", {
1155
- account: x,
1156
- error
1157
- });
1158
- await this.recordIndexFailure({
1159
- table: "tx",
1160
- event: "create",
1161
- entityId: x?.hash,
1162
- payload: x,
1163
- error
1164
- });
1165
- }
1897
+ this.trackIndexWrite((async () => {
1898
+ try {
1899
+ const tx = await (0, _ocap_indexdb_lib_util.createIndexedTransaction)(x, ctx, this.indexdb);
1900
+ await this.indexdb.tx.insert(tx);
1901
+ if (typeof require_hooks.onCreateTx === "function") await require_hooks.onCreateTx(tx, ctx, this);
1902
+ } catch (error) {
1903
+ this.logger.error("create tx index failed", {
1904
+ account: x,
1905
+ error
1906
+ });
1907
+ await this.recordIndexFailure({
1908
+ table: "tx",
1909
+ event: "create",
1910
+ entityId: x?.hash,
1911
+ payload: x,
1912
+ error
1913
+ });
1914
+ }
1915
+ })());
1166
1916
  });
1167
- this.statedb.account.on("create", async (x) => {
1168
- try {
1169
- await this.indexdb.account.insert(await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1170
- } catch (error) {
1171
- this.logger.error("create account index failed", {
1172
- account: x,
1173
- error
1174
- });
1175
- await this.recordIndexFailure({
1176
- table: "account",
1177
- event: "create",
1178
- entityId: x?.address,
1179
- payload: x,
1180
- error
1181
- });
1182
- }
1917
+ this.statedb.account.on("create", (x) => {
1918
+ this.trackIndexWrite((async () => {
1919
+ try {
1920
+ await this.indexdb.account.insert(await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1921
+ } catch (error) {
1922
+ this.logger.error("create account index failed", {
1923
+ account: x,
1924
+ error
1925
+ });
1926
+ await this.recordIndexFailure({
1927
+ table: "account",
1928
+ event: "create",
1929
+ entityId: x?.address,
1930
+ payload: x,
1931
+ error
1932
+ });
1933
+ }
1934
+ })());
1183
1935
  });
1184
- this.statedb.account.on("update", async (x) => {
1185
- try {
1186
- await this.indexdb.account.update(x.address, await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1187
- } catch (error) {
1188
- this.logger.error("update account index failed", {
1189
- account: x,
1190
- error
1191
- });
1192
- await this.recordIndexFailure({
1193
- table: "account",
1194
- event: "update",
1195
- entityId: x?.address,
1196
- payload: x,
1197
- error
1198
- });
1199
- }
1936
+ this.statedb.account.on("update", (x) => {
1937
+ this.trackIndexWrite((async () => {
1938
+ try {
1939
+ await this.indexdb.account.update(x.address, await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1940
+ } catch (error) {
1941
+ this.logger.error("update account index failed", {
1942
+ account: x,
1943
+ error
1944
+ });
1945
+ await this.recordIndexFailure({
1946
+ table: "account",
1947
+ event: "update",
1948
+ entityId: x?.address,
1949
+ payload: x,
1950
+ error
1951
+ });
1952
+ }
1953
+ })());
1200
1954
  });
1201
1955
  const mapping = {
1202
1956
  asset: [
@@ -1250,45 +2004,49 @@ var OCAPResolver = class {
1250
2004
  };
1251
2005
  Object.keys(mapping).forEach((table) => {
1252
2006
  const [fn, key, onCreate, onUpdate] = mapping[table];
1253
- this.statedb[table].on("create", async (x, _ctx) => {
1254
- try {
1255
- const ctx = this.enrichIndexContext(_ctx);
1256
- const doc = await fn(x, ctx, this.indexdb);
1257
- await this.indexdb[table].insert(doc);
1258
- if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
1259
- } catch (error) {
1260
- this.logger.error(`create ${table} index failed`, {
1261
- [table]: x,
1262
- error
1263
- });
1264
- await this.recordIndexFailure({
1265
- table,
1266
- event: "create",
1267
- entityId: x?.[key],
1268
- payload: x,
1269
- error
1270
- });
1271
- }
2007
+ this.statedb[table].on("create", (x, _ctx) => {
2008
+ this.trackIndexWrite((async () => {
2009
+ try {
2010
+ const ctx = this.enrichIndexContext(_ctx);
2011
+ const doc = await fn(x, ctx, this.indexdb);
2012
+ await this.indexdb[table].insert(doc);
2013
+ if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
2014
+ } catch (error) {
2015
+ this.logger.error(`create ${table} index failed`, {
2016
+ [table]: x,
2017
+ error
2018
+ });
2019
+ await this.recordIndexFailure({
2020
+ table,
2021
+ event: "create",
2022
+ entityId: x?.[key],
2023
+ payload: x,
2024
+ error
2025
+ });
2026
+ }
2027
+ })());
1272
2028
  });
1273
- this.statedb[table].on("update", async (x, _ctx) => {
1274
- try {
1275
- const ctx = this.enrichIndexContext(_ctx);
1276
- const doc = await fn(x, ctx, this.indexdb);
1277
- await this.indexdb[table].update(doc[key], doc);
1278
- if (typeof onUpdate === "function") onUpdate(doc, ctx, this.indexdb, this);
1279
- } catch (error) {
1280
- this.logger.error(`update ${table} index failed`, {
1281
- [table]: x,
1282
- error
1283
- });
1284
- await this.recordIndexFailure({
1285
- table,
1286
- event: "update",
1287
- entityId: x?.[key],
1288
- payload: x,
1289
- error
1290
- });
1291
- }
2029
+ this.statedb[table].on("update", (x, _ctx) => {
2030
+ this.trackIndexWrite((async () => {
2031
+ try {
2032
+ const ctx = this.enrichIndexContext(_ctx);
2033
+ const doc = await fn(x, ctx, this.indexdb);
2034
+ await this.indexdb[table].update(doc[key], doc);
2035
+ if (typeof onUpdate === "function") await onUpdate(doc, ctx, this.indexdb, this);
2036
+ } catch (error) {
2037
+ this.logger.error(`update ${table} index failed`, {
2038
+ [table]: x,
2039
+ error
2040
+ });
2041
+ await this.recordIndexFailure({
2042
+ table,
2043
+ event: "update",
2044
+ entityId: x?.[key],
2045
+ payload: x,
2046
+ error
2047
+ });
2048
+ }
2049
+ })());
1292
2050
  });
1293
2051
  });
1294
2052
  }
@@ -1333,7 +2091,8 @@ var OCAPResolver = class {
1333
2091
  async getReplayTxRollupContext(state) {
1334
2092
  const type = typeof state?.type === "string" ? state.type : "";
1335
2093
  const txType = type ? `fg:t:${type}` : "";
1336
- const address = state?.tx?.itxJson?.rollup;
2094
+ const itxJson = state?.tx?.itxJson;
2095
+ const address = itxJson?.rollup || (type === "create_rollup" ? itxJson?.address : void 0);
1337
2096
  if (typeof address !== "string" || !address) return txType ? { txType } : {};
1338
2097
  const row = await this.statedb.rollup.get(address);
1339
2098
  if (!row) return txType ? { txType } : {};
@@ -1377,9 +2136,9 @@ var OCAPResolver = class {
1377
2136
  };
1378
2137
  const doc$1 = state?.tx && state?.hash && typeof state?.Valid !== "undefined" ? state : await (0, _ocap_indexdb_lib_util.createIndexedTransaction)(state, ctx$1, this.indexdb);
1379
2138
  const existing$1 = await this.indexdb.tx.get(doc$1.hash);
1380
- if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, doc$1);
2139
+ if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, (0, _ocap_indexdb_lib_util.formatTxBeforeInsert)(doc$1));
1381
2140
  else if (!existing$1) await this.indexdb.tx.insert(doc$1);
1382
- else await this.indexdb.tx.update(doc$1.hash, doc$1);
2141
+ else await this.indexdb.tx.update(doc$1.hash, (0, _ocap_indexdb_lib_util.formatTxBeforeInsert)(doc$1));
1383
2142
  if (event === "create" && !existing$1 && typeof require_hooks.onCreateTx === "function") await require_hooks.onCreateTx(doc$1, ctx$1, this);
1384
2143
  return;
1385
2144
  }
@@ -1821,6 +2580,7 @@ var OCAPResolver = class {
1821
2580
  return await this.tokenDistribution.updateByToken(tokenAddress, force);
1822
2581
  }
1823
2582
  async getTokenDistribution(args = {}) {
2583
+ assertResolverNotHaltedForDataRead(this);
1824
2584
  const { tokenAddress = this.config.token.address } = args;
1825
2585
  return await this.tokenDistribution.getDistribution(tokenAddress);
1826
2586
  }
@@ -1908,6 +2668,41 @@ var OCAPResolver = class {
1908
2668
  };
1909
2669
 
1910
2670
  //#endregion
2671
+ exports.ConsensusAbortError = require_hotstuff_runtime.ConsensusAbortError;
2672
+ exports.DEFAULT_FOLLOWER_MAX_SYNC_LAG = require_follower.DEFAULT_FOLLOWER_MAX_SYNC_LAG;
2673
+ exports.DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS = require_follower.DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS;
2674
+ exports.DEFAULT_FOLLOWER_POLL_INTERVAL_MS = require_follower.DEFAULT_FOLLOWER_POLL_INTERVAL_MS;
2675
+ exports.FollowerSyncService = require_follower.FollowerSyncService;
2676
+ exports.GRAPHQL_INDEXED_TX_COLUMNS = GRAPHQL_INDEXED_TX_COLUMNS;
2677
+ exports.HotStuffNodeRuntime = require_hotstuff_runtime.HotStuffNodeRuntime;
2678
+ exports.LedgerEntryReplayer = require_replayer.LedgerEntryReplayer;
2679
+ exports.MAX_BLOCKED_ACCOUNTS = require_node_preferences.MAX_BLOCKED_ACCOUNTS;
2680
+ exports.MAX_CONFIG_BODY_BYTES = require_node_preferences.MAX_CONFIG_BODY_BYTES;
2681
+ exports.MAX_MEMO_LENGTH = require_node_preferences.MAX_MEMO_LENGTH;
2682
+ exports.MAX_PEER_URLS = require_node_preferences.MAX_PEER_URLS;
2683
+ exports.MAX_RESERVED_SYMBOLS = require_node_preferences.MAX_RESERVED_SYMBOLS;
2684
+ exports.MAX_TRUSTED_ACCOUNTS = require_node_preferences.MAX_TRUSTED_ACCOUNTS;
2685
+ exports.NodePreferencesError = require_node_preferences.NodePreferencesError;
2686
+ exports.NodePreferencesManager = require_node_preferences.NodePreferencesManager;
2687
+ exports.UNIFIED_CONSOLE_APP_JS = require_dashboard.UNIFIED_CONSOLE_APP_JS;
2688
+ exports.applyBootRuntimePreferences = require_node_preferences.applyBootRuntimePreferences;
2689
+ exports.buildUnifiedConsoleHtml = require_dashboard.buildUnifiedConsoleHtml;
2690
+ exports.collectLedgerHealthSummary = require_dashboard.collectLedgerHealthSummary;
2691
+ exports.createAdminAuthGuard = require_node_preferences.createAdminAuthGuard;
2692
+ exports.createExplorerMiddleware = require_explorer.createExplorerMiddleware;
2693
+ exports.createFollowerPeerFetchGuard = require_node_preferences.createFollowerPeerFetchGuard;
2694
+ exports.createNodeDashboardRouter = require_dashboard.createNodeDashboardRouter;
2695
+ exports.createNodeMaintenanceController = require_dashboard.createNodeMaintenanceController;
2696
+ exports.createUnifiedConsoleMiddleware = require_dashboard.createUnifiedConsoleMiddleware;
1911
2697
  exports.default = OCAPResolver;
1912
2698
  exports.formatData = formatData;
1913
- exports.formatDelegationOps = formatDelegationOps;
2699
+ exports.formatDelegationOps = formatDelegationOps;
2700
+ exports.isDashboardEnabled = require_dashboard.isDashboardEnabled;
2701
+ exports.isExplorerEnabled = require_explorer.isExplorerEnabled;
2702
+ exports.isPrivateOrReservedIpAddress = require_node_preferences.isPrivateOrReservedIpAddress;
2703
+ exports.isTransientSqliteLockError = require_follower.isTransientSqliteLockError;
2704
+ exports.isValidAccountAddressCandidate = require_node_preferences.isValidAccountAddressCandidate;
2705
+ exports.loadNodePreferences = require_node_preferences.loadNodePreferences;
2706
+ exports.normalizeBlockedAccountKey = require_node_preferences.normalizeBlockedAccountKey;
2707
+ exports.timingSafeTokenEqual = require_node_preferences.timingSafeTokenEqual;
2708
+ exports.validateFollowerPeerUrls = require_node_preferences.validateFollowerPeerUrls;