Bitcoin Core  22.99.0
P2P Digital Currency
bech32.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-2020 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 <bech32.h>
6 #include <test/fuzz/fuzz.h>
7 #include <test/util/str.h>
8 #include <util/strencodings.h>
9 
10 #include <cassert>
11 #include <cstdint>
12 #include <string>
13 #include <utility>
14 #include <vector>
15 
17 {
18  const std::string random_string(buffer.begin(), buffer.end());
19  const auto r1 = bech32::Decode(random_string);
20  if (r1.hrp.empty()) {
21  assert(r1.encoding == bech32::Encoding::INVALID);
22  assert(r1.data.empty());
23  } else {
24  assert(r1.encoding != bech32::Encoding::INVALID);
25  const std::string reencoded = bech32::Encode(r1.encoding, r1.hrp, r1.data);
26  assert(CaseInsensitiveEqual(random_string, reencoded));
27  }
28 
29  std::vector<unsigned char> input;
30  ConvertBits<8, 5, true>([&](unsigned char c) { input.push_back(c); }, buffer.begin(), buffer.end());
31 
32  if (input.size() + 3 + 6 <= 90) {
33  // If it's possible to encode input in Bech32(m) without exceeding the 90-character limit:
34  for (auto encoding : {bech32::Encoding::BECH32, bech32::Encoding::BECH32M}) {
35  const std::string encoded = bech32::Encode(encoding, "bc", input);
36  assert(!encoded.empty());
37  const auto r2 = bech32::Decode(encoded);
38  assert(r2.encoding == encoding);
39  assert(r2.hrp == "bc");
40  assert(r2.data == input);
41  }
42  }
43 }
str.h
assert
assert(!tx.IsCoinBase())
FUZZ_TARGET
FUZZ_TARGET(bech32)
Definition: bech32.cpp:16
bech32::Decode
DecodeResult Decode(const std::string &str)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:168
bech32::Encoding::BECH32
@ BECH32
Bech32 encoding as defined in BIP173.
strencodings.h
bech32::Encoding::INVALID
@ INVALID
Failed decoding.
CaseInsensitiveEqual
bool CaseInsensitiveEqual(const std::string &s1, const std::string &s2)
Definition: str.cpp:10
bech32
Definition: bech32.cpp:10
bech32::Encoding::BECH32M
@ BECH32M
Bech32m encoding as defined in BIP350.
fuzz.h
bech32.h
bech32::Encode
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:152