首页 > 解决方案 > Test if first two bits of hash are both 1

问题描述

For blockchain mining, I need to test whether the first two bits of a hash are both 1. I am using a Python library called Simple-Python-Blockchain, which calculates a hash using the following method:

    def hash(self):
        h = hashlib.sha256()
        h.update(
        str(self.nonce).encode('utf-8') +
        str(self.data).encode('utf-8') +
        str(self.previous_hash).encode('utf-8') +
        str(self.timestamp).encode('utf-8') +
        str(self.blockNo).encode('utf-8')
        )
        return h.hexdigest()

I tried this way:

str(int(block.hash(),16)).startswith("11")

Please help me understand what has to be done.

标签: pythonblockchain

解决方案


The hash method in your question uses the SHA-256 algorithm, and returns the result as a hexadecimal string. To get the first two bits, we only need to look at the first hexadecimal digit, which encodes the first four bits:

>>> import hashlib
>>> h = hashlib.sha256(b'Hello, world!')
>>> first_4_bits = int(h.hexdigest()[0], base=16)
3

The first two bits will be the upper two bits of this number, so we can right-shift by two places and then compare with the number 3, which is 11 in binary:

>>> (first_4_bits >> 2) == 3
False

Alternatively, we can take advantage of the fact that only c, d, e and f in hexadecimal have 11 as their first two bits:

>>> h.hexdigest()[0] >= 'c'
False

推荐阅读