Bugfix: bitcoin/script: Correctly interpret P2SH addresses, and reject anything unrec...
[bitcoin:eloipool.git] / bitcoin / script.py
1 from base58 import b58decode
2 from util import dblsha
3
4 def _Address2PKH(addr):
5         try:
6                 addr = b58decode(addr, 25)
7         except:
8                 return None
9         if addr is None:
10                 return None
11         ver = addr[0]
12         cksumA = addr[-4:]
13         cksumB = dblsha(addr[:-4])[:4]
14         if cksumA != cksumB:
15                 return None
16         return (ver, addr[1:-4])
17
18 class BitcoinScript:
19         @classmethod
20         def toAddress(cls, addr):
21                 d = _Address2PKH(addr)
22                 if not d:
23                         raise ValueError('invalid address')
24                 (ver, pubkeyhash) = d
25                 if ver == 0 or ver == 111:
26                         return b'\x76\xa9\x14' + pubkeyhash + b'\x88\xac'
27                 elif ver == 5 or ver == 196:
28                         return b'\xa9\x14' + pubkeyhash + '\x87'
29                 raise ValueError('invalid address version')
30
31 def countSigOps(s):
32         # FIXME: don't count data as ops
33         c = 0
34         for ch in s:
35                 if 0xac == ch & 0xfe:
36                         c += 1
37                 elif 0xae == ch & 0xfe:
38                         c += 20
39         return c