3 extern crate lightning;
4 extern crate secp256k1;
6 use bitcoin::blockdata::block::BlockHeader;
7 use bitcoin::blockdata::transaction::{Transaction, TxOut};
8 use bitcoin::blockdata::script::Script;
9 use bitcoin::network::constants::Network;
10 use bitcoin::network::serialize::{serialize, BitcoinHash};
11 use bitcoin::util::hash::Sha256dHash;
13 use crypto::digest::Digest;
15 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil};
16 use lightning::chain::transaction::OutPoint;
17 use lightning::ln::channelmonitor;
18 use lightning::ln::channelmanager::ChannelManager;
19 use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
20 use lightning::ln::router::Router;
21 use lightning::util::events::{EventsProvider,Event};
22 use lightning::util::reset_rng_state;
23 use lightning::util::logger::Logger;
24 use lightning::util::sha2::Sha256;
28 use utils::test_logger;
30 use secp256k1::key::{PublicKey,SecretKey};
31 use secp256k1::Secp256k1;
33 use std::cell::RefCell;
34 use std::collections::HashMap;
37 use std::sync::atomic::{AtomicUsize,Ordering};
40 pub fn slice_to_be16(v: &[u8]) -> u16 {
41 ((v[0] as u16) << 8*1) |
42 ((v[1] as u16) << 8*0)
46 pub fn slice_to_be24(v: &[u8]) -> u32 {
47 ((v[0] as u32) << 8*2) |
48 ((v[1] as u32) << 8*1) |
49 ((v[2] as u32) << 8*0)
53 pub fn slice_to_be32(v: &[u8]) -> u32 {
54 ((v[0] as u32) << 8*3) |
55 ((v[1] as u32) << 8*2) |
56 ((v[2] as u32) << 8*1) |
57 ((v[3] as u32) << 8*0)
61 pub fn be64_to_array(u: u64) -> [u8; 8] {
63 v[0] = ((u >> 8*7) & 0xff) as u8;
64 v[1] = ((u >> 8*6) & 0xff) as u8;
65 v[2] = ((u >> 8*5) & 0xff) as u8;
66 v[3] = ((u >> 8*4) & 0xff) as u8;
67 v[4] = ((u >> 8*3) & 0xff) as u8;
68 v[5] = ((u >> 8*2) & 0xff) as u8;
69 v[6] = ((u >> 8*1) & 0xff) as u8;
70 v[7] = ((u >> 8*0) & 0xff) as u8;
76 read_pos: AtomicUsize,
79 fn get_slice(&self, len: usize) -> Option<&[u8]> {
80 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
81 if self.data.len() < old_pos + len {
84 Some(&self.data[old_pos..old_pos + len])
88 struct FuzzEstimator {
89 input: Arc<InputData>,
91 impl FeeEstimator for FuzzEstimator {
92 fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u64 {
93 //TODO: We should actually be testing at least much more than 64k...
94 match self.input.get_slice(2) {
95 Some(slice) => slice_to_be16(slice) as u64 * 250,
101 struct TestChannelMonitor {}
102 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
103 fn add_update_monitor(&self, _funding_txo: OutPoint, _monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
109 struct TestBroadcaster {}
110 impl BroadcasterInterface for TestBroadcaster {
111 fn broadcast_transaction(&self, _tx: &Transaction) {}
117 peers_connected: &'a RefCell<[bool; 256]>,
119 impl<'a> SocketDescriptor for Peer<'a> {
120 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
121 assert!(write_offset < data.len());
122 data.len() - write_offset
124 fn disconnect_socket(&mut self) {
125 assert!(self.peers_connected.borrow()[self.id as usize]);
126 self.peers_connected.borrow_mut()[self.id as usize] = false;
129 impl<'a> PartialEq for Peer<'a> {
130 fn eq(&self, other: &Self) -> bool {
134 impl<'a> Eq for Peer<'a> {}
135 impl<'a> Hash for Peer<'a> {
136 fn hash<H : std::hash::Hasher>(&self, h: &mut H) {
142 pub fn do_test(data: &[u8]) {
145 let input = Arc::new(InputData {
147 read_pos: AtomicUsize::new(0),
149 let fee_est = Arc::new(FuzzEstimator {
150 input: input.clone(),
153 macro_rules! get_slice {
155 match input.get_slice($len as usize) {
156 Some(slice) => slice,
162 let secp_ctx = Secp256k1::new();
163 macro_rules! get_pubkey {
165 match PublicKey::from_slice(&secp_ctx, get_slice!(33)) {
172 let our_network_key = match SecretKey::from_slice(&secp_ctx, get_slice!(32)) {
177 let logger: Arc<Logger> = Arc::new(test_logger::TestLogger{});
178 let monitor = Arc::new(TestChannelMonitor{});
179 let watch = Arc::new(ChainWatchInterfaceUtil::new(Arc::clone(&logger)));
180 let broadcast = Arc::new(TestBroadcaster{});
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)));
185 let peers = RefCell::new([false; 256]);
186 let handler = PeerManager::new(MessageHandler {
187 chan_handler: channelmanager.clone(),
188 route_handler: router.clone(),
189 }, our_network_key, Arc::clone(&logger));
191 let mut should_forward = false;
192 let mut payments_received: Vec<[u8; 32]> = Vec::new();
193 let mut payments_sent = 0;
194 let mut pending_funding_generation: Vec<([u8; 32], u64, Script)> = Vec::new();
195 let mut pending_funding_signatures = HashMap::new();
196 let mut pending_funding_relay = Vec::new();
199 match get_slice!(1)[0] {
203 if !peers.borrow()[i-1] {
208 if new_id == 0 { return; }
209 peers.borrow_mut()[new_id - 1] = true;
210 handler.new_outbound_connection(get_pubkey!(), Peer{id: (new_id - 1) as u8, peers_connected: &peers}).unwrap();
215 if !peers.borrow()[i-1] {
220 if new_id == 0 { return; }
221 peers.borrow_mut()[new_id - 1] = true;
222 handler.new_inbound_connection(Peer{id: (new_id - 1) as u8, peers_connected: &peers}).unwrap();
225 let peer_id = get_slice!(1)[0];
226 if !peers.borrow()[peer_id as usize] { return; }
227 peers.borrow_mut()[peer_id as usize] = false;
228 handler.disconnect_event(&Peer{id: peer_id, peers_connected: &peers});
231 let peer_id = get_slice!(1)[0];
232 if !peers.borrow()[peer_id as usize] { return; }
233 match handler.read_event(&mut Peer{id: peer_id, peers_connected: &peers}, get_slice!(get_slice!(1)[0]).to_vec()) {
234 Ok(res) => assert!(!res),
235 Err(_) => { peers.borrow_mut()[peer_id as usize] = false; }
239 let value = slice_to_be24(get_slice!(3)) as u64;
240 let route = match router.get_route(&get_pubkey!(), None, &Vec::new(), value, 42) {
244 let mut payment_hash = [0; 32];
245 payment_hash[0..8].copy_from_slice(&be64_to_array(payments_sent));
246 let mut sha = Sha256::new();
247 sha.input(&payment_hash);
248 sha.result(&mut payment_hash);
250 match channelmanager.send_payment(route, payment_hash) {
256 let peer_id = get_slice!(1)[0];
257 if !peers.borrow()[peer_id as usize] { return; }
258 let their_key = get_pubkey!();
259 let chan_value = slice_to_be24(get_slice!(3)) as u64;
260 let push_msat_value = slice_to_be24(get_slice!(3)) as u64;
261 if channelmanager.create_channel(their_key, chan_value, push_msat_value, 0).is_err() { return; }
264 let mut channels = channelmanager.list_channels();
265 let channel_id = get_slice!(1)[0] as usize;
266 if channel_id >= channels.len() { return; }
267 channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) });
268 if channelmanager.close_channel(&channels[channel_id].channel_id).is_err() { return; }
272 channelmanager.process_pending_htlc_forwards();
273 handler.process_events();
274 should_forward = false;
278 for payment in payments_received.drain(..) {
279 // SHA256 is defined as XOR of all input bytes placed in the first byte, and 0s
280 // for the remaining bytes. Thus, if not all remaining bytes are 0s we cannot
281 // fulfill this HTLC, but if they are, we can just take the first byte and
282 // place that anywhere in our preimage.
283 if &payment[1..] != &[0; 31] {
284 channelmanager.fail_htlc_backwards(&payment);
286 let mut payment_preimage = [0; 32];
287 payment_preimage[0] = payment[0];
288 channelmanager.claim_funds(payment_preimage);
293 for payment in payments_received.drain(..) {
294 channelmanager.fail_htlc_backwards(&payment);
298 for funding_generation in pending_funding_generation.drain(..) {
299 let mut tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: vec![TxOut {
300 value: funding_generation.1, script_pubkey: funding_generation.2,
302 let funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
303 let mut found_duplicate_txo = false;
304 for chan in channelmanager.list_channels() {
305 if chan.channel_id == funding_output.to_channel_id() {
306 found_duplicate_txo = true;
309 if !found_duplicate_txo {
310 channelmanager.funding_transaction_generated(&funding_generation.0, funding_output.clone());
311 pending_funding_signatures.insert(funding_output, tx);
316 if !pending_funding_relay.is_empty() {
317 let mut txn = Vec::with_capacity(pending_funding_relay.len());
318 let mut txn_idxs = Vec::with_capacity(pending_funding_relay.len());
319 for (idx, tx) in pending_funding_relay.iter().enumerate() {
321 txn_idxs.push(idx as u32 + 1);
324 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
325 channelmanager.block_connected(&header, 1, &txn[..], &txn_idxs[..]);
329 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
330 channelmanager.block_connected(&header, i, &txn[..], &txn_idxs[..]);
333 pending_funding_relay.clear();
337 for event in handler.get_and_clear_pending_events() {
339 Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, output_script, .. } => {
340 pending_funding_generation.push((temporary_channel_id, channel_value_satoshis, output_script));
342 Event::FundingBroadcastSafe { funding_txo, .. } => {
343 pending_funding_relay.push(pending_funding_signatures.remove(&funding_txo).unwrap());
345 Event::PaymentReceived { payment_hash, .. } => {
346 payments_received.push(payment_hash);
348 Event::PaymentSent {..} => {},
349 Event::PaymentFailed {..} => {},
351 Event::PendingHTLCsForwardable {..} => {
352 should_forward = true;
354 _ => panic!("Unknown event"),
360 #[cfg(feature = "afl")]
362 #[cfg(feature = "afl")]
364 afl::read_stdio_bytes(|data| {
369 #[cfg(feature = "honggfuzz")]
370 #[macro_use] extern crate honggfuzz;
371 #[cfg(feature = "honggfuzz")]
384 fn duplicate_crash() {
385 super::do_test(&::hex::decode("00").unwrap());