forked from StellarRouter/StellarRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2242 lines (1961 loc) · 83.5 KB
/
Copy pathlib.rs
File metadata and controls
2242 lines (1961 loc) · 83.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![no_std]
//! # router-middleware
//!
//! Pre/post call hook middleware for the stellar-router suite.
//! Supports rate limiting, call logging, and per-route fee configuration.
//!
//! ## Features
//! - Per-caller rate limiting (max calls per time window)
//! - Call event logging with timestamps
//! - Configurable per-route fees
//! - Admin-controlled hook enable/disable
//!
//! ## Events (following naming convention: past tense verbs in snake_case)
//! - `pre_call` — Pre-call validation hook executed
//! - `post_call` — Post-call hook executed
//! - `circuit_opened` — Circuit breaker opened for route
//! - `middleware_enabled` — Global middleware enabled/disabled
//! - `call_log_cleared` — Call log cleared for route
//! - `admin_transferred` — Admin transferred to new address
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, Address, Env, Map, String, Symbol, Vec,
};
// ── Storage Keys ──────────────────────────────────────────────────────────────
#[contracttype]
pub enum DataKey {
Admin,
RouteCallState(String), // route_name -> RouteCallState
RouteConfig(String), // route_name -> RouteConfig
GlobalEnabled,
TotalCalls,
CallLog(String), // route_name -> CallLogState
ConfiguredRoutes, // Vec<String>
CallLogSummary(String), // route_name -> CallLogSummary
}
// ── Types ─────────────────────────────────────────────────────────────────────
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RateLimitState {
/// Number of calls in current window
pub calls_in_window: u32,
/// Timestamp when window started
pub window_start: u64,
/// Total number of times rate limit was exceeded
pub total_violations: u32,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteRateLimitStats {
/// Total number of calls across all callers in current window
pub total_calls_in_window: u32,
/// Timestamp when the current window started (earliest window start among all callers)
pub window_start: u64,
/// Total number of rate limit violations across all callers
pub total_violations: u32,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteConfig {
/// Max calls per window (0 = unlimited)
pub max_calls_per_window: u32,
/// Window size in seconds
pub window_seconds: u64,
/// Whether this route is enabled
pub enabled: bool,
/// Circuit breaker failure threshold (0 = disabled)
pub failure_threshold: u32,
/// Circuit breaker recovery window in seconds
pub recovery_window_seconds: u64,
/// Max call log entries to keep (0 = disabled)
pub log_retention: u32,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct CircuitBreakerState {
/// Number of consecutive failures
pub failure_count: u32,
/// Timestamp when circuit was opened
pub opened_at: u64,
/// Whether circuit is currently open
pub is_open: bool,
/// Whether circuit is in half-open state (probe mode)
pub is_half_open: bool,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct RouteCallState {
/// Per-caller rate limit state for the route
pub rate_limits: Map<Address, RateLimitState>,
/// Route-level circuit breaker state
pub circuit_breaker: CircuitBreakerState,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct CallLogEntry {
/// The caller address
pub caller: Address,
/// Timestamp of the call
pub timestamp: u64,
/// Whether the call succeeded
pub success: bool,
/// The route that was called
pub route: String,
}
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct CallLogState {
/// Fixed-capacity call entries retained for the route
pub entries: Vec<CallLogEntry>,
/// Index of the oldest entry in `entries` (0 when not wrapped)
pub head: u32,
}
/// Aggregated summary for a route's call log.
/// Maintained incrementally to avoid loading all entries.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct CallLogSummary {
pub total_calls: u32,
pub success_count: u32,
pub failure_count: u32,
pub last_call_timestamp: u64,
}
// ── Errors ────────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum MiddlewareError {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
RateLimitExceeded = 4,
RouteDisabled = 5,
MiddlewareDisabled = 6,
InvalidConfig = 7,
CircuitOpen = 8,
}
// ── Contract ──────────────────────────────────────────────────────────────────
#[contract]
pub struct RouterMiddleware;
#[contractimpl]
impl RouterMiddleware {
/// Initialize middleware with an admin.
///
/// Must be called exactly once. Sets the admin, enables middleware globally,
/// and resets the total call counter to zero.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `admin` - The address that will have admin privileges over this middleware.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`MiddlewareError::AlreadyInitialized`] — if the contract has already been initialized.
pub fn initialize(env: Env, admin: Address) -> Result<(), MiddlewareError> {
if env.storage().instance().has(&DataKey::Admin) {
return Err(MiddlewareError::AlreadyInitialized);
}
env.storage().instance().set(&DataKey::Admin, &admin);
env.storage().instance().set(&DataKey::GlobalEnabled, &true);
env.storage().instance().set(&DataKey::TotalCalls, &0u64);
Ok(())
}
/// Configure a route's middleware settings.
///
/// Sets the rate-limit window and call cap for `route`, and whether the
/// route is enabled. If `max_calls_per_window` is 0, rate limiting is
/// disabled for that route. Caller must be the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `route` - The route name to configure.
/// * `max_calls_per_window` - Maximum allowed calls per time window (0 = unlimited).
/// * `window_seconds` - Duration of the rate-limit window in seconds.
/// * `enabled` - Whether this route should be enabled.
/// * `failure_threshold` - Circuit breaker failure threshold (0 = disabled).
/// * `recovery_window_seconds` - Circuit breaker recovery window in seconds.
/// * `log_retention` - Maximum call log entries to keep (0 = disabled).
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`MiddlewareError::Unauthorized`] — if `caller` is not the admin.
/// * [`MiddlewareError::InvalidConfig`] — if `window_seconds` is 0 while `max_calls_per_window` > 0.
/// * [`MiddlewareError::NotInitialized`] — if the contract has not been initialized.
pub fn configure_route(
env: Env,
caller: Address,
route: String,
max_calls_per_window: u32,
window_seconds: u64,
enabled: bool,
failure_threshold: u32,
recovery_window_seconds: u64,
log_retention: u32,
) -> Result<(), MiddlewareError> {
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, MiddlewareError)?;
if window_seconds == 0 && max_calls_per_window > 0 {
return Err(MiddlewareError::InvalidConfig);
}
let config = RouteConfig {
max_calls_per_window,
window_seconds,
enabled,
failure_threshold,
recovery_window_seconds,
log_retention,
};
env.storage()
.instance()
.set(&DataKey::RouteConfig(route.clone()), &config);
let mut configured: Vec<String> = env
.storage()
.instance()
.get(&DataKey::ConfiguredRoutes)
.unwrap_or_else(|| Vec::new(&env));
if !configured.contains(&route) {
configured.push_back(route.clone());
env.storage()
.instance()
.set(&DataKey::ConfiguredRoutes, &configured);
}
Ok(())
}
/// Pre-call hook: validates rate limits and route status.
///
/// Must be called before routing to a contract. Checks that middleware is
/// globally enabled, that the specific route is enabled, and that the
/// `caller` has not exceeded their rate limit for `route`. All validation
/// is performed before any state is written — if any check fails, no state
/// is modified. On success, increments the global call counter, updates the
/// rate limit state, and emits a `pre_call` event.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address making the routed call.
/// * `route` - The name of the route being called.
///
/// # Returns
/// `Ok(())` if the call is allowed to proceed.
///
/// # Errors
/// * [`MiddlewareError::MiddlewareDisabled`] — if middleware is globally disabled.
/// * [`MiddlewareError::RouteDisabled`] — if the specific route is disabled.
/// * [`MiddlewareError::RateLimitExceeded`] — if `caller` has exceeded the rate limit for `route`.
/// * [`MiddlewareError::CircuitOpen`] — if the circuit breaker is open for the route.
pub fn pre_call(env: Env, caller: Address, route: String) -> Result<(), MiddlewareError> {
// ── Validation phase (no state writes) ───────────────────────────────
// 1. Check global enable
let enabled: bool = env
.storage()
.instance()
.get(&DataKey::GlobalEnabled)
.unwrap_or(true);
if !enabled {
return Err(MiddlewareError::MiddlewareDisabled);
}
// 2. Compute new states (if applicable) without writing yet
let new_route_call_state = if let Some(config) = env
.storage()
.instance()
.get::<DataKey, RouteConfig>(&DataKey::RouteConfig(route.clone()))
{
let mut route_call_state: RouteCallState = env
.storage()
.instance()
.get(&DataKey::RouteCallState(route.clone()))
.unwrap_or(RouteCallState {
rate_limits: Map::new(&env),
circuit_breaker: CircuitBreakerState {
failure_count: 0,
opened_at: 0,
is_open: false,
is_half_open: false,
},
});
// 2a. Route enabled check
if !config.enabled {
return Err(MiddlewareError::RouteDisabled);
}
// 2b. Circuit breaker check
let mut state_changed = false;
if config.failure_threshold > 0 {
if route_call_state.circuit_breaker.is_open {
let now = env.ledger().timestamp();
let recovers = config.recovery_window_seconds > 0
&& now
>= route_call_state.circuit_breaker.opened_at
+ config.recovery_window_seconds;
if !recovers {
return Err(MiddlewareError::CircuitOpen);
}
// Transition to half-open state for probe call
route_call_state.circuit_breaker.is_open = false;
route_call_state.circuit_breaker.is_half_open = true;
state_changed = true;
} else if route_call_state.circuit_breaker.is_half_open {
// Already in half-open state - allow this probe call
// The state will be updated in post_call based on success/failure
}
}
// 2c. Rate limit check — compute new state but do not write yet
if config.max_calls_per_window > 0 {
let now = env.ledger().timestamp();
let state: RateLimitState = route_call_state
.rate_limits
.get(caller.clone())
.unwrap_or(RateLimitState {
calls_in_window: 0,
window_start: now,
total_violations: 0,
});
let window_elapsed = now >= state.window_start + config.window_seconds;
let calls = if window_elapsed {
0
} else {
state.calls_in_window
};
let window_start = if window_elapsed {
now
} else {
state.window_start
};
if calls >= config.max_calls_per_window {
// Increment violation counter before returning error
route_call_state.rate_limits.set(
caller.clone(),
RateLimitState {
calls_in_window: calls,
window_start,
total_violations: state.total_violations + 1,
},
);
env.storage()
.instance()
.set(&DataKey::RouteCallState(route.clone()), &route_call_state);
return Err(MiddlewareError::RateLimitExceeded);
}
route_call_state.rate_limits.set(
caller.clone(),
RateLimitState {
calls_in_window: calls + 1,
window_start,
total_violations: state.total_violations,
},
);
state_changed = true;
}
if state_changed {
Some(route_call_state)
} else {
None
}
} else {
None
};
// ── Commit phase (all checks passed — write state atomically) ─────────
// Re-check global and route enabled flags immediately before committing
// to close the window between validation and write.
let still_enabled: bool = env
.storage()
.instance()
.get(&DataKey::GlobalEnabled)
.unwrap_or(true);
if !still_enabled {
return Err(MiddlewareError::MiddlewareDisabled);
}
if let Some(config) = env
.storage()
.instance()
.get::<DataKey, RouteConfig>(&DataKey::RouteConfig(route.clone()))
{
if !config.enabled {
return Err(MiddlewareError::RouteDisabled);
}
}
// Write combined route call state once (rate limit + circuit breaker)
if let Some(route_call_state) = new_route_call_state {
env.storage()
.instance()
.set(&DataKey::RouteCallState(route.clone()), &route_call_state);
}
// Increment global call counter
let total: u64 = env
.storage()
.instance()
.get(&DataKey::TotalCalls)
.unwrap_or(0);
env.storage()
.instance()
.set(&DataKey::TotalCalls, &(total + 1));
// Emit call event
env.events().publish(
(Symbol::new(&env, "pre_call"),),
(caller.clone(), route.clone()),
);
Ok(())
}
/// Post-call hook: tracks failures and manages circuit breaker.
///
/// Should be called after a routed contract call completes. Emits a
/// `post_call` event with the caller, route name, and outcome. If the call
/// failed and the route has a circuit breaker configured, increments the
/// failure count and trips the circuit if the threshold is reached.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address that made the routed call.
/// * `route` - The name of the route that was called.
/// * `success` - `true` if the call succeeded, `false` if it failed.
pub fn post_call(env: Env, caller: Address, route: String, success: bool) {
env.events().publish(
(Symbol::new(&env, "post_call"),),
(caller.clone(), route.clone(), success),
);
// Log the call if retention is enabled
if let Some(config) = env
.storage()
.instance()
.get::<DataKey, RouteConfig>(&DataKey::RouteConfig(route.clone()))
{
if config.log_retention > 0 {
let mut log: CallLogState = env
.storage()
.instance()
.get(&DataKey::CallLog(route.clone()))
.unwrap_or(CallLogState {
entries: Vec::new(&env),
head: 0,
});
let entry = CallLogEntry {
caller: caller.clone(),
timestamp: env.ledger().timestamp(),
success,
route: route.clone(),
};
let cap = config.log_retention;
if log.entries.len() < cap {
log.entries.push_back(entry);
} else if cap > 0 {
// Overwrite oldest slot and advance head (fixed-size ring buffer)
log.entries.set(log.head, entry);
log.head = (log.head + 1) % cap;
}
env.storage()
.instance()
.set(&DataKey::CallLog(route.clone()), &log);
// Update summary incrementally (avoids reloading all entries)
let mut summary: CallLogSummary = env
.storage()
.instance()
.get(&DataKey::CallLogSummary(route.clone()))
.unwrap_or(CallLogSummary {
total_calls: 0,
success_count: 0,
failure_count: 0,
last_call_timestamp: 0,
});
summary.total_calls += 1;
if success {
summary.success_count += 1;
} else {
summary.failure_count += 1;
}
summary.last_call_timestamp = env.ledger().timestamp();
env.storage()
.instance()
.set(&DataKey::CallLogSummary(route.clone()), &summary);
}
}
if !success {
if let Some(config) = env
.storage()
.instance()
.get::<DataKey, RouteConfig>(&DataKey::RouteConfig(route.clone()))
{
if config.failure_threshold > 0 {
let mut route_call_state: RouteCallState = env
.storage()
.instance()
.get(&DataKey::RouteCallState(route.clone()))
.unwrap_or(RouteCallState {
rate_limits: Map::new(&env),
circuit_breaker: CircuitBreakerState {
failure_count: 0,
opened_at: 0,
is_open: false,
is_half_open: false,
},
});
// Handle half-open state: if probe fails, reopen circuit
if route_call_state.circuit_breaker.is_half_open {
route_call_state.circuit_breaker.is_half_open = false;
route_call_state.circuit_breaker.is_open = true;
route_call_state.circuit_breaker.opened_at = env.ledger().timestamp();
route_call_state.circuit_breaker.failure_count = 1;
env.events().publish(
(Symbol::new(&env, "circuit_opened"),),
(
route.clone(),
route_call_state.circuit_breaker.failure_count,
),
);
} else {
// Normal failure handling
route_call_state.circuit_breaker.failure_count += 1;
if route_call_state.circuit_breaker.failure_count
>= config.failure_threshold
{
route_call_state.circuit_breaker.is_open = true;
route_call_state.circuit_breaker.opened_at = env.ledger().timestamp();
env.events().publish(
(Symbol::new(&env, "circuit_opened"),),
(
route.clone(),
route_call_state.circuit_breaker.failure_count,
),
);
}
}
env.storage()
.instance()
.set(&DataKey::RouteCallState(route), &route_call_state);
}
}
} else if let Some(config) = env
.storage()
.instance()
.get::<DataKey, RouteConfig>(&DataKey::RouteConfig(route.clone()))
{
if config.failure_threshold > 0 {
let mut route_call_state: RouteCallState = env
.storage()
.instance()
.get(&DataKey::RouteCallState(route.clone()))
.unwrap_or(RouteCallState {
rate_limits: Map::new(&env),
circuit_breaker: CircuitBreakerState {
failure_count: 0,
opened_at: 0,
is_open: false,
is_half_open: false,
},
});
// Handle half-open state: if probe succeeds, close circuit
if route_call_state.circuit_breaker.is_half_open {
route_call_state.circuit_breaker.is_half_open = false;
route_call_state.circuit_breaker.failure_count = 0;
} else if !route_call_state.circuit_breaker.is_open
&& route_call_state.circuit_breaker.failure_count > 0
{
route_call_state.circuit_breaker.failure_count = 0;
}
env.storage()
.instance()
.set(&DataKey::RouteCallState(route), &route_call_state);
}
}
}
/// Enable or disable all middleware globally.
///
/// When disabled, `pre_call` will return
/// [`MiddlewareError::MiddlewareDisabled`] for every route. Caller must be
/// the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `enabled` - `true` to enable middleware, `false` to disable it.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`MiddlewareError::Unauthorized`] — if `caller` is not the admin.
/// * [`MiddlewareError::NotInitialized`] — if the contract has not been initialized.
pub fn set_global_enabled(
env: Env,
caller: Address,
enabled: bool,
) -> Result<(), MiddlewareError> {
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, MiddlewareError)?;
env.storage()
.instance()
.set(&DataKey::GlobalEnabled, &enabled);
env.events()
.publish((Symbol::new(&env, "middleware_enabled"),), enabled);
Ok(())
}
/// Get total calls processed.
///
/// Returns the cumulative count of calls that have passed through
/// `pre_call` since the contract was initialized.
///
/// # Arguments
/// * `env` - The Soroban environment.
///
/// # Returns
/// The total number of pre-call invocations.
pub fn total_calls(env: Env) -> u64 {
env.storage()
.instance()
.get(&DataKey::TotalCalls)
.unwrap_or(0)
}
/// Get the call log for a route.
///
/// Returns the list of recent call log entries for `route`, up to the
/// configured retention limit. Entries are in chronological order (oldest first).
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `route` - The route name to retrieve logs for.
///
/// # Returns
/// A [`Vec<CallLogEntry>`] of call log entries.
pub fn get_call_log(env: Env, route: String) -> Vec<CallLogEntry> {
let Some(log_state) = env
.storage()
.instance()
.get::<DataKey, CallLogState>(&DataKey::CallLog(route))
else {
return Vec::new(&env);
};
if log_state.entries.is_empty() || log_state.head == 0 {
return log_state.entries;
}
let len = log_state.entries.len();
let mut ordered = Vec::new(&env);
for i in 0..len {
let idx = (log_state.head + i) % len;
if let Some(entry) = log_state.entries.get(idx) {
ordered.push_back(entry);
}
}
ordered
}
/// Get a filtered call log for a route.
///
/// Returns only successful or only failed call log entries for `route`,
/// reducing data transfer for monitoring use cases compared to `get_call_log`.
/// Entries are returned in chronological order (oldest first).
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `route` - The route name to retrieve logs for.
/// * `success_only` - If `true`, returns only successful entries; if `false`, returns only failed entries.
///
/// # Returns
/// A [`Vec<CallLogEntry>`] containing only entries matching the filter.
pub fn get_call_log_filtered(env: Env, route: String, success_only: bool) -> Vec<CallLogEntry> {
let Some(log_state) = env
.storage()
.instance()
.get::<DataKey, CallLogState>(&DataKey::CallLog(route))
else {
return Vec::new(&env);
};
if log_state.entries.is_empty() {
return Vec::new(&env);
}
let len = log_state.entries.len();
let mut ordered = Vec::new(&env);
if log_state.head == 0 {
for i in 0..len {
if let Some(entry) = log_state.entries.get(i) {
if entry.success == success_only {
ordered.push_back(entry);
}
}
}
} else {
for i in 0..len {
let idx = (log_state.head + i) % len;
if let Some(entry) = log_state.entries.get(idx) {
if entry.success == success_only {
ordered.push_back(entry);
}
}
}
}
ordered
}
/// Get the number of call log entries for a route.
///
/// More efficient than loading the full call log when callers only need
/// the current retained length.
/// Returns the number of call log entries stored for a route.
///
/// More efficient than get_call_log(route).len() as it avoids loading all entries.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `route` - The route name to get the log length for.
///
/// # Returns
/// The number of call log entries as `u32`.
pub fn get_call_log_length(env: Env, route: String) -> u32 {
env.storage()
.instance()
.get::<DataKey, CallLogState>(&DataKey::CallLog(route))
.map(|log| log.entries.len())
.unwrap_or(0)
}
/// Get an aggregated summary of call log stats for a route.
///
/// Returns total calls, success count, failure count, and last call timestamp
/// without loading all log entries. The summary is maintained incrementally
/// by `post_call` whenever log retention is enabled for the route.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `route` - The route name to summarize.
///
/// # Returns
/// `Some(CallLogSummary)` if any calls have been logged, `None` otherwise.
pub fn get_call_log_summary(env: Env, route: String) -> Option<CallLogSummary> {
env.storage()
.instance()
.get(&DataKey::CallLogSummary(route))
}
/// Clear all call log entries for a route.
///
/// Caller must be the admin. This allows manual clearing of the call log
/// for a route, for example after a security incident, to start fresh
/// without changing the retention configuration.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `route` - The route name to clear the call log for.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`MiddlewareError::Unauthorized`] — if the caller is not the admin.
pub fn reset_route_call_log(
env: Env,
caller: Address,
route: String,
) -> Result<(), MiddlewareError> {
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, MiddlewareError)?;
env.storage()
.instance()
.remove(&DataKey::CallLog(route.clone()));
env.events()
.publish((Symbol::new(&env, "call_log_cleared"),), route);
Ok(())
}
/// Get rate limit state for a caller on a specific route.
///
/// Returns the current [`RateLimitState`] for `caller` on `route`, which includes the
/// number of calls made in the current window and when the window started.
///
/// If the window has elapsed, returns a reset state with `calls_in_window = 0`
/// and updated `window_start`.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `route` - The route name to look up.
/// * `caller` - The address whose rate limit state to retrieve.
///
/// # Returns
/// `Some(`[`RateLimitState`]`)` if the caller has made at least one call on this route,
/// `None` otherwise.
pub fn rate_limit_state(env: Env, route: String, caller: Address) -> Option<RateLimitState> {
let route_call_state: RouteCallState = env
.storage()
.instance()
.get(&DataKey::RouteCallState(route.clone()))?;
let state: RateLimitState = route_call_state.rate_limits.get(caller)?;
// If route config exists, apply window expiry logic
if let Some(config) = env
.storage()
.instance()
.get::<DataKey, RouteConfig>(&DataKey::RouteConfig(route))
{
let now = env.ledger().timestamp();
let window_elapsed = now >= state.window_start + config.window_seconds;
if window_elapsed {
Some(RateLimitState {
calls_in_window: 0,
window_start: now,
total_violations: state.total_violations,
})
} else {
Some(state)
}
} else {
// No config for this route — return raw state as-is
Some(state)
}
}
/// Get rate limit statistics for a caller on a specific route.
///
/// Returns the current [`RateLimitState`] for `caller` on `route`, which includes the
/// number of calls made in the current window, the window start time, and the total
/// number of times the rate limit has been exceeded.
///
/// If the window has elapsed, returns a reset state with `calls_in_window = 0`
/// and updated `window_start`, but preserves the `total_violations` count.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `route` - The route name to look up.
/// * `caller` - The address whose rate limit stats to retrieve.
///
/// # Returns
/// `Some(`[`RateLimitState`]`)` if the caller has made at least one call on this route,
/// `None` otherwise.
pub fn get_rate_limit_stats(
env: Env,
route: String,
caller: Address,
) -> Option<RateLimitState> {
Self::rate_limit_state(env, route, caller)
}
/// Get aggregated rate limit statistics for a route across all callers.
///
/// Returns the total number of calls in the current window, the earliest window start time,
/// and the total number of rate limit violations across all callers for the given route.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `route` - The route name to look up.
///
/// # Returns
/// `Some(`[`RouteRateLimitStats`]`)` if any caller has made calls on this route,
/// `None` otherwise.
pub fn get_route_rate_limit_stats(env: Env, route: String) -> Option<RouteRateLimitStats> {
let route_call_state: RouteCallState = env
.storage()
.instance()
.get(&DataKey::RouteCallState(route.clone()))?;
if route_call_state.rate_limits.is_empty() {
return None;
}
let mut total_calls_in_window: u32 = 0;
let mut total_violations: u32 = 0;
let mut earliest_window_start: u64 = u64::MAX;
// Get route config to apply window expiry logic
let config = env
.storage()
.instance()
.get::<DataKey, RouteConfig>(&DataKey::RouteConfig(route.clone()));
let now = env.ledger().timestamp();
for (_caller, state) in route_call_state.rate_limits.iter() {
let (calls, window_start) = if let Some(ref cfg) = config {
let window_elapsed = now >= state.window_start + cfg.window_seconds;
if window_elapsed {
(0, now)
} else {
(state.calls_in_window, state.window_start)
}
} else {
(state.calls_in_window, state.window_start)
};
total_calls_in_window += calls;
total_violations += state.total_violations;
if window_start < earliest_window_start {
earliest_window_start = window_start;
}
}
// If no valid window start was found, use current time
let final_window_start = if earliest_window_start == u64::MAX {
now
} else {
earliest_window_start
};
Some(RouteRateLimitStats {
total_calls_in_window,
window_start: final_window_start,
total_violations,
})
}
/// Reset rate limit state for a caller on a specific route.
///
/// Clears the rate limit storage key for the given caller/route pair, allowing
/// the caller to make calls again without waiting for the window to expire.
/// Caller must be the admin.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `caller` - The address initiating the call; must be the admin.
/// * `route` - The route name to reset the rate limit for.
/// * `target_caller` - The address whose rate limit state should be reset.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
/// * [`MiddlewareError::Unauthorized`] — if `caller` is not the admin.
/// * [`MiddlewareError::NotInitialized`] — if the contract has not been initialized.
pub fn reset_rate_limit(
env: Env,
caller: Address,
route: String,
target_caller: Address,
) -> Result<(), MiddlewareError> {
caller.require_auth();
router_common::require_admin_simple!(&env, &caller, &DataKey::Admin, MiddlewareError)?;
let mut route_call_state: RouteCallState = env
.storage()
.instance()
.get(&DataKey::RouteCallState(route.clone()))
.unwrap_or(RouteCallState {
rate_limits: Map::new(&env),
circuit_breaker: CircuitBreakerState {
failure_count: 0,
opened_at: 0,
is_open: false,
is_half_open: false,
},
});
route_call_state.rate_limits.remove(target_caller.clone());
env.storage()