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 all 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
105 changes: 99 additions & 6 deletions src/bitcoind_rpc.rs
Expand Up @@ -7,6 +7,7 @@ use ::bitcoin::{
};
use bitcoin::{consensus::encode, Script};
use reqwest::Url;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

pub type Result<T> = std::result::Result<T, Error>;
Expand Down Expand Up @@ -37,6 +38,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 @@ -204,22 +218,57 @@ impl Client {
Ok(txid)
}

pub async fn get_raw_transaction(&self, wallet_name: &str, txid: Txid) -> Result<Transaction> {
let hex: String = self
pub async fn get_raw_transaction(&self, txid: Txid) -> Result<Transaction> {
let hex: String = self.get_raw_transaction_rpc(txid, false).await?;
let bytes: Vec<u8> = FromHex::from_hex(&hex)?;
let transaction = bitcoin::consensus::encode::deserialize(&bytes)?;

Ok(transaction)
}

pub async fn get_raw_transaction_verbose(
&self,
txid: Txid,
) -> Result<GetRawTransactionVerboseResponse> {
let res = self.get_raw_transaction_rpc(txid, true).await?;

Ok(res)
}

async fn get_raw_transaction_rpc<R>(&self, txid: Txid, is_verbose: bool) -> Result<R>
where
R: std::fmt::Debug + DeserializeOwned,
{
let res = self
.rpc_client
.send(json_rpc::Request::new(
"getrawtransaction",
vec![json_rpc::serialize(txid)?, json_rpc::serialize(is_verbose)?],
JSONRPC_VERSION.into(),
))
.await?;

Ok(res)
}

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(
"getrawtransaction",
"gettransaction",
vec![json_rpc::serialize(txid)?],
JSONRPC_VERSION.into(),
),
)
.await?;
let bytes: Vec<u8> = FromHex::from_hex(&hex)?;
let transaction = bitcoin::consensus::encode::deserialize(&bytes)?;

Ok(transaction)
Ok(res)
}

pub async fn dump_wallet(&self, wallet_name: &str, filename: &std::path::Path) -> Result<()> {
Expand Down Expand Up @@ -421,6 +470,18 @@ impl Client {
.await?;
Ok(address_info)
}

pub async fn get_block(&self, block_hash: &bitcoin::BlockHash) -> Result<GetBlockResponse> {
let res = self
.rpc_client
.send(json_rpc::Request::new(
"getblock",
vec![json_rpc::serialize(block_hash)?],
JSONRPC_VERSION.into(),
))
.await?;
Ok(res)
}
}

#[derive(Debug, thiserror::Error)]
Expand Down Expand Up @@ -582,6 +643,38 @@ 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,
}

/// Response to the RPC command `getrawtransaction`, when the second
/// argument is set to `true`.
///
/// 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/rawtransactions/getrawtransaction/)
#[derive(Clone, Copy, Debug, Deserialize)]
pub struct GetRawTransactionVerboseResponse {
#[serde(rename = "blockhash")]
pub block_hash: Option<bitcoin::BlockHash>,
}

/// Response to the RPC command `getblock`.
///
/// 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/blockchain/getblock/)
#[derive(Copy, Clone, Debug, Deserialize)]
pub struct GetBlockResponse {
pub height: u32,
}

#[cfg(all(test, feature = "test-docker"))]
mod test {
use super::*;
Expand Down
102 changes: 98 additions & 4 deletions 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 All @@ -72,9 +76,11 @@ impl Wallet {
}

pub async fn get_raw_transaction(&self, txid: Txid) -> Result<Transaction> {
self.bitcoind_client
.get_raw_transaction(&self.name, txid)
.await
self.bitcoind_client.get_raw_transaction(txid).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> {
Expand Down Expand Up @@ -106,13 +112,55 @@ impl Wallet {
pub async fn finalize_psbt(&self, psbt: PsbtBase64) -> Result<FinalizedPsbt> {
self.bitcoind_client.finalize_psbt(&self.name, psbt).await
}

pub async fn transaction_block_height(&self, txid: Txid) -> Result<Option<u32>> {
let res = self
.bitcoind_client
.get_raw_transaction_verbose(txid)
.await?;

let block_hash = match res.block_hash {
Some(block_hash) => block_hash,
None => return Ok(None),
};

let res = self.bitcoind_client.get_block(&block_hash).await?;

Ok(Some(res.height))
}
}

#[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 +251,50 @@ 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)
}

#[tokio::test]
async fn transaction_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 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();

// wait for the transaction to be included in a block, so that
// it has a block height field assigned to it when calling
// `getrawtransaction`
delay_for(Duration::from_secs(2)).await;

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