-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathv1.rs
403 lines (366 loc) · 15.9 KB
/
v1.rs
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::collections::HashMap;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use anyhow::{anyhow, Context, Result};
use bitcoincore_rpc::bitcoin::Amount;
use bitcoincore_rpc::RpcApi;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full};
use hyper::body::{Buf, Bytes, Incoming};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use payjoin::bitcoin::psbt::Psbt;
use payjoin::bitcoin::{self, FeeRate};
use payjoin::receive::{PayjoinProposal, UncheckedProposal};
use payjoin::send::v1::SenderBuilder;
use payjoin::{Error, PjUriBuilder, Uri, UriExt};
use tokio::net::TcpListener;
use super::config::AppConfig;
use super::App as AppTrait;
use crate::app::{http_agent, input_pair_from_list_unspent};
use crate::db::Database;
#[cfg(feature = "_danger-local-https")]
pub const LOCAL_CERT_FILE: &str = "localhost.der";
struct Headers<'a>(&'a hyper::HeaderMap);
impl payjoin::receive::Headers for Headers<'_> {
fn get_header(&self, key: &str) -> Option<&str> {
self.0.get(key).map(|v| v.to_str()).transpose().ok().flatten()
}
}
#[derive(Clone)]
pub(crate) struct App {
config: AppConfig,
db: Arc<Database>,
}
#[async_trait::async_trait]
impl AppTrait for App {
fn new(config: AppConfig) -> Result<Self> {
let db = Arc::new(Database::create(&config.db_path)?);
let app = Self { config, db };
app.bitcoind()?
.get_blockchain_info()
.context("Failed to connect to bitcoind. Check config RPC connection.")?;
Ok(app)
}
fn bitcoind(&self) -> Result<bitcoincore_rpc::Client> {
match &self.config.bitcoind_cookie {
Some(cookie) => bitcoincore_rpc::Client::new(
self.config.bitcoind_rpchost.as_str(),
bitcoincore_rpc::Auth::CookieFile(cookie.into()),
),
None => bitcoincore_rpc::Client::new(
self.config.bitcoind_rpchost.as_str(),
bitcoincore_rpc::Auth::UserPass(
self.config.bitcoind_rpcuser.clone(),
self.config.bitcoind_rpcpassword.clone(),
),
),
}
.with_context(|| "Failed to connect to bitcoind")
}
async fn send_payjoin(&self, bip21: &str, fee_rate: &f32) -> Result<()> {
let uri =
Uri::try_from(bip21).map_err(|e| anyhow!("Failed to create URI from BIP21: {}", e))?;
let uri = uri.assume_checked();
let uri = uri.check_pj_supported().map_err(|_| anyhow!("URI does not support Payjoin"))?;
let psbt = self.create_original_psbt(&uri, fee_rate)?;
let fee_rate_sat_per_kwu = fee_rate * 250.0_f32;
let fee_rate = FeeRate::from_sat_per_kwu(fee_rate_sat_per_kwu.ceil() as u64);
let (req, ctx) = SenderBuilder::new(psbt, uri.clone())
.build_recommended(fee_rate)
.with_context(|| "Failed to build payjoin request")?
.extract_v1()?;
let http = http_agent()?;
let body = String::from_utf8(req.body.clone()).unwrap();
println!("Sending fallback request to {}", &req.url);
let response = http
.post(req.url)
.header("Content-Type", req.content_type)
.body(body.clone())
.send()
.await
.with_context(|| "HTTP request failed")?;
let fallback_tx = Psbt::from_str(&body)
.map_err(|e| anyhow!("Failed to load PSBT from base64: {}", e))?
.extract_tx()?;
println!("Sent fallback transaction txid: {}", fallback_tx.compute_txid());
println!(
"Sent fallback transaction hex: {:#}",
payjoin::bitcoin::consensus::encode::serialize_hex(&fallback_tx)
);
let psbt = ctx.process_response(&mut response.bytes().await?.to_vec().as_slice()).map_err(
|e| {
log::debug!("Error processing response: {:?}", e);
anyhow!("Failed to process response {}", e)
},
)?;
self.process_pj_response(psbt)?;
Ok(())
}
async fn receive_payjoin(self, amount_arg: &str) -> Result<()> {
let pj_uri_string = self.construct_payjoin_uri(amount_arg, None)?;
println!(
"Listening at {}. Configured to accept payjoin at BIP 21 Payjoin Uri:",
self.config.port
);
println!("{}", pj_uri_string);
self.start_http_server().await?;
Ok(())
}
}
impl App {
fn construct_payjoin_uri(
&self,
amount_arg: &str,
fallback_target: Option<&str>,
) -> Result<String> {
let pj_receiver_address = self.bitcoind()?.get_new_address(None, None)?.assume_checked();
let amount = Amount::from_sat(amount_arg.parse()?);
let pj_part = match fallback_target {
Some(target) => target,
None => self.config.pj_endpoint.as_str(),
};
let pj_part = payjoin::Url::parse(pj_part)
.map_err(|e| anyhow!("Failed to parse pj_endpoint: {}", e))?;
let pj_uri = PjUriBuilder::new(pj_receiver_address, pj_part).amount(amount).build();
Ok(pj_uri.to_string())
}
async fn start_http_server(self) -> Result<()> {
let addr = SocketAddr::from(([0, 0, 0, 0], self.config.port));
let listener = TcpListener::bind(addr).await?;
let app = self.clone();
#[cfg(feature = "_danger-local-https")]
let tls_acceptor = Self::init_tls_acceptor()?;
while let Ok((stream, _)) = listener.accept().await {
let app = app.clone();
#[cfg(feature = "_danger-local-https")]
let tls_acceptor = tls_acceptor.clone();
tokio::spawn(async move {
#[cfg(feature = "_danger-local-https")]
let stream = match tls_acceptor.accept(stream).await {
Ok(tls_stream) => tls_stream,
Err(e) => {
log::error!("TLS accept error: {}", e);
return;
}
};
let _ = http1::Builder::new()
.serve_connection(
TokioIo::new(stream),
service_fn(move |req| app.clone().handle_web_request(req)),
)
.await;
});
}
Ok(())
}
#[cfg(feature = "_danger-local-https")]
fn init_tls_acceptor() -> Result<tokio_rustls::TlsAcceptor> {
use std::io::Write;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::ServerConfig;
use tokio_rustls::TlsAcceptor;
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;
let cert_der = cert.serialize_der()?;
let mut local_cert_path = std::env::temp_dir();
local_cert_path.push(LOCAL_CERT_FILE);
let mut file = std::fs::File::create(local_cert_path)?;
file.write_all(&cert_der)?;
let key = PrivateKeyDer::try_from(cert.serialize_private_key_der())
.map_err(|e| anyhow::anyhow!("Could not parse key: {}", e))?;
let certs = vec![CertificateDer::from(cert_der)];
let mut server_config = ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(certs, key)
.map_err(|e| anyhow::anyhow!("TLS error: {}", e))?;
server_config.alpn_protocols =
vec![b"h2".to_vec(), b"http/1.1".to_vec(), b"http/1.0".to_vec()];
Ok(TlsAcceptor::from(Arc::new(server_config)))
}
async fn handle_web_request(
self,
req: Request<Incoming>,
) -> Result<Response<BoxBody<Bytes, hyper::Error>>> {
log::debug!("Received request: {:?}", req);
let mut response = match (req.method(), req.uri().path()) {
(&Method::GET, "/bip21") => {
let query_string = req.uri().query().unwrap_or("");
log::debug!("{:?}, {:?}", req.method(), query_string);
let query_params: HashMap<_, _> =
url::form_urlencoded::parse(query_string.as_bytes()).into_owned().collect();
let amount = query_params.get("amount").map(|amt| {
Amount::from_btc(amt.parse().expect("Failed to parse amount")).unwrap()
});
self.handle_get_bip21(amount)
.map_err(|e| {
log::error!("Error handling request: {}", e);
Response::builder().status(500).body(full(e.to_string())).unwrap()
})
.unwrap_or_else(|err_resp| err_resp)
}
(&Method::POST, _) => self
.handle_payjoin_post(req)
.await
.map_err(|e| match e {
Error::BadRequest(e) => {
log::error!("Error handling request: {}", e);
Response::builder().status(400).body(full(e.to_string())).unwrap()
}
e => {
log::error!("Error handling request: {}", e);
Response::builder().status(500).body(full(e.to_string())).unwrap()
}
})
.unwrap_or_else(|err_resp| err_resp),
_ => Response::builder().status(StatusCode::NOT_FOUND).body(full("Not found")).unwrap(),
};
response
.headers_mut()
.insert("Access-Control-Allow-Origin", hyper::header::HeaderValue::from_static("*"));
Ok(response)
}
fn handle_get_bip21(
&self,
amount: Option<Amount>,
) -> Result<Response<BoxBody<Bytes, hyper::Error>>, Error> {
let address = self
.bitcoind()
.map_err(|e| Error::Server(e.into()))?
.get_new_address(None, None)
.map_err(|e| Error::Server(e.into()))?
.assume_checked();
let uri_string = if let Some(amount) = amount {
format!(
"{}?amount={}&pj={}",
address.to_qr_uri(),
amount.to_btc(),
self.config.pj_endpoint
)
} else {
format!("{}?pj={}", address.to_qr_uri(), self.config.pj_endpoint)
};
let uri = payjoin::Uri::try_from(uri_string.clone())
.map_err(|_| Error::Server(anyhow!("Could not parse payjoin URI string.").into()))?;
let _ = uri.assume_checked(); // we just got it from bitcoind above
Ok(Response::new(full(uri_string)))
}
async fn handle_payjoin_post(
&self,
req: Request<Incoming>,
) -> Result<Response<BoxBody<Bytes, hyper::Error>>, Error> {
let (parts, body) = req.into_parts();
let headers = Headers(&parts.headers);
let query_string = parts.uri.query().unwrap_or("");
let body = body.collect().await.map_err(|e| Error::Server(e.into()))?.aggregate().reader();
let proposal =
payjoin::receive::UncheckedProposal::from_request(body, query_string, headers)?;
let payjoin_proposal = self.process_v1_proposal(proposal)?;
let psbt = payjoin_proposal.psbt();
let body = psbt.to_string();
println!(
"Responded with Payjoin proposal {}",
psbt.clone().extract_tx_unchecked_fee_rate().compute_txid()
);
Ok(Response::new(full(body)))
}
fn process_v1_proposal(&self, proposal: UncheckedProposal) -> Result<PayjoinProposal, Error> {
let bitcoind = self.bitcoind().map_err(|e| Error::Server(e.into()))?;
// in a payment processor where the sender could go offline, this is where you schedule to broadcast the original_tx
let _to_broadcast_in_failure_case = proposal.extract_tx_to_schedule_broadcast();
// The network is used for checks later
let network = bitcoind.get_blockchain_info().map_err(|e| Error::Server(e.into()))?.chain;
// Receive Check 1: Can Broadcast
let proposal = proposal.check_broadcast_suitability(None, |tx| {
let raw_tx = bitcoin::consensus::encode::serialize_hex(&tx);
let mempool_results =
bitcoind.test_mempool_accept(&[raw_tx]).map_err(|e| Error::Server(e.into()))?;
match mempool_results.first() {
Some(result) => Ok(result.allowed),
None => Err(Error::Server(
anyhow!("No mempool results returned on broadcast check").into(),
)),
}
})?;
log::trace!("check1");
// Receive Check 2: receiver can't sign for proposal inputs
let proposal = proposal.check_inputs_not_owned(|input| {
if let Ok(address) = bitcoin::Address::from_script(input, network) {
bitcoind
.get_address_info(&address)
.map(|info| info.is_mine.unwrap_or(false))
.map_err(|e| Error::Server(e.into()))
} else {
Ok(false)
}
})?;
log::trace!("check2");
// Receive Check 3: have we seen this input before? More of a check for non-interactive i.e. payment processor receivers.
let payjoin = proposal.check_no_inputs_seen_before(|input| {
self.db.insert_input_seen_before(*input).map_err(|e| Error::Server(e.into()))
})?;
log::trace!("check3");
let payjoin = payjoin.identify_receiver_outputs(|output_script| {
if let Ok(address) = bitcoin::Address::from_script(output_script, network) {
bitcoind
.get_address_info(&address)
.map(|info| info.is_mine.unwrap_or(false))
.map_err(|e| Error::Server(e.into()))
} else {
Ok(false)
}
})?;
let payjoin = payjoin
.substitute_receiver_script(
&bitcoind
.get_new_address(None, None)
.map_err(|e| Error::Server(e.into()))?
.require_network(network)
.map_err(|e| Error::Server(e.into()))?
.script_pubkey(),
)
.map_err(|e| Error::Server(e.into()))?
.commit_outputs();
let provisional_payjoin = try_contributing_inputs(payjoin.clone(), &bitcoind)
.unwrap_or_else(|e| {
log::warn!("Failed to contribute inputs: {}", e);
payjoin.commit_inputs()
});
let payjoin_proposal = provisional_payjoin.finalize_proposal(
|psbt: &Psbt| {
bitcoind
.wallet_process_psbt(&psbt.to_string(), None, None, Some(false))
.map(|res| Psbt::from_str(&res.psbt).map_err(|e| Error::Server(e.into())))
.map_err(|e| Error::Server(e.into()))?
},
Some(bitcoin::FeeRate::MIN),
self.config.max_fee_rate.map_or(Ok(FeeRate::ZERO), |fee_rate| {
FeeRate::from_sat_per_vb(fee_rate).ok_or(Error::Server("Invalid fee rate".into()))
})?,
)?;
Ok(payjoin_proposal)
}
}
fn try_contributing_inputs(
payjoin: payjoin::receive::WantsInputs,
bitcoind: &bitcoincore_rpc::Client,
) -> Result<payjoin::receive::ProvisionalProposal> {
let candidate_inputs = bitcoind
.list_unspent(None, None, None, None, None)
.context("Failed to list unspent from bitcoind")?
.into_iter()
.map(input_pair_from_list_unspent);
let selected_input = payjoin
.try_preserving_privacy(candidate_inputs)
.map_err(|e| anyhow!("Failed to make privacy preserving selection: {}", e))?;
log::debug!("selected input: {:#?}", selected_input);
Ok(payjoin
.contribute_inputs(vec![selected_input])
.expect("This shouldn't happen. Failed to contribute inputs.")
.commit_inputs())
}
fn full<T: Into<Bytes>>(chunk: T) -> BoxBody<Bytes, hyper::Error> {
Full::new(chunk.into()).map_err(|never| match never {}).boxed()
}