sp1-sdk 6.4.0

The SP1 SDK for building and proving zkVM programs
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
//! # Network Prover
//!
//! This module provides an implementation of the [`crate::Prover`] trait that can generate proofs
//! on a remote RPC server.

use std::time::{Duration, Instant};

use super::prove::NetworkProveBuilder;
use crate::{
    network::{
        client::{parse_fulfillment_status, NetworkClient},
        proto::{
            types::{
                ExecutionStatus, FulfillmentStatus, FulfillmentStrategy, ProofMode, ProofRequest,
            },
            GetProofRequestStatusResponse,
        },
        signer::NetworkSigner,
        tee::{client::Client as TeeClient, verify_tee_proof},
        Error, NetworkMode, DEFAULT_AUCTION_TIMEOUT_DURATION, DEFAULT_GAS_LIMIT,
        DEFAULT_MAX_PRICE_PER_PGU_BUFFER, MAINNET_EXPLORER_URL, MAINNET_RPC_URL,
        PRIVATE_EXPLORER_URL, PRIVATE_NETWORK_RPC_URL, RESERVED_EXPLORER_URL, RESERVED_RPC_URL,
        TEE_NETWORK_RPC_URL,
    },
    prover::{verify_proof, BaseProveRequest, SendFutureResult},
    ProofFromNetwork, Prover, SP1ProofMode, SP1ProofWithPublicValues, SP1ProvingKey,
    SP1VerifyingKey,
};

use crate::network::proto::GetProofRequestParamsResponse;

use alloy_primitives::{Address, B256, U256};
use anyhow::{Context, Result};
use sp1_build::Elf;
use sp1_core_executor::{SP1Context, StatusCode};
use sp1_core_machine::io::SP1Stdin;
use sp1_core_machine::riscv::RiscvAir;
use sp1_hypercube::Machine;
use sp1_primitives::SP1Field;
use sp1_prover::worker::{SP1LightNode, SP1NodeCore};
use sp1_prover::SP1_CIRCUIT_VERSION;

use tokio::time::sleep;

/// An implementation of [`crate::ProverClient`] that can generate proofs on a remote RPC server.
#[derive(Clone)]
pub struct NetworkProver {
    pub(crate) client: NetworkClient,
    pub(crate) node: SP1LightNode,
    pub(crate) tee_signers: Vec<Address>,
    pub(crate) network_mode: NetworkMode,
    /// Whether to use hosted defaults for proof requests.
    ///
    /// When set, [`NetworkProver::prove`] skips local simulation and sets the cycle and gas limits
    /// to their maximum, so that `prove(&pk, stdin).await` works without any network-specific
    /// toggles. This is the behavior wanted by self-hosted clusters talking to the
    /// network-gateway. It is independent of [`NetworkMode`]; a hosted prover runs in
    /// [`NetworkMode::Reserved`].
    pub(crate) hosted: bool,
}

impl Prover for NetworkProver {
    // todo!(n): Remove usage of anyhow.
    type ProvingKey = SP1ProvingKey;
    type Error = anyhow::Error;
    type ProveRequest<'a> = NetworkProveBuilder<'a>;

    fn inner(&self) -> &SP1NodeCore {
        self.node.inner()
    }

    fn setup(&self, elf: Elf) -> impl SendFutureResult<Self::ProvingKey, Self::Error> {
        async move {
            let vk = self.node.setup(&elf).await?;
            let pk = SP1ProvingKey { vk, elf };
            Ok(pk)
        }
    }

    fn prove<'a>(&'a self, pk: &'a Self::ProvingKey, stdin: SP1Stdin) -> Self::ProveRequest<'a> {
        let strategy = self.default_fulfillment_strategy();

        // A hosted prover skips simulation and proves up to the maximum limits by default, so that
        // `prove(&pk, stdin).await` works with no network-specific toggles. These remain overridable
        // per request via the builder methods.
        let (skip_simulation, cycle_limit, gas_limit) =
            if self.hosted { (true, Some(u64::MAX), Some(u64::MAX)) } else { (false, None, None) };

        NetworkProveBuilder {
            base: BaseProveRequest::new(self, pk, stdin),
            timeout: None,
            strategy,
            skip_simulation,
            cycle_limit,
            gas_limit,
            tee_2fa: false,
            min_auction_period: 0,
            whitelist: None,
            auctioneer: None,
            executor: None,
            verifier: None,
            treasury: None,
            max_price_per_pgu: None,
            max_price_per_pgu_buffer: None,
            auction_timeout: None,
            private_stdin: false,
        }
    }

    fn verify(
        &self,
        proof: &SP1ProofWithPublicValues,
        vkey: &SP1VerifyingKey,
        status_code: Option<StatusCode>,
    ) -> Result<(), crate::SP1VerificationError> {
        if let Some(tee_proof) = &proof.tee_proof {
            verify_tee_proof(&self.tee_signers, tee_proof, vkey, proof.public_values.as_ref())?;
        }

        verify_proof(self.inner(), self.version(), proof, vkey, status_code)
    }
}

/// Returns `true` if the error is a wait-loop terminal failure that the auction fallback path
/// should retry against high-availability provers. The retry is single-shot — guarded by
/// `whitelist.is_none()` at the call site, which is set on retry — so adding a variant here
/// cannot produce an unbounded retry loop.
///
/// Settlement failures (`RequestReverted`) are deliberately NOT retryable by default. The SDK only
/// sees the terminal status, not a stable retry reason, so retrying here can burn more PROVE on
/// deterministic failures. Callers who own a different policy can inspect the error and resubmit.
fn should_retry_with_ha_fallback(error: &Error) -> bool {
    matches!(
        error,
        Error::RequestUnfulfillable { .. }
            | Error::RequestTimedOut { .. }
            | Error::RequestAuctionTimedOut { .. }
            | Error::RequestExpired { .. }
    )
}

/// Maps the post-RPC status to a public outcome. Pure logic, kept separate from the RPC path so
/// the decision boundaries are unit-testable without mocking transport.
///
/// Priority (matches the inline order in `process_proof_status` prior to this extraction):
///   1. `FulfillmentStatus::Fulfilled` -> `Ok((proof, Fulfilled))` even past deadline
///   2. `ExecutionStatus::Unexecutable` -> `Error::RequestUnexecutable`
///   3. `FulfillmentStatus::Unfulfillable` -> `Error::RequestUnfulfillable`
///   4. `FulfillmentStatus::Reverted` -> `Error::RequestReverted`
///   5. `FulfillmentStatus::Expired` -> `Error::RequestExpired`
///   6. `deadline_exceeded` -> `Error::RequestTimedOut`
///   7. otherwise (Unspecified, Requested, Assigned) -> `Ok((None, status))` for the caller to poll
fn decide_status_outcome(
    request_id: B256,
    execution_status: ExecutionStatus,
    fulfillment_status: FulfillmentStatus,
    maybe_proof: Option<SP1ProofWithPublicValues>,
    deadline_exceeded: bool,
) -> Result<(Option<SP1ProofWithPublicValues>, FulfillmentStatus)> {
    if fulfillment_status == FulfillmentStatus::Fulfilled {
        return Ok((maybe_proof, fulfillment_status));
    }
    if execution_status == ExecutionStatus::Unexecutable {
        return Err(Error::RequestUnexecutable { request_id: request_id.to_vec() }.into());
    }
    match fulfillment_status {
        FulfillmentStatus::Unfulfillable => {
            return Err(Error::RequestUnfulfillable { request_id: request_id.to_vec() }.into());
        }
        FulfillmentStatus::Reverted => {
            return Err(Error::RequestReverted { request_id: request_id.to_vec() }.into());
        }
        FulfillmentStatus::Expired => {
            return Err(Error::RequestExpired { request_id: request_id.to_vec() }.into());
        }
        _ => {}
    }
    if deadline_exceeded {
        return Err(Error::RequestTimedOut { request_id: request_id.to_vec() }.into());
    }
    Ok((None, fulfillment_status))
}

impl NetworkProver {
    /// Creates a new [`NetworkProver`] with the given signer and network mode.
    ///
    /// # Details
    /// * `signer`: The network signer to use for signing requests. Can be a `NetworkSigner`,
    ///   private key string, or anything that implements `Into<NetworkSigner>`.
    /// * `rpc_url`: The rpc url to use for the prover network.
    /// * `network_mode`: The network mode determining which proving strategy to use.
    ///
    /// # Examples
    /// Using a private key string:
    /// ```rust,no_run
    /// use sp1_sdk::{network::NetworkMode, NetworkProver};
    ///
    /// let prover = NetworkProver::new("0x...", "...", NetworkMode::Mainnet);
    /// ```
    ///
    /// Using a `NetworkSigner`:
    /// ```rust,no_run
    /// use sp1_sdk::{
    ///     network::{signer::NetworkSigner, NetworkMode},
    ///     NetworkProver,
    /// };
    ///
    /// let signer = NetworkSigner::local("0x...").unwrap();
    /// let prover = NetworkProver::new(signer, "...", NetworkMode::Reserved);
    /// ```
    #[must_use]
    pub async fn new(
        signer: impl Into<NetworkSigner>,
        rpc_url: &str,
        network_mode: NetworkMode,
    ) -> Self {
        Self::new_with_machine(signer, rpc_url, network_mode, RiscvAir::machine()).await
    }

    #[must_use]
    /// Same as `new` but with a custom machine
    pub async fn new_with_machine(
        signer: impl Into<NetworkSigner>,
        rpc_url: &str,
        network_mode: NetworkMode,
        machine: Machine<SP1Field, RiscvAir<SP1Field>>,
    ) -> Self {
        // Install default CryptoProvider if not already installed.
        let _ = rustls::crypto::ring::default_provider().install_default();

        let signer = signer.into();
        let node = SP1LightNode::new_with_machine(machine).await;
        let client = NetworkClient::new(signer, rpc_url, network_mode);
        Self { client, node, tee_signers: vec![], network_mode, hosted: false }
    }

    /// Sets the list of TEE signers, used for verifying TEE proofs.
    #[must_use]
    pub fn with_tee_signers(mut self, tee_signers: Vec<Address>) -> Self {
        self.tee_signers = tee_signers;
        self
    }

    /// Sets whether this prover uses hosted defaults (skip simulation, max cycle and gas limits).
    ///
    /// See [`NetworkProver::hosted`] for details.
    #[must_use]
    pub(crate) fn with_hosted(mut self, hosted: bool) -> Self {
        self.hosted = hosted;
        self
    }

    /// Gets the network mode of this prover.
    #[must_use]
    pub fn network_mode(&self) -> NetworkMode {
        self.network_mode
    }

    /// Gets the default fulfillment strategy for this prover's network mode.
    #[must_use]
    pub fn default_fulfillment_strategy(&self) -> FulfillmentStrategy {
        match self.network_mode {
            NetworkMode::Mainnet => FulfillmentStrategy::Auction,
            NetworkMode::Reserved => FulfillmentStrategy::Hosted,
        }
    }

    /// Get the credit balance of your account on the prover network.
    ///
    /// # Example
    /// ```rust,no_run
    /// use sp1_sdk::{ProverClient, SP1Stdin};
    ///
    /// tokio_test::block_on(async {
    ///     let client = ProverClient::builder().network().build().await;
    ///     let balance = client.get_balance().await.unwrap();
    /// })
    /// ```
    pub async fn get_balance(&self) -> Result<U256> {
        self.client.get_balance().await
    }

    /// Registers a program if it is not already registered.
    ///
    /// # Details
    /// * `vk`: The verifying key to use for the program.
    /// * `elf`: The elf to use for the program.
    ///
    /// Note that this method requires that the user honestly registers the program (i.e., the elf
    /// matches the vk).
    ///
    /// # Example
    /// ```rust,no_run
    /// use sp1_sdk::{Elf, Prover, ProverClient, ProvingKey, SP1Stdin};
    ///
    /// tokio_test::block_on(async {
    ///     let elf = Elf::Static(&[1, 2, 3]);
    ///     let client = ProverClient::builder().network().build().await;
    ///     let pk = client.setup(elf).await.unwrap();
    ///     let vk_hash = client.register_program(&pk.verifying_key(), pk.elf()).await.unwrap();
    /// });
    /// ```
    pub async fn register_program(&self, vk: &SP1VerifyingKey, elf: &[u8]) -> Result<B256> {
        self.client.register_program(vk, elf).await
    }

    /// Gets the proof request parameters from the network.
    ///
    /// # Details
    /// * `mode`: The proof mode to get the parameters for.
    ///
    /// # Example
    /// ```rust,no_run
    /// use sp1_sdk::{ProverClient, SP1ProofMode};
    /// tokio_test::block_on(async {
    ///     let client = ProverClient::builder().network().build().await;
    ///     let params = client.get_proof_request_params(SP1ProofMode::Compressed).await.unwrap();
    /// })
    /// ```
    pub async fn get_proof_request_params(
        &self,
        mode: SP1ProofMode,
    ) -> Result<GetProofRequestParamsResponse> {
        match self.network_mode {
            NetworkMode::Mainnet => {
                let response = self.client.get_proof_request_params(mode.into()).await?;
                Ok(response)
            }
            NetworkMode::Reserved => {
                Err(anyhow::anyhow!(
                    "get_proof_request_params is only available in Mainnet mode (auction-based proving). This feature is not supported in Reserved mode."
                ))
            }
        }
    }

    /// Gets the status of a proof request. Re-exposes the status response from the client.
    ///
    /// # Details
    /// * `request_id`: The request ID to get the status of.
    ///
    /// # Example
    /// ```rust,no_run
    /// use sp1_sdk::{network::B256, ProverClient};
    ///
    /// tokio_test::block_on(async {
    ///     let request_id = B256::from_slice(&vec![1u8; 32]);
    ///     let client = ProverClient::builder().network().build().await;
    ///     let (status, maybe_proof) = client.get_proof_status(request_id).await.unwrap();
    /// })
    /// ```
    pub async fn get_proof_status(
        &self,
        request_id: B256,
    ) -> Result<(GetProofRequestStatusResponse, Option<SP1ProofWithPublicValues>)> {
        let (status, maybe_proof): (GetProofRequestStatusResponse, Option<ProofFromNetwork>) =
            self.client.get_proof_request_status(request_id, None).await?;
        let maybe_proof = maybe_proof.map(Into::into);
        Ok((status, maybe_proof))
    }

    /// Gets the proof request details, if available.
    ///
    /// The [`ProofRequest`] type contains useful information about the request, like the cycle
    /// count, or the gas used.
    ///
    /// # Details
    /// * `request_id`: The request ID to get the status of.
    ///
    /// # Example
    /// ```rust,no_run
    /// use sp1_sdk::{network::B256, ProverClient};
    ///
    /// tokio_test::block_on(async {
    ///     let request_id = B256::from_slice(&vec![1u8; 32]);
    ///     let client = ProverClient::builder().network().build().await;
    ///     let request = client.get_proof_request(request_id).await.unwrap();
    /// })
    /// ```
    pub async fn get_proof_request(&self, request_id: B256) -> Result<Option<ProofRequest>> {
        let res = self.client.get_proof_request_details(request_id, None).await?;
        Ok(res.request)
    }

    /// Gets the status of a proof request with handling for timeouts and unfulfillable requests.
    ///
    /// Returns the proof if it is fulfilled and the fulfillment status. Handles statuses indicating
    /// that the proof is unfulfillable or unexecutable with errors.
    ///
    /// # Details
    /// * `request_id`: The request ID to get the status of.
    /// * `remaining_timeout`: The remaining timeout for the proof request.
    ///
    /// # Example
    /// ```rust,no_run
    /// use sp1_sdk::{network::B256, ProverClient};
    ///
    /// tokio_test::block_on(async {
    ///     let request_id = B256::from_slice(&vec![1u8; 32]);
    ///     let client = ProverClient::builder().network().build().await;
    ///     let (maybe_proof, fulfillment_status) =
    ///         client.process_proof_status(request_id, None).await.unwrap();
    /// })
    /// ```
    pub async fn process_proof_status(
        &self,
        request_id: B256,
        remaining_timeout: Option<Duration>,
    ) -> Result<(Option<SP1ProofWithPublicValues>, FulfillmentStatus)> {
        // Get the status.
        let (status, maybe_proof): (GetProofRequestStatusResponse, Option<ProofFromNetwork>) =
            self.client.get_proof_request_status(request_id, remaining_timeout).await?;

        let maybe_proof: Option<SP1ProofWithPublicValues> = maybe_proof.map(Into::into);

        let execution_status = ExecutionStatus::try_from(status.execution_status()).unwrap();
        let fulfillment_status = parse_fulfillment_status(status.fulfillment_status(), request_id)?;

        let current_time =
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
        let deadline_exceeded = current_time > status.deadline();

        decide_status_outcome(
            request_id,
            execution_status,
            fulfillment_status,
            maybe_proof,
            deadline_exceeded,
        )
    }

    /// Requests a proof from the prover network, returning the request ID.
    ///
    /// # Details
    /// * `vk_hash`: The hash of the verifying key to use for the proof.
    /// * `stdin`: The input to use for the proof.
    /// * `mode`: The proof mode to use for the proof.
    /// * `strategy`: The fulfillment strategy to use for the proof.
    /// * `cycle_limit`: The cycle limit to use for the proof.
    /// * `gas_limit`: The gas limit to use for the proof.
    /// * `timeout`: The timeout for the proof request.
    /// * `min_auction_period`: The minimum auction period for the proof request in seconds.
    /// * `whitelist`: The auction whitelist for the proof request.
    /// * `auctioneer`: The auctioneer address for the proof request.
    /// * `executor`: The executor address for the proof request.
    /// * `verifier`: The verifier address for the proof request.
    /// * `treasury`: The treasury address for the proof request.
    /// * `public_values_hash`: The hash of the public values to use for the proof.
    /// * `base_fee`: The base fee to use for the proof request.
    /// * `max_price_per_pgu`: The maximum price per PGU to use for the proof request.
    /// * `domain`: The domain bytes to use for the proof request.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn request_proof(
        &self,
        vk_hash: B256,
        stdin: &SP1Stdin,
        mode: ProofMode,
        strategy: FulfillmentStrategy,
        cycle_limit: u64,
        gas_limit: u64,
        timeout: Option<Duration>,
        min_auction_period: u64,
        whitelist: Option<Vec<Address>>,
        auctioneer: Address,
        executor: Address,
        verifier: Address,
        treasury: Address,
        public_values_hash: Option<Vec<u8>>,
        base_fee: u64,
        max_price_per_pgu: u64,
        domain: Vec<u8>,
        private_stdin: bool,
    ) -> Result<B256> {
        if self.client.rpc_url == TEE_NETWORK_RPC_URL && strategy != FulfillmentStrategy::Reserved {
            return Err(anyhow::anyhow!(
                "Private proving is available with reserved fulfillment strategy only. Use FulfillmentStrategy::Reserved."
            ));
        }

        // Get the timeout. If no timeout is specified, auto-calculate based on gas limit for
        // Mainnet, use default timeout for Reserved.
        let timeout_secs = timeout.map_or_else(
            || match self.network_mode {
                NetworkMode::Mainnet => super::utils::calculate_timeout_from_gas_limit(gas_limit),
                NetworkMode::Reserved => super::DEFAULT_TIMEOUT_SECS,
            },
            |dur| dur.as_secs(),
        );

        let max_price_per_bpgu = max_price_per_pgu * 1_000_000_000;

        // Log the request.
        tracing::info!("Requesting proof:");
        tracing::info!("├─ Strategy: {:?}", strategy);
        tracing::info!("├─ Proof mode: {:?}", mode);
        tracing::info!("├─ Circuit version: {}", SP1_CIRCUIT_VERSION);
        tracing::info!("├─ Timeout: {} seconds", timeout_secs);
        if let Some(ref hash) = public_values_hash {
            tracing::info!("├─ Public values hash: 0x{}", hex::encode(hash));
        }
        if strategy == FulfillmentStrategy::Auction {
            tracing::info!(
                "├─ Base fee: {} ({} $PROVE)",
                base_fee,
                Self::format_prove_amount(base_fee)
            );
            tracing::info!(
                "├─ Max price per bPGU: {} ({} $PROVE)",
                max_price_per_bpgu,
                Self::format_prove_amount(max_price_per_bpgu)
            );
            tracing::info!("├─ Minimum auction period: {:?} seconds", min_auction_period);
            tracing::info!("├─ Prover Whitelist: {:?}", whitelist);
        }
        tracing::info!("├─ Cycle limit: {} cycles", cycle_limit);
        tracing::info!("└─ Gas limit: {} PGUs", gas_limit);

        // Request the proof.
        let response = self
            .client
            .request_proof(
                vk_hash,
                stdin,
                mode,
                SP1_CIRCUIT_VERSION,
                strategy,
                timeout_secs,
                cycle_limit,
                gas_limit,
                min_auction_period,
                whitelist,
                auctioneer,
                executor,
                verifier,
                treasury,
                public_values_hash,
                base_fee,
                max_price_per_pgu,
                domain,
                private_stdin,
            )
            .await?;

        // Log the request ID and transaction hash.
        let tx_hash = B256::from_slice(response.tx_hash());
        let request_id = B256::from_slice(response.request_id());
        tracing::info!("Created request {} in transaction {:?}", request_id, tx_hash);

        let explorer = match self.client.rpc_url.trim_end_matches('/') {
            MAINNET_RPC_URL => Some(MAINNET_EXPLORER_URL),
            RESERVED_RPC_URL => Some(RESERVED_EXPLORER_URL),
            PRIVATE_NETWORK_RPC_URL => Some(PRIVATE_EXPLORER_URL),
            _ => None,
        };

        if let Some(base_url) = explorer {
            tracing::info!("View request status at: {}/request/{}", base_url, request_id);
        }

        Ok(request_id)
    }

    /// Cancels a proof request by updating the deadline to the current time.
    /// Only available in Mainnet mode (auction-based proving).
    pub async fn cancel_request(&self, request_id: B256) -> Result<()> {
        match self.network_mode {
            NetworkMode::Mainnet => {
                self.client.cancel_request(request_id).await?;
                Ok(())
            }
            NetworkMode::Reserved => {
                Err(anyhow::anyhow!(
                    "cancel_request is only available in Mainnet mode (auction-based proving). This feature is not supported in Reserved mode."
                ))
            }
        }
    }

    /// Waits for a proof to be generated and returns the proof. If a timeout is supplied, the
    /// function will return an error if the proof is not generated within the timeout.
    /// If `auction_timeout` is supplied, the function will return an error if the proof request
    /// remains in "requested" status for longer than the auction timeout.
    pub async fn wait_proof(
        &self,
        request_id: B256,
        timeout: Option<Duration>,
        auction_timeout: Option<Duration>,
    ) -> Result<SP1ProofWithPublicValues> {
        let mut is_assigned = false;
        let start_time = Instant::now();
        let mut requested_start_time: Option<Instant> = None;
        #[allow(unused)]
        let auction_timeout_duration = auction_timeout.unwrap_or(DEFAULT_AUCTION_TIMEOUT_DURATION);

        loop {
            // Calculate the remaining timeout.
            if let Some(timeout) = timeout {
                if start_time.elapsed() > timeout {
                    return Err(Error::RequestTimedOut { request_id: request_id.to_vec() }.into());
                }
            }
            let remaining_timeout = timeout.map(|t| {
                let elapsed = start_time.elapsed();
                t.checked_sub(elapsed).unwrap_or(Duration::from_secs(0))
            });

            let (maybe_proof, fulfillment_status) =
                self.process_proof_status(request_id, remaining_timeout).await?;

            if fulfillment_status == FulfillmentStatus::Fulfilled {
                return Ok(maybe_proof.unwrap());
            } else if fulfillment_status == FulfillmentStatus::Assigned && !is_assigned {
                tracing::info!("Proof request assigned, proving...");
                is_assigned = true;
            } else if fulfillment_status == FulfillmentStatus::Requested {
                // Track when we first entered requested status.
                if requested_start_time.is_none() {
                    requested_start_time = Some(Instant::now());
                }

                // Check if we've exceeded the auction timeout (only for Mainnet mode).
                if self.network_mode == NetworkMode::Mainnet {
                    if let Some(req_start) = requested_start_time {
                        if req_start.elapsed() > auction_timeout_duration {
                            tracing::info!("Auction period exceeded, cancelling request...");
                            self.client.cancel_request(request_id).await?;
                            return Err(Error::RequestAuctionTimedOut {
                                request_id: request_id.to_vec(),
                            }
                            .into());
                        }
                    }
                }
            }

            sleep(Duration::from_secs(2)).await;
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn request_proof_impl(
        &self,
        pk: &SP1ProvingKey,
        stdin: &SP1Stdin,
        mode: SP1ProofMode,
        strategy: FulfillmentStrategy,
        timeout: Option<Duration>,
        skip_simulation: bool,
        cycle_limit: Option<u64>,
        gas_limit: Option<u64>,
        min_auction_period: u64,
        whitelist: Option<Vec<Address>>,
        auctioneer: Option<Address>,
        executor: Option<Address>,
        verifier: Option<Address>,
        treasury: Option<Address>,
        max_price_per_pgu: Option<u64>,
        max_price_per_pgu_buffer: Option<u64>,
        private_stdin: bool,
    ) -> Result<B256> {
        let vk_hash = self.register_program(&pk.vk, &pk.elf).await?;
        let (cycle_limit, gas_limit, public_values_hash) = self
            .get_execution_limits(cycle_limit, gas_limit, &pk.elf, stdin, skip_simulation)
            .await?;
        let (auctioneer, executor, verifier, treasury, max_price_per_pgu, base_fee, domain) = self
            .get_auction_request_params(
                mode,
                auctioneer,
                executor,
                verifier,
                treasury,
                max_price_per_pgu,
                max_price_per_pgu_buffer,
            )
            .await?;

        self.request_proof(
            vk_hash,
            stdin,
            mode.into(),
            strategy,
            cycle_limit,
            gas_limit,
            timeout,
            min_auction_period,
            whitelist,
            auctioneer,
            executor,
            verifier,
            treasury,
            public_values_hash,
            base_fee,
            max_price_per_pgu,
            domain,
            private_stdin,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn prove_impl(
        &self,
        pk: &SP1ProvingKey,
        stdin: &SP1Stdin,
        mode: SP1ProofMode,
        strategy: FulfillmentStrategy,
        timeout: Option<Duration>,
        skip_simulation: bool,
        cycle_limit: Option<u64>,
        gas_limit: Option<u64>,
        tee_2fa: bool,
        min_auction_period: u64,
        whitelist: Option<Vec<Address>>,
        auctioneer: Option<Address>,
        executor: Option<Address>,
        verifier: Option<Address>,
        treasury: Option<Address>,
        max_price_per_pgu: Option<u64>,
        max_price_per_pgu_buffer: Option<u64>,
        auction_timeout: Option<Duration>,
        private_stdin: bool,
    ) -> Result<SP1ProofWithPublicValues> {
        #[allow(unused_mut)]
        let mut whitelist = whitelist.clone();

        // Attempt to get proof, with retry logic for failed auction requests.
        #[allow(clippy::never_loop)]
        loop {
            let request_id = self
                .request_proof_impl(
                    pk,
                    stdin,
                    mode,
                    strategy,
                    timeout,
                    skip_simulation,
                    cycle_limit,
                    gas_limit,
                    min_auction_period,
                    whitelist.clone(),
                    auctioneer,
                    executor,
                    verifier,
                    treasury,
                    max_price_per_pgu,
                    max_price_per_pgu_buffer,
                    private_stdin,
                )
                .await?;

            // If 2FA is enabled, spawn a task to get the tee proof.
            // Note: We only support one type of TEE proof for now.
            let handle = if tee_2fa {
                let elf_vec = pk.elf.to_vec();
                let request = super::tee::api::TEERequest::new(
                    &self.client.signer,
                    *request_id,
                    elf_vec,
                    stdin.clone(),
                    cycle_limit.unwrap_or_else(|| {
                        super::utils::get_default_cycle_limit_for_mode(self.network_mode)
                    }),
                )
                .await?;

                Some(tokio::spawn(async move {
                    let tee_client = TeeClient::default();

                    tee_client.execute(request).await
                }))
            } else {
                None
            };

            // Wait for the proof to be generated.
            let mut proof = match self.wait_proof(request_id, timeout, auction_timeout).await {
                Ok(proof) => proof,
                Err(e) => {
                    // Check if this is a Mainnet auction request that we can retry.
                    if self.network_mode == NetworkMode::Mainnet {
                        if let Some(network_error) = e.downcast_ref::<Error>() {
                            if should_retry_with_ha_fallback(network_error)
                                && strategy == FulfillmentStrategy::Auction
                                && whitelist.is_none()
                            {
                                tracing::warn!(
                                    "Retrying auction request with fallback whitelist..."
                                );

                                // Get fallback high availability provers and retry.
                                let mut rpc = self.client.auction_prover_network_client().await?;
                                let fallback_whitelist = rpc
                                    .get_provers_by_uptime(
                                        crate::network::proto::auction_types::GetProversByUptimeRequest {
                                            high_availability_only: true,
                                        },
                                    )
                                    .await?
                                    .into_inner()
                                    .provers
                                    .into_iter()
                                    .map(|p| Address::from_slice(&p))
                                    .collect::<Vec<_>>();
                                if fallback_whitelist.is_empty() {
                                    tracing::warn!("No fallback high availability provers found.");
                                    return Err(e);
                                }
                                whitelist = Some(fallback_whitelist);
                                continue;
                            }
                        }
                    }

                    // If we can't retry, return the error.
                    return Err(e);
                }
            };

            // If 2FA is enabled, wait for the tee proof to be generated and add it to the proof.
            if let Some(handle) = handle {
                let tee_proof = handle
                    .await
                    .context("Spawning a new task to get the tee proof failed")?
                    .context("Error response from TEE server")?;

                proof.tee_proof = Some(tee_proof.as_prefix_bytes());
            }

            return Ok(proof);
        }
    }

    /// The cycle limit and gas limit are determined according to the following priority:
    ///
    /// 1. If either of the limits are explicitly set by the requester, use the specified value.
    /// 2. If simulation is enabled, calculate the limits by simulating the execution of the
    ///    program. This is the default behavior.
    /// 3. Otherwise, use the default limits ([`MAINNET_DEFAULT_CYCLE_LIMIT`] or
    ///    [`RESERVED_DEFAULT_CYCLE_LIMIT`] and [`DEFAULT_GAS_LIMIT`]).
    async fn get_execution_limits(
        &self,
        cycle_limit: Option<u64>,
        gas_limit: Option<u64>,
        elf: &[u8],
        stdin: &SP1Stdin,
        skip_simulation: bool,
    ) -> Result<(u64, u64, Option<Vec<u8>>)> {
        let cycle_limit_value = if let Some(cycles) = cycle_limit {
            cycles
        } else if skip_simulation {
            super::utils::get_default_cycle_limit_for_mode(self.network_mode)
        } else {
            // Will be calculated through simulation.
            0
        };

        let gas_limit_value = if let Some(gas) = gas_limit {
            gas
        } else if skip_simulation {
            DEFAULT_GAS_LIMIT
        } else {
            // Will be calculated through simulation.
            0
        };

        // If both limits were explicitly provided or skip_simulation is true, return immediately.
        if (cycle_limit.is_some() && gas_limit.is_some()) || skip_simulation {
            return Ok((cycle_limit_value, gas_limit_value, None));
        }

        // One of the limits were not provided and simulation is not skipped, so simulate to get
        // one. or both limits.
        let execute_result = self
            .node
            .execute(elf, stdin.clone(), SP1Context::builder().calculate_gas(true).build())
            .await
            .map_err(|_| Error::SimulationFailed)?;

        let (_, committed_value_digest, report) = execute_result;

        // Use simulated values for the ones that are not explicitly provided.
        let final_cycle_limit = if cycle_limit.is_none() {
            report.total_instruction_count()
        } else {
            cycle_limit_value
        };
        let final_gas_limit = if gas_limit.is_none() {
            report.gas().unwrap_or(DEFAULT_GAS_LIMIT)
        } else {
            gas_limit_value
        };

        let public_values_hash = Some(committed_value_digest.to_vec());

        Ok((final_cycle_limit, final_gas_limit, public_values_hash))
    }

    /// The proof request parameters for the auction strategy are determined according to the
    /// following priority:
    ///
    /// 1. If the parameter is explicitly set by the requester, use the specified value.
    /// 2. Otherwise, use the default values fetched from the network RPC.
    #[allow(unused_variables)]
    #[allow(clippy::unused_async, clippy::too_many_arguments)]
    async fn get_auction_request_params(
        &self,
        mode: SP1ProofMode,
        auctioneer: Option<Address>,
        executor: Option<Address>,
        verifier: Option<Address>,
        treasury: Option<Address>,
        max_price_per_pgu: Option<u64>,
        max_price_per_pgu_buffer: Option<u64>,
    ) -> Result<(Address, Address, Address, Address, u64, u64, Vec<u8>)> {
        match self.network_mode {
            NetworkMode::Mainnet => {
                let params = self.get_proof_request_params(mode).await?;
                match params {
                    GetProofRequestParamsResponse::Auction(auction_params) => {
                        let auctioneer_value = if let Some(auctioneer) = auctioneer {
                            auctioneer
                        } else {
                            Address::from_slice(&auction_params.auctioneer)
                        };
                        let executor_value = if let Some(executor) = executor {
                            executor
                        } else {
                            Address::from_slice(&auction_params.executor)
                        };
                        let verifier_value = if let Some(verifier) = verifier {
                            verifier
                        } else {
                            Address::from_slice(&auction_params.verifier)
                        };
                        let treasury_value = if let Some(treasury) = treasury {
                            treasury
                        } else {
                            Address::from_slice(&auction_params.treasury)
                        };
                        let max_price_per_pgu_value = if let Some(v) = max_price_per_pgu {
                            v
                        } else {
                            let base = auction_params.max_price_per_pgu.parse::<u64>().map_err(
                                |e| {
                                    anyhow::anyhow!(
                                        "invalid max_price_per_pgu {:?}: {e}",
                                        auction_params.max_price_per_pgu
                                    )
                                },
                            )?;
                            let pct = max_price_per_pgu_buffer.unwrap_or(DEFAULT_MAX_PRICE_PER_PGU_BUFFER);
                            let buffered = buffer_max_price_per_pgu(base, pct);
                            // Align to the network's auction tick when advertised. `tick_size == 0`
                            // means an older RPC that predates the field — leave the value as-is so
                            // the bidder still rounds it on intake.
                            align_to_tick(buffered, auction_params.tick_size)
                        };
                        let base_fee = auction_params
                            .base_fee
                            .parse::<u64>()
                            .expect("invalid base_fee");
                        Ok((auctioneer_value, executor_value, verifier_value, treasury_value, max_price_per_pgu_value, base_fee, auction_params.domain))
                    }
                    GetProofRequestParamsResponse::Unsupported => {
                        Err(anyhow::anyhow!(
                            "get_proof_request_params is not supported in {:?} mode. This operation is only available for Mainnet (auction-based proving).",
                            self.network_mode
                        ))
                    }
                }
            }
            NetworkMode::Reserved => {
                // Reserved mode doesn't use auction parameters.
                Ok((Address::ZERO, Address::ZERO, Address::ZERO, Address::ZERO, 0, 0, vec![]))
            }
        }
    }

    /// Formats a PROVE amount (with 18 decimals) as a string with 4 decimal places.
    fn format_prove_amount(amount: u64) -> String {
        let whole = amount / 1_000_000_000_000_000_000;
        let remainder = amount % 1_000_000_000_000_000_000;
        let frac = remainder / 100_000_000_000_000;
        format!("{whole}.{frac:04}")
    }
}

impl From<SP1ProofMode> for ProofMode {
    fn from(value: SP1ProofMode) -> Self {
        match value {
            SP1ProofMode::Core => Self::Core,
            SP1ProofMode::Compressed => Self::Compressed,
            SP1ProofMode::Plonk => Self::Plonk,
            SP1ProofMode::Groth16 => Self::Groth16,
        }
    }
}

/// Apply a percentage buffer to the server-supplied `max_price_per_pgu` default. If the
/// buffered value overflows `u64`, log and return `base` unchanged.
fn buffer_max_price_per_pgu(base: u64, buffer_pct: u64) -> u64 {
    let buffered = u128::from(base).saturating_mul(u128::from(buffer_pct)) / 100;
    u64::try_from(buffered).unwrap_or_else(|_| {
        tracing::warn!(
            buffered,
            "buffered max_price_per_pgu overflows u64; using server-supplied default"
        );
        base
    })
}

/// Floor `value` to a multiple of `tick`. A tick of `0` or `1` returns `value` unchanged,
/// so older RPCs that don't advertise a tick — or future envs without one — are no-ops.
fn align_to_tick(value: u64, tick: u64) -> u64 {
    if tick <= 1 {
        return value;
    }
    value - (value % tick)
}

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

    #[test]
    fn buffer_applied_to_base() {
        // 1000 * 120 / 100 = 1200.
        assert_eq!(buffer_max_price_per_pgu(1000, 120), 1200);
    }

    #[test]
    fn custom_buffer_pct_applied() {
        // Caller can override the buffer; 1000 * 150 / 100 = 1500.
        assert_eq!(buffer_max_price_per_pgu(1000, 150), 1500);
    }

    #[test]
    fn overflow_returns_base() {
        // u64::MAX * u64::MAX saturates to u128::MAX; /100 is well beyond u64::MAX.
        assert_eq!(buffer_max_price_per_pgu(u64::MAX, u64::MAX), u64::MAX);
    }

    #[test]
    fn align_floors_to_tick() {
        // 1_234_567_890 floored to a 10M tick.
        assert_eq!(align_to_tick(1_234_567_890, 10_000_000), 1_230_000_000);
    }

    #[test]
    fn align_zero_tick_is_no_op() {
        // Older RPCs return tick_size=0; must pass the buffered value through unchanged.
        assert_eq!(align_to_tick(1_234_567_890, 0), 1_234_567_890);
        assert_eq!(align_to_tick(1_234_567_890, 1), 1_234_567_890);
    }
}

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

    fn rid() -> B256 {
        B256::from([0xab; 32])
    }

    #[test]
    fn fulfilled_takes_precedence_over_unexecutable_and_deadline() {
        // Per #2737 ordering: a Fulfilled proof should be returned even if both Unexecutable
        // and the deadline are concurrent — the proof is in hand.
        let (proof, status) = decide_status_outcome(
            rid(),
            ExecutionStatus::Unexecutable,
            FulfillmentStatus::Fulfilled,
            None,
            true,
        )
        .unwrap();
        assert!(proof.is_none());
        assert_eq!(status, FulfillmentStatus::Fulfilled);
    }

    #[test]
    fn unexecutable_maps_to_request_unexecutable() {
        let err = decide_status_outcome(
            rid(),
            ExecutionStatus::Unexecutable,
            FulfillmentStatus::Assigned,
            None,
            false,
        )
        .unwrap_err();
        assert!(matches!(err.downcast_ref::<Error>(), Some(Error::RequestUnexecutable { .. })));
    }

    #[test]
    fn unfulfillable_maps_to_request_unfulfillable() {
        let err = decide_status_outcome(
            rid(),
            ExecutionStatus::Executed,
            FulfillmentStatus::Unfulfillable,
            None,
            false,
        )
        .unwrap_err();
        assert!(matches!(err.downcast_ref::<Error>(), Some(Error::RequestUnfulfillable { .. })));
    }

    #[test]
    fn reverted_maps_to_request_reverted() {
        let err = decide_status_outcome(
            rid(),
            ExecutionStatus::Executed,
            FulfillmentStatus::Reverted,
            None,
            false,
        )
        .unwrap_err();
        let net = err.downcast_ref::<Error>().expect("network error");
        assert!(matches!(net, Error::RequestReverted { .. }));
        assert!(net.to_string().contains("failed during settlement"));
    }

    #[test]
    fn expired_maps_to_request_expired() {
        let err = decide_status_outcome(
            rid(),
            ExecutionStatus::Executed,
            FulfillmentStatus::Expired,
            None,
            false,
        )
        .unwrap_err();
        let net = err.downcast_ref::<Error>().expect("network error");
        assert!(matches!(net, Error::RequestExpired { .. }));
        assert!(net.to_string().contains("expired"));
    }

    #[test]
    fn deadline_exceeded_maps_to_request_timed_out_for_in_progress_states() {
        for fs in [
            FulfillmentStatus::UnspecifiedFulfillmentStatus,
            FulfillmentStatus::Requested,
            FulfillmentStatus::Assigned,
        ] {
            let err = decide_status_outcome(rid(), ExecutionStatus::Executed, fs, None, true)
                .unwrap_err();
            assert!(
                matches!(err.downcast_ref::<Error>(), Some(Error::RequestTimedOut { .. })),
                "fs={fs:?} should map to RequestTimedOut when deadline exceeded",
            );
        }
    }

    #[test]
    fn polling_states_return_ok_with_status() {
        for fs in [
            FulfillmentStatus::UnspecifiedFulfillmentStatus,
            FulfillmentStatus::Requested,
            FulfillmentStatus::Assigned,
        ] {
            let (proof, status) =
                decide_status_outcome(rid(), ExecutionStatus::Executed, fs, None, false).unwrap();
            assert!(proof.is_none());
            assert_eq!(status, fs);
        }
    }

    #[test]
    fn ha_fallback_retries_expired_but_not_reverted() {
        let request_id = rid().to_vec();
        // Expired joins the existing retryable set.
        assert!(should_retry_with_ha_fallback(&Error::RequestExpired {
            request_id: request_id.clone()
        }));
        assert!(should_retry_with_ha_fallback(&Error::RequestUnfulfillable {
            request_id: request_id.clone()
        }));
        assert!(should_retry_with_ha_fallback(&Error::RequestTimedOut {
            request_id: request_id.clone()
        }));
        assert!(should_retry_with_ha_fallback(&Error::RequestAuctionTimedOut {
            request_id: request_id.clone()
        }));
        // Settlement failures stay terminal by default; retry policy needs caller context.
        assert!(!should_retry_with_ha_fallback(&Error::RequestReverted {
            request_id: request_id.clone()
        }));
        // RequestUnexecutable also stays out of the retry set (pre-existing behavior).
        assert!(!should_retry_with_ha_fallback(&Error::RequestUnexecutable { request_id }));
    }

    #[test]
    fn error_display_strings_for_new_variants() {
        let request_id = vec![0xde, 0xad, 0xbe, 0xef];
        let reverted = Error::RequestReverted { request_id: request_id.clone() }.to_string();
        assert_eq!(reverted, "Proof request 0xdeadbeef failed during settlement");
        let expired = Error::RequestExpired { request_id }.to_string();
        assert_eq!(expired, "Proof request 0xdeadbeef expired before a proof was submitted");
    }
}