【发布时间】:2019-10-16 14:41:44
【问题描述】:
我正在尝试用 Java 编写一个非常简单的默克尔树实现。
我正在使用比特币区块链上block 170 中的 txid 值作为参考,所以我可以看到正确的结果应该是什么。
该区块对应的txid如下:
b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082
f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16
据我了解,比特币的默克尔树实现方式如下:
- 将区块中的交易分成两对
- 字节交换 txids
- 连接 txids
- 对连接的对进行双重哈希
需要注意的是:
If there's no additional pairs of txids, concatenate the result of the first pair after double hashing with itself and repeat
我的代码位于如下所示的 switch 语句中:
case "test merkle root": {
// txid A
String A = "b1fea52486ce0c62bb442b530a3f0132b826c74e473d1f2c220bfa78111c5082";
// txid A byte-swapped
String A_little = MainChain.swapEndianness(A);
// txid B
String B = "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16";
// txid B byte-swapped
String B_little = MainChain.swapEndianness(B);
// txid A + B concatenated
String AB_little = A_little + B_little;
// double hash of byte-swapped concatenated A+B
String ABdoubleHash = SHA256.generateSHA256Hash(SHA256.generateSHA256Hash(AB_little));
// double hash concatenated with itself
String ABAB_little = ABdoubleHash + ABdoubleHash;
// double hash of self-concatenated double-hashed txid
String merkleRootLittleEndian = SHA256.generateSHA256Hash(SHA256.generateSHA256Hash(ABAB_little));
// print result byte-swapped back to big-endian
System.out.println("Merkle root: " + MainChain.swapEndianness(merkleRootLittleEndian));
}
我写的swapEndianness方法并不是真正的‘字节级’交换,而是只是改变了String的顺序,看起来是这样的:
public static String swapEndianness(String hash) {
char[] hashAsCharArray = hash.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = hash.length() - 1; i > 0; i-=2) {
sb.append(hashAsCharArray[i - 1]);
sb.append(hashAsCharArray[i]);
}
return sb.toString();
}
这两个txid的merkle root的预期结果是:
7dac2c5666815c17a3b36427de37bb9d2e2c5ccec3f8633eb91a4205cb4c10ff
但是,我最终得到的结果是:
3b40cab1157838cc41b08e27641f65d245957ab07b3504d94bc2d355abaed06c
我没有得到我期望的结果是因为我在进行字节交换时作弊,是因为我错过了一个步骤,还是因为我的代码中有错误(或这些错误的某种组合)?任何帮助将不胜感激!
【问题讨论】:
标签: java merkle-tree