如何计算比特币的 SHA256 哈希 header
How to compute SHA256 hash for bitcoin header
我想了解工作量证明算法。我计算了一个块 header (其中包括随机数):
"02000000aaf8ab82362344f49083ee4edef795362cf135293564c4070000000000000000c009bb6222e9bc4cdb8f26b2e8a2f8d163509691a4038fa692abf9a474c9b21476800755c02e17181fe6c1c3"
我必须对此应用 SHA256 两次。正确答案应该是:
"00000000000000001354e21fea9c1ec9ac337c8a6c0bda736ec1096663383429"
我尝试了pack
、unpack
、hex
等,但我无法得到这个输出。使用 SHA256 将输入转换为输出的正确 Ruby 代码是什么?
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"
糟糕,由于某种原因,结果有点 "backwards"。也许这是一个字节顺序问题?让我们用反转的二进制数据再试一次:
result = d2.reverse.unpack("H*").join
# => "00000000000000001354e21fea9c1ec9ac337c8a6c0bda736ec1096663383429"
宾果!
编辑:澄清一下,这是一个反复试验的解决方案。我对工作量证明算法没有任何特别的见解!
我想了解工作量证明算法。我计算了一个块 header (其中包括随机数):
"02000000aaf8ab82362344f49083ee4edef795362cf135293564c4070000000000000000c009bb6222e9bc4cdb8f26b2e8a2f8d163509691a4038fa692abf9a474c9b21476800755c02e17181fe6c1c3"
我必须对此应用 SHA256 两次。正确答案应该是:
"00000000000000001354e21fea9c1ec9ac337c8a6c0bda736ec1096663383429"
我尝试了pack
、unpack
、hex
等,但我无法得到这个输出。使用 SHA256 将输入转换为输出的正确 Ruby 代码是什么?
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"
糟糕,由于某种原因,结果有点 "backwards"。也许这是一个字节顺序问题?让我们用反转的二进制数据再试一次:
result = d2.reverse.unpack("H*").join
# => "00000000000000001354e21fea9c1ec9ac337c8a6c0bda736ec1096663383429"
宾果!
编辑:澄清一下,这是一个反复试验的解决方案。我对工作量证明算法没有任何特别的见解!