You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

138 lines
4.7 KiB

#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
9 years ago
# 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:
#
9 years ago
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
9 years ago
# 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 queue
import threading, os, json
from collections import defaultdict
try:
from SimpleWebSocketServer import WebSocket, SimpleSSLWebSocketServer
except ImportError:
import sys
sys.exit("install SimpleWebSocketServer")
8 years ago
from . import util
8 years ago
request_queue = queue.Queue()
class ElectrumWebSocket(WebSocket):
def handleMessage(self):
assert self.data[0:3] == 'id:'
util.print_error("message received", self.data)
request_id = self.data[3:]
request_queue.put((self, request_id))
def handleConnected(self):
util.print_error("connected", self.address)
def handleClose(self):
util.print_error("closed", self.address)
class WsClientThread(util.DaemonThread):
9 years ago
def __init__(self, config, network):
util.DaemonThread.__init__(self)
9 years ago
self.network = network
self.config = config
7 years ago
self.response_queue = queue.Queue()
self.subscriptions = defaultdict(list)
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:
s = f.read()
d = json.loads(s)
addr = d.get('address')
amount = d.get('amount')
return addr, amount
def reading_thread(self):
while self.is_running():
try:
ws, request_id = request_queue.get()
7 years ago
except queue.Empty:
continue
try:
addr, amount = self.make_request(request_id)
except:
continue
9 years ago
l = self.subscriptions.get(addr, [])
l.append((ws, amount))
self.subscriptions[addr] = l
self.network.subscribe_to_addresses([addr], self.response_queue.put)
def run(self):
threading.Thread(target=self.reading_thread).start()
while self.is_running():
try:
r = self.response_queue.get(timeout=0.1)
7 years ago
except queue.Empty:
continue
9 years ago
util.print_error('response', r)
method = r.get('method')
Remove explicit send calls, part deux (#4408) * Rename synchronous_get to synchronous_send This makes it more inline with the method 'send' of which synchronous_send is the, well, synchronous version. * Move protocol strings from scripts to network This is again a small step in the right direction. The network module is going to accumulate more and more of these simple methods. Once everything is moved into that module, that module is going to be split. Note that I've left the scripts which use scripts/util.py alone. I suspect the same functionality can be reached when using just lib/network.py and that scripts/util.py is obsolete. * Remove protocol string from verifier and websocket Websocket still has some references, that'll take more work to remove. Once the network module has been split this should be easy. I took the liberty to rename a variable to better show what it is. * Remove protocol strings from remainder The naming scheme I'm following for the newly introduced methods in the network module is: 'blockchain.<subject>.<action>' -> def <action>_(for|to)_<subject> * Move explicit protocol calls closer to each other This makes it easier to keep track of the methods which are due to be extracted. * Remove `send` when using `get_transaction` This is the final step to formalize (the informal) interface of the network module. A chance of note is changed interface for async/sync calls. It is no longer required to use the `synchronous_send` call. Merely NOT passing a callback makes the call synchronous. I feel this makes the API more intuitive to work with and easier to replace with a different network module. * Remove send from get_merkle_for_transaction The pattern which emerged for calling the lambda yielded an slight refactor. I'm not happy with the name for the `__invoke` method. * Remove explict send from websockets * Remove explicit send from scripts * Remove explicit send from wallet * Remove explicit sync_send from commands, scripts * Remove optional timeout parameter This parameter doesn't seem to be used a lot and removing it makes the remaining calls easier. Potentionally a contentious choice! * Rename `broadcast` to `broadcast_transaction` Doing so makes the method name consistent with the other ElectrumX protocol method names. * Remove synchronous_send Now every method is intuitive in what it does, no special handling required. The `broadcast_transaction` method is weird. I've opted not to change the return type b/c I found it hard to know what the exact consequences are. But ideally this method should just works as all the other ElectrumX related messages. On the other hand this shows nicely how you _can_ do something differnt quite easy. * Rename the awkwardly name `__invoke` method The new name reflects what it does. * Process the result of linter feedback I've used flake8-diff (and ignored a couple of line length warnings). * Rename tx_response to on_tx_response This fell through the cracks when this branch was rebased. * subscript_to_scripthash should be get_balance An oversight while refactoring. * Add missing return statement Without this statement the transaction would have been broadcasted twice. * Pass list of tuples to send not single tuple * Add @staticmethod decorator * Fix argument to be an array
7 years ago
scripthash = r.get('params')[0]
result = r.get('result')
if result is None:
continue
if method == 'blockchain.scripthash.subscribe':
Remove explicit send calls, part deux (#4408) * Rename synchronous_get to synchronous_send This makes it more inline with the method 'send' of which synchronous_send is the, well, synchronous version. * Move protocol strings from scripts to network This is again a small step in the right direction. The network module is going to accumulate more and more of these simple methods. Once everything is moved into that module, that module is going to be split. Note that I've left the scripts which use scripts/util.py alone. I suspect the same functionality can be reached when using just lib/network.py and that scripts/util.py is obsolete. * Remove protocol string from verifier and websocket Websocket still has some references, that'll take more work to remove. Once the network module has been split this should be easy. I took the liberty to rename a variable to better show what it is. * Remove protocol strings from remainder The naming scheme I'm following for the newly introduced methods in the network module is: 'blockchain.<subject>.<action>' -> def <action>_(for|to)_<subject> * Move explicit protocol calls closer to each other This makes it easier to keep track of the methods which are due to be extracted. * Remove `send` when using `get_transaction` This is the final step to formalize (the informal) interface of the network module. A chance of note is changed interface for async/sync calls. It is no longer required to use the `synchronous_send` call. Merely NOT passing a callback makes the call synchronous. I feel this makes the API more intuitive to work with and easier to replace with a different network module. * Remove send from get_merkle_for_transaction The pattern which emerged for calling the lambda yielded an slight refactor. I'm not happy with the name for the `__invoke` method. * Remove explict send from websockets * Remove explicit send from scripts * Remove explicit send from wallet * Remove explicit sync_send from commands, scripts * Remove optional timeout parameter This parameter doesn't seem to be used a lot and removing it makes the remaining calls easier. Potentionally a contentious choice! * Rename `broadcast` to `broadcast_transaction` Doing so makes the method name consistent with the other ElectrumX protocol method names. * Remove synchronous_send Now every method is intuitive in what it does, no special handling required. The `broadcast_transaction` method is weird. I've opted not to change the return type b/c I found it hard to know what the exact consequences are. But ideally this method should just works as all the other ElectrumX related messages. On the other hand this shows nicely how you _can_ do something differnt quite easy. * Rename the awkwardly name `__invoke` method The new name reflects what it does. * Process the result of linter feedback I've used flake8-diff (and ignored a couple of line length warnings). * Rename tx_response to on_tx_response This fell through the cracks when this branch was rebased. * subscript_to_scripthash should be get_balance An oversight while refactoring. * Add missing return statement Without this statement the transaction would have been broadcasted twice. * Pass list of tuples to send not single tuple * Add @staticmethod decorator * Fix argument to be an array
7 years ago
self.network.get_balance_for_scripthash(
scripthash, self.response_queue.put)
elif method == 'blockchain.scripthash.get_balance':
Remove explicit send calls, part deux (#4408) * Rename synchronous_get to synchronous_send This makes it more inline with the method 'send' of which synchronous_send is the, well, synchronous version. * Move protocol strings from scripts to network This is again a small step in the right direction. The network module is going to accumulate more and more of these simple methods. Once everything is moved into that module, that module is going to be split. Note that I've left the scripts which use scripts/util.py alone. I suspect the same functionality can be reached when using just lib/network.py and that scripts/util.py is obsolete. * Remove protocol string from verifier and websocket Websocket still has some references, that'll take more work to remove. Once the network module has been split this should be easy. I took the liberty to rename a variable to better show what it is. * Remove protocol strings from remainder The naming scheme I'm following for the newly introduced methods in the network module is: 'blockchain.<subject>.<action>' -> def <action>_(for|to)_<subject> * Move explicit protocol calls closer to each other This makes it easier to keep track of the methods which are due to be extracted. * Remove `send` when using `get_transaction` This is the final step to formalize (the informal) interface of the network module. A chance of note is changed interface for async/sync calls. It is no longer required to use the `synchronous_send` call. Merely NOT passing a callback makes the call synchronous. I feel this makes the API more intuitive to work with and easier to replace with a different network module. * Remove send from get_merkle_for_transaction The pattern which emerged for calling the lambda yielded an slight refactor. I'm not happy with the name for the `__invoke` method. * Remove explict send from websockets * Remove explicit send from scripts * Remove explicit send from wallet * Remove explicit sync_send from commands, scripts * Remove optional timeout parameter This parameter doesn't seem to be used a lot and removing it makes the remaining calls easier. Potentionally a contentious choice! * Rename `broadcast` to `broadcast_transaction` Doing so makes the method name consistent with the other ElectrumX protocol method names. * Remove synchronous_send Now every method is intuitive in what it does, no special handling required. The `broadcast_transaction` method is weird. I've opted not to change the return type b/c I found it hard to know what the exact consequences are. But ideally this method should just works as all the other ElectrumX related messages. On the other hand this shows nicely how you _can_ do something differnt quite easy. * Rename the awkwardly name `__invoke` method The new name reflects what it does. * Process the result of linter feedback I've used flake8-diff (and ignored a couple of line length warnings). * Rename tx_response to on_tx_response This fell through the cracks when this branch was rebased. * subscript_to_scripthash should be get_balance An oversight while refactoring. * Add missing return statement Without this statement the transaction would have been broadcasted twice. * Pass list of tuples to send not single tuple * Add @staticmethod decorator * Fix argument to be an array
7 years ago
addr = self.network.h2addr.get(scripthash, None)
if addr is None:
Remove explicit send calls, part deux (#4408) * Rename synchronous_get to synchronous_send This makes it more inline with the method 'send' of which synchronous_send is the, well, synchronous version. * Move protocol strings from scripts to network This is again a small step in the right direction. The network module is going to accumulate more and more of these simple methods. Once everything is moved into that module, that module is going to be split. Note that I've left the scripts which use scripts/util.py alone. I suspect the same functionality can be reached when using just lib/network.py and that scripts/util.py is obsolete. * Remove protocol string from verifier and websocket Websocket still has some references, that'll take more work to remove. Once the network module has been split this should be easy. I took the liberty to rename a variable to better show what it is. * Remove protocol strings from remainder The naming scheme I'm following for the newly introduced methods in the network module is: 'blockchain.<subject>.<action>' -> def <action>_(for|to)_<subject> * Move explicit protocol calls closer to each other This makes it easier to keep track of the methods which are due to be extracted. * Remove `send` when using `get_transaction` This is the final step to formalize (the informal) interface of the network module. A chance of note is changed interface for async/sync calls. It is no longer required to use the `synchronous_send` call. Merely NOT passing a callback makes the call synchronous. I feel this makes the API more intuitive to work with and easier to replace with a different network module. * Remove send from get_merkle_for_transaction The pattern which emerged for calling the lambda yielded an slight refactor. I'm not happy with the name for the `__invoke` method. * Remove explict send from websockets * Remove explicit send from scripts * Remove explicit send from wallet * Remove explicit sync_send from commands, scripts * Remove optional timeout parameter This parameter doesn't seem to be used a lot and removing it makes the remaining calls easier. Potentionally a contentious choice! * Rename `broadcast` to `broadcast_transaction` Doing so makes the method name consistent with the other ElectrumX protocol method names. * Remove synchronous_send Now every method is intuitive in what it does, no special handling required. The `broadcast_transaction` method is weird. I've opted not to change the return type b/c I found it hard to know what the exact consequences are. But ideally this method should just works as all the other ElectrumX related messages. On the other hand this shows nicely how you _can_ do something differnt quite easy. * Rename the awkwardly name `__invoke` method The new name reflects what it does. * Process the result of linter feedback I've used flake8-diff (and ignored a couple of line length warnings). * Rename tx_response to on_tx_response This fell through the cracks when this branch was rebased. * subscript_to_scripthash should be get_balance An oversight while refactoring. * Add missing return statement Without this statement the transaction would have been broadcasted twice. * Pass list of tuples to send not single tuple * Add @staticmethod decorator * Fix argument to be an array
7 years ago
util.print_error(
"can't find address for scripthash: %s" % scripthash)
9 years ago
l = self.subscriptions.get(addr, [])
9 years ago
for ws, amount in l:
9 years ago
if not ws.closed:
if sum(result.values()) >=amount:
ws.sendMessage('paid')
9 years ago
class WebSocketServer(threading.Thread):
def __init__(self, config, ns):
threading.Thread.__init__(self)
self.config = config
self.net_server = ns
self.daemon = True
def run(self):
t = WsClientThread(self.config, self.net_server)
t.start()
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()