2017-01-18 00:34:40 +01:00
|
|
|
# Copyright (c) 2011 Jeff Garzik
|
|
|
|
#
|
|
|
|
# Previous copyright, from python-jsonrpc/jsonrpc/proxy.py:
|
|
|
|
#
|
|
|
|
# Copyright (c) 2007 Jan-Klaas Kollhof
|
|
|
|
#
|
|
|
|
# This file is part of jsonrpc.
|
|
|
|
#
|
|
|
|
# jsonrpc is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2.1 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This software is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Lesser General Public License
|
|
|
|
# along with this software; if not, write to the Free Software
|
|
|
|
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
|
|
|
"""HTTP proxy for opening RPC connection to bitcoind.
|
|
|
|
|
|
|
|
AuthServiceProxy has the following improvements over python-jsonrpc's
|
|
|
|
ServiceProxy class:
|
|
|
|
|
|
|
|
- HTTP connections persist for the life of the AuthServiceProxy object
|
|
|
|
(if server supports HTTP/1.1)
|
|
|
|
- sends protocol 'version', per JSON-RPC 1.1
|
|
|
|
- sends proper, incrementing 'id'
|
|
|
|
- sends Basic HTTP authentication headers
|
|
|
|
- parses all JSON numbers that look like floats as Decimal
|
|
|
|
- uses standard Python json lib
|
2014-03-13 22:51:05 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
import http.client as httplib
|
|
|
|
except ImportError:
|
|
|
|
import httplib
|
|
|
|
import base64
|
|
|
|
import decimal
|
2014-07-08 20:31:13 +02:00
|
|
|
import json
|
|
|
|
import logging
|
2016-11-02 20:08:54 +01:00
|
|
|
import socket
|
2017-04-17 10:50:00 +02:00
|
|
|
import time
|
2014-03-13 22:51:05 +01:00
|
|
|
try:
|
|
|
|
import urllib.parse as urlparse
|
|
|
|
except ImportError:
|
|
|
|
import urlparse
|
|
|
|
|
|
|
|
USER_AGENT = "AuthServiceProxy/0.1"
|
|
|
|
|
|
|
|
HTTP_TIMEOUT = 30
|
|
|
|
|
2014-07-08 20:31:13 +02:00
|
|
|
log = logging.getLogger("BitcoinRPC")
|
2014-03-13 22:51:05 +01:00
|
|
|
|
|
|
|
class JSONRPCException(Exception):
|
|
|
|
def __init__(self, rpc_error):
|
2016-09-25 20:02:14 +02:00
|
|
|
try:
|
|
|
|
errmsg = '%(message)s (%(code)i)' % rpc_error
|
|
|
|
except (KeyError, TypeError):
|
|
|
|
errmsg = ''
|
|
|
|
Exception.__init__(self, errmsg)
|
2014-03-13 22:51:05 +01:00
|
|
|
self.error = rpc_error
|
|
|
|
|
|
|
|
|
2014-07-08 20:31:13 +02:00
|
|
|
def EncodeDecimal(o):
|
|
|
|
if isinstance(o, decimal.Decimal):
|
2016-03-28 11:44:19 +02:00
|
|
|
return str(o)
|
2014-07-08 20:31:13 +02:00
|
|
|
raise TypeError(repr(o) + " is not JSON serializable")
|
|
|
|
|
2014-03-13 22:51:05 +01:00
|
|
|
class AuthServiceProxy(object):
|
2014-07-08 20:31:13 +02:00
|
|
|
__id_count = 0
|
|
|
|
|
2016-04-28 15:17:41 +02:00
|
|
|
# ensure_ascii: escape unicode as \uXXXX, passed to json.dumps
|
|
|
|
def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None, ensure_ascii=True):
|
2014-03-13 22:51:05 +01:00
|
|
|
self.__service_url = service_url
|
2015-10-11 07:41:19 +02:00
|
|
|
self._service_name = service_name
|
2016-04-28 15:17:41 +02:00
|
|
|
self.ensure_ascii = ensure_ascii # can be toggled on the fly by tests
|
2014-03-13 22:51:05 +01:00
|
|
|
self.__url = urlparse.urlparse(service_url)
|
|
|
|
if self.__url.port is None:
|
|
|
|
port = 80
|
|
|
|
else:
|
|
|
|
port = self.__url.port
|
|
|
|
(user, passwd) = (self.__url.username, self.__url.password)
|
|
|
|
try:
|
|
|
|
user = user.encode('utf8')
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
try:
|
|
|
|
passwd = passwd.encode('utf8')
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
authpair = user + b':' + passwd
|
|
|
|
self.__auth_header = b'Basic ' + base64.b64encode(authpair)
|
|
|
|
|
|
|
|
if connection:
|
|
|
|
# Callables re-use the connection of the original proxy
|
|
|
|
self.__conn = connection
|
|
|
|
elif self.__url.scheme == 'https':
|
|
|
|
self.__conn = httplib.HTTPSConnection(self.__url.hostname, port,
|
2016-03-28 12:28:49 +02:00
|
|
|
timeout=timeout)
|
2014-03-13 22:51:05 +01:00
|
|
|
else:
|
|
|
|
self.__conn = httplib.HTTPConnection(self.__url.hostname, port,
|
2016-03-28 12:28:49 +02:00
|
|
|
timeout=timeout)
|
2014-03-13 22:51:05 +01:00
|
|
|
|
|
|
|
def __getattr__(self, name):
|
|
|
|
if name.startswith('__') and name.endswith('__'):
|
|
|
|
# Python internal stuff
|
|
|
|
raise AttributeError
|
2015-10-11 07:41:19 +02:00
|
|
|
if self._service_name is not None:
|
|
|
|
name = "%s.%s" % (self._service_name, name)
|
2014-03-13 22:51:05 +01:00
|
|
|
return AuthServiceProxy(self.__service_url, name, connection=self.__conn)
|
|
|
|
|
2015-09-19 14:12:44 +02:00
|
|
|
def _request(self, method, path, postdata):
|
|
|
|
'''
|
|
|
|
Do a HTTP request, with retry if we get disconnected (e.g. due to a timeout).
|
|
|
|
This is a workaround for https://bugs.python.org/issue3566 which is fixed in Python 3.5.
|
|
|
|
'''
|
|
|
|
headers = {'Host': self.__url.hostname,
|
|
|
|
'User-Agent': USER_AGENT,
|
|
|
|
'Authorization': self.__auth_header,
|
|
|
|
'Content-type': 'application/json'}
|
|
|
|
try:
|
|
|
|
self.__conn.request(method, path, postdata, headers)
|
|
|
|
return self._get_response()
|
|
|
|
except httplib.BadStatusLine as e:
|
|
|
|
if e.line == "''": # if connection was closed, try again
|
|
|
|
self.__conn.close()
|
|
|
|
self.__conn.request(method, path, postdata, headers)
|
|
|
|
return self._get_response()
|
|
|
|
else:
|
|
|
|
raise
|
2016-09-29 17:02:08 +02:00
|
|
|
except (BrokenPipeError,ConnectionResetError):
|
|
|
|
# Python 3.5+ raises BrokenPipeError instead of BadStatusLine when the connection was reset
|
|
|
|
# ConnectionResetError happens on FreeBSD with Python 3.4
|
2016-05-13 04:49:19 +02:00
|
|
|
self.__conn.close()
|
|
|
|
self.__conn.request(method, path, postdata, headers)
|
|
|
|
return self._get_response()
|
2015-09-19 14:12:44 +02:00
|
|
|
|
2017-09-07 23:38:11 +02:00
|
|
|
def get_request(self, *args, **argsn):
|
2014-07-08 20:31:13 +02:00
|
|
|
AuthServiceProxy.__id_count += 1
|
2014-03-13 22:51:05 +01:00
|
|
|
|
2015-10-11 07:41:19 +02:00
|
|
|
log.debug("-%s-> %s %s"%(AuthServiceProxy.__id_count, self._service_name,
|
2016-04-28 15:17:41 +02:00
|
|
|
json.dumps(args, default=EncodeDecimal, ensure_ascii=self.ensure_ascii)))
|
2016-09-25 20:29:26 +02:00
|
|
|
if args and argsn:
|
|
|
|
raise ValueError('Cannot handle both named and positional arguments')
|
2017-09-07 23:38:11 +02:00
|
|
|
return {'version': '1.1',
|
|
|
|
'method': self._service_name,
|
|
|
|
'params': args or argsn,
|
|
|
|
'id': AuthServiceProxy.__id_count}
|
|
|
|
|
|
|
|
def __call__(self, *args, **argsn):
|
|
|
|
postdata = json.dumps(self.get_request(*args, **argsn), default=EncodeDecimal, ensure_ascii=self.ensure_ascii)
|
2016-04-28 15:17:41 +02:00
|
|
|
response = self._request('POST', self.__url.path, postdata.encode('utf-8'))
|
2014-03-13 22:51:05 +01:00
|
|
|
if response['error'] is not None:
|
|
|
|
raise JSONRPCException(response['error'])
|
|
|
|
elif 'result' not in response:
|
|
|
|
raise JSONRPCException({
|
|
|
|
'code': -343, 'message': 'missing JSON-RPC result'})
|
|
|
|
else:
|
|
|
|
return response['result']
|
|
|
|
|
2017-09-07 23:38:11 +02:00
|
|
|
def batch(self, rpc_call_list):
|
2016-04-28 15:17:41 +02:00
|
|
|
postdata = json.dumps(list(rpc_call_list), default=EncodeDecimal, ensure_ascii=self.ensure_ascii)
|
2014-07-08 20:31:13 +02:00
|
|
|
log.debug("--> "+postdata)
|
2016-04-28 15:17:41 +02:00
|
|
|
return self._request('POST', self.__url.path, postdata.encode('utf-8'))
|
2014-03-13 22:51:05 +01:00
|
|
|
|
|
|
|
def _get_response(self):
|
2017-04-17 10:50:00 +02:00
|
|
|
req_start_time = time.time()
|
2016-11-02 20:08:54 +01:00
|
|
|
try:
|
|
|
|
http_response = self.__conn.getresponse()
|
|
|
|
except socket.timeout as e:
|
|
|
|
raise JSONRPCException({
|
|
|
|
'code': -344,
|
|
|
|
'message': '%r RPC took longer than %f seconds. Consider '
|
|
|
|
'using larger timeout for calls that take '
|
|
|
|
'longer to return.' % (self._service_name,
|
|
|
|
self.__conn.timeout)})
|
2014-03-13 22:51:05 +01:00
|
|
|
if http_response is None:
|
|
|
|
raise JSONRPCException({
|
|
|
|
'code': -342, 'message': 'missing HTTP response from server'})
|
|
|
|
|
2016-04-07 15:21:01 +02:00
|
|
|
content_type = http_response.getheader('Content-Type')
|
|
|
|
if content_type != 'application/json':
|
|
|
|
raise JSONRPCException({
|
|
|
|
'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (http_response.status, http_response.reason)})
|
|
|
|
|
2014-07-08 20:31:13 +02:00
|
|
|
responsedata = http_response.read().decode('utf8')
|
|
|
|
response = json.loads(responsedata, parse_float=decimal.Decimal)
|
2017-04-17 10:50:00 +02:00
|
|
|
elapsed = time.time() - req_start_time
|
2014-07-08 20:31:13 +02:00
|
|
|
if "error" in response and response["error"] is None:
|
2017-04-17 10:50:00 +02:00
|
|
|
log.debug("<-%s- [%.6f] %s"%(response["id"], elapsed, json.dumps(response["result"], default=EncodeDecimal, ensure_ascii=self.ensure_ascii)))
|
2014-07-08 20:31:13 +02:00
|
|
|
else:
|
2017-04-17 10:50:00 +02:00
|
|
|
log.debug("<-- [%.6f] %s"%(elapsed,responsedata))
|
2014-07-08 20:31:13 +02:00
|
|
|
return response
|
2017-07-13 16:53:42 +02:00
|
|
|
|
|
|
|
def __truediv__(self, relative_uri):
|
|
|
|
return AuthServiceProxy("{}/{}".format(self.__service_url, relative_uri), self._service_name, connection=self.__conn)
|