Fix some new indentation nits
[rust-lightning] / fuzz / src / router.rs
1 use bitcoin::blockdata::script::{Script, Builder};
2 use bitcoin::blockdata::block::Block;
3 use bitcoin::blockdata::transaction::Transaction;
4 use bitcoin::hash_types::{Txid, BlockHash};
5
6 use lightning::chain::chaininterface::{ChainError,ChainWatchInterface};
7 use lightning::ln::channelmanager::ChannelDetails;
8 use lightning::ln::features::InitFeatures;
9 use lightning::ln::msgs;
10 use lightning::ln::msgs::RoutingMessageHandler;
11 use lightning::routing::router::{get_route, RouteHint};
12 use lightning::util::logger::Logger;
13 use lightning::util::ser::Readable;
14 use lightning::routing::network_graph::{NetGraphMsgHandler, RoutingFees};
15
16 use bitcoin::secp256k1::key::PublicKey;
17
18 use utils::test_logger;
19
20 use std::sync::Arc;
21 use std::sync::atomic::{AtomicUsize, Ordering};
22
23 #[inline]
24 pub fn slice_to_be16(v: &[u8]) -> u16 {
25         ((v[0] as u16) << 8*1) |
26         ((v[1] as u16) << 8*0)
27 }
28
29 #[inline]
30 pub fn slice_to_be32(v: &[u8]) -> u32 {
31         ((v[0] as u32) << 8*3) |
32         ((v[1] as u32) << 8*2) |
33         ((v[2] as u32) << 8*1) |
34         ((v[3] as u32) << 8*0)
35 }
36
37 #[inline]
38 pub fn slice_to_be64(v: &[u8]) -> u64 {
39         ((v[0] as u64) << 8*7) |
40         ((v[1] as u64) << 8*6) |
41         ((v[2] as u64) << 8*5) |
42         ((v[3] as u64) << 8*4) |
43         ((v[4] as u64) << 8*3) |
44         ((v[5] as u64) << 8*2) |
45         ((v[6] as u64) << 8*1) |
46         ((v[7] as u64) << 8*0)
47 }
48
49
50 struct InputData {
51         data: Vec<u8>,
52         read_pos: AtomicUsize,
53 }
54 impl InputData {
55         fn get_slice(&self, len: usize) -> Option<&[u8]> {
56                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
57                 if self.data.len() < old_pos + len {
58                         return None;
59                 }
60                 Some(&self.data[old_pos..old_pos + len])
61         }
62         fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
63                 let old_pos = self.read_pos.load(Ordering::Acquire);
64                 if self.data.len() < old_pos + len {
65                         return None;
66                 }
67                 Some(&self.data[old_pos..old_pos + len])
68         }
69 }
70
71 struct DummyChainWatcher {
72         input: Arc<InputData>,
73 }
74
75 impl ChainWatchInterface for DummyChainWatcher {
76         fn install_watch_tx(&self, _txid: &Txid, _script_pub_key: &Script) { }
77         fn install_watch_outpoint(&self, _outpoint: (Txid, u32), _out_script: &Script) { }
78         fn watch_all_txn(&self) { }
79         fn filter_block<'a>(&self, _block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
80                 (Vec::new(), Vec::new())
81         }
82         fn reentered(&self) -> usize { 0 }
83
84         fn get_chain_utxo(&self, _genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
85                 match self.input.get_slice(2) {
86                         Some(&[0, _]) => Err(ChainError::NotSupported),
87                         Some(&[1, _]) => Err(ChainError::NotWatched),
88                         Some(&[2, _]) => Err(ChainError::UnknownTx),
89                         Some(&[_, x]) => Ok((Builder::new().push_int(x as i64).into_script().to_v0_p2wsh(), 0)),
90                         None => Err(ChainError::UnknownTx),
91                         _ => unreachable!(),
92                 }
93         }
94 }
95
96 #[inline]
97 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
98         let input = Arc::new(InputData {
99                 data: data.to_vec(),
100                 read_pos: AtomicUsize::new(0),
101         });
102         macro_rules! get_slice_nonadvancing {
103                 ($len: expr) => {
104                         match input.get_slice_nonadvancing($len as usize) {
105                                 Some(slice) => slice,
106                                 None => return,
107                         }
108                 }
109         }
110         macro_rules! get_slice {
111                 ($len: expr) => {
112                         match input.get_slice($len as usize) {
113                                 Some(slice) => slice,
114                                 None => return,
115                         }
116                 }
117         }
118
119         macro_rules! decode_msg {
120                 ($MsgType: path, $len: expr) => {{
121                         let mut reader = ::std::io::Cursor::new(get_slice!($len));
122                         match <$MsgType>::read(&mut reader) {
123                                 Ok(msg) => msg,
124                                 Err(e) => match e {
125                                         msgs::DecodeError::UnknownVersion => return,
126                                         msgs::DecodeError::UnknownRequiredFeature => return,
127                                         msgs::DecodeError::InvalidValue => return,
128                                         msgs::DecodeError::BadLengthDescriptor => return,
129                                         msgs::DecodeError::ShortRead => panic!("We picked the length..."),
130                                         msgs::DecodeError::Io(e) => panic!(format!("{}", e)),
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         macro_rules! get_pubkey {
146                 () => {
147                         match PublicKey::from_slice(get_slice!(33)) {
148                                 Ok(key) => key,
149                                 Err(_) => return,
150                         }
151                 }
152         }
153
154         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
155         let chain_monitor = Arc::new(DummyChainWatcher {
156                 input: Arc::clone(&input),
157         });
158
159         let our_pubkey = get_pubkey!();
160         let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
161
162         loop {
163                 match get_slice!(1)[0] {
164                         0 => {
165                                 let start_len = slice_to_be16(&get_slice_nonadvancing!(64 + 2)[64..64 + 2]) as usize;
166                                 let addr_len = slice_to_be16(&get_slice_nonadvancing!(64+start_len+2 + 74)[64+start_len+2 + 72..64+start_len+2 + 74]);
167                                 if addr_len > (37+1)*4 {
168                                         return;
169                                 }
170                                 let _ = net_graph_msg_handler.handle_node_announcement(&decode_msg_with_len16!(msgs::NodeAnnouncement, 64, 288));
171                         },
172                         1 => {
173                                 let _ = net_graph_msg_handler.handle_channel_announcement(&decode_msg_with_len16!(msgs::ChannelAnnouncement, 64*4, 32+8+33*4));
174                         },
175                         2 => {
176                                 let _ = net_graph_msg_handler.handle_channel_update(&decode_msg!(msgs::ChannelUpdate, 128));
177                         },
178                         3 => {
179                                 match get_slice!(1)[0] {
180                                         0 => {
181                                                 net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {msg: decode_msg!(msgs::ChannelUpdate, 128)});
182                                         },
183                                         1 => {
184                                                 let short_channel_id = slice_to_be64(get_slice!(8));
185                                                 net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed {short_channel_id, is_permanent: false});
186                                         },
187                                         _ => return,
188                                 }
189                         },
190                         4 => {
191                                 let target = get_pubkey!();
192                                 let mut first_hops_vec = Vec::new();
193                                 let first_hops = match get_slice!(1)[0] {
194                                         0 => None,
195                                         1 => {
196                                                 let count = slice_to_be16(get_slice!(2));
197                                                 for _ in 0..count {
198                                                         first_hops_vec.push(ChannelDetails {
199                                                                 channel_id: [0; 32],
200                                                                 short_channel_id: Some(slice_to_be64(get_slice!(8))),
201                                                                 remote_network_id: get_pubkey!(),
202                                                                 counterparty_features: InitFeatures::empty(),
203                                                                 channel_value_satoshis: slice_to_be64(get_slice!(8)),
204                                                                 user_id: 0,
205                                                                 inbound_capacity_msat: 0,
206                                                                 is_live: true,
207                                                                 outbound_capacity_msat: 0,
208                                                         });
209                                                 }
210                                                 Some(&first_hops_vec[..])
211                                         },
212                                         _ => return,
213                                 };
214                                 let mut last_hops_vec = Vec::new();
215                                 let last_hops = {
216                                         let count = slice_to_be16(get_slice!(2));
217                                         for _ in 0..count {
218                                                 last_hops_vec.push(RouteHint {
219                                                         src_node_id: get_pubkey!(),
220                                                         short_channel_id: slice_to_be64(get_slice!(8)),
221                                                         fees: RoutingFees {
222                                                                 base_msat: slice_to_be32(get_slice!(4)),
223                                                                 proportional_millionths: slice_to_be32(get_slice!(4)),
224                                                         },
225                                                         cltv_expiry_delta: slice_to_be16(get_slice!(2)),
226                                                         htlc_minimum_msat: slice_to_be64(get_slice!(8)),
227                                                 });
228                                         }
229                                         &last_hops_vec[..]
230                                 };
231                                 let _ = get_route(&our_pubkey, &net_graph_msg_handler, &target, first_hops, last_hops, slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)), Arc::clone(&logger));
232                         },
233                         _ => return,
234                 }
235         }
236 }
237
238 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
239         do_test(data, out);
240 }
241
242 #[no_mangle]
243 pub extern "C" fn router_run(data: *const u8, datalen: usize) {
244         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
245 }