Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion Cargo-minimal.lock
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,17 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"

[[package]]
name = "corepc-types"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a7f2faedffc7c654e348e2da6c6416090525c6072979fee9681d620d1d398a4"
dependencies = [
"bitcoin",
"serde",
"serde_json",
]

[[package]]
name = "cpufeatures"
version = "0.1.5"
Expand Down Expand Up @@ -1672,11 +1683,12 @@ version = "0.2.0"
dependencies = [
"anyhow",
"async-trait",
"bitcoincore-rpc",
"clap",
"config",
"corepc-types",
"dirs",
"env_logger",
"futures",
"http-body-util",
"hyper",
"hyper-rustls",
Expand All @@ -1689,6 +1701,7 @@ dependencies = [
"reqwest",
"rustls 0.22.4",
"serde",
"serde_json",
"sled",
"tempfile",
"tokio",
Expand Down
15 changes: 14 additions & 1 deletion Cargo-recent.lock
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,17 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"

[[package]]
name = "corepc-types"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a7f2faedffc7c654e348e2da6c6416090525c6072979fee9681d620d1d398a4"
dependencies = [
"bitcoin",
"serde",
"serde_json",
]

[[package]]
name = "cpufeatures"
version = "0.1.5"
Expand Down Expand Up @@ -1672,11 +1683,12 @@ version = "0.2.0"
dependencies = [
"anyhow",
"async-trait",
"bitcoincore-rpc",
"clap",
"config",
"corepc-types",
"dirs",
"env_logger",
"futures",
"http-body-util",
"hyper",
"hyper-rustls",
Expand All @@ -1689,6 +1701,7 @@ dependencies = [
"reqwest",
"rustls 0.22.4",
"serde",
"serde_json",
"sled",
"tempfile",
"tokio",
Expand Down
6 changes: 4 additions & 2 deletions payjoin-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,20 @@ v2 = ["payjoin/v2", "payjoin/io"]
[dependencies]
anyhow = "1.0.70"
async-trait = "0.1"
bitcoincore-rpc = "0.19.0"
clap = { version = "~4.0.32", features = ["derive"] }
config = "0.13.3"
corepc-types = "0.8.0"
env_logger = "0.9.0"
futures = "0.3"
http-body-util = { version = "0.1", optional = true }
hyper = { version = "1", features = ["http1", "server"], optional = true }
hyper-rustls = { version = "0.26", optional = true }
hyper-util = { version = "0.1", optional = true }
log = "0.4.7"
payjoin = { version = "0.24.0", default-features = false }
rcgen = { version = "0.11.1", optional = true }
reqwest = { version = "0.12", default-features = false }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde_json = "1.0"
rustls = { version = "0.22.4", optional = true }
serde = { version = "1.0.160", features = ["derive"] }
sled = "0.34"
Expand Down
6 changes: 3 additions & 3 deletions payjoin-cli/src/app/mod.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use std::collections::HashMap;

use anyhow::{anyhow, Result};
use bitcoincore_rpc::bitcoin::Amount;
use payjoin::bitcoin::psbt::Psbt;
use payjoin::bitcoin::FeeRate;
use payjoin::bitcoin::{Amount, FeeRate};
use payjoin::{bitcoin, PjUri};
use tokio::signal;
use tokio::sync::watch;

pub mod config;
pub mod rpc;
pub mod wallet;
use crate::app::config::Config;
use crate::app::wallet::BitcoindWallet;
Expand All @@ -20,7 +20,7 @@ pub(crate) mod v2;

#[async_trait::async_trait]
pub trait App: Send + Sync {
fn new(config: Config) -> Result<Self>
async fn new(config: Config) -> Result<Self>
where
Self: Sized;
fn wallet(&self) -> BitcoindWallet;
Expand Down
258 changes: 258 additions & 0 deletions payjoin-cli/src/app/rpc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
use std::collections::HashMap;
use std::path::PathBuf;

use anyhow::{anyhow, Context, Result};
use corepc_types::v26::{WalletCreateFundedPsbt, WalletProcessPsbt};
use payjoin::bitcoin::{Address, Amount, Network, Txid};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

/// Authentication method for Bitcoin Core RPC
#[derive(Clone, Debug)]
pub enum Auth {
UserPass(String, String),
CookieFile(PathBuf),
}

/// Internal async Bitcoin RPC client using reqwest
pub struct AsyncBitcoinRpc {
client: Client,
url: String,
username: String,
password: String,
}

impl AsyncBitcoinRpc {
pub async fn new(url: String, auth: Auth) -> Result<Self> {
let client =
Client::builder().use_rustls_tls().build().context("Failed to create HTTP client")?;

// Load credentials once at initialization - no repeated file I/O
let (username, password) = match auth {
Auth::UserPass(user, pass) => (user, pass),
Auth::CookieFile(path) => {
let cookie = tokio::fs::read_to_string(&path)
.await
.with_context(|| format!("Failed to read cookie file: {path:?}"))?;
let parts: Vec<&str> = cookie.trim().split(':').collect();
if parts.len() != 2 {
return Err(anyhow!("Invalid cookie format in file: {path:?}"));
}
(parts[0].to_string(), parts[1].to_string())
}
};

Ok(Self { client, url, username, password })
}

/// Get base URL without wallet path for blockchain-level calls
fn get_base_url(&self) -> String {
if let Some(pos) = self.url.find("/wallet/") {
self.url[..pos].to_string()
} else {
self.url.clone()
}
}

/// Make a JSON-RPC call to Bitcoin Core
async fn call_rpc<T>(&self, method: &str, params: serde_json::Value) -> Result<T>
where
T: for<'de> Deserialize<'de>,
{
// Determine which URL to use based on the method
// Blockchain/network calls go to base URL, wallet calls go to wallet URL
let url = match method {
"getblockchaininfo" | "getnetworkinfo" | "getmininginfo" | "getblockcount"
| "getbestblockhash" | "getblock" | "getblockhash" | "gettxout" => self.get_base_url(),
_ => self.url.clone(),
};

let request_body = json!({
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": 1
});

let request = self
.client
.post(&url)
.json(&request_body)
.basic_auth(&self.username, Some(&self.password));

let response = request.send().await.context("Failed to send RPC request")?;

if !response.status().is_success() {
return Err(anyhow!("RPC request failed with status: {}", response.status()));
}
Comment thread
bc1cindy marked this conversation as resolved.

let json: RpcResponse<T> = response.json().await.context("Failed to parse RPC response")?;

match json {
RpcResponse::Success { result, .. } => Ok(result),
RpcResponse::Error { error, .. } => Err(anyhow!("RPC error: {:?}", error)),
}
}

pub async fn wallet_create_funded_psbt(
&self,
inputs: &[Value],
outputs: &HashMap<String, Amount>,
locktime: Option<u32>,
options: Option<Value>,
bip32derivs: Option<bool>,
) -> Result<WalletCreateFundedPsbt> {
let outputs_btc: HashMap<String, f64> =
outputs.iter().map(|(addr, amount)| (addr.clone(), amount.to_btc())).collect();

let locktime = locktime.unwrap_or(0);
let options = options.unwrap_or_else(|| json!({}));
let bip32derivs = bip32derivs.unwrap_or(true);

let params = json!([inputs, outputs_btc, locktime, options, bip32derivs]);
self.call_rpc("walletcreatefundedpsbt", params).await
}

pub async fn wallet_process_psbt(
&self,
psbt: &str,
sign: Option<bool>,
sighash_type: Option<String>,
bip32derivs: Option<bool>,
) -> Result<WalletProcessPsbt> {
let sign = sign.unwrap_or(true);
let sighash_type = sighash_type.unwrap_or_else(|| "ALL".to_string());
let bip32derivs = bip32derivs.unwrap_or(true);

let params = json!([psbt, sign, sighash_type, bip32derivs]);
self.call_rpc("walletprocesspsbt", params).await
}

pub async fn finalize_psbt(
&self,
psbt: &str,
extract: Option<bool>,
) -> Result<FinalizePsbtResult> {
let extract = extract.unwrap_or(true);
let params = json!([psbt, extract]);
self.call_rpc("finalizepsbt", params).await
}

pub async fn test_mempool_accept(
&self,
rawtxs: &[String],
) -> Result<Vec<TestMempoolAcceptResult>> {
let params = json!([rawtxs]);
self.call_rpc("testmempoolaccept", params).await
}

pub async fn send_raw_transaction(&self, hex: &[u8]) -> Result<Txid> {
use payjoin::bitcoin::hex::DisplayHex;
let hex_string = hex.to_lower_hex_string();
let params = json!([hex_string]);
let txid_string: String = self.call_rpc("sendrawtransaction", params).await?;
Ok(txid_string.parse()?)
}

pub async fn get_address_info(&self, address: &Address) -> Result<GetAddressInfoResult> {
let params = json!([address.to_string()]);
self.call_rpc("getaddressinfo", params).await
}

pub async fn get_new_address(
&self,
label: Option<&str>,
address_type: Option<&str>,
) -> Result<Address<payjoin::bitcoin::address::NetworkUnchecked>> {
let params = if label.is_none() && address_type.is_none() {
json!([])
} else {
json!([label, address_type])
};

let address_string: String = self.call_rpc("getnewaddress", params).await?;
let addr: payjoin::bitcoin::Address<payjoin::bitcoin::address::NetworkUnchecked> =
address_string.parse().context("Failed to parse address")?;
Ok(addr)
}

pub async fn list_unspent(
&self,
minconf: Option<u32>,
maxconf: Option<u32>,
addresses: Option<&[Address]>,
include_unsafe: Option<bool>,
query_options: Option<Value>,
) -> Result<Vec<ListUnspentResult>> {
let addresses_str: Option<Vec<String>> =
addresses.map(|addrs| addrs.iter().map(|a| a.to_string()).collect());
let params = json!([minconf, maxconf, addresses_str, include_unsafe, query_options]);
self.call_rpc("listunspent", params).await
}

pub async fn get_blockchain_info(&self) -> Result<serde_json::Value> {
let params = json!([]);
self.call_rpc("getblockchaininfo", params).await
}

pub async fn network(&self) -> Result<Network> {
let info = self.get_blockchain_info().await?;
let chain = info["chain"].as_str().ok_or_else(|| anyhow!("Missing chain field"))?;
match chain {
"main" => Ok(Network::Bitcoin),
"test" => Ok(Network::Testnet),
"regtest" => Ok(Network::Regtest),
"signet" => Ok(Network::Signet),
other => Err(anyhow!("Unknown network: {}", other)),
}
}
}

/// JSON-RPC response envelope
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum RpcResponse<T> {
Success { result: T, error: Option<Value>, id: Value },
Error { result: Option<Value>, error: RpcError, id: Value },
}

#[derive(Serialize, Deserialize, Debug)]
struct RpcError {
code: i32,
message: String,
}

/// Result type for testmempoolaccept RPC call - minimal struct for our use case
#[derive(Debug, Deserialize)]
pub struct TestMempoolAcceptResult {
pub allowed: bool,
// Ignore additional fields that Bitcoin Core v29 may include
}

/// Result type for getaddressinfo RPC call - minimal struct for our use case
#[derive(Debug, Deserialize)]
pub struct GetAddressInfoResult {
#[serde(rename = "ismine")]
pub is_mine: bool,
}

/// Result type for listunspent RPC call - compatible with both v26 and v29+
#[derive(Debug, Deserialize)]
pub struct ListUnspentResult {
pub txid: String,
pub vout: u32,
#[serde(rename = "scriptPubKey")]
pub script_pubkey: String,
pub amount: f64,
// Optional fields for compatibility with newer Bitcoin Core versions
#[serde(rename = "redeemScript")]
pub redeem_script: Option<String>,
// Ignore additional fields that Bitcoin Core v29+ may include
}

/// Result type for finalizepsbt RPC call - compatible with both v26 and v29+
#[derive(Debug, Deserialize)]
pub struct FinalizePsbtResult {
pub hex: Option<String>,
}
Loading