Skip to content

Commit

Permalink
Merge pull request #56 from hax0kartik/main
Browse files Browse the repository at this point in the history
Add target for generating header_and_shortids from block
  • Loading branch information
brunoerg authored Jul 5, 2024
2 parents caf44c1 + 63b37a1 commit 632860d
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
28 changes: 28 additions & 0 deletions rust_bitcoin_lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,34 @@ pub unsafe extern "C" fn rust_bitcoin_addrv2(data: *const u8, len: usize, actual
}
}

#[no_mangle]
pub unsafe extern "C" fn rust_bitcoin_headerandshortids(data: *const u8, len: usize) -> i32 {
// Safety: Ensure that the data pointer is valid for the given length
let data_slice = slice::from_raw_parts(data, len);

let res = deserialize_partial::<Block>(data_slice);

match res {
Ok(block) => {
// 101 is a random nonce value and 2 specifies that we want to use segwit
let compact = HeaderAndShortIds::from_block(&block.0, 101, 2, &[]);

match compact {
Ok(c) => return (c.prefilled_txs.len() + c.short_ids.len()).try_into().unwrap(),
Err(_) => return -1,
}

},
Err(err) => {
if err.to_string().starts_with("unsupported segwit version") {
return -2;
}

return -1;
}
}
}

#[no_mangle]
pub unsafe extern "C" fn rust_bitcoin_cmpctblocks(data: *const u8, len: usize) -> i32 {
// Safety: Ensure that the data pointer is valid for the given length
Expand Down
38 changes: 38 additions & 0 deletions targets/headerandshortids.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <fuzzer/FuzzedDataProvider.h>
#include <string>
#include <iostream>

#include "bitcoin/src/test/fuzz/fuzz.h"
#include "bitcoin/src/blockencodings.h"
#include "bitcoin/src/streams.h"

extern "C" int rust_bitcoin_headerandshortids(const uint8_t *data, size_t len);

int HeaderAndShortIdsCore(Span<const uint8_t> buffer)
{
DataStream ds{buffer};
CBlock block;
int res = 0;
try {
ds >> TX_WITH_WITNESS(block);
if (block.vtx.size() < 1) return res;
CBlockHeaderAndShortTxIDs block_header_and_short_txids {block}; // use the value of 101 as nonce
res = block_header_and_short_txids.BlockTxCount();
} catch (const std::ios_base::failure& e) {
if (std::string(e.what()).find("Superfluous witness record") != std::string::npos)
return -2;
return -1;
}
return res;
}

FUZZ_TARGET(header_and_shortids)
{
int core{HeaderAndShortIdsCore(buffer)};
int rust_bitcoin{rust_bitcoin_headerandshortids(buffer.data(), buffer.size())};

if (core == -2 || rust_bitcoin == -2)
return;

assert(core == rust_bitcoin);
}

0 comments on commit 632860d

Please sign in to comment.