|
| 1 | +// Copyright (c) 2021 The Bitcoin Core developers |
| 2 | +// Distributed under the MIT software license, see the accompanying |
| 3 | +// file COPYING or http://www.opensource.org/licenses/mit-license.php. |
| 4 | + |
| 5 | +#include <core_io.h> |
| 6 | +#include <hash.h> |
| 7 | +#include <key.h> |
| 8 | +#include <script/miniscript.h> |
| 9 | +#include <script/script.h> |
| 10 | +#include <test/fuzz/FuzzedDataProvider.h> |
| 11 | +#include <test/fuzz/fuzz.h> |
| 12 | +#include <test/fuzz/util.h> |
| 13 | +#include <util/strencodings.h> |
| 14 | + |
| 15 | +namespace { |
| 16 | + |
| 17 | +//! Context that implements naive conversion from/to script only, for roundtrip testing. |
| 18 | +struct ScriptParserContext { |
| 19 | + //! For Script roundtrip we never need the key from a key hash. |
| 20 | + struct Key { |
| 21 | + bool is_hash; |
| 22 | + std::vector<unsigned char> data; |
| 23 | + }; |
| 24 | + |
| 25 | + const std::vector<unsigned char>& ToPKBytes(const Key& key) const |
| 26 | + { |
| 27 | + assert(!key.is_hash); |
| 28 | + return key.data; |
| 29 | + } |
| 30 | + |
| 31 | + const std::vector<unsigned char> ToPKHBytes(const Key& key) const |
| 32 | + { |
| 33 | + if (key.is_hash) return key.data; |
| 34 | + const auto h = Hash160(key.data); |
| 35 | + return {h.begin(), h.end()}; |
| 36 | + } |
| 37 | + |
| 38 | + template<typename I> |
| 39 | + std::optional<Key> FromPKBytes(I first, I last) const |
| 40 | + { |
| 41 | + Key key; |
| 42 | + key.data.assign(first, last); |
| 43 | + key.is_hash = false; |
| 44 | + return key; |
| 45 | + } |
| 46 | + |
| 47 | + template<typename I> |
| 48 | + std::optional<Key> FromPKHBytes(I first, I last) const |
| 49 | + { |
| 50 | + Key key; |
| 51 | + key.data.assign(first, last); |
| 52 | + key.is_hash = true; |
| 53 | + return key; |
| 54 | + } |
| 55 | +} SCRIPT_PARSER_CONTEXT; |
| 56 | + |
| 57 | +} |
| 58 | + |
| 59 | +/* Fuzz tests that test parsing from a script, and roundtripping via script. */ |
| 60 | +FUZZ_TARGET(miniscript_script) |
| 61 | +{ |
| 62 | + FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); |
| 63 | + const std::optional<CScript> script = ConsumeDeserializable<CScript>(fuzzed_data_provider); |
| 64 | + if (!script) return; |
| 65 | + |
| 66 | + const auto ms = miniscript::FromScript(*script, SCRIPT_PARSER_CONTEXT); |
| 67 | + if (!ms) return; |
| 68 | + |
| 69 | + assert(ms->ToScript(SCRIPT_PARSER_CONTEXT) == *script); |
| 70 | +} |
0 commit comments