fix get_pubkeys call
[electrum-nvc.git] / lib / transaction.py
index 74f2d58..f15aa23 100644 (file)
@@ -416,23 +416,76 @@ def get_address_from_output_script(bytes):
     # 65 BYTES:... CHECKSIG
     match = [ opcodes.OP_PUSHDATA4, opcodes.OP_CHECKSIG ]
     if match_decoded(decoded, match):
-        return "pubkey:" + decoded[0][1].encode('hex')
+        return 'pubkey', decoded[0][1].encode('hex')
 
     # Pay-by-Bitcoin-address TxOuts look like:
     # DUP HASH160 20 BYTES:... EQUALVERIFY CHECKSIG
     match = [ opcodes.OP_DUP, opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUALVERIFY, opcodes.OP_CHECKSIG ]
     if match_decoded(decoded, match):
-        return hash_160_to_bc_address(decoded[2][1])
+        return 'address', hash_160_to_bc_address(decoded[2][1])
 
     # p2sh
     match = [ opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUAL ]
     if match_decoded(decoded, match):
-        return hash_160_to_bc_address(decoded[1][1],5)
+        return 'address', hash_160_to_bc_address(decoded[1][1],5)
 
-    return "(None)"
+    return "(None)", "(None)"
 
 
 
+    
+
+def parse_input(vds):
+    d = {}
+    prevout_hash = hash_encode(vds.read_bytes(32))
+    prevout_n = vds.read_uint32()
+    scriptSig = vds.read_bytes(vds.read_compact_size())
+    sequence = vds.read_uint32()
+    if prevout_hash == '00'*32:
+        d['is_coinbase'] = True
+    else:
+        d['is_coinbase'] = False
+        d['prevout_hash'] = prevout_hash
+        d['prevout_n'] = prevout_n
+        d['sequence'] = sequence
+        d['pubkeys'] = []
+        d['signatures'] = {}
+        d['address'] = None
+        if scriptSig:
+            parse_scriptSig(d, scriptSig)
+    return d
+
+
+def parse_output(vds, i):
+    d = {}
+    d['value'] = vds.read_int64()
+    scriptPubKey = vds.read_bytes(vds.read_compact_size())
+    type, address = get_address_from_output_script(scriptPubKey)
+    d['type'] = type
+    d['address'] = address
+    d['scriptPubKey'] = scriptPubKey.encode('hex')
+    d['prevout_n'] = i
+    return d
+
+
+def deserialize(raw):
+    vds = BCDataStream()
+    vds.write(raw.decode('hex'))
+    d = {}
+    start = vds.read_cursor
+    d['version'] = vds.read_int32()
+    n_vin = vds.read_compact_size()
+    d['inputs'] = []
+    for i in xrange(n_vin):
+        d['inputs'].append(parse_input(vds))
+    n_vout = vds.read_compact_size()
+    d['outputs'] = []
+    for i in xrange(n_vout):
+        d['outputs'].append(parse_output(vds, i))
+    d['lockTime'] = vds.read_uint32()
+    return d
+
+
 push_script = lambda x: op_push(len(x)/2) + x
 
 class Transaction:
@@ -442,12 +495,25 @@ class Transaction:
             self.raw = self.serialize(self.inputs, self.outputs, for_sig = None) # for_sig=-1 means do not sign
         return self.raw
 
-    def __init__(self, inputs, outputs):
+    def __init__(self, inputs, outputs, locktime=0):
         self.inputs = inputs
         self.outputs = outputs
-        self.locktime = 0
+        self.locktime = locktime
         self.raw = None
         
+    @classmethod
+    def deserialize(klass, raw):
+        self = klass([],[])
+        self.update(raw)
+        return self
+
+    def update(self, raw):
+        d = deserialize(raw)
+        self.raw = raw
+        self.inputs = d['inputs']
+        self.outputs = map(lambda x: (x['type'], x['address'], x['value']), d['outputs'])
+        self.locktime = d['lockTime']
+
 
     @classmethod 
     def sweep(klass, privkeys, network, to_address, fee):
@@ -456,7 +522,7 @@ class Transaction:
             pubkey = public_key_from_private_key(privkey)
             address = address_from_private_key(privkey)
             u = network.synchronous_get([ ('blockchain.address.listunspent',[address])])[0]
-            pay_script = klass.pay_script(address)
+            pay_script = klass.pay_script('address', address)
             for item in u:
                 item['scriptPubKey'] = pay_script
                 item['redeemPubkey'] = pubkey
@@ -469,7 +535,7 @@ class Transaction:
             return
 
         total = sum( map(lambda x:int(x.get('value')), inputs) ) - fee
-        outputs = [(to_address, total)]
+        outputs = [('address', to_address, total)]
         self = klass(inputs, outputs)
         self.sign({ pubkey:privkey })
         return self
@@ -503,10 +569,12 @@ class Transaction:
 
 
     @classmethod
-    def pay_script(self, addr):
-        if addr.startswith('OP_RETURN:'):
-            h = addr[10:].encode('hex')
+    def pay_script(self, type, addr):
+        if type == 'op_return':
+            h = addr.encode('hex')
             return '6a' + push_script(h)
+        else:
+            assert type == 'address'
         addrtype, hash_160 = bc_address_to_hash_160(addr)
         if addrtype == 0:
             script = '76a9'                                      # op_dup, op_hash_160
@@ -564,7 +632,7 @@ class Transaction:
                     script += push_script(redeem_script)
 
             elif for_sig==i:
-                script = txin['redeemScript'] if p2sh else klass.pay_script(address)
+                script = txin['redeemScript'] if p2sh else klass.pay_script('address', address)
             else:
                 script = ''
             s += var_int( len(script)/2 )                            # script length
@@ -573,9 +641,9 @@ class Transaction:
 
         s += var_int( len(outputs) )                                 # number of outputs
         for output in outputs:
-            addr, amount = output
+            type, addr, amount = output
             s += int_to_hex( amount, 8)                              # amount
-            script = klass.pay_script(addr)
+            script = klass.pay_script(type, addr)
             s += var_int( len(script)/2 )                           #  script length
             s += script                                             #  script
         s += int_to_hex(0,4)                                        #  lock time
@@ -677,66 +745,6 @@ class Transaction:
         self.raw = self.serialize( self.inputs, self.outputs )
 
 
-
-    @classmethod
-    def deserialize(klass, raw):
-        vds = BCDataStream()
-        vds.write(raw.decode('hex'))
-        d = {}
-        start = vds.read_cursor
-        d['version'] = vds.read_int32()
-        n_vin = vds.read_compact_size()
-        d['inputs'] = []
-        for i in xrange(n_vin):
-            d['inputs'].append(klass.parse_input(vds))
-        n_vout = vds.read_compact_size()
-        d['outputs'] = []
-        for i in xrange(n_vout):
-            d['outputs'].append(klass.parse_output(vds, i))
-        d['lockTime'] = vds.read_uint32()
-
-        inputs = d['inputs']
-        outputs = map(lambda x: (x['address'], x['value']), d['outputs'])
-
-        self = klass(inputs, outputs)
-        self.raw = raw
-        self.locktime = d['lockTime']
-        return self
-    
-    @classmethod
-    def parse_input(self, vds):
-        d = {}
-        prevout_hash = hash_encode(vds.read_bytes(32))
-        prevout_n = vds.read_uint32()
-        scriptSig = vds.read_bytes(vds.read_compact_size())
-        sequence = vds.read_uint32()
-
-        if prevout_hash == '00'*32:
-            d['is_coinbase'] = True
-        else:
-            d['is_coinbase'] = False
-            d['prevout_hash'] = prevout_hash
-            d['prevout_n'] = prevout_n
-            d['sequence'] = sequence
-            d['pubkeys'] = []
-            d['signatures'] = {}
-            d['address'] = None
-            if scriptSig:
-                parse_scriptSig(d, scriptSig)
-        return d
-
-    @classmethod
-    def parse_output(self, vds, i):
-        d = {}
-        d['value'] = vds.read_int64()
-        scriptPubKey = vds.read_bytes(vds.read_compact_size())
-        address = get_address_from_output_script(scriptPubKey)
-        d['address'] = address
-        d['scriptPubKey'] = scriptPubKey.encode('hex')
-        d['prevout_n'] = i
-        return d
-
-
     def add_pubkey_addresses(self, txlist):
         for i in self.inputs:
             if i.get("address") == "(pubkey)":
@@ -750,11 +758,11 @@ class Transaction:
     def get_outputs(self):
         """convert pubkeys to addresses"""
         o = []
-        for x, v in self.outputs:
-            if bitcoin.is_address(x):
+        for type, x, v in self.outputs:
+            if type == 'address':
                 addr = x
-            elif x.startswith('pubkey:'):
-                addr = public_key_to_bc_address(x[7:].decode('hex'))
+            elif type == 'pubkey':
+                addr = public_key_to_bc_address(x.decode('hex'))
             else:
                 addr = "(None)"
             o.append((addr,v))
@@ -845,7 +853,7 @@ class Transaction:
         if size >= 10000: 
             return True
 
-        for o in self.outputs:
+        for o in self.get_outputs():
             value = o[1]
             if value < 1000000:
                 return True