Files
triangles_v5/src/crypto_ecdh.cpp
T
sami7777 150828b806 C++20 modernization: nullptr, constexpr, smart pointers, thread safety, enum class
- Replace ~320 NULL occurrences with nullptr across 47 files (-184 net lines)
- static const -> constexpr for version, coin, utility constants
- Collapse 9 PushMessage overloads into 1 variadic template with fold expressions
- Convert boost::array -> std::array, boost::type_traits -> std:: equivalents
- pwalletMain, pScriptCheckQueue, pScriptCheckThreads -> unique_ptr
- mapOrphanBlocks values: raw CBlock* -> unique_ptr<CBlock>
- Fix data races: add locks to wallet registration, pindexBest reads, mempool exists
- pwalletdbEncryption: raw new/delete -> local unique_ptr, remove exit() calls
- PoS reward overflow: CBigNum intermediate for nCoinAge * nRewardCoinYear
- memset -> OPENSSL_cleanse for secure zeroing
- Fix const-cast UB in SetMerkleBranch
- Log silent catch(...) blocks instead of silently swallowing
- Enum class: GetMinFeeMode, WalletFeature
- std::string_view for 8 utility function parameters
- Range-for with structured bindings: 63 iterator loops modernized
- std::make_pair -> brace init: 35 sites
- Delegating constructors: CWallet, CBlockIndex
- Merkle tree caching, std::array for GetMedianTimePast
- CScript copy ctor -> = default, operator!= -> = default
2026-05-08 21:34:24 -07:00

57 lines
1.7 KiB
C++

// Copyright (c) 2026 The Triangles developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypto_ecdh.h"
#include <cstring>
#include <mutex>
#include <secp256k1.h>
#include <secp256k1_ecdh.h>
namespace {
// One process-wide context is sufficient for ECDH — no signing or verification
// flags needed. Created lazily on first use; libsecp256k1 contexts are
// thread-safe for read-only operations like ECDH.
secp256k1_context* GetECDHContext()
{
static std::once_flag once;
static secp256k1_context* ctx = nullptr;
std::call_once(once, []() {
ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
});
return ctx;
}
// Hash function callback that returns the raw X coordinate of the shared
// point. Mirrors OpenSSL's ECDH_compute_key behaviour when the KDF is nullptr.
int hash_xonly(unsigned char* output,
const unsigned char* x32,
const unsigned char* /*y32*/,
void* /*data*/)
{
std::memcpy(output, x32, 32);
return 1;
}
} // namespace
bool ECDH_xonly_secp256k1(unsigned char out32[32],
const unsigned char privkey32[32],
const unsigned char* pubkey,
std::size_t pubkey_len)
{
if (pubkey_len != 33 && pubkey_len != 65) return false;
secp256k1_context* ctx = GetECDHContext();
if (!ctx) return false;
secp256k1_pubkey pk;
if (!secp256k1_ec_pubkey_parse(ctx, &pk, pubkey, pubkey_len))
return false;
return secp256k1_ecdh(ctx, out32, &pk, privkey32, hash_xonly, nullptr) == 1;
}