sort signatures for multisig
[electrum-nvc.git] / lib / transaction.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
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.
10 #
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.
15 #
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/>.
18
19
20 # Note: The deserialization code originally comes from ABE.
21
22
23 from bitcoin import *
24 from util import print_error
25 import time
26 import struct
27
28 #
29 # Workalike python implementation of Bitcoin's CDataStream class.
30 #
31 import struct
32 import StringIO
33 import mmap
34
35 class SerializationError(Exception):
36     """ Thrown when there's a problem deserializing or serializing """
37
38 class BCDataStream(object):
39     def __init__(self):
40         self.input = None
41         self.read_cursor = 0
42
43     def clear(self):
44         self.input = None
45         self.read_cursor = 0
46
47     def write(self, bytes):  # Initialize with string of bytes
48         if self.input is None:
49             self.input = bytes
50         else:
51             self.input += bytes
52
53     def map_file(self, file, start):  # Initialize with bytes from file
54         self.input = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
55         self.read_cursor = start
56
57     def seek_file(self, position):
58         self.read_cursor = position
59         
60     def close_file(self):
61         self.input.close()
62
63     def read_string(self):
64         # Strings are encoded depending on length:
65         # 0 to 252 :  1-byte-length followed by bytes (if any)
66         # 253 to 65,535 : byte'253' 2-byte-length followed by bytes
67         # 65,536 to 4,294,967,295 : byte '254' 4-byte-length followed by bytes
68         # ... and the Bitcoin client is coded to understand:
69         # greater than 4,294,967,295 : byte '255' 8-byte-length followed by bytes of string
70         # ... but I don't think it actually handles any strings that big.
71         if self.input is None:
72             raise SerializationError("call write(bytes) before trying to deserialize")
73
74         try:
75             length = self.read_compact_size()
76         except IndexError:
77             raise SerializationError("attempt to read past end of buffer")
78
79         return self.read_bytes(length)
80
81     def write_string(self, string):
82         # Length-encoded as with read-string
83         self.write_compact_size(len(string))
84         self.write(string)
85
86     def read_bytes(self, length):
87         try:
88             result = self.input[self.read_cursor:self.read_cursor+length]
89             self.read_cursor += length
90             return result
91         except IndexError:
92             raise SerializationError("attempt to read past end of buffer")
93
94         return ''
95
96     def read_boolean(self): return self.read_bytes(1)[0] != chr(0)
97     def read_int16(self): return self._read_num('<h')
98     def read_uint16(self): return self._read_num('<H')
99     def read_int32(self): return self._read_num('<i')
100     def read_uint32(self): return self._read_num('<I')
101     def read_int64(self): return self._read_num('<q')
102     def read_uint64(self): return self._read_num('<Q')
103
104     def write_boolean(self, val): return self.write(chr(1) if val else chr(0))
105     def write_int16(self, val): return self._write_num('<h', val)
106     def write_uint16(self, val): return self._write_num('<H', val)
107     def write_int32(self, val): return self._write_num('<i', val)
108     def write_uint32(self, val): return self._write_num('<I', val)
109     def write_int64(self, val): return self._write_num('<q', val)
110     def write_uint64(self, val): return self._write_num('<Q', val)
111
112     def read_compact_size(self):
113         size = ord(self.input[self.read_cursor])
114         self.read_cursor += 1
115         if size == 253:
116             size = self._read_num('<H')
117         elif size == 254:
118             size = self._read_num('<I')
119         elif size == 255:
120             size = self._read_num('<Q')
121         return size
122
123     def write_compact_size(self, size):
124         if size < 0:
125             raise SerializationError("attempt to write size < 0")
126         elif size < 253:
127             self.write(chr(size))
128         elif size < 2**16:
129             self.write('\xfd')
130             self._write_num('<H', size)
131         elif size < 2**32:
132             self.write('\xfe')
133             self._write_num('<I', size)
134         elif size < 2**64:
135             self.write('\xff')
136             self._write_num('<Q', size)
137
138     def _read_num(self, format):
139         (i,) = struct.unpack_from(format, self.input, self.read_cursor)
140         self.read_cursor += struct.calcsize(format)
141         return i
142
143     def _write_num(self, format, num):
144         s = struct.pack(format, num)
145         self.write(s)
146
147 #
148 # enum-like type
149 # From the Python Cookbook, downloaded from http://code.activestate.com/recipes/67107/
150 #
151 import types, string, exceptions
152
153 class EnumException(exceptions.Exception):
154     pass
155
156 class Enumeration:
157     def __init__(self, name, enumList):
158         self.__doc__ = name
159         lookup = { }
160         reverseLookup = { }
161         i = 0
162         uniqueNames = [ ]
163         uniqueValues = [ ]
164         for x in enumList:
165             if type(x) == types.TupleType:
166                 x, i = x
167             if type(x) != types.StringType:
168                 raise EnumException, "enum name is not a string: " + x
169             if type(i) != types.IntType:
170                 raise EnumException, "enum value is not an integer: " + i
171             if x in uniqueNames:
172                 raise EnumException, "enum name is not unique: " + x
173             if i in uniqueValues:
174                 raise EnumException, "enum value is not unique for " + x
175             uniqueNames.append(x)
176             uniqueValues.append(i)
177             lookup[x] = i
178             reverseLookup[i] = x
179             i = i + 1
180         self.lookup = lookup
181         self.reverseLookup = reverseLookup
182     def __getattr__(self, attr):
183         if not self.lookup.has_key(attr):
184             raise AttributeError
185         return self.lookup[attr]
186     def whatis(self, value):
187         return self.reverseLookup[value]
188
189
190 # This function comes from bitcointools, bct-LICENSE.txt.
191 def long_hex(bytes):
192     return bytes.encode('hex_codec')
193
194 # This function comes from bitcointools, bct-LICENSE.txt.
195 def short_hex(bytes):
196     t = bytes.encode('hex_codec')
197     if len(t) < 11:
198         return t
199     return t[0:4]+"..."+t[-4:]
200
201
202
203
204 def parse_redeemScript(bytes):
205     dec = [ x for x in script_GetOp(bytes.decode('hex')) ]
206
207     # 2 of 2
208     match = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2, opcodes.OP_CHECKMULTISIG ]
209     if match_decoded(dec, match):
210         pubkeys = [ dec[1][1].encode('hex'), dec[2][1].encode('hex') ]
211         return 2, pubkeys
212
213     # 2 of 3
214     match = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_3, opcodes.OP_CHECKMULTISIG ]
215     if match_decoded(dec, match):
216         pubkeys = [ dec[1][1].encode('hex'), dec[2][1].encode('hex'), dec[3][1].encode('hex') ]
217         return 2, pubkeys
218
219
220
221 opcodes = Enumeration("Opcodes", [
222     ("OP_0", 0), ("OP_PUSHDATA1",76), "OP_PUSHDATA2", "OP_PUSHDATA4", "OP_1NEGATE", "OP_RESERVED",
223     "OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "OP_6", "OP_7",
224     "OP_8", "OP_9", "OP_10", "OP_11", "OP_12", "OP_13", "OP_14", "OP_15", "OP_16",
225     "OP_NOP", "OP_VER", "OP_IF", "OP_NOTIF", "OP_VERIF", "OP_VERNOTIF", "OP_ELSE", "OP_ENDIF", "OP_VERIFY",
226     "OP_RETURN", "OP_TOALTSTACK", "OP_FROMALTSTACK", "OP_2DROP", "OP_2DUP", "OP_3DUP", "OP_2OVER", "OP_2ROT", "OP_2SWAP",
227     "OP_IFDUP", "OP_DEPTH", "OP_DROP", "OP_DUP", "OP_NIP", "OP_OVER", "OP_PICK", "OP_ROLL", "OP_ROT",
228     "OP_SWAP", "OP_TUCK", "OP_CAT", "OP_SUBSTR", "OP_LEFT", "OP_RIGHT", "OP_SIZE", "OP_INVERT", "OP_AND",
229     "OP_OR", "OP_XOR", "OP_EQUAL", "OP_EQUALVERIFY", "OP_RESERVED1", "OP_RESERVED2", "OP_1ADD", "OP_1SUB", "OP_2MUL",
230     "OP_2DIV", "OP_NEGATE", "OP_ABS", "OP_NOT", "OP_0NOTEQUAL", "OP_ADD", "OP_SUB", "OP_MUL", "OP_DIV",
231     "OP_MOD", "OP_LSHIFT", "OP_RSHIFT", "OP_BOOLAND", "OP_BOOLOR",
232     "OP_NUMEQUAL", "OP_NUMEQUALVERIFY", "OP_NUMNOTEQUAL", "OP_LESSTHAN",
233     "OP_GREATERTHAN", "OP_LESSTHANOREQUAL", "OP_GREATERTHANOREQUAL", "OP_MIN", "OP_MAX",
234     "OP_WITHIN", "OP_RIPEMD160", "OP_SHA1", "OP_SHA256", "OP_HASH160",
235     "OP_HASH256", "OP_CODESEPARATOR", "OP_CHECKSIG", "OP_CHECKSIGVERIFY", "OP_CHECKMULTISIG",
236     "OP_CHECKMULTISIGVERIFY",
237     ("OP_SINGLEBYTE_END", 0xF0),
238     ("OP_DOUBLEBYTE_BEGIN", 0xF000),
239     "OP_PUBKEY", "OP_PUBKEYHASH",
240     ("OP_INVALIDOPCODE", 0xFFFF),
241 ])
242
243
244 def script_GetOp(bytes):
245     i = 0
246     while i < len(bytes):
247         vch = None
248         opcode = ord(bytes[i])
249         i += 1
250         if opcode >= opcodes.OP_SINGLEBYTE_END:
251             opcode <<= 8
252             opcode |= ord(bytes[i])
253             i += 1
254
255         if opcode <= opcodes.OP_PUSHDATA4:
256             nSize = opcode
257             if opcode == opcodes.OP_PUSHDATA1:
258                 nSize = ord(bytes[i])
259                 i += 1
260             elif opcode == opcodes.OP_PUSHDATA2:
261                 (nSize,) = struct.unpack_from('<H', bytes, i)
262                 i += 2
263             elif opcode == opcodes.OP_PUSHDATA4:
264                 (nSize,) = struct.unpack_from('<I', bytes, i)
265                 i += 4
266             vch = bytes[i:i+nSize]
267             i += nSize
268
269         yield (opcode, vch, i)
270
271
272 def script_GetOpName(opcode):
273     return (opcodes.whatis(opcode)).replace("OP_", "")
274
275
276 def decode_script(bytes):
277     result = ''
278     for (opcode, vch, i) in script_GetOp(bytes):
279         if len(result) > 0: result += " "
280         if opcode <= opcodes.OP_PUSHDATA4:
281             result += "%d:"%(opcode,)
282             result += short_hex(vch)
283         else:
284             result += script_GetOpName(opcode)
285     return result
286
287
288 def match_decoded(decoded, to_match):
289     if len(decoded) != len(to_match):
290         return False;
291     for i in range(len(decoded)):
292         if to_match[i] == opcodes.OP_PUSHDATA4 and decoded[i][0] <= opcodes.OP_PUSHDATA4 and decoded[i][0]>0:
293             continue  # Opcodes below OP_PUSHDATA4 all just push data onto stack, and are equivalent.
294         if to_match[i] != decoded[i][0]:
295             return False
296     return True
297
298 def get_address_from_input_script(bytes):
299     try:
300         decoded = [ x for x in script_GetOp(bytes) ]
301     except Exception:
302         # coinbase transactions raise an exception
303         print_error("cannot find address in input script", bytes.encode('hex'))
304         return [], [], "(None)"
305
306     # payto_pubkey
307     match = [ opcodes.OP_PUSHDATA4 ]
308     if match_decoded(decoded, match):
309         return None, None, "(pubkey)"
310
311     # non-generated TxIn transactions push a signature
312     # (seventy-something bytes) and then their public key
313     # (65 bytes) onto the stack:
314     match = [ opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4 ]
315     if match_decoded(decoded, match):
316         return None, None, public_key_to_bc_address(decoded[1][1])
317
318     # p2sh transaction, 2 of n
319     match = [ opcodes.OP_0 ]
320     while len(match) < len(decoded):
321         match.append(opcodes.OP_PUSHDATA4)
322
323     if match_decoded(decoded, match):
324
325         redeemScript = decoded[-1][1]
326         num = len(match) - 2
327         signatures = map(lambda x:x[1][:-1].encode('hex'), decoded[1:-1])
328
329         dec2 = [ x for x in script_GetOp(redeemScript) ]
330
331         # 2 of 2
332         match2 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2, opcodes.OP_CHECKMULTISIG ]
333         if match_decoded(dec2, match2):
334             pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex') ]
335             return pubkeys, signatures, hash_160_to_bc_address(hash_160(redeemScript), 5)
336  
337         # 2 of 3
338         match2 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_3, opcodes.OP_CHECKMULTISIG ]
339         if match_decoded(dec2, match2):
340             pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex'), dec2[3][1].encode('hex') ]
341             return pubkeys, signatures, hash_160_to_bc_address(hash_160(redeemScript), 5)
342
343     print_error("cannot find address in input script", bytes.encode('hex'))
344     return [], [], "(None)"
345
346
347
348 def get_address_from_output_script(bytes):
349     decoded = [ x for x in script_GetOp(bytes) ]
350
351     # The Genesis Block, self-payments, and pay-by-IP-address payments look like:
352     # 65 BYTES:... CHECKSIG
353     match = [ opcodes.OP_PUSHDATA4, opcodes.OP_CHECKSIG ]
354     if match_decoded(decoded, match):
355         return True, public_key_to_bc_address(decoded[0][1])
356
357     # Pay-by-Bitcoin-address TxOuts look like:
358     # DUP HASH160 20 BYTES:... EQUALVERIFY CHECKSIG
359     match = [ opcodes.OP_DUP, opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUALVERIFY, opcodes.OP_CHECKSIG ]
360     if match_decoded(decoded, match):
361         return False, hash_160_to_bc_address(decoded[2][1])
362
363     # p2sh
364     match = [ opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUAL ]
365     if match_decoded(decoded, match):
366         return False, hash_160_to_bc_address(decoded[1][1],5)
367
368     return False, "(None)"
369
370
371 class Transaction:
372     
373     def __init__(self, raw, is_complete = True):
374         self.raw = raw
375         self.deserialize()
376         self.inputs = self.d['inputs']
377         self.outputs = self.d['outputs']
378         self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
379         self.locktime = self.d['lockTime']
380         self.is_complete = is_complete
381         
382     def __str__(self):
383         return self.raw
384
385     @classmethod
386     def from_io(klass, inputs, outputs):
387         raw = klass.serialize(inputs, outputs, for_sig = -1) # for_sig=-1 means do not sign
388         self = klass(raw)
389         self.is_complete = False
390         self.inputs = inputs
391         self.outputs = outputs
392         return self
393
394     @classmethod
395     def multisig_script(klass, public_keys, num=None):
396         n = len(public_keys)
397         if num is None: num = n
398         # supports only "2 of 2", and "2 of 3" transactions
399         assert num <= n and n in [2,3]
400     
401         if num==2:
402             s = '52'
403         elif num == 3:
404             s = '53'
405         else:
406             raise
407     
408         for k in public_keys:
409             s += var_int(len(k)/2)
410             s += k
411         if n==2:
412             s += '52'
413         elif n==3:
414             s += '53'
415         else:
416             raise
417         s += 'ae'
418
419         return s
420
421     @classmethod
422     def serialize( klass, inputs, outputs, for_sig = None ):
423
424         s  = int_to_hex(1,4)                                         # version
425         s += var_int( len(inputs) )                                  # number of inputs
426         for i in range(len(inputs)):
427             txin = inputs[i]
428             s += txin['prevout_hash'].decode('hex')[::-1].encode('hex')   # prev hash
429             s += int_to_hex(txin['prevout_n'],4)                          # prev index
430
431             if for_sig is None:
432                 signatures = txin['signatures']
433                 pubkeys = txin['pubkeys']
434                 if not txin.get('redeemScript'):
435                     pubkey = pubkeys[0]
436                     script = ''
437                     if signatures:
438                         sig = signatures[0]
439                         sig = sig + '01'                                 # hashtype
440                         script += op_push(len(sig)/2)
441                         script += sig
442                     script += op_push(len(pubkey)/2)
443                     script += pubkey
444                 else:
445                     script = '00'                                    # op_0
446                     for pubkey in pubkeys:
447                         sig = signatures.get(pubkey)
448                         if not sig: continue
449                         sig = sig + '01'
450                         script += op_push(len(sig)/2)
451                         script += sig
452
453                     redeem_script = klass.multisig_script(pubkeys,2)
454                     script += op_push(len(redeem_script)/2)
455                     script += redeem_script
456
457             elif for_sig==i:
458                 if txin.get('redeemScript'):
459                     script = txin['redeemScript']                    # p2sh uses the inner script
460                 else:
461                     script = txin['scriptPubKey']                    # scriptsig
462             else:
463                 script=''
464             s += var_int( len(script)/2 )                            # script length
465             s += script
466             s += "ffffffff"                                          # sequence
467
468         s += var_int( len(outputs) )                                 # number of outputs
469         for output in outputs:
470             addr, amount = output
471             s += int_to_hex( amount, 8)                              # amount
472             addrtype, hash_160 = bc_address_to_hash_160(addr)
473             if addrtype == 0:
474                 script = '76a9'                                      # op_dup, op_hash_160
475                 script += '14'                                       # push 0x14 bytes
476                 script += hash_160.encode('hex')
477                 script += '88ac'                                     # op_equalverify, op_checksig
478             elif addrtype == 5:
479                 script = 'a9'                                        # op_hash_160
480                 script += '14'                                       # push 0x14 bytes
481                 script += hash_160.encode('hex')
482                 script += '87'                                       # op_equal
483             else:
484                 raise
485             
486             s += var_int( len(script)/2 )                           #  script length
487             s += script                                             #  script
488         s += int_to_hex(0,4)                                        #  lock time
489         if for_sig is not None and for_sig != -1:
490             s += int_to_hex(1, 4)                                   #  hash type
491         return s
492
493
494     def for_sig(self,i):
495         return self.serialize(self.inputs, self.outputs, for_sig = i)
496
497
498     def hash(self):
499         return Hash(self.raw.decode('hex') )[::-1].encode('hex')
500
501
502
503     def sign(self, keypairs):
504         is_complete = True
505         print_error("tx.sign(), keypairs:", keypairs)
506
507         for i, txin in enumerate(self.inputs):
508
509             # if the input is multisig, parse redeem script
510             redeem_script = txin.get('redeemScript')
511             num, redeem_pubkeys = parse_redeemScript(redeem_script) if redeem_script else (1, [txin.get('redeemPubkey')])
512
513             # add pubkeys
514             txin["pubkeys"] = redeem_pubkeys
515             # get list of already existing signatures
516             signatures = txin.get("signatures",{})
517             # continue if this txin is complete
518             if len(signatures) == num:
519                 continue
520
521             tx_for_sig = self.serialize( self.inputs, self.outputs, for_sig = i )
522
523             print_error("redeem pubkeys input %d"%i, redeem_pubkeys)
524             for pubkey in redeem_pubkeys:
525                 # check if we have the corresponding private key
526                 if pubkey in keypairs.keys():
527                     # add signature
528                     sec = keypairs[pubkey]
529                     compressed = is_compressed(sec)
530                     pkey = regenerate_key(sec)
531                     secexp = pkey.secret
532                     private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
533                     public_key = private_key.get_verifying_key()
534                     sig = private_key.sign_digest_deterministic( Hash( tx_for_sig.decode('hex') ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_der )
535                     assert public_key.verify_digest( sig, Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
536
537                     # insert signature in the list
538                     signatures[pubkey] = sig.encode('hex')
539                     print_error("adding signature for", pubkey)
540             
541             txin["signatures"] = signatures
542             is_complete = is_complete and len(signatures) == num
543
544         print_error("is_complete", is_complete)
545         self.is_complete = is_complete
546         self.raw = self.serialize( self.inputs, self.outputs )
547
548
549     def deserialize(self):
550         vds = BCDataStream()
551         vds.write(self.raw.decode('hex'))
552         d = {}
553         start = vds.read_cursor
554         d['version'] = vds.read_int32()
555         n_vin = vds.read_compact_size()
556         d['inputs'] = []
557         for i in xrange(n_vin):
558             d['inputs'].append(self.parse_input(vds))
559         n_vout = vds.read_compact_size()
560         d['outputs'] = []
561         for i in xrange(n_vout):
562             d['outputs'].append(self.parse_output(vds, i))
563         d['lockTime'] = vds.read_uint32()
564         self.d = d
565         return self.d
566     
567
568     def parse_input(self, vds):
569         d = {}
570         d['prevout_hash'] = hash_encode(vds.read_bytes(32))
571         d['prevout_n'] = vds.read_uint32()
572         scriptSig = vds.read_bytes(vds.read_compact_size())
573         d['sequence'] = vds.read_uint32()
574
575         if scriptSig:
576             pubkeys, signatures, address = get_address_from_input_script(scriptSig)
577         else:
578             pubkeys = []
579             signatures = {}
580             address = None
581
582         d['address'] = address
583         d['signatures'] = signatures
584         return d
585
586
587     def parse_output(self, vds, i):
588         d = {}
589         d['value'] = vds.read_int64()
590         scriptPubKey = vds.read_bytes(vds.read_compact_size())
591         is_pubkey, address = get_address_from_output_script(scriptPubKey)
592         d['is_pubkey'] = is_pubkey
593         d['address'] = address
594         d['scriptPubKey'] = scriptPubKey.encode('hex')
595         d['prevout_n'] = i
596         return d
597
598
599     def add_extra_addresses(self, txlist):
600         for i in self.inputs:
601             if i.get("address") == "(pubkey)":
602                 prev_tx = txlist.get(i.get('prevout_hash'))
603                 if prev_tx:
604                     address, value = prev_tx.outputs[i.get('prevout_n')]
605                     print_error("found pay-to-pubkey address:", address)
606                     i["address"] = address
607
608
609     def has_address(self, addr):
610         found = False
611         for txin in self.inputs:
612             if addr == txin.get('address'): 
613                 found = True
614                 break
615         for txout in self.outputs:
616             if addr == txout[0]:
617                 found = True
618                 break
619         return found
620
621
622     def get_value(self, addresses, prevout_values):
623         # return the balance for that tx
624         is_relevant = False
625         is_send = False
626         is_pruned = False
627         is_partial = False
628         v_in = v_out = v_out_mine = 0
629
630         for item in self.inputs:
631             addr = item.get('address')
632             if addr in addresses:
633                 is_send = True
634                 is_relevant = True
635                 key = item['prevout_hash']  + ':%d'%item['prevout_n']
636                 value = prevout_values.get( key )
637                 if value is None:
638                     is_pruned = True
639                 else:
640                     v_in += value
641             else:
642                 is_partial = True
643
644         if not is_send: is_partial = False
645                     
646         for item in self.outputs:
647             addr, value = item
648             v_out += value
649             if addr in addresses:
650                 v_out_mine += value
651                 is_relevant = True
652
653         if is_pruned:
654             # some inputs are mine:
655             fee = None
656             if is_send:
657                 v = v_out_mine - v_out
658             else:
659                 # no input is mine
660                 v = v_out_mine
661
662         else:
663             v = v_out_mine - v_in
664
665             if is_partial:
666                 # some inputs are mine, but not all
667                 fee = None
668                 is_send = v < 0
669             else:
670                 # all inputs are mine
671                 fee = v_out - v_in
672
673         return is_relevant, is_send, v, fee
674
675
676     def get_input_info(self):
677         info = []
678         for i in self.inputs:
679             item = { 
680                 'prevout_hash':i['prevout_hash'], 
681                 'prevout_n':i['prevout_n'],
682                 'address':i.get('address'),
683                 'KeyID':i.get('KeyID'),
684                 'scriptPubKey':i.get('scriptPubKey'),
685                 'redeemScript':i.get('redeemScript'),
686                 'redeemPubkey':i.get('redeemPubkey'),
687                 'pubkeys':i.get('pubkeys'),
688                 'signatures':i.get('signatures',{}),
689                 }
690             info.append(item)
691         return info
692
693
694     def as_dict(self):
695         import json
696         out = {
697             "hex":self.raw,
698             "complete":self.is_complete
699             }
700
701         if not self.is_complete:
702             input_info = self.get_input_info()
703             out['input_info'] = json.dumps(input_info).replace(' ','')
704
705         return out
706
707
708     def requires_fee(self, verifier):
709         # see https://en.bitcoin.it/wiki/Transaction_fees
710         threshold = 57600000
711         size = len(self.raw)/2
712         if size >= 10000: 
713             return True
714
715         for o in self.outputs:
716             value = o[1]
717             if value < 1000000:
718                 return True
719         sum = 0
720         for i in self.inputs:
721             age = verifier.get_confirmations(i["prevout_hash"])[0]
722             sum += i["value"] * age
723         priority = sum / size
724         print_error(priority, threshold)
725         return priority < threshold 
726
727
728
729     def add_input_info(self, input_info):
730         for i, txin in enumerate(self.inputs):
731             item = input_info[i]
732             txin['address'] = item['address']
733             txin['signatures'] = item['signatures']
734             txin['scriptPubKey'] = item['scriptPubKey']
735             txin['redeemScript'] = item.get('redeemScript')
736             txin['redeemPubkey'] = item.get('redeemPubkey')
737             txin['KeyID'] = item.get('KeyID')