Skip to content

Commit

Permalink
Generic difficulty conversions (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanjiang Yu committed Apr 15, 2019
1 parent 4c121d0 commit 652e780
Show file tree
Hide file tree
Showing 16 changed files with 207 additions and 148 deletions.
29 changes: 29 additions & 0 deletions src/Difficulty.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
The MIT License (MIT)
Copyright (c) [2019] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "Difficulty.h"

void BitsToTarget(uint32_t bits, uint256 &target) {
target = ArithToUint256(arith_uint256{}.SetCompact(bits));
}
104 changes: 104 additions & 0 deletions src/Difficulty.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
The MIT License (MIT)
Copyright (c) [2019] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#pragma once

#include "arith_uint256.h"
#include "uint256.h"

#include <array>
#include <cmath>
#include <cstdint>
#include <string>

void BitsToTarget(uint32_t bits, uint256 &target);

template <uint32_t DiffOneBits, size_t TableSize = 64>
struct Difficulty {
static const uint64_t GetDiffOneBits() { return DiffOneBits; }

static const arith_uint256 &GetDiffOneTarget() {
static const auto DiffOneTarget = arith_uint256{}.SetCompact(DiffOneBits);
return DiffOneTarget;
}

static const std::array<uint256, TableSize> &GetDiffToTargetTable() {
static const auto DiffToTargetTable = GenerateDiffToTargetTable();
return DiffToTargetTable;
}

static std::array<uint256, TableSize> GenerateDiffToTargetTable() {
std::array<uint256, TableSize> table;
uint32_t shifts = 0;
for (auto &target : table) {
target = ArithToUint256(GetDiffOneTarget() >> (shifts++));
}
return table;
}

static uint64_t TargetToDiff(uint256 &target) {
arith_uint256 t = UintToArith256(target);
return (GetDiffOneTarget() / t).GetLow64();
}

static uint64_t TargetToDiff(const std::string &str) {
auto target = uint256S(str);
return TargetToDiff(target);
}

static void
DiffToTarget(uint64_t diff, uint256 &target, bool useTable = true) {
static const auto MaxTarget = uint256S(
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
if (diff == 0) {
target = MaxTarget;
return;
}

if (useTable) {
// try to find by table
static const auto &DiffToTargetTable = GetDiffToTargetTable();
auto p = static_cast<uint64_t>(log2(diff));
if (p < TableSize && diff == (1ull << p)) {
target = DiffToTargetTable[p];
return;
}
}

// If it is not found in the table, it will be calculated.
target = ArithToUint256(GetDiffOneTarget() / diff);
}

static void BitsToDifficulty(uint32_t bits, double *difficulty) {
arith_uint256 target;
target.SetCompact(bits);
*difficulty = GetDiffOneTarget().getdouble() / target.getdouble();
}

static void BitsToDifficulty(uint32_t bits, uint64_t *difficulty) {
arith_uint256 target;
target.SetCompact(bits);
*difficulty = (GetDiffOneTarget() / target).GetLow64();
}
};
14 changes: 7 additions & 7 deletions src/bitcoin/BitcoinUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@
#include <key_io.h>
#endif

#include "CommonBitcoin.h"

#if defined(CHAIN_TYPE_BCH) || defined(CHAIN_TYPE_BSV)

// header that defined DecodeDestination & IsValidDestinationString
Expand Down Expand Up @@ -114,19 +112,21 @@ std::vector<uint256> BlockMerkleBranch(const CBlock &block, uint32_t position);
#endif

uint256 ComputeCoinbaseMerkleRoot(
const std::vector<char> &coinbaseBin, const vector<uint256> &merkleBranch);
const std::vector<char> &coinbaseBin,
const std::vector<uint256> &merkleBranch);

std::string EncodeHexBlock(const CBlock &block);
std::string EncodeHexBlockHeader(const CBlockHeader &blkHeader);

int64_t GetBlockReward(int nHeight, const Consensus::Params &consensusParams);

bool checkBitcoinRPC(const string &rpcAddr, const string &rpcUserpass);
bool checkBitcoinRPC(
const std::string &rpcAddr, const std::string &rpcUserpass);

int32_t getBlockHeightFromCoinbase(const string &coinbase1);
int32_t getBlockHeightFromCoinbase(const std::string &coinbase1);

string getNotifyHashStr(const uint256 &hash);
string getNotifyUint32Str(const uint32_t var);
std::string getNotifyHashStr(const uint256 &hash);
std::string getNotifyUint32Str(const uint32_t var);

inline uint16_t SwapUint(uint16_t v) {
return (v >> 8) | (v << 8);
Expand Down
98 changes: 0 additions & 98 deletions src/bitcoin/CommonBitcoin.cc

This file was deleted.

25 changes: 9 additions & 16 deletions src/bitcoin/CommonBitcoin.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,14 @@
#ifndef POOL_COMMON_BITCOIN_H_
#define POOL_COMMON_BITCOIN_H_

#include "Common.h"

#include <uint256.h>

////////////////////////////// for Bitcoin //////////////////////////////
uint64_t TargetToDiff(uint256 &target);
uint64_t TargetToDiff(const string &str);

void BitsToTarget(uint32_t bits, uint256 &target);
void DiffToTarget(uint64_t diff, uint256 &target, bool useTable = true);
void BitsToDifficulty(uint32_t bits, double *difficulty);
void BitsToDifficulty(uint32_t bits, uint64_t *difficulty);

uint32_t GetDiff1Bits();

////////////////////////////// for Bitcoin //////////////////////////////
#include "Difficulty.h"

#ifdef CHAIN_TYPE_LTC
using BitcoinDifficulty = Difficulty<0x1f00ffff>;
#elif defined(CHAIN_TYPE_ZEC)
using BitcoinDifficulty = Difficulty<0x1f07ffff>;
#else
using BitcoinDifficulty = Difficulty<0x1d00ffff>;
#endif

#endif
4 changes: 2 additions & 2 deletions src/bitcoin/StratumBitcoin.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ class ShareBitcoin : public sharebase::BitcoinMsg {
}

double networkDifficulty = 1.0; // 0.0;
BitsToDifficulty(blkbits(), &networkDifficulty);
BitcoinDifficulty::BitsToDifficulty(blkbits(), &networkDifficulty);

if (networkDifficulty < (double)sharediff()) {
return 1.0;
Expand Down Expand Up @@ -223,7 +223,7 @@ class ShareBitcoin : public sharebase::BitcoinMsg {
std::string toString() const {

double networkDifficulty = 0.0;
BitsToDifficulty(blkbits(), &networkDifficulty);
BitcoinDifficulty::BitsToDifficulty(blkbits(), &networkDifficulty);

return Strings::Format(
"share(jobId: %u, ip: %s, userId: %d, "
Expand Down
2 changes: 1 addition & 1 deletion src/bitcoin/StratumMinerBitcoin.cc
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ void StratumMinerBitcoin::handleRequest_Submit(

// calc jobTarget
uint256 jobTarget;
DiffToTarget(share.sharediff(), jobTarget);
BitcoinDifficulty::DiffToTarget(share.sharediff(), jobTarget);

// we send share to kafka by default, but if there are lots of invalid
// shares in a short time, we just drop them.
Expand Down
5 changes: 3 additions & 2 deletions src/bitcoin/StratumServerBitcoin.cc
Original file line number Diff line number Diff line change
Expand Up @@ -524,8 +524,9 @@ int ServerBitcoin::checkShare(
// print out high diff share, 2^10 = 1024
if ((bnBlockHash >> 10) <= bnNetworkTarget) {
LOG(INFO) << "high diff share, blkhash: " << blkHash.ToString()
<< ", diff: " << TargetToDiff(blkHash)
<< ", networkDiff: " << TargetToDiff(sjob->networkTarget_)
<< ", diff: " << BitcoinDifficulty::TargetToDiff(blkHash)
<< ", networkDiff: "
<< BitcoinDifficulty::TargetToDiff(sjob->networkTarget_)
<< ", by: " << workFullName;
}

Expand Down
6 changes: 3 additions & 3 deletions src/bitcoin/StratumSessionBitcoin.cc
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ void StratumSessionBitcoin::sendSetDifficulty(
#ifdef CHAIN_TYPE_ZEC
// {"id": null, "method": "mining.set_target", "params": ["TARGET"]}
uint256 target;
DiffToTarget(difficulty, target);
BitcoinDifficulty::DiffToTarget(difficulty, target);

s = Strings::Format(
"{\"id\":null,\"method\":\"mining.set_target\""
Expand Down Expand Up @@ -443,8 +443,8 @@ void StratumSessionBitcoin::handleRequest_SuggestTarget(
return;
}

suggestedDiff_ =
formatDifficulty(TargetToDiff(jparams.children()->at(0).str()));
suggestedDiff_ = formatDifficulty(
BitcoinDifficulty::TargetToDiff(jparams.children()->at(0).str()));
responseTrue(idStr);
}

Expand Down
5 changes: 3 additions & 2 deletions src/bitcoin/WatcherBitcoin.cc
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,9 @@ void PoolWatchClientBitcoin::handleStratumMessage(const string &line) {
// 2 times.
// @see <https://www.bitcoinabc.org/2017-11-01-DAA/>
double poolDiff, jobDiff;
BitsToDifficulty(poolStratumJob->nBits_, &poolDiff);
BitsToDifficulty(nBits, &jobDiff);
BitcoinDifficulty::BitsToDifficulty(
poolStratumJob->nBits_, &poolDiff);
BitcoinDifficulty::BitsToDifficulty(nBits, &jobDiff);
double multiple = jobDiff / poolDiff;
if (multiple < 0.5 || multiple > 2.0) {
LOG(WARNING) << "<" << poolName_
Expand Down
Loading

0 comments on commit 652e780

Please sign in to comment.