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;
12 use bitcoin::util::uint::Uint256;
14 use crypto::sha2::Sha256;
15 use crypto::digest::Digest;
17 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil};
18 use lightning::chain::transaction::OutPoint;
19 use lightning::ln::channelmonitor;
20 use lightning::ln::channelmanager::ChannelManager;
21 use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
22 use lightning::ln::router::Router;
23 use lightning::util::events::{EventsProvider,Event};
24 use lightning::util::reset_rng_state;
26 use secp256k1::key::{PublicKey,SecretKey};
27 use secp256k1::Secp256k1;
29 use std::collections::HashMap;
31 use std::sync::atomic::{AtomicUsize,Ordering};
34 pub fn slice_to_be16(v: &[u8]) -> u16 {
35 ((v[0] as u16) << 8*1) |
36 ((v[1] as u16) << 8*0)
40 pub fn slice_to_be24(v: &[u8]) -> u32 {
41 ((v[0] as u32) << 8*2) |
42 ((v[1] as u32) << 8*1) |
43 ((v[2] as u32) << 8*0)
47 pub fn slice_to_be32(v: &[u8]) -> u32 {
48 ((v[0] as u32) << 8*3) |
49 ((v[1] as u32) << 8*2) |
50 ((v[2] as u32) << 8*1) |
51 ((v[3] as u32) << 8*0)
55 pub fn be64_to_array(u: u64) -> [u8; 8] {
57 v[0] = ((u >> 8*7) & 0xff) as u8;
58 v[1] = ((u >> 8*6) & 0xff) as u8;
59 v[2] = ((u >> 8*5) & 0xff) as u8;
60 v[3] = ((u >> 8*4) & 0xff) as u8;
61 v[4] = ((u >> 8*3) & 0xff) as u8;
62 v[5] = ((u >> 8*2) & 0xff) as u8;
63 v[6] = ((u >> 8*1) & 0xff) as u8;
64 v[7] = ((u >> 8*0) & 0xff) as u8;
70 read_pos: AtomicUsize,
73 fn get_slice(&self, len: usize) -> Option<&[u8]> {
74 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
75 if self.data.len() < old_pos + len {
78 Some(&self.data[old_pos..old_pos + len])
82 struct FuzzEstimator {
83 input: Arc<InputData>,
85 impl FeeEstimator for FuzzEstimator {
86 fn get_est_sat_per_vbyte(&self, _: ConfirmationTarget) -> u64 {
87 //TODO: We should actually be testing at least much more than 64k...
88 match self.input.get_slice(2) {
89 Some(slice) => slice_to_be16(slice) as u64,
95 struct TestChannelMonitor {}
96 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
97 fn add_update_monitor(&self, _funding_txo: OutPoint, _monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
103 struct TestBroadcaster {}
104 impl BroadcasterInterface for TestBroadcaster {
105 fn broadcast_transaction(&self, _tx: &Transaction) {}
108 #[derive(Clone, PartialEq, Eq, Hash)]
112 impl SocketDescriptor for Peer {
113 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
114 assert!(write_offset < data.len());
115 data.len() - write_offset
120 pub fn do_test(data: &[u8]) {
123 let input = Arc::new(InputData {
125 read_pos: AtomicUsize::new(0),
127 let fee_est = Arc::new(FuzzEstimator {
128 input: input.clone(),
131 macro_rules! get_slice {
133 match input.get_slice($len as usize) {
134 Some(slice) => slice,
140 let secp_ctx = Secp256k1::new();
141 macro_rules! get_pubkey {
143 match PublicKey::from_slice(&secp_ctx, get_slice!(33)) {
150 let our_network_key = match SecretKey::from_slice(&secp_ctx, get_slice!(32)) {
155 let monitor = Arc::new(TestChannelMonitor{});
156 let watch = Arc::new(ChainWatchInterfaceUtil::new());
157 let broadcast = Arc::new(TestBroadcaster{});
159 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();
160 let router = Arc::new(Router::new(PublicKey::from_secret_key(&secp_ctx, &our_network_key).unwrap()));
162 let handler = PeerManager::new(MessageHandler {
163 chan_handler: channelmanager.clone(),
164 route_handler: router.clone(),
167 let mut peers = [false; 256];
168 let mut should_forward = false;
169 let mut payments_received = Vec::new();
170 let mut payments_sent = 0;
171 let mut pending_funding_generation: Vec<(Uint256, u64, Script)> = Vec::new();
172 let mut pending_funding_signatures = HashMap::new();
173 let mut pending_funding_relay = Vec::new();
176 match get_slice!(1)[0] {
185 if new_id == 0 { return; }
186 peers[new_id - 1] = true;
187 handler.new_outbound_connection(get_pubkey!(), Peer{id: (new_id - 1) as u8}).unwrap();
197 if new_id == 0 { return; }
198 peers[new_id - 1] = true;
199 handler.new_inbound_connection(Peer{id: (new_id - 1) as u8}).unwrap();
202 let peer_id = get_slice!(1)[0];
203 if !peers[peer_id as usize] { return; }
204 peers[peer_id as usize] = false;
205 handler.disconnect_event(&Peer{id: peer_id});
208 let peer_id = get_slice!(1)[0];
209 if !peers[peer_id as usize] { return; }
210 match handler.read_event(&mut Peer{id: peer_id}, get_slice!(get_slice!(1)[0]).to_vec()) {
211 Ok(res) => assert!(!res),
212 Err(_) => { peers[peer_id as usize] = false; }
216 let value = slice_to_be24(get_slice!(3)) as u64;
217 let route = match router.get_route(&get_pubkey!(), &Vec::new(), value, 42) {
221 let mut payment_hash = [0; 32];
222 payment_hash[0..8].copy_from_slice(&be64_to_array(payments_sent));
223 let mut sha = Sha256::new();
224 sha.input(&payment_hash);
225 sha.result(&mut payment_hash);
226 for i in 1..32 { payment_hash[i] = 0; }
228 match channelmanager.send_payment(route, payment_hash) {
234 let peer_id = get_slice!(1)[0];
235 if !peers[peer_id as usize] { return; }
236 let their_key = get_pubkey!();
237 let chan_value = slice_to_be24(get_slice!(3)) as u64;
238 if channelmanager.create_channel(their_key, chan_value, 0).is_err() { return; }
241 let mut channels = channelmanager.list_channels();
242 let channel_id = get_slice!(1)[0] as usize;
243 if channel_id >= channels.len() { return; }
244 channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) });
245 if channelmanager.close_channel(&channels[channel_id].channel_id).is_err() { return; }
249 channelmanager.process_pending_htlc_forward();
250 handler.process_events();
251 should_forward = false;
255 for payment in payments_received.drain(..) {
256 let mut payment_preimage = None;
257 for i in 0..payments_sent {
258 let mut payment_hash = [0; 32];
259 payment_hash[0..8].copy_from_slice(&be64_to_array(i));
260 let mut sha = Sha256::new();
261 sha.input(&payment_hash);
262 sha.result(&mut payment_hash);
263 for i in 1..32 { payment_hash[i] = 0; }
264 if payment_hash == payment {
265 payment_hash = [0; 32];
266 payment_hash[0..8].copy_from_slice(&be64_to_array(i));
267 payment_preimage = Some(payment_hash);
271 channelmanager.claim_funds(payment_preimage.unwrap());
275 for payment in payments_received.drain(..) {
276 channelmanager.fail_htlc_backwards(&payment);
280 for funding_generation in pending_funding_generation.drain(..) {
281 let mut tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: vec![TxOut {
282 value: funding_generation.1, script_pubkey: funding_generation.2,
284 let funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
285 channelmanager.funding_transaction_generated(&funding_generation.0, funding_output.clone());
286 pending_funding_signatures.insert(funding_output, tx);
290 if !pending_funding_relay.is_empty() {
291 let mut txn = Vec::with_capacity(pending_funding_relay.len());
292 let mut txn_idxs = Vec::with_capacity(pending_funding_relay.len());
293 for (idx, tx) in pending_funding_relay.iter().enumerate() {
295 txn_idxs.push(idx as u32 + 1);
298 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
299 channelmanager.block_connected(&header, 1, &txn[..], &txn_idxs[..]);
303 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
304 channelmanager.block_connected(&header, i, &txn[..], &txn_idxs[..]);
307 pending_funding_relay.clear();
311 for event in handler.get_and_clear_pending_events() {
313 Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, output_script, .. } => {
314 pending_funding_generation.push((temporary_channel_id, channel_value_satoshis, output_script));
316 Event::FundingBroadcastSafe { funding_txo, .. } => {
317 pending_funding_relay.push(pending_funding_signatures.remove(&funding_txo).unwrap());
319 Event::PaymentReceived { payment_hash, .. } => {
320 payments_received.push(payment_hash);
322 Event::PaymentSent {..} => {},
323 Event::PaymentFailed {..} => {},
325 Event::PendingHTLCsForwardable {..} => {
326 should_forward = true;
328 _ => panic!("Unknown event"),
334 #[cfg(feature = "afl")]
336 #[cfg(feature = "afl")]
338 afl::read_stdio_bytes(|data| {
343 #[cfg(feature = "honggfuzz")]
344 #[macro_use] extern crate honggfuzz;
345 #[cfg(feature = "honggfuzz")]
356 fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {
358 for (idx, c) in hex.as_bytes().iter().enumerate() {
361 b'A'...b'F' => b |= c - b'A' + 10,
362 b'a'...b'f' => b |= c - b'a' + 10,
363 b'0'...b'9' => b |= c - b'0',
364 _ => panic!("Bad hex"),
374 fn duplicate_crash() {
375 let mut a = Vec::new();
376 extend_vec_from_hex("00", &mut a);