Tuesday, August 22, 2023
HomeBitcointhe way to hash block header in c++

the way to hash block header in c++


<- Advertisement ->

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

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

Anyway, this is the method it’s best to take:

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

  2. Hash headerData utilizing SHA-256 twice utilizing the CalculateDigest() technique 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.knowledge(), headerString.dimension());
    decoder.MessageEnd();

    // Hash the byte array twice
    SHA256 hasher;

    byte hash1[SHA256::DIGESTSIZE];
    hasher.calculateDigest(hash1, (byte*)headerData.knowledge(), headerData.dimension());
    
    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;
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments