Skip to content

Commit

Permalink
initial tests implementation
Browse files Browse the repository at this point in the history
Signed-off-by: wthrajat <rajatkhanduri290102@gmail.com>
  • Loading branch information
wthrajat committed Feb 21, 2024
1 parent 3beb77c commit 0529dd6
Show file tree
Hide file tree
Showing 3 changed files with 173 additions and 44 deletions.
2 changes: 1 addition & 1 deletion src/test_framework.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
//! Spawns one Taker and multiple Makers, with/without special behavior, connect them to bitcoind regtest node,
//! and initializes the database.
//!
//! The tests data are stored in the `tests/temp-files` directory, which is auto-removed after each successful test.
//! The tests data are stored in the `/tmp/teleport/tests/temp-files/` directory, which is auto-removed after each successful test or after a reboot.
//! Do not invoke [TestFramework::stop] function at the end of the test, to persis this data for debugging.
//!
//! The test data also includes the backend bitcoind data-directory, which is useful for observing the blockchain states after a swap.
Expand Down
1 change: 1 addition & 0 deletions src/wallet/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ use super::{
const HARDENDED_DERIVATION: &str = "m/84'/1'/0'";

/// Represents a Bitcoin wallet with associated functionality and data.
#[derive(Debug)]

Check warning on line 54 in src/wallet/api.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/api.rs#L54

Added line #L54 was not covered by tests
pub struct Wallet {
pub(crate) rpc: Client,
wallet_file_path: PathBuf,
Expand Down
214 changes: 171 additions & 43 deletions src/wallet/direct_send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,11 +265,18 @@ impl Wallet {
#[cfg(test)]
mod tests {
use super::*;
use crate::wallet::rpc;
use crate::{utill, wallet::rpc};
use bip39::Mnemonic;
use bitcoin::Txid;
use bitcoind::bitcoincore_rpc::Auth;
use std::path::PathBuf;
use bitcoin::{
secp256k1::rand::{distributions::Alphanumeric, thread_rng, Rng},
Txid,
};
use bitcoind::{bitcoincore_rpc::Auth, BitcoinD, Conf};
use rpc::RPCConfig;
use std::{
path::PathBuf,
sync::{Arc, RwLock},
};

#[test]
fn test_send_amount_parsing() {
Expand Down Expand Up @@ -386,46 +393,167 @@ mod tests {

#[test]
fn test_create_direct_send() {
let mut path = PathBuf::new();
path.push("/tmp/teleport/test-wallet-direct-send");

let rpc_config = rpc::RPCConfig {
url: "http://localhost:8332".to_string(),
auth: Auth::UserPass("username".to_string(), "password".to_string()),
network: Network::Testnet,
wallet_name: String::from("test-wallet"),
};
// let mnemonic = "abandon ability able about above absent absorb abstract absurd abuse access accident";
let mnemonic_seedphrase = Mnemonic::generate(12).unwrap().to_string();
let passphrase =
"abandon ability able about above absent absorb abstract absurd abuse access accident"
.trim()
.to_string();

let mut wallet_instance = Wallet::init(&path, &rpc_config, mnemonic_seedphrase, passphrase)
.expect("wallet instance error");

let fee_rate = 100_000;
let send_amount = SendAmount::Amount(Amount::from_sat(1000));
let destination = Destination::Wallet;
let coins_to_spend = vec![
CoinToSpend::LongForm(OutPoint {
txid: Txid::from_str(
"5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456",
)
.unwrap(),
vout: 0,
}),
CoinToSpend::ShortForm {
prefix: "123abc".to_string(),
suffix: "def456".to_string(),
vout: 0,
},
];
#[derive(Debug)]

Check warning on line 396 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L396

Added line #L396 was not covered by tests
pub struct DirectSendTest {
bitcoind: BitcoinD,
_temp_dir: PathBuf,
shutdown: Arc<RwLock<bool>>,

Check warning on line 400 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L399-L400

Added lines #L399 - L400 were not covered by tests
}
fn get_random_tmp_dir() -> PathBuf {
let s: String = thread_rng()

Check warning on line 403 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L402-L403

Added lines #L402 - L403 were not covered by tests
.sample_iter(&Alphanumeric)
.take(8)
.map(char::from)
.collect();
let path = "/tmp/teleport/direct-send-test/".to_string() + &s;
PathBuf::from(path)
}

Check warning on line 410 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L408-L410

Added lines #L408 - L410 were not covered by tests
// For this we will initialise a Bitcoind in the background

impl DirectSendTest {
pub async fn init(bitcoind_conf: Option<Conf<'_>>) -> Arc<Self> {

Check warning on line 414 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L414

Added line #L414 was not covered by tests
utill::setup_logger();
let temp_dir = get_random_tmp_dir();
// Remove if previously existing
if temp_dir.exists() {
std::fs::remove_dir_all::<PathBuf>(temp_dir.clone()).unwrap();
}
println!("temporary directory : {}", temp_dir.display());

// Initiate the bitcoind backend.
let mut conf = bitcoind_conf.unwrap_or_default();
conf.args.push("-txindex=1"); // txindex is must, or else wallet sync won't work
conf.staticdir = Some(temp_dir.join(".bitcoin"));
log::info!("bitcoind configuration: {:?}", conf.args);
let bitcoind = BitcoinD::from_downloaded_with_conf(&conf).unwrap();
// Generate initial 101 blocks
let mining_address = bitcoind
.client
.get_new_address(None, None)
.unwrap()
.require_network(bitcoind::bitcoincore_rpc::bitcoin::Network::Regtest)
.unwrap();
bitcoind
.client
.generate_to_address(101, &mining_address)
.unwrap();
log::info!("bitcoind initiated!!");

let shutdown = Arc::new(RwLock::new(false));
let test_framework = Arc::new(Self {
bitcoind,
_temp_dir: temp_dir.clone(),
shutdown,
});
log::info!("spawning block generation thread");
let tf_clone = test_framework.clone();
std::thread::spawn(move || {
while !*tf_clone.shutdown.read().unwrap() {
std::thread::sleep(std::time::Duration::from_millis(500));
tf_clone.generate_1_block();
log::debug!("created 1 block");
}
log::info!("ending block generation thread");
});
test_framework
}

Check warning on line 459 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L459

Added line #L459 was not covered by tests
/// Generate 1 block in the backend bitcoind.
pub fn generate_1_block(&self) {
let mining_address = self

Check warning on line 463 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L462-L463

Added lines #L462 - L463 were not covered by tests
.bitcoind
.client
.get_new_address(None, None)

Check warning on line 466 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L466

Added line #L466 was not covered by tests
.unwrap()
.require_network(bitcoind::bitcoincore_rpc::bitcoin::Network::Regtest)

Check warning on line 468 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L468

Added line #L468 was not covered by tests
.unwrap();
self.bitcoind

Check warning on line 470 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L470

Added line #L470 was not covered by tests
.client
.generate_to_address(1, &mining_address)
.unwrap();
}

Check warning on line 474 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L473-L474

Added lines #L473 - L474 were not covered by tests

let result =
wallet_instance.create_direct_send(fee_rate, send_amount, destination, &coins_to_spend);
/// Stop bitcoind and clean up all test data.
pub fn stop(&self) {
log::info!("Stopping Test Framework");

Check warning on line 478 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L477-L478

Added lines #L477 - L478 were not covered by tests
// stop all framework threads.
*self.shutdown.write().unwrap() = true;

Check warning on line 480 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L480

Added line #L480 was not covered by tests
// stop bitcoind
let _ = self.bitcoind.client.stop().unwrap();
}

Check warning on line 483 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L482-L483

Added lines #L482 - L483 were not covered by tests

assert!(result.is_ok());
pub fn get_block_count(&self) -> u64 {
self.bitcoind.client.get_block_count().unwrap()
}

Check warning on line 487 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L485-L487

Added lines #L485 - L487 were not covered by tests
}

/// Initializes a [TestFramework] given a [RPCConfig].
impl From<&DirectSendTest> for RPCConfig {
fn from(value: &DirectSendTest) -> Self {
println!(" ----- initialising -----");
let url = value.bitcoind.rpc_url().split_at(7).1.to_string();
let auth = Auth::CookieFile(value.bitcoind.params.cookie_file.clone());
let network = utill::str_to_bitcoin_network(
value

Check warning on line 497 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L492-L497

Added lines #L492 - L497 were not covered by tests
.bitcoind
.client
.get_blockchain_info()
.unwrap()
.chain
.as_str(),
);
let mut path = PathBuf::new();
path.push("/tmp/teleport/direct-send-test/test-wallet");

Check warning on line 506 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L504-L506

Added lines #L504 - L506 were not covered by tests

let rpc_config = rpc::RPCConfig {
url: "http://localhost:18444".to_string(),
auth: Auth::UserPass(
"regtestrpcuser".to_string(),
"regtestrpcpass".to_string(),
),
network: Network::Regtest,
wallet_name: String::from("test_wallet_ds"),
};

Check warning on line 516 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L508-L516

Added lines #L508 - L516 were not covered by tests
// allowed 12 words example = "abandon ability able about above absent absorb abstract absurd abuse access accident";
let mnemonic_seedphrase = Mnemonic::generate(12).unwrap().to_string();

Check warning on line 518 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L518

Added line #L518 was not covered by tests

let mut wallet_instance =
Wallet::init(&path, &rpc_config, mnemonic_seedphrase, "".to_string())

Check warning on line 521 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L521

Added line #L521 was not covered by tests
.expect("Hmm getting instance error");
println!(" ------ wallet instance - {:#?}", wallet_instance);
let fee_rate = 100_000;
let send_amount = SendAmount::Amount(Amount::from_sat(1000));
let destination = Destination::Wallet;
let coins_to_spend = vec![
CoinToSpend::LongForm(OutPoint {
txid: Txid::from_str(

Check warning on line 529 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L523-L529

Added lines #L523 - L529 were not covered by tests
"5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456",
)
.unwrap(),
vout: 0,
}),
CoinToSpend::ShortForm {
prefix: "123abc".to_string(),
suffix: "def456".to_string(),

Check warning on line 537 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L535-L537

Added lines #L535 - L537 were not covered by tests
vout: 0,
},

Check warning on line 539 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L539

Added line #L539 was not covered by tests
];

let result = wallet_instance.create_direct_send(

Check warning on line 542 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L542

Added line #L542 was not covered by tests
fee_rate,
send_amount,
destination,
&coins_to_spend,
);
assert!(result.is_ok());

Check warning on line 548 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L545-L548

Added lines #L545 - L548 were not covered by tests

Self {
url,
auth,

Check warning on line 552 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L550-L552

Added lines #L550 - L552 were not covered by tests
network,
..Default::default()
}
}

Check warning on line 556 in src/wallet/direct_send.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/direct_send.rs#L554-L556

Added lines #L554 - L556 were not covered by tests
}
}
}

0 comments on commit 0529dd6

Please sign in to comment.