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

+1-1
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

+2
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

+51
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

+31
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

+37
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

+27
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

+15
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

+32
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

+6
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

+3
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

src/secp256k1/.cirrus.yml

+15-7
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ env:
2121
ECDH: no
2222
RECOVERY: no
2323
SCHNORRSIG: no
24+
ELLSWIFT: no
2425
### test options
2526
SECP256K1_TEST_ITERS:
2627
BENCH: yes
@@ -74,12 +75,12 @@ task:
7475
<< : *LINUX_CONTAINER
7576
matrix: &ENV_MATRIX
7677
- env: {WIDEMUL: int64, RECOVERY: yes}
77-
- env: {WIDEMUL: int64, ECDH: yes, SCHNORRSIG: yes}
78+
- env: {WIDEMUL: int64, ECDH: yes, SCHNORRSIG: yes, ELLSWIFT: yes}
7879
- env: {WIDEMUL: int128}
79-
- env: {WIDEMUL: int128_struct}
80-
- env: {WIDEMUL: int128, RECOVERY: yes, SCHNORRSIG: yes}
80+
- env: {WIDEMUL: int128_struct, ELLSWIFT: yes}
81+
- env: {WIDEMUL: int128, RECOVERY: yes, SCHNORRSIG: yes, ELLSWIFT: yes}
8182
- env: {WIDEMUL: int128, ECDH: yes, SCHNORRSIG: yes}
82-
- env: {WIDEMUL: int128, ASM: x86_64}
83+
- env: {WIDEMUL: int128, ASM: x86_64 , ELLSWIFT: yes}
8384
- env: { RECOVERY: yes, SCHNORRSIG: yes}
8485
- env: {CTIMETESTS: no, RECOVERY: yes, ECDH: yes, SCHNORRSIG: yes, CPPFLAGS: -DVERIFY}
8586
- env: {BUILD: distcheck, WITH_VALGRIND: no, CTIMETESTS: no, BENCH: no}
@@ -154,6 +155,7 @@ task:
154155
ECDH: yes
155156
RECOVERY: yes
156157
SCHNORRSIG: yes
158+
ELLSWIFT: yes
157159
CTIMETESTS: no
158160
<< : *MERGE_BASE
159161
test_script:
@@ -173,10 +175,11 @@ task:
173175
ECDH: yes
174176
RECOVERY: yes
175177
SCHNORRSIG: yes
178+
ELLSWIFT: yes
176179
CTIMETESTS: no
177180
matrix:
178181
- env: {}
179-
- env: {EXPERIMENTAL: yes, ASM: arm}
182+
- env: {EXPERIMENTAL: yes, ASM: arm32}
180183
<< : *MERGE_BASE
181184
test_script:
182185
- ./ci/cirrus.sh
@@ -193,6 +196,7 @@ task:
193196
ECDH: yes
194197
RECOVERY: yes
195198
SCHNORRSIG: yes
199+
ELLSWIFT: yes
196200
CTIMETESTS: no
197201
<< : *MERGE_BASE
198202
test_script:
@@ -210,6 +214,7 @@ task:
210214
ECDH: yes
211215
RECOVERY: yes
212216
SCHNORRSIG: yes
217+
ELLSWIFT: yes
213218
CTIMETESTS: no
214219
<< : *MERGE_BASE
215220
test_script:
@@ -247,6 +252,7 @@ task:
247252
RECOVERY: yes
248253
EXPERIMENTAL: yes
249254
SCHNORRSIG: yes
255+
ELLSWIFT: yes
250256
CTIMETESTS: no
251257
# Use a MinGW-w64 host to tell ./configure we're building for Windows.
252258
# This will detect some MinGW-w64 tools but then make will need only
@@ -286,6 +292,7 @@ task:
286292
ECDH: yes
287293
RECOVERY: yes
288294
SCHNORRSIG: yes
295+
ELLSWIFT: yes
289296
CTIMETESTS: no
290297
matrix:
291298
- name: "Valgrind (memcheck)"
@@ -361,6 +368,7 @@ task:
361368
ECDH: yes
362369
RECOVERY: yes
363370
SCHNORRSIG: yes
371+
ELLSWIFT: yes
364372
<< : *MERGE_BASE
365373
test_script:
366374
- ./ci/cirrus.sh
@@ -397,13 +405,13 @@ task:
397405
- PowerShell -NoLogo -Command if ($env:CIRRUS_PR -ne $null) { git fetch $env:CIRRUS_REPO_CLONE_URL pull/$env:CIRRUS_PR/merge; git reset --hard FETCH_HEAD; }
398406
configure_script:
399407
- '%x64_NATIVE_TOOLS%'
400-
- cmake -G "Visual Studio 17 2022" -A x64 -S . -B build -DSECP256K1_ENABLE_MODULE_RECOVERY=ON -DSECP256K1_BUILD_EXAMPLES=ON
408+
- cmake -E env CFLAGS="/WX" cmake -G "Visual Studio 17 2022" -A x64 -S . -B build -DSECP256K1_ENABLE_MODULE_RECOVERY=ON -DSECP256K1_BUILD_EXAMPLES=ON
401409
build_script:
402410
- '%x64_NATIVE_TOOLS%'
403411
- cmake --build build --config RelWithDebInfo -- -property:UseMultiToolTask=true;CL_MPcount=5
404412
check_script:
405413
- '%x64_NATIVE_TOOLS%'
406-
- ctest --test-dir build -j 5
414+
- ctest -C RelWithDebInfo --test-dir build -j 5
407415
- build\src\RelWithDebInfo\bench_ecmult.exe
408416
- build\src\RelWithDebInfo\bench_internal.exe
409417
- build\src\RelWithDebInfo\bench.exe

0 commit comments

Comments
 (0)