Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
sander2 committed Aug 14, 2023
1 parent cb49166 commit f92e8ca
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 18 deletions.
2 changes: 0 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions bitcoin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ light-client = []

[dependencies]
thiserror = "1.0"
bitcoincore-rpc = { git = "https://github.com/rust-bitcoin/rust-bitcoincore-rpc", rev = "7bd815f1e1ae721404719ee8e6867064b7c68494" }
bitcoincore-rpc = { path = "/home/sander/workspace/rust-bitcoincore-rpc/client/" }
hex = "0.4.2"
async-trait = "0.1.40"
tokio = { version = "1.0", features = ["full"] }
Expand All @@ -36,9 +36,9 @@ serde_json = "1.0.82"

# Substrate dependencies
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
regex = "1.4.3"

[dev-dependencies]
mockall = "0.8.1"
regex = "1.4.3"
rand = "0.7"
serial_test = "*"
2 changes: 2 additions & 0 deletions bitcoin/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ pub enum Error {
TransactionSigningError,
#[error("Failed to obtain public key")]
MissingPublicKey,
#[error("getaddressinfo did not return a derivation path")]
MissingDerivationPath,
#[error("Failed to connect")]
ConnectionRefused,
#[error("Wallet not found")]
Expand Down
86 changes: 74 additions & 12 deletions bitcoin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ mod iter;

use async_trait::async_trait;
use backoff::{backoff::Backoff, future::retry, ExponentialBackoff};
use bitcoincore_rpc::{
bitcoin::consensus::encode::serialize_hex,
bitcoincore_rpc_json::{GetDescriptorInfoResult, ImportDescriptors, ScanningDetails, Timestamp},
};
pub use bitcoincore_rpc::{
bitcoin as bitcoin_primitives,
bitcoin::{
Expand Down Expand Up @@ -47,7 +43,10 @@ pub use bitcoincore_rpc::{
jsonrpc::{self, error::RpcError, Error as JsonRpcError},
Auth, Client, Error as BitcoinError, RpcApi,
};
use bitcoincore_rpc::{bitcoin::consensus::encode::serialize_hex, bitcoincore_rpc_json::ScanningDetails};
use bitcoincore_rpc::{
bitcoin::consensus::encode::serialize_hex,
bitcoincore_rpc_json::{GetDescriptorInfoResult, ImportDescriptors, ScanningDetails, Timestamp},
};
pub use electrs::{ElectrsClient, Error as ElectrsError};
pub use error::{BitcoinRpcError, ConversionError, Error};
pub use iter::{reverse_stream_transactions, stream_blocks, stream_in_chain_transactions};
Expand Down Expand Up @@ -832,21 +831,84 @@ impl BitcoinCoreApi for BitcoinCore {
}

fn dump_private_key(&self, address: &Address) -> Result<PrivateKey, Error> {
Ok(self.rpc.dump_private_key(address)?)
let address_info = self.rpc.get_address_info(&address).unwrap();
dbg!(&address_info);
let derivation_path = address_info.hd_key_path.ok_or(Error::MissingDerivationPath)?;
let result = self.rpc.list_descriptors(true)?;

for descriptor in result.descriptors {
let range = descriptor
.range
.map(|[start, end]| [start, end.max(descriptor.next.unwrap_or(end))]);

for generated_address in self.rpc.derive_addresses(&descriptor.desc, range)? {
if address == &generated_address.assume_checked() {
info!("Found private address! {}", descriptor.desc);

let re = regex::Regex::new(r".*[(]([tx]prv[a-zA-Z0-9]+)").expect("Regex is known good");
if let Some(caps) = re.captures(&descriptor.desc) {
println!("private key = {}", &caps[1]);
// assert_eq!("", &caps[1]);
let key = bitcoincore_rpc::bitcoin::bip32::ExtendedPrivKey::from_str(&caps[1]).unwrap();
let secp = bitcoincore_rpc::bitcoin::key::Secp256k1::new();
let private_key = key.derive_priv(&secp, &derivation_path).unwrap().to_priv();
warn!(
"wif: {}",
private_key.to_wif()
);

return Ok(private_key);
}



// wif
let re = regex::Regex::new(r".*[(]([LKc][a-zA-Z0-9]{51})[)]").expect("Regex is known good");
if let Some(caps) = re.captures(&descriptor.desc) {
println!("wif = {}", &caps[1]);
assert!(derivation_path.is_master());
let private_key = PrivateKey::from_wif(&caps[1]).unwrap();
return Ok(private_key);
}
}
}
}

// let wallet_pubkey = address_info.pubkey.ok_or(Error::MissingPublicKey)?;

panic!()
}

fn import_private_key(&self, private_key: &PrivateKey, is_derivation_key: bool) -> Result<(), Error> {
Ok(self.rpc.import_private_key(
private_key,
is_derivation_key.then_some(DERIVATION_KEY_LABEL),
Some(false),
)?)
let wif = private_key.to_wif();
let info = self.rpc.get_descriptor_info(&format!("wpkh({wif})"))?;
let checksum = info.checksum.unwrap();
let req = ImportDescriptors {
descriptor: format!("wpkh({wif})#{checksum}"),
timestamp: Timestamp::Now,
active: Some(false),
range: None,
next_index: None,
internal: None,
label: is_derivation_key.then_some(DERIVATION_KEY_LABEL.to_owned()),
};
let result = self.rpc.import_descriptors(req)?;
assert_eq!(result.len(), 1);
assert!(result[0].success);

Ok(())
// assert!(resu
// Ok(self.rpc.import_private_key(
// private_key,
// is_derivation_key.then_some(DERIVATION_KEY_LABEL),
// Some(false),
// )?)
}

/// Derive and import the private key for the master public key and public secret
async fn add_new_deposit_key(&self, public_key: PublicKey, secret_key: Vec<u8>) -> Result<(), Error> {
let address = Address::p2wpkh(&public_key, self.network).map_err(ConversionError::from)?;
let private_key = self.rpc.dump_private_key(&address)?;
let private_key = self.dump_private_key(&address)?;
let deposit_secret_key =
addr::calculate_deposit_secret_key(private_key.inner, SecretKey::from_slice(&secret_key)?)?;
self.import_private_key(
Expand Down
2 changes: 1 addition & 1 deletion runtime/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ compile_error!("Tests are only supported for the kintsugi runtime");

cfg_if::cfg_if! {
if #[cfg(feature = "parachain-metadata-interlay")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1025000..1026000;
const DEFAULT_SPEC_VERSION: Range<u32> = 1024000..1025000;
pub const DEFAULT_SPEC_NAME: &str = "interlay-parachain";
pub const SS58_PREFIX: u16 = 2032;
} else if #[cfg(feature = "parachain-metadata-kintsugi")] {
Expand Down
5 changes: 4 additions & 1 deletion vault/src/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use runtime::{
PrettyPrint, RegisterVaultEvent, StoreMainChainHeaderEvent, TryFromSymbol, UpdateActiveBlockEvent, UtilFuncs,
VaultCurrencyPair, VaultId, VaultRegistryPallet,
};
use std::{collections::HashMap, pin::Pin, sync::Arc, time::Duration};
use std::{collections::HashMap, pin::Pin, sync::Arc, time::Duration, str::FromStr};
use tokio::{sync::RwLock, time::sleep};

pub const VERSION: &str = git_version!(args = ["--tags"]);
Expand Down Expand Up @@ -651,6 +651,9 @@ impl VaultService {
)
.await?;

// let address = bitcoin::bitcoin_primitives::Address::from_str("bcrt1qseu4xznuehrclpqn9r40ghgs092tfv6j2428dh").unwrap().assume_checked();
// self.btc_rpc_master_wallet.dump_private_key(&address).unwrap();

let startup_height = self.await_parachain_block().await?;

let open_request_executor = execute_open_requests(
Expand Down

0 comments on commit f92e8ca

Please sign in to comment.