Add an argument for core rpc and network

This commit is contained in:
Sosthene 2024-05-28 11:11:17 +02:00
parent 0d5149eb96
commit 7e5dc17841
2 changed files with 48 additions and 24 deletions

View File

@ -16,6 +16,7 @@ use sdk_common::sp_client::bitcoin::{consensus::deserialize, hashes::hex::FromHe
use serde_json::{json, Value};
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
@ -89,9 +90,7 @@ fn read_cookie(path: &Path) -> Result<(String, String)> {
Ok((parts[0].to_owned(), parts[1].to_owned()))
}
fn rpc_connect(rpcwallet: Option<String>) -> Result<Client> {
let mut rpc_url = "http://127.0.0.1:39332".to_owned();
fn rpc_connect(rpcwallet: Option<String>, network: Network, mut rpc_url: String) -> Result<Client> {
match rpcwallet {
Some(rpcwallet) => rpc_url.push_str(&rpcwallet),
None => (),
@ -102,9 +101,12 @@ fn rpc_connect(rpcwallet: Option<String>) -> Result<Client> {
let builder = jsonrpc::simple_http::SimpleHttpTransport::builder()
.url(&rpc_url)?
.timeout(Duration::from_secs(30));
let daemon_auth = SensitiveAuth(Auth::CookieFile(
PathBuf::from_str("/home/sosthene/.bitcoin/signet/.cookie").unwrap(),
));
let home = env::var("HOME")?;
let mut cookie_path = PathBuf::from_str(&home)?;
cookie_path.push(".bitcoin");
cookie_path.push(network.to_core_arg());
cookie_path.push(".cookie");
let daemon_auth = SensitiveAuth(Auth::CookieFile(cookie_path));
let builder = match daemon_auth.get_auth() {
Auth::None => builder,
Auth::UserPass(user, pass) => builder.auth(user, Some(pass)),
@ -127,11 +129,13 @@ pub struct Daemon {
impl Daemon {
pub(crate) fn connect(
rpcwallet: Option<String>,
rpc_url: String,
network: Network,
// config: &Config,
// exit_flag: &ExitFlag,
// metrics: &Metrics,
) -> Result<Self> {
let mut rpc = rpc_connect(rpcwallet)?;
let mut rpc = rpc_connect(rpcwallet, network, rpc_url)?;
loop {
match rpc_poll(&mut rpc, false) {

View File

@ -2,7 +2,9 @@ use std::{
collections::HashMap,
env,
fmt::Debug,
fs,
net::SocketAddr,
path::PathBuf,
str::FromStr,
sync::{Arc, Mutex, MutexGuard, OnceLock},
time::{Duration, Instant},
@ -10,6 +12,7 @@ use std::{
use bitcoincore_rpc::json::{self as bitcoin_json};
use futures_util::{future, pin_mut, stream::TryStreamExt, FutureExt, StreamExt};
use log::{debug, error, info, warn};
use sdk_common::sp_client::bitcoin::{
absolute::LockTime,
consensus::{deserialize, serialize},
@ -288,7 +291,10 @@ fn faucet_send(
let wallet = sp_wallet.get_wallet()?;
let signed_psbt = create_transaction_for_address_with_shared_secret(
recipient, &wallet, Some(commitment), fee_estimate,
recipient,
&wallet,
Some(commitment),
fee_estimate,
)?;
let psbt = Psbt::from_str(&signed_psbt)?;
@ -349,7 +355,7 @@ fn faucet_send(
let ext_spk = ScriptBuf::new_p2tr_tweaked(ext_output_key.dangerous_assume_tweaked());
let change_spk = ScriptBuf::new_p2tr_tweaked(change_output_key.dangerous_assume_tweaked());
let mut op_return = PushBytesBuf::new();
op_return.extend_from_slice(&Vec::from_hex(commitment)?)?;
let data_spk = ScriptBuf::new_op_return(op_return);
@ -751,36 +757,50 @@ async fn handle_zmq(peers: PeerMap, shared_daemon: SharedDaemon) {
async fn main() -> Result<()> {
env_logger::init();
let addr = env::args()
// This is rudimentary, if you change the network don't forget to change rpc_url either, we won't do that for you
let rpc_url = env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:38332".to_owned());
let listening_addr = env::args()
.nth(2)
.unwrap_or_else(|| "127.0.0.1:8090".to_string());
let wallet_name = env::args().nth(2).unwrap_or_else(|| "default".to_owned());
let is_testnet: bool = env::args()
.nth(3)
.unwrap_or_else(|| "true".to_owned())
.parse()
.expect("Please provide either \"true\" or \"false\"");
let core_wallet: Option<String> = env::args().nth(4);
let wallet_name = env::args().nth(3).unwrap_or_else(|| "default".to_owned());
let network_arg: String = env::args().nth(4).unwrap_or_else(|| "signet".to_owned());
let core_wallet: Option<String> = env::args().nth(5);
MESSAGECACHE.set(MessageCache::new()).expect("Message Cache initialization failed");
let network = Network::from_core_arg(&network_arg)?;
if network == Network::Bitcoin {
warn!("Running on mainnet, you're on your own");
}
MESSAGECACHE
.set(MessageCache::new())
.expect("Message Cache initialization failed");
tokio::spawn(clean_up());
let peers = PeerMap::new(Mutex::new(HashMap::new()));
// Connect the rpc daemon
let shared_daemon = Arc::new(Mutex::new(Daemon::connect(core_wallet)?));
let shared_daemon = Arc::new(Mutex::new(Daemon::connect(core_wallet, rpc_url, network)?));
let current_tip: u32 = shared_daemon
.lock_anyhow()?
.get_current_height()?
.try_into()?;
let mut config_dir = env::var("HOME")?;
config_dir.push_str("/.4nk");
let sp_wallet_file = JsonFile::new(&config_dir, &wallet_name);
let mut config_dir = PathBuf::from_str(&env::var("HOME")?)?;
config_dir.push(".4nk");
let sp_wallet_file = JsonFile::new(&config_dir, &PathBuf::from_str(&wallet_name)?);
fs::create_dir_all(config_dir)?;
// load an existing sp_wallet, or create a new one
let is_testnet = if network == Network::Bitcoin {
false
} else {
true
};
let sp_wallet = match <JsonFile as Storage<SpWallet>>::load(&sp_wallet_file) {
Err(_) => {
let mut seed = [0u8; 64];
@ -845,9 +865,9 @@ async fn main() -> Result<()> {
tokio::spawn(handle_zmq(peers.clone(), shared_daemon.clone()));
// Create the event loop and TCP listener we'll accept connections on.
let try_socket = TcpListener::bind(&addr).await;
let try_socket = TcpListener::bind(&listening_addr).await;
let listener = try_socket.expect("Failed to bind");
debug!("Listening on: {}", addr);
debug!("Listening on: {}", listening_addr);
// Let's spawn the handling of each connection in a separate task.
while let Ok((stream, addr)) = listener.accept().await {