Skip to content
Open
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
2 changes: 2 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.
```
5 changes: 4 additions & 1 deletion ldk-server-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ struct Cli {
#[arg(short, long, default_value = "localhost:3000")]
base_url: String,

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

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

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"
28 changes: 26 additions & 2 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 @@ -32,6 +34,7 @@ use ldk_server_protos::endpoints::{
use ldk_server_protos::error::{ErrorCode, ErrorResponse};
use reqwest::header::CONTENT_TYPE;
use reqwest::Client;
use std::time::{SystemTime, UNIX_EPOCH};

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

Expand All @@ -40,12 +43,31 @@ const APPLICATION_OCTET_STREAM: &str = "application/octet-stream";
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() }
/// `api_key` is used for HMAC-based authentication.
pub fn new(base_url: String, api_key: String) -> Self {
Self { base_url, client: Client::new(), 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.
Expand Down Expand Up @@ -196,10 +218,12 @@ impl LdkServerClient {
&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
1 change: 1 addition & 0 deletions ldk-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,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
2 changes: 1 addition & 1 deletion ldk-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ fn main() {
match res {
Ok((stream, _)) => {
let io_stream = TokioIo::new(stream);
let node_service = NodeService::new(Arc::clone(&node), Arc::clone(&paginated_store));
let node_service = NodeService::new(Arc::clone(&node), Arc::clone(&paginated_store), config_file.auth_config.clone());
runtime.spawn(async move {
if let Err(err) = http1::Builder::new().serve_connection(io_stream, node_service).await {
error!("Failed to serve connection: {}", err);
Expand Down
Loading