starknet_api 0.18.0-rc.0

Starknet Rust types related to computation and execution.
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
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;

use apollo_sizeof::SizeOf;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use starknet_types_core::felt::Felt;
use strum::EnumIter;

use crate::block::{BlockHash, BlockNumber, GasPrice, NonzeroGasPrice};
use crate::crypto::utils::HashChain;
use crate::execution_resources::{GasAmount, GasVector};
use crate::hash::StarkHash;
use crate::serde_utils::PrefixedBytesAsHex;
use crate::{StarknetApiError, StarknetApiResult};

pub const HIGH_GAS_AMOUNT: u64 = 10000000000; // A high gas amount that should be enough for execution.

/// A fee.
#[cfg_attr(any(test, feature = "testing"), derive(derive_more::Add, derive_more::Deref))]
#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    derive_more::Display,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
)]
#[serde(from = "PrefixedBytesAsHex<16_usize>", into = "PrefixedBytesAsHex<16_usize>")]
pub struct Fee(pub u128);

impl Fee {
    pub fn checked_add(self, rhs: Fee) -> Option<Fee> {
        self.0.checked_add(rhs.0).map(Fee)
    }

    pub const fn saturating_add(self, rhs: Self) -> Self {
        Self(self.0.saturating_add(rhs.0))
    }

    pub fn checked_div_ceil(self, rhs: NonzeroGasPrice) -> Option<GasAmount> {
        self.checked_div(rhs).map(|value| {
            if value
                .checked_mul(rhs.into())
                .expect("Multiplying by denominator of floor division cannot overflow.")
                < self
            {
                (value.0 + 1).into()
            } else {
                value
            }
        })
    }

    pub fn checked_div(self, rhs: NonzeroGasPrice) -> Option<GasAmount> {
        match u64::try_from(self.0 / rhs.get().0) {
            Ok(value) => Some(value.into()),
            Err(_) => None,
        }
    }

    pub fn saturating_div(self, rhs: NonzeroGasPrice) -> GasAmount {
        self.checked_div(rhs).unwrap_or(GasAmount::MAX)
    }
}

impl From<PrefixedBytesAsHex<16_usize>> for Fee {
    fn from(value: PrefixedBytesAsHex<16_usize>) -> Self {
        Self(u128::from_be_bytes(value.0))
    }
}

impl From<Fee> for PrefixedBytesAsHex<16_usize> {
    fn from(fee: Fee) -> Self {
        Self(fee.0.to_be_bytes())
    }
}

impl From<Fee> for Felt {
    fn from(fee: Fee) -> Self {
        Self::from(fee.0)
    }
}

/// A contract address salt.
#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    SizeOf,
)]
pub struct ContractAddressSalt(pub StarkHash);

/// A transaction signature, wrapped in `Arc` for efficient cloning and safe sharing across threads.
/// `Rc` is avoided due to its lack of thread safety, and `Mutex` is unnecessary as the signature
/// vector is immutable and never modified.
#[derive(
    Debug, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord, SizeOf,
)]
pub struct TransactionSignature(pub Arc<Vec<Felt>>);

/// The calldata of a transaction.
#[derive(
    Debug, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord, SizeOf,
)]
pub struct Calldata(pub Arc<Vec<Felt>>);

impl From<Vec<Felt>> for Calldata {
    fn from(value: Vec<Felt>) -> Self {
        Self(Arc::new(value))
    }
}

#[macro_export]
macro_rules! calldata {
    ( $( $x:expr ),* ) => {
        $crate::transaction::fields::Calldata(vec![$($x),*].into())
    };
}

/// Transaction fee tip.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Deserialize,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
    derive_more::Deref,
    derive_more::Display,
    SizeOf,
)]
#[serde(from = "PrefixedBytesAsHex<8_usize>", into = "PrefixedBytesAsHex<8_usize>")]
pub struct Tip(pub u64);

impl From<PrefixedBytesAsHex<8_usize>> for Tip {
    fn from(value: PrefixedBytesAsHex<8_usize>) -> Self {
        Self(u64::from_be_bytes(value.0))
    }
}

impl From<Tip> for PrefixedBytesAsHex<8_usize> {
    fn from(tip: Tip) -> Self {
        Self(tip.0.to_be_bytes())
    }
}

impl From<Tip> for Felt {
    fn from(tip: Tip) -> Self {
        Self::from(tip.0)
    }
}

impl From<Tip> for GasPrice {
    fn from(tip: Tip) -> Self {
        Self(tip.0.into())
    }
}

impl Tip {
    pub const ZERO: Self = Self(0);
}

/// Execution resource.
#[derive(
    Clone,
    Copy,
    Debug,
    Deserialize,
    derive_more::Display,
    EnumIter,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
)]
pub enum Resource {
    #[serde(rename = "L1_GAS")]
    L1Gas,
    #[serde(rename = "L2_GAS")]
    L2Gas,
    #[serde(rename = "L1_DATA")]
    #[serde(alias = "L1_DATA_GAS")]
    L1DataGas,
}

impl Resource {
    pub fn to_hex(&self) -> &'static str {
        match self {
            Resource::L1Gas => "0x00000000000000000000000000000000000000000000000000004c315f474153",
            Resource::L2Gas => "0x00000000000000000000000000000000000000000000000000004c325f474153",
            Resource::L1DataGas => {
                "0x000000000000000000000000000000000000000000000000004c315f44415441"
            }
        }
    }
}

/// Fee bounds for an execution resource.
/// TODO(Yael): add types ResourceAmount and ResourcePrice and use them instead of u64 and u128.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Deserialize,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
    SizeOf,
)]
// TODO(Nimrod): Consider renaming this struct.
pub struct ResourceBounds {
    // Specifies the maximum amount of each resource allowed for usage during the execution.
    #[serde(serialize_with = "gas_amount_to_hex", deserialize_with = "hex_to_gas_amount")]
    pub max_amount: GasAmount,

    // Specifies the maximum price the user is willing to pay for each resource unit.
    #[serde(serialize_with = "gas_price_to_hex", deserialize_with = "hex_to_gas_price")]
    pub max_price_per_unit: GasPrice,
}

impl std::fmt::Display for ResourceBounds {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{{ max_amount: {}, max_price_per_unit: {} }}",
            self.max_amount, self.max_price_per_unit
        )
    }
}

impl ResourceBounds {
    /// Returns true iff both the max amount and the max amount per unit is zero.
    pub fn is_zero(&self) -> bool {
        self.max_amount == GasAmount(0) && self.max_price_per_unit == GasPrice(0)
    }
}

fn gas_amount_to_hex<S>(value: &GasAmount, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(&format!("0x{:x}", value.0))
}

fn hex_to_gas_amount<'de, D>(deserializer: D) -> Result<GasAmount, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    Ok(GasAmount(
        u64::from_str_radix(s.trim_start_matches("0x"), 16).map_err(serde::de::Error::custom)?,
    ))
}

fn gas_price_to_hex<S>(value: &GasPrice, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(&format!("0x{:x}", value.0))
}

fn hex_to_gas_price<'de, D>(deserializer: D) -> Result<GasPrice, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    Ok(GasPrice(
        u128::from_str_radix(s.trim_start_matches("0x"), 16).map_err(serde::de::Error::custom)?,
    ))
}

pub fn hex_to_tip<'de, D>(deserializer: D) -> Result<Tip, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    Ok(Tip(u64::from_str_radix(s.trim_start_matches("0x"), 16).map_err(serde::de::Error::custom)?))
}

pub struct ResourceAsFelts {
    pub resource_name: Felt,
    pub max_amount: Felt,
    pub max_price_per_unit: Felt,
}

impl ResourceAsFelts {
    pub fn new(resource: Resource, resource_bounds: &ResourceBounds) -> StarknetApiResult<Self> {
        let resource_as_hex = resource.to_hex();
        Ok(Self {
            resource_name: Felt::from_hex(resource_as_hex).map_err(|_| {
                StarknetApiError::ResourceHexToFeltConversion(resource_as_hex.to_string())
            })?,
            max_amount: Felt::from(resource_bounds.max_amount),
            max_price_per_unit: Felt::from(resource_bounds.max_price_per_unit),
        })
    }

    pub fn flatten(self) -> Vec<Felt> {
        vec![self.resource_name, self.max_amount, self.max_price_per_unit]
    }
}

pub fn valid_resource_bounds_as_felts(
    resource_bounds: &ValidResourceBounds,
    exclude_l1_data_gas: bool,
) -> Result<Vec<ResourceAsFelts>, StarknetApiError> {
    let mut resource_bounds_vec: Vec<_> = vec![
        ResourceAsFelts::new(Resource::L1Gas, &resource_bounds.get_l1_bounds())?,
        ResourceAsFelts::new(Resource::L2Gas, &resource_bounds.get_l2_bounds())?,
    ];
    if exclude_l1_data_gas {
        return Ok(resource_bounds_vec);
    }
    if let ValidResourceBounds::AllResources(AllResourceBounds { l1_data_gas, .. }) =
        resource_bounds
    {
        resource_bounds_vec.push(ResourceAsFelts::new(Resource::L1DataGas, l1_data_gas)?)
    }
    Ok(resource_bounds_vec)
}

#[derive(Debug, PartialEq)]
pub enum GasVectorComputationMode {
    All,
    NoL2Gas,
}

/// A mapping from execution resources to their corresponding fee bounds..
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
// TODO(Nimrod): Remove this struct definition.
pub struct DeprecatedResourceBoundsMapping(pub BTreeMap<Resource, ResourceBounds>);

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum ValidResourceBounds {
    L1Gas(ResourceBounds), // Pre 0.13.3. Only L1 gas. L2 bounds are signed but never used.
    AllResources(AllResourceBounds),
}

impl ValidResourceBounds {
    pub fn get_l1_bounds(&self) -> ResourceBounds {
        match self {
            Self::L1Gas(l1_bounds) => *l1_bounds,
            Self::AllResources(AllResourceBounds { l1_gas, .. }) => *l1_gas,
        }
    }

    pub fn get_l2_bounds(&self) -> ResourceBounds {
        match self {
            Self::L1Gas(_) => ResourceBounds::default(),
            Self::AllResources(AllResourceBounds { l2_gas, .. }) => *l2_gas,
        }
    }

    /// Returns the maximum possible fee that can be charged for the transaction.
    /// The computation is saturating, meaning that if the result is larger than the maximum
    /// possible fee, the maximum possible fee is returned.
    pub fn max_possible_fee(&self, tip: Tip) -> Fee {
        match self {
            ValidResourceBounds::L1Gas(l1_bounds) => {
                l1_bounds.max_amount.saturating_mul(l1_bounds.max_price_per_unit)
            }
            ValidResourceBounds::AllResources(AllResourceBounds {
                l1_gas,
                l2_gas,
                l1_data_gas,
            }) => l1_gas
                .max_amount
                .saturating_mul(l1_gas.max_price_per_unit)
                .saturating_add(
                    l2_gas
                        .max_amount
                        .saturating_mul(l2_gas.max_price_per_unit.saturating_add(tip.into())),
                )
                .saturating_add(
                    l1_data_gas.max_amount.saturating_mul(l1_data_gas.max_price_per_unit),
                ),
        }
    }

    pub fn get_gas_vector_computation_mode(&self) -> GasVectorComputationMode {
        match self {
            Self::AllResources(_) => GasVectorComputationMode::All,
            Self::L1Gas(_) => GasVectorComputationMode::NoL2Gas,
        }
    }

    pub fn new_unlimited_gas_no_fee_enforcement() -> Self {
        let default_l2_gas_amount = GasAmount(HIGH_GAS_AMOUNT); // Sufficient to avoid out of gas errors.
        let default_resource =
            ResourceBounds { max_amount: GasAmount(0), max_price_per_unit: GasPrice(1) };
        Self::AllResources(AllResourceBounds {
            l1_gas: default_resource,
            l2_gas: ResourceBounds {
                max_amount: default_l2_gas_amount,
                max_price_per_unit: GasPrice(0), // Set to zero for no enforce_fee mechanism.
            },
            l1_data_gas: default_resource,
        })
    }

    #[cfg(any(feature = "testing", test))]
    pub fn create_for_testing_no_fee_enforcement() -> Self {
        Self::new_unlimited_gas_no_fee_enforcement()
    }

    #[cfg(any(feature = "testing", test))]
    pub fn create_for_testing() -> Self {
        Self::AllResources(AllResourceBounds::create_for_testing())
    }

    /// Utility method to "zip" an amount vector and a price vector to get an AllResourceBounds.
    #[cfg(any(feature = "testing", test))]
    pub fn all_bounds_from_vectors(
        gas: &crate::execution_resources::GasVector,
        prices: &crate::block::GasPriceVector,
    ) -> Self {
        let l1_gas = ResourceBounds {
            max_amount: gas.l1_gas,
            max_price_per_unit: prices.l1_gas_price.into(),
        };
        let l2_gas = ResourceBounds {
            max_amount: gas.l2_gas,
            max_price_per_unit: prices.l2_gas_price.into(),
        };
        let l1_data_gas = ResourceBounds {
            max_amount: gas.l1_data_gas,
            max_price_per_unit: prices.l1_data_gas_price.into(),
        };
        Self::AllResources(AllResourceBounds { l1_gas, l2_gas, l1_data_gas })
    }
}

impl Default for ValidResourceBounds {
    fn default() -> Self {
        Self::AllResources(AllResourceBounds::default())
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Deserialize,
    Eq,
    PartialEq,
    Hash,
    Ord,
    PartialOrd,
    Serialize,
    SizeOf,
)]
pub struct AllResourceBounds {
    pub l1_gas: ResourceBounds,
    pub l2_gas: ResourceBounds,
    pub l1_data_gas: ResourceBounds,
}

impl AllResourceBounds {
    #[cfg(any(feature = "testing", test))]
    pub fn create_for_testing() -> Self {
        let resource_bounds =
            ResourceBounds { max_amount: GasAmount(0), max_price_per_unit: GasPrice(1) };
        Self { l1_gas: resource_bounds, l2_gas: resource_bounds, l1_data_gas: resource_bounds }
    }
}

impl std::fmt::Display for AllResourceBounds {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{{ l1_gas: {}, l2_gas: {}, l1_data_gas: {} }}",
            self.l1_gas, self.l2_gas, self.l1_data_gas
        )
    }
}

impl AllResourceBounds {
    pub fn get_bound(&self, resource: Resource) -> ResourceBounds {
        match resource {
            Resource::L1Gas => self.l1_gas,
            Resource::L2Gas => self.l2_gas,
            Resource::L1DataGas => self.l1_data_gas,
        }
    }

    pub fn to_max_amounts(&self) -> GasVector {
        GasVector {
            l1_gas: self.l1_gas.max_amount,
            l1_data_gas: self.l1_data_gas.max_amount,
            l2_gas: self.l2_gas.max_amount,
        }
    }
}

/// Deserializes raw resource bounds, given as map, into valid resource bounds.
// TODO(Nimrod): Figure out how to get same result with adding #[derive(Deserialize)].
impl<'de> Deserialize<'de> for ValidResourceBounds {
    fn deserialize<D>(de: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw_resource_bounds: BTreeMap<Resource, ResourceBounds> = Deserialize::deserialize(de)?;
        ValidResourceBounds::try_from(DeprecatedResourceBoundsMapping(raw_resource_bounds))
            .map_err(serde::de::Error::custom)
    }
}

/// Serializes ValidResourceBounds as map for Backwards compatibility.
// TODO(Nimrod): Figure out how to get same result with adding #[derive(Serialize)].
impl Serialize for ValidResourceBounds {
    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let map = match self {
            ValidResourceBounds::L1Gas(l1_gas) => BTreeMap::from([
                (Resource::L1Gas, *l1_gas),
                (Resource::L2Gas, ResourceBounds::default()),
            ]),
            ValidResourceBounds::AllResources(AllResourceBounds {
                l1_gas,
                l2_gas,
                l1_data_gas,
            }) => BTreeMap::from([
                (Resource::L1Gas, *l1_gas),
                (Resource::L2Gas, *l2_gas),
                (Resource::L1DataGas, *l1_data_gas),
            ]),
        };
        DeprecatedResourceBoundsMapping(map).serialize(s)
    }
}

impl TryFrom<DeprecatedResourceBoundsMapping> for ValidResourceBounds {
    type Error = StarknetApiError;
    fn try_from(
        resource_bounds_mapping: DeprecatedResourceBoundsMapping,
    ) -> Result<Self, Self::Error> {
        if let (Some(l1_bounds), Some(l2_bounds)) = (
            resource_bounds_mapping.0.get(&Resource::L1Gas),
            resource_bounds_mapping.0.get(&Resource::L2Gas),
        ) {
            match resource_bounds_mapping.0.get(&Resource::L1DataGas) {
                Some(data_bounds) => Ok(Self::AllResources(AllResourceBounds {
                    l1_gas: *l1_bounds,
                    l1_data_gas: *data_bounds,
                    l2_gas: *l2_bounds,
                })),
                None => {
                    if l2_bounds.is_zero() {
                        Ok(Self::L1Gas(*l1_bounds))
                    } else {
                        Err(StarknetApiError::InvalidResourceMappingInitializer(format!(
                            "Missing data gas bounds but L2 gas bound is not zero: \
                             {resource_bounds_mapping:?}",
                        )))
                    }
                }
            }
        } else {
            Err(StarknetApiError::InvalidResourceMappingInitializer(format!(
                "{resource_bounds_mapping:?}",
            )))
        }
    }
}

/// Paymaster-related data.
#[derive(
    Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, SizeOf,
)]
pub struct PaymasterData(pub Vec<Felt>);

impl PaymasterData {
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// If nonempty, will contain the required data for deploying and initializing an account contract:
/// its class hash, address salt and constructor calldata.
#[derive(
    Debug, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord, SizeOf,
)]
pub struct AccountDeploymentData(pub Vec<Felt>);

impl AccountDeploymentData {
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

// Represent the string `VIRTUAL_SNOS` as a Felt.
pub const VIRTUAL_SNOS: Felt = Felt::from_hex_unchecked("0x5649525455414c5f534e4f53");

// Represent the `PROOF_VERSION` marker as a Felt ('PROOF0').
pub const PROOF_VERSION: Felt = Felt::from_hex_unchecked("0x50524f4f4630");

/// The version of the virtual OS output (short string 'VIRTUAL_SNOS0').
/// This must match the Cairo constant `VIRTUAL_OS_OUTPUT_VERSION` in `virtual_os_output.cairo`.
pub const VIRTUAL_OS_OUTPUT_VERSION: Felt =
    Felt::from_hex_unchecked("0x5649525455414c5f534e4f5330");

/// Client-provided proof facts used for client-side proving.
/// Only needed when the client supplies a proof; otherwise empty.
#[derive(
    Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, SizeOf,
)]
pub struct ProofFacts(pub Arc<Vec<Felt>>);

impl ProofFacts {
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn hash(&self) -> Felt {
        HashChain::new().chain_iter(self.0.iter()).get_poseidon_hash()
    }
}

/// Represents the variants of proof facts associated with a transaction.
///
/// Currently, only SNOS proof facts are supported.
/// The `Empty` variant indicates that the transaction does not utilize the client-side proving
/// feature.
pub enum ProofFactsVariant {
    Empty,
    Snos(SnosProofFacts),
}

impl TryFrom<&ProofFacts> for ProofFactsVariant {
    type Error = StarknetApiError;
    fn try_from(proof_facts: &ProofFacts) -> Result<Self, Self::Error> {
        if proof_facts.0.is_empty() {
            return Ok(ProofFactsVariant::Empty);
        }

        let Some(([proof_version, variant_marker], snos_fields)) =
            proof_facts.0.split_at_checked(2)
        else {
            return Err(StarknetApiError::InvalidProofFacts(format!(
                "Proof facts must have at least 2 fields, got {}",
                proof_facts.0.len()
            )));
        };

        // Validate that the first element is PROOF_VERSION.
        if *proof_version != PROOF_VERSION {
            return Err(StarknetApiError::InvalidProofFacts(format!(
                "Expected first field to be {} (PROOF_VERSION), but got {}",
                PROOF_VERSION, proof_version
            )));
        }

        // Validate that the second element is VIRTUAL_SNOS.
        if *variant_marker != VIRTUAL_SNOS {
            return Err(StarknetApiError::InvalidProofFacts(format!(
                "Non-SNOS proofs are not currently supported. Expected second field to be {} \
                 (VIRTUAL_SNOS), but got {}",
                VIRTUAL_SNOS, variant_marker
            )));
        }

        let [program_hash, output_version, block_number_felt, block_hash, config_hash, ..] =
            snos_fields
        else {
            return Err(StarknetApiError::InvalidProofFacts(format!(
                "SNOS proof facts is too small with {} fields",
                proof_facts.0.len()
            )));
        };

        // TODO(Yoni): reuse VirtualOsOutput parsing.
        let expected_version = VIRTUAL_OS_OUTPUT_VERSION;
        if *output_version != expected_version {
            return Err(StarknetApiError::InvalidProofFacts(format!(
                "Expected SNOS proof facts version to be {} (VIRTUAL_OS_OUTPUT_VERSION), but got \
                 {}",
                expected_version, output_version
            )));
        }

        let block_number = BlockNumber((*block_number_felt).try_into().map_err(|_| {
            StarknetApiError::InvalidProofFacts(format!(
                "Block number field is not a valid u64: {}",
                block_number_felt
            ))
        })?);

        Ok(ProofFactsVariant::Snos(SnosProofFacts {
            proof_version: *proof_version,
            program_hash: *program_hash,
            block_number,
            block_hash: BlockHash(*block_hash),
            config_hash: *config_hash,
        }))
    }
}

/// Contains the required fields for valid SNOS proof facts.
///
/// A valid SNOS proof facts structure must include these fields as its first five entries.
pub struct SnosProofFacts {
    pub proof_version: Felt,
    pub program_hash: StarkHash,
    pub block_number: BlockNumber,
    pub block_hash: BlockHash,
    pub config_hash: StarkHash,
}

impl From<Vec<Felt>> for ProofFacts {
    fn from(value: Vec<Felt>) -> Self {
        Self(Arc::new(value))
    }
}

impl TryFrom<ProofFacts> for SnosProofFacts {
    type Error = StarknetApiError;
    fn try_from(proof_facts: ProofFacts) -> Result<Self, Self::Error> {
        match ProofFactsVariant::try_from(&proof_facts) {
            Ok(ProofFactsVariant::Snos(snos_proof_facts)) => Ok(snos_proof_facts),
            _ => Err(StarknetApiError::InvalidProofFacts(format!(
                "Invalid SNOS proof facts: {proof_facts:?}",
            ))),
        }
    }
}

/// Client-provided proof used for client-side proving.
/// Serialized as a base64 string of big-endian u32 bytes.
#[derive(
    Clone,
    Default,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    SizeOf,
    derive_more::Deref,
    derive_more::From,
)]
pub struct Proof(pub Arc<Vec<u8>>);

impl fmt::Debug for Proof {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let len = self.0.len();

        if len == 0 { write!(f, "Proof([])") } else { write!(f, "Proof(<{} elements>)", len) }
    }
}

impl Serialize for Proof {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&base64::encode(&*self.0))
    }
}

impl<'de> Deserialize<'de> for Proof {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        if s.is_empty() {
            return Ok(Self::default());
        }
        let bytes = base64::decode(&s).map_err(serde::de::Error::custom)?;
        Ok(Self(Arc::new(bytes)))
    }
}

impl From<Vec<u8>> for Proof {
    fn from(value: Vec<u8>) -> Self {
        Self(Arc::new(value))
    }
}

impl Proof {
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}