Branch data Line data Source code
1 : : // Copyright (c) 2017-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 <boost/test/unit_test.hpp> 6 : : 7 : : #include <chain.h> 8 : : #include <rpc/blockchain.h> 9 : : #include <test/util/setup_common.h> 10 : : #include <util/string.h> 11 : : 12 : : #include <cstdlib> 13 : : 14 : : /* Equality between doubles is imprecise. Comparison should be done 15 : : * with a small threshold of tolerance, rather than exact equality. 16 : : */ 17 : 0 : static bool DoubleEquals(double a, double b, double epsilon) 18 : 0 : { 19 : 0 : return std::abs(a - b) < epsilon; 20 : : } 21 : : 22 : 0 : static CBlockIndex* CreateBlockIndexWithNbits(uint32_t nbits) 23 : : { 24 : 0 : CBlockIndex* block_index = new CBlockIndex(); 25 : 0 : block_index->nHeight = 46367; 26 : 0 : block_index->nTime = 1269211443; 27 : 0 : block_index->nBits = nbits; 28 : 0 : return block_index; 29 : 0 : } 30 : : 31 : 0 : static void RejectDifficultyMismatch(double difficulty, double expected_difficulty) { 32 : 0 : BOOST_CHECK_MESSAGE( 33 : : DoubleEquals(difficulty, expected_difficulty, 0.00001), 34 : : "Difficulty was " + ToString(difficulty) 35 : : + " but was expected to be " + ToString(expected_difficulty)); 36 : 0 : } 37 : : 38 : : /* Given a BlockIndex with the provided nbits, 39 : : * verify that the expected difficulty results. 40 : : */ 41 : 0 : static void TestDifficulty(uint32_t nbits, double expected_difficulty) 42 : : { 43 : 0 : CBlockIndex* block_index = CreateBlockIndexWithNbits(nbits); 44 : 0 : double difficulty = GetDifficulty(block_index); 45 : 0 : delete block_index; 46 : : 47 : 0 : RejectDifficultyMismatch(difficulty, expected_difficulty); 48 : 0 : } 49 : : 50 : 0 : BOOST_FIXTURE_TEST_SUITE(blockchain_tests, BasicTestingSetup) 51 : : 52 : 0 : BOOST_AUTO_TEST_CASE(get_difficulty_for_very_low_target) 53 : : { 54 : 0 : TestDifficulty(0x1f111111, 0.000001); 55 : 0 : } 56 : : 57 : 0 : BOOST_AUTO_TEST_CASE(get_difficulty_for_low_target) 58 : : { 59 : 0 : TestDifficulty(0x1ef88f6f, 0.000016); 60 : 0 : } 61 : : 62 : 0 : BOOST_AUTO_TEST_CASE(get_difficulty_for_mid_target) 63 : : { 64 : 0 : TestDifficulty(0x1df88f6f, 0.004023); 65 : 0 : } 66 : : 67 : 0 : BOOST_AUTO_TEST_CASE(get_difficulty_for_high_target) 68 : : { 69 : 0 : TestDifficulty(0x1cf88f6f, 1.029916); 70 : 0 : } 71 : : 72 : 0 : BOOST_AUTO_TEST_CASE(get_difficulty_for_very_high_target) 73 : : { 74 : 0 : TestDifficulty(0x12345678, 5913134931067755359633408.0); 75 : 0 : } 76 : : 77 : 0 : BOOST_AUTO_TEST_SUITE_END()