SideChain: use full 128 bits in get_difficulty

This commit is contained in:
SChernykh
2022-11-15 16:39:39 +01:00
parent e9a2e4b076
commit b3bce1651b
4 changed files with 166 additions and 33 deletions
+48 -1
View File
@@ -197,6 +197,41 @@ struct difficulty_type
return *this;
}
FORCEINLINE difficulty_type& operator-=(const difficulty_type& b)
{
#ifdef _MSC_VER
_subborrow_u64(_subborrow_u64(0, lo, b.lo, &lo), hi, b.hi, &hi);
#elif __GNUC__
*reinterpret_cast<unsigned __int128*>(this) -= *reinterpret_cast<const unsigned __int128*>(&b);
#else
const uint64_t t = b.lo;
const uint64_t carry = (lo < t) ? 1 : 0;
lo -= t;
hi -= b.hi + carry;
#endif
return *this;
}
FORCEINLINE difficulty_type& operator*=(const uint64_t b)
{
uint64_t t;
lo = umul128(lo, b, &t);
hi = t + hi * b;
return *this;
}
FORCEINLINE difficulty_type& operator/=(const uint64_t b)
{
const uint64_t t = hi;
hi = t / b;
uint64_t r;
lo = udiv128(t % b, lo, b, &r);
return *this;
}
FORCEINLINE bool operator<(const difficulty_type& other) const
{
if (hi < other.hi) return true;
@@ -244,7 +279,19 @@ struct difficulty_type
static_assert(sizeof(difficulty_type) == sizeof(uint64_t) * 2, "struct difficulty_type has invalid size, check your compiler options");
static_assert(std::is_standard_layout<difficulty_type>::value, "struct difficulty_type is not a POD, check your compiler options");
difficulty_type operator+(const difficulty_type& a, const difficulty_type& b);
FORCEINLINE difficulty_type operator+(const difficulty_type& a, const difficulty_type& b)
{
difficulty_type result = a;
result += b;
return result;
}
FORCEINLINE difficulty_type operator-(const difficulty_type& a, const difficulty_type& b)
{
difficulty_type result = a;
result -= b;
return result;
}
struct TxMempoolData
{
+3 -14
View File
@@ -1209,20 +1209,9 @@ bool SideChain::get_difficulty(const PoolBlock* tip, std::vector<DifficultyData>
}
}
// This is correct as long as the difference between two 128-bit difficulties is less than 2^64, even if it wraps
const uint64_t delta_diff = diff2.lo - diff1.lo;
uint64_t product[2];
product[0] = umul128(delta_diff, m_targetBlockTime, &product[1]);
if (product[1] >= delta_t) {
LOGERR(1, "calculated difficulty is too high for block at height = " << tip->m_sidechainHeight << ", id = " << tip->m_sidechainId << ", mainchain height = " << tip->m_txinGenHeight);
return false;
}
uint64_t rem;
curDifficulty.lo = udiv128(product[1], product[0], delta_t, &rem);
curDifficulty.hi = 0;
curDifficulty = diff2 - diff1;
curDifficulty *= m_targetBlockTime;
curDifficulty /= delta_t;
if (curDifficulty < m_minDifficulty) {
curDifficulty = m_minDifficulty;
-7
View File
@@ -126,13 +126,6 @@ NOINLINE bool difficulty_type::check_pow(const hash& pow_hash) const
return true;
}
difficulty_type operator+(const difficulty_type& a, const difficulty_type& b)
{
difficulty_type result = a;
result += b;
return result;
}
std::ostream& operator<<(std::ostream& s, const difficulty_type& d)
{
char buf[log::Stream::BUF_SIZE + 1];