【问题标题】:My Merkle Tree calculation does not match the actual one我的默克尔树计算与实际不符
【发布时间】:2023-01-05 10:42:25
【问题描述】:

我正在研究比特币。

https://en.bitcoin.it/wiki/Protocol_documentation#Merkle_Trees

我阅读了上面的 URL 并在 Python 中实现了 Merkle 根。

使用下面的 API,我收集了区块 641150 中的所有交易并计算了默克尔根。

https://www.blockchain.com/explorer/api/blockchain_api

下面是期望值 67a637b1c49d95165b3dd3177033adbbbc880f6da3620498d451ee0976d7b1f4 (https://www.blockchain.com/btc/block/641150)

我计算的值如下 f2a2207a1e8360b75729fd2f23659b1b79b14940b6e4982a985cf6aa6f941ad7

怎么了?

我的 python 代码是;

from hashlib import sha256
import requests, json

base_url = 'https://blockchain.info/rawblock/'
block_hash = '000000000000000000042cef688cf40b4a70ac814e4222e6646bd6bb79d18168'
end_point = base_url + block_hash

def reverse(hex_be):
    bytes_be = bytes.fromhex(hex_be)
    bytes_le = bytes_be[::-1]
    hex_le = bytes_le.hex()
    return hex_le
    
def dhash(hash):
    return sha256(sha256(hash.encode('utf-8')).hexdigest().encode('utf-8')).hexdigest()

def culculate_merkle(hash_list):

    if len(hash_list) == 1:
        return dhash(hash_list[0])

    hashed_list = list(map(dhash, hash_list))

    if len(hashed_list) % 2 == 1:
        hashed_list.append(hashed_list[-1])
    
    parent_hash_list = []
        
    it = iter(hashed_list)
    for hash1, hash2 in zip(it, it):
        parent_hash_list.append(hash1 + hash2)

    hashed_list = list(map(dhash, hash_list))
    return culculate_merkle(parent_hash_list)

data = requests.get(end_point)
jsondata = json.loads(data.text)
tx_list = list(map(lambda tx_object: tx_object['hash'], jsondata['tx']))

markleroot = '67a637b1c49d95165b3dd3177033adbbbc880f6da3620498d451ee0976d7b1f4'

tx_list = list(map(reverse, tx_list))

output = culculate_merkle(tx_list)
output = reverse(output)
print(output)

结果

$ python merkleTree.py
f2a2207a1e8360b75729fd2f23659b1b79b14940b6e4982a985cf6aa6f941ad7

我希望得到以下输出结果

67a637b1c49d95165b3dd3177033adbbbc880f6da3620498d451ee0976d7b1f4

【问题讨论】:

    标签: python sha256 bitcoin merkle-tree


    【解决方案1】:

    自我解决

    第一的: dhash 计算方法有误。 第二: 从 API 获取的哈希列表已经应用了一次 dhash。 ⇒ 第一次在没有这个视角的情况下执行 dash

    完整的源代码总结在以下博客中(日文) https://tec.tecotec.co.jp/entry/2022/12/25/000000

    【讨论】:

      猜你喜欢
      • 2014-02-13
      • 2019-05-17
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2019-09-18
      相关资源
      最近更新 更多