Merge pull request #17 from TheBlueMatt/2017-04-channel-close
[rust-lightning] / fuzz / fuzz_targets / full_stack_target.rs
1 extern crate bitcoin;
2 extern crate lightning;
3 extern crate secp256k1;
4
5 use bitcoin::blockdata::transaction::Transaction;
6 use bitcoin::network::constants::Network;
7 use bitcoin::util::hash::Sha256dHash;
8
9 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,FeeEstimator,ChainWatchInterfaceUtil};
10 use lightning::ln::{channelmonitor,msgs};
11 use lightning::ln::channelmanager::ChannelManager;
12 use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
13 use lightning::ln::router::Router;
14
15 use secp256k1::key::{PublicKey,SecretKey};
16 use secp256k1::Secp256k1;
17
18 use std::sync::Arc;
19 use std::sync::atomic::{AtomicUsize,Ordering};
20
21 #[inline]
22 pub fn slice_to_be16(v: &[u8]) -> u16 {
23         ((v[0] as u16) << 8*1) |
24         ((v[1] as u16) << 8*0)
25 }
26
27 #[inline]
28 pub fn slice_to_be32(v: &[u8]) -> u32 {
29         ((v[0] as u32) << 8*3) |
30         ((v[1] as u32) << 8*2) |
31         ((v[2] as u32) << 8*1) |
32         ((v[3] as u32) << 8*0)
33 }
34
35 struct InputData {
36         data: Vec<u8>,
37         read_pos: AtomicUsize,
38 }
39 impl InputData {
40         fn get_slice(&self, len: usize) -> Option<&[u8]> {
41                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
42                 if self.data.len() < old_pos + len {
43                         return None;
44                 }
45                 Some(&self.data[old_pos..old_pos + len])
46         }
47         fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
48                 let old_pos = self.read_pos.load(Ordering::Acquire);
49                 if self.data.len() < old_pos + len {
50                         return None;
51                 }
52                 Some(&self.data[old_pos..old_pos + len])
53         }
54 }
55
56 struct FuzzEstimator {
57         input: Arc<InputData>,
58 }
59 impl FeeEstimator for FuzzEstimator {
60         fn get_est_sat_per_vbyte(&self, _: ConfirmationTarget) -> u64 {
61                 //TODO: We should actually be testing at least much more than 64k...
62                 match self.input.get_slice(2) {
63                         Some(slice) => slice_to_be16(slice) as u64,
64                         None => 0
65                 }
66         }
67 }
68
69 struct TestChannelMonitor {}
70 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
71         fn add_update_monitor(&self, _funding_txo: (Sha256dHash, u16), _monitor: channelmonitor::ChannelMonitor) -> Result<(), msgs::HandleError> {
72                 //TODO!
73                 Ok(())
74         }
75 }
76
77 struct TestBroadcaster {}
78 impl BroadcasterInterface for TestBroadcaster {
79         fn broadcast_transaction(&self, _tx: &Transaction) {}
80 }
81
82 #[derive(Clone, PartialEq, Eq, Hash)]
83 struct Peer {
84         id: u8,
85 }
86 impl SocketDescriptor for Peer {
87         fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
88                 assert!(write_offset < data.len());
89                 data.len() - write_offset
90         }
91 }
92
93 #[inline]
94 pub fn do_test(data: &[u8]) {
95         let input = Arc::new(InputData {
96                 data: data.to_vec(),
97                 read_pos: AtomicUsize::new(0),
98         });
99         let fee_est = Arc::new(FuzzEstimator {
100                 input: input.clone(),
101         });
102
103         macro_rules! get_slice {
104                 ($len: expr) => {
105                         match input.get_slice($len as usize) {
106                                 Some(slice) => slice,
107                                 None => return,
108                         }
109                 }
110         }
111
112         let secp_ctx = Secp256k1::new();
113         macro_rules! get_pubkey {
114                 () => {
115                         match PublicKey::from_slice(&secp_ctx, get_slice!(33)) {
116                                 Ok(key) => key,
117                                 Err(_) => return,
118                         }
119                 }
120         }
121
122         let our_network_key = match SecretKey::from_slice(&secp_ctx, get_slice!(32)) {
123                 Ok(key) => key,
124                 Err(_) => return,
125         };
126
127         let monitor = Arc::new(TestChannelMonitor{});
128         let watch = Arc::new(ChainWatchInterfaceUtil::new());
129         let broadcast = Arc::new(TestBroadcaster{});
130
131         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();
132         let router = Arc::new(Router::new(PublicKey::from_secret_key(&secp_ctx, &our_network_key).unwrap()));
133
134         let handler = PeerManager::new(MessageHandler {
135                 chan_handler: channelmanager.clone(),
136                 route_handler: router.clone(),
137         }, our_network_key);
138
139         let mut peers = [false; 256];
140
141         loop {
142                 match get_slice!(1)[0] {
143                         0 => {
144                                 let mut new_id = 0;
145                                 for i in 1..256 {
146                                         if !peers[i-1] {
147                                                 new_id = i;
148                                                 break;
149                                         }
150                                 }
151                                 if new_id == 0 { return; }
152                                 peers[new_id - 1] = true;
153                                 handler.new_outbound_connection(get_pubkey!(), Peer{id: (new_id - 1) as u8}).unwrap();
154                         },
155                         1 => {
156                                 let mut new_id = 0;
157                                 for i in 1..256 {
158                                         if !peers[i-1] {
159                                                 new_id = i;
160                                                 break;
161                                         }
162                                 }
163                                 if new_id == 0 { return; }
164                                 peers[new_id - 1] = true;
165                                 handler.new_inbound_connection(Peer{id: (new_id - 1) as u8}).unwrap();
166                         },
167                         2 => {
168                                 let peer_id = get_slice!(1)[0];
169                                 if !peers[peer_id as usize] { return; }
170                                 peers[peer_id as usize] = false;
171                                 handler.disconnect_event(&Peer{id: peer_id});
172                         },
173                         3 => {
174                                 let peer_id = get_slice!(1)[0];
175                                 if !peers[peer_id as usize] { return; }
176                                 match handler.read_event(&mut Peer{id: peer_id}, get_slice!(get_slice!(1)[0]).to_vec()) {
177                                         Ok(res) => assert!(!res),
178                                         Err(_) => { peers[peer_id as usize] = false; }
179                                 }
180                         },
181                         _ => return,
182                 }
183         }
184 }
185
186 #[cfg(feature = "afl")]
187 extern crate afl;
188 #[cfg(feature = "afl")]
189 fn main() {
190         afl::read_stdio_bytes(|data| {
191                 do_test(&data);
192         });
193 }
194
195 #[cfg(feature = "honggfuzz")]
196 #[macro_use] extern crate honggfuzz;
197 #[cfg(feature = "honggfuzz")]
198 fn main() {
199         loop {
200                 fuzz!(|data| {
201                         do_test(data);
202                 });
203         }
204 }
205
206 #[cfg(test)]
207 mod tests {
208         fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {
209                 let mut b = 0;
210                 for (idx, c) in hex.as_bytes().iter().enumerate() {
211                         b <<= 4;
212                         match *c {
213                                 b'A'...b'F' => b |= c - b'A' + 10,
214                                 b'a'...b'f' => b |= c - b'a' + 10,
215                                 b'0'...b'9' => b |= c - b'0',
216                                 _ => panic!("Bad hex"),
217                         }
218                         if (idx & 1) == 1 {
219                                 out.push(b);
220                                 b = 0;
221                         }
222                 }
223         }
224
225         #[test]
226         fn duplicate_crash() {
227                 let mut a = Vec::new();
228                 extend_vec_from_hex("00", &mut a);
229                 super::do_test(&a);
230         }
231 }