2 extern crate bitcoin_hashes;
3 extern crate lightning;
4 extern crate secp256k1;
6 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
7 use bitcoin::blockdata::script::{Script, Builder};
8 use bitcoin::blockdata::block::Block;
9 use bitcoin::blockdata::transaction::Transaction;
11 use lightning::chain::chaininterface::{ChainError,ChainWatchInterface};
12 use lightning::ln::channelmanager::ChannelDetails;
13 use lightning::ln::msgs;
14 use lightning::ln::msgs::{RoutingMessageHandler};
15 use lightning::ln::router::{Router, RouteHint};
16 use lightning::util::logger::Logger;
17 use lightning::util::ser::Readable;
19 use secp256k1::key::PublicKey;
23 use utils::test_logger;
26 use std::sync::atomic::{AtomicUsize, Ordering};
29 pub fn slice_to_be16(v: &[u8]) -> u16 {
30 ((v[0] as u16) << 8*1) |
31 ((v[1] as u16) << 8*0)
35 pub fn slice_to_be32(v: &[u8]) -> u32 {
36 ((v[0] as u32) << 8*3) |
37 ((v[1] as u32) << 8*2) |
38 ((v[2] as u32) << 8*1) |
39 ((v[3] as u32) << 8*0)
43 pub fn slice_to_be64(v: &[u8]) -> u64 {
44 ((v[0] as u64) << 8*7) |
45 ((v[1] as u64) << 8*6) |
46 ((v[2] as u64) << 8*5) |
47 ((v[3] as u64) << 8*4) |
48 ((v[4] as u64) << 8*3) |
49 ((v[5] as u64) << 8*2) |
50 ((v[6] as u64) << 8*1) |
51 ((v[7] as u64) << 8*0)
57 read_pos: AtomicUsize,
60 fn get_slice(&self, len: usize) -> Option<&[u8]> {
61 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
62 if self.data.len() < old_pos + len {
65 Some(&self.data[old_pos..old_pos + len])
67 fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
68 let old_pos = self.read_pos.load(Ordering::Acquire);
69 if self.data.len() < old_pos + len {
72 Some(&self.data[old_pos..old_pos + len])
76 struct DummyChainWatcher {
77 input: Arc<InputData>,
80 impl ChainWatchInterface for DummyChainWatcher {
81 fn install_watch_tx(&self, _txid: &Sha256dHash, _script_pub_key: &Script) { }
82 fn install_watch_outpoint(&self, _outpoint: (Sha256dHash, u32), _out_script: &Script) { }
83 fn watch_all_txn(&self) { }
84 fn filter_block<'a>(&self, _block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
85 (Vec::new(), Vec::new())
87 fn reentered(&self) -> usize { 0 }
89 fn get_chain_utxo(&self, _genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
90 match self.input.get_slice(2) {
91 Some(&[0, _]) => Err(ChainError::NotSupported),
92 Some(&[1, _]) => Err(ChainError::NotWatched),
93 Some(&[2, _]) => Err(ChainError::UnknownTx),
94 Some(&[_, x]) => Ok((Builder::new().push_int(x as i64).into_script().to_v0_p2wsh(), 0)),
95 None => Err(ChainError::UnknownTx),
102 pub fn do_test(data: &[u8]) {
103 let input = Arc::new(InputData {
105 read_pos: AtomicUsize::new(0),
107 macro_rules! get_slice_nonadvancing {
109 match input.get_slice_nonadvancing($len as usize) {
110 Some(slice) => slice,
115 macro_rules! get_slice {
117 match input.get_slice($len as usize) {
118 Some(slice) => slice,
124 macro_rules! decode_msg {
125 ($MsgType: path, $len: expr) => {{
126 let mut reader = ::std::io::Cursor::new(get_slice!($len));
127 match <($MsgType)>::read(&mut reader) {
130 msgs::DecodeError::UnknownVersion => return,
131 msgs::DecodeError::UnknownRequiredFeature => return,
132 msgs::DecodeError::InvalidValue => return,
133 msgs::DecodeError::ExtraAddressesPerType => return,
134 msgs::DecodeError::BadLengthDescriptor => return,
135 msgs::DecodeError::ShortRead => panic!("We picked the length..."),
136 msgs::DecodeError::Io(e) => panic!(format!("{}", e)),
142 macro_rules! decode_msg_with_len16 {
143 ($MsgType: path, $begin_len: expr, $excess: expr) => {
145 let extra_len = slice_to_be16(&get_slice_nonadvancing!($begin_len as usize + 2)[$begin_len..$begin_len + 2]);
146 decode_msg!($MsgType, $begin_len as usize + 2 + (extra_len as usize) + $excess)
151 macro_rules! get_pubkey {
153 match PublicKey::from_slice(get_slice!(33)) {
160 let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new("".to_owned()));
161 let chain_monitor = Arc::new(DummyChainWatcher {
162 input: Arc::clone(&input),
165 let our_pubkey = get_pubkey!();
166 let router = Router::new(our_pubkey.clone(), chain_monitor, Arc::clone(&logger));
169 match get_slice!(1)[0] {
171 let start_len = slice_to_be16(&get_slice_nonadvancing!(64 + 2)[64..64 + 2]) as usize;
172 let addr_len = slice_to_be16(&get_slice_nonadvancing!(64+start_len+2 + 74)[64+start_len+2 + 72..64+start_len+2 + 74]);
173 if addr_len > (37+1)*4 {
176 let _ = router.handle_node_announcement(&decode_msg_with_len16!(msgs::NodeAnnouncement, 64, 288));
179 let _ = router.handle_channel_announcement(&decode_msg_with_len16!(msgs::ChannelAnnouncement, 64*4, 32+8+33*4));
182 let _ = router.handle_channel_update(&decode_msg!(msgs::ChannelUpdate, 128));
185 match get_slice!(1)[0] {
187 router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {msg: decode_msg!(msgs::ChannelUpdate, 128)});
190 let short_channel_id = slice_to_be64(get_slice!(8));
191 router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed {short_channel_id, is_permanent: false});
197 let target = get_pubkey!();
198 let mut first_hops_vec = Vec::new();
199 let first_hops = match get_slice!(1)[0] {
202 let count = slice_to_be16(get_slice!(2));
204 first_hops_vec.push(ChannelDetails {
206 short_channel_id: Some(slice_to_be64(get_slice!(8))),
207 remote_network_id: get_pubkey!(),
208 channel_value_satoshis: slice_to_be64(get_slice!(8)),
210 inbound_capacity_msat: 0,
212 outbound_capacity_msat: 0,
215 Some(&first_hops_vec[..])
219 let mut last_hops_vec = Vec::new();
221 let count = slice_to_be16(get_slice!(2));
223 last_hops_vec.push(RouteHint {
224 src_node_id: get_pubkey!(),
225 short_channel_id: slice_to_be64(get_slice!(8)),
226 fee_base_msat: slice_to_be32(get_slice!(4)),
227 fee_proportional_millionths: slice_to_be32(get_slice!(4)),
228 cltv_expiry_delta: slice_to_be16(get_slice!(2)),
229 htlc_minimum_msat: slice_to_be64(get_slice!(8)),
234 let _ = router.get_route(&target, first_hops, last_hops, slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)));
241 #[cfg(feature = "afl")]
242 #[macro_use] extern crate afl;
243 #[cfg(feature = "afl")]
250 #[cfg(feature = "honggfuzz")]
251 #[macro_use] extern crate honggfuzz;
252 #[cfg(feature = "honggfuzz")]
266 fn duplicate_crash() {
267 super::do_test(&::hex::decode("00").unwrap());