python - 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.
解决方案
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
推荐阅读
- reactjs - 表示。js findById 与反应
- sql-server - 使用 OpenRowSet 从 Excel 文件中获取一些 NULL 标题
- java - 在 json-io 中读取数组:无法将对象强制转换为 List
- c# - 基于消息头值的 RabbitMQ 队列计数
- python - 当父类需要声明它时,避免在python子类中使用类变量
- python - Python Snake 游戏边框与坐标
- swift - 未找到 PropertyListDecoder 句柄键
- r - 如何使R数据表按钮保存到特定位置
- python - 具有散景的图像绘图的较小范围填充
- google-app-engine - Google App Engine Cron 未在特定时间触发端点