forked from lightningdevkit/ldk-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
312 lines (277 loc) · 12.8 KB
/
client.rs
File metadata and controls
312 lines (277 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
use std::time::{SystemTime, UNIX_EPOCH};
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,
CloseChannelRequest, CloseChannelResponse, ConnectPeerRequest, ConnectPeerResponse,
ForceCloseChannelRequest, ForceCloseChannelResponse, GetBalancesRequest, GetBalancesResponse,
GetNodeInfoRequest, GetNodeInfoResponse, GetPaymentDetailsRequest, GetPaymentDetailsResponse,
ListChannelsRequest, ListChannelsResponse, ListForwardedPaymentsRequest,
ListForwardedPaymentsResponse, ListPaymentsRequest, ListPaymentsResponse,
OnchainReceiveRequest, OnchainReceiveResponse, OnchainSendRequest, OnchainSendResponse,
OpenChannelRequest, OpenChannelResponse, SpliceInRequest, SpliceInResponse, SpliceOutRequest,
SpliceOutResponse, UpdateChannelConfigRequest, UpdateChannelConfigResponse,
};
use ldk_server_protos::endpoints::{
BOLT11_RECEIVE_PATH, BOLT11_SEND_PATH, BOLT12_RECEIVE_PATH, BOLT12_SEND_PATH,
CLOSE_CHANNEL_PATH, CONNECT_PEER_PATH, FORCE_CLOSE_CHANNEL_PATH, GET_BALANCES_PATH,
GET_NODE_INFO_PATH, GET_PAYMENT_DETAILS_PATH, LIST_CHANNELS_PATH, LIST_FORWARDED_PAYMENTS_PATH,
LIST_PAYMENTS_PATH, ONCHAIN_RECEIVE_PATH, ONCHAIN_SEND_PATH, OPEN_CHANNEL_PATH, SPLICE_IN_PATH,
SPLICE_OUT_PATH, UPDATE_CHANNEL_CONFIG_PATH,
};
use ldk_server_protos::error::{ErrorCode, ErrorResponse};
use prost::Message;
use reqwest::header::CONTENT_TYPE;
use reqwest::{Certificate, Client};
use crate::error::LdkServerError;
use crate::error::LdkServerErrorCode::{
AuthError, InternalError, InternalServerError, InvalidRequestError, LightningError,
};
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.crt` 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.
///
/// `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.crt` 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(×tamp.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!("https://{}/{GET_NODE_INFO_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieves an overview of all known balances.
/// For API contract/usage, refer to docs for [`GetBalancesRequest`] and [`GetBalancesResponse`].
pub async fn get_balances(
&self, request: GetBalancesRequest,
) -> Result<GetBalancesResponse, LdkServerError> {
let url = format!("https://{}/{GET_BALANCES_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieve a new on-chain funding address.
/// For API contract/usage, refer to docs for [`OnchainReceiveRequest`] and [`OnchainReceiveResponse`].
pub async fn onchain_receive(
&self, request: OnchainReceiveRequest,
) -> Result<OnchainReceiveResponse, LdkServerError> {
let url = format!("https://{}/{ONCHAIN_RECEIVE_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Send an on-chain payment to the given address.
/// For API contract/usage, refer to docs for [`OnchainSendRequest`] and [`OnchainSendResponse`].
pub async fn onchain_send(
&self, request: OnchainSendRequest,
) -> Result<OnchainSendResponse, LdkServerError> {
let url = format!("https://{}/{ONCHAIN_SEND_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieve a new BOLT11 payable invoice.
/// For API contract/usage, refer to docs for [`Bolt11ReceiveRequest`] and [`Bolt11ReceiveResponse`].
pub async fn bolt11_receive(
&self, request: Bolt11ReceiveRequest,
) -> Result<Bolt11ReceiveResponse, LdkServerError> {
let url = format!("https://{}/{BOLT11_RECEIVE_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Send a payment for a BOLT11 invoice.
/// For API contract/usage, refer to docs for [`Bolt11SendRequest`] and [`Bolt11SendResponse`].
pub async fn bolt11_send(
&self, request: Bolt11SendRequest,
) -> Result<Bolt11SendResponse, LdkServerError> {
let url = format!("https://{}/{BOLT11_SEND_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieve a new BOLT11 payable offer.
/// For API contract/usage, refer to docs for [`Bolt12ReceiveRequest`] and [`Bolt12ReceiveResponse`].
pub async fn bolt12_receive(
&self, request: Bolt12ReceiveRequest,
) -> Result<Bolt12ReceiveResponse, LdkServerError> {
let url = format!("https://{}/{BOLT12_RECEIVE_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Send a payment for a BOLT12 offer.
/// For API contract/usage, refer to docs for [`Bolt12SendRequest`] and [`Bolt12SendResponse`].
pub async fn bolt12_send(
&self, request: Bolt12SendRequest,
) -> Result<Bolt12SendResponse, LdkServerError> {
let url = format!("https://{}/{BOLT12_SEND_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Creates a new outbound channel.
/// For API contract/usage, refer to docs for [`OpenChannelRequest`] and [`OpenChannelResponse`].
pub async fn open_channel(
&self, request: OpenChannelRequest,
) -> Result<OpenChannelResponse, LdkServerError> {
let url = format!("https://{}/{OPEN_CHANNEL_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Splices funds into the channel specified by given request.
/// For API contract/usage, refer to docs for [`SpliceInRequest`] and [`SpliceInResponse`].
pub async fn splice_in(
&self, request: SpliceInRequest,
) -> Result<SpliceInResponse, LdkServerError> {
let url = format!("https://{}/{SPLICE_IN_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Splices funds out of the channel specified by given request.
/// For API contract/usage, refer to docs for [`SpliceOutRequest`] and [`SpliceOutResponse`].
pub async fn splice_out(
&self, request: SpliceOutRequest,
) -> Result<SpliceOutResponse, LdkServerError> {
let url = format!("https://{}/{SPLICE_OUT_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Closes the channel specified by given request.
/// For API contract/usage, refer to docs for [`CloseChannelRequest`] and [`CloseChannelResponse`].
pub async fn close_channel(
&self, request: CloseChannelRequest,
) -> Result<CloseChannelResponse, LdkServerError> {
let url = format!("https://{}/{CLOSE_CHANNEL_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Force closes the channel specified by given request.
/// For API contract/usage, refer to docs for [`ForceCloseChannelRequest`] and [`ForceCloseChannelResponse`].
pub async fn force_close_channel(
&self, request: ForceCloseChannelRequest,
) -> Result<ForceCloseChannelResponse, LdkServerError> {
let url = format!("https://{}/{FORCE_CLOSE_CHANNEL_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieves list of known channels.
/// For API contract/usage, refer to docs for [`ListChannelsRequest`] and [`ListChannelsResponse`].
pub async fn list_channels(
&self, request: ListChannelsRequest,
) -> Result<ListChannelsResponse, LdkServerError> {
let url = format!("https://{}/{LIST_CHANNELS_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieves list of all payments sent or received by us.
/// For API contract/usage, refer to docs for [`ListPaymentsRequest`] and [`ListPaymentsResponse`].
pub async fn list_payments(
&self, request: ListPaymentsRequest,
) -> Result<ListPaymentsResponse, LdkServerError> {
let url = format!("https://{}/{LIST_PAYMENTS_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Updates the config for a previously opened channel.
/// For API contract/usage, refer to docs for [`UpdateChannelConfigRequest`] and [`UpdateChannelConfigResponse`].
pub async fn update_channel_config(
&self, request: UpdateChannelConfigRequest,
) -> Result<UpdateChannelConfigResponse, LdkServerError> {
let url = format!("https://{}/{UPDATE_CHANNEL_CONFIG_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieves payment details for a given payment id.
/// For API contract/usage, refer to docs for [`GetPaymentDetailsRequest`] and [`GetPaymentDetailsResponse`].
pub async fn get_payment_details(
&self, request: GetPaymentDetailsRequest,
) -> Result<GetPaymentDetailsResponse, LdkServerError> {
let url = format!("https://{}/{GET_PAYMENT_DETAILS_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Retrieves list of all forwarded payments.
/// For API contract/usage, refer to docs for [`ListForwardedPaymentsRequest`] and [`ListForwardedPaymentsResponse`].
pub async fn list_forwarded_payments(
&self, request: ListForwardedPaymentsRequest,
) -> Result<ListForwardedPaymentsResponse, LdkServerError> {
let url = format!("https://{}/{LIST_FORWARDED_PAYMENTS_PATH}", self.base_url);
self.post_request(&request, &url).await
}
/// Connect to a peer on the Lightning Network.
/// For API contract/usage, refer to docs for [`ConnectPeerRequest`] and [`ConnectPeerResponse`].
pub async fn connect_peer(
&self, request: ConnectPeerRequest,
) -> Result<ConnectPeerResponse, LdkServerError> {
let url = format!("https://{}/{CONNECT_PEER_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
.map_err(|e| {
LdkServerError::new(InternalError, format!("HTTP request failed: {}", e))
})?;
let status = response_raw.status();
let payload = response_raw.bytes().await.map_err(|e| {
LdkServerError::new(InternalError, format!("Failed to read response body: {}", e))
})?;
if status.is_success() {
Ok(Rs::decode(&payload[..]).map_err(|e| {
LdkServerError::new(
InternalError,
format!("Failed to decode success response: {}", e),
)
})?)
} else {
let error_response = ErrorResponse::decode(&payload[..]).map_err(|e| {
LdkServerError::new(
InternalError,
format!("Failed to decode error response (status {}): {}", status, e),
)
})?;
let error_code = match ErrorCode::from_i32(error_response.error_code) {
Some(ErrorCode::InvalidRequestError) => InvalidRequestError,
Some(ErrorCode::AuthError) => AuthError,
Some(ErrorCode::LightningError) => LightningError,
Some(ErrorCode::InternalServerError) => InternalServerError,
Some(ErrorCode::UnknownError) | None => InternalError,
};
Err(LdkServerError::new(error_code, error_response.message))
}
}
}