beignet 0.36.0 → 0.37.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 (153) hide show
  1. package/README.md +13 -6
  2. package/dist/cli/beignet-node.js +1073 -33
  3. package/dist/cli/beignet-node.js.map +1 -1
  4. package/dist/cli/cli.js +149 -42
  5. package/dist/cli/cli.js.map +1 -1
  6. package/dist/cli/daemon.js +93 -14
  7. package/dist/cli/daemon.js.map +1 -1
  8. package/dist/cli/errors.js +10 -0
  9. package/dist/cli/errors.js.map +1 -1
  10. package/dist/cli/offline-receive.js +146 -30
  11. package/dist/cli/offline-receive.js.map +1 -1
  12. package/dist/cli/openapi.js +424 -21
  13. package/dist/cli/openapi.js.map +1 -1
  14. package/dist/cli/receive-steering.js +210 -0
  15. package/dist/cli/receive-steering.js.map +1 -0
  16. package/dist/cli/routes.js +22 -0
  17. package/dist/cli/routes.js.map +1 -1
  18. package/dist/direct-funding/bitcoin-core.js +548 -0
  19. package/dist/direct-funding/bitcoin-core.js.map +1 -0
  20. package/dist/direct-funding/client.js +257 -0
  21. package/dist/direct-funding/client.js.map +1 -0
  22. package/dist/direct-funding/index.js +47 -0
  23. package/dist/direct-funding/index.js.map +1 -0
  24. package/dist/direct-funding/node.js +119 -0
  25. package/dist/direct-funding/node.js.map +1 -0
  26. package/dist/direct-funding/peer-messaging.js +359 -0
  27. package/dist/direct-funding/peer-messaging.js.map +1 -0
  28. package/dist/direct-funding/psbt.js +282 -0
  29. package/dist/direct-funding/psbt.js.map +1 -0
  30. package/dist/direct-funding/transports.js +77 -0
  31. package/dist/direct-funding/transports.js.map +1 -0
  32. package/dist/lightning/chain/hashes.js +13 -0
  33. package/dist/lightning/chain/hashes.js.map +1 -0
  34. package/dist/lightning/channel/channel-actions.js +1 -0
  35. package/dist/lightning/channel/channel-actions.js.map +1 -1
  36. package/dist/lightning/channel/channel-manager.js +132 -12
  37. package/dist/lightning/channel/channel-manager.js.map +1 -1
  38. package/dist/lightning/channel/channel-state.js.map +1 -1
  39. package/dist/lightning/channel/channel.js +471 -29
  40. package/dist/lightning/channel/channel.js.map +1 -1
  41. package/dist/lightning/channel/composite-splice-record.js +140 -0
  42. package/dist/lightning/channel/composite-splice-record.js.map +1 -0
  43. package/dist/lightning/channel/index.js +1 -0
  44. package/dist/lightning/channel/index.js.map +1 -1
  45. package/dist/lightning/channel/splice-weight.js +2 -0
  46. package/dist/lightning/channel/splice-weight.js.map +1 -1
  47. package/dist/lightning/channel/types.js +5 -8
  48. package/dist/lightning/channel/types.js.map +1 -1
  49. package/dist/lightning/direct-funding/receiver/engine.js +5 -2
  50. package/dist/lightning/direct-funding/receiver/engine.js.map +1 -1
  51. package/dist/lightning/direct-funding/receiver/types.js.map +1 -1
  52. package/dist/lightning/direct-funding/requests.js +20 -1
  53. package/dist/lightning/direct-funding/requests.js.map +1 -1
  54. package/dist/lightning/direct-funding/sender/engine.js +25 -2
  55. package/dist/lightning/direct-funding/sender/engine.js.map +1 -1
  56. package/dist/lightning/direct-funding/types.js +5 -5
  57. package/dist/lightning/direct-funding/types.js.map +1 -1
  58. package/dist/lightning/features/flags.js +16 -2
  59. package/dist/lightning/features/flags.js.map +1 -1
  60. package/dist/lightning/gossip/network-graph.js +30 -9
  61. package/dist/lightning/gossip/network-graph.js.map +1 -1
  62. package/dist/lightning/gossip/pathfinding.js +117 -2
  63. package/dist/lightning/gossip/pathfinding.js.map +1 -1
  64. package/dist/lightning/gossip/types.js +3 -1
  65. package/dist/lightning/gossip/types.js.map +1 -1
  66. package/dist/lightning/liquidity/index.js +10 -1
  67. package/dist/lightning/liquidity/index.js.map +1 -1
  68. package/dist/lightning/liquidity/primaries.js +274 -0
  69. package/dist/lightning/liquidity/primaries.js.map +1 -0
  70. package/dist/lightning/node/composite-splice-engine.js +1278 -0
  71. package/dist/lightning/node/composite-splice-engine.js.map +1 -0
  72. package/dist/lightning/node/index.js +1 -0
  73. package/dist/lightning/node/index.js.map +1 -1
  74. package/dist/lightning/node/lightning-node.js +412 -45
  75. package/dist/lightning/node/lightning-node.js.map +1 -1
  76. package/dist/lightning/node/types.js.map +1 -1
  77. package/dist/lightning/recovery/capsule.js +30 -0
  78. package/dist/lightning/recovery/capsule.js.map +1 -1
  79. package/dist/lightning/recovery/frame-codec.js +78 -16
  80. package/dist/lightning/recovery/frame-codec.js.map +1 -1
  81. package/dist/lightning/recovery/guardian-replication.js +92 -21
  82. package/dist/lightning/recovery/guardian-replication.js.map +1 -1
  83. package/dist/lightning/recovery/journal.js +85 -7
  84. package/dist/lightning/recovery/journal.js.map +1 -1
  85. package/dist/lightning/recovery/recovery-manager.js +5 -0
  86. package/dist/lightning/recovery/recovery-manager.js.map +1 -1
  87. package/dist/lightning/recovery/types.js.map +1 -1
  88. package/dist/lightning/storage/add-onion.js +63 -0
  89. package/dist/lightning/storage/add-onion.js.map +1 -0
  90. package/dist/lightning/storage/capabilities.js +6 -0
  91. package/dist/lightning/storage/capabilities.js.map +1 -1
  92. package/dist/lightning/storage/conformance.js +64 -0
  93. package/dist/lightning/storage/conformance.js.map +1 -1
  94. package/dist/lightning/storage/memory-storage.js +26 -0
  95. package/dist/lightning/storage/memory-storage.js.map +1 -1
  96. package/dist/lightning/storage/serialization.js +22 -5
  97. package/dist/lightning/storage/serialization.js.map +1 -1
  98. package/dist/lightning/storage/sqlite-storage.js +37 -1
  99. package/dist/lightning/storage/sqlite-storage.js.map +1 -1
  100. package/dist/lightning/storage/types.js.map +1 -1
  101. package/dist/types/cli/beignet-node.d.ts +272 -15
  102. package/dist/types/cli/errors.d.ts +7 -0
  103. package/dist/types/cli/offline-receive.d.ts +55 -9
  104. package/dist/types/cli/receive-steering.d.ts +135 -0
  105. package/dist/types/cli/routes.d.ts +41 -0
  106. package/dist/types/cli/types.d.ts +164 -3
  107. package/dist/types/direct-funding/bitcoin-core.d.ts +78 -0
  108. package/dist/types/direct-funding/client.d.ts +64 -0
  109. package/dist/types/direct-funding/index.d.ts +18 -0
  110. package/dist/types/direct-funding/node.d.ts +22 -0
  111. package/dist/types/direct-funding/peer-messaging.d.ts +74 -0
  112. package/dist/types/direct-funding/psbt.d.ts +27 -0
  113. package/dist/types/direct-funding/transports.d.ts +14 -0
  114. package/dist/types/lightning/chain/hashes.d.ts +11 -0
  115. package/dist/types/lightning/channel/channel-actions.d.ts +19 -2
  116. package/dist/types/lightning/channel/channel-manager.d.ts +37 -1
  117. package/dist/types/lightning/channel/channel-state.d.ts +21 -0
  118. package/dist/types/lightning/channel/channel.d.ts +106 -1
  119. package/dist/types/lightning/channel/composite-splice-record.d.ts +91 -0
  120. package/dist/types/lightning/channel/events.d.ts +9 -0
  121. package/dist/types/lightning/channel/index.d.ts +1 -0
  122. package/dist/types/lightning/channel/splice-weight.d.ts +13 -0
  123. package/dist/types/lightning/channel/types.d.ts +1 -8
  124. package/dist/types/lightning/direct-funding/receiver/types.d.ts +4 -1
  125. package/dist/types/lightning/direct-funding/requests.d.ts +1 -0
  126. package/dist/types/lightning/direct-funding/sender/engine.d.ts +11 -0
  127. package/dist/types/lightning/direct-funding/types.d.ts +9 -0
  128. package/dist/types/lightning/features/flags.d.ts +13 -1
  129. package/dist/types/lightning/gossip/network-graph.d.ts +8 -6
  130. package/dist/types/lightning/gossip/pathfinding.d.ts +8 -0
  131. package/dist/types/lightning/gossip/types.d.ts +2 -0
  132. package/dist/types/lightning/liquidity/index.d.ts +2 -0
  133. package/dist/types/lightning/liquidity/primaries.d.ts +127 -0
  134. package/dist/types/lightning/node/composite-splice-engine.d.ts +258 -0
  135. package/dist/types/lightning/node/events.d.ts +19 -1
  136. package/dist/types/lightning/node/index.d.ts +1 -0
  137. package/dist/types/lightning/node/lightning-node.d.ts +138 -4
  138. package/dist/types/lightning/node/types.d.ts +4 -1
  139. package/dist/types/lightning/recovery/capsule.d.ts +0 -10
  140. package/dist/types/lightning/recovery/guardian-replication.d.ts +32 -5
  141. package/dist/types/lightning/recovery/journal.d.ts +19 -0
  142. package/dist/types/lightning/recovery/types.d.ts +11 -1
  143. package/dist/types/lightning/storage/add-onion.d.ts +18 -0
  144. package/dist/types/lightning/storage/memory-storage.d.ts +7 -0
  145. package/dist/types/lightning/storage/serialization.d.ts +14 -0
  146. package/dist/types/lightning/storage/sqlite-storage.d.ts +6 -1
  147. package/dist/types/lightning/storage/types.d.ts +17 -1
  148. package/docs/AUTOMATIC-OFFLINE-RECEIVE.md +33 -9
  149. package/docs/MPP-SENDING.md +30 -0
  150. package/docs/MULTI-CHANNEL-SPLICE-OUT.md +622 -0
  151. package/docs/README.md +3 -0
  152. package/docs/RECOVERY-PROTOCOL.md +4 -1
  153. package/package.json +20 -4
@@ -30,7 +30,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
30
30
  return result;
31
31
  };
32
32
  Object.defineProperty(exports, "__esModule", { value: true });
33
- exports.BeignetNode = exports.jitInvoiceError = exports.holdInvoiceEvent = exports.jsonSafeEvent = exports.jitReceiveRefusal = exports.leaseRatesRefusal = exports.defaultMaxFeeMsat = exports.DEFAULT_MAX_FEE_FLOOR_SATS = exports.DEFAULT_MAX_FEE_PPM = exports.clampDirectFundingMinimum = exports.DAILY_SPEND_STATE_KEY = exports.MAX_ASYNC_SPEND_CLAIMS = exports.ASYNC_SPEND_CLAIM_TTL_MS = exports.jsonToRouteHops = exports.routeHopsToJson = exports.spliceRefusalError = exports.decodeOfferInput = exports.paymentAdmissionSats = exports.paymentSpendSats = exports.hopFeeMsat = exports.spendLimitSats = exports.decodeInvoiceInput = exports.ENGINE_PAYMENT_ERROR_CODES = exports.parseScid = exports.formatScid = exports.gossipPrimeLatch = exports.defaultDataDirForMnemonic = exports.parseRecoveryMode = void 0;
33
+ exports.BeignetNode = exports.jitInvoiceError = exports.holdInvoiceEvent = exports.jsonSafeEvent = exports.jitReceiveRefusal = exports.leaseRatesRefusal = exports.defaultMaxFeeMsat = exports.DEFAULT_MAX_FEE_FLOOR_SATS = exports.DEFAULT_MAX_FEE_PPM = exports.clampDirectFundingMinimum = exports.DAILY_SPEND_STATE_KEY = exports.MAX_ASYNC_SPEND_CLAIMS = exports.ASYNC_SPEND_CLAIM_TTL_MS = exports.jsonToRouteHops = exports.routeHopsToJson = exports.spliceRefusalError = exports.compositeSpliceRefusalError = exports.CHANNEL_SEND_QUOTE_TTL_MS = exports.decodeOfferInput = exports.paymentAdmissionSats = exports.paymentSpendSats = exports.hopFeeMsat = exports.spendLimitSats = exports.decodeInvoiceInput = exports.ENGINE_PAYMENT_ERROR_CODES = exports.parseScid = exports.formatScid = exports.gossipPrimeLatch = exports.defaultDataDirForMnemonic = exports.parseRecoveryMode = void 0;
34
34
  const iroh_config_1 = require("./iroh-config");
35
35
  const electrum_tls_config_1 = require("./electrum-tls-config");
36
36
  const iroh_node_1 = require("../lightning/transport/iroh-node");
@@ -66,6 +66,8 @@ const splice_1 = require("../lightning/message/splice");
66
66
  const types_3 = require("../lightning/ffor/types");
67
67
  const messages_1 = require("../lightning/ffor/messages");
68
68
  const splice_weight_1 = require("../lightning/channel/splice-weight");
69
+ const composite_splice_engine_1 = require("../lightning/node/composite-splice-engine");
70
+ const composite_splice_record_1 = require("../lightning/channel/composite-splice-record");
69
71
  const l402_1 = require("../lightning/l402");
70
72
  const validation_1 = require("../lightning/validation");
71
73
  const wallet_funding_provider_1 = require("../lightning/wallet/wallet-funding-provider");
@@ -85,6 +87,8 @@ const jit_receive_1 = require("../lightning/liquidity/jit-receive");
85
87
  const peer_uri_1 = require("../lightning/transport/peer-uri");
86
88
  const ecdh_1 = require("../lightning/crypto/ecdh");
87
89
  const direct_funding_1 = require("../lightning/direct-funding");
90
+ const primaries_1 = require("../lightning/liquidity/primaries");
91
+ const receive_steering_1 = require("./receive-steering");
88
92
  const direct_funding_2 = require("./direct-funding");
89
93
  const daemon_state_keys_1 = require("./daemon-state-keys");
90
94
  const types_6 = require("../lightning/node/types");
@@ -451,6 +455,35 @@ const SPLICE_REFUSAL_CODES = {
451
455
  [types_6.SpliceRefusalCode.SPLICE_BUSY]: errors_1.BeignetErrorCode.SPLICE_BUSY,
452
456
  [types_6.SpliceRefusalCode.SPLICE_REFUSED]: errors_1.BeignetErrorCode.SPLICE_REFUSED
453
457
  };
458
+ /** How long a channel send quote (issue #1922) can be executed. */
459
+ exports.CHANNEL_SEND_QUOTE_TTL_MS = 2 * 60000;
460
+ /** The most an operator's abort reason may carry; it travels in tx_abort. */
461
+ const CHANNEL_SEND_ABORT_REASON_MAX_BYTES = 1024;
462
+ const COMPOSITE_REFUSAL_CODES = {
463
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.INVALID_PARAMS]: errors_1.BeignetErrorCode.INVALID_PARAMS,
464
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.BUSY]: errors_1.BeignetErrorCode.SPLICE_BUSY,
465
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.STORAGE_REQUIRED]: errors_1.BeignetErrorCode.NOT_PERSISTED,
466
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.CHANNEL_NOT_FOUND]: errors_1.BeignetErrorCode.CHANNEL_NOT_FOUND,
467
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.NO_ELIGIBLE_CHANNELS]: errors_1.BeignetErrorCode.SPLICE_REFUSED,
468
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.INSUFFICIENT_BALANCE]: errors_1.BeignetErrorCode.INSUFFICIENT_BALANCE,
469
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.SINGLE_CHANNEL_SUFFICES]: errors_1.BeignetErrorCode.SPLICE_REFUSED,
470
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.NOT_FOUND]: errors_1.BeignetErrorCode.NOT_FOUND,
471
+ [composite_splice_engine_1.CompositeSpliceRefusalCode.TOO_LATE]: errors_1.BeignetErrorCode.SPLICE_REFUSED
472
+ };
473
+ /**
474
+ * A composite splice refusal as the BeignetError the daemon answers with: the
475
+ * engine's code mapped to the error code's status, and the per-channel
476
+ * reasons, when any, appended to the message so a client knows what to fix.
477
+ */
478
+ function compositeSpliceRefusalError(refusal) {
479
+ const skipped = refusal.skipped?.length
480
+ ? `; skipped: ${refusal.skipped
481
+ .map((c) => `${c.channelId.toString('hex').slice(0, 12)}: ${c.reason}`)
482
+ .join(', ')}`
483
+ : '';
484
+ return new errors_1.BeignetError(COMPOSITE_REFUSAL_CODES[refusal.code] ?? errors_1.BeignetErrorCode.SPLICE_REFUSED, `${refusal.error}${skipped}`);
485
+ }
486
+ exports.compositeSpliceRefusalError = compositeSpliceRefusalError;
454
487
  /**
455
488
  * A refusing SpliceResult as the error the daemon answers with, or null for a
456
489
  * splice that started. An untyped refusal (an older engine, a code this build
@@ -649,6 +682,19 @@ function requirePositiveSafeInteger(value, field) {
649
682
  }
650
683
  return value;
651
684
  }
685
+ /**
686
+ * Refuse an `lspPubkey` option that is not a compressed public key. The type
687
+ * is checked before the pattern: a regex alone reads an array holding one
688
+ * key as its string form and passes it, and the first `.toLowerCase()` on it
689
+ * then surfaces as a server error instead of INVALID_PARAMS.
690
+ */
691
+ function checkLspPubkey(value) {
692
+ if (value === undefined)
693
+ return;
694
+ if (typeof value !== 'string' || !/^0[23][0-9a-fA-F]{64}$/.test(value)) {
695
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'lspPubkey must be a 33-byte compressed public key (66 hex chars)');
696
+ }
697
+ }
652
698
  /**
653
699
  * A satoshi amount that may legitimately be nothing: a fee ceiling of zero
654
700
  * ("route for free or fail"), an invoice with no amount, a push of nothing.
@@ -1132,6 +1178,8 @@ function listenerLabel(kind) {
1132
1178
  ? 'Iroh listener'
1133
1179
  : 'WebSocket listener';
1134
1180
  }
1181
+ /** How long `connectPeer` waits for a dial unless `connectTimeoutMs` says otherwise. */
1182
+ const DEFAULT_CONNECT_TIMEOUT_MS = 15000;
1135
1183
  class BeignetNode extends typed_emitter_1.TypedEmitter {
1136
1184
  getOfflineReceive() {
1137
1185
  if (!this.offlineReceive)
@@ -1280,7 +1328,7 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
1280
1328
  * the node down), so an attempt that outlived its node records nothing.
1281
1329
  */
1282
1330
  this._listenEpoch = 0;
1283
- this._connectTimeoutMs = 15000;
1331
+ this._connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT_MS;
1284
1332
  // The daily ledger (issue #977). _dailySpentSats is the combined LN +
1285
1333
  // onchain total; the two source counters below only feed the
1286
1334
  // GET /spend-limit breakdown. Every field down to _asyncSpendClaims is
@@ -2384,6 +2432,9 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
2384
2432
  : undefined;
2385
2433
  this.log('info', 'Splice complete', { channelId, fundingTxid });
2386
2434
  this.emit('splice:complete', { channelId, fundingTxid });
2435
+ this._onSingleChannelSendSpliceEvent(channelId, 'LOCKED', {
2436
+ txid: fundingTxid
2437
+ });
2387
2438
  });
2388
2439
  // The rest of the splice lifecycle (issue #760): an abort, a conflict
2389
2440
  // verdict on an input the splice carried, and the revert that settles
@@ -2393,7 +2444,14 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
2393
2444
  const channelId = data.channelId.toString('hex');
2394
2445
  this.log('info', 'Splice aborted', { channelId, reason: data.reason });
2395
2446
  this.emit('splice:aborted', { channelId, reason: data.reason });
2447
+ this._onSingleChannelSendSpliceEvent(channelId, 'ABORTED', {
2448
+ reason: data.reason
2449
+ });
2396
2450
  });
2451
+ // A composite channel send (issue #1922): its stages drive the spend
2452
+ // reservation (charged at RELEASED, released at ABORTED) and are
2453
+ // relayed as channel-send:stage under the quote id.
2454
+ this.node.on('composite-splice:stage', (event) => this._onCompositeSpliceStage(event));
2397
2455
  this.node.on('splice:conflicted', (data) => {
2398
2456
  const channelId = data.channelId.toString('hex');
2399
2457
  this.log('warn', 'Splice cannot confirm: an input was spent elsewhere; asking the peer to revert', {
@@ -2540,6 +2598,20 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
2540
2598
  outChannelId: data.outChannelId.toString('hex')
2541
2599
  });
2542
2600
  });
2601
+ this.node.on('htlc:forward-refused', (data) => {
2602
+ const info = {
2603
+ inChannelId: data.inChannelId.toString('hex'),
2604
+ outChannelId: data.outChannelId.toString('hex'),
2605
+ amountMsat: data.amountMsat.toString(),
2606
+ paymentHash: data.paymentHash.toString('hex'),
2607
+ reason: data.reason,
2608
+ ...(data.channelErrorCode !== undefined
2609
+ ? { channelErrorCode: data.channelErrorCode }
2610
+ : {})
2611
+ };
2612
+ this.log('info', 'HTLC forward refused', info);
2613
+ this.emit('htlc:forward-refused', info);
2614
+ });
2543
2615
  this.node.on('htlc:fulfilled', (data) => {
2544
2616
  this.emit('htlc:fulfilled', {
2545
2617
  channelId: data.channelId.toString('hex'),
@@ -2627,6 +2699,14 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
2627
2699
  this.log('warn', 'Peer error', { pubkey, error: err.message });
2628
2700
  this.emit('peer:error', { pubkey, message: err.message });
2629
2701
  });
2702
+ // The engine logs it already, through the same logger.
2703
+ this.node.on('peer:warning', ({ pubkey, channelId, text }) => {
2704
+ this.emit('peer:warning', {
2705
+ pubkey,
2706
+ channelId: channelId ? channelId.toString('hex') : null,
2707
+ text
2708
+ });
2709
+ });
2630
2710
  // Forward node:ready event
2631
2711
  this.node.on('node:ready', () => {
2632
2712
  this.log('info', 'Node ready');
@@ -3117,21 +3197,31 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
3117
3197
  * A guardian that refuses a record as too large, or because its quota
3118
3198
  * is full, can take nothing after it, so in quorum mode the node stops
3119
3199
  * releasing channel updates and in async mode its backup stops
3120
- * advancing. Neither shows up anywhere else.
3200
+ * advancing. One that advertises a record limit below the floor is sent
3201
+ * nothing at all (issue #1954). None of these shows up anywhere else.
3121
3202
  */
3122
3203
  relayRecordTooLarge(event) {
3123
- if (event.type !== 'record:too-large' &&
3124
- event.type !== 'record:quota-refused') {
3204
+ const relayed = {
3205
+ 'record:too-large': [
3206
+ 'Recovery guardian refused an oversized record',
3207
+ 'RECOVERY_RECORD_TOO_LARGE'
3208
+ ],
3209
+ 'record:quota-refused': [
3210
+ 'Recovery guardian refused a record: its quota is full',
3211
+ 'RECOVERY_GUARDIAN_QUOTA_EXCEEDED'
3212
+ ],
3213
+ 'record:limit-too-small': [
3214
+ 'Recovery guardian refused: its record limit is too small for this node',
3215
+ 'RECOVERY_GUARDIAN_LIMIT_TOO_SMALL'
3216
+ ]
3217
+ };
3218
+ const entry = relayed[event.type];
3219
+ if (!entry)
3125
3220
  return;
3126
- }
3127
- const tooLarge = event.type === 'record:too-large';
3128
- this.log('error', tooLarge
3129
- ? 'Recovery guardian refused an oversized record'
3130
- : 'Recovery guardian refused a record: its quota is full', { detail: event.detail });
3221
+ const [message, code] = entry;
3222
+ this.log('error', message, { detail: event.detail });
3131
3223
  const data = {
3132
- code: tooLarge
3133
- ? 'RECOVERY_RECORD_TOO_LARGE'
3134
- : 'RECOVERY_GUARDIAN_QUOTA_EXCEEDED',
3224
+ code,
3135
3225
  message: event.detail,
3136
3226
  timestamp: Date.now()
3137
3227
  };
@@ -5903,6 +5993,14 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
5903
5993
  }
5904
5994
  // ─────────────── Peers ───────────────
5905
5995
  async connectPeer(pubkey, host, port, transport) {
5996
+ return this.connectPeerWithin(pubkey, host, port, transport, this._connectTimeoutMs);
5997
+ }
5998
+ /**
5999
+ * `connectPeer` under a caller's own deadline. A steered receive passes
6000
+ * what its budget allows for this one dial; the public method passes the
6001
+ * node's connect timeout.
6002
+ */
6003
+ async connectPeerWithin(pubkey, host, port, transport, timeoutMs) {
5906
6004
  // listPeers reports the lowercase key the node registers the peer under.
5907
6005
  pubkey = (0, validation_1.normalizeHexPubkey)(pubkey);
5908
6006
  // Where we are dialing, for error messages: explicit host:port, or the
@@ -5915,7 +6013,7 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
5915
6013
  let timer;
5916
6014
  const connectPromise = this.node.connectPeer(pubkey, host, port, transport);
5917
6015
  const timeoutPromise = new Promise((_, reject) => {
5918
- timer = setTimeout(() => reject(new errors_1.BeignetError('CONNECT_TIMEOUT', `connectPeer timed out after ${this._connectTimeoutMs}ms (is ${target} the peer's P2P address?)`)), this._connectTimeoutMs);
6016
+ timer = setTimeout(() => reject(new errors_1.BeignetError('CONNECT_TIMEOUT', `connectPeer timed out after ${timeoutMs}ms (is ${target} the peer's P2P address?)`)), timeoutMs);
5919
6017
  });
5920
6018
  try {
5921
6019
  await Promise.race([connectPromise, timeoutPromise]);
@@ -5962,6 +6060,23 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
5962
6060
  ...(p.iroh ? { iroh: p.iroh } : {})
5963
6061
  }));
5964
6062
  }
6063
+ /**
6064
+ * The address this node last dialed a peer at, if it ever did, in this run
6065
+ * or an earlier one (the last successful dial is persisted), and the
6066
+ * transport it used. A peer that only ever connected inbound has none:
6067
+ * `listPeers` then shows the far end of its socket, whose port is
6068
+ * ephemeral, so this is what to consult for an address others can dial.
6069
+ */
6070
+ getPeerAddress(pubkey) {
6071
+ const addr = this.node.getPeerAddress(pubkey);
6072
+ if (!addr)
6073
+ return undefined;
6074
+ return {
6075
+ host: addr.host,
6076
+ port: addr.port,
6077
+ ...(addr.transport ? { transport: addr.transport.type } : {})
6078
+ };
6079
+ }
5965
6080
  /**
5966
6081
  * Start a p2p gossip sync with one peer, logging rather than throwing on
5967
6082
  * failure. The automatic connect-time path routes through here, deferred
@@ -7132,11 +7247,19 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7132
7247
  * Needs the LSP peer connected and running the JIT receive engine. A
7133
7248
  * declined, timed-out or over-priced intent throws, and no invoice is
7134
7249
  * created: nothing then carries an allowance for a fee nobody agreed.
7250
+ *
7251
+ * With no `lspPubkey` the receive is steered through the ranked primaries
7252
+ * (issue #1922): each is tried in `listPrimaries` selection order, dialed
7253
+ * by its stored address when it is not connected, and passed over when
7254
+ * it is unreachable, times out, declines, quotes above the ceilings, or
7255
+ * is fenced by NEW_CHANNELS_REFUSED. One budget bounds the whole walk.
7256
+ * NO_PRIMARY_AVAILABLE names every primary's reason when none takes it;
7257
+ * INVALID_PARAMS when none is configured. Passing over a primary is safe
7258
+ * because the invoice is minted only after an LSP's ack: an intent that
7259
+ * timed out there expires on its own and is never advertised.
7135
7260
  */
7136
7261
  async createJitInvoice(opts) {
7137
- if (!/^0[23][0-9a-fA-F]{64}$/.test(opts.lspPubkey)) {
7138
- throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'lspPubkey must be a 33-byte compressed public key (66 hex chars)');
7139
- }
7262
+ checkLspPubkey(opts.lspPubkey);
7140
7263
  if (opts.feeMode !== undefined &&
7141
7264
  opts.feeMode !== 'skim' &&
7142
7265
  opts.feeMode !== 'hop') {
@@ -7151,10 +7274,85 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7151
7274
  if (opts.expirySecs !== undefined)
7152
7275
  requireInvoiceExpiry(opts.expirySecs, 'expirySecs');
7153
7276
  requireInvoiceDescription(opts.description);
7277
+ if (opts.lspPubkey !== undefined) {
7278
+ return this.jitInvoiceAt(opts.lspPubkey, opts, amountMsat);
7279
+ }
7280
+ const budgetMs = this.steerBudget(opts.timeoutMs);
7281
+ const { value, skipped } = await (0, receive_steering_1.steerReceive)({
7282
+ candidates: this.receiveCandidates(),
7283
+ isConnected: (pubkey) => this.isPeerConnected(pubkey),
7284
+ connect: (candidate, timeoutMs) => this.dialPrimary(candidate, timeoutMs),
7285
+ attempt: (candidate, timeoutMs) => this.jitInvoiceAt(candidate.pubkey, opts, amountMsat, timeoutMs),
7286
+ candidateCodes: receive_steering_1.JIT_STEER_CODES,
7287
+ budgetMs,
7288
+ lastConnectCapMs: this._connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
7289
+ onSkip: (skip) => this.logSteerSkip('JIT invoice', skip)
7290
+ });
7291
+ return skipped.length ? { ...value, skipped } : value;
7292
+ }
7293
+ /**
7294
+ * The budget a steered receive walks under: the caller's, else the
7295
+ * default that fits inside a 20 s client timeout.
7296
+ */
7297
+ steerBudget(timeoutMs) {
7298
+ if (timeoutMs === undefined)
7299
+ return receive_steering_1.STEER_BUDGET_MS;
7300
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
7301
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'timeoutMs must be a positive whole number of milliseconds');
7302
+ }
7303
+ return timeoutMs;
7304
+ }
7305
+ logSteerSkip(what, skip) {
7306
+ this.log('info', `${what}: passed over primary ${skip.pubkey.slice(0, 16)}`, {
7307
+ rank: skip.rank,
7308
+ stage: skip.stage,
7309
+ code: skip.code,
7310
+ message: skip.message
7311
+ });
7312
+ }
7313
+ /** Whether the node has this peer up, init exchanged or at least transport up. */
7314
+ isPeerConnected(pubkey) {
7315
+ return this.listPeers().some((p) => p.pubkey === pubkey && (p.state === 'ready' || p.state === 'connected'));
7316
+ }
7317
+ /**
7318
+ * The ranked primaries in the order a receive tries them, each with the
7319
+ * address it was configured with, for the dial. INVALID_PARAMS when none
7320
+ * is configured: a wallet without a policy names its peer, as before.
7321
+ */
7322
+ receiveCandidates() {
7323
+ const policy = this.primariesStore().get();
7324
+ if (policy.primaries.length === 0) {
7325
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'lspPubkey is required when no primaries are configured (see listPrimaries)');
7326
+ }
7327
+ const byKey = new Map(policy.primaries.map((p) => [p.pubkey, p]));
7328
+ const balances = this.primaryBalances();
7329
+ return (0, primaries_1.selectReceiveTargets)(policy, new Map([...balances].map(([peer, b]) => [peer, b.sats]))).map((c) => {
7330
+ const stored = byKey.get(c.pubkey);
7331
+ return {
7332
+ pubkey: c.pubkey,
7333
+ rank: c.rank,
7334
+ balanceSat: c.balanceSat,
7335
+ ...(stored?.host !== undefined ? { host: stored.host } : {}),
7336
+ ...(stored?.port !== undefined ? { port: stored.port } : {}),
7337
+ ...(stored?.uri !== undefined ? { uri: stored.uri } : {})
7338
+ };
7339
+ });
7340
+ }
7341
+ /** Dial a primary by its stored address, under the walk's deadline. */
7342
+ async dialPrimary(candidate, timeoutMs) {
7343
+ const { host, port, transport } = (0, receive_steering_1.dialTargetOf)(candidate);
7344
+ await this.connectPeerWithin(candidate.pubkey, host, port, transport, timeoutMs);
7345
+ }
7346
+ /**
7347
+ * The JIT invoice at one LSP: the library call and its typed failures.
7348
+ * `timeoutMs` bounds the wait for the LSP's ack when a steered walk has
7349
+ * less than the ack window left.
7350
+ */
7351
+ async jitInvoiceAt(lspPubkey, opts, amountMsat, timeoutMs) {
7154
7352
  let result;
7155
7353
  try {
7156
7354
  result = await this.node.createJitInvoice({
7157
- lspPubkeyHex: opts.lspPubkey,
7355
+ lspPubkeyHex: lspPubkey,
7158
7356
  amountMsat,
7159
7357
  description: opts.description || '',
7160
7358
  ...(opts.expirySecs !== undefined ? { expiry: opts.expirySecs } : {}),
@@ -7169,7 +7367,8 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7169
7367
  maxFeePpm: requireNonNegativeSafeInteger(opts.maxFeePpm, 'maxFeePpm')
7170
7368
  }
7171
7369
  : {}),
7172
- ...(opts.feeMode !== undefined ? { feeMode: opts.feeMode } : {})
7370
+ ...(opts.feeMode !== undefined ? { feeMode: opts.feeMode } : {}),
7371
+ ...(timeoutMs !== undefined ? { timeoutMs } : {})
7173
7372
  });
7174
7373
  }
7175
7374
  catch (err) {
@@ -7180,6 +7379,7 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7180
7379
  paymentHash: result.paymentHash.toString('hex'),
7181
7380
  paymentSecret: result.paymentSecret.toString('hex'),
7182
7381
  amountSats: opts.amountSats || undefined,
7382
+ lspPubkey,
7183
7383
  flatFeeSat: Number(result.flatFeeSat),
7184
7384
  feePpm: result.feePpm,
7185
7385
  feeMode: result.feeMode
@@ -7241,10 +7441,7 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7241
7441
  update.unpairedSpliceDepth > splice_1.SPLICE_LOCK_DEPTH_ACCEPT_MAX)) {
7242
7442
  throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, `unpairedSpliceDepth must be an integer between 1 and ${splice_1.SPLICE_LOCK_DEPTH_ACCEPT_MAX}`);
7243
7443
  }
7244
- if (update.lspPubkey !== undefined &&
7245
- !/^0[23][0-9a-fA-F]{64}$/.test(update.lspPubkey)) {
7246
- throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'lspPubkey must be a 33-byte compressed public key (66 hex chars)');
7247
- }
7444
+ checkLspPubkey(update.lspPubkey);
7248
7445
  if (update.lspPort !== undefined) {
7249
7446
  if (!Number.isInteger(update.lspPort) ||
7250
7447
  update.lspPort < 1 ||
@@ -7392,21 +7589,58 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7392
7589
  * #687). Transport failures (peer not connected, no reply in time) are
7393
7590
  * typed the way POST /jit/invoice types them; the LSP's own decline is
7394
7591
  * carried in the answer.
7592
+ *
7593
+ * With no `lspPubkey` the quote is steered the way `createJitInvoice`
7594
+ * steers the invoice (issue #1922): the answer prices the first ranked
7595
+ * primary that would serve the receive within the ceilings, so a create
7596
+ * that names that `lspPubkey` lands where the quote did. A decline moves
7597
+ * on to the next primary; NO_PRIMARY_AVAILABLE carries every reason when
7598
+ * none would serve it.
7395
7599
  */
7396
7600
  async getJitQuote(opts) {
7397
- if (!/^0[23][0-9a-fA-F]{64}$/.test(opts.lspPubkey)) {
7398
- throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'lspPubkey must be a 33-byte compressed public key (66 hex chars)');
7399
- }
7601
+ checkLspPubkey(opts.lspPubkey);
7400
7602
  const amountSats = opts.amountSats !== undefined && opts.amountSats !== 0
7401
7603
  ? requireNonNegativeSafeInteger(opts.amountSats, 'amountSats')
7402
7604
  : null;
7605
+ const targetRemainingInboundSat = BigInt(requireNonNegativeSafeInteger(opts.targetRemainingInboundSat ?? 0, 'targetRemainingInboundSat'));
7606
+ if (opts.lspPubkey !== undefined) {
7607
+ return this.jitQuoteAt(opts.lspPubkey, amountSats, targetRemainingInboundSat);
7608
+ }
7609
+ const budgetMs = this.steerBudget(opts.timeoutMs);
7610
+ const { value, skipped } = await (0, receive_steering_1.steerReceive)({
7611
+ candidates: this.receiveCandidates(),
7612
+ isConnected: (pubkey) => this.isPeerConnected(pubkey),
7613
+ connect: (candidate, timeoutMs) => this.dialPrimary(candidate, timeoutMs),
7614
+ attempt: async (candidate, timeoutMs) => {
7615
+ const quote = await this.jitQuoteAt(candidate.pubkey, amountSats, targetRemainingInboundSat, timeoutMs);
7616
+ // A decline or an over-ceiling price is this primary's answer,
7617
+ // and a create here would be refused the same way: on to the
7618
+ // next one, so quote and create agree on the peer.
7619
+ if (!quote.accepted) {
7620
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.JIT_REFUSED, `LSP declined the JIT receive: ${quote.reason ?? 'no reason given'}`);
7621
+ }
7622
+ if (!quote.withinCeilings) {
7623
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.JIT_REFUSED, `LSP quote (${quote.flatFeeSat} sat + ${quote.feePpm} ppm) is above the accepted ceiling (${quote.client.maxFlatFeeSat} sat + ${quote.client.maxFeePpm} ppm)`);
7624
+ }
7625
+ return quote;
7626
+ },
7627
+ candidateCodes: receive_steering_1.JIT_STEER_CODES,
7628
+ budgetMs,
7629
+ lastConnectCapMs: this._connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
7630
+ onSkip: (skip) => this.logSteerSkip('JIT quote', skip)
7631
+ });
7632
+ return skipped.length ? { ...value, skipped } : value;
7633
+ }
7634
+ /** The quote at one LSP: the library call and its typed failures. */
7635
+ async jitQuoteAt(lspPubkey, amountSats, targetRemainingInboundSat, timeoutMs) {
7403
7636
  let quote;
7404
7637
  try {
7405
- quote = await this.node.requestJitQuote(opts.lspPubkey, {
7638
+ quote = await this.node.requestJitQuote(lspPubkey, {
7406
7639
  ...(amountSats !== null
7407
7640
  ? { maxAmountMsat: BigInt(amountSats) * 1000n }
7408
7641
  : {}),
7409
- targetRemainingInboundSat: BigInt(requireNonNegativeSafeInteger(opts.targetRemainingInboundSat ?? 0, 'targetRemainingInboundSat'))
7642
+ targetRemainingInboundSat,
7643
+ ...(timeoutMs !== undefined ? { timeoutMs } : {})
7410
7644
  });
7411
7645
  }
7412
7646
  catch (err) {
@@ -7414,7 +7648,7 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7414
7648
  }
7415
7649
  const ceilings = this.node.getJitClientCeilings();
7416
7650
  return {
7417
- lspPubkey: opts.lspPubkey,
7651
+ lspPubkey,
7418
7652
  amountSats,
7419
7653
  accepted: quote.accepted,
7420
7654
  reason: quote.reason ?? null,
@@ -7445,6 +7679,107 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7445
7679
  minAmountSat: clampDirectFundingMinimum(policy.minAmountSat ?? 0)
7446
7680
  };
7447
7681
  }
7682
+ // ───────── Ranked receive primaries (issue #1922) ─────────
7683
+ /**
7684
+ * The store over the current storage, rebuilt when the storage is replaced
7685
+ * (a capsule restore swaps the database in-process).
7686
+ */
7687
+ primariesStore() {
7688
+ const storage = this.storage;
7689
+ if (!this._primaries || this._primaries.storage !== storage) {
7690
+ const store = new primaries_1.PrimariesStore({ storage });
7691
+ store.restore();
7692
+ this._primaries = { store, storage };
7693
+ }
7694
+ return this._primaries.store;
7695
+ }
7696
+ /** Run a store write, mapping its refusals onto the node's error codes. */
7697
+ primariesWrite(write) {
7698
+ try {
7699
+ write(this.primariesStore());
7700
+ }
7701
+ catch (err) {
7702
+ if (err instanceof primaries_1.PrimariesError) {
7703
+ throw new errors_1.BeignetError(err.code === primaries_1.PrimariesErrorCode.PERSIST_FAILED
7704
+ ? errors_1.BeignetErrorCode.INTERNAL_ERROR
7705
+ : errors_1.BeignetErrorCode.INVALID_PARAMS, err.message);
7706
+ }
7707
+ throw err;
7708
+ }
7709
+ return this.listPrimaries();
7710
+ }
7711
+ /**
7712
+ * Local balance and channel count per peer, over the channels a routing
7713
+ * hint would be built for (looking through a reconnect), so a primary that
7714
+ * is briefly away keeps the balance it holds.
7715
+ */
7716
+ primaryBalances() {
7717
+ const out = new Map();
7718
+ const manager = this.node.getChannelManager();
7719
+ for (const channel of manager.listChannels()) {
7720
+ if (!channel.acceptsNewHtlcs(true))
7721
+ continue;
7722
+ const channelId = channel.getChannelId();
7723
+ const peer = channelId ? manager.getPeerForChannel(channelId) : null;
7724
+ if (!peer)
7725
+ continue;
7726
+ const entry = out.get(peer) ?? { sats: 0, channels: 0 };
7727
+ entry.sats += Number(channel.getFullState().localBalanceMsat / 1000n);
7728
+ entry.channels += 1;
7729
+ out.set(peer, entry);
7730
+ }
7731
+ return out;
7732
+ }
7733
+ /**
7734
+ * The ranked primaries with their balances, and which one a receive with no
7735
+ * peer named goes to. `createJitInvoice`, `getJitQuote` and the automatic
7736
+ * offline receive routes walk this order when the caller names no peer.
7737
+ */
7738
+ listPrimaries() {
7739
+ const policy = this.primariesStore().get();
7740
+ const balances = this.primaryBalances();
7741
+ const order = (0, primaries_1.selectReceiveTargets)(policy, new Map([...balances].map(([peer, b]) => [peer, b.sats])));
7742
+ const position = new Map(order.map((c, i) => [c.pubkey, i]));
7743
+ return {
7744
+ fillThresholdSat: policy.fillThresholdSat,
7745
+ primaries: policy.primaries.map((p, i) => {
7746
+ const at = position.get(p.pubkey);
7747
+ return {
7748
+ pubkey: p.pubkey,
7749
+ rank: i + 1,
7750
+ host: p.host ?? null,
7751
+ port: p.port ?? null,
7752
+ uri: p.uri ?? null,
7753
+ thresholdSat: policy.fillThresholdSat,
7754
+ balanceSat: order[at].balanceSat,
7755
+ channelCount: balances.get(p.pubkey)?.channels ?? 0,
7756
+ belowThreshold: order[at].belowThreshold,
7757
+ isReceiveTarget: at === 0,
7758
+ selectionOrder: at + 1
7759
+ };
7760
+ }),
7761
+ receiveTarget: order[0]?.pubkey ?? null
7762
+ };
7763
+ }
7764
+ /**
7765
+ * Add a primary at `rank` (1-based, default last). Reach it by `host` and
7766
+ * `port`, or by `uri` for ws://, wss:// and iroh: peers.
7767
+ */
7768
+ addPrimary(opts) {
7769
+ const { rank, ...entry } = opts;
7770
+ return this.primariesWrite((store) => store.add(entry, rank));
7771
+ }
7772
+ removePrimary(pubkey) {
7773
+ return this.primariesWrite((store) => store.remove(pubkey));
7774
+ }
7775
+ /** Re-rank: `pubkeys` names every primary once, highest rank first. */
7776
+ reorderPrimaries(pubkeys) {
7777
+ return this.primariesWrite((store) => store.reorder(pubkeys));
7778
+ }
7779
+ /** Set the fill threshold in sats, or null for no cap. */
7780
+ setPrimariesFillThreshold(fillThresholdSat) {
7781
+ return this.primariesWrite((store) => store.setFillThreshold(fillThresholdSat));
7782
+ }
7448
7783
  /**
7449
7784
  * Mint a payment request: a receipt hash whose preimage stays here, and the
7450
7785
  * base64url envelope a payer pays.
@@ -7453,6 +7788,21 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7453
7788
  * dashboard sends the browser's own hostname and the app's manager sends
7454
7789
  * PUBLIC_HOST, both with this wallet's listen port, and this node has no way
7455
7790
  * to know which is right.
7791
+ *
7792
+ * `lspPubkey` names the peer the funding is negotiated with (issue #1922).
7793
+ * It must be a configured primary or the policy's liquidity peer, else
7794
+ * INVALID_PARAMS: the route that names it runs at invoice scope, and the
7795
+ * peer a direct-funded channel opens with holds every payment it receives.
7796
+ * The envelope's relay descriptors name it, at the address the primaries
7797
+ * list stores for it, else the policy's address for it, else the one this
7798
+ * node dialed it at, and the receiver opens the channel with it when the
7799
+ * offer arrives, whatever the direct-funding policy says by then. Omitted,
7800
+ * the ranked primaries choose when any are configured: the first in
7801
+ * `listPrimaries` selection order with a known address is bound, the
7802
+ * others are listed in `skipped`, and NO_PRIMARY_AVAILABLE answers when
7803
+ * none has one. Nothing is dialed, since the request is paid later and
7804
+ * the payer reaches this node through that primary's relay. With no
7805
+ * primaries the policy's liquidity peer serves, as before.
7456
7806
  */
7457
7807
  createDirectFundingRequest(opts) {
7458
7808
  if (opts.port !== undefined) {
@@ -7460,19 +7810,52 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7460
7810
  throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'port must be a TCP port between 1 and 65535');
7461
7811
  }
7462
7812
  }
7813
+ checkLspPubkey(opts.lspPubkey);
7463
7814
  const amountSats = opts.amountSats !== undefined && opts.amountSats !== 0
7464
7815
  ? requireNonNegativeSafeInteger(opts.amountSats, 'amountSats')
7465
7816
  : undefined;
7817
+ const base = {
7818
+ ...(opts.host !== undefined ? { host: opts.host } : {}),
7819
+ ...(opts.port !== undefined ? { port: opts.port } : {}),
7820
+ ...(amountSats !== undefined ? { amountSat: BigInt(amountSats) } : {})
7821
+ };
7822
+ if (opts.lspPubkey !== undefined) {
7823
+ const pubkey = opts.lspPubkey.toLowerCase();
7824
+ this.requireLiquidityPeerConfigured(pubkey);
7825
+ return this.mintDirectFundingRequestAt(base, {
7826
+ pubkey,
7827
+ address: this.liquidityAddressOf(pubkey)
7828
+ });
7829
+ }
7830
+ if (this.primariesStore().get().primaries.length > 0) {
7831
+ return this.steeredDirectFundingRequest(base);
7832
+ }
7833
+ return this.mintDirectFundingRequestAt(base);
7834
+ }
7835
+ /** The mint at one peer, or at the policy's: the library call and its typed failures. */
7836
+ mintDirectFundingRequestAt(base, bound) {
7466
7837
  try {
7467
7838
  const minted = this.node.mintDirectFundingRequest({
7468
- ...(opts.host !== undefined ? { host: opts.host } : {}),
7469
- ...(opts.port !== undefined ? { port: opts.port } : {}),
7470
- ...(amountSats !== undefined ? { amountSat: BigInt(amountSats) } : {})
7839
+ ...base,
7840
+ ...(bound
7841
+ ? {
7842
+ liquidityPeer: bound.pubkey,
7843
+ ...(bound.address
7844
+ ? {
7845
+ liquidityHost: bound.address.host,
7846
+ liquidityPort: bound.address.port
7847
+ }
7848
+ : {})
7849
+ }
7850
+ : {})
7471
7851
  });
7472
7852
  return {
7473
7853
  paymentHash: minted.record.receiptHash,
7474
7854
  expiresAt: minted.expiresAt,
7475
- request: minted.request
7855
+ request: minted.request,
7856
+ lspPubkey: minted.record.liquidityPeer ??
7857
+ this.node.getDirectFundingPolicy()?.liquidityPeer ??
7858
+ null
7476
7859
  };
7477
7860
  }
7478
7861
  catch (err) {
@@ -7484,6 +7867,73 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
7484
7867
  throw this.directFundingFailure(err);
7485
7868
  }
7486
7869
  }
7870
+ /**
7871
+ * Refuse a named liquidity peer the operator never configured. The route
7872
+ * that names one runs at invoice scope, and the peer a direct-funded
7873
+ * channel opens with holds every payment it receives, so which peers can
7874
+ * be named stays with the admin routes: the primaries, and the policy.
7875
+ */
7876
+ requireLiquidityPeerConfigured(pubkey) {
7877
+ if (this.node.getDirectFundingPolicy()?.liquidityPeer?.toLowerCase() ===
7878
+ pubkey)
7879
+ return;
7880
+ if (this.primariesStore()
7881
+ .get()
7882
+ .primaries.some((p) => p.pubkey === pubkey))
7883
+ return;
7884
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'lspPubkey is neither a configured primary nor the direct-funding liquidity peer');
7885
+ }
7886
+ /**
7887
+ * Where a payer reaches this peer's relay: the address the primaries list
7888
+ * stores for it (host and port, or a TCP peer URI), else the address the
7889
+ * direct-funding policy names for it, else the one this node dialed it at.
7890
+ * Never the one it is merely up on: a peer that dialed us is listed at its
7891
+ * socket's source port, which is ephemeral.
7892
+ */
7893
+ liquidityAddressOf(pubkey) {
7894
+ const stored = this.primariesStore()
7895
+ .get()
7896
+ .primaries.find((p) => p.pubkey === pubkey);
7897
+ const fromStored = (0, receive_steering_1.relayAddressOf)(stored, undefined);
7898
+ if (fromStored)
7899
+ return fromStored;
7900
+ const policy = this.node.getDirectFundingPolicy();
7901
+ if (policy?.liquidityPeer?.toLowerCase() === pubkey &&
7902
+ policy.liquidityHost &&
7903
+ policy.liquidityPort) {
7904
+ return { host: policy.liquidityHost, port: policy.liquidityPort };
7905
+ }
7906
+ return (0, receive_steering_1.relayAddressOf)(undefined, this.getPeerAddress(pubkey));
7907
+ }
7908
+ /**
7909
+ * The request bound to the first primary in selection order whose relay a
7910
+ * payer could be told how to reach. A primary with no known address is
7911
+ * passed over and listed in `skipped`; with none left, NO_PRIMARY_AVAILABLE.
7912
+ */
7913
+ steeredDirectFundingRequest(base) {
7914
+ const skipped = [];
7915
+ for (const candidate of this.receiveCandidates()) {
7916
+ const address = this.liquidityAddressOf(candidate.pubkey);
7917
+ if (!address) {
7918
+ const skip = {
7919
+ pubkey: candidate.pubkey,
7920
+ rank: candidate.rank,
7921
+ stage: 'attempt',
7922
+ code: errors_1.BeignetErrorCode.RECEIVE_UNAVAILABLE,
7923
+ message: 'no address is known for this primary: store its host and port with it, or dial it over TCP'
7924
+ };
7925
+ skipped.push(skip);
7926
+ this.logSteerSkip('direct-funding request', skip);
7927
+ continue;
7928
+ }
7929
+ const minted = this.mintDirectFundingRequestAt(base, {
7930
+ pubkey: candidate.pubkey,
7931
+ address
7932
+ });
7933
+ return skipped.length ? { ...minted, skipped } : minted;
7934
+ }
7935
+ throw (0, receive_steering_1.noPrimaryAvailable)(skipped);
7936
+ }
7487
7937
  /**
7488
7938
  * Read a direct-funding request and start connecting to the node a send of it
7489
7939
  * would talk to first, so the dial is under way before the user presses
@@ -10001,6 +10451,596 @@ class BeignetNode extends typed_emitter_1.TypedEmitter {
10001
10451
  return result;
10002
10452
  }
10003
10453
  // ─────────────── BOLT 12 Offers ───────────────
10454
+ // ─── Channel send (issue #1922) ───
10455
+ channelSendQuotes() {
10456
+ return (this._channelSendQuotes ?? (this._channelSendQuotes = new Map()));
10457
+ }
10458
+ channelSendRuns() {
10459
+ return (this._channelSends ?? (this._channelSends = new Map()));
10460
+ }
10461
+ compositeReservations() {
10462
+ return (this._compositeReservations ?? (this._compositeReservations = new Map()));
10463
+ }
10464
+ channelSendInflight() {
10465
+ return (this._channelSendInflight ?? (this._channelSendInflight = new Map()));
10466
+ }
10467
+ /**
10468
+ * Quote paying `address` out of this node's channels (issue #1922,
10469
+ * docs/MULTI-CHANNEL-SPLICE-OUT.md section 7). One channel whose
10470
+ * splice-out bound covers amount plus fee takes the single-channel path,
10471
+ * from the channel with the largest spendable balance; otherwise the
10472
+ * composite engine plans one transaction out of several channels, debited
10473
+ * largest spendable balance first, with the fee split in proportion. The
10474
+ * amount plus the whole fee is checked against the per-payment and daily
10475
+ * limits here, so a refusal comes before anything is reserved. Nothing
10476
+ * moves: the quote is executed with executeChannelSend within
10477
+ * CHANNEL_SEND_QUOTE_TTL_MS.
10478
+ */
10479
+ async quoteChannelSend(address, amountSats, feeratePerkw) {
10480
+ if (typeof address !== 'string' || address.length === 0) {
10481
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'address required');
10482
+ }
10483
+ requirePositiveSafeInteger(amountSats, 'amountSats');
10484
+ requireU32(feeratePerkw, 'feeratePerkw', 253, splice_weight_1.MAX_SPLICE_FEERATE_PERKW);
10485
+ const destinationScript = this._decodeSpliceDestination(address);
10486
+ if (!destinationScript) {
10487
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'address required');
10488
+ }
10489
+ const quoteId = crypto.randomBytes(32).toString('hex');
10490
+ const expiresAt = Date.now() + exports.CHANNEL_SEND_QUOTE_TTL_MS;
10491
+ let quote;
10492
+ let channelIds;
10493
+ const single = this._singleChannelSend(amountSats, feeratePerkw, destinationScript);
10494
+ if (single) {
10495
+ channelIds = [single.channelId];
10496
+ quote = {
10497
+ quoteId,
10498
+ kind: 'single',
10499
+ address,
10500
+ amountSats,
10501
+ feeSats: single.feeSats,
10502
+ totalSats: amountSats + single.feeSats,
10503
+ feeratePerkw,
10504
+ channels: [
10505
+ {
10506
+ channelId: single.channelId.toString('hex'),
10507
+ debitSats: amountSats,
10508
+ feeSats: single.feeSats,
10509
+ oldCapacitySats: single.oldCapacitySats,
10510
+ newCapacitySats: single.oldCapacitySats - amountSats - single.feeSats
10511
+ }
10512
+ ],
10513
+ skipped: [],
10514
+ expiresAt
10515
+ };
10516
+ }
10517
+ else {
10518
+ const planned = await this.node.planCompositeSpliceOut({
10519
+ destinationScript,
10520
+ amountSats: BigInt(amountSats),
10521
+ fundingFeeratePerkw: feeratePerkw
10522
+ });
10523
+ if (!planned.ok)
10524
+ throw compositeSpliceRefusalError(planned);
10525
+ const plan = planned.plan;
10526
+ channelIds = plan.channels.map((c) => c.channelId);
10527
+ const channels = plan.channels.map((c) => ({
10528
+ channelId: c.channelId.toString('hex'),
10529
+ debitSats: Number(c.debitSats),
10530
+ feeSats: Number(c.feeSats),
10531
+ oldCapacitySats: Number(c.oldCapacitySats),
10532
+ newCapacitySats: Number(c.newCapacitySats)
10533
+ }));
10534
+ quote = {
10535
+ quoteId,
10536
+ kind: 'composite',
10537
+ address,
10538
+ amountSats,
10539
+ feeSats: Number(plan.feeSats),
10540
+ totalSats: amountSats + Number(plan.feeSats),
10541
+ feeratePerkw,
10542
+ channels,
10543
+ skipped: plan.skipped.map((c) => ({
10544
+ channelId: c.channelId.toString('hex'),
10545
+ reason: c.reason
10546
+ })),
10547
+ expiresAt
10548
+ };
10549
+ }
10550
+ this._checkMaxPayment(quote.totalSats, amountSats, {
10551
+ name: 'on-chain fees',
10552
+ param: 'feeratePerkw'
10553
+ });
10554
+ this._checkSpendLimit(quote.totalSats);
10555
+ this.pruneChannelSendQuotes();
10556
+ this.channelSendQuotes().set(quoteId, {
10557
+ quote,
10558
+ destinationScript,
10559
+ channelIds
10560
+ });
10561
+ return quote;
10562
+ }
10563
+ /**
10564
+ * The channel with the largest spendable balance whose single splice-out
10565
+ * bound covers the amount plus its fee, or null when none does. The same
10566
+ * predicate spliceOut applies (spliceQuote), on channels that are NORMAL,
10567
+ * not busy, not pending a lock, and whose peer splices.
10568
+ */
10569
+ _singleChannelSend(amountSats, feeratePerkw, destinationScript) {
10570
+ let best = null;
10571
+ const manager = this.node.getChannelManager();
10572
+ for (const channel of manager.listChannels()) {
10573
+ const channelId = channel.getChannelId();
10574
+ if (!channelId)
10575
+ continue;
10576
+ if (channel.getState() !== types_7.ChannelState.NORMAL)
10577
+ continue;
10578
+ if (channel.spliceBusyReason())
10579
+ continue;
10580
+ if (channel.getFullState().spliceInFlight)
10581
+ continue;
10582
+ const peer = manager.getPeerForChannel(channelId);
10583
+ if (peer && this.node.peerSupportsSplicing(peer) === false)
10584
+ continue;
10585
+ let quote;
10586
+ try {
10587
+ quote = this.node.spliceQuote(channelId, 'out', feeratePerkw, destinationScript);
10588
+ }
10589
+ catch {
10590
+ continue;
10591
+ }
10592
+ if (quote.maxAmountSats < amountSats)
10593
+ continue;
10594
+ // The amount-specific preflight spliceOut runs: the destination is an
10595
+ // interactive-tx output that must clear this channel's negotiated
10596
+ // dust floor, and a fee at or above the amount is refused as a
10597
+ // footgun. A channel that would refuse at execute is not ranked.
10598
+ if (BigInt(amountSats) < channel.spliceInteractiveTxDustFloor()) {
10599
+ continue;
10600
+ }
10601
+ if (quote.feeSats >= amountSats)
10602
+ continue;
10603
+ if (!best || quote.spendableSats > best.spendableSats) {
10604
+ best = {
10605
+ channelId,
10606
+ feeSats: quote.feeSats,
10607
+ oldCapacitySats: Number(channel.getFundingSatoshis()),
10608
+ spendableSats: quote.spendableSats
10609
+ };
10610
+ }
10611
+ }
10612
+ return best;
10613
+ }
10614
+ pruneChannelSendQuotes() {
10615
+ const now = Date.now();
10616
+ for (const [id, stored] of this.channelSendQuotes()) {
10617
+ if (stored.quote.expiresAt < now)
10618
+ this.channelSendQuotes().delete(id);
10619
+ }
10620
+ }
10621
+ /**
10622
+ * Run a quoted channel send (issue #1922). The limits are checked again
10623
+ * against the current ledger. A single-channel quote runs spliceOut and
10624
+ * records amount plus fee at once, as an address-targeted splice-out does.
10625
+ * A composite reserves amount plus fee in _pendingSpendSats at PLANNED,
10626
+ * records it at RELEASED (the point past which the money leaves) and
10627
+ * releases it at ABORTED or CONFLICTED, so a composite that never
10628
+ * releases costs nothing of the day's budget. Executing the same quote id
10629
+ * again returns the first execution and runs nothing (the daemon route is
10630
+ * idempotent on top of this). A stale or unknown quote is refused before
10631
+ * any side effect.
10632
+ */
10633
+ async executeChannelSend(quoteId) {
10634
+ requireChannelIdHex(quoteId, 'quoteId');
10635
+ const existing = this.channelSendRuns().get(quoteId);
10636
+ if (existing)
10637
+ return this.channelSendStatus(existing);
10638
+ // A retry that arrives while the first execution is still starting
10639
+ // awaits that execution instead of entering the engine again.
10640
+ const inflight = this.channelSendInflight().get(quoteId);
10641
+ if (inflight)
10642
+ return inflight;
10643
+ const execution = this._executeChannelSendOnce(quoteId).finally(() => this.channelSendInflight().delete(quoteId));
10644
+ this.channelSendInflight().set(quoteId, execution);
10645
+ return execution;
10646
+ }
10647
+ async _executeChannelSendOnce(quoteId) {
10648
+ const stored = this.channelSendQuotes().get(quoteId);
10649
+ if (!stored) {
10650
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.NOT_FOUND, 'channel send quote not found (unknown, expired or already executed)');
10651
+ }
10652
+ if (Date.now() > stored.quote.expiresAt) {
10653
+ this.channelSendQuotes().delete(quoteId);
10654
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'channel send quote expired; quote again');
10655
+ }
10656
+ const { quote, destinationScript, channelIds } = stored;
10657
+ this._checkMaxPayment(quote.totalSats, quote.amountSats, {
10658
+ name: 'on-chain fees',
10659
+ param: 'feeratePerkw'
10660
+ });
10661
+ this._checkSpendLimit(quote.totalSats);
10662
+ if (quote.kind === 'single') {
10663
+ const result = fundingOrRefuse(() => this.node.spliceOut(channelIds[0], BigInt(quote.amountSats), quote.feeratePerkw, destinationScript));
10664
+ if (!result.ok)
10665
+ throw spliceRefusalError(result);
10666
+ this._recordSpend(quote.totalSats, 'onchain');
10667
+ this.channelSendQuotes().delete(quoteId);
10668
+ const run = {
10669
+ status: {
10670
+ id: quoteId,
10671
+ kind: 'single',
10672
+ stage: 'STARTED',
10673
+ address: quote.address,
10674
+ amountSats: quote.amountSats,
10675
+ feeSats: quote.feeSats,
10676
+ channelId: quote.channels[0].channelId,
10677
+ startedAt: Date.now()
10678
+ }
10679
+ };
10680
+ this.channelSendRuns().set(quoteId, run);
10681
+ this.emit('channel-send:stage', { id: quoteId, stage: 'STARTED' });
10682
+ return this.channelSendStatus(run);
10683
+ }
10684
+ // Composite. The quote may be two minutes old: plan again on the current
10685
+ // balances over the quoted channel set, so the fee the engine prices now
10686
+ // is what the limits see and the ledger counts (a channel that no longer
10687
+ // qualifies refuses the plan).
10688
+ const replanned = await this.node.planCompositeSpliceOut({
10689
+ destinationScript,
10690
+ amountSats: BigInt(quote.amountSats),
10691
+ fundingFeeratePerkw: quote.feeratePerkw,
10692
+ channelIds
10693
+ });
10694
+ if (!replanned.ok)
10695
+ throw compositeSpliceRefusalError(replanned);
10696
+ const feeSats = Number(replanned.plan.feeSats);
10697
+ const totalSats = quote.amountSats + feeSats;
10698
+ if (totalSats !== quote.totalSats) {
10699
+ this._checkMaxPayment(totalSats, quote.amountSats, {
10700
+ name: 'on-chain fees',
10701
+ param: 'feeratePerkw'
10702
+ });
10703
+ this._checkSpendLimit(totalSats);
10704
+ }
10705
+ const reservation = {
10706
+ totalSats,
10707
+ charged: false,
10708
+ released: false
10709
+ };
10710
+ const run = {
10711
+ status: {
10712
+ id: quoteId,
10713
+ kind: 'composite',
10714
+ stage: 'PLANNED',
10715
+ address: quote.address,
10716
+ amountSats: quote.amountSats,
10717
+ feeSats,
10718
+ startedAt: Date.now()
10719
+ },
10720
+ reservation
10721
+ };
10722
+ await this._withCompositeStartLock(async () => {
10723
+ // Reserve before the engine runs, so a concurrent spend cannot
10724
+ // double-count the day's budget while the sessions negotiate, and
10725
+ // register the run before the await, so a stage the engine emits
10726
+ // inside start() is relayed under the quote id.
10727
+ this._pendingSpendSats += totalSats;
10728
+ this._startingChannelSend = run;
10729
+ this.channelSendRuns().set(quoteId, run);
10730
+ let started;
10731
+ try {
10732
+ started = await this.node.startCompositeSpliceOut({
10733
+ destinationScript,
10734
+ amountSats: BigInt(quote.amountSats),
10735
+ fundingFeeratePerkw: quote.feeratePerkw,
10736
+ channelIds
10737
+ });
10738
+ }
10739
+ catch (err) {
10740
+ this._releaseCompositeReservation(reservation);
10741
+ this.channelSendRuns().delete(quoteId);
10742
+ throw err;
10743
+ }
10744
+ finally {
10745
+ this._startingChannelSend = null;
10746
+ }
10747
+ if (!started.ok) {
10748
+ this._releaseCompositeReservation(reservation);
10749
+ this.channelSendRuns().delete(quoteId);
10750
+ throw compositeSpliceRefusalError(started);
10751
+ }
10752
+ const compositeId = started.id.toString('hex');
10753
+ run.status.compositeId = compositeId;
10754
+ this.compositeReservations().set(compositeId, reservation);
10755
+ this.channelSendQuotes().delete(quoteId);
10756
+ // The fee the engine priced at start is what leaves. A balance that
10757
+ // moved between the plan above and the start changes it: the
10758
+ // reservation follows, and a total the limits no longer admit
10759
+ // unwinds the composite before any commitment.
10760
+ const startedTotal = quote.amountSats + Number(started.plan.feeSats);
10761
+ if (startedTotal !== reservation.totalSats && !reservation.charged) {
10762
+ if (startedTotal > reservation.totalSats) {
10763
+ try {
10764
+ this._checkMaxPayment(startedTotal, quote.amountSats, {
10765
+ name: 'on-chain fees',
10766
+ param: 'feeratePerkw'
10767
+ });
10768
+ this._checkSpendLimit(startedTotal - reservation.totalSats);
10769
+ }
10770
+ catch (err) {
10771
+ this.node.abortCompositeSplice(started.id, 'fee priced at start exceeds the spend limits');
10772
+ this._releaseCompositeReservation(reservation);
10773
+ this.channelSendRuns().delete(quoteId);
10774
+ throw err;
10775
+ }
10776
+ }
10777
+ if (!reservation.released) {
10778
+ this._pendingSpendSats += startedTotal - reservation.totalSats;
10779
+ }
10780
+ reservation.totalSats = startedTotal;
10781
+ run.status.feeSats = Number(started.plan.feeSats);
10782
+ }
10783
+ // Stages the engine emitted inside start() were bound to this run by
10784
+ // _onCompositeSpliceStage; the record settles anything that was not.
10785
+ this._reconcileCompositeReservation(run, started.id);
10786
+ });
10787
+ return this.channelSendStatus(run);
10788
+ }
10789
+ _withCompositeStartLock(fn) {
10790
+ const previous = this._compositeStartChain ?? Promise.resolve();
10791
+ const next = previous.then(fn, fn);
10792
+ this._compositeStartChain = next.then(() => undefined, () => undefined);
10793
+ return next;
10794
+ }
10795
+ /**
10796
+ * Settle a composite's reservation from its record: RELEASED or later
10797
+ * charges it, ABORTED or CONFLICTED before any charge releases it. Covers
10798
+ * a stage the engine emitted before the run was bound to its id, and
10799
+ * brings the run's status up to the record.
10800
+ */
10801
+ _reconcileCompositeReservation(run, compositeId) {
10802
+ const record = this.node.getCompositeSplice(compositeId);
10803
+ if (!record)
10804
+ return;
10805
+ const reservation = run.reservation;
10806
+ if (reservation && !reservation.charged) {
10807
+ if ((0, composite_splice_record_1.compositeSpliceStageAtLeast)(record.stage, 'RELEASED')) {
10808
+ this._chargeCompositeReservation(reservation);
10809
+ }
10810
+ else if (record.stage === 'ABORTED' || record.stage === 'CONFLICTED') {
10811
+ this._releaseCompositeReservation(reservation);
10812
+ }
10813
+ }
10814
+ run.status.stage = record.stage;
10815
+ if (record.txid) {
10816
+ run.status.txid = (0, identifiers_1.txidToDisplayHex)(Buffer.from(record.txid, 'hex'));
10817
+ }
10818
+ if (record.reason)
10819
+ run.status.reason = record.reason;
10820
+ if ((0, composite_splice_record_1.compositeSpliceStageIsTerminal)(record.stage)) {
10821
+ run.endedAt ?? (run.endedAt = Date.now());
10822
+ }
10823
+ }
10824
+ /** The reservation becomes a recorded on-chain spend, once. */
10825
+ _chargeCompositeReservation(reservation) {
10826
+ if (reservation.charged)
10827
+ return;
10828
+ reservation.charged = true;
10829
+ this._releaseCompositeReservation(reservation);
10830
+ this._recordSpend(reservation.totalSats, 'onchain');
10831
+ }
10832
+ /**
10833
+ * A single-channel send is a splice-out on one channel, so its outcome is
10834
+ * the channel's: splice:complete moves the run to LOCKED with the new
10835
+ * funding txid, splice:aborted to ABORTED with the reason, each relayed on
10836
+ * channel-send:stage. A run already past STARTED is left alone (a later
10837
+ * splice on the same channel is not this send).
10838
+ */
10839
+ _onSingleChannelSendSpliceEvent(channelId, stage, detail) {
10840
+ for (const run of this.channelSendRuns().values()) {
10841
+ if (run.status.kind !== 'single')
10842
+ continue;
10843
+ if (run.status.channelId !== channelId)
10844
+ continue;
10845
+ if (run.status.stage !== 'STARTED')
10846
+ continue;
10847
+ run.status.stage = stage;
10848
+ if (detail.txid)
10849
+ run.status.txid = detail.txid;
10850
+ if (detail.reason)
10851
+ run.status.reason = detail.reason;
10852
+ run.endedAt = Date.now();
10853
+ const data = {
10854
+ id: run.status.id,
10855
+ stage,
10856
+ ...(detail.txid ? { txid: detail.txid } : {}),
10857
+ ...(detail.reason ? { reason: detail.reason } : {})
10858
+ };
10859
+ this.log('info', 'Channel send stage', data);
10860
+ this.emit('channel-send:stage', data);
10861
+ }
10862
+ }
10863
+ /**
10864
+ * Drop runs that ended longer ago than the engine keeps its records
10865
+ * (COMPOSITE_SPLICE_RETENTION_MS), so a long-lived daemon's list does not
10866
+ * grow without end. A run still under way is never dropped.
10867
+ */
10868
+ pruneChannelSendRuns() {
10869
+ const cutoff = Date.now() - composite_splice_engine_1.COMPOSITE_SPLICE_RETENTION_MS;
10870
+ for (const [id, run] of this.channelSendRuns()) {
10871
+ if (run.endedAt === undefined || run.endedAt >= cutoff)
10872
+ continue;
10873
+ this.channelSendRuns().delete(id);
10874
+ if (run.status.compositeId) {
10875
+ this.compositeReservations().delete(run.status.compositeId);
10876
+ }
10877
+ }
10878
+ }
10879
+ _releaseCompositeReservation(reservation) {
10880
+ if (reservation.released)
10881
+ return;
10882
+ reservation.released = true;
10883
+ this._pendingSpendSats = Math.max(0, this._pendingSpendSats - reservation.totalSats);
10884
+ }
10885
+ /**
10886
+ * A composite's stage (issue #1922). RELEASED converts the reservation into
10887
+ * a recorded on-chain spend; ABORTED or CONFLICTED before the charge
10888
+ * releases it (a charge that already happened stays: CONFLICTED follows
10889
+ * RELEASED, and the budget treats an uncertain outcome as spent, as the
10890
+ * Lightning claims do). The stage is relayed under the quote id, or the
10891
+ * composite id for a composite this node did not quote (a restart).
10892
+ */
10893
+ _onCompositeSpliceStage(event) {
10894
+ const compositeId = event.id.toString('hex');
10895
+ let run;
10896
+ for (const candidate of this.channelSendRuns().values()) {
10897
+ if (candidate.status.compositeId === compositeId) {
10898
+ run = candidate;
10899
+ break;
10900
+ }
10901
+ }
10902
+ // PLANNED is the first stage of a new composite and the engine emits it
10903
+ // inside start(), before the id comes back: it belongs to the one run
10904
+ // that is starting (starts are serialized), which learns its id here.
10905
+ const starting = this._startingChannelSend;
10906
+ if (!run &&
10907
+ event.stage === 'PLANNED' &&
10908
+ starting &&
10909
+ !starting.status.compositeId) {
10910
+ run = starting;
10911
+ run.status.compositeId = compositeId;
10912
+ if (run.reservation) {
10913
+ this.compositeReservations().set(compositeId, run.reservation);
10914
+ }
10915
+ }
10916
+ const reservation = this.compositeReservations().get(compositeId);
10917
+ if (reservation) {
10918
+ if (event.stage === 'RELEASED') {
10919
+ this._chargeCompositeReservation(reservation);
10920
+ }
10921
+ else if ((event.stage === 'ABORTED' || event.stage === 'CONFLICTED') &&
10922
+ !reservation.charged) {
10923
+ this._releaseCompositeReservation(reservation);
10924
+ }
10925
+ }
10926
+ const txid = event.txid ? (0, identifiers_1.txidToDisplayHex)(event.txid) : undefined;
10927
+ if (run) {
10928
+ run.status.stage = event.stage;
10929
+ if (txid)
10930
+ run.status.txid = txid;
10931
+ if (event.reason)
10932
+ run.status.reason = event.reason;
10933
+ if ((0, composite_splice_record_1.compositeSpliceStageIsTerminal)(event.stage)) {
10934
+ run.endedAt ?? (run.endedAt = Date.now());
10935
+ }
10936
+ }
10937
+ const data = {
10938
+ id: run?.status.id ?? compositeId,
10939
+ compositeId,
10940
+ stage: event.stage,
10941
+ ...(txid ? { txid } : {}),
10942
+ ...(event.reason ? { reason: event.reason } : {})
10943
+ };
10944
+ this.log('info', 'Channel send stage', data);
10945
+ this.emit('channel-send:stage', data);
10946
+ }
10947
+ channelSendStatus(run) {
10948
+ const status = { ...run.status };
10949
+ if (status.compositeId) {
10950
+ const record = this.node.getCompositeSplice(Buffer.from(status.compositeId, 'hex'));
10951
+ if (record) {
10952
+ status.record = record;
10953
+ status.stage = record.stage;
10954
+ if (record.txid) {
10955
+ status.txid = (0, identifiers_1.txidToDisplayHex)(Buffer.from(record.txid, 'hex'));
10956
+ }
10957
+ if (record.reason)
10958
+ status.reason = record.reason;
10959
+ }
10960
+ }
10961
+ return status;
10962
+ }
10963
+ channelSendStatusFromRecord(record) {
10964
+ return {
10965
+ id: record.id,
10966
+ kind: 'composite',
10967
+ stage: record.stage,
10968
+ amountSats: Number(record.amountSats),
10969
+ feeSats: Number(record.feeSats),
10970
+ compositeId: record.id,
10971
+ ...(record.txid
10972
+ ? { txid: (0, identifiers_1.txidToDisplayHex)(Buffer.from(record.txid, 'hex')) }
10973
+ : {}),
10974
+ ...(record.reason ? { reason: record.reason } : {}),
10975
+ startedAt: record.createdAt,
10976
+ record
10977
+ };
10978
+ }
10979
+ /**
10980
+ * A channel send by its quote id, or a composite by its record id (one
10981
+ * this node restored without having quoted it). Null when unknown.
10982
+ */
10983
+ getChannelSend(id) {
10984
+ requireChannelIdHex(id, 'id');
10985
+ this.pruneChannelSendRuns();
10986
+ const run = this.channelSendRuns().get(id);
10987
+ if (run)
10988
+ return this.channelSendStatus(run);
10989
+ const record = this.node.getCompositeSplice(Buffer.from(id, 'hex'));
10990
+ return record ? this.channelSendStatusFromRecord(record) : null;
10991
+ }
10992
+ /** Every channel send this node executed, plus composites it holds without a quote, oldest first. */
10993
+ listChannelSends() {
10994
+ this.pruneChannelSendRuns();
10995
+ const out = [];
10996
+ const seen = new Set();
10997
+ for (const run of this.channelSendRuns().values()) {
10998
+ out.push(this.channelSendStatus(run));
10999
+ if (run.status.compositeId)
11000
+ seen.add(run.status.compositeId);
11001
+ }
11002
+ for (const record of this.node.listCompositeSplices()) {
11003
+ if (seen.has(record.id))
11004
+ continue;
11005
+ out.push(this.channelSendStatusFromRecord(record));
11006
+ }
11007
+ return out.sort((a, b) => a.startedAt - b.startedAt);
11008
+ }
11009
+ /**
11010
+ * Abort a composite channel send before RELEASED (issue #1922) and return
11011
+ * its status. A single-channel send is a splice-out already under way and
11012
+ * is not aborted from here; past RELEASED the transaction may confirm and
11013
+ * the engine refuses.
11014
+ */
11015
+ abortChannelSend(id, reason) {
11016
+ requireChannelIdHex(id, 'id');
11017
+ // The reason rides every session's tx_abort; a value that cannot be
11018
+ // encoded would stop the unwind between channels.
11019
+ if (reason !== undefined) {
11020
+ if (typeof reason !== 'string') {
11021
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, 'reason must be a string');
11022
+ }
11023
+ if (Buffer.byteLength(reason, 'utf8') > CHANNEL_SEND_ABORT_REASON_MAX_BYTES) {
11024
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.INVALID_PARAMS, `reason must be at most ${CHANNEL_SEND_ABORT_REASON_MAX_BYTES} bytes of UTF-8`);
11025
+ }
11026
+ }
11027
+ const run = this.channelSendRuns().get(id);
11028
+ if (run && run.status.kind === 'single') {
11029
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.SPLICE_REFUSED, 'a single-channel send is a splice-out already under way; it cannot be aborted here');
11030
+ }
11031
+ const compositeId = run?.status.compositeId ?? id;
11032
+ const result = this.node.abortCompositeSplice(Buffer.from(compositeId, 'hex'), reason);
11033
+ if (!result.ok) {
11034
+ throw new errors_1.BeignetError(result.code === composite_splice_engine_1.CompositeSpliceRefusalCode.NOT_FOUND
11035
+ ? errors_1.BeignetErrorCode.NOT_FOUND
11036
+ : errors_1.BeignetErrorCode.SPLICE_REFUSED, result.error ?? 'composite splice cannot be aborted');
11037
+ }
11038
+ const status = this.getChannelSend(id);
11039
+ if (!status) {
11040
+ throw new errors_1.BeignetError(errors_1.BeignetErrorCode.NOT_FOUND, 'channel send not found after the abort');
11041
+ }
11042
+ return status;
11043
+ }
10004
11044
  decodeOfferString(offerStr) {
10005
11045
  const offer = decodeOfferInput(offerStr);
10006
11046
  return this.toOfferInfo(offer, offerStr);