Skip to content

Commit

Permalink
Merge pull request #12 from btccom/develop
Browse files Browse the repository at this point in the history
improve format diff, O(n^2) -> O(n)
  • Loading branch information
bitkevin authored Jan 5, 2017
2 parents 36fde0d + e13ab5b commit 20aefac
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 22 deletions.
18 changes: 18 additions & 0 deletions src/Common.h
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,22 @@ inline void BitsToDifficulty(uint32 bits, uint64 *difficulty) {
*difficulty = (uint64)diff;
}

// diff must be 2^N
inline uint64_t formatDifficulty(const uint64_t diff) {
// set 2^63 as maximum difficulty, 2^63 = 9223372036854775808
const uint64_t kMaxDiff = 9223372036854775808ull;
if (diff >= kMaxDiff) {
return kMaxDiff;
}

uint64_t newDiff = 1;
int i = 0;
while (newDiff < diff) {
newDiff = newDiff << 1;
i++;
}
assert(i <= 63);
return 1ULL << i;
}

#endif
26 changes: 4 additions & 22 deletions src/StratumSession.cc
Original file line number Diff line number Diff line change
Expand Up @@ -480,27 +480,16 @@ void StratumSession::_handleRequest_AuthorizePassword(const string &password) {
}
}

d = formatDifficulty(d);
md = formatDifficulty(md);

// set min diff first
if (md >= DiffController::kMinDiff_) {
// diff must be 2^N
double i = 1;
while ((uint64_t)exp2(i) < md) {
i++;
}
md = (uint64_t)exp2(i);

diffController_.setMinDiff(md);
}

// than set current diff
if (d >= DiffController::kMinDiff_) {
// diff must be 2^N
double i = 1;
while ((uint64_t)exp2(i) < d) {
i++;
}
d = (uint64_t)exp2(i);

diffController_.resetCurDiff(d);
}
}
Expand Down Expand Up @@ -584,14 +573,7 @@ void StratumSession::handleExMessage_AuthorizeAgentWorker(const int64_t workerId
}

void StratumSession::_handleRequest_SetDifficulty(uint64_t suggestDiff) {
// suggestDiff must be 2^N
double i = 1;
while ((uint64_t)exp2(i) < suggestDiff) {
i++;
}
suggestDiff = (uint64_t)exp2(i);

diffController_.resetCurDiff(suggestDiff);
diffController_.resetCurDiff(formatDifficulty(suggestDiff));
}

void StratumSession::handleRequest_SuggestTarget(const string &idStr,
Expand Down
12 changes: 12 additions & 0 deletions test/TestCommon.cc
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,15 @@ TEST(Common, BitsToDifficulty) {
ASSERT_EQ((uint64_t)(d * 10000.0), 163074209ull);
}

TEST(Common, formatDifficulty) {
ASSERT_EQ(formatDifficulty(UINT64_MAX), 9223372036854775808ull);

// 2^32 = UINT32_MAX + 1
ASSERT_EQ(formatDifficulty(UINT32_MAX), (uint64_t)UINT32_MAX + 1);
ASSERT_EQ(formatDifficulty((uint64_t)UINT32_MAX + 1), (uint64_t)UINT32_MAX + 1);

ASSERT_EQ(formatDifficulty(0), 1);
ASSERT_EQ(formatDifficulty(1), 1);
ASSERT_EQ(formatDifficulty(2), 2);
ASSERT_EQ(formatDifficulty(3), 4);
}

0 comments on commit 20aefac

Please sign in to comment.