Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/cont_integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ jobs:
run: cargo clippy --all-targets

- name: Unit and Integration tests
run: cargo test
run: RUST_LOG=off cargo test
Comment thread
sdmg15 marked this conversation as resolved.

protocol:
name: Build and test protocol
Expand Down Expand Up @@ -107,5 +107,5 @@ jobs:
run: cargo clippy --all-targets

- name: Unit and Integration tests
run: cargo test
run: RUST_LOG=off cargo test

18 changes: 14 additions & 4 deletions Cargo.lock

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

6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["protocol", "rpc", "wallet", "testenv"]
members = ["protocol", "rpc", "wallet", "testenv", "bmp_tracing"]
exclude = ["poc"]

[workspace.dependencies]
Expand All @@ -24,7 +24,9 @@ tempfile = "3.25.0"
thiserror = "2.0.18"
tokio = "1.49.0"
tracing = "0.1.44"
tracing-subscriber = "0.3.22"
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"

[workspace.lints.rust]
Expand Down
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions bmp_tracing/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "bmp_tracing"
version = "0.1.0"
edition = "2024"

[dependencies]
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
tracing-core = { workspace = true }

[lints]
workspace = true
79 changes: 79 additions & 0 deletions bmp_tracing/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
pub use tracing;
pub use tracing_subscriber;

use std::error::Error as _;
use std::fs::File;
use std::io;
use std::path::PathBuf;

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<S>(self) -> Box<dyn Layer<S> + 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(false)
.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::<tracing_subscriber::filter::ParseError>()) {
eprintln!("Could not parse `RUST_LOG` environment variable: {e}");
}
EnvFilter::new(default_level)
});

// Build and init the subscriber
tracing_subscriber::registry()
.with(filter)
.with(config.layer())
.init();
}
2 changes: 2 additions & 0 deletions protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ rand_chacha = { workspace = true }
thiserror = { workspace = true }
# TODO move this to dev-dependencies:
testenv = { path = "../testenv" }
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
21 changes: 15 additions & 6 deletions protocol/src/protocol_musig_adaptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,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)
Expand Down Expand Up @@ -122,7 +124,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)?;
Expand Down Expand Up @@ -297,11 +299,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<Round2Parameter> {
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);
Expand Down Expand Up @@ -749,7 +758,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.
Expand Down
5 changes: 3 additions & 2 deletions protocol/tests/protocol_integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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);

Expand Down Expand Up @@ -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(())
}
Expand Down
2 changes: 1 addition & 1 deletion rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"}

Expand Down
5 changes: 4 additions & 1 deletion rpc/src/bin/musigd.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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)]
Expand All @@ -24,6 +24,9 @@ struct Cli {
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let cli: Cli = Cli::parse();

bmp_tracing::init("info");

let testenv = TestEnv::new()?;

let addr = format!("127.0.0.1:{}", cli.port).parse()?;
Expand Down
7 changes: 5 additions & 2 deletions rpc/src/wallet.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
#![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};

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};
Expand Down
4 changes: 2 additions & 2 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading
Loading