我试图理解工作证明算法。我计算了一个块头(包括nonce):
"02000000aaf8ab82362344f49083ee4edef795362cf135293564c4070000000000000000c009bb6222e9bc4cdb8f26b2e8a2f8d163509691a4038fa692abf9a474c9b21476800755c02e17181fe6c1c3"
我必须两次使用SHA256。正确的答案应该是:
"00000000000000001354e21fea9c1ec9ac337c8a6c0bda736ec1096663383429"
我尝试了pack
,unpack
,hex
等,但我无法获得此输出。使用SHA256将输入转换为输出的正确Ruby代码是什么?
答案 0 :(得分:4)
header_hex = "02000000aaf8ab82362344f49083ee4edef795362cf135293564c4070000000000000000c009bb6222e9bc4cdb8f26b2e8a2f8d163509691a4038fa692abf9a474c9b21476800755c02e17181fe6c1c3"
# Decode header hex into binary string
header = [header_hex].pack("H*")
# Apply SHA256 twice
require "digest"
d1 = Digest::SHA256.digest(header)
d2 = Digest::SHA256.digest(d1)
# Convert to hex
result = d2.unpack("H*").join
# => "293438636609c16e73da0b6c8a7c33acc91e9cea1fe254130000000000000000"
哎呀,由于某种原因,结果有点“倒退”。也许这是一个字节排序问题?让我们再次尝试反转二进制数据:
result = d2.reverse.unpack("H*").join
# => "00000000000000001354e21fea9c1ec9ac337c8a6c0bda736ec1096663383429"
宾果!
编辑:只是为了澄清,这是一个试错法的解决方案。我对工作证明算法没有任何特别的了解!