diff --git a/src/random.cpp b/src/random.cpp index 08bfc5385..7a6feb084 100644 --- a/src/random.cpp +++ b/src/random.cpp @@ -1,779 +1,788 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #ifdef WIN32 #include // for Windows API #include #endif #include #include #include #include // for LogPrintf() #include #include #include #include // for Mutex #include // for GetTime() #include #include #include #ifndef WIN32 #include #include #endif #ifdef HAVE_SYS_GETRANDOM #include #include #endif #if defined(HAVE_GETENTROPY) || \ (defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)) #include #endif #if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) #include #endif #ifdef HAVE_SYSCTL_ARND #include #include // for ARRAYLEN #endif [[noreturn]] static void RandFailure() { LogPrintf("Failed to read randomness, aborting\n"); std::abort(); } static inline int64_t GetPerformanceCounter() noexcept { // Read the hardware time stamp counter when available. // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information. #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) return __rdtsc(); #elif !defined(_MSC_VER) && defined(__i386__) uint64_t r = 0; // Constrain the r variable to the eax:edx pair. __asm__ volatile("rdtsc" : "=A"(r)); return r; #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) uint64_t r1 = 0, r2 = 0; // Constrain r1 to rax and r2 to rdx. __asm__ volatile("rdtsc" : "=a"(r1), "=d"(r2)); return (r2 << 32) | r1; #else // Fall back to using C++11 clock (usually microsecond or nanosecond // precision) return std::chrono::high_resolution_clock::now().time_since_epoch().count(); #endif } #ifdef HAVE_GETCPUID static bool g_rdrand_supported = false; static bool g_rdseed_supported = false; static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000; static constexpr uint32_t CPUID_F7_EBX_RDSEED = 0x00040000; #ifdef bit_RDRND static_assert(CPUID_F1_ECX_RDRAND == bit_RDRND, "Unexpected value for bit_RDRND"); #endif #ifdef bit_RDSEED static_assert(CPUID_F7_EBX_RDSEED == bit_RDSEED, "Unexpected value for bit_RDSEED"); #endif static void InitHardwareRand() { uint32_t eax, ebx, ecx, edx; GetCPUID(1, 0, eax, ebx, ecx, edx); if (ecx & CPUID_F1_ECX_RDRAND) { g_rdrand_supported = true; } GetCPUID(7, 0, eax, ebx, ecx, edx); if (ebx & CPUID_F7_EBX_RDSEED) { g_rdseed_supported = true; } } static void ReportHardwareRand() { // This must be done in a separate function, as InitHardwareRand() may be // indirectly called from global constructors, before logging is // initialized. if (g_rdseed_supported) { LogPrintf("Using RdSeed as additional entropy source\n"); } if (g_rdrand_supported) { LogPrintf("Using RdRand as an additional entropy source\n"); } } /** * Read 64 bits of entropy using rdrand. * * Must only be called when RdRand is supported. */ static uint64_t GetRdRand() noexcept { // RdRand may very rarely fail. Invoke it up to 10 times in a loop to reduce // this risk. #ifdef __i386__ uint8_t ok; uint32_t r1, r2; for (int i = 0; i < 10; ++i) { // rdrand %eax __asm__ volatile(".byte 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r1), "=q"(ok)::"cc"); if (ok) { break; } } for (int i = 0; i < 10; ++i) { // rdrand %eax __asm__ volatile(".byte 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r2), "=q"(ok)::"cc"); if (ok) { break; } } return (uint64_t(r2) << 32) | r1; #elif defined(__x86_64__) || defined(__amd64__) uint8_t ok; uint64_t r1; for (int i = 0; i < 10; ++i) { // rdrand %rax __asm__ volatile(".byte 0x48, 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r1), "=q"(ok)::"cc"); if (ok) { break; } } return r1; #else #error "RdRand is only supported on x86 and x86_64" #endif } /** * Read 64 bits of entropy using rdseed. * * Must only be called when RdSeed is supported. */ static uint64_t GetRdSeed() noexcept { // RdSeed may fail when the HW RNG is overloaded. Loop indefinitely until // enough entropy is gathered, but pause after every failure. #ifdef __i386__ uint8_t ok; uint32_t r1, r2; do { // rdseed %eax __asm__ volatile(".byte 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r1), "=q"(ok)::"cc"); if (ok) { break; } __asm__ volatile("pause"); } while (true); do { // rdseed %eax __asm__ volatile(".byte 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r2), "=q"(ok)::"cc"); if (ok) { break; } __asm__ volatile("pause"); } while (true); return (uint64_t(r2) << 32) | r1; #elif defined(__x86_64__) || defined(__amd64__) uint8_t ok; uint64_t r1; do { // rdseed %rax __asm__ volatile(".byte 0x48, 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r1), "=q"(ok)::"cc"); if (ok) { break; } __asm__ volatile("pause"); } while (true); return r1; #else #error "RdSeed is only supported on x86 and x86_64" #endif } #else /** * Access to other hardware random number generators could be added here later, * assuming it is sufficiently fast (in the order of a few hundred CPU cycles). * Slower sources should probably be invoked separately, and/or only from * RandAddPeriodic (which is called once a minute). */ static void InitHardwareRand() {} static void ReportHardwareRand() {} #endif /** * Add 64 bits of entropy gathered from hardware to hasher. Do nothing if not * supported. */ static void SeedHardwareFast(CSHA512 &hasher) noexcept { #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) if (g_rdrand_supported) { uint64_t out = GetRdRand(); hasher.Write((const uint8_t *)&out, sizeof(out)); return; } #endif } /** * Add 256 bits of entropy gathered from hardware to hasher. Do nothing if not * supported. */ static void SeedHardwareSlow(CSHA512 &hasher) noexcept { #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) // When we want 256 bits of entropy, prefer RdSeed over RdRand, as it's // guaranteed to produce independent randomness on every call. if (g_rdseed_supported) { for (int i = 0; i < 4; ++i) { uint64_t out = GetRdSeed(); hasher.Write((const uint8_t *)&out, sizeof(out)); } return; } // When falling back to RdRand, XOR the result of 1024 results. // This guarantees a reseeding occurs between each. if (g_rdrand_supported) { for (int i = 0; i < 4; ++i) { uint64_t out = 0; for (int j = 0; j < 1024; ++j) { out ^= GetRdRand(); } hasher.Write((const uint8_t *)&out, sizeof(out)); } return; } #endif } /** * Use repeated SHA512 to strengthen the randomness in seed32, and feed into * hasher. */ static void Strengthen(const uint8_t (&seed)[32], int microseconds, CSHA512 &hasher) noexcept { CSHA512 inner_hasher; inner_hasher.Write(seed, sizeof(seed)); // Hash loop uint8_t buffer[64]; int64_t stop = GetTimeMicros() + microseconds; do { for (int i = 0; i < 1000; ++i) { inner_hasher.Finalize(buffer); inner_hasher.Reset(); inner_hasher.Write(buffer, sizeof(buffer)); } // Benchmark operation and feed it into outer hasher. int64_t perf = GetPerformanceCounter(); hasher.Write((const uint8_t *)&perf, sizeof(perf)); } while (GetTimeMicros() < stop); // Produce output from inner state and feed it to outer hasher. inner_hasher.Finalize(buffer); hasher.Write(buffer, sizeof(buffer)); // Try to clean up. inner_hasher.Reset(); memory_cleanse(buffer, sizeof(buffer)); } #ifndef WIN32 /** * Fallback: get 32 bytes of system entropy from /dev/urandom. The most * compatible way to get cryptographic randomness on UNIX-ish platforms. */ static void GetDevURandom(uint8_t *ent32) { int f = open("/dev/urandom", O_RDONLY); if (f == -1) { RandFailure(); } int have = 0; do { ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have); if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) { close(f); RandFailure(); } have += n; } while (have < NUM_OS_RANDOM_BYTES); close(f); } #endif /** Get 32 bytes of system entropy. */ void GetOSRand(uint8_t *ent32) { #if defined(WIN32) HCRYPTPROV hProvider; int ret = CryptAcquireContextW(&hProvider, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!ret) { RandFailure(); } ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32); if (!ret) { RandFailure(); } CryptReleaseContext(hProvider, 0); #elif defined(HAVE_SYS_GETRANDOM) /** * Linux. From the getrandom(2) man page: * "If the urandom source has been initialized, reads of up to 256 bytes * will always return as many bytes as requested and will not be interrupted * by signals." */ int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0); if (rv != NUM_OS_RANDOM_BYTES) { if (rv < 0 && errno == ENOSYS) { /* Fallback for kernel <3.17: the return value will be -1 and errno * ENOSYS if the syscall is not available, in that case fall back * to /dev/urandom. */ GetDevURandom(ent32); } else { RandFailure(); } } #elif defined(HAVE_GETENTROPY) && defined(__OpenBSD__) /** * On OpenBSD this can return up to 256 bytes of entropy, will return an * error if more are requested. * The call cannot return less than the requested number of bytes. * getentropy is explicitly limited to openbsd here, as a similar (but not * the same) function may exist on other platforms via glibc. */ if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) // We need a fallback for OSX < 10.12 if (&getentropy != nullptr) { if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } } else { GetDevURandom(ent32); } #elif defined(HAVE_SYSCTL_ARND) /** * FreeBSD and similar. It is possible for the call to return less bytes * than requested, so need to read in a loop. */ static const int name[2] = {CTL_KERN, KERN_ARND}; int have = 0; do { size_t len = NUM_OS_RANDOM_BYTES - have; if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, nullptr, 0) != 0) { RandFailure(); } have += len; } while (have < NUM_OS_RANDOM_BYTES); #else /** * Fall back to /dev/urandom if there is no specific method implemented to * get system entropy for this OS. */ GetDevURandom(ent32); #endif } namespace { class RNGState { Mutex m_mutex; /** * The RNG state consists of 256 bits of entropy, taken from the output of * one operation's SHA512 output, and fed as input to the next one. * Carrying 256 bits of entropy should be sufficient to guarantee * unpredictability as long as any entropy source was ever unpredictable * to an attacker. To protect against situations where an attacker might * observe the RNG's state, fresh entropy is always mixed when * GetStrongRandBytes is called. */ uint8_t m_state[32] GUARDED_BY(m_mutex) = {0}; uint64_t m_counter GUARDED_BY(m_mutex) = 0; bool m_strongly_seeded GUARDED_BY(m_mutex) = false; Mutex m_events_mutex; CSHA256 m_events_hasher GUARDED_BY(m_events_mutex); public: RNGState() noexcept { InitHardwareRand(); } ~RNGState() {} void AddEvent(uint32_t event_info) noexcept { LOCK(m_events_mutex); m_events_hasher.Write((const uint8_t *)&event_info, sizeof(event_info)); // Get the low four bytes of the performance counter. This translates to // roughly the subsecond part. uint32_t perfcounter = (GetPerformanceCounter() & 0xffffffff); m_events_hasher.Write((const uint8_t *)&perfcounter, sizeof(perfcounter)); } /** * Feed (the hash of) all events added through AddEvent() to hasher. */ void SeedEvents(CSHA512 &hasher) noexcept { // We use only SHA256 for the events hashing to get the ASM speedups we // have for SHA256, since we want it to be fast as network peers may be // able to trigger it repeatedly. LOCK(m_events_mutex); uint8_t events_hash[32]; m_events_hasher.Finalize(events_hash); hasher.Write(events_hash, 32); // Re-initialize the hasher with the finalized state to use later. m_events_hasher.Reset(); m_events_hasher.Write(events_hash, 32); } /** * Extract up to 32 bytes of entropy from the RNG state, mixing in new * entropy from hasher. * * If this function has never been called with strong_seed = true, false is * returned. */ bool MixExtract(uint8_t *out, size_t num, CSHA512 &&hasher, bool strong_seed) noexcept { assert(num <= 32); uint8_t buf[64]; static_assert(sizeof(buf) == CSHA512::OUTPUT_SIZE, "Buffer needs to have hasher's output size"); bool ret; { LOCK(m_mutex); ret = (m_strongly_seeded |= strong_seed); // Write the current state of the RNG into the hasher hasher.Write(m_state, 32); // Write a new counter number into the state hasher.Write((const uint8_t *)&m_counter, sizeof(m_counter)); ++m_counter; // Finalize the hasher hasher.Finalize(buf); // Store the last 32 bytes of the hash output as new RNG state. memcpy(m_state, buf + 32, 32); } // If desired, copy (up to) the first 32 bytes of the hash output as // output. if (num) { assert(out != nullptr); memcpy(out, buf, num); } // Best effort cleanup of internal state hasher.Reset(); memory_cleanse(buf, 64); return ret; } }; RNGState &GetRNGState() noexcept { // This C++11 idiom relies on the guarantee that static variable are // initialized on first call, even when multiple parallel calls are // permitted. static std::vector> g_rng(1); return g_rng[0]; } } // namespace /** * A note on the use of noexcept in the seeding functions below: * * None of the RNG code should ever throw any exception. */ static void SeedTimestamp(CSHA512 &hasher) noexcept { int64_t perfcounter = GetPerformanceCounter(); hasher.Write((const uint8_t *)&perfcounter, sizeof(perfcounter)); } static void SeedFast(CSHA512 &hasher) noexcept { uint8_t buffer[32]; // Stack pointer to indirectly commit to thread/callstack const uint8_t *ptr = buffer; hasher.Write((const uint8_t *)&ptr, sizeof(ptr)); // Hardware randomness is very fast when available; use it always. SeedHardwareFast(hasher); // High-precision timestamp SeedTimestamp(hasher); } static void SeedSlow(CSHA512 &hasher, RNGState &rng) noexcept { uint8_t buffer[32]; // Everything that the 'fast' seeder includes SeedFast(hasher); // OS randomness GetOSRand(buffer); hasher.Write(buffer, sizeof(buffer)); // Add the events hasher into the mix rng.SeedEvents(hasher); // High-precision timestamp. // // Note that we also commit to a timestamp in the Fast seeder, so we // indirectly commit to a benchmark of all the entropy gathering sources in // this function). SeedTimestamp(hasher); } /** Extract entropy from rng, strengthen it, and feed it into hasher. */ static void SeedStrengthen(CSHA512 &hasher, RNGState &rng, int microseconds) noexcept { // Generate 32 bytes of entropy from the RNG, and a copy of the entropy // already in hasher. uint8_t strengthen_seed[32]; rng.MixExtract(strengthen_seed, sizeof(strengthen_seed), CSHA512(hasher), false); // Strengthen the seed, and feed it into hasher. Strengthen(strengthen_seed, microseconds, hasher); } static void SeedPeriodic(CSHA512 &hasher, RNGState &rng) noexcept { // Everything that the 'fast' seeder includes SeedFast(hasher); // High-precision timestamp SeedTimestamp(hasher); // Add the events hasher into the mix rng.SeedEvents(hasher); // Dynamic environment data (performance monitoring, ...) auto old_size = hasher.Size(); RandAddDynamicEnv(hasher); LogPrint(BCLog::RAND, "Feeding %i bytes of dynamic environment data into RNG\n", hasher.Size() - old_size); // Strengthen for 10ms SeedStrengthen(hasher, rng, 10000); } static void SeedStartup(CSHA512 &hasher, RNGState &rng) noexcept { // Gather 256 bits of hardware randomness, if available SeedHardwareSlow(hasher); // Everything that the 'slow' seeder includes. SeedSlow(hasher, rng); // Dynamic environment data (performance monitoring, ...) auto old_size = hasher.Size(); RandAddDynamicEnv(hasher); // Static environment data RandAddStaticEnv(hasher); LogPrint(BCLog::RAND, "Feeding %i bytes of environment data into RNG\n", hasher.Size() - old_size); // Strengthen for 100ms SeedStrengthen(hasher, rng, 100000); } enum class RNGLevel { FAST, //!< Automatically called by GetRandBytes SLOW, //!< Automatically called by GetStrongRandBytes PERIODIC, //!< Called by RandAddPeriodic() }; static void ProcRand(uint8_t *out, int num, RNGLevel level) noexcept { // Make sure the RNG is initialized first (as all Seed* function possibly // need hwrand to be available). RNGState &rng = GetRNGState(); assert(num <= 32); CSHA512 hasher; switch (level) { case RNGLevel::FAST: SeedFast(hasher); break; case RNGLevel::SLOW: SeedSlow(hasher, rng); break; case RNGLevel::PERIODIC: SeedPeriodic(hasher, rng); break; } // Combine with and update state if (!rng.MixExtract(out, num, std::move(hasher), false)) { // On the first invocation, also seed with SeedStartup(). CSHA512 startup_hasher; SeedStartup(startup_hasher, rng); rng.MixExtract(out, num, std::move(startup_hasher), true); } } void GetRandBytes(uint8_t *buf, int num) noexcept { ProcRand(buf, num, RNGLevel::FAST); } void GetStrongRandBytes(uint8_t *buf, int num) noexcept { ProcRand(buf, num, RNGLevel::SLOW); } void RandAddPeriodic() noexcept { ProcRand(nullptr, 0, RNGLevel::PERIODIC); } void RandAddEvent(const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); } bool g_mock_deterministic_tests{false}; uint64_t GetRand(uint64_t nMax) noexcept { return FastRandomContext(g_mock_deterministic_tests).randrange(nMax); } std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept { return std::chrono::microseconds{GetRand(duration_max.count())}; } int GetRandInt(int nMax) noexcept { return GetRand(nMax); } uint256 GetRandHash() noexcept { uint256 hash; GetRandBytes((uint8_t *)&hash, sizeof(hash)); return hash; } void FastRandomContext::RandomSeed() { uint256 seed = GetRandHash(); rng.SetKey(seed.begin(), 32); requires_seed = false; } +uint160 FastRandomContext::rand160() noexcept { + if (bytebuf_size < 20) { + FillByteBuffer(); + } + uint160 ret; + memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 20); + bytebuf_size -= 20; + return ret; +} + uint256 FastRandomContext::rand256() noexcept { if (bytebuf_size < 32) { FillByteBuffer(); } uint256 ret; memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32); bytebuf_size -= 32; return ret; } - std::vector FastRandomContext::randbytes(size_t len) { if (requires_seed) { RandomSeed(); } std::vector ret(len); if (len > 0) { rng.Keystream(&ret[0], len); } return ret; } FastRandomContext::FastRandomContext(const uint256 &seed) noexcept : requires_seed(false), bytebuf_size(0), bitbuf_size(0) { rng.SetKey(seed.begin(), 32); } bool Random_SanityCheck() { uint64_t start = GetPerformanceCounter(); /** * This does not measure the quality of randomness, but it does test that * GetOSRand() overwrites all 32 bytes of the output given a maximum number * of tries. */ static const ssize_t MAX_TRIES = 1024; uint8_t data[NUM_OS_RANDOM_BYTES]; /* Tracks which bytes have been overwritten at least once */ bool overwritten[NUM_OS_RANDOM_BYTES] = {}; int num_overwritten; int tries = 0; /** * Loop until all bytes have been overwritten at least once, or max number * tries reached. */ do { memset(data, 0, NUM_OS_RANDOM_BYTES); GetOSRand(data); for (int x = 0; x < NUM_OS_RANDOM_BYTES; ++x) { overwritten[x] |= (data[x] != 0); } num_overwritten = 0; for (int x = 0; x < NUM_OS_RANDOM_BYTES; ++x) { if (overwritten[x]) { num_overwritten += 1; } } tries += 1; } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES); /* If this failed, bailed out after too many tries */ if (num_overwritten != NUM_OS_RANDOM_BYTES) { return false; } // Check that GetPerformanceCounter increases at least during a GetOSRand() // call + 1ms sleep. std::this_thread::sleep_for(std::chrono::milliseconds(1)); uint64_t stop = GetPerformanceCounter(); if (stop == start) { return false; } // We called GetPerformanceCounter. Use it as entropy. CSHA512 to_add; to_add.Write((const uint8_t *)&start, sizeof(start)); to_add.Write((const uint8_t *)&stop, sizeof(stop)); GetRNGState().MixExtract(nullptr, 0, std::move(to_add), false); return true; } FastRandomContext::FastRandomContext(bool fDeterministic) noexcept : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0) { if (!fDeterministic) { return; } uint256 seed; rng.SetKey(seed.begin(), 32); } FastRandomContext &FastRandomContext:: operator=(FastRandomContext &&from) noexcept { requires_seed = from.requires_seed; rng = from.rng; std::copy(std::begin(from.bytebuf), std::end(from.bytebuf), std::begin(bytebuf)); bytebuf_size = from.bytebuf_size; bitbuf = from.bitbuf; bitbuf_size = from.bitbuf_size; from.requires_seed = true; from.bytebuf_size = 0; from.bitbuf_size = 0; return *this; } void RandomInit() { // Invoke RNG code to trigger initialization (if not already performed) ProcRand(nullptr, 0, RNGLevel::FAST); ReportHardwareRand(); } diff --git a/src/random.h b/src/random.h index 5d01fa512..982e0e50a 100644 --- a/src/random.h +++ b/src/random.h @@ -1,266 +1,269 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_RANDOM_H #define BITCOIN_RANDOM_H #include #include #include #include // For std::chrono::microseconds #include #include /** * Overall design of the RNG and entropy sources. * * We maintain a single global 256-bit RNG state for all high-quality * randomness. The following (classes of) functions interact with that state by * mixing in new entropy, and optionally extracting random output from it: * * - The GetRand*() class of functions, as well as construction of * FastRandomContext objects, perform 'fast' seeding, consisting of mixing in: * - A stack pointer (indirectly committing to calling thread and call stack) * - A high-precision timestamp (rdtsc when available, c++ * high_resolution_clock otherwise) * - 64 bits from the hardware RNG (rdrand) when available. * These entropy sources are very fast, and only designed to protect against * situations where a VM state restore/copy results in multiple systems with the * same randomness. FastRandomContext on the other hand does not protect against * this once created, but is even faster (and acceptable to use inside tight * loops). * * - The GetStrongRand*() class of function perform 'slow' seeding, including * everything that fast seeding includes, but additionally: * - OS entropy (/dev/urandom, getrandom(), ...). The application will * terminate if this entropy source fails. * - Another high-precision timestamp (indirectly committing to a benchmark of * all the previous sources). These entropy sources are slower, but designed to * make sure the RNG state contains fresh data that is unpredictable to * attackers. * * - RandAddPeriodic() seeds everything that fast seeding includes, but * additionally: * - A high-precision timestamp * - Dynamic environment data (performance monitoring, ...) * - Strengthen the entropy for 10 ms using repeated SHA512. * This is run once every minute. * * On first use of the RNG (regardless of what function is called first), all * entropy sources used in the 'slow' seeder are included, but also: * - 256 bits from the hardware RNG (rdseed or rdrand) when available. * - Dynamic environment data (performance monitoring, ...) * - Static environment data * - Strengthen the entropy for 100 ms using repeated SHA512. * * When mixing in new entropy, H = SHA512(entropy || old_rng_state) is computed, * and (up to) the first 32 bytes of H are produced as output, while the last 32 * bytes become the new RNG state. */ /** * Generate random data via the internal PRNG. * * These functions are designed to be fast (sub microsecond), but do not * necessarily meaningfully add entropy to the PRNG state. * * Thread-safe. */ void GetRandBytes(uint8_t *buf, int num) noexcept; uint64_t GetRand(uint64_t nMax) noexcept; std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept; int GetRandInt(int nMax) noexcept; uint256 GetRandHash() noexcept; /** * Gather entropy from various sources, feed it into the internal PRNG, and * generate random data using it. * * This function will cause failure whenever the OS RNG fails. * * Thread-safe. */ void GetStrongRandBytes(uint8_t *buf, int num) noexcept; /** * Gather entropy from various expensive sources, and feed them to the PRNG * state. * * Thread-safe. */ void RandAddPeriodic() noexcept; /** * Gathers entropy from the low bits of the time at which events occur. Should * be called with a uint32_t describing the event at the time an event occurs. * * Thread-safe. */ void RandAddEvent(const uint32_t event_info) noexcept; /** * Fast randomness source. This is seeded once with secure random data, but * is completely deterministic and does not gather more entropy after that. * * This class is not thread-safe. */ class FastRandomContext { private: bool requires_seed; ChaCha20 rng; uint8_t bytebuf[64]; int bytebuf_size; uint64_t bitbuf; int bitbuf_size; void RandomSeed(); void FillByteBuffer() { if (requires_seed) { RandomSeed(); } rng.Keystream(bytebuf, sizeof(bytebuf)); bytebuf_size = sizeof(bytebuf); } void FillBitBuffer() { bitbuf = rand64(); bitbuf_size = 64; } public: explicit FastRandomContext(bool fDeterministic = false) noexcept; /** Initialize with explicit seed (only for testing) */ explicit FastRandomContext(const uint256 &seed) noexcept; // Do not permit copying a FastRandomContext (move it, or create a new one // to get reseeded). FastRandomContext(const FastRandomContext &) = delete; FastRandomContext(FastRandomContext &&) = delete; FastRandomContext &operator=(const FastRandomContext &) = delete; /** * Move a FastRandomContext. If the original one is used again, it will be * reseeded. */ FastRandomContext &operator=(FastRandomContext &&from) noexcept; /** Generate a random 64-bit integer. */ uint64_t rand64() noexcept { if (bytebuf_size < 8) { FillByteBuffer(); } uint64_t ret = ReadLE64(bytebuf + 64 - bytebuf_size); bytebuf_size -= 8; return ret; } /** Generate a random (bits)-bit integer. */ uint64_t randbits(int bits) noexcept { if (bits == 0) { return 0; } else if (bits > 32) { return rand64() >> (64 - bits); } else { if (bitbuf_size < bits) { FillBitBuffer(); } uint64_t ret = bitbuf & (~uint64_t(0) >> (64 - bits)); bitbuf >>= bits; bitbuf_size -= bits; return ret; } } /** Generate a random integer in the range [0..range). */ uint64_t randrange(uint64_t range) noexcept { assert(range); --range; int bits = CountBits(range); while (true) { uint64_t ret = randbits(bits); if (ret <= range) { return ret; } } } /** Generate random bytes. */ std::vector randbytes(size_t len); /** Generate a random 32-bit integer. */ uint32_t rand32() noexcept { return randbits(32); } + /** generate a random uint160. */ + uint160 rand160() noexcept; + /** generate a random uint256. */ uint256 rand256() noexcept; /** Generate a random boolean. */ bool randbool() noexcept { return randbits(1); } // Compatibility with the C++11 UniformRandomBitGenerator concept typedef uint64_t result_type; static constexpr uint64_t min() { return 0; } static constexpr uint64_t max() { return std::numeric_limits::max(); } inline uint64_t operator()() noexcept { return rand64(); } }; /** * More efficient than using std::shuffle on a FastRandomContext. * * This is more efficient as std::shuffle will consume entropy in groups of * 64 bits at the time and throw away most. * * This also works around a bug in libstdc++ std::shuffle that may cause * type::operator=(type&&) to be invoked on itself, which the library's * debug mode detects and panics on. This is a known issue, see * https://stackoverflow.com/questions/22915325/avoiding-self-assignment-in-stdshuffle */ template void Shuffle(I first, I last, R &&rng) { while (first != last) { size_t j = rng.randrange(last - first); if (j) { using std::swap; swap(*first, *(first + j)); } ++first; } } /** * Number of random bytes returned by GetOSRand. * When changing this constant make sure to change all call sites, and make * sure that the underlying OS APIs for all platforms support the number. * (many cap out at 256 bytes). */ static const int NUM_OS_RANDOM_BYTES = 32; /** * Get 32 bytes of system entropy. Do not use this in application code: use * GetStrongRandBytes instead. */ void GetOSRand(uint8_t *ent32); /** * Check that OS randomness is available and returning the requested number of * bytes. */ bool Random_SanityCheck(); /** * Initialize global RNG state and log any CPU features that are used. * * Calling this function is optional. RNG state will be initialized when first * needed if it is not called. */ void RandomInit(); #endif // BITCOIN_RANDOM_H diff --git a/src/test/cashaddrenc_tests.cpp b/src/test/cashaddrenc_tests.cpp index 0087bdd1c..61bb947c3 100644 --- a/src/test/cashaddrenc_tests.cpp +++ b/src/test/cashaddrenc_tests.cpp @@ -1,465 +1,455 @@ // Copyright (c) 2017-2020 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #include #include namespace { std::vector GetNetworks() { return {CBaseChainParams::MAIN, CBaseChainParams::TESTNET, CBaseChainParams::REGTEST}; } -uint160 insecure_GetRandUInt160(FastRandomContext &rand) { - uint160 n; - for (uint8_t *c = n.begin(); c != n.end(); ++c) { - *c = static_cast(rand.rand32()); - } - return n; -} - std::vector insecure_GetRandomByteArray(FastRandomContext &rand, size_t n) { std::vector out; out.reserve(n); for (size_t i = 0; i < n; i++) { out.push_back(uint8_t(rand.randbits(8))); } return out; } class DstTypeChecker : public boost::static_visitor { public: void operator()(const PKHash &id) { isKey = true; } void operator()(const ScriptHash &id) { isScript = true; } void operator()(const CNoDestination &) {} static bool IsScriptDst(const CTxDestination &d) { DstTypeChecker checker; boost::apply_visitor(checker, d); return checker.isScript; } static bool IsKeyDst(const CTxDestination &d) { DstTypeChecker checker; boost::apply_visitor(checker, d); return checker.isKey; } private: DstTypeChecker() : isKey(false), isScript(false) {} bool isKey; bool isScript; }; // Map all possible size bits in the version to the expected size of the // hash in bytes. const std::array, 8> valid_sizes = { {{0, 20}, {1, 24}, {2, 28}, {3, 32}, {4, 40}, {5, 48}, {6, 56}, {7, 64}}}; } // namespace BOOST_FIXTURE_TEST_SUITE(cashaddrenc_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(encode_decode_all_sizes) { FastRandomContext rand(true); const std::string prefix = "bitcoincash"; for (auto ps : valid_sizes) { std::vector data = insecure_GetRandomByteArray(rand, ps.second); CashAddrContent content = {PUBKEY_TYPE, data}; std::vector packed_data = PackCashAddrContent(content); // Check that the packed size is correct BOOST_CHECK_EQUAL(packed_data[1] >> 2, ps.first); std::string address = cashaddr::Encode(prefix, packed_data); // Check that the address decodes properly CashAddrContent decoded = DecodeCashAddrContent(address, prefix); BOOST_CHECK_EQUAL_COLLECTIONS( std::begin(content.hash), std::end(content.hash), std::begin(decoded.hash), std::end(decoded.hash)); } } BOOST_AUTO_TEST_CASE(check_packaddr_throws) { FastRandomContext rand(true); for (auto ps : valid_sizes) { std::vector data = insecure_GetRandomByteArray(rand, ps.second - 1); CashAddrContent content = {PUBKEY_TYPE, data}; BOOST_CHECK_THROW(PackCashAddrContent(content), std::runtime_error); } } BOOST_AUTO_TEST_CASE(encode_decode) { std::vector toTest = {CNoDestination{}, PKHash(uint160S("badf00d")), ScriptHash(uint160S("f00dbad"))}; for (auto dst : toTest) { for (auto net : GetNetworks()) { const auto netParams = CreateChainParams(net); std::string encoded = EncodeCashAddr(dst, *netParams); CTxDestination decoded = DecodeCashAddr(encoded, *netParams); BOOST_CHECK(dst == decoded); } } } // Check that an encoded cash address is not valid on another network. BOOST_AUTO_TEST_CASE(invalid_on_wrong_network) { const CTxDestination dst = PKHash(uint160S("c0ffee")); const CTxDestination invalidDst = CNoDestination{}; for (auto net : GetNetworks()) { for (auto otherNet : GetNetworks()) { if (net == otherNet) { continue; } const auto netParams = CreateChainParams(net); std::string encoded = EncodeCashAddr(dst, *netParams); const auto otherNetParams = CreateChainParams(otherNet); CTxDestination decoded = DecodeCashAddr(encoded, *otherNetParams); BOOST_CHECK(decoded != dst); BOOST_CHECK(decoded == invalidDst); } } } BOOST_AUTO_TEST_CASE(random_dst) { - FastRandomContext rand(true); - const size_t NUM_TESTS = 5000; const auto params = CreateChainParams(CBaseChainParams::MAIN); for (size_t i = 0; i < NUM_TESTS; ++i) { - uint160 hash = insecure_GetRandUInt160(rand); + uint160 hash = InsecureRand160(); const CTxDestination dst_key = PKHash(hash); const CTxDestination dst_scr = ScriptHash(hash); const std::string encoded_key = EncodeCashAddr(dst_key, *params); const CTxDestination decoded_key = DecodeCashAddr(encoded_key, *params); const std::string encoded_scr = EncodeCashAddr(dst_scr, *params); const CTxDestination decoded_scr = DecodeCashAddr(encoded_scr, *params); std::string err("cashaddr failed for hash: "); err += hash.ToString(); BOOST_CHECK_MESSAGE(dst_key == decoded_key, err); BOOST_CHECK_MESSAGE(dst_scr == decoded_scr, err); BOOST_CHECK_MESSAGE(DstTypeChecker::IsKeyDst(decoded_key), err); BOOST_CHECK_MESSAGE(DstTypeChecker::IsScriptDst(decoded_scr), err); } } /** * Cashaddr payload made of 5-bit nibbles. The last one is padded. When * converting back to bytes, this extra padding is truncated. In order to ensure * cashaddr are cannonicals, we check that the data we truncate is zeroed. */ BOOST_AUTO_TEST_CASE(check_padding) { uint8_t version = 0; std::vector data = {version}; for (size_t i = 0; i < 33; ++i) { data.push_back(1); } BOOST_CHECK_EQUAL(data.size(), 34UL); const CTxDestination nodst = CNoDestination{}; const auto params = CreateChainParams(CBaseChainParams::MAIN); for (uint8_t i = 0; i < 32; i++) { data[data.size() - 1] = i; std::string fake = cashaddr::Encode(params->CashAddrPrefix(), data); CTxDestination dst = DecodeCashAddr(fake, *params); // We have 168 bits of payload encoded as 170 bits in 5 bits nimbles. As // a result, we must have 2 zeros. if (i & 0x03) { BOOST_CHECK(dst == nodst); } else { BOOST_CHECK(dst != nodst); } } } /** * We ensure type is extracted properly from the version. */ BOOST_AUTO_TEST_CASE(check_type) { std::vector data; data.resize(34); const std::string prefix = "bitcoincash"; for (uint8_t v = 0; v < 16; v++) { std::fill(begin(data), end(data), 0); data[0] = v; auto content = DecodeCashAddrContent(cashaddr::Encode(prefix, data), prefix); BOOST_CHECK_EQUAL(content.type, v); BOOST_CHECK_EQUAL(content.hash.size(), 20UL); // Check that using the reserved bit result in a failure. data[0] |= 0x10; content = DecodeCashAddrContent(cashaddr::Encode(prefix, data), prefix); BOOST_CHECK_EQUAL(content.type, 0); BOOST_CHECK_EQUAL(content.hash.size(), 0UL); } } /** * We ensure size is extracted and checked properly. */ BOOST_AUTO_TEST_CASE(check_size) { const CTxDestination nodst = CNoDestination{}; const std::string prefix = "bitcoincash"; std::vector data; for (auto ps : valid_sizes) { // Number of bytes required for a 5-bit packed version of a hash, with // version byte. Add half a byte(4) so integer math provides the next // multiple-of-5 that would fit all the data. size_t expectedSize = (8 * (1 + ps.second) + 4) / 5; data.resize(expectedSize); std::fill(begin(data), end(data), 0); // After conversion from 8 bit packing to 5 bit packing, the size will // be in the second 5-bit group, shifted left twice. data[1] = ps.first << 2; auto content = DecodeCashAddrContent(cashaddr::Encode(prefix, data), prefix); BOOST_CHECK_EQUAL(content.type, 0); BOOST_CHECK_EQUAL(content.hash.size(), ps.second); data.push_back(0); content = DecodeCashAddrContent(cashaddr::Encode(prefix, data), prefix); BOOST_CHECK_EQUAL(content.type, 0); BOOST_CHECK_EQUAL(content.hash.size(), 0UL); data.pop_back(); data.pop_back(); content = DecodeCashAddrContent(cashaddr::Encode(prefix, data), prefix); BOOST_CHECK_EQUAL(content.type, 0); BOOST_CHECK_EQUAL(content.hash.size(), 0UL); } } BOOST_AUTO_TEST_CASE(test_encode_address) { const auto params = CreateChainParams(CBaseChainParams::MAIN); std::vector> hash{ {118, 160, 64, 83, 189, 160, 168, 139, 218, 81, 119, 184, 106, 21, 195, 178, 159, 85, 152, 115}, {203, 72, 18, 50, 41, 156, 213, 116, 49, 81, 172, 75, 45, 99, 174, 25, 142, 123, 176, 169}, {1, 31, 40, 228, 115, 201, 95, 64, 19, 215, 213, 62, 197, 251, 195, 180, 45, 248, 237, 16}}; std::vector pubkey = { "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a", "bitcoincash:qr95sy3j9xwd2ap32xkykttr4cvcu7as4y0qverfuy", "bitcoincash:qqq3728yw0y47sqn6l2na30mcw6zm78dzqre909m2r"}; std::vector script = { "bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq", "bitcoincash:pr95sy3j9xwd2ap32xkykttr4cvcu7as4yc93ky28e", "bitcoincash:pqq3728yw0y47sqn6l2na30mcw6zm78dzq5ucqzc37"}; for (size_t i = 0; i < hash.size(); ++i) { const CTxDestination dstKey = PKHash(uint160(hash[i])); BOOST_CHECK_EQUAL(pubkey[i], EncodeCashAddr(dstKey, *params)); CashAddrContent keyContent{PUBKEY_TYPE, hash[i]}; BOOST_CHECK_EQUAL(pubkey[i], EncodeCashAddr("bitcoincash", keyContent)); const CTxDestination dstScript = ScriptHash(uint160(hash[i])); BOOST_CHECK_EQUAL(script[i], EncodeCashAddr(dstScript, *params)); CashAddrContent scriptContent{SCRIPT_TYPE, hash[i]}; BOOST_CHECK_EQUAL(script[i], EncodeCashAddr("bitcoincash", scriptContent)); } } struct CashAddrTestVector { std::string prefix; CashAddrType type; std::vector hash; std::string addr; }; BOOST_AUTO_TEST_CASE(test_vectors) { std::vector cases = { // 20 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("F5BF48B397DAE70BE82B3CCA4793F8EB2B6CDAC9"), "bitcoincash:qr6m7j9njldwwzlg9v7v53unlr4jkmx6eylep8ekg2"}, {"bchtest", SCRIPT_TYPE, ParseHex("F5BF48B397DAE70BE82B3CCA4793F8EB2B6CDAC9"), "bchtest:pr6m7j9njldwwzlg9v7v53unlr4jkmx6eyvwc0uz5t"}, {"prefix", CashAddrType(15), ParseHex("F5BF48B397DAE70BE82B3CCA4793F8EB2B6CDAC9"), "prefix:0r6m7j9njldwwzlg9v7v53unlr4jkmx6ey3qnjwsrf"}, {"bchreg", PUBKEY_TYPE, ParseHex("d85c2b71d0060b09c9886aeb815e50991dda124d"), "bchreg:qrv9c2m36qrqkzwf3p4whq272zv3mksjf5ln6v9le5"}, {"bchreg", PUBKEY_TYPE, ParseHex("00aea9a2e5f0f876a588df5546e8742d1d87008f"), "bchreg:qqq2a2dzuhc0sa493r0423hgwsk3mpcq3upac4z3wr"}, // 24 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("7ADBF6C17084BC86C1706827B41A56F5CA32865925E946EA"), "bitcoincash:q9adhakpwzztepkpwp5z0dq62m6u5v5xtyj7j3h2ws4mr9g0"}, {"bchtest", SCRIPT_TYPE, ParseHex("7ADBF6C17084BC86C1706827B41A56F5CA32865925E946EA"), "bchtest:p9adhakpwzztepkpwp5z0dq62m6u5v5xtyj7j3h2u94tsynr"}, {"prefix", CashAddrType(15), ParseHex("7ADBF6C17084BC86C1706827B41A56F5CA32865925E946EA"), "prefix:09adhakpwzztepkpwp5z0dq62m6u5v5xtyj7j3h2p29kc2lp"}, // 28 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("3A84F9CF51AAE98A3BB3A78BF16A6183790B18719126325BFC0C075B"), "bitcoincash:qgagf7w02x4wnz3mkwnchut2vxphjzccwxgjvvjmlsxqwkcw59jxxuz"}, {"bchtest", SCRIPT_TYPE, ParseHex("3A84F9CF51AAE98A3BB3A78BF16A6183790B18719126325BFC0C075B"), "bchtest:pgagf7w02x4wnz3mkwnchut2vxphjzccwxgjvvjmlsxqwkcvs7md7wt"}, {"prefix", CashAddrType(15), ParseHex("3A84F9CF51AAE98A3BB3A78BF16A6183790B18719126325BFC0C075B"), "prefix:0gagf7w02x4wnz3mkwnchut2vxphjzccwxgjvvjmlsxqwkc5djw8s9g"}, // 32 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("3173EF6623C6B48FFD1A3DCC0CC6489B0A07BB47A37F47CFEF4FE69DE825" "C060"), "bitcoincash:" "qvch8mmxy0rtfrlarg7ucrxxfzds5pamg73h7370aa87d80gyhqxq5nlegake"}, {"bchtest", SCRIPT_TYPE, ParseHex("3173EF6623C6B48FFD1A3DCC0CC6489B0A07BB47A37F47CFEF4FE69DE825" "C060"), "bchtest:" "pvch8mmxy0rtfrlarg7ucrxxfzds5pamg73h7370aa87d80gyhqxq7fqng6m6"}, {"prefix", CashAddrType(15), ParseHex("3173EF6623C6B48FFD1A3DCC0CC6489B0A07BB47A37F47CFEF4FE69DE825" "C060"), "prefix:" "0vch8mmxy0rtfrlarg7ucrxxfzds5pamg73h7370aa87d80gyhqxqsh6jgp6w"}, // 40 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("C07138323E00FA4FC122D3B85B9628EA810B3F381706385E289B0B256311" "97D194B5C238BEB136FB"), "bitcoincash:" "qnq8zwpj8cq05n7pytfmskuk9r4gzzel8qtsvwz79zdskftrzxtar994cgutavfklv39g" "r3uvz"}, {"bchtest", SCRIPT_TYPE, ParseHex("C07138323E00FA4FC122D3B85B9628EA810B3F381706385E289B0B256311" "97D194B5C238BEB136FB"), "bchtest:" "pnq8zwpj8cq05n7pytfmskuk9r4gzzel8qtsvwz79zdskftrzxtar994cgutavfklvmgm" "6ynej"}, {"prefix", CashAddrType(15), ParseHex("C07138323E00FA4FC122D3B85B9628EA810B3F381706385E289B0B256311" "97D194B5C238BEB136FB"), "prefix:" "0nq8zwpj8cq05n7pytfmskuk9r4gzzel8qtsvwz79zdskftrzxtar994cgutavfklvwsv" "ctzqy"}, // 48 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("E361CA9A7F99107C17A622E047E3745D3E19CF804ED63C5C40C6BA763696" "B98241223D8CE62AD48D863F4CB18C930E4C"), "bitcoincash:" "qh3krj5607v3qlqh5c3wq3lrw3wnuxw0sp8dv0zugrrt5a3kj6ucysfz8kxwv2k53krr7" "n933jfsunqex2w82sl"}, {"bchtest", SCRIPT_TYPE, ParseHex("E361CA9A7F99107C17A622E047E3745D3E19CF804ED63C5C40C6BA763696" "B98241223D8CE62AD48D863F4CB18C930E4C"), "bchtest:" "ph3krj5607v3qlqh5c3wq3lrw3wnuxw0sp8dv0zugrrt5a3kj6ucysfz8kxwv2k53krr7" "n933jfsunqnzf7mt6x"}, {"prefix", CashAddrType(15), ParseHex("E361CA9A7F99107C17A622E047E3745D3E19CF804ED63C5C40C6BA763696" "B98241223D8CE62AD48D863F4CB18C930E4C"), "prefix:" "0h3krj5607v3qlqh5c3wq3lrw3wnuxw0sp8dv0zugrrt5a3kj6ucysfz8kxwv2k53krr7" "n933jfsunqakcssnmn"}, // 56 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("D9FA7C4C6EF56DC4FF423BAAE6D495DBFF663D034A72D1DC7D52CBFE7D1E" "6858F9D523AC0A7A5C34077638E4DD1A701BD017842789982041"), "bitcoincash:" "qmvl5lzvdm6km38lgga64ek5jhdl7e3aqd9895wu04fvhlnare5937w4ywkq57juxsrhv" "w8ym5d8qx7sz7zz0zvcypqscw8jd03f"}, {"bchtest", SCRIPT_TYPE, ParseHex("D9FA7C4C6EF56DC4FF423BAAE6D495DBFF663D034A72D1DC7D52CBFE7D1E" "6858F9D523AC0A7A5C34077638E4DD1A701BD017842789982041"), "bchtest:" "pmvl5lzvdm6km38lgga64ek5jhdl7e3aqd9895wu04fvhlnare5937w4ywkq57juxsrhv" "w8ym5d8qx7sz7zz0zvcypqs6kgdsg2g"}, {"prefix", CashAddrType(15), ParseHex("D9FA7C4C6EF56DC4FF423BAAE6D495DBFF663D034A72D1DC7D52CBFE7D1E" "6858F9D523AC0A7A5C34077638E4DD1A701BD017842789982041"), "prefix:" "0mvl5lzvdm6km38lgga64ek5jhdl7e3aqd9895wu04fvhlnare5937w4ywkq57juxsrhv" "w8ym5d8qx7sz7zz0zvcypqsgjrqpnw8"}, // 64 bytes {"bitcoincash", PUBKEY_TYPE, ParseHex("D0F346310D5513D9E01E299978624BA883E6BDA8F4C60883C10F28C2967E" "67EC77ECC7EEEAEAFC6DA89FAD72D11AC961E164678B868AEEEC5F2C1DA0" "8884175B"), "bitcoincash:" "qlg0x333p4238k0qrc5ej7rzfw5g8e4a4r6vvzyrcy8j3s5k0en7calvclhw46hudk5fl" "ttj6ydvjc0pv3nchp52amk97tqa5zygg96mtky5sv5w"}, {"bchtest", SCRIPT_TYPE, ParseHex("D0F346310D5513D9E01E299978624BA883E6BDA8F4C60883C10F28C2967E" "67EC77ECC7EEEAEAFC6DA89FAD72D11AC961E164678B868AEEEC5F2C1DA0" "8884175B"), "bchtest:" "plg0x333p4238k0qrc5ej7rzfw5g8e4a4r6vvzyrcy8j3s5k0en7calvclhw46hudk5fl" "ttj6ydvjc0pv3nchp52amk97tqa5zygg96mc773cwez"}, {"prefix", CashAddrType(15), ParseHex("D0F346310D5513D9E01E299978624BA883E6BDA8F4C60883C10F28C2967E" "67EC77ECC7EEEAEAFC6DA89FAD72D11AC961E164678B868AEEEC5F2C1DA0" "8884175B"), "prefix:" "0lg0x333p4238k0qrc5ej7rzfw5g8e4a4r6vvzyrcy8j3s5k0en7calvclhw46hudk5fl" "ttj6ydvjc0pv3nchp52amk97tqa5zygg96ms92w6845"}, }; for (const auto &t : cases) { CashAddrContent content{t.type, t.hash}; BOOST_CHECK_EQUAL(t.addr, EncodeCashAddr(t.prefix, content)); std::string err("hash mistmatch for address: "); err += t.addr; content = DecodeCashAddrContent(t.addr, t.prefix); BOOST_CHECK_EQUAL(t.type, content.type); BOOST_CHECK_MESSAGE(t.hash == content.hash, err); } } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/util/setup_common.h b/src/test/util/setup_common.h index e7f7ef0df..3e5fab241 100644 --- a/src/test/util/setup_common.h +++ b/src/test/util/setup_common.h @@ -1,196 +1,199 @@ // Copyright (c) 2015-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_UTIL_SETUP_COMMON_H #define BITCOIN_TEST_UTIL_SETUP_COMMON_H #include #include #include #include #include #include #include #include #include #include #include // For boost::thread_group #include /** * Version of Boost::test prior to 1.64 have issues when dealing with nullptr_t. * In order to work around this, we ensure that the null pointers are typed in a * way that Boost will like better. * * TODO: Use nullptr directly once the minimum version of boost is 1.64 or more. */ #define NULLPTR(T) static_cast(nullptr) // Enable BOOST_CHECK_EQUAL for enum class types template std::ostream &operator<<( typename std::enable_if::value, std::ostream>::type &stream, const T &e) { return stream << static_cast::type>(e); } /** * This global and the helpers that use it are not thread-safe. * * If thread-safety is needed, the global could be made thread_local (given * that thread_local is supported on all architectures we support) or a * per-thread instance could be used in the multi-threaded test. */ extern FastRandomContext g_insecure_rand_ctx; /** * Flag to make GetRand in random.h return the same number */ extern bool g_mock_deterministic_tests; enum class SeedRand { ZEROS, //!< Seed with a compile time constant of zeros SEED, //!< Call the Seed() helper }; /** * Seed the given random ctx or use the seed passed in via an * environment var */ void Seed(FastRandomContext &ctx); static inline void SeedInsecureRand(SeedRand seed = SeedRand::SEED) { if (seed == SeedRand::ZEROS) { g_insecure_rand_ctx = FastRandomContext(/* deterministic */ true); } else { Seed(g_insecure_rand_ctx); } } static inline uint32_t InsecureRand32() { return g_insecure_rand_ctx.rand32(); } +static inline uint160 InsecureRand160() { + return g_insecure_rand_ctx.rand160(); +} static inline uint256 InsecureRand256() { return g_insecure_rand_ctx.rand256(); } static inline uint64_t InsecureRandBits(int bits) { return g_insecure_rand_ctx.randbits(bits); } static inline uint64_t InsecureRandRange(uint64_t range) { return g_insecure_rand_ctx.randrange(range); } static inline bool InsecureRandBool() { return g_insecure_rand_ctx.randbool(); } static constexpr Amount CENT(COIN / 100); /** * Basic testing setup. * This just configures logging, data dir and chain parameters. */ struct BasicTestingSetup { ECCVerifyHandle globalVerifyHandle; NodeContext m_node; explicit BasicTestingSetup( const std::string &chainName = CBaseChainParams::MAIN); ~BasicTestingSetup(); private: const fs::path m_path_root; }; /** * Testing setup that configures a complete environment. * Included are coins database, script check threads setup. */ struct TestingSetup : public BasicTestingSetup { boost::thread_group threadGroup; explicit TestingSetup( const std::string &chainName = CBaseChainParams::MAIN); ~TestingSetup(); }; /** Identical to TestingSetup, but chain set to regtest */ struct RegTestingSetup : public TestingSetup { RegTestingSetup() : TestingSetup{CBaseChainParams::REGTEST} {} }; class CBlock; class CMutableTransaction; class CScript; // // Testing fixture that pre-creates a // 100-block REGTEST-mode block chain // struct TestChain100Setup : public RegTestingSetup { TestChain100Setup(); // Create a new block with just given transactions, coinbase paying to // scriptPubKey, and try to add it to the current chain. CBlock CreateAndProcessBlock(const std::vector &txns, const CScript &scriptPubKey); ~TestChain100Setup(); // For convenience, coinbase transactions. std::vector m_coinbase_txns; // private/public key needed to spend coinbase transactions. CKey coinbaseKey; }; class CTxMemPoolEntry; struct TestMemPoolEntryHelper { // Default values Amount nFee; int64_t nTime; unsigned int nHeight; bool spendsCoinbase; unsigned int nSigOpCount; TestMemPoolEntryHelper() : nFee(), nTime(0), nHeight(1), spendsCoinbase(false), nSigOpCount(1) {} CTxMemPoolEntry FromTx(const CMutableTransaction &tx); CTxMemPoolEntry FromTx(const CTransactionRef &tx); // Change the default value TestMemPoolEntryHelper &Fee(Amount _fee) { nFee = _fee; return *this; } TestMemPoolEntryHelper &Time(int64_t _time) { nTime = _time; return *this; } TestMemPoolEntryHelper &Height(unsigned int _height) { nHeight = _height; return *this; } TestMemPoolEntryHelper &SpendsCoinbase(bool _flag) { spendsCoinbase = _flag; return *this; } TestMemPoolEntryHelper &SigOpCount(unsigned int _nSigOpCount) { nSigOpCount = _nSigOpCount; return *this; } }; enum class ScriptError; // define implicit conversions here so that these types may be used in // BOOST_*_EQUAL std::ostream &operator<<(std::ostream &os, const uint256 &num); std::ostream &operator<<(std::ostream &os, const ScriptError &err); CBlock getBlock13b8a(); #endif // BITCOIN_TEST_UTIL_SETUP_COMMON_H