From d372c53548f62e5bc9fcb421619087377a0023ba Mon Sep 17 00:00:00 2001 From: Sonkeng Maldini Date: Thu, 19 Feb 2026 14:40:19 +0100 Subject: [PATCH 1/5] Initialize tracing crate --- Cargo.lock | 16 +++++++---- Cargo.toml | 5 ++-- README.md | 15 +++++++++++ bmp_tracing/Cargo.toml | 11 ++++++++ bmp_tracing/src/lib.rs | 35 +++++++++++++++++++++++++ rpc/Cargo.toml | 2 +- rpc/src/bin/musigd.rs | 5 +++- rpc/src/bmp_service.rs | 2 +- rpc/src/bmp_wallet_service.rs | 2 +- rpc/src/observable.rs | 2 +- rpc/src/wallet.rs | 7 +++-- rustfmt.toml | 4 +-- testenv/Cargo.toml | 5 ++-- testenv/src/lib.rs | 28 ++------------------ wallet/Cargo.toml | 3 +-- wallet/src/bmp_wallet.rs | 2 ++ wallet/src/utils.rs | 1 + wallet/tests/wallet_integration_test.rs | 7 +++-- 18 files changed, 101 insertions(+), 51 deletions(-) create mode 100644 bmp_tracing/Cargo.toml create mode 100644 bmp_tracing/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 387210a..438ec44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -488,6 +488,14 @@ dependencies = [ "generic-array", ] +[[package]] +name = "bmp_tracing" +version = "0.1.0" +dependencies = [ + "tracing", + "tracing-subscriber", +] + [[package]] name = "bstr" version = "1.12.1" @@ -1986,6 +1994,7 @@ dependencies = [ "assert_cmd", "bdk_bitcoind_rpc", "bdk_wallet", + "bmp_tracing", "clap", "const_format", "drop-stream", @@ -2007,7 +2016,6 @@ dependencies = [ "tonic-prost", "tonic-prost-build", "tracing", - "tracing-subscriber", "unimock", ] @@ -2399,6 +2407,7 @@ dependencies = [ "bdk_bitcoind_rpc", "bdk_electrum", "bdk_wallet", + "bmp_tracing", "electrsd", "hex", "hmac", @@ -2407,8 +2416,6 @@ dependencies = [ "sha2", "simple-semaphore", "tempfile", - "tracing", - "tracing-subscriber", ] [[package]] @@ -2807,6 +2814,7 @@ dependencies = [ "bdk_electrum", "bdk_kyoto", "bdk_wallet", + "bmp_tracing", "hex", "rand 0.9.2", "rusqlite", @@ -2814,8 +2822,6 @@ dependencies = [ "simple-semaphore", "tempfile", "testenv", - "tracing", - "tracing-subscriber", "zeroize", ] diff --git a/Cargo.toml b/Cargo.toml index 6883907..b520d17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["protocol", "rpc", "wallet", "testenv"] +members = ["protocol", "rpc", "wallet", "testenv", "bmp_tracing"] exclude = ["poc"] [workspace.dependencies] @@ -24,7 +24,8 @@ tempfile = "3.25.0" thiserror = "2.0.18" tokio = "1.49.0" tracing = "0.1.44" -tracing-subscriber = "0.3.22" +tracing-subscriber = { version = "0.3.22", features = ["env-filter"] } +bmp_tracing = { path = "bmp_tracing" } zeroize = "1.8.2" [workspace.lints.rust] diff --git a/README.md b/README.md index f54b9f4..607e293 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,21 @@ To set it up you need to run the following command. The command will copy the pre-commit script to your local `.git/hooks/pre-commit` file. This helps us keeping clean build and focus on the essentials parts when reviewing pull requests. +## logging / tracing + +A small helper crate called `bmp_tracing` lives in the workspace. It +exposes a single initialization function that all binaries and test +environments should call once at startup. The API is intentionally +minimal: + +```rust +bmp_tracing::init("info"); +``` + +The function reads the standard `RUST_LOG` environment variable and falls +back to the supplied default level. You can disable logging completely by +setting `RUST_LOG=off`. + ## running the tests to run the test you need a work regtest environment as provided by nigiri. You may need to diff --git a/bmp_tracing/Cargo.toml b/bmp_tracing/Cargo.toml new file mode 100644 index 0000000..d1f2568 --- /dev/null +++ b/bmp_tracing/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "bmp_tracing" +version = "0.1.0" +edition = "2024" + +[dependencies] +tracing = { workspace = true } +tracing-subscriber = { workspace = true } + +[lints] +workspace = true diff --git a/bmp_tracing/src/lib.rs b/bmp_tracing/src/lib.rs new file mode 100644 index 0000000..b19c435 --- /dev/null +++ b/bmp_tracing/src/lib.rs @@ -0,0 +1,35 @@ +pub use tracing; +pub use tracing_subscriber::*; + +use std::error::Error as _; + +use tracing_subscriber::layer::SubscriberExt as _; +use tracing_subscriber::util::SubscriberInitExt as _; + +pub fn init(default_level: &str) { + if tracing::dispatcher::has_been_set() { + return; + } + + if let Ok(val) = std::env::var("RUST_LOG") + && (val.eq_ignore_ascii_case("off") || val.eq_ignore_ascii_case("none")) + { + return; + } + + let filter = EnvFilter::try_from_default_env().unwrap_or_else(|e| { + if matches!(e.source(), Some(s) if s.is::()) { + eprintln!("Could not parse `RUST_LOG` environment variable: {e}"); + } + EnvFilter::new(default_level) + }); + + tracing_subscriber::registry() + .with(filter) + .with( + fmt::layer() + .map_fmt_fields(tracing_subscriber::field::MakeExt::debug_alt) + .with_writer(std::io::stderr), + ) + .init(); +} diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index a08f665..646966c 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -23,11 +23,11 @@ tokio-stream = "0.1.18" tonic = "0.14.4" tonic-prost = "0.14.4" tracing = { workspace = true } +bmp_tracing = { workspace = true } unimock = { version = "0.6.8", optional = true } # Dependencies used only by the binary target(s): # TODO: Consider making a workspace of separate packages to avoid pulling these into the library: clap = { version = "4.5.59", features = ["derive"] } -tracing-subscriber = { workspace = true, features = ["env-filter"] } # TODO move this to dev-dependencies: testenv = { path ="../testenv"} diff --git a/rpc/src/bin/musigd.rs b/rpc/src/bin/musigd.rs index 31b5231..1abcb58 100644 --- a/rpc/src/bin/musigd.rs +++ b/rpc/src/bin/musigd.rs @@ -1,6 +1,7 @@ use std::error::Error; use std::sync::Arc; +use bmp_tracing::tracing::info; use clap::Parser; use rpc::bmp_service::BmpServiceImpl; use rpc::bmp_wallet_service::BmpWalletServiceImpl; @@ -10,7 +11,6 @@ use rpc::server::{MusigImpl, MusigServer, WalletImpl, WalletServer}; use rpc::wallet::WalletServiceImpl; use testenv::TestEnv; use tonic::transport::Server; -use tracing::info; #[derive(Debug, Parser)] #[command(version, about, long_about = None)] @@ -24,6 +24,9 @@ struct Cli { #[tokio::main] async fn main() -> Result<(), Box> { let cli: Cli = Cli::parse(); + + bmp_tracing::init("info"); + let testenv = TestEnv::new()?; let addr = format!("127.0.0.1:{}", cli.port).parse()?; diff --git a/rpc/src/bmp_service.rs b/rpc/src/bmp_service.rs index e5815c7..94697a0 100644 --- a/rpc/src/bmp_service.rs +++ b/rpc/src/bmp_service.rs @@ -2,13 +2,13 @@ use std::collections::HashMap; use std::sync::Mutex; use bdk_wallet::bitcoin::Amount; +use bmp_tracing::tracing::info; use protocol::protocol_musig_adaptor::{ BMPContext, BMPProtocol, MemWallet, ProtocolRole, Round1Parameter, }; use protocol::wallet_service::WalletService; use testenv::TestEnv; use tonic::{Request, Response, Result, Status}; -use tracing::info; use crate::pb::bmp_protocol::bmp_protocol_service_server::BmpProtocolService; use crate::pb::bmp_protocol::{self, InitializeRequest, InitializeResponse, Role}; diff --git a/rpc/src/bmp_wallet_service.rs b/rpc/src/bmp_wallet_service.rs index 22d479e..feb73a1 100644 --- a/rpc/src/bmp_wallet_service.rs +++ b/rpc/src/bmp_wallet_service.rs @@ -1,5 +1,5 @@ +use bmp_tracing::tracing::info; use tonic::{Request, Response, Result}; -use tracing::info; use crate::pb::bmp_wallet; use crate::pb::bmp_wallet::wallet_server::Wallet; diff --git a/rpc/src/observable.rs b/rpc/src/observable.rs index bae47b6..3e16b29 100644 --- a/rpc/src/observable.rs +++ b/rpc/src/observable.rs @@ -4,10 +4,10 @@ use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::hash::Hash; +use bmp_tracing::tracing::trace; use futures_util::Stream; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; -use tracing::trace; #[derive(Debug, Default)] pub struct Observable { diff --git a/rpc/src/wallet.rs b/rpc/src/wallet.rs index 21c7da7..80ff945 100644 --- a/rpc/src/wallet.rs +++ b/rpc/src/wallet.rs @@ -1,4 +1,7 @@ -#![cfg_attr(feature = "unimock", expect(clippy::ignored_unit_patterns, reason = "macro-generated code"))] +#![cfg_attr( + feature = "unimock", + expect(clippy::ignored_unit_patterns, reason = "macro-generated code") +)] use std::sync::{Arc, Mutex, RwLock}; @@ -7,13 +10,13 @@ use bdk_bitcoind_rpc::Emitter; use bdk_wallet::bitcoin::{Network, Transaction, Txid}; use bdk_wallet::chain::{ChainPosition, CheckPoint, ConfirmationBlockTime}; use bdk_wallet::{AddressInfo, Balance, KeychainKind, LocalOutput, Wallet}; +use bmp_tracing::tracing::{debug, error, info, trace}; use drop_stream::DropStreamExt as _; use futures_util::never::Never; use futures_util::stream::{BoxStream, StreamExt as _}; use thiserror::Error; use tokio::task::{self, JoinHandle}; use tokio::time::{self, Duration, MissedTickBehavior}; -use tracing::{debug, error, info, trace}; use crate::observable::ObservableHashMap; diff --git a/rustfmt.toml b/rustfmt.toml index 24f1db2..58bbf54 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -2,7 +2,7 @@ comment_width = 100 format_code_in_doc_comments = true wrap_comments = true reorder_imports = true -edition = "2021" +edition = "2024" imports_granularity = "Module" group_imports = "StdExternalCrate" -style_edition = "2021" +style_edition = "2024" diff --git a/testenv/Cargo.toml b/testenv/Cargo.toml index b9755a4..7deaf91 100644 --- a/testenv/Cargo.toml +++ b/testenv/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "testenv" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] # Workspace dependencies @@ -14,8 +14,7 @@ rand = { workspace = true } secp = { workspace = true } simple-semaphore = { workspace = true } tempfile = { workspace = true } -tracing = { workspace = true } -tracing-subscriber = { workspace = true, features = ["env-filter"] } +bmp_tracing = { workspace = true } electrsd = { version = "0.36.1", features = [ "esplora_a33e97e1", diff --git a/testenv/src/lib.rs b/testenv/src/lib.rs index e23432b..fd96e93 100644 --- a/testenv/src/lib.rs +++ b/testenv/src/lib.rs @@ -1,6 +1,5 @@ //! Bitcoin regtest environment using electrsd with automatic executable downloads -use std::error::Error as _; use std::net::SocketAddrV4; use std::sync::{Arc, LazyLock}; use std::time::Duration; @@ -24,11 +23,6 @@ use secp::Scalar; use sha2::Sha256; use simple_semaphore::{Permit, Semaphore}; use tempfile::{tempdir, TempDir}; -use tracing_subscriber::field::MakeExt; -use tracing_subscriber::filter::{EnvFilter, ParseError}; -use tracing_subscriber::fmt; -use tracing_subscriber::layer::SubscriberExt as _; -use tracing_subscriber::util::SubscriberInitExt as _; /// Bitcoin regtest environment manager pub struct TestEnv { @@ -190,26 +184,8 @@ impl TestEnv { Node::from_downloaded_with_conf(&bitcoin_config)? }; - // also enables tracing if wanted - // - if !tracing::dispatcher::has_been_set() { - let filter = EnvFilter::try_from_default_env() - .unwrap_or_else(|e| { - if matches!(e.source(), Some(s) if s.is::()) { - eprintln!("Could not parse `RUST_LOG` environment variable: {e}"); - } - EnvFilter::new("info")//,rpc=debug") - }); - - if !tracing::dispatcher::has_been_set() { - tracing_subscriber::registry() - .with(filter) - .with(fmt::layer() - .map_fmt_fields(MakeExt::debug_alt) - .with_writer(std::io::stderr)) - .init(); - } - } + // initialize global tracing subscriber, defaulting to `info`. + bmp_tracing::init("info"); // Try to get electrs executable (from environment or downloads) let electrs_exe = if let Ok(path) = std::env::var("ELECTRS_EXEC") { diff --git a/wallet/Cargo.toml b/wallet/Cargo.toml index c04ac98..359c5a2 100644 --- a/wallet/Cargo.toml +++ b/wallet/Cargo.toml @@ -14,8 +14,7 @@ hex = { workspace = true } rand = { workspace = true } rusqlite = { workspace = true } secp = { workspace = true } -tracing = { workspace = true } -tracing-subscriber = { workspace = true } +bmp_tracing = { workspace = true } zeroize = { workspace = true } [dev-dependencies] diff --git a/wallet/src/bmp_wallet.rs b/wallet/src/bmp_wallet.rs index 0c16b1e..e8f57d3 100644 --- a/wallet/src/bmp_wallet.rs +++ b/wallet/src/bmp_wallet.rs @@ -21,6 +21,7 @@ use bdk_wallet::{ AddressInfo, Balance, ChangeSet, KeychainKind, PersistedWallet, SignOptions, TxBuilder, TxOrdering, Utxo, Wallet, WalletPersister, WeightedUtxo, }; +use bmp_tracing::tracing; use rand::RngCore as _; use secp::Scalar; @@ -752,6 +753,7 @@ mod tests { use bdk_wallet::chain::{self, BlockId}; use bdk_wallet::test_utils::{receive_output_to_address, ReceiveTo}; use bdk_wallet::{AddressInfo, KeychainKind, SignOptions}; + use bmp_tracing::tracing; use rand::RngCore as _; use secp::Scalar; use simple_semaphore::{self, Semaphore}; diff --git a/wallet/src/utils.rs b/wallet/src/utils.rs index a768106..519a07e 100644 --- a/wallet/src/utils.rs +++ b/wallet/src/utils.rs @@ -5,6 +5,7 @@ use base64::engine::general_purpose; use base64::Engine as _; use bdk_kyoto::bip157::tokio; use bdk_kyoto::{Info, Receiver, UnboundedReceiver, Warning}; +use bmp_tracing::tracing; use zeroize::Zeroize as _; /// Derives a 256-bit key from a password and salt using Argon2. diff --git a/wallet/tests/wallet_integration_test.rs b/wallet/tests/wallet_integration_test.rs index ed800ab..9097372 100644 --- a/wallet/tests/wallet_integration_test.rs +++ b/wallet/tests/wallet_integration_test.rs @@ -242,8 +242,7 @@ async fn test_cbf_main_wallet() -> anyhow::Result<()> { #[tokio::test] async fn test_cbf_imported() -> anyhow::Result<()> { let env = TestEnv::new()?; - env.mine_blocks(1)?; - env.wait_for_block()?; + env.mine_block()?; let mut wallet = BMPWallet::new(Network::Regtest)?; @@ -269,8 +268,8 @@ async fn test_cbf_imported() -> anyhow::Result<()> { #[tokio::test] async fn test_cbf_imported_and_main() -> anyhow::Result<()> { let env = TestEnv::new()?; - env.mine_blocks(1)?; - env.wait_for_block()?; + env.mine_block()?; + let mut wallet = BMPWallet::new(Network::Regtest)?; let addr = wallet.next_unused_address(KeychainKind::External); env.fund_address(&addr, Amount::from_sat(100_000))?; From 5483186c65fdf2c4bb9de6b17eb6b437e6a6ea67 Mon Sep 17 00:00:00 2001 From: Sonkeng Maldini Date: Tue, 24 Feb 2026 20:12:31 +0100 Subject: [PATCH 2/5] feat: allow different output source for traces --- Cargo.lock | 1 + Cargo.toml | 1 + bmp_tracing/Cargo.toml | 1 + bmp_tracing/src/lib.rs | 60 ++++++++++++++++++++++++++++++++++++------ 4 files changed, 55 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 438ec44..6761724 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -493,6 +493,7 @@ name = "bmp_tracing" version = "0.1.0" dependencies = [ "tracing", + "tracing-core", "tracing-subscriber", ] diff --git a/Cargo.toml b/Cargo.toml index b520d17..875fc62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ tempfile = "3.25.0" thiserror = "2.0.18" tokio = "1.49.0" tracing = "0.1.44" +tracing-core = {version = "0.1.35", default-features = false} tracing-subscriber = { version = "0.3.22", features = ["env-filter"] } bmp_tracing = { path = "bmp_tracing" } zeroize = "1.8.2" diff --git a/bmp_tracing/Cargo.toml b/bmp_tracing/Cargo.toml index d1f2568..270f0d3 100644 --- a/bmp_tracing/Cargo.toml +++ b/bmp_tracing/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] tracing = { workspace = true } tracing-subscriber = { workspace = true } +tracing-core = { workspace = true } [lints] workspace = true diff --git a/bmp_tracing/src/lib.rs b/bmp_tracing/src/lib.rs index b19c435..5d0edde 100644 --- a/bmp_tracing/src/lib.rs +++ b/bmp_tracing/src/lib.rs @@ -1,22 +1,69 @@ pub use tracing; -pub use tracing_subscriber::*; +pub use tracing_subscriber; use std::error::Error as _; +use std::fs::File; +use std::io; +use std::path::PathBuf; -use tracing_subscriber::layer::SubscriberExt as _; -use tracing_subscriber::util::SubscriberInitExt as _; +use tracing_subscriber::filter::EnvFilter; +use tracing_subscriber::{ + Layer, fmt, layer::SubscriberExt as _, registry::LookupSpan, util::SubscriberInitExt as _, +}; +#[derive(Debug, Clone)] +#[expect(clippy::exhaustive_enums)] +pub enum LogConfig { + File(PathBuf), + Stdout, + Stderr, +} + +impl LogConfig { + pub fn layer(self) -> Box + Send + Sync + 'static> + where + S: tracing_core::Subscriber, + for<'a> S: LookupSpan<'a>, + { + // Shared configuration regardless of where logs are output to. + let fmt_layer = fmt::layer() + .with_line_number(true) + .with_file(true) + .with_thread_ids(false) + .with_thread_names(true) + .map_fmt_fields(tracing_subscriber::field::MakeExt::debug_alt); + + match self { + Self::File(path) => { + let file = File::create(&path) + .unwrap_or_else(|e| panic!("failed to create log file at {e}")); + Box::new(fmt_layer.with_writer(file)) + } + Self::Stdout => Box::new(fmt_layer.with_writer(io::stdout)), + Self::Stderr => Box::new(fmt_layer.with_writer(io::stderr)), + } + } +} + +/// Initialize tracing with default configuration pub fn init(default_level: &str) { + init_with_config(default_level, LogConfig::Stdout); +} + +/// Initialize tracing with custom output configuration. +pub fn init_with_config(default_level: &str, config: LogConfig) { if tracing::dispatcher::has_been_set() { return; } + // Check if tracing is explicitly disabled if let Ok(val) = std::env::var("RUST_LOG") && (val.eq_ignore_ascii_case("off") || val.eq_ignore_ascii_case("none")) { return; } + // Create the filter layer let filter = EnvFilter::try_from_default_env().unwrap_or_else(|e| { if matches!(e.source(), Some(s) if s.is::()) { eprintln!("Could not parse `RUST_LOG` environment variable: {e}"); @@ -24,12 +71,9 @@ pub fn init(default_level: &str) { EnvFilter::new(default_level) }); + // Build and init the subscriber tracing_subscriber::registry() .with(filter) - .with( - fmt::layer() - .map_fmt_fields(tracing_subscriber::field::MakeExt::debug_alt) - .with_writer(std::io::stderr), - ) + .with(config.layer()) .init(); } From 3190107d77aab352b379947659f5b059b1172bc9 Mon Sep 17 00:00:00 2001 From: Sonkeng Maldini Date: Tue, 24 Feb 2026 21:15:22 +0100 Subject: [PATCH 3/5] feat: replace println statements with tracing --- Cargo.lock | 1 + bmp_tracing/src/lib.rs | 2 +- protocol/Cargo.toml | 1 + protocol/src/protocol_musig_adaptor.rs | 22 ++++++--- protocol/tests/protocol_integration_tests.rs | 5 +- rpc/src/bin/musig-cli.rs | 8 ++-- testenv/src/lib.rs | 49 +++++++++++--------- 7 files changed, 54 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6761724..5883dde 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1810,6 +1810,7 @@ dependencies = [ "anyhow", "bdk_electrum", "bdk_wallet", + "bmp_tracing", "const_format", "dotenv", "musig2", diff --git a/bmp_tracing/src/lib.rs b/bmp_tracing/src/lib.rs index 5d0edde..df4839c 100644 --- a/bmp_tracing/src/lib.rs +++ b/bmp_tracing/src/lib.rs @@ -30,7 +30,7 @@ impl LogConfig { .with_line_number(true) .with_file(true) .with_thread_ids(false) - .with_thread_names(true) + .with_thread_names(false) .map_fmt_fields(tracing_subscriber::field::MakeExt::debug_alt); match self { diff --git a/protocol/Cargo.toml b/protocol/Cargo.toml index 5947f6d..c4995b6 100644 --- a/protocol/Cargo.toml +++ b/protocol/Cargo.toml @@ -15,6 +15,7 @@ rand_chacha = { workspace = true } thiserror = { workspace = true } # TODO move this to dev-dependencies: testenv = { path = "../testenv" } +bmp_tracing = { workspace = true } [dev-dependencies] bdk_wallet = { workspace = true, features = ["test-utils"] } diff --git a/protocol/src/protocol_musig_adaptor.rs b/protocol/src/protocol_musig_adaptor.rs index 5bc594f..e24c12b 100644 --- a/protocol/src/protocol_musig_adaptor.rs +++ b/protocol/src/protocol_musig_adaptor.rs @@ -10,6 +10,7 @@ use bdk_wallet::bitcoin::{ }; use bdk_wallet::template::{Bip86, DescriptorTemplate as _}; use bdk_wallet::{AddressInfo, KeychainKind, SignOptions, Wallet}; +use bmp_tracing::tracing; use musig2::secp::{MaybeScalar, Point}; use musig2::{PartialSignature, PubNonce}; use rand::RngCore as _; @@ -84,9 +85,11 @@ impl MemWallet { let network: Network = Network::Regtest; let xprv: Xpriv = Xpriv::new_master(network, &seed)?; - println!("Generated Master Private Key:\n{xprv}\nWarning: be very careful with private \ + tracing::info!( + "Generated Master Private Key:\n{xprv}\nWarning: be very careful with private \ keys when using MainNet! We are logging these values for convenience only because this \ - is an example on RegTest.\n"); + is an example on RegTest.\n" + ); let (descriptor, external_map, _) = Bip86(xprv, KeychainKind::External) .build(network) @@ -122,7 +125,7 @@ impl MemWallet { stdout.flush().expect("must flush"); } }); - eprintln!("requesting update..."); + tracing::info!("requesting update..."); let update = self .client .full_scan(request, STOP_GAP, BATCH_SIZE, false)?; @@ -297,11 +300,18 @@ impl BMPProtocol { }) } - #[expect(clippy::similar_names, reason = "easy to distinguish local variable names in this case")] + #[expect( + clippy::similar_names, + reason = "easy to distinguish local variable names in this case" + )] pub fn round2(&mut self, bob: Round1Parameter) -> anyhow::Result { self.check_round(2); assert_ne!(bob.p_a, bob.q_a, "Bob is sending the same point for P' and Q'."); - println!("The {:?} sellers secret for P_Tik is {:?}.", self.ctx.role, self.p_tik.my_key_share()?.prv_key()?); + tracing::debug!( + "The {:?} sellers secret for P_Tik is {:?}.", + self.ctx.role, + self.p_tik.my_key_share()?.prv_key()? + ); // key Aggregation ----- self.p_tik.set_peers_pub_key(bob.p_a); @@ -749,7 +759,7 @@ impl SwapTx { if self.role == ProtocolRole::Buyer { p_tik.set_peers_prv_key(self.fund_sig.reveal_adaptor_secret(signature)?)?; p_tik.aggregate_prv_key_shares()?; - println!("revealed p_tik aggregated secret key: {:?}", p_tik.peers_key_share()?.prv_key()?); + tracing::debug!("revealed p_tik aggregated secret key: {:?}", p_tik.peers_key_share()?.prv_key()?); // p_tik shall have the other sec key and the aggregated secret key. // TODO Bob can import now the aggregated key into his wallet. there is no risk that // Alice may publish any transaction messing with it. diff --git a/protocol/tests/protocol_integration_tests.rs b/protocol/tests/protocol_integration_tests.rs index b555abe..987b3ca 100644 --- a/protocol/tests/protocol_integration_tests.rs +++ b/protocol/tests/protocol_integration_tests.rs @@ -2,6 +2,7 @@ use bdk_wallet::bitcoin; use bitcoin::key::{Keypair, Secp256k1, TapTweak as _, TweakedKeypair, TweakedPublicKey}; use bitcoin::secp256k1::Message; use bitcoin::{Amount, TapSighashType}; +use bmp_tracing::tracing; use musig2::KeyAggContext; use musig2::secp::Point; use protocol::protocol_musig_adaptor::{BMPContext, BMPProtocol, MemWallet, ProtocolRole}; @@ -18,7 +19,7 @@ fn test_initial_tx_creation() -> anyhow::Result<()> { } fn initial_tx_creation(env: &TestEnv) -> anyhow::Result<(BMPProtocol, BMPProtocol)> { - println!("running..."); + tracing::debug!("running..."); let alice_funds = MemWallet::funded_wallet(env); let bob_funds = MemWallet::funded_wallet(env); @@ -130,7 +131,7 @@ fn test_claim() -> anyhow::Result<()> { let tx = alice.claim_tx_me.broadcast(&alice.ctx)?; - println!("http://localhost:5000/tx/{tx}"); + tracing::info!("http://localhost:5000/tx/{tx}"); env.mine_block()?; Ok(()) } diff --git a/rpc/src/bin/musig-cli.rs b/rpc/src/bin/musig-cli.rs index 6670666..767ae42 100644 --- a/rpc/src/bin/musig-cli.rs +++ b/rpc/src/bin/musig-cli.rs @@ -42,17 +42,17 @@ async fn main() -> Result<(), Box> { Commands::WalletBalance => { let response = client.wallet_balance(Request::new(WalletBalanceRequest {})).await?; drop(client); - println!("{}", serde_json::to_string_pretty(&response.into_inner())?); + tracing::info!("{}", serde_json::to_string_pretty(&response.into_inner())?); } Commands::NewAddress => { let response = client.new_address(Request::new(NewAddressRequest {})).await?; drop(client); - println!("{}", serde_json::to_string_pretty(&response.into_inner())?); + tracing::info!("{}", serde_json::to_string_pretty(&response.into_inner())?); } Commands::ListUnspent => { let response = client.list_unspent(Request::new(ListUnspentRequest {})).await?; drop(client); - println!("{}", serde_json::to_string_pretty(&response.into_inner())?); + tracing::info!("{}", serde_json::to_string_pretty(&response.into_inner())?); } Commands::NotifyConfidence { tx_id } => { let tx_id = tx_id.parse::()?.to_byte_array().into(); @@ -60,7 +60,7 @@ async fn main() -> Result<(), Box> { drop(client); let mut stream = response.into_inner(); while let Some(event_result) = stream.next().await { - println!("{}", serde_json::to_string_pretty(&event_result?)?); + tracing::info!("{}", serde_json::to_string_pretty(&event_result?)?); } } } diff --git a/testenv/src/lib.rs b/testenv/src/lib.rs index fd96e93..44b6c47 100644 --- a/testenv/src/lib.rs +++ b/testenv/src/lib.rs @@ -7,22 +7,23 @@ use std::time::Duration; use anyhow::{Context as _, Result}; use bdk_bitcoind_rpc::bitcoincore_rpc; use bdk_bitcoind_rpc::bitcoincore_rpc::{Auth, RpcApi as _}; -use bdk_electrum::bdk_core::bitcoin::{KnownHrp, XOnlyPublicKey}; use bdk_electrum::BdkElectrumClient; +use bdk_electrum::bdk_core::bitcoin::{KnownHrp, XOnlyPublicKey}; use bdk_wallet::bitcoin::address::NetworkChecked; use bdk_wallet::bitcoin::key::Secp256k1; use bdk_wallet::bitcoin::secp256k1::All; use bdk_wallet::bitcoin::{Address, Amount, BlockHash, Network, Transaction, Txid}; +use bmp_tracing::tracing; pub use corepc_node::get_available_port; use electrsd::corepc_node::Node; use electrsd::electrum_client::{Client, ElectrumApi}; -use electrsd::{corepc_node, ElectrsD}; +use electrsd::{ElectrsD, corepc_node}; use hmac::{Hmac, Mac as _}; use rand::{Rng as _, RngCore as _}; use secp::Scalar; use sha2::Sha256; use simple_semaphore::{Permit, Semaphore}; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; /// Bitcoin regtest environment manager pub struct TestEnv { @@ -163,7 +164,7 @@ impl TestEnv { std::env::set_current_dir(tmp_dir.path()).expect("failed to set current directory"); // Try to start bitcoind (from environment or downloads) - println!("Starting bitcoind..."); + tracing::info!("Starting bitcoind..."); // rpcauth for each bitcoind and save the pwd // let (rpc_auth, bitcoin_rpc_pwd) = generate_rpcauth("bitcoin", Some("bitcoin")); let (rpc_auth, bitcoin_rpc_pwd) = generate_rpcauth("bitcoin", None); @@ -174,10 +175,10 @@ impl TestEnv { bitcoin_config.args.push(&*auth_config); let bitcoind = if let Ok(path) = std::env::var("BITCOIND_EXEC") { - println!("Using custom bitcoind executable: {path}"); + tracing::info!("Using custom bitcoind executable: {path}"); Node::with_conf(&path, &bitcoin_config)? } else { - println!( + tracing::info!( "BITCOIND_EXEC not set! Falling back to downloaded version at {}", corepc_node::downloaded_exe_path()? ); @@ -189,17 +190,17 @@ impl TestEnv { // Try to get electrs executable (from environment or downloads) let electrs_exe = if let Ok(path) = std::env::var("ELECTRS_EXEC") { - println!("Using custom electrs executable: {path}"); + tracing::info!("Using custom electrs executable: {path}"); path } else { // Try to use downloaded electrs let path = electrsd::downloaded_exe_path() .expect("No downloaded electrs found, trying electrs in PATH..."); - println!("Using downloaded electrs: {path}"); + tracing::info!("Using downloaded electrs: {path}"); path }; - println!("Starting electrsd..."); + tracing::info!("Starting electrsd..."); let electrsd = ElectrsD::with_conf(electrs_exe, &bitcoind, &config.electrsd) .with_context(|| "Starting electrsd failed...")?; @@ -221,7 +222,7 @@ impl TestEnv { container_name: None, bitcoin_rpc_pwd }; - println!("Bitcoin regtest environment ready!"); + tracing::info!("Bitcoin regtest environment ready!"); Ok(test_env) } @@ -266,9 +267,14 @@ impl TestEnv { self.explorer_process = Some(child); self.container_name = Some(container_name); - eprintln!("Starting explorer in container, access it at http://127.0.0.1:{browser_port}/blocks"); - eprintln!("you can check the container logs with: "); - eprintln!("podman logs -f --timestamps {}", self.container_name.as_ref().unwrap()); + tracing::info!( + "Starting explorer in container, access it at http://127.0.0.1:{browser_port}/blocks" + ); + tracing::info!("you can check the container logs with: "); + tracing::info!( + "podman logs -f --timestamps {}", + self.container_name.as_ref().unwrap() + ); Ok(()) } @@ -457,16 +463,16 @@ impl TestEnv { impl Drop for TestEnv { fn drop(&mut self) { if let Some(name) = self.container_name.take() { - eprintln!("Stopping explorer container {name}..."); + tracing::info!("Stopping explorer container {name}..."); let output = std::process::Command::new("podman") .args(["stop", &name]) .output(); - eprintln!("explorer container returned {output:?}..."); + tracing::info!("explorer container returned {output:?}..."); } // Try graceful shutdown first (SIGTERM) if let Some(mut child) = self.explorer_process.take() { - eprintln!("Shutting down explorer process..."); + tracing::info!("Shutting down explorer process..."); // Send SIGTERM (graceful) let _ = child.kill(); @@ -478,6 +484,7 @@ impl Drop for TestEnv { #[cfg(test)] mod tests { use bdk_bitcoind_rpc::bitcoincore_rpc::RpcApi as _; + use bmp_tracing::tracing; use super::*; @@ -523,18 +530,18 @@ mod tests { // Create new address let address = env.new_address()?; - println!("Created address: {address}"); + tracing::info!("Created address: {address}"); // Address is already verified to be on regtest network when created via new_address() // Get initial balance let initial_balance = env.bitcoind.client.get_balance()?; - println!("Initial balance: {initial_balance:?} BTC"); + tracing::info!("Initial balance: {initial_balance:?} BTC"); // Fund address with 1000 satoshis let amount = Amount::from_sat(1000); let txid = env.fund_address(&address, amount)?; - println!("Funded address with txid: {txid}"); + tracing::info!("Funded address with txid: {txid}"); // Verify the transaction was created assert_ne!( @@ -550,7 +557,7 @@ mod tests { // Wait for the transaction to appear in electrum env.wait_for_tx(txid)?; - println!("Transaction confirmed in electrum"); + tracing::info!("Transaction confirmed in electrum"); // Verify we can get the transaction from bitcoind let tx = env.bitcoind.client.get_transaction(txid)?; @@ -565,7 +572,7 @@ mod tests { .unwrap(); assert_eq!(receive_amount, amount); - println!("Transaction amount verified: {receive_amount}"); + tracing::info!("Transaction amount verified: {receive_amount}"); Ok(()) } From 1204eb479b82e2a01732d3ada0dc4d31083b69d0 Mon Sep 17 00:00:00 2001 From: Sonkeng Maldini Date: Tue, 24 Feb 2026 21:25:47 +0100 Subject: [PATCH 4/5] turn log off on CI --- .github/workflows/cont_integration.yml | 4 ++-- rpc/src/bin/musig-cli.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/cont_integration.yml b/.github/workflows/cont_integration.yml index a9592c8..01f154d 100644 --- a/.github/workflows/cont_integration.yml +++ b/.github/workflows/cont_integration.yml @@ -65,7 +65,7 @@ jobs: run: cargo clippy --all-targets - name: Unit and Integration tests - run: cargo test + run: RUST_LOG=off cargo test protocol: name: Build and test protocol @@ -107,5 +107,5 @@ jobs: run: cargo clippy --all-targets - name: Unit and Integration tests - run: cargo test + run: RUST_LOG=off cargo test diff --git a/rpc/src/bin/musig-cli.rs b/rpc/src/bin/musig-cli.rs index 767ae42..6670666 100644 --- a/rpc/src/bin/musig-cli.rs +++ b/rpc/src/bin/musig-cli.rs @@ -42,17 +42,17 @@ async fn main() -> Result<(), Box> { Commands::WalletBalance => { let response = client.wallet_balance(Request::new(WalletBalanceRequest {})).await?; drop(client); - tracing::info!("{}", serde_json::to_string_pretty(&response.into_inner())?); + println!("{}", serde_json::to_string_pretty(&response.into_inner())?); } Commands::NewAddress => { let response = client.new_address(Request::new(NewAddressRequest {})).await?; drop(client); - tracing::info!("{}", serde_json::to_string_pretty(&response.into_inner())?); + println!("{}", serde_json::to_string_pretty(&response.into_inner())?); } Commands::ListUnspent => { let response = client.list_unspent(Request::new(ListUnspentRequest {})).await?; drop(client); - tracing::info!("{}", serde_json::to_string_pretty(&response.into_inner())?); + println!("{}", serde_json::to_string_pretty(&response.into_inner())?); } Commands::NotifyConfidence { tx_id } => { let tx_id = tx_id.parse::()?.to_byte_array().into(); @@ -60,7 +60,7 @@ async fn main() -> Result<(), Box> { drop(client); let mut stream = response.into_inner(); while let Some(event_result) = stream.next().await { - tracing::info!("{}", serde_json::to_string_pretty(&event_result?)?); + println!("{}", serde_json::to_string_pretty(&event_result?)?); } } } From 6935bdadfff1ffa2d4a744fc80bf83c8962fbcec Mon Sep 17 00:00:00 2001 From: Sonkeng Maldini Date: Wed, 25 Feb 2026 10:02:45 +0100 Subject: [PATCH 5/5] only use bmp_tracing on bin and test crates --- Cargo.lock | 2 ++ protocol/Cargo.toml | 3 ++- protocol/src/protocol_musig_adaptor.rs | 1 - rpc/src/bmp_service.rs | 2 +- rpc/src/bmp_wallet_service.rs | 2 +- rpc/src/observable.rs | 2 +- rpc/src/wallet.rs | 4 ++-- wallet/Cargo.toml | 3 ++- wallet/src/bmp_wallet.rs | 1 - wallet/src/utils.rs | 1 - 10 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5883dde..2ab2743 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1820,6 +1820,7 @@ dependencies = [ "testenv", "thiserror", "tokio", + "tracing", ] [[package]] @@ -2824,6 +2825,7 @@ dependencies = [ "simple-semaphore", "tempfile", "testenv", + "tracing", "zeroize", ] diff --git a/protocol/Cargo.toml b/protocol/Cargo.toml index c4995b6..951465e 100644 --- a/protocol/Cargo.toml +++ b/protocol/Cargo.toml @@ -15,12 +15,13 @@ rand_chacha = { workspace = true } thiserror = { workspace = true } # TODO move this to dev-dependencies: testenv = { path = "../testenv" } -bmp_tracing = { workspace = true } +tracing = { workspace = true } [dev-dependencies] bdk_wallet = { workspace = true, features = ["test-utils"] } const_format = { workspace = true } tokio = { workspace = true, features = ["macros", "test-util"] } +bmp_tracing = { workspace = true } [lints] workspace = true diff --git a/protocol/src/protocol_musig_adaptor.rs b/protocol/src/protocol_musig_adaptor.rs index e24c12b..b40e63c 100644 --- a/protocol/src/protocol_musig_adaptor.rs +++ b/protocol/src/protocol_musig_adaptor.rs @@ -10,7 +10,6 @@ use bdk_wallet::bitcoin::{ }; use bdk_wallet::template::{Bip86, DescriptorTemplate as _}; use bdk_wallet::{AddressInfo, KeychainKind, SignOptions, Wallet}; -use bmp_tracing::tracing; use musig2::secp::{MaybeScalar, Point}; use musig2::{PartialSignature, PubNonce}; use rand::RngCore as _; diff --git a/rpc/src/bmp_service.rs b/rpc/src/bmp_service.rs index 94697a0..e5815c7 100644 --- a/rpc/src/bmp_service.rs +++ b/rpc/src/bmp_service.rs @@ -2,13 +2,13 @@ use std::collections::HashMap; use std::sync::Mutex; use bdk_wallet::bitcoin::Amount; -use bmp_tracing::tracing::info; use protocol::protocol_musig_adaptor::{ BMPContext, BMPProtocol, MemWallet, ProtocolRole, Round1Parameter, }; use protocol::wallet_service::WalletService; use testenv::TestEnv; use tonic::{Request, Response, Result, Status}; +use tracing::info; use crate::pb::bmp_protocol::bmp_protocol_service_server::BmpProtocolService; use crate::pb::bmp_protocol::{self, InitializeRequest, InitializeResponse, Role}; diff --git a/rpc/src/bmp_wallet_service.rs b/rpc/src/bmp_wallet_service.rs index feb73a1..22d479e 100644 --- a/rpc/src/bmp_wallet_service.rs +++ b/rpc/src/bmp_wallet_service.rs @@ -1,5 +1,5 @@ -use bmp_tracing::tracing::info; use tonic::{Request, Response, Result}; +use tracing::info; use crate::pb::bmp_wallet; use crate::pb::bmp_wallet::wallet_server::Wallet; diff --git a/rpc/src/observable.rs b/rpc/src/observable.rs index 3e16b29..bae47b6 100644 --- a/rpc/src/observable.rs +++ b/rpc/src/observable.rs @@ -4,10 +4,10 @@ use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::hash::Hash; -use bmp_tracing::tracing::trace; use futures_util::Stream; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; +use tracing::trace; #[derive(Debug, Default)] pub struct Observable { diff --git a/rpc/src/wallet.rs b/rpc/src/wallet.rs index 80ff945..6e65733 100644 --- a/rpc/src/wallet.rs +++ b/rpc/src/wallet.rs @@ -5,18 +5,18 @@ use std::sync::{Arc, Mutex, RwLock}; -use bdk_bitcoind_rpc::bitcoincore_rpc::{Client, RpcApi as _}; use bdk_bitcoind_rpc::Emitter; +use bdk_bitcoind_rpc::bitcoincore_rpc::{Client, RpcApi as _}; use bdk_wallet::bitcoin::{Network, Transaction, Txid}; use bdk_wallet::chain::{ChainPosition, CheckPoint, ConfirmationBlockTime}; use bdk_wallet::{AddressInfo, Balance, KeychainKind, LocalOutput, Wallet}; -use bmp_tracing::tracing::{debug, error, info, trace}; use drop_stream::DropStreamExt as _; use futures_util::never::Never; use futures_util::stream::{BoxStream, StreamExt as _}; use thiserror::Error; use tokio::task::{self, JoinHandle}; use tokio::time::{self, Duration, MissedTickBehavior}; +use tracing::{debug, error, info, trace}; use crate::observable::ObservableHashMap; diff --git a/wallet/Cargo.toml b/wallet/Cargo.toml index 359c5a2..c15928b 100644 --- a/wallet/Cargo.toml +++ b/wallet/Cargo.toml @@ -14,11 +14,12 @@ hex = { workspace = true } rand = { workspace = true } rusqlite = { workspace = true } secp = { workspace = true } -bmp_tracing = { workspace = true } +tracing = { workspace = true } zeroize = { workspace = true } [dev-dependencies] bdk_wallet = { workspace = true, features = ["test-utils"] } +bmp_tracing = { workspace = true } simple-semaphore = { workspace = true } tempfile = { workspace = true } testenv = { path = "../testenv"} diff --git a/wallet/src/bmp_wallet.rs b/wallet/src/bmp_wallet.rs index e8f57d3..e1bc9d9 100644 --- a/wallet/src/bmp_wallet.rs +++ b/wallet/src/bmp_wallet.rs @@ -21,7 +21,6 @@ use bdk_wallet::{ AddressInfo, Balance, ChangeSet, KeychainKind, PersistedWallet, SignOptions, TxBuilder, TxOrdering, Utxo, Wallet, WalletPersister, WeightedUtxo, }; -use bmp_tracing::tracing; use rand::RngCore as _; use secp::Scalar; diff --git a/wallet/src/utils.rs b/wallet/src/utils.rs index 519a07e..a768106 100644 --- a/wallet/src/utils.rs +++ b/wallet/src/utils.rs @@ -5,7 +5,6 @@ use base64::engine::general_purpose; use base64::Engine as _; use bdk_kyoto::bip157::tokio; use bdk_kyoto::{Info, Receiver, UnboundedReceiver, Warning}; -use bmp_tracing::tracing; use zeroize::Zeroize as _; /// Derives a 256-bit key from a password and salt using Argon2.