Add DummyChainWatcher in route_target
[rust-lightning] / fuzz / fuzz_targets / router_target.rs
1 extern crate bitcoin;
2 extern crate lightning;
3 extern crate secp256k1;
4
5 use bitcoin::util::hash::Sha256dHash;
6 use bitcoin::blockdata::script::{Script, Builder};
7 use bitcoin::blockdata::opcodes;
8
9 use lightning::chain::chaininterface::{ChainError,ChainWatchInterface, ChainListener};
10 use lightning::ln::channelmanager::ChannelDetails;
11 use lightning::ln::msgs;
12 use lightning::ln::msgs::{MsgDecodable, RoutingMessageHandler};
13 use lightning::ln::router::{Router, RouteHint};
14 use lightning::util::reset_rng_state;
15 use lightning::util::logger::Logger;
16
17 use secp256k1::key::PublicKey;
18 use secp256k1::Secp256k1;
19
20 mod utils;
21
22 use utils::test_logger;
23
24 use std::sync::{Weak, Arc};
25 use std::sync::atomic::{AtomicUsize, Ordering};
26
27 #[inline]
28 pub fn slice_to_be16(v: &[u8]) -> u16 {
29         ((v[0] as u16) << 8*1) |
30         ((v[1] as u16) << 8*0)
31 }
32
33 #[inline]
34 pub fn slice_to_be32(v: &[u8]) -> u32 {
35         ((v[0] as u32) << 8*3) |
36         ((v[1] as u32) << 8*2) |
37         ((v[2] as u32) << 8*1) |
38         ((v[3] as u32) << 8*0)
39 }
40
41 #[inline]
42 pub fn slice_to_be64(v: &[u8]) -> u64 {
43         ((v[0] as u64) << 8*7) |
44         ((v[1] as u64) << 8*6) |
45         ((v[2] as u64) << 8*5) |
46         ((v[3] as u64) << 8*4) |
47         ((v[4] as u64) << 8*3) |
48         ((v[5] as u64) << 8*2) |
49         ((v[6] as u64) << 8*1) |
50         ((v[7] as u64) << 8*0)
51 }
52
53
54 struct InputData {
55         data: Vec<u8>,
56         read_pos: AtomicUsize,
57 }
58 impl InputData {
59         fn get_slice(&self, len: usize) -> Option<&[u8]> {
60                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
61                 if self.data.len() < old_pos + len {
62                         return None;
63                 }
64                 Some(&self.data[old_pos..old_pos + len])
65         }
66 }
67
68 struct DummyChainWatcher {
69         input: Arc<InputData>,
70 }
71
72 impl ChainWatchInterface for DummyChainWatcher {
73         fn install_watch_script(&self, _script_pub_key: &Script) {
74         }
75
76         fn install_watch_outpoint(&self, _outpoint: (Sha256dHash, u32), _out_script: &Script) {
77         }
78
79         fn watch_all_txn(&self) {
80         }
81
82         fn register_listener(&self, _listener: Weak<ChainListener>) {
83         }
84
85         fn get_chain_utxo(&self, _genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
86                 match self.input.get_slice(1) {
87                         Some(slice) => Ok((Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).into_script().to_v0_p2wsh(), 0)),
88                         None => Err(ChainError::UnknownTx),
89                 }
90         }
91 }
92
93 #[inline]
94 pub fn do_test(data: &[u8]) {
95         reset_rng_state();
96
97         let mut read_pos = 0;
98         macro_rules! get_slice_nonadvancing {
99                 ($len: expr) => {
100                         {
101                                 if data.len() < read_pos + $len as usize {
102                                         return;
103                                 }
104                                 &data[read_pos..read_pos + $len as usize]
105                         }
106                 }
107         }
108         macro_rules! get_slice {
109                 ($len: expr) => {
110                         {
111                                 let res = get_slice_nonadvancing!($len);
112                                 read_pos += $len;
113                                 res
114                         }
115                 }
116         }
117
118         macro_rules! decode_msg {
119                 ($MsgType: path, $len: expr) => {
120                         match <($MsgType)>::decode(get_slice!($len)) {
121                                 Ok(msg) => msg,
122                                 Err(e) => match e {
123                                         msgs::DecodeError::UnknownRealmByte => return,
124                                         msgs::DecodeError::UnknownRequiredFeature => return,
125                                         msgs::DecodeError::BadPublicKey => return,
126                                         msgs::DecodeError::BadSignature => return,
127                                         msgs::DecodeError::BadText => return,
128                                         msgs::DecodeError::ExtraAddressesPerType => return,
129                                         msgs::DecodeError::BadLengthDescriptor => return,
130                                         msgs::DecodeError::ShortRead => panic!("We picked the length..."),
131                                 }
132                         }
133                 }
134         }
135
136         macro_rules! decode_msg_with_len16 {
137                 ($MsgType: path, $begin_len: expr, $excess: expr) => {
138                         {
139                                 let extra_len = slice_to_be16(&get_slice_nonadvancing!($begin_len as usize + 2)[$begin_len..$begin_len + 2]);
140                                 decode_msg!($MsgType, $begin_len as usize + 2 + (extra_len as usize) + $excess)
141                         }
142                 }
143         }
144
145         let secp_ctx = Secp256k1::new();
146         macro_rules! get_pubkey {
147                 () => {
148                         match PublicKey::from_slice(&secp_ctx, get_slice!(33)) {
149                                 Ok(key) => key,
150                                 Err(_) => return,
151                         }
152                 }
153         }
154
155         let logger: Arc<Logger> = Arc::new(test_logger::TestLogger{});
156         let input = Arc::new(InputData {
157                 data: data.to_vec(),
158                 read_pos: AtomicUsize::new(0),
159         });
160         let chain_monitor = Arc::new(DummyChainWatcher {
161                 input: input,
162         });
163
164         let our_pubkey = get_pubkey!();
165         let router = Router::new(our_pubkey.clone(), chain_monitor, Arc::clone(&logger));
166
167         loop {
168                 match get_slice!(1)[0] {
169                         0 => {
170                                 let start_len = slice_to_be16(&get_slice_nonadvancing!(64 + 2)[64..64 + 2]) as usize;
171                                 let addr_len = slice_to_be16(&get_slice_nonadvancing!(64+start_len+2 + 74)[64+start_len+2 + 72..64+start_len+2 + 74]);
172                                 if addr_len > (37+1)*4 {
173                                         return;
174                                 }
175                                 let _ = router.handle_node_announcement(&decode_msg_with_len16!(msgs::NodeAnnouncement, 64, 288));
176                         },
177                         1 => {
178                                 let _ = router.handle_channel_announcement(&decode_msg_with_len16!(msgs::ChannelAnnouncement, 64*4, 32+8+33*4));
179                         },
180                         2 => {
181                                 let _ = router.handle_channel_update(&decode_msg!(msgs::ChannelUpdate, 128));
182                         },
183                         3 => {
184                                 match get_slice!(1)[0] {
185                                         0 => {
186                                                 router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {msg: decode_msg!(msgs::ChannelUpdate, 128)});
187                                         },
188                                         1 => {
189                                                 let short_channel_id = slice_to_be64(get_slice!(8));
190                                                 router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed {short_channel_id});
191                                         },
192                                         _ => return,
193                                 }
194                         },
195                         4 => {
196                                 let target = get_pubkey!();
197                                 let mut first_hops_vec = Vec::new();
198                                 let first_hops = match get_slice!(1)[0] {
199                                         0 => None,
200                                         1 => {
201                                                 let count = slice_to_be16(get_slice!(2));
202                                                 for _ in 0..count {
203                                                         first_hops_vec.push(ChannelDetails {
204                                                                 channel_id: [0; 32],
205                                                                 short_channel_id: Some(slice_to_be64(get_slice!(8))),
206                                                                 remote_network_id: get_pubkey!(),
207                                                                 channel_value_satoshis: slice_to_be64(get_slice!(8)),
208                                                                 user_id: 0,
209                                                         });
210                                                 }
211                                                 Some(&first_hops_vec[..])
212                                         },
213                                         _ => return,
214                                 };
215                                 let mut last_hops_vec = Vec::new();
216                                 let last_hops = {
217                                         let count = slice_to_be16(get_slice!(2));
218                                         for _ in 0..count {
219                                                 last_hops_vec.push(RouteHint {
220                                                         src_node_id: get_pubkey!(),
221                                                         short_channel_id: slice_to_be64(get_slice!(8)),
222                                                         fee_base_msat: slice_to_be32(get_slice!(4)),
223                                                         fee_proportional_millionths: slice_to_be32(get_slice!(4)),
224                                                         cltv_expiry_delta: slice_to_be16(get_slice!(2)),
225                                                         htlc_minimum_msat: slice_to_be64(get_slice!(8)),
226                                                 });
227                                         }
228                                         &last_hops_vec[..]
229                                 };
230                                 let _ = router.get_route(&target, first_hops, last_hops, slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)));
231                         },
232                         _ => return,
233                 }
234         }
235 }
236
237 #[cfg(feature = "afl")]
238 #[macro_use] extern crate afl;
239 #[cfg(feature = "afl")]
240 fn main() {
241         fuzz!(|data| {
242                 do_test(data);
243         });
244 }
245
246 #[cfg(feature = "honggfuzz")]
247 #[macro_use] extern crate honggfuzz;
248 #[cfg(feature = "honggfuzz")]
249 fn main() {
250         loop {
251                 fuzz!(|data| {
252                         do_test(data);
253                 });
254         }
255 }
256
257 extern crate hex;
258 #[cfg(test)]
259 mod tests {
260
261         #[test]
262         fn duplicate_crash() {
263                 super::do_test(&::hex::decode("00").unwrap());
264         }
265 }