Esempio n. 1
0
def is_ready():
    """this method used by the client to check if the server is alive, caught up, and ready to accept requests.
    If the server is NOT caught up, a 525 error will be returned actually before hitting this point. Thus,
    if we actually return data from this function, it should always be true. (may change this behaviour later)"""

    ip = flask.request.headers.get('X-Real-Ip', flask.request.remote_addr)
    country = module_config['GEOIP'].country_code_by_addr(ip)
    return {
        'caught_up':
        blockfeed.fuzzy_is_caught_up(),
        'last_message_index':
        config.state['last_message_index'],
        'cw_last_message_seq':
        config.state['cw_last_message_seq'],
        'block_height':
        config.state['cp_backend_block_index'],
        'testnet':
        config.TESTNET,
        'regtest':
        config.REGTEST,
        'ip':
        ip,
        'country':
        country,
        'quote_assets':
        config.QUOTE_ASSETS,
        'quick_buy_enable':
        True
        if module_config['VENDING_MACHINE_PROVIDER'] is not None else False
    }
Esempio n. 2
0
    def handle_post():
        # don't do anything if we're not caught up
        if not blockfeed.fuzzy_is_caught_up():
            obj_error = jsonrpc.exceptions.JSONRPCServerError(
                data="Server is not caught up. Please try again later.")
            response = flask.Response(obj_error.json.encode(),
                                      525,
                                      mimetype='application/json')
            #^ 525 is a custom response code we use for this one purpose
            _set_cors_headers(response)
            return response

        try:
            request_json = flask.request.get_data().decode('utf-8')
            request_data = json.loads(request_json)
            assert 'id' in request_data and request_data[
                'jsonrpc'] == "2.0" and request_data['method']
            # params may be omitted
        except:
            obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest(
                data="Invalid JSON-RPC 2.0 request format")
            response = flask.Response(obj_error.json.encode(),
                                      200,
                                      mimetype='application/json')
            _set_cors_headers(response)
            return response

        # only arguments passed as a dict are supported
        if request_data.get('params', None) and not isinstance(
                request_data['params'], dict):
            obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest(
                data=
                'Arguments must be passed as a JSON object (list of unnamed arguments not supported)'
            )
            response = flask.Response(obj_error.json.encode(),
                                      200,
                                      mimetype='application/json')
            _set_cors_headers(response)
            return response
        rpc_response = jsonrpc.JSONRPCResponseManager.handle(request_json, API)
        rpc_response_json = json.dumps(rpc_response.data,
                                       default=util.json_dthandler).encode()

        # log the request data
        try:
            assert 'method' in request_data
            tx_logger.info(
                "TRANSACTION --- %s ||| REQUEST: %s ||| RESPONSE: %s" %
                (request_data['method'], request_json, rpc_response_json))
        except Exception as e:
            logger.info("Could not log transaction: Invalid format: %s" % e)

        response = flask.Response(rpc_response_json,
                                  200,
                                  mimetype='application/json')
        _set_cors_headers(response)
        return response
Esempio n. 3
0
def is_ready():
    """this method used by the client to check if the server is alive, caught up, and ready to accept requests.
    If the server is NOT caught up, a 525 error will be returned actually before hitting this point. Thus,
    if we actually return data from this function, it should always be true. (may change this behaviour later)"""

    ip = flask.request.headers.get('X-Real-Ip', flask.request.remote_addr)
    country = module_config['GEOIP'].country_code_by_addr(ip)
    return {
        'caught_up': blockfeed.fuzzy_is_caught_up(),
        'last_message_index': config.state['last_message_index'],
        'block_height': config.state['cp_backend_block_index'],
        'testnet': config.TESTNET,
        'ip': ip,
        'country': country,
        'quote_assets': config.QUOTE_ASSETS,
        'quick_buy_enable': True if module_config['VENDING_MACHINE_PROVIDER'] is not None else False
    }
def is_ready():
    """this method used by the client to check if the server is alive, caught up, and ready to accept requests.
    If the server is NOT caught up, a 525 error will be returned actually before hitting this point. Thus,
    if we actually return data from this function, it should always be true. (may change this behaviour later)"""

    ip = flask.request.headers.get("X-Real-Ip", flask.request.remote_addr)
    country = module_config["GEOIP"].country_code_by_addr(ip)
    return {
        "caught_up": blockfeed.fuzzy_is_caught_up(),
        "last_message_index": config.state["last_message_index"],
        "cw_last_message_seq": config.state["cw_last_message_seq"],
        "block_height": config.state["cp_backend_block_index"],
        "testnet": config.TESTNET,
        "ip": ip,
        "country": country,
        "quote_assets": config.QUOTE_ASSETS,
        "quick_buy_enable": True if module_config["VENDING_MACHINE_PROVIDER"] is not None else False,
    }
Esempio n. 5
0
    def handle_post():
        # don't do anything if we're not caught up
        if not blockfeed.fuzzy_is_caught_up():
            obj_error = jsonrpc.exceptions.JSONRPCServerError(data="Server is not caught up. Please try again later.")
            response = flask.Response(obj_error.json.encode(), 525, mimetype='application/json')
            #^ 525 is a custom response code we use for this one purpose
            _set_cors_headers(response)
            return response

        try:
            request_json = flask.request.get_data().decode('utf-8')
            request_data = json.loads(request_json)
            assert 'id' in request_data and request_data['jsonrpc'] == "2.0" and request_data['method']
            # params may be omitted
        except:
            obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest(data="Invalid JSON-RPC 2.0 request format")
            response = flask.Response(obj_error.json.encode(), 200, mimetype='application/json')
            _set_cors_headers(response)
            return response

        # only arguments passed as a dict are supported
        if request_data.get('params', None) and not isinstance(request_data['params'], dict):
            obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest(
                data='Arguments must be passed as a JSON object (list of unnamed arguments not supported)')
            response = flask.Response(obj_error.json.encode(), 200, mimetype='application/json')
            _set_cors_headers(response)
            return response
        rpc_response = jsonrpc.JSONRPCResponseManager.handle(request_json, API)
        rpc_response_json = json.dumps(rpc_response.data, default=util.json_dthandler).encode()

        # log the request data
        try:
            assert 'method' in request_data
            tx_logger.info("TRANSACTION --- %s ||| REQUEST: %s ||| RESPONSE: %s" % (request_data['method'], request_json, rpc_response_json))
        except Exception as e:
            logger.info("Could not log transaction: Invalid format: %s" % e)

        response = flask.Response(rpc_response_json, 200, mimetype='application/json')
        _set_cors_headers(response)
        return response
Esempio n. 6
0
    def handle_get():
        if flask.request.headers.get("Content-Type", None) == 'application/csp-report':
            try:
                data_json = flask.request.get_data().decode('utf-8')
                data = json.loads(data_json)
                assert 'csp-report' in data
            except Exception as e:
                obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest(data="Invalid JSON-RPC 2.0 request format")
                return flask.Response(obj_error.json.encode(), 200, mimetype='application/json')

            tx_logger.info("***CSP SECURITY --- %s" % data_json)
            return flask.Response('', 200)

        #"ping" counterpartyd to test
        cp_s = time.time()
        cp_result_valid = True
        try:
            cp_status = util.call_jsonrpc_api("get_running_info", abort_on_error=True, use_cache=False)['result']
        except:
            cp_result_valid = False
        cp_e = time.time()

        #"ping" counterblockd to test, as well
        cb_s = time.time()
        cb_result_valid = True
        cb_result_error_code = None
        payload = {
            "id": 0,
            "jsonrpc": "2.0",
            "method": "is_ready",
            "params": [],
        }
        headers = {'content-type': 'application/json', 'Connection': 'close'}
        try:
            url = "http://127.0.0.1:%s/api/" % config.RPC_PORT
            r = grequests.map((grequests.post(url, data=json.dumps(payload), headers=headers),))[0]
            if r is None:
                raise Exception("result is None")
        except Exception as e:
            cb_result_valid = False
            cb_result_error_code = "GOT EXCEPTION: %s" % e
        else:
            if r.status_code != 200:
                cb_result_valid = False
                cb_result_error_code = "GOT STATUS %s" % r.status_code if r else 'COULD NOT CONTACT'
            cb_result = r.json()
            if 'error' in cb_result:
                cb_result_valid = False
                cb_result_error_code = "GOT ERROR: %s" % cb_result['error']
        cb_e = time.time()

        result = {
            'counterparty-server': 'OK' if cp_result_valid else 'NOT OK',
            'counterparty-server_ver': '%s.%s.%s' % (
                cp_status['version_major'], cp_status['version_minor'], cp_status['version_revision']) if cp_result_valid else '?',
            'counterparty-server_last_block': cp_status['last_block'] if cp_result_valid else '?',
            'counterparty-server_last_message_index': cp_status['last_message_index'] if cp_result_valid else '?',
            'counterparty-server_caught_up': config.state['cp_caught_up'],
            'counterparty-server_check_elapsed': cp_e - cp_s,

            'counterblock': 'OK' if cb_result_valid else 'NOT OK',
            'counterblock_ver': config.VERSION,
            'counterblock_check_elapsed': cb_e - cb_s,
            'counterblock_error': cb_result_error_code,
            'counterblock_last_message_index': config.state['last_message_index'],
            'counterblock_caught_up': blockfeed.fuzzy_is_caught_up(),
            'counterblock_cur_block': {'block_hash': config.state['cur_block'].get('block_hash', '??'),
                                       'block_index': config.state['cur_block'].get('block_index', '??')},
            'counterblock_last_processed_block': {'block_hash': config.state['my_latest_block'].get('block_hash', '??'),
                                                  'block_index': config.state['my_latest_block'].get('block_index', '??')},
        }

        response_code = 200
        # error if we couldn't make a successful call to counterparty-server or counterblock's API (500)
        if not cp_result_valid or not cb_result_valid:
            response_code = 500
            result['ERROR'] = "counterparty-server_api_contact_error"
        # error 510 if the counterparty-server last block is more than 1 block behind backend
        elif not result['counterparty-server_caught_up']:
            response_code = 510
            result['ERROR'] = "counterparty-server_not_caught_up"
        # error 511 if the counterblock last block is more than 1 block behind counterparty-server
        elif not result['counterblock_caught_up']:
            response_code = 511
            result['ERROR'] = "counterblock_not_caught_up"
        else:
            result['ERROR'] = None

        response = flask.Response(json.dumps(result), response_code, mimetype='application/json')
        _set_cors_headers(response)
        return response
Esempio n. 7
0
    def handle_get():
        if flask.request.headers.get("Content-Type", None) == 'application/csp-report':
            try:
                data_json = flask.request.get_data().decode('utf-8')
                data = json.loads(data_json)
                assert 'csp-report' in data
            except Exception as e:
                obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest(data="Invalid JSON-RPC 2.0 request format")
                return flask.Response(obj_error.json.encode(), 200, mimetype='application/json')

            tx_logger.info("***CSP SECURITY --- %s" % data_json)
            return flask.Response('', 200)

        #"ping" counterpartyd to test
        cp_s = time.time()
        cp_result_valid = True
        try:
            cp_status = util.call_jsonrpc_api("get_running_info", abort_on_error=True)['result']
        except:
            cp_result_valid = False
        cp_e = time.time()

        #"ping" counterblockd to test, as well
        cb_s = time.time()
        cb_result_valid = True
        cb_result_error_code = None
        payload = {
            "id": 0,
            "jsonrpc": "2.0",
            "method": "is_ready",
            "params": [],
        }
        headers = {'content-type': 'application/json', 'Connection': 'close'}
        try:
            url = "http://127.0.0.1:%s/api/" % config.RPC_PORT
            r = grequests.map((grequests.post(url, data=json.dumps(payload), headers=headers),))[0]
            if r is None:
                raise Exception("result is None")
        except Exception as e:
            cb_result_valid = False
            cb_result_error_code = "GOT EXCEPTION: %s" % e
        else:
            if r.status_code != 200:
                cb_result_valid = False
                cb_result_error_code = "GOT STATUS %s" % r.status_code if r else 'COULD NOT CONTACT'
            cb_result = r.json()
            if 'error' in cb_result:
                cb_result_valid = False
                cb_result_error_code = "GOT ERROR: %s" % cb_result['error']
        cb_e = time.time()

        result = {
            'counterparty-server': 'OK' if cp_result_valid else 'NOT OK',
            'counterparty-server_ver': '%s.%s.%s' % (
                cp_status['version_major'], cp_status['version_minor'], cp_status['version_revision']) if cp_result_valid else '?',
            'counterparty-server_last_block': cp_status['last_block'] if cp_result_valid else '?',
            'counterparty-server_last_message_index': cp_status['last_message_index'] if cp_result_valid else '?',
            'counterparty-server_caught_up': config.state['cp_caught_up'],
            'counterparty-server_check_elapsed': cp_e - cp_s,

            'counterblock': 'OK' if cb_result_valid else 'NOT OK',
            'counterblock_ver': config.VERSION,
            'counterblock_check_elapsed': cb_e - cb_s,
            'counterblock_error': cb_result_error_code,
            'counterblock_last_message_index': config.state['last_message_index'],
            'counterblock_caught_up': blockfeed.fuzzy_is_caught_up(),
            'counterblock_cur_block': {'block_hash': config.state['cur_block'].get('block_hash', '??'),
                                       'block_index': config.state['cur_block'].get('block_index', '??')},
            'counterblock_last_processed_block': {'block_hash': config.state['my_latest_block'].get('block_hash', '??'),
                                                  'block_index': config.state['my_latest_block'].get('block_index', '??')},
        }

        response_code = 200
        # error if we couldn't make a successful call to counterparty-server or counterblock's API (500)
        if not cp_result_valid or not cb_result_valid:
            response_code = 500
            result['ERROR'] = "counterparty-server_api_contact_error"
        # error 510 if the counterparty-server last block is more than 1 block behind backend
        elif not result['counterparty-server_caught_up']:
            response_code = 510
            result['ERROR'] = "counterparty-server_not_caught_up"
        # error 511 if the counterblock last block is more than 1 block behind counterparty-server
        elif not result['counterblock_caught_up']:
            response_code = 511
            result['ERROR'] = "counterblock_not_caught_up"
        else:
            result['ERROR'] = None

        response = flask.Response(json.dumps(result), response_code, mimetype='application/json')
        _set_cors_headers(response)
        return response
Esempio n. 8
0
            'counterparty-server_caught_up':
            config.state['cp_caught_up'],
            'counterparty-server_check_elapsed':
            cp_e - cp_s,
            'counterblock':
            'OK' if cb_result_valid else 'NOT OK',
            'counterblock_ver':
            config.VERSION,
            'counterblock_check_elapsed':
            cb_e - cb_s,
            'counterblock_error':
            cb_result_error_code,
            'counterblock_last_message_index':
            config.state['last_message_index'],
            'counterblock_caught_up':
            blockfeed.fuzzy_is_caught_up(),
            'counterblock_cur_block': {
                'block_hash':
                config.state['cur_block'].get('block_hash', '??'),
                'block_index':
                config.state['cur_block'].get('block_index', '??')
            },
            'counterblock_last_processed_block': {
                'block_hash':
                config.state['my_latest_block'].get('block_hash', '??'),
                'block_index':
                config.state['my_latest_block'].get('block_index', '??')
            },
        }

        response_code = 200
Esempio n. 9
0
        
        result = {
            'counterparty-server': 'OK' if cp_result_valid else 'NOT OK',
            'counterparty-server_ver': '%s.%s.%s' % (
                cp_status['version_major'], cp_status['version_minor'], cp_status['version_revision']) if cp_result_valid else '?',
            'counterparty-server_last_block': cp_status['last_block'] if cp_result_valid else '?',
            'counterparty-server_last_message_index': cp_status['last_message_index'] if cp_result_valid else '?',
            'counterparty-server_caught_up': config.state['cp_caught_up'],
            'counterparty-server_check_elapsed': cp_e - cp_s,

            'counterblock': 'OK' if cb_result_valid else 'NOT OK',
            'counterblock_ver': config.VERSION,
            'counterblock_check_elapsed': cb_e - cb_s,
            'counterblock_error': cb_result_error_code,
            'counterblock_last_message_index': config.state['last_message_index'],
            'counterblock_caught_up': blockfeed.fuzzy_is_caught_up(),
            'counterblock_cur_block': {'block_hash': config.state['cur_block'].get('block_hash', '??'),
                                       'block_index': config.state['cur_block'].get('block_index', '??')},
            'counterblock_last_processed_block': {'block_hash': config.state['my_latest_block'].get('block_hash', '??'),
                                                  'block_index': config.state['my_latest_block'].get('block_index', '??')},
        }
        
        response_code = 200
        #error if we couldn't make a successful call to counterparty-server or counterblock's API (500)
        if not cp_result_valid or not cb_result_valid:
            response_code = 500
            result['ERROR'] = "counterparty-server_api_contact_error"
        #error 510 if the counterparty-server last block is more than 1 block behind backend
        elif not result['counterparty-server_caught_up']:
            response_code = 510
            result['ERROR'] = "counterparty-server_not_caught_up"