Skip to content

Commit

Permalink
tests and external
Browse files Browse the repository at this point in the history
  • Loading branch information
zupzup committed Oct 24, 2024
1 parent aca66e2 commit b842bfd
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 111 deletions.
2 changes: 1 addition & 1 deletion src/blockchain/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ impl Chain {
#[tokio::main]
async fn check_if_paid(address: String, amount: u64) -> bool {
let info_about_address =
external::bitcoin::AddressInfo::get_testnet_address_info(address.clone()).await;
external::bitcoin::AddressInfo::get_address_info(address.clone()).await;
let received_summ = info_about_address.chain_stats.funded_txo_sum;
let spent_summ = info_about_address.chain_stats.spent_txo_sum;
// let received_summ_mempool = info_about_address.mempool_stats.funded_txo_sum;
Expand Down
57 changes: 24 additions & 33 deletions src/external/bitcoin.rs
Original file line number Diff line number Diff line change
@@ -1,53 +1,44 @@
use crate::{bill::BitcreditBill, constants::USEDNET};
use bitcoin::Network;
use serde::Deserialize;
use std::str::FromStr;

#[derive(Deserialize, Debug)]
pub struct ChainStats {
pub funded_txo_count: u64,
pub funded_txo_sum: u64,
pub spent_txo_count: u64,
pub spent_txo_sum: u64,
pub tx_count: u64,
}

#[derive(Deserialize, Debug)]
pub struct MempoolStats {
pub struct Stats {
#[allow(dead_code)]
pub funded_txo_count: u64,
pub funded_txo_sum: u64,
#[allow(dead_code)]
pub spent_txo_count: u64,
pub spent_txo_sum: u64,
#[allow(dead_code)]
pub tx_count: u64,
}

#[derive(Deserialize, Debug)]
pub struct AddressInfo {
#[allow(dead_code)]
address: String,
pub chain_stats: ChainStats,
pub mempool_stats: MempoolStats,
pub chain_stats: Stats,
pub mempool_stats: Stats,
}

impl AddressInfo {
pub async fn get_testnet_address_info(address: String) -> Self {
let request_url = format!(
"https://blockstream.info/testnet/api/address/{address}",
address = address
);
let address: AddressInfo = reqwest::get(&request_url)
.await
.expect("Failed to send request")
.json()
.await
.expect("Failed to read response");

address
}

async fn get_mainnet_address_info(address: String) -> Self {
let request_url = format!(
"https://blockstream.info/api/address/{address}",
address = address
);
pub async fn get_address_info(address: String) -> Self {
let request_url = match USEDNET {
Network::Bitcoin => {
format!(
"https://blockstream.info/api/address/{address}",
address = address
)
}
_ => {
format!(
"https://blockstream.info/testnet/api/address/{address}",
address = address
)
}
};
let address: AddressInfo = reqwest::get(&request_url)
.await
.expect("Failed to send request")
Expand Down Expand Up @@ -165,7 +156,7 @@ pub async fn get_mainnet_last_block_height() -> u64 {

pub async fn check_if_paid(address: String, amount: u64) -> (bool, u64) {
//todo check what net we used
let info_about_address = AddressInfo::get_testnet_address_info(address.clone()).await;
let info_about_address = AddressInfo::get_address_info(address.clone()).await;
let received_summ = info_about_address.chain_stats.funded_txo_sum;
let spent_summ = info_about_address.chain_stats.spent_txo_sum;
let received_summ_mempool = info_about_address.mempool_stats.funded_txo_sum;
Expand Down
7 changes: 2 additions & 5 deletions src/external/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{fs, path::PathBuf};
use url::Url;

use crate::bill::{
identity::{read_identity_from_file, read_peer_id_from_file, Identity},
identity::read_peer_id_from_file,
quotes::{
add_bitcredit_quote_and_amount_in_quotes_map, add_bitcredit_token_in_quotes_map,
add_in_quotes_map, get_quote_from_map, read_quotes_map,
Expand All @@ -32,9 +32,6 @@ pub async fn accept_mint_bitcredit(

let mint_url = Url::parse("http://127.0.0.1:3338").expect("Invalid url");

let identity: Identity = read_identity_from_file();
let bitcoin_key = identity.bitcoin_public_key.clone();

let wallet: Wallet<_, CrossPlatformHttpClient> = Wallet::builder()
.with_localstore(localstore)
.build()
Expand Down Expand Up @@ -183,7 +180,7 @@ pub async fn init_wallet() {
}
let db_path = dir.join("wallet.db").to_str().unwrap().to_string();

let localstore = SqliteLocalStore::with_path(db_path.clone())
let _localstore = SqliteLocalStore::with_path(db_path.clone())
.await
.expect("Cannot parse local store");

Expand Down
21 changes: 4 additions & 17 deletions src/external/time.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,16 @@
use serde::Deserialize;

const URL: &str = "https://api.timezonedb.com/v2.1/get-time-zone?key=RQ6ZFDOXPVLR&format=json&by=zone&zone=Europe/Vienna";

/// Documented at https://timezonedb.com/references/get-time-zone
#[derive(Deserialize, Debug)]
pub struct TimeApi {
status: String,
message: String,
countryCode: String,
countryName: String,
regionName: String,
cityName: String,
zoneName: String,
abbreviation: String,
gmtOffset: i64,
dst: String,
zoneStart: i64,
zoneEnd: i64,
nextAbbreviation: String,
pub timestamp: i64,
formatted: String,
}

impl TimeApi {
pub async fn get_atomic_time() -> Self {
let request_url = "https://api.timezonedb.com/v2.1/get-time-zone?key=RQ6ZFDOXPVLR&format=json&by=zone&zone=Europe/Vienna".to_string();

reqwest::get(&request_url)
reqwest::get(URL)
.await
.expect("Failed to send request")
.json()
Expand Down
75 changes: 20 additions & 55 deletions src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,22 @@
#[cfg(test)]
mod test {
use crate::bill::{
identity::{
byte_array_to_size_array_keypair, byte_array_to_size_array_peer_id,
create_new_identity, read_identity_from_file, Identity,
},
BitcreditBill,
use crate::bill::identity::{
byte_array_to_size_array_keypair, byte_array_to_size_array_peer_id, create_new_identity,
};
use crate::external::bitcoin::AddressInfo;
use crate::util::numbers_to_words::encode;
use crate::util::rsa::generation_rsa_key;
use crate::util::structure_as_u8_slice;
use bitcoin::secp256k1::Scalar;
use borsh::to_vec;
use libp2p::identity::Keypair;
use libp2p::PeerId;
use moksha_core::primitives::{CurrencyUnit, PaymentMethod};
use moksha_wallet::http::CrossPlatformHttpClient;
use moksha_wallet::localstore::sqlite::SqliteLocalStore;
use moksha_wallet::wallet::Wallet;
use openssl::rsa::{Padding, Rsa};
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::{fs, mem};
use url::Url;

fn bill_to_byte_array(bill: &BitcreditBill) -> Vec<u8> {
to_vec(bill).unwrap()
}
// fn bill_to_byte_array(bill: &BitcreditBill) -> Vec<u8> {
// to_vec(bill).unwrap()
// }

//TODO: Change. Because we create new bill every time we run tests

Expand Down Expand Up @@ -204,7 +194,7 @@ mod test {
bitcoin::Network::Testnet,
);
let public_key1 = private_key1.public_key(&s1);
let address1 = bitcoin::Address::p2pkh(&public_key1, bitcoin::Network::Testnet);
let _address1 = bitcoin::Address::p2pkh(public_key1, bitcoin::Network::Testnet);

let s2 = bitcoin::secp256k1::Secp256k1::new();
let private_key2 = bitcoin::PrivateKey::new(
Expand All @@ -213,16 +203,16 @@ mod test {
bitcoin::Network::Testnet,
);
let public_key2 = private_key1.public_key(&s2);
let address2 = bitcoin::Address::p2pkh(&public_key2, bitcoin::Network::Testnet);
let _address2 = bitcoin::Address::p2pkh(public_key2, bitcoin::Network::Testnet);

let private_key3 = private_key1
.inner
.add_tweak(&Scalar::from(private_key2.inner.clone()))
.add_tweak(&Scalar::from(private_key2.inner))
.unwrap();
let pr_key3 = bitcoin::PrivateKey::new(private_key3, bitcoin::Network::Testnet);
let public_key3 = public_key1.inner.combine(&public_key2.inner).unwrap();
let pub_key3 = bitcoin::PublicKey::new(public_key3);
let address3 = bitcoin::Address::p2pkh(&pub_key3, bitcoin::Network::Testnet);
let address3 = bitcoin::Address::p2pkh(pub_key3, bitcoin::Network::Testnet);

println!("private key: {}", pr_key3);
println!("public key: {}", pub_key3);
Expand Down Expand Up @@ -380,31 +370,6 @@ mod test {

#[tokio::test]
async fn test_api() {
#[derive(Deserialize, Debug)]
struct ChainStats {
funded_txo_count: u32,
funded_txo_sum: u32,
spent_txo_count: u32,
spent_txo_sum: u32,
tx_count: u32,
}

#[derive(Deserialize, Debug)]
struct MempoolStats {
funded_txo_count: u32,
funded_txo_sum: u32,
spent_txo_count: u32,
spent_txo_sum: u32,
tx_count: u32,
}

#[derive(Deserialize, Debug)]
struct User {
address: String,
chain_stats: ChainStats,
mempool_stats: MempoolStats,
}

let request_url = format!(
"https://blockstream.info/testnet/api/address/{address}",
address = "mzYHxNxTTGrrxnwSc1RvqTusK4EM88o6yj"
Expand All @@ -417,7 +382,7 @@ mod test {
.await
.expect("Failed to read response");
println!("{:?}", response1);
let response: User = reqwest::get(&request_url)
let response: AddressInfo = reqwest::get(&request_url)
.await
.expect("Failed to send request")
.json()
Expand All @@ -436,11 +401,11 @@ mod test {
let secp2 = bitcoin::secp256k1::Secp256k1::new();
let key_pair2 =
bitcoin::secp256k1::Keypair::new(&secp2, &mut bitcoin::secp256k1::rand::thread_rng());
let xonly2 = bitcoin::secp256k1::XOnlyPublicKey::from_keypair(&key_pair2);
let _xonly2 = bitcoin::secp256k1::XOnlyPublicKey::from_keypair(&key_pair2);

let msg = bitcoin::secp256k1::Message::from_slice(&[0xab; 32]).unwrap();
let msg = bitcoin::secp256k1::Message::from_digest_slice(&[0xab; 32]).unwrap();
let a = secp1.sign_schnorr(&msg, &key_pair1);
let b = secp2
secp2
.verify_schnorr(&a, &msg, &xonly1.0)
.expect("verify failed");
}
Expand All @@ -449,7 +414,7 @@ mod test {
fn structure_to_bytes() {
let ed25519_keys = Keypair::generate_ed25519();
let peer_id = PeerId::from(ed25519_keys.public());
let id = create_new_identity(
let _id = create_new_identity(
"qwq".to_string(),
"adsda".to_string(),
"ewqe".to_string(),
Expand All @@ -473,11 +438,11 @@ mod test {

let data_key = fs::read("test/keys").expect("Unable to read file with keypair");
let key_pair_bytes_sized = byte_array_to_size_array_keypair(data_key.as_slice());
let key_pair2: Keypair = unsafe { mem::transmute_copy(key_pair_bytes_sized) };
let _key_pair2: Keypair = unsafe { mem::transmute_copy(key_pair_bytes_sized) };

let data_peer_id = fs::read("test/peer_id").expect("Unable to read file with peer_id");
let peer_id_bytes_sized = byte_array_to_size_array_peer_id(data_peer_id.as_slice());
let peer_id2: PeerId = unsafe { mem::transmute_copy(peer_id_bytes_sized) };
let _peer_id2: PeerId = unsafe { mem::transmute_copy(peer_id_bytes_sized) };
}

// #[test]
Expand Down Expand Up @@ -611,7 +576,7 @@ mod test {

let public_key =
Rsa::public_key_from_pem(rsa_key.public_key_to_pem().unwrap().as_slice()).unwrap();
let private_key =
let _private_key =
Rsa::private_key_from_pem(rsa_key.private_key_to_pem().unwrap().as_slice()).unwrap();

// Encrypt with public key
Expand All @@ -638,7 +603,7 @@ mod test {
// Generate a keypair
let rsa_key = generation_rsa_key();

let p_key =
let _p_key =
Rsa::public_key_from_pem(rsa_key.public_key_to_pem().unwrap().as_slice()).unwrap();

// Encrypt with public key
Expand Down

0 comments on commit b842bfd

Please sign in to comment.