Struct lightning_signer::node::Node

source ·
pub struct Node { /* private fields */ }
Expand description

A signer for one Lightning node.

use std::sync::Arc;

use lightning_signer::channel::{ChannelSlot, ChannelBase};
use lightning_signer::node::{Node, NodeConfig, NodeServices, SyncLogger};
use lightning_signer::persist::{DummyPersister, Persist};
use lightning_signer::policy::simple_validator::SimpleValidatorFactory;
use lightning_signer::signer::ClockStartingTimeFactory;
use lightning_signer::signer::derive::KeyDerivationStyle;
use lightning_signer::util::clock::StandardClock;
use lightning_signer::util::test_logger::TestLogger;
use lightning_signer::bitcoin;
use bitcoin::Network;

let persister: Arc<dyn Persist> = Arc::new(DummyPersister {});
let seed = [0; 32];
let config = NodeConfig { network: Network::Testnet, key_derivation_style: KeyDerivationStyle::Native };
let validator_factory = Arc::new(SimpleValidatorFactory::new());
let starting_time_factory = ClockStartingTimeFactory::new();
let clock = Arc::new(StandardClock());
let services = NodeServices {
    validator_factory,
    starting_time_factory,
    persister,
    clock,
};
let node = Arc::new(Node::new(config, &seed, vec![], services));
// TODO: persist the seed
let (channel_id, opt_stub) = node.new_channel(None, &node).expect("new channel");
assert!(opt_stub.is_some());
let channel_slot_mutex = node.get_channel(&channel_id).expect("get channel");
let channel_slot = channel_slot_mutex.lock().expect("lock");
match &*channel_slot {
    ChannelSlot::Stub(stub) => {
        // Do things with the stub, such as readying it or getting the points
        let holder_basepoints = stub.get_channel_basepoints();
    }
    ChannelSlot::Ready(_) => panic!("expected a stub")
}

Implementations§

source§

impl Node

source

pub fn new( node_config: NodeConfig, seed: &[u8], allowlist: Vec<Allowable>, services: NodeServices ) -> Node

Create a node.

NOTE: you must persist the node yourself if it is new.

source

pub fn new_from_persistence( node_config: NodeConfig, seed: &[u8], allowlist: Vec<Allowable>, services: NodeServices, state: NodeState ) -> Node

Restore a node.

source

pub fn get_persister(&self) -> Arc<dyn Persist>

persister

source

pub fn get_onion_reply_secret(&self) -> [u8; 32]

onion reply secret

source

pub fn get_bolt12_pubkey(&self) -> PublicKey

BOLT 12 x-only pubkey

source

pub fn sign_bolt12( &self, messagename: &[u8], fieldname: &[u8], merkleroot: &[u8; 32], publictweak_opt: Option<&[u8]> ) -> Result<Signature, Status>

BOLT 12 sign

source

pub fn derive_secret(&self, info: &[u8]) -> SecretKey

derive secret

source

pub fn set_validator_factory( &self, validator_factory: Arc<dyn ValidatorFactory> )

Set the node’s validator factory

source

pub fn get_id(&self) -> PublicKey

Get the node ID, which is the same as the node public key

source

pub fn log_prefix(&self) -> String

Get suitable node identity string for logging

source

pub fn get_state(&self) -> MutexGuard<'_, NodeState>

Lock and return the node state

source

pub fn get_inbound_payment_key_material(&self) -> KeyMaterial

Get secret key material as bytes for use in encrypting and decrypting inbound payment data.

This method must return the same value each time it is called.

source

pub fn get_channel( &self, channel_id: &ChannelId ) -> Result<Arc<Mutex<ChannelSlot>>, Status>

Get the Mutex protected channel slot

source

pub fn with_channel_base<F, T>( &self, channel_id: &ChannelId, f: F ) -> Result<T, Status>where F: Fn(&mut dyn ChannelBase) -> Result<T, Status> + Sized,

Execute a function with an existing channel.

The channel may be a stub or a ready channel. An invalid_argument Status will be returned if the channel does not exist.

source

pub fn with_ready_channel<F, T>( &self, channel_id: &ChannelId, f: F ) -> Result<T, Status>where F: Fn(&mut Channel) -> Result<T, Status> + Sized,

Execute a function with an existing ready channel.

An invalid_argument Status will be returned if the channel does not exist.

source

pub fn find_channel_with_funding_outpoint( &self, outpoint: &OutPoint ) -> Option<Arc<Mutex<ChannelSlot>>>

Get a channel given its funding outpoint, or None if no such channel exists.

source

pub fn new_channel( &self, opt_channel_id: Option<ChannelId>, arc_self: &Arc<Node> ) -> Result<(ChannelId, Option<ChannelSlot>), Status>

Create a new channel, which starts out as a stub.

The initial channel ID may be specified in opt_channel_id. If the channel with this ID already exists, the existing stub is returned.

If unspecified, a channel ID will be generated.

Returns the channel ID and the stub.

If there was already a channel with this ID, it is returned.

source

pub fn restore_node( node_id: &PublicKey, node_entry: NodeEntry, seed: &[u8], services: NodeServices ) -> Arc<Node>

Restore a node from a persisted NodeEntry.

You can get the NodeEntry from Persist::get_nodes.

The channels are also restored from the persister.

source

pub fn restore_nodes( services: NodeServices, seed_persister: Arc<dyn SeedPersist> ) -> Map<PublicKey, Arc<Node>>

Restore all nodes from persister.

The channels of each node are also restored.

source

pub fn ready_channel( &self, channel_id0: ChannelId, opt_channel_id: Option<ChannelId>, setup: ChannelSetup, holder_shutdown_key_path: &[u32] ) -> Result<Channel, Status>

Ready a new channel, making it available for use.

This populates fields that are known later in the channel creation flow, such as fields that are supplied by the counterparty and funding outpoint.

  • channel_id0 - the original channel ID supplied to Node::new_channel
  • opt_channel_id - the permanent channel ID

The channel is promoted from a ChannelStub to a Channel. After this call, the channel may be referred to by either ID.

source

pub fn get_heartbeat(&self) -> SignedHeartbeat

Get a signed heartbeat message The heartbeat is signed with the account master key.

source

pub fn unchecked_sign_onchain_tx( &self, tx: &Transaction, ipaths: &[Vec<u32>], values_sat: &[u64], spendtypes: &[SpendType], uniclosekeys: Vec<Option<(SecretKey, Vec<Vec<u8>>)>> ) -> Result<Vec<Vec<Vec<u8>>>, Status>

Sign an onchain transaction (funding tx or simple sweeps).

check_onchain_tx must be called first to validate the transaction. The two are separate so that the caller can check for approval if there is an unknown destination.

The transaction may fund multiple channels at once.

Returns a witness stack for each input. Inputs that are marked as SpendType::Invalid are not signed and get an empty witness stack.

  • ipaths - derivation path for the wallet key per input
  • values_sat - the amount in satoshi per input
  • spendtypes - spend type per input, or Invalid if this input is to be signed by someone else.
  • uniclosekeys - an optional unilateral close key to use instead of the wallet key. Takes precedence over the ipaths entry. This is used when we are sweeping a unilateral close and funding a channel in a single tx. The second item in the tuple is the witness stack suffix - zero or more script parameters and the redeemscript.
source

pub fn check_onchain_tx( &self, tx: &Transaction, values_sat: &[u64], spendtypes: &[SpendType], uniclosekeys: &[Option<(SecretKey, Vec<Vec<u8>>)>], opaths: &[Vec<u32>] ) -> Result<(), ValidationError>

Check an onchain transaction (funding tx or simple sweeps).

This is normally followed by a call to unchecked_sign_onchain_tx.

If the result is ValidationError::UncheckedDestinations, the caller could still ask for manual approval and then sign the transaction.

The transaction may fund multiple channels at once.

  • values_sat - the amount in satoshi per input
  • spendtypes - spend type per input, or Invalid if this input is to be signed by someone else.
  • uniclosekeys - an optional unilateral close key to use instead of the wallet key. Takes precedence over the ipaths entry. This is used when we are sweeping a unilateral close and funding a channel in a single tx. The second item in the tuple is the witness stack suffix - zero or more script parameters and the redeemscript.
  • opaths - derivation path per output. Empty for non-wallet/non-xpub-whitelist outputs.
source

pub fn get_ldk_shutdown_scriptpubkey(&self) -> ShutdownScript

Get shutdown_pubkey to use as PublicKey at channel closure

source

pub fn get_account_extended_key(&self) -> &ExtendedPrivKey

Get the layer-1 xprv

source

pub fn get_account_extended_pubkey(&self) -> ExtendedPubKey

Get the layer-1 xpub

source

pub fn sign_node_announcement(&self, na: &[u8]) -> Result<Signature, Status>

Sign a node announcement using the node key

source

pub fn sign_channel_update(&self, cu: &[u8]) -> Result<Signature, Status>

Sign a channel update or announcement using the node key

source

pub fn sign_gossip_message( &self, msg: &UnsignedGossipMessage<'_> ) -> Result<Signature, Status>

Sign gossip messages

source

pub fn sign_invoice( &self, hrp_bytes: &[u8], invoice_data: &[u5] ) -> Result<RecoverableSignature, Status>

Sign an invoice and start tracking incoming payment for its payment hash

source

pub fn sign_message(&self, message: &[u8]) -> Result<Vec<u8>, Status>

Sign a Lightning message

source

pub fn channels( &self ) -> MutexGuard<'_, OrderedMap<ChannelId, Arc<Mutex<ChannelSlot>>>>

Get the channels this node knows about. Currently, channels are not pruned once closed, but this will change.

source

pub fn ecdh(&self, other_key: &PublicKey) -> Vec<u8>

Perform an ECDH operation between the node key and a public key This can be used for onion packet decoding

source

pub fn spend_spendable_outputs( &self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, secp_ctx: &Secp256k1<All> ) -> Result<Transaction, ()>

See MyKeysManager::spend_spendable_outputs.

For LDK compatibility.

source

pub fn allowlist(&self) -> Result<Vec<String>, Status>

Returns the node’s current allowlist.

source

pub fn allowables(&self) -> Vec<Allowable>

Returns the node’s current allowlist.

source

pub fn add_allowlist(&self, addlist: &[String]) -> Result<(), Status>

Adds addresses to the node’s current allowlist.

source

pub fn set_allowlist(&self, allowlist: &[String]) -> Result<(), Status>

Replace the nodes allowlist with the provided allowlist.

source

pub fn remove_allowlist(&self, rmlist: &[String]) -> Result<(), Status>

Removes addresses from the node’s current allowlist.

source

pub fn get_tracker(&self) -> MutexGuard<'_, ChainTracker<ChainMonitor>>

Chain tracker with lock

source

pub fn get_chain_height(&self) -> u32

Height of chain

source

pub fn add_invoice(&self, raw_invoice: SignedRawInvoice) -> Result<bool, Status>

Add an invoice. Used by the signer to map HTLCs to destination payees, so that payee public keys can be allowlisted for policy control. Returns true if the invoice was added, false otherwise.

source

pub fn add_keysend( &self, payee: PublicKey, payment_hash: PaymentHash, amount_msat: u64 ) -> Result<bool, Status>

Add a keysend payment.

Returns true if the keysend was added, false otherwise.

The payee is currently not validated.

source

pub fn has_payment( &self, hash: &PaymentHash, invoice_hash: &[u8; 32] ) -> Result<bool, Status>

Check to see if a payment has already been added

source

pub fn payment_state_from_invoice( raw_invoice: SignedRawInvoice ) -> Result<(PaymentHash, PaymentState, [u8; 32], Invoice), Status>

Validate the invoice and create a tracking state for it.

Returns the payment hash, invoice state, and the hash of the raw invoice that was signed.

source

pub fn payment_state_from_keysend( payee: PublicKey, payment_hash: PaymentHash, amount_msat: u64 ) -> Result<(PaymentState, [u8; 32]), Status>

Create tracking state for an ad-hoc payment (keysend). The payee is not validated yet.

Returns the invoice state

Trait Implementations§

source§

impl Debug for Node

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl NodeMonitor for Node

source§

fn channel_balance(&self) -> ChannelBalance

Get the balance
source§

impl Wallet for Node

source§

fn allowlist_contains(&self, script_pubkey: &Script, path: &[u32]) -> bool

Returns true if script_pubkey is in the node’s allowlist.

source§

fn can_spend( &self, child_path: &[u32], script_pubkey: &Script ) -> Result<bool, Status>

True if the wallet can spend the given output with a derived key
source§

fn get_native_address(&self, child_path: &[u32]) -> Result<Address, Status>

Returns the native segwit address at path
source§

fn get_wrapped_address(&self, child_path: &[u32]) -> Result<Address, Status>

Returns the wrapped segwit address at path
source§

fn network(&self) -> Network

Returns the network

Auto Trait Implementations§

§

impl !RefUnwindSafe for Node

§

impl Send for Node

§

impl Sync for Node

§

impl Unpin for Node

§

impl !UnwindSafe for Node

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V