Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from portlandhodl/main.rs
Created January 25, 2025 03:30
Show Gist options
  • Save RandyMcMillan/e6e60368a9ca020f81792439b2f11b42 to your computer and use it in GitHub Desktop.
Save RandyMcMillan/e6e60368a9ca020f81792439b2f11b42 to your computer and use it in GitHub Desktop.
Get Block Template Rust Example 1
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
use bitcoincore_rpc::{Auth, Client, RpcApi};
use serde_json::Value;
struct AppState {
btc_client: Client,
}
#[get("/blocktemplate")]
async fn get_block_template(data: web::Data<AppState>) -> impl Responder {
// Create template request with required segwit rules
let template_request = serde_json::json!({
"rules": ["segwit"]
});
match data.btc_client.call::<Value>("getblocktemplate", &[template_request]) {
Ok(template) => HttpResponse::Ok().json(template),
Err(e) => {
eprintln!("Error getting block template: {}", e);
HttpResponse::InternalServerError().json(format!("Error: {}", e))
}
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Bitcoin Core RPC client setup
let rpc_url = "http://127.0.0.1:8332";
let auth = Auth::UserPass("test".to_string(), "test".to_string());
let btc_client = Client::new(rpc_url, auth)
.expect("Failed to create Bitcoin Core RPC client");
// Create shared state
let app_state = web::Data::new(AppState {
btc_client,
});
println!("Starting server at http://127.0.0.1:8080");
// Start actix-web server
HttpServer::new(move || {
App::new()
.app_data(app_state.clone())
.service(get_block_template)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment