Skip to content

Commit ddc9e0c

Browse files
committed
Add header::difficulty().
1 parent 986ac9c commit ddc9e0c

3 files changed

Lines changed: 32 additions & 3 deletions

File tree

include/bitcoin/system/chain/header.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ class BC_API header
8181
void to_data(std::ostream& stream) const NOEXCEPT;
8282
void to_data(writer& sink) const NOEXCEPT;
8383

84-
8584
/// Properties.
8685
/// -----------------------------------------------------------------------
8786
/// Native properties.
@@ -96,6 +95,7 @@ class BC_API header
9695
/// Computed properties.
9796
uint256_t proof() const NOEXCEPT;
9897
hash_digest hash() const NOEXCEPT;
98+
double difficulty() const NOEXCEPT;
9999

100100
/// Cache and metadata.
101101
/// -----------------------------------------------------------------------

src/chain/header.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,29 @@ hash_digest header::hash() const NOEXCEPT
268268
return digest;
269269
}
270270

271+
// computed, not used in consensus.
272+
double header::difficulty() const NOEXCEPT
273+
{
274+
auto shift = bit_and(shift_right(bits_, 24), 0xff_u32);
275+
auto difference =
276+
static_cast<double>(0x0000ffff_u32) /
277+
static_cast<double>(bit_and(bits_, 0x00ffffff_u32));
278+
279+
while (shift < 29u)
280+
{
281+
difference *= 256.0;
282+
++shift;
283+
}
284+
285+
while (shift > 29u)
286+
{
287+
difference /= 256.0;
288+
--shift;
289+
}
290+
291+
return difference;
292+
}
293+
271294
// Cache and metadata.
272295
// ----------------------------------------------------------------------------
273296

test/chain/header.cpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,14 +240,20 @@ BOOST_AUTO_TEST_CASE(header__to_data__writer__expected)
240240
// properties
241241
// ----------------------------------------------------------------------------
242242

243-
// hash
244-
245243
BOOST_AUTO_TEST_CASE(header__proof__genesis_block__expected)
246244
{
247245
const chain::block block{ settings(selection::mainnet).genesis_block };
248246
BOOST_REQUIRE_EQUAL(block.header().proof(), 0x0000000100010001);
249247
}
250248

249+
// hash
250+
251+
BOOST_AUTO_TEST_CASE(header__difficulty__genesis_block__expected)
252+
{
253+
const chain::block block{ settings(selection::mainnet).genesis_block };
254+
BOOST_REQUIRE_EQUAL(block.header().difficulty(), 1.0);
255+
}
256+
251257
// validation (public)
252258
// ----------------------------------------------------------------------------
253259

0 commit comments

Comments
 (0)