Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Add file based Config support. by G8XSU · Pull Request #28 · lightningdevkit/ldk-server · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add file based Config support. by G8XSU · Pull Request #28 · lightningdevkit/ldk-server · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add file based Config support. by G8XSU · Pull Request #28 · lightningdevkit/ldk-server · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Add file based Config support. by G8XSU · Pull Request #28 · lightningdevkit/ldk-server · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add file based Config support. by G8XSU · Pull Request #28 · lightningdevkit/ldk-server · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add file based Config support. by G8XSU · Pull Request #28 · lightningdevkit/ldk-server · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Add file based Config support. by G8XSU · Pull Request #28 · lightningdevkit/ldk-server · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ldk-server/ldk-server.config
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
{
// The addresses on which the lightning node will listen for incoming connections.
"listening_address": "localhost:3001",

// The Bitcoin network to use.
"network": "regtest",

// The address on which LDK Server will accept incoming requests.
"rest_service_address": "127.0.0.1:3002",

// The path where the underlying LDK and BDK persist their data.
"storage_dir_path": "/tmp",

// Bitcoin Core's RPC endpoint.
"bitcoind_rpc_address": "127.0.0.1:8332",

// Bitcoin Core's RPC user.
"bitcoind_rpc_user": "bitcoind-testuser",

// Bitcoin Core's RPC password.
"bitcoind_rpc_password": "bitcoind-testpassword"
}
64 changes: 17 additions & 47 deletions ldk-server/src/main.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,8 +5,6 @@ mod util;

use crate::service::NodeService;

use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::{Builder, Event, LogLevel};

use tokio::net::TcpListener;
Expand All@@ -15,65 +13,36 @@ use tokio::signal::unix::SignalKind;
use hyper::server::conn::http1;
use hyper_util::rt::TokioIo;

use crate::util::config::load_config;
use ldk_node::config::Config;
use std::net::SocketAddr;
use std::str::FromStr;
use std::path::Path;
use std::sync::Arc;

fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 8 {
eprintln!(
"Usage: {} storage_path listening_addr rest_svc_addr network bitcoind_rpc_addr bitcoind_rpc_user bitcoind_rpc_password",
args[0]
);
if args.len() < 2 {
eprintln!("Usage: {} config_path", args[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the config strategy we wanna pursue? Just passing the file path? A lot of libraries have a multi-layered approach, using a config file, which can be overridden by environment variables, which can be overridden by command-line arguments, and all of that is neatly integrated into man and --help, but typically uses a third-party library.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding multiple levels of config knobs could add confusion,
for now i chose to keep it simple json config without any config reading dependencies.

With more and more config options, cli args won't really be feasible.
Although we could add support for overriding some config-values with env vars in future if needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, fair enough. What about defaults? It looks like currently the JSON file needs to have all the fields? Also, does the reading of the JSON file currently allow for additional fields that aren't used by us? Or even comment lines?

@G8XSUG8XSUDec 4, 2024

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defaults will need to be configured/handled in code.
Yes, currently it needs all the fields to be present, it does allow unknown-fields not being used by us. (added a test)
And doesn't allow comments currently. :(

I did have the option to use something like toml but wasn't sure about crate dependency for it.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added basic functionality to remove simple single-line comments using '//', tested in tests in latest commit.
Key/value can't contain '//' without escaping since it is a control character.

std::process::exit(-1);
}

let mut config = Config::default();
config.storage_dir_path = args[1].clone();
config.log_level = LogLevel::Trace;
let mut ldk_node_config = Config::default();
let config_file = load_config(Path::new(&args[1])).expect("Invalid configuration file.");

config.listening_addresses = match SocketAddress::from_str(&args[2]) {
Ok(addr) => Some(vec![addr]),
Err(_) => {
eprintln!("Failed to parse listening_addr: {}", args[2]);
std::process::exit(-1);
},
};

let rest_svc_addr = match SocketAddr::from_str(&args[3]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse rest_svc_addr: {}", args[3]);
std::process::exit(-1);
},
};
ldk_node_config.log_level = LogLevel::Trace;
ldk_node_config.storage_dir_path = config_file.storage_dir_path;
ldk_node_config.listening_addresses = Some(vec![config_file.listening_addr]);
ldk_node_config.network = config_file.network;

config.network = match Network::from_str(&args[4]) {
Ok(network) => network,
Err(_) => {
eprintln!("Unsupported network: {}. Use 'bitcoin', 'testnet', 'regtest', 'signet', 'regtest'.", args[4]);
std::process::exit(-1);
},
};

let mut builder = Builder::from_config(config);
let mut builder = Builder::from_config(ldk_node_config);

let bitcoind_rpc_addr = match SocketAddr::from_str(&args[5]) {
Ok(addr) => addr,
Err(_) => {
eprintln!("Failed to parse bitcoind_rpc_addr: {}", args[3]);
std::process::exit(-1);
},
};
let bitcoind_rpc_addr = config_file.bitcoind_rpc_addr;

builder.set_chain_source_bitcoind_rpc(
bitcoind_rpc_addr.ip().to_string(),
bitcoind_rpc_addr.port(),
args[6].clone(),
args[7].clone(),
config_file.bitcoind_rpc_user,
config_file.bitcoind_rpc_password,
);

let runtime = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
Expand DownExpand Up@@ -116,8 +85,9 @@ fn main() {
},
};
let event_node = Arc::clone(&node);
let rest_svc_listener =
TcpListener::bind(rest_svc_addr).await.expect("Failed to bind listening port");
let rest_svc_listener = TcpListener::bind(config_file.rest_service_addr)
.await
.expect("Failed to bind listening port");
loop {
tokio::select! {
event = event_node.next_event_async() => {
Expand Down
136 changes: 136 additions & 0 deletions ldk-server/src/util/config.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::{fs, io};

/// Configuration for LDK Server.
#[derive(PartialEq, Eq, Debug)]
pub struct Config {
pub listening_addr: SocketAddress,
pub network: Network,
pub rest_service_addr: SocketAddr,
pub storage_dir_path: String,
pub bitcoind_rpc_addr: SocketAddr,
pub bitcoind_rpc_user: String,
pub bitcoind_rpc_password: String,
}

impl TryFrom<JsonConfig> for Config {
type Error = io::Error;

fn try_from(json_config: JsonConfig) -> io::Result<Self> {
let listening_addr =
SocketAddress::from_str(&json_config.listening_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid listening address configured: {}", e),
)
})?;
let rest_service_addr =
SocketAddr::from_str(&json_config.rest_service_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid rest service address configured: {}", e),
)
})?;

let bitcoind_rpc_addr =
SocketAddr::from_str(&json_config.bitcoind_rpc_address).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid bitcoind RPC address configured: {}", e),
)
})?;

Ok(Config {
listening_addr,
network: json_config.network,
rest_service_addr,
storage_dir_path: json_config.storage_dir_path,
bitcoind_rpc_addr,
bitcoind_rpc_user: json_config.bitcoind_rpc_user,
bitcoind_rpc_password: json_config.bitcoind_rpc_password,
})
}
}

/// Configuration loaded from a JSON file.
#[derive(Deserialize, Serialize)]
pub struct JsonConfig {
listening_address: String,
network: Network,
rest_service_address: String,
storage_dir_path: String,
bitcoind_rpc_address: String,
bitcoind_rpc_user: String,
bitcoind_rpc_password: String,
}

/// Loads the configuration from a JSON file at the given path.
pub fn load_config<P: AsRef<Path>>(config_path: P) -> io::Result<Config> {
let file_contents = fs::read_to_string(config_path.as_ref()).map_err(|e| {
io::Error::new(
e.kind(),
format!("Failed to read config file '{}': {}", config_path.as_ref().display(), e),
)
})?;

let json_string = remove_json_comments(file_contents.as_str());
let json_config: JsonConfig = serde_json::from_str(&json_string).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Config file contains invalid JSON format: {}", e),
)
})?;
Ok(Config::try_from(json_config)?)
}

fn remove_json_comments(s: &str) -> String {
s.lines()
.map(|line| if let Some(pos) = line.find("//") { &line[..pos] } else { line })
.collect::<Vec<&str>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
use ldk_node::{bitcoin::Network, lightning::ln::msgs::SocketAddress};
use std::str::FromStr;

#[test]
fn test_read_json_config_from_file() {
let storage_path = std::env::temp_dir();
let config_file_name = "config.json";

let json_config = r#"{
"listening_address": "localhost:3001",
"network": "regtest",
"rest_service_address": "127.0.0.1:3002",
"storage_dir_path": "/tmp",
"bitcoind_rpc_address":"127.0.0.1:8332", // comment-1
"bitcoind_rpc_user": "bitcoind-testuser",
"bitcoind_rpc_password": "bitcoind-testpassword",
"unknown_key": "random-value"
// comment-2
}"#;

fs::write(storage_path.join(config_file_name), json_config).unwrap();

assert_eq!(
load_config(storage_path.join(config_file_name)).unwrap(),
Config {
listening_addr: SocketAddress::from_str("localhost:3001").unwrap(),
network: Network::Regtest,
rest_service_addr: SocketAddr::from_str("127.0.0.1:3002").unwrap(),
storage_dir_path: "/tmp".to_string(),
bitcoind_rpc_addr: SocketAddr::from_str("127.0.0.1:8332").unwrap(),
bitcoind_rpc_user: "bitcoind-testuser".to_string(),
bitcoind_rpc_password: "bitcoind-testpassword".to_string(),
}
)
}
}
1 change: 1 addition & 0 deletions ldk-server/src/util/mod.rs
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
pub(crate) mod config;
pub(crate) mod proto_adapter;