1 # this code comes from ABE. it can probably be simplified
5 #from bitcoin import public_key_to_bc_address, hash_160_to_bc_address, hash_encode
12 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
13 hash_encode = lambda x: x[::-1].encode('hex')
14 hash_decode = lambda x: x.decode('hex')[::-1]
16 def hash_160(public_key):
17 md = hashlib.new('ripemd160')
18 md.update(hashlib.sha256(public_key).digest())
21 def public_key_to_bc_address(public_key):
22 h160 = hash_160(public_key)
23 return hash_160_to_bc_address(h160)
25 def hash_160_to_bc_address(h160):
26 vh160 = chr(addrtype) + h160
29 return b58encode(addr)
31 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
32 __b58base = len(__b58chars)
35 """ encode v, which is a string of bytes, to base58."""
38 for (i, c) in enumerate(v[::-1]):
39 long_value += (256**i) * ord(c)
42 while long_value >= __b58base:
43 div, mod = divmod(long_value, __b58base)
44 result = __b58chars[mod] + result
46 result = __b58chars[long_value] + result
48 # Bitcoin does a little leading-zero-compression:
49 # leading 0-bytes in the input become leading-1s
52 if c == '\0': nPad += 1
55 return (__b58chars[0]*nPad) + result
57 def b58decode(v, length):
58 """ decode v into a string of len bytes."""
60 for (i, c) in enumerate(v[::-1]):
61 long_value += __b58chars.find(c) * (__b58base**i)
64 while long_value >= 256:
65 div, mod = divmod(long_value, 256)
66 result = chr(mod) + result
68 result = chr(long_value) + result
72 if c == __b58chars[0]: nPad += 1
75 result = chr(0)*nPad + result
76 if length is not None and len(result) != length:
83 # Workalike python implementation of Bitcoin's CDataStream class.
89 class SerializationError(Exception):
90 """ Thrown when there's a problem deserializing or serializing """
92 class BCDataStream(object):
101 def write(self, bytes): # Initialize with string of bytes
102 if self.input is None:
107 def map_file(self, file, start): # Initialize with bytes from file
108 self.input = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
109 self.read_cursor = start
110 def seek_file(self, position):
111 self.read_cursor = position
112 def close_file(self):
115 def read_string(self):
116 # Strings are encoded depending on length:
117 # 0 to 252 : 1-byte-length followed by bytes (if any)
118 # 253 to 65,535 : byte'253' 2-byte-length followed by bytes
119 # 65,536 to 4,294,967,295 : byte '254' 4-byte-length followed by bytes
120 # ... and the Bitcoin client is coded to understand:
121 # greater than 4,294,967,295 : byte '255' 8-byte-length followed by bytes of string
122 # ... but I don't think it actually handles any strings that big.
123 if self.input is None:
124 raise SerializationError("call write(bytes) before trying to deserialize")
127 length = self.read_compact_size()
129 raise SerializationError("attempt to read past end of buffer")
131 return self.read_bytes(length)
133 def write_string(self, string):
134 # Length-encoded as with read-string
135 self.write_compact_size(len(string))
138 def read_bytes(self, length):
140 result = self.input[self.read_cursor:self.read_cursor+length]
141 self.read_cursor += length
144 raise SerializationError("attempt to read past end of buffer")
148 def read_boolean(self): return self.read_bytes(1)[0] != chr(0)
149 def read_int16(self): return self._read_num('<h')
150 def read_uint16(self): return self._read_num('<H')
151 def read_int32(self): return self._read_num('<i')
152 def read_uint32(self): return self._read_num('<I')
153 def read_int64(self): return self._read_num('<q')
154 def read_uint64(self): return self._read_num('<Q')
156 def write_boolean(self, val): return self.write(chr(1) if val else chr(0))
157 def write_int16(self, val): return self._write_num('<h', val)
158 def write_uint16(self, val): return self._write_num('<H', val)
159 def write_int32(self, val): return self._write_num('<i', val)
160 def write_uint32(self, val): return self._write_num('<I', val)
161 def write_int64(self, val): return self._write_num('<q', val)
162 def write_uint64(self, val): return self._write_num('<Q', val)
164 def read_compact_size(self):
165 size = ord(self.input[self.read_cursor])
166 self.read_cursor += 1
168 size = self._read_num('<H')
170 size = self._read_num('<I')
172 size = self._read_num('<Q')
175 def write_compact_size(self, size):
177 raise SerializationError("attempt to write size < 0")
179 self.write(chr(size))
182 self._write_num('<H', size)
185 self._write_num('<I', size)
188 self._write_num('<Q', size)
190 def _read_num(self, format):
191 (i,) = struct.unpack_from(format, self.input, self.read_cursor)
192 self.read_cursor += struct.calcsize(format)
195 def _write_num(self, format, num):
196 s = struct.pack(format, num)
201 # From the Python Cookbook, downloaded from http://code.activestate.com/recipes/67107/
203 import types, string, exceptions
205 class EnumException(exceptions.Exception):
209 def __init__(self, name, enumList):
217 if type(x) == types.TupleType:
219 if type(x) != types.StringType:
220 raise EnumException, "enum name is not a string: " + x
221 if type(i) != types.IntType:
222 raise EnumException, "enum value is not an integer: " + i
224 raise EnumException, "enum name is not unique: " + x
225 if i in uniqueValues:
226 raise EnumException, "enum value is not unique for " + x
227 uniqueNames.append(x)
228 uniqueValues.append(i)
233 self.reverseLookup = reverseLookup
234 def __getattr__(self, attr):
235 if not self.lookup.has_key(attr):
237 return self.lookup[attr]
238 def whatis(self, value):
239 return self.reverseLookup[value]
242 # This function comes from bitcointools, bct-LICENSE.txt.
244 return bytes.encode('hex_codec')
246 # This function comes from bitcointools, bct-LICENSE.txt.
247 def short_hex(bytes):
248 t = bytes.encode('hex_codec')
251 return t[0:4]+"..."+t[-4:]
257 d['prevout_hash'] = hash_encode(vds.read_bytes(32))
258 d['prevout_n'] = vds.read_uint32()
259 scriptSig = vds.read_bytes(vds.read_compact_size())
260 d['sequence'] = vds.read_uint32()
261 # actually I don't need that at all
262 # if not is_coinbase: d['address'] = extract_public_key(scriptSig)
263 # d['script'] = decode_script(scriptSig)
267 def parse_TxOut(vds, i):
269 d['value'] = vds.read_int64()
270 scriptPubKey = vds.read_bytes(vds.read_compact_size())
271 d['address'] = extract_public_key(scriptPubKey)
272 #d['script'] = decode_script(scriptPubKey)
273 d['raw_output_script'] = scriptPubKey.encode('hex')
278 def parse_Transaction(vds, is_coinbase):
280 start = vds.read_cursor
281 d['version'] = vds.read_int32()
282 n_vin = vds.read_compact_size()
284 for i in xrange(n_vin):
287 d['inputs'].append(o)
288 n_vout = vds.read_compact_size()
290 for i in xrange(n_vout):
291 o = parse_TxOut(vds, i)
293 #if o['address'] == "None" and o['value']==0:
294 # print("skipping strange tx output with zero value")
296 # if o['address'] != "None":
297 d['outputs'].append(o)
299 d['lockTime'] = vds.read_uint32()
305 opcodes = Enumeration("Opcodes", [
306 ("OP_0", 0), ("OP_PUSHDATA1",76), "OP_PUSHDATA2", "OP_PUSHDATA4", "OP_1NEGATE", "OP_RESERVED",
307 "OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "OP_6", "OP_7",
308 "OP_8", "OP_9", "OP_10", "OP_11", "OP_12", "OP_13", "OP_14", "OP_15", "OP_16",
309 "OP_NOP", "OP_VER", "OP_IF", "OP_NOTIF", "OP_VERIF", "OP_VERNOTIF", "OP_ELSE", "OP_ENDIF", "OP_VERIFY",
310 "OP_RETURN", "OP_TOALTSTACK", "OP_FROMALTSTACK", "OP_2DROP", "OP_2DUP", "OP_3DUP", "OP_2OVER", "OP_2ROT", "OP_2SWAP",
311 "OP_IFDUP", "OP_DEPTH", "OP_DROP", "OP_DUP", "OP_NIP", "OP_OVER", "OP_PICK", "OP_ROLL", "OP_ROT",
312 "OP_SWAP", "OP_TUCK", "OP_CAT", "OP_SUBSTR", "OP_LEFT", "OP_RIGHT", "OP_SIZE", "OP_INVERT", "OP_AND",
313 "OP_OR", "OP_XOR", "OP_EQUAL", "OP_EQUALVERIFY", "OP_RESERVED1", "OP_RESERVED2", "OP_1ADD", "OP_1SUB", "OP_2MUL",
314 "OP_2DIV", "OP_NEGATE", "OP_ABS", "OP_NOT", "OP_0NOTEQUAL", "OP_ADD", "OP_SUB", "OP_MUL", "OP_DIV",
315 "OP_MOD", "OP_LSHIFT", "OP_RSHIFT", "OP_BOOLAND", "OP_BOOLOR",
316 "OP_NUMEQUAL", "OP_NUMEQUALVERIFY", "OP_NUMNOTEQUAL", "OP_LESSTHAN",
317 "OP_GREATERTHAN", "OP_LESSTHANOREQUAL", "OP_GREATERTHANOREQUAL", "OP_MIN", "OP_MAX",
318 "OP_WITHIN", "OP_RIPEMD160", "OP_SHA1", "OP_SHA256", "OP_HASH160",
319 "OP_HASH256", "OP_CODESEPARATOR", "OP_CHECKSIG", "OP_CHECKSIGVERIFY", "OP_CHECKMULTISIG",
320 "OP_CHECKMULTISIGVERIFY",
321 ("OP_SINGLEBYTE_END", 0xF0),
322 ("OP_DOUBLEBYTE_BEGIN", 0xF000),
323 "OP_PUBKEY", "OP_PUBKEYHASH",
324 ("OP_INVALIDOPCODE", 0xFFFF),
327 def script_GetOp(bytes):
329 while i < len(bytes):
331 opcode = ord(bytes[i])
333 if opcode >= opcodes.OP_SINGLEBYTE_END:
335 opcode |= ord(bytes[i])
338 if opcode <= opcodes.OP_PUSHDATA4:
340 if opcode == opcodes.OP_PUSHDATA1:
341 nSize = ord(bytes[i])
343 elif opcode == opcodes.OP_PUSHDATA2:
344 (nSize,) = struct.unpack_from('<H', bytes, i)
346 elif opcode == opcodes.OP_PUSHDATA4:
347 (nSize,) = struct.unpack_from('<I', bytes, i)
349 vch = bytes[i:i+nSize]
352 yield (opcode, vch, i)
354 def script_GetOpName(opcode):
355 return (opcodes.whatis(opcode)).replace("OP_", "")
357 def decode_script(bytes):
359 for (opcode, vch, i) in script_GetOp(bytes):
360 if len(result) > 0: result += " "
361 if opcode <= opcodes.OP_PUSHDATA4:
362 result += "%d:"%(opcode,)
363 result += short_hex(vch)
365 result += script_GetOpName(opcode)
368 def match_decoded(decoded, to_match):
369 if len(decoded) != len(to_match):
371 for i in range(len(decoded)):
372 if to_match[i] == opcodes.OP_PUSHDATA4 and decoded[i][0] <= opcodes.OP_PUSHDATA4:
373 continue # Opcodes below OP_PUSHDATA4 all just push data onto stack, and are equivalent.
374 if to_match[i] != decoded[i][0]:
378 def extract_public_key(bytes):
379 decoded = [ x for x in script_GetOp(bytes) ]
381 # non-generated TxIn transactions push a signature
382 # (seventy-something bytes) and then their public key
383 # (65 bytes) onto the stack:
384 match = [ opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4 ]
385 if match_decoded(decoded, match):
386 return public_key_to_bc_address(decoded[1][1])
388 # The Genesis Block, self-payments, and pay-by-IP-address payments look like:
389 # 65 BYTES:... CHECKSIG
390 match = [ opcodes.OP_PUSHDATA4, opcodes.OP_CHECKSIG ]
391 if match_decoded(decoded, match):
392 return public_key_to_bc_address(decoded[0][1])
394 # coins sent to black hole
395 # DUP HASH160 20 BYTES:... EQUALVERIFY CHECKSIG
396 match = [ opcodes.OP_DUP, opcodes.OP_HASH160, opcodes.OP_0, opcodes.OP_EQUALVERIFY, opcodes.OP_CHECKSIG ]
397 if match_decoded(decoded, match):
400 # Pay-by-Bitcoin-address TxOuts look like:
401 # DUP HASH160 20 BYTES:... EQUALVERIFY CHECKSIG
402 match = [ opcodes.OP_DUP, opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUALVERIFY, opcodes.OP_CHECKSIG ]
403 if match_decoded(decoded, match):
404 return hash_160_to_bc_address(decoded[2][1])
407 match = [ opcodes.OP_DUP, opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUALVERIFY, opcodes.OP_CHECKSIG, opcodes.OP_NOP ]
408 if match_decoded(decoded, match):
409 return hash_160_to_bc_address(decoded[2][1])
411 #raise BaseException("address not found in script") see ce35795fb64c268a52324b884793b3165233b1e6d678ccaadf760628ec34d76b