forked from StellarCheckMate/Checkmate-Escrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1921 lines (1717 loc) · 71 KB
/
Copy pathlib.rs
File metadata and controls
1921 lines (1717 loc) · 71 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]
/// Oracle Contract for Checkmate — verification and consensus for chess match results.
///
/// For a comprehensive reference of all error codes (their numeric values, causes, and recovery
/// actions), see [`Error Codes Reference`](../../docs/error-codes.md).
///
/// # Error Codes Quick Reference
///
/// Every function that returns a `Result<T, Error>` surfaces errors as numeric discriminants.
/// Common errors:
/// - `#1` — `Unauthorized` — Caller is not the configured admin or contract not initialized
/// - `#2` — `AlreadySubmitted` — Result already recorded for this match
/// - `#3` — `ResultNotFound` — No result stored for this match
/// - `#5` — `ContractPaused` — Contract paused; submissions blocked
/// - `#9` — `RateLimitExceeded` — Oracle exceeded hourly/daily submission quota
///
/// See [`docs/error-codes.md`](../../docs/error-codes.md) for all 21 error codes with causes and recovery actions.
pub mod errors;
pub mod types;
use errors::Error;
use soroban_sdk::{contract, contractimpl, symbol_short, token, Address, Env, String, Symbol, Vec};
use types::{
BatchResultEntry, CandidateTally, ConsensusState, DataKey, OracleMetrics, OracleRegistration,
OracleSubmissionEntry, OracleVoteRecord, PendingSlash, Platform, RateLimitConfig,
RateLimitStatus, RateWindow, ResultEntry, Winner,
};
/// Maximum response time SLA threshold, in milliseconds (5 seconds).
const SLA_MAX_RESPONSE_TIME_MS: u64 = 5_000;
/// Maximum number of entries accepted in a single batch submission.
/// Designed for v2.0 tournament use; future versions may raise this limit.
const MAX_BATCH_SIZE: u32 = 100;
/// ~30 days at 5s/ledger.
const MATCH_TTL_LEDGERS: u32 = 518_400;
/// Default TTL for cached oracle game results (1 hour).
const DEFAULT_CACHE_TTL_SECS: u64 = 3_600;
/// Default maximum submissions accepted from a single oracle per rolling hour.
const DEFAULT_HOURLY_LIMIT: u32 = 100;
/// Default maximum submissions accepted from a single oracle per rolling day.
const DEFAULT_DAILY_LIMIT: u32 = 1_000;
/// Length of the hourly rate-limit window, in seconds.
const HOURLY_WINDOW_SECS: u64 = 3_600;
/// Length of the daily rate-limit window, in seconds.
const DAILY_WINDOW_SECS: u64 = 86_400;
/// Emit a suspicious-pattern alert once usage reaches this percentage of a limit.
const RATE_LIMIT_ALERT_THRESHOLD_PCT: u64 = 80;
/// TTL for rate-limit window storage: ~2 days at 5s/ledger, comfortably longer
/// than the daily window so counters never expire mid-window.
const RATE_LIMIT_TTL_LEDGERS: u32 = 34_560;
/// Default m-of-n consensus threshold: a single matching submission finalizes
/// a result. This is the degenerate n=1 configuration that reproduces the
/// original single-admin-oracle deployment via `submit_oracle_result`.
const DEFAULT_CONSENSUS_THRESHOLD: u32 = 1;
/// Basis points of an oracle's remaining stake slashed automatically when it
/// is caught equivocating (submitting two conflicting results for the same
/// match_id). Equivocation is unambiguous and provable on-chain, so it is
/// slashed at the maximum: the oracle's entire remaining stake.
const EQUIVOCATION_SLASH_BPS: i128 = 10_000;
/// Basis points of an oracle's remaining stake automatically slashed when its
/// submission ends up on the losing side of a finalized consensus vote (a
/// minority result contradicted by a threshold-strong majority), or on the
/// losing side of an admin's resolution of a deadlocked (disputed) match.
/// Lower than the equivocation penalty because being outvoted can reflect an
/// honest disagreement (e.g. a stale platform API read) rather than malice.
const MINORITY_SLASH_BPS: i128 = 1_000;
/// Extend instance storage TTL on every invocation so Admin and Paused never expire.
fn extend_instance_ttl(env: &Env) {
env.storage()
.instance()
.extend_ttl(MATCH_TTL_LEDGERS / 2, MATCH_TTL_LEDGERS);
}
#[contract]
pub struct OracleContract;
#[contractimpl]
impl OracleContract {
/// Initialize with a trusted admin (the off-chain oracle service).
///
/// # Errors
/// - [`Error::AlreadyInitialized`] — contract has already been initialized.
pub fn initialize(env: Env, admin: Address) -> Result<(), Error> {
extend_instance_ttl(&env);
if env.storage().instance().has(&DataKey::Admin) {
return Err(Error::AlreadyInitialized);
}
env.storage().instance().set(&DataKey::Admin, &admin);
env.events()
.publish((Symbol::new(&env, "oracle"), symbol_short!("init")), &admin);
Ok(())
}
/// Register an oracle with a token stake that can be slashed if needed.
///
/// If `oracle_address` already has a registration, `stake_amount` is
/// added to its existing `oracle_stake` rather than overwriting it — this
/// is the top-up path an oracle uses to replenish its bond after a
/// partial slash. `token` must match the token of the existing
/// registration; topping up with a different token is rejected, since
/// stake denominated in two different tokens cannot be meaningfully
/// summed.
///
/// # Errors
/// - [`Error::InsufficientStake`] — `stake_amount` is not positive.
/// - [`Error::StakeTokenMismatch`] — `token` differs from the token
/// backing this oracle's existing registration.
pub fn register_oracle_with_stake(
env: Env,
oracle_address: Address,
stake_amount: i128,
token: Address,
) -> Result<(), Error> {
extend_instance_ttl(&env);
oracle_address.require_auth();
if stake_amount <= 0 {
return Err(Error::InsufficientStake);
}
let registration_key = DataKey::OracleRegistration(oracle_address.clone());
let existing: Option<OracleRegistration> = env.storage().instance().get(®istration_key);
if let Some(existing) = &existing {
if existing.token != token {
return Err(Error::StakeTokenMismatch);
}
}
let token_client = token::Client::new(&env, &token);
token_client.transfer(
&oracle_address,
&env.current_contract_address(),
&stake_amount,
);
let new_stake = existing
.map(|r| r.oracle_stake)
.unwrap_or(0)
.saturating_add(stake_amount);
env.storage().instance().set(
®istration_key,
&OracleRegistration {
oracle_address: oracle_address.clone(),
oracle_stake: new_stake,
token: token.clone(),
},
);
let mut oracle_set: Vec<Address> = env
.storage()
.instance()
.get(&DataKey::OracleSet)
.unwrap_or(Vec::new(&env));
if !oracle_set.contains(&oracle_address) {
oracle_set.push_back(oracle_address.clone());
env.storage()
.instance()
.set(&DataKey::OracleSet, &oracle_set);
}
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("stake")),
(oracle_address, stake_amount, token),
);
Ok(())
}
/// Set the number of ledgers a staged slash must wait before it can be
/// finalized via [`Self::finalize_slash`]. Admin-only.
///
/// Setting this to `0` restores immediate-finalization behavior (a
/// staged slash becomes eligible on the very ledger it was staged).
pub fn set_slashing_grace_period(
env: Env,
grace_period_ledgers: u32,
) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
env.storage()
.instance()
.set(&DataKey::SlashingGracePeriodLedgers, &grace_period_ledgers);
env.events().publish(
(Symbol::new(&env, "admin"), symbol_short!("slash_gp")),
(grace_period_ledgers, admin),
);
Ok(())
}
/// Get the current slashing grace period, in ledgers. Defaults to 0
/// (immediate finalization) if never configured.
pub fn get_slashing_grace_period(env: Env) -> u32 {
env.storage()
.instance()
.get(&DataKey::SlashingGracePeriodLedgers)
.unwrap_or(0)
}
/// Stage a slash of a registered oracle's stake. Admin-only.
///
/// The slash is not applied immediately — it is recorded as a
/// [`PendingSlash`] and must be finalized via [`Self::finalize_slash`]
/// after `slashing_grace_period_ledgers` ledgers have elapsed. This
/// gives governance a window to intervene with
/// [`Self::admin_cancel_slash`] if the slash was triggered by a
/// contract bug or data corruption rather than genuine oracle
/// misbehavior.
///
/// `match_id` is the match whose result triggered the slash, and is
/// used only as an identifier for the pending slash (an oracle can have
/// at most one pending slash per match).
pub fn slash_oracle(
env: Env,
oracle_address: Address,
match_id: u64,
slash_amount: i128,
) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let registration: OracleRegistration = env
.storage()
.instance()
.get(&DataKey::OracleRegistration(oracle_address.clone()))
.ok_or(Error::InsufficientStake)?;
if slash_amount <= 0 || slash_amount > registration.oracle_stake {
return Err(Error::InsufficientStake);
}
let grace_period: u32 = Self::get_slashing_grace_period(env.clone());
let staged_ledger = env.ledger().sequence();
let pending = PendingSlash {
oracle_address: oracle_address.clone(),
match_id,
slash_amount,
token: registration.token.clone(),
staged_ledger,
eligible_ledger: staged_ledger.saturating_add(grace_period),
};
env.storage().instance().set(
&DataKey::PendingSlash(oracle_address.clone(), match_id),
&pending,
);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("slashstg")),
(oracle_address, match_id, slash_amount, admin),
);
Ok(())
}
/// Finalize a previously staged slash once its grace period has
/// elapsed, transferring the slashed stake to the admin (treasury).
/// Anyone may call this (it only executes what governance already had
/// the opportunity to cancel), but it is expected to be called by the
/// off-chain oracle service once `eligible_ledger` has passed.
///
/// # Errors
/// - [`Error::SlashNotFound`] — no pending slash for this (oracle, match_id).
/// - [`Error::SlashGracePeriodNotElapsed`] — called before `eligible_ledger`.
pub fn finalize_slash(
env: Env,
oracle_address: Address,
match_id: u64,
) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
let key = DataKey::PendingSlash(oracle_address.clone(), match_id);
let pending: PendingSlash = env
.storage()
.instance()
.get(&key)
.ok_or(Error::SlashNotFound)?;
if env.ledger().sequence() < pending.eligible_ledger {
return Err(Error::SlashGracePeriodNotElapsed);
}
let mut registration: OracleRegistration = env
.storage()
.instance()
.get(&DataKey::OracleRegistration(oracle_address.clone()))
.ok_or(Error::InsufficientStake)?;
let slash_amount = pending.slash_amount.min(registration.oracle_stake);
registration.oracle_stake -= slash_amount;
env.storage().instance().set(
&DataKey::OracleRegistration(oracle_address.clone()),
®istration,
);
env.storage().instance().remove(&key);
if slash_amount > 0 {
let token_client = token::Client::new(&env, &pending.token);
token_client.transfer(&env.current_contract_address(), &admin, &slash_amount);
}
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("slash")),
(oracle_address, match_id, slash_amount),
);
Ok(())
}
/// Cancel a staged slash before it is finalized — governance
/// intervention for slashes triggered by a contract bug or data
/// corruption rather than genuine oracle misbehavior. Admin-only.
///
/// # Errors
/// - [`Error::SlashNotFound`] — no pending slash for this (oracle, match_id).
pub fn admin_cancel_slash(
env: Env,
oracle_address: Address,
match_id: u64,
) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let key = DataKey::PendingSlash(oracle_address.clone(), match_id);
if !env.storage().instance().has(&key) {
return Err(Error::SlashNotFound);
}
env.storage().instance().remove(&key);
env.events().publish(
(Symbol::new(&env, "admin"), symbol_short!("slashcxl")),
(oracle_address, match_id, admin),
);
Ok(())
}
/// Return the pending slash staged for (oracle_address, match_id), if any.
pub fn get_pending_slash(
env: Env,
oracle_address: Address,
match_id: u64,
) -> Option<PendingSlash> {
env.storage()
.instance()
.get(&DataKey::PendingSlash(oracle_address, match_id))
}
/// Admin submits a verified match result on-chain.
/// Invariant: No results can be submitted while the contract is paused.
///
/// # Errors
/// - [`Error::ContractPaused`] — contract is paused.
/// - [`Error::Unauthorized`] — contract has not been initialized or caller is not the admin.
/// - [`Error::RateLimitExceeded`] — the oracle has exceeded its hourly or daily submission limit.
/// - [`Error::AlreadySubmitted`] — a result for `match_id` has already been recorded.
/// - [`Error::InvalidGameId`] — `game_id` is empty.
pub fn submit_result(
env: Env,
match_id: u64,
game_id: String,
platform: Platform,
result: Winner,
response_time_ms: u64,
confidence: Option<u8>,
) -> Result<(), Error> {
extend_instance_ttl(&env);
// Check if contract is paused first
if env
.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
{
return Err(Error::ContractPaused);
}
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let registration: Option<OracleRegistration> = env
.storage()
.instance()
.get(&DataKey::OracleRegistration(admin.clone()));
if let Some(registration) = registration {
if registration.oracle_stake <= 0 {
return Err(Error::InsufficientStake);
}
}
Self::check_oracle_rate_limit(&env, &admin, 1)?;
Self::update_oracle_metrics(&env, &admin, response_time_ms)?;
if env.storage().persistent().has(&DataKey::Result(match_id)) {
return Err(Error::AlreadySubmitted);
}
if game_id.is_empty() {
return Err(Error::InvalidGameId);
}
env.storage().persistent().set(
&DataKey::Result(match_id),
&ResultEntry {
game_id: game_id.clone(),
platform: platform.clone(),
result: result.clone(),
submitted_ledger: env.ledger().sequence(),
submitter: admin.clone(),
confidence: confidence.clone(),
},
);
env.storage().persistent().extend_ttl(
&DataKey::Result(match_id),
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
let expiry = env.ledger().timestamp() + DEFAULT_CACHE_TTL_SECS;
let cache_key = DataKey::OracleCache(game_id.clone(), platform.clone());
env.storage()
.persistent()
.set(&cache_key, &(result.clone(), expiry));
env.storage()
.persistent()
.extend_ttl(&cache_key, MATCH_TTL_LEDGERS, MATCH_TTL_LEDGERS);
// Index this submission in the per-oracle history list (#1364).
Self::append_oracle_submission(&env, &admin, match_id, game_id, platform, result.clone());
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("result")),
(match_id, result),
);
Ok(())
}
/// Submit results for multiple matches atomically.
///
/// All entries are validated before any storage writes occur (all-or-nothing).
/// Maximum batch size is 100 entries (see [`MAX_BATCH_SIZE`]).
///
/// # Errors
/// - [`Error::ContractPaused`] — contract is paused.
/// - [`Error::Unauthorized`] — not initialized or caller is not the admin.
/// - [`Error::RateLimitExceeded`] — the oracle has exceeded its hourly or daily submission limit.
/// - [`Error::BatchTooLarge`] — `entries` exceeds 100 items.
/// - [`Error::InvalidGameId`] — any entry has an empty `game_id`.
/// - [`Error::BatchDuplicateEntry`] — two entries share the same `match_id`.
/// - [`Error::AlreadySubmitted`] — a result for any `match_id` already exists.
pub fn submit_batch_results(env: Env, entries: Vec<BatchResultEntry>) -> Result<(), Error> {
extend_instance_ttl(&env);
if env
.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
{
return Err(Error::ContractPaused);
}
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
let registration: Option<OracleRegistration> = env
.storage()
.instance()
.get(&DataKey::OracleRegistration(admin.clone()));
if let Some(registration) = registration {
if registration.oracle_stake <= 0 {
return Err(Error::InsufficientStake);
}
}
let len = entries.len();
if len > MAX_BATCH_SIZE {
return Err(Error::BatchTooLarge);
}
// Each entry in the batch counts as one submission toward the oracle's
// rate limit, checked atomically against the whole batch size.
Self::check_oracle_rate_limit(&env, &admin, len)?;
// Validate all entries before writing anything (atomic guarantee).
for i in 0..len {
let entry = entries.get(i).unwrap();
if entry.game_id.is_empty() {
return Err(Error::InvalidGameId);
}
// Intra-batch duplicate detection (O(n²) acceptable for n ≤ 100).
for j in (i + 1)..len {
if entries.get(j).unwrap().match_id == entry.match_id {
return Err(Error::BatchDuplicateEntry);
}
}
if env
.storage()
.persistent()
.has(&DataKey::Result(entry.match_id))
{
return Err(Error::AlreadySubmitted);
}
}
// All checks passed — commit atomically.
let current_ledger = env.ledger().sequence();
let expiry = env.ledger().timestamp() + DEFAULT_CACHE_TTL_SECS;
for i in 0..len {
let entry = entries.get(i).unwrap();
env.storage().persistent().set(
&DataKey::Result(entry.match_id),
&ResultEntry {
game_id: entry.game_id.clone(),
platform: entry.platform.clone(),
result: entry.result.clone(),
submitted_ledger: current_ledger,
submitter: admin.clone(),
confidence: entry.confidence.clone(),
},
);
env.storage().persistent().extend_ttl(
&DataKey::Result(entry.match_id),
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
let cache_key = DataKey::OracleCache(entry.game_id.clone(), entry.platform.clone());
env.storage()
.persistent()
.set(&cache_key, &(entry.result.clone(), expiry));
env.storage()
.persistent()
.extend_ttl(&cache_key, MATCH_TTL_LEDGERS, MATCH_TTL_LEDGERS);
// Index this submission in the per-oracle history list (#1364).
Self::append_oracle_submission(
&env,
&admin,
entry.match_id,
entry.game_id,
entry.platform,
entry.result.clone(),
);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("result")),
(entry.match_id, entry.result),
);
}
env.events()
.publish((Symbol::new(&env, "oracle"), symbol_short!("batch")), len);
Ok(())
}
/// Submit a match result as one vote in an m-of-n oracle consensus.
///
/// Unlike [`submit_result`], which is gated by admin auth alone, this is
/// the genuine multi-oracle path: any address independently registered
/// via [`register_oracle_with_stake`] with a positive stake may call this
/// directly (it authenticates itself, not the admin). A match result is
/// finalized into [`get_result`]-visible storage only once a candidate
/// (game_id, platform, result) has been submitted by at least
/// [`get_consensus_threshold`] distinct registered oracles.
///
/// With the default threshold of 1, a single registered oracle's
/// submission finalizes immediately — the degenerate n=1 configuration
/// that mirrors the original single-admin-oracle deployment.
///
/// # Disagreement handling
/// - If a submission's (game_id, platform, result) doesn't yet have
/// enough matching votes, it is recorded and the match stays pending.
/// - If a candidate reaches the threshold, it is finalized and every
/// oracle that had already voted for a *different* candidate for this
/// match is automatically slashed [`MINORITY_SLASH_BPS`] of its
/// remaining stake — majority wins, minority is slashed.
/// - If votes split enough that no remaining eligible oracle could still
/// push any candidate over the threshold (a deadlock), the match is
/// flagged disputed and awaits admin resolution via
/// [`resolve_disputed_match`].
/// - If the same oracle submits two different candidates for the same
/// match (equivocation), the vote is discarded and the oracle's entire
/// remaining stake is slashed immediately. This case returns `Ok(())`
/// rather than an error — a contract call that returns `Err` reverts
/// every storage write made during it, which would undo the slash. The
/// caller detects it via the `oracle/equivoc` event.
///
/// # Errors
/// - [`Error::ContractPaused`] — contract is paused.
/// - [`Error::Unauthorized`] — contract has not been initialized.
/// - [`Error::InvalidGameId`] — `game_id` is empty.
/// - [`Error::NotRegisteredOracle`] — `oracle` has never registered stake.
/// - [`Error::InsufficientStake`] — `oracle`'s stake has been slashed to zero.
/// - [`Error::AlreadySubmitted`] — the match is already finalized, or this
/// oracle already cast this exact vote.
/// - [`Error::RateLimitExceeded`] — `oracle` has exceeded its submission quota.
/// - [`Error::MatchDisputed`] — the match has already deadlocked and is
/// awaiting admin resolution.
pub fn submit_oracle_result(
env: Env,
oracle: Address,
match_id: u64,
game_id: String,
platform: Platform,
result: Winner,
response_time_ms: u64,
) -> Result<(), Error> {
extend_instance_ttl(&env);
if env
.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
{
return Err(Error::ContractPaused);
}
if !env.storage().instance().has(&DataKey::Admin) {
return Err(Error::Unauthorized);
}
oracle.require_auth();
if game_id.is_empty() {
return Err(Error::InvalidGameId);
}
let registration: OracleRegistration = env
.storage()
.instance()
.get(&DataKey::OracleRegistration(oracle.clone()))
.ok_or(Error::NotRegisteredOracle)?;
if registration.oracle_stake <= 0 {
return Err(Error::InsufficientStake);
}
// If the match is already finalized, check whether this oracle's vote
// conflicts with the winning result. A conflicting late vote (i.e. the
// oracle submits a different result than the one that was already
// finalized by the majority) is treated as a minority vote and slashed
// accordingly — this covers the draw-finalization case where oracles
// that voted Player1/Player2 arrive after Draw has already won.
//
// A contract call that returns `Err` reverts *all* storage writes
// (including the slash), so a conflicting late vote must return `Ok`
// for the slash to commit, just like the equivocation case.
if env.storage().persistent().has(&DataKey::Result(match_id)) {
let finalized: ResultEntry = env
.storage()
.persistent()
.get(&DataKey::Result(match_id))
.unwrap();
let conflicts = finalized.result != result
|| finalized.platform != platform
|| finalized.game_id != game_id;
if conflicts {
// Late conflicting vote — slash as minority and return Ok so
// the slash commits (same pattern as equivocation handling).
Self::slash_bps(&env, &oracle, MINORITY_SLASH_BPS);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("minority")),
(match_id, oracle),
);
return Ok(());
}
return Err(Error::AlreadySubmitted);
}
Self::check_oracle_rate_limit(&env, &oracle, 1)?;
Self::update_oracle_metrics(&env, &oracle, response_time_ms)?;
let vote_key = DataKey::OracleVote(match_id, oracle.clone());
let vote = OracleVoteRecord {
game_id: game_id.clone(),
platform: platform.clone(),
result: result.clone(),
};
if let Some(prev) = env
.storage()
.persistent()
.get::<_, OracleVoteRecord>(&vote_key)
{
if prev == vote {
return Err(Error::AlreadySubmitted);
}
// A contract call that returns `Err` reverts *all* storage writes
// made during the call, including the slash below — so proven
// equivocation must return `Ok` for the penalty to actually
// commit. Callers detect it via the `oracle/equivoc` event (and
// the resulting drop in the oracle's stake) rather than an error.
Self::slash_bps(&env, &oracle, EQUIVOCATION_SLASH_BPS);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("equivoc")),
(match_id, oracle),
);
return Ok(());
}
let mut state: ConsensusState = env
.storage()
.persistent()
.get(&DataKey::MatchVotes(match_id))
.unwrap_or(ConsensusState {
candidates: Vec::new(&env),
disputed: false,
});
if state.disputed {
return Err(Error::MatchDisputed);
}
env.storage().persistent().set(&vote_key, &vote);
env.storage()
.persistent()
.extend_ttl(&vote_key, MATCH_TTL_LEDGERS, MATCH_TTL_LEDGERS);
let threshold = Self::consensus_threshold(&env);
let mut winning_idx: Option<u32> = None;
let mut found_existing = false;
for i in 0..state.candidates.len() {
let mut candidate = state.candidates.get(i).unwrap();
if candidate.result == result
&& candidate.platform == platform
&& candidate.game_id == game_id
{
candidate.submitters.push_back(oracle.clone());
if candidate.submitters.len() >= threshold {
winning_idx = Some(i);
}
state.candidates.set(i, candidate);
found_existing = true;
break;
}
}
if !found_existing {
let mut submitters = Vec::new(&env);
submitters.push_back(oracle.clone());
let reached = submitters.len() >= threshold;
let idx = state.candidates.len();
state.candidates.push_back(CandidateTally {
game_id: game_id.clone(),
platform: platform.clone(),
result: result.clone(),
submitters,
});
if reached {
winning_idx = Some(idx);
}
}
if let Some(idx) = winning_idx {
let winning = state.candidates.get(idx).unwrap();
env.storage().persistent().set(
&DataKey::Result(match_id),
&ResultEntry {
game_id: winning.game_id.clone(),
platform: winning.platform.clone(),
result: winning.result.clone(),
submitted_ledger: env.ledger().sequence(),
submitter: oracle.clone(),
},
);
env.storage().persistent().extend_ttl(
&DataKey::Result(match_id),
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
let expiry = env.ledger().timestamp() + DEFAULT_CACHE_TTL_SECS;
let cache_key = DataKey::OracleCache(winning.game_id.clone(), winning.platform.clone());
env.storage()
.persistent()
.set(&cache_key, &(winning.result.clone(), expiry));
env.storage()
.persistent()
.extend_ttl(&cache_key, MATCH_TTL_LEDGERS, MATCH_TTL_LEDGERS);
// Index this submission in each winning oracle's per-address history (#1364).
for k in 0..winning.submitters.len() {
let winning_oracle = winning.submitters.get(k).unwrap();
Self::append_oracle_submission(
&env,
&winning_oracle,
match_id,
winning.game_id.clone(),
winning.platform.clone(),
winning.result.clone(),
);
}
// Majority wins, minority is slashed: every oracle that voted for
// a losing candidate is automatically penalized.
for i in 0..state.candidates.len() {
if i == idx {
continue;
}
let losing = state.candidates.get(i).unwrap();
for j in 0..losing.submitters.len() {
let minority_oracle = losing.submitters.get(j).unwrap();
Self::slash_bps(&env, &minority_oracle, MINORITY_SLASH_BPS);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("minority")),
(match_id, minority_oracle),
);
}
}
env.storage()
.persistent()
.remove(&DataKey::MatchVotes(match_id));
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("result")),
(match_id, winning.result),
);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("finalzd")),
(match_id, winning.submitters.len(), threshold),
);
} else {
let remaining = Self::remaining_eligible_oracles(&env, match_id);
let mut still_possible = false;
for i in 0..state.candidates.len() {
let candidate = state.candidates.get(i).unwrap();
if candidate.submitters.len().saturating_add(remaining) >= threshold {
still_possible = true;
break;
}
}
if !still_possible {
state.disputed = true;
env.storage()
.persistent()
.remove(&DataKey::OracleCache(game_id, platform));
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("disputed")),
match_id,
);
}
env.storage()
.persistent()
.set(&DataKey::MatchVotes(match_id), &state);
env.storage().persistent().extend_ttl(
&DataKey::MatchVotes(match_id),
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("vote")),
(match_id, oracle, result),
);
}
Ok(())
}
/// Admin resolves a match whose m-of-n consensus deadlocked (see
/// [`submit_oracle_result`]): no remaining eligible oracle vote could
/// still push any candidate result over the configured threshold.
///
/// Finalizes the match with the admin's chosen result and slashes every
/// oracle whose recorded vote disagreed with it — the admin acts as the
/// tie-breaker of last resort, consistent with the admin's existing
/// ultimate authority elsewhere in this contract (`slash_oracle`,
/// `update_admin`, `pause`). See docs/oracle.md for the full consensus
/// protocol and its migration path from single-oracle deployments.
///
/// # Errors
/// - [`Error::Unauthorized`] — contract has not been initialized or caller is not the admin.
/// - [`Error::AlreadySubmitted`] — the match already has a finalized result.
/// - [`Error::MatchNotDisputed`] — the match has no consensus votes recorded,
/// or its consensus has not deadlocked.
pub fn resolve_disputed_match(
env: Env,
match_id: u64,
game_id: String,
platform: Platform,
result: Winner,
) -> Result<(), Error> {
extend_instance_ttl(&env);
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(Error::Unauthorized)?;
admin.require_auth();
if env.storage().persistent().has(&DataKey::Result(match_id)) {
return Err(Error::AlreadySubmitted);
}
let state: ConsensusState = env
.storage()
.persistent()
.get(&DataKey::MatchVotes(match_id))
.ok_or(Error::MatchNotDisputed)?;
if !state.disputed {
return Err(Error::MatchNotDisputed);
}
for i in 0..state.candidates.len() {
let candidate = state.candidates.get(i).unwrap();
let agrees = candidate.result == result
&& candidate.platform == platform
&& candidate.game_id == game_id;
if !agrees {
for j in 0..candidate.submitters.len() {
let wrong_oracle = candidate.submitters.get(j).unwrap();
Self::slash_bps(&env, &wrong_oracle, MINORITY_SLASH_BPS);
env.events().publish(
(Symbol::new(&env, "oracle"), symbol_short!("minority")),
(match_id, wrong_oracle),
);
}
}
}
env.storage().persistent().set(
&DataKey::Result(match_id),
&ResultEntry {
game_id: game_id.clone(),
platform: platform.clone(),
result: result.clone(),
submitted_ledger: env.ledger().sequence(),
submitter: admin,
},
);
env.storage().persistent().extend_ttl(
&DataKey::Result(match_id),
MATCH_TTL_LEDGERS,
MATCH_TTL_LEDGERS,
);
let expiry = env.ledger().timestamp() + DEFAULT_CACHE_TTL_SECS;
let cache_key = DataKey::OracleCache(game_id, platform);
env.storage()
.persistent()
.set(&cache_key, &(result.clone(), expiry));
env.storage()
.persistent()
.extend_ttl(&cache_key, MATCH_TTL_LEDGERS, MATCH_TTL_LEDGERS);
env.storage()
.persistent()
.remove(&DataKey::MatchVotes(match_id));