1111
1212//! Esplora by way of `reqwest` HTTP client.
1313
14- use std:: collections:: HashMap ;
14+ use std:: collections:: { HashMap , HashSet } ;
1515use std:: marker:: PhantomData ;
1616use std:: str:: FromStr ;
1717use std:: time:: Duration ;
1818
1919use bitcoin:: block:: Header as BlockHeader ;
20- use bitcoin:: consensus:: { deserialize, serialize, Decodable , Encodable } ;
20+ use bitcoin:: consensus:: encode:: serialize_hex;
21+ use bitcoin:: consensus:: { deserialize, serialize, Decodable } ;
2122use bitcoin:: hashes:: { sha256, Hash } ;
2223use bitcoin:: hex:: { DisplayHex , FromHex } ;
2324use bitcoin:: { Address , Block , BlockHash , MerkleBlock , Script , Transaction , Txid } ;
2425
2526#[ allow( unused_imports) ]
2627use log:: { debug, error, info, trace} ;
2728
28- use reqwest:: { header, Client , Response } ;
29+ use reqwest:: { header, Body , Client , Response } ;
2930
3031use crate :: {
3132 AddressStats , BlockInfo , BlockStatus , BlockSummary , Builder , Error , MempoolRecentTx ,
32- MempoolStats , MerkleProof , OutputStatus , ScriptHashStats , Tx , TxStatus , Utxo ,
33- BASE_BACKOFF_MILLIS , RETRYABLE_ERROR_CODES ,
33+ MempoolStats , MerkleProof , OutputStatus , ScriptHashStats , SubmitPackageResult , Tx , TxStatus ,
34+ Utxo , BASE_BACKOFF_MILLIS , RETRYABLE_ERROR_CODES ,
3435} ;
3536
3637/// An async client for interacting with an Esplora API server.
@@ -249,21 +250,27 @@ impl<S: Sleeper> AsyncClient<S> {
249250 }
250251 }
251252
252- /// Make an HTTP POST request to given URL, serializing from any `T` that
253- /// implement [`bitcoin::consensus::Encodable`].
254- ///
255- /// It should be used when requesting Esplora endpoints that expected a
256- /// native bitcoin type serialized with [`bitcoin::consensus::Encodable`].
253+ /// Make an HTTP POST request to given URL, converting any `T` that
254+ /// implement [`Into<Body>`] and setting query parameters, if any.
257255 ///
258256 /// # Errors
259257 ///
260258 /// This function will return an error either from the HTTP client, or the
261- /// [`bitcoin::consensus::Encodable`] serialization.
262- async fn post_request_hex < T : Encodable > ( & self , path : & str , body : T ) -> Result < ( ) , Error > {
263- let url = format ! ( "{}{}" , self . url, path) ;
264- let body = serialize :: < T > ( & body) . to_lower_hex_string ( ) ;
259+ /// response's [`serde_json`] deserialization.
260+ async fn post_request_bytes < T : Into < Body > > (
261+ & self ,
262+ path : & str ,
263+ body : T ,
264+ query_params : Option < HashSet < ( & str , String ) > > ,
265+ ) -> Result < Response , Error > {
266+ let url: String = format ! ( "{}{}" , self . url, path) ;
267+ let mut request = self . client . post ( url) . body ( body) ;
268+
269+ for param in query_params. unwrap_or_default ( ) {
270+ request = request. query ( & param) ;
271+ }
265272
266- let response = self . client . post ( url ) . body ( body ) . send ( ) . await ?;
273+ let response = request . send ( ) . await ?;
267274
268275 if !response. status ( ) . is_success ( ) {
269276 return Err ( Error :: HttpResponse {
@@ -272,7 +279,7 @@ impl<S: Sleeper> AsyncClient<S> {
272279 } ) ;
273280 }
274281
275- Ok ( ( ) )
282+ Ok ( response )
276283 }
277284
278285 /// Get a [`Transaction`] option given its [`Txid`]
@@ -365,8 +372,49 @@ impl<S: Sleeper> AsyncClient<S> {
365372 }
366373
367374 /// Broadcast a [`Transaction`] to Esplora
368- pub async fn broadcast ( & self , transaction : & Transaction ) -> Result < ( ) , Error > {
369- self . post_request_hex ( "/tx" , transaction) . await
375+ pub async fn broadcast ( & self , transaction : & Transaction ) -> Result < Txid , Error > {
376+ let body = serialize :: < Transaction > ( transaction) . to_lower_hex_string ( ) ;
377+ let response = self . post_request_bytes ( "/tx" , body, None ) . await ?;
378+ let txid = Txid :: from_str ( & response. text ( ) . await ?) . map_err ( |_| Error :: InvalidResponse ) ?;
379+ Ok ( txid)
380+ }
381+
382+ /// Broadcast a package of [`Transaction`] to Esplora
383+ ///
384+ /// If `maxfeerate` is provided, any transaction whose
385+ /// fee is higher will be rejected
386+ ///
387+ /// If `maxburnamount` is provided, any transaction
388+ /// with higher provably unspendable outputs amount
389+ /// will be rejected.
390+ pub async fn submit_package (
391+ & self ,
392+ transactions : & [ Transaction ] ,
393+ maxfeerate : Option < f64 > ,
394+ maxburnamount : Option < f64 > ,
395+ ) -> Result < SubmitPackageResult , Error > {
396+ let mut queryparams = HashSet :: < ( & str , String ) > :: new ( ) ;
397+ if let Some ( maxfeerate) = maxfeerate {
398+ queryparams. insert ( ( "maxfeerate" , maxfeerate. to_string ( ) ) ) ;
399+ }
400+ if let Some ( maxburnamount) = maxburnamount {
401+ queryparams. insert ( ( "maxburnamount" , maxburnamount. to_string ( ) ) ) ;
402+ }
403+
404+ let serialized_txs = transactions
405+ . iter ( )
406+ . map ( |tx| serialize_hex ( & tx) )
407+ . collect :: < Vec < _ > > ( ) ;
408+
409+ let response = self
410+ . post_request_bytes (
411+ "/txs/package" ,
412+ serde_json:: to_string ( & serialized_txs) . unwrap ( ) ,
413+ Some ( queryparams) ,
414+ )
415+ . await ?;
416+
417+ Ok ( response. json :: < SubmitPackageResult > ( ) . await ?)
370418 }
371419
372420 /// Get the current height of the blockchain tip
0 commit comments