def do_POST(self): if not self.is_rpc_path_valid(): self.report_404() return try: max_chunk_size = 10 * 1024 * 1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L) session_id = None c = self.headers.get('cookie') if c: if c[0:8] == 'SESSION=': # print "found cookie", c[8:] session_id = c[8:] if session_id is None: session_id = self.server.create_session() # print "setting cookie", session_id response = self.server._marshaled_dispatch(session_id, data) self.send_response(200) except Exception, e: self.send_response(500) err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) response = fault.response() print "500", trace_string
def handle_one_request(self): """Handle one client request.""" request = self.rfile.readline() response = "" try: # Access to protected member; pylint: disable=W0212 response = self.server._marshaled_dispatch(request) # No exception type specified; pylint: disable=W0702 except: # The server had an unexpected exception. # dump the error to stderr print(traceback.format_exc(), file=sys.stderr) # Return the error to the caller. err_lines = traceback.format_exc().splitlines() trace_string = '{0} | {1}'.format(err_lines[-3], err_lines[-1]) fault = rpclib.Fault(-32603, 'Server error: {0}'.format(trace_string)) response = fault.response() # tell the server to exit self.server.initiate_shutdown() self.wfile.write(response) self.wfile.flush()
def do_GET(self): if not self.is_rpc_path_valid(): self.report_404() return try: session_id = None c = self.headers.get('cookie') if c: if c[0:8] == 'SESSION=': # print "found cookie", c[8:] session_id = c[8:] if session_id is None: session_id = self.server.create_session() # print "setting cookie", session_id data = json.dumps([]) response = self.server._marshaled_dispatch(session_id, data) self.send_response(200) except Exception, e: self.send_response(500) err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) response = fault.response() print "500", trace_string
def _dispatch(self, method, params): func = None try: func = self.funcs[method] except KeyError: if self.instance is not None: if hasattr(self.instance, '_dispatch'): return self.instance._dispatch(method, params) else: try: func = SimpleXMLRPCServer.resolve_dotted_attribute( self.instance, method, True) except AttributeError: pass if func is not None: try: if type(params) is types.ListType: response = func(*params) else: response = func(**params) return response except TypeError: return Fault(-32602, 'Invalid parameters: ') except: err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) return fault else: return Fault(-32601, 'Method %s not supported.' % method)
def do_POST(self): if not self.is_rpc_path_valid(): self.report_404() return try: max_chunk_size = 10*1024*1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L) global logger clientIP, port = self.client_address logger.debug('Post Request from Client %s:%s - \"POST / HTTP/1.0 200\" -' % (clientIP, port)) response = self.server._marshaled_dispatch(data) logger.debug('Client request: %s' % data) logger.debug('Server response: %s' % response) self.send_response(200) except Exception, e: self.send_response(500) err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) response = fault.response()
def do_POST(self): if not self.is_rpc_path_valid(): self.report_404() return try: max_chunk_size = 10 * 1024 * 1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size).decode() L.append(chunk) size_remaining -= len(L[-1]) data = ''.join(L) response = self.server._marshaled_dispatch(data) self.send_response(200) except Exception as ex: self.send_response(500) err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) response = fault.response() if response is None: response = '' self.send_header("Content-type", "application/json-rpc") self.send_header("Content-length", str(len(response))) self.end_headers() if isinstance(response, bytes): self.wfile.write(response) else: self.wfile.write(response.encode()) self.wfile.flush() self.connection.shutdown(1)
def _marshaled_dispatch(self, data, dispatch_method=None, path=None): #print 2222, self.dispatchers try: response = self.dispatchers[path]._marshaled_dispatch( data, dispatch_method, path) except: # report low level exception back to server # (each dispatcher should have handled their own # exceptions) exc_type, exc_value = sys.exc_info()[:2] response = jsonrpclib.dumps(jsonrpclib.Fault( 1, "%s:%s" % (exc_type, exc_value)), None, encoding=self.encoding, allow_none=self.allow_none) return response
def do_POST(self): if not self.is_rpc_path_valid(): self.report_404() return try: max_chunk_size = 10*1024*1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L) session_id = None c = self.headers.get('cookie') if c: if c[0:8] == 'SESSION=': #print "found cookie", c[8:] session_id = c[8:] if session_id is None: session_id = self.server.create_session() #print "setting cookie", session_id response = self.server._marshaled_dispatch(session_id, data) self.send_response(200) except Exception as e: self.send_response(500) err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) response = fault.response() print("500", trace_string) if response is None: response = '' if session_id: self.send_header("Set-Cookie", "SESSION=%s" % session_id) self.send_header("Content-type", "application/json-rpc") self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response) self.wfile.flush() self.shutdown_connection()
def split_coins(self, wallet_name: Optional[str] = None, password: Optional[str] = None, coin_count: Optional[int] = 25) -> str: wallet = self._get_wallet(wallet_name) confirmed_coins = wallet.get_spendable_coins(None, {'confirmed_only': True}) if len(confirmed_coins) > 3: return jsonrpclib.Fault(50, "confirmed-coins-exist", len(confirmed_coins)) all_coins = wallet.get_spendable_coins(None, {}) confirmed_coins = list(c for c in all_coins if c['height'] >= 0 and c['value'] > 10000000) to_split_coin = None if len(confirmed_coins): confirmed_coins = sorted(confirmed_coins, key=lambda v: v['value'], reverse=True) to_split_coin = confirmed_coins[0] if to_split_coin is not None and len(all_coins) < coin_count: additional_count = coin_count - len(all_coins) unused_addresses = wallet.get_unused_addresses() if len(unused_addresses) < additional_count: wallet.create_new_addresses(False, additional_count) unused_addresses = wallet.get_unused_addresses() dispersal_value = to_split_coin['value'] - 2000 outputs = [] for i in range(additional_count): outputs.append( TxOutput(dispersal_value // additional_count, unused_addresses[i].to_script())) if sum(v[2] for v in outputs) > dispersal_value - (2 * len(outputs)): tx = wallet.make_unsigned_transaction([to_split_coin], outputs, app_state.config) wallet.sign_transaction(tx, password) return { "tx_hex": str(tx), "tx_id": tx.txid(), } return None
def broadcast_transaction(self, tx_hex: Optional[str]=None, wallet_name: Optional[str]=None, wallet_memo: Optional[str]=None) -> str: wallet = None if wallet_name and wallet_memo: wallet = self._get_wallet(wallet_name) tx = Transaction(tx_hex) try: tx_id = app_state.daemon.network.broadcast_transaction_and_wait(tx) except aiorpcx.jsonrpc.RPCError as e: if e.code == 1 and e.message.find("too-long-mempool-chain") != -1: return jsonrpclib.Fault(100, "too-long-mempool-chain") print("raising rpc error", e.code, e.message) raise e if tx.is_complete() and wallet_name and wallet_memo: wallet.set_label(tx_id, wallet_memo) return tx_id
def _marshaled_dispatch(self, data, dispatch_method=None, path=None): """Dispatches an JSON-RPC method from marshalled (JSON) data. JSON-RPC methods are dispatched from the marshalled (JSON) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleJSONRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior. Returns: The JSON-RPC string to return. """ method = '' params = [] ident = '' try: request = json.loads(data) print 'request:', request jsonrpclib.ValidateRequest(request) method = request['method'] params = request['params'] ident = request['id'] # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) response = jsonrpclib.CreateResponseString(response, ident) except jsonrpclib.Fault as fault: response = jsonrpclib.CreateResponseString(fault, ident) except: # report exception back to server exc_type, exc_value, _ = sys.exc_info() response = jsonrpclib.CreateResponseString( jsonrpclib.Fault(1, '%s:%s' % (exc_type, exc_value)), ident) print 'response:', response return response
def do_POST(self): if not self.is_rpc_path_valid(): self.report_404() return try: max_chunk_size = 10 * 1024 * 1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L) response = self.server._marshaled_dispatch(data) self.send_response(200) except Exception, e: self.send_response(500) err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) response = fault.response()
def do_POST(self): if not self.is_rpc_path_valid(): self.report_404() return try: max_chunk_size = 10 * 1024 * 1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) content_read = self.rfile.read(chunk_size) if (content_read): L.append(content_read) else: logging.warn("0 bytes was read from the socket " "indicating the peer has performed a " "shutdown. Close the socket and return.") self.connection.shutdown(1) return size_remaining -= len(L[-1]) data = ''.join(L) response = self.server._marshaled_dispatch(data) self.send_response(200) except Exception: self.send_response(500) err_lines = traceback.format_exc().splitlines() trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) response = fault.response() if response is None: response = '' self.send_header("Content-type", "application/json-rpc") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response) self.wfile.flush() self.connection.shutdown(1)
def _fault(self, error): return jsonrpclib.Fault(*error)
except Fault, fault: response = jsonrpclib.dumps(fault, None, allow_none=self.allow_none, encoding=self.encoding) except: # report exception back to server exc_type, exc_value, exc_tb = sys.exc_info() if hasattr( self, '_send_traceback_header') and self._send_traceback_header: exc_value = str(exc_value) + '\n' + traceback.format_exc() print exc_value sys.stdout.flush() response = jsonrpclib.dumps( jsonrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), None, encoding=self.encoding, allow_none=self.allow_none, ) return response def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = self.funcs.keys() if self.instance is not None: # Instance can implement _listMethod to return a list of # methods