# Beignet CLI & BeignetNode API A simplified interface for the beignet Bitcoin + Lightning library. Two ways to use it: 1. **`BeignetNode` class** -- import into TypeScript/JS scripts 2. **`beignet` CLI** -- run shell commands that talk to an HTTP daemon Both return plain JSON with hex string IDs and satoshi amounts (no Buffer, no bigint). --- ## Quick Start ### CLI ```bash # Initialize (generates mnemonic and API token, writes ~/.beignet/config.json; # the token is printed once, and every command below reads it from the config) npx ts-node src/cli/cli.ts init --network regtest # Start the daemon (stays in foreground, listens on 127.0.0.1:2112) npx ts-node src/cli/cli.ts start # In another terminal: npx ts-node src/cli/cli.ts info npx ts-node src/cli/cli.ts balance npx ts-node src/cli/cli.ts address npx ts-node src/cli/cli.ts invoice create 1000 "coffee" npx ts-node src/cli/cli.ts stop ``` After `npm run build`, you can also use the compiled version: ```bash node dist/cli/cli.js start --network regtest # or if installed globally via npm link: beignet start --network regtest ``` ### Programmatic (TypeScript) `BeignetNode` and the error helpers are in `beignet/node`, `startDaemon` is in `beignet/daemon`, and `beignet/cli` exports both. ```typescript import { BeignetNode } from 'beignet/node'; const node = await BeignetNode.create({ network: 'regtest', electrumHost: '127.0.0.1', electrumPort: 60001, }); console.log(node.getInfo()); // { nodeId: "02ab...", network: "regtest", onchainBalanceSats: 0, ... } const addr = await node.getNewAddress(); // "bcrt1q..." const invoice = node.createInvoice(1000, "test payment"); // { bolt11: "lnbcrt10n1...", paymentHash: "ab12...", amountSats: 1000 } await node.destroy(); ``` --- ## BeignetNode API ### Factory `BeignetNode.create(options)` takes `BeignetNodeOptions`. `network` is the only option it requires. The table is generated from the interface in `beignet-node.ts` by `npm run docs:tables`; edit the doc comments there, not the table. Nested rows (`swaps.minSat`) are fields of an object option. | Option | Type | Description | |--------|------|-------------| | `waiveClientReserve?` | `boolean` | Primary-only switch for new private client channels. Default false. | | `mnemonic?` | `string` | BIP39 mnemonic for the wallet and node keys. A new one is generated when omitted. | | `network?` | `'mainnet' \| 'testnet' \| 'regtest' \| 'signet'` | Required by create(), which throws INVALID_PARAMS without it. | | `alias?` | `string` | Node alias advertised in node_announcement. | | `dataDir?` | `string` | Directory for the SQLite database and the instance lock, used as given. Default: `~/.beignet/data/`, where the tag is the first 16 hex characters of the mnemonic's SHA-256, so each seed gets its own database. With `storage` there is no default, and without a dataDir the node writes no files. | | `storage?` | `IStorageBackend & IWalletDataStorage` | Storage to run on instead of SQLite, such as a MemoryStorage or a backend over a React Native database. It must implement the walletData capability, where the node keeps its wallet state, spend ledger and sweep journal. create() opens it and destroy() closes it. SQLite is then never loaded, storageEncryption does not apply, the payment queue is kept in memory, and backupPath, backup() and capsule restore, which copy or install a SQLite file, are refused. | | `allowMultipleInstances?` | `boolean` | Skip the single-instance lock on the data dir (default false). Leave this off unless you have a specific reason — two instances sharing one data dir share a node identity and SQLite DB, which causes connection churn and risks database corruption. | | `electrumHost?` | `string` | Electrum server host (default: the network's built-in server). | | `electrumPort?` | `number` | Electrum server port (default: the built-in server's). | | `electrumTls?` | `boolean` | Connect to Electrum over TLS (default: the built-in server's setting). The certificate is checked only with electrumTlsVerify. | | `feeEstimationSource?` | `'electrum' \| 'http' \| 'auto'` | Where the wallet sources on-chain fee estimates (default 'auto'): 'electrum' queries only the connected Electrum server (no clearnet HTTP leak), 'http' uses mempool.space/blocktank, 'auto' prefers Electrum and falls back to HTTP when Electrum is unavailable. | | `addressType?` | `'p2wpkh' \| 'p2tr'` | On-chain address type for the wallet (default 'p2wpkh'). 'p2tr' gives taproot deposit addresses; channel funding and splices can spend both kinds (issue #548, LFBW port #532 workstream 1F). | | `listenPort?` | `number` | Accept inbound Lightning peers over TCP on this port. Off when unset. | | `websocketPort?` | `number` | Accept inbound Lightning peers over WebSocket (RFC 6455) on this port. Opt-in and additive: coexists with the TCP listener on listenPort. | | `maxInboundPeers?` | `number` | Inbound peer connections (default 125); once this many are up, only peers holding a channel with this node are admitted. | | `preferAnchors?` | `boolean` | Open anchor channels (default true); false opens legacy static_remotekey channels. | | `finalTaprootWallet?` | `boolean` | Opt in to an original, freshly generated regtest type-80 wallet. | | `finalCommitmentUpdates?` | `boolean` | Enroll a new regtest wallet for type-80 payments, splicing and closes. | | `dualFundedAssets?` | `boolean` | Enroll a fresh regtest wallet for dual-funded asset channel opening. | | `assetSplice?` | `boolean` | Enroll a fresh regtest wallet for asset channel splices. | | `assetSpliceRecovery?` | `boolean` | Enroll a fresh regtest wallet for revocable asset payouts across splices. | | `largeChannels?` | `boolean` | option_wumbo (large_channels, default false): advertise the bit and lift the 2^24 sat funding cap (up to 10 BTC) for peers that also advertise it. | | `autoBootstrap?` | `boolean` | Connect to DNS seed peers (BOLT 10) at startup (default false). | | `autoReconnect?` | `boolean` | Enable auto-reconnection to peers (default true) | | `autoUpdateChannelFees?` | `boolean` | Periodically bump channel commitment feerates via update_fee (default false). Off by default — an unsynced fee bump desyncs commitments and breaks HTLCs. | | `forwardingEnabled?` | `boolean` | Relay third-party HTLCs, i.e. act as a routing hop (default true). Set false for a wallet that should not route: every forward is declined up front with temporary_node_failure and our channel_updates advertise the BOLT 7 disable bit. Does not affect the node's own sends/receives. | | `routingFeeBaseMsat?` | `number` | Node-wide default routing fee policy advertised in channel_update, mapped onto the library's forwarding.feeBaseMsat / forwarding.feePropMillionths / forwarding.cltvDelta (defaults 1000 / 1 / 40). BOLT 7 encodes them as u32 / u32 / u16; out-of-range values are refused in init because the wire write would otherwise wrap or throw only after gossip is being built. Per-channel overrides via updateChannelPolicy win over these defaults. Issue #532 workstream 1B. | | `routingFeePpm?` | `number` | Proportional routing fee in ppm (default 1); see routingFeeBaseMsat. | | `routingCltvDelta?` | `number` | CLTV delta this node requires on forwards (default 40); see routingFeeBaseMsat. | | `leaseRates?` | `ILeaseRates` | Liquidity ads (bLIP-0051, option_will_fund) SELLER policy: answer a buyer's request_funds by leasing inbound liquidity at these rates, funded from this wallet. Setting it advertises the option_will_fund feature bit. Refused in init unless every field is an integer within its wire width (u16 or u32): the rates are encoded into the SIGNED will_fund record, where channel_fee_max_base_msat is a tu32 whose encoder silently wraps an out-of-range value, i.e. the node would sign rates it never configured. | | `jitReceive?` | `object` | JIT channel receive (issue #595). `enabled` turns on the LSP role, which fronts channel funding with this node's own coins for wallet peers and charges flatFeeSat + feePpm for it. maxFlatFeeSat / maxFeePpm are the other role, and apply whether or not the LSP role is on: they cap what this node accepts when it asks an LSP for a JIT receive of its own. maxClientFundingSats / maxConcurrentFundings / maxTotalFundingSats bound what the LSP role fronts (issue #665); unset keeps the library defaults. | | `jitReceive.enabled?` | `boolean` | Run the LSP role. | | `jitReceive.flatFeeSat?` | `number` | LSP role: flat part of the opening fee, in sats. | | `jitReceive.feePpm?` | `number` | LSP role: proportional part of the opening fee, in ppm of the held total. | | `jitReceive.maxFlatFeeSat?` | `number` | Client role: the largest flat fee this node accepts from an LSP. | | `jitReceive.maxFeePpm?` | `number` | Client role: the largest proportional fee this node accepts from an LSP. | | `jitReceive.maxClientFundingSats?` | `number` | LSP role: the most fronted for one client, open or splice (library default 1,000,000 sats). | | `jitReceive.maxConcurrentFundings?` | `number` | LSP role: opens plus splices in flight at once (library default 3). | | `jitReceive.maxTotalFundingSats?` | `number` | LSP role: lifetime sats this node may front, counted across restarts. Unbounded when unset. | | `swaps?` | `object` | Reverse swap provider (issue #737): on only with enabled === true. The numbers are whole sats/blocks; unset ones keep the library defaults. | | `swaps.enabled?` | `boolean` | Serve reverse swaps. | | `swaps.flatFeeSat?` | `number` | Flat part of the swap fee, in sats (both directions). | | `swaps.feePpm?` | `number` | Proportional part of the swap fee, in ppm (both directions). | | `swaps.minSat?` | `number` | Smallest swap accepted, in sats. | | `swaps.maxSat?` | `number` | Largest swap accepted, in sats. | | `swaps.maxExposureSat?` | `number` | Principal at risk across every unresolved swap, in sats. | | `swaps.maxConcurrent?` | `number` | Swaps whose principal may be at risk at once. | | `swaps.refundDeltaBlocks?` | `number` | Reverse swap: blocks from create to the contract's refund height. | | `swaps.fundingConfs?` | `number` | Depth a funding output needs before the provider relies on it. | | `swaps.resolutionConfs?` | `number` | Depth a spend needs before the provider treats it as the outcome. | | `swaps.submarine?` | `boolean` | The submarine direction (issue #743): a peer locks coins in a contract, this node pays the peer's invoice and claims them. On only with submarine === true (and the role enabled); the fee terms and caps above apply to both directions. | | `swaps.claimSafetyBlocks?` | `number` | Submarine: blocks between the last possible outgoing HTLC expiry and the refund height (library default 24). | | `swaps.paymentMaxFeePpm?` | `number` | Submarine: routing fee this node will spend, per million of the invoice (library default 5000). | | `swaps.claimBumpIntervalBlocks?` | `number` | Submarine: blocks an unconfirmed claim waits before a rebuild at a higher fee (library default 2). | | `swaps.submarineRefundDeltaBlocks?` | `number` | Submarine: blocks from create to the contract's refund height (library default 288). | | `dfRelay?` | `boolean` | Relay direct-funding frames for OTHER nodes (BEIGNET_DF_RELAY, issue #613). Off by default: forwarding opaque frames between strangers is work done for other people, metered but not free. The three lanes this node uses for its own payments and receives are always available. | | `dfMinAmountSat?` | `number` | Smallest direct-funding offer this node will serve (BEIGNET_DF_MIN_AMOUNT). Values under the 5000 sat protocol floor, zero included, clamp up to it. | | `autoGossipSync?` | `boolean` | Request a gossip graph sync from each peer on connect (default true). Without this the node only knows its own channels and cannot route multi-hop payments to destinations beyond its direct peers. | | `rapidGossipSync?` | `boolean` | Download the full network graph via Rapid Gossip Sync on startup (default true on mainnet). This is the reliable, lightweight way to obtain the graph needed for multi-hop routing — a few MB over HTTPS instead of crawling p2p gossip. Set false to rely solely on p2p gossip from peers. | | `rapidGossipSyncUrl?` | `string` | Rapid Gossip Sync snapshot URL (defaults to the public LDK endpoint). | | `eagerGossipVerify?` | `boolean` | Signature-verify foreign broadcast gossip at intake (default false). By default verification is deferred until a gossip query asks for an entry, which skips nearly the whole first-dump verification cost; nothing unverified is ever served either way. Set true on relay-class nodes that serve the graph: intake and restore verify eagerly and signatureless RGS-primed entries are re-fetched signed from peers. | | `deferGraphRestore?` | `boolean` | Bring back the stored network map in time slices after create() returns, rather than inside it (default false). For a node that runs on an app's only JavaScript thread, as a phone wallet's does: a large map otherwise holds that thread for seconds as the wallet opens. Until it is back, payments, rebalances and channel suggestions wait for it, a synchronous route query (estimateRouteFee, probeRoute, queryRoute, quotePayAll) finishes it first, gossip that would write the graph and the boot RGS import wait for it, and getGraphInfo() says `restoring`. The waits are skipped while no restore runs, so a node that restores inline sees no change. getGraphRestoreStats() is null until then, and `graph:restored` reports it. | | `onError?` | `(error: { code: string; message: string; timestamp: number; channelId?: ChannelIdHex; txid?: TxidHex; retained?: boolean; channelErrorCode?: ChannelErrorCode }) => void` | Optional error callback — receives all node:error events instead of silently absorbing them | | `logLevel?` | `LogLevel` | Log level (default 'info'). Set to 'silent' to suppress. | | `wireTrace?` | `boolean \| string[]` | Forwarded to LightningNode's wireTrace: log non-gossip wire messages (type and length) at info, for every peer (true) or the listed pubkeys. | | `logger?` | `ILogger` | Leveled diagnostic logger. When set, every log entry that passes logLevel is forwarded to it (in addition to the 'log' event) and it is injected into the underlying Wallet and LightningNode. When unset, behavior is unchanged: BeignetNode only emits 'log' events and the wallet keeps its default console output. | | `extensions?` | `readonly IBeignetExtension[]` | Host extensions to run inside this node (docs/EXTENSIONS.md). Each is attached once the on-chain wallet exists and again after every in-process rebuild; the daemon serves its routes under `/x/`. A malformed entry refuses create() with INVALID_PARAMS, and one that throws while running is reported by `GET /extensions` and left out. | | `electrumServers?` | `Array<{ host: string; port: number; tls?: boolean }>` | Multiple Electrum servers for failover redundancy | | `backupPath?` | `string` | Path for automated periodic backups (enables backup scheduling) | | `backupIntervalMs?` | `number` | Backup interval in milliseconds (default: 6 hours, requires backupPath) | | `dailySpendLimitSats?` | `number` | COMBINED daily spending limit in satoshis, shared by Lightning payments (payInvoice, sendPaymentAsync, sendKeysend, payOffer, sendToRoute and the queue) AND external on-chain sends (sendOnchain and sendMaxOnchain, address-targeted spliceOut and sendDirectFunding, counted as amount + fee). A Lightning payment reserves its amount plus its routing-fee cap at admission and is charged its amount plus the fee actually paid when it settles (issue #1008); sendToRoute reserves and charges what its first hop carries. A circular rebalance (rebalanceChannel, executeRebalances) counts its routing fee only. Excluded by design: consolidateUtxos (self-pay), our own channel opens/splices/funding, bumpFeeOnchain/boostOnchain (fee-only), and the submarine swap provider's payment of the counterparty's invoice, which is bounded by the provider's own per-swap fee cap and by the swap-in it is funded from rather than by this limit. Resets at midnight UTC. NOTE: before v0.3.0 this limit covered Lightning only. | | `maxPaymentSats?` | `number` | Maximum amount in satoshis for a single payment. Rejects any payInvoice/sendPaymentAsync/sendKeysend/payOffer/sendToRoute call whose amount plus routing-fee cap exceeds this (issue #1008): the cap is the caller's maxFeeSats/maxFeeMsat, or the default of 1% of the amount with a 50 sat floor when none is given. Prevents accidental large payments. External on-chain sends are capped too: sendOnchain, address-targeted spliceOut and sendDirectFunding on amount + fee, sendMaxOnchain on the whole sweep. Circular rebalances are not capped, since the amount comes back. The submarine swap provider's payment of the counterparty's invoice is excluded by design: the provider's own per-swap fee cap and the swap-in it is funded from bound it. | | `connectTimeoutMs?` | `number` | Timeout for connectPeer() in milliseconds (default: 15000) | | `torProxy?` | `string` | SOCKS5 proxy for reaching Tor `.onion` peers, as "host:port" (e.g. "127.0.0.1:9050"). Required to connect to peers that only advertise an onion address. Needs a running Tor daemon/Tor Browser on that port. | | `torProxyOnionOnly?` | `boolean` | Use torProxy for `.onion` peers only and dial public clearnet peers directly (LND's `tor.skip-proxy-for-clearnet-targets`, "hybrid mode"). Without it every public peer rides the proxy. Private and loopback hosts are dialed directly either way. Needs torProxy: startup is refused when this is set without one, since it only chooses which hosts use the configured proxy. Applies to peer dials and watchtower connections. | | `announceAddresses?` | `string[]` | Addresses to advertise in our node_announcement so remote peers can discover and dial us, as "host[:port]" strings (port defaults to 9735). Supports IPv4, "[ipv6]:port", Tor v3 ".onion" and DNS hostnames. Only announced once the node has at least one public channel. | | `watchtowers?` | `string[]` | Watchtowers to ship encrypted justice data to at every revocation, as "pubkey@host:port" URIs (LND altruist wtwire protocol). Off when empty. | | `recoveryMode?` | `string` | Recovery Protocol mode (docs/RECOVERY-PROTOCOL.md section 8). Exact values 'off' \| 'peer-storage' \| 'async-remote' \| 'quorum'; anything else is treated as off, the safe fallback (an existing quorum-marked database still refuses to start unbarriered at the library level). | | `recoveryGuardians?` | `Array` | Guardian set for the guardian-backed modes, as "<64-hex-x-only-pubkey>@<http(s) url>" URIs or structured { guardianId, url, auth? } entries (crash-v1: exactly three). The structured form carries the transport credential a retrieved capsule hands back through revealCapsuleGuardians. A malformed entry throws rather than silently changing the quorum arithmetic; the daemon validates these before create so a typo never boots a node. | | `recoveryProfile?` | `string` | Fault-model profile; 'crash-v1' is the only value and the default. | | `recoveryLeaseCheckIntervalMs?` | `number` | Guardian modes: how often an idle confirmed writer re-asks the guardian set whether its lease is still current (issue #455). Default 5 minutes; 0 disables. A proven newer epoch fences exactly as a refused append would; an outage never changes the gate. | | `recoveryReestablishHoldMs?` | `number` | peer-storage mode: how long a peer's channel_reestablish for a channel this node has no record of is held before the BOLT 1 error goes out (issue #462). Default 10 minutes; 0 answers immediately, which is the pre-#462 conduct. A node restoring over peer_storage boots empty on purpose and gets the peer's reestablish in the same instant as the Recovery Capsule that answers it, so failing the channel there force-closes exactly what the restore is about to resume. Ignored in every other mode. | | `recoveryAutoApply?` | `boolean` | peer-storage mode: apply the best Recovery Capsule storage peers return on a boot whose database is empty, with no operator call, and rebuild the node in-process on it (issue #690). Local durability has no fencing, so this automates an unfenced adoption: an old device still running keeps acting on the same channels. Off by default; refused outside peer-storage mode. | | `recoveryAutoApplySettleMs?` | `number` | Settle floor in ms from the first capsule's arrival (default 15000). | | `recoveryAutoApplyMaxWaitMs?` | `number` | Ceiling in ms from the first arrival (default 120000); must be at least the settle floor and fit inside recoveryReestablishHoldMs. | | `guardianServe?` | `boolean` | Serve the reference guardian to other nodes over bolt8 sessions at this node's Lightning address (docs/RECOVERY-GUARDIAN-WIRE.md 2.7, issue #699). Needs an inbound listener (listenPort). Independent of this node's own recovery mode, and kept serving while this node's own writer lease is quarantined (the guardian-only lane). | | `fforSettle?` | `object` | FFOR settlement peer role (issue #729): answer ff_init for receivers. Off by default, since an epoch locks its whole budget of this node's liquidity. | | `fforSettle.enabled` | `boolean` | Answer ff_init; only an exact true turns it on. | | `fforSettle.maxBudgetMsat?` | `string \| number` | Largest epoch budget accepted, in msat. | | `fforSettle.maxEpochBlocks?` | `number` | Longest epoch accepted, in blocks. | | `fforSettle.feeBaseMsat?` | `number` | Smallest base fee accepted, in msat. | | `fforSettle.feePpm?` | `number` | Smallest proportional fee accepted, in ppm. | | `fforConcurrent?` | `boolean` | Advertise FFOR concurrent receive, feature bits 442/443 (default true). | | `fforSettleConcurrent?` | `boolean` | Accept new concurrent-profile settlements when fforSettle is on (default true). | | `fforWitness?` | `object` | FFOR receipt witness role: store a receiver-encrypted record of every delegated preimage this node relays before propagating the fulfil. | | `fforWitness.enabled` | `boolean` | Run the witness role. | | `fforWitness.maxMailboxes?` | `number` | Mailboxes this node hosts at once. | | `fforWitness.maxBytes?` | `number` | Bytes all mailboxes may occupy. | | `fforIssuer?` | `boolean` | FFOR issuer role: answer BOLT 12 invoice requests for offers a receiver delegated to this node. Needs fforWitness. | | `fforReceiveFunding?` | `FforReceiveFunding` | FFOR settlement peer: policy for funding new receive channels for receivers (BEIGNET_FFOR_RECEIVE_FUNDING). Off unless enabled. | | `guardianToken?` | `string` | Bearer token every guardian session must present; absent runs open. | | `guardianMaxBytesPerSet?` | `number` | Disk one served set may occupy before writes are refused (256 MiB). | | `guardianMaxSets?` | `number` | Sets this node will register (default 16). | | `guardianMaxCiphertextBytes?` | `number` | Advertised per-record ciphertext limit (default 4 MiB, which is also the least a node accepts from a guardian). | | `storageEncryption?` | `boolean` | Encrypt the SQLite database at rest with a key derived from the wallet seed (default true). An existing plaintext database is migrated in place on first open; restoring a backup requires the same mnemonic. Set false to keep storage in plaintext. | | `peerStorageEnabled?` | `boolean` | BOLT 1 peer storage (default true): push our seed-encrypted static channel backup to connected peers that advertise option_provide_storage, store one small blob per channel/trusted peer in return, and keep the newest valid SCB peers hand back on reconnect (see getPeerRetrievedBackup). Recovery stays explicit via restoreFromScb. | | `autoRebalance?` | `object` | Automatic circular rebalancing (default DISABLED). When enabled the node periodically executes the advisor's rebalance plan, spending at most budgetSatsPerDay in routing fees per UTC day. Off unless enabled: true. Each run is an executeRebalances call, so drain mode and dailySpendLimitSats hold it as they hold a manual one. | | `autoRebalance.enabled?` | `boolean` | Master switch; only an explicit true turns it on. | | `autoRebalance.budgetSatsPerDay?` | `number` | Most routing fees spent on rebalances per UTC day, in sats (default 1000). | | `autoRebalance.minImbalancePct?` | `number` | Local-balance percent below or above which a channel is imbalanced (default 20). | | `autoRebalance.intervalMs?` | `number` | Run interval in ms (default 3,600,000, one hour). | | `autoTuneFees?` | `object` | Automatic routing-fee (ppm) tuning (default DISABLED). When enabled the node periodically nudges each channel's proportional fee up 25% when its outbound side is depleted but still forwarding, and down 25% when it saw no forwards in the window, clamped to [floorPpm, ceilPpm]. | | `autoTuneFees.enabled?` | `boolean` | Master switch; only an explicit true turns it on. | | `autoTuneFees.intervalMs?` | `number` | Tune interval and forwarding observation window in ms (default six hours). | | `autoTuneFees.floorPpm?` | `number` | Lowest ppm the tuner sets (default 1). | | `autoTuneFees.ceilPpm?` | `number` | Highest ppm the tuner sets (default 10,000). | | `iroh?` | `boolean` | Experimental phone link. Peers and relays can see your IP address. | | `irohRelays?` | `string[]` | Custom relays replace the public defaults. Empty disables relays. | | `irohDiscovery?` | `boolean` | Public endpoint discovery and publication (default true when enabled). | | `irohRelayOnly?` | `boolean` | Keep every Iroh connection on the relay (default false). No direct path is offered or taken, so someone who holds the node's Iroh link cannot learn its IP address; the relay operator still sees it. Slower than a direct path. Needs a relay, and learned addresses are then dialed through the SOCKS5 proxy or not at all. The node dials out over Iroh only with irohDiscovery off, and only to a peer on one of its own relays: any other relay would see its address. With an Iroh binding that cannot remove its IP transport, the node stops serving Iroh on a network whose router grants port mappings (see the Iroh section). | | `porchRelays?` | `(string \| IPorchRelayConfig)[]` | Porch relays to wait at, so the node can hand out `wss://` peer links that do not say where it runs. Each is a relay URL (`wss://host[:port]`), or `{ url, token }` for a relay that asks a node for a token. Unset or empty leaves Porch off. | | `porchVia?` | `PorchVia` | How the relays are dialed. `tor` sends every relay connection through the SOCKS5 proxy (torProxy, else 127.0.0.1:9050), so the relay does not learn the node's address either. `direct` dials them directly whatever torProxy says. Unset dials a relay as any other peer at that host. | | `porchProxy?` | `string` | A SOCKS5 proxy for the relay connections alone, as "host:port". Every relay is dialed through it and never directly, so the relay sees the proxy and not the node, while peers go on being dialed as torProxy says. Any SOCKS5 proxy that asks for no credentials will do: a second Tor, or a VPN or tunnel that offers one, at that detour's cost in time and not Tor's. Refused together with porchVia `direct`. | | `porchStandbys?` | `number` | Idle connections kept at each relay. Each one takes one visitor, and is replaced when it does. Default 2, at most 8. | | `porchToken?` | `string` | The token of a private relay, when exactly one relay is configured. With several, each relay's token goes in its own porchRelays entry. | | `electrumTlsVerify?` | `boolean` | Verify Electrum TLS certificates (default false). Every TLS connection the wallet opens, to the configured server or to a public fallback, is accepted only when its certificate chains to a trusted CA and matches the host name, or when its SHA-256 fingerprint is in electrumTlsFingerprints. | | `electrumTlsFingerprints?` | `string[]` | SHA-256 fingerprints of Electrum certificates to accept without a CA, for servers with self-signed certificates. Hex with or without colons, as printed by `openssl x509 -noout -fingerprint -sha256`. Needs electrumTlsVerify. | Internally wires together: `Wallet` + `LightningNode` + `SqliteStorage` (or the backend passed as `storage`) + `WalletFundingProvider` + `ElectrumBackend`. ### Methods All methods return plain objects. IDs are hex strings. Amounts are numbers in satoshis. The signatures name three of those IDs: `ChannelIdHex` and `PaymentHashHex` (32 bytes, 64 hex characters) and `TxidHex` (64 hex characters in display byte order, as bitcoind and block explorers print a txid). All three are aliases of `string` and exported from `beignet/cli`. A method that looks up or acts on a channel or a payment by its id refuses a malformed one as `INVALID_PARAMS`. #### Info | Method | Returns | Description | |--------|---------|-------------| | `getInfo()` | `NodeInfo` | Node ID, network, balances, peer/channel counts | | `getMnemonic()` | `string` | The BIP39 mnemonic | | `getBalance()` | `BalanceInfo` | `{ onchain, lightning, total, unsettledSats }` in sats | | `signMessage(message)` | `{ signature, pubkey }` | Sign with the node key (LND-compatible: `Lightning Signed Message:` prefix, double-SHA256, compact recoverable ECDSA, zbase32). Verifiable with `lncli verifymessage` | | `verifyMessage(message, signature)` | `{ valid, pubkey, knownNode }` | Recover the signer pubkey from an LND-style signature; `knownNode` says whether it is in our graph. Compare `pubkey` to the expected signer | #### On-chain | Method | Returns | Description | |--------|---------|-------------| | `getNewAddress()` | `Promise` | Next unused bech32 receive address | | `sendOnchain(address, amountSats, satsPerVbyte?)` | `Promise` | Build, sign, broadcast tx. Returns `{ txid, hex }`. Optional fee rate. | | `sendMaxOnchain(address, satsPerVbyte?)` | `Promise` | Sweep the entire spendable balance to one address (amount = balance minus fee) | | `bumpFeeOnchain(txid, satsPerVbyte)` | `Promise` | RBF-replace an unconfirmed wallet tx at a higher fee rate (BIP 125); NOT_BOOSTABLE when RBF is unavailable | | `boostOnchain(txid, satsPerVbyte?)` | `Promise` | Fee-bump a tx: RBF when possible, else CPFP to a fresh wallet address | | `listBoostableTransactions()` | `BoostableTransactions` | Unconfirmed wallet txs eligible for RBF and/or CPFP | | `consolidateUtxos(satsPerVbyte?)` | `Promise` | Merge all UTXOs into one output at a fresh wallet address (send-max-to-self) | | `buildPsbt(outputs, satsPerVbyte?)` | `Promise` | Build an UNSIGNED PSBT for an external signer (hardware wallet); nothing is signed or broadcast | | `importSignedPsbt(psbtBase64, unsignedPsbtBase64?)` | `PsbtImportInfo` | Validate + finalize an externally signed PSBT that this node built (same inputs and outputs), or that matches `unsignedPsbtBase64` (needed after a restart); returns `{ txid, txHex }` WITHOUT broadcasting | | `combinePsbts(psbts)` | `{ psbtBase64 }` | Combine partially signed copies of the same PSBT (multi-party signing) | | `refreshWallet()` | `Promise` | Sync UTXOs from Electrum (incremental: wallet state persists in the node's SQLite DB across restarts) | | `listUtxos()` | `UtxoInfo[]` | Wallet UTXOs; each entry carries a `frozen` flag | | `freezeUtxo(txid, index)` | `Promise<{ frozen }>` | Freeze a UTXO: excluded from ALL coin selection (send/send-max/consolidate/PSBT build) until unfrozen; still counted in the balance | | `unfreezeUtxo(txid, index)` | `Promise<{ unfrozen }>` | Make a frozen UTXO spendable again | | `setAddressLabel(address, label)` | `Promise<{ address, label }>` | Set a user label for an address (empty label clears it) | | `listAddressLabels()` | `Record` | All user address labels keyed by address | | `exportDescriptors()` | `DescriptorsInfo` | BIP 380 output descriptors (with checksums) for all four address types. Public keys only; private keys are never exported | #### Peers | Method | Returns | Description | |--------|---------|-------------| | `connectPeer(pubkey, host, port)` | `Promise` | Connect to Lightning peer. Times out after `connectTimeoutMs` (default 15s). | | `disconnectPeer(pubkey)` | `void` | Disconnect peer | | `listPeers()` | `PeerInfo[]` | List connected peers | | `getPorchLinks()` | `PorchLinksInfo` | The [Porch links](#porch-links) this node serves, each with one URI per relay, and how it stands with each relay. `enabled: false` when no relay is configured | | `createPorchLink(label?)` | `PorchLinkInfo` | Make a Porch link of its own, to hand to one person or device. Written to the database before the relays are told of it. Throws `INVALID_PARAMS` when Porch is off, the label is over 64 characters or 256 links are served | | `revokePorchLink(id)` | `{ revoked: true, id }` | Revoke a Porch link for good: it stops resolving and every peer connected through it is disconnected. Throws `NOT_FOUND` for a link that is not served | | `getPeerAddress(pubkey)` | `Pick \| undefined` | The address this node last dialed the peer at, if it ever did, in this run or, from the persisted peer addresses, an earlier one. A peer that only ever connected inbound has none: `listPeers()` then shows its socket's ephemeral source port | #### DNS Bootstrap (BOLT 10) | Method | Returns | Description | |--------|---------|-------------| | `bootstrapPeers()` | `Promise` | Discover peers via DNS seeds | | `connectToSeeds(maxPeers?)` | `Promise` | Connect to discovered seed peers | #### Trusted Peers (Zero-Conf) | Method | Returns | Description | |--------|---------|-------------| | `addTrustedPeer(pubkey)` | `TrustedPeerInfo` | Trust a peer for zero-conf channels | | `removeTrustedPeer(pubkey)` | `TrustedPeerInfo` | Remove peer from trusted set | | `listTrustedPeers()` | `TrustedPeerInfo[]` | List all trusted peers | #### Channels | Method | Returns | Description | |--------|---------|-------------| | `openChannel(pubkey, amountSats, opts?)` | `ChannelInfo` | Open channel, auto-funded from wallet. `opts: { pushSats?, satsPerVbyte?, max?, trusted? }`; `max` funds from the whole spendable balance and needs `satsPerVbyte`. The positional form `(pubkey, amountSats, pushSats?, satsPerVbyte?, max?, trusted?)` is deprecated | | `openChannelAndWait(pubkey, amountSats, opts?)` | `Promise` | Open channel + wait for NORMAL state. `opts: { pushSats?, timeoutMs? }` | | `openZeroConfChannel(pubkey, sats, pushSats?)` | `ChannelInfo` | Open zero-conf channel (peer must be trusted) | | `openChannelV2(pubkey, params)` | `ChannelInfo` | Open dual-funded v2 channel | | `closeChannel(channelId, acceptStaleStateRisk?, address?)` | `Promise<{ ok, error? }>` | Cooperative close (`await` it): optional `address` pays an external destination and records the signed payout in on-chain history. Without it, the payout goes to a wallet-scanned address on the change chain, never to a handed-out receive address. A capsule-restored channel needs `acceptStaleStateRisk: true`, because a mutual close signs the balances that row carries | | `forceCloseChannel(channelId, acceptStaleStateRisk?)` | `{ ok, error?, commitmentTxid? }` | Force close; the sweep pays the wallet's change chain, never a handed-out receive address. A capsule-restored channel needs `acceptStaleStateRisk: true` | | `startAssetSplice(channelIdHex, fundingFeeratePerkw, minimumDepth)` | `Promise<{ started: true }>` | Begin a private asset splice on an enrolled regtest wallet | | `spliceIn(channelId, amountSats, feerate)` | `SpliceResult` | Add funds to existing channel | | `spliceOut(channelId, amountSats, feerate, destinationAddress?)` | `SpliceResult` | Withdraw funds from channel, to the wallet or an external address. An address-targeted splice-out counts amount + fee against `maxPaymentSats` and `dailySpendLimitSats` | | `quoteChannelSend(address, amountSats, feeratePerkw)` | `Promise` | Quote paying an address out of the channels (issue #1922): one channel when its splice-out bound covers amount + fee (the largest spendable balance), else one transaction out of several channels, debited largest first with the fee split in proportion. Amount + fee is checked against `maxPaymentSats` and `dailySpendLimitSats`. Nothing moves; the quote lasts two minutes | | `executeChannelSend(quoteId)` | `Promise` | Run a quote: a single-channel splice-out (records amount + fee at once) or a composite (reserves amount + fee, charges it at RELEASED, releases it at ABORTED). The same quote id returns the first execution | | `getChannelSend(id)` | `ChannelSendStatus \| null` | A channel send by quote id, or a composite by record id | | `listChannelSends()` | `ChannelSendStatus[]` | Every channel send this node executed, plus composites it holds without a quote | | `abortChannelSend(id, reason?)` | `ChannelSendStatus` | Abort a composite before its signatures are released and return its status; refused past RELEASED and for a single-channel send | | `listChannels()` | `ChannelInfo[]` | List all channels | | `getChannel(channelId)` | `ChannelInfo \| null` | Get specific channel | | `updateChannelFee(channelId, feeratePerKw)` | `{ ok: true }` | Update channel COMMITMENT feerate via update_fee (min 253). Not the routing fee policy | | `connectAndOpenChannel(pubkey, host, port, amountSats, opts?)` | `Promise` | Connect to peer + open channel in one call. `opts: { pushSats? }` | | `ensureMinimumChannels(count, satsPerChannel, opts?)` | `Promise` | Auto-open channels to meet minimum count. Connects to peers via gossip graph addresses before opening. `opts: { timeoutMs? }` | #### Invoices | Method | Returns | Description | |--------|---------|-------------| | `createInvoice(amountSats?, description?, expirySecs?, descriptionHash?)` | `InvoiceInfo` | Create BOLT 11 invoice. Use `descriptionHash` (hex Buffer) for hashed descriptions > 639 bytes — omit `description` when using hash. Returns `paymentSecret` for correlating incoming payments. | | `decodeInvoice(bolt11)` | `DecodedInvoice` | Decode a BOLT 11 invoice. One for another network is refused with `INVALID_INVOICE` | | `listInvoices()` | `InvoiceInfo[]` | List all created invoices. `status` is `PAID` on a completed receive for the hash, from the in-memory record or, once the engine has pruned it, the database row (one database read per call), so a paid invoice never reads `EXPIRED` or `PENDING` later | | `createHoldInvoice({ paymentHash, amountMsat?, amountSats?, description?, expiry?, minFinalCltvExpiry? })` | `InvoiceInfo` | Hold invoice for a caller-supplied `sha256(preimage)`: the preimage stays with the caller and the incoming HTLC parks instead of settling. `minFinalCltvExpiry` is 1..2016 blocks and sets the BOLT 11 `c` tag | | `settleHoldInvoice(preimage)` | `{ paymentHash }` | Validate `sha256(preimage)` and fulfill every parked HTLC (all MPP parts) | | `cancelHoldInvoice(paymentHash)` | `{ paymentHash, htlcsFailed }` | Fail parked HTLCs back (`incorrect_or_unknown_payment_details`) and close the invoice | | `listHoldInvoices()` | `HoldInvoiceInfo[]` | Hold invoices with state `OPEN\|ACCEPTED\|SETTLED\|CANCELLED` and parked totals | ##### Hold invoices A hold (HODL) invoice decouples HTLC acceptance from settlement. The caller generates a preimage, keeps it, and hands `sha256(preimage)` to `createHoldInvoice`. When the payer pays, the HTLC is validated and **parked**: the payer sees the payment as in-flight (PENDING) while the recipient decides. `settleHoldInvoice(preimage)` completes it (the payer receives the preimage); `cancelHoldInvoice(paymentHash)` fails it back as if the invoice were unknown. Parked HTLCs are restart-safe (they re-park from storage) and are **auto-cancelled** by the CLTV sweeper 18 blocks before the HTLC expiry, so a forgotten hold can never force an on-chain timeout. Typical uses: escrow-style flows, just-in-time inventory checks, atomic swaps (the reverse swap provider below mints them; the submarine provider pays a peer's ordinary invoice). Hold progress fires events (`hold:accepted`, `hold:settled`, `hold:cancelled`), relayed over SSE and webhooks. `hold:accepted` fires for each new parked part, including partial MPP payments. Before funding a swap, compare `BigInt(heldAmountMsat)` with the full expected amount in millisatoshis. The `ACCEPTED` state alone does not mean the invoice is fully funded. The final hop enforces the invoice's `minFinalCltvExpiry` on every arriving HTLC, and each event and `GET /invoices/held` row reports the realised `earliestExpiry` and `cancelHeight` of the parked set, so a swap provider can verify the Lightning leg outlives its on-chain refund before funding. #### Payments | Method | Returns | Description | |--------|---------|-------------| | `payInvoice(bolt11, opts?)` | `Promise` | Pay invoice. `opts: { timeoutMs?, maxFeeSats?, maxFeeMsat?, amountSats?, metadata?, cltvLimit? }`; the positional form `(bolt11, timeoutMs?, maxFeeSats?, amountSats?, metadata?, cltvLimit?, maxFeeMsat?)` is deprecated. **Blocks until settled or timeout** (default 60s). At the timeout the payment is failed only when no HTLC is out for it; with one still in flight the record stays `PENDING` until that HTLC resolves, no further route is tried after the timeout, and the record is failed when the HTLC fails or its on-chain timeout resolves; the `PAYMENT_TIMEOUT` message says so (issue #976). `maxFeeSats` caps routing fees in whole sats; `maxFeeMsat` (a number or a decimal string) caps them exactly, for a caller holding an exact quote such as `estimatePayment`'s `estimatedFeeMsat`; with neither, the cap is 1% of the amount, never below 50 sats. The spending limits count the amount plus the cap (see Spending Limits). Pass one or the other: both at once is refused with `INVALID_PARAMS`; a route over the cap is refused with `FEE_EXCEEDS_MAX` (409 over HTTP, permanent for `isRetryableError` and `payInvoiceWithRetry`) and nothing is sent. `amountSats` is required for amount-less invoices. `metadata` attaches key-value labels. `cltvLimit` caps the payment's total CLTV expiry at that many blocks above the current tip (every attempt, retry and MPP part); when no route fits it fails with `CLTV_EXCEEDS_MAX` and nothing is sent. A swap provider paying the counterparty's invoice sets it from the on-chain refund height (#751). | | `payInvoiceSafe(bolt11, opts?)` | `Promise` | Takes `payInvoice`'s options (the positional form is deprecated here too). Like `payInvoice` but **never throws**: catches all errors and resolves with the hash's existing record when there is one (after a timeout with an HTLC still out, the `PENDING` record, which no further route is tried for and which is failed when that HTLC fails or its on-chain timeout resolves; for a duplicate refusal, the record the engine refused from) and otherwise with `status: 'FAILED'`. The `failureDescription` field contains `[ERROR_CODE] message` for machine parsing. | | `sendPaymentAsync(bolt11, maxFeeSats?, amountSats?, metadata?, cltvLimit?)` | `{ paymentHash, status: 'PENDING' \| 'FAILED' }` | Fire-and-forget pay. Returns immediately, `FAILED` when the engine refused the submission outright (an expired invoice, an HTLC the channel would not take). Poll `getPayment()` for settlement. Drain mode and the spending limits are applied at submission, so it can throw `SERVICE_DRAINING` or `SPENDING_LIMIT_EXCEEDED`; the limits use the invoice's own amount whenever it carries one, since that is what gets paid. | | `payInvoiceWithRetry(bolt11, opts?)` | `Promise` | Pay with exponential backoff retry. `opts: { maxRetries? (3), backoffMs? (2000), maxFeeSats?, amountSats?, metadata?, cltvLimit? }`. Emits `payment:retry` events. | | `cancelPayment(paymentHash)` | `{ ok: true }` | Cancel a pending outbound payment (marks as FAILED). The HTLC cannot be retracted, so a cancelled payment keeps holding its amount against the daily limit until that HTLC settles or fails back, or the 24h window ends; `getDailySpendInfo().pendingSats` shows what is held. A payment with `unresolved` on its row is refused with `PAYMENT_UNRESOLVED`: it may have been paid. | | `listPayments(filter?)` | `PaymentInfo[]` | List payments sorted by createdAt desc. Filter by `status`, `direction`, `since`, `limit`, `offset`, `metadataKey`, `metadataValue`. Reads through to the node database: a completed or failed payment stays listed with its status after the engine prunes its in-memory record (24 hours after completion, oldest first past 10,000), however long the node has been running. A database read that fails fails the call rather than returning a shorter list. | | `getPayment(paymentHash)` | `PaymentInfo \| null` | Get specific payment: the in-memory record, else its database row, so a payment is found however long ago it completed | | `paymentOutcome(paymentHash)` | `'settled' \| 'live' \| 'gone'` | Where an outgoing payment stands, judged as the engine judges a duplicate: `settled` once paid, `live` while its record is `PENDING` or an HTLC for it can still settle, `gone` otherwise, when paying again cannot pay twice | | `setPaymentMetadata(paymentHash, metadata)` | `void` | Attach key-value metadata to an existing payment | | `sendKeysend(pubkey, amountSats, timeoutMs?, maxFeeSats?, metadata?, onPaymentHash?)` | `Promise` | Spontaneous payment (no invoice). **Blocks until settled or timeout** (default 60s), with the same timeout rule as `payInvoice`. Without `maxFeeSats` the routing fee is capped at 1% of the amount, never below 50 sats; the spending limits count the amount plus the cap. `onPaymentHash(hash)` is called before the HTLC goes out; a throw from it refuses the payment. | | `sendKeysendSafe(pubkey, amountSats, timeoutMs?, maxFeeSats?, metadata?)` | `Promise` | Like `sendKeysend` but **never throws** — resolves with `status: 'FAILED'` instead. | #### BOLT 12 Offers | Method | Returns | Description | |--------|---------|-------------| | `createOffer({ description, amountSats?, issuer? })` | `OfferInfo` | Create a reusable BOLT 12 offer | | `decodeOfferString(offerStr)` | `OfferInfo` | Decode a BOLT 12 offer string without paying | | `listOffers()` | `OfferInfo[]` | List local offers | | `payOffer(offerStr, amountSats?, timeoutMs?, maxFeeSats?, maxFeeMsat?, onPaymentHash?)` | `Promise` | Pay a BOLT 12 offer (requests invoice, then pays). **Blocks until settled or timeout** (default 60s), with the same timeout rule as `payInvoice`. Drain mode and the spending limits apply to the returned invoice's amount. `maxFeeSats` / `maxFeeMsat` cap the routing fee exactly as `payInvoice`'s do (one or the other; both at once is `INVALID_PARAMS`, judged before the invoice is requested). The cap covers the public hops plus the invoice's own blinded-path fee, which the payee writes into the invoice and which is otherwise paid unbounded (#1001); an invoice path over the cap is skipped for the invoice's other paths, and when none fits the payment is refused with `FEE_EXCEEDS_MAX` and nothing is sent. `onPaymentHash(hash)` is called with the invoice's hash before the HTLC goes out; a throw from it refuses the payment | #### Channel Readiness | Method | Returns | Description | |--------|---------|-------------| | `getReadyChannels()` | `ChannelInfo[]` | List channels that are NORMAL and will accept a new HTLC | | `canSend(amountSats)` | `{ canSend, bestChannelId?, availableSats }` | Check if you can send this amount (accounts for channel reserves) | | `canReceive(amountSats)` | `{ canReceive, bestChannelId?, availableSats }` | Check if you can receive this amount (accounts for channel reserves) | #### Route Estimation & Probing | Method | Returns | Description | |--------|---------|-------------| | `estimateRouteFee(bolt11, amountSats?)` | `RouteEstimate \| null` | Estimate fee without sending. Returns `{ feeSats, feeMsat, hops, cltvDelta }` or null. `feeSats` is rounded up, so it is safe to pass as `maxFeeSats`; `feeMsat` is the exact fee | | `probeRoute(destination, amountSats)` | `{ success, feeSats?, hops? }` | Probe route viability to a destination node | | `estimatePayment(bolt11, amountSats?)` | `PaymentEstimate \| null` | Full payment intelligence: success probability, route quality, estimated fee and time, warnings | #### Graph Queries | Method | Returns | Description | |--------|---------|-------------| | `getGraphInfo()` | `GraphInfo` | Node/channel counts + last gossip sync time this session | | `isGraphRestoring()` | `boolean` | Whether a deferred restore of the stored network map (`deferGraphRestore`) is still running | | `whenGraphRestored()` | `Promise` | Settles once the stored network map is back; false if a storage failure or `destroy()` cut it short. Never rejects | | `getGraphRestoreStats()` | `IGraphRestoreStats \| null` | How the stored network map came back as the node was built: rows read, stale and orphan rows, the graph left, the milliseconds of each step, and `constructMs`, the whole node build | | `getGraphNode(pubkey)` | `GraphNodeInfo \| null` | Node announcement info (alias, addresses, features) + its known channel SCIDs | | `getGraphChannel(scid)` | `GraphChannelInfo \| null` | Channel endpoints, capacity (from htlc_maximum_msat) and both directions' policies | | `describeGraph(limit?, offset?)` | `GraphDescribeResult` | Paged channel dump (limit defaults to 500, capped at 500) | | `queryRoute(destination, amountSats, maxFeeSats?)` | `RouteQueryResult` | Compute a route WITHOUT sending; hops feed `sendToRoute` | | `sendToRoute(paymentHash, route, paymentSecret?)` | `PaymentInfo` | Send a payment along an explicit route from `queryRoute`. Drain mode and the spending limits apply to what the first hop carries (the amount plus every fee in the route), which is what leaves the node, and the settlement is charged to the daily spend at that figure; the first hop must carry at least the final hop's amount (`INVALID_PARAMS` otherwise) | #### Payment Proof | Method | Returns | Description | |--------|---------|-------------| | `getPaymentProof(paymentHash)` | `PaymentProof \| null` | Cryptographic proof of a completed payment (preimage, invoice, route info) The proof of a payment that asset HTLCs carried has `auxiliary: true` and `auxiliaryValueSats`, since its `amountSats` and `feeSats` are the bitcoin that carried the asset. | | `verifyPaymentProof(paymentHash)` | `PaymentProofVerification` | Verify proof cryptographically: `sha256(preimage) === paymentHash`. Returns `{ valid, proof?, error? }` | #### Payment Queue | Method | Returns | Description | |--------|---------|-------------| | `enqueuePayment(bolt11, priority?, opts?)` | `QueuedPayment` | Add payment to priority queue (1-10, lower = higher priority). `opts: { amountSats?, maxFeeSats?, metadata? }` | | `listQueue()` | `QueuedPayment[]` | The queued and dispatching entries, with the 1000 most recently finished | | `getQueuedPayment(id)` | `QueuedPayment \| undefined` | One queue entry by id, whatever its status, from memory or the database | | `listQueueHistory(opts?)` | `QueuedPayment[]` | Finished entries, the most recently finished first. `opts: { limit?, before? }`: up to `limit` (default 100, at most 1000), after the entry with id `before` | | `cancelQueuedPayment(id)` | `boolean` | Cancel a queued payment by ID | | `resolveInterruptedPayment(bolt11)` | `Promise` | How a payment the queue was dispatching ended (one a restart interrupted, or one still out at the queue's payment timeout), from the node's record (in memory, then on disk): `{ status: 'completed', paymentHash }` or `{ status: 'unpaid' }`, once every HTLC offered for it is resolved. The queue's resolver for such an entry | | `whenReadyToPay(run)` | `void` | Calls `run` once the node can pay: after a pending guardian restore, once the node is ready, and once some channel can carry an HTLC (or there is no channel); never after shutdown | Entries survive a restart. The queue dispatches the restored ones once some channel can carry an HTLC after the start (or no channel is left that could), and looks again on every `channel:usable`, without waiting for another enqueue. A payment enqueued before that dispatches on its own; the restored ones wait. An entry left `dispatching` by a restart is checked against the node's record for its invoice before anything sends it again: a payment that was made is recorded `completed`, one whose HTLCs are still out stays `dispatching` until they resolve, and only one that paid nothing is queued again (issue #967). A `PaymentQueue` built without a `resolveInterrupted` option records such an entry `failed` instead, and one you build yourself dispatches restored entries only once you call `start()`. A dispatch whose HTLC is still out when the queue's own payment timeout fires (60 s by default) is not recorded `failed` either: it stays `dispatching`, its concurrency slot is released, and it is recorded from the node's outcome through the same check, `completed` when the payment settles and `failed` ("Payment was left pending by the dispatch and then failed without paying") once every HTLC resolved with nothing paid; it is not queued again in this process; a restart settles it like any interrupted entry, and one that paid nothing is then queued again. An entry the resolver could not answer (no node to ask yet) is asked about again on `start()` and on `resettle()`, which the daemon calls once a capsule resume has rebuilt the node; a `PaymentQueue` you build yourself calls `resettle()` itself. A `PaymentQueue` without a resolver records such a dispatch `failed` with its outcome unknown, for you to look up before paying that invoice again (issue #976). `amountSats` and `maxFeeSats` must be whole numbers of satoshis, zero or greater; `enqueuePayment` (and `POST /queue/add`) refuses anything else with `INVALID_PARAMS`. An entry whose amount is in its invoice rather than in `amountSats` waits for capacity for that amount just as one with `amountSats` does, instead of being dispatched unchecked into "no route" (issue #981); a `PaymentQueue` you build yourself gets this by passing `invoiceAmountSats`, a callback that returns the invoice's amount in whole satoshis, since the queue never decodes an invoice itself. The daemon and `BeignetNode` share one queue per process: the routes under `/queue` and `enqueuePayment`/`listQueue`/`cancelQueuedPayment` serve the same `PaymentQueue`, which persists through the node's current storage, so it keeps working after an in-process capsule restore replaces the database (issue #978). Memory holds every queued and dispatching entry but only the 1000 most recently finished ones, so a long-running queue neither grows nor slows with its history; a `PaymentQueue` you build yourself sets this with `maxRetainedHistory` (`Infinity` keeps them all). The older ones stay in the database: `getQueuedPayment(id)` (`GET /queue/entry`) finds any entry, and `listQueueHistory` (`GET /queue/history`) pages through every finished one. Only `PaymentQueue.prune()` deletes queue history, and it never touches a queued or dispatching entry (issue #1866). #### Liquidity & Channel Intelligence | Method | Returns | Description | |--------|---------|-------------| | `getLiquiditySnapshot()` | `LiquiditySnapshot` | Liquidity analysis with actionable recommendations (OPEN_CHANNEL, CLOSE_CHANNEL, REBALANCE) | | `getChannelSuggestions(count?)` | `ChannelSuggestion[]` | Graph-based channel open suggestions scored by connectivity, capacity, freshness, relevance | | `getFeeSnapshot()` | `FeeSnapshot \| null` | On-chain fee trend analysis with open/wait recommendation | | `getAdvisorRecommendations()` | `AdvisorRecommendations` | Liquidity analysis plus the concrete circular-rebalance plan (read-only) | | `rebalanceChannel(fromId, toId, amountSats, maxFeeSats)` | `Promise` | Circular rebalance (self-payment out fromId, back in toId). Aborts without paying if the route fee exceeds `maxFeeSats`. The fee counts against `dailySpendLimitSats` A rebalance that names an asset channel, from or to, is refused with `INVALID_PARAMS` before the fee cap is charged. | | `executeRebalances(budgetSatsPerDay?)` | `Promise` | Run the advisor's rebalance plan under a per-UTC-day fee budget (persisted; restarts never overspend the day). The fees count against `dailySpendLimitSats` | | `listPrimaries()` | `PrimariesInfo` | The ranked receive primaries (issue #1922): each one's `rank`, address, `thresholdSat`, `balanceSat` (our local balance summed over our usable channels with it), `channelCount`, `belowThreshold`, `isReceiveTarget` and `selectionOrder`, plus `fillThresholdSat` and `receiveTarget`. The target is the first primary in rank order below the threshold; when every one is at or above it, the lowest balance, ties to the higher rank. `createJitInvoice`, `getJitQuote`, `createDirectFundingRequest` and the `/receive/*` routes walk `selectionOrder` when the caller names no peer | | `addPrimary({ pubkey, host?, port?, uri?, rank? })` | `PrimariesInfo` | Add a primary at `rank` (1-based, default last), reached by `host`/`port` or by a `uri` (`pubkey@address`, ws://, wss:// and iroh: included). Refuses a malformed pubkey, a duplicate, a bad port, a host without a port, an out-of-range rank or a 33rd entry with `INVALID_PARAMS`. Persisted | | `removePrimary(pubkey)` | `PrimariesInfo` | Drop a primary (`INVALID_PARAMS` when it is not one). Its channels are left as they are. Persisted | | `reorderPrimaries(pubkeys)` | `PrimariesInfo` | Re-rank: `pubkeys` names every primary once, highest rank first (`INVALID_PARAMS` otherwise). Persisted | | `setPrimariesFillThreshold(sats \| null)` | `PrimariesInfo` | Sats of local balance a primary is filled to before receives move on; `null` for no cap. A negative or fractional value is `INVALID_PARAMS`. Persisted | Automatic execution is **off by default**: pass `autoRebalance: { enabled: true, budgetSatsPerDay, minImbalancePct }` and/or `autoTuneFees: { enabled: true, intervalMs, floorPpm, ceilPpm }` in `BeignetNodeOptions` to turn on the periodic rebalance scan and routing-fee (ppm) auto-tuning. #### Statistics | Method | Returns | Description | |--------|---------|-------------| | `getStats(windowMs?)` | `NodeStats` | Payment stats with optional time window. Includes `avgPaymentTimeSec` and `avgFeePct` when data available | #### Database Backup | Method | Returns | Description | |--------|---------|-------------| | `backup(destPath)` | `Promise` | Create online backup of SQLite database, with its MAC in `.hmac` | | `backupAssetChannelFrame(channelId, destPath)` | `Promise` | Export an encrypted recovery frame for one funded generation 5 regtest channel to a new file | | `storageFiles()` | `string[]` | The live database, its sidecars and the instance lock (paths `POST /backup` refuses to write over) | Storage encryption: the SQLite database is encrypted at rest by default with a key derived (HKDF-SHA256) from the wallet's BIP39 seed. Sensitive payloads (channel state, preimages, payment secrets, invoices, payments, chain-monitor state) are AES-256-GCM encrypted, so backups made with `backup()` are encrypted too; restoring one requires the same mnemonic. Pre-encryption databases are migrated in place on first open. Set `storageEncryption: false` to opt out (plaintext storage). Lookup columns (payment hashes, channel ids, peer pubkeys, gossip) stay plaintext, so the database file, its sidecars and every backup are created `0600` and the data directory `0700` (see [File permissions](#file-permissions)). #### Static Channel Backup (SCB) | Method | Returns | Description | |--------|---------|-------------| | `exportStaticChannelBackup()` | `{ encoded, channelCount, path }` | Build, encrypt, and write the static channel backup | A static channel backup is a small, portable, versioned blob holding the minimum needed to recover funds for every open channel without the full database: per channel it records the channel id, peer node id and last-known addresses, funding outpoint (txid internal byte order + output index), capacity, per-channel key index, channel type, role, and taproot/anchor flags. The blob is JSON encrypted with AES-256-GCM under a key derived (HKDF-SHA256, info `beignet-scb-v1`) from the wallet's BIP39 seed, encoded as `beignet-scb-v1:` + base64 - it is useless without the mnemonic. The file is written atomically to `/channels.scb` and refreshed automatically whenever the channel set changes (channel open/splice calls, `channel:ready`, `channel:closed`, and channel resolution). Store a copy off-machine (e.g. via `beignet backup scb ` or `GET /backup/scb`). #### Automatic Peer Backup (BOLT 1 peer storage) | Method / Command | Returns | Description | |--------|---------|-------------| | `getPeerRetrievedBackup()` | `{ encoded, createdAt, fromPeer, channelCount, source } \| null` | Most useful valid SCB a peer returned this session, directly (`source: 'scb'`) or embedded in a Recovery Capsule (`source: 'capsule'`, re-encoded under the wallet seed); an empty backup never displaces one naming channels (daemon: `GET /backup/peer-retrieved`; CLI: `beignet backup peer-retrieved`) | With `peerStorageEnabled` (default true) the node advertises `option_provide_storage` and uses it in both directions: - **Our backup, held by peers.** Every SCB refresh is pushed as an opaque `peer_storage` blob to each connected peer that advertises the feature, and each such peer returns its held copy via `peer_storage_retrieval` on every reconnect. Recovery-from-nothing: reinstall with the mnemonic, connect to your old peers, read `GET /backup/peer-retrieved`, and feed its `encoded` blob to `POST /restore/scb`. Nothing is restored automatically - recovery stays explicit, and SCB recovery never broadcasts a stale commitment, so a peer returning an old blob is harmless. - **Trust model.** Peers only ever see the seed-encrypted `beignet-scb-v1` ciphertext; without the mnemonic it is useless to them. Blobs returned by peers are untrusted input: anything that does not decrypt as our own SCB is ignored, and among valid ones only the newest (`createdAt`) is kept. - **Storing for peers.** In return the node holds ONE blob (max 65531 bytes, newest wins) per peer it has a non-closed channel with or trusts (zero-conf trusted set), accepts at most one blob per peer per 60 seconds, and sends it back on every reconnect. Blobs from strangers are dropped. Stored blobs live in the `peer_storage_blobs` table, encrypted at rest like the rest of the database. #### Restore | Method / Command | Returns | Description | |--------|---------|-------------| | `restoreFromScb(encoded)` | `Promise<{ recovering, skipped, channelCount }>` | Recover channels from an SCB blob (daemon: `POST /restore/scb` with `{ encoded }` or `{ path }`; CLI: `beignet restore scb `) | | `beignet restore db [--unauthenticated]` | JSON result | Copy an authenticated database backup into place (OFFLINE, local CLI operation - no daemon call) | | `beignet restore asset-channel ` | JSON result | Repair one funded regtest asset channel on its enrolled original device while the daemon is stopped. | | `restoreFromGuardians()` | `Promise<{ exact, framesApplied, guardiansRepaired, epoch }>` | Restore from guardian replicas and start the node on the restored state (daemon: `POST /recovery/restore` with `{ confirm: true }`; CLI: `beignet recovery restore`) | | `restoreFromCapsules({ unfenced?, omitAssetChannels? })` | `Promise<{ tier, channelCount, framesApplied, head, newestSeenHead, rejectedCandidates, restartRequired, unfenced?, recovering?, skipped?, omittedAssetChannels? }>` | Peer-storage mode: restore from the Recovery Capsules storage peers returned this session (daemon: `POST /recovery/restore-capsule` with `{ confirm: true }`; CLI: `beignet recovery restore-capsule`). Tier 2 installs the exact state into a fresh database and holds the daemon until a restart; Tier 1 recovers the embedded SCB on the live node. `omitAssetChannels: true` leaves the asset channels the capsule holds out in place of refusing the restore, and lists them in `omittedAssetChannels` as `{ channelId, peerPubkey, capacitySats }`; the payments that were in flight on one are listed by hash in `unresolvedPayments` and stay PENDING with `unresolved` on their rows ([docs/EXTENSIONS.md](../../docs/EXTENSIONS.md)) | After a regtest channel enrolled with `--asset-splice-recovery` is funded and ready, run `beignet backup asset-channel ` to save an encrypted local recovery frame. Choose a new filename for each export. Frames taken before and after a splice are hash-linked on the original device. Keep the asset extension's matching recovery backup alongside the engine backup. Both `--asset-splice` and `--asset-splice-recovery` wallets also support a full SQLite snapshot through `beignet backup `. Keep its `.hmac` file. To repair one channel, stop the daemon on the enrolled device and run `beignet restore asset-channel ` with its original database, signer and device journal present. The command recognizes either supported format, restores missing opening records and checks the saved journal prefix against the device's current history. The result reports `snapshotSequence` and `currentSequence` for the splice journal, plus `frameSequence` for a channel frame. An earlier backup can recover later confirmed payouts using the records on that device. Guardian and peer-storage recovery have their own formats. - **SCB restore = on-chain recovery only.** The backup holds no commitment state, so the channels themselves cannot be resumed. Each entry is reconstructed as a broadcast-banned channel (`ERRORED`, data-loss flagged - the node will never publish its own stale commitment), the funding outpoint is watched, and the peer is contacted so the normal reestablish exchange proves our state stale. The honest peer then force-closes with ITS commitment and the node sweeps only our `to_remote` balance to the wallet. Funds arrive on-chain after the peer's force-close confirms; in-flight HTLCs and anything beyond `to_remote` are not recoverable this way. The blob decrypts only with the wallet mnemonic, and a backup taken on another network is refused. - **DB restore = full state.** `beignet restore db ` copies a backup made with `backup()` over `/.db`. The node must be STOPPED: the command refuses while a daemon holds the wallet's single-instance lock (and holds that lock itself during the copy). Every backup is written with an HMAC-SHA256 of the whole file in `.hmac`, under a key derived (HKDF-SHA256, info `beignet-db-backup-mac-v1`) from the wallet seed; keep the two files together. The restore copies the backup next to the database, and refuses it unless that copy is a SQLite database whose MAC matches, so a backup modified by anyone without the mnemonic (or made by another wallet) never replaces the live database. Any existing database is preserved at `.pre-restore-` first, and stale `-wal`/`-shm` sidecars are moved aside so they cannot corrupt the restored file. The database is encrypted under the wallet seed, so the node must be started with the same mnemonic that made the backup. Backups made before backups carried a MAC have no `.hmac` file and are refused; restore one with `--unauthenticated` only when you know it was not modified, then take a fresh backup once the node is running. The MAC proves the backup is yours, not that it is current, and a peer holding a newer state can hide that at reestablish and wait for the node to broadcast a commitment it has already revoked. So the restore leaves a marker (`.restored`), and the next start puts every open channel under the same hold a capsule restore gets (`restoreRecencyUnproven`): channels resume and existing HTLCs settle, but the node never force-closes one on its own and takes no new HTLCs. Closing one from this node, cooperatively or by force, needs `acceptStaleStateRisk: true`; the safe exit is the peer's own close. Prefer the most recent backup, and rely on SCB recovery when in doubt. - **Guardian restore = resume the channels.** With the Recovery Protocol in a guardian mode (below), the node's safety-critical state is replicated as an encrypted journal to a 2-of-3 guardian set, and a restore reconstructs the exact channel state and RESUMES the channels via `channel_reestablish` instead of force-closing. See "Guardian recovery" next. #### Hosting a guardian (bolt8) Any beignet node that listens for peers can serve the reference guardian to other beignet nodes (docs/RECOVERY-GUARDIAN-WIRE.md 2.7, issue #699). Start it with `BEIGNET_GUARDIAN_SERVE=true`; the guardian is reached at the node's ordinary Lightning address, over a dedicated BOLT 8 session the writer opens under a fresh key, so the host never learns which Lightning node it guards. Its guardian id is derived from the node seed, so a node rebuilt from its seed keeps the same id. A wallet adds it by resolving the node's URI (`beignet recovery resolve-guardian @host:port`, or the daemon's `POST /recovery/resolve-guardian`) to an entry of the form `@bolt8://@host:port`, and pins that in `BEIGNET_RECOVERY_GUARDIANS` like any other guardian. A host keeps serving while its own writer lease is quarantined (the guardian-only lane), so nodes that guard each other can restart together. Quotas (`BEIGNET_GUARDIAN_MAX_BYTES`, `_MAX_SETS`) refuse new writes rather than delete, because pruning a namespace wedges a stranger's node for good. A set still shrinks: each writer tells its guardians which snapshot all of them hold, and they free the records below it. #### Rotating guardians A wallet's guardian set is no longer fixed for life (docs/RECOVERY-GUARDIAN-WIRE.md 5.9, issue #701). `beignet recovery rotate-guardians ` (or `POST /recovery/rotate-guardians`) moves the wallet to a new set, one member or all three, without closing a channel: the daemon registers the namespace with the incoming set under its current lease at the next generation, backfills the retained journal until two of the incoming three hold the tip, switches in one transaction, and retires the outgoing set with `ROTATE_SET`. A restore device still configured with the outgoing set reads the rotation off any outgoing guardian and follows it to the live set by itself; `GET /recovery/status` reports the `generation`, `configuredSetStale` once the env lags the journal, and `rotation.followed` on a boot that followed one. A previous device still running on the outgoing set freezes the moment it sees the new generation, in a capsule or in a guardian's answer. A rotation interrupted by a crash resumes once the gate confirms; a retirement the outgoing set has not accepted yet is retried in the background. A wallet that has journaled nothing yet (`lastDurableSequence` `"0"`) rotates too, for example to swap a member before first use (issue #862). With no journal on disk an unused wallet and a wallet that lost its journal look the same, so the switch waits until both sets confirm the namespace holds nothing, with at least two members of each answering. If a set holds records this journal does not, the rotation is refused with `ROTATION_UNAVAILABLE` (409) and the outgoing set is left untouched: restore instead of rotating. If too few members answer, it is refused with `ROTATION_NO_QUORUM`. If the wallet's first entry lands while the sets are being asked, it is refused with `ROTATION_NOT_CATCHING_UP`, and a retry completes it. A pending or refused rotation never blocks the wallet's first durable write. #### Guardian recovery (Recovery Protocol) The Recovery Protocol (docs/RECOVERY-PROTOCOL.md) is configured entirely through env/config, following the other `BEIGNET_*` settings: ```bash BEIGNET_RECOVERY_MODE=quorum # off | peer-storage | async-remote | quorum BEIGNET_RECOVERY_GUARDIANS=<64-hex-pubkey>@https://g1.example,<64-hex-pubkey>@https://g2.example,<64-hex-pubkey>@http://.onion BEIGNET_RECOVERY_PROFILE=crash-v1 # optional; crash-v1 is the only value BEIGNET_RECOVERY_REESTABLISH_HOLD_MS=600000 # peer-storage only; 0 disables BEIGNET_RECOVERY_AUTO_APPLY=false # peer-storage only; apply the best capsule on an empty boot, no operator call BEIGNET_RECOVERY_AUTO_APPLY_SETTLE_MS=15000 # wait this long after the first capsule for slower replicas BEIGNET_RECOVERY_AUTO_APPLY_MAX_WAIT_MS=120000 # never wait longer than this; must fit inside the hold ``` - `off` (default): nothing changes. - `peer-storage`: the encrypted recovery journal is kept locally and a Recovery Capsule (SCB + journal) is distributed over BOLT 1 peer storage. No guardians involved, so no fencing between devices either. Restore: boot the same mnemonic on a FRESH data dir in this mode (an empty node pushes nothing, so the peers keep the capsule), connect to the peers the node had channels with, check `capsules` on `GET /recovery/status`, then `POST /recovery/restore-capsule` with `{ "confirm": true }`. Connecting before you restore is safe: in this mode the node HOLDS a peer's `channel_reestablish` for a channel the empty database has no record of instead of answering it with the BOLT 1 unknown-channel error, which would make the peer force-close the channel the restore is about to resume (issue #462). `GET /recovery/status` lists each held peer under `node.heldReestablish` with the `expiresAt` you have to beat; past that the error goes out as before. The window is `BEIGNET_RECOVERY_REESTABLISH_HOLD_MS` (default 600000; 0 answers immediately) and it is granted once per peer and channel. When an inline journal validates (Tier 2) the exact state is installed into a fresh database, the daemon holds in the `restart-required` state (every route but the recovery surface answers 503 `NODE_RESTART_REQUIRED`) and a restart resumes the channels; the previous database is kept beside it as `.db.pre-capsule-restore-`, and API-key revocations, webhooks and peer addresses follow into the restored one. The swap is crash-safe: a marker (`.capsule-restore.json`) lets the next boot finish an interrupted swap. Otherwise (Tier 1) the embedded SCB is recovered on the live node like `POST /restore/scb`. A Tier 2 restore brings the channels back HOLDABLE, not fully live. A capsule is best-effort recency by construction and a compatible `channel_reestablish` proves compatibility, not recency, so every restored channel carries `restoreRecencyUnproven` on `GET /recovery/status` for the rest of its life. While it is set the daemon never force-closes that channel on its own initiative (a peer error and the reestablish/errored timeout backstops are all held, and the channel asks its peer to close instead), and the channel takes no new HTLCs, since the on-chain HTLC deadline backstops that would enforce them can never fire. Existing HTLCs still settle and fail, and the balance is intact. A cooperative close is refused by default in BOTH directions too: a mutual close pays out the balances the restored row carries, and a stale capsule's allocation can only be the peer-favourable one, since any payment received after the checkpoint is missing from it. An ERRORED one reports `status: "restore_recency_unproven"` rather than `force_closing`. The exits are the peer closing, or the operator's labelled acknowledgement on either close: `beignet channel close --accept-stale-state-risk` (`POST /channel/close` with `acceptStaleStateRisk: true`) accepts the stale-split risk and covers the whole negotiation, and `beignet channel forceclose --accept-stale-state-risk` (`POST /channel/forceclose` with `acceptStaleStateRisk: true`) accepts that publishing a commitment the peer may already have revoked forfeits the whole channel balance. Both are refused without the flag. The FFOR enforcement routes publish the same commitment and take the same flag: `POST /ffor/enforce`, and `POST /ffor/recover` with `forceCloseIfUnreachable: true`, are refused on such a channel without `acceptStaleStateRisk: true` (issue #908). The same hold has a second origin (issue #907): a peer whose `channel_reestablish` claims this node is behind (a `next_revocation_number` above anything this node released) without showing the per-commitment secret that would prove it, all zeroes included. The channel fails with a wire error, is ERRORED, and carries `reestablishRecencyUnproven` on `GET /recovery/status` with `status: "reestablish_recency_unproven"`: no automatic close, no new HTLCs, the peer asked to close on every reconnect. A hostile peer can put a healthy channel here at no cost, so the exit is the same labelled acknowledgement, `beignet channel forceclose --accept-stale-state-risk`, refused without it with wording for this case. A third origin is a LOCAL fault (issue #919): this node's own `channel_reestablish` could not be built, because its shachain store holds no per-commitment secret at the index its revocation counter names. BOLT 2 permits an all-zero `your_last_per_commitment_secret` only at `next_revocation_number` 0, so there is no honest value to send above it and nothing is sent: the peer gets a BOLT 1 error saying only that this node cannot produce the message (naming the missing secret would tell a peer where its own revoked commitments may go unpunished), and the operator gets a `node:error` with code `REESTABLISH_SECRET_MISSING` naming the channel, the revocation index and the exit, plus a `reestablish_secret_missing` structured log. The channel carries `reestablishSecretMissing` on `GET /recovery/status` with `status: "reestablish_secret_missing"` and the same hold: no automatic close, no new HTLCs, the peer asked to close on every reconnect, and `beignet channel forceclose --accept-stale-state-risk` as the operator exit, refused without the flag with wording for this case. The hold is PERMANENT: a shachain store cannot regrow a secret it never wrote, so the peer's close and the acknowledged force close are the only two exits. `GET /channel//diagnostics` reports it as `HELD_SECRET_MISSING`. Either hold disarms the on-chain HTLC deadline backstops, so each one that declines to close announces it: a `node:error` with code `HTLC_DEADLINE_HELD` (on the SSE stream and the `onError` callback), carrying the channel, the HTLC id and payment hash, its `cltv_expiry`, the current height, which hold it is and the acknowledged force close that is the exit. Throttled per HTLC per backstop, roughly hourly, so a hold standing for weeks does not flood the stream. A peer can put a channel into the reestablish hold at no cost, and only an operator can take it out before a CLTV deadline passes, so these are the events to alert on. The same acknowledgement is required on those FFOR routes for the reestablish and secret-missing origins. The `ffor:enforce` event carries `restoreRecencyUnproven: true`, `reestablishRecencyUnproven: true`, `reestablishSecretMissing: true`, or several of them, matching the channel's holds, so the embedder knows to ask. - `async-remote`: the journal also replicates in the background to the guardian set (exactly three `pubkey@url` entries; the pubkey is the guardian's x-only identity key). Wire traffic never waits on guardians. - `quorum`: safety-critical wire messages (`revoke_and_ack`, `update_fulfill_htlc`, ...) are additionally HELD until the journal frame behind them is acknowledged by 2 of 3 guardians. This is the strongest tier: a device destroyed at any moment restores on new hardware and resumes its channels, and the epoch takeover fences the old device if it ever comes back. Operational notes: - A malformed guardian entry, a wrong guardian count, or guardians configured without a guardian mode REFUSE daemon startup: silently dropping a guardian would change the quorum arithmetic. An unknown `BEIGNET_RECOVERY_MODE` value falls back to `off` (the usual typo rule), but never silently: a database already marked quorum then refuses to start unbarriered at the library level, and configured guardians beside a typo'd mode refuse too. - In the guardian modes the node boots QUARANTINED: it makes no peer connections until a guardian quorum confirms this device still owns the writer lease (split-brain protection). If the guardians are unreachable at boot, the daemon and its API come up, peer traffic waits, and confirmation retries on a backoff; `GET /recovery/status` shows `gate: "quarantined"`. A normal restart does NOT need the guardians reachable: the persisted lease short-circuits the boot decision, only the confirmation waits. - Once confirmed, an idle node re-checks its lease with the guardians every `BEIGNET_RECOVERY_LEASE_CHECK_MS` (default 300000; 0 disables) so a device superseded while parked reports `fenced` within that window instead of at its next commit or restart. An outage never changes the gate. - A fenced device was taken over by another restored from the same seed, and every update that device made revoked a commitment this one still stores. So while the gate is `fenced`, and while it is `quarantined` (where a takeover cannot yet be ruled out), every force close route (`/channel/forceclose`, `/ffor/enforce`, `/ffor/recover` with `forceCloseIfUnreachable`) is refused without `acceptStaleStateRisk: true` (issue #1013). Close from the device that took over instead, or let the peer close. - Restore-from-nothing: start the daemon with the same mnemonic, the same guardian set, and a FRESH data dir. The boot detects the namespace on the guardians and holds in a restore-pending state where only `GET /recovery/status`, `POST /recovery/restore`, `GET /events`, `GET /openapi.json` and `POST /stop` answer (everything else returns 503 `NODE_RESTORE_PENDING`; `/health` reads as not-ready, which is true). `POST /recovery/restore` with `{ "confirm": true }` performs the guardian takeover, streams `recovery:restore-progress` events over SSE/webhooks, builds the node on the restored state, and returns the restore report. The confirm flag is required because the takeover permanently fences any still-running previous device. The restore is crash-safe and re-runnable. - Lost the guardian set too: every capsule a guardian-mode node pushes names its guardians. Boot the fresh data dir in `peer-storage` mode (it pushes nothing while empty), connect to the peers the node had channels with, read `capsules.best.guardians` on `GET /recovery/status` (`guardianId` plus transports; credentials are never reported there), rebuild `BEIGNET_RECOVERY_GUARDIANS` as `@` entries and restart in the guardian mode: that boot holds restore-pending as above. When the guardians require a transport credential, `beignet recovery capsule-guardians` (`POST /recovery/capsule-guardians`, admin scope, `{ "confirm": true }`) hands back the set WITH credentials as config-file entries: put them under `recoveryGuardians` in the config file as objects `{ "guardianId", "url", "auth" }` (the env form stays `pubkey@url`; a URL must not carry userinfo, credentials go in `auth`). A running guardian-mode node only reports a capsule's set, it never adopts one; a set that differs from the configured one is logged as a warning. - `POST /recovery/restore-capsule` refuses a capsule that names guardians by default (409 `CAPSULE_RESTORE_GUARDIAN_BACKED`): that state belongs to a guardian-backed namespace and restores through the guardian set with fencing, not from peer storage, and not by force-closing channels the guardians could resume exactly. The emergency SCB-only path is unchanged: `GET /backup/peer-retrieved` plus `POST /restore/scb`. A quorum-durability journal is refused whether or not the capsule names guardians (409 `CAPSULE_RESTORE_QUORUM_NAMESPACE`; capsules from before locators existed carry none): it cannot boot without its quorum. - Guardian set gone for good: `{ "confirm": true, "unfenced": true }` (`beignet recovery restore-capsule --unfenced`) is the labelled escape hatch from spec 5.7. It restores the capsule anyway and CANNOT fence the previous writer: if that device still runs, it keeps acting on the same channels. The report carries the named guardians under `unfenced`, and the restore progress stream says so. It is the only exception to the default refusal, and it never applies to a quorum-durability journal: such a chain refuses to boot without its quorum, so its only paths are the guardians or the SCB route. - Zero-touch peer-storage restore (issue #690): with `BEIGNET_RECOVERY_AUTO_APPLY=true` the daemon performs the capsule restore itself on a boot whose database is empty. Every capsule a storage peer returns is announced as `recovery:capsule-retrieved`; the first arrival opens a settle window, and the best capsule is applied once every connected storage peer has answered and `BEIGNET_RECOVERY_AUTO_APPLY_SETTLE_MS` (default 15 s) has passed, or at `BEIGNET_RECOVERY_AUTO_APPLY_MAX_WAIT_MS` (default 2 minutes) at the latest, which must fit inside the reestablish hold. A Tier 2 install then rebuilds the node in-process on the restored database (no restart; `recovery:restored` carries `resumed: true`), and channels the capsule's journal did not carry are named in a `capsule:uncovered` progress event and recovered through the peer (they close safely, the SCB degradation). The flag automates an UNFENCED adoption: local durability cannot fence a previous device that still runs, so an embedder asks the operator once (at seed import) rather than defaulting it on. Refusals are the manual route's, made once and reported under `autoApply.lastReason` on `GET /recovery/status` (phases `idle`, `settling`, `applying`, `applied`, `refused`); a database that already holds state is never a target. A capsule that holds asset channels is refused as the route refuses it and no channel is left out without being asked: `autoApply.refusal` then holds the route's code and its `assetChannels` list, the `capsule:auto-refused` progress event carries the same `refusal`, and the capsule stays a candidate for the confirmed call with `omitAssetChannels`. At Tier 1, where an asset entry of the backup is skipped and the rest recovered, the entries skipped are listed under `autoApply.skippedAssetChannels`. - Recovery events relayed over SSE and webhooks (always on): `recovery:durable`, `recovery:fenced`, `recovery:backfill-lost`, `recovery:reestablish-held`, `recovery:capsule-retrieved`, `recovery:guardian_unreachable`, `recovery:restore-progress`, `recovery:restored`. #### Health & Monitoring | Method | Returns | Description | |--------|---------|-------------| | `getHealth()` | `HealthInfo` | Node health: status, uptime, block height, electrum, peers, channels, graph | | `getChannelHealth(channelId)` | `ChannelHealth \| null` | Channel liquidity health: balance %, HTLC slot usage, warnings | | `getMainnetReadiness()` | `ReadinessReport` | Weighted readiness checklist (storage, chain backend, channels, fees, etc.) | | `getMetrics()` | `string` | Prometheus text exposition format metrics (channels, payments, balances, peers, uptime, etc.) | | `triggerBackup()` | `Promise` | Trigger an on-demand backup (requires `backupPath` configured) | | `getActionLog(options?)` | `ActionLogEntry[]` | Query persistent action log. `options: { category?, since?, limit? }` | | `getNodeUri(externalHost?)` | `string \| null` | Node connection URI (`pubkey@host:port`). Returns null if not listening. | | `getNode()` | `LightningNode` | Access the underlying LightningNode for event wiring | #### Waiting | Method | Returns | Description | |--------|---------|-------------| | `waitForReady(timeoutMs?)` | `Promise` | Wait for node to be fully operational (peers reconnected, channels restored). Default 30s timeout. | | `waitForChannelReady(channelId, timeoutMs?)` | `Promise` | Wait for channel to reach NORMAL state (default 60s timeout) | | `waitForPayment(paymentHash, timeoutMs?)` | `Promise` | Wait for payment to settle (default 60s timeout) | #### Spending Limits > **SEMANTICS CHANGE: the daily spend limit is now a COMBINED Lightning + > on-chain budget.** It previously covered Lightning payments only. If you > rely on `dailySpendLimitSats`, external on-chain sends now consume the same > budget: `sendOnchain` (`POST /send`) and `sendMaxOnchain` > (`POST /send-max`) each count **amount + fee** against the daily limit and > are rejected with `SPENDING_LIMIT_EXCEEDED` once it is exhausted. For > send-max the check runs against the actual computed sweep total before > broadcast. An address-targeted `spliceOut` and `sendDirectFunding` > (`POST /direct-funding/send`) count the same way; direct funding is charged > its amount plus the fee ceiling it was given, because the exact fee is only > known once the receiver has built the transaction. Excluded by design (they > are not external spends): `consolidateUtxos` (self-pay), our own channel > opens/splices/funding, and > `bumpFeeOnchain`/`boostOnchain` (fee-only). PSBT building is also not > counted (nothing is broadcast). Resets at midnight UTC. `maxPaymentSats` covers the same external on-chain sends, judged on the same figure as the daily limit: `sendOnchain`, an address-targeted `spliceOut` and `sendDirectFunding` on the amount plus the fee, and `sendMaxOnchain` on the whole sweep. The exclusions above are outside it too. Circular rebalances (`rebalanceChannel`, `executeRebalances` and their routes) are refused with `SERVICE_DRAINING` while the node drains, and with `NODE_DESTROYED` once a shutdown starts, before anything is charged. A drain or shutdown that starts during an `executeRebalances` run stops the plans it has not tried yet. The amount comes back to the node, so only the routing fee counts against the daily limit. The day is charged `maxFeeSats` (`rebalanceChannel`) or the day's advisor fee budget (`executeRebalances`) when the call starts, and gets back what the fees actually paid did not use when it returns. A rebalance whose wait times out, or that a shutdown or crash interrupts, keeps its fee cap charged, because its HTLC can still settle. `maxPaymentSats` does not apply to them. Each `autoRebalance` run is an `executeRebalances` call, so all of this holds for it too. Every invoice payment (`payInvoice`, `payInvoiceSafe`, `payInvoiceWithRetry`, `sendPaymentAsync`, the queue and their routes) is checked and recorded at the amount that actually gets paid: the invoice's own amount whenever it carries one, and `amountSats` only for an amount-less invoice. A fractional msat amount rounds up. `payOffer` is checked and recorded the same way, against the amount of the BOLT 12 invoice the payee returns for the offer, which is what gets paid whatever `amountSats` asked for. Routing fees count too (issue #1008). Every Lightning pay path (`payInvoice`, `payInvoiceSafe`, `payInvoiceWithRetry`, the queue, `sendPaymentAsync`, `sendKeysend`, `payOffer` and their routes) sends under a fee cap: the caller's `maxFeeSats` / `maxFeeMsat`, or, when none is given, 1% of the amount rounded up and never below 50 sats. `maxPaymentSats` and the daily limit are judged on the amount PLUS that cap at admission, and the day is charged the amount plus the fee actually paid at settlement (the reservation stands in for a settlement whose record cannot say what it cost). A payment that fits a limit on its amount alone but not with its cap is refused with `SPENDING_LIMIT_EXCEEDED`, and the message says to lower `maxFeeSats` or the amount. `sendToRoute` and `POST /payment/send-to-route` are admitted and charged on what the first hop carries, which is the amount plus every fee in the route, with no cap on top. `validatePayment(bolt11, amountSats?, maxFeeSats?)` previews the same judgement for a BOLT 11 payment; `estimatePayment` and `estimateRouteFee` preview the amount. A settlement that lands while the process is down is charged by the boot reconciliation at the same figure as a live one: the amount plus the fee the record says was paid, or the reservation when no record can say. Excluded by design: the submarine swap provider's payment of the counterparty's invoice runs outside `maxPaymentSats`, the daily limit and the ledger; the provider's own per-swap fee cap and the swap-in it is funded from bound it. The ledger is persisted (issue #977): a restart within the UTC day resumes the day's total, and the budget a payment still holds while its HTLC is out comes back with it. A Lightning payment is charged when it settles, once, whichever path sent it (`payInvoice`, `sendKeysend`, `payOffer`, `sendPaymentAsync`), including a settle that lands after `payInvoice` gave up waiting or after a restart. Before this the counters were per-process, so every restart started the day at zero. Failed payments are not charged, and a payment that fails with nothing left in flight gives its budget back at once. A payment cancelled while its HTLC is out keeps its budget held until that HTLC settles or fails back, or the 24h window ends: the HTLC cannot be retracted, and releasing the budget on the cancel would let it be spent twice. `getDailySpendInfo().pendingSats` is what in-flight payments hold, and `remainingSats` subtracts it, so it is what the next payment can pass. | Method | Returns | Description | |--------|---------|-------------| | `getDailySpendInfo()` | `DailySpendInfo` | Current combined limit status: `{ totalSats, lightningSats, onchainSats, limitSats, remainingSats, pendingSats, resetsAt }` plus the legacy `spentSats` field (equals `totalSats`) for back-compat | #### Drain Mode | Method | Returns | Description | |--------|---------|-------------| | `setDraining(enabled)` | `void` | Enable/disable drain mode. When enabled, every payment entry point (`payInvoice()`, `sendPaymentAsync()`, `sendKeysend()`, `payOffer()`) throws `SERVICE_DRAINING`. `payOffer()` re-checks after the invoice request, so a drain that starts during it still stops the payment. | | `isDraining()` | `boolean` | Whether the node is currently draining | | `hasPendingPayments()` | `boolean` | Whether there are in-flight payments, or other work a drained stop waits for: a direct-funding send, a swap's funding, and on a node with asset channels a forward with an asset leg in flight or an end of one its host has not taken | #### Lifecycle | Method | Returns | Description | |--------|---------|-------------| | `gracefulShutdown(timeoutMs?)` | `Promise` | Graceful shutdown: drains in-flight HTLCs, persists state, then stops the node, then the on-chain wallet, then closes the database, so the wallet's last writes land (default 30s timeout). With host extensions, their `stop('shutdown')` hooks run first and their wait is part of `timeoutMs`, at most half of it and at most 5 seconds; the HTLC drain gets what is left | | `destroy()` | `Promise` | Immediate shutdown (stops the node, then the on-chain wallet, then closes the database) | ### Events `BeignetNode` is a typed emitter: `on`, `once` and `emit` accept only the events of `BeignetNodeEvents` (`types.ts`), so a listener on a misspelled event does not compile. All event data is JSON-safe (hex strings, numbers, decimal strings for msat; no Buffer or bigint). ```typescript node.on('payment:received', (info) => console.log(info.amountSats)); node.on('channel:ready', ({ channelId }) => console.log(channelId)); node.on('node:error', ({ code, message, channelId }) => console.error(code, message, channelId)); ``` The table is generated from `BeignetNodeEvents` by `npm run docs:tables`. The SSE column says whether the daemon relays the event to `GET /events` and webhooks: always, only with `htlcEvents` (`--htlc-events`, `BEIGNET_HTLC_EVENTS`), or never. | Event | Arguments | SSE | Description | |-------|-----------|-----|-------------| | `payment:received` | `(info: PaymentInfo)` | yes | Incoming payment settled. | | `payment:sent` | `(info: PaymentInfo)` | yes | Outgoing payment completed. | | `payment:failed` | `(info: PaymentInfo)` | yes | Outgoing payment failed. | | `payment:retry` | `(data: { paymentHash: PaymentHashHex; attempt: number; maxRetries: number; nextRetryMs: number; error: string })` | no | payInvoiceWithRetry is about to wait nextRetryMs and try again after a retryable failure. | | `invoice:settled` | `(data: { paymentHash: PaymentHashHex; bolt11: string; amountSats: number; auxiliary?: true })` | yes | An invoice this node issued was paid. A keysend fires only `payment:received`. | | `hold:accepted` | `(data: HoldInvoiceEvent)` | yes | A part joined a hold invoice's parked set (issue #746), fired for each new part, including partial MPP payments. Before funding a swap, compare BigInt(heldAmountMsat) with the full expected amount in msat: ACCEPTED alone does not mean the invoice is fully funded. | | `hold:settled` | `(data: HoldInvoiceEvent)` | yes | A hold invoice's preimage was revealed and every parked part fulfilled. | | `hold:cancelled` | `(data: HoldInvoiceEvent & { reason: HoldCancelReason })` | yes | A hold invoice was cancelled and every parked part failed back. | | `transaction:received` | `(info: OnchainTxInfo)` | yes | An incoming on-chain transaction first appeared. It may already carry a height when it was found at a catch-up sync after downtime, and no separate `transaction:confirmed` fires then. Initial-sync history does not replay as events. | | `transaction:sent` | `(info: OnchainTxInfo)` | yes | An outgoing on-chain transaction first appeared; the same rules as `transaction:received`. | | `transaction:confirmed` | `(info: OnchainTxInfo)` | yes | A transaction the wallet already held moved from the mempool into a block, in either direction (`info.type` says which). At most one per transaction. | | `onchain:rbf` | `(data: { txids: TxidHex[] })` | no | A replacement was observed: the listed txids were replaced (RBF) and are dead; whatever was watching them should stop (issue #548). | | `channel:opening` | `(data: { channelId: ChannelIdHex; fundingTxid: TxidHex; auxiliary?: true })` | yes | Funding was negotiated and the funding transaction broadcast or watched. | | `channel:ready` | `(data: { channelId: ChannelIdHex; auxiliary?: true })` | yes | The channel reached NORMAL state. | | `channel:usable` | `(data: { channelId: ChannelIdHex; auxiliary?: true })` | no | The channel can take a new HTLC again: it reached NORMAL on channel_ready, finished reestablishing on a reconnect, a splice locked or unwound, or its funding quarantine lifted. Fires on every reconnect. The payment queues start and retry on it (issue #967). | | `channel:pending-close` | `(data: { channelId: ChannelIdHex; initiator: 'local' \| 'remote'; auxiliary?: true })` | yes | A cooperative close started, by this node (`local`) or the peer (`remote`). | | `channel:force-closing` | `(data: { channelId: ChannelIdHex; initiator: 'local' \| 'remote'; auxiliary?: true })` | yes | A force close started: this node broadcast its commitment (`local`) or the peer's appeared on chain (`remote`). | | `channel:closed` | `(data: { channelId: ChannelIdHex; auxiliary?: true })` | yes | The funding output was spent and the spend classified. Outputs may still be unswept: `channel:resolved` is the terminal event. | | `channel:resolved` | `(data: { channelId: ChannelIdHex; auxiliary?: true })` | yes | The true terminal event of a close: every on-chain output of the channel is irrevocably swept or claimed and the channel state becomes CLOSED. | | `channel:voided` | `(data: { channelId: ChannelIdHex; auxiliary?: true })` | no | The channel was removed with nothing to close on chain, and its persisted state was durably deleted: its unconfirmed funding tx vanished from mempool and chain, or the open was aborted or abandoned before any funding existed. | | `splice:complete` | `(data: { channelId: ChannelIdHex; fundingTxid?: TxidHex })` | yes | splice_locked exchanged both ways: the channel runs on the new funding (fundingTxid, display order). | | `splice:aborted` | `(data: { channelId: ChannelIdHex; reason: string })` | yes | A splice negotiation was unwound by tx_abort before its point of no return. | | `channel-send:stage` | `(data: { id: string; compositeId?: string; stage: ChannelSendStage; txid?: TxidHex; reason?: string })` | yes | A channel send (issue #1922) reached a stage: a single-channel splice-out is STARTED, then LOCKED or ABORTED as its channel's splice completes or aborts; a composite reports its record's stage (PLANNED, NEGOTIATING, COMMITTED, PEERS_SIGNED, RELEASED, BROADCAST, LOCKED, ABORTED or CONFLICTED, with the reason), every stage from PLANNED on. `id` is the quote id the execute call returned, or the composite id for a composite restored without one; `txid` (display order) is the new funding transaction, for a composite from COMMITTED on. | | `splice:conflicted` | `(data: { channelId: ChannelIdHex; spliceTxid: TxidHex; conflictTxid: TxidHex; inputIndex: number; height: number })` | yes | An input of an in-flight splice that this node does not vouch for was spent by conflictTxid, confirmed six deep while the splice is not on chain: the splice can never confirm, and the peer is being asked to revert (issue #760). | | `splice:reverted` | `(data: { channelId: ChannelIdHex; spliceTxid: TxidHex; conflictTxid: TxidHex })` | yes | Both sides verified the conflict on their own chain view and returned to the pre-splice funding; the channel is NORMAL on the old outpoint (issue #760). | | `htlc:forwarded` | `(data: { inChannelId: ChannelIdHex; outChannelId: ChannelIdHex; amountInMsat: string; amountOutMsat: string; feeMsat: string; auxiliary?: true; inAuxiliaryAmount?: string; inWireAmountMsat?: string; outAuxiliaryAmount?: string; outWireAmountMsat?: string; nextHopScid?: string })` | `htlcEvents` | A forward through this node settled and earned feeMsat. Msat values are decimal strings. A forward with an asset leg (issue #2098, step 7) carries `auxiliary: true` and the fields of ForwardingEventInfo beside it, as strings. | | `htlc:forward-refused` | `(data: { inChannelId: ChannelIdHex; outChannelId: ChannelIdHex; amountMsat: string; paymentHash: PaymentHashHex; reason: string; channelErrorCode?: ChannelErrorCode; auxiliary?: true })` | yes | The outgoing channel refused to add a forward, so it was failed back to the sender with temporary_channel_failure. Someone else's payment was turned away, so it is not a `node:error`. `reason` is the channel's refusal text, `channelErrorCode` its code when it gave one (INSUFFICIENT_BALANCE, LIMIT_EXCEEDED, ...), `amountMsat` the amount it would have carried as a decimal string. | | `htlc:fulfilled` | `(data: { channelId: ChannelIdHex; htlcId: string })` | `htlcEvents` | The peer fulfilled an HTLC this node offered: a part of its own payment or the outgoing leg of a forward. Raised once per HTLC: a reconnect or restart raises it again only when this node had not yet stored what the fulfil settled (the preimage, the forward or the payment record). | | `htlc:failed` | `(data: { channelId: ChannelIdHex; htlcId: string })` | `htlcEvents` | The peer failed an HTLC this node offered: a part of its own payment or the outgoing leg of a forward. | | `peer:connect` | `(data: { pubkey: string })` | yes | A peer connected. | | `peer:disconnect` | `(data: { pubkey: string; closedBy?: 'peer' \| 'us'; reason?: string; direction?: 'inbound' \| 'outbound'; uptimeMs?: number })` | yes | A peer disconnected. When the transport knows the cause, `closedBy` says which side closed the connection, `reason` gives the transport or protocol error behind it (for example 'read ECONNRESET' or 'Pong timeout'), `direction` says who dialed, and `uptimeMs` how long it was up. A disconnect with no known cause carries only `pubkey`. | | `peer:error` | `(data: { pubkey: string; message: string })` | no | A peer connection reported an error. | | `peer:warning` | `(data: { pubkey: string; channelId: ChannelIdHex \| null; text: string })` | yes | A peer sent a BOLT 1 warning: the connection and its channels stay as they were, so it is not a `node:error`. channelId is null when the warning is about the connection rather than one channel; text is the peer's text as printable ASCII. | | `node:error` | `(data: { code: string; message: string; timestamp: number; channelId?: ChannelIdHex; txid?: TxidHex; retained?: boolean; channelErrorCode?: ChannelErrorCode })` | yes | An operational error (non-fatal), also passed to the onError option. `code` is a NodeErrorCode or one BeignetNode raises itself, such as ELECTRUM_FAILOVER_FAILED. | | `node:ready` | `()` | yes | The node is fully operational: peers reconnected and channels restored. | | `graph:restored` | `(stats: IGraphRestoreStats)` | no | A deferred restore of the stored network map (deferGraphRestore) ended: how it went, as getGraphRestoreStats() returns it. An inline restore ends inside create(), before anyone can listen, so it is read from the getter instead. | | `gossip:synced` | `(data: { channelsAdded: number; updatesApplied: number; downloadMs: number; applyMs: number; busyMs: number; slices: number })` | no | A Rapid Gossip Sync snapshot was downloaded and applied. downloadMs is the fetch; applyMs is the import from start to finish, of which busyMs was spent applying, in `slices` turns of the event loop (the rest went to other work between slices). | | `log` | `(entry: { level: string; message: string; data?: Record; timestamp: number })` | no | A structured log entry at or above the logLevel option. | | `backup:completed` | `(data: { path: string; timestamp: number })` | no | A scheduled database backup (backupPath) was written. | | `backup:failed` | `(data: { path: string; error: string; timestamp: number })` | no | A scheduled database backup (backupPath) failed. | | `electrum:failover` | `(data: { from: { host: string; port: number }; to: { host: string; port: number }; timestamp: number })` | no | The wallet reconnected to the next of electrumServers after the current one failed. | | `recovery:durable` | `(data: { through: string })` | yes | Recovery Protocol (docs/RECOVERY-PROTOCOL.md section 8): the journal is durable through this frame sequence. | | `recovery:fenced` | `(data: { supersededBy: { epoch: string; writerPublicKey: string; sequence: string; frameHash: string } \| null })` | yes | A newer writer epoch owns this recovery namespace: this device must not send another channel message. supersededBy is the superseding writer's guardian state when the barrier saw one. | | `recovery:backfill-lost` | `(data: { detail: string })` | yes | The journal was compacted past frames a guardian had not yet received, so that guardian cannot be backfilled. | | `recovery:reestablish-held` | `(data: { peerPubkey: string; channelId: ChannelIdHex; expiresAt: number })` | yes | peer-storage mode: a peer's channel_reestablish for a channel this node has no record of was held instead of failed (issue #462). Apply a Recovery Capsule before expiresAt or the peer force-closes. | | `recovery:guardian_unreachable` | `(data: { detail: string; sequence?: string })` | yes | A durability barrier could not reach a guardian. | | `recovery:capsule-retrieved` | `(data: { fromPeer: string; writerEpoch: string; latestSequence: string; inline: boolean; channelCount: number; candidates: number })` | yes | A storage peer returned a Recovery Capsule that became (or replaced) this node's best candidate from that peer (issue #690). Only newer heads are announced, so an equal-head re-send after a reconnect is silent. candidates counts the peers holding a valid capsule. | | `recovery:restore-progress` | `(data: { type: string; detail: string; refusal?: AssetRestoreRefusal })` | yes | A step of a guardian or capsule restore. The `capsule:auto-refused` step of an automatic apply refused for the asset channels the capsule holds also carries `refusal`, with the code and the channels. | | `recovery:restored` | `(data: { exact: boolean; framesApplied: number; guardiansRepaired: number; epoch: string; tier?: 1 \| 2; restartRequired?: boolean; resumed?: boolean })` | yes | A guardian or capsule restore finished. | | `guardian:set-registered` | `(data: { detail: string; setId?: string })` | yes | Guardian hosting (issue #699): this node started serving a guardian set. | | `guardian:quota-refused` | `(data: { detail: string; setId?: string })` | yes | Guardian hosting: a quota refused a registration or a write. | | `guardian:session-violation` | `(data: { detail: string; peer?: string })` | yes | Guardian hosting: a session violated framing and was dropped. | | `recovery:rotation-progress` | `(data: { type: string; detail: string; generation?: string })` | yes | Guardian-set rotation (wire 5.9, issue #701): a step of a rotation this node runs. | | `recovery:rotated` | `(data: { generation: string; guardians: Array<{ guardianId: string; url: string }> })` | yes | Guardian-set rotation: the switch, with the set that carries the journal from then on. | | `recovery:rotation-followed` | `(data: { generation: string; from: string[]; to: string[] })` | yes | Guardian-set rotation: this boot followed a retired set to the live one. | | `ffor:state` | `(data: { channelId: ChannelIdHex; state: string; epoch: Record })` | yes | An FFOR epoch's committed state changed, with the same record view GET /ffor/epoch serves. | | `ffor:settled` | `(data: Record)` | yes | Settlement peer side: a delegated slot settled upstream. | | `ffor:slot-resolved` | `(data: Record)` | yes | A concurrent-profile slot reached its terminal outcome. | | `ffor:delegated-failed` | `(data: Record)` | yes | Settlement peer side: a delegated slot's payment was failed back upstream. | | `ffor:enforce` | `(data: { channelId: ChannelIdHex; epoch: Record; restoreRecencyUnproven?: true; reestablishRecencyUnproven?: true; reestablishSecretMissing?: true })` | yes | A peer contradicted an ACTIVE FFOR epoch: enforce it on chain (POST /ffor/enforce). | | `ffor:witness-provisioned` | `(data: Record)` | yes | Witness role: a receiver provisioned a mailbox on this node. | | `ffor:witness-recorded` | `(data: Record)` | yes | Witness role: a delegated preimage's record was stored. | | `ffor:witness-released` | `(data: Record)` | yes | Witness role: a held fulfil was propagated, once recorded or at its CLTV deadline. | | `ffor:witness-refused` | `(data: Record)` | yes | Witness role: a provision was refused with the reason. | | `ffor:witness-closed` | `(data: Record)` | yes | Witness role: the receiver closed its mailbox; held records remain. | | `ffor:witness-expired` | `(data: Record)` | yes | Witness role: a mailbox passed its retention and expired. | | `ffor:witness-audit` | `(data: Record)` | yes | A witness record fetched for a slot failed verification. | | `ffor:issuer-provisioned` | `(data: Record)` | yes | Issuer role: a receiver delegated an offer and provisioned its slots. | | `ffor:issuer-issued` | `(data: Record)` | yes | Issuer role: an invoice was issued against a slot to a payer. | | `ffor:issuer-retired` | `(data: Record)` | yes | Issuer role: a delegated offer stopped issuing, with the reason. | | `swap:created` | `(data: Record)` | yes | A swap row was created: for a reverse swap with its hold invoice minted, for a submarine swap once its terms verified. | | `swap:held` | `(data: Record)` | yes | Reverse swap: the complete committed payment set is held by the hold invoice; a partial MPP set never funds. | | `swap:funding` | `(data: Record)` | yes | Reverse swap: the funding transaction was built, verified and recorded, and is being broadcast. | | `swap:funded` | `(data: Record)` | yes | The swap's funding confirmed to the configured depth. | | `swap:claimed` | `(data: Record)` | yes | Reverse swap: a claim spend with a verified preimage was seen at any depth; the preimage is recorded before the hold settles. | | `swap:settled` | `(data: Record)` | yes | Reverse swap: the hold was released with the claimed preimage. | | `swap:refund-broadcast` | `(data: Record)` | yes | Reverse swap: no claim by the refund height, so a refund to the node's sweep destination was broadcast. | | `swap:refunded` | `(data: Record)` | yes | Reverse swap: the refund confirmed, and only then the hold is cancelled. | | `swap:hold-cancelled` | `(data: Record)` | yes | Reverse swap: the hold invoice was cancelled. | | `swap:exposed` | `(data: Record)` | yes | Funds are at risk: on a reverse swap the hold was cancelled while coins were or may be on chain; on a submarine swap a payment is out while the contract is not claimable. | | `swap:failed` | `(data: Record)` | yes | The swap failed, with the reason. | | `swap:funding-seen` | `(data: Record)` | yes | Submarine swap: an output paying the contract, of at least the amount, was seen at any depth. | | `swap:funding-lost` | `(data: Record)` | yes | Submarine swap: the unconfirmed funding was replaced or vanished and none is left. | | `swap:paying` | `(data: Record)` | yes | Submarine swap: this node started paying the client's invoice under the swap's expiry ceiling. | | `swap:payment-unresolved` | `(data: Record)` | yes | Submarine swap: HTLCs are still out past the unresolved threshold (informational). | | `swap:preimage` | `(data: Record)` | yes | Submarine swap: the payment's preimage is known, from a fulfil or a claim seen on chain downstream. | | `swap:claim-broadcast` | `(data: Record)` | yes | Submarine swap: the claim to the sweep destination was built, persisted and broadcast. | | `swap:claim-confirmed` | `(data: Record)` | yes | Submarine swap: the claim confirmed to the resolution depth. | | `swap:payment-failed` | `(data: Record)` | yes | Submarine swap: every HTLC ended without a preimage; a preimage learned later still promotes the row. | | `swap:cancelled` | `(data: Record)` | yes | Submarine swap: cancelled before anything was paid (invoice expired, ceiling no longer fits, client spent the funding, or the operator cancelled). | | `jit:intent` | `(data: { scidHex: string; walletPubkeyHex: string; paymentHashHex?: string; maxAmountMsat: string; expectedTotalMsat?: string; targetRemainingInboundSat: string; expiresAt: number })` | yes | A wallet's request was accepted, keyed by the intercept scid this LSP minted for it. | | `jit:intent-superseded` | `(data: { scidHex: string; walletPubkeyHex: string })` | yes | An idle intent was replaced by a newer one from the same wallet. | | `jit:intercepted` | `(data: { scidHex?: string; channelIdHex?: string; amountMsat: string })` | yes | A payment part was held for an intent, or on the splice path for an existing channel. | | `jit:funding` | `(data: { scidHex?: string; channelIdHex?: string; fundingSats: string })` | yes | The zero-conf open or the splice that funds the held parts started. | | `jit:forwarded` | `(data: { scidHex?: string; channelIdHex?: string; parts: number })` | yes | The held parts were delivered over the new liquidity. | | `jit:failed` | `(data: { scidHex?: string; channelIdHex?: string; parts: number; reason: string })` | yes | The held parts were failed back upstream with the reason. | | `direct-funding:offer:accepted` | `(data: { offerId: string; paired: boolean; resumed?: boolean })` | yes | Direct funding, receiver side (issue #669): a payer's offer was accepted. `paired` says whether it came from a peer in the trusted set, which decides zero-conf and the splice path; `resumed` marks one picked up again after a restart. | | `direct-funding:offer:declined` | `(data: { offerId: string; reason: string })` | yes | A payer's offer was declined with the reason. | | `direct-funding:offer:failed` | `(data: { offerId: string; reason: string })` | yes | An accepted offer failed with the reason. | | `direct-funding:offer:completed` | `(data: { offerId: string })` | yes | An offer completed with the funding out. | Most FFOR and swap events are typed `Record`. Those FFOR payloads are the `LightningNode` event payloads of the same name (see `LightningNodeEvents` in [src/lightning/README.md](../lightning/README.md#events-reference)) made JSON-safe: Buffers as hex, bigints as decimal strings. Every swap event is an `ISwapEvent`: `swapId`, `paymentHash` (hex), `peer`, `state`, `onchainSat` and `invoiceMsat` (decimal strings) and `refundHeight`, with `direction: 'submarine'` on submarine swaps, plus the transition's own facts such as the funding, claim or refund txid and the reason. A configured listener that does not bind is not fatal, and is never silent (issues #861 and #933). When the OS refuses the bind (the port is taken, or not permitted), the node raises `node:error` with code `LISTEN_FAILED`, naming the listener, the port and the OS error, and saying inbound peers cannot connect (and, for a guardian host, that its guardian is unreachable). It is logged, kept in `GET /logs?category=error` and passed to `onError`; a throwing `onError` does not fail the boot. Nothing retries it: free the port and restart. `GET /info` carries the port asked for as `listenPort` and the reason as `listenError` (or `websocketListenError`), with `state: 'failed'` and the OS code as `errno`. In a guardian recovery mode (`async-remote`, `quorum`) the startup quarantine refuses the bind until writer ownership is confirmed and any startup repair is receipted: `listenError.state` is `'held'` meanwhile, no `LISTEN_FAILED` is raised, and the listener binds on its own once the gate opens (`'fenced'` if the node is fenced instead, when it stays down). A fence also closes a listener that was bound, which then reads `'fenced'` and gives no `GET /node/uri`. A guardian host's TCP bind is admitted during quarantine by the guardian-only lane. A failure at startup is raised before the daemon's SSE stream and webhooks are wired, so read it from `GET /info`. The `log` event fires based on the `logLevel` option. Set `logLevel: 'debug'` for verbose output, `'silent'` to suppress. Pass a `logger` (any `ILogger`, e.g. `createConsoleLogger(level)` from the main package) to also receive those entries as `logger.debug/info/warn/error(message, meta)` calls; the daemon uses this with `--log-level` / `BEIGNET_LOG_LEVEL` to print diagnostics to stderr (silent by default). ### Return Types ```typescript interface NodeInfo { nodeId: string; // 33-byte compressed pubkey, hex alias?: string; network: string; // 'mainnet' | 'testnet' | 'signet' | 'regtest' blockHeight: number; onchainBalanceSats: number; lightningBalanceSats: number; pendingCloseBalanceSats: number; // local balance of closing channels not yet in the wallet (see below) channelCount: number; // every known channel row, incl. CLOSED/FORCE_CLOSED openChannelCount: number; // channels not in a terminal state peerCount: number; listening: boolean; // an inbound listener (TCP or WebSocket) is bound listenPort?: number; // the TCP port asked for, present whenever one was configured, bound or not listenError?: ListenerProblem; // why the TCP listener is not bound; absent while it is websocketPort?: number; // the WebSocket listener port, only while bound websocketListenError?: ListenerProblem; // why the WebSocket listener is not bound } interface ListenerProblem { port: number; // the port asked for state: 'failed' | 'held' | 'fenced'; message: string; // the OS error, or why the bind is held errno?: string; // EADDRINUSE, EACCES, ... when the OS refused } interface BalanceInfo { onchain: number; // sats lightning: number; // sats total: number; // sats unsettledSats?: number; // sats locked in in-flight HTLCs assetChannelSats?: number; // sats on this side of asset channels that are not closing and not over (opening, open, peer away, failed); only with one, in neither lightning nor total assetChannelClosingSats?: number; // sats on this side of asset channels that are closing (see below); only with one } interface PeerInfo { pubkey: string; host: string; port: number; state: string; } interface ChannelInfo { channelId: string; // 32-byte hex peerPubkey: string; // 33-byte compressed pubkey hex state: string; // e.g. 'NORMAL', 'AWAITING_FUNDING_CONFIRMED' preReestablishState?: string; // the state a disconnect or restart left for AWAITING_REESTABLISH; present exactly while there (issue #1899) localBalanceSats: number; remoteBalanceSats: number; capacitySats: number; isAnchor: boolean; // true if anchor channel (option_anchors_zero_fee_htlc_tx) fundingTxid?: string; // funding transaction ID hex (display order) shortChannelId?: string; // e.g. "800000x1x0" feeratePerKw?: number; // current commitment feerate htlcCount?: number; // number of active HTLCs pendingSpliceLocalBalanceSats?: number; // local balance once the in-flight splice locks; present only mid-splice pendingSpliceTxid?: string; // the in-flight splice's txid, display order; present exactly when pendingSpliceLocalBalanceSats is (issue #1060) previousFundingTxids?: string[]; // fundings retired by adopted splices, oldest first, display order; absent when never spliced (issue #1060) lockedFundingTxids?: string[]; // fundings this channel locked (both channel_ready, or both splice_locked), oldest first, display order; kept through close. Not listed or absent means not known, not never locked: a channel from an earlier version is seeded only with what its stored state proves. On a zero-conf channel a lock comes before confirmation (issue #1899) closeStatus?: { // present for closing/closed channels closer: 'local' | 'remote' | 'cooperative' | 'unknown'; reason?: string; // 'user' or an automatic close code; absent for peer closes closingTxid?: string; broadcast: boolean; // close tx reached the network (broadcast ok or spend observed) confirmationHeight: number; // 0 while unconfirmed resolution: 'pending' | 'sweeping' | 'resolved'; fundsAvailableHeight?: number; // to_local CSV maturity, our force close only }; } interface InvoiceInfo { bolt11: string; // full BOLT 11 invoice string paymentHash: string; // 32-byte hex paymentSecret?: string; // 32-byte hex — correlate incoming payments without re-decoding amountSats?: number; description?: string; // invoice description expiry?: number; // expiry in seconds createdAt?: number; // unix seconds status?: 'PENDING' | 'PAID' | 'EXPIRED'; // derived from payment state + expiry } interface DecodedInvoice { network: string; // 'bc', 'tb', 'bcrt' amountSats?: number; timestamp: number; paymentHash: string; // hex paymentSecret?: string; // hex description?: string; payeeNodeKey?: string; // hex expiry?: number; // seconds minFinalCltvExpiry?: number; routingHints?: Array>; } interface PaymentInfo { paymentHash: string; // hex preimage?: string; // hex, present when settled amountSats: number; // OUTGOING: what left the node, fees included, rounded up // INCOMING: what the node was credited, rounded down feeSats?: number; // OUTGOING: routing fee paid; INCOMING: a JIT LSP's skim // (invoice amount less amountSats); rounded up status: 'PENDING' | 'COMPLETED' | 'FAILED'; direction: 'OUTGOING' | 'INCOMING'; failureCode?: number; // BOLT 4 failure code failureDescription?: string; // human-readable createdAt: number; // unix ms completedAt?: number; // unix ms metadata?: Record; // agent-defined key-value labels } interface RetryPaymentResult extends PaymentInfo { attempts: number; // total attempts made (1 = first try succeeded) } interface RetryPaymentOptions { maxRetries?: number; // default 3 backoffMs?: number; // base delay in ms, default 2000 (2s, 4s, 8s, ...) maxFeeSats?: number; // routing fee cap amountSats?: number; // for amount-less invoices metadata?: Record; } interface PaymentFilter { status?: 'PENDING' | 'COMPLETED' | 'FAILED'; direction?: 'OUTGOING' | 'INCOMING'; since?: number; // unix ms — only payments after this time limit?: number; // max results offset?: number; // skip first N results metadataKey?: string; // filter by metadata key existence (or key=value with metadataValue) metadataValue?: string; // filter by metadata key=value match (requires metadataKey) } interface RouteEstimate { feeSats: number; hops: number; cltvDelta: number; } interface NodeStats { totalPaymentsSent: number; totalPaymentsReceived: number; totalPaymentsFailed: number; totalSatsSent: number; // sum of PaymentInfo.amountSats: fees included, rounded up totalSatsReceived: number; totalFeesPaid: number; // sum of PaymentInfo.feeSats, rounded up successRate: number; // 0.0 to 1.0 uptimeMs: number; windowMs?: number; // present when time window specified avgPaymentTimeSec?: number; // avg completed payment time avgFeePct?: number; // avg fee as % of payment amount } interface TxInfo { txid: string; hex: string; } interface OfferInfo { offerId: string; // 32-byte hex description: string; encoded?: string; // bech32m "lno1..." string (present on creation) amountSats?: number; // amount in satoshis (converted from msat) issuer?: string; issuerId?: string; // 33-byte hex quantityMax?: number; absoluteExpiry?: number; // unix seconds } interface TrustedPeerInfo { pubkey: string; // 33-byte hex trusted: boolean; } interface SpliceResult { ok: boolean; // true = the splice started, not that it completed error?: string; // set on a refusal code?: SpliceRefusalCode; // CHANNEL_NOT_FOUND | SPLICING_NOT_NEGOTIATED | // INVALID_PARAMS | INSUFFICIENT_BALANCE | // FUNDING_PROVIDER_REQUIRED | SPLICE_BUSY | // SPLICE_REFUSED } interface BootstrapPeerInfo { pubkey: string; // 33-byte hex host: string; port: number; } interface Bolt12InvoiceInfo { paymentHash: string; // hex amountSats: number; description: string; nodeId: string; // hex createdAt: number; // unix seconds relativeExpiry?: number; // seconds } interface ChannelHealth { channelId: string; // 32-byte hex state: string; // e.g. 'NORMAL', 'AWAITING_REESTABLISH' localBalancePct: number; // 0-100, local balance as % of capacity remoteBalancePct: number; // 0-100, remote balance as % of capacity htlcCount: number; // number of active HTLCs maxHtlcs: number; // max allowed HTLCs capacitySats: number; // total channel capacity warnings: string[]; // 'LOW_OUTBOUND_LIQUIDITY', 'LOW_INBOUND_LIQUIDITY', // 'HTLC_SLOTS_NEARLY_FULL', 'AWAITING_REESTABLISH' } interface DailySpendInfo { limitSats: number | null; // null if no limit configured spentSats: number; // sats spent today (persisted; survives a restart within the UTC day) remainingSats: number; // sats the next payment can pass: limit minus spent minus pending (Infinity if no limit) pendingSats: number; // sats held by payments still in flight resetsAt: number; // unix ms — next midnight UTC } interface HealthInfo { status: 'ready' | 'syncing' | 'degraded'; uptime: number; // ms since start blockHeight: number; electrumConnected: boolean; peerCount: number; channelCount: number; readyChannelCount: number; // NORMAL channels that will accept a new HTLC graphNodes: number; graphChannels: number; } interface EventMessage { type: string; // e.g. 'payment:received', 'channel:ready' data: Record; } interface PaymentProof { paymentHash: string; // hex preimage: string; // hex amountSats: number; // as PaymentInfo.amountSats completedAt: number; // unix ms invoice?: string; // original BOLT 11 invoice string hopCount?: number; feeSats?: number; // as PaymentInfo.feeSats } interface PaymentProofVerification { valid: boolean; // true if sha256(preimage) === paymentHash proof?: PaymentProof; // the proof data (if found) error?: string; // error message if verification failed } interface PaymentEstimate { successProbabilityPct: number; // 0-100 estimatedTimeMs: number; routeQuality: 'HIGH' | 'MEDIUM' | 'LOW'; warning?: string; alternativeAvailable: boolean; // MPP route exists estimatedFeeSats: number; // rounded UP, safe to pass as maxFeeSats estimatedFeeMsat: string; // exact fee, decimal string hopCount: number; } interface LiquiditySnapshot { totalLocalBalanceSats: number; totalRemoteBalanceSats: number; totalCapacitySats: number; channelCount: number; activeChannelCount: number; outboundLiquidityPct: number; // 0-100 inboundLiquidityPct: number; // 0-100 recommendations: LiquidityRecommendation[]; } interface LiquidityRecommendation { type: 'OPEN_CHANNEL' | 'CLOSE_CHANNEL' | 'REBALANCE_NEEDED'; priority: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO'; reason: string; channelId?: string; // present for channel-specific recommendations } interface ChannelSuggestion { nodeId: string; // 33-byte hex alias?: string; score: number; // 0-100 channelCount: number; totalCapacitySats: number; reason: string; // e.g. 'well-connected, high capacity' } interface FeeSnapshot { currentSatPerVbyte: number; trend: 'RISING' | 'FALLING' | 'STABLE'; percentile: number; // 0-100 recommendation: 'OPEN_NOW' | 'WAIT' | 'NEUTRAL'; estimatedOpenChannelCostSats: number; sampleCount: number; minSatPerVbyte: number; maxSatPerVbyte: number; avgSatPerVbyte: number; } interface QueuedPayment { id: string; bolt11: string; priority: number; // 1 (highest) to 10 (lowest) status: 'queued' | 'dispatching' | 'completed' | 'failed' | 'cancelled'; amountSats?: number; maxFeeSats?: number; metadata?: Record; error?: string; createdAt: number; completedAt?: number; } interface WebhookRegistration { id: string; url: string; events: string[]; // e.g. ['payment:received', '*'] secret?: string; // masked as '***' in list responses createdAt: number; } interface ActionLogEntry { category: string; // 'payment' | 'channel' | 'htlc' | 'fee' | 'peer' | 'chain' action: string; timestamp: number; // unix ms data: Record; } interface ReadinessReport { score: number; // 0-100 weighted pass rate ready: boolean; // true if no CRITICAL failures checks: ReadinessCheck[]; } interface ReadinessCheck { name: string; // e.g. 'STORAGE_CONFIGURED', 'CHAIN_BACKEND_CONNECTED' status: 'PASS' | 'WARN' | 'FAIL'; severity: 'CRITICAL' | 'WARNING' | 'INFO'; message: string; } // The events and their payloads: see the Events table above. type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'; interface LogEntry { level: LogLevel; message: string; data?: Record; timestamp: number; } ``` `assetChannelClosingSats` (on `getBalance()` and `GET /balance`) is the local balance of every asset channel that is SHUTTING_DOWN, NEGOTIATING_CLOSING, or FORCE_CLOSED with this wallet's balance output not yet spent in a block. An asset channel is in no figure for bitcoin on its way back to the wallet, `pendingCloseBalanceSats` included, because its bitcoin stays under the asset outputs that the close or the sweep pays; this figure is where it is read while the channel closes, which after a force close is the whole of the closer's delay. It is absent from the answer of a wallet with no such channel. Every asset channel that is not over is in exactly one of the two figures: `assetChannelSats` holds each one that is not closing, whatever its state (still opening; open; waiting for its peer; failed and not yet closed), and `assetChannelClosingSats` each one that is. A channel is counted once its funding transaction is out: one this wallet funds from the moment the node has broadcast the transaction and the network took it, one the peer funds from the moment the node has seen it confirmed. Until then it is in neither, whatever its state, because the coins a funding transaction spends are still in `onchain` while the transaction only exists: an opening given up between `funding_created` and the broadcast is never counted. A funding the host signs and publishes itself is counted from its confirmation, since the node does not see that broadcast. The broadcast is what the running node saw: after a restart a channel whose funding is still unconfirmed is counted again once the node has handed the retained transaction to the network again, which it does when it starts and on every block. A closed channel and a force closed one whose balance output has been spent are in neither. `pendingCloseBalanceSats` is the local balance of every SHUTTING_DOWN, NEGOTIATING_CLOSING and FORCE_CLOSED channel whose funds the wallet does not count yet. A FORCE_CLOSED channel leaves the figure in the same read in which the wallet history first holds the sweep of its balance output (our to_remote on the peer's commitment, our to_local on ours), which the wallet counts from the mempool on, so a sat of the channel is in `onchainBalanceSats` or in `pendingCloseBalanceSats`, never both. If the wallet drops the sweep again (evicted, replaced, a restart before its first sync), the channel is back in the figure in that read. ### Channel States Channels progress through these states: | State | Can Send Payments? | Description | |-------|-------------------|-------------| | `AWAITING_FUNDING_CONFIRMED` | No | Funding tx broadcast, waiting for on-chain confirmations | | `AWAITING_CHANNEL_READY` | No | Funding confirmed, exchanging `channel_ready` messages | | `CHANNEL_READY` | No | Private final type-80 peers have exchanged readiness at funding depth | | `NORMAL` | **Yes** | Fully operational — HTLCs can be sent and received | | `AWAITING_REESTABLISH` | No | Reconnected after disconnect, re-syncing state | | `SHUTTING_DOWN` | No | Cooperative close initiated, no new HTLCs | | `NEGOTIATING_CLOSING` | No | Exchanging closing fee proposals | | `FORCE_CLOSED` | No | A unilateral close is on chain and the chain monitor is sweeping our outputs | | `CLOSED` | No | Channel closed (cooperative or forced). A force close gets here once every output that is ours to claim is swept and 100 blocks deep; the peer's own output (its to_remote on our commitment, its to_local on its own current one) does not hold the transition, since only the peer can spend it | Only channels in `NORMAL` state can send/receive payments. ### Error Handling All errors throw `BeignetError` with a `code`, `message`, and optional `failureCode` (BOLT 4): ```typescript import { BeignetError, isRetryableError, isPermanentFailure } from 'beignet/cli'; try { await node.payInvoice(bolt11); } catch (err) { if (err instanceof BeignetError) { console.log(err.code); // 'PAYMENT_FAILED', 'PAYMENT_TIMEOUT', etc. console.log(err.message); // 'Payment failed: unknown_next_peer' console.log(err.failureCode); // BOLT 4 failure code (e.g. 0x400f) if (isRetryableError(err)) { // Transient failure — safe to retry (no route, timeout, temp failure) } if (isPermanentFailure(err)) { // Permanent failure — give up (expired, invalid, PERM flag set) } } } ``` Error codes (`BeignetErrorCode` enum). The HTTP column is the status the daemon answers with: **4xx** when the request cannot be served as written, **409** when the node's own state conflicts with it, **502/504** when the trouble is upstream of us (the peer, the network), **503** when waiting genuinely changes the answer, and **500** only when the node itself failed. An agent can retry on 5xx and must not repeat a 4xx unchanged. | Code | Category | HTTP | Description | |------|----------|------|-------------| | `WALLET_CREATE_FAILED` | Wallet | 500 | On-chain wallet initialization failed | | `ADDRESS_FAILED` | Wallet | 500 | Could not derive new address | | `SEND_FAILED` | Wallet | 500 | On-chain send failed | | `REFRESH_FAILED` | Wallet | 500 | Wallet sync failed | | `NOT_BOOSTABLE` | Wallet | 409 | Transaction cannot be fee-bumped (unknown, confirmed, or not RBF/CPFP-able) | | `NOTHING_TO_CONSOLIDATE` | Wallet | 409 | Consolidation needs at least two spendable UTXOs | | `INSTANCE_ALREADY_RUNNING` | Wallet | n/a | Another instance holds the data-dir lock (startup only, never over HTTP) | | `ASSET_PROVIDER_REQUIRED` | Node | 409 | The database holds asset channels and no attached extension supplies the provider that runs them; the node is not started and no row is changed ([docs/EXTENSIONS.md](../../docs/EXTENSIONS.md)). From a capsule restore, `error.details.assetChannels` lists the channels, and `omitAssetChannels` restores without them | | `ASSET_PROVIDER_CONFLICT` | Node | 409 | Two attached extensions both supply an asset channel provider; the node is not started | | `ASSET_PROVIDER_FAILED` | Node | 409 | The extension whose asset channel provider the node was built with refused the node in `bind()`; the node is not started. All three refuse a start, and reach HTTP only from a route that rebuilds the node | | `ASSET_RESTORE_REFUSED` | Node | 409 | A restore holds asset channels and the extension that supplies the node's asset channels did not say it can restore them (`canRestore`); nothing of the restore was installed. With no such extension attached the refusal is `ASSET_PROVIDER_REQUIRED`. From a capsule restore, `error.details.assetChannels` lists the channels as `{ channelId, peerPubkey, capacitySats }`, and `POST /recovery/restore-capsule` with `omitAssetChannels: true` restores without them | | `PAYMENT_UNRESOLVED` | Node | 409 | The payment has an HTLC on an asset channel a capsule restore left out (`unresolved` on its row). It may have been paid, so it is not cancelled and stays PENDING | | `ASSET_GUARDIAN_START_REFUSED` | Node | 409 | The wallet holds asset channels and was started in a guardian recovery mode (`async-remote` or `quorum`). Nothing was started and nothing reached a guardian. Close the asset channels, or start without the guardian backup (`peer-storage` or `off`). | | `PAYMENT_FAILED` | Payments | 502 | Lightning payment failed | | `FEE_EXCEEDS_MAX` | Payments | 409 | Every route costs more than the caller's `maxFeeSats` / `maxFeeMsat`; nothing was sent (permanent: the same request meets the same cap) | | `PAYMENT_TIMEOUT` | Payments | 504 | Payment did not settle within timeout. The payment is failed only when no HTLC is out for it; with one still in flight the record stays `PENDING` until it resolves, no further route is tried, and the record is failed when the HTLC fails or its on-chain timeout resolves; the message says so (issue #976). The error carries the payment's `paymentHash` (issue #1094) | | `INVOICE_EXPIRED` | Payments | 410 | Invoice has expired | | `NO_ROUTE` | Payments | 502 | No route found to destination | | `INVALID_INVOICE` | Payments | 400 | BOLT 11 string failed to parse | | `INVALID_OFFER` | Payments | 400 | BOLT 12 offer string failed to parse | | `INSUFFICIENT_BALANCE` | Payments | 409 | Not enough balance to send, or to fund the requested open | | `DUPLICATE_PAYMENT` | Payments | 409 | Payment with this hash already completed, or still has an HTLC out; `payInvoiceSafe` returns the existing record instead | | `SPENDING_LIMIT_EXCEEDED` | Payments | 403 | Daily spending limit exceeded (permanent) | | `CHANNEL_NOT_FOUND` | Channels | 404 | Channel ID does not exist | | `CHANNEL_NOT_READY` | Channels | 409 | Channel is not in NORMAL state | | `OPEN_FAILED` | Channels | 409 | Channel open failed | | `CLOSE_FAILED` | Channels | 500 | Cooperative close failed | | `FORCE_CLOSE_FAILED` | Channels | 500 | Force close failed | | `ZERO_CONF_FAILED` | Channels | 500 | Zero-conf channel open failed | | `FUNDING_PROVIDER_REQUIRED` | Channels | 409 | The node has no funding provider able to serve this open or splice | | `FEE_ESTIMATE_NOT_READY` | Channels | 503 | The fee estimator has not delivered its first sample; retry shortly | | `SPLICING_NOT_NEGOTIATED` | Channels | 409 | `option_splice`/`option_quiesce` is missing on one side of the pair | | `SPLICE_REFUSED` | Channels | 409 | The channel exists but would not start the splice (state, peer, size) | | `SPLICE_BUSY` | Channels | 503 | The channel would splice but is held off by a state that ends on its own; retry the same request | | `UPDATE_FEE_FAILED` | Channels | 409 | The channel would not take the commitment feerate (its state, not the opener, an FFOR epoch, the bounds or the reserve) | | `PEER_NOT_CONNECTED` | Peers | 409 | Peer is not connected | | `HOLD_RESOLUTION_PENDING` | Invoices | 503 | `settleHoldInvoice`/`cancelHoldInvoice` left HTLCs parked for the hash: a channel refused them, or a settle or cancel is already under way. The hold is live; do not switch to the other action | | `JIT_REFUSED` | Invoices | 400 | JIT receive: the LSP declined the intent, quoted above the wallet's ceiling, or answered with no intercept scid; the message carries the reason | | `SWAP_NOT_CANCELLABLE` | Swaps | 409 | Reverse swap provider: the swap is past CREATED/HELD, so it resolves on chain by claim or refund and cannot be cancelled | | `JIT_TIMEOUT` | Invoices | 504 | JIT receive: the LSP never answered the intent inside the ack window (retryable) | | `NO_PRIMARY_AVAILABLE` | Invoices | 503 | A receive that named no peer walked the ranked primaries and none took it: unreachable, timed out, declined, or not reached inside the budget; the message names each one's reason (retryable) | | `CONNECT_FAILED` | Peers | 502 | Dialing the peer failed | | `CONNECT_TIMEOUT` | Peers | 504 | The peer did not answer the dial in time | | `NODE_DESTROYED` | Node | 409 | Operation on destroyed node | | `INVALID_PARAMS` | Node | 400 | Missing or invalid request parameters | | `NOT_FOUND` | Node | 404 | Resource not found | | `BODY_TOO_LARGE` | Node | 413 | Request body exceeds 1MB | | `MNEMONIC_REQUIRES_AUTH` | Node | 403 | apiToken or apiKeys required for mnemonic access | | `UNAUTHORIZED` | Node | 401 | Invalid or missing auth token / API key | | `FORBIDDEN` | Node | 403 | Valid API key without the scope a route requires | | `SERVICE_DRAINING` | Node | 409 | Node is draining, no new payments accepted | | `IDEMPOTENCY_CONFLICT` | HTTP | 409 | Same idempotency key used with different request body | | `EXTENSION_ERROR` | HTTP | set by the extension | A refusal from a host extension's route; `error.extension` carries `{ id, code, details? }` ([docs/EXTENSIONS.md](../../docs/EXTENSIONS.md)) | | `EXTENSION_UNAVAILABLE` | HTTP | 503 | A route of a host extension that failed or is stopped; retryable | | `RATE_LIMITED` | HTTP | 429 | Too many requests (token bucket rate limiter) | `SEND_FAILED`, `CLOSE_FAILED`, `FORCE_CLOSE_FAILED`, `ZERO_CONF_FAILED` and the `PSBT_*` codes keep the 500 default on purpose: each covers both caller-state problems and genuine node faults, so no single status is honest until they are split. The two close codes have had their caller-state half split off at the source: `POST /channel/close` and `POST /channel/forceclose` answer **400 `INVALID_PARAMS`** for a malformed channel id and **404 `CHANNEL_NOT_FOUND`** for a channel the node does not hold, so a 500 from either now means a channel that exists and would not close. The table lists the common codes. `BeignetError.code` is typed `BeignetErrorCodeValue`, a closed union of every `BeignetErrorCode` string, so a `switch` over it can be exhaustive and the enum is the whole vocabulary the daemon answers with, recovery, sweep, receive, L402 and direct-funding codes included. `isBeignetErrorCode(value)` checks a code read off a response. `BeignetError` extends `CodedError`, the base every coded error in the library shares. **Retryability is one decision, not two.** Every code answered with 502, 503 or 504 is one `isRetryableError()` returns true for, and a test walks the status map to keep them from drifting apart. The status also reads the BOLT 4 failure code: a `PAYMENT_FAILED` carrying the PERM flag answers **409**, not `PAYMENT_FAILED`'s usual 502, because the payee refuses it every time. Failure bodies carry `failureCode` so a caller can make the same judgment itself. #### Typed Payment Errors (Lightning Layer) When a send is refused, the underlying `LightningNode` throws a `LightningPaymentError` with a typed `code` property. The CLI layer catches these and maps them to `BeignetErrorCode`, in `payInvoice()`, `sendPaymentAsync()`, `sendKeysend()` and `payOffer()` alike (issue #991), so every payment route answers a refusal with its own code and HTTP status. When driving the `LightningNode` directly you can import and check them yourself: ```typescript import { LightningPaymentError, LightningErrorCode } from 'beignet/cli'; try { await node.payInvoice(bolt11); } catch (err) { if (err instanceof LightningPaymentError) { switch (err.code) { case LightningErrorCode.NO_ROUTE: // No path to destination case LightningErrorCode.DUPLICATE_PAYMENT: // Payment hash already paid or in-flight case LightningErrorCode.NO_CHANNEL_TO_HOP: // No channel to first hop peer case LightningErrorCode.FEE_EXCEEDS_MAX: // Route fee exceeds maxFeeMsat case LightningErrorCode.MISSING_AMOUNT: // Amount-less invoice with no amount case LightningErrorCode.INVALID_INVOICE: // Cannot determine payee case LightningErrorCode.INVOICE_EXPIRED: // Invoice has expired } } } ``` `LightningPaymentError` extends `Error`, so existing `catch` blocks continue to work. The `code` property enables programmatic error handling without string matching. #### Typed Channel-Open Refusals (Lightning Layer) A channel open the engine refuses on the caller's own arguments (a push toward a dual-fund peer, a `pushSats` above the funding amount, a non-positive fee rate, `max` without a pinned rate, a trusted open toward a peer that never negotiated `option_zeroconf`) throws an `InvalidChannelOpenError`. Every open entry point converts it to `INVALID_PARAMS`, so the daemon answers **HTTP 400 with the engine's message** instead of scrubbing it to a generic 500. Node faults stay untyped and still answer 500. ```typescript import { BeignetError } from 'beignet/cli'; try { node.openChannel(peerPubkey, 100_000, { pushSats: 50_000 }); } catch (err) { if (err instanceof BeignetError && err.code === 'INVALID_PARAMS') { // The request cannot be served as written; err.message says why. } } ``` `InvalidChannelOpenError` is what an embedder driving a raw `LightningNode` catches (it is exported from `beignet/cli` too); on `BeignetNode` and over HTTP the refusal always arrives as `INVALID_PARAMS`. A splice refused the same way throws the sibling `InvalidSpliceError`, which converts identically. #### Typed Channel-Funding State Refusals (Lightning Layer) A request the node cannot serve for its **own** state or configuration is a different thing: the request is well formed, this node cannot serve it as things stand. `INVALID_PARAMS` would be a lie, so these throw a `ChannelFundingUnavailableError` carrying a `code`, and each code answers with a status of its own. | `ChannelFundingUnavailableCode` | Reaches the caller as | HTTP | |---|---|---| | `FUNDING_PROVIDER_REQUIRED` | `FUNDING_PROVIDER_REQUIRED` | 409 | | `INSUFFICIENT_BALANCE` | `INSUFFICIENT_BALANCE` | 409 | | `FEE_ESTIMATE_NOT_READY` | `FEE_ESTIMATE_NOT_READY` | 503 | | `CHANNEL_NOT_FOUND` | `CHANNEL_NOT_FOUND` | 404 | ```typescript import { BeignetError, isRetryableError } from 'beignet/cli'; try { node.openChannel(peerPubkey, 100_000, { satsPerVbyte: 5, max: true }); } catch (err) { if (err instanceof BeignetError && isRetryableError(err)) { // FEE_ESTIMATE_NOT_READY: the estimator's first sample lands in // milliseconds, so a retry succeeds. Everything else needs a decision. } } ``` Node faults are still deliberately untyped, so they keep scrubbing to a generic **500** with the detail in the daemon log only. #### Splice Refusals A splice starts asynchronously, so a refusal is **returned**, not thrown: `spliceIn`/`spliceOut` answer `{ ok: false, error, code }`. The daemon converts that code at the route boundary, so `POST /channel/splice-in` and `POST /channel/splice-out` answer a refused splice as a failure envelope, never a 200 carrying `ok: false` under `result`. A channel send (issue #1922) pays an address out of the channels in two calls. `quoteChannelSend(address, amountSats, feeratePerkw)` returns a plan: `single`, naming the channel with the largest spendable balance whose splice-out bound covers amount + fee, or `composite`, one transaction out of several channels (debited largest spendable balance first, the fee split in proportion to each debit, rounded up per channel), with each channel's debit, fee share and new capacity, the channels left out and why, and a `quoteId` that lasts two minutes. Amount + fee is checked against `maxPaymentSats` and `dailySpendLimitSats` at quote and again at execute, where a composite is planned again on the current balances so the fee the ledger counts is the one priced then. `executeChannelSend(quoteId)` runs it: a single-channel send is a `spliceOut` and records amount + fee at once; a composite reserves amount + fee in the pending budget, charges it when the node's signatures are released (the point past which the money leaves) and releases it if the composite aborts first, so a composite that never releases costs nothing of the day's budget. Executing the same quote id again returns the first execution and runs nothing, also while the first is still starting, and `POST /channel-send/execute` is idempotent on top of that. `getChannelSend(id)` and `listChannelSends()` report the stage (a single is `STARTED`, then `LOCKED` or `ABORTED` as its channel's splice completes or aborts; a composite reports its record's stage) and the record, and keep a finished send for seven days, as the engine keeps its records; `abortChannelSend(id)` unwinds a composite before its release. The stages arrive on `channel-send:stage`. A node whose storage lacks the `compositeSplices` capability group, or that runs without the recovery journal, answers `NOT_PERSISTED` to a composite quote. See [docs/MULTI-CHANNEL-SPLICE-OUT.md](../../docs/MULTI-CHANNEL-SPLICE-OUT.md). | `SpliceRefusalCode` | Reaches the caller as | HTTP | |---|---|---| | `CHANNEL_NOT_FOUND` | `CHANNEL_NOT_FOUND` | 404 | | `INVALID_PARAMS` | `INVALID_PARAMS` | 400 | | `INSUFFICIENT_BALANCE` | `INSUFFICIENT_BALANCE` | 409 | | `FUNDING_PROVIDER_REQUIRED` | `FUNDING_PROVIDER_REQUIRED` | 409 | | `SPLICING_NOT_NEGOTIATED` | `SPLICING_NOT_NEGOTIATED` | 409 | | `SPLICE_BUSY` | `SPLICE_BUSY` | 503 | | `SPLICE_REFUSED` | `SPLICE_REFUSED` | 409 | A 2xx means the splice **started**. Its outcome arrives on the `splice:complete`, `splice:aborted`, `splice:reverted` and `node:error` events (a depth-locked splice whose external input was spent elsewhere is reverted to the old funding by agreement with the peer, issue #760; `splice:conflicted` and `node:error` code `SPLICE_INPUT_CONFLICT` precede it). `SPLICE_BUSY` is the one refusal to retry unchanged: the channel would splice but is held off by a state that ends on its own (a splice already in progress, a previous abort still awaiting the peer's echo, a quiescence session the peer owns, HTLCs still settling, the peer reconnecting). `isRetryableError` agrees; every other refusal code is permanent for the request as sent. --- ## CLI Commands The CLI is a thin HTTP client. `init` and `start` are handled locally, and `porch-relay` runs a server of its own; all other commands send requests to the daemon on `127.0.0.1:2112`. All output is JSON. Add `--pretty` for indented output. ### Setup ```bash beignet init [--network regtest] [--alias mynode] [--final-taproot-wallet] [--final-commitment-updates | --dual-funded-assets | --asset-splice] beignet start [--port 2112] [--host 0.0.0.0] [--daemon] [--anchors] [--api-token ] \ [--backup-path /path/to/backup.db] [--backup-interval 21600000] \ [--daily-spend-limit 100000] [--tls-cert /path/cert.pem] [--tls-key /path/key.pem] \ [--htlc-events] [--log-level info] [--extension /abs/path/module.js] beignet stop ``` `--extension` (repeatable, or `BEIGNET_EXTENSIONS`) names a host extension to run inside the daemon, by the absolute path of its module. A flag with no path after it refuses the start. See [docs/EXTENSIONS.md](../../docs/EXTENSIONS.md). Seed generation is CLI-only: `beignet init` creates the mnemonic (or you supply one via `BEIGNET_MNEMONIC`/config); the daemon never generates or replaces a seed. `GET /mnemonic` only reveals the configured seed, and only when `apiToken` or `apiKeys` is set (admin scope). `init` also mints an `apiToken` (32 random bytes, hex) whenever the config carries neither `apiToken` nor `apiKeys` and the environment supplies neither `BEIGNET_API_TOKEN` nor `BEIGNET_API_KEYS`. The token is saved to `config.json` and printed once, as `apiToken` with a `note` on how to send it; an existing token or key set is left alone and never printed. Running `init` on a config an older release wrote (mnemonic, no credential) adds a token the same way. The mnemonic is printed only by the `init` that creates it; a re-run answers `Config already exists` without it. `beignet start` with no credential at all keeps running but warns on stderr: `authentication is off: any local process can drive this daemon; run beignet init or set apiToken`. ### API key management ```bash beignet auth keys # list named API keys (names, scopes, revoked/expired, # expiresAt/rotatedAt; never secrets) beignet auth revoke # disable a named key immediately (persisted; # survives restarts) beignet auth rotate # mint a new random secret for a named key; # printed ONCE, cannot be retrieved again ``` Any command accepts `--api-key ` (alias of `--api-token`) or the `BEIGNET_API_KEY` env var to authenticate with a named key instead of the legacy token. ### Info ```bash beignet info # {"ok":true,"result":{"nodeId":"02ab...","network":"regtest","blockHeight":100,...}} beignet balance # {"ok":true,"result":{"onchain":50000,"lightning":10000,"total":60000}} beignet address # {"ok":true,"result":{"address":"bcrt1q..."}} beignet mnemonic # {"ok":true,"result":{"mnemonic":"abandon abandon ..."}} beignet health # {"ok":true,"result":{"status":"ready","uptime":3600000,...}} beignet readiness # {"ok":true,"result":{"score":85,"ready":true,"checks":[...]}} beignet metrics # beignet_channels_total{state="NORMAL"} 2 # beignet_balance_sats{type="lightning"} 50000 # ... (Prometheus text format, not JSON) beignet stats # {"ok":true,"result":{"totalPaymentsSent":10,...}} beignet stats 3600000 # {"ok":true,"result":{"totalPaymentsSent":3,"windowMs":3600000,...}} beignet ready # {"ok":true,"result":{"ready":true}} beignet liquidity # {"ok":true,"result":{"totalLocalBalanceSats":500000,...,"recommendations":[...]}} beignet fees # {"ok":true,"result":{"currentSatPerVbyte":12,"trend":"FALLING","recommendation":"OPEN_NOW",...}} beignet spend-limit # Combined LN + on-chain budget with breakdown (spentSats == totalSats, kept for back-compat): # {"ok":true,"result":{"limitSats":100000,"spentSats":2500,"remainingSats":97500,"pendingSats":0,"resetsAt":...,"totalSats":2500,"lightningSats":1500,"onchainSats":1000}} beignet logs --category payment --limit 20 # {"ok":true,"result":[{"category":"payment","action":"sent","timestamp":...,"data":{...}}]} beignet can-send 50000 beignet can-receive 50000 # {"ok":true,"result":{"canSend":true,...}} beignet node uri --host mynode.example.com # {"ok":true,"result":{"uri":"02ab...@mynode.example.com:9735"}} beignet node wait-ready --timeout 30000 # Blocks until the node is operational beignet extensions # {"ok":true,"result":{"api":"beignet-extension-api/1","extensions":[]}} ``` ### On-chain ```bash beignet send
# {"ok":true,"result":{"txid":"ab12...","hex":"0200..."}} beignet send-max
[satsPerVbyte] # Sweep the whole balance: {"ok":true,"result":{"txid":"cd34...","hex":"0200..."}} beignet tx bump-fee # RBF replacement: {"ok":true,"result":{"txid":"ef56...","boostType":"rbf","feeSats":420,"originalTxid":"ab12..."}} beignet tx boost [satsPerVbyte] # Auto RBF-else-CPFP: {"ok":true,"result":{"txid":"0178...","boostType":"cpfp",...}} beignet tx boostable # {"ok":true,"result":{"rbf":[...],"cpfp":[...]}} beignet consolidate [satsPerVbyte] # {"ok":true,"result":{"txid":"23ab...","utxosConsolidated":7,"address":"bc1q...","feeSats":310}} beignet psbt build
[satsPerVbyte] # Unsigned PSBT for a hardware wallet: {"ok":true,"result":{"psbtBase64":"cHNi...","feeSats":418,...}} beignet psbt import-signed [unsignedPsbt|file] # Validate + finalize (no broadcast): {"ok":true,"result":{"txid":"ab12...","txHex":"0200..."}} # The daemon remembers its 50 most recent builds, in memory only. After a # restart (or 50 newer builds), pass the unsigned PSBT from `psbt build` too. beignet psbt combine # {"ok":true,"result":{"psbtBase64":"cHNi..."}} beignet wallet refresh # {"ok":true,"result":{"refreshed":true}} beignet utxos # Each UTXO carries a frozen flag: # {"ok":true,"result":[{"txid":"ab12...","vout":0,"valueSats":50000,"frozen":false,...}]} beignet utxo freeze # {"ok":true,"result":{"frozen":"ab12...:0"}} beignet utxo unfreeze # {"ok":true,"result":{"unfrozen":"ab12...:0"}} beignet utxo frozen # List only frozen UTXOs beignet address label bc1q... "cold storage change" # {"ok":true,"result":{"address":"bc1q...","label":"cold storage change"}} beignet address labels # {"ok":true,"result":{"bc1q...":"cold storage change"}} beignet wallet descriptors # BIP 380 descriptors for all four address types (public keys only, with checksums): # {"ok":true,"result":{"fingerprint":"73c5da0a","descriptors":[{"addressType":"p2wpkh","external":"wpkh([73c5da0a/84h/0h/0h]xpub.../0/*)#...","internal":"wpkh(.../1/*)#..."},...]}} ``` On-chain sends signal BIP 125 replace-by-fee, so an underpaying transaction can later be bumped with `tx bump-fee` (or `tx boost`, which falls back to CPFP when RBF is unavailable). The wallet's staged send is reset after every `send`, `send-max`, `consolidate`, `psbt build` and boost, so a restart never replays an earlier call's recipients, and external signing keys are never written to storage. **Daily spend limit (combined):** when the daemon is started with `--daily-spend-limit`, `send` and `send-max` count amount + fee against the SAME daily budget as Lightning payments and fail with `SPENDING_LIMIT_EXCEEDED` once it is exhausted. This limit was previously Lightning-only. The ledger is persisted, so a daemon restart within the UTC day resumes the day's total rather than starting it at zero. `consolidate`, channel funding and `tx bump-fee`/`tx boost` are not counted. Frozen UTXOs are excluded from every send path (`send`, `send-max`, `consolidate`, `psbt build`) until unfrozen. **Multi-account and wallet birthday (library only):** `Wallet.create` accepts `account` (BIP32 account index, default 0; per-account storage isolation) and `birthdayHeight` (persisted creation-height metadata, exported with descriptors). The daemon always runs a single account-0 wallet and does not expose either option. `birthdayHeight` cannot speed up Electrum scans (the protocol has no height-filtered history), it is recorded for future backends and external tooling. The on-chain wallet's state (addresses, UTXOs, transactions) persists in the node's SQLite database (encrypted at rest when `storageEncryption` is on, the default), so restarts sync incrementally from Electrum instead of rebuilding the wallet from scratch. ### Peers ```bash beignet peer connect beignet peer disconnect beignet peer list ``` ### DNS Bootstrap (BOLT 10) ```bash beignet bootstrap discover # {"ok":true,"result":[{"pubkey":"02ab...","host":"1.2.3.4","port":9735},...]} beignet bootstrap connect 5 # {"ok":true,"result":{"connected":["02ab...","03cd..."]}} ``` ### Trusted Peers (Zero-Conf) ```bash beignet trusted-peer add # {"ok":true,"result":{"pubkey":"02ab...","trusted":true}} beignet trusted-peer remove # {"ok":true,"result":{"pubkey":"02ab...","trusted":false}} beignet trusted-peer list # {"ok":true,"result":[{"pubkey":"02ab...","trusted":true}]} ``` The set is durable: it is written to the wallet database on every add and remove, and reloaded at startup before any peer can reconnect. Membership is symmetric and says this node will treat that peer's UNCONFIRMED funding as a usable channel, so it is also what makes an inbound zero-conf open acceptable. An acceptor that does not carry the opener refuses a zero_conf open outright rather than downgrading it to a confirmed one, which is why a wallet receiving through a JIT LSP has to carry that LSP here. ### Receive primaries ```bash beignet primaries add --host 10.0.0.2 --port 9735 [--rank 1] beignet primaries add --uri '@iroh:' beignet primaries threshold 1000000 # or: none beignet primaries reorder beignet primaries remove beignet primaries list # {"ok":true,"result":{"fillThresholdSat":1000000,"receiveTarget":"02ab...","primaries":[{"pubkey":"02ab...","rank":1,"balanceSat":400000,"isReceiveTarget":true,...}]}} ``` The list and the threshold are saved in the wallet database and survive a restart. A receive that names no peer is steered by them: `invoice jit` and `jit quote` without an LSP, and `GET /receive/quote` without a `peer`, walk the primaries in `selectionOrder`, dial one that is not connected by its stored address (JIT only), and pass over one that is unreachable, times out, declines or quotes above the fee ceilings, under one 18 s budget for the whole walk. The answer names the primary that took it in `lspPubkey` (or `peer`) and lists the others in `skipped`; 503 `NO_PRIMARY_AVAILABLE` names every reason when none took it, and 400 `INVALID_PARAMS` answers when no primary is configured. A call that names its peer never falls back. A direct-funding request is bound to the peer it is minted for: `POST /direct-funding/request` without `lspPubkey` binds to the first primary in `selectionOrder` with a known address, with `lspPubkey` binds to that peer when it is a configured primary or the policy's liquidity peer (400 `INVALID_PARAMS` for any other, since the route runs at invoice scope), and an automatic offline receive that falls back to direct funding binds to the peer its quote named. The envelope's relay descriptors name that peer and the receiver negotiates the funding with it when the offer arrives, whatever the direct-funding policy's liquidity peer is by then. Nothing is dialed for a mint: the payer reaches this node through that primary's relay later. ### Channels For a private Bitcoin type-80 channel, initialize a fresh regtest wallet on each Beignet peer with `beignet init --network regtest --final-commitment-updates`. Fund the opener, connect the peers and run `beignet channel open-v2 --final-taproot`. HTTP clients can send `POST /channel/open-v2` with `finalTaproot` set to `true`. For a two-contributor asset opening, initialize both fresh regtest wallets with `beignet init --network regtest --dual-funded-assets`, attach an asset extension with the `dualFunding:v1` provider on both nodes, and configure the contributions in that extension. Run `beignet channel open-v2 --dual-funded-assets` or set `dualFundedAssets` to `true` in the HTTP request. The channel becomes ready after the configured confirmation depth and successful proof import on both wallets. See [the extension contract](../../docs/EXTENSIONS.md#dual-funded-asset-opening-on-regtest). Each original wallet saves its unilateral exit before sending funding witnesses. After the funding reaches the negotiated depth and the peers exchange `channel_ready`, `GET /channels` reports `NORMAL`. The daemon can then pay and receive invoices. After restart it checks the funding and reestablishes with the peer before sending another update. A reorg that removes the necessary funding depth suspends payments. Use the ordinary splice-in and splice-out commands to change the channel capacity. Both parties retain enforceable commitments for the old and new funding while the splice awaits matching locks. Ordinary payments during that interval commit to each live funding outpoint. The daemon supports one pending splice per channel. It declines fee replacement during opening and splicing. Once both peers lock the new funding at the negotiated depth, subsequent updates spend the new outpoint. If a peer discards an unsigned splice on disconnect, the original wallet releases its selected inputs and a retry uses new funding keys. Use `beignet channel close ` for a cooperative close or `beignet channel forceclose ` to publish the current unilateral exit. An original daemon with a chain connection claims its eligible outputs to the wallet after the applicable delay. A local HTLC second-stage transaction also needs a spendable wallet fee input. Restart with the original wallet directory and device journal. An encrypted SQLite backup preserves public messages and recovery records. Selecting a current unilateral exit or issuing new signatures requires the original device journal. Keep the original device through final settlement. A whole-device rollback can also roll back that journal. The earlier `--final-taproot-wallet` enrollment still provides the opening and readiness profile for existing regtest wallets. It reaches `CHANNEL_READY`. Commitment updates require fresh enrollment with the new switch. ```bash beignet channel open [pushSats] beignet channel open-zeroconf [pushSats] beignet channel open-v2 [fundingFeeratePerkw] [--final-taproot] [--request-funds ] [--blockheight ] [--max-lease-rates ''] # The lease flags buy inbound liquidity (option_will_fund) at or under the # given rate ceiling; --blockheight defaults to the node's current tip. beignet channel open-and-wait [pushSats] [--timeout 60000] beignet channel connect-and-open [pushSats] beignet channel close [--address
] [--accept-stale-state-risk] beignet channel close-quote [--address
] beignet channel forceclose [--accept-stale-state-risk] # Both closes pay out to a wallet-owned address the wallet scans, on the # internal change chain: the next unused change address when the wallet can # produce one (consecutive closes may get the same address until it sees use), # falling back to the startup sweep address (the stored change address when # Electrum was down at startup) and then the funding-key address, so the # closed balance is tracked and spendable without a rescue sweep. Never a # receive address: the next unused receive address is the one `address new` / # `POST /address/new` handed out most recently, and a payout there would read # as that receive request being paid (issue #1064). # A channel restored from a Recovery Capsule refuses either close without the # flag. Cooperative: a mutual close pays out restored balances that cannot be # proven current. Force: if the peer holds a newer state the broadcast is # revoked and the whole channel balance goes to the justice path. beignet channel forceclose --offline [--network ] [--accept-stale-state-risk] # The same force close with the daemon stopped, for when it cannot start. The # wallet comes from config.json or BEIGNET_MNEMONIC, never from the command # line, and Electrum is dialed with the configured host, port and TLS # settings. It takes the daemon's instance lock, so it is refused while the # daemon runs. It connects to no peers, waits up to a minute for Electrum # (closing nothing if it never answers) and up to a minute for the broadcast, # then prints the commitment txid. Run it again on a channel already force # closed and it rebroadcasts the commitment. beignet channel rebroadcast-close beignet channel splice-in beignet channel splice-out [address] # [address] pays the spliced-out funds to an external address directly (one # transaction, no wallet hop); omitted, they go to the wallet beignet channel ensure-minimum 3 500000 # Auto-open channels to at least 3 using graph suggestions, 500k sats each beignet channel update-policy [--base-fee-msat N] [--ppm N] [--cltv-delta N] [--htlc-min-msat N] [--htlc-max-msat N] beignet channel update-commitment-feerate # COMMITMENT feerate (BOLT 2 update_fee, opener only) - not the routing policy beignet channel policy beignet channel list beignet channel ready # Only channels in NORMAL state beignet channel get # channel get/list include the effective routing policy fields beignet channel health beignet channel suggestions [count] beignet channel wait-ready [--timeout 60000] ``` ### Routing Fee Policy Per-channel control of the ROUTING policy advertised in `channel_update` (not the commitment feerate, which is `/channel/update-commitment-feerate`): base fee, proportional fee (ppm), CLTV delta, and HTLC min/max. Unset fields fall back to the node-wide defaults; overrides persist across restarts. Announced channels re-broadcast the updated `channel_update` immediately; unannounced channels send it directly to the peer. ```bash beignet channel update-policy ab12... --base-fee-msat 500 --ppm 100 # {"ok":true,"result":{"updated":1,"policies":[{"channelId":"ab12...","feeBaseMsat":500,"feeProportionalMillionths":100,"cltvExpiryDelta":40,"htlcMinimumMsat":"1000","htlcMaximumMsat":"500000000","source":"override"}]}} beignet channel update-policy all --cltv-delta 80 # Applies to every channel; other fields keep their current values ``` ### Forwarding History Ledger of settled forwards (HTLCs this node relayed where both legs fulfilled), with the fee earned per forward. Records persist in the node database (capped at 100k rows, oldest pruned first). Msat values are decimal strings. Failed forwards are not recorded. A forward with an asset leg (issue #2098) carries `"auxiliary":true`. Its amounts are what each leg was worth, never a carrier: the host's value of an incoming asset leg in, the amount the onion asked the node to forward out. `inAuxiliaryAmount` and `inWireAmountMsat`, `outAuxiliaryAmount` and `outWireAmountMsat` give the units and carrier of each asset leg, and `nextHopScid` the next hop the onion named. The summary counts such forwards apart, in `auxiliary`, so its bitcoin totals count ordinary forwards only. ```bash beignet forwards --since 1751000000000 --limit 50 # {"ok":true,"result":[{"id":7,"settledAt":1751234567890,"inChannelId":"ab12...","outChannelId":"cd34...","amountInMsat":"5005000","amountOutMsat":"5000000","feeMsat":"5000"}]} beignet forwards summary --since 1751000000000 # {"ok":true,"result":{"count":42,"volumeOutMsat":"210000000","feesEarnedMsat":"210000"}} ### Graph Queries lncli-style read access to the gossip network graph, plus manual routing: compute a route without paying, then (optionally) pay along exactly that route. SCIDs are formatted `xx` (16-char hex also accepted). ```bash beignet graph info # {"ok":true,"result":{"nodeCount":18432,"channelCount":51200,"lastSyncAt":1767952800000}} beignet graph node 02abc... # {"ok":true,"result":{"pubkey":"02abc...","alias":"ACINQ","color":"ff9900","addresses":[...],"featuresHex":"8000...","lastUpdate":1767950000,"channelCount":3,"channels":["700000x1x0",...]}} beignet graph channel 700000x1x0 # {"ok":true,"result":{"shortChannelId":"700000x1x0","node1Pubkey":"02ab..","node2Pubkey":"03cd..","capacitySats":1000000,"node1Policy":{"feeBaseMsat":1000,"feeProportionalMillionths":1,"cltvExpiryDelta":40,"htlcMinimumMsat":"1000","htlcMaximumMsat":"1000000000","disabled":false,"lastUpdate":1767950000},"node2Policy":{...}}} beignet graph describe --limit 100 --offset 200 # Paged dump: {"ok":true,"result":{"totalChannels":51200,"limit":100,"offset":200,"channels":[...]}} beignet route query 02abc... 50000 --max-fee 100 # Computes a route WITHOUT paying: # {"ok":true,"result":{"destination":"02abc...","amountSats":50000,"hops":[{"pubkey":"03cd..","shortChannelId":"700000x1x0","amountToForwardMsat":"50001000","outgoingCltvValue":80,"feeMsat":"1000","cltvExpiryDelta":40},...],"totalAmountMsat":"50001000","totalFeeMsat":"1000","totalCltvDelta":80,"finalCltvExpiry":40}} beignet route query 02abc... 50000 --pretty > route.json beignet payment send-to-route route.json --payment-secret # Pays along exactly that route (accepts a file path or inline JSON; # both the full result object and a bare {"hops":[...]} work) beignet route estimate [sats] # {"ok":true,"result":{"feeSats":2,"hops":3,"cltvDelta":120}} beignet route probe 02abc... 50000 # Probes route viability without paying ``` ### Invoices & Payments ```bash beignet invoice create [sats] [description] # {"ok":true,"result":{"bolt11":"lnbcrt10n1...","paymentHash":"ab12...","amountSats":1000}} beignet invoice decode # {"ok":true,"result":{"network":"bcrt","amountSats":1000,"paymentHash":"ab12...",...}} beignet invoice validate [sats] # Pre-flight checks (decode, capacity, route): {"ok":true,"result":{"status":"OK","checks":[...]}} beignet invoice get # Details of an invoice this node created beignet invoice pay # Blocks until payment settles or fails (60s timeout) # {"ok":true,"result":{"paymentHash":"ab12...","preimage":"cd34...","status":"COMPLETED",...}} beignet invoice pay-safe [--max-fee 100] [--amount 1000] [--timeout 60000] # Never errors: resolves with status FAILED instead beignet invoice pay-async [--max-fee 100] [--amount 1000] # Fire-and-forget: returns {paymentHash,status} immediately; poll 'payment get' beignet invoice pay-retry [--max-retries 5] [--backoff-ms 1000] [--max-fee 100] # Retries with exponential backoff on transient failures # {"ok":true,"result":{"paymentHash":"ab12...","status":"COMPLETED","attempts":2,...}} beignet keysend [--max-fee 100] [--timeout 60000] beignet keysend safe # Spontaneous payment, no invoice ('safe' resolves FAILED instead of erroring) beignet invoice list # {"ok":true,"result":[{"bolt11":"lnbcrt10n1...","paymentHash":"ab12...","amountSats":1000,...}]} # Hold invoices: you keep the preimage; the payer's HTLC parks until you settle beignet invoice create-hold 1000 "escrow" --expiry 3600 # {"ok":true,"result":{"bolt11":"lnbcrt10n1...","paymentHash":"ab12...","amountSats":1000}} # Swap leg: the delta has to outlive the on-chain refund timeout and the margins # after it, or the payer gets its sats back over Lightning and still claims the # contract. A parked HTLC is cancelled 18 blocks before it expires, and the # refund still has to be resolved after that, so the reverse swap role asks for # refund 144 + resolution 24 + cancellation 18 + padding 8 = 194. beignet invoice create-hold 1000 "swap" --min-final-cltv 194 beignet invoice held # {"ok":true,"result":[{"paymentHash":"ab12...","state":"ACCEPTED","heldAmountMsat":"1000000","htlcCount":1,...}]} beignet invoice settle-hold # fulfills the parked HTLC(s) beignet invoice cancel-hold # fails them back to the payer beignet payment list [--limit 1000] [--offset 0] beignet payment get beignet payment cancel beignet payment wait [--timeout 60000] beignet payment proof beignet payment verify-proof beignet payment estimate [sats] beignet payment metadata '{"orderId":"1234"}' # Payment queue: ordered dispatch with priorities beignet queue add [--priority 5] [--amount 1000] [--max-fee 100] beignet queue list beignet queue cancel beignet queue get beignet queue history [--limit 100] [--before ] ``` ### Messages & Gossip ```bash beignet message sign "proof of node ownership" # {"ok":true,"result":{"signature":"d7y...104 zbase32 chars...","pubkey":"02ab..."}} beignet message verify "proof of node ownership" # {"ok":true,"result":{"valid":true,"pubkey":"02ab...","knownNode":true}} beignet gossip sync # sync graph from all connected peers beignet gossip sync-rapid # Rapid Gossip Sync snapshot (mainnet) beignet channel diagnostics beignet address validate bc1q... beignet recover-fallback-funds --fee-rate 5 beignet backup trigger ``` ### Guardian Recovery ```bash beignet recovery status # Recovery Protocol status: mode, guardian set, # startup gate, last durable sequence beignet recovery restore # take this namespace over from the guardian # replicas and start the node on the restored # state (restore-pending daemons only; channels # RESUME instead of force-closing) beignet recovery restore-capsule # peer-storage mode: restore from the # Recovery Capsules storage peers returned # (connect to the old channel peers first; # Tier 2 asks for a daemon restart) # --unfenced: guardian set gone; restores a # guardian-backed capsule WITHOUT fencing the # old writer (never for quorum journals) # --omit-asset-channels: leave the asset # channels the capsule holds out of the restore beignet recovery capsule-guardians # the best retrieved capsule's guardian set beignet recovery resolve-guardian @host:port # a beignet node as a guardian entry beignet recovery rotate-guardians # move to a new guardian set, channels running beignet guardian status # the guardian this node serves to others # with credentials, as config entries ``` ### BOLT 12 Offers ```bash beignet offer create "Coffee" 1000 # {"ok":true,"result":{"offerId":"ab12...","description":"Coffee","amountSats":1000,"encoded":"lno1..."}} beignet offer list # {"ok":true,"result":[{"offerId":"ab12...","description":"Coffee",...}]} beignet offer decode lno1... # {"ok":true,"result":{"offerId":"ab12...","description":"Coffee","amountSats":1000,...}} beignet offer pay lno1... 1000 # Requests invoice from offer issuer, then pays it # {"ok":true,"result":{"paymentHash":"ab12...","status":"COMPLETED",...}} beignet offer pay lno1... 1000 --max-fee 5 # Same, refusing to pay more than 5 sats of routing fee (public hops plus the # invoice's own blinded-path fee); over the cap nothing is sent ``` ### Webhooks (CLI) ```bash beignet webhooks register https://myagent.com/callback payment:received,channel:ready --secret mysecret beignet webhooks register https://myagent.com/callback '*' # '*' subscribes to every event, including any added in future versions beignet webhooks list beignet webhooks unregister ``` Most daemon endpoints have a CLI command. HTTP-only exceptions include `GET /events` (SSE stream for long-lived consumers; use `webhooks` from the CLI instead) and `GET /openapi.json` (machine-readable API discovery). The deprecated `POST /channel/update-fee` alias is covered by `channel update-commitment-feerate`. The app-driven FFOR lifecycle uses `/ffor/*` and `/receive/*` directly over HTTP. `GET /receive/quote` answers with a `mode` and `POST /receive/invoice` with a matching `kind`: `bolt11` when a channel that already exists with that peer can carry the payment offline, and `direct-funding` otherwise, which returns a direct-funding `request` instead of an invoice. Automatic receiving never opens a channel to obtain inbound liquidity. A quote with no `peer` is steered through the ranked primaries, and a create with no `peer` binds to the one its reviewed quote named. A direct-funding request is bound to the peer it was quoted at, whatever the direct-funding policy names. See [automatic receiving](../../docs/AUTOMATIC-OFFLINE-RECEIVE.md#daemon-api) for the durable invoice preparation and reconciliation API. With concurrent receive negotiated, a funded home channel can carry an offline invoice and ordinary online payments within its remaining capacity. `BEIGNET_FFOR_CONCURRENT` and `BEIGNET_FFOR_SETTLE_CONCURRENT` both default to true and accept explicit `false`. The settlement role must still be enabled separately. `POST /ffor/sync` refreshes receipts without retiring the book. The `ffor` block on channels and the concurrent entries in `/receive/status` expose reserved inbound capacity and unresolved slots. Keep reserved channels out of automatic splicing and channel close. Retirement of version 2 unknown slots can remain `DRAINING` after the invoice expires. ### Porch links (CLI) ```bash beignet porch links # {"ok":true,"result":{"enabled":true,"listening":true,"links":[{"id":"5f0c...","default":true,"uris":["02ab...@wss://relay.example/v1/p/k3v..."]}],"relays":[{"relay":"wss://relay.example","state":"ready","idle":2,"circuits":0,"proxied":false}]}} beignet porch links create --label "Dana's phone" # {"ok":true,"result":{"id":"9d41...","label":"Dana's phone","createdAt":1731350000000,"uris":["02ab...@wss://relay.example/v1/p/q7x..."]}} beignet porch links revoke 9d41... # {"ok":true,"result":{"revoked":true,"id":"9d41..."}} ``` The node needs `porchRelays` configured: see [Porch links](#porch-links). ### Porch relay `beignet porch-relay` runs a Porch relay: a small server that lets a node at home hand out a `wss://` peer link without telling anyone where it runs. The node dials out to the relay and waits there. A visitor connects to the relay with an ordinary `pubkey@wss://relay/v1/p/` link, and the relay pairs the two and copies bytes it cannot read (they are BOLT 8). It needs no wallet, no data directory and no daemon, and belongs on a small server with a public address. Setting one up, with the proxy configuration and a service unit, is in [docs/PORCH.md](../../docs/PORCH.md). The protocol, what each party learns and every limit are in [docs/PORCH-PROTOCOL.md](../../docs/PORCH-PROTOCOL.md). ```bash # Behind a TLS terminator (Caddy, nginx) that forwards wss://relay.example here beignet porch-relay --url wss://relay.example --trusted-proxy 127.0.0.1 # Serving TLS itself beignet porch-relay --url wss://relay.example:8443 --host 0.0.0.0 --port 8443 \ --tls-cert fullchain.pem --tls-key privkey.pem ``` | Flag | Meaning | | --- | --- | | `--url ` | The relay's public URL as nodes are given it: `wss://host[:port]`, or `ws://` for an onion service. Required. Repeat it for a relay with more than one name. A node registers only with a relay that names itself by the URL the node dialed. | | `--port ` | Listen port (default 2114) | | `--host
` | Listen address (default `127.0.0.1`) | | `--tls-cert `, `--tls-key ` | Serve TLS directly. Without them, put a TLS terminator in front. | | `--token-file ` | A private relay: only a node that presents this token may register. `BEIGNET_PORCH_RELAY_TOKEN` sets it too. | | `--trusted-proxy ` | A reverse proxy whose `X-Forwarded-For` is believed. Repeatable. Without it every connection through a proxy counts as the proxy's own, and the per-address limits do nothing. | | `--limit =` | Override one limit by its name in `IPorchRelayLimits`, for example `--limit connections=2048`. Repeatable. | | `--stats ` | Print the relay's counters to stderr at this interval | An unknown flag is an error. `GET /health` answers `{"ok":true}`. The relay keeps no state: restarting it drops the connections that were open, and nodes dial back in. It prints one JSON line when it is listening and runs until it is signalled. A node is pointed at a relay with `porchRelays`: see [Porch links](#porch-links). ### JSON Envelope Every response follows this format: ```json // Success {"ok": true, "result": { ... }} // Failure {"ok": false, "error": {"code": "PAYMENT_FAILED", "message": "No route found"}} ``` --- ## Configuration ### Config File `~/.beignet/config.json`: ```json { "mnemonic": "abandon abandon ...", "network": "regtest", "alias": "mynode", "dataDir": "/custom/path", "electrumHost": "127.0.0.1", "electrumPort": 60001, "electrumTls": false, "listenPort": 9735, "daemonHost": "127.0.0.1", "daemonPort": 2112, "preferAnchors": true, "apiToken": "mysecrettoken", "apiKeys": [ { "name": "monitor", "key": "readonlysecret", "scopes": ["readonly"] }, { "name": "shop", "key": "invoicesecret", "scopes": ["invoice", "readonly"] }, { "name": "ops", "key": "adminsecret", "scopes": ["admin"] }, { "name": "contractor", "key": "temporarysecret", "scopes": ["readonly"], "expiresAt": "2027-01-01T00:00:00Z" } ], "autoBootstrap": false, "backupPath": "/var/backups/beignet/node.db", "backupIntervalMs": 21600000, "electrumServers": [ { "host": "electrum1.bluewallet.io", "port": 443, "tls": true }, { "host": "electrum2.bluewallet.io", "port": 443, "tls": true } ], "dailySpendLimitSats": 100000, "connectTimeoutMs": 15000, "tlsCert": "/etc/ssl/beignet/cert.pem", "tlsKey": "/etc/ssl/beignet/key.pem", "rateLimit": { "maxRequests": 100, "windowMs": 60000 }, "htlcEvents": false } ``` ### File permissions The config file carries the mnemonic and the API token, so everything under `~/.beignet` is created owner-only: `~/.beignet` and the data directory are `0700`, and `config.json`, `daemon.pid`, the SQLite database with its `-wal` and `-shm` sidecars, the instance lock, database backups (`backup()`, the scheduled backup, `POST /backup`) and their `.hmac` files, restore copies and SCB exports are `0600`. The modes are set explicitly rather than trusted to the umask; the CLI also sets the process umask to `077` for `init`, `start`, `backup` and `restore`, so anything else those commands create is owner-only too. A library host that embeds `BeignetNode` keeps its own umask. A `config.json` or `~/.beignet` written by an earlier release is tightened the next time the config is read (every CLI command reads it), with one line on stderr naming the path: `beignet: tightened permissions on (was 0644, now 0600)`. When the chmod is refused (a read-only or foreign filesystem) a warning is printed once instead and startup continues. On Windows, where ACLs govern access, none of this applies. ### Environment Variables Environment variables override the config file but are overridden by CLI flags. | Variable | Description | |----------|-------------| | `BEIGNET_MNEMONIC` | BIP39 mnemonic | | `BEIGNET_NETWORK` | `mainnet`, `testnet`, `signet` or `regtest` | | `BEIGNET_ALIAS` | Node alias | | `BEIGNET_DATA_DIR` | Data directory, used as given (default `~/.beignet/data/`, a subdirectory per mnemonic; see `dataDir` under [Factory](#factory)) | | `BEIGNET_ELECTRUM_HOST` | Electrum server hostname | | `BEIGNET_ELECTRUM_PORT` | Electrum server port | | `BEIGNET_ELECTRUM_TLS` | `true` or `false` | | `BEIGNET_ELECTRUM_TLS_VERIFY` | `true` checks Electrum TLS certificates (default off); anything but `true`, `false` or empty refuses startup | | `BEIGNET_ELECTRUM_TLS_FINGERPRINTS` | Comma-separated SHA-256 certificate fingerprints to accept for self-signed servers; needs `BEIGNET_ELECTRUM_TLS_VERIFY=true` | | `BEIGNET_LISTEN_PORT` | Lightning listen port | | `BEIGNET_MAX_INBOUND_PEERS` | Inbound peer connections (default 125); once this many are up, only peers holding a channel with this node are admitted | | `BEIGNET_DAEMON_HOST` | HTTP daemon bind address (default: `127.0.0.1`) | | `BEIGNET_DAEMON_PORT` | HTTP daemon port | | `BEIGNET_PREFER_ANCHORS` | `true` to prefer anchor channels | | `BEIGNET_API_TOKEN` | Legacy single API token (implicit admin scope) | | `BEIGNET_API_KEYS` | Named scoped API keys as a JSON array: `[{"name","key","scopes":["readonly"\|"invoice"\|"admin"]}]` | | `BEIGNET_API_KEY` | CLI-side only: bearer credential the CLI sends to the daemon (alias of `BEIGNET_API_TOKEN` for named-key secrets) | | `BEIGNET_AUTO_BOOTSTRAP` | `true` to auto-connect to DNS seed peers on start | | `BEIGNET_BACKUP_PATH` | Automated backup destination path | | `BEIGNET_BACKUP_INTERVAL_MS` | Backup interval in milliseconds (default: 21600000 = 6h) | | `BEIGNET_DAILY_SPEND_LIMIT_SATS` | Daily spending limit in satoshis (resets at midnight UTC; the day's ledger survives a restart) | | `BEIGNET_CONNECT_TIMEOUT_MS` | Timeout for `connectPeer()` in milliseconds (default: 15000) | | `BEIGNET_TLS_CERT` | Path to TLS certificate for HTTPS daemon | | `BEIGNET_TLS_KEY` | Path to TLS private key for HTTPS daemon | | `BEIGNET_TOR_PROXY` | SOCKS5 proxy as `host:port` for outbound Lightning peer and watchtower connections (e.g. Tor at `127.0.0.1:9050`); `.onion` peers need one. Unset, `.onion` peers fall back to `127.0.0.1:9050` and everything else is dialed directly | | `BEIGNET_TOR_PROXY_ONION_ONLY` | `true` to use `BEIGNET_TOR_PROXY` for `.onion` hosts only and dial public clearnet hosts directly (hybrid mode, LND's `tor.skip-proxy-for-clearnet-targets`); exact `true`/`false`, anything else is ignored. Needs `BEIGNET_TOR_PROXY`, or startup is refused | | `BEIGNET_HTLC_EVENTS` | `true` to relay per-HTLC events over SSE + webhooks | | `BEIGNET_EXTENSIONS` | Host extensions to run inside the daemon: comma-separated absolute paths of modules that export `beignetExtension` ([docs/EXTENSIONS.md](../../docs/EXTENSIONS.md)). Environment and `--extension` only, never `config.json`. A path that is relative, missing, or writable by another user refuses the start | | `BEIGNET_EAGER_GOSSIP_VERIFY` | `true` to verify foreign gossip signatures at intake instead of lazily at serve time (default: lazy; exact `true`/`false`, anything else is ignored) | | `BEIGNET_LOG_LEVEL` | Daemon stderr log level: `debug`, `info`, `warn`, `error`, `silent` (default: silent) | | `BEIGNET_WIRE_TRACE` | Log every non-gossip wire message (direction, type, length; no payloads) at `info`: `1` for every peer, or comma-separated peer pubkeys (default: off) | | `BEIGNET_RECOVERY_MODE` | Recovery Protocol mode: `off`, `peer-storage`, `async-remote`, `quorum` (default: off; unknown values fall back to off) | | `BEIGNET_RECOVERY_GUARDIANS` | Guardian set for async-remote/quorum, comma-separated `<64-hex-x-only-pubkey>@` where the URL is `http(s)://...` for an HTTP guardian or `bolt8://<66-hex node id>@host:port` for a guardian hosted by a beignet node (crash-v1: exactly three; malformed entries refuse startup) | | `BEIGNET_RECOVERY_PROFILE` | Recovery fault-model profile; `crash-v1` is the only accepted value and the default | | `BEIGNET_RECOVERY_LEASE_CHECK_MS` | Guardian modes: idle writer lease re-check cadence in ms, an integer in 0..2147483647 (default: 300000; 0 disables; anything else refuses startup) | | `BEIGNET_RECOVERY_REESTABLISH_HOLD_MS` | peer-storage mode: how long an unknown channel's `channel_reestablish` is held before the BOLT 1 error goes out, an integer in 0..2147483647 (default: 600000; 0 answers immediately; anything else refuses startup) | | `BEIGNET_GUARDIAN_SERVE` | `true` to serve the reference guardian to other beignet nodes over bolt8 sessions at this node's Lightning address (docs/RECOVERY-GUARDIAN-WIRE.md 2.7); needs `BEIGNET_LISTEN_PORT`. Independent of this node's own recovery mode, and kept serving while this node's own writer lease is quarantined | | `BEIGNET_GUARDIAN_TOKEN` | Bearer token every guardian session must present; unset runs open (BOLT 8 already encrypts and authenticates the host, so the token is an allow-list) | | `BEIGNET_GUARDIAN_MAX_BYTES` | Hard bound on the content one served guardian set may store (its encoded rows; SQLite's overhead comes on top): every write, epoch rows and rotations included, that would cross it is refused with `ERR_QUOTA_EXCEEDED` (default 268435456). A set registers at most 8 namespaces, and each may store an eighth of this. Refuses, never deletes | | `BEIGNET_GUARDIAN_MAX_SETS` | Guardian sets this node will register (default 16) | | `BEIGNET_GUARDIAN_MAX_CIPHERTEXT_BYTES` | Advertised per-record ciphertext limit (default 4194304; protocol cap 16 MiB) | | `BEIGNET_RECOVERY_AUTO_APPLY` | peer-storage mode: on a boot whose database is empty, apply the best Recovery Capsule the storage peers return with no operator call and rebuild the node in-process on it (exact `true`/`false`; default off; refused outside peer-storage mode). Cannot fence a previous device that still runs | | `BEIGNET_RECOVERY_AUTO_APPLY_SETTLE_MS` | Auto-apply settle floor from the first capsule's arrival, so a slower replica still competes for the selection (default: 15000) | | `BEIGNET_RECOVERY_AUTO_APPLY_MAX_WAIT_MS` | Auto-apply ceiling from the first arrival; storage peers that never connect are not waited for past it (default: 120000; must be at least the settle floor and below `BEIGNET_RECOVERY_REESTABLISH_HOLD_MS`) | | `BEIGNET_FEE_BASE_MSAT` | Node-wide default routing base fee advertised in `channel_update`, an integer in 0..4294967295 msat (default: 1000; anything else refuses startup). Per-channel `channel update-policy` overrides win | | `BEIGNET_FEE_PPM` | Node-wide default proportional routing fee in millionths, an integer in 0..4294967295 (default: 1; anything else refuses startup). Per-channel overrides win | | `BEIGNET_CLTV_DELTA` | Node-wide default forwarding CLTV delta, an integer in 1..65535, `>= 18` recommended (default: 40; anything else refuses startup). Per-channel overrides win | | `BEIGNET_LEASE_RATES` | Liquidity ads (`option_will_fund`) seller policy: a JSON object `{"fundingWeightWitness":n,"leaseFeeBasis":n,"leaseFeeBaseSat":n,"channelFeeMaxBaseMsat":n,"channelFeeMaxProportionalThousandths":n}` (u16/u16/u32/u32/u16). Setting it sells inbound liquidity at these rates and advertises the feature bit; malformed or out-of-range values refuse startup; unset means never sell | | `BEIGNET_JIT_RECEIVE` | JIT channel receive, LSP role: hold HTLCs addressed to intercept SCIDs registered by wallet peers, fund a zero-conf channel with THIS node's coins, then forward (`true`/`false`, default off) | | `BEIGNET_JIT_FLAT_FEE_SAT` | Flat part of the opening fee the LSP role deducts from a JIT delivery, an integer in 0..4294967295 (default 0) | | `BEIGNET_JIT_FEE_PPM` | Proportional part of that fee in millionths of the delivered total, an integer in 0..1000000 (default 0) | | `BEIGNET_JIT_MAX_FLAT_FEE_SAT` | Wallet role: most an LSP may quote `POST /jit/invoice` as a flat fee before the intent is refused (default 10000) | | `BEIGNET_JIT_MAX_FEE_PPM` | Wallet role: most an LSP may quote as a proportional fee, in millionths (default 50000). Applies whether or not the LSP role is on | | `BEIGNET_JIT_MAX_CLIENT_FUNDING_SAT` | LSP role: most this node fronts for ONE client, open or splice (default 1000000; a partly numeric value refuses startup) | | `BEIGNET_JIT_MAX_CONCURRENT_FUNDINGS` | LSP role: fundings (opens plus splices) allowed in flight at once, an integer in 0..1000 (default 3). With the per-client cap this bounds what is committed at any instant | | `BEIGNET_JIT_MAX_TOTAL_FUNDING_SAT` | LSP role: lifetime budget of sats this node may ever front, counted across restarts (default unset, meaning no lifetime budget: exposure at any instant is bounded by the two caps above) | | `BEIGNET_SWAPS` | Reverse swap provider role (issue #737): a peer pays this node a hold invoice, this node funds a P2WSH contract the peer claims on chain, and the claim's preimage settles the hold (`true`/`false`, default off: the role locks THIS node's coins in contracts for peers) | | `BEIGNET_SWAP_FLAT_FEE_SAT` | Flat part of the swap fee, sats (default 0) | | `BEIGNET_SWAP_FEE_PPM` | Proportional part of the swap fee in millionths of the on-chain amount (default 0). The quoted funding miner fee is added to both | | `BEIGNET_SWAP_MIN_SAT` / `BEIGNET_SWAP_MAX_SAT` | Smallest and largest on-chain amount served (defaults 10000 / 1000000) | | `BEIGNET_SWAP_MAX_EXPOSURE_SAT` | Most principal this node will have at risk on chain across unresolved swaps at once (default 5000000) | | `BEIGNET_SWAP_MAX_CONCURRENT` | Swaps with principal at risk allowed at once (default 8); an unpaid create does not count | | `BEIGNET_SWAP_REFUND_DELTA_BLOCKS` | Blocks from create to the contract's refund height (default 144; a client may prefer another within the provider's bounds). The hold invoice's final CLTV is derived from the swap's delta so a paid hold always outlives the refund | | `BEIGNET_SWAP_FUNDING_CONFS` / `BEIGNET_SWAP_RESOLUTION_CONFS` | Depth the funding needs before it counts, and depth a claim or refund needs before it is the outcome (defaults 1 / 3). A claim settles the hold at any depth, the mempool included; a refund cancels it only at this depth. Both directions share these | | `BEIGNET_SWAP_SUBMARINE` | With `BEIGNET_SWAPS=true`, also serve the submarine direction (issue #743): a peer locks coins in a P2WSH contract whose preimage branch is this node's, this node pays the peer's own invoice once the funding has confirmed to `BEIGNET_SWAP_FUNDING_CONFS` and been re-verified unspent, with every HTLC bound to the refund height minus the claim margins, and claims the coins with the preimage. Exact `true`/`false`, default off: the node pays out Lightning funds against a contract it must then claim. The fee terms and exposure caps above apply to both directions | | `BEIGNET_SWAP_CLAIM_SAFETY_BLOCKS` | Blocks between the last possible outgoing HTLC expiry and the peer's refund height, for a late preimage to be claimed and confirmed (default 24) | | `BEIGNET_SWAP_PAYMENT_MAX_FEE_PPM` | Routing fee this node may spend on the payment, per million of the invoice (default 5000); charged into the swap fee floor on top of the flat, ppm and claim miner fee | | `BEIGNET_SWAP_CLAIM_BUMP_INTERVAL_BLOCKS` | Blocks an unconfirmed claim waits before it is rebuilt at a higher fee (default 2); inside the claim safety window the claim is bumped every block, up to the whole output above dust | | `BEIGNET_SWAP_SUBMARINE_REFUND_DELTA_BLOCKS` | Blocks from a submarine create to its refund height (default 288, bounds 144 to 432); an invoice whose final CLTV plus a 72 block route budget cannot fit under the refund height minus the margins is refused as `CLTV_UNFITTABLE` | | `BEIGNET_DF_RELAY` | Relay direct-funding frames for OTHER nodes (`true`/`false`, default off). Paying and being paid needs nothing switched on; this is work done for strangers, metered but not free | | `BEIGNET_DF_MIN_AMOUNT` | Smallest direct-funding offer this node serves, a whole number of satoshis. Clamps up to the 5000 sat protocol floor; a partly numeric value refuses startup | ### Experimental Iroh phone link `BEIGNET_IROH=true` enables an additional Iroh listener and outbound dialer. TCP, Tor, Hybrid routing and WebSocket settings continue to apply to other peers. Iroh requires the optional `@number0/iroh` package and Node 20.3 or later. A failed native installation leaves ordinary networking available; enabling Iroh then reports `irohListenError` on `/info`. This is opt-in and is intended for a phone connecting to its owner's primary node. It provides encryption, not anonymity: the peer can see your IP address, and a relay can see endpoint identities, IP addresses, timing and traffic volume. The relay cannot read BOLT 8 plaintext. Keep Tor for peers where you need to hide your IP address. There is no automatic switch of existing peers to Iroh. | Environment variable | Meaning | | --- | --- | | `BEIGNET_IROH` | Exactly `true` enables the experimental transport; unset or `false` leaves it off | | `BEIGNET_IROH_RELAYS` | Comma-separated HTTP(S) relay URLs replacing n0's public defaults; an empty value disables relays | | `BEIGNET_IROH_DISCOVERY` | Exactly `false` disables public endpoint discovery and publication; defaults to `true` when Iroh is enabled | | `BEIGNET_IROH_RELAY_ONLY` | Exactly `true` keeps every Iroh connection on the relay so a peer never learns this node's IP address; unset or `false` allows direct paths | The corresponding config keys are `iroh`, `irohRelays`, `irohDiscovery` and `irohRelayOnly`. Discovery and relay selection are independent. To avoid public discovery and public relays, disable discovery and provide your own relay URLs. With discovery disabled, a dial requires a relay hint, and `/info` waits for a home relay before publishing the URI. No inbound port mapping or router forwarding is required. #### Relay-only By default, anyone who dials the node's Iroh link learns its IP address while the two endpoints look for a direct path, so the link is only safe in the owner's hands. `BEIGNET_IROH_RELAY_ONLY=true` (config key `irohRelayOnly`) keeps every Iroh connection on the relay, inbound and outbound. The node offers no IP address to a peer and takes no direct path, so the link can be given to someone else. What that costs and what it does not cover: - The relay operator still sees the node's IP address, along with endpoint identities, timing and traffic volume. With the default relays that is n0. Set `irohRelays` to a relay you run to keep it to yourself. - Every packet takes the relay. The qualification run in `docs/IROH-RELAY-ONLY-QUALIFICATION-2026-11-11.md` measured a median payment of 171 to 192 ms relay-only against 92 to 108 ms on a direct path, and a phone with a usable channel 1.3 s after its engine restarted against 0.7 s. - It does not take the address back. A peer that connected while relay-only was off keeps the addresses it learned until its own process restarts, and may go on probing them; the node no longer answers there. Switch relay-only on before the link is first handed out. - It needs a relay: an empty `irohRelays` with `irohRelayOnly` refuses startup. `/info` publishes `irohUri` once the node has a home relay. - It covers Iroh. Whoever is given an address to dial sees where the dial comes from, so a relay-only node also dials addresses it merely learned (a channel peer's announced address, a node found through gossip or DNS seeds, a direct-funding lane) through the SOCKS5 proxy (`BEIGNET_TOR_PROXY`) or not at all. Addresses you pass to `peer connect` yourself are dialed as before, and so is an address stored before the mode was switched on. - It dials out over Iroh only through its own relays (`irohRelays`, or n0's). A dial reaches a peer through the peer's relay, that relay sees where the dial comes from, and the peer picks it: as the relay in its link, and as the relay in the record it publishes, which Iroh looks up on every dial while discovery is on and then sends to as well. So with discovery on (the default) a relay-only node makes no Iroh dial at all, and with `irohDiscovery` off it dials only an address whose relay is one of its own. `peer connect` to any other `iroh:` address fails before anything is sent, and says which of the two it was. Peers connecting in are not affected, and the node goes on serving its link. - `announceAddresses` still publishes what you put in it. Startup logs a warning when it holds a clearnet address. `/info` reports `irohRelayOnly: true` and, while the endpoint is bound, `irohRelayOnlyMode`: | Mode | Meaning | | --- | --- | | `native` | The Iroh binding removed the endpoint's IP transport. It has no socket to send from, asks the router for nothing and discovers no address. | | `loopback-pin` | The binding cannot remove the IP transport (`@number0/iroh` up to 1.2.0), so its UDP sockets are bound to loopback. No direct path can form, but Iroh still asks the router for a port mapping. | `loopback-pin` is best effort. Where the router answers UPnP, NAT-PMP or PCP, Iroh adds the mapped public address to the endpoint's own address list. The node watches that list for as long as the endpoint lives, and for the first twelve seconds the endpoint stays silent: it accepts no connection, makes none, and `/info` carries no `irohUri`. Startup is not held up by the watch, but a peer waits for it: the same qualification measured 17 to 20 s from a node restart to a usable channel, against about 2 s with relay-only off. When a routable address appears the node closes the endpoint and does not bind another: `/info` carries `irohListenError` with `errno: "IROH_RELAY_ONLY_VIOLATED"`, and `node:error` is raised with that code (`LISTEN_FAILED` instead when the address is already there as the endpoint binds). The message counts the addresses and never prints them. So on a home network with port mapping switched on, `loopback-pin` refuses to run. Turn port mapping off on the router, or run the node on a bridged container network (Umbrel's default), where no router answers. A mapping first granted while peers are connected can reach them in the moment before the endpoint closes. The pin needs the host's IPv6 loopback address as well as the IPv4 one. On Linux with IPv6 switched off by sysctl (`net.ipv6.conf.all.disable_ipv6=1`) there is no `::1`, while Iroh can still open an IPv6 socket, on every address. The node does not serve Iroh over such a socket: it refuses the bind, and `irohListenError` says why. Switching IPv6 back on for the loopback interface alone (`net.ipv6.conf.lo.disable_ipv6=0`) is enough, and the other interfaces can stay as they are. Iroh's discovery is not a second way out. With the default preset the endpoint publishes a signed record to n0's DNS server so that others can find it by its id, and the node does not hold that back during the watch. Iroh publishes relay addresses only: it drops every IP address before it signs the record (the publisher's default, `AddrFilter::relay_only`, in the Iroh that the bindings up to 1.2.0 are built on). Read back from n0's server on a home network with port mapping, the record of an endpoint that held a routable address carried its relay URL and nothing else. `scripts/regtest-live/iroh-qualification/discovery-record.cjs` repeats the check. `GET /info` includes `irohAvailable: true` for engines with this integration, plus `irohUri` while an Iroh connection string is available. The URI has the form: ```text @iroh:?relay= ``` The endpoint id is 32 bytes in hexadecimal; the parser also accepts Iroh's unpadded base32 form. The relay hint is optional when discovery is enabled. The endpoint key is HKDF-SHA256 of the BIP39 seed, with a 32-byte zero salt and UTF-8 info `beignet/iroh/identity/v1`, producing 32 bytes. It is independent of the Lightning private key and survives a mnemonic restore, including the same BIP39 passphrase. The connection still authenticates the Lightning pubkey with BOLT 8 inside the QUIC stream. ```sh BEIGNET_IROH=true beignet start beignet peer connect '@iroh:' ``` The API accepts the same address as structured fields: ```json { "pubkey": "", "transport": "iroh", "endpointId": "", "relayUrl": "https://relay.example/" } ``` Post this to `/peer/connect`. Omit `host` and `port`, or use the endpoint id as `host` and `0` as `port`. An optional `fallbackOnion: { "host": ".onion", "port": 9735 }` identifies an onion address for the same Lightning pubkey. The dial starts Iroh first and starts the configured SOCKS5/Tor connection after 1.5 seconds, or immediately if Iroh fails. It runs BOLT 8 only on the first socket to connect and closes a late losing socket. A connected socket that subsequently fails authentication does not trigger the other transport. `GET /peers` includes `transport: "iroh"` and `iroh: { endpointId, path, rttMs }`. `path` is `direct`, `relay` or `unknown`; RTT is omitted until available. Tor fallback reports `transport: "tcp"`. The saved preferred address remains Iroh, including its optional onion fallback, so reconnects try Iroh first again. Iroh addresses are retained in channel backups and never published in gossip. Backup address strings carry the endpoint and relay; reconfigure the optional onion fallback after restoring a backup. The adapter and Node integration have local QUIC, handshake, channel payment, reconnect, storage, configuration and API tests. Funding in the local channel test is simulated. Live relay-only payments, the mid-payment network-cut sweep, long outage timing, and real Umbrel and phone lifecycle tests remain release validation work. Umbrel's per-wallet switch and Connect card, and Chicory's native mobile bridge and primary settings, are separate companion changes. ### Porch links A Porch link is a peer URI that reaches the node without saying where it runs: ```text @wss:///v1/p/ ``` The node dials out to one or more Porch relays and waits there. Whoever holds the link connects to the relay, the relay pairs the two connections, and BOLT 8 runs end to end through it. The dialer needs nothing new: the link is an ordinary `wss://` peer address, so `beignet peer connect ''` and `primaries add --uri ''` take it as they take any other. No inbound port, port forwarding or public address is needed at home. Run a relay with [`beignet porch-relay`](#porch-relay), or use one somebody else runs. | Environment variable | Config key | Meaning | | --- | --- | --- | | `BEIGNET_PORCH_RELAYS` | `porchRelays` | Comma-separated relay URLs (`wss://host[:port]`, or `ws://` for an onion service). Empty or unset leaves Porch off. In the config file an entry can also be `{ "url": "...", "token": "..." }` | | `BEIGNET_PORCH_VIA` | `porchVia` | `tor` dials every relay through the SOCKS5 proxy (`torProxy`, else `127.0.0.1:9050`), with the relay's name unresolved and no direct dial to fall back to. `direct` dials them directly whatever `torProxy` says. Unset dials a relay as any other peer at that host | | `BEIGNET_PORCH_PROXY` | `porchProxy` | A SOCKS5 proxy for the relay connections alone, as `host:port`. Every relay is dialed through it, with the relay's name unresolved and no direct dial to fall back to, while peers go on being dialed as `torProxy` says. Any SOCKS5 proxy that asks for no credentials will do, Tor or not. Refused together with `porchVia: direct`, and for a relay at a private address | | `BEIGNET_PORCH_STANDBYS` | `porchStandbys` | Idle connections kept at each relay (default 2, at most 8). Each takes one visitor and is replaced at once | | `BEIGNET_PORCH_TOKEN` | `porchToken` | The token of a private relay, when exactly one relay is configured. With several relays this is refused, because a token sent to each would be disclosed to the others: give each its own in a `{ url, token }` entry | Who learns what: - **Whoever holds a link** learns the relay's name and the node's Lightning pubkey, which the link states. Not the node's address. - **The relay** sees the node's address, each visitor's address, when they connect and how much they send. It cannot read or change the traffic. It is not told the Lightning pubkey, though it can test a guess by dialing the link itself. `GET /info` reports `proxied: false` for such a relay. With `porchVia: tor` (`proxied: true`) the relay does not see the node's address either, at the cost of Tor's latency on every message. `porchProxy` does the same through a proxy of your choosing, which then sees the address in the relay's place. - A visitor whose peer dials go through a proxy (`torProxy`) reaches the relay through it, so the relay does not see the visitor's address either. With both ends proxied it sees neither. - A relay you run yourself is one whose operator is you. With Porch on, the node stops dialing addresses a peer chose: an address learned from a peer's `node_announcement` is dialed only through the SOCKS5 proxy, because a direct dial to it would show the peer where the node is. A clearnet address in `announceAddresses` still publishes itself to the whole network, and startup logs a warning when one is set. `GET /info` carries `porchAvailable: true` on engines with this integration and, once relays are configured, a `porch` block: ```json { "porch": { "uris": ["02ab...@wss://relay.example/v1/p/k3v..."], "links": 1, "relays": [ { "relay": "wss://relay.example", "state": "ready", "idle": 2, "circuits": 0, "proxied": false } ] } } ``` `uris` is the seed's link, one URI per relay; any of them reaches the node. A relay's `state` is `ready` (links through it work), `connecting`, `unreachable` (retried with backoff, with the reason in `lastError`), `refused` (the relay turned the node down: a wrong token, too many links), `no-links` (every link is revoked, so the node stays away) or `stopped`. A relay that is away is status, not a failed listener: the node keeps dialing and the same link works again when the relay is back. `porchListenError` appears only when the node is not waiting at all, held by a guardian recovery mode's startup quarantine or fenced, as `listenError` does for the TCP listener. **Links.** Every node has one link from its seed, so it is the same after a restore. `POST /porch/links/create` (`beignet porch links create`) makes another with a random id and an optional label, up to 256, so each person or device can have its own. `POST /porch/links/revoke` takes one back: it stops resolving at the relays and every peer connected through it is disconnected, channel peers included. Their channels stay open, and they reconnect once they are given a link that works. Revoking is permanent and is written to the database before it takes effect. The seed's link can be revoked as well and stays revoked on that database, including across a capsule restore, which carries the record over. Two cases bring a revoked link back, because the record of the revocation is not there: a restore from the seed alone (the seed's link returns and the made links are gone), and a database restored from a backup taken before the revocation. `GET /peers` lists a peer that came in through a link with `host: "porch:"`, `transport: "ws"` and `porch: { relay, link }`, where `link` is the id of the link it used. The node never learns such a peer's address. All visitors through one relay share the per-address admission limits (4 handshakes in progress, 8 peers without a channel); a peer with a channel is admitted past the second. Which setup to choose and what each one measured is in [docs/PORCH.md](../../docs/PORCH.md). The protocol and every limit are in [docs/PORCH-PROTOCOL.md](../../docs/PORCH-PROTOCOL.md). ### Tor proxy `BEIGNET_TOR_PROXY` (`--tor-proxy`, config key `torProxy`) sets the SOCKS5 proxy for outbound peer and watchtower connections. On its own it proxies every public host, which hides the node's clearnet address from its peers at the cost of Tor's latency on every dial. `BEIGNET_TOR_PROXY_ONION_ONLY=true` (`--tor-proxy-onion-only`, config key `torProxyOnionOnly`) keeps the proxy for `.onion` hosts only, so a node can reach onion peers through a Tor that lives elsewhere (a separate container, say) while dialing clearnet peers directly. It needs `BEIGNET_TOR_PROXY`: set alone it has nothing to act on and startup is refused. Private and loopback hosts are dialed directly in every case, because Tor refuses them. | Destination | proxy alone | proxy plus onion-only | |---|---|---| | `.onion` | proxy | proxy | | private or loopback | direct | direct | | public clearnet | proxy | direct | A WebSocket peer (`ws://` or `wss://`, a Porch link included) is routed by the same table, on the host in its URL. Through the proxy the name is sent to the proxy unresolved, TLS runs inside the tunnel, and a proxy that is down fails the dial: there is no direct dial behind it. Guardian sessions over bolt8 already dial only onion hosts through the proxy. ### Priority Order CLI flags > environment variables > config file > defaults. ### Default Electrum Servers | Network | Host | Port | TLS | |---------|------|------|-----| | mainnet | `bitkit.to` | 9999 | yes | | testnet | `electrum.blockstream.info` | 60002 | yes | | regtest | `electrs.bitkit.stag0.blocktank.to` | 9999 | yes | The mainnet and regtest defaults are the servers the Bitkit app uses. > The regtest default is a hosted Synonym regtest Electrum server. For local > development against your own regtest node, override it with > `BEIGNET_ELECTRUM_HOST`/`BEIGNET_ELECTRUM_PORT` or the `electrumHost`/ > `electrumPort` options. **Certificate verification.** A TLS Electrum connection is encrypted, but by default it accepts any certificate, so an on-path attacker can stand in for the server. With `BEIGNET_ELECTRUM_TLS_VERIFY=true` (`electrumTlsVerify`) the daemon accepts only a certificate that chains to a trusted CA and matches the host name, or one whose SHA-256 fingerprint is listed in `BEIGNET_ELECTRUM_TLS_FINGERPRINTS` (`electrumTlsFingerprints`, from `openssl x509 -noout -fingerprint -sha256`). The check covers the public fallback servers too, and a host the daemon pins to IPv4 before dialing is still checked against the name you configured. Fingerprints without verification refuse startup rather than being ignored. With `BEIGNET_ELECTRUM_TLS=false` the configured server is plain TCP and is never checked, so only the TLS fallback servers are verified; the daemon starts anyway and logs a warning saying so. Nodes created in one process (`BeignetNode.create`) share a single Electrum connection per network, so they must use the same `electrumTlsVerify` and `electrumTlsFingerprints`. A node whose settings differ from those of a node already running on the same network is refused with `INVALID_PARAMS`. The mainnet and regtest defaults pass with no pin: each serves a certificate a public authority signed for its name. Of the mainnet fallback peers, as of October 2026 only `bitkit.to` passes; `bitcoin.lu.ke` and `kirsche.emzy.de` serve self-signed certificates and `electrum.aantonop.com` does not answer. So with verification on, an outage of `bitkit.to` leaves the daemon without Electrum until a server it can verify answers. Run your own server as well if that matters. --- ## HTTP API The daemon exposes these endpoints on `127.0.0.1:2112` (configurable via `daemonHost`/`daemonPort`). All POST endpoints accept JSON bodies. HTTPS is supported when started with `--tls-cert` and `--tls-key`. A malformed request (an unparseable request target, or a `Host` header that is not a valid host) answers `400 INVALID_PARAMS` and never terminates the process; `beignet start` also logs any unhandled rejection or uncaught exception with its stack and keeps running. These endpoints support the `X-Idempotency-Key` header (24h cache): `/invoice/pay`, `/invoice/pay-safe`, `/invoice/pay-async`, `/invoice/pay-retry`, `/keysend`, `/keysend/safe`, `/l402/fetch`, `/rebalance`, `/advisor/execute-rebalances`, `/direct-funding/send`, `/send`, `/send-max`, `/offer/pay`, `/channel/asset-splice`, `/channel/splice-out`, `/channel-send/execute`, `/channel/open`, `/channel/open-v2`, `/channel/open-zeroconf`, `/channel/connect-and-open`. A repeat with the same key and body returns the cached response; the same key with a different body returns `409 IDEMPOTENCY_CONFLICT`. A thrown error is not cached, so a keyed retry after one runs again, with one exception: a keyed `/offer/pay` or `/keysend` that answered `PAYMENT_TIMEOUT` is remembered by its payment hash, because a rerun would pay under a fresh hash (a new invoice, a new preimage) and could pay twice (issues #1094, #1133). A retry of it answers `200` with the payment once it completed, `409 DUPLICATE_PAYMENT` carrying `paymentHash` while an HTLC for it can still settle, and runs again only once nothing sent for it can. Any other `POST` that carries the header answers `400 INVALID_PARAMS` without running. The cache is in memory, so it does not survive a daemon restart, except for these payment hashes: a keyed `/offer/pay` or `/keysend` stores its hash before the HTLC goes out and keeps it after a `PAYMENT_TIMEOUT`, so a retry after a restart or a crash is answered the same way (issues #1132, #1153). A hash that cannot be stored refuses the payment with `503 NOT_PERSISTED`, and nothing is sent. ### Authentication Two kinds of credentials, usable together: - **Legacy single token** -- `apiToken` (via `--api-token`, `BEIGNET_API_TOKEN`, or config file). Backward compatible: it keeps working and carries an implicit `admin` scope. - **Named scoped keys** -- the `apiKeys` config array (or `BEIGNET_API_KEYS` env var as JSON): `[{ "name": "monitor", "key": "", "scopes": ["readonly"], "expiresAt": "2027-01-01T00:00:00Z" }, ...]`. A key may hold multiple scopes; `expiresAt` is optional. When any credential is configured, all endpoints require an `Authorization: Bearer ` header. Exceptions (always accessible): - `GET /health`, `GET /ready` -- monitoring tools - `GET /openapi.json` -- API discovery - `GET /metrics` -- Prometheus scrapers, only with `metricsPublic` (it reports balances) These still count against the rate limiter when `rateLimit` is configured. A daemon bound beyond loopback refuses to start when the `apiToken` or any `apiKeys` secret is shorter than 16 characters, unless `insecure` is set: there the credential is the only lock, and the rate limiter is off unless configured. Prefer `BEIGNET_API_TOKEN` or the config file to `--api-token`, whose value any local user can read from the process list. The rate limiter is the `rateLimit` config file key: `{ "maxRequests": 100, "windowMs": 60000, "trustedProxies": [] }`, every field optional, so `{}` turns it on with those defaults. A client past its bucket gets `429 RATE_LIMITED`. Buckets are keyed on the peer address, and `X-Forwarded-For` is read only when the peer is listed in `trustedProxies`; without that, every client behind a proxy shares the proxy's bucket. A `maxRequests`, `windowMs` or `maxClients` that is not a positive integer refuses startup. Whether or not it is on, the server holds at most 256 connections at once (SSE streams and waits included) and closes any more as they arrive. A client has 30 seconds to send its headers and 120 seconds for the whole request, and an idle keep-alive connection is closed after 5 seconds. Every install `beignet init` creates carries an `apiToken` (see [Setup](#setup)). If neither `apiToken` nor `apiKeys` is configured (a config written by hand or by a release before 0.22.0's successor), all endpoints are open to local processes, `GET /mnemonic` excepted (it needs auth, and `admin`), the daemon logs a warning at boot, and three browser guards keep a web page from driving it (issue #1005): | Guard | Refusal | |-------|---------| | A request with a body must carry `Content-Type: application/json` (media type parameters such as `; charset=utf-8` are fine, case does not matter). A body with no Content-Type is refused too: `fetch()` in `no-cors` mode sends `text/plain` or nothing, with no preflight. | `415 UNSUPPORTED_MEDIA_TYPE` | | An `Origin` header must equal the configured `cors` origin string; with `cors` off, any `Origin` is refused, `null` included. Without an `Origin`, a `Sec-Fetch-Site: cross-site` request is refused (`same-origin`, `same-site` and `none` pass). With wildcard CORS (an `insecure` opt-in), any origin passes. | `403 CROSS_SITE_REQUEST_REFUSED` | | The `Host` header must name the loopback address the daemon is bound on: `localhost`, `127.0.0.0/8` or `[::1]`, with or without a port, or the configured `daemonHost` when it is a concrete address. A missing `Host` (HTTP/1.0) passes only on a loopback bind. This defeats DNS rebinding, where a page reads answers through a name that resolves to 127.0.0.1. Skipped for a wildcard bind (`0.0.0.0`, `::`, only possible under `insecure`). | `421 HOST_NOT_ALLOWED` | The guards run ahead of the rate limiter and the auth middleware and apply to every route, the auth-exempt ones and the SSE stream included; only `OPTIONS` (204) is exempt. Plain clients (curl, the CLI, the SDKs) send none of those headers, so they are unaffected; a reverse proxy in front of an unauthenticated daemon must forward a loopback `Host` (or the daemon needs a credential, which is the better fix). With a credential configured the guards do not run at all: a browser cannot attach a bearer token cross-site, and non-browser clients keep sending whatever Content-Type they like. **Scopes:** | Scope | Grants | |-------|--------| | `readonly` | Every GET route (except `GET /mnemonic` and `GET /webhooks`) plus POSTs that are pure queries: estimate/validate/decode/verify and the wait endpoints. | | `invoice` | Receive-side routes: creating invoices/offers/hold invoices, settling/cancelling holds, `POST /address/new`, invoice/offer lookups and decoding, `GET /can-receive`, `POST /payment/wait`, and the `GET /events` SSE stream. | | `admin` | Everything, including paying/spending, channel and peer management, PSBTs, backups, webhooks management, `POST /stop`, and API key management. | Every route declares its scopes in `src/cli/routes.ts` (`ROUTES`, read into `ROUTE_SCOPES`), where the field is required, and a route not in that table fails closed (admin-only). Notable classifications: all webhook routes including `GET /webhooks` are admin-only (callback URLs can embed credentials; management is one unit); `POST /message/sign` is admin-only because it signs with the node identity key; `GET /events` (SSE) accepts `readonly` and `invoice`. Key comparison is constant-time (SHA-256 digests compared with `crypto.timingSafeEqual`), for the legacy token too. Failures return **401** `UNAUTHORIZED` for a bad or missing key and **403** `FORBIDDEN` for a valid key without a required scope. **Expiry:** a named key may declare `expiresAt` (ISO 8601, e.g. `"2027-01-01T00:00:00Z"`). From that moment the key fails authentication exactly like an unknown key (401); the check happens on every request, so no restart is needed. An unparseable `expiresAt` is rejected at daemon startup (`INVALID_PARAMS`). `GET /auth/keys` reports `expiresAt` and a computed `expired` boolean per key. **Rotation:** `POST /auth/keys/rotate {"name": "..."}` (`beignet auth rotate `, admin scope) mints a cryptographically random 32-byte hex secret for an existing named key. The old secret stops authenticating immediately; scopes and expiry are unchanged. The new secret appears ONCE in the response -- only its SHA-256 digest is stored, so it cannot be retrieved again; if it is lost, rotate again. Rotating a revoked key reinstates it under the new secret (the old, possibly compromised secret stays dead). **Persistence:** rotation and revocation are written to the node database (the encrypted `wallet_data` table -- digests only, never plaintext secrets) and are re-applied over the config-declared keys on every start. This fixes the earlier limitation where revocation was in-memory only and a daemon restart resurrected a revoked key. The config file remains the source of truth for the key *set*: overrides apply by name, an override whose name left the config is pruned, and editing a key's secret in the config discards any stored rotation/revocation for that name (an explicit config re-key wins). Removing a key from the config file remains the ultimate cleanup. **Legacy token caveats:** the single `apiToken` has no name, so it can be neither rotated nor expired nor revoked at runtime -- its behavior is unchanged. To retire it, change or remove it in the config and restart. Prefer named `apiKeys` for anything that needs lifecycle management. ### Endpoints The matching commands are `wallet sweep-prepare `, `wallet sweep-submit `, `wallet sweep-cancel ` and `wallet sweep-get `. Preparation and submission are separate: preparation persists the exact signed transaction, and submission never selects coins again. Cancellation remains `cancelling` if reservation cleanup is interrupted; repeat it to finish. Submitted inputs retain their reservations after confirmation to prevent another send after a reorg. Generic UTXO freeze and unfreeze cannot take over these inputs. Database replacement carries the journal and its reservations together, and refuses an unresolved sweep. | Method | Path | Parameters | Description | |--------|------|------------|-------------| | GET | `/info` | -- | Node info | | GET | `/mnemonic` | -- | Show mnemonic (requires apiToken) | | GET | `/balance` | -- | Balances | | GET | `/health` | -- | Health status (auth-exempt) | | GET | `/openapi.json` | -- | OpenAPI 3.0 spec (auth-exempt) | | GET | `/stats` | `?window=` | Node statistics (optional time window in ms) | | GET | `/peers` | -- | List peers | | GET | `/channels` | -- | List channels | | GET | `/channels/ready` | -- | List channels that are NORMAL and will accept a new HTLC (a capsule-restored channel holding for recency is excluded) | | GET | `/can-send` | `?amountSats=` | Check send capacity | | GET | `/can-receive` | `?amountSats=` | Check receive capacity | | GET | `/payments` | `?status=&direction=&since=&limit=&offset=` | List payments (filterable), newest first. One page per call: `limit` defaults to and may not exceed 1000, so page with `offset`. Read through to the node database, so a completed or failed payment stays listed after the engine prunes its in-memory record (24 hours after completion); a database read that fails answers 500, never a shorter list. A PENDING row with `unresolved: { code: 'CHANNEL_OMITTED_AT_RESTORE', channelIds }` is a payment that had an HTLC on an asset channel a capsule restore left out: the wallet cannot learn whether it was paid, never reports it paid or failed, and does not send it again | | GET | `/forwards` | `?since=&until=&limit=&offset=&channelId=` | Settled forwards with fees earned (msat values as strings); a forward with an asset leg is marked `auxiliary` | | GET | `/forwards/summary` | `?since=` | Forwarding totals over ordinary forwards: `{ count, volumeOutMsat, feesEarnedMsat }`, with `auxiliary` (the same totals over forwards with an asset leg) when there is one | | GET | `/invoices` | -- | List created invoices. `status` is `PAID` on a completed receive, from the in-memory record or the database row once the engine has pruned it, so a paid invoice never reads `EXPIRED` or `PENDING` later. An invoice that is not `PAID` carries the `unresolved` of its payment record when an HTLC of it was on an asset channel a capsule restore left out | | GET | `/channel` | `?channelId=` | Get channel (query param or body) | | GET | `/channel/health` | `?channelId=` | Channel health assessment with liquidity warnings | | GET | `/payment` | `?paymentHash=` | Get payment (query param or body): the in-memory record, else its database row, so a payment is found however long ago it completed | | GET | `/trusted-peers` | -- | List trusted peers | | GET | `/offers` | -- | List BOLT 12 offers | | GET | `/events` | -- | SSE event stream (auth-gated) | | POST | `/address/new` | -- | New address | | POST | `/wallet/refresh` | -- | Sync wallet | | POST | `/send` | `{ address, amountSats, satsPerVbyte? }` | Send on-chain (optional fee rate). Counts amount + fee against the combined daily spend limit | | POST | `/send-max` | `{ address, satsPerVbyte? }` | Sweep the whole on-chain balance to one address. The computed sweep total is checked against the combined daily spend limit before broadcast | | POST | `/onchain/sweep/prepare` | `{ requestId, address, satsPerVbyte, inputOutpoints: [{txid, vout}], debitSats, maxFeeSats }` | Reserve the reviewed wallet-owned inputs and persist one signed sweep without broadcasting. Reject foreign, frozen or pledged inputs and a changed debit or excessive fee | | POST | `/onchain/sweep/submit` | `{ requestId }` | Submit or rebroadcast the same saved transaction. First submission records the spend exactly once before broadcast | | POST | `/onchain/sweep/cancel` | `{ requestId }` | Cancel only before any broadcast attempt, releasing only this request's reservations | | GET | `/onchain/sweep` | `?requestId=` | Read durable sweep status without signed hex. A lost response is resolved by querying or submitting this same ID | | POST | `/tx/bump-fee` | `{ txid, satsPerVbyte }` | RBF an unconfirmed tx at a higher fee (NOT_BOOSTABLE if RBF unavailable) | | POST | `/tx/boost` | `{ txid, satsPerVbyte? }` | Fee-bump a tx: RBF when possible, else CPFP | | GET | `/transactions/boostable` | -- | Unconfirmed txs eligible for RBF/CPFP, by method | | POST | `/consolidate` | `{ satsPerVbyte? }` | Merge all UTXOs into one output at a fresh wallet address | | POST | `/psbt/build` | `{ outputs, satsPerVbyte? }` | Build an UNSIGNED PSBT for an external signer | | POST | `/psbt/import-signed` | `{ psbtBase64, unsignedPsbtBase64? }` | Validate + finalize a signed PSBT this node built, or one matching `unsignedPsbtBase64` (no broadcast) | | POST | `/psbt/combine` | `{ psbts }` | Combine partially signed PSBT copies | | POST | `/utxo/freeze` | `{ txid, index }` | Freeze a UTXO: excluded from all coin selection until unfrozen | | POST | `/utxo/unfreeze` | `{ txid, index }` | Unfreeze a previously frozen UTXO | | POST | `/address/label` | `{ address, label }` | Set a user label for an address (empty label clears it) | | GET | `/address/labels` | -- | All user address labels keyed by address | | GET | `/wallet/descriptors` | -- | BIP 380 output descriptors (checksummed, public keys only) | | POST | `/peer/connect` | `{ pubkey, host, port }` | Connect peer | | POST | `/peer/disconnect` | `{ pubkey }` | Disconnect peer | | POST | `/peers/bootstrap` | -- | Discover peers via DNS | | POST | `/peers/connect-seeds` | `{ maxPeers? }` | Connect to seed peers | | POST | `/trusted-peer/add` | `{ pubkey }` | Trust peer for zero-conf | | POST | `/trusted-peer/remove` | `{ pubkey }` | Remove trusted peer | | POST | `/channel/open` | `{ pubkey, amountSats, pushSats? }` | Open channel | | POST | `/channel/open-zeroconf` | `{ pubkey, amountSats, pushSats? }` | Open zero-conf channel | | POST | `/channel/open-v2` | `{ pubkey, amountSats, fundingFeeratePerkw?, finalTaproot?, dualFundedAssets?, ... }` | Open a v2 channel. Enrolled regtest wallets can request private final type 80. | | POST | `/channels/ensure-minimum` | `{ count, satsPerChannel, timeoutMs? }` | Auto-open channels to meet minimum count | | POST | `/channel/connect-and-open` | `{ pubkey, host, port, amountSats, pushSats? }` | Connect + open in one call | | POST | `/channel/open-and-wait` | `{ pubkey, amountSats, pushSats?, timeoutMs? }` | Open channel + wait for NORMAL state | | POST | `/channel/close` | `{ channelId, acceptStaleStateRisk? }` | Coop close; the payout goes to the wallet's change chain, never a handed-out receive address. The flag is required for a capsule-restored channel | | POST | `/channel/forceclose` | `{ channelId, acceptStaleStateRisk? }` | Force close; the sweep pays the wallet's change chain, never a handed-out receive address. The flag is required for a capsule-restored channel | | POST | `/channel/rebroadcast-close` | `{ channelId }` | Rebroadcast the recorded close tx of a force-closed channel (or an unconfirmed mutual close); idempotent, always rebuilds from the latest state | | POST | `/channel/asset-splice` | `{ channelId, fundingFeeratePerkw, minimumDepth }` | Start a private regtest asset splice. Watch `splice:complete` for adoption | | POST | `/channel/splice-in` | `{ channelId, amountSats, feeratePerkw }` | Splice-in funds. A 2xx means the splice started; a refusal is a failure envelope (404 `CHANNEL_NOT_FOUND`, 409 `SPLICING_NOT_NEGOTIATED` / `FUNDING_PROVIDER_REQUIRED` / `SPLICE_REFUSED`, 503 `SPLICE_BUSY`, 400 `INVALID_PARAMS`) | | POST | `/channel/splice-out` | `{ channelId, amountSats, feeratePerkw, address? }` | Splice-out funds, optionally to an external address. Same refusal codes, plus 409 `INSUFFICIENT_BALANCE` | | POST | `/channel-send/quote` | `{ address, amountSats, feeratePerkw }` | Quote paying an address out of one channel or several in one transaction (issue #1922). 403 `SPENDING_LIMIT_EXCEEDED`, 409 `INSUFFICIENT_BALANCE` or `SPLICE_REFUSED` (with each channel's reason), 503 `SPLICE_BUSY` or `NOT_PERSISTED` | | POST | `/channel-send/execute` | `{ quoteId }` | Run a channel send quote; idempotent on the quote id. 404 `NOT_FOUND` for an unknown or consumed quote, 400 for an expired one | | GET | `/channel-send/status` | `?id=` | Stage and record of a channel send (quote id or composite id) | | GET | `/channel-send/list` | | Every channel send this node holds | | POST | `/channel-send/abort` | `{ id, reason? }` | Abort a composite before release. 409 `SPLICE_REFUSED` past RELEASED or for a single-channel send | | POST | `/invoice/create` | `{ amountSats?, description?, minFinalCltvExpiry? }` | Create invoice (omit amountSats for amount-less; `minFinalCltvExpiry` buys final-CLTV headroom for a receive an LSP may settle through a splice) | | POST | `/jit/invoice` | `{ lspPubkey?, amountSats?, description?, expirySecs?, targetRemainingInboundSat?, maxFlatFeeSat?, maxFeePpm? }` | Create an invoice payable with no channel: registers a receive intent with the LSP, which funds a channel mid-payment and deducts the quoted opening fee. Returns the invoice plus `lspPubkey`, `flatFeeSat` and `feePpm`. No `lspPubkey`: steered through `/primaries` in `selectionOrder`, with the passed-over ones in `skipped` (503 `NO_PRIMARY_AVAILABLE` when none takes it) | | GET | `/jit/status` | -- | The JIT receive role as it stands: `enabled`, the client ceilings, and (when on) `lsp` with the opening fee, the exposure caps, sats reserved and fronted, live intents, held HTLCs and fundings in flight. Readonly scope | | GET | `/jit/quote` | `?lspPubkey=&amountSats=&targetRemainingInboundSat=` | Price a JIT receive at that LSP without registering an intent: `accepted`, a plain-language `reason` when declined, `flatFeeSat`, `feePpm`, `feeSats` on this amount, `fundingSats` the LSP would front, `maxClientFundingSats`, and `withinCeilings` against this node's own limits. The LSP must be connected (409 `PEER_NOT_CONNECTED`, 504 `JIT_TIMEOUT`). No `lspPubkey`: priced at the first ranked primary that would serve it, named in `lspPubkey`, the others in `skipped`. Readonly scope | | GET | `/swaps/status` | -- | Swap provider (issues #737 and #743): `enabled`, and when on the fee terms, exposure caps, timing, reverse swaps per state and `exposedSat` at risk on chain; `submarine` reports the on-chain to Lightning direction the same way (`enabled: false` when it is off). Readonly scope | | GET | `/swaps` | `?id=` | The swap ledger (or one swap) in both directions (`direction` is `reverse` or `submarine`): state, contract terms, funding, payment, claim, refund and resolution facts; amounts as decimal strings, no private key. Readonly scope | | POST | `/swaps/cancel` | `{ id }` | Cancel a swap before any funds moved: a reverse swap in CREATED or HELD (closes its hold invoice), a submarine swap before PAYING (the peer refunds its own coins at the refund height). Also ends a stranded reverse swap: EXPOSED, with `strandedHeight` set because this process found its funding absent past the refund height; the operator vouches the funding will not confirm, and spending its inputs makes sure. Answers `{ id, cancelled: true }`; past that a swap resolves on chain by claim or refund (409 `SWAP_NOT_CANCELLABLE`). Admin scope | | POST | `/direct-funding/configure` | `{ lspPubkey?, lspHost?, lspPort?, targetInboundSat?, trusted?, allowSplice?, allowUnpairedSplice?, unpairedSpliceDepth?, minAmountSat? }` | Set the direct-funding policy. A partial MERGE, never a replace: a field the body does not name keeps its value. `trusted` lets an open go zero-conf; `allowSplice` lets a paired payer grow the existing channel with the liquidity peer instead of opening a second one; `allowUnpairedSplice` lets an anonymous payer do the same when its coin is confirmed, with a splice that locks at `unpairedSpliceDepth` confirmations (1..2016, default 3) rather than at broadcast, whatever the channel type (an anonymous payer with an unconfirmed coin still gets a new confirmed channel). While a splice with the liquidity peer is still confirming, every further offer is declined before the payer's witness leaves, so the payer falls back to a plain send. The three switches must be booleans (400 `INVALID_PARAMS` otherwise). `minAmountSat` clamps up to the 5000 sat floor and the response reports the clamped value. Returns the full effective config | | GET | `/direct-funding/config` | -- | Read the effective policy, `allowUnpairedSplice` and `unpairedSpliceDepth` included; `lspPubkey` is null when no liquidity peer is set, in which case a request that bound no peer of its own is not served | | GET | `/direct-funding/received` | -- | The payments received against our requests, newest first: `receiptHash` (the request's `paymentHash`), `requestId`, `offerId`, `fundingTxid`, `channelId`, `splice`, `amountSat`, `status` (`PAID`, or `REVERTED` when the splice it went into was undone), `paidAt`, and `lockedAt` once this node saw the funding lock (channel_ready for an open, splice_locked for a splice, both sent and received; issue #1899). `lockedAt` stays after the channel closes; for a lock from before this version it is the first start that recorded it, and on a zero-conf channel it comes before the funding confirms. A direct-funding payment settles no invoice and pays no address, so this is how a client tells its request was paid. Kept 30 days from the payment (or its lock or revert), at most 512, outliving the request itself. Readonly scope | | POST | `/direct-funding/request` | `{ host?, port?, amountSats?, lspPubkey?, expirySecs? }` | Mint a payment request: returns `{ paymentHash, expiresAt, request, lspPubkey, skipped? }`, where `request` is the base64url envelope a payer pays (BIP 21 parameter `bgnq`). `host`/`port` are the address a payer can reach this node on and are used exactly as given. `lspPubkey` binds the request to that peer (issue #1922), which must be a configured primary or the policy's liquidity peer (400 `INVALID_PARAMS` otherwise: this route runs at invoice scope, and that peer holds every payment the channel receives): its relay descriptors name it and the receiver negotiates the funding with it when the offer arrives, whatever the policy says by then. Omitted, the ranked primaries choose when any are configured: the first in `selectionOrder` with a known address (stored with the primary, or the TCP address this node dialed it at) is bound, the others are listed in `skipped`, and 503 `NO_PRIMARY_AVAILABLE` answers when none has one. Nothing is dialed. With no primaries the policy's liquidity peer serves, as before. `expirySecs` sets how long the request stays payable, in whole seconds up to 604800 (seven days), else 400 `INVALID_PARAMS`; omitted, a request lives for an hour. Invoice scope | | POST | `/direct-funding/prepare` | `{ request }` | Decode a request and start connecting to the node a send would talk to first, without waiting for the dial. Returns `{ requestId, receiverNodeId, amountSat, expiresAt, connection, peerNodeId? }`, where `connection` is `connected`, `connecting`, `awaiting_receiver` or `none`. Spends nothing and writes no payment record; a later `send` joins a dial still in progress. Admin scope | | POST | `/direct-funding/send` | `{ request, amountSats?, maxTotalFeeSat?, recoverReceipt? }` | Pay a request from one of our coins. Set `recoverReceipt` to ask the receiver to replay a receipt that never arrived (issue #767): it acts only on a post-witness payment with no receipt yet, re-sends the recorded offer with no second coin, signature or freeze, and returns the recorded outcome plus a `caveat` if the receiver cannot be reached. **Rejects only before our witness leaves the device**; after that it resolves with what is known plus a `caveat`, because a client that falls back to a plain on-chain send on any error cannot tell a late rejection from an early one and would pay twice. Idempotent on the request id, sets no deadline of its own, and accepts `feeHeadroomSats` as an alias for `maxTotalFeeSat`. The money leaves for a stranger's channel, so amount + fee ceiling counts against the combined daily spend limit, and a draining node refuses it (both before the exchange opens, and neither for a request that already has an attempt: a duplicate call spends nothing new, and refusing one would be read as "nothing happened") | | GET | `/primaries` | -- | The ranked receive primaries with their balances and the current receive target, as `listPrimaries` returns them. Readonly scope | | POST | `/primaries/add` | `{ pubkey, host?, port?, uri?, rank? }` | Add a primary (400 `INVALID_PARAMS` on a malformed pubkey, a duplicate, a bad port or rank). Returns the whole list. Admin scope | | POST | `/primaries/remove` | `{ pubkey }` | Drop a primary. Returns the whole list. Admin scope | | POST | `/primaries/reorder` | `{ order }` | Re-rank: `order` names every primary once, highest rank first. Returns the whole list. Admin scope | | POST | `/primaries/threshold` | `{ fillThresholdSat }` | Set the fill threshold in sats, `null` for no cap (400 `INVALID_PARAMS` when negative or fractional). Returns the whole list. Admin scope | | POST | `/invoice/create-hold` | `{ paymentHash, amountMsat?, amountSats?, description?, expiry?, minFinalCltvExpiry? }` | Create hold invoice for a caller-supplied payment hash (HTLCs park until settle/cancel). `minFinalCltvExpiry` is 1..2016 blocks; on a swap leg it has to clear the on-chain refund timeout plus the 18-block hold cancellation margin and the refund's own resolution time | | POST | `/invoice/settle-hold` | `{ preimage }` | Settle a parked hold invoice (fulfills all MPP parts) | | POST | `/invoice/cancel-hold` | `{ paymentHash }` | Cancel a hold invoice; fails parked HTLCs back | | GET | `/invoices/held` | -- | List hold invoices with state + parked totals. Each row also carries `minFinalCltvExpiry` (the delta the invoice advertised and the final hop enforces on every arriving HTLC) and the realised expiry of the parked set: `earliestExpiry`, `cancelMarginBlocks` and `cancelHeight` (null before any part is committed). A swap provider checks `earliestExpiry` against its on-chain refund timeout before funding instead of trusting the advertised delta. A row has `auxiliary: true` while a parked part of its set is an asset HTLC and after such a set settled, and no other row has the field; `heldAmountMsat` is then what the node holds for those HTLCs | | POST | `/invoice/decode` | `{ bolt11 }` | Decode invoice | | POST | `/invoice/pay` | `{ bolt11, timeoutMs?, maxFeeSats?, maxFeeMsat?, amountSats?, metadata?, cltvLimit? }` | Pay invoice (`amountSats` for amount-less invoices, `metadata` for labels). Without `maxFeeSats`/`maxFeeMsat` the routing fee is capped at 1% of the amount, never below 50 sats; `maxPaymentSats` and the daily limit count the amount plus the cap (403 `SPENDING_LIMIT_EXCEEDED`, the message says whether to lower `maxFeeSats` or the amount). `cltvLimit` bounds the payment's total CLTV expiry in blocks above the current tip; no route under it answers `409 CLTV_EXCEEDS_MAX` with nothing sent, and a node without a tip yet answers `503 CHAIN_NOT_SYNCED`. | | POST | `/invoice/pay-safe` | `{ bolt11, timeoutMs?, maxFeeSats?, maxFeeMsat?, amountSats?, metadata?, cltvLimit? }` | Pay invoice; resolves with `status: 'FAILED'` on failure instead of error. Same fee cap and limits as `/invoice/pay`; a limit refusal is reported in `failureDescription`. | | POST | `/invoice/pay-retry` | `{ bolt11, maxRetries?, backoffMs?, maxFeeSats?, amountSats?, metadata?, cltvLimit? }` | Pay with exponential backoff retry. Returns `RetryPaymentResult` with `attempts`. | | POST | `/invoice/pay-async` | `{ bolt11, maxFeeSats?, amountSats?, metadata?, cltvLimit? }` | Fire-and-forget pay; returns `{ paymentHash, status }` immediately. Poll `GET /payment` for settlement. Answers 409 while draining and 403 over a spending limit. A refusal carries the same code and status as `/invoice/pay`: 409 `DUPLICATE_PAYMENT` for a hash already paid or still in flight, 502 `NO_ROUTE`, 400 `INVALID_INVOICE`, and so on, never a bare 502 `PAYMENT_FAILED` (issue #991). | | POST | `/payment/cancel` | `{ paymentHash }` | Cancel a pending outbound payment (marks as FAILED). 409 `PAYMENT_UNRESOLVED` for a payment with `unresolved` on its row | | POST | `/payment/metadata` | `{ paymentHash, metadata }` | Attach key-value metadata to an existing payment | | POST | `/route/estimate` | `{ bolt11, amountSats? }` | Estimate route fee without sending | | POST | `/route/probe` | `{ destination, amountSats }` | Probe route viability to a destination | | GET | `/graph/info` | -- | Network graph summary: node/channel counts, last sync time | | GET | `/graph/node` | `?pubkey=` | Node announcement info + its known channel SCIDs (404 if unknown) | | GET | `/graph/channel` | `?scid=` | Channel endpoints, capacity and both directions' policies (404 if unknown) | | GET | `/graph/describe` | `?limit=&offset=` | Paged channel dump (limit defaults to 500, capped at 500) | | POST | `/route/query` | `{ destination, amountSats, maxFeeSats? }` | Compute a route WITHOUT sending; hops feed `/payment/send-to-route` | | POST | `/payment/send-to-route` | `{ paymentHash, route: { hops }, paymentSecret? }` | Send a payment along an explicit route from `/route/query`. Answers 409 while draining and 403 over a spending limit, judged on what the first hop carries (amount plus every fee); a first hop below the final amount or a negative amount is 400 `INVALID_PARAMS` | | POST | `/backup` | `{ destPath, channelId?, overwrite? }` | Admin export. A database backup returns `path` and `macPath` and accepts `overwrite: true` for an existing backup. Supplying a generation 5 channel ID exports an encrypted recovery frame to a new file and returns `path` and `channelId`. The daemon protects its live database, sidecars, instance lock, `config.json` and `daemon.pid`. | | GET | `/backup/scb` | - | Export encrypted static channel backup `{ encoded, channelCount, path }` | | POST | `/backup/trigger` | -- | Run the configured scheduled backup now (no-op when `backupPath` unset) | | POST | `/message/sign` | `{ message }` | Sign message with the node key (LND-compatible zbase32 signature) | | POST | `/message/verify` | `{ message, signature }` | Recover signer pubkey; `knownNode` = present in our graph | | POST | `/gossip/sync` | `{ pubkey? }` | Gossip sync from one peer or all connected peers | | POST | `/gossip/sync-rapid` | -- | Rapid Gossip Sync snapshot (mainnet only) | | GET | `/channel/diagnostics` | `?channelId=` | Routing-readiness diagnostics (SCID/announcement/peer issues) | | POST | `/address/validate` | `{ address }` | Validate a Bitcoin address for the active network | | POST | `/recover-fallback-funds` | `{ feeRatePerVbyte? }` | Sweep funding-key fallback UTXOs into the wallet | | POST | `/channel/update-commitment-feerate` | `{ channelId, feeratePerKw }` | Update channel COMMITMENT feerate via update_fee (min 253). Not the routing fee policy | | POST | `/channel/update-fee` | `{ channelId, feeratePerKw }` | Deprecated alias for `/channel/update-commitment-feerate` | | POST | `/channel/update-policy` | `{ channelId?, all?, feeBaseMsat?, feeProportionalMillionths?, cltvExpiryDelta?, htlcMinimumMsat?, htlcMaximumMsat? }` | Set ROUTING fee policy per channel (or `all: true`); regenerates + re-broadcasts channel_update | | GET | `/channel/policy` | `?channelId=` | Effective routing policy (override or node defaults) with `source` field | | POST | `/node/wait-ready` | `{ timeoutMs? }` | Wait for node to be fully operational (default 30s). Like the two waits below: `timeoutMs` is capped at 10 minutes, and a credential with 16 waits already open is refused with 429 `RATE_LIMITED` | | POST | `/channel/wait-ready` | `{ channelId, timeoutMs? }` | Wait for channel to reach NORMAL (default 60s) | | POST | `/payment/wait` | `{ paymentHash, timeoutMs? }` | Wait for payment to settle (default 60s) | | POST | `/offer/create` | `{ description, amountSats?, issuer? }` | Create BOLT 12 offer | | POST | `/offer/decode` | `{ offer }` | Decode a BOLT 12 offer string | | POST | `/offer/pay` | `{ offer, amountSats?, timeoutMs?, maxFeeSats?, maxFeeMsat? }` | Pay BOLT 12 offer. Answers 409 while draining and 403 over a spending limit, judged on the invoice the payee returns. `maxFeeSats` or `maxFeeMsat` (a number or a decimal string) caps the routing fee, including the invoice's own blinded-path fee; over the cap answers 409 `FEE_EXCEEDS_MAX` with nothing sent; both at once is 400 `INVALID_PARAMS`. A 504 `PAYMENT_TIMEOUT` carries the `paymentHash` to query with `GET /payment`; a keyed retry of it does not request a new invoice while that payment can still settle (issue #1094). | | GET | `/payment/proof` | `?paymentHash=` | Cryptographic payment proof (preimage, invoice, route) | | GET | `/payment/verify-proof` | `?paymentHash=` | Verify proof: `sha256(preimage) === paymentHash` | | GET | `/node/uri` | `?host=` | Node connection URI (`pubkey@host:port`). Optional external host override. | | POST | `/payment/estimate` | `{ bolt11, amountSats? }` | Payment intelligence: success probability, route quality, fees | | GET | `/liquidity` | -- | Liquidity analysis with recommendations | | GET | `/extensions` | -- | Host extensions running in this daemon ([docs/EXTENSIONS.md](../../docs/EXTENSIONS.md)): `{ api, extensions: [{ id, version, state, generation, error?, routes, events, status? }] }`. Each extension's own routes are served under `/x/`, and a refusal from one answers `EXTENSION_ERROR` with the extension's id and code under `error.extension` | | GET | `/channel/suggestions` | `?count=` | Graph-based channel open suggestions | | GET | `/fees` | -- | On-chain fee trend analysis | | GET | `/logs` | `?category=&since=&limit=` | Query persistent action log | | GET | `/readiness` | -- | Mainnet readiness checklist (12 checks) | | GET | `/metrics` | readonly | Prometheus text exposition format metrics (auth-gated: reports balances; `metricsPublic: true` serves it without auth) | | POST | `/webhooks/register` | `{ url, events, secret? }` | Register webhook callback | | DELETE | `/webhooks/unregister` | `{ id }` | Remove webhook | | GET | `/webhooks` | -- | List registered webhooks | | GET | `/porch/links` | -- | The [Porch links](#porch-links) served, each with one URI per relay, and each relay's state | | POST | `/porch/links/create` | `{ label? }` | Make a Porch link of its own (admin) | | POST | `/porch/links/revoke` | `{ id }` | Revoke a Porch link and disconnect the peers that came in through it (admin) | | POST | `/queue/add` | `{ bolt11, priority?, amountSats?, maxFeeSats?, metadata? }` | Enqueue payment. Dispatched through `/invoice/pay-safe`, with the same default fee cap and limits | | GET | `/queue` | -- | List the queued and dispatching payments, with the 1000 most recently finished | | GET | `/queue/history` | `?limit=&before=` | Finished queue entries, the most recently finished first: up to `limit` (default 100, at most 1000), after the entry with id `before` | | GET | `/queue/entry` | `?id=` | One queue entry by id, whatever its status, from memory or the database | | POST | `/queue/cancel` | `{ id }` | Cancel queued payment | | POST | `/keysend` | `{ pubkey, amountSats, timeoutMs?, maxFeeSats?, metadata? }` | Spontaneous payment (no invoice). Blocks until settled. Without `maxFeeSats` the fee is capped at 1% of the amount, never below 50 sats; the spending limits count the amount plus the cap. A 504 `PAYMENT_TIMEOUT` carries the `paymentHash` to query with `GET /payment`; a keyed retry of it does not send again while that payment can still settle (issue #1133). | | POST | `/keysend/safe` | `{ pubkey, amountSats, timeoutMs?, maxFeeSats?, metadata? }` | Keysend that never errors — resolves with `status: 'FAILED'` instead. | | GET | `/spend-limit` | -- | COMBINED LN + on-chain daily spend limit status: `{ totalSats, lightningSats, onchainSats, limitSats, remainingSats, pendingSats, resetsAt, spentSats }` (`spentSats` mirrors `totalSats` for back-compat; `pendingSats` is what in-flight payments hold and `remainingSats` subtracts it). Persisted: the figures survive a restart within the UTC day, and a payment that settles after a timeout or a restart is still counted once | | GET | `/auth/keys` | -- | List named API keys: names, scopes, revoked/expired flags, expiresAt/rotatedAt (never secrets; admin scope) | | POST | `/auth/keys/revoke` | `{ name }` | Disable a named API key immediately (admin scope; persisted, survives restarts) | | POST | `/auth/keys/rotate` | `{ name }` | Mint a new random secret for a named key; returned once, old secret dies immediately (admin scope; persisted) | | GET | `/recovery/status` | -- | Recovery Protocol status: mode, guardian set, daemon state (`disabled`/`running`/`restore-required`/`restoring`/`restart-required`/`fenced`), the node view (startup gate, durability, last durable sequence, per-channel recovery status), and the Recovery Capsules storage peers returned this session (`capsules`, whose `best` names the guardian locators the capsule carries, credentials redacted), plus `autoApply` (the automatic capsule application: enabled, phase, settleUntil, lastReason, `refusal: { code, assetChannels }` when it was refused for the asset channels the capsule holds, and `skippedAssetChannels` when it applied a backup at Tier 1 and skipped asset entries of it). 404 on an older daemon = predates the feature; 200 with `disabled` = supported but off | | POST | `/recovery/restore` | `{ confirm: true }` | Restore from guardian replicas and start the node on the restored state (restore-pending daemons only; channels RESUME instead of force-closing; the takeover permanently fences the previous writer). Progress streams over SSE as `recovery:restore-progress` | | POST | `/recovery/restore-capsule` | `{ confirm: true, unfenced?: boolean, omitAssetChannels?: boolean }` | Peer-storage mode: restore from the Recovery Capsules storage peers returned this session. Tier 2 installs the exact state into a fresh database and holds the daemon until a restart (503 `NODE_RESTART_REQUIRED` elsewhere); Tier 1 recovers the embedded SCB on the live node. A capsule that holds asset channels the wallet cannot restore is refused with the channels under `error.details.assetChannels`; `omitAssetChannels: true` leaves them out and answers them under `omittedAssetChannels`, with the payments that were in flight on one under `unresolvedPayments`. Progress streams over SSE as `recovery:restore-progress` | | GET | `/guardian/status` | -- | The guardian this node serves to others: `{ serving }` plus guardian id, token requirement, sessions, served sets (members, namespaces, bytes) and limits whenever hosting is on. `serving` is false when hosting is off, and also while the Lightning listener guardians dial is not bound, when `listenError` says why (issue #861) | | POST | `/recovery/rotate-guardians` | `{ guardians: [3 entries], confirm: true }` | Move this wallet to a new guardian set (one member or all three) with the channels running (wire 5.9): register with the incoming set under the current lease at the next generation, backfill, switch, retire the outgoing set. The env keeps naming the old set until updated; the journal's set is in force and the status route reports `configuredSetStale` | | POST | `/recovery/resolve-guardian` | `{ uri }` | A beignet node's `@host:port` to a guardian entry `@bolt8://@host:port`, by asking its guardian over a bolt8 session. Adopts nothing | | POST | `/recovery/capsule-guardians` | `{ confirm: true }` | The guardian set the best retrieved capsule names, INCLUDING transport credentials, as config-file entries for `recoveryGuardians`. The status route redacts credentials; this admin handoff is how a seed restore whose guardians need authentication gets them back. Nothing is adopted or persisted | | POST | `/stop` | `{ drain?, drainTimeoutMs? }` | Stop daemon. `drain: true` waits for in-flight payments before shutting down. | ### Server-Sent Events (SSE) `GET /events` opens a persistent connection that streams events as they occur: ``` event: payment:received data: {"paymentHash":"ab12...","amountSats":1000,"status":"COMPLETED"} event: channel:ready data: {"channelId":"cd34..."} ``` The SSE column of the [Events](#events) table lists which events the stream and webhooks carry. Recovery, hold-invoice, JIT receive, direct-funding, FFOR and swap events are always relayed; per-HTLC events only with `--htlc-events`. - `invoice:settled` fires when an invoice this node issued is paid. `payment:received` also covers spontaneous (keysend) receives, which have no invoice. - `channel:force-closing` fires both when this node broadcasts its own commitment (`initiator: "local"`) and when a peer's unilateral close is detected on-chain (`initiator: "remote"`). - `node:error` carries `code`, `message`, `timestamp` and, when the error belongs to a channel, `channelId`. The three broadcast codes also carry `txid` (display order) and `retained` (issue #1062): | Code | Meaning | `retained` | |------|---------|------------| | `BROADCAST_FAILED` | The chain watcher could not hand a transaction to the backend; it retries on the next block | `true` when the node itself also holds the transaction (a pending funding, an in-flight or adopted but unconfirmed splice) | | `BROADCAST_PERMANENT_FAILURE` | The watcher's retries ran out and it dropped the transaction from its queue | `true` means the node still re-sends it on every block until it confirms; `false` (a close, a sweep) means nothing else will | | `SPLICE_BROADCAST_REFUSED` | The backend refused a fully signed splice the node re-sends every block; raised once per transaction and reason, with the backend's reason in the message | always `true` | - The `hold:*` events carry `{paymentHash, state, heldAmountMsat, htlcCount, minFinalCltvExpiry, earliestExpiry, cancelMarginBlocks, cancelHeight}`, plus `reason` (`api` or `expiry-scan`) on `hold:cancelled`. The amount, count and expiry fields describe the set acted on. Terminal events retain these totals even though a subsequent `GET /invoices/held` row has zero parked parts. `hold:accepted` fires once per new MPP part with the running total. Before funding, require `BigInt(heldAmountMsat)` to cover the full expected amount. For an amountless invoice, use the amount agreed with the payer. A `hold:*` event has `auxiliary: true` when a part of the set it acted on is an asset HTLC, and no other has the field. Per-HTLC events (`htlc:forwarded`, `htlc:fulfilled`, `htlc:failed`) are relayed only when the daemon is started with `--htlc-events` (config `htlcEvents: true`, env `BEIGNET_HTLC_EVENTS=true`); routing nodes generate one event per HTLC, so they are off by default. `htlc:forward-refused` is the exception and is always relayed: it is a forward the outgoing channel refused to add (failed back with `temporary_channel_failure`), which earlier versions reported as a `CHANNEL_ERROR` `node:error` with the same text a refused send of the node's own carries. The daemon also logs it at info as `HTLC forward refused`. A keepalive comment (`: keepalive`) is sent every 30 seconds to prevent proxy timeouts. At most 16 streams per credential (and 64 in all) are open at once; another is refused with 429 `RATE_LIMITED`. A client that stops reading is disconnected once more than 1 MB is waiting for it. ### Webhooks For agent frameworks that prefer callbacks over persistent connections, register webhook URLs: ```bash # Register a webhook curl -X POST http://localhost:2112/webhooks/register \ -H "Content-Type: application/json" \ -d '{"url": "https://myagent.com/callback", "events": ["payment:received"], "secret": "mysecret"}' # {"ok":true,"result":{"id":"abc123...","url":"https://...","events":["payment:received"],...}} # List webhooks curl http://localhost:2112/webhooks # {"ok":true,"result":[...]} # Unregister curl -X DELETE http://localhost:2112/webhooks/unregister \ -H "Content-Type: application/json" \ -d '{"id": "abc123..."}' ``` Webhook deliveries are POST requests with JSON body `{ event, data, timestamp }`. When a `secret` is configured, an `X-Webhook-Signature: sha256=` header is included for payload verification. Webhooks and their secrets are persisted to SQLite (the secrets in the encrypted wallet data, and only when storage encryption is on) and survive daemon restarts. A registration stored by an earlier release kept only a hash of its secret, and delivers unsigned until it is registered again. The `url` must be `http:` or `https:`. A loopback, private (RFC 1918, CGNAT, unique-local) or link-local host is refused with 403 `PRIVATE_NETWORK_REFUSED` unless the request sets `"allowPrivateNetwork": true` (CLI: `--allow-private-network`), the same opt-in as `POST /l402/fetch`. Payloads omit the payment `preimage` that `payment:sent` and `payment:received` carry over SSE; read it from `GET /payment`. Registering with `"events": ["*"]` matches every relayed event, including the invoice, channel-lifecycle, and (when `--htlc-events` is enabled) HTLC events, plus any event types added in future versions. The event list matches the SSE list above. For each registration and payment hash, hold lifecycle deliveries run in order, including the one retry after a failed delivery. Other payment hashes can proceed independently. Retries retain the original payload and timestamp. Delivery is best effort: a request can be received more than once, and an event is dropped after both attempts fail. Handle duplicates without repeating funding and treat `SETTLED` and `CANCELLED` as terminal. After a disconnect or missed delivery, reconcile with `GET /invoices/held` before acting on an old acceptance event. Deliveries wait for a worker: at most 4 per registration and 32 in all are in flight or waiting to retry, and registrations take turns, so a slow recipient does not hold up the others. An attempt that takes longer than 5 seconds, response included, fails. Queued and active deliveries may hold at most 1 MiB of payload per registration and 8 MiB in all. An event that would pass either ceiling is not delivered to that registration. Unregistering drops the registration's queued deliveries and its pending retries. Stopping the daemon drops all of them and aborts the requests in flight. `GET /metrics` reports `beignet_webhook_deliveries_active`, `beignet_webhook_deliveries_queued`, `beignet_webhook_queued_bytes`, and `beignet_webhook_deliveries_total` by `outcome` (`delivered`, `failed`, `overflow`, `discarded`). A library host sets the ceilings with the second `WebhookManager` constructor argument. ### API Versioning All endpoints support an optional `/v1/` prefix for forward compatibility. The daemon strips the prefix automatically: ``` GET /v1/info → handled as GET /info POST /v1/invoice/pay → handled as POST /invoice/pay ``` All responses include `X-API-Version: 1` header. Non-prefixed routes continue to work unchanged. ### CORS Enable CORS with `cors: true` (allows all origins) or `cors: 'https://myapp.com'` (specific origin) in DaemonOptions. Wildcard CORS requires authentication: with `apiToken`/`apiKeys` unset, `cors: true` is refused at startup (any page the operator visits could otherwise drive the API); pass an explicit origin, configure auth, or set `insecure: true` to accept the risk. While authentication is off, the configured origin string is also the only `Origin` the browser guards admit (see [Authentication](#authentication)): a page at any other origin is refused with `403 CROSS_SITE_REQUEST_REFUSED` before the route runs. ```typescript startDaemon({ cors: true, apiToken: '...' }); // Access-Control-Allow-Origin: * startDaemon({ cors: 'https://myapp.com' }); // specific origin ``` Handles `OPTIONS` preflight requests automatically (`GET, POST, DELETE, OPTIONS`). The allowed request headers are `Content-Type`, `Authorization` and `X-Idempotency-Key`, so a browser client can send keyed `POST` requests (the `X-Idempotency-Key` header is documented under [HTTP API](#http-api)). --- ## File Layout ``` src/cli/ types.ts -- JSON-serializable response types errors.ts -- BeignetError + BeignetErrorCode + BOLT failure descriptions beignet-node.ts -- Core wrapper class (most important file) config.ts -- Config file + PID file management daemon.ts -- HTTP daemon (http.createServer) routes.ts -- Route table: each route's scopes and request pipeline flags auth.ts -- Scoped API keys: route->scope map, constant-time authenticator openapi.ts -- OpenAPI 3.0 spec generator (served at GET /openapi.json) webhooks.ts -- WebhookManager (register, dispatch, HMAC signing) payment-queue.ts -- PaymentQueue (priority, concurrency, capacity-aware) http-rate-limiter.ts -- Token-bucket HTTP rate limiter cli.ts -- CLI entry point (#!/usr/bin/env node) index.ts -- Barrel exports README.md -- This file src/lightning/advisor/ liquidity-advisor.ts -- Channel liquidity analysis and recommendations fee-advisor.ts -- On-chain fee trend tracking (144-sample circular buffer) channel-suggestions.ts -- Graph-based channel open suggestions index.ts -- Barrel exports docs/ AI_AGENT_GUIDE.md -- Comprehensive deployment guide for AI agents tests/cli/ beignet-node.test.ts -- Unit tests webhooks.test.ts -- Webhook tests payment-queue.test.ts -- Payment queue tests payment-retry.test.ts -- Payment retry with backoff tests readiness.test.ts -- Readiness checklist tests metrics.test.ts -- Prometheus metrics tests electrum-failover.test.ts -- Electrum failover tests auto-backup.test.ts -- Automated backup tests ensure-channels.test.ts -- Auto-open minimum channels tests deployment-guide.test.ts -- Guide existence tests competitive-improvements.test.ts -- Spending limits, idempotency, TLS, drain mode tests ``` --- ## Tests ```bash # Run CLI unit tests (no infrastructure needed; the spawn tests run dist/cli/cli.js) npm run build npm run test:cli # Run daemon/Electrum integration tests (requires Electrum server) npm run test:integration # Run lightning unit tests npm run test:lightning # Run lightning and CLI unit tests at once (builds first) npm test # Interop suites against the Docker nodes. LND_REST_PORT / LND_REST_HOST (and # LND_TAPROOT_REST_PORT / LND_TAPROOT_REST_HOST) move the endpoints; a suite # whose LND is unreachable skips with a line naming the port, and # INTEROP_REQUIRE_LND=1 / INTEROP_REQUIRE_LND_TAPROOT=1 fail instead of # skipping. See "Interop testing" in the top-level README. npm run test:interop ``` ### Cooperative close to an address `POST /channel/close-quote` accepts `{ channelId, address? }` and returns the expected `amountSats`, our `feeSats`, the whole transaction's `networkFeeSats`, `feeratePerkw`, `feePayer`, and `feeEstimated: true`. `BeignetNode.closeQuote(channelId, address?)` provides the same read-only estimate. The peer's shutdown script and fee negotiation can change the final payout. Legacy closes charge the opener; simple close can charge the party whose signed candidate confirms. `POST /channel/close` accepts the same optional address. It validates the network, checks external spend limits, and refuses while HTLCs, updates or a splice are pending. The ordinary wallet payout and explicit stale-state acknowledgement keep their existing behavior. An external close saves its destination before sending shutdown and retains signed payout candidates before broadcast. `GET /transactions` includes one `sent` row for the selected cooperative transaction with `source: "cooperative-close"`, `channelId`, the actual payout, our actual fee and its confirmation state, including after a restart. A force close remains a separate action.