Skip to content

Commit 43bb106

Browse files
committed
Merge bitcoin/bitcoin#24213: refactor: use Span in random.*
3ae7791 refactor: use Span in random.* (pasta) Pull request description: ~This PR does two things~ 1. use a Span<unsigned char> for GetRandBytes and GetStrongRandBytes ~2. make GetRand a template for which any integral type can be used, where the default behavior is to return a random integral up to the max of the integral unless a max is provided. This simplifies a lot of code from `GetRand(std::numeric_limits<uint64_t>::max()` -> `GetRand<uint64_t>()`~ MarcoFalke this was inspired by your comment here: bitcoin/bitcoin#24185 (comment) about using Span, so hopefully I'll be able to get this PR done and merged 😂 ~Also, if requested I could revert the `GetRand(std::numeric_limits<uint64_t>::max()` -> `GetRand<uint64_t>()` related changes if it ends up causing too many conflicts~ ACKs for top commit: laanwj: Thank you! Code review re-ACK 3ae7791 Tree-SHA512: 12375a83b68b288916ba0de81cfcab4aac14389a66a36811ae850427435eb67dd55e47df9ac3ec47db4e214f4330139e548bec815fff8a3f571484ea558dca79
2 parents 346e780 + 3ae7791 commit 43bb106

File tree

12 files changed

+21
-19
lines changed

12 files changed

+21
-19
lines changed

src/addrdb.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data
4949
{
5050
// Generate random temporary filename
5151
uint16_t randv = 0;
52-
GetRandBytes((unsigned char*)&randv, sizeof(randv));
52+
GetRandBytes({(unsigned char*)&randv, sizeof(randv)});
5353
std::string tmpfn = strprintf("%s.%04x", prefix, randv);
5454

5555
// open temp output file, and associate with CAutoFile

src/dbwrapper.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
227227
std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
228228
{
229229
std::vector<uint8_t> ret(OBFUSCATE_KEY_NUM_BYTES);
230-
GetRandBytes(ret.data(), OBFUSCATE_KEY_NUM_BYTES);
230+
GetRandBytes(ret);
231231
return ret;
232232
}
233233

src/key.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ bool CKey::Check(const unsigned char *vch) {
159159

160160
void CKey::MakeNewKey(bool fCompressedIn) {
161161
do {
162-
GetStrongRandBytes(keydata.data(), keydata.size());
162+
GetStrongRandBytes(keydata);
163163
} while (!Check(keydata.data()));
164164
fValid = true;
165165
fCompressed = fCompressedIn;
@@ -244,7 +244,7 @@ bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
244244
}
245245
unsigned char rnd[8];
246246
std::string str = "Bitcoin key verification\n";
247-
GetRandBytes(rnd, sizeof(rnd));
247+
GetRandBytes(rnd);
248248
uint256 hash;
249249
CHash256().Write(MakeUCharSpan(str)).Write(rnd).Finalize(hash);
250250
std::vector<unsigned char> vchSig;
@@ -397,7 +397,7 @@ void ECC_Start() {
397397
{
398398
// Pass in a random blinding seed to the secp256k1 context.
399399
std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
400-
GetRandBytes(vseed.data(), 32);
400+
GetRandBytes(vseed);
401401
bool ret = secp256k1_context_randomize(ctx, vseed.data());
402402
assert(ret);
403403
}

src/net_processing.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4472,7 +4472,7 @@ void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::mic
44724472
if (pingSend) {
44734473
uint64_t nonce = 0;
44744474
while (nonce == 0) {
4475-
GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4475+
GetRandBytes({(unsigned char*)&nonce, sizeof(nonce)});
44764476
}
44774477
peer.m_ping_queued = false;
44784478
peer.m_ping_start = now;

src/random.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#include <logging.h>
1717
#include <randomenv.h>
1818
#include <support/allocators/secure.h>
19+
#include <span.h>
1920
#include <sync.h> // for Mutex
2021
#include <util/time.h> // for GetTimeMicros()
2122

@@ -578,8 +579,8 @@ static void ProcRand(unsigned char* out, int num, RNGLevel level) noexcept
578579
}
579580
}
580581

581-
void GetRandBytes(unsigned char* buf, int num) noexcept { ProcRand(buf, num, RNGLevel::FAST); }
582-
void GetStrongRandBytes(unsigned char* buf, int num) noexcept { ProcRand(buf, num, RNGLevel::SLOW); }
582+
void GetRandBytes(Span<unsigned char> bytes) noexcept { ProcRand(bytes.data(), bytes.size(), RNGLevel::FAST); }
583+
void GetStrongRandBytes(Span<unsigned char> bytes) noexcept { ProcRand(bytes.data(), bytes.size(), RNGLevel::SLOW); }
583584
void RandAddPeriodic() noexcept { ProcRand(nullptr, 0, RNGLevel::PERIODIC); }
584585
void RandAddEvent(const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); }
585586

@@ -598,7 +599,7 @@ int GetRandInt(int nMax) noexcept
598599
uint256 GetRandHash() noexcept
599600
{
600601
uint256 hash;
601-
GetRandBytes((unsigned char*)&hash, sizeof(hash));
602+
GetRandBytes(hash);
602603
return hash;
603604
}
604605

src/random.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
#include <crypto/chacha20.h>
1010
#include <crypto/common.h>
11+
#include <span.h>
1112
#include <uint256.h>
1213

1314
#include <chrono>
@@ -66,7 +67,7 @@
6667
*
6768
* Thread-safe.
6869
*/
69-
void GetRandBytes(unsigned char* buf, int num) noexcept;
70+
void GetRandBytes(Span<unsigned char> bytes) noexcept;
7071
/** Generate a uniform random integer in the range [0..range). Precondition: range > 0 */
7172
uint64_t GetRand(uint64_t nMax) noexcept;
7273
/** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */
@@ -105,7 +106,7 @@ uint256 GetRandHash() noexcept;
105106
*
106107
* Thread-safe.
107108
*/
108-
void GetStrongRandBytes(unsigned char* buf, int num) noexcept;
109+
void GetStrongRandBytes(Span<unsigned char> bytes) noexcept;
109110

110111
/**
111112
* Gather entropy from various expensive sources, and feed them to the PRNG state.

src/rpc/request.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ bool GenerateAuthCookie(std::string *cookie_out)
8282
{
8383
const size_t COOKIE_SIZE = 32;
8484
unsigned char rand_pwd[COOKIE_SIZE];
85-
GetRandBytes(rand_pwd, COOKIE_SIZE);
85+
GetRandBytes(rand_pwd);
8686
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
8787

8888
/** the umask determines what permissions are used to create this file -

src/test/key_tests.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(key_key_negation)
204204
// create a dummy hash for signature comparison
205205
unsigned char rnd[8];
206206
std::string str = "Bitcoin key verification\n";
207-
GetRandBytes(rnd, sizeof(rnd));
207+
GetRandBytes(rnd);
208208
uint256 hash;
209209
CHash256().Write(MakeUCharSpan(str)).Write(rnd).Finalize(hash);
210210

src/torcontrol.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,7 @@ void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorContro
582582
// _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
583583
cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
584584
clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
585-
GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
585+
GetRandBytes(clientNonce);
586586
_conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
587587
} else {
588588
if (status_cookie.first) {

src/util/bytevectorhash.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88

99
ByteVectorHash::ByteVectorHash()
1010
{
11-
GetRandBytes(reinterpret_cast<unsigned char*>(&m_k0), sizeof(m_k0));
12-
GetRandBytes(reinterpret_cast<unsigned char*>(&m_k1), sizeof(m_k1));
11+
GetRandBytes({reinterpret_cast<unsigned char*>(&m_k0), sizeof(m_k0)});
12+
GetRandBytes({reinterpret_cast<unsigned char*>(&m_k1), sizeof(m_k1)});
1313
}
1414

1515
size_t ByteVectorHash::operator()(const std::vector<unsigned char>& input) const

0 commit comments

Comments
 (0)