Skip to content

Commit 34fc392

Browse files
committed
Fuzz test for ECDH
1 parent b6e83db commit 34fc392

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/test/fuzz/key.cpp

+52
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,19 @@
1515
#include <script/sign.h>
1616
#include <script/signingprovider.h>
1717
#include <script/standard.h>
18+
#include <secp256k1.h>
19+
#include <secp256k1_ellswift.h>
1820
#include <streams.h>
21+
#include <test/fuzz/FuzzedDataProvider.h>
1922
#include <test/fuzz/fuzz.h>
2023
#include <util/strencodings.h>
2124

25+
#include <array>
2226
#include <cassert>
27+
#include <cstddef>
2328
#include <cstdint>
2429
#include <numeric>
30+
#include <optional>
2531
#include <string>
2632
#include <vector>
2733

@@ -303,3 +309,49 @@ FUZZ_TARGET_INIT(key, initialize_key)
303309
}
304310
}
305311
}
312+
313+
std::optional<std::array<std::byte, 64>> GetEll64(const CPubKey& pubkey) {
314+
std::array<std::byte, 64> ell64;
315+
316+
auto ctx = secp256k1_context_static;
317+
secp256k1_pubkey pubkey_internal;
318+
if (!secp256k1_ec_pubkey_parse(ctx, &pubkey_internal, pubkey.data(), pubkey.size())) {
319+
return {};
320+
}
321+
322+
std::array<unsigned char, 32> rnd32;
323+
GetRandBytes(rnd32);
324+
secp256k1_ellswift_encode(ctx, reinterpret_cast<unsigned char*>(ell64.data()), &pubkey_internal, rnd32.data());
325+
return ell64;
326+
}
327+
328+
FUZZ_TARGET_INIT(bip324_ecdh, initialize_key)
329+
{
330+
FuzzedDataProvider fdp{buffer.data(), buffer.size()};
331+
auto rnd32 = fdp.ConsumeBytes<uint8_t>(32);
332+
rnd32.resize(32);
333+
CKey k1;
334+
k1.Set(rnd32.begin(), rnd32.end(), true);
335+
336+
if (!k1.IsValid()) {
337+
return;
338+
}
339+
340+
rnd32 = fdp.ConsumeBytes<uint8_t>(32);
341+
rnd32.resize(32);
342+
CKey k2;
343+
k2.Set(rnd32.begin(), rnd32.end(), true);
344+
345+
if (!k2.IsValid()) {
346+
return;
347+
}
348+
349+
auto k1_ellswift = GetEll64(k1.GetPubKey());
350+
auto k2_ellswift = GetEll64(k2.GetPubKey());
351+
assert(k1_ellswift.has_value() && k2_ellswift.has_value());
352+
353+
bool initiating = fdp.ConsumeBool();
354+
auto ecdh_secret_1 = k1.ComputeBIP324ECDHSecret(k2_ellswift.value(), k1_ellswift.value(), initiating);
355+
auto ecdh_secret_2 = k2.ComputeBIP324ECDHSecret(k1_ellswift.value(), k2_ellswift.value(), !initiating);
356+
assert(ecdh_secret_1.value() == ecdh_secret_2.value());
357+
}

0 commit comments

Comments
 (0)