Bitcoin Core  22.99.0
P2P Digital Currency
key_io_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-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 <test/data/key_io_invalid.json.h>
6 #include <test/data/key_io_valid.json.h>
7 
8 #include <key.h>
9 #include <key_io.h>
10 #include <script/script.h>
11 #include <test/util/setup_common.h>
12 #include <util/strencodings.h>
13 
14 #include <boost/test/unit_test.hpp>
15 
16 #include <univalue.h>
17 
18 UniValue read_json(const std::string& jsondata);
19 
21 
22 // Goal: check that parsed keys match test payload
23 BOOST_AUTO_TEST_CASE(key_io_valid_parse)
24 {
25  UniValue tests = read_json(std::string(json_tests::key_io_valid, json_tests::key_io_valid + sizeof(json_tests::key_io_valid)));
26  CKey privkey;
27  CTxDestination destination;
29 
30  for (unsigned int idx = 0; idx < tests.size(); idx++) {
31  UniValue test = tests[idx];
32  std::string strTest = test.write();
33  if (test.size() < 3) { // Allow for extra stuff (useful for comments)
34  BOOST_ERROR("Bad test: " << strTest);
35  continue;
36  }
37  std::string exp_base58string = test[0].get_str();
38  std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
39  const UniValue &metadata = test[2].get_obj();
40  bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
41  SelectParams(find_value(metadata, "chain").get_str());
42  bool try_case_flip = find_value(metadata, "tryCaseFlip").isNull() ? false : find_value(metadata, "tryCaseFlip").get_bool();
43  if (isPrivkey) {
44  bool isCompressed = find_value(metadata, "isCompressed").get_bool();
45  // Must be valid private key
46  privkey = DecodeSecret(exp_base58string);
47  BOOST_CHECK_MESSAGE(privkey.IsValid(), "!IsValid:" + strTest);
48  BOOST_CHECK_MESSAGE(privkey.IsCompressed() == isCompressed, "compressed mismatch:" + strTest);
49  BOOST_CHECK_MESSAGE(privkey.size() == exp_payload.size() && std::equal(privkey.begin(), privkey.end(), exp_payload.begin()), "key mismatch:" + strTest);
50 
51  // Private key must be invalid public key
52  destination = DecodeDestination(exp_base58string);
53  BOOST_CHECK_MESSAGE(!IsValidDestination(destination), "IsValid privkey as pubkey:" + strTest);
54  } else {
55  // Must be valid public key
56  destination = DecodeDestination(exp_base58string);
57  CScript script = GetScriptForDestination(destination);
58  BOOST_CHECK_MESSAGE(IsValidDestination(destination), "!IsValid:" + strTest);
59  BOOST_CHECK_EQUAL(HexStr(script), HexStr(exp_payload));
60 
61  // Try flipped case version
62  for (char& c : exp_base58string) {
63  if (c >= 'a' && c <= 'z') {
64  c = (c - 'a') + 'A';
65  } else if (c >= 'A' && c <= 'Z') {
66  c = (c - 'A') + 'a';
67  }
68  }
69  destination = DecodeDestination(exp_base58string);
70  BOOST_CHECK_MESSAGE(IsValidDestination(destination) == try_case_flip, "!IsValid case flipped:" + strTest);
71  if (IsValidDestination(destination)) {
72  script = GetScriptForDestination(destination);
73  BOOST_CHECK_EQUAL(HexStr(script), HexStr(exp_payload));
74  }
75 
76  // Public key must be invalid private key
77  privkey = DecodeSecret(exp_base58string);
78  BOOST_CHECK_MESSAGE(!privkey.IsValid(), "IsValid pubkey as privkey:" + strTest);
79  }
80  }
81 }
82 
83 // Goal: check that generated keys match test vectors
84 BOOST_AUTO_TEST_CASE(key_io_valid_gen)
85 {
86  UniValue tests = read_json(std::string(json_tests::key_io_valid, json_tests::key_io_valid + sizeof(json_tests::key_io_valid)));
87 
88  for (unsigned int idx = 0; idx < tests.size(); idx++) {
89  UniValue test = tests[idx];
90  std::string strTest = test.write();
91  if (test.size() < 3) // Allow for extra stuff (useful for comments)
92  {
93  BOOST_ERROR("Bad test: " << strTest);
94  continue;
95  }
96  std::string exp_base58string = test[0].get_str();
97  std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
98  const UniValue &metadata = test[2].get_obj();
99  bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
100  SelectParams(find_value(metadata, "chain").get_str());
101  if (isPrivkey) {
102  bool isCompressed = find_value(metadata, "isCompressed").get_bool();
103  CKey key;
104  key.Set(exp_payload.begin(), exp_payload.end(), isCompressed);
105  assert(key.IsValid());
106  BOOST_CHECK_MESSAGE(EncodeSecret(key) == exp_base58string, "result mismatch: " + strTest);
107  } else {
108  CTxDestination dest;
109  CScript exp_script(exp_payload.begin(), exp_payload.end());
110  BOOST_CHECK(ExtractDestination(exp_script, dest));
111  std::string address = EncodeDestination(dest);
112 
113  BOOST_CHECK_EQUAL(address, exp_base58string);
114  }
115  }
116 
118 }
119 
120 
121 // Goal: check that base58 parsing code is robust against a variety of corrupted data
122 BOOST_AUTO_TEST_CASE(key_io_invalid)
123 {
124  UniValue tests = read_json(std::string(json_tests::key_io_invalid, json_tests::key_io_invalid + sizeof(json_tests::key_io_invalid))); // Negative testcases
125  CKey privkey;
126  CTxDestination destination;
127 
128  for (unsigned int idx = 0; idx < tests.size(); idx++) {
129  UniValue test = tests[idx];
130  std::string strTest = test.write();
131  if (test.size() < 1) // Allow for extra stuff (useful for comments)
132  {
133  BOOST_ERROR("Bad test: " << strTest);
134  continue;
135  }
136  std::string exp_base58string = test[0].get_str();
137 
138  // must be invalid as public and as private key
140  SelectParams(chain);
141  destination = DecodeDestination(exp_base58string);
142  BOOST_CHECK_MESSAGE(!IsValidDestination(destination), "IsValid pubkey in mainnet:" + strTest);
143  privkey = DecodeSecret(exp_base58string);
144  BOOST_CHECK_MESSAGE(!privkey.IsValid(), "IsValid privkey in mainnet:" + strTest);
145  }
146  }
147 }
148 
CKey::IsCompressed
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:95
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: strencodings.cpp:84
assert
assert(!tx.IsCoinBase())
UniValue::get_bool
bool get_bool() const
Definition: univalue_get.cpp:90
key_io.h
setup_common.h
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:351
CKey::Set
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:73
CBaseChainParams::TESTNET
static const std::string TESTNET
Definition: chainparamsbase.h:23
UniValue::isNull
bool isNull() const
Definition: univalue.h:77
UniValue::write
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Definition: univalue_write.cpp:29
BOOST_FIXTURE_TEST_SUITE
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
BOOST_AUTO_TEST_SUITE_END
BOOST_AUTO_TEST_SUITE_END()
UniValue
Definition: univalue.h:19
CKey::end
const unsigned char * end() const
Definition: key.h:89
UniValue::get_str
const std::string & get_str() const
Definition: univalue_get.cpp:97
CKey::begin
const unsigned char * begin() const
Definition: key.h:88
strencodings.h
UniValue::get_obj
const UniValue & get_obj() const
Definition: univalue_get.cpp:134
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
IsValidDestination
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:373
EncodeSecret
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:196
BOOST_AUTO_TEST_CASE
BOOST_AUTO_TEST_CASE(key_io_valid_parse)
Definition: key_io_tests.cpp:23
univalue.h
CBaseChainParams::REGTEST
static const std::string REGTEST
Definition: chainparamsbase.h:25
read_json
UniValue read_json(const std::string &jsondata)
Definition: script_tests.cpp:42
CKey::IsValid
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:92
BasicTestingSetup
Basic testing setup.
Definition: setup_common.h:76
SelectParams
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
Definition: chainparams.cpp:555
DecodeSecret
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:178
DecodeDestination
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
Definition: key_io.cpp:261
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
script.h
ExtractDestination
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:213
CBaseChainParams::MAIN
static const std::string MAIN
Chain name strings.
Definition: chainparamsbase.h:22
key.h
CKey::size
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:87
CKey
An encapsulated private key.
Definition: key.h:26
UniValue::size
size_t size() const
Definition: univalue.h:68
find_value
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:594
EncodeDestination
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:256
BOOST_CHECK
#define BOOST_CHECK(expr)
Definition: object.cpp:17
BOOST_CHECK_EQUAL
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
CBaseChainParams::SIGNET
static const std::string SIGNET
Definition: chainparamsbase.h:24