Sha256
我如何計算這個原始交易的 txid?
我正在嘗試使用 Python 解析比特幣塊。
我通過 JSON-RPC 呼叫 getrawtransaction。我懂了:
01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d014dffffffff0100f2052a01000000434104e70a02f5af48a1989bf630d92523c9d14c45c75f7d1b998e962bff6ff9995fc5bdb44f1793b37495d80324acba7c8f537caaf8432b8d47987313060cc82d8a93ac00000000
我如何計算這個原始交易的 txid?
Txids有兩種形式; 內部用於出口和Merkle葉(內部字節順序)以及RPC呼叫和塊資源管理器(RPC字節順序)的表單。這些通常被稱為,相應的,小型字節字節順序和大埠字節順序(儘管這些描述並不完全準確)。
以下是來自BitcoIn.org開發人員文件的Python程式碼為您提出的事務中的TXID生成表單:
#!/usr/bin/env python from sys import byteorder from hashlib import sha256 ## You can put in $data an 80-byte block header to get its header hash, ## or a raw transaction to get its txid data = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d014dffffffff0100f2052a01000000434104e70a02f5af48a1989bf630d92523c9d14c45c75f7d1b998e962bff6ff9995fc5bdb44f1793b37495d80324acba7c8f537caaf8432b8d47987313060cc82d8a93ac00000000".decode("hex") hash = sha256(sha256(data).digest()).digest() print "Warning: this code only tested on a little-endian x86_64 arch" print print "System byte order:", byteorder print "Internal-Byte-Order Hash: ", hash.encode('hex_codec') print "RPC-Byte-Order Hash: ", hash[::-1].encode('hex_codec')
這是輸出:
Warning: this code only tested on a little-endian x86_64 arch System byte order: little Internal-Byte-Order Hash: 660802c98f18fd34fd16d61c63cf447568370124ac5f3be626c2e1c3c9f0052d RPC-Byte-Order Hash: 2d05f0c9c3e1c226e63b5fac240137687544cf631cd616fd34fd188fc9020866
比特幣使用的內部字節序實際上是Little-Endian,而 RPC 字節序是Big-Endian。有關解釋其工作原理的詳細資訊,請參閱此連結。