diff options
Diffstat (limited to 'btc-wire/src/rpc.rs')
-rw-r--r-- | btc-wire/src/rpc.rs | 32 |
1 files changed, 22 insertions, 10 deletions
diff --git a/btc-wire/src/rpc.rs b/btc-wire/src/rpc.rs index 814127a..f022737 100644 --- a/btc-wire/src/rpc.rs +++ b/btc-wire/src/rpc.rs @@ -31,8 +31,8 @@ use serde_json::{json, Value}; use std::{ fmt::Debug, io::{self, BufRead, BufReader, Write}, - net::TcpStream, - time::Duration, + net::{TcpStream, SocketAddr}, + time::{Duration, Instant}, }; use crate::config::{BitcoinConfig, BtcAuth}; @@ -113,6 +113,8 @@ const EMPTY: [(); 0] = []; /// Bitcoin RPC connection pub struct Rpc { + last_call: Instant, + addr: SocketAddr, path: String, id: u64, cookie: String, @@ -149,6 +151,8 @@ impl Rpc { let conn = BufReader::new(sock); Ok(Self { + last_call: Instant::now(), + addr: config.addr, path, id: 0, cookie: format!("Basic {}", base64::encode(token)), @@ -161,7 +165,13 @@ impl Rpc { where T: serde::de::DeserializeOwned + Debug, { - // TODO rethink timeout + // Handle bitcoind RPC client timeout + if self.last_call.elapsed() > Duration::from_secs(60) { + // Create new connection + let sock = TcpStream::connect_timeout(&self.addr, Duration::from_secs(5))?; + self.conn = BufReader::new(sock); + } + let request = RpcRequest { method, id: self.id, @@ -203,7 +213,7 @@ impl Rpc { // Read body let amount = sock.read_until(b'\n', buf)?; let response: RpcResponse<T> = serde_json::from_slice(&buf[..amount])?; - match response { + let result = match response { RpcResponse::RpcResponse { result, error, id } => { assert_eq!(self.id, id); self.id += 1; @@ -220,7 +230,9 @@ impl Rpc { } } RpcResponse::Error(msg) => Err(Error::Bitcoin(msg)), - } + }; + self.last_call = Instant::now(); + return result; } /* ----- Wallet management ----- */ @@ -266,11 +278,6 @@ impl Rpc { /* ----- Getter ----- */ - /// Get block hash at a given height - pub fn get_block_hash(&mut self, height: u32) -> Result<BlockHash> { - self.call("getblockhash", &[height]) - } - /// Get blockchain info pub fn get_blockchain_info(&mut self) -> Result<BlockchainInfo> { self.call("getblockchaininfo", &EMPTY) @@ -291,6 +298,11 @@ impl Rpc { self.call("getrawtransaction", &(id, true)) } + /// Get genesis block hash + pub fn get_genesis(&mut self) -> Result<BlockHash> { + self.call("getblockhash", &[0]) + } + /* ----- Transactions ----- */ /// Send bitcoin transaction |