ln-service
Version:
Interaction helper for your Lightning Network daemon
1,622 lines (1,217 loc) • 251 kB
Markdown
# Lightning Network Service
[](https://badge.fury.io/js/ln-service)
## Overview
The core of this project is a gRPC interface for node.js projects, available
through npm.
Supported LND versions:
- v0.19.0-beta to v0.19.1-beta
- v0.18.0-beta to v0.18.5-beta
- v0.17.0-beta to v0.17.5-beta
- v0.16.0-beta to v0.16.4-beta
- v0.15.2-beta to v0.15.5-beta
- v0.14.4-beta to v0.14.5-beta
For typescript-ready methods, check out https://github.com/alexbosworth/lightning#readme
## Installing LND
There is a guide to installing LND on the LND repository:
https://github.com/lightningnetwork/lnd/blob/master/docs/INSTALL.md
Example LND configuration options (~/.lnd/lnd.conf)
```ini
[Application Options]
externalip=IP
rpclisten=0.0.0.0:10009
[Bitcoin]
bitcoin.active=1
bitcoin.mainnet=1
bitcoin.node=bitcoind
```
If you are interacting with your node remotely, make sure to set (in
`[Application Options]`)
```ini
tlsextradomain=YOURDOMAIN
```
If you're adding TLS settings, regenerate the cert and key by stopping lnd,
deleting the tls.cert and tls.key - then restart lnd to regenerate.
If you're going to use extended gRPC APIs, make sure to add the APIs to make
tags.
```sh
make && make install tags="autopilotrpc chainrpc invoicesrpc peersrpc routerrpc signrpc walletrpc watchtowerrpc wtclientrpc"
```
## Using gRPC
You can install ln-service service via npm
npm install ln-service
To use authenticated methods you will need to provide LND credentials.
To export the credentials via a command, you can install
[balanceofsatoshis](https://github.com/alexbosworth/balanceofsatoshis):
`npm install -g balanceofsatoshis` and export via `bos credentials --cleartext`
Or you can export them manually:
Run `base64` on the tls.cert and admin.macaroon files to get the encoded
authentication data to create the LND connection. You can find these files in
the LND directory. (~/.lnd or ~/Library/Application Support/Lnd)
base64 tls.cert
base64 data/chain/bitcoin/mainnet/admin.macaroon
Be careful to avoid copying any newline characters in creds. To exclude them:
base64 -w0 ~/.lnd/tls.cert
base64 -w0 ~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon
You can then use these to interact with your LND node directly:
```node
const lnService = require('ln-service');
const {lnd} = lnService.authenticatedLndGrpc({
cert: 'base64 encoded tls.cert',
macaroon: 'base64 encoded admin.macaroon',
socket: '127.0.0.1:10009',
});
// Callback syntax
lnService.getWalletInfo({lnd}, (err, result) => {
const nodeKey = result.public_key;
});
// Promise syntax
const nodePublicKey = (await lnService.getWalletInfo({lnd})).public_key;
```
An [unauthenticatedLndGrpc](#unauthenticatedLndGrpc) function is also available
for `unlocker` methods.
## Subscriptions
- Besides the events listed in this documentation, all `EventEmitter` objects
returned by any of the `subscribeTo...` methods also offer an `error`
event. This event is triggered e.g. when LND is shut down. So, in order to
detect and correctly handle such a situation, robust client code should
generally also add a listener for the `error` event. For example, a
function that will wait for and return the next forward but throw an
exception when LND is either not reachable or shuts down while waiting for
the forward would look something like this:
``` node
const getNextForward = async (lnd) => {
const emitter = subscribeToForwards({ lnd });
try {
return await new Promise((resolve, reject) => {
emitter.on("forward", resolve);
// Without the following line, the function will never throw
// when the connection is lost after calling subscribeToForwards
emitter.on("error", reject);
});
} finally {
emitter.removeAllListeners();
}
};
```
- After the last listener has been removed from an `EventEmitter` object, the
subscription is released and subsequent attempts to add a listener will
result in an error. Call `subscribeTo...` again and add new listeners to the
new `EventEmitter` object.
## All Methods
- [addAdvertisedFeature](#addadvertisedfeature) - Advertise a supported feature
- [addExternalSocket](#addexternalsocket) - Advertise a new p2p host:ip address
- [addPeer](#addpeer) - Connect to a peer
- [authenticatedLndGrpc](#authenticatedlndgrpc) - LND API Object
- [beginGroupSigningSession](#begingroupsigningsession) - Start MuSig2 session
- [broadcastChainTransaction](#broadcastchaintransaction) - Push a chain tx
- [cancelHodlInvoice](#cancelhodlinvoice) - Cancel a held or any open invoice
- [cancelPendingChannel](#cancelpendingchannel) - Cancel a pending open channel
- [changePassword](#changepassword) - Change the wallet unlock password
- [closeChannel](#closechannel) - Terminate an open channel
- [connectWatchtower](#connectwatchtower) - Connect a watchtower
- [createChainAddress](#createchainaddress) - Get a chain address to receive at
- [createFundedPsbt](#createfundedpsbt): Create a funded PSBT given inputs and
outputs
- [createHodlInvoice](#createhodlinvoice) - Make a HODL HTLC invoice
- [createInvoice](#createinvoice) - Make a regular invoice
- [createSeed](#createseed) - Generate a wallet seed for a new wallet
- [createSignedRequest](#createsignedrequest) - create a signed payment request
- [createUnsignedRequest](#createunsignedrequest) - create an unsigned invoice
- [createWallet](#createwallet) - Make a new wallet
- [decodePaymentRequest](#decodepaymentrequest) - Decode a Lightning invoice
- [deleteChainTransaction](#deletechaintransaction) - Remove chain transaction
- [deleteFailedPayAttempts](#deletefailedpayattempts) - Remove records of
failed pay attempts
- [deleteFailedPayments](#deletefailedpayments) - Remove records of payments
that failed
- [deleteForwardingReputations](#deleteforwardingreputations) - Wipe node reps
- [deletePayment](#deletepayment) - Delete the record of a single past payment
- [deletePayments](#deletepayments) - Delete entire history of past payments
- [deletePendingChannel](#deletependingchannel) - Delete a pending channel that
will never confirm due to a conflicting confirmed transaction
- [diffieHellmanComputeSecret](#diffiehellmancomputesecret) - Get DH shared key
- [disableChannel](#disablechannel) - Disable a channel for outgoing payments
- [disconnectWatchtower](#disconnectwatchtower) - Disconnect a watchtower
- [enableChannel](#enablechannel) - Enable a channel for outgoing payments
- [endGroupSigningSession](#endgroupsigningsession) - Complete MuSig2 session
- [fundPendingChannels](#fundpendingchannels) - Fund pending open channels
- [fundPsbt](#fundpsbt) - Create an unsigned PSBT with funding inputs and
spending outputs
- [getAccessIds](#getaccessids) - Get granted macaroon root access ids
- [getAutopilot](#getautopilot) - Get autopilot status or node scores
- [getBackup](#getbackup) - Get a backup of a channel
- [getBackups](#getbackups) - Get a backup for all channels
- [getBlock](#getblock) - Get the raw block data given a block id in the chain
- [getBlockHeader](#getblockheader) - Get the raw block header for a block
- [getChainAddresses](#getchainaddresses) - Get created chain addresses
- [getChainBalance](#getchainbalance) - Get the confirmed chain balance
- [getChainFeeEstimate](#getchainfeeestimate) - Get a chain fee estimate
- [getChainFeeRate](#getchainfeerate) - Get the fee rate for a conf target
- [getChainTransaction](#getchaintransaction) - Get single wallet transaction
- [getChainTransactions](#getchaintransactions) - Get all chain transactions
- [getChannel](#getchannel) - Get graph information about a channel
- [getChannelBalance](#getchannelbalance) - Get the balance of channel funds
- [getChannels](#getchannels) - Get all open channels
- [getClosedChannels](#getclosedchannels) - Get previously open channels
- [getConfiguration](#getconfiguration) - Get configuration information
- [getConnectedWatchtowers](#getconnectedwatchtowers) - Get connected towers
- [getEphemeralChannelIds](#getephemeralchannelids) - Get other channel ids
- [getFailedPayments](#getfailedpayments) - Get payments that were failed back
- [getFeeRates](#getfeerates) - Get current routing fee rates
- [getForwardingConfidence](#getforwardingconfidence) - Get pairwise confidence
- [getForwardingReputations](#getforwardingreputations) - Get graph reputations
- [getForwards](#getforwards) - Get forwarded routed payments
- [getHeight](#getheight) - Get the current best chain height and block hash
- [getIdentity](#getidentity) - Get the node's identity key
- [getInvoice](#getinvoice) - Get a previously created invoice
- [getInvoices](#getinvoices) - Get all previously created invoices
- [getLockedUtxos](#getlockedutxos) - Get all previously locked UTXOs
- [getMasterPublicKeys](#getmasterpublickeys) - Get a list of master pub keys
- [getMethods](#getmethods) - Get available methods and associated permissions
- [getNetworkCentrality](#getnetworkcentrality) - Get centrality score for nodes
- [getNetworkGraph](#getnetworkgraph) - Get the channels and nodes of the graph
- [getNetworkInfo](#getnetworkinfo) - Get high-level graph info
- [getNode](#getnode) - Get graph info about a single node and its channels
- [getPathfindingSettings](#getpathfindingsettings) - Get pathfinding system
settings
- [getPayment](#getpayment) - Get a past payment
- [getPayments](#getpayments) - Get all past payments
- [getPeers](#getpeers) - Get all connected peers
- [getPendingChainBalance](#getpendingchainbalance) - Get pending chain balance
- [getPendingChannels](#getpendingchannels) - Get channels in pending states
- [getPendingPayments](#getpendingpayments) - Get in-flight outgoing payments
- [getPendingSweeps](#getpendingsweeps) - Get sweeps waiting for resolution
- [getPublicKey](#getpublickey) - Get a public key out of the seed
- [getRouteConfidence](#getrouteconfidence) - Get confidence in a route
- [getRouteThroughHops](#getroutethroughhops) - Get a route through nodes
- [getRouteToDestination](#getroutetodestination) - Get a route to a destination
- [getRoutingFeeEstimate](#getroutingfeeestimate) - Get offchain fee estimate
- [getSettlementStatus](#getsettlementstatus) - Get status of a received HTLC
- [getSweepTransactions](#getsweeptransactions) - Get transactions sweeping to
self
- [getTowerServerInfo](#gettowerserverinfo) - Get information about tower server
- [getUtxos](#getutxos) - Get on-chain unspent outputs
- [getWalletInfo](#getwalletinfo) - Get general wallet info
- [getWalletStatus](#getwalletstatus) - Get the status of the wallet
- [getWalletVersion](#getwalletversion) - Get the build and version of the LND
- [grantAccess](#grantaccess) - Grant an access credential macaroon
- [grpcProxyServer](#grpcproxyserver) - REST proxy server for calling to gRPC
- [isDestinationPayable](#isdestinationpayable) - Check can pay to destination
- [lockUtxo](#lockutxo) - Lock a UTXO temporarily to prevent it being used
- [openChannel](#openchannel) - Open a new channel
- [openChannels](#openchannels) - Open channels with external funding
- [parsePaymentRequest](#parsepaymentrequest) - Parse a BOLT11 Payment Request
- [partiallySignPsbt](#partiallysignpsbt) - Sign a PSBT without finalizing it
- [pay](#pay) - Send a payment
- [payViaPaymentDetails](#payviapaymentdetails) - Pay using decomposed details
- [payViaPaymentRequest](#payviapaymentrequest) - Pay using a payment request
- [payViaRoutes](#payviaroutes) - Make a payment over specified routes
- [prepareForChannelProposal](#prepareforchannelproposal) - setup for a channel
proposal
- [probeForRoute](#probeforroute) - Actively probe to find a payable route
- [proposeChannel](#proposechannel) - Offer a channel proposal to a peer
- [recoverFundsFromChannel](#recoverfundsfromchannel) - Restore a channel
- [recoverFundsFromChannels](#recoverfundsfromchannels) - Restore all channels
- [removeAdvertisedFeature](#removeadvertisedfeature) - Remove feature from ad
- [removeExternalSocket](#removeexternalsocket) - Remove a p2p host:ip announce
- [removePeer](#removepeer) - Disconnect from a connected peer
- [requestBatchedFeeIncrease](#requestbatchedfeeincrease) - Request a batched
CPFP spend on an unconfirmed outpoint
- [requestChainFeeIncrease](#requestchainfeeincrease) - Request a CPFP spend on
a UTXO
- [restrictMacaroon](#restrictmacaroon) - Add limitations to a macaroon
- [revokeAccess](#revokeaccess) - Revoke all access macaroons given to an id
- [routeFromChannels](#routefromchannels) - Convert channel series to a route
- [sendMessageToPeer](#sendmessagetopeer) - Send a custom message to a peer
- [sendToChainAddress](#sendtochainaddress) - Send on-chain to an address
- [sendToChainAddresses](#sendtochainaddresses) - Send on-chain to addresses
- [sendToChainOutputScripts](#sendtochainoutputscripts) - Send to on-chain
script outputs
- [setAutopilot](#setautopilot) - Turn autopilot on and set autopilot scores
- [settleHodlInvoice](#settlehodlinvoice) - Accept a HODL HTLC invoice
- [signBytes](#signbytes) - Sign over arbitrary bytes with node keys
- [signChainAddressMessage](#signchainaddressmessage) - Sign with chain address
- [signMessage](#signmessage) - Sign a message with the node identity key
- [signPsbt](#signpsbt) - Sign and finalize an unsigned PSBT using internal keys
- [signTransaction](#signtransaction) - Sign an on-chain transaction
- [stopDaemon](#stopdaemon) - Stop lnd
- [subscribeToBackups](#subscribetobackups) - Subscribe to channel backups
- [subscribeToBlocks](#subscribetoblocks) - Subscribe to on-chain blocks
- [subscribeToChainAddress](#subscribetochainaddress) - Subscribe to receives
- [subscribeToChainSpend](#subscribetochainspend) - Subscribe to chain spends
- [subscribeToChannels](#subscribetochannels) - Subscribe to channel statuses
- [subscribeToForwardRequests](#subscribetoforwardrequests) - Interactively
route
- [subscribeToForwards](#subscribetoforwards) - Subscribe to HTLC events
- [subscribeToGraph](#subscribetograph) - Subscribe to network graph updates
- [subscribeToInvoice](#subscribetoinvoice) - Subscribe to invoice updates
- [subscribeToInvoices](#subscribetoinvoices) - Subscribe to all invoices
- [subscribeToOpenRequests](#subscribetoopenrequests) - Approve open requests
- [subscribeToPastPayment](#subscribetopastpayment) - Subscribe to a payment
- [subscribeToPastPayments](#subscribetopastpayments) - Subscribe to all sent
payments
- [subscribeToPayViaDetails](#subscribetopayviadetails) - Pay using details
- [subscribeToPayViaRequest](#subscribetopayviarequest) - Pay using a request
- [subscribeToPayViaRoutes](#subscribetopayviaroutes) - Pay using routes
- [subscribeToPayments](#subscribetopayments) - Subscribe to outgoing payments
- [subscribeToPeerMessages](#subscribetopeermessages) - Listen to incoming
custom messages
- [subscribeToPeers](#subscribetopeers) - Subscribe to peers connectivity
- [subscribeToProbe](#subscribetoprobe) - Subscribe to a probe for a route
- [subscribeToProbeForRoute](#subscribetoprobeforroute) - Probe for a route
- [subscribeToRpcRequests](#subscribetorpcrequests) - Subscribe to rpc requests
- [subscribeToTransactions](#subscribetotransactions) - Subscribe to chain tx
- [subscribeToWalletStatus](#subscribetowalletstatus) - Subscribe to node state
- [unauthenticatedLndGrpc](#unauthenticatedLndGrpc) - LND for locked lnd APIs
- [unlockUtxo](#unlockutxo) - Release a locked UTXO so that it can be used
again
- [unlockWallet](#unlockwallet) - Unlock a locked lnd
- [updateAlias](#updatealias) - Update node graph identity alias
- [updateChainTransaction](#updatechaintransaction) - Update a chain
transaction
- [updateColor](#updatecolor) - Update node graph color value
- [updateConnectedWatchtower](#updateconnectedwatchtower) - Update watchtower
- [updateGroupSigningSession](#updategroupsigningsession) - Sign with MuSig2
- [updatePathfindingSettings](#updatepathfindingsettings) - Update pathfinding
configuration
- [updateRoutingFees](#updateroutingfees) - Change routing fees
- [verifyAccess](#verifyaccess) - Verify a macaroon has access
- [verifyBackup](#verifybackup) - Verify a channel backup
- [verifyBackups](#verifybackups) - Verify a set of channel backups
- [verifyBytesSignature](#verifybytessignature) - Verify a signature over bytes
- [verifyChainAddressMessage](#verifychainaddressmessage) - Check chain message
- [verifyMessage](#verifymessage) - Verify a message signed by a node identity
## Additional Libraries
- [bolt01](https://npmjs.com/package/bolt01) - bolt01 messaging utilities
- [bolt03](https://npmjs.com/package/bolt03) - bolt03 transaction utilities
- [bolt07](https://npmjs.com/package/bolt07) - bolt07 channel gossip utilities
- [bolt09](https://npmjs.com/package/bolt09) - bolt09 feature flag utilities
- [invoices](https://npmjs.com/package/invoices) - bolt11 request utilities
- [lightning](https://npmjs.com/package/lightning) - methods with typescript
typing support
- [ln-accounting](https://npmjs.com/package/ln-accounting) - accounting records
- [ln-docker-daemons](https://github.com/alexbosworth/ln-docker-daemons) -
run regtest integration tests
- [ln-pathfinding](https://npmjs.com/package/ln-pathfinding) - pathfinding
utilities
- [ln-sync](https://www.npmjs.com/package/ln-sync) - metadata helper methods
- [probing](https://npmjs.com/package/probing) - payment probing utilities
- [psbt](https://www.npmjs.com/package/psbt) - BIP 174 PSBT utilities
### addAdvertisedFeature
Add an advertised feature to the graph node announcement
Note: this method is not supported in LND versions 0.14.5 and below
Requires LND built with `peersrpc` build tag
Requires `peers:write` permissions
{
feature: <BOLT 09 Feature Bit Number>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {addAdvertisedFeature} = require('ln-service');
// Add a new supported feature to the graph node announcement
await addAdvertisedFeature({lnd, feature: 12345});
```
### addExternalSocket
Add a new advertised p2p socket address
Note: this method is not supported in LND versions 0.14.5 and below
Requires LND built with `peersrpc` build tag
Requires `peers:write` permissions
{
lnd: <Authenticated LND API Object>
socket: <Add Socket Address String>
}
@returns via cbk or Promise
Example:
```node
const {addExternalSocket} = require('ln-service');
// Add a new address to advertise on the graph via gossip
await addExternalSocket({lnd, socket: '192.168.0.1:9735'});
```
### addPeer
Add a peer if possible (not self, or already connected)
Requires `peers:write` permission
`timeout` is not supported in LND 0.11.1 and below
{
[is_temporary]: <Add Peer as Temporary Peer Bool> // Default: false
lnd: <Authenticated LND API Object>
public_key: <Public Key Hex String>
[retry_count]: <Retry Count Number>
[retry_delay]: <Delay Retry By Milliseconds Number>
socket: <Host Network Address And Optional Port String> // ip:port
[timeout]: <Connection Attempt Timeout Milliseconds Number>
}
@returns via cbk or Promise
Example:
```node
const {addPeer} = require('ln-service');
const socket = hostIp + ':' + portNumber;
await addPeer({lnd, socket, public_key: publicKeyHexString});
```
### authenticatedLndGrpc
Initiate a gRPC API Methods Object for authenticated methods
Both the cert and macaroon expect the entire serialized LND generated file
{
[cert]: <Base64 or Hex Serialized LND TLS Cert>
[macaroon]: <Base64 or Hex Serialized Macaroon String>
[path]: <Path to Proto Files Directory String>
[socket]: <Host:Port String>
}
@throws
<Error>
@returns
{
lnd: {
autopilot: <Autopilot API Methods Object>
chain: <ChainNotifier API Methods Object>
default: <Default API Methods Object>
invoices: <Invoices API Methods Object>
router: <Router API Methods Object>
signer: <Signer Methods API Object>
tower_client: <Watchtower Client Methods Object>
tower_server: <Watchtower Server Methods API Object>
wallet: <WalletKit gRPC Methods API Object>
version: <Version Methods API Object>
}
}
Example:
```node
const lnService = require('ln-service');
const {lnd} = lnService.authenticatedLndGrpc({
cert: 'base64 encoded tls.cert',
macaroon: 'base64 encoded admin.macaroon',
socket: '127.0.0.1:10009',
});
const wallet = await lnService.getWalletInfo({lnd});
```
### beginGroupSigningSession
Start a MuSig2 group signing session
Requires LND built with `signrpc`, `walletrpc` build tags
Requires `address:read`, `signer:generate` permissions
This method is not supported in LND 0.14.5 and below
{
lnd: <Authenticated LND API Object>
[is_key_spend]: <Key Is BIP 86 Key Spend Key Bool>
key_family: <HD Seed Key Family Number>
key_index: <Key Index Number>
public_keys: [<External Public Key Hex String>]
[root_hash]: <Taproot Script Root Hash Hex String>
}
@returns via cbk or Promise
{
external_key: <Final Script or Top Level Public Key Hex String>
id: <Session Id Hex String>
[internal_key]: <Internal Top Level Public Key Hex String>
nonce: <Session Compound Nonces Hex String>
}
Example:
```node
const {beginGroupSigningSession} = require('ln-service');
const session = await beginGroupSigningSession({
lnd,
key_family: 0,
key_index: 0,
public_keys: [externalPublicKey],
});
```
### broadcastChainTransaction
Publish a raw blockchain transaction to Blockchain network peers
Requires LND built with `walletrpc` tag
{
[description]: <Transaction Label String>
lnd: <Authenticated LND API Object>
transaction: <Transaction Hex String>
}
@returns via cbk or Promise
{
id: <Transaction Id Hex String>
}
Example:
```node
const {broadcastChainTransaction} = require('ln-service');
const transaction = hexEncodedTransactionString;
// Broadcast transaction to the p2p network
const {id} = await broadcastChainTransaction({lnd, transaction});
```
### cancelHodlInvoice
Cancel an invoice
This call can cancel both HODL invoices and also void regular invoices
Requires LND built with `invoicesrpc`
Requires `invoices:write` permission
{
id: <Payment Preimage Hash Hex String>
lnd: <Authenticated RPC LND API Object>
}
Example:
```node
const {cancelHodlInvoice} = require('ln-service');
const id = paymentRequestPreimageHashHexString;
await cancelHodlInvoice({id, lnd});
```
### cancelPendingChannel
Cancel an external funding pending channel
{
id: <Pending Channel Id Hex String>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {cancelPendingChannel, openChannels} = require('ln-service');
const channelsToOpen = [{capacity: 1e6, partner_public_key: publicKey}];
const {pending} = await openChannels({lnd, channels: channelsToOpen});
const [id] = pending;
// Cancel the pending channel open request
await cancelPendingChannel({id, lnd});
```
### changePassword
Change wallet password
Requires locked LND and unauthenticated LND connection
{
current_password: <Current Password String>
lnd: <Unauthenticated LND API Object>
new_password: <New Password String>
}
@returns via cbk or Promise
Example:
```node
const {changePassword} = require('ln-service');
await changePassword({lnd, current_password: pass, new_password: newPass});
```
### closeChannel
Close a channel.
Either an id or a transaction id / transaction output index is required
If cooperatively closing, pass a public key and socket to connect
`max_tokens_per_vbyte` will be ignored when closing a peer initiated channel
Requires `info:read`, `offchain:write`, `onchain:write`, `peers:write`
permissions
`max_tokens_per_vbyte` is not supported in LND 0.15.0 and below
`is_graceful_close` is not supported in LND 0.17.5 and below
{
[address]: <Request Sending Local Channel Funds To Address String>
[id]: <Standard Format Channel Id String>
[is_force_close]: <Is Force Close Bool>
[is_graceful_close]: <Is Waiting For Pending Payments to Coop Close Bool>
lnd: <Authenticated LND API Object>
[max_tokens_per_vbyte]: <Fail Cooperative Close Above Fee Rate Number>
[public_key]: <Peer Public Key String>
[socket]: <Peer Socket String>
[target_confirmations]: <Confirmation Target Number>
[tokens_per_vbyte]: <Target Tokens Per Virtual Byte Number>
[transaction_id]: <Transaction Id Hex String>
[transaction_vout]: <Transaction Output Index Number>
}
@returns via cbk or Promise
{
transaction_id: <Closing Transaction Id Hex String>
transaction_vout: <Closing Transaction Vout Number>
}
Example:
```node
const {closeChannel} = require('ln-service');
const closing = await closeChannel({id, lnd});
```
### connectWatchtower
Connect to a watchtower
This method requires LND built with `wtclientrpc` build tag
Requires `offchain:write` permission
{
lnd: <Authenticated LND API Object>
public_key: <Watchtower Public Key Hex String>
socket: <Network Socket Address IP:PORT String>
}
Example:
```node
const {connectWatchtower, getTowerServerInfo} = require('ln-service');
const {tower} = await getTowerServerInfo({lnd: towerServerLnd});
const [socket] = tower.sockets;
await connectWatchtower({lnd, socket, public_key: tower.public_key});
```
### createChainAddress
Create a new receive address.
Requires `address:write` permission
LND 0.14.5 and below do not support p2tr addresses
{
[format]: <Receive Address Type String> // "np2wpkh" || "p2tr" || "p2wpkh"
[is_unused]: <Get As-Yet Unused Address Bool>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
{
address: <Chain Address String>
}
Example:
```node
const {createChainAddress} = require('ln-service');
const format = 'p2wpkh';
const {address} = await createChainAddress({format, lnd});
```
### createFundedPsbt
Create an unsigned funded PSBT given inputs or outputs
When specifying local inputs, they must be locked before using
`change_format` options: `p2tr` (only one change type is supported)
`utxo_selection` methods: 'largest', 'random'
Requires `onchain:write` permission
Requires LND built with `walletrpc` tag
This method is not supported on LND 0.17.5 or below
{
[fee_tokens_per_vbyte]: <Chain Fee Tokens Per Virtual Byte Number>
[inputs]: [{
[sequence]: <Sequence Number>
transaction_id: <Unspent Transaction Id Hex String>
transaction_vout: <Unspent Transaction Output Index Number>
}]
lnd: <Authenticated LND API Object>
[min_confirmations]: <Select Inputs With Minimum Confirmations Number>
[outputs]: [{
[is_change]: <Use This Output For Change Bool>
script: <Output Script Hex String>
tokens: <Send Tokens Tokens Number>
}]
[target_confirmations]: <Blocks To Wait for Confirmation Number>
[timelock]: <Spendable Lock Time on Transaction Number>
[utxo_selection]: <Select Inputs Using Selection Methodology Type String>
[version]: <Transaction Version Number>
}
@returns via cbk or Promise
{
psbt: <Unsigned PSBT Hex String>
}
```node
const {createFundedPsbt} = require('ln-service');
const script = '00';
const tokens = 1e6;
// Create an unsigned PSBT that sends 1mm to an output script
const {psbt} = await createFundedPsbt({lnd, outputs: [{script, tokens}]});
```
### createHodlInvoice
Create HODL invoice. This invoice will not settle automatically when an
HTLC arrives. It must be settled separately with the secret preimage.
Warning: make sure to cancel the created invoice before its CLTV timeout.
Requires LND built with `invoicesrpc` tag
Requires `address:write`, `invoices:write` permission
{
[cltv_delta]: <Final CLTV Delta Number>
[description]: <Invoice Description String>
[description_hash]: <Hashed Description of Payment Hex String>
[expires_at]: <Expires At ISO 8601 Date String>
[id]: <Payment Hash Hex String>
[is_fallback_included]: <Is Fallback Address Included Bool>
[is_fallback_nested]: <Is Fallback Address Nested Bool>
[is_including_private_channels]: <Invoice Includes Private Channels Bool>
lnd: <Authenticated LND API Object>
[mtokens]: <Millitokens String>
[routes]: [[{
[base_fee_mtokens]: <Base Routing Fee In Millitokens String>
[channel]: <Standard Format Channel Id String>
[cltv_delta]: <CLTV Blocks Delta Number>
[fee_rate]: <Fee Rate In Millitokens Per Million Number>
public_key: <Forward Edge Public Key Hex String>
}]]
[tokens]: <Tokens Number>
}
@returns via cbk or Promise
{
[chain_address]: <Backup Address String>
created_at: <ISO 8601 Date String>
description: <Description String>
id: <Payment Hash Hex String>
mtokens: <Millitokens String>
request: <BOLT 11 Encoded Payment Request String>
[secret]: <Hex Encoded Payment Secret String>
tokens: <Tokens Number>
}
Example:
```node
const {createHash, randomBytes} = require('crypto');
const {createHodlInvoice, settleHodlInvoice} = require('ln-service');
const {subscribeToInvoice} = require('ln-service');
const randomSecret = () => randomBytes(32);
const sha256 = buffer => createHash('sha256').update(buffer).digest('hex');
// Choose an r_hash for this invoice, a single sha256, on say randomBytes(32)
const secret = randomSecret();
const id = sha256(secret);
// Supply an authenticatedLndGrpc object for an lnd built with invoicesrpc tag
const {request} = await createHodlInvoice({id, lnd});
// Share the request with the payer and wait for a payment
const sub = subscribeToInvoice({id, lnd});
sub.on('invoice_updated', async invoice => {
// Only actively held invoices can be settled
if (!invoice.is_held) {
return;
}
// Use the secret to claim the funds
await settleHodlInvoice({lnd, secret: secret.toString('hex')});
});
```
### createInvoice
Create a Lightning invoice.
Requires `address:write`, `invoices:write` permission
`payment` is not supported on LND 0.11.1 and below
{
[cltv_delta]: <CLTV Delta Number>
[description]: <Invoice Description String>
[description_hash]: <Hashed Description of Payment Hex String>
[expires_at]: <Expires At ISO 8601 Date String>
[is_encrypting_routes]: <Use Blinded Paths For Inbound Routes Bool>
[is_fallback_included]: <Is Fallback Address Included Bool>
[is_fallback_nested]: <Is Fallback Address Nested Bool>
[is_including_private_channels]: <Invoice Includes Private Channels Bool>
lnd: <Authenticated LND API Object>
[secret]: <Payment Preimage Hex String>
[mtokens]: <Millitokens String>
[routes]: [[{
[base_fee_mtokens]: <Base Routing Fee In Millitokens String>
[channel]: <Standard Format Channel Id String>
[cltv_delta]: <CLTV Blocks Delta Number>
[fee_rate]: <Fee Rate In Millitokens Per Million Number>
public_key: <Forward Edge Public Key Hex String>
}]]
[tokens]: <Tokens Number>
}
@returns via cbk or Promise
{
[chain_address]: <Backup Address String>
created_at: <ISO 8601 Date String>
[description]: <Description String>
id: <Payment Hash Hex String>
[mtokens]: <Millitokens String>
[payment]: <Payment Identifying Secret Hex String>
request: <BOLT 11 Encoded Payment Request String>
secret: <Hex Encoded Payment Secret String>
[tokens]: <Tokens Number>
}
Example:
```node
const {createInvoice} = require('ln-service');
// Create a zero value invoice
const invoice = await createInvoice({lnd});
```
### createSeed
Create a wallet seed
Requires unlocked lnd and unauthenticated LND API Object
{
lnd: <Unauthenticated LND API Object>
[passphrase]: <Seed Passphrase String>
}
@returns via cbk or Promise
{
seed: <Cipher Seed Mnemonic String>
}
Example:
```node
const {createSeed, createWallet} = require('ln-service');
const {seed} = await createSeed({lnd});
// Use the seed to create a wallet
await createWallet({lnd, seed, password: '123456'});
```
### createSignedRequest
Assemble a signed payment request
{
destination: <Destination Public Key Hex String>
hrp: <Request Human Readable Part String>
signature: <Request Hash Signature Hex String>
tags: [<Request Tag Word Number>]
}
@throws
<Error>
@returns
{
request: <BOLT 11 Encoded Payment Request String>
}
Example:
```node
const {createSignedRequest} = require('ln-service');
// Get hrp and signature from createUnsignedRequest
// Get signature via standard private key signing, or LND signBytes
const {request} = createSignedRequest({
destination: nodePublicKey,
hrp: amountAndNetworkHrp,
signature: signedPreimageHash,
tags: paymentRequestTags,
});
```
### createUnsignedRequest
Create an unsigned payment request
{
[chain_addresses]: [<Chain Address String>]
[cltv_delta]: <CLTV Delta Number>
[created_at]: <Invoice Creation Date ISO 8601 String>
[description]: <Description String>
[description_hash]: <Description Hash Hex String>
destination: <Public Key String>
[expires_at]: <ISO 8601 Date String>
features: [{
bit: <BOLT 09 Feature Bit Number>
}]
id: <Preimage SHA256 Hash Hex String>
[mtokens]: <Requested Milli-Tokens Value String> (can exceed Number limit)
network: <Network Name String>
[payment]: <Payment Identifier Hex String>
[routes]: [[{
[base_fee_mtokens]: <Base Fee Millitokens String>
[channel]: <Standard Format Channel Id String>
[cltv_delta]: <Final CLTV Expiration Blocks Delta Number>
[fee_rate]: <Fees Charged in Millitokens Per Million Number>
public_key: <Forward Edge Public Key Hex String>
}]]
[tokens]: <Requested Chain Tokens Number> (note: can differ from mtokens)
}
@returns
{
hash: <Payment Request Signature Hash Hex String>
hrp: <Human Readable Part of Payment Request String>
preimage: <Signature Hash Preimage Hex String>
tags: [<Data Tag Number>]
}
Example:
```node
const {createUnsignedRequest} = require('ln-service');
const unsignedComponents = createUnsignedRequest({
destination: nodePublicKey,
id: rHashHexString,
network: 'bitcoin',
});
// Use createSignedRequest and a signature to create a complete request
```
### createWallet
Create a wallet
Requires unlocked lnd and unauthenticated LND API Object
{
lnd: <Unauthenticated LND API Object>
[passphrase]: <AEZSeed Encryption Passphrase String>
password: <Wallet Password String>
seed: <Seed Mnemonic String>
}
@returns via cbk or Promise
{
macaroon: <Base64 Encoded Admin Macaroon String>
}
Example:
```node
const {createWallet} = require('ln-service');
const {seed} = await createSeed({lnd});
await createWallet({lnd, seed, password: 'password'});
```
### decodePaymentRequest
Get decoded payment request
Requires `offchain:read` permission
{
lnd: <Authenticated LND API Object>
request: <BOLT 11 Payment Request String>
}
@returns via cbk or Promise
{
chain_address: <Fallback Chain Address String>
[cltv_delta]: <Final CLTV Delta Number>
created_at: <Payment Request Created At ISO 8601 Date String>
description: <Payment Description String>
description_hash: <Payment Longer Description Hash Hex String>
destination: <Public Key Hex String>
expires_at: <ISO 8601 Date String>
features: [{
bit: <BOLT 09 Feature Bit Number>
is_known: <Feature is Known Bool>
is_required: <Feature Support is Required To Pay Bool>
type: <Feature Type String>
}]
id: <Payment Hash Hex String>
is_expired: <Invoice is Expired Bool>
mtokens: <Requested Millitokens String>
[payment]: <Payment Identifier Hex Encoded String>
routes: [[{
[base_fee_mtokens]: <Base Routing Fee In Millitokens String>
[channel]: <Standard Format Channel Id String>
[cltv_delta]: <CLTV Blocks Delta Number>
[fee_rate]: <Fee Rate In Millitokens Per Million Number>
public_key: <Forward Edge Public Key Hex String>
}]]
safe_tokens: <Requested Tokens Rounded Up Number>
tokens: <Requested Tokens Rounded Down Number>
}
Example:
```node
const {decodePaymentRequest} = require('ln-service');
const request = 'bolt11EncodedPaymentRequestString';
const details = await decodePaymentRequest({lnd, request});
```
### deleteChainTransaction
Remove a chain transaction.
Requires `onchain:write` permission
This method is not supported on LND 0.17.5 and below
{
id: <Transaction Id Hex String>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {deleteChainTransaction} = require('ln-service');
// Eliminate past broadcast chain transaction
await deleteChainTransaction({id, lnd});
```
### deleteFailedPayAttempts
Delete failed payment attempt records
Requires `offchain:write` permission
Method not supported on LND 0.12.1 or below
`id` is not supported on LND 0.13.4 or below
{
[id]: <Delete Only Failed Attempt Records For Payment With Hash Hex String>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {deleteFailedPayAttempts} = require('ln-service');
// Eliminate all the records of past failed payment attempts
await deleteFailedPayAttempts({lnd});
```
### deleteFailedPayments
Delete failed payment records
Requires `offchain:write` permission
Method not supported on LND 0.12.1 or below
{
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {deleteFailedPayments} = require('ln-service');
// Eliminate all the records of past failed payments
await deleteFailedPayments({lnd});
```
### deleteForwardingReputations
Delete all forwarding reputations
Requires `offchain:write` permission
{
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {deleteForwardingReputations} = require('ln-service');
// Delete all routing reputations to clear pathfinding memory
await deleteForwardingReputations({});
```
### deletePayment
Delete a payment record
Requires `offchain:write` permission
Note: this method is not supported on LND 0.13.4 and below
{
id: <Payment Preimage Hash Hex String>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {deletePayment} = require('ln-service');
// Eliminate the records of a payment
await deletePayment({id, lnd});
```
### deletePayments
Delete all records of payments
Requires `offchain:write` permission
{
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
Example:
```node
const {deletePayments} = require('ln-service');
// Eliminate all the records of past payments
await deletePayments({lnd});
```
### deletePendingChannel
Delete a pending channel
Pass the confirmed conflicting transaction that spends the same input to
make sure that no funds are being deleted.
This method is not supported on LND 0.13.3 and below
{
confirmed_transaction: <Hex Encoded Conflicting Transaction String>
lnd: <Authenticated LND API Object>
pending_transaction: <Hex Encoded Pending Transaction String>
pending_transaction_vout: <Pending Channel Output Index Number>
}
@returns via cbk or Promise
```node
const {deletePendingChannel} = require('ln-service');
// Delete a stuck pending channel
await deletePendingChannel({
lnd,
confirmed_transaction: confirmedTransactionHex,
pending_transaction: stuckPendingChannelOpenTxHex,
pending_transaction_vout: pendingChannelOutputIndexNumber,
});
```
### diffieHellmanComputeSecret
Derive a shared secret
Key family and key index default to 6 and 0, which is the node identity key
Requires LND built with `signerrpc` build tag
Requires `signer:generate` permission
{
[key_family]: <Key Family Number>
[key_index]: <Key Index Number>
lnd: <Authenticated LND API Object>
partner_public_key: <Public Key Hex String>
}
@returns via cbk or Promise
{
secret: <Shared Secret Hex String>
}
### disableChannel
Mark a channel as temporarily disabled for outbound payments and forwards
Note: this method is not supported in LND versions 0.12.1 and below
Requires `offchain:write` permission
{
lnd: <Authenticated LND API Object>
transaction_id: <Channel Funding Transaction Id Hex String>
transaction_vout: <Channel Funding Transaction Output Index Number>
}
@returns via cbk or Promise
Example:
```node
const {disableChannel} = await require('ln-service');
const [channel] = (await getChannels({lnd})).channels;
// Disable outgoing traffic via the channel
await disableChannel({
lnd,
transaction_id: channel.transaction_id,
transaction_vout: channel.transaction_vout,
});
```
### disconnectWatchtower
Disconnect a watchtower
Requires LND built with `wtclientrpc` build tag
Requires `offchain:write` permission
{
lnd: <Authenticated LND API Object>
public_key: <Watchtower Public Key Hex String>
}
@returns via cbk or Promise
```node
const {disconnectWatchtower, getConnectedWatchtowers} = require('ln-service');
const [tower] = (await getConnectedWatchtowers({lnd})).towers;
await disconnectWatchtower({lnd, public_key: tower.public_key});
```
### enableChannel
Mark a channel as enabled for outbound payments and forwards
Setting `is_force_enable` will prevent future automated disabling/enabling
Note: this method is not supported in LND versions 0.12.1 and below
Requires `offchain:write` permission
{
[is_force_enable]: <Force Channel Enabled Bool>
lnd: <Authenticated LND API Object>
transaction_id: <Channel Funding Transaction Id Hex String>
transaction_vout: <Channel Funding Transaction Output Index Number>
}
@returns via cbk or Promise
Example:
```node
const {enableChannel} = await require('ln-service');
const [channel] = (await getChannels({lnd})).channels;
// Enable outgoing traffic via the channel
await enableChannel({
lnd,
transaction_id: channel.transaction_id,
transaction_vout: channel.transaction_vout,
});
```
### endGroupSigningSession
Complete a MuSig2 signing session
Requires LND built with `signrpc` build tag
Requires `signer:generate` permission
This method is not supported in LND 0.14.5 and below
{
id: <Session Id Hex String>
lnd: <Authenticated LND API Object>
[signatures]: [<Combine External Partial Signature Hex String>]
}
@returns via cbk or Promise
{
[signature]: <Combined Signature Hex String>
}
Example:
```node
const {endGroupSigningSession} = require('ln-service');
// Cancel a group signing session
await endGroupSigningSession({id, lnd});
```
### fundPendingChannels
Fund pending channels
Requires `offchain:write`, `onchain:write` permissions
{
channels: [<Pending Channel Id Hex String>]
funding: <Signed Funding Transaction PSBT Hex String>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
```node
const {fundPendingChannels, openChannels} = require('ln-service');
const channelsToOpen = [{capacity: 1e6, partner_public_key: publicKey}];
const {pending} = await openChannels({lnd, channel: channelsToOpen});
const channels = pending.map(n => n.id);
// Fund the pending open channels request
await fundPendingChannels({channels, lnd, funding: psbt});
```
### fundPsbt
Lock and optionally select inputs to a partially signed transaction
Specify outputs or PSBT with the outputs encoded
If there are no inputs passed, internal UTXOs will be selected and locked
`utxo_selection` methods: 'largest', 'random'
`change_format` options: `p2tr` (only one change type is supported)
Requires `onchain:write` permission
Requires LND built with `walletrpc` tag
This method is not supported in LND 0.11.1 and below
Specifying 0 for `min_confirmations` is not supported in LND 0.13.0 and below
`utxo_selection` is not supported in LND 0.17.5 and below
{
[change_format]: <Change Address Address Format String>
[fee_tokens_per_vbyte]: <Chain Fee Tokens Per Virtual Byte Number>
[inputs]: [{
transaction_id: <Unspent Transaction Id Hex String>
transaction_vout: <Unspent Transaction Output Index Number>
}]
lnd: <Authenticated LND API Object>
[min_confirmations]: <Spend UTXOs With Minimum Confirmations Number>
[outputs]: [{
address: <Chain Address String>
tokens: <Send Tokens Tokens Number>
}]
[target_confirmations]: <Confirmations To Wait Number>
[psbt]: <Existing PSBT Hex String>
[utxo_selection]: <Select UTXOs Using Method String>
}
@returns via cbk or Promise
{
inputs: [{
[lock_expires_at]: <UTXO Lock Expires At ISO 8601 Date String>
[lock_id]: <UTXO Lock Id Hex String>
transaction_id: <Unspent Transaction Id Hex String>
transaction_vout: <Unspent Transaction Output Index Number>
}]
outputs: [{
is_change: <Spends To a Generated Change Output Bool>
output_script: <Output Script Hex String>
tokens: <Send Tokens Tokens Number>
}]
psbt: <Unsigned PSBT Hex String>
}
Example:
```node
const {fundPsbt} = require('ln-service');
const address = 'chainAddress';
const tokens = 1000000;
// Create an unsigned PSBT that sends 1mm to a chain address
const {psbt} = await fundPsbt({lnd, outputs: [{address, tokens}]});
// This PSBT can be used with signPsbt to sign and finalize for broadcast
```
### getAccessIds
Get outstanding access ids given out
Note: this method is not supported in LND versions 0.11.1 and below
Requires `macaroon:read` permission
{
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
{
ids: [<Root Access Id Number>]
}
Example:
```node
const {getAccessIds, grantAccess} = require('ln-service');
// Create a macaroon that can be used to make off-chain payments
const {macaroon} = await grantAccess({lnd, id: '1', is_ok_to_pay: true});
// Get outstanding ids
const {ids} = await getAccessIds({lnd});
// The specified id '1' will appear in the ids array
```
### getAutopilot
Get Autopilot status
Optionally, get the score of nodes as considered by the autopilot.
Local scores reflect an internal scoring that includes local channel info
Permission `info:read` is required
{
lnd: <Authenticated LND Object>
[node_scores]: [<Get Score For Public Key Hex String>]
}
@returns via cbk or Promise
{
is_enabled: <Autopilot is Enabled Bool>
nodes: [{
local_preferential_score: <Local-adjusted Pref Attachment Score Number>
local_score: <Local-adjusted Externally Set Score Number>
preferential_score: <Preferential Attachment Score Number>
public_key: <Node Public Key Hex String>
score: <Externally Set Score Number>
weighted_local_score: <Combined Weighted Locally-Adjusted Score Number>
weighted_score: <Combined Weighted Score Number>
}]
}
Example:
```node
const {getAutopilot} = require('ln-service');
const isAutopilotEnabled = (await getAutopilot({lnd})).is_enabled;
```
### getBackup
Get the static channel backup for a channel
Requires `offchain:read` permission
{
lnd: <Authenticated LND API Object>
transaction_id: <Funding Transaction Id Hex String>
transaction_vout: <Funding Transaction Output Index Number>
}
@returns via cbk or Promise
{
backup: <Channel Backup Hex String>
}
Example:
```node
const {getBackup, getChannels} = require('ln-service');
const [channel] = (await getChannels({lnd})).channels;
const {backup} = await getBackup({
lnd,
transaction_id: channel.transaction_id,
transaction_vout: channel.transaction_vout,
});
```
### getBackups
Get all channel backups
Requires `offchain:read` permission
{
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
{
backup: <All Channels Backup Hex String>
channels: [{
backup: <Individualized Channel Backup Hex String>
transaction_id: <Channel Funding Transaction Id Hex String>
transaction_vout: <Channel Funding Transaction Output Index Number>
}]
}
Example:
```node
const {getBackups} = require('ln-service');
const {backup} = await getBackups({lnd});
```
### getBlock
Get a block in the chain
This method requires LND built with `chainrpc` build tag
Requires `onchain:read` permission
This method is not supported on LND 0.15.5 and below
{
[height]: <Block Height Number>
[id]: <Block Hash Hex String>
lnd: <Authenticated LND API Object>
}
@returns via cbk or Promise
{
block: <Raw Block Bytes Hex String>
}
Example:
```node
const {getBlock, getHeight} = require('ln-service');
const chain = await getHeight({lnd});
const {block} = await getBlock({lnd, id: chain.current_block_hash});
const las