update validate_tx script
[electrum-nvc.git] / scripts / merchant.py
index 32e68ac..e12cdb4 100644 (file)
@@ -21,7 +21,7 @@ import time, thread, sys, socket, os
 import urllib2,json
 import MySQLdb as mdb
 import Queue
-from electrum import Wallet, TcpStratumInterface
+from electrum import Wallet, Interface, WalletVerifier
 
 import ConfigParser
 config = ConfigParser.ConfigParser()
@@ -33,7 +33,6 @@ db_password = config.get('db','password')
 db_name = config.get('db','name')
 
 electrum_server = config.get('electrum','server')
-mpk = config.get('electrum','mpk')
 
 my_password = config.get('main','password')
 my_host = config.get('main','host')
@@ -44,52 +43,60 @@ cb_expired = config.get('callback','expired')
 cb_password = config.get('callback','password')
 
 wallet = Wallet()
-wallet.master_public_key = mpk.decode('hex')
+wallet.master_public_key = config.get('electrum','mpk')
 
 
 
 omg_addresses = {}
 
-def electrum_input_thread(in_queue, i):
+def electrum_input_thread(in_queue):
     while True:
-        addr, amount = in_queue.get(True,1000000000)
+        addr, amount, confirmations = in_queue.get(True,1000000000)
         if addr in omg_addresses: 
             continue
         else:
             print "subscribing to ", addr
-            omg_addresses[addr] = amount
-            i.send([('blockchain.address.subscribe',[addr])])
+            omg_addresses[addr] = {'requested':float(amount), 'confirmations':int(confirmations)}
+            interface.send([('blockchain.address.subscribe',[addr])])
 
 
-def electrum_output_thread(out_queue, i):
+def electrum_output_thread(out_queue):
     while True:
-        r = i.responses.get(True, 100000000000)
+        r = interface.get_response()
+        print r
         method = r.get('method') 
 
         if method == 'blockchain.address.subscribe':
             addr = r.get('params')[0]
-            i.send([('blockchain.address.get_history',[addr])])
+            interface.send([('blockchain.address.get_history',[addr])])
 
         elif method == 'blockchain.address.get_history':
             addr = r.get('params')[0]
-            #print "received history for", addr
-            confirmed = unconfirmed = 0
             h = r.get('result')
-            if h is None:
-                continue
+            if h is None: continue
+            omg_addresses[addr]['history'] = h
             for item in h:
-                v = item['value']
-                if v<0: continue
-                if item['height']:
-                    confirmed += v
-                else:
-                    unconfirmed += v
+                tx_hash = item.get('tx_hash')
+                verifier.add(tx_hash)
+
+        elif method == 'blockchain.numblocks.subscribe':
+            for addr in omg_addresses:
+                h = omg_addresses[addr].get('history',[])
+                amount = omg_addresses[addr].get('requested')
+                confs = omg_addresses[addr].get('confirmations')
+                val = 0
+
+                for item in h:
+                    tx_hash = item.get('tx_hash')
+                    v = item['value']
+                    if v<0: continue
+                    if verifier.get_confirmations(tx_hash) >= conf:
+                        val += v
                 
-            s = (confirmed+unconfirmed)/1.e8
-            print "balance for %s:"%addr, s
-            amount = float(omg_addresses.get(addr))
-            if s>=amount:
-                out_queue.put( ('payment',addr) )
+                s = (val)/1.e8
+                print "balance for %s:"%addr, s
+                if s>=amount:
+                    out_queue.put( ('payment',addr) )
 
 
 stopping = False
@@ -101,7 +108,7 @@ def do_stop():
 def do_create(conn):
     # creation
     cur = conn.cursor()
-    cur.execute("CREATE TABLE electrum_payments (id INT PRIMARY KEY, address VARCHAR(40), amount FLOAT, received_at TIMESTAMP, expires_at TIMESTAMP, paid INT(1), processed INT(1));")
+    cur.execute("CREATE TABLE electrum_payments (id INT PRIMARY KEY, address VARCHAR(40), amount FLOAT, confirmations INT(8), received_at TIMESTAMP, expires_at TIMESTAMP, paid INT(1), processed INT(1));")
     conn.commit()
 
 def process_request(i, amount, confirmations, expires_in, password):
@@ -114,7 +121,7 @@ def process_request(i, amount, confirmations, expires_in, password):
     return addr
 
 def get_mpk():
-    return wallet.master_public_key.encode('hex')
+    return wallet.master_public_key
 
 
 def server_thread(conn):
@@ -157,16 +164,19 @@ if __name__ == '__main__':
     print "using database", db_name
     conn = mdb.connect(db_instance, db_user, db_password, db_name);
 
-    i = TcpStratumInterface(electrum_server, 50001)
-    i.init_socket()
-    i.start()
+    interface = Interface({'server':"%s:%d:t"%(electrum_server, 50001)})
+    interface.start()
+    interface.send([('blockchain.numblocks.subscribe',[])])
+
+    verifier = WalletVerifier(interface, {})
+    verifier.start()
     
 
     # this process detects when addresses have paid
     in_queue = Queue.Queue()
     out_queue = Queue.Queue()
-    thread.start_new_thread(electrum_input_thread, (in_queue,i))
-    thread.start_new_thread(electrum_output_thread, (out_queue,i))
+    thread.start_new_thread(electrum_input_thread, (in_queue,))
+    thread.start_new_thread(electrum_output_thread, (out_queue,))
 
     thread.start_new_thread(server_thread, (conn,))
 
@@ -175,7 +185,7 @@ if __name__ == '__main__':
         cur = conn.cursor()
 
         # get a list of addresses to watch
-        cur.execute("SELECT address, amount FROM electrum_payments WHERE paid IS NULL;")
+        cur.execute("SELECT address, amount, confirmations FROM electrum_payments WHERE paid IS NULL;")
         data = cur.fetchall()
         for item in data: 
             in_queue.put(item)
@@ -192,9 +202,9 @@ if __name__ == '__main__':
             id = cur.fetchone()[0]
             cur.execute("update electrum_payments set paid=1 where id=%d;"%(id))
         elif cmd == 'request':
-            i, addr, amount, hours = params
-            sql = "INSERT INTO electrum_payments (id, address, amount, received_at, expires_at, paid, processed)"\
-                + " VALUES (%d, '%s', %f, CURRENT_TIMESTAMP, ADDTIME(CURRENT_TIMESTAMP, '0 %d:0:0'), NULL, NULL);"%(i, addr, amount, hours)
+            i, addr, amount, confs, hours = params
+            sql = "INSERT INTO electrum_payments (id, address, amount, confirmations, received_at, expires_at, paid, processed)"\
+                + " VALUES (%d, '%s', %f, %d, CURRENT_TIMESTAMP, ADDTIME(CURRENT_TIMESTAMP, '0 %d:0:0'), NULL, NULL);"%(i, addr, amount, confs, hours)
             cur.execute(sql)