summaryrefslogtreecommitdiffstats
path: root/bitvend/processor.py
blob: 8b7c9f18693d7d2524be1581b41d9f9599c6c0f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import threading
import json
import websocket
import time
import logging

from bitvend.utils import to_local_currency
from bitvend.models import db, Transaction


class PaymentProcessor(threading.Thread):
    daemon = True
    input_address = None
    device = None
    last_pong = None
    app = None

    def __init__(self, device, input_address=None, app=None):
        super(PaymentProcessor, self).__init__()
        self.device = device
        self.input_address = input_address
        self.logger = logging.getLogger(type(self).__name__)

        if app:
            self.init_app(app)

    def init_app(self, app):
        self.app = app

        if not self.input_address:
            self.input_address = self.app.config['INPUT_ADDRESS']

    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))

        with self.app.app_context():
            tx = Transaction(tx_hash=tx_hash)
            tx.value = to_local_currency(tx_value)
            db.session.add(tx)
            db.session.commit()

        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), tx_hash)
        self.device.begin_session(to_local_currency(tx_value), tx_hash)
        self.device.begin_session(to_local_currency(tx_value), tx_hash)

    def on_message(self, ws, message):
        #print message
        data = json.loads(message)

        if data['op'] == 'utx':
            self.process_transaction(data)
        elif data['op'] == 'pong':
            self.last_pong = time.time()

    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
        self.last_pong = time.time()
        while True:
            # FIXME check last ping time
            ws.send(json.dumps({
                "op": "ping"
                }))
            time.sleep(20)

            if time.time() - self.last_pong > 60:
                ws.close()