Merge 679f825ba3 into merged_master (Bitcoin PR bitcoin/bitcoin#27479)

This commit is contained in:
Byron Hambly 2025-06-28 09:46:07 +02:00
commit 2a1d79e0f0
14 changed files with 310 additions and 3 deletions

View file

@ -14,7 +14,7 @@
</ItemGroup>
<ItemDefinitionGroup>
<ClCompile>
<PreprocessorDefinitions>ENABLE_MODULE_GENERATOR;ENABLE_MODULE_RANGEPROOF;ENABLE_MODULE_SURJECTIONPROOF;ECMULT_WINDOW_SIZE=15;ECMULT_GEN_PREC_BITS=8;ENABLE_MODULE_WHITELIST;ENABLE_MODULE_ECDH;ENABLE_MODULE_ECDSA_ADAPTOR;ENABLE_MODULE_ECDSA_S2C;ENABLE_MODULE_RECOVERY;ENABLE_MODULE_EXTRAKEYS;ENABLE_MODULE_SCHNORRSIG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>ENABLE_MODULE_GENERATOR;ENABLE_MODULE_RANGEPROOF;ENABLE_MODULE_SURJECTIONPROOF;ECMULT_WINDOW_SIZE=15;ECMULT_GEN_PREC_BITS=8;ENABLE_MODULE_WHITELIST;ENABLE_MODULE_ECDH;ENABLE_MODULE_ECDSA_ADAPTOR;ENABLE_MODULE_ECDSA_S2C;ENABLE_MODULE_RECOVERY;ENABLE_MODULE_EXTRAKEYS;ENABLE_MODULE_SCHNORRSIG;ENABLE_MODULE_ELLSWIFT;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<UndefinePreprocessorDefinitions>USE_ASM_X86_64;%(UndefinePreprocessorDefinitions)</UndefinePreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\src\secp256k1;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DisableSpecificWarnings>4005;4146;4244;4267;4334</DisableSpecificWarnings>

View file

@ -18,6 +18,7 @@ bench_bench_bitcoin_SOURCES = \
bench/bench.cpp \
bench/bench.h \
bench/bench_bitcoin.cpp \
bench/bip324_ecdh.cpp \
bench/block_assemble.cpp \
bench/ccoins_caching.cpp \
bench/chacha20.cpp \
@ -29,6 +30,7 @@ bench_bench_bitcoin_SOURCES = \
bench/data.h \
bench/descriptors.cpp \
bench/duplicate_inputs.cpp \
bench/ellswift.cpp \
bench/examples.cpp \
bench/gcs_filter.cpp \
bench/hashpadding.cpp \

51
src/bench/bip324_ecdh.cpp Normal file
View file

@ -0,0 +1,51 @@
// Copyright (c) 2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <key.h>
#include <pubkey.h>
#include <random.h>
#include <span.h>
#include <array>
#include <cstddef>
static void BIP324_ECDH(benchmark::Bench& bench)
{
ECC_Start();
FastRandomContext rng;
std::array<std::byte, 32> key_data;
std::array<std::byte, EllSwiftPubKey::size()> our_ellswift_data;
std::array<std::byte, EllSwiftPubKey::size()> their_ellswift_data;
rng.fillrand(key_data);
rng.fillrand(our_ellswift_data);
rng.fillrand(their_ellswift_data);
bench.batch(1).unit("ecdh").run([&] {
CKey key;
key.Set(UCharCast(key_data.data()), UCharCast(key_data.data()) + 32, true);
EllSwiftPubKey our_ellswift(our_ellswift_data);
EllSwiftPubKey their_ellswift(their_ellswift_data);
auto ret = key.ComputeBIP324ECDHSecret(their_ellswift, our_ellswift, true);
// To make sure that the computation is not the same on every iteration (ellswift decoding
// is variable-time), distribute bytes from the shared secret over the 3 inputs. The most
// important one is their_ellswift, because that one is actually decoded, so it's given most
// bytes. The data is copied into the middle, so that both halves are affected:
// - Copy 8 bytes from the resulting shared secret into middle of the private key.
std::copy(ret.begin(), ret.begin() + 8, key_data.begin() + 12);
// - Copy 8 bytes from the resulting shared secret into the middle of our ellswift key.
std::copy(ret.begin() + 8, ret.begin() + 16, our_ellswift_data.begin() + 28);
// - Copy 16 bytes from the resulting shared secret into the middle of their ellswift key.
std::copy(ret.begin() + 16, ret.end(), their_ellswift_data.begin() + 24);
});
ECC_Stop();
}
BENCHMARK(BIP324_ECDH, benchmark::PriorityLevel::HIGH);

31
src/bench/ellswift.cpp Normal file
View file

@ -0,0 +1,31 @@
// Copyright (c) 2022-2023 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <key.h>
#include <random.h>
static void EllSwiftCreate(benchmark::Bench& bench)
{
ECC_Start();
CKey key;
key.MakeNewKey(true);
uint256 entropy = GetRandHash();
bench.batch(1).unit("pubkey").run([&] {
auto ret = key.EllSwiftCreate(AsBytes(Span{entropy}));
/* Use the first 32 bytes of the ellswift encoded public key as next private key. */
key.Set(UCharCast(ret.data()), UCharCast(ret.data()) + 32, true);
assert(key.IsValid());
/* Use the last 32 bytes of the ellswift encoded public key as next entropy. */
std::copy(ret.begin() + 32, ret.begin() + 64, AsBytePtr(entropy.data()));
});
ECC_Stop();
}
BENCHMARK(EllSwiftCreate, benchmark::PriorityLevel::HIGH);

View file

@ -12,6 +12,7 @@
#include <secp256k1.h>
#include <secp256k1_ecdh.h>
#include <secp256k1_ellswift.h>
#include <secp256k1_extrakeys.h>
#include <secp256k1_recovery.h>
#include <secp256k1_schnorrsig.h>
@ -345,6 +346,42 @@ bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const
return ret;
}
EllSwiftPubKey CKey::EllSwiftCreate(Span<const std::byte> ent32) const
{
assert(fValid);
assert(ent32.size() == 32);
std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey;
auto success = secp256k1_ellswift_create(secp256k1_context_sign,
UCharCast(encoded_pubkey.data()),
keydata.data(),
UCharCast(ent32.data()));
// Should always succeed for valid keys (asserted above).
assert(success);
return {encoded_pubkey};
}
ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const
{
assert(fValid);
ECDHSecret output;
// BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs
// accordingly:
bool success = secp256k1_ellswift_xdh(secp256k1_context_sign,
UCharCast(output.data()),
UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()),
UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()),
keydata.data(),
initiating ? 0 : 1,
secp256k1_ellswift_xdh_hash_function_bip324,
nullptr);
// Should always succeed for valid keys (assert above).
assert(success);
return output;
}
bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
out.nDepth = nDepth + 1;

View file

@ -22,6 +22,12 @@
*/
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
/** Size of ECDH shared secrets. */
constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
/** An encapsulated private key. */
class CKey
{
@ -161,6 +167,27 @@ public:
//! Load private key and check that public key matches.
bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
/** Create an ellswift-encoded public key for this key, with specified entropy.
*
* entropy must be a 32-byte span with additional entropy to use in the encoding. Every
* public key has ~2^256 different encodings, and this function will deterministically pick
* one of them, based on entropy. Note that even without truly random entropy, the
* resulting encoding will be indistinguishable from uniform to any adversary who does not
* know the private key (because the private key itself is always used as entropy as well).
*/
EllSwiftPubKey EllSwiftCreate(Span<const std::byte> entropy) const;
/** Compute a BIP324-style ECDH shared secret.
*
* - their_ellswift: EllSwiftPubKey that was received from the other side.
* - our_ellswift: EllSwiftPubKey that was sent to the other side (must have been generated
* from *this using EllSwiftCreate()).
* - initiating: whether we are the initiating party (true) or responding party (false).
*/
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
const EllSwiftPubKey& our_ellswift,
bool initiating) const;
};
struct CExtKey {

View file

@ -7,6 +7,7 @@
#include <hash.h>
#include <secp256k1.h>
#include <secp256k1_ellswift.h>
#include <secp256k1_extrakeys.h>
#include <secp256k1_recovery.h>
#include <secp256k1_schnorrsig.h>
@ -359,6 +360,20 @@ bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChi
return true;
}
CPubKey EllSwiftPubKey::Decode() const
{
secp256k1_pubkey pubkey;
secp256k1_ellswift_decode(secp256k1_context_static, &pubkey, UCharCast(m_pubkey.data()));
size_t sz = CPubKey::COMPRESSED_SIZE;
std::array<uint8_t, CPubKey::COMPRESSED_SIZE> vch_bytes;
secp256k1_ec_pubkey_serialize(secp256k1_context_static, vch_bytes.data(), &sz, &pubkey, SECP256K1_EC_COMPRESSED);
assert(sz == vch_bytes.size());
return CPubKey{vch_bytes.begin(), vch_bytes.end()};
}
void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);

View file

@ -298,6 +298,38 @@ public:
SERIALIZE_METHODS(XOnlyPubKey, obj) { READWRITE(obj.m_keydata); }
};
/** An ElligatorSwift-encoded public key. */
struct EllSwiftPubKey
{
private:
static constexpr size_t SIZE = 64;
std::array<std::byte, SIZE> m_pubkey;
public:
/** Construct a new ellswift public key from a given serialization. */
EllSwiftPubKey(const std::array<std::byte, SIZE>& ellswift) :
m_pubkey(ellswift) {}
/** Decode to normal compressed CPubKey (for debugging purposes). */
CPubKey Decode() const;
// Read-only access for serialization.
const std::byte* data() const { return m_pubkey.data(); }
static constexpr size_t size() { return SIZE; }
auto begin() const { return m_pubkey.cbegin(); }
auto end() const { return m_pubkey.cend(); }
bool friend operator==(const EllSwiftPubKey& a, const EllSwiftPubKey& b)
{
return a.m_pubkey == b.m_pubkey;
}
bool friend operator!=(const EllSwiftPubKey& a, const EllSwiftPubKey& b)
{
return a.m_pubkey != b.m_pubkey;
}
};
struct CExtPubKey {
unsigned char version[4];
unsigned char nDepth;

View file

@ -599,6 +599,12 @@ std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
return ret;
}
void FastRandomContext::fillrand(Span<std::byte> output)
{
if (requires_seed) RandomSeed();
rng.Keystream(UCharCast(output.data()), output.size());
}
FastRandomContext::FastRandomContext(const uint256& seed) noexcept : requires_seed(false), bitbuf_size(0)
{
rng.SetKey32(seed.begin());

View file

@ -213,6 +213,9 @@ public:
/** Generate random bytes. */
std::vector<unsigned char> randbytes(size_t len);
/** Fill a byte Span with random bytes. */
void fillrand(Span<std::byte> output);
/** Generate a random 32-bit integer. */
uint32_t rand32() noexcept { return randbits(32); }

View file

@ -14,6 +14,8 @@
#ifndef SECP256K1_FIELD_INNER5X52_IMPL_H
#define SECP256K1_FIELD_INNER5X52_IMPL_H
#include "util.h"
SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) {
/**
* Registers: rdx:rax = multiplication accumulator
@ -278,7 +280,7 @@ __asm__ __volatile__(
"addq %%rsi,%%r8\n"
/* r[4] = c */
"movq %%r8,32(%%rdi)\n"
: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3)
: "+S"(a), "=&m"(tmp1), "=&m"(tmp2), "=&m"(tmp3)
: "b"(b), "D"(r)
: "%rax", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory"
);
@ -493,7 +495,7 @@ __asm__ __volatile__(
"addq %%rsi,%%r8\n"
/* r[4] = c */
"movq %%r8,32(%%rdi)\n"
: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3)
: "+S"(a), "=&m"(tmp1), "=&m"(tmp2), "=&m"(tmp3)
: "D"(r)
: "%rax", "%rbx", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory"
);

View file

@ -274,6 +274,7 @@ Span<std::byte> MakeWritableByteSpan(V&& v) noexcept
// Helper functions to safely cast to unsigned char pointers.
inline unsigned char* UCharCast(char* c) { return (unsigned char*)c; }
inline unsigned char* UCharCast(unsigned char* c) { return c; }
inline unsigned char* UCharCast(std::byte* c) { return (unsigned char*)c; }
inline const unsigned char* UCharCast(const char* c) { return (unsigned char*)c; }
inline const unsigned char* UCharCast(const unsigned char* c) { return c; }
inline const unsigned char* UCharCast(const std::byte* c) { return reinterpret_cast<const unsigned char*>(c); }

View file

@ -15,13 +15,17 @@
#include <script/signingprovider.h>
#include <script/standard.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <util/chaintype.h>
#include <util/strencodings.h>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <numeric>
#include <optional>
#include <string>
#include <vector>
@ -303,3 +307,79 @@ FUZZ_TARGET_INIT(key, initialize_key)
}
}
}
FUZZ_TARGET_INIT(ellswift_roundtrip, initialize_key)
{
FuzzedDataProvider fdp{buffer.data(), buffer.size()};
auto key_bytes = fdp.ConsumeBytes<uint8_t>(32);
key_bytes.resize(32);
CKey key;
key.Set(key_bytes.begin(), key_bytes.end(), true);
if (!key.IsValid()) return;
auto ent32 = fdp.ConsumeBytes<std::byte>(32);
ent32.resize(32);
auto encoded_ellswift = key.EllSwiftCreate(ent32);
auto decoded_pubkey = encoded_ellswift.Decode();
assert(key.VerifyPubKey(decoded_pubkey));
}
FUZZ_TARGET_INIT(bip324_ecdh, initialize_key)
{
FuzzedDataProvider fdp{buffer.data(), buffer.size()};
// We generate private key, k1.
auto rnd32 = fdp.ConsumeBytes<uint8_t>(32);
rnd32.resize(32);
CKey k1;
k1.Set(rnd32.begin(), rnd32.end(), true);
if (!k1.IsValid()) return;
// They generate private key, k2.
rnd32 = fdp.ConsumeBytes<uint8_t>(32);
rnd32.resize(32);
CKey k2;
k2.Set(rnd32.begin(), rnd32.end(), true);
if (!k2.IsValid()) return;
// We construct an ellswift encoding for our key, k1_ellswift.
auto ent32_1 = fdp.ConsumeBytes<std::byte>(32);
ent32_1.resize(32);
auto k1_ellswift = k1.EllSwiftCreate(ent32_1);
// They construct an ellswift encoding for their key, k2_ellswift.
auto ent32_2 = fdp.ConsumeBytes<std::byte>(32);
ent32_2.resize(32);
auto k2_ellswift = k2.EllSwiftCreate(ent32_2);
// They construct another (possibly distinct) ellswift encoding for their key, k2_ellswift_bad.
auto ent32_2_bad = fdp.ConsumeBytes<std::byte>(32);
ent32_2_bad.resize(32);
auto k2_ellswift_bad = k2.EllSwiftCreate(ent32_2_bad);
assert((ent32_2_bad == ent32_2) == (k2_ellswift_bad == k2_ellswift));
// Determine who is who.
bool initiating = fdp.ConsumeBool();
// We compute our shared secret using our key and their public key.
auto ecdh_secret_1 = k1.ComputeBIP324ECDHSecret(k2_ellswift, k1_ellswift, initiating);
// They compute their shared secret using their key and our public key.
auto ecdh_secret_2 = k2.ComputeBIP324ECDHSecret(k1_ellswift, k2_ellswift, !initiating);
// Those must match, as everyone is behaving correctly.
assert(ecdh_secret_1 == ecdh_secret_2);
if (k1_ellswift != k2_ellswift) {
// Unless the two keys are exactly identical, acting as the wrong party breaks things.
auto ecdh_secret_bad = k1.ComputeBIP324ECDHSecret(k2_ellswift, k1_ellswift, !initiating);
assert(ecdh_secret_bad != ecdh_secret_1);
}
if (k2_ellswift_bad != k2_ellswift) {
// Unless both encodings created by them are identical, using the second one breaks things.
auto ecdh_secret_bad = k1.ComputeBIP324ECDHSecret(k2_ellswift_bad, k1_ellswift, initiating);
assert(ecdh_secret_bad != ecdh_secret_1);
}
}

View file

@ -344,4 +344,24 @@ BOOST_AUTO_TEST_CASE(bip340_test_vectors)
}
}
BOOST_AUTO_TEST_CASE(key_ellswift)
{
for (const auto& secret : {strSecret1, strSecret2, strSecret1C, strSecret2C}) {
CKey key = DecodeSecret(secret);
BOOST_CHECK(key.IsValid());
uint256 ent32 = InsecureRand256();
auto ellswift = key.EllSwiftCreate(AsBytes(Span{ent32}));
CPubKey decoded_pubkey = ellswift.Decode();
if (!key.IsCompressed()) {
// The decoding constructor returns a compressed pubkey. If the
// original was uncompressed, we must decompress the decoded one
// to compare.
decoded_pubkey.Decompress();
}
BOOST_CHECK(key.GetPubKey() == decoded_pubkey);
}
}
BOOST_AUTO_TEST_SUITE_END()