Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add several wallet APIs #10

Merged
merged 5 commits into from Oct 30, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Expand Up @@ -13,7 +13,7 @@ hex = "0.4.2"
reqwest = { version = "0.10", default-features = false, features = ["json", "native-tls"] }
serde = "1.0"
serde_json = "1.0"
testcontainers = "0.9"
testcontainers = "0.10"
thiserror = "1.0"
tokio = { version = "0.2", default-features = false, features = ["blocking", "macros", "rt-core", "time"] }
tracing = "0.1"
Expand Down
43 changes: 43 additions & 0 deletions src/bitcoind_rpc.rs
Expand Up @@ -37,6 +37,19 @@ impl Client {
Ok(blockchain_info.mediantime)
}

pub async fn block_height(&self) -> Result<u32> {
let block_height = self
.rpc_client
.send::<Vec<()>, _>(json_rpc::Request::new(
"getblockcount",
vec![],
JSONRPC_VERSION.into(),
))
.await?;

Ok(block_height)
}

async fn blockchain_info(&self) -> Result<BlockchainInfo> {
let blockchain_info = self
.rpc_client
Expand Down Expand Up @@ -222,6 +235,26 @@ impl Client {
Ok(transaction)
}

pub async fn get_transaction(
&self,
wallet_name: &str,
txid: Txid,
) -> Result<WalletTransactionInfo> {
let res = self
.rpc_client
.send_with_path(
format!("/wallet/{}", wallet_name),
json_rpc::Request::new(
"gettransaction",
vec![json_rpc::serialize(txid)?],
JSONRPC_VERSION.into(),
),
)
.await?;

Ok(res)
}

pub async fn dump_wallet(&self, wallet_name: &str, filename: &std::path::Path) -> Result<()> {
let _: DumpWalletResponse = self
.rpc_client
Expand Down Expand Up @@ -582,6 +615,16 @@ pub struct AddressInfo {
pub labels: Vec<String>,
}

/// Response to the RPC command `gettransaction`.
///
/// It only defines one field, but can be expanded to include all the
/// fields returned by `bitcoind` (see:
/// https://bitcoincore.org/en/doc/0.19.0/rpc/wallet/gettransaction/)
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub struct WalletTransactionInfo {
pub fee: f64,
}

#[cfg(all(test, feature = "test-docker"))]
mod test {
use super::*;
Expand Down
54 changes: 53 additions & 1 deletion src/wallet.rs
@@ -1,6 +1,6 @@
use crate::bitcoind_rpc::{
AddressInfo, Client, FinalizedPsbt, ProcessedPsbt, PsbtBase64, Result, Unspent,
WalletInfoResponse,
WalletInfoResponse, WalletTransactionInfo,
};
use bitcoin::{Address, Amount, Transaction, Txid};
use url::Url;
Expand Down Expand Up @@ -47,6 +47,10 @@ impl Wallet {
Ok(self.bitcoind_client.median_time().await?)
}

pub async fn block_height(&self) -> Result<u32> {
Ok(self.bitcoind_client.block_height().await?)
}

pub async fn new_address(&self) -> Result<Address> {
self.bitcoind_client
.get_new_address(&self.name, None, Some("bech32".into()))
Expand Down Expand Up @@ -77,6 +81,10 @@ impl Wallet {
.await
}

pub async fn get_wallet_transaction(&self, txid: Txid) -> Result<WalletTransactionInfo> {
self.bitcoind_client.get_transaction(&self.name, txid).await
}

pub async fn address_info(&self, address: &Address) -> Result<AddressInfo> {
self.bitcoind_client.address_info(&self.name, address).await
}
Expand Down Expand Up @@ -110,9 +118,35 @@ impl Wallet {

#[cfg(test)]
mod test {
use std::time::Duration;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extra newline.

use crate::{Bitcoind, Wallet};
use bitcoin::util::psbt::PartiallySignedTransaction;
use bitcoin::{Amount, Transaction, TxOut};
use tokio::time::delay_for;

#[tokio::test]
async fn get_wallet_transaction() {
let tc_client = testcontainers::clients::Cli::default();
let bitcoind = Bitcoind::new(&tc_client, "0.19.1").unwrap();
bitcoind.init(5).await.unwrap();

let wallet = Wallet::new("wallet", bitcoind.node_url.clone())
.await
.unwrap();
let mint_address = wallet.new_address().await.unwrap();
let mint_amount = bitcoin::Amount::from_btc(3.0).unwrap();
bitcoind.mint(mint_address, mint_amount).await.unwrap();

let pay_address = wallet.new_address().await.unwrap();
let pay_amount = bitcoin::Amount::from_btc(1.0).unwrap();
let txid = wallet
.send_to_address(pay_address, pay_amount)
.await
.unwrap();

let _res = wallet.get_wallet_transaction(txid).await.unwrap();
}

#[tokio::test]
async fn two_party_psbt_test() {
Expand Down Expand Up @@ -203,4 +237,22 @@ mod test {
.unwrap();
println!("Final tx_id: {:?}", txid);
}

#[tokio::test]
async fn block_height() {
let tc_client = testcontainers::clients::Cli::default();
let bitcoind = Bitcoind::new(&tc_client, "0.19.1").unwrap();
bitcoind.init(5).await.unwrap();

let wallet = Wallet::new("wallet", bitcoind.node_url.clone())
.await
.unwrap();

let height_0 = wallet.block_height().await.unwrap();
delay_for(Duration::from_secs(2)).await;

let height_1 = wallet.block_height().await.unwrap();

assert!(height_1 > height_0)
}
}