Skip to content

Commit d03f701

Browse files
feat: add quorum caching to prevent DoS vulnerability
Previously, /quorums and /previous endpoints made fresh RPC calls to Dash Core on every request, creating a DoS vulnerability. This adds a QuorumCache following the same pattern as MasternodeCache: - TTL-based caching with configurable interval (default 60s) - Separate caches for current and previous quorums - Background refresh task - 30-second timeout protection on RPC calls - New QUORUM_CACHE_TTL_SECONDS env var / config option Also removes the /quorums/clear endpoint as it's no longer applicable with cache-based architecture. Co-Authored-By: Claude Opus 4.5 <[email protected]>
1 parent d40e479 commit d03f701

4 files changed

Lines changed: 286 additions & 86 deletions

File tree

‎src/api.rs‎

Lines changed: 31 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
use crate::config::Config;
2-
use crate::quorum_list::{QuorumList, QuorumListEntry};
32
use crate::masternode::EvoMasternodeList;
43
use crate::masternode_cache::MasternodeCache;
4+
use crate::quorum_cache::QuorumCache;
5+
use crate::quorum_list::QuorumListEntry;
56
use axum::{
67
extract::{Path, State},
78
http::StatusCode,
89
response::Json,
9-
routing::{get, post},
10+
routing::get,
1011
Router,
1112
};
1213
use serde::Serialize;
13-
use std::sync::{Arc, RwLock};
14+
use std::sync::Arc;
1415
use tower_http::cors::CorsLayer;
1516

16-
pub type SharedQuorumList = Arc<RwLock<QuorumList>>;
17+
pub type SharedQuorumCache = Arc<QuorumCache>;
1718
pub type SharedConfig = Arc<Config>;
1819
pub type SharedMasternodeCache = Arc<MasternodeCache>;
1920

@@ -99,17 +100,16 @@ impl From<&QuorumListEntry> for QuorumEntryResponse {
99100
}
100101

101102

102-
pub fn create_router(shared_list: SharedQuorumList, config: Config, masternode_cache: SharedMasternodeCache) -> Router {
103+
pub fn create_router(quorum_cache: SharedQuorumCache, config: Config, masternode_cache: SharedMasternodeCache) -> Router {
103104
let shared_config = Arc::new(config);
104105
Router::new()
105106
.route("/health", get(health_check))
106107
.route("/quorums", get(get_all_quorums))
107108
.route("/quorums/stats", get(get_quorum_stats))
108-
.route("/quorums/clear", post(clear_quorums))
109109
.route("/previous", get(get_previous_quorums))
110110
.route("/quorums/:hash", get(get_quorum_by_hash))
111111
.route("/masternodes", get(get_masternodes))
112-
.with_state((shared_list, shared_config, masternode_cache))
112+
.with_state((quorum_cache, shared_config, masternode_cache))
113113
.layer(CorsLayer::permissive())
114114
}
115115

@@ -118,109 +118,70 @@ async fn health_check() -> Json<ApiResponse<String>> {
118118
}
119119

120120
async fn get_all_quorums(
121-
State((shared_list, config, _)): State<(SharedQuorumList, SharedConfig, SharedMasternodeCache)>,
121+
State((quorum_cache, _, _)): State<(SharedQuorumCache, SharedConfig, SharedMasternodeCache)>,
122122
) -> Result<Json<ApiResponse<Vec<QuorumEntryResponse>>>, StatusCode> {
123-
// Fetch fresh quorums from Dash Core
124-
match crate::quorum_loader::load_initial_quorums(&config).await {
125-
Ok(new_quorums) => {
126-
// Update the shared list with fresh data
127-
match shared_list.write() {
128-
Ok(mut list) => {
129-
*list = new_quorums;
130-
}
131-
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
132-
}
133-
134-
// Now read and return the updated list
135-
match shared_list.read() {
136-
Ok(list) => {
137-
let quorums: Vec<QuorumEntryResponse> = list.iter().map(|entry| entry.into()).collect();
138-
Ok(Json(ApiResponse::success(quorums)))
139-
}
140-
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
141-
}
123+
match quorum_cache.get_quorums().await {
124+
Ok(quorums) => {
125+
let quorums: Vec<QuorumEntryResponse> = quorums.iter().map(|entry| entry.into()).collect();
126+
Ok(Json(ApiResponse::success(quorums)))
142127
}
143128
Err(e) => Ok(Json(ApiResponse::error(format!("Failed to load quorums: {}", e))))
144129
}
145130
}
146131

147132
async fn get_quorum_stats(
148-
State((shared_list, _, _)): State<(SharedQuorumList, SharedConfig, SharedMasternodeCache)>,
133+
State((quorum_cache, _, _)): State<(SharedQuorumCache, SharedConfig, SharedMasternodeCache)>,
149134
) -> Result<Json<ApiResponse<QuorumStats>>, StatusCode> {
150-
match shared_list.read() {
151-
Ok(list) => {
135+
match quorum_cache.get_quorums().await {
136+
Ok(quorums) => {
152137
let stats = QuorumStats {
153-
total_count: list.len(),
154-
is_empty: list.is_empty(),
138+
total_count: quorums.len(),
139+
is_empty: quorums.is_empty(),
155140
};
156141
Ok(Json(ApiResponse::success(stats)))
157142
}
158-
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
143+
Err(e) => Ok(Json(ApiResponse::error(format!("Failed to get quorum stats: {}", e))))
159144
}
160145
}
161146

162147
async fn get_quorum_by_hash(
163148
Path(hash): Path<String>,
164-
State((shared_list, _, _)): State<(SharedQuorumList, SharedConfig, SharedMasternodeCache)>,
149+
State((quorum_cache, _, _)): State<(SharedQuorumCache, SharedConfig, SharedMasternodeCache)>,
165150
) -> Result<Json<ApiResponse<QuorumEntryResponse>>, StatusCode> {
166151
let hash_bytes = match hex::decode(&hash) {
167152
Ok(bytes) if bytes.len() == 32 => bytes,
168153
_ => return Ok(Json(ApiResponse::error("Invalid hash format. Must be 32 bytes hex encoded.".to_string()))),
169154
};
170155

171-
match shared_list.read() {
172-
Ok(list) => {
173-
if let Some(entry) = list.get_entry(&hash_bytes) {
156+
match quorum_cache.get_quorums().await {
157+
Ok(quorums) => {
158+
if let Some(entry) = quorums.get_entry(&hash_bytes) {
174159
Ok(Json(ApiResponse::success(entry.into())))
175160
} else {
176161
Ok(Json(ApiResponse::error("Quorum not found".to_string())))
177162
}
178163
}
179-
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
180-
}
181-
}
182-
183-
184-
async fn clear_quorums(
185-
State((shared_list, _, _)): State<(SharedQuorumList, SharedConfig, SharedMasternodeCache)>,
186-
) -> Result<Json<ApiResponse<String>>, StatusCode> {
187-
match shared_list.write() {
188-
Ok(mut list) => {
189-
list.clear();
190-
Ok(Json(ApiResponse::success("All quorums cleared successfully".to_string())))
191-
}
192-
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
164+
Err(e) => Ok(Json(ApiResponse::error(format!("Failed to get quorums: {}", e))))
193165
}
194166
}
195167

196168
#[axum::debug_handler]
197169
async fn get_previous_quorums(
198-
State((_, config, _)): State<(SharedQuorumList, SharedConfig, SharedMasternodeCache)>,
170+
State((quorum_cache, _, _)): State<(SharedQuorumCache, SharedConfig, SharedMasternodeCache)>,
199171
) -> Result<Json<ApiResponse<QuorumsAtHeightResponse>>, StatusCode> {
200-
match crate::quorum_loader::get_current_block_height(&config).await {
201-
Ok(current_height) => {
202-
let previous_height = if current_height >= config.quorum.previous_blocks_offset {
203-
current_height - config.quorum.previous_blocks_offset
204-
} else {
205-
0
206-
};
207-
208-
match crate::quorum_loader::load_quorums_at_height(&config, previous_height).await {
209-
Ok(quorum_list) => {
210-
let quorums: Vec<QuorumEntryResponse> = quorum_list.iter().map(|entry| entry.into()).collect();
211-
let response = QuorumsAtHeightResponse { height: previous_height, quorums };
212-
Ok(Json(ApiResponse::success(response)))
213-
}
214-
Err(e) => Ok(Json(ApiResponse::error(format!("Failed to load quorums: {}", e))))
215-
}
172+
match quorum_cache.get_previous_quorums().await {
173+
Ok((height, quorum_list)) => {
174+
let quorums: Vec<QuorumEntryResponse> = quorum_list.iter().map(|entry| entry.into()).collect();
175+
let response = QuorumsAtHeightResponse { height, quorums };
176+
Ok(Json(ApiResponse::success(response)))
216177
}
217-
Err(e) => Ok(Json(ApiResponse::error(format!("Failed to get block height: {}", e))))
178+
Err(e) => Ok(Json(ApiResponse::error(format!("Failed to load previous quorums: {}", e))))
218179
}
219180
}
220181

221182
#[axum::debug_handler]
222183
async fn get_masternodes(
223-
State((_, config, masternode_cache)): State<(SharedQuorumList, SharedConfig, SharedMasternodeCache)>,
184+
State((_, config, masternode_cache)): State<(SharedQuorumCache, SharedConfig, SharedMasternodeCache)>,
224185
) -> Result<Json<ApiResponse<EvoMasternodeList>>, StatusCode> {
225186
match masternode_cache.get_masternodes().await {
226187
Ok(masternodes) => {

‎src/config.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,12 @@ pub struct RpcConfig {
112112
#[derive(Debug, Clone, Serialize, Deserialize)]
113113
pub struct QuorumConfig {
114114
pub previous_blocks_offset: u32,
115+
#[serde(default = "default_cache_ttl")]
116+
pub cache_ttl_seconds: u64,
117+
}
118+
119+
fn default_cache_ttl() -> u64 {
120+
60
115121
}
116122

117123
impl Default for Config {
@@ -128,6 +134,7 @@ impl Default for Config {
128134
},
129135
quorum: QuorumConfig {
130136
previous_blocks_offset: 8,
137+
cache_ttl_seconds: default_cache_ttl(),
131138
},
132139
network: Network::default(),
133140
docker: DockerConfig::default(),
@@ -181,6 +188,12 @@ impl Config {
181188
}
182189
}
183190

191+
if let Ok(ttl) = std::env::var("QUORUM_CACHE_TTL_SECONDS") {
192+
if let Ok(ttl_num) = ttl.parse::<u64>() {
193+
config.quorum.cache_ttl_seconds = ttl_num;
194+
}
195+
}
196+
184197
if let Ok(network_str) = std::env::var("DASH_NETWORK") {
185198
config.network =
186199
Network::try_from(network_str.as_str()).unwrap_or_else(|e| panic!("{}", e));

‎src/main.rs‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@ mod api;
22
mod config;
33
mod quorum_list;
44
mod quorum_loader;
5+
mod quorum_cache;
56
mod masternode;
67
mod masternode_loader;
78
mod masternode_cache;
89
mod grpc_client;
910

10-
use api::SharedQuorumList;
1111
use config::Config;
12-
use quorum_list::QuorumList;
1312
use masternode_cache::MasternodeCache;
14-
use std::sync::{Arc, RwLock};
13+
use quorum_cache::QuorumCache;
14+
use std::sync::Arc;
1515
use tokio::net::TcpListener;
1616

1717
#[tokio::main]
@@ -27,22 +27,25 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
2727
println!(" LLMQ Type: {} (ID: {})", config.get_llmq_type(), config.get_llmq_type_id());
2828
println!(" DAPI Port: {}", config.get_dapi_port());
2929
println!(" Previous blocks offset: {}", config.quorum.previous_blocks_offset);
30-
31-
// Load initial quorums from Dash Core
32-
println!("Loading initial quorums from Dash Core...");
33-
let initial_quorums = match quorum_loader::load_initial_quorums(&config).await {
30+
println!(" Quorum cache TTL: {}s", config.quorum.cache_ttl_seconds);
31+
32+
// Create quorum cache
33+
let quorum_cache = Arc::new(QuorumCache::new(config.clone()));
34+
35+
// Populate quorum cache on startup
36+
println!("Loading initial quorums...");
37+
match quorum_cache.get_quorums().await {
3438
Ok(quorums) => {
35-
println!("Successfully loaded {} quorums", quorums.len());
36-
quorums
39+
println!("Successfully loaded {} quorums into cache", quorums.len());
3740
}
3841
Err(e) => {
39-
println!("Warning: Failed to load initial quorums: {}. Starting with empty list.", e);
40-
QuorumList::new()
42+
eprintln!("Warning: Failed to load initial quorums: {}. Cache will populate on first request.", e);
4143
}
42-
};
43-
44-
let shared_quorum_list: SharedQuorumList = Arc::new(RwLock::new(initial_quorums));
45-
44+
}
45+
46+
// Start background refresh for quorum cache
47+
quorum_cache.clone().start_background_refresh().await;
48+
4649
// Create masternode cache
4750
let masternode_cache = Arc::new(MasternodeCache::new(config.clone()));
4851

@@ -61,7 +64,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
6164
masternode_cache.clone().start_background_refresh().await;
6265

6366
// Start the API server
64-
let app = api::create_router(shared_quorum_list.clone(), config.clone(), masternode_cache.clone());
67+
let app = api::create_router(quorum_cache.clone(), config.clone(), masternode_cache.clone());
6568
let listener = TcpListener::bind(format!("{}:{}", config.server.host, config.server.port)).await?;
6669

6770
println!("API Server starting on {}:{}", config.server.host, config.server.port);

0 commit comments

Comments
 (0)