Skip to content

Commit 1a9ef40

Browse files
authored
Merge pull request #91 from ariard/logging_interface
Logging interface
2 parents 587f2b3 + 0029f04 commit 1a9ef40

16 files changed

+362
-32
lines changed

Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ build = "build.rs"
1515
# Supports tracking channels with a non-bitcoin chain hashes. Currently enables all kinds of fun DoS attacks.
1616
non_bitcoin_chain_hash_routing = []
1717
fuzztarget = ["secp256k1/fuzztarget", "bitcoin/fuzztarget"]
18+
# Unlog messages superior at targeted level.
19+
max_level_off = []
20+
max_level_error = []
21+
max_level_warn = []
22+
max_level_info = []
23+
max_level_debug = []
1824

1925
[dependencies]
2026
bitcoin = "0.13"

fuzz/fuzz_targets/channel_target.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,17 @@ use lightning::ln::msgs::{MsgDecodable, ErrorAction};
1414
use lightning::chain::chaininterface::{FeeEstimator, ConfirmationTarget};
1515
use lightning::chain::transaction::OutPoint;
1616
use lightning::util::reset_rng_state;
17+
use lightning::util::logger::Logger;
18+
19+
mod utils;
20+
21+
use utils::test_logger;
1722

1823
use secp256k1::key::{PublicKey, SecretKey};
1924
use secp256k1::Secp256k1;
2025

2126
use std::sync::atomic::{AtomicUsize,Ordering};
27+
use std::sync::Arc;
2228

2329
#[inline]
2430
pub fn slice_to_be16(v: &[u8]) -> u16 {
@@ -101,6 +107,8 @@ pub fn do_test(data: &[u8]) {
101107
input: &input,
102108
};
103109

110+
let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new());
111+
104112
macro_rules! get_slice {
105113
($len: expr) => {
106114
match input.get_slice($len as usize) {
@@ -191,7 +199,7 @@ pub fn do_test(data: &[u8]) {
191199
let mut channel = if get_slice!(1)[0] != 0 {
192200
let chan_value = slice_to_be24(get_slice!(3));
193201

194-
let mut chan = Channel::new_outbound(&fee_est, chan_keys!(), their_pubkey, chan_value, get_slice!(1)[0] == 0, slice_to_be64(get_slice!(8)));
202+
let mut chan = Channel::new_outbound(&fee_est, chan_keys!(), their_pubkey, chan_value, get_slice!(1)[0] == 0, slice_to_be64(get_slice!(8)), Arc::clone(&logger));
195203
chan.get_open_channel(Sha256dHash::from(get_slice!(32)), &fee_est).unwrap();
196204
let accept_chan = if get_slice!(1)[0] == 0 {
197205
decode_msg_with_len16!(msgs::AcceptChannel, 270, 1)
@@ -213,7 +221,7 @@ pub fn do_test(data: &[u8]) {
213221
} else {
214222
decode_msg!(msgs::OpenChannel, 2*32+6*8+4+2*2+6*33+1)
215223
};
216-
let mut chan = match Channel::new_from_req(&fee_est, chan_keys!(), their_pubkey, &open_chan, slice_to_be64(get_slice!(8)), false, get_slice!(1)[0] == 0) {
224+
let mut chan = match Channel::new_from_req(&fee_est, chan_keys!(), their_pubkey, &open_chan, slice_to_be64(get_slice!(8)), false, get_slice!(1)[0] == 0, Arc::clone(&logger)) {
217225
Ok(chan) => chan,
218226
Err(_) => return,
219227
};

fuzz/fuzz_targets/full_stack_target.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
2121
use lightning::ln::router::Router;
2222
use lightning::util::events::{EventsProvider,Event};
2323
use lightning::util::reset_rng_state;
24+
use lightning::util::logger::Logger;
25+
26+
mod utils;
27+
28+
use utils::test_logger;
2429

2530
use secp256k1::key::{PublicKey,SecretKey};
2631
use secp256k1::Secp256k1;
@@ -169,18 +174,19 @@ pub fn do_test(data: &[u8]) {
169174
Err(_) => return,
170175
};
171176

177+
let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new());
172178
let monitor = Arc::new(TestChannelMonitor{});
173-
let watch = Arc::new(ChainWatchInterfaceUtil::new());
179+
let watch = Arc::new(ChainWatchInterfaceUtil::new(Arc::clone(&logger)));
174180
let broadcast = Arc::new(TestBroadcaster{});
175181

176-
let channelmanager = ChannelManager::new(our_network_key, slice_to_be32(get_slice!(4)), get_slice!(1)[0] != 0, Network::Bitcoin, fee_est.clone(), monitor.clone(), watch.clone(), broadcast.clone()).unwrap();
177-
let router = Arc::new(Router::new(PublicKey::from_secret_key(&secp_ctx, &our_network_key).unwrap()));
182+
let channelmanager = ChannelManager::new(our_network_key, slice_to_be32(get_slice!(4)), get_slice!(1)[0] != 0, Network::Bitcoin, fee_est.clone(), monitor.clone(), watch.clone(), broadcast.clone(), Arc::clone(&logger)).unwrap();
183+
let router = Arc::new(Router::new(PublicKey::from_secret_key(&secp_ctx, &our_network_key).unwrap(), Arc::clone(&logger)));
178184

179185
let peers = RefCell::new([false; 256]);
180186
let handler = PeerManager::new(MessageHandler {
181187
chan_handler: channelmanager.clone(),
182188
route_handler: router.clone(),
183-
}, our_network_key);
189+
}, our_network_key, Arc::clone(&logger));
184190

185191
let mut should_forward = false;
186192
let mut payments_received = Vec::new();

fuzz/fuzz_targets/router_target.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,17 @@ use lightning::ln::msgs;
77
use lightning::ln::msgs::{MsgDecodable, RoutingMessageHandler};
88
use lightning::ln::router::{Router, RouteHint};
99
use lightning::util::reset_rng_state;
10+
use lightning::util::logger::Logger;
1011

1112
use secp256k1::key::PublicKey;
1213
use secp256k1::Secp256k1;
1314

15+
mod utils;
16+
17+
use utils::test_logger;
18+
19+
use std::sync::Arc;
20+
1421
#[inline]
1522
pub fn slice_to_be16(v: &[u8]) -> u16 {
1623
((v[0] as u16) << 8*1) |
@@ -98,8 +105,10 @@ pub fn do_test(data: &[u8]) {
98105
}
99106
}
100107

108+
let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new());
109+
101110
let our_pubkey = get_pubkey!();
102-
let router = Router::new(our_pubkey.clone());
111+
let router = Router::new(our_pubkey.clone(), Arc::clone(&logger));
103112

104113
loop {
105114
match get_slice!(1)[0] {

fuzz/fuzz_targets/utils/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pub(crate) mod test_logger;
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use lightning::util::logger::{Logger, Level, Record};
2+
3+
pub struct TestLogger {
4+
level: Level,
5+
}
6+
7+
impl TestLogger {
8+
pub fn new() -> TestLogger {
9+
TestLogger {
10+
level: Level::Off,
11+
}
12+
}
13+
pub fn enable(&mut self, level: Level) {
14+
self.level = level;
15+
}
16+
}
17+
18+
impl Logger for TestLogger {
19+
fn log(&self, record: &Record) {
20+
#[cfg(any(test, not(feature = "fuzztarget")))]
21+
println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args);
22+
}
23+
}

src/chain/chaininterface.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ use bitcoin::blockdata::block::{Block, BlockHeader};
22
use bitcoin::blockdata::transaction::Transaction;
33
use bitcoin::blockdata::script::Script;
44
use bitcoin::util::hash::Sha256dHash;
5-
use std::sync::{Mutex,Weak,MutexGuard};
5+
use util::logger::Logger;
6+
use std::sync::{Mutex,Weak,MutexGuard,Arc};
67
use std::sync::atomic::{AtomicUsize, Ordering};
78

89
/// An interface to request notification of certain scripts as they appear the
@@ -70,7 +71,8 @@ pub trait FeeEstimator: Sync + Send {
7071
pub struct ChainWatchInterfaceUtil {
7172
watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
7273
listeners: Mutex<Vec<Weak<ChainListener>>>,
73-
reentered: AtomicUsize
74+
reentered: AtomicUsize,
75+
logger: Arc<Logger>,
7476
}
7577

7678
/// Register listener
@@ -100,11 +102,12 @@ impl ChainWatchInterface for ChainWatchInterfaceUtil {
100102
}
101103

102104
impl ChainWatchInterfaceUtil {
103-
pub fn new() -> ChainWatchInterfaceUtil {
105+
pub fn new(logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
104106
ChainWatchInterfaceUtil {
105107
watched: Mutex::new((Vec::new(), Vec::new(), false)),
106108
listeners: Mutex::new(Vec::new()),
107-
reentered: AtomicUsize::new(1)
109+
reentered: AtomicUsize::new(1),
110+
logger: logger,
108111
}
109112
}
110113

src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ extern crate rand;
66
extern crate secp256k1;
77
#[cfg(test)] extern crate hex;
88

9+
#[macro_use]
10+
pub mod util;
911
pub mod chain;
1012
pub mod ln;
11-
pub mod util;

src/ln/channel.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,13 @@ use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
2323
use chain::transaction::OutPoint;
2424
use util::{transaction_utils,rng};
2525
use util::sha2::Sha256;
26+
use util::logger::{Logger, Record};
2627

2728
use std;
2829
use std::default::Default;
2930
use std::{cmp,mem};
3031
use std::time::Instant;
32+
use std::sync::{Arc};
3133

3234
pub struct ChannelKeys {
3335
pub funding_key: SecretKey,
@@ -303,6 +305,8 @@ pub struct Channel {
303305
their_shutdown_scriptpubkey: Option<Script>,
304306

305307
channel_monitor: ChannelMonitor,
308+
309+
logger: Arc<Logger>,
306310
}
307311

308312
const OUR_MAX_HTLCS: u16 = 5; //TODO
@@ -361,7 +365,7 @@ impl Channel {
361365
// Constructors:
362366

363367
/// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`
364-
pub fn new_outbound(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, channel_value_satoshis: u64, announce_publicly: bool, user_id: u64) -> Channel {
368+
pub fn new_outbound(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, channel_value_satoshis: u64, announce_publicly: bool, user_id: u64, logger: Arc<Logger>) -> Channel {
365369
if channel_value_satoshis >= MAX_FUNDING_SATOSHIS {
366370
panic!("funding value > 2^24");
367371
}
@@ -429,6 +433,8 @@ impl Channel {
429433
their_shutdown_scriptpubkey: None,
430434

431435
channel_monitor: channel_monitor,
436+
437+
logger,
432438
}
433439
}
434440

@@ -446,7 +452,7 @@ impl Channel {
446452
/// Assumes chain_hash has already been checked and corresponds with what we expect!
447453
/// Generally prefers to take the DisconnectPeer action on failure, as a notice to the sender
448454
/// that we're rejecting the new channel.
449-
pub fn new_from_req(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, msg: &msgs::OpenChannel, user_id: u64, require_announce: bool, allow_announce: bool) -> Result<Channel, HandleError> {
455+
pub fn new_from_req(fee_estimator: &FeeEstimator, chan_keys: ChannelKeys, their_node_id: PublicKey, msg: &msgs::OpenChannel, user_id: u64, require_announce: bool, allow_announce: bool, logger: Arc<Logger>) -> Result<Channel, HandleError> {
450456
// Check sanity of message fields:
451457
if msg.funding_satoshis >= MAX_FUNDING_SATOSHIS {
452458
return Err(HandleError{err: "funding value > 2^24", action: Some(msgs::ErrorAction::DisconnectPeer{ msg: None })});
@@ -548,6 +554,8 @@ impl Channel {
548554
their_shutdown_scriptpubkey: None,
549555

550556
channel_monitor: channel_monitor,
557+
558+
logger,
551559
};
552560

553561
let obscure_factor = chan.get_commitment_transaction_number_obscure_factor();
@@ -1748,7 +1756,7 @@ impl Channel {
17481756

17491757
match self.secp_ctx.verify(&sighash, &msg.signature, &self.their_funding_pubkey) {
17501758
Ok(_) => {},
1751-
Err(_) => {
1759+
Err(_e) => {
17521760
// The remote end may have decided to revoke their output due to inconsistent dust
17531761
// limits, so check for that case by re-checking the signature here.
17541762
closing_tx = self.build_closing_transaction(msg.fee_satoshis, true).0;
@@ -2111,6 +2119,7 @@ impl Channel {
21112119
let (our_signature, commitment_tx) = match self.get_outbound_funding_created_signature() {
21122120
Ok(res) => res,
21132121
Err(e) => {
2122+
log_error!(self, "Got bad signatures: {}!", e.err);
21142123
self.channel_monitor.unset_funding_info();
21152124
return Err(e);
21162125
}
@@ -2409,10 +2418,13 @@ mod tests {
24092418
use ln::chan_utils;
24102419
use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
24112420
use chain::transaction::OutPoint;
2421+
use util::test_utils;
2422+
use util::logger::Logger;
24122423
use secp256k1::{Secp256k1,Message,Signature};
24132424
use secp256k1::key::{SecretKey,PublicKey};
24142425
use crypto::sha2::Sha256;
24152426
use crypto::digest::Digest;
2427+
use std::sync::Arc;
24162428

24172429
struct TestFeeEstimator {
24182430
fee_est: u64
@@ -2433,6 +2445,7 @@ mod tests {
24332445
fn outbound_commitment_test() {
24342446
// Test vectors from BOLT 3 Appendix C:
24352447
let feeest = TestFeeEstimator{fee_est: 15000};
2448+
let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
24362449
let secp_ctx = Secp256k1::new();
24372450

24382451
let chan_keys = ChannelKeys {
@@ -2450,7 +2463,7 @@ mod tests {
24502463
assert_eq!(PublicKey::from_secret_key(&secp_ctx, &chan_keys.funding_key).unwrap().serialize()[..],
24512464
hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]);
24522465

2453-
let mut chan = Channel::new_outbound(&feeest, chan_keys, PublicKey::new(), 10000000, false, 42); // Nothing uses their network key in this test
2466+
let mut chan = Channel::new_outbound(&feeest, chan_keys, PublicKey::new(), 10000000, false, 42, Arc::clone(&logger)); // Nothing uses their network key in this test
24542467
chan.their_to_self_delay = 144;
24552468
chan.our_dust_limit_satoshis = 546;
24562469

0 commit comments

Comments
 (0)