Skip to content
Draft
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
25 changes: 25 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ cargo run --bin ldk-server ./ldk-server/ldk-server-config.toml

Interact with the node using CLI:
```
./target/debug/ldk-server-cli -b localhost:3002 onchain-receive # To generate onchain-receive address.
./target/debug/ldk-server-cli -b localhost:3002 help # To print help/available commands.
./target/debug/ldk-server-cli -b localhost:3002 --api-key your-secret-api-key onchain-receive # To generate onchain-receive address.
./target/debug/ldk-server-cli -b localhost:3002 --api-key your-secret-api-key help # To print help/available commands.
```
23 changes: 22 additions & 1 deletion ldk-server-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ struct Cli {
#[arg(short, long, default_value = "localhost:3000")]
base_url: String,

#[arg(short, long)]
api_key: String,

#[arg(
short,
long,
help = "Path to the server's TLS certificate file (PEM format). Found at <server_storage_dir>/tls_cert.pem"
)]
tls_cert: String,

#[command(subcommand)]
command: Commands,
}
Expand Down Expand Up @@ -214,7 +224,18 @@ enum Commands {
#[tokio::main]
async fn main() {
let cli = Cli::parse();
let client = LdkServerClient::new(cli.base_url);

// Load server certificate for TLS verification
let server_cert_pem = std::fs::read(&cli.tls_cert).unwrap_or_else(|e| {
eprintln!("Failed to read server certificate file '{}': {}", cli.tls_cert, e);
std::process::exit(1);
});

let client =
LdkServerClient::new(cli.base_url, cli.api_key, &server_cert_pem).unwrap_or_else(|e| {
eprintln!("Failed to create client: {e}");
std::process::exit(1);
});

match cli.command {
Commands::GetNodeInfo => {
Expand Down
1 change: 1 addition & 0 deletions ldk-server-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ serde = ["ldk-server-protos/serde"]
ldk-server-protos = { path = "../ldk-server-protos" }
reqwest = { version = "0.11.13", default-features = false, features = ["rustls-tls"] }
prost = { version = "0.11.6", default-features = false, features = ["std", "prost-derive"] }
bitcoin_hashes = "0.14"
78 changes: 59 additions & 19 deletions ldk-server-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use crate::error::LdkServerError;
use crate::error::LdkServerErrorCode::{
AuthError, InternalError, InternalServerError, InvalidRequestError, LightningError,
};
use bitcoin_hashes::hmac::{Hmac, HmacEngine};
use bitcoin_hashes::{sha256, Hash, HashEngine};
use ldk_server_protos::api::{
Bolt11ReceiveRequest, Bolt11ReceiveResponse, Bolt11SendRequest, Bolt11SendResponse,
Bolt12ReceiveRequest, Bolt12ReceiveResponse, Bolt12SendRequest, Bolt12SendResponse,
Expand All @@ -31,29 +33,65 @@ use ldk_server_protos::endpoints::{
};
use ldk_server_protos::error::{ErrorCode, ErrorResponse};
use reqwest::header::CONTENT_TYPE;
use reqwest::Client;
use reqwest::{Certificate, Client};
use std::time::{SystemTime, UNIX_EPOCH};

const APPLICATION_OCTET_STREAM: &str = "application/octet-stream";

/// Client to access a hosted instance of LDK Server.
///
/// The client requires the server's TLS certificate to be provided for verification.
/// This certificate can be found at `<server_storage_dir>/tls_cert.pem` after the
/// server generates it on first startup.
#[derive(Clone)]
pub struct LdkServerClient {
base_url: String,
client: Client,
api_key: String,
}

impl LdkServerClient {
/// Constructs a [`LdkServerClient`] using `base_url` as the ldk-server endpoint.
pub fn new(base_url: String) -> Self {
Self { base_url, client: Client::new() }
///
/// `base_url` should not include the scheme, e.g., `localhost:3000`.
/// `api_key` is used for HMAC-based authentication.
/// `server_cert_pem` is the server's TLS certificate in PEM format. This can be
/// found at `<server_storage_dir>/tls_cert.pem` after the server starts.
pub fn new(base_url: String, api_key: String, server_cert_pem: &[u8]) -> Result<Self, String> {
let cert = Certificate::from_pem(server_cert_pem)
.map_err(|e| format!("Failed to parse server certificate: {e}"))?;

let client = Client::builder()
.add_root_certificate(cert)
.build()
.map_err(|e| format!("Failed to build HTTP client: {e}"))?;

Ok(Self { base_url, client, api_key })
}

/// Computes the HMAC-SHA256 authentication header value.
/// Format: "HMAC <timestamp>:<hmac_hex>"
fn compute_auth_header(&self, body: &[u8]) -> String {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("System time should be after Unix epoch")
.as_secs();

// Compute HMAC-SHA256(api_key, timestamp_bytes || body)
let mut hmac_engine: HmacEngine<sha256::Hash> = HmacEngine::new(self.api_key.as_bytes());
hmac_engine.input(&timestamp.to_be_bytes());
hmac_engine.input(body);
let hmac_result = Hmac::<sha256::Hash>::from_engine(hmac_engine);

format!("HMAC {}:{}", timestamp, hmac_result)
}

/// Retrieve the latest node info like `node_id`, `current_best_block` etc.
/// For API contract/usage, refer to docs for [`GetNodeInfoRequest`] and [`GetNodeInfoResponse`].
pub async fn get_node_info(
&self, request: GetNodeInfoRequest,
) -> Result<GetNodeInfoResponse, LdkServerError> {
let url = format!("http://{}/{GET_NODE_INFO_PATH}", self.base_url);
let url = format!("https://{}/{GET_NODE_INFO_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -62,7 +100,7 @@ impl LdkServerClient {
pub async fn get_balances(
&self, request: GetBalancesRequest,
) -> Result<GetBalancesResponse, LdkServerError> {
let url = format!("http://{}/{GET_BALANCES_PATH}", self.base_url);
let url = format!("https://{}/{GET_BALANCES_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -71,7 +109,7 @@ impl LdkServerClient {
pub async fn onchain_receive(
&self, request: OnchainReceiveRequest,
) -> Result<OnchainReceiveResponse, LdkServerError> {
let url = format!("http://{}/{ONCHAIN_RECEIVE_PATH}", self.base_url);
let url = format!("https://{}/{ONCHAIN_RECEIVE_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -80,7 +118,7 @@ impl LdkServerClient {
pub async fn onchain_send(
&self, request: OnchainSendRequest,
) -> Result<OnchainSendResponse, LdkServerError> {
let url = format!("http://{}/{ONCHAIN_SEND_PATH}", self.base_url);
let url = format!("https://{}/{ONCHAIN_SEND_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -89,7 +127,7 @@ impl LdkServerClient {
pub async fn bolt11_receive(
&self, request: Bolt11ReceiveRequest,
) -> Result<Bolt11ReceiveResponse, LdkServerError> {
let url = format!("http://{}/{BOLT11_RECEIVE_PATH}", self.base_url);
let url = format!("https://{}/{BOLT11_RECEIVE_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -98,7 +136,7 @@ impl LdkServerClient {
pub async fn bolt11_send(
&self, request: Bolt11SendRequest,
) -> Result<Bolt11SendResponse, LdkServerError> {
let url = format!("http://{}/{BOLT11_SEND_PATH}", self.base_url);
let url = format!("https://{}/{BOLT11_SEND_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -107,7 +145,7 @@ impl LdkServerClient {
pub async fn bolt12_receive(
&self, request: Bolt12ReceiveRequest,
) -> Result<Bolt12ReceiveResponse, LdkServerError> {
let url = format!("http://{}/{BOLT12_RECEIVE_PATH}", self.base_url);
let url = format!("https://{}/{BOLT12_RECEIVE_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -116,7 +154,7 @@ impl LdkServerClient {
pub async fn bolt12_send(
&self, request: Bolt12SendRequest,
) -> Result<Bolt12SendResponse, LdkServerError> {
let url = format!("http://{}/{BOLT12_SEND_PATH}", self.base_url);
let url = format!("https://{}/{BOLT12_SEND_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -125,7 +163,7 @@ impl LdkServerClient {
pub async fn open_channel(
&self, request: OpenChannelRequest,
) -> Result<OpenChannelResponse, LdkServerError> {
let url = format!("http://{}/{OPEN_CHANNEL_PATH}", self.base_url);
let url = format!("https://{}/{OPEN_CHANNEL_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -134,7 +172,7 @@ impl LdkServerClient {
pub async fn splice_in(
&self, request: SpliceInRequest,
) -> Result<SpliceInResponse, LdkServerError> {
let url = format!("http://{}/{SPLICE_IN_PATH}", self.base_url);
let url = format!("https://{}/{SPLICE_IN_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -143,7 +181,7 @@ impl LdkServerClient {
pub async fn splice_out(
&self, request: SpliceOutRequest,
) -> Result<SpliceOutResponse, LdkServerError> {
let url = format!("http://{}/{SPLICE_OUT_PATH}", self.base_url);
let url = format!("https://{}/{SPLICE_OUT_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -152,7 +190,7 @@ impl LdkServerClient {
pub async fn close_channel(
&self, request: CloseChannelRequest,
) -> Result<CloseChannelResponse, LdkServerError> {
let url = format!("http://{}/{CLOSE_CHANNEL_PATH}", self.base_url);
let url = format!("https://{}/{CLOSE_CHANNEL_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -161,7 +199,7 @@ impl LdkServerClient {
pub async fn force_close_channel(
&self, request: ForceCloseChannelRequest,
) -> Result<ForceCloseChannelResponse, LdkServerError> {
let url = format!("http://{}/{FORCE_CLOSE_CHANNEL_PATH}", self.base_url);
let url = format!("https://{}/{FORCE_CLOSE_CHANNEL_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -170,7 +208,7 @@ impl LdkServerClient {
pub async fn list_channels(
&self, request: ListChannelsRequest,
) -> Result<ListChannelsResponse, LdkServerError> {
let url = format!("http://{}/{LIST_CHANNELS_PATH}", self.base_url);
let url = format!("https://{}/{LIST_CHANNELS_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -179,7 +217,7 @@ impl LdkServerClient {
pub async fn list_payments(
&self, request: ListPaymentsRequest,
) -> Result<ListPaymentsResponse, LdkServerError> {
let url = format!("http://{}/{LIST_PAYMENTS_PATH}", self.base_url);
let url = format!("https://{}/{LIST_PAYMENTS_PATH}", self.base_url);
self.post_request(&request, &url).await
}

Expand All @@ -188,18 +226,20 @@ impl LdkServerClient {
pub async fn update_channel_config(
&self, request: UpdateChannelConfigRequest,
) -> Result<UpdateChannelConfigResponse, LdkServerError> {
let url = format!("http://{}/{UPDATE_CHANNEL_CONFIG_PATH}", self.base_url);
let url = format!("https://{}/{UPDATE_CHANNEL_CONFIG_PATH}", self.base_url);
self.post_request(&request, &url).await
}

async fn post_request<Rq: Message, Rs: Message + Default>(
&self, request: &Rq, url: &str,
) -> Result<Rs, LdkServerError> {
let request_body = request.encode_to_vec();
let auth_header = self.compute_auth_header(&request_body);
let response_raw = self
.client
.post(url)
.header(CONTENT_TYPE, APPLICATION_OCTET_STREAM)
.header("X-Auth", auth_header)
.body(request_body)
.send()
.await
Expand Down
3 changes: 3 additions & 0 deletions ldk-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ hyper = { version = "1", default-features = false, features = ["server", "http1"
http-body-util = { version = "0.1", default-features = false }
hyper-util = { version = "0.1", default-features = false, features = ["server-graceful"] }
tokio = { version = "1.38.0", default-features = false, features = ["time", "signal", "rt-multi-thread"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["ring"] }
rcgen = { version = "0.13", default-features = false, features = ["ring"] }
prost = { version = "0.11.6", default-features = false, features = ["std"] }
ldk-server-protos = { path = "../ldk-server-protos" }
bytes = { version = "1.4.0", default-features = false }
Expand All @@ -20,6 +22,7 @@ async-trait = { version = "0.1.85", default-features = false }
toml = { version = "0.8.9", default-features = false, features = ["parse"] }
chrono = { version = "0.4", default-features = false, features = ["clock"] }
log = "0.4.28"
base64 = { version = "0.21", default-features = false, features = ["std"] }

# Required for RabittMQ based EventPublisher. Only enabled for `events-rabbitmq` feature.
lapin = { version = "2.4.0", features = ["rustls"], default-features = false, optional = true }
Expand Down
4 changes: 4 additions & 0 deletions ldk-server/ldk-server-config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ dir_path = "/tmp/ldk-server/" # Path for LDK and BDK data persis
level = "Debug" # Log level (Error, Warn, Info, Debug, Trace)
file_path = "/tmp/ldk-server/ldk-server.log" # Log file path

# HMAC Authentication (REQUIRED)
[auth]
api_key = "your-secret-api-key"

# Must set either bitcoind or esplora settings, but not both

# Bitcoin Core settings
Expand Down
4 changes: 4 additions & 0 deletions ldk-server/src/api/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub(crate) enum LdkServerErrorCode {
/// Please refer to [`protos::error::ErrorCode::InvalidRequestError`].
InvalidRequestError,

/// Please refer to [`protos::error::ErrorCode::AuthError`].
AuthError,

/// Please refer to [`protos::error::ErrorCode::LightningError`].
LightningError,

Expand All @@ -54,6 +57,7 @@ impl fmt::Display for LdkServerErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LdkServerErrorCode::InvalidRequestError => write!(f, "InvalidRequestError"),
LdkServerErrorCode::AuthError => write!(f, "AuthError"),
LdkServerErrorCode::LightningError => write!(f, "LightningError"),
LdkServerErrorCode::InternalServerError => write!(f, "InternalServerError"),
}
Expand Down
Loading