Coverage Report

Created: 2025-09-19 18:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/test/fuzz/key.cpp
Line
Count
Source
1
// Copyright (c) 2020-present 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 <chainparams.h>
6
#include <key.h>
7
#include <key_io.h>
8
#include <outputtype.h>
9
#include <policy/policy.h>
10
#include <pubkey.h>
11
#include <rpc/util.h>
12
#include <script/keyorigin.h>
13
#include <script/script.h>
14
#include <script/sign.h>
15
#include <script/signingprovider.h>
16
#include <script/solver.h>
17
#include <streams.h>
18
#include <test/fuzz/FuzzedDataProvider.h>
19
#include <test/fuzz/fuzz.h>
20
#include <test/fuzz/util.h>
21
#include <test/util/random.h>
22
#include <util/chaintype.h>
23
#include <util/strencodings.h>
24
25
#include <array>
26
#include <cassert>
27
#include <cstddef>
28
#include <cstdint>
29
#include <numeric>
30
#include <optional>
31
#include <string>
32
#include <vector>
33
34
void initialize_key()
35
0
{
36
0
    static ECC_Context ecc_context{};
37
0
    SelectParams(ChainType::REGTEST);
38
0
}
39
40
FUZZ_TARGET(key, .init = initialize_key)
41
0
{
42
0
    SeedRandomStateForTest(SeedRand::ZEROS);
43
0
    const CKey key = [&] {
44
0
        CKey k;
45
0
        k.Set(buffer.begin(), buffer.end(), true);
46
0
        return k;
47
0
    }();
48
0
    if (!key.IsValid()) {
49
0
        return;
50
0
    }
51
52
0
    {
53
0
        assert(key.begin() + key.size() == key.end());
54
0
        assert(key.IsCompressed());
55
0
        assert(key.size() == 32);
56
0
        assert(DecodeSecret(EncodeSecret(key)) == key);
57
0
    }
58
59
0
    {
60
0
        CKey invalid_key;
61
0
        assert(!(invalid_key == key));
62
0
        assert(!invalid_key.IsCompressed());
63
0
        assert(!invalid_key.IsValid());
64
0
        assert(invalid_key.size() == 0);
65
0
    }
66
67
0
    {
68
0
        CKey uncompressed_key;
69
0
        uncompressed_key.Set(buffer.begin(), buffer.end(), false);
70
0
        assert(!(uncompressed_key == key));
71
0
        assert(!uncompressed_key.IsCompressed());
72
0
        assert(key.size() == 32);
73
0
        assert(uncompressed_key.begin() + uncompressed_key.size() == uncompressed_key.end());
74
0
        assert(uncompressed_key.IsValid());
75
0
    }
76
77
0
    {
78
0
        CKey copied_key;
79
0
        copied_key.Set(key.begin(), key.end(), key.IsCompressed());
80
0
        assert(copied_key == key);
81
0
    }
82
83
0
    const uint256 random_uint256 = Hash(buffer);
84
85
0
    {
86
0
        CKey child_key;
87
0
        ChainCode child_chaincode;
88
0
        const bool ok = key.Derive(child_key, child_chaincode, 0, random_uint256);
89
0
        assert(ok);
90
0
        assert(child_key.IsValid());
91
0
        assert(!(child_key == key));
92
0
        assert(child_chaincode != random_uint256);
93
0
    }
94
95
0
    const CPubKey pubkey = key.GetPubKey();
96
97
0
    {
98
0
        assert(pubkey.size() == 33);
99
0
        assert(key.VerifyPubKey(pubkey));
100
0
        assert(pubkey.GetHash() != random_uint256);
101
0
        assert(pubkey.begin() + pubkey.size() == pubkey.end());
102
0
        assert(pubkey.data() == pubkey.begin());
103
0
        assert(pubkey.IsCompressed());
104
0
        assert(pubkey.IsValid());
105
0
        assert(pubkey.IsFullyValid());
106
0
        assert(HexToPubKey(HexStr(pubkey)) == pubkey);
107
0
    }
108
109
0
    {
110
0
        DataStream data_stream{};
111
0
        pubkey.Serialize(data_stream);
112
113
0
        CPubKey pubkey_deserialized;
114
0
        pubkey_deserialized.Unserialize(data_stream);
115
0
        assert(pubkey_deserialized == pubkey);
116
0
    }
117
118
0
    {
119
0
        const CScript tx_pubkey_script = GetScriptForRawPubKey(pubkey);
120
0
        assert(!tx_pubkey_script.IsPayToScriptHash());
121
0
        assert(!tx_pubkey_script.IsPayToWitnessScriptHash());
122
0
        assert(!tx_pubkey_script.IsPushOnly());
123
0
        assert(!tx_pubkey_script.IsUnspendable());
124
0
        assert(tx_pubkey_script.HasValidOps());
125
0
        assert(tx_pubkey_script.size() == 35);
126
127
0
        const CScript tx_multisig_script = GetScriptForMultisig(1, {pubkey});
128
0
        assert(!tx_multisig_script.IsPayToScriptHash());
129
0
        assert(!tx_multisig_script.IsPayToWitnessScriptHash());
130
0
        assert(!tx_multisig_script.IsPushOnly());
131
0
        assert(!tx_multisig_script.IsUnspendable());
132
0
        assert(tx_multisig_script.HasValidOps());
133
0
        assert(tx_multisig_script.size() == 37);
134
135
0
        FillableSigningProvider fillable_signing_provider;
136
0
        assert(!IsSegWitOutput(fillable_signing_provider, tx_pubkey_script));
137
0
        assert(!IsSegWitOutput(fillable_signing_provider, tx_multisig_script));
138
0
        assert(fillable_signing_provider.GetKeys().size() == 0);
139
0
        assert(!fillable_signing_provider.HaveKey(pubkey.GetID()));
140
141
0
        const bool ok_add_key = fillable_signing_provider.AddKey(key);
142
0
        assert(ok_add_key);
143
0
        assert(fillable_signing_provider.HaveKey(pubkey.GetID()));
144
145
0
        FillableSigningProvider fillable_signing_provider_pub;
146
0
        assert(!fillable_signing_provider_pub.HaveKey(pubkey.GetID()));
147
148
0
        const bool ok_add_key_pubkey = fillable_signing_provider_pub.AddKeyPubKey(key, pubkey);
149
0
        assert(ok_add_key_pubkey);
150
0
        assert(fillable_signing_provider_pub.HaveKey(pubkey.GetID()));
151
152
0
        TxoutType which_type_tx_pubkey;
153
0
        const bool is_standard_tx_pubkey = IsStandard(tx_pubkey_script, which_type_tx_pubkey);
154
0
        assert(is_standard_tx_pubkey);
155
0
        assert(which_type_tx_pubkey == TxoutType::PUBKEY);
156
157
0
        TxoutType which_type_tx_multisig;
158
0
        const bool is_standard_tx_multisig = IsStandard(tx_multisig_script, which_type_tx_multisig);
159
0
        assert(is_standard_tx_multisig);
160
0
        assert(which_type_tx_multisig == TxoutType::MULTISIG);
161
162
0
        std::vector<std::vector<unsigned char>> v_solutions_ret_tx_pubkey;
163
0
        const TxoutType outtype_tx_pubkey = Solver(tx_pubkey_script, v_solutions_ret_tx_pubkey);
164
0
        assert(outtype_tx_pubkey == TxoutType::PUBKEY);
165
0
        assert(v_solutions_ret_tx_pubkey.size() == 1);
166
0
        assert(v_solutions_ret_tx_pubkey[0].size() == 33);
167
168
0
        std::vector<std::vector<unsigned char>> v_solutions_ret_tx_multisig;
169
0
        const TxoutType outtype_tx_multisig = Solver(tx_multisig_script, v_solutions_ret_tx_multisig);
170
0
        assert(outtype_tx_multisig == TxoutType::MULTISIG);
171
0
        assert(v_solutions_ret_tx_multisig.size() == 3);
172
0
        assert(v_solutions_ret_tx_multisig[0].size() == 1);
173
0
        assert(v_solutions_ret_tx_multisig[1].size() == 33);
174
0
        assert(v_solutions_ret_tx_multisig[2].size() == 1);
175
176
0
        OutputType output_type{};
177
0
        const CTxDestination tx_destination{PKHash{pubkey}};
178
0
        assert(output_type == OutputType::LEGACY);
179
0
        assert(IsValidDestination(tx_destination));
180
0
        assert(PKHash{pubkey} == *std::get_if<PKHash>(&tx_destination));
181
182
0
        const CScript script_for_destination = GetScriptForDestination(tx_destination);
183
0
        assert(script_for_destination.size() == 25);
184
185
0
        const std::string destination_address = EncodeDestination(tx_destination);
186
0
        assert(DecodeDestination(destination_address) == tx_destination);
187
188
0
        CKeyID key_id = pubkey.GetID();
189
0
        assert(!key_id.IsNull());
190
0
        assert(key_id == CKeyID{key_id});
191
0
        assert(key_id == GetKeyForDestination(fillable_signing_provider, tx_destination));
192
193
0
        CPubKey pubkey_out;
194
0
        const bool ok_get_pubkey = fillable_signing_provider.GetPubKey(key_id, pubkey_out);
195
0
        assert(ok_get_pubkey);
196
197
0
        CKey key_out;
198
0
        const bool ok_get_key = fillable_signing_provider.GetKey(key_id, key_out);
199
0
        assert(ok_get_key);
200
0
        assert(fillable_signing_provider.GetKeys().size() == 1);
201
0
        assert(fillable_signing_provider.HaveKey(key_id));
202
203
0
        KeyOriginInfo key_origin_info;
204
0
        const bool ok_get_key_origin = fillable_signing_provider.GetKeyOrigin(key_id, key_origin_info);
205
0
        assert(!ok_get_key_origin);
206
0
    }
207
208
0
    {
209
0
        const std::vector<unsigned char> vch_pubkey{pubkey.begin(), pubkey.end()};
210
0
        assert(CPubKey::ValidSize(vch_pubkey));
211
0
        assert(!CPubKey::ValidSize({pubkey.begin(), pubkey.begin() + pubkey.size() - 1}));
212
213
0
        const CPubKey pubkey_ctor_1{vch_pubkey};
214
0
        assert(pubkey == pubkey_ctor_1);
215
216
0
        const CPubKey pubkey_ctor_2{vch_pubkey.begin(), vch_pubkey.end()};
217
0
        assert(pubkey == pubkey_ctor_2);
218
219
0
        CPubKey pubkey_set;
220
0
        pubkey_set.Set(vch_pubkey.begin(), vch_pubkey.end());
221
0
        assert(pubkey == pubkey_set);
222
0
    }
223
224
0
    {
225
0
        const CPubKey invalid_pubkey{};
226
0
        assert(!invalid_pubkey.IsValid());
227
0
        assert(!invalid_pubkey.IsFullyValid());
228
0
        assert(!(pubkey == invalid_pubkey));
229
0
        assert(pubkey != invalid_pubkey);
230
0
        assert(pubkey < invalid_pubkey);
231
0
    }
232
233
0
    {
234
        // Cover CPubKey's operator[](unsigned int pos)
235
0
        unsigned int sum = 0;
236
0
        for (size_t i = 0; i < pubkey.size(); ++i) {
237
0
            sum += pubkey[i];
238
0
        }
239
0
        assert(std::accumulate(pubkey.begin(), pubkey.end(), 0U) == sum);
240
0
    }
241
242
0
    {
243
0
        CPubKey decompressed_pubkey = pubkey;
244
0
        assert(decompressed_pubkey.IsCompressed());
245
246
0
        const bool ok = decompressed_pubkey.Decompress();
247
0
        assert(ok);
248
0
        assert(!decompressed_pubkey.IsCompressed());
249
0
        assert(decompressed_pubkey.size() == 65);
250
0
    }
251
252
0
    {
253
0
        std::vector<unsigned char> vch_sig;
254
0
        const bool ok = key.Sign(random_uint256, vch_sig, false);
255
0
        assert(ok);
256
0
        assert(pubkey.Verify(random_uint256, vch_sig));
257
0
        assert(CPubKey::CheckLowS(vch_sig));
258
259
0
        const std::vector<unsigned char> vch_invalid_sig{vch_sig.begin(), vch_sig.begin() + vch_sig.size() - 1};
260
0
        assert(!pubkey.Verify(random_uint256, vch_invalid_sig));
261
0
        assert(!CPubKey::CheckLowS(vch_invalid_sig));
262
0
    }
263
264
0
    {
265
0
        std::vector<unsigned char> vch_compact_sig;
266
0
        const bool ok_sign_compact = key.SignCompact(random_uint256, vch_compact_sig);
267
0
        assert(ok_sign_compact);
268
269
0
        CPubKey recover_pubkey;
270
0
        const bool ok_recover_compact = recover_pubkey.RecoverCompact(random_uint256, vch_compact_sig);
271
0
        assert(ok_recover_compact);
272
0
        assert(recover_pubkey == pubkey);
273
0
    }
274
275
0
    {
276
0
        CPubKey child_pubkey;
277
0
        ChainCode child_chaincode;
278
0
        const bool ok = pubkey.Derive(child_pubkey, child_chaincode, 0, random_uint256);
279
0
        assert(ok);
280
0
        assert(child_pubkey != pubkey);
281
0
        assert(child_pubkey.IsCompressed());
282
0
        assert(child_pubkey.IsFullyValid());
283
0
        assert(child_pubkey.IsValid());
284
0
        assert(child_pubkey.size() == 33);
285
0
        assert(child_chaincode != random_uint256);
286
0
    }
287
288
0
    const CPrivKey priv_key = key.GetPrivKey();
289
290
0
    {
291
0
        for (const bool skip_check : {true, false}) {
292
0
            CKey loaded_key;
293
0
            const bool ok = loaded_key.Load(priv_key, pubkey, skip_check);
294
0
            assert(ok);
295
0
            assert(key == loaded_key);
296
0
        }
297
0
    }
298
0
}
299
300
FUZZ_TARGET(ellswift_roundtrip, .init = initialize_key)
301
0
{
302
0
    FuzzedDataProvider fdp{buffer.data(), buffer.size()};
303
304
0
    CKey key = ConsumePrivateKey(fdp, /*compressed=*/true);
305
0
    if (!key.IsValid()) return;
306
307
0
    auto ent32 = fdp.ConsumeBytes<std::byte>(32);
308
0
    ent32.resize(32);
309
310
0
    auto encoded_ellswift = key.EllSwiftCreate(ent32);
311
0
    auto decoded_pubkey = encoded_ellswift.Decode();
312
313
0
    uint256 hash{ConsumeUInt256(fdp)};
314
0
    std::vector<unsigned char> sig;
315
0
    key.Sign(hash, sig);
316
0
    assert(decoded_pubkey.Verify(hash, sig));
317
0
}
318
319
FUZZ_TARGET(bip324_ecdh, .init = initialize_key)
320
0
{
321
0
    FuzzedDataProvider fdp{buffer.data(), buffer.size()};
322
323
    // We generate private key, k1.
324
0
    CKey k1 = ConsumePrivateKey(fdp, /*compressed=*/true);
325
0
    if (!k1.IsValid()) return;
326
327
    // They generate private key, k2.
328
0
    CKey k2 = ConsumePrivateKey(fdp, /*compressed=*/true);
329
0
    if (!k2.IsValid()) return;
330
331
    // We construct an ellswift encoding for our key, k1_ellswift.
332
0
    auto ent32_1 = fdp.ConsumeBytes<std::byte>(32);
333
0
    ent32_1.resize(32);
334
0
    auto k1_ellswift = k1.EllSwiftCreate(ent32_1);
335
336
    // They construct an ellswift encoding for their key, k2_ellswift.
337
0
    auto ent32_2 = fdp.ConsumeBytes<std::byte>(32);
338
0
    ent32_2.resize(32);
339
0
    auto k2_ellswift = k2.EllSwiftCreate(ent32_2);
340
341
    // They construct another (possibly distinct) ellswift encoding for their key, k2_ellswift_bad.
342
0
    auto ent32_2_bad = fdp.ConsumeBytes<std::byte>(32);
343
0
    ent32_2_bad.resize(32);
344
0
    auto k2_ellswift_bad = k2.EllSwiftCreate(ent32_2_bad);
345
0
    assert((ent32_2_bad == ent32_2) == (k2_ellswift_bad == k2_ellswift));
346
347
    // Determine who is who.
348
0
    bool initiating = fdp.ConsumeBool();
349
350
    // We compute our shared secret using our key and their public key.
351
0
    auto ecdh_secret_1 = k1.ComputeBIP324ECDHSecret(k2_ellswift, k1_ellswift, initiating);
352
    // They compute their shared secret using their key and our public key.
353
0
    auto ecdh_secret_2 = k2.ComputeBIP324ECDHSecret(k1_ellswift, k2_ellswift, !initiating);
354
    // Those must match, as everyone is behaving correctly.
355
0
    assert(ecdh_secret_1 == ecdh_secret_2);
356
357
0
    if (k1_ellswift != k2_ellswift) {
358
        // Unless the two keys are exactly identical, acting as the wrong party breaks things.
359
0
        auto ecdh_secret_bad = k1.ComputeBIP324ECDHSecret(k2_ellswift, k1_ellswift, !initiating);
360
0
        assert(ecdh_secret_bad != ecdh_secret_1);
361
0
    }
362
363
0
    if (k2_ellswift_bad != k2_ellswift) {
364
        // Unless both encodings created by them are identical, using the second one breaks things.
365
0
        auto ecdh_secret_bad = k1.ComputeBIP324ECDHSecret(k2_ellswift_bad, k1_ellswift, initiating);
366
        assert(ecdh_secret_bad != ecdh_secret_1);
367
0
    }
368
0
}