sp1_sdk/network/
utils.rs

1//! # Network Utils
2//!
3//! This module provides utility functions for the network module.
4
5#![allow(deprecated)]
6
7use anyhow::Result;
8use prost::Message;
9
10use std::cmp::{max, min};
11
12use super::signer::NetworkSigner;
13
14/// Trait for signing network protobuf messages.
15pub(crate) trait Signable: Message {
16    async fn sign(&self, signer: &NetworkSigner) -> Result<Vec<u8>>;
17}
18
19impl<T: Message> Signable for T {
20    async fn sign(&self, signer: &NetworkSigner) -> Result<Vec<u8>> {
21        let signature = signer.sign_message(self.encode_to_vec().as_slice()).await?;
22        Ok(signature.as_bytes().to_vec())
23    }
24}
25
26/// Sign a message and return the raw signature object.
27pub(crate) async fn sign_raw(
28    message: &[u8],
29    signer: &NetworkSigner,
30) -> Result<alloy_primitives::Signature> {
31    Ok(signer.sign_message(message).await?)
32}
33
34/// Sign a message and return signature bytes with Ethereum-style recovery ID.
35pub(crate) async fn sign_message(message: &[u8], signer: &NetworkSigner) -> Result<Vec<u8>> {
36    let signature = signer.sign_message(message).await?;
37    let bytes = signature.as_bytes();
38
39    // Extract r,s (first 64 bytes) and v (last byte).
40    let mut signature_bytes = bytes[..64].to_vec();
41    let v = bytes[64];
42
43    // Ethereum uses 27 + v for the recovery id.
44    signature_bytes.push(v + 27);
45
46    Ok(signature_bytes)
47}
48
49/// Calculate the timeout for a proof request based on gas limit.
50///
51/// Uses a base timeout of 5 minutes plus 1 second per 2000000 prover gas. The timeout is capped at
52/// 4 hours.
53pub(crate) fn calculate_timeout_from_gas_limit(gas_limit: u64) -> u64 {
54    let base_timeout = 300; // 5 minutes
55    let gas_based_timeout = gas_limit / 2_000_000;
56    min(max(base_timeout, gas_based_timeout), 14400)
57}
58
59/// Get the default RPC URL for the given network mode.
60#[must_use]
61pub fn get_default_rpc_url_for_mode(network_mode: super::NetworkMode) -> String {
62    match network_mode {
63        super::NetworkMode::Mainnet => super::MAINNET_RPC_URL.to_string(),
64        super::NetworkMode::Reserved => super::RESERVED_RPC_URL.to_string(),
65    }
66}
67
68/// Get the explorer URL for the given network mode.
69#[must_use]
70pub fn get_explorer_url_for_mode(network_mode: super::NetworkMode) -> &'static str {
71    match network_mode {
72        super::NetworkMode::Mainnet => super::MAINNET_EXPLORER_URL,
73        super::NetworkMode::Reserved => super::RESERVED_EXPLORER_URL,
74    }
75}
76
77/// Get the default cycle limit for the given network mode.
78#[must_use]
79pub fn get_default_cycle_limit_for_mode(network_mode: super::NetworkMode) -> u64 {
80    match network_mode {
81        super::NetworkMode::Mainnet => super::MAINNET_DEFAULT_CYCLE_LIMIT,
82        super::NetworkMode::Reserved => super::RESERVED_DEFAULT_CYCLE_LIMIT,
83    }
84}