rialo-types 0.1.0

Rialo Types
Documentation
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
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! # Oracle Module
//!
//! This module contains all core oracle-related types and structures.
//!
//! ## Oracle Identification
//! - [`OracleId`] - Uniquely identifies an oracle using a nonce and creator
//!
//! ## Oracle Configuration & State
//! - [`OracleInfo`] - Complete oracle definition and configuration
//! - [`OracleEntry`] - Oracle registry entry with metadata
//!
//! ## Oracle Values
//! - [`OracleValue`] - String value (plain or encrypted)
//! - [`OracleValueBody`] - Binary value (plain or encrypted)
//!
//! ## Oracle Targets & Updates
//! - [`TargetOracle`] - Defines what the oracle should query (HTTP, Time, etc.)
//! - [`OracleUpdateResult`] - Result of an oracle update with signature
//!
//! ## Oracle Requests & Scheduling
//! - [`OracleRequest`] - Request parameters for oracle execution
//! - [`UpdateFrequency`] - How often the oracle should run
//! - [`StartingRound`] - When the oracle should start

use std::{collections::BTreeMap, convert::Infallible, fmt, ops::Deref, str::FromStr, sync::Arc};

use borsh::{BorshDeserialize, BorshSerialize};
#[cfg(feature = "non-pdk")]
use clap::Subcommand;
use rialo_cli_representable::Representable;
use rialo_limits::{max_oracle_output_serialized_bytes, MIN_VIABLE_LIMIT_OF_ORACLE_OUTPUT_SIZE};
use rialo_s_compute_budget::compute_budget_limits::{MAX_COMPUTE_UNIT_LIMIT, MAX_HEAP_FRAME_BYTES};
use rialo_s_pubkey::Pubkey;
use serde::{Deserialize, Serialize};
use serde_big_array::BigArray;
#[cfg(feature = "non-pdk")]
use url::Url;

use crate::{Headers, HttpFilter, Nonce, OracleDutyConfig, RetryConfig};

// ============================================================================
// Oracle Identification
// ============================================================================

/// Oracle identifier that uniquely identifies an oracle using a nonce and creator
#[derive(
    Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct OracleId {
    pub nonce: Nonce,
    pub creator: Pubkey,
}

impl OracleId {
    /// Create a new OracleId from a nonce and creator
    pub fn new(creator: Pubkey, nonce: impl Into<Nonce>) -> Self {
        Self {
            nonce: nonce.into(),
            creator,
        }
    }
}

impl fmt::Display for OracleId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", &self.nonce, &self.creator)
    }
}

// ============================================================================
// Oracle Configuration & State
// ============================================================================

/// Represents an oracle's definition and configuration
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Representable)]
#[representable(human_readable = "oracle_info_human_readable")]
pub struct OracleInfo {
    /// Unique identifier
    pub id: OracleId,
    /// Description for the oracle
    pub description: String,
    /// When the oracle should bring back data
    pub update_frequency: UpdateFrequency,
    /// URLs for the oracle
    pub target_oracles: Vec<TargetOracle>,
    /// Round in which the oracle will start
    pub starting_round: StartingRound,
    /// Whether oracle is active
    pub is_active: bool,
    /// When oracle was created
    pub created_at: i64,
    /// Aggregator to be run at report time
    pub aggregators: Vec<(String, Pubkey)>,
    /// Number of validators to assign per oracle request
    #[serde(default = "default_validators_per_duty")]
    pub validators_per_duty: u32,
    /// How to deal with failed oracle duties.
    pub retry_config: RetryConfig,
    /// Delay sufficient for the oracle to complete, in blocks.
    #[serde(default = "default_oracle_request_delay")]
    pub oracle_request_delay: u32,
    /// Optionally, change the compute usage limit.
    pub compute_units_limit: Option<u32>,
    /// Optionally, change the heap size limit.
    pub heap_size_limit: Option<u32>,
}

fn oracle_info_human_readable(info: &OracleInfo) -> String {
    let mut out = String::new();

    out.push_str(&format!("Oracle ID: {}\n", info.id));
    out.push_str(&format!("Description: {}\n", info.description));
    out.push_str(&format!("Active: {}\n", info.is_active));
    out.push_str(&format!("Starting Round: {:?}\n", info.starting_round));
    out.push_str(&format!("Update Frequency: {:?}\n", info.update_frequency));
    out.push_str(&format!("Created At: {}\n", info.created_at));
    out.push_str(&format!(
        "Validators Per Duty: {}\n",
        info.validators_per_duty
    ));
    out.push_str(&format!(
        "Oracle Request Delay: {}\n",
        info.oracle_request_delay
    ));

    out.push_str("\nRetry Config:\n");
    out.push_str(&format!(
        "  - Retry Delay: {}\n",
        info.retry_config.retry_delay()
    ));
    out.push_str(&format!(
        "  - Max Retries: {:?}\n",
        info.retry_config.num_retries()
    ));

    if !info.target_oracles.is_empty() {
        out.push_str(&format!(
            "\nTarget Oracles ({}):\n",
            info.target_oracles.len()
        ));
        for (i, target) in info.target_oracles.iter().enumerate() {
            out.push_str(&format!("  {}. {:?}\n", i + 1, target));
        }
    }

    if !info.aggregators.is_empty() {
        out.push_str(&format!("\nAggregators ({}):\n", info.aggregators.len()));
        for (topic, agg) in &info.aggregators {
            out.push_str(&format!("  - {} -> {}\n", topic, agg));
        }
    }

    if let Some(compute_units) = info.compute_units_limit {
        out.push_str(&format!("\nCompute Units Limit: {}\n", compute_units));
    }

    if let Some(heap_size) = info.heap_size_limit {
        out.push_str(&format!("Heap Size Limit: {}\n", heap_size));
    }

    out
}

impl Default for OracleInfo {
    fn default() -> Self {
        Self {
            id: OracleId::default(),
            description: String::new(),
            update_frequency: UpdateFrequency::default(),
            target_oracles: Vec::new(),
            starting_round: StartingRound::default(),
            is_active: false,
            created_at: 0,
            aggregators: Vec::new(),
            validators_per_duty: default_validators_per_duty(),
            retry_config: RetryConfig::default(),
            oracle_request_delay: default_oracle_request_delay(),
            compute_units_limit: None,
            heap_size_limit: None,
        }
    }
}

impl OracleInfo {
    /// Returns true if the oracle should start as soon as possible (ASAP),
    /// rather than at a specific round.
    pub fn is_asap(&self) -> bool {
        matches!(self.starting_round, StartingRound::Asap)
    }

    /// Validates all oracle configuration fields and their consistency.
    pub fn validate(&self) -> Result<(), String> {
        match self.starting_round {
            StartingRound::Asap => {
                if !matches!(self.update_frequency, UpdateFrequency::OneShot) {
                    return Err("ASAP oracles cannot be periodic".to_string());
                }
            }
            StartingRound::Round(starting_round) => {
                match self.update_frequency {
                    UpdateFrequency::OneShot => {}
                    UpdateFrequency::Periodic(period)
                    | UpdateFrequency::LimitedPeriodic(period, _) => {
                        if period == 0 {
                            return Err("update frequency cannot be zero".to_string());
                        }

                        // Additional validation for LimitedPeriodic
                        if let UpdateFrequency::LimitedPeriodic(_, end_round) =
                            self.update_frequency
                        {
                            if starting_round >= end_round {
                                return Err("end_round of a LimitedPeriodic oracle should be above starting_round".to_string());
                            }
                        }
                    }
                }
            }
        }

        // Validate `target_oracles`.
        if self.target_oracles.is_empty() {
            return Err("OracleTargets cannot be empty".to_string());
        }

        // Validate `retry_config`.
        if self.retry_config.retry_delay() == 0 {
            return Err("Retry delay cannot be zero".to_string());
        }

        // Validate `oracle_request_delay`.
        if self.oracle_request_delay < OracleDutyConfig::MIN_ORACLE_REQUEST_DELAY {
            return Err(format!(
                "oracle_request_delay cannot be below {}",
                OracleDutyConfig::MIN_ORACLE_REQUEST_DELAY
            ));
        }
        if self.oracle_request_delay > OracleDutyConfig::MAX_ORACLE_REQUEST_DELAY {
            return Err(format!(
                "oracle_request_delay cannot be above {}",
                OracleDutyConfig::MAX_ORACLE_REQUEST_DELAY
            ));
        }

        // Validate `validators_per_duty`.
        if self.validators_per_duty == 0 {
            return Err("validators_per_duty cannot be 0".to_string());
        }
        let max_oracle_output_size = max_oracle_output_serialized_bytes(self.validators_per_duty);
        if max_oracle_output_size < MIN_VIABLE_LIMIT_OF_ORACLE_OUTPUT_SIZE {
            return Err(format!("validators_per_duty is too high, results in max size of oracle updates that is too low: {max_oracle_output_size} vs {MIN_VIABLE_LIMIT_OF_ORACLE_OUTPUT_SIZE}"));
        }

        // Validate `compute_units_limit`.
        if let Some(compute_units_limit) = self.compute_units_limit {
            if compute_units_limit == 0 {
                return Err("compute_usage_limit cannot be Some(0)".to_string());
            }
            if compute_units_limit > MAX_COMPUTE_UNIT_LIMIT {
                return Err(format!("compute_usage_limit cannot be above MAX_COMPUTE_UNIT_LIMIT={MAX_COMPUTE_UNIT_LIMIT}"));
            }
        }

        // Validate `heap_size_limit`.
        if let Some(heap_size_limit) = self.heap_size_limit {
            if heap_size_limit == 0 {
                return Err("heap_size_limit cannot be Some(0)".to_string());
            }
            if heap_size_limit > MAX_HEAP_FRAME_BYTES {
                return Err(format!(
                    "heap_size_limit cannot be above MAX_HEAP_FRAME_BYTES={MAX_HEAP_FRAME_BYTES}"
                ));
            }
        }

        Ok(())
    }
}

fn default_validators_per_duty() -> u32 {
    crate::OracleDutyConfig::DEFAULT_VALIDATORS_PER_DUTY
}

fn default_oracle_request_delay() -> u32 {
    crate::OracleDutyConfig::DEFAULT_ORACLE_REQUEST_DELAY
}

/// Represents an oracle registry entry containing oracle information and metadata.
///
/// This struct stores oracle data along with a hash of the data for change detection
/// and tracking information about when the entry was last modified.
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct OracleEntry {
    oracle_info: Arc<OracleInfo>,
    data_hash: [u8; OracleEntry::HASH_LENGTH],
    last_modified_round: u64,
}

impl OracleEntry {
    const HASH_LENGTH: usize = 32;

    /// Creates a new OracleEntry instance.
    ///
    /// # Arguments
    ///
    /// * `data`: The account data as a byte vector.
    /// * `data_hash`: The hash of the account data.
    /// * `last_modified_round`: The round in which the account was last modified.
    pub fn new(
        oracle_info: OracleInfo,
        data_hash: [u8; Self::HASH_LENGTH],
        last_modified_round: u64,
    ) -> Self {
        Self {
            oracle_info: Arc::new(oracle_info),
            data_hash,
            last_modified_round,
        }
    }

    /// Retrieves the account data.
    ///
    /// # Returns
    ///
    /// The account data as an OracleInfo.
    pub fn oracle_info(&self) -> Arc<OracleInfo> {
        self.oracle_info.clone()
    }

    /// Retrieves the last modified round.
    ///
    /// # Returns
    ///
    /// The last modified round as a `u64`.
    pub fn last_modified_round(&self) -> u64 {
        self.last_modified_round
    }

    /// Retrieves the hash of the account data.
    ///
    /// # Returns
    ///
    /// The hash of the account data as a byte array.
    pub fn data_hash(&self) -> &[u8; Self::HASH_LENGTH] {
        &self.data_hash
    }
}

// ============================================================================
// Oracle Values
// ============================================================================

/// Represents a value that can be either plain text or encrypted.
///
/// This enum is used to handle oracle data that may contain sensitive information
/// that needs to be encrypted when transmitted or stored, while also supporting
/// plain text values for non-sensitive data.
///
/// # Variants
/// * `Plain(String)` - A plain text value that is not encrypted
/// * `Encrypted(String)` - A base64-encoded encrypted value that requires decryption within a TEE
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum OracleValue {
    Plain(String),
    Encrypted(String),
}

impl Default for OracleValue {
    fn default() -> Self {
        OracleValue::Plain(String::new())
    }
}

/// A wrapper type around `OracleValue` specifically for handling URLs in oracle configurations.
///
/// This type provides a convenient way to handle both plain text and encrypted URLs:
/// - Plain text URLs are stored directly as strings
/// - Encrypted URLs are stored as base64-encoded encrypted strings prefixed with "enc://"
///
/// The type implements common traits like Display and FromStr for easy conversion and
/// formatting, and integrates with the url crate when the "non-pdk" feature is enabled.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use rialo_types::OracleUrl;
///
/// // Create from plain text URL
/// let plain_url = OracleUrl::from("https://example.com");
///
/// // Create from encrypted URL
/// let encrypted_url = OracleUrl::from("enc://encrypted_data");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct OracleUrl(OracleValue);

impl fmt::Display for OracleUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            OracleValue::Plain(ref s) => write!(f, "{}", s),
            OracleValue::Encrypted(ref s) => write!(f, "enc://{}", s),
        }
    }
}

impl Deref for OracleUrl {
    type Target = OracleValue;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(feature = "non-pdk")]
impl From<Url> for OracleUrl {
    fn from(url: Url) -> Self {
        url.to_string().into()
    }
}

#[cfg(feature = "non-pdk")]
impl From<&Url> for OracleUrl {
    fn from(url: &Url) -> Self {
        Self(OracleValue::Plain(url.to_string()))
    }
}

impl From<String> for OracleUrl {
    fn from(url: String) -> Self {
        url.as_str().into()
    }
}

impl From<&str> for OracleUrl {
    fn from(s: &str) -> Self {
        if let Some(encrypted) = s.strip_prefix("enc://") {
            Self(OracleValue::Encrypted(encrypted.into()))
        } else {
            // If it isn't prefixed with `enc://`, treat it as plain text
            Self(OracleValue::Plain(s.into()))
        }
    }
}

impl FromStr for OracleUrl {
    type Err = Infallible;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(s.into())
    }
}

/// Represents a value that can be either plain data or encrypted.
///
/// This enum is used to handle oracle data that may contain sensitive information
/// that needs to be encrypted when transmitted or stored, while also supporting
/// plain text values for non-sensitive data.
///
/// # Variants
/// * `Plain(Vec<u8>)` - Data that is not encrypted
/// * `Encrypted(Vec<u8>)` - A encrypted data that requires decryption within a TEE
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub enum OracleValueBody {
    Plain(Vec<u8>),
    Encrypted(Vec<u8>),
}

impl Default for OracleValueBody {
    fn default() -> Self {
        OracleValueBody::Plain(vec![])
    }
}

impl FromStr for OracleValueBody {
    type Err = Infallible;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(OracleValueBody::Plain(s.as_bytes().to_vec()))
    }
}

// ============================================================================
// Oracle Targets
// ============================================================================

/// Enum that represents the target of the oracle request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum_macros::AsRefStr)]
#[cfg_attr(feature = "non-pdk", derive(Subcommand))]
pub enum TargetOracle {
    /// HTTP GET request to the oracle. The URL is specified in the OracleDutyRequest.
    /// The URL must be an HTTPS URL.
    /// The filter is optional, and if provided, it is used to filter the response.
    HttpGet {
        #[cfg_attr(feature = "non-pdk", clap(long = "target-url", value_parser = clap::value_parser!(OracleUrl)))]
        url: OracleUrl,
        #[cfg_attr(feature = "non-pdk", clap(long, default_value = None))]
        filter: Option<Vec<HttpFilter>>,
        #[cfg_attr(feature = "non-pdk", clap(long, default_value_t = Headers::default()))]
        headers: Headers,
    },
    /// HTTP POST request to the oracle. The URL is specified in the OracleDutyRequest.
    /// The URL must be an HTTPS URL. This oracle type is restricted to single-validator assignment
    /// to prevent duplicate operations on non-idempotent endpoints.
    HttpPost {
        #[cfg_attr(feature = "non-pdk", clap(long = "target-url", value_parser = clap::value_parser!(OracleUrl)))]
        url: OracleUrl,
        #[cfg_attr(feature = "non-pdk", clap(long))]
        filter: Option<Vec<HttpFilter>>,
        #[cfg_attr(feature = "non-pdk", clap(long, value_parser = clap::value_parser!(OracleValueBody)))]
        body: OracleValueBody,
        #[cfg_attr(feature = "non-pdk", clap(long))]
        content_type: String,
        #[cfg_attr(feature = "non-pdk", clap(long, default_value_t = Headers::default()))]
        headers: Headers,
    },
    /// Get the current time from several NIST servers.
    Time,
    /// Get the current price of several select cryptocurrencies.
    PriceReactor,
    /// Only used for testing purposes, to simulate an oracle that always returns a fixed value.
    /// TODO: remove this variant with a cfg testing flag.
    Number,
    /// Generate a shared secret key within a committee of TEEs.
    /// The manager TEE generates the key and distributes it to all committee members.
    SecretKeyGeneration {
        #[cfg_attr(feature = "non-pdk", clap(long))]
        committee_id: String,
        #[cfg_attr(feature = "non-pdk", clap(long))]
        committee_members: Vec<String>,
    },
    /// Encrypt a secret key for a target TEE using their public key.
    /// This is used to share keys with TEEs outside the original committee.
    SecretKeyEncryption {
        #[cfg_attr(feature = "non-pdk", clap(long))]
        target_tee_id: String,
        #[cfg_attr(feature = "non-pdk", clap(long))]
        secret_data: Vec<u8>,
        #[cfg_attr(feature = "non-pdk", clap(long))]
        committee_id: String,
    },
    /// Decrypt a secret key that was encrypted for this TEE.
    /// This is used by TEEs to access keys shared with them.
    SecretKeyDecryption {
        #[cfg_attr(feature = "non-pdk", clap(long))]
        encrypted_data: Vec<u8>,
        #[cfg_attr(feature = "non-pdk", clap(long))]
        source_committee_id: String,
    },
}

impl FromStr for TargetOracle {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "Time" {
            Ok(TargetOracle::Time)
        } else if s == "PriceReactor" {
            Ok(TargetOracle::PriceReactor)
        } else if s == "SecretKeyGeneration" {
            Err("SecretKeyGeneration oracle requires committee_id and committee_members parameters. Use the appropriate API to create this oracle type.".to_string())
        } else if s == "SecretKeyEncryption" {
            Err("SecretKeyEncryption oracle requires target_tee_id, secret_data, and committee_id parameters. Use the appropriate API to create this oracle type.".to_string())
        } else if s == "SecretKeyDecryption" {
            Err("SecretKeyDecryption oracle requires encrypted_data and source_committee_id parameters. Use the appropriate API to create this oracle type.".to_string())
        } else if s == "number" {
            Err("The 'number' oracle is only for testing purposes and should not be used in production.".to_string())
        } else {
            if let Some(rest) = s.strip_prefix("HttpGet:") {
                let parts: Vec<&str> = rest.splitn(2, '|').collect();
                if parts.is_empty() {
                    return Err(
                        "Invalid HttpGet format. Use 'HttpGet:<url>[|<filter>]'.".to_string()
                    );
                }

                let url = parts[0].to_string();
                let filter = if parts.len() > 1 && !parts[1].is_empty() {
                    Some(vec![HttpFilter::from_str(parts[1])?])
                } else {
                    None
                };

                // Validate URL (only when url crate is available)
                #[cfg(feature = "non-pdk")]
                if Url::parse(&url).is_err() {
                    return Err(format!("Invalid URL: {url}"));
                }

                return Ok(TargetOracle::HttpGet {
                    url: url.into(),
                    filter,
                    headers: Headers::default(),
                });
            }

            Err(format!("Unknown TargetOracle type: {s}"))
        }
    }
}

// ============================================================================
// Oracle Updates
// ============================================================================

/// A structure representing the result of an oracle update
/// This structure is designed to fit within Solana's transaction size limit
/// TODO: <https://linear.app/subzero-labs/issue/SUB-449/audit-transaction-sizes-in-the-oracle-subsystem>
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct OracleUpdateResult {
    /// The identifier of the oracle (should be kept under 100 bytes)
    pub oracle_id: OracleId,

    /// The round in which this result should be proposed
    pub proposal_round: u32,

    /// Blake3 hash of `oracle_result` (32 bytes)
    #[serde(with = "BigArray")]
    pub response_hash: [u8; 32],

    /// Signature of the hash of the oracle response, base64 encoded.
    #[serde(with = "BigArray")]
    pub signature: [u8; 64],

    /// Response data (up to MAX_ORACLE_RESPONSE_DATA_SIZE bytes in size)
    pub oracle_result: Vec<u8>,

    /// Optional attestation report, if available
    /// This can be used to provide additional context or verification of the oracle result.
    pub attestation_report: Option<crate::AttestationReport>,
}

impl OracleUpdateResult {
    /// Create an OracleUpdateResult
    pub fn new(
        oracle_id: OracleId,
        proposal_round: u32,
        oracle_result: Vec<u8>,
        signature: [u8; 64],
        attestation_report: Option<crate::AttestationReport>,
    ) -> Result<Self, &'static str> {
        let hash = blake3::hash(&oracle_result);

        // This is a temporary solution to avoid having to deal with the size of the oracle result
        #[cfg(feature = "non-pdk")]
        let oracle_result = if oracle_result.len() > rialo_limits::MAX_TRANSACTION_SIZE as usize {
            tracing::error!(
                "Oracle result size {} exceeds maximum size {}, dropping the result.",
                oracle_result.len(),
                rialo_limits::MAX_TRANSACTION_SIZE as usize
            );
            return Err("Oracle result exceeds maximum size");
        } else {
            // Use the oracle result as-is
            oracle_result
        };

        #[cfg(not(feature = "non-pdk"))]
        let oracle_result = oracle_result;

        Ok(Self {
            oracle_id,
            proposal_round,
            response_hash: *hash.as_bytes(),
            signature,
            oracle_result,
            attestation_report,
        })
    }
}

impl Default for OracleUpdateResult {
    fn default() -> Self {
        Self {
            oracle_id: OracleId::default(),
            proposal_round: 0,
            response_hash: [0; 32],
            signature: [0; 64],
            oracle_result: vec![],
            attestation_report: None,
        }
    }
}

// ============================================================================
// Oracle Requests & Scheduling
// ============================================================================

/// Represents a request to an oracle with parameters that can be used to specify the query.
/// The parameters are stored as a BTreeMap to allow for flexible key-value pairs.
/// This structure is serialized using Borsh for efficient storage and transmission.
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct OracleRequest {
    pub params: BTreeMap<String, String>,
}

/// The frequency of the oracle update.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum UpdateFrequency {
    /// The oracle will update once.
    #[default]
    OneShot,
    /// The oracle will update every N rounds.
    Periodic(u32),
    /// The oracle will update every N rounds, but only up to end_round.
    /// First parameter is the frequency, second parameter is the end round.
    LimitedPeriodic(u32, u32),
}

/// Starting round configuration for oracles
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy)]
pub enum StartingRound {
    /// Start at a specific round number
    Round(u32),
    /// Start as soon as possible
    Asap,
}

impl Default for StartingRound {
    fn default() -> Self {
        StartingRound::Round(0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn base_valid_oracle_info() -> OracleInfo {
        OracleInfo {
            description: "test".to_string(),
            target_oracles: vec![TargetOracle::Time],
            // Default is OneShot, which is allowed for both Asap and Round
            update_frequency: UpdateFrequency::OneShot,
            // Start at round 0 by default
            starting_round: StartingRound::Round(0),
            // Reasonable defaults for the rest
            retry_config: RetryConfig::default(),
            // Keep other fields as default
            ..OracleInfo::default()
        }
    }

    #[test]
    fn test_is_asap_true_and_false() {
        let mut info = base_valid_oracle_info();
        assert!(!info.is_asap());
        info.starting_round = StartingRound::Asap;
        assert!(info.is_asap());
    }

    #[test]
    fn test_validate_success_minimal() {
        let info = base_valid_oracle_info();
        assert!(info.validate().is_ok());
    }

    #[test]
    fn test_asap_cannot_be_periodic() {
        let mut info = base_valid_oracle_info();
        info.starting_round = StartingRound::Asap;
        info.update_frequency = UpdateFrequency::Periodic(10);
        let err = info.validate().unwrap_err();
        assert!(err.contains("ASAP oracles cannot be periodic"));
    }

    #[test]
    fn test_asap_cannot_be_limited_periodic() {
        let mut info = base_valid_oracle_info();
        info.starting_round = StartingRound::Asap;
        info.update_frequency = UpdateFrequency::LimitedPeriodic(5, 100);
        let err = info.validate().unwrap_err();
        assert!(err.contains("ASAP oracles cannot be periodic"));
    }

    #[test]
    fn test_periodic_with_zero_period_is_invalid() {
        let mut info = base_valid_oracle_info();
        info.starting_round = StartingRound::Round(1);
        info.update_frequency = UpdateFrequency::Periodic(0);
        let err = info.validate().unwrap_err();
        assert!(err.contains("update frequency cannot be zero"));
    }

    #[test]
    fn test_limited_periodic_with_zero_period_is_invalid() {
        let mut info = base_valid_oracle_info();
        info.starting_round = StartingRound::Round(1);
        info.update_frequency = UpdateFrequency::LimitedPeriodic(0, 100);
        let err = info.validate().unwrap_err();
        assert!(err.contains("update frequency cannot be zero"));
    }

    #[test]
    fn test_limited_periodic_end_round_must_be_above_starting_round() {
        let mut info = base_valid_oracle_info();
        info.starting_round = StartingRound::Round(5);
        info.update_frequency = UpdateFrequency::LimitedPeriodic(3, 5);
        let err = info.validate().unwrap_err();
        assert!(
            err.contains("end_round of a LimitedPeriodic oracle should be above starting_round")
        );
    }

    #[test]
    fn test_limited_periodic_end_round_below_starting_round_is_invalid() {
        let mut info = base_valid_oracle_info();
        info.starting_round = StartingRound::Round(10);
        info.update_frequency = UpdateFrequency::LimitedPeriodic(3, 9);
        let err = info.validate().unwrap_err();
        assert!(
            err.contains("end_round of a LimitedPeriodic oracle should be above starting_round")
        );
    }

    #[test]
    fn test_target_oracles_cannot_be_empty() {
        let mut info = base_valid_oracle_info();
        info.target_oracles.clear();
        let err = info.validate().unwrap_err();
        assert!(err.contains("OracleTargets cannot be empty"));
    }

    #[test]
    fn test_retry_delay_cannot_be_zero() {
        let mut info = base_valid_oracle_info();
        info.retry_config = crate::RetryConfig::new(0, 0);
        let err = info.validate().unwrap_err();
        assert!(err.contains("Retry delay cannot be zero"));
    }

    #[test]
    fn test_oracle_request_delay_bounds() {
        // Below minimum
        let mut info = base_valid_oracle_info();
        info.oracle_request_delay = crate::OracleDutyConfig::MIN_ORACLE_REQUEST_DELAY - 1;
        let err = info.validate().unwrap_err();
        assert!(err.contains(&format!(
            "oracle_request_delay cannot be below {}",
            crate::OracleDutyConfig::MIN_ORACLE_REQUEST_DELAY
        )));

        // Above maximum
        let mut info = base_valid_oracle_info();
        info.oracle_request_delay = crate::OracleDutyConfig::MAX_ORACLE_REQUEST_DELAY + 1;
        let err = info.validate().unwrap_err();
        assert!(err.contains(&format!(
            "oracle_request_delay cannot be above {}",
            crate::OracleDutyConfig::MAX_ORACLE_REQUEST_DELAY
        )));
    }

    #[test]
    fn test_validators_per_duty_cannot_be_zero() {
        let mut info = base_valid_oracle_info();
        info.validators_per_duty = 0;
        let err = info.validate().unwrap_err();
        assert!(err.contains("validators_per_duty cannot be 0"));
    }

    #[test]
    fn test_validators_per_duty_too_high_results_in_too_low_output_size() {
        let mut info = base_valid_oracle_info();
        info.validators_per_duty = 1_000_000; // ridiculously high
        let err = info.validate().unwrap_err();
        assert!(err.contains("validators_per_duty is too high"));
    }

    #[test]
    fn test_compute_units_limit_checks() {
        // Zero is invalid
        let mut info = base_valid_oracle_info();
        info.compute_units_limit = Some(0);
        let err = info.validate().unwrap_err();
        assert!(err.contains("compute_usage_limit cannot be Some(0)"));

        // Above max is invalid
        let mut info = base_valid_oracle_info();
        info.compute_units_limit =
            Some(rialo_s_compute_budget::compute_budget_limits::MAX_COMPUTE_UNIT_LIMIT + 1);
        let err = info.validate().unwrap_err();
        assert!(err.contains(&format!(
            "compute_usage_limit cannot be above MAX_COMPUTE_UNIT_LIMIT={}",
            rialo_s_compute_budget::compute_budget_limits::MAX_COMPUTE_UNIT_LIMIT
        )));
    }

    #[test]
    fn test_heap_size_limit_checks() {
        // Zero is invalid
        let mut info = base_valid_oracle_info();
        info.heap_size_limit = Some(0);
        let err = info.validate().unwrap_err();
        assert!(err.contains("heap_size_limit cannot be Some(0)"));

        // Above max is invalid
        let mut info = base_valid_oracle_info();
        info.heap_size_limit =
            Some(rialo_s_compute_budget::compute_budget_limits::MAX_HEAP_FRAME_BYTES + 1);
        let err = info.validate().unwrap_err();
        assert!(err.contains(&format!(
            "heap_size_limit cannot be above MAX_HEAP_FRAME_BYTES={}",
            rialo_s_compute_budget::compute_budget_limits::MAX_HEAP_FRAME_BYTES
        )));
    }
}