Struct 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,
    use_checkpoints: true,
    allow_deep_reorgs: true, // not for production
};
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,
    trusted_oracle_pubkeys: vec![],
};
let node = Arc::new(Node::new(config, &seed, vec![], services));
// TODO: persist the seed
let (channel_id, opt_stub) = node.new_channel_with_random_id(&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 update_velocity_controls(&self)

Update the velocity controls with any spec changes from the policy

Source

pub fn get_entropy_source(&self) -> &dyn EntropySource

Get an entropy source

Source

pub fn get_clock(&self) -> Arc<dyn Clock>

Clock

Source

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

Restore a node.

Source

pub fn make_keys_manager( node_config: &NodeConfig, seed: &[u8], services: &NodeServices, ) -> (MyKeysManager, PublicKey)

Create a keys manager - useful for bootstrapping a node from persistence, so the persistence key can be derived.

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 get_persistence_pubkey(&self) -> PublicKey

persistence pubkey

Source

pub fn get_persistence_shared_secret( &self, server_pubkey: &PublicKey, ) -> [u8; 32]

persistence shared secret

Source

pub fn get_persistence_auth_token(&self, server_pubkey: &PublicKey) -> [u8; 32]

Persistence auth token

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 persist_all(&self)

Persist everything. This is normally not needed, as the node will persist itself, but may be useful if switching to a new persister.

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_channel<F, T>( &self, channel_id: &ChannelId, f: F, ) -> Result<T, Status>
where F: FnOnce(&mut Channel) -> Result<T, Status> + Sized,

Execute a function with an existing configured 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_with_random_id( &self, arc_self: &Arc<Node>, ) -> Result<(ChannelId, Option<ChannelSlot>), Status>

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

Returns a generated channel ID and the stub.

Source

pub fn new_channel( &self, dbid: u64, peer_id: &[u8; 33], arc_self: &Arc<Node>, ) -> Result<(ChannelId, Option<ChannelSlot>), Status>

Create a new channel from a seed identifier (aka a dbid) and a peer node id

The seed id must never be reused as revocation secrets may be publicly known. Rather than store all historical ids, this method requires seed ids to increase monotonically, checked against a high-water mark which is set when forgetting channels.

Setting the high-water mark on forgetting rather than creating channels allows for some slack in the system to accomodate reordered requests.

If the seed id is not monotonic the method returns an error. Otherwise, it returns the new channel id and stub.

Source

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

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>, ) -> Result<Map<PublicKey, Arc<Node>>, Status>

Restore all nodes from persister.

The channels of each node are also restored.

Source

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

Setup 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>], prev_outs: &[TxOut], 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
  • prev_outs - the previous outputs used as inputs for this tx
  • 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, segwit_flags: &[bool], prev_outs: &[TxOut], 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.

  • input_txs - previous tx for inputs when funding channel
  • prev_outs - the previous outputs used as inputs for this tx
  • 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 check_wallet_pubkey( &self, child_path: &[u32], pubkey: PublicKey, ) -> Result<bool, Status>

Check the submitted wallet pubkey

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_tagged_message( &self, tag: &[u8], message: &[u8], ) -> Result<Vec<u8>, Status>

Sign a message, with the specified tag. Notice that you most likely are looking for sign_message which adds the lightning message tag, so the signature cannot be reused for unintended use-cases. The tag specifies the domain in which the signature should be usable. It is up to the caller to ensure that tags are prefix-free.

Source

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

Sign a Lightning message

Source

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

Lock and return all the channels this node knows about.

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: ScriptBuf, feerate_sat_per_1000_weight: u32, ) -> 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, invoice: Invoice) -> 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( invoice: &Invoice, ) -> Result<(PaymentHash, PaymentState, [u8; 32]), Status>

Create a tracking state for the invoice

Returns the payment hash, payment 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, now: Duration, ) -> Result<(PaymentState, [u8; 32]), Status>

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

Returns the invoice state

Source

pub fn forget_channel(&self, channel_id: &ChannelId) -> Result<(), Status>

The node tells us that it is forgetting a channel

Source

pub fn chaninfo(&self) -> Vec<SlotInfo>

Log channel information

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 can_spend( &self, child_path: &[u32], script_pubkey: &ScriptBuf, ) -> 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_taproot_address(&self, child_path: &[u32]) -> Result<Address, Status>

Returns the p2tr address at path
Source§

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

👎Deprecated since 0.9.0: Use native addresses instead
Returns the wrapped segwit address at path
Source§

fn allowlist_contains_payee(&self, payee: PublicKey) -> bool

Returns true if the given destination Lightning payee is in the node’s allowlist
Source§

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

True if the script_pubkey is in the node’s allowlist
Source§

fn network(&self) -> Network

Returns the network

Auto Trait Implementations§

§

impl !Freeze for Node

§

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 T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

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

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

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

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more