Skip to content

Instantly share code, notes, and snippets.

@yuntai
Last active May 8, 2018 02:41
Show Gist options
  • Save yuntai/94115e4420426759399c50423b4a4c9b to your computer and use it in GitHub Desktop.
Save yuntai/94115e4420426759399c50423b4a4c9b to your computer and use it in GitHub Desktop.
extern crate lightning;
extern crate secp256k1;
use secp256k1::key::PublicKey;
use secp256k1::{Secp256k1};
use lightning::ln::msgs;
use lightning::util::reset_rng_state;
use std::sync::atomic::{AtomicUsize,Ordering};
use lightning::ln::msgs::{MsgEncodable, MsgDecodable};
#[inline]
pub fn slice_to_be16(v: &[u8]) -> u16 {
((v[0] as u16) << 8*1) |
((v[1] as u16) << 8*0)
}
struct InputData<'a> {
data: &'a [u8],
read_pos: AtomicUsize,
}
impl<'a> InputData<'a> {
fn get_slice(&self, len: usize) -> Option<&'a [u8]> {
let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
if self.data.len() < old_pos + len {
return None;
}
Some(&self.data[old_pos..old_pos + len])
}
}
#[inline]
pub fn do_test(data: &[u8]) {
reset_rng_state();
let input = InputData {
data,
read_pos: AtomicUsize::new(0),
};
macro_rules! get_slice {
($len: expr) => {
match input.get_slice($len as usize) {
Some(slice) => slice,
None => return,
}
}
}
let secp_ctx = &Secp256k1::new();
macro_rules! get_pubkey {
($s: expr) => {
match PublicKey::from_slice(&secp_ctx, $s) {
Ok(key) => key,
Err(e) => return,
}
}
}
loop {
let s = get_slice!(33);
let key = get_pubkey!(s);
let t = &key.serialize()[..];
assert_eq!(s, t);
}
}
#[cfg(feature = "afl")]
extern crate afl;
#[cfg(feature = "afl")]
fn main() {
afl::read_stdio_bytes(|data| {
do_test(&data);
});
}
#[cfg(feature = "honggfuzz")]
#[macro_use] extern crate honggfuzz;
#[cfg(feature = "honggfuzz")]
fn main() {
loop {
fuzz!(|data| {
do_test(data);
});
}
}
#[cfg(test)]
mod tests {
fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {
let mut b = 0;
for (idx, c) in hex.as_bytes().iter().enumerate() {
b <<= 4;
match *c {
b'A'...b'F' => b |= c - b'A' + 10,
b'a'...b'f' => b |= c - b'a' + 10,
b'0'...b'9' => b |= c - b'0',
_ => panic!("Bad hex"),
}
if (idx & 1) == 1 {
out.push(b);
b = 0;
}
}
}
#[test]
fn duplicate_crash() {
let mut a = Vec::new();
extend_vec_from_hex("00", &mut a);
super::do_test(&a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment