# beignet

> A self-custodial, JS Bitcoin wallet + Lightning Network management library.

Latest version **0.45.1** (published 2026-11-23) · MIT license · 0 weekly downloads

## Install

```sh
npm install beignet
pnpm add beignet
yarn add beignet
bun add beignet
```

Provides the command `beignet`.

## Health

**Score 70/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads; large bundle; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.45.1 |
| Published | 2026-11-23 |
| First published | 2023-12-18 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | ^22.23.4 \|\| ^24.22.1 \|\| >=26.12.1 |
| Dependencies | 17 |
| Unpacked size | 21 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | coreyphillips |
| Maintainers | coreyphillips, bitcoinerrorlog, pwltr, shacollision, ovitrif, 86667-tomos |
| Keywords | Bitcoin, wallet, lightning, lightning-network, bolt, ai-agent |

## Links

- npm: https://www.npmjs.com/package/beignet
- Repository: https://github.com/coreyphillips/beignet
- Homepage: https://github.com/coreyphillips/beignet#readme
- Issues: https://github.com/coreyphillips/beignet/issues
- npm.io page: https://npm.io/package/beignet

## Dependencies (17)

- [net](https://npm.io/package/net.md) 1.0.2
- [bip21](https://npm.io/package/bip21.md) 2.0.3
- [bip32](https://npm.io/package/bip32.md) 4.0.0
- [bip39](https://npm.io/package/bip39.md) 3.1.0
- [socks](https://npm.io/package/socks.md) ^2.8.7
- [bech32](https://npm.io/package/bech32.md) 2.0.0
- [ecpair](https://npm.io/package/ecpair.md) 2.1.0
- [@noble/hashes](https://npm.io/package/@noble/hashes.md) 1.8.0
- [bitcoin-units](https://npm.io/package/bitcoin-units.md) 0.3.0
- [bitcoinjs-lib](https://npm.io/package/bitcoinjs-lib.md) 6.1.10
- [@noble/secp256k1](https://npm.io/package/@noble/secp256k1.md) 1.7.2
- [lodash.clonedeep](https://npm.io/package/lodash.clonedeep.md) 4.5.0
- [rn-electrum-client](https://npm.io/package/rn-electrum-client.md) 0.0.22
- [@brandonblack/musig](https://npm.io/package/@brandonblack/musig.md) ^0.0.1-alpha.1
- [@types/better-sqlite3](https://npm.io/package/@types/better-sqlite3.md) ^7.6.13
- [@bitcoinerlab/secp256k1](https://npm.io/package/@bitcoinerlab/secp256k1.md) 1.0.5
- [bitcoin-address-validation](https://npm.io/package/bitcoin-address-validation.md) 2.2.3

## Recent versions

- 0.45.1 (latest) — 2026-11-23
- 0.45.0 — 2026-11-22
- 0.44.0 — 2026-11-21
- 0.43.6 — 2026-11-20
- 0.43.5 — 2026-11-19
- 0.43.4 — 2026-11-19
- 0.43.3 — 2026-11-19
- 0.43.2 — 2026-11-18
- 0.43.1 — 2026-11-18
- 0.43.0 — 2026-11-17
- 0.42.0 — 2026-11-16
- 0.41.0 — 2026-11-15
- 0.40.0 — 2026-11-13
- 0.39.0 — 2026-11-12
- 0.38.4 — 2026-11-10
- … 152 more at https://npm.io/package/beignet/versions

## README

# Beignet

A self-custodial Bitcoin wallet library for JavaScript/TypeScript with a **full Lightning Network implementation**. Beignet implements the Lightning protocol and channel state machine in TypeScript rather than wrapping LND, CLN or LDK: it speaks BOLT 8 over a real TCP socket and runs its own BOLT 2 state machine.

Two layers, one mnemonic:

- **On-chain wallet:** HD keys, address generation, UTXO tracking, transaction building, PSBT/hardware signing, multisig, watch-only, Electrum connectivity.
- **Lightning:** channel lifecycle, onion-routed payments, BOLT 11 invoices, BOLT 12 offers, gossip and pathfinding, anchors, splicing, taproot channels, watchtower client. Interop-tested against LND, Core Lightning and Eclair on regtest.

Requires **Node.js 22.23.4+, 24.22.1+ or 26.12.1+**. Earlier releases on those lines, and all of Node.js 18 and 20, lack the October 21, 2026 Node.js security fixes; the daemon warns at startup when it runs on one. MIT licensed.

**Jump to:** [Install](#install) · [Examples](#try-the-examples) · [On-chain wallet](#on-chain-wallet) · [Lightning](#lightning) · [Daemon & CLI](#http-daemon--cli) · [Protocol layer](#protocol-layer-advanced) · [Tests](#tests) · [Status & limitations](#status--limitations)

## Install

```bash
npm install beignet     # or: yarn add beignet
```

Smallest thing that works. `net` and `tls` are injected so the same code runs on Node and React Native:

```typescript
import net from 'net';
import tls from 'tls';
import { Wallet, generateMnemonic } from 'beignet';

const result = await Wallet.create({
  mnemonic: generateMnemonic(),
  electrumOptions: { net, tls }
});
if (result.isErr()) throw result.error;
const wallet = result.value;

console.log(await wallet.getAddress());
console.log(wallet.getBalance());
```

From here: [the on-chain wallet](#on-chain-wallet) for sending, PSBTs, multisig and watch-only, or [Lightning](#lightning) for channels and payments.

For adding `bgnq` direct-funding payments to another wallet, see the [standalone TypeScript payer SDK](packages/direct-funding/README.md). It includes a PSBT signing adapter, Bitcoin Core integration, and a channel-free peer client. This package exports the same SDK as `beignet/direct-funding` and `beignet/direct-funding/node`.

## Try the examples

The fastest way to understand the whole system is to run the two REPL examples against a live wallet and a live node. Both are checked-in TypeScript you can read and edit.

```bash
git clone git@github.com:coreyphillips/beignet.git && cd beignet
npm install
```

### 1. On-chain wallet REPL

```bash
npm run example
```

Creates a regtest wallet (a fresh mnemonic unless `BEIGNET_MNEMONIC` holds one), syncs it against a public Electrum server, prints the balance and a receive address, then drops you at a `>` prompt with the wallet bound to `wallet`. Type `help()` for the command list.

```js
> wallet.getBalance()
> await wallet.getAddress()
> await wallet.refreshWallet()
> await wallet.send({ address: 'bcrt1q...', amount: 10000, satsPerByte: 2 })
```

State persists as JSON under `example/walletData/`. Pass `testnet` or `mainnet` to change the network. To reuse a wallet, see [reusing a mnemonic](#reusing-a-mnemonic) below.

### 2. Lightning node REPL

```bash
npm run example:lightning
```

Boots a real regtest Lightning node (`BeignetNode`) with an auto-created wallet, storage and funding provider, waits for it to become operational, prints info/balance/health, and drops you at a `beignet>` prompt with the node bound to `node`. Type `help()` for the command list. Top-level `await` works.

```js
beignet> await node.getNewAddress()          // fund this on-chain, then:
beignet> await node.connectAndOpenChannel(pubkey, host, port, 200000)
beignet> node.createInvoice(1000, 'coffee').bolt11
beignet> await node.payInvoice('lnbc...')
beignet> node.getLiquiditySnapshot()
```

The flags you will actually reach for (everything after `--`):

| Flag | Effect |
|------|--------|
| `mainnet` \| `testnet` \| `regtest` | Network, as a bare positional arg (default `regtest`) |
| `--electrum-host <h>` `--electrum-port <p>` | Point at your own Electrum server |
| `--alias <name>` | Node alias in `node_announcement` |

```bash
# named regtest node against a local Electrum server
npm run example:lightning -- regtest --electrum-host 127.0.0.1 --electrum-port 60001 --alias mynode
```

Tor, full-graph gossip, the low-level `LightningNode` variant and the non-interactive payment-API walkthrough have flags too: see [the flag reference](example/REPL_TESTING.md#repl-flags).

Node state lives in a SQLite DB under `~/.beignet/data/<hash-of-mnemonic>/` (the `--low-level` example uses `example/lightningData/node.db`).

Both examples run through `ts-node`. The on-chain example runs straight off the TypeScript sources. The Lightning example imports only the public entry points (`beignet`, `beignet/cli`, `beignet/lightning`, `beignet/lightning/sqlite`), so `npm run example:lightning` builds `dist/` first, and the file runs unchanged in a project that installed `beignet` from npm.

**→ [example/REPL_TESTING.md](example/REPL_TESTING.md) is a copy-pasteable walkthrough** of the whole lifecycle in the REPL: funding, peers, channels, invoices, payments, keysend, offers, splicing, closing, backup.

### Reusing a mnemonic

Both examples read an existing mnemonic from `BEIGNET_MNEMONIC` and exit if one is passed as an argument, where it would sit in shell history and the process list. `read -rs` keeps it off the screen as well:

```bash
read -rs BEIGNET_MNEMONIC && export BEIGNET_MNEMONIC   # paste the words, press Enter
npm run example:lightning -- mainnet
```

Without `BEIGNET_MNEMONIC`, both examples generate a mnemonic and print it before anything else. That output is its only copy, so write it down before funding the wallet, and bring your own on mainnet.

## Which entry point?

| Import | Contains | Use when |
|--------|----------|----------|
| `beignet` | `Wallet`, `generateMnemonic`, types | You want the on-chain wallet |
| `beignet/node` | `BeignetNode`, error helpers | **You want Lightning.** Sats-denominated, string IDs, structured errors. Runs on React Native |
| `beignet/daemon` | `startDaemon`, API keys, webhooks | You serve the HTTP API from your own Node process |
| `beignet/cli` | Both of the above | Existing imports; it loads the daemon too |
| `beignet/lightning` | Namespaced protocol modules (`node`, `channel`, `onion`, ...) | You need the raw BOLT layer: bigint msat, Buffer IDs, wire messages |
| `beignet/lightning/sqlite` | `SqliteStorage`, `GuardianStore` | You persist a node to SQLite. Needs the optional `better-sqlite3` |
| `beignet/lightning/iroh-node` | `createNodeIrohEndpoint` | You link nodes over Iroh on Node.js. Needs the optional `@number0/iroh` addon |
| `beignet/direct-funding` | `DirectFundingClient`, `BitcoinCoreWalletAdapter`, `createPsbtCoinSigner` | You pay `bgnq` direct-funding requests from another wallet. Loads no node, wallet or receiver engine |
| `beignet/direct-funding/node` | `FileDirectFundingStorage`, `NodePeerMessaging` | The payer SDK on Node.js: file storage and a channel-free BOLT 8 peer client |

## On-chain wallet

```typescript
import net from 'net';
import tls from 'tls';
import { Wallet, generateMnemonic } from 'beignet';

const res = await Wallet.create({
  mnemonic: generateMnemonic(),
  electrumOptions: { net, tls } // required: inject the socket implementations
});
if (res.isErr()) throw res.error;
const wallet = res.value;

const address = await wallet.getAddress();
const balance = wallet.getBalance();

await wallet.send({ address: 'bc1q...', amount: 50_000, satsPerByte: 2 });
await wallet.sendMany({ txs: [{ address: 'bc1q...', amount: 1000 }] });
await wallet.refreshWallet();

const utxos = wallet.listUtxos(); // what the last refresh stored
const history = await wallet.fetchAddressHistory('bc1q...'); // asks Electrum

// Build and sign without broadcasting, then broadcast separately
const signed = await wallet.createSignedTransaction({ address: 'bc1q...', amount: 50_000 });
if (signed.isOk()) await wallet.broadcastTransaction(signed.value.txHex);
```

A method's verb says where its answer comes from: `get*` and `list*` read what the wallet holds, `fetch*` asks Electrum, and `refresh*` asks Electrum and stores the answer. [docs/API-CONVENTIONS.md](docs/API-CONVENTIONS.md) lists the older names, which still work and go in the next major release.

Most fallible calls return a `Result<T>`: check `isErr()` before reading `.value`. The error is a `CodedError`: branch on `error.code`, never on the message, which can be reworded. The code is an `EWalletErrorCode` (`UNSPECIFIED` when the failure has no code of its own), or the code of an error passed through unchanged, such as `WATCH_ONLY_CANNOT_SIGN` or a `BoostError`'s. `error.cause` holds the failure it wraps, when there is one.

A few calls do not return a `Result`, so check them differently:

- `getAddress()` resolves to `''` when it cannot derive an address.
- `fetchFeeEstimates()` never errs. When its sources fail it returns the previous estimates or built-in defaults (fixed values on regtest).
- `updateAddressType()` throws on a type the wallet cannot use, and `resetAddressIndexes()` resolves to nothing.

Balances, UTXO values and send amounts are satoshis, and fee rates are sat/vB: every `satsPerByte` option and field is sat/vB despite its name. Stored transactions (`wallet.transactions`) carry their amounts in satoshis as `valueSats`, `feeSats`, `totalInputSats`, `matchedInputSats`, `totalOutputSats` and `matchedOutputSats`. Their older BTC twins (`value`, `fee`, `totalInputValue` and the rest) are deprecated and go in the next major release. `btcToSats`, `satsToMsat` and `msatToSatsFloor` convert between units.

Options worth knowing on `Wallet.create`: `network` (`Network.bitcoin` | `testnet` | `regtest` | `signet`), `addressType` (`EAddressType.p2wpkh` default, `p2sh` for P2SH-wrapped segwit, `p2pkh`, `p2tr`), `passphrase`, `account`, `storage`, `logger`, `onMessage`, `coinSelectPreference`, `feeEstimationSource`, `gapLimitOptions`, `remainOffline`.

`remainOffline: true` makes a wallet that never opens a connection: no Electrum server, and no fee lookup over HTTP. Calls that need a server fail, and a refresh stops after deriving the first addresses.

`wallet.data` is a frozen copy of the wallet's data, taken when it is read. Change data with `wallet.updateData({ utxos, balance })`, which replaces those fields and saves them in order with the wallet's own writes. Each read of `wallet.data` copies the whole history, so code reading one field often should use `wallet.balance`, `wallet.utxos` or `wallet.transactions`.

<details>
<summary><b>Fees, sweeping, boosting, coin control, events and shutdown</b></summary>

```typescript
import { EBoostType } from 'beignet';

const fees = await wallet.fetchFeeEstimates(); // { fast, normal, slow, minimum, timestamp }, sat/vB
await wallet.sendMax({ address: 'bc1q...', satsPerByte: fees.normal }); // sweeps every unfrozen coin

// Fee bumping an unconfirmed transaction
wallet.canBoost(txid);                     // { canBoost, rbf, cpfp }
wallet.getBoostableTransactions();         // { rbf: [...], cpfp: [...] }
await wallet.boost({ txid, type: EBoostType.rbf, satsPerByte: 20 }); // or EBoostType.cpfp

// Coin control: a frozen coin is left out of every coin selection
await wallet.freezeUtxo({ txid, vout: 0 });
await wallet.unfreezeUtxo({ txid, vout: 0 });
wallet.listUtxos();           // every coin, frozen ones included
wallet.listFrozenUtxos();
wallet.getBalanceBreakdown(); // { total, spendable, frozen }

// Waits (up to refreshTimeout) for an in-flight refresh and queued storage writes
await wallet.stop();
```

`onMessage(key, data)` on `Wallet.create` receives wallet events. The keys are `newBlock`, `transactionReceived`, `transactionSent`, `transactionConfirmed` (each with `{ transaction }`), `reorg` (the affected UTXOs), `rbf` (the replaced txids), `connectedToElectrum` (`true` or `false`) and `storageWriteFailed` (a write storage refused). `disableMessages: true` silences them, and `disableMessagesOnCreate: true` holds them until the first refresh ends, so stored history does not replay as news.

</details>

<details>
<summary><b>Custom Electrum servers, failover, fee sources, BIP21</b></summary>

```typescript
import { EProtocol, Network, Wallet } from 'beignet';

const res = await Wallet.create({
  mnemonic,
  network: Network.bitcoin,
  feeEstimationSource: 'electrum', // 'electrum' | 'http' | 'auto' (default)
  electrumOptions: {
    net,
    tls,
    servers: [
      { host: 'bitcoin.lu.ke', ssl: 50002, tcp: 50001, protocol: EProtocol.ssl },
      { host: 'mempool.space', ssl: 60602, tcp: 60601, protocol: EProtocol.ssl }
    ]
  }
});
```

- **Failover:** with multiple servers the wallet rotates through them in order on connect/reconnect failure, then through hardcoded fallback peers for the network, with a per-server cooldown so dead servers are not hammered. Inspect `wallet.electrum.currentServer` and `wallet.electrum.rotationCount`.
- **Certificate verification:** by default a TLS Electrum connection is encrypted but the server certificate is not checked, because the client library dials with `rejectUnauthorized: false`. An on-path attacker can therefore stand in for the server. On Node, pass `tls: withTlsVerification(tls)` to accept only certificates that chain to a trusted CA and match the host, and add `{ fingerprints: ['AB:CD:…'] }` to also accept self-signed servers by SHA-256 fingerprint (`openssl x509 -noout -fingerprint -sha256`). A caller that resolves the host itself and dials the address passes `{ servernames: { [address]: hostName } }` so the check still uses the name. The client library keeps one connection per network for the whole process, shared by every wallet on that network, so wallets in one process should all pass the same `tls`. The daemon verifies when `BEIGNET_ELECTRUM_TLS_VERIFY=true` (see `src/cli/README.md`); it is off by default. React Native does not verify yet.
- **Fee source:** `'electrum'` queries only the connected server via `blockchain.estimatefee`, so fee lookups never leak to mempool.space/blocktank over clearnet. `'auto'` prefers Electrum and falls back to HTTP. All remote rates are clamped to 5000 sat/vB.
- **Networks:** mainnet, testnet, regtest and signet work end to end (wallet, Electrum, CLI/daemon `--network signet`, Lightning chain hash and `tbs` invoice prefix). Signet shares testnet address formats and coin type 1.
- **BIP21:** `encodeBip21({ address, amountSats?, label?, message? })` builds a `bitcoin:` URI.

</details>

<details>
<summary><b>Watch-only wallets (account xpub)</b></summary>

Built from an account-level extended public key instead of a mnemonic. The key is assumed to sit at `m/purpose'/coin'/account'` (e.g. `m/84'/0'/0'`), so addresses derive as `xpub/0/i` and `xpub/1/i`. SLIP-132 version bytes are normalized: `zpub`/`vpub` implies p2wpkh, `ypub`/`upub` implies p2sh-p2wpkh (`EAddressType.p2sh`), a plain `xpub`/`tpub` uses `addressType` (default p2wpkh). One account xpub yields exactly one address type, so a watch-only wallet monitors only that type.

```typescript
const res = await Wallet.createWatchOnly({
  xpub: 'zpub6r...',
  network: Network.bitcoin,
  electrumOptions: { net, tls }
});
if (res.isErr()) return;
const watchOnly = res.value;

await watchOnly.getAddress(); // works
watchOnly.getBalance();       // works

const send = await watchOnly.send({ address: 'bc1q...', amount: 1000 });
// send.isErr() === true, message: 'watch-only wallet cannot sign'
```

The full read-only surface works: address generation, gap-limit scanning, Electrum refresh, balances, history, UTXOs, fee estimates, address subscriptions. Anything needing private keys (`send`/`sendMax`/`sendMany`/`sweepPrivateKey`/`getPrivateKey`) fails with the typed `WatchOnlySigningError` (`code: 'WATCH_ONLY_CANNOT_SIGN'`). Library-only for now: the HTTP daemon always runs with a mnemonic.

</details>

<details>
<summary><b>Hardware wallets and external signers (PSBT)</b></summary>

`buildPsbt` runs the normal setup (coin selection, change, fee) but stops before signing, returning a base64 PSBT populated with what a hardware signer needs: `witnessUtxo` (or `nonWitnessUtxo` for legacy p2pkh), `redeemScript` for p2sh-p2wpkh, `tapInternalKey` plus `tapBip32Derivation` for p2tr, and `bip32Derivation` on every wallet input. The change output carries the same derivation fields, so the signer shows it as change rather than as a second recipient. Works on full and watch-only wallets.

```typescript
// 1. Build (never touches private keys)
const build = await wallet.buildPsbt({ address: 'bc1q...', amount: 50_000, satsPerByte: 4 });
if (build.isErr()) return;
const { psbtBase64, fee, vsizeEstimate } = build.value;

// 2. Sign externally (hardware wallet, HWI, another machine)
const signedBase64 = await myHardwareWallet.signPsbt(psbtBase64);

// 3. Import: checks the inputs and outputs are the ones built, validates a
//    signature on EVERY input, finalizes, does NOT broadcast
const imported = wallet.importSignedPsbt(signedBase64);
if (imported.isErr()) return; // changed outputs, missing/invalid signatures are rejected loudly
const { txHex, txid } = imported.value;

// 4. Broadcast when ready
await wallet.broadcastTransaction(txHex);

// Multi-party: merge partially signed copies of the same PSBT
const combined = wallet.combinePsbts([copyA, copyB]);
```

`importSignedPsbt` finalizes only a PSBT that spends the same inputs to the same outputs as one this wallet instance built (it remembers its 50 most recent builds, in memory). To import a PSBT built elsewhere, or after a restart, pass the unsigned PSBT as the second argument: `wallet.importSignedPsbt(signedBase64, psbtBase64)`. Inputs the signer already finalized are refused, since their signatures cannot be checked.

For watch-only wallets the true master fingerprint is unknowable from an account xpub, so the xpub's parent fingerprint is used: signers should locate keys by derivation path.

Also on the daemon (`POST /psbt/build`, `/psbt/import-signed`, `/psbt/combine`) and the CLI (`beignet psbt build|import-signed|combine`). A restart forgets the daemon's builds, so the import there takes the unsigned PSBT too: `unsignedPsbtBase64` on the route, a second argument to `beignet psbt import-signed`.

</details>

<details>
<summary><b>Multisig (P2WSH sortedmulti)</b></summary>

`Wallet.createMultisig` creates a descriptor-based sorted-multisig wallet, `wsh(sortedmulti(threshold, key1, key2, ...))`: the interoperable standard used by Bitcoin Core, Sparrow and Specter. Derivation follows BIP 48 script type 2 (`m/48'/coin'/account'/2'`, receive `/0/*`, change `/1/*`) and keys are BIP 67 ordered at every index, so any wallet built from the same account xpubs produces identical addresses regardless of cosigner order.

Cosigners are account-level extended public keys (`xpub`/`tpub`, or SLIP-132 `Zpub`/`Vpub`, normalized automatically). With a mnemonic, this wallet IS one of the cosigners: its BIP 48 account xpub is derived and included automatically (pass `ourXpub` to assert it; a mismatch is rejected). Omit the mnemonic for a watch-only coordinator.

Spending is PSBT-only. `send`/`sendMany`/`sendMax` fail with `MultisigSpendError` (`code: 'MULTISIG_REQUIRES_PSBT'`).

```typescript
// 1. Each cosigner builds the same quorum from the others' BIP 48 account xpubs.
const a = await Wallet.createMultisig({
  threshold: 2,
  mnemonic: mnemonicA,       // we are one cosigner; our xpub is added automatically
  cosigners: [xpubB, xpubC],
  network: Network.bitcoin,
  electrumOptions: { net, tls }
});
const b = await Wallet.createMultisig({ threshold: 2, mnemonic: mnemonicB, cosigners: [xpubA, xpubC], /* ... */ });

// An optional watch-only coordinator holds no keys at all.
const c = await Wallet.createMultisig({ threshold: 2, cosigners: [xpubA, xpubB, xpubC], /* ... */ });

if (a.isErr() || b.isErr() || c.isErr()) return;
const [walletA, walletB, coordinator] = [a.value, b.value, c.value];

// 2. Fund it: every instance derives the same addresses.
const deposit = await walletA.getAddress();

// 3. Build the unsigned PSBT (any instance, coordinator included).
const built = await walletA.buildPsbt({ address: 'bc1q...', amount: 50_000, satsPerByte: 4 });
if (built.isErr()) return;
const unsigned = built.value.psbtBase64;

// 4. Each cosigner signs their own copy (nothing finalizes below threshold).
const signedA = walletA.signPsbtWithOurKey(unsigned);
const signedB = walletB.signPsbtWithOurKey(unsigned);
if (signedA.isErr() || signedB.isErr()) return;

// 5. Combine, finalize at threshold, broadcast. The coordinator did not build
//    the PSBT, so it checks the combined one against the unsigned original.
const combined = coordinator.combinePsbts([signedA.value, signedB.value]);
if (combined.isErr()) return;
const finalized = coordinator.importSignedPsbt(combined.value, unsigned); // 2-of-3 met
if (finalized.isErr()) return;
await coordinator.broadcastTransaction(finalized.value.txHex);

// Below threshold it fails loudly:
// 'Input 0 is below the multisig threshold: have 1 signature(s), need 2.'

// Interop: import into Bitcoin Core / Sparrow / Specter.
const exported = coordinator.exportDescriptors(); // Result<IExportDescriptorsResponse>
if (exported.isErr()) return;
exported.value.descriptors[0].external;
// wsh(sortedmulti(2,[fp/48h/0h/0h/2h]xpub.../0/*,[fp]xpub.../0/*,...))#checksum
```

`buildPsbt` attaches the `witnessScript` and one `bip32Derivation` per cosigner to every input. `importSignedPsbt` counts VALID partial signatures per input against the witnessScript threshold and refuses to finalize below it. Library-only for now: the daemon wallet stays single-sig.

</details>

<details>
<summary><b>Storage, encryption and leveled logging</b></summary>

The wallet persists through the `storage` option, an `IWalletStorage`: `getData(key)`, `setData(key, value)` and the optional `setTransactionChanges` below. It holds one value per `IWalletData` field, under `<name>-<network>-<field>` (`<name>-<network>-acct<n>-<field>` for a non-zero account), and each value is plain JSON data. `createMemoryStorage()` implements all of it in memory: use it for tests and short-lived wallets, and start from it when writing a persistent store. Without `storage` the wallet keeps its data in memory and saves nothing.

Values are handed over as-is, so by default they are stored in plaintext. Persisted data is addresses, indexes, UTXOs, transactions, balance and fee estimates: no private keys and no mnemonic are ever written, so exposure is a privacy concern (full wallet history), not fund loss. The staged send (`transaction`) is written without signing keys, so a key pair handed to `sweepPrivateKey` or `addExternalInputs` never reaches storage, and `send`, `sendMany`, `sendMax`, `buildPsbt` and `sweepPrivateKey` reset the staged send when they return, so a restart never replays an earlier call's recipients.

`getData` must return `ok(undefined)` for a key it does not hold and `err` only when the read fails. `Wallet.create` returns an error on a failed read rather than start from defaults and save them over the data it could not read; pass `resetOnReadFailure: true` to start from defaults anyway.

`setData` must keep a copy of the value: the wallet goes on changing the object it handed over. Writes to one key arrive one at a time, in the order the wallet made them. A write that resolves `err`, or rejects, reaches `onMessage` as `storageWriteFailed`.

By default every change to the transaction history hands `setData` the whole history. A storage that also implements `setTransactionChanges(key, { set, deleted })` gets only the records that changed: new transactions, confirmations, reorgs, deletions and boosts. Its `getData` must then return the history with those changes applied. Replacing or clearing the history, and the one-time upgrade of old records on load, still go through `setData`. `createEncryptedStorage` does not pass `setTransactionChanges` through, so an encrypted storage keeps receiving the whole history.

Wrap any `IWalletStorage` with `createEncryptedStorage` to encrypt at rest with AES-256-GCM under an HKDF-derived key from the seed. Pre-existing plaintext values pass through unchanged and migrate lazily as they are rewritten.

```typescript
import * as bip39 from 'bip39';
import { createConsoleLogger, createEncryptedStorage, Wallet } from 'beignet';

const seed = bip39.mnemonicToSeedSync(mnemonic);
const wallet = await Wallet.create({
  mnemonic,
  storage: createEncryptedStorage({ getData, setData }, seed),
  logger: createConsoleLogger('warn'), // only warn + error reach the console
  electrumOptions: { net, tls }
});
```

Diagnostics flow through a small injectable `ILogger` (`debug`/`info`/`warn`/`error`, each `(message, meta?)`), with filtering `debug < info < warn < error` plus `'silent'`. This is separate from the Lightning node's persisted structured action log (`getActionLog`).

- `Wallet.create({ logger })` defaults to `createConsoleLogger('info')`, preserving historical console output. `disableMessages` is independent: it only gates `onMessage` callbacks.
- `LightningNode` defaults to `noopLogger` (silent). Every action-log entry is also mirrored to `logger.debug('category:action', data)`.
- `BeignetNode.create({ logger, logLevel })` forwards passing entries to the logger (in addition to the `'log'` event) and injects it into the underlying `Wallet` and `LightningNode`.
- Daemon: `beignet start --log-level <debug|info|warn|error|silent>` (or `BEIGNET_LOG_LEVEL`, or `logLevel` in `~/.beignet/config.json`) prints to stderr. Unset keeps the daemon silent; stdout stays reserved for command output.

</details>

## Lightning

> **Beignet is under active development.** Evaluate it on regtest, signet, or with small
> amounts you can afford to lose. Read [Status & limitations](#status--limitations) before
> putting meaningful mainnet funds behind it: this is a self-custodial Lightning
> implementation, and channel funds are only as safe as the node watching them.

`BeignetNode` from `beignet/node` is the recommended API: it wraps the protocol layer with satoshi amounts, string channel IDs and structured error codes. `beignet/cli` exports it too.

```typescript
import { BeignetNode, isRetryableError } from 'beignet/node';

// Creates the wallet, storage and funding provider for you
const node = await BeignetNode.create({
  mnemonic: 'abandon abandon ... about',
  network: 'regtest',
  electrumHost: '127.0.0.1',
  electrumPort: 60001
});

node.getInfo();    // { nodeId, network, alias, ... }
node.getHealth();  // { status: 'ready', peers, channels, ... }
node.isReady();    // true once the node has active channels

const inv = node.createInvoice(1000, 'coffee');
console.log(inv.bolt11);

try {
  const payment = await node.payInvoice('lnbcrt10n1...');
  console.log(payment.status); // 'COMPLETED'
} catch (err) {
  if (isRetryableError(err)) {
    // transient: no route, timeout. Safe to retry
  } else {
    // permanent: invalid invoice, expired. Do not retry
  }
}

node.listChannels();
node.listPayments();
node.listInvoices();

await node.destroy();
```

`BeignetNode` is a typed emitter: `node.on('channel:ready', ({ channelId }) => ...)`. Every event, its payload and whether the daemon relays it over SSE is in the [generated events table](src/cli/README.md#events); every `BeignetNode.create` option is in the [options table](src/cli/README.md#factory).

Useful variants: `payInvoiceSafe` (never throws), `payInvoiceWithRetry({ maxRetries, backoffMs, maxFeeSats })`, `sendPaymentAsync` (returns the hash immediately), `connectAndOpenChannel`, `openChannelAndWait`, `sendKeysend`, `createOffer`/`payOffer`, `spliceIn`/`spliceOut`, `backup`, `gracefulShutdown`.

**→ [docs/AI_AGENT_GUIDE.md](docs/AI_AGENT_GUIDE.md)** covers deployment in depth: channel strategy, liquidity management, monitoring and Prometheus metrics, pre-flight validation, safety rails, retry/backoff patterns, idempotency keys, spend limits, drain mode, backup and recovery, mainnet checklist.

### Decision-support APIs

Built-in advisors, not usually found in a Lightning library:

```typescript
// Channel balance analysis with actionable recommendations
const liquidity = node.getLiquiditySnapshot();
console.log('Outbound:', liquidity.outboundLiquidityPct + '%');
for (const rec of liquidity.recommendations) {
  console.log(`[${rec.priority}] ${rec.type}: ${rec.reason}`);
}

node.getChannelSuggestions(3);  // graph-based peer suggestions for opens
node.getFeeSnapshot();          // on-chain fee trend: OPEN_NOW / WAIT / NEUTRAL
node.estimatePayment(bolt11);   // success probability + estimated fee, pre-send
node.getMainnetReadiness();     // 12-check weighted readiness report
```

<details>
<summary><b>Advisor execution: circular rebalancing and fee auto-tuning</b></summary>

The advisor can act, not just recommend. Both features are **off by default**.

```typescript
// One-shot circular rebalance: self-payment out over `from` and back in over `to`.
// Aborts WITHOUT paying if the route fee exceeds maxFeeSats.
await node.rebalanceChannel(fromChannelId, toChannelId, 50_000, /* maxFeeSats */ 50);

node.getAdvisorRecommendations();        // read-only: analyze() + rebalancePlan[]
await node.executeRebalances(/* budgetSatsPerDay */ 500);
```

Automatic modes, opt-in via `BeignetNodeOptions` / `INodeConfig`:

```typescript
const node = await BeignetNode.create({
  mnemonic,
  network: 'mainnet',
  // Periodically executes the rebalance plan. Routing fees spent on rebalances
  // are capped per UTC day and the running spend is persisted, so restarts
  // never overspend the same day. Resets at midnight UTC.
  autoRebalance: { enabled: true, budgetSatsPerDay: 500, minImbalancePct: 20 },
  // Every intervalMs (default 6h) nudges each channel's proportional fee:
  // +25% when outbound is depleted (<20% local) but still forwarding, -25% when
  // the channel saw no forwards in the window, clamped to [floorPpm, ceilPpm].
  // One adjustment per channel per interval.
  autoTuneFees: { enabled: true, floorPpm: 1, ceilPpm: 5_000 }
});
```

Daemon: `POST /rebalance`, `GET /advisor/recommendations`, `POST /advisor/execute-rebalances`.
CLI: `beignet rebalance <from> <to> <sats> --max-fee <sats>`, `beignet advisor recommendations`, `beignet advisor execute-rebalances [--budget <sats>]`.

</details>

<details>
<summary><b>Watchtowers (altruist client)</b></summary>

Penalty enforcement normally needs this node's chain monitor to be online: if a counterparty broadcasts a revoked commitment while you are offline, nobody sweeps the breach. The watchtower client closes that gap. At every revocation it builds an encrypted justice kit (the revoked commitment's breach hint plus a pre-signed to_local penalty) and ships it to remote towers over BOLT 8. When a tower later sees the breach on chain it decrypts the kit and broadcasts the penalty for you.

```typescript
const node = await BeignetNode.create({
  mnemonic,
  network: 'mainnet',
  watchtowers: ['03abc...@tower.example.com:9911'] // off when empty
});
```

- **Altruist only.** Sessions use `reward = 0`. There is no server mode: beignet is a tower client, not a tower.
- **LND-tower compatible.** Implements LND's `wtwire` protocol (Init/CreateSession/StateUpdate/DeleteSession, message types 600-607) and both justice blob versions (XChaCha20-Poly1305, breach hint `SHA256(txid)[:16]`, key `SHA256(txid‖txid)`), so it works with existing public LND altruist towers.
- **Legacy, anchor and taproot channels.** The to_local revocation penalty (the fund-critical punishment) is packed for all three. Legacy and anchor channels use the version-0 kit; simple taproot channels use the version-1 kit (schnorr signatures). An LND tower accepts one blob type per session, so the client runs a separate session per blob type against each tower.
- **Taproot needs a tower that accepts it.** An LND v0.20 tower does (tested live). A tower that refuses the taproot blob type (`CreateSession` code 64) gets no taproot backups: they stay queued and are offered again on the next connection, while legacy and anchor backups to that tower keep flowing.
- **Durable.** Per-tower session state and the un-acked backlog are persisted (encrypted at rest) and drained with exponential backoff on reconnect. An un-acked update is never dropped silently.

Daemon: `GET /watchtowers`, `POST /watchtower/add`, `DELETE /watchtower/remove`.
CLI: `beignet watchtower list|add <pubkey@host:port>|remove <uri>`, daemon flag `--watchtower` (repeatable) or `BEIGNET_WATCHTOWERS`.

</details>

## HTTP daemon & CLI

The same node runs as an HTTP/SSE daemon for language-agnostic integrations, driven by a JSON CLI.

```bash
# 1. Generate a mnemonic, an API token and ~/.beignet/config.json
npx beignet init --network regtest
# {"ok":true,"result":{"message":"Initialized","mnemonic":"...","network":"regtest",
#   "apiToken":"3f9c...64 hex...","note":"apiToken was generated and saved to config.json; ..."}}

# 2. Start the daemon (add --daemon to background it). It reads the token from
#    config.json; --api-token or BEIGNET_API_TOKEN override it.
BEIGNET_ELECTRUM_HOST=127.0.0.1 BEIGNET_ELECTRUM_PORT=60001 BEIGNET_ELECTRUM_TLS=false \
  npx beignet start --network regtest

# 3. Drive it with the CLI (thin HTTP client, JSON out; it sends the token itself)
npx beignet info --pretty
npx beignet address
npx beignet channel connect-and-open <pubkey> <host> <port> 200000
npx beignet invoice create 1000 "coffee"
npx beignet invoice pay <bolt11>
```

Electrum and most other settings come from `~/.beignet/config.json` or the environment (`BEIGNET_MNEMONIC`, `BEIGNET_ELECTRUM_HOST`, `BEIGNET_ELECTRUM_PORT`, `BEIGNET_NETWORK`, ...). Run `npx beignet help` for the full command and flag list.

`config.json` holds the mnemonic, so everything under `~/.beignet` is created owner-only (`0700` directories, `0600` files: config, pid file, database and sidecars, backups, SCB exports), the CLI runs `init`, `start`, `backup` and `restore` under umask `077`, and a config file an earlier release left readable is tightened the next time it is read, with a notice on stderr. Details in [src/cli/README.md](src/cli/README.md#file-permissions).

Or over HTTP directly, with the token `init` printed (or `apiToken` from `~/.beignet/config.json`):

```bash
TOKEN=3f9c...   # the apiToken from beignet init
curl -X POST http://localhost:2112/invoice/create -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"amountSats": 1000, "description": "coffee"}'

curl -X POST http://localhost:2112/invoice/pay -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"bolt11": "lnbcrt10n1..."}'

curl -N http://localhost:2112/events -H "Authorization: Bearer $TOKEN"  # SSE stream
curl http://localhost:2112/ready                                       # load-balancer probe
```

- Responses are `{ "ok": true, "result": {...} }` or `{ "ok": false, "error": { "code": "...", "message": "..." } }`.
- Full spec at `GET /openapi.json`.
- Authentication is on for every install `beignet init` creates (releases after 0.22.0): `init` mints a random `apiToken` and saves it in `config.json` (run `init` again on an older config to add one). Auth is off only for a config with neither `apiToken` nor `apiKeys` (named keys with `readonly`/`invoice`/`admin` scopes); `beignet start` warns on stderr in that case. `GET /health`, `/ready` and `/openapi.json` are auth-exempt; `/metrics` only with `metricsPublic`; everything else requires the bearer token. The daemon binds `127.0.0.1` by default.
- While auth is off, three browser guards keep a web page from driving the loopback daemon (issue #1005): a request body must be `Content-Type: application/json` (else `415 UNSUPPORTED_MEDIA_TYPE`), an `Origin` other than the configured `cors` origin or a `Sec-Fetch-Site: cross-site` request is refused (`403 CROSS_SITE_REQUEST_REFUSED`), and the `Host` header must be the loopback name the daemon is bound on (else `421 HOST_NOT_ALLOWED`, which also defeats DNS rebinding). They apply to every route but `OPTIONS`; plain clients (curl, the CLI, the SDKs) send none of those headers and are unaffected, and with a token configured the guards do not run at all.
- Embed it instead of shelling out: `import { startDaemon } from 'beignet/daemon'`.

### FFOR offline receive

Fast-Forward Offline Receive (spec: github.com/coreyphillips/ffor, Variant D) lets a
wallet receive while offline through a settlement peer that holds a pre-signed
voucher book. The daemon exposes the receiver's lifecycle under `/ffor/*`
(`/ffor/epoch/start`, `/ffor/invoice`, `/ffor/epoch/close`, `/ffor/preimage`,
`/ffor/witness/provision`, `/ffor/issuer/offer`, `/ffor/issuer/provision`,
`/ffor/sync`, `/ffor/recover`, `/ffor/enforce`, `/ffor/epochs`, `/ffor/epoch`,
`/ffor/witness/close`, `/ffor/issuer/issued`) and three roles a
node can run for others, each an explicit opt-in switched on with an exact
`true`:

| Env | Role |
|---|---|
| `BEIGNET_FFOR_SETTLE` | Answer `ff_init` as a settlement peer. `BEIGNET_FFOR_MAX_BUDGET_MSAT`, `BEIGNET_FFOR_MAX_EPOCH_BLOCKS`, `BEIGNET_FFOR_FEE_BASE_MSAT` and `BEIGNET_FFOR_FEE_PPM` bound what it accepts. Off by default: an epoch locks the whole budget of this node's liquidity. `GET /ffor/settlements` lists them. |
| `BEIGNET_FFOR_WITNESS` | Store a receiver-encrypted record of every delegated preimage this node relays before propagating the fulfil (a receipt witness). `BEIGNET_FFOR_WITNESS_MAX_MAILBOXES` and `BEIGNET_FFOR_WITNESS_MAX_BYTES` cap it. `GET /ffor/witness/status`. |
| `BEIGNET_FFOR_ISSUER` | Answer BOLT 12 invoice requests for offers a receiver delegated to this node, one fixed-amount slot per invoice. Needs the witness. `GET /ffor/issuer/status`. |

The SSE stream carries every `ffor:*` event (see the [events table](src/cli/README.md#events)).

The experimental concurrent profile keeps ordinary payments available
within the channel's remaining capacity. `LightningNode.fforSync()` fetches paid
slot receipts and redeems them while other vouchers remain live.
`rescueFforEpoch()` syncs a connected concurrent book without retiring it.
Feature bits 442/443 are advertised by default when their dependencies are enabled.
See [concurrent receive and reserved retirement](docs/FFOR-RESERVED-RETIREMENT.md)
for the version 1 and 2 contracts and storage requirements. The daemon enables
advertisement with `BEIGNET_FFOR_CONCURRENT=true` and new concurrent settlement
with `BEIGNET_FFOR_SETTLE_CONCURRENT=true`; both default to true. Set either to
`false` to disable it. Settlement still requires its separate role to be enabled. The automatic coordinator can reuse a funded home channel when
the peers negotiate concurrent settlement. See the
[automatic receive API](docs/AUTOMATIC-OFFLINE-RECEIVE.md#concurrent-receive)
for sync, retirement and reserved-capacity fields.

### Swaps (Lightning to on-chain, and on-chain to Lightning)

A beignet node can serve swaps to any Lightning peer in both directions.
Reverse (issue #737): the peer pays a hold invoice, this node funds a P2WSH
contract the peer claims on chain with its preimage, and the claim settles
the hold. Submarine (issue #743): the peer locks coins in a P2WSH contract,
this node pays the peer's own invoice under an absolute HTLC expiry ceiling,
and the preimage that payment reveals claims the coins. Each direction is an
explicit opt-in switched on with an exact `true`, because it puts this node's
own funds at risk for peers:

| Env | Role |
|---|---|
| `BEIGNET_SWAPS` | Serve reverse swaps. `BEIGNET_SWAP_FLAT_FEE_SAT` and `BEIGNET_SWAP_FEE_PPM` price them; `BEIGNET_SWAP_MIN_SAT`, `BEIGNET_SWAP_MAX_SAT`, `BEIGNET_SWAP_MAX_EXPOSURE_SAT` and `BEIGNET_SWAP_MAX_CONCURRENT` cap what is at risk; `BEIGNET_SWAP_REFUND_DELTA_BLOCKS`, `BEIGNET_SWAP_FUNDING_CONFS` and `BEIGNET_SWAP_RESOLUTION_CONFS` set the timing. `GET /swaps/status`, `GET /swaps`, `POST /swaps/cancel`. |
| `BEIGNET_SWAP_SUBMARINE` | With `BEIGNET_SWAPS`, also serve submarine swaps (on-chain to Lightning): a peer locks coins in a contract, this node pays the peer's invoice under an absolute HTLC expiry ceiling and claims the coins with the preimage. `BEIGNET_SWAP_CLAIM_SAFETY_BLOCKS`, `BEIGNET_SWAP_PAYMENT_MAX_FEE_PPM`, `BEIGNET_SWAP_CLAIM_BUMP_INTERVAL_BLOCKS` and `BEIGNET_SWAP_SUBMARINE_REFUND_DELTA_BLOCKS` set the direction's margins; the fee and exposure caps above apply to both. |

The reverse provider funds only against the complete committed MPP set of
the hold invoice, settles the hold the moment a claim reveals the preimage
(mempool included), and cancels the hold only after its own refund has
confirmed to policy depth; never because the refund height passed. The
submarine provider pays only once the peer's funding has confirmed to policy
depth and been re-verified unspent immediately before the dispatch, binds
every HTLC of the payment to `refundHeight` minus its claim margins, judges
the payment by the node's own HTLC view (never by a wall clock or a failed
record while an HTLC is out), and persists its claim before broadcasting it.
The SSE stream carries every `swap:*` event of both directions (see the
[events table](src/cli/README.md#events)).

## Protocol layer (advanced)

Use this only if you need the BOLT layer directly: bigint msat, Buffer IDs, raw wire messages. `beignet/lightning` exports **namespaces**, not flat symbols.

```typescript
import net from 'net';
import tls from 'tls';
import { Wallet, generateMnemonic } from 'beignet';
import { invoice, node as ln, wallet as lnWallet } from 'beignet/lightning';

const mnemonic = generateMnemonic();

// 1. On-chain wallet (the same mnemonic funds both layers)
const res = await Wallet.create({ mnemonic, electrumOptions: { net, tls } });
if (res.isErr()) throw res.error;

// 2. Lightning node with auto-funding from the wallet
const node = ln.LightningNode.fromMnemonic(mnemonic, {
  network: invoice.Network.REGTEST,
  enableNetworking: true,
  fundingProvider: new lnWallet.WalletFundingProvider(res.value)
});

// 3. Connect and open: fully automatic with a funding provider
await node.connectPeer('03...pubkey', '127.0.0.1', 9735);
node.openChannel('03...pubkey', 100_000n);

// 4. Invoice and payment
node.createInvoice({ amountMsat: 50_000n, description: 'coffee' });
node.sendPayment(invoiceString);

// 5. Events. Channel-scoped events carry an object, not a bare id
node.on('channel:ready', ({ channelId }) => console.log(channelId.toString('hex')));
node.on('payment:received', (p) => console.log(p.amountMsat, 'msat'));
node.on('node:error', (err) => console.error(`[${err.code}]`, err.message));
```

Without a `fundingProvider`, build the funding transaction yourself and call `node.createFunding(channel, fundingTxid, outputIndex, signature)` after `openChannel`.

```
LightningNode              High-level API (typed EventEmitter)
  ├── ChannelManager       Multiplexes messages to Channel instances
  │     ├── Channel        BOLT 2 state machine (returns ChannelAction[])
  │     └── ChainMonitor   BOLT 5 force-close detection + sweep
  ├── PeerManager          TCP/WebSocket connections + Noise_XK encrypted transport
  │     └── Peer           Per-connection BOLT 8 handshake + message framing
  ├── NetworkGraph         BOLT 7 gossip topology + Dijkstra pathfinding
  ├── invoice (module)     BOLT 11 encode/decode/sign functions
  └── FundingProvider?     Auto-builds + broadcasts funding txs (via Wallet)
```

**Key design principle:** `Channel` is fully transport-agnostic. Every method returns a `ChannelAction[]` (send message, broadcast tx, watch output, ...) that `ChannelManager` maps to real transport or chain operations, which makes the state machine testable without network I/O.

**→ [src/lightning/README.md](src/lightning/README.md)** documents the protocol layer in detail: data flow, events reference, typed payment errors, channel lifecycle, zero-conf, anchors, dual funding, splicing, offers, onion messages, forwarding, chain monitoring.

The protocol-layer README has the [BOLT coverage table](src/lightning/README.md#bolt-specification-coverage) and the [module reference](src/lightning/README.md#module-reference), one row per module of `src/lightning/` with its key exports. `beignet/lightning` re-exports each module as a namespace, camel-casing hyphenated names: `import { asyncPayments, ffor, watchtower } from 'beignet/lightning'`.

`SqliteStorage` and `GuardianStore` load from `beignet/lightning/sqlite`. They need `better-sqlite3`, an optional dependency that npm installs by default, and `beignet/lightning` loads without it.

## Tests

Use **Node.js 24 (24.22.1+)** for development and `npm ci` to install the locked tools.
CI uses Node.js 24.22.1.

The lint configuration keeps the established CommonJS imports, enum aliases,
unused catch bindings, `any` warnings and Chai assertion style. Rules removed
from the upgraded linter's recommended preset remain explicitly enabled where
they were enforced before. Prettier covers TypeScript semicolons, with the core
semicolon rule retained for JavaScript. Typed promise checks remain enabled for
every TypeScript file.

```bash
npm test                   # same as test:local
npm run test:local         # build, then test:lightning + test:cli at once; no infrastructure needed
npm run coverage           # test:local under c8, with a coverage summary of src
npm run test:lightning     # 9500+ Lightning unit tests (parallel), no infrastructure needed
npm run test:cli           # 2400+ CLI + daemon unit tests (parallel), no infrastructure needed; run npm run build first
npm run test:conformance   # 300+ official BOLT vector cases (subset of test:lightning)
npm run test:chaos         # recovery kill matrices (parallel), split out of test:lightning
npm run test:sigkill       # process-level SIGKILL chaos matrix (builds dist first)
npm run test:full-channel  # an asset channel full of HTLCs on the chain, 20 each way (minutes a case), split out of test:lightning
npm run test:api           # exported API vs tests/api-snapshot (npm run api:snapshot regenerates it)
npm run test:direct-funding # standalone payer SDK, wallet adapters and packaging
npm run test:direct-funding:regtest # real Core wallets and funding transactions (needs Docker)
npm run test:integration   # daemon/Electrum integration (needs an Electrum server)
npm run test:interop       # 300+ cases vs LND/CLN/Eclair (needs Docker)
npm run test:interop:ffor  # FFOR Variant D chain gates on regtest (needs only the bitcoind container)
npm run test:interop:ffor-concurrent  # Concurrent receive process, durable boundary and current-chain qualification (bitcoind regtest)
```

Counts are floors, not snapshots, and this is the only place they are kept. Run the suites for exact numbers (`npx mocha --dry-run` with a suite's arguments counts without running).

`test:cli` spawns the built `dist/cli/cli.js`, so its spawn tests fail with a
message to run `npm run build` when `dist/` is missing or older than `src/`.
`test:local` builds first.

`test:local` is the fast inner loop. `test:lightning` and `test:cli` are
independent processes and neither saturates the machine alone, so running them at
once beats running them in sequence. Measured on 8 cores: 195.6s in sequence
before this existed, 106.1s in sequence once `test:cli` gained `--parallel`, and
**77.1s together**. It prints a per-suite summary and, on
failure, the failing suite's output.

`test:chaos` is deliberately not in that bundle. Its cases carry real wall-clock
budgets that do not care how loaded the box is (`chaosWait` defaults to 15s, the
quorum barrier to 20s), and sharing the machine ate one of them: running all
three concurrently failed with `chaosWait timed out with the victim alive` while
the same suite passes 30/30 on its own. Run it separately. See
`scripts/run-suites.js` for the worker split and why more workers is not better.

`npm run coverage` prints a line, branch and function summary for `src`, and
writes per-file numbers to `coverage/coverage-summary.json` and per-line hits to
`coverage/lcov.info`. On master pushes, CI prints a summary at the end of each
lightning shard and of its `test:cli` step; pull request runs skip c8. The numbers are information, not a gate:
no threshold is set, and nothing fails on a percentage. A file the run never
loads counts as wholly uncovered. Two runs of the same tree can differ by a few
covered lines, because tests with random keys reach different branches. c8 also
counts a comment or type declaration as covered when the code around it ran.

The on-chain wallet suites live in `tests/*.test.ts` and connect to **live public
Electrum servers**, so they need network access and can fail on a server outage
rather than on your change. Each script runs `npm run build` first:

```bash
npm run test:wallet        # also test:transaction, test:electrum, test:storage,
                           # test:derivation, test:receive, test:boost
```

The on-chain files without a dedicated script (multisig, PSBT, watch-only,
descriptors, signet and others) run through mocha directly:

```bash
npx mocha --exit -r ts-node/register 'tests/multisig.test.ts'
```

`test:conformance` runs the official BOLT test vectors (BOLT 1 bigsize/TLV, BOLT 3 commitments and anchors and per-commitment secrets, BOLT 4 onion/route-blinding/onion-errors, BOLT 7 extended queries, BOLT 8 transport, BOLT 11 invoices, BOLT 12 offers/signatures) under `tests/lightning/conformance/`.

<details>
<summary><b>Interop testing against real implementations</b></summary>

The interop suite drives beignet against real nodes on Bitcoin regtest.

```bash
docker compose -f docker/docker-compose.yml up -d   # wait ~30s for nodes to sync
npm run test:interop
```

Services in `docker/docker-compose.yml`:

| Service | Image | Ports |
|---------|-------|-------|
| bitcoind | Bitcoin Core 31.0 (regtest) | RPC 43782, ZMQ 28334/28335/28336 |
| lnd | `lightninglabs/lnd:v0.20.0-beta` | P2P 9735, REST 8081 |
| cln | `elementsproject/lightningd:v26.06.1` | CLNRest 3010 |
| eclair | 0.14.1, built locally from the release zip (`docker/eclair/Dockerfile`) | HTTP API 8082 |
| electrs | `getumbrel/electrs:v0.10.10` | Electrum 60001 |

The LND helpers read `LND_REST_HOST` / `LND_REST_PORT` (default `127.0.0.1:8081`) and `LND_P2P_HOST` / `LND_P2P_PORT` (default `127.0.0.1:9735`); the dedicated taproot container reads `LND_TAPROOT_REST_HOST` / `LND_TAPROOT_REST_PORT` (default `127.0.0.1:8082`) and `LND_TAPROOT_P2P_HOST` / `LND_TAPROOT_P2P_PORT` (default `127.0.0.1:9736`). Point them at whatever your `docker/docker-compose.override.yml` publishes, for example `LND_REST_PORT=8091 npm run test:interop`.

An LND suite that has no usable counterparty skips itself and prints one line naming the suite, the endpoint it probed and the variables that move it (`[skip] lnd-jit-receive: LND REST not reachable at 127.0.0.1:8081 (set LND_REST_PORT / LND_REST_HOST)`, or `... LND reachable but macaroon read failed (docker exec lnd ...)`). A skip is invisible in a passing summary, so for a pre-release gate set `INTEROP_REQUIRE_LND=1` (and `INTEROP_REQUIRE_LND_TAPROOT=1` for the taproot suites): the same condition then fails the suite with that reason instead of skipping it.

Covered per implementation: BOLT 8 handshake and BOLT 1 init/feature negotiation, disconnect/reconnect and ping/pong survival, channel open in both directions, bidirectional payments and payment_secret validation, MPP, SCID aliases, cooperative close, reestablish, gossip sync, inbound connections, anchor channels, anchor force-close with wallet-funded CPFP and HTLC-timeout fee-attach, and crash recovery. Beyond the shared matrix: taproot channel lifecycle vs LND (open, pay both directions, reestablish, coop and force close, penalty, SCB recovery), splice matrix and lease/liquidity-ads flows vs CLN, `simple_close` vs Eclair, blinded-path payments, and the watchtower client vs an LND tower.

Interop tests are excluded from `npm run test:lightning`.

</details>

## Status & limitations

Beignet is under active development. Known gaps and caveats:

| Feature | Status | Detail |
|---------|--------|--------|
| Mainnet battle-testing | Limited | Interop-tested on regtest, with some flows validated live on mainnet. Exercise caution with large balances. |
| Watchtowers | Client only (altruist) | Punishes breaches while you are offline via remote LND altruist towers. Legacy, anchor and taproot channels are backed up, each blob type in its own session. Taproot backups need a tower that accepts the taproot blob type, and stay queued at one that refuses it. No server mode. |
| LSP / LSPS protocols | Not implemented | No automated inbound liquidity via LSPS0/1/2. Liquidity ads (bLIP-51) cover negotiated leases; otherwise open channels manually. |
| Trampoline routing | Not implemented | All route computation is local. |
| BOLT 12 offers | Newer | Offers, invoice_request/invoice over onion messages and receive-side settlement work, but the surface is less battle-tested than BOLT 11. Prefer BOLT 11 in production. |
| Async payments | LSP-dependent | Hold invoices plus AsyncPaymentManager let an offline receiver be paid, but the receiver's LSP must run the held-forward/wake flow. |
| Simple taproot channels | Experimental | Full lifecycle validated against LND v0.20 on regtest, but the feature bit is still in staging upstream. Not recommended for mainnet balances. |
| Splicing / dual funding | Partial | Validated against CLN on regtest (`cln-splice-matrix.test.ts`): splice-out, repeat splices on a spliced channel, payments over it, CLN-initiated splices with beignet as acceptor, multi-UTXO and third-party-input splice-ins, and resume after a mid-splice disconnect. Splice-in and splice-out were also validated live against CLN on mainnet. v2 dual-funded opens are implemented both as initiator and acceptor. Not yet supported: splice RBF ([#765](https://github.com/coreyphillips/beignet/issues/765)) and splicing taproot channels ([#150](https://github.com/coreyphillips/beignet/issues/150)). |
| Mobile background | Limited | Works on React Native but has no background sync or push-notification support. |

Recommended safeguards in production:

- Cap exposure with `maxPaymentSats` and `dailySpendLimitSats`. Both count a
  payment's amount plus its routing-fee cap, so the fee cannot slip past them:
  the cap is `maxFeeSats`/`maxFeeMsat` when you pass one, and 1% of the
  amount (never below 50 sats) when you do not. Both also cover external
  on-chain sends (amount plus fee); see the Spending Limits section of
  `src/cli/README.md`.
- Call `validatePayment()` before every send.
- Set `backupPath` for automated database backups, and keep an SCB (`beignet backup scb`).
- Keep `~/.beignet` and the data directory owner-only. The CLI creates them `0700`/`0600` and tightens an older config on load; check them again after copying files between hosts.
- Pass multiple `electrumServers` for connection redundancy.
- Configure watchtowers so breaches are punished while you are offline.
- Monitor `node:error` events and the `/health` endpoint.
- Start with small channels and increase gradually.

## React Native

`react-native-tcp-socket` is a drop-in replacement for `net` and `tls`:

```json
{
  "react-native": {
    "net": "react-native-tcp-socket",
    "tls": "react-native-tcp-socket"
  }
}
```

`BeignetNode` runs there from `beignet/node`, on storage passed in place of SQLite:

```typescript
import { BeignetNode } from 'beignet/node';
import { storage } from 'beignet/lightning';

const node = await BeignetNode.create({
  network: 'mainnet',
  mnemonic,
  storage: new storage.MemoryStorage(), // or a backend over the app's database
});
```

Neither entry loads `fs`, `net`, `tls` or better-sqlite3 when imported. The node requires `net` and `tls` when it opens a connection, and `fs` only for a `dataDir`, which a node on `storage` does not need. Both entries still import `crypto`, `path`, `os`, `dns`, `http`, `https` and `zlib`, so the bundle needs a substitute for each.

The backend must implement the `walletData` capability: the node keeps its wallet state, spend ledger and sweep journal there. `MemoryStorage` loses everything when the app exits, so a wallet needs a backend over a persistent store; [src/lightning/README.md](src/lightning/README.md) describes the interface and its conformance suite. On such a node the payment queue lives in memory, and what copies or installs a SQLite file (`backupPath`, `backup()`, capsule restore) is refused.

Nothing in the `beignet` entry loads Node `crypto` until `createEncryptedStorage` is first called. It then needs HKDF-SHA256, random bytes and AES-256-GCM. An app that encrypts wallet storage either ships a `crypto` shim that covers those, or passes its own implementation (of the `ICryptoProvider` interface) to `setCryptoProvider` before the first call. Each primitive is checked against a known-answer vector before its first use, and one that fails throws an error naming it rather than returning wrong bytes. The check catches a missing or broken primitive, not a weak one: no test can tell predictable random bytes from secure ones, so a provider's `randomBytes` must come from the platform's secure generator.

## Documentation

[docs/README.md](docs/README.md) indexes every guide, reference and design document in the repository.

The API reference for every entry point (`beignet`, `beignet/node`, `beignet/daemon`, `beignet/cli`, `beignet/lightning`, `beignet/lightning/sqlite`, `beignet/lightning/iroh-node`, `beignet/direct-funding`, `beignet/direct-funding/node`) is generated by typedoc and not kept in git. CI builds it on every run and uploads it as the `api-docs` artifact of the docs workflow; `npm run docs:html` (or `docs:markdown`) builds it locally into `api-docs/`.

## Support

Open an issue, or reach out on [Telegram](https://t.me/bitkitchat).

## Security

Report a vulnerability privately, as [SECURITY.md](SECURITY.md) describes, and not in a public issue.

## Contributing

[CONTRIBUTING.md](CONTRIBUTING.md) covers setup, the checks CI runs, and the rules for pull requests.

## License

MIT

---
_Source: https://npm.io/package/beignet · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
