Skip to content

Commit e9f5b4b

Browse files
laanwjPastaPastaPasta
authored andcommitted
Merge 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#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
1 parent 7e0474a commit e9f5b4b

15 files changed

+24
-23
lines changed

src/addrdb.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data
9999
{
100100
// Generate random temporary filename
101101
uint16_t randv = 0;
102-
GetRandBytes((unsigned char*)&randv, sizeof(randv));
102+
GetRandBytes({(unsigned char*)&randv, sizeof(randv)});
103103
std::string tmpfn = strprintf("%s.%04x", prefix, randv);
104104

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

src/bls/bls.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ void CBLSSecretKey::MakeNewKey()
6363
{
6464
unsigned char buf[SerSize];
6565
while (true) {
66-
GetStrongRandBytes(buf, sizeof(buf));
66+
GetStrongRandBytes({buf, sizeof(buf)});
6767
try {
6868
impl = bls::PrivateKey::FromBytes(bls::Bytes(reinterpret_cast<const uint8_t*>(buf), SerSize));
6969
break;

src/bls/bls_ies.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ void CBLSIESMultiRecipientBlobs::InitEncrypt(size_t count)
9797
{
9898
ephemeralSecretKey.MakeNewKey();
9999
ephemeralPubKey = ephemeralSecretKey.GetPublicKey();
100-
GetStrongRandBytes(ivSeed.begin(), ivSeed.size());
100+
GetStrongRandBytes({ivSeed.begin(), ivSeed.size()});
101101

102102
uint256 iv = ivSeed;
103103
ivVector.resize(count);

src/dbwrapper.cpp

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

src/key.cpp

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

158158
void CKey::MakeNewKey(bool fCompressedIn) {
159159
do {
160-
GetStrongRandBytes(keydata.data(), keydata.size());
160+
GetStrongRandBytes(keydata);
161161
} while (!Check(keydata.data()));
162162
fValid = true;
163163
fCompressed = fCompressedIn;
@@ -242,7 +242,7 @@ bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
242242
}
243243
unsigned char rnd[8];
244244
std::string str = "Bitcoin key verification\n";
245-
GetRandBytes(rnd, sizeof(rnd));
245+
GetRandBytes(rnd);
246246
uint256 hash;
247247
CHash256().Write(MakeUCharSpan(str)).Write(rnd).Finalize(hash);
248248
std::vector<unsigned char> vchSig;
@@ -406,7 +406,7 @@ void ECC_Start() {
406406
{
407407
// Pass in a random blinding seed to the secp256k1 context.
408408
std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
409-
GetRandBytes(vseed.data(), 32);
409+
GetRandBytes(vseed);
410410
bool ret = secp256k1_context_randomize(ctx, vseed.data());
411411
assert(ret);
412412
}

src/net_processing.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,7 +1247,7 @@ void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer)
12471247
CAddress addrMe = CAddress(CService(), nLocalNodeServices);
12481248

12491249
uint256 mnauthChallenge;
1250-
GetRandBytes(mnauthChallenge.begin(), mnauthChallenge.size());
1250+
GetRandBytes({mnauthChallenge.begin(), mnauthChallenge.size()});
12511251
pnode.SetSentMNAuthChallenge(mnauthChallenge);
12521252

12531253
int nProtocolVersion = PROTOCOL_VERSION;
@@ -5220,7 +5220,7 @@ void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::mic
52205220
if (pingSend) {
52215221
uint64_t nonce = 0;
52225222
while (nonce == 0) {
5223-
GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5223+
GetRandBytes({(unsigned char*)&nonce, sizeof(nonce)});
52245224
}
52255225
peer.m_ping_queued = false;
52265226
peer.m_ping_start = now;

src/random.cpp

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

@@ -582,8 +583,8 @@ static void ProcRand(unsigned char* out, int num, RNGLevel level) noexcept
582583
}
583584
}
584585

585-
void GetRandBytes(unsigned char* buf, int num) noexcept { ProcRand(buf, num, RNGLevel::FAST); }
586-
void GetStrongRandBytes(unsigned char* buf, int num) noexcept { ProcRand(buf, num, RNGLevel::SLOW); }
586+
void GetRandBytes(Span<unsigned char> bytes) noexcept { ProcRand(bytes.data(), bytes.size(), RNGLevel::FAST); }
587+
void GetStrongRandBytes(Span<unsigned char> bytes) noexcept { ProcRand(bytes.data(), bytes.size(), RNGLevel::SLOW); }
587588
void RandAddPeriodic() noexcept { ProcRand(nullptr, 0, RNGLevel::PERIODIC); }
588589
void RandAddEvent(const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); }
589590

@@ -602,7 +603,7 @@ int GetRandInt(int nMax) noexcept
602603
uint256 GetRandHash() noexcept
603604
{
604605
uint256 hash;
605-
GetRandBytes((unsigned char*)&hash, sizeof(hash));
606+
GetRandBytes(hash);
606607
return hash;
607608
}
608609

src/random.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
*
7070
* Thread-safe.
7171
*/
72-
void GetRandBytes(unsigned char* buf, int num) noexcept;
72+
void GetRandBytes(Span<unsigned char> bytes) noexcept;
7373
/** Generate a uniform random integer in the range [0..range). Precondition: range > 0 */
7474
uint64_t GetRand(uint64_t nMax) noexcept;
7575
/** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */
@@ -98,7 +98,7 @@ bool GetRandBool(double rate);
9898
*
9999
* Thread-safe.
100100
*/
101-
void GetStrongRandBytes(unsigned char* buf, int num) noexcept;
101+
void GetStrongRandBytes(Span<unsigned char> bytes) noexcept;
102102

103103
/**
104104
* 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
@@ -77,7 +77,7 @@ bool GenerateAuthCookie(std::string *cookie_out)
7777
{
7878
const size_t COOKIE_SIZE = 32;
7979
unsigned char rand_pwd[COOKIE_SIZE];
80-
GetRandBytes(rand_pwd, COOKIE_SIZE);
80+
GetRandBytes(rand_pwd);
8181
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
8282

8383
/** 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

0 commit comments

Comments
 (0)