Skip to content

Commit

Permalink
add cookie auth and fix test
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisguida committed Dec 12, 2023
1 parent c49faf6 commit c5a7839
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 92 deletions.
24 changes: 12 additions & 12 deletions flake.lock

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

9 changes: 5 additions & 4 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@
let
cln-overlay = final: prev: {
clightning = prev.clightning.overrideAttrs {
version = "23.03.2";
version = "23.11";
src = prev.fetchFromGitHub {
owner = "niftynei";
repo = "lightning";
rev = "44c5b523683160e8c20bda200c6a5a59ea40bc5e";
sha256 = "sha256-tWxnuVHhXl7JWwMxQ46b+Jd7PeoMVr7pnWXv5Of5AeI=";
#rev = "44c5b523683160e8c20bda200c6a5a59ea40bc5e";
rev = "37ad798a02336a82460b865fd4e6a29d8880856c";
sha256 = "sha256-pkXU4JB5Y2oN/2DfYNRgGJdH36Nz3gmVfC/Exv2E2Zk=";
fetchSubmodules = true;
};
};
Expand All @@ -38,7 +39,7 @@
};

devShell = pkgs.mkShell {
buildInputs = with pkgs; [ bash cargo rustc rustfmt pre-commit rustPackages.clippy pkg-config openssl bitcoin clightning ];
buildInputs = with pkgs; [ bash cargo rustc rustfmt pre-commit rustPackages.clippy pkg-config openssl bitcoin clightning poetry ];
RUST_SRC_PATH = pkgs.rustPlatform.rustLibSrc;
shellHook = ''
echo "Entering devshell..."
Expand Down
100 changes: 60 additions & 40 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ extern crate serde_json;

use bdk::chain::tx_graph::CanonicalTx;
use bdk::chain::ConfirmationTimeAnchor;
use bitcoincore_rpc::Auth;
use clap::error::ErrorKind;
use clap::{CommandFactory, Parser, Subcommand};
use cln_rpc::model::DatastoreMode;
use cln_rpc::{
model::requests::{DatastoreRequest, ListdatastoreRequest},
ClnRpc, Request, Response,
};
use home::home_dir;
use serde::{Deserialize, Serialize};
use serde_json::Value;

Expand All @@ -33,6 +35,9 @@ use smaug::state::{Smaug, State};

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
// std::env::set_var("CLN_PLUGIN_LOG", "cln_plugin=info,cln_rpc=info,debug");
eprintln!("STARTING SMAUG");
eprintln!("log set to {}", std::env::var("CLN_PLUGIN_LOG")?);
let builder = Builder::new(tokio::io::stdin(), tokio::io::stdout())
.option(options::ConfigOption::new(
"smaug_network",
Expand All @@ -46,18 +51,23 @@ async fn main() -> Result<(), anyhow::Error> {
))
.option(options::ConfigOption::new(
"smaug_brpc_port",
options::Value::Integer(8332),
"Bitcoind RPC port (default 8332)",
options::Value::OptInteger,
"Bitcoind RPC port",
))
.option(options::ConfigOption::new(
"smaug_brpc_user",
options::Value::OptString,
"Bitcoind RPC user (Required)",
"Bitcoind RPC user (Required if cookie file unavailable)",
))
.option(options::ConfigOption::new(
"smaug_brpc_pass",
options::Value::OptString,
"Bitcoind RPC password (Required)",
"Bitcoind RPC password (Required if cookie file unavailable)",
))
.option(options::ConfigOption::new(
"smaug_brpc_cookie_dir",
options::Value::OptString,
"Bitcoind data directory (for cookie file access)",
))
.notification(messages::NotificationTopic::new(UTXO_DEPOSIT_TAG))
.notification(messages::NotificationTopic::new(UTXO_SPENT_TAG))
Expand All @@ -84,7 +94,7 @@ async fn main() -> Result<(), anyhow::Error> {
);
let network = match configured_plugin.option("smaug_network") {
Some(smaug_network) => match smaug_network.as_str() {
Some(wdn) => wdn.to_owned(),
Some(sn) => sn.to_owned(),
None => configured_plugin.configuration().network,
},
None => configured_plugin.configuration().network,
Expand All @@ -103,36 +113,50 @@ async fn main() -> Result<(), anyhow::Error> {
let brpc_port: u16 = match configured_plugin.option("smaug_brpc_port") {
Some(smaug_brpc_port) => match smaug_brpc_port.as_i64() {
Some(sbp) => u16::try_from(sbp)?,
None => {
return Err(anyhow!(
"must specify smaug_brpc_port (your bitcoind instance rpcport)"
))
}
None => match network.as_str() {
"regtest" => 18334,
_ => 8332,
},
},
None => return Err(anyhow!("must specify smaug_brpc_port")),
};
let brpc_user = match configured_plugin.option("smaug_brpc_user") {
Some(smaug_brpc_user) => match smaug_brpc_user.as_str() {
Some(wdn) => wdn.to_owned(),
None => return Err(anyhow!("must specify smaug_brpc_user")),
None => match network.as_str() {
"regtest" => 18334,
_ => 8332,
},
None => {
};
let mut brpc_auth: Auth = Auth::None;
if let Some(bu_val) = configured_plugin.option("smaug_brpc_user") {
if let Some(sbu) = bu_val.as_str() {
if let Some(bs_val) = configured_plugin.option("smaug_brpc_pass") {
if let Some(sbp) = bs_val.as_str() {
brpc_auth = Auth::UserPass(sbu.to_owned(), sbp.to_owned());
}
}
}
if let Auth::None = brpc_auth {
return Err(anyhow!(
"must specify smaug_brpc_user (your bitcoind instance rpcuser)"
))
"specified `smaug_brpc_user` but did not specify `smaug_brpc_pass`"
));
}
};
let brpc_pass = match configured_plugin.option("smaug_brpc_pass") {
Some(smaug_brpc_pass) => match smaug_brpc_pass.as_str() {
Some(wdn) => wdn.to_owned(),
None => {
return Err(anyhow!(
"must specify smaug_brpc_pass (your bitcoind instance rpcpassword)"
))
} else {
if let Some(smaug_brpc_cookie_dir) = configured_plugin.option("smaug_brpc_cookie_dir") {
if let Some(sbcd) = smaug_brpc_cookie_dir.as_str() {
brpc_auth = Auth::CookieFile(PathBuf::from(sbcd).join(".cookie"))
} else {
if network == "regtest" {
brpc_auth = Auth::CookieFile(
home_dir()
.expect("cannot determine home dir")
.join(".bitcoin/regtest")
.join(".cookie"),
);
}
}
},
None => return Err(anyhow!("must specify smaug_brpc_pass")),
}
};
if let Auth::None = brpc_auth {
return Err(anyhow!("must specify either `smaug_bprc_cookie_dir` or `smaug_brpc_user` and `smaug_brpc_pass`"));
}
log::trace!("using auth info: {:?}", brpc_auth);
let ln_dir: PathBuf = configured_plugin.configuration().lightning_dir.into();
// Create data dir if it does not exist
fs::create_dir_all(ln_dir.join(SMAUG_DATADIR)).unwrap_or_else(|e| {
Expand Down Expand Up @@ -182,8 +206,7 @@ async fn main() -> Result<(), anyhow::Error> {
network: network.clone(),
brpc_host: brpc_host.clone(),
brpc_port: brpc_port.clone(),
brpc_user: brpc_user.clone(),
brpc_pass: brpc_pass.clone(),
brpc_auth: brpc_auth.clone(),
db_dir: ln_dir.join(SMAUG_DATADIR),
};
let plugin_state = Arc::new(Mutex::new(watch_descriptor.clone()));
Expand Down Expand Up @@ -291,20 +314,19 @@ async fn add(plugin: Plugin<State>, args: AddArgs) -> Result<serde_json::Value,
let mut dw = DescriptorWallet::from_args(args, plugin.state().lock().await.network.clone())
.map_err(|e| anyhow!("error parsing args: {}", e))?;
log::trace!("params = {:?}", dw);
let (db_dir, brpc_host, brpc_port, brpc_user, brpc_pass) = {
let (db_dir, brpc_host, brpc_port, brpc_auth) = {
let state = plugin.state().lock().await;
(
state.db_dir.clone(),
// FIXME: actually use the RpcConnection struct instead of this nonsense
state.brpc_host.clone(),
state.brpc_port.clone(),
state.brpc_user.clone(),
state.brpc_pass.clone(),
state.brpc_auth.clone(),
)
};
let mut dw_clone = dw.clone();
let wallet = dw_clone
.fetch_wallet(db_dir, brpc_host, brpc_port, brpc_user, brpc_pass)
.fetch_wallet(db_dir, brpc_host, brpc_port, brpc_auth)
.await?;
let bdk_transactions_iter = wallet.transactions();
let mut transactions = Vec::<CanonicalTx<'_, Transaction, ConfirmationTimeAnchor>>::new();
Expand Down Expand Up @@ -419,14 +441,13 @@ async fn block_added_handler(plugin: Plugin<State>, v: serde_json::Value) -> Res
"Smaug state!!! {:?}",
plugin.state().lock().await.wallets.clone()
);
let (db_dir, brpc_host, brpc_port, brpc_user, brpc_pass) = {
let (db_dir, brpc_host, brpc_port, brpc_auth) = {
let state = plugin.state().lock().await;
(
state.db_dir.clone(),
state.brpc_host.clone(),
state.brpc_port.clone(),
state.brpc_user.clone(),
state.brpc_pass.clone(),
state.brpc_auth.clone(),
)
};

Expand All @@ -445,8 +466,7 @@ async fn block_added_handler(plugin: Plugin<State>, v: serde_json::Value) -> Res
db_dir.clone(),
brpc_host.clone(),
brpc_port.clone(),
brpc_user.clone(),
brpc_pass.clone(),
brpc_auth.clone(),
)
.await?;

Expand Down
13 changes: 7 additions & 6 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{collections::BTreeMap, path::PathBuf, sync::Arc};

use bdk::bitcoin;
use bitcoincore_rpc::Auth;
use tokio::sync::Mutex;

use crate::wallet::DescriptorWallet;
Expand All @@ -17,10 +18,11 @@ pub struct Smaug {
pub brpc_host: String,
/// Bitcoind RPC port
pub brpc_port: u16,
/// Bitcoind RPC user
pub brpc_user: String,
/// Bitcoind RPC password
pub brpc_pass: String,
// /// Bitcoind RPC user
// pub brpc_user: String,
// /// Bitcoind RPC password
// pub brpc_pass: String,
pub brpc_auth: Auth,
/// The db path relevant to our wallets
pub db_dir: PathBuf,
}
Expand All @@ -32,8 +34,7 @@ impl Smaug {
network: bitcoin::Network::Bitcoin.to_string(),
brpc_host: String::from("127.0.0.1"),
brpc_port: 8332,
brpc_user: String::from("bitcoin"),
brpc_pass: String::from("password"),
brpc_auth: Auth::None,
db_dir: PathBuf::new(),
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,7 @@ impl DescriptorWallet {
db_dir: PathBuf,
brpc_host: String,
brpc_port: u16,
brpc_user: String,
brpc_pass: String,
brpc_auth: Auth,
) -> Result<Wallet<Store<'_, bdk::wallet::ChangeSet>>, Error> {
log::trace!("creating path");
let db_filename = self.get_name()?;
Expand All @@ -307,7 +306,8 @@ impl DescriptorWallet {

let rpc_client = Client::new_with_timeout(
&format!("http://{}:{}", brpc_host.clone(), brpc_port.clone()),
Auth::UserPass(brpc_user.clone(), brpc_pass.clone()), // Auth::CookieFile(PathBuf::from("/home/cguida/.bitcoin/regtest/.cookie"))
brpc_auth,
// Auth::UserPass(brpc_user.clone(), brpc_pass.clone()), // Auth::CookieFile(PathBuf::from("/home/cguida/.bitcoin/regtest/.cookie"))
Duration::from_secs(3600),
)?;

Expand Down
Loading

0 comments on commit c5a7839

Please sign in to comment.