3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 from functools import partial
20 from itertools import imap
29 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
30 __b58base = len(__b58chars)
34 return s.decode('hex')[::-1].encode('hex')
37 def int_to_hex(i, length=1):
38 s = hex(i)[2:].rstrip('L')
39 s = "0"*(2*length - len(s)) + s
47 return "fd" + int_to_hex(i, 2)
49 return "fe" + int_to_hex(i, 4)
51 return "ff" + int_to_hex(i, 8)
54 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
57 hash_encode = lambda x: x[::-1].encode('hex')
60 hash_decode = lambda x: x.decode('hex')[::-1]
63 def header_to_string(res):
64 pbh = res.get('prev_block_hash')
68 return int_to_hex(res.get('version'), 4) \
70 + rev_hex(res.get('merkle_root')) \
71 + int_to_hex(int(res.get('timestamp')), 4) \
72 + int_to_hex(int(res.get('bits')), 4) \
73 + int_to_hex(int(res.get('nonce')), 4)
77 return int('0x' + s[::-1].encode('hex'), 16)
80 def header_from_string(s):
82 'version': hex_to_int(s[0:4]),
83 'prev_block_hash': hash_encode(s[4:36]),
84 'merkle_root': hash_encode(s[36:68]),
85 'timestamp': hex_to_int(s[68:72]),
86 'bits': hex_to_int(s[72:76]),
87 'nonce': hex_to_int(s[76:80]),
91 ############ functions from pywallet #####################
96 def hash_160(public_key):
98 md = hashlib.new('ripemd160')
99 md.update(hashlib.sha256(public_key).digest())
103 md = ripemd.new(hashlib.sha256(public_key).digest())
107 def public_key_to_bc_address(public_key):
108 return hash_160_to_bc_address(hash_160(public_key))
111 def hash_160_to_bc_address(h160):
114 vh160 = chr(addrtype) + h160
116 addr = vh160 + h[0:4]
117 return b58encode(addr)
120 def bc_address_to_hash_160(addr):
123 bytes = b58decode(addr, 25)
128 """encode v, which is a string of bytes, to base58."""
131 for (i, c) in enumerate(v[::-1]):
132 long_value += (256**i) * ord(c)
135 while long_value >= __b58base:
136 div, mod = divmod(long_value, __b58base)
137 result = __b58chars[mod] + result
139 result = __b58chars[long_value] + result
141 # Bitcoin does a little leading-zero-compression:
142 # leading 0-bytes in the input become leading-1s
150 return (__b58chars[0]*nPad) + result
153 def b58decode(v, length):
154 """ decode v into a string of len bytes."""
156 for (i, c) in enumerate(v[::-1]):
157 long_value += __b58chars.find(c) * (__b58base**i)
160 while long_value >= 256:
161 div, mod = divmod(long_value, 256)
162 result = chr(mod) + result
164 result = chr(long_value) + result
168 if c == __b58chars[0]:
173 result = chr(0)*nPad + result
174 if length is not None and len(result) != length:
180 def EncodeBase58Check(vchIn):
182 return b58encode(vchIn + hash[0:4])
185 def DecodeBase58Check(psz):
186 vchRet = b58decode(psz, None)
197 def PrivKeyToSecret(privkey):
198 return privkey[9:9+32]
201 def SecretToASecret(secret):
202 vchIn = chr(addrtype+128) + secret
203 return EncodeBase58Check(vchIn)
206 def ASecretToSecret(key):
207 vch = DecodeBase58Check(key)
208 if vch and vch[0] == chr(addrtype+128):
214 ########### end pywallet functions #######################
216 def random_string(length):
217 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(length))
221 return time.strftime("[%d/%m/%Y-%H:%M:%S]")
224 print_lock = threading.Lock()
227 def print_log(*args):
229 sys.stderr.write(timestr() + " " + " ".join(imap(str, args)) + "\n")