用于构造merkle树和验证日志证明的python库
pymerkle的Python项目详细描述
pymerkle:一个用于构造merkle树和验证日志证明的python库
完整的文档可以在pymerkle.readthedocs.org找到。
此库实现
- 一个用于binary-balancedmerkle树(可能有odd叶子数)的类,能够生成consistency proof(除了audit proof(以及inclusion tests),支持所有哈希算法(包括sha3变体)和提供的大多数编码类型通过
Python>=3.6
- 防御second preimage攻击
- 验证生成的证明的灵活机制< /LI>
它是目前唯一一个实现上述所有功能的python库,着眼于Certificate Transparency等协议和实际应用程序。
安装
pip3 install pymerkle
快速示例
另请参见Usage and API
frompymerkleimport*# Import merkle_tree, validate_proof# and proof_validatortree=merkle_tree()# Create empty SHA256/UTF-8 Merkle-tree with# defense against second-preimage attackvalidator=proof_validator()# Create object for validating proofs# Successively update the tree with one hundred recordsforiinrange(100):tree.update(bytes('{}-th record'.format(i),'utf-8'))p=tree.audit_proof(b'12-th record')# Generate audit-proof for the given recordq=tree.audit_proof(55)# Generate audit-proof based upon the 56-th leaf# Quick validation of the above proofsvalidate_proof(target_hash=tree.root_hash(),proof=p)# Truevalidate_proof(target_hash=tree.root_hash(),proof=q)# True# Store the tree's current state (root-hash and length) for later usetop_hash=tree.root_hash()length=tree.length()# Update the tree by encrypting a new logtree.encrypt_log('logs/sample_log')# Generate consistency-proof for the stage before encrypting the logr=tree.consistency_proof(old_hash=top_hash,sublength=length)# Validate consistency-proof and generate receiptvalidation_receipt=validator.validate(target_hash=tree.root_hash(),proof=r)
树结构
与大多数实现相反,merkle树始终是binary balanced,除了外部节点(leaves)具有two父节点外,所有节点都是。这可以实现如下目的:在附加一块新叶时,不必提升或复制一片孤叶,而是创建一个分叉节点,这样具有相同叶数的树总是具有相同的结构,并且可以避免不同生长策略之间的输入冲突(独立于已配置哈希和编码类型)。这种标准化对于以下方面更为重要:
- 快速生成一致性证明路径(基于2的递减幂的加法分解)
- 在追加新叶后快速重新计算根哈希,因为只需要重新计算树最左边分支处的哈希
- 内存效率,因为相对于树的长度,节点的高度和总数都控制在最小值。例如,具有9叶的树在本实现中具有17节点,而所描述的结构中的节点总数是20。
该拓扑结构与this论文第5.4节描述的二进制sekura tree的拓扑结构相同。遵循pymerkle.merkle_tree.update
方法的直接算法以获得进一步的了解,或者在项目存储库中的^{
偏离比特币规范
与merkle树的bitcoin规范相反,为了使树保持真正的二元性,孤独的叶子不会被复制。相反,在最右边的分支创建分支节点允许树在任何更新时保持平衡。因此,即使对第二次preimage攻击(见下文)的安全性被停用,当前按结构实现的方法也不受所述攻击的攻击here的影响。
防御第二次图像前攻击
默认情况下,对第二个preimage攻击的防御被激活。大致来说,它包括以下安全措施:
在计算叶的散列值之前,用空的十六进制
0x00
在计算散列任何内部节点之前,用十六进制单位
0x01
(请参见here或here了解一些细节)。阅读项目存储库中的^{
运行测试
要运行所有集成测试,请执行
./run_tests.sh
从项目的根目录中。或者,运行命令pytest tests/
。您只能使用命令pytest tests/test_log_encryption.py
运行特定的测试文件,例如test_log_encryption.py
是啊。