summaryrefslogtreecommitdiffstats
path: root/bitvend/processor.py
diff options
context:
space:
mode:
Diffstat (limited to 'bitvend/processor.py')
-rw-r--r--bitvend/processor.py94
1 files changed, 94 insertions, 0 deletions
diff --git a/bitvend/processor.py b/bitvend/processor.py
new file mode 100644
index 0000000..1291940
--- /dev/null
+++ b/bitvend/processor.py
@@ -0,0 +1,94 @@
+import threading
+import json
+import websocket
+import pprint
+import time
+import logging
+
+from bitvend.utils import to_local_currency
+
+
+class PaymentProcessor(threading.Thread):
+ daemon = True
+ input_address = None
+ device = None
+
+ def __init__(self, device, input_address='12fkW5EBb3uBy1zD8pan4TcbabP5Fjato7'):
+ super(PaymentProcessor, self).__init__()
+ self.device = device
+ self.input_address = input_address
+ self.logger = logging.getLogger(type(self).__name__)
+
+ def run(self):
+ self.logger.info('Starting...')
+ ws = websocket.WebSocketApp(
+ "wss://ws.blockchain.info/inv",
+ on_message=self.on_message,
+ on_error=self.on_error,
+ on_close=self.on_close)
+
+ ws.on_open = self.on_open
+
+ while True:
+ ws.run_forever()
+
+ def process_transaction(self, tx):
+ tx_size = tx['x']['size']
+ tx_hash = tx['x']['hash']
+ tx_value = sum([
+ o['value'] for o in tx['x']['out'] if o['addr'] == self.input_address
+ ], 0)
+ fee = sum([i['prev_out']['value'] for i in tx['x']['inputs']]) - \
+ sum([o['value'] for o in tx['x']['out']])
+
+ fee_byte = fee / tx_size
+
+ self.logger.info('%r %r %r %r %r', tx_size, tx_hash, tx_value, fee, fee_byte)
+ self.logger.info('In local currency: %r', to_local_currency(tx_value))
+
+ if to_local_currency(tx_value) < 100:
+ self.logger.warning('Whyyyy so low...')
+ return
+
+ if fee_byte < 50:
+ self.logger.warning('Fee too low...')
+ return
+
+ self.logger.info('Transaction ok, going to device...')
+
+ # FIXME we need better handling of ACK on POLL responses...
+ self.device.begin_session(to_local_currency(tx_value))
+ self.device.begin_session(to_local_currency(tx_value))
+ self.device.begin_session(to_local_currency(tx_value))
+
+ def on_message(self, ws, message):
+ #print message
+ data = json.loads(message)
+ if data['op'] == 'utx':
+ self.process_transaction(data)
+
+ def on_error(self, ws, error):
+ self.logger.error(error)
+
+ def on_close(self, ws):
+ self.logger.info('Connection closed')
+
+ def on_open(self, ws):
+ self.logger.info('Connected')
+
+ ws.send(json.dumps({
+ "op": "addr_sub",
+ "addr": self.input_address
+ }))
+
+ threading.Thread(target=self.keepalive, args=(ws,), daemon=True).start()
+
+ def keepalive(self, ws):
+ # Keepalive thread target, just send ping once in a while
+ while True:
+ # FIXME check last ping time
+ self.logger.info('Pinging...')
+ ws.send(json.dumps({
+ "op": "ping"
+ }))
+ time.sleep(20)