Exemplo n.º 1
0
    def _send_rpc(self, method, params=[]):
        request_data = json.dumps({'id': 0,
                                   'method': method,
                                   'params': params})

        req = Request(self.rpc_host)
        req.add_header("Authorization", "Basic %s" % self.auth)
        req.add_header("Content-Type", "text/plain")
        req.add_data(bytes(request_data, 'ascii'))

        try:
            file = urlopen(req)
            result = file.read()
            file.close()
            result = json.loads(str(result, 'ascii'))
        except HTTPError as e:
            try:
                result = e.read()
                result = json.loads(str(result, 'ascii'))
            except:
                logger.error(result)
                raise e
        if result['error']:
            raise RPCError(result['error'])
        return result['result']
Exemplo n.º 2
0
    def _serve_worker(self, socket, remote):
        logger.debug('Connection from %s:%d' % remote)
        try:
            file = socket.makefile()
            headers, uri, data = jsonrpc.read_http_request(file)

            auth = {'username': '******', 'difficulty': 1}
            if 'authorization' in headers:
                _, auth = headers['authorization'].split(' ')
                username, password = str(base64.decodestring(
                    bytes(auth, 'ascii')), 'ascii').split(':')
                auth = database.authenticate(username, password)
                if not auth['result']:
                    jsonrpc.send_http_response(file, 403, None, {})
                    return

            logger.debug('\nRequest: %s' % (data))
            code, result = jsonrpc.process_request(headers, uri, data,
                                                   self.work, auth)
            logger.debug('\nResponse:%s' % (result))
            jsonrpc.send_http_response(file, code, result,
                                       self._get_extended_headers(headers))
        except IsStratumConnection as e:
            self._handle_stratum(file, e.firstline)
        except:
            logger.debug('Request handle exception')
            logger.debug(traceback.format_exc())
            jsonrpc.send_http_response(file, 400, None)
        finally:
            logger.debug('Request process complete')
            try:
                file.close()
                socket.close()
            except:
                pass
Exemplo n.º 3
0
    def __init__(self, host, port, username, password):
        if not host or not port or not username or not password:
            config_file = self._get_config_file()
            if not os.path.exists(config_file):
                raise Exception("Cannot find configuration")

            if not host:
                host = 'localhost'
            if not port:
                port = self._get_default_port()

            with open(config_file, 'r') as f:
                data = f.read()
            data = data.splitlines(False)
            for i in data:
                if i.find('=') == -1:
                    continue
                k, v = i.split('=')
                if k == 'rpcuser':
                    username = v
                elif k == 'rpcpassword':
                    password = v
                elif k == 'rpcport':
                    port = v

        self.rpc_host = 'http://%s:%r' % (host, port)
        self.auth = base64.encodestring(bytes('%s:%s' % (username, password),
                                        'ascii'))
        self.auth = str(self.auth, 'ascii').replace('\n', '')
        logger.debug('RPC Host: %s' % self.rpc_host)
Exemplo n.º 4
0
    def _send_rpc(self, method, params=[]):
        request_data = json.dumps({
            'id': 0,
            'method': method,
            'params': params
        })

        req = Request(self.rpc_host)
        req.add_header("Authorization", "Basic %s" % self.auth)
        req.add_header("Content-Type", "text/plain")
        req.add_data(bytes(request_data, 'ascii'))

        try:
            file = urlopen(req)
            result = file.read()
            file.close()
            result = json.loads(str(result, 'ascii'))
        except HTTPError as e:
            try:
                result = e.read()
                result = json.loads(str(result, 'ascii'))
            except:
                logger.error(result)
                raise e
        if result['error']:
            raise RPCError(result['error'])
        return result['result']
Exemplo n.º 5
0
    def __init__(self, host, port, username, password):
        if not host or not port or not username or not password:
            config_file = self._get_config_file()
            if not os.path.exists(config_file):
                raise Exception("Cannot find configuration")

            if not host:
                host = 'localhost'
            if not port:
                port = self._get_default_port()

            with open(config_file, 'r') as f:
                data = f.read()
            data = data.splitlines(False)
            for i in data:
                if i.find('=') == -1:
                    continue
                k, v = i.split('=')
                if k == 'rpcuser':
                    username = v
                elif k == 'rpcpassword':
                    password = v
                elif k == 'rpcport':
                    port = v

        self.rpc_host = 'http://%s:%r' % (host, port)
        self.auth = base64.encodestring(
            bytes('%s:%s' % (username, password), 'ascii'))
        self.auth = str(self.auth, 'ascii').replace('\n', '')
        logger.debug('RPC Host: %s' % self.rpc_host)
Exemplo n.º 6
0
def send_http_response(file, code, content, headers=None):
    if code == 200:
        message = 'OK'
    elif code == 500:
        message = 'Internal Server Error'
    elif code == 400:
        message = 'Bad Request'
    elif code == 403:
        message = 'Forbidden'
    file.write(bytes('HTTP/1.1 %d %s\r\n' % (code, message), 'ascii'))
    file.write(bytes('Server: dlunchpool\r\n', 'ascii'))
    if content:
        file.write(bytes('Content-Length: %d\r\n' % len(content), 'ascii'))
        file.write(bytes('Content-Type: application/json\r\n', 'ascii'))
    if headers:
        for i in headers:
            file.write(bytes('%s: %s\r\n' % (i, headers[i]), 'ascii'))
    file.write(bytes('\r\n', 'ascii'))
    if content:
        file.write(bytes(content, 'ascii'))
    file.flush()
Exemplo n.º 7
0
def send_http_response(file, code, content, headers=None):
    if code == 200:
        message = 'OK'
    elif code == 500:
        message = 'Internal Server Error'
    elif code == 400:
        message = 'Bad Request'
    elif code == 403:
        message = 'Forbidden'
    file.write(bytes('HTTP/1.1 %d %s\r\n' % (code, message), 'ascii'))
    file.write(bytes('Server: dlunchpool\r\n', 'ascii'))
    if content:
        file.write(bytes('Content-Length: %d\r\n' % len(content), 'ascii'))
        file.write(bytes('Content-Type: application/json\r\n', 'ascii'))
    if headers:
        for i in headers:
            file.write(bytes('%s: %s\r\n' % (i, headers[i]), 'ascii'))
    file.write(bytes('\r\n', 'ascii'))
    if content:
        file.write(bytes(content, 'ascii'))
    file.flush()
Exemplo n.º 8
0
    def _serve_worker(self, socket, remote):
        logger.debug('Connection from %s:%d' % remote)
        try:
            file = socket.makefile()
            headers, uri, data = jsonrpc.read_http_request(file)

            auth = {'username': '******', 'difficulty': 1}
            if 'authorization' in headers:
                _, auth = headers['authorization'].split(' ')
                username, password = str(
                    base64.decodestring(bytes(auth, 'ascii')),
                    'ascii').split(':')
                auth = database.authenticate(username, password)
                if not auth['result']:
                    jsonrpc.send_http_response(file, 403, None, {})
                    return

            logger.debug('\nRequest: %s' % (data))
            code, result = jsonrpc.process_request(headers, uri, data,
                                                   self.work, auth)
            logger.debug('\nResponse:%s' % (result))
            jsonrpc.send_http_response(file, code, result,
                                       self._get_extended_headers(headers))
        except IsStratumConnection as e:
            self._handle_stratum(file, e.firstline)
        except:
            logger.debug('Request handle exception')
            logger.debug(traceback.format_exc())
            jsonrpc.send_http_response(file, 400, None)
        finally:
            logger.debug('Request process complete')
            try:
                file.close()
                socket.close()
            except:
                pass
Exemplo n.º 9
0
 def _send_stratum_message(self, message):
     logger.debug('Stratum send: %s' % message)
     self.file.write(bytes(message + '\n', 'ascii'))
     self.file.flush()