What’s best method to validate bitcoin goal (issue) worth in C++

0
60


I’ve give you following model that appears to be working accurately for few check circumstances I’ve outlined.

First we want a helper operate that prints hex worth given binary knowledge:

void hexdump(unsigned char *knowledge, int len)
{
    int c = 0;
    whereas (c < len)
    {
        cout << hex << std::setw(2) << std::setfill('0') << static_cast<int>(knowledge[c++]);
    }
    printf("n");
}

Now lets outline the precise operate that takes block.bits and converts it to 256 bit worth in reminiscence:

bool convert_bits(uint32_t bits, uint64_t* worth, int val_len = 4)
{
    assert(val_len == 4);
    assert(worth != NULL);

    if (val_len != 4 || worth == NULL)
    {
        return false;
    }

    // if bits =  0x1b0404cb, hex goal = 0x0404cb * 2**(8*(0x1b - 3)) 
    uint32_t x = 8 * ((bits >> 24) - 3); // variety of zero bits on proper
    uint64_t val = bits & 0x00FFFFFF;

    // Variety of most bits required for val is 24.
    assert(x <= (256 - 24));
    if (x > (256 - 24))
    {
        return false;
    }   

    int startq = (3 - int(x / 64));
    int endq = (3 - int((x + 24) / 64));

    int shift = ((3 + endq) * 64 - x);
    if (startq != endq)
    {
        shift = 64 - shift;
    }

    worth[startq] = htobe64(val << shift);
    worth[endq] = htobe64(val >> shift);

    return true;
}

Now lets check the above operate:

int predominant()
{
    uint64_t num[4] = { 0, 0, 0, 0 };
    if(convert_bits(0x1b0404cb, num))
    {
        hexdump((unsigned char *)num, sizeof(uint64_t) * 4);
    }
    return 0;
}

This prints: 00000000000404cb000000000000000000000000000000000000000000000000

LEAVE A REPLY

Please enter your comment!
Please enter your name here