import logging import unittest from aucoin import util logging.basicConfig(level=logging.DEBUG) class TestUtil(unittest.TestCase): def test_hash(self): digest = util.hash(b"Hello, world!") self.assertEqual("315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3", digest.hex()) def test_merkle_root_example(self): """ This test is based on the example from https://en.bitcoin.it/wiki/Protocol_documentation#Merkle_Trees """ a = b"a" b = b"b" c = b"c" # 1st layer d1 = util.hash(a) d2 = util.hash(b) d3 = util.hash(c) d4 = util.hash(c) # odd number of elements, so we take c twice. # 2nd layer d5 = util.hash(d1 + d2) d6 = util.hash(d3 + d4) # 3rd layer: the root d7 = util.hash(d5 + d6) self.assertEqual(d7, util.merkle_root_hash([a, b, c])) def test_merkle_root_long(self): a = b"a" b = b"b" c = b"c" d = b"d" e = b"e" f = b"f" # 1st layer d1 = util.hash(a) d2 = util.hash(b) d3 = util.hash(c) d4 = util.hash(d) d5 = util.hash(e) d6 = util.hash(f) # 2nd layer d7 = util.hash(d1 + d2) d8 = util.hash(d3 + d4) d9 = util.hash(d5 + d6) d10 = d9 # odd number of elements, so we take d9 twice. # 3rd layer d11 = util.hash(d7 + d8) d12 = util.hash(d9 + d10) # 4th layer: the root d13 = util.hash(d11 + d12) self.assertEqual(d13, util.merkle_root_hash([a, b, c, d, e, f])) if __name__ == '__main__': unittest.main()