Skip to content

Commit

Permalink
f Re-introduce Network newtype
Browse files Browse the repository at this point in the history
... as `bitcoin::Network` is now `non_exhaustive`.
  • Loading branch information
tnull committed Dec 18, 2023
1 parent 5b92b44 commit 06db0fb
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 28 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@ LDK Node is a self-custodial Lightning node in library form. Its central goal is
The primary abstraction of the library is the [`Node`][api_docs_node], which can be retrieved by setting up and configuring a [`Builder`][api_docs_builder] to your liking and calling one of the `build` methods. `Node` can then be controlled via commands such as `start`, `stop`, `connect_open_channel`, `send_payment`, etc.

```rust
use ldk_node::Builder;
use ldk_node::{Builder, Network};
use ldk_node::lightning_invoice::Invoice;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::bitcoin::secp256k1::PublicKey;
use ldk_node::bitcoin::Network;
use std::str::FromStr;

fn main() {
Expand Down
20 changes: 9 additions & 11 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use crate::peer_store::PeerStore;
use crate::sweep::OutputSweeper;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, FakeMessageRouter, GossipSync, KeysManager, NetworkGraph,
OnionMessenger, PeerManager,
ChainMonitor, ChannelManager, FakeMessageRouter, GossipSync, KeysManager, Network,
NetworkGraph, OnionMessenger, PeerManager,
};
use crate::wallet::Wallet;
use crate::LogLevel;
Expand Down Expand Up @@ -47,8 +47,6 @@ use bdk::blockchain::esplora::EsploraBlockchain;
use bdk::database::SqliteDatabase;
use bdk::template::Bip84;

use bitcoin::Network;

use bip39::Mnemonic;

use bitcoin::BlockHash;
Expand Down Expand Up @@ -436,16 +434,16 @@ fn build_with_store_internal<K: KVStore + Sync + Send + 'static>(
logger: Arc<FilesystemLogger>, kv_store: Arc<K>,
) -> Result<Node<K>, BuildError> {
// Initialize the on-chain wallet and chain access
let xprv =
bitcoin::bip32::ExtendedPrivKey::new_master(config.network, &seed_bytes).map_err(|e| {
let xprv = bitcoin::bip32::ExtendedPrivKey::new_master(config.network.into(), &seed_bytes)
.map_err(|e| {
log_error!(logger, "Failed to derive master secret: {}", e);
BuildError::InvalidSeedBytes
})?;

let wallet_name = bdk::wallet::wallet_name_from_descriptor(
Bip84(xprv, bdk::KeychainKind::External),
Some(Bip84(xprv, bdk::KeychainKind::Internal)),
config.network,
config.network.into(),
&Secp256k1::new(),
)
.map_err(|e| {
Expand All @@ -459,7 +457,7 @@ fn build_with_store_internal<K: KVStore + Sync + Send + 'static>(
let bdk_wallet = bdk::Wallet::new(
Bip84(xprv, bdk::KeychainKind::External),
Some(Bip84(xprv, bdk::KeychainKind::Internal)),
config.network,
config.network.into(),
database,
)
.map_err(|e| {
Expand Down Expand Up @@ -537,7 +535,7 @@ fn build_with_store_internal<K: KVStore + Sync + Send + 'static>(
Ok(graph) => Arc::new(graph),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Arc::new(NetworkGraph::new(config.network, Arc::clone(&logger)))
Arc::new(NetworkGraph::new(config.network.into(), Arc::clone(&logger)))
} else {
return Err(BuildError::ReadFailed);
}
Expand Down Expand Up @@ -629,10 +627,10 @@ fn build_with_store_internal<K: KVStore + Sync + Send + 'static>(
} else {
// We're starting a fresh node.
let genesis_block_hash =
bitcoin::blockdata::constants::genesis_block(config.network).block_hash();
bitcoin::blockdata::constants::genesis_block(config.network.into()).block_hash();

let chain_params = ChainParameters {
network: config.network,
network: config.network.into(),
best_block: BestBlock::new(genesis_block_hash, 0),
};
channelmanager::ChannelManager::new(
Expand Down
11 changes: 4 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@
//! [`send_payment`], etc.:
//!
//! ```no_run
//! use ldk_node::Builder;
//! use ldk_node::{Builder, Network};
//! use ldk_node::lightning_invoice::Bolt11Invoice;
//! use ldk_node::lightning::ln::msgs::SocketAddress;
//! use ldk_node::bitcoin::secp256k1::PublicKey;
//! use ldk_node::bitcoin::Network;
//! use std::str::FromStr;
//!
//! fn main() {
Expand Down Expand Up @@ -125,7 +124,7 @@ use types::{
Broadcaster, ChainMonitor, ChannelManager, FeeEstimator, KeysManager, NetworkGraph,
PeerManager, Router, Scorer, Sweeper, Wallet,
};
pub use types::{ChannelDetails, PeerDetails, UserChannelId};
pub use types::{ChannelDetails, Network, PeerDetails, UserChannelId};

use logger::{log_error, log_info, log_trace, FilesystemLogger, Logger};

Expand All @@ -150,7 +149,6 @@ use lightning_invoice::{payment, Bolt11Invoice, Currency};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::PublicKey;
use bitcoin::Network;

use bitcoin::{Address, Txid};

Expand Down Expand Up @@ -1498,7 +1496,7 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
fn receive_payment_inner(
&self, amount_msat: Option<u64>, description: &str, expiry_secs: u32,
) -> Result<Bolt11Invoice, Error> {
let currency = Currency::from(self.config.network);
let currency = Currency::from(bitcoin::Network::from(self.config.network));
let keys_manager = Arc::clone(&self.keys_manager);
let invoice = match lightning_invoice::utils::create_invoice_from_channelmanager(
&self.channel_manager,
Expand Down Expand Up @@ -1551,8 +1549,7 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
///
/// For example, you could retrieve all stored outbound payments as follows:
/// ```
/// # use ldk_node::{Builder, Config, PaymentDirection};
/// # use ldk_node::bitcoin::Network;
/// # use ldk_node::{Builder, Config, Network, PaymentDirection};
/// # let mut config = Config::default();
/// # config.network = Network::Regtest;
/// # config.storage_dir_path = "/tmp/ldk_node_test/".to_string();
Expand Down
4 changes: 2 additions & 2 deletions src/test/functional_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::builder::NodeBuilder;
use crate::io::test_utils::TestSyncStore;
use crate::test::utils::*;
use crate::test::utils::{expect_channel_pending_event, expect_event, open_channel, random_config};
use crate::{Error, Event, Node, PaymentDirection, PaymentStatus};
use crate::{Error, Event, Network, Node, PaymentDirection, PaymentStatus};

use bitcoin::Amount;
use electrsd::bitcoind::BitcoinD;
Expand Down Expand Up @@ -409,7 +409,7 @@ fn multi_hop_sending() {
#[test]
fn connect_to_public_testnet_esplora() {
let mut config = random_config();
config.network = bitcoin::Network::Testnet;
config.network = Network::Testnet;
let mut builder = NodeBuilder::from_config(config);
builder.set_esplora_server("https://blockstream.info/testnet/api".to_string());
let node = builder.build().unwrap();
Expand Down
6 changes: 3 additions & 3 deletions src/test/utils.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::builder::NodeBuilder;
use crate::io::test_utils::TestSyncStore;
use crate::{Config, Event, Node};
use crate::{Config, Event, Network, Node};
use lightning::ln::msgs::SocketAddress;
use lightning::util::logger::{Level, Logger, Record};
use lightning::util::persist::KVStore;

use bitcoin::{Address, Amount, Network, OutPoint, Txid};
use bitcoin::{Address, Amount, OutPoint, Txid};

use bitcoind::bitcoincore_rpc::RpcApi;
use electrsd::bitcoind::bitcoincore_rpc::bitcoincore_rpc_json::AddressType;
Expand Down Expand Up @@ -239,7 +239,7 @@ pub fn generate_blocks_and_wait(bitcoind: &BitcoinD, electrsd: &ElectrsD, num: u
.client
.get_new_address(Some("test"), Some(AddressType::Legacy))
.expect("failed to get new address")
.require_network(Network::Regtest)
.require_network(bitcoin::Network::Regtest)
.expect("failed to get new address");
// TODO: expect this Result once the WouldBlock issue is resolved upstream.
let _block_hashes_res = bitcoind.client.generate_to_address(num as u64, &address);
Expand Down
54 changes: 54 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ use lightning_transaction_sync::EsploraSyncClient;
use bitcoin::secp256k1::{self, PublicKey, Secp256k1};
use bitcoin::OutPoint;

use std::fmt;
use std::str::FromStr;
use std::sync::{Arc, Mutex, RwLock};

pub(crate) type ChainMonitor<K> = chainmonitor::ChainMonitor<
Expand Down Expand Up @@ -137,6 +139,58 @@ pub(crate) type Sweeper<K> = OutputSweeper<
Arc<FilesystemLogger>,
>;

/// The cryptocurrency network to act on.
#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug)]
pub enum Network {
/// Mainnet Bitcoin.
Bitcoin,
/// Bitcoin's testnet network.
Testnet,
/// Bitcoin's signet network.
Signet,
/// Bitcoin's regtest network.
Regtest,
}

impl TryFrom<bitcoin::Network> for Network {
type Error = ();

fn try_from(network: bitcoin::Network) -> Result<Self, Self::Error> {
match network {
bitcoin::Network::Bitcoin => Ok(Self::Bitcoin),
bitcoin::Network::Testnet => Ok(Self::Testnet),
bitcoin::Network::Signet => Ok(Self::Signet),
bitcoin::Network::Regtest => Ok(Self::Regtest),
_ => Err(()),
}
}
}

impl From<Network> for bitcoin::Network {
fn from(network: Network) -> Self {
match network {
Network::Bitcoin => bitcoin::Network::Bitcoin,
Network::Testnet => bitcoin::Network::Testnet,
Network::Signet => bitcoin::Network::Signet,
Network::Regtest => bitcoin::Network::Regtest,
}
}
}

impl fmt::Display for Network {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
bitcoin::Network::from(*self).fmt(f)
}
}

impl FromStr for Network {
type Err = ();

fn from_str(s: &str) -> Result<Self, Self::Err> {
bitcoin::Network::from_str(s).map_err(|_| ())?.try_into()
}
}

/// A local, potentially user-provided, identifier of a channel.
///
/// By default, this will be randomly generated for the user to ensure local uniqueness.
Expand Down
6 changes: 3 additions & 3 deletions tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#![cfg(cln_test)]

use ldk_node::{Config, LogLevel};
use ldk_node::{Config, LogLevel, Network};

use lightning::ln::msgs::SocketAddress;

use bitcoin::{Address, Amount, Network, OutPoint, Txid};
use bitcoin::{Address, Amount, OutPoint, Txid};

use bitcoincore_rpc::bitcoincore_rpc_json::AddressType;
use bitcoincore_rpc::Client as BitcoindClient;
Expand Down Expand Up @@ -126,7 +126,7 @@ pub(crate) fn generate_blocks_and_wait(
let address = bitcoind
.get_new_address(Some("test"), Some(AddressType::Legacy))
.expect("failed to get new address")
.require_network(Network::Regtest)
.require_network(bitcoin::Network::Regtest)
.expect("failed to get new address");
// TODO: expect this Result once the WouldBlock issue is resolved upstream.
let _block_hashes_res = bitcoind.generate_to_address(num as u64, &address);
Expand Down

0 comments on commit 06db0fb

Please sign in to comment.