From b4e047837157f8c81def922bbde17b67a419294e Mon Sep 17 00:00:00 2001 From: Vukasin Gostovic Date: Sun, 2 Jul 2023 14:57:05 +0200 Subject: [PATCH] Add heartbeat check --- dummy_server.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ src/rpc/rpc.rs | 17 ++++++++++++++++- 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 dummy_server.py diff --git a/dummy_server.py b/dummy_server.py new file mode 100644 index 0000000..8bda9ea --- /dev/null +++ b/dummy_server.py @@ -0,0 +1,48 @@ +from http.server import BaseHTTPRequestHandler, HTTPServer +import json + + +class DummyRPCHandler(BaseHTTPRequestHandler): + def _set_response(self, status_code=200): + self.send_response(status_code) + self.send_header('Content-type', 'application/json') + self.end_headers() + + def do_POST(self): + content_length = int(self.headers['Content-Length']) + request_body = self.rfile.read(content_length) + rpc_request = json.loads(request_body) + + if rpc_request['method'] == 'eth_blockNumber': + response = { + "jsonrpc": "2.0", + "id": rpc_request['id'], + "result": "0x123456" # Dummy block number + } + else: + response = { + "jsonrpc": "2.0", + "id": rpc_request['id'], + "error": { + "code": -32601, + "message": "Method not found" + } + } + + self._set_response() + self.wfile.write(json.dumps(response).encode()) + + def do_GET(self): + self._set_response(404) + self.wfile.write(b'Not found') + + +def run_server(): + server_address = ('localhost', 8000) + httpd = HTTPServer(server_address, DummyRPCHandler) + print('Dummy RPC server is running on http://localhost:8000...') + httpd.serve_forever() + + +if __name__ == '__main__': + run_server() \ No newline at end of file diff --git a/src/rpc/rpc.rs b/src/rpc/rpc.rs index 0845f6f..483a4ea 100644 --- a/src/rpc/rpc.rs +++ b/src/rpc/rpc.rs @@ -1,5 +1,6 @@ use url::Url; use std::thread::sleep; +use std::time::Instant; use tokio::time::Duration; use serde::{Deserialize, Serialize}; @@ -233,9 +234,23 @@ impl RpcConnection { let mut new_blocknumber = blocknumber.clone(); println!("Listening for new blocks from block {}...", hex_to_decimal(&blocknumber).unwrap()); + // Start timer for the *heartbeat* + let mut start_time = Instant::now(); + while blocknumber == new_blocknumber { - // sleep for 1 second + // sleep for set duration sleep(Duration::from_millis(time)); + + // Add this as a *heartbeat* so users are less confused if nothing is happening + let elapsed_time = start_time.elapsed(); + + if elapsed_time >= Duration::from_secs(60) { + println!("!!! \x1b[93mNo new blocks have been detected in 60 seconds! Check your node(s)\x1b[0m !!!"); + println!("Still listening..."); + start_time = Instant::now(); + } + + new_blocknumber = self.block_number().await? }