I am currently in the process of creating a simple bitcoin miner in c++, and need some help optimizing part of it.
I have a string in hexadecimal value, which is parsed into binary (code below) due to the need to run the OpenSSL sha256 hashing function on it. I need to continuous do sha256 hashing, however each time the last 8 chars of the hexadecimal value need to be incremented.
Currently I do this by converting the binary value back to an hexadecimal value, convert the last 8 chars of that to a long, increment the long, and then convert the whole thing back to binary again, which of course is highly inefficient.
What is the most optimal way of incrementing the binary value?
// parse an hexidemical string into a binary format
void toBytes(std::string input,unsigned char *result){
for(int i=0, j=0; i < input.size(); j++, i+=2) {
std::string twoChars = input.substr(i,2);
result[j] = (unsigned char)std::stoi(twoChars,0,16);
}
}
// converts a binary unsigned char into a hexademical string
std::string toHex(unsigned char* data, int len) {
std::string result("");
char buf[2];
int c;
c=0;
while(c < len) {
sprintf(buf,"%.2x", data[c++]);
result+=buf;
}
return result;
}
Here's my current, and very inefficient addition:
void addNonce(unsigned char * binary, int length) {
std::string hex = toHex(binary, length);
std::string nonceString = hex.substr(152,8);
long nonce = std::strtol(hex.substr(152,8).c_str(),NULL,16 );
nonce++;
char buf[8];
sprintf(buf, "%.8lx", nonce);
hex.replace(152,8,buf);
toBytes(hex,binary);
}
Here's an example of an incrementation in hexadecimal format (I need to increment once, then hash that, increment again, hash, until the maximum value):
020000001fba9705b223d40c25b0aba35fee549aa477307862fb45ad18020000
0000000033d14883e297679e3f9a5eb108dab72ff0998e7622e427273e90027e
312ba443105315513c1f051a00000000
020000001fba9705b223d40c25b0aba35fee549aa477307862fb45ad18020000
0000000033d14883e297679e3f9a5eb108dab72ff0998e7622e427273e90027e
312ba443105315513c1f051a00000001
Up to the maximum value
020000001fba9705b223d40c25b0aba35fee549aa477307862fb45ad18020000
0000000033d14883e297679e3f9a5eb108dab72ff0998e7622e427273e90027e
312ba443105315513c1f051aFFFFFFFF