commit c19edfb549084be1eb329357c627708bc1145804
parent dac317dbc499388a09c059780a81663b47fe80dc
Author: NicholasFarrow <nicholas.w.farrow@gmail.com>
Date:   Wed, 23 Dec 2020 23:12:31 +1100
Code restructuring, invoice & payment inheritance, exception handling for connections, payment logic
Diffstat:
7 files changed, 121 insertions(+), 73 deletions(-)
diff --git a/invoice/__init__.py b/invoice/__init__.py
@@ -1,18 +0,0 @@
-import uuid
-
-import config
-from .price_feed import get_btc_value
-
-
-class invoice():
-    def __init__(self, dollar_value, currency, label):
-        self.dollar_value = dollar_value
-        self.currency = currency
-        self.value = get_btc_value(dollar_value, currency)
-        self.label = label
-        self.id = str(uuid.uuid4)
-        self.status = 'Payment initialised.'
-        self.response = ''
-        self.time_left = config.payment_timeout
-        self.confirmed_paid = 0
-        self.unconfirmed_paid = 0
diff --git a/invoice/payment_invoice.py b/invoice/payment_invoice.py
@@ -0,0 +1,18 @@
+import uuid
+
+import config
+from .price_feed import get_btc_value
+
+
+class invoice:
+    def __init__(self, dollar_value, currency, label):
+        self.dollar_value = dollar_value
+        self.currency = currency
+        self.value = get_btc_value(dollar_value, currency)
+        self.label = label
+        self.id = str(uuid.uuid4())
+        self.status = 'Payment initialised.'
+        self.response = ''
+        self.time_left = config.payment_timeout
+        self.confirmed_paid = 0
+        self.unconfirmed_paid = 0
diff --git a/invoice/price_feed.py b/invoice/price_feed.py
@@ -1,28 +1,37 @@
 import requests
 
+import config
+
 def get_price(currency):
     price_feed = "https://api.coindesk.com/v1/bpi/currentprice.json"
     r = requests.get(price_feed)
-    
-    try:
-        price_data = r.json()
-        prices = price_data['bpi']
-    except:
-        print("Failed to reach {}.".format(price_feed))
-        return None
+
+    for i in range(config.connection_attempts):
+        try:
+            price_data = r.json()
+            prices = price_data['bpi']
+            break
+
+        except Exception as e:
+            print(e)
+            print("Attempting again... {}/{}...".format(i+1, config.connection_attempts))
+
+    else:
+        raise("Failed to reach {}.".format(price_feed))
+
 
     try:
         price = prices[currency]['rate'].replace(',', '')
+        return price
+
     except:
         print("Failed to find currency {} from {}.".format(currency, price_feed))
         return None
 
-    return price
-
 
 def get_btc_value(dollar_value, currency):
     if (price := get_price(currency)) is not None:
-        
+
         try:
             float_value = dollar_value / float(price)
             if not isinstance(float_value, float):
diff --git a/pay/bitcoind.py b/pay/bitcoind.py
@@ -1,27 +1,30 @@
 import config
 import subprocess
+from invoice.payment_invoice import invoice
 
-class btcd:
-    def __init__(self, invoice):
-        self.__dict__ = invoice.__dict__.copy()
+class btcd(invoice):
+    def __init__(self, dollar_value, currency, label):
+        super().__init__(dollar_value, currency, label)
+        print(self.__dict__)
+        # self.__dict__ = invoice.__dict__.copy()
 
         from bitcoinrpc.authproxy import AuthServiceProxy
 
         connection_str = "http://{}:{}@{}:{}".format(config.username, config.password, config.host, config.rpcport)
         print("Attempting to connect to {}.".format(connection_str))
 
-        try:
-            self.rpc = AuthServiceProxy(connection_str)
-            # info = self.rpc.getblockchaininfo()
-            # info = self.rpc.help()
+        for i in range(config.connection_attempts):
+            try:
+                self.rpc = AuthServiceProxy(connection_str)
+                info = self.rpc.getblockchaininfo()
+                print("Successfully contacted bitcoind.")
+                break
 
-            print("Successfully contacted bitcoind.")
-            print("-"*10)
-            #print(info)
-            print("-"*10)
-
-        except Exception as e:
-            print(e)
+            except Exception as e:
+                print(e)
+                print("Attempting again... {}/{}...".format(i+1, config.connection_attempts))
+        else:
+            raise Exception("Could not connect to bitcoind. Check your RPC / port tunneling settings and try again.")
 
     def check_payment(self):
         self.address = "bc1qwxlwghumfmhwdc2deyn7h42syp2t496penax2y"
@@ -39,5 +42,10 @@ class btcd:
         return conf_paid, unconf_paid
 
     def get_address(self):
-        self.address = self.rpc.getnewaddress(self.label)
+        for i in range(config.connection_attempts):
+            try:
+                self.address = self.rpc.getnewaddress(self.label)
+            except Exception as e:
+                print(e)
+                print("Attempting again... {}/{}...".format(i+1, config.connection_attempts))
         return
diff --git a/server.py b/server.py
@@ -61,9 +61,10 @@ def make_payment(payload):
         # Nothing?
         # Run custom script?
 
-def create_invoice(amount, currency, label):
-    payment_invoice = invoice.invoice(amount, currency, label)
-    payment = bitcoind.btcd(payment_invoice)
+def create_invoice(dollar_amount, currency, label):
+    # payment_invoice = invoice.invoice(amount, currency, label)
+    payment = bitcoind.btcd(dollar_amount, currency, label)
+    # payment = bitcoind.btcd(payment_invoice)
     payment.get_address()
     return payment
 
@@ -89,6 +90,8 @@ def make_payment(payment):
     while (time_left := config.payment_timeout - (time.time() - payment.start_time)) > 0:
         payment.time_left = time_left
         payment.confirmed_paid, payment.unconfirmed_paid = payment.check_payment()
+        print()
+        print(payment.__dict__)
 
         if payment.confirmed_paid > payment.value:
             payment.paid = True
diff --git a/static/server_connection.js b/static/server_connection.js
@@ -0,0 +1,24 @@
+$(document).ready(function() {
+    namespace = '/pay';
+    var socket = io(namespace);
+
+    socket.on('connect', function() {
+        socket.emit('initialise', {'data': 'initialising payment...'});
+    });
+
+    socket.on('payresponse', function(msg, cb) {
+        console.log(msg.response);
+        $('#status').text(msg.status).html();
+        $('#address').text(msg.address).html();
+        $('#amount').text(msg.amount).html();
+        $('#log').append('<br>' + $('<div/>').text(msg.response).html());
+        $('#timer').text(msg.time_left).html();
+        if (cb)
+            cb();
+    });
+
+    $('form#pay').submit(function(event) {
+        socket.emit('payment', {'amount': $('#pay_data').val(), 'label' : null});
+        return false;
+    });
+});
diff --git a/templates/index.html b/templates/index.html
@@ -4,34 +4,35 @@
     <title>BTCPyServer</title>
     <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
     <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js"></script>
-    <script type="text/javascript" charset="utf-8">
-        $(document).ready(function() {
-            namespace = '/pay';
-            var socket = io(namespace);
-
-            socket.on('connect', function() {
-                socket.emit('initialise', {'data': 'initialising payment...'});
-            });
-
-            socket.on('payresponse', function(msg, cb) {
-                console.log(msg.response);
-                $('#status').text(msg.status).html();
-                $('#address').text(msg.address).html();
-                $('#amount').text(msg.amount).html();
-                $('#log').append('<br>' + $('<div/>').text(msg.response).html());
-                $('#timer').text(msg.time_left).html();
-                if (cb)
-                    cb();
-            });
-
-            $('form#pay').submit(function(event) {
-                socket.emit('payment', {'amount': $('#pay_data').val(), 'label' : null});
-                return false;
-            });
+    <script src="{{ url_for('static', filename='server_connection.js') }}"></script>
+    <!-- <script type="text/javascript"  charset="utf-8">
+    $(document).ready(function() {
+        namespace = '/pay';
+        var socket = io(namespace);
+
+        socket.on('connect', function() {
+            socket.emit('initialise', {'data': 'initialising payment...'});
+        });
+
+        socket.on('payresponse', function(msg, cb) {
+            console.log(msg.response);
+            $('#status').text(msg.status).html();
+            $('#address').text(msg.address).html();
+            $('#amount').text(msg.amount).html();
+            $('#log').append('<br>' + $('<div/>').text(msg.response).html());
+            $('#timer').text(msg.time_left).html();
+            if (cb)
+                cb();
         });
-    </script>
 
-    <script type="text/javascript"  charset="utf-8">
+        $('form#pay').submit(function(event) {
+            socket.emit('payment', {'amount': $('#pay_data').val(), 'label' : null});
+            return false;
+        });
+    });
+    </script> -->
+
+    <!-- <script type="text/javascript"  charset="utf-8">
         intervalTimer = setInterval(function () {
             var currentTime = document.getElementById('timer').innerHTML;
             if (currentTime <= 0) {
@@ -39,7 +40,7 @@
             }
             document.getElementById('timer').innerHTML = Math.round(currentTime - 1);
         }, 1000)
-    </script>
+    </script> -->
 </head>
 
 <body style="background-color:white;">
@@ -57,5 +58,8 @@
     <p>Amount: <span id="amount"></span> BTC</p>
     <p><span id="timer"></span> seconds left.<p>
     <div id="log" ></div>
+
+    <div id="paybutton"></div>
+    <script
 </body>
 </html>