simulator-client 0.30.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! Program overrides: swap a program's binary for your own ELF in a running session.
//!
//! [`modify_program_via_rpc`] reads the deploy slot, the existing upgrade authority and the
//! rent-exempt minimum from the session's RPC endpoint, then returns an account override to send
//! in a [`Continue`](crate::Continue). It retries failed RPC calls up to 10 times with jittered
//! exponential backoff, at most 10 s apart. [`build_program_injection`] builds the same
//! override offline when you already know those values.

use std::{collections::BTreeMap, time::Duration};

use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
use solana_address::{ADDRESS_BYTES, Address};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_loader_v3_interface::state::UpgradeableLoaderState;
use solana_sdk_ids::bpf_loader_upgradeable;
use thiserror::Error;
use tokio_retry::{
    Retry,
    strategy::{ExponentialBackoff, jitter},
};
use tracing::warn;

use crate::error::err_chain;

const MODIFY_RPC_RETRIES: usize = 10;
// `ExponentialBackoff::from_millis(base)` multiplies `current` by `base` each
// step, so naive `from_millis(500)` blows up to multi-minute waits within a
// few iterations. Use `from_millis(2).factor(500)` for a 2x ramp scaled to
// 1s/2s/4s/8s..., capped by `MODIFY_RPC_MAX_DELAY` so total worst-case wait
// stays well under the server's session disconnect timeout.
const MODIFY_RPC_BACKOFF_BASE: u64 = 2;
const MODIFY_RPC_BACKOFF_FACTOR_MS: u64 = 500;
const MODIFY_RPC_MAX_DELAY: Duration = Duration::from_secs(10);

/// Error returned by [`modify_program_via_rpc`].
#[derive(Debug, Error)]
#[allow(missing_docs)]
pub enum ProgramModError {
    /// The program ID is not a base58 address. Stop: fix the ID.
    #[error("invalid program id `{id}`")]
    InvalidProgramId { id: String },

    /// An RPC call still failed after every retry, for example because the program has no
    /// `ProgramData` account in the session.
    #[error("RPC error: {source}")]
    Rpc {
        /// The last RPC error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
}

/// Build a BPF Loader Upgradeable `ProgramData` account override from raw ELF bytes.
///
/// Returns a map of `{programdata_address: AccountData}` ready to pass to
/// [`Continue::builder().modify_accounts(...)`](crate::Continue).
///
/// The ELF is wrapped in the standard `ProgramData` header, always
/// `UpgradeableLoaderState::size_of_programdata_metadata()` (45) bytes because the loader
/// reads the ELF from that fixed offset:
/// ```text
/// [0..4]    variant = 3  (u32 LE, UpgradeableLoaderState::ProgramData)
/// [4..12]   deploy_slot  (u64 LE)
/// [12]      upgrade_authority discriminant (0 = None, 1 = Some)
/// [13..45]  upgrade_authority pubkey bytes (zeroed when None)
/// [45..]    ELF program binary
/// ```
///
/// `deploy_slot` should be set to `start_slot.saturating_sub(1)` so the program
/// appears deployed *before* the first executed slot. Deploying at `start_slot`
/// itself triggers the SVM's same-slot restriction, marking the program unloaded.
///
/// `lamports` must be at least rent-exempt for the resulting `45 + elf.len()` bytes.
/// Fetch the exact minimum with
/// `rpc.get_minimum_balance_for_rent_exemption(data_len).await?`.
///
/// ## Example
///
/// ```no_run
/// use simulator_client::{Address, build_program_injection};
///
/// let program_id: Address = "YourProgramId...".parse().unwrap();
/// // Compute the programdata PDA using solana_loader_v3_interface::get_program_data_address,
/// // then convert to Address.
/// let programdata_addr: Address = "ProgramDataAddr...".parse().unwrap();
/// let elf = std::fs::read("my_program.so").unwrap();
/// let deploy_slot = 399_834_991; // start_slot - 1
///
/// let mods = build_program_injection(programdata_addr, &elf, deploy_slot, None, 10_000_000_000);
/// // Pass mods to Continue::builder().modify_accounts(mods).build()
/// ```
pub fn build_program_injection(
    programdata_address: Address,
    elf: &[u8],
    deploy_slot: u64,
    upgrade_authority: Option<Address>,
    lamports: u64,
) -> BTreeMap<Address, AccountData> {
    let data = build_programdata_bytes(elf, deploy_slot, upgrade_authority.as_ref());

    let account = AccountData {
        space: data.len() as u64,
        data: EncodedBinary::from_bytes(&data, BinaryEncoding::Base64),
        executable: false,
        lamports,
        owner: bpf_loader_upgradeable::ID,
    };

    let mut map = BTreeMap::new();
    map.insert(programdata_address, account);
    map
}

/// Serialize ELF bytes into a `ProgramData` account data blob.
///
/// Exposed as a building block if you need to construct the account yourself
/// (e.g. to set a custom lamport amount after calling
/// `rpc.get_minimum_balance_for_rent_exemption`).
pub fn build_programdata_bytes(
    elf: &[u8],
    deploy_slot: u64,
    upgrade_authority: Option<&Address>,
) -> Vec<u8> {
    let mut data = Vec::with_capacity(UpgradeableLoaderState::size_of_programdata(elf.len()));

    // variant = 3 (UpgradeableLoaderState::ProgramData)
    data.extend_from_slice(&3u32.to_le_bytes());
    // deployment slot
    data.extend_from_slice(&deploy_slot.to_le_bytes());

    match upgrade_authority {
        None => {
            data.push(0); // Option::None
            data.extend_from_slice(&[0; ADDRESS_BYTES]);
        }
        Some(authority) => {
            data.push(1); // Option::Some
            data.extend_from_slice(authority.as_ref());
        }
    }

    data.extend_from_slice(elf);
    data
}

/// Build a program-data account override, fetching the deploy slot and rent
/// exemption from the given RPC client.
///
/// Pass any RPC client that can see the current cluster state, such as
/// [`ManagedBacktestSession::rpc`](crate::ManagedBacktestSession::rpc).
///
/// # Errors
///
/// [`ProgramModError::InvalidProgramId`] at once, or [`ProgramModError::Rpc`] once the
/// retries run out.
pub async fn modify_program_via_rpc(
    rpc: &RpcClient,
    program_id: &str,
    elf: &[u8],
) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
    let program_addr: Address =
        program_id
            .parse()
            .map_err(|_| ProgramModError::InvalidProgramId {
                id: program_id.to_string(),
            })?;
    let programdata_addr = solana_loader_v3_interface::get_program_data_address(&program_addr);

    let strategy = ExponentialBackoff::from_millis(MODIFY_RPC_BACKOFF_BASE)
        .factor(MODIFY_RPC_BACKOFF_FACTOR_MS)
        .max_delay(MODIFY_RPC_MAX_DELAY)
        .map(jitter)
        .take(MODIFY_RPC_RETRIES);

    Retry::start(strategy, || async {
        modify_program_via_rpc_once(rpc, programdata_addr, elf)
            .await
            .inspect_err(|e| {
                warn!(
                    program_id,
                    error = %err_chain(e),
                    "modify_program_via_rpc attempt failed"
                )
            })
    })
    .await
}

async fn modify_program_via_rpc_once(
    rpc: &RpcClient,
    programdata_addr: Address,
    elf: &[u8],
) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
    let slot = rpc.get_slot().await.map_err(|e| ProgramModError::Rpc {
        source: Box::new(e),
    })?;
    let deploy_slot = slot.saturating_sub(1);

    let existing = rpc
        .get_account(&programdata_addr)
        .await
        .map_err(|e| ProgramModError::Rpc {
            source: Box::new(e),
        })?;

    let upgrade_authority = if existing.data.get(12).copied() == Some(1) {
        existing.data.get(13..45).and_then(|b| {
            let bytes: [u8; 32] = b.try_into().ok()?;
            Some(Address::from(bytes))
        })
    } else {
        None
    };

    let data_len = UpgradeableLoaderState::size_of_programdata(elf.len());
    let lamports = rpc
        .get_minimum_balance_for_rent_exemption(data_len)
        .await
        .map_err(|e| ProgramModError::Rpc {
            source: Box::new(e),
        })?;

    Ok(build_program_injection(
        programdata_addr,
        elf,
        deploy_slot,
        upgrade_authority,
        lamports,
    ))
}

#[cfg(test)]
mod tests {
    use std::net::Ipv4Addr;

    use axum::{Json, Router, routing::post};
    use base64::{Engine, prelude::BASE64_STANDARD};
    use rstest::rstest;
    use serde_json::{Value, json};
    use solana_account_decoder::parse_bpf_loader::{
        BpfUpgradeableLoaderAccountType, UiProgramData, parse_bpf_upgradeable_loader,
    };

    use super::*;

    const ELF: &[u8] = b"\x7fELF program bytes";
    const DEPLOY_SLOT: u64 = 399_834_991;
    const AUTHORITY: Address = Address::new_from_array([7; 32]);
    const PROGRAMDATA: Address = Address::new_from_array([9; 32]);

    #[rstest]
    #[case::no_authority(None)]
    #[case::authority(Some(AUTHORITY))]
    fn programdata_holds_the_elf_at_the_loaders_offset(#[case] authority: Option<Address>) {
        let data = build_programdata_bytes(ELF, DEPLOY_SLOT, authority.as_ref());

        let Ok(BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
            slot,
            authority: parsed_authority,
            ..
        })) = parse_bpf_upgradeable_loader(&data)
        else {
            panic!("not a ProgramData account");
        };
        assert_eq!(slot, DEPLOY_SLOT);
        assert_eq!(parsed_authority, authority.map(|a| a.to_string()));
        assert_eq!(
            data.get(UpgradeableLoaderState::size_of_programdata_metadata()..),
            Some(ELF)
        );
    }

    /// A JSON-RPC node holding `programdata` whose rent for a data length is that length.
    async fn start_stub_rpc(programdata: Vec<u8>) -> RpcClient {
        let account = json!({
            "data": [BASE64_STANDARD.encode(programdata), "base64"],
            "executable": false,
            "lamports": 1,
            "owner": bpf_loader_upgradeable::ID.to_string(),
            "rentEpoch": 0,
        });
        let answer = move |Json(request): Json<Value>| {
            let result = match request["method"].as_str() {
                Some("getSlot") => json!(DEPLOY_SLOT),
                Some("getAccountInfo") => json!({ "context": { "slot": 1 }, "value": account }),
                Some("getMinimumBalanceForRentExemption") => request["params"][0].clone(),
                method => panic!("unexpected RPC call {method:?}"),
            };
            async move { Json(json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })) }
        };
        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
            .await
            .expect("bind stub RPC");
        let address = listener.local_addr().expect("stub address");
        tokio::spawn(async move {
            let _ = axum::serve(listener, Router::new().route("/", post(answer))).await;
        });
        RpcClient::new(format!("http://{address}"))
    }

    #[tokio::test]
    async fn rpc_injection_is_rent_exempt_for_its_own_size() {
        let rpc = start_stub_rpc(build_programdata_bytes(ELF, 0, None)).await;

        let injection = modify_program_via_rpc_once(&rpc, PROGRAMDATA, ELF)
            .await
            .expect("build the injection");

        let account = &injection[&PROGRAMDATA];
        assert_eq!(account.lamports, account.space);
    }
}