Files
pallectrum/electrum/websockets.py

133 lines
4.6 KiB
Python
Raw Normal View History

2015-07-24 11:39:12 +02:00
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
2016-02-23 11:36:42 +01:00
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
2015-07-24 11:39:12 +02:00
#
2016-02-23 11:36:42 +01:00
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
2015-07-24 11:39:12 +02:00
#
2016-02-23 11:36:42 +01:00
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import threading
import os
import json
2015-07-24 11:39:12 +02:00
from collections import defaultdict
import asyncio
2018-10-22 16:41:25 +02:00
from typing import Dict, List, Tuple, TYPE_CHECKING
import traceback
import sys
2015-07-24 11:39:12 +02:00
try:
from SimpleWebSocketServer import WebSocket, SimpleSSLWebSocketServer
except ImportError:
sys.exit("install SimpleWebSocketServer")
2015-07-24 11:39:12 +02:00
2018-07-01 15:59:32 +02:00
from . import bitcoin
from .synchronizer import SynchronizerBase
2019-04-26 18:52:26 +02:00
from .logging import Logger
2018-10-22 16:41:25 +02:00
if TYPE_CHECKING:
from .network import Network
from .simple_config import SimpleConfig
request_queue = asyncio.Queue()
2015-07-24 11:39:12 +02:00
2019-04-26 18:52:26 +02:00
class ElectrumWebSocket(WebSocket, Logger):
def __init__(self):
WebSocket.__init__(self)
Logger.__init__(self)
2015-07-24 11:39:12 +02:00
def handleMessage(self):
assert self.data[0:3] == 'id:'
2019-04-26 18:52:26 +02:00
self.logger.info(f"message received {self.data}")
2015-07-24 11:39:12 +02:00
request_id = self.data[3:]
asyncio.run_coroutine_threadsafe(
request_queue.put((self, request_id)), asyncio.get_event_loop())
2015-07-24 11:39:12 +02:00
def handleConnected(self):
2019-04-26 18:52:26 +02:00
self.logger.info(f"connected {self.address}")
2015-07-24 11:39:12 +02:00
def handleClose(self):
2019-04-26 18:52:26 +02:00
self.logger.info(f"closed {self.address}")
2015-07-24 11:39:12 +02:00
class BalanceMonitor(SynchronizerBase):
2015-07-24 11:39:12 +02:00
2018-10-22 16:41:25 +02:00
def __init__(self, config: 'SimpleConfig', network: 'Network'):
SynchronizerBase.__init__(self, network)
2015-07-24 11:39:12 +02:00
self.config = config
2018-10-11 16:30:30 +02:00
self.expected_payments = defaultdict(list) # type: Dict[str, List[Tuple[WebSocket, int]]]
2015-07-24 11:39:12 +02:00
def make_request(self, request_id):
# read json file
rdir = self.config.get('requests_dir')
n = os.path.join(rdir, 'req', request_id[0], request_id[1], request_id, request_id + '.json')
with open(n, encoding='utf-8') as f:
2015-07-24 11:39:12 +02:00
s = f.read()
d = json.loads(s)
addr = d.get('address')
amount = d.get('amount')
return addr, amount
async def main(self):
# resend existing subscriptions if we were restarted
for addr in self.expected_payments:
await self._add_address(addr)
# main loop
while True:
ws, request_id = await request_queue.get()
2015-07-24 11:39:12 +02:00
try:
addr, amount = self.make_request(request_id)
except Exception:
2019-04-26 18:52:26 +02:00
self.logger.exception('')
2015-07-24 11:39:12 +02:00
continue
self.expected_payments[addr].append((ws, amount))
await self._add_address(addr)
2015-11-25 10:32:46 +01:00
async def _on_address_status(self, addr, status):
2019-04-26 18:52:26 +02:00
self.logger.info(f'new status for addr {addr}')
sh = bitcoin.address_to_scripthash(addr)
balance = await self.network.get_balance_for_scripthash(sh)
for ws, amount in self.expected_payments[addr]:
if not ws.closed:
if sum(balance.values()) >= amount:
ws.sendMessage('paid')
2015-07-24 11:39:12 +02:00
class WebSocketServer(threading.Thread):
2018-10-22 16:41:25 +02:00
def __init__(self, config: 'SimpleConfig', network: 'Network'):
2015-07-24 11:39:12 +02:00
threading.Thread.__init__(self)
self.config = config
self.network = network
asyncio.set_event_loop(network.asyncio_loop)
2015-07-24 11:39:12 +02:00
self.daemon = True
self.balance_monitor = BalanceMonitor(self.config, self.network)
self.start()
2015-07-24 11:39:12 +02:00
def run(self):
asyncio.set_event_loop(self.network.asyncio_loop)
2015-07-24 11:39:12 +02:00
host = self.config.get('websocket_server')
port = self.config.get('websocket_port', 9999)
certfile = self.config.get('ssl_chain')
keyfile = self.config.get('ssl_privkey')
self.server = SimpleSSLWebSocketServer(host, port, ElectrumWebSocket, certfile, keyfile)
self.server.serveforever()