tests: Add fuzzing harness for Bech32 encoding/decoding

pull/17357/head
practicalswift 5 years ago
parent 85a34b1683
commit b7541705d0

@ -7,6 +7,7 @@ FUZZ_TARGETS = \
test/fuzz/address_deserialize \
test/fuzz/addrman_deserialize \
test/fuzz/banentry_deserialize \
test/fuzz/bech32 \
test/fuzz/block_deserialize \
test/fuzz/blockheader_deserialize \
test/fuzz/blocklocator_deserialize \
@ -65,11 +66,13 @@ BITCOIN_TEST_SUITE = \
test/util/str.cpp
FUZZ_SUITE = \
test/setup_common.h \
test/setup_common.cpp \
test/fuzz/fuzz.cpp \
test/fuzz/fuzz.h \
test/fuzz/FuzzedDataProvider.h
test/fuzz/FuzzedDataProvider.h \
test/setup_common.cpp \
test/setup_common.h \
test/util/str.cpp \
test/util/str.h
FUZZ_SUITE_LD_COMMON = \
$(LIBBITCOIN_SERVER) \
@ -242,6 +245,12 @@ test_fuzz_banentry_deserialize_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
test_fuzz_banentry_deserialize_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
test_fuzz_banentry_deserialize_LDADD = $(FUZZ_SUITE_LD_COMMON)
test_fuzz_bech32_SOURCES = $(FUZZ_SUITE) test/fuzz/bech32.cpp
test_fuzz_bech32_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
test_fuzz_bech32_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
test_fuzz_bech32_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
test_fuzz_bech32_LDADD = $(FUZZ_SUITE_LD_COMMON)
test_fuzz_txundo_deserialize_SOURCES = $(FUZZ_SUITE) test/fuzz/deserialize.cpp
test_fuzz_txundo_deserialize_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) -DTXUNDO_DESERIALIZE=1
test_fuzz_txundo_deserialize_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)

@ -0,0 +1,43 @@
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bech32.h>
#include <test/fuzz/fuzz.h>
#include <test/util/str.h>
#include <util/strencodings.h>
#include <cassert>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
void test_one_input(const std::vector<uint8_t>& buffer)
{
const std::string random_string(buffer.begin(), buffer.end());
const std::pair<std::string, std::vector<uint8_t>> r1 = bech32::Decode(random_string);
if (r1.first.empty()) {
assert(r1.second.empty());
} else {
const std::string& hrp = r1.first;
const std::vector<uint8_t>& data = r1.second;
const std::string reencoded = bech32::Encode(hrp, data);
assert(CaseInsensitiveEqual(random_string, reencoded));
}
std::vector<unsigned char> input;
ConvertBits<8, 5, true>([&](unsigned char c) { input.push_back(c); }, buffer.begin(), buffer.end());
const std::string encoded = bech32::Encode("bc", input);
assert(!encoded.empty());
const std::pair<std::string, std::vector<uint8_t>> r2 = bech32::Decode(encoded);
if (r2.first.empty()) {
assert(r2.second.empty());
} else {
const std::string& hrp = r2.first;
const std::vector<uint8_t>& data = r2.second;
assert(hrp == "bc");
assert(data == input);
}
}
Loading…
Cancel
Save