Skip to content

Commit

Permalink
chore: tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
thesimplekid committed Jul 15, 2024
1 parent b469ab1 commit bf30ec8
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 38 deletions.
3 changes: 2 additions & 1 deletion Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ description = "Core Lightning plugin for paying invoices with nostr connect (NIP
[dependencies]
anyhow = "1"
thiserror = "1"
log = "0.4"
cln-plugin = "0.1.9"
cln-rpc = "0.1.9"
futures = "0.3.26"
Expand All @@ -25,3 +24,5 @@ tungstenite = { version = "0.23", features = ["rustls-tls-webpki-roots"]}
dirs = "5.0.1"
hex = "0.4.3"
lightning-invoice = "0.31.0"
tracing = { version = "0.1.40", features = ["log"] }
tracing-subscriber = "0.3.18"
38 changes: 20 additions & 18 deletions src/cln_nwc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl ClnNwc {
cln_rpc_socket: PathBuf,
) -> Result<Self> {
let cln_client = cln_rpc::ClnRpc::new(&cln_rpc_socket).await.map_err(|err| {
log::error!("Could not start cln rpc: {}", err);
tracing::error!("Could not start cln rpc: {}", err);
anyhow!("Could not start cln rpc")
})?;

Expand All @@ -65,6 +65,8 @@ impl ClnNwc {
client_keys.secret_key()?.clone(),
None,
);
tracing::info!("URL: {}", wallet_connect_uri.to_string());
println!("URL: {}", wallet_connect_uri.to_string());

let client = Client::new(nwc_keys.clone());
client.add_relay(relay.clone()).await?;
Expand All @@ -84,7 +86,7 @@ impl ClnNwc {
/// Checks that it is a valid event and from an authorized pubkey
pub async fn verify_event(&self, event: &Event) -> Result<Request> {
if event.verify().is_err() {
log::info!("Event {} is invalid", event.id.to_hex());
tracing::info!("Event {} is invalid", event.id.to_hex());
bail!("Event is not a valid nostr event")
}

Expand All @@ -96,22 +98,22 @@ impl ClnNwc {
) {
Ok(content) => content,
Err(err) => {
log::info!("Could not decrypt: {err}");
tracing::info!("Could not decrypt: {err}");
bail!("Could not decrypt event");
}
};

let request = match nip47::Request::from_json(&content) {
Ok(req) => req,
Err(err) => {
log::warn!("Could not decode request {:?}", err);
tracing::warn!("Could not decode request {:?}", err);
bail!("Could not decrypt event");
}
};

// Check event is from correct pubkey
if event.pubkey.ne(&self.client_keys.public_key()) {
log::info!("Event from incorrect pubkey: {}", event.pubkey.to_string());
tracing::info!("Event from incorrect pubkey: {}", event.pubkey.to_string());
let response = nip47::Response {
result_type: request.method,
error: Some(NIP47Error {
Expand Down Expand Up @@ -148,7 +150,7 @@ impl ClnNwc {
EventBuilder::auth(challenge, relay.clone()).to_event(&self.nwc_keys)
{
if let Err(err) = self.nostr_client.send_event(auth_event).await {
log::warn!("Could not broadcast event: {err}");
tracing::warn!("Could not broadcast event: {err}");
bail!("Could not broadcast auth event")
}
}
Expand All @@ -172,20 +174,20 @@ impl ClnNwc {

// Check amount is < then config max
if amount.msat().gt(&(limits.max_invoice.msat())) {
log::info!("Invoice too large: {amount:?} > {:?}", limits.max_invoice);
tracing::info!("Invoice too large: {amount:?} > {:?}", limits.max_invoice);
bail!("Limit too large");
}

// Check spend does not exceed daily or hourly limit
if limits.check_limit(amount).is_err() {
log::info!("Sending {} msat will exceed limit", amount.msat());
log::info!(
tracing::info!("Sending {} msat will exceed limit", amount.msat());
tracing::info!(
"Hour limit: {} msats, Hour spent: {} msats",
limits.hour_limit.msat(),
limits.hour_value.msat()
);

log::info!(
tracing::info!(
"Day limit: {} msats, Day Spent: {} msats",
limits.day_limit.msat(),
limits.day_value.msat()
Expand All @@ -204,8 +206,8 @@ impl ClnNwc {
Bolt11InvoiceDescription::Hash(hash) => hash.0.to_string(),
};

log::debug!("Pay invoice request: {}", bolt11);
// Send payment
tracing::debug!("Pay invoice request: {}", bolt11);
// Sendpayment
let cln_response = self
.cln_rpc
.lock()
Expand Down Expand Up @@ -257,22 +259,22 @@ impl ClnNwc {
)
}
PayStatus::PENDING => {
log::info!("CLN returned pending response");
tracing::info!("CLN returned pending response");
limits.add_spend(amount);
bail!("Payment pending");
}
PayStatus::FAILED => {
log::error!("Payment failed: {}", bolt11.payment_hash());
tracing::error!("Payment failed: {}", bolt11.payment_hash());
bail!("Payment Failed");
}
}
}
Ok(response) => {
log::error!("Wrong cln response for pay request: {:?}", response);
tracing::error!("Wrong cln response for pay request: {:?}", response);
bail!("Wrong CLN response")
}
Err(err) => {
log::error!("Cln error response for pay: {:?}", err);
tracing::error!("Cln error response for pay: {:?}", err);
bail!("Rpc error response")
}
};
Expand Down Expand Up @@ -330,11 +332,11 @@ impl ClnNwc {
)
}
Ok(response) => {
log::error!("Wrong cln response for pay request: {:?}", response);
tracing::error!("Wrong cln response for pay request: {:?}", response);
bail!("Wrong CLN response")
}
Err(err) => {
log::error!("Cln error response for pay: {:?}", err);
tracing::error!("Cln error response for pay: {:?}", err);
bail!("Rpc error response")
}
};
Expand Down
40 changes: 22 additions & 18 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use cln_rpc::primitives::Amount;
use dirs::config_dir;
use futures::{Stream, StreamExt};
use limits::Limits;
use log::{info, warn};
use nostr_sdk::nips::nip47;
use nostr_sdk::{
ClientMessage, Filter, JsonUtil, Keys, Kind, PublicKey, RelayMessage, SubscriptionId, Url,
Expand All @@ -37,7 +36,12 @@ const CONFIG_PATH: &str = "nostr_connect_config_path";

#[tokio::main]
async fn main() -> anyhow::Result<()> {
info!("Starting cln-nostr-connect");
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();

tracing::info!("Starting cln-nostr-connect");
println!("Starting cln");
let config_option =
ConfigOption::new_str_no_default(CONFIG_PATH, "Nostr wallet connect config path");

Expand Down Expand Up @@ -74,7 +78,7 @@ async fn main() -> anyhow::Result<()> {
.subscribe("shutdown",
// Handle CLN `shutdown` if it is sent
|plugin: Plugin<()>, _: serde_json::Value| async move {
info!("Received \"shutdown\" notification from lightningd ... requesting cln_plugin shutdown");
tracing::info!("Received \"shutdown\" notification from lightningd ... requesting cln_plugin shutdown");
plugin.shutdown().ok();
plugin.join().await
})
Expand All @@ -97,7 +101,7 @@ async fn main() -> anyhow::Result<()> {
.join("config"),
};

info!("Nostr Wallet Connect Config: {:?}", config_path);
tracing::info!("Nostr Wallet Connect Config: {:?}", config_path);
let nwc_keys = plugin
.option(&nwc_secret_option)
.expect("NWC Secret must be defined")
Expand Down Expand Up @@ -158,7 +162,7 @@ async fn main() -> anyhow::Result<()> {
match event_stream(client_keys.clone().public_key(), relay_clone.clone()).await {
Ok(stream) => stream,
Err(err) => {
warn!("Event Stream Error: {:?}", err);
tracing::warn!("Event Stream Error: {:?}", err);
continue;
}
};
Expand All @@ -174,11 +178,11 @@ async fn main() -> anyhow::Result<()> {
} => {
let request = match cln_nwc.verify_event(&event).await {
Ok(request) => {
log::info!("Received a valid nostr event: {}", event.id);
tracing::info!("Received a valid nostr event: {}", event.id);
request
}
Err(_) => {
log::info!("Received an invalid nostr event: {}", event.id);
tracing::info!("Received an invalid nostr event: {}", event.id);
continue;
}
};
Expand All @@ -190,20 +194,20 @@ async fn main() -> anyhow::Result<()> {
.await
{
Ok(_) => {
log::info!("Paid invoice for event: {}", event.id);
tracing::info!("Paid invoice for event: {}", event.id);
}
Err(_) => {
log::error!("Failed to pay invoice for event {}", event.id);
tracing::error!("Failed to pay invoice for event {}", event.id);
}
}
}
nip47::RequestParams::GetBalance => {
match cln_nwc.get_balance(event.deref()).await {
Ok(_) => {
log::info!("Got balance for: {}", event.id);
tracing::info!("Got balance for: {}", event.id);
}
Err(_) => {
log::info!("Failed to get balance for event {}:", event.id);
tracing::info!("Failed to get balance for event {}:", event.id);
}
}
}
Expand Down Expand Up @@ -233,7 +237,7 @@ async fn main() -> anyhow::Result<()> {
_ => continue,
}
}
warn!("Event stream has ended");
tracing::warn!("Event stream has ended");
}

// Ok(())
Expand All @@ -260,7 +264,7 @@ async fn connect_relay(

return Ok(socket);
} else {
info!("Attempted connection to {} failed", url);
tracing::info!("Attempted connection to {} failed", url);
}

if attempt == 99 {
Expand Down Expand Up @@ -289,12 +293,12 @@ async fn event_stream(
Ok(msg) => msg,
Err(err) => {
// Handle disconnection
info!("WebSocket disconnected: {}", err);
info!("Attempting to reconnect ...");
tracing::info!("WebSocket disconnected: {}", err);
tracing::info!("Attempting to reconnect ...");
match connect_relay(relay.clone(), connect_client_pubkey).await {
Ok(new_socket) => socket = Arc::new(Mutex::new(new_socket)),
Err(err) => {
info!("{}", err);
tracing::info!("{}", err);
return None;
}
}
Expand All @@ -306,7 +310,7 @@ async fn event_stream(
let msg_text = match msg.to_text() {
Ok(msg_test) => msg_test,
Err(_) => {
info!("Failed to convert message to text");
tracing::info!("Failed to convert message to text");
continue;
}
};
Expand All @@ -324,7 +328,7 @@ async fn event_stream(
_ => continue,
}
} else {
info!("Got unexpected message: {:?}", msg);
tracing::info!("Got unexpected message: {:?}", msg);
}
}
},
Expand Down

0 comments on commit bf30ec8

Please sign in to comment.