Bugfix: bitcoin/script: Correctly interpret P2SH addresses, and reject anything unrec...
[bitcoin:eloipool.git] / merkletree.py
1 from bitcoin.txn import Txn
2 from util import dblsha
3
4 class MerkleTree:
5         def __init__(self, data):
6                 self.data = data
7                 self.recalculate()
8         
9         def recalculate(self):
10                 L = self.data
11                 steps = []
12                 if len(L) > 1:
13                         if isinstance(L[1], Txn):
14                                 L = list(map(lambda a: a.txid if a else a, L))
15                         while True:
16                                 Ll = len(L)
17                                 steps.append(L[1])
18                                 if Ll == 2:
19                                         break
20                                 if Ll % 2:
21                                         L += [L[-1]]
22                                 L = [None] + [dblsha(L[i] + L[i + 1]) for i in range(2, Ll, 2)]
23                 self._steps = steps
24         
25         def withFirst(self, f):
26                 if isinstance(f, Txn):
27                         f = f.txid
28                 steps = self._steps
29                 for s in steps:
30                         f = dblsha(f + s)
31                 return f
32         
33         def merkleRoot(self):
34                 return self.withFirst(self.data[0])
35
36 # MerkleTree test case
37 from binascii import a2b_hex, b2a_hex
38 mt = MerkleTree([None] + [a2b_hex(a) for a in [
39         '999d2c8bb6bda0bf784d9ebeb631d711dbbbfe1bc006ea13d6ad0d6a2649a971',
40         '3f92594d5a3d7b4df29d7dd7c46a0dac39a96e751ba0fc9bab5435ea5e22a19d',
41         'a5633f03855f541d8e60a6340fc491d49709dc821f3acb571956a856637adcb6',
42         '28d97c850eaf917a4c76c02474b05b70a197eaefb468d21c22ed110afe8ec9e0',
43 ]])
44 assert(
45         b'82293f182d5db07d08acf334a5a907012bbb9990851557ac0ec028116081bd5a' ==
46         b2a_hex(mt.withFirst(a2b_hex('d43b669fb42cfa84695b844c0402d410213faa4f3e66cb7248f688ff19d5e5f7')))
47 )