the best way to hash block header in c++

0
52


Firstly, you might have a reputation battle; hash is each the std::string argument handed to calcHash(), and likewise the title of your CryptoPP::SHA256 object. This code will not even compile, so are you positive that is the code you are utilizing?

The code itself is considerably troublesome to learn, too, since you go round nameless objects to nested constructors in an try to be concise, however this simply makes issues needlessly complicated to the reader. Maybe you might have copy-pasted one-liners from different locations?

Anyway, this is the strategy it is best to take:

  1. Use HexDecoder (not HexEncoder) to transform your enter string (let’s name it headerString) to a byte array of the info represented by that hexadecimal string (name the consequence headerData).

  2. Hash headerData utilizing SHA-256 twice utilizing the CalculateDigest() methodology of a CryptoPP::SHA256 object, storing the end in a byte array (name it hash2, as a result of we name the primary hash hash1).

  3. Use HexEncoder to transform hash2 right into a string which is a hexadecimal illustration of the hash (name it hashString).

Here is that in code:

#embrace <iostream>

utilizing namespace std;
utilizing namespace CryptoPP;

static void printHash(std::string headerString) {
    // Convert hex string to byte array
    string headerData;
    HexDecoder decoder = new HexDecoder(new StringSink(headerData));
    decoder.Put((byte*)headerString.information(), headerString.measurement());
    decoder.MessageEnd();

    // Hash the byte array twice
    SHA256 hasher;

    byte hash1[SHA256::DIGESTSIZE];
    hasher.calculateDigest(hash1, (byte*)headerData.information(), headerData.measurement());
    
    byte hash2[SHA256::DIGESTSIZE];
    hasher.calculateDigest(hash2, hash1, hash1.size);

    // Convert consequence to hex string
    string hashString;
    HexEncoder encoder = new HexEncoder(new StringSink(hashString));
    encoder.Put(hash2, sizeof(hash2));
    encoder.MessageEnd();

    // Print the hash
    cout << asLowerCase(hashString) << endl;
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here