Skip to content

Commit

Permalink
Refactor RPC server initialization to accept network configuration an…
Browse files Browse the repository at this point in the history
…d improve error handling
  • Loading branch information
jamesatomc committed Nov 23, 2024
1 parent 4ce9262 commit 5fba927
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
5 changes: 3 additions & 2 deletions crates/kari/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ use key::{check_wallet_exists, list_wallet_files};
use network::{NetworkConfig, NetworkType};

use p2p_protocol::P2PNetwork;
use rpc::start_rpc_server;
use serde_json::json;
use k2::blockchain::{get_kari_dir, load_blockchain, save_blockchain, BALANCES};
use k2::chain_id::CHAIN_ID;
use crate::blockchain_simulation::run_blockchain;
use crate::rpc::start_rpc_server;


static VERSION: &str = "0.2.2";
Expand Down Expand Up @@ -207,9 +207,10 @@ async fn start_node() {
}
});


tokio::spawn(async move {
println!("Starting RPC server...");
start_rpc_server().await;
start_rpc_server(network_config).await;
});

tokio::spawn(async move {
Expand Down
30 changes: 23 additions & 7 deletions crates/kari/src/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::net::{IpAddr, Ipv4Addr, SocketAddr};

use futures::FutureExt;
use jsonrpc_core::{IoHandler, Params, Result as JsonRpcResult};
use jsonrpc_http_server::{ServerBuilder, AccessControlAllowOrigin, DomainsValidation};
use network::NetworkConfig;
use serde_json::Value as JsonValue;
use k2::blockchain::BLOCKCHAIN;
use crate::CHAIN_ID;
Expand Down Expand Up @@ -32,9 +35,10 @@ fn get_block_by_index(params: Params) -> JsonRpcResult<JsonValue> {
}
}

pub async fn start_rpc_server() {
pub async fn start_rpc_server(network_config: NetworkConfig) {
let mut io = IoHandler::new();

// Existing methods
io.add_method("get_latest_block", |params| {
futures::future::ready(get_latest_block(params)).boxed()
});
Expand All @@ -47,11 +51,23 @@ pub async fn start_rpc_server() {
futures::future::ready(get_block_by_index(params)).boxed()
});

let server = ServerBuilder::new(io)
.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Any]))
.start_http(&"127.0.0.1:3030".parse().unwrap())
.expect("Unable to start RPC server");
// Create socket address from network config
let addr = SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
network_config.port
);

println!("RPC server running on http://127.0.0.1:3030");
server.wait();
match ServerBuilder::new(io)
.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Any]))
.start_http(&addr)
{
Ok(server) => {
println!("RPC server running on http://127.0.0.1:{}", network_config.port);
server.wait();
}
Err(e) => {
eprintln!("Failed to start RPC server: {}", e);
std::process::exit(1);
}
}
}

0 comments on commit 5fba927

Please sign in to comment.