Skip to content

Commit 679f825

Browse files
committed
Merge bitcoin/bitcoin#27479: BIP324: ElligatorSwift integrations
3168b08 Bench test for EllSwift ECDH (Pieter Wuille) 42d759f Bench tests for CKey->EllSwift (dhruv) 2e5a8a4 Fuzz test for Ellswift ECDH (dhruv) c3ac9f5 Fuzz test for CKey->EllSwift->CPubKey creation/decoding (dhruv) aae432a Unit test for ellswift creation/decoding roundtrip (dhruv) eff72a0 Add ElligatorSwift key creation and ECDH logic (Pieter Wuille) 42239f8 Enable ellswift module in libsecp256k1 (dhruv) 901336e Squashed 'src/secp256k1/' changes from 4258c54f4e..705ce7ed8c (Pieter Wuille) Pull request description: This replaces #23432 and part of #23561. This PR introduces all of the ElligatorSwift-related changes (libsecp256k1 updates, generation, decoding, ECDH, tests, fuzzing, benchmarks) needed for BIP324. ElligatorSwift is a special 64-byte encoding format for public keys introduced in libsecp256k1 in bitcoin-core/secp256k1#1129. It has the property that *every* 64-byte array is a valid encoding for some public key, and every key has approximately $2^{256}$ encodings. Furthermore, it is possible to efficiently generate a uniformly random encoding for a given public key or private key. This is used for the key exchange phase in BIP324, to achieve a byte stream that is entirely pseudorandom, even before the shared encryption key is established. ACKs for top commit: instagibbs: reACK bitcoin/bitcoin@3168b08 achow101: ACK 3168b08 theStack: re-ACK 3168b08 Tree-SHA512: 308ac3d33e9a2deecb65826cbf0390480a38de201918429c35c796f3421cdf94c5501d027a043ae8f012cfaa0584656da1de6393bfba3532ab4c20f9533f06a6
2 parents 296735f + 3168b08 commit 679f825

File tree

90 files changed

+4198
-1176
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

90 files changed

+4198
-1176
lines changed

build_msvc/libsecp256k1/libsecp256k1.vcxproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
</ItemGroup>
1515
<ItemDefinitionGroup>
1616
<ClCompile>
17-
<PreprocessorDefinitions>ENABLE_MODULE_RECOVERY;ENABLE_MODULE_EXTRAKEYS;ENABLE_MODULE_SCHNORRSIG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
17+
<PreprocessorDefinitions>ENABLE_MODULE_RECOVERY;ENABLE_MODULE_EXTRAKEYS;ENABLE_MODULE_SCHNORRSIG;ENABLE_MODULE_ELLSWIFT;%(PreprocessorDefinitions)</PreprocessorDefinitions>
1818
<UndefinePreprocessorDefinitions>USE_ASM_X86_64;%(UndefinePreprocessorDefinitions)</UndefinePreprocessorDefinitions>
1919
<AdditionalIncludeDirectories>..\..\src\secp256k1;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
2020
<DisableSpecificWarnings>4146;4244;4267;4334</DisableSpecificWarnings>

src/Makefile.bench.include

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ bench_bench_bitcoin_SOURCES = \
1818
bench/bench.cpp \
1919
bench/bench.h \
2020
bench/bench_bitcoin.cpp \
21+
bench/bip324_ecdh.cpp \
2122
bench/block_assemble.cpp \
2223
bench/ccoins_caching.cpp \
2324
bench/chacha20.cpp \
@@ -29,6 +30,7 @@ bench_bench_bitcoin_SOURCES = \
2930
bench/data.h \
3031
bench/descriptors.cpp \
3132
bench/duplicate_inputs.cpp \
33+
bench/ellswift.cpp \
3234
bench/examples.cpp \
3335
bench/gcs_filter.cpp \
3436
bench/hashpadding.cpp \

src/bench/bip324_ecdh.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Copyright (c) 2022 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 <bench/bench.h>
6+
7+
#include <key.h>
8+
#include <pubkey.h>
9+
#include <random.h>
10+
#include <span.h>
11+
12+
#include <array>
13+
#include <cstddef>
14+
15+
static void BIP324_ECDH(benchmark::Bench& bench)
16+
{
17+
ECC_Start();
18+
FastRandomContext rng;
19+
20+
std::array<std::byte, 32> key_data;
21+
std::array<std::byte, EllSwiftPubKey::size()> our_ellswift_data;
22+
std::array<std::byte, EllSwiftPubKey::size()> their_ellswift_data;
23+
24+
rng.fillrand(key_data);
25+
rng.fillrand(our_ellswift_data);
26+
rng.fillrand(their_ellswift_data);
27+
28+
bench.batch(1).unit("ecdh").run([&] {
29+
CKey key;
30+
key.Set(UCharCast(key_data.data()), UCharCast(key_data.data()) + 32, true);
31+
EllSwiftPubKey our_ellswift(our_ellswift_data);
32+
EllSwiftPubKey their_ellswift(their_ellswift_data);
33+
34+
auto ret = key.ComputeBIP324ECDHSecret(their_ellswift, our_ellswift, true);
35+
36+
// To make sure that the computation is not the same on every iteration (ellswift decoding
37+
// is variable-time), distribute bytes from the shared secret over the 3 inputs. The most
38+
// important one is their_ellswift, because that one is actually decoded, so it's given most
39+
// bytes. The data is copied into the middle, so that both halves are affected:
40+
// - Copy 8 bytes from the resulting shared secret into middle of the private key.
41+
std::copy(ret.begin(), ret.begin() + 8, key_data.begin() + 12);
42+
// - Copy 8 bytes from the resulting shared secret into the middle of our ellswift key.
43+
std::copy(ret.begin() + 8, ret.begin() + 16, our_ellswift_data.begin() + 28);
44+
// - Copy 16 bytes from the resulting shared secret into the middle of their ellswift key.
45+
std::copy(ret.begin() + 16, ret.end(), their_ellswift_data.begin() + 24);
46+
});
47+
48+
ECC_Stop();
49+
}
50+
51+
BENCHMARK(BIP324_ECDH, benchmark::PriorityLevel::HIGH);

src/bench/ellswift.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Copyright (c) 2022-2023 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 <bench/bench.h>
6+
7+
#include <key.h>
8+
#include <random.h>
9+
10+
static void EllSwiftCreate(benchmark::Bench& bench)
11+
{
12+
ECC_Start();
13+
14+
CKey key;
15+
key.MakeNewKey(true);
16+
17+
uint256 entropy = GetRandHash();
18+
19+
bench.batch(1).unit("pubkey").run([&] {
20+
auto ret = key.EllSwiftCreate(AsBytes(Span{entropy}));
21+
/* Use the first 32 bytes of the ellswift encoded public key as next private key. */
22+
key.Set(UCharCast(ret.data()), UCharCast(ret.data()) + 32, true);
23+
assert(key.IsValid());
24+
/* Use the last 32 bytes of the ellswift encoded public key as next entropy. */
25+
std::copy(ret.begin() + 32, ret.begin() + 64, AsBytePtr(entropy.data()));
26+
});
27+
28+
ECC_Stop();
29+
}
30+
31+
BENCHMARK(EllSwiftCreate, benchmark::PriorityLevel::HIGH);

src/key.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <random.h>
1212

1313
#include <secp256k1.h>
14+
#include <secp256k1_ellswift.h>
1415
#include <secp256k1_extrakeys.h>
1516
#include <secp256k1_recovery.h>
1617
#include <secp256k1_schnorrsig.h>
@@ -331,6 +332,42 @@ bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const
331332
return ret;
332333
}
333334

335+
EllSwiftPubKey CKey::EllSwiftCreate(Span<const std::byte> ent32) const
336+
{
337+
assert(fValid);
338+
assert(ent32.size() == 32);
339+
std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey;
340+
341+
auto success = secp256k1_ellswift_create(secp256k1_context_sign,
342+
UCharCast(encoded_pubkey.data()),
343+
keydata.data(),
344+
UCharCast(ent32.data()));
345+
346+
// Should always succeed for valid keys (asserted above).
347+
assert(success);
348+
return {encoded_pubkey};
349+
}
350+
351+
ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const
352+
{
353+
assert(fValid);
354+
355+
ECDHSecret output;
356+
// BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs
357+
// accordingly:
358+
bool success = secp256k1_ellswift_xdh(secp256k1_context_sign,
359+
UCharCast(output.data()),
360+
UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()),
361+
UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()),
362+
keydata.data(),
363+
initiating ? 0 : 1,
364+
secp256k1_ellswift_xdh_hash_function_bip324,
365+
nullptr);
366+
// Should always succeed for valid keys (assert above).
367+
assert(success);
368+
return output;
369+
}
370+
334371
bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
335372
if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
336373
out.nDepth = nDepth + 1;

src/key.h

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@
2222
*/
2323
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
2424

25+
/** Size of ECDH shared secrets. */
26+
constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
27+
28+
// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
29+
using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;
30+
2531
/** An encapsulated private key. */
2632
class CKey
2733
{
@@ -156,6 +162,27 @@ class CKey
156162

157163
//! Load private key and check that public key matches.
158164
bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
165+
166+
/** Create an ellswift-encoded public key for this key, with specified entropy.
167+
*
168+
* entropy must be a 32-byte span with additional entropy to use in the encoding. Every
169+
* public key has ~2^256 different encodings, and this function will deterministically pick
170+
* one of them, based on entropy. Note that even without truly random entropy, the
171+
* resulting encoding will be indistinguishable from uniform to any adversary who does not
172+
* know the private key (because the private key itself is always used as entropy as well).
173+
*/
174+
EllSwiftPubKey EllSwiftCreate(Span<const std::byte> entropy) const;
175+
176+
/** Compute a BIP324-style ECDH shared secret.
177+
*
178+
* - their_ellswift: EllSwiftPubKey that was received from the other side.
179+
* - our_ellswift: EllSwiftPubKey that was sent to the other side (must have been generated
180+
* from *this using EllSwiftCreate()).
181+
* - initiating: whether we are the initiating party (true) or responding party (false).
182+
*/
183+
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
184+
const EllSwiftPubKey& our_ellswift,
185+
bool initiating) const;
159186
};
160187

161188
struct CExtKey {

src/pubkey.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
#include <hash.h>
99
#include <secp256k1.h>
10+
#include <secp256k1_ellswift.h>
1011
#include <secp256k1_extrakeys.h>
1112
#include <secp256k1_recovery.h>
1213
#include <secp256k1_schnorrsig.h>
@@ -335,6 +336,20 @@ bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChi
335336
return true;
336337
}
337338

339+
CPubKey EllSwiftPubKey::Decode() const
340+
{
341+
secp256k1_pubkey pubkey;
342+
secp256k1_ellswift_decode(secp256k1_context_static, &pubkey, UCharCast(m_pubkey.data()));
343+
344+
size_t sz = CPubKey::COMPRESSED_SIZE;
345+
std::array<uint8_t, CPubKey::COMPRESSED_SIZE> vch_bytes;
346+
347+
secp256k1_ec_pubkey_serialize(secp256k1_context_static, vch_bytes.data(), &sz, &pubkey, SECP256K1_EC_COMPRESSED);
348+
assert(sz == vch_bytes.size());
349+
350+
return CPubKey{vch_bytes.begin(), vch_bytes.end()};
351+
}
352+
338353
void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
339354
code[0] = nDepth;
340355
memcpy(code+1, vchFingerprint, 4);

src/pubkey.h

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,38 @@ class XOnlyPubKey
291291
SERIALIZE_METHODS(XOnlyPubKey, obj) { READWRITE(obj.m_keydata); }
292292
};
293293

294+
/** An ElligatorSwift-encoded public key. */
295+
struct EllSwiftPubKey
296+
{
297+
private:
298+
static constexpr size_t SIZE = 64;
299+
std::array<std::byte, SIZE> m_pubkey;
300+
301+
public:
302+
/** Construct a new ellswift public key from a given serialization. */
303+
EllSwiftPubKey(const std::array<std::byte, SIZE>& ellswift) :
304+
m_pubkey(ellswift) {}
305+
306+
/** Decode to normal compressed CPubKey (for debugging purposes). */
307+
CPubKey Decode() const;
308+
309+
// Read-only access for serialization.
310+
const std::byte* data() const { return m_pubkey.data(); }
311+
static constexpr size_t size() { return SIZE; }
312+
auto begin() const { return m_pubkey.cbegin(); }
313+
auto end() const { return m_pubkey.cend(); }
314+
315+
bool friend operator==(const EllSwiftPubKey& a, const EllSwiftPubKey& b)
316+
{
317+
return a.m_pubkey == b.m_pubkey;
318+
}
319+
320+
bool friend operator!=(const EllSwiftPubKey& a, const EllSwiftPubKey& b)
321+
{
322+
return a.m_pubkey != b.m_pubkey;
323+
}
324+
};
325+
294326
struct CExtPubKey {
295327
unsigned char version[4];
296328
unsigned char nDepth;

src/random.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,6 +599,12 @@ std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
599599
return ret;
600600
}
601601

602+
void FastRandomContext::fillrand(Span<std::byte> output)
603+
{
604+
if (requires_seed) RandomSeed();
605+
rng.Keystream(UCharCast(output.data()), output.size());
606+
}
607+
602608
FastRandomContext::FastRandomContext(const uint256& seed) noexcept : requires_seed(false), bitbuf_size(0)
603609
{
604610
rng.SetKey32(seed.begin());

src/random.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,9 @@ class FastRandomContext
213213
/** Generate random bytes. */
214214
std::vector<unsigned char> randbytes(size_t len);
215215

216+
/** Fill a byte Span with random bytes. */
217+
void fillrand(Span<std::byte> output);
218+
216219
/** Generate a random 32-bit integer. */
217220
uint32_t rand32() noexcept { return randbits(32); }
218221

0 commit comments

Comments
 (0)