Skip to main content

simulator_client/
injection.rs

1use std::{collections::BTreeMap, time::Duration};
2
3use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
4use solana_address::Address;
5use solana_client::nonblocking::rpc_client::RpcClient;
6use solana_sdk_ids::bpf_loader_upgradeable;
7use thiserror::Error;
8use tokio_retry::{
9    Retry,
10    strategy::{ExponentialBackoff, jitter},
11};
12use tracing::warn;
13
14use crate::error::err_chain;
15
16const MODIFY_RPC_RETRIES: usize = 10;
17// `ExponentialBackoff::from_millis(base)` multiplies `current` by `base` each
18// step, so naive `from_millis(500)` blows up to multi-minute waits within a
19// few iterations. Use `from_millis(2).factor(500)` for a 2x ramp scaled to
20// 1s/2s/4s/8s..., capped by `MODIFY_RPC_MAX_DELAY` so total worst-case wait
21// stays well under the server's session disconnect timeout.
22const MODIFY_RPC_BACKOFF_BASE: u64 = 2;
23const MODIFY_RPC_BACKOFF_FACTOR_MS: u64 = 500;
24const MODIFY_RPC_MAX_DELAY: Duration = Duration::from_secs(10);
25
26/// Error returned by [`BacktestSession::modify_program`](crate::BacktestSession::modify_program).
27#[derive(Debug, Error)]
28pub enum ProgramModError {
29    #[error("session has no rpc_endpoint (was the session created?)")]
30    NoRpcEndpoint,
31
32    #[error("invalid program id `{id}`")]
33    InvalidProgramId { id: String },
34
35    #[error("RPC error: {source}")]
36    Rpc {
37        #[source]
38        source: Box<dyn std::error::Error + Send + Sync>,
39    },
40}
41
42/// Build a BPF Loader Upgradeable `ProgramData` account modification from raw ELF bytes.
43///
44/// Returns a map of `{programdata_address: AccountData}` ready to pass to
45/// [`Continue::builder().modify_accounts(...)`](crate::Continue).
46///
47/// The ELF is wrapped in the standard `ProgramData` header format:
48/// ```text
49/// [0..4]    variant = 3  (u32 LE, UpgradeableLoaderState::ProgramData)
50/// [4..12]   deploy_slot  (u64 LE)
51/// [12]      upgrade_authority discriminant (0 = None, 1 = Some)
52/// [13..45]  upgrade_authority pubkey bytes (32 bytes, present only when Some)
53/// [45..]    ELF bytecode
54/// ```
55///
56/// `deploy_slot` should be set to `start_slot.saturating_sub(1)` so the program
57/// appears deployed *before* the first executed slot. Deploying at `start_slot`
58/// itself triggers the SVM's same-slot restriction, marking the program unloaded.
59///
60/// `lamports` must be at least rent-exempt for the resulting account size.
61/// With `upgrade_authority = None` the data length is `13 + elf.len()`;
62/// with `Some(authority)` it is `45 + elf.len()`.
63/// Fetch the exact minimum with
64/// `rpc.get_minimum_balance_for_rent_exemption(data_len).await?`.
65///
66/// ## Example
67///
68/// ```no_run
69/// use simulator_client::build_program_injection;
70/// use solana_address::Address;
71///
72/// let program_id: Address = "YourProgramId...".parse().unwrap();
73/// // Compute the programdata PDA using solana_loader_v3_interface::get_program_data_address,
74/// // then convert to Address.
75/// let programdata_addr: Address = "ProgramDataAddr...".parse().unwrap();
76/// let elf = std::fs::read("my_program.so").unwrap();
77/// let deploy_slot = 399_834_991; // start_slot - 1
78///
79/// let mods = build_program_injection(programdata_addr, &elf, deploy_slot, None, 10_000_000_000);
80/// // Pass mods to Continue::builder().modify_accounts(mods).build()
81/// ```
82pub fn build_program_injection(
83    programdata_address: Address,
84    elf: &[u8],
85    deploy_slot: u64,
86    upgrade_authority: Option<Address>,
87    lamports: u64,
88) -> BTreeMap<Address, AccountData> {
89    let data = build_programdata_bytes(elf, deploy_slot, upgrade_authority.as_ref());
90
91    let account = AccountData {
92        space: data.len() as u64,
93        data: EncodedBinary::from_bytes(&data, BinaryEncoding::Base64),
94        executable: false,
95        lamports,
96        owner: bpf_loader_upgradeable::ID,
97    };
98
99    let mut map = BTreeMap::new();
100    map.insert(programdata_address, account);
101    map
102}
103
104/// Serialize ELF bytes into a `ProgramData` account data blob.
105///
106/// Exposed as a building block if you need to construct the account yourself
107/// (e.g. to set a custom lamport amount after calling
108/// `rpc.get_minimum_balance_for_rent_exemption`).
109pub fn build_programdata_bytes(
110    elf: &[u8],
111    deploy_slot: u64,
112    upgrade_authority: Option<&Address>,
113) -> Vec<u8> {
114    let header_len = if upgrade_authority.is_some() { 45 } else { 13 };
115    let mut data = Vec::with_capacity(header_len + elf.len());
116
117    // variant = 3 (UpgradeableLoaderState::ProgramData)
118    data.extend_from_slice(&3u32.to_le_bytes());
119    // deployment slot
120    data.extend_from_slice(&deploy_slot.to_le_bytes());
121
122    match upgrade_authority {
123        None => {
124            data.push(0); // Option::None
125        }
126        Some(authority) => {
127            data.push(1); // Option::Some
128            data.extend_from_slice(authority.as_ref());
129        }
130    }
131
132    data.extend_from_slice(elf);
133    data
134}
135
136/// Build a program-data account modification, fetching the deploy slot and rent
137/// exemption from the given RPC client.
138///
139/// Equivalent to [`BacktestSession::modify_program`](crate::BacktestSession::modify_program)
140/// but usable without holding a session — pass any RPC client that can see the
141/// current cluster state.
142pub async fn modify_program_via_rpc(
143    rpc: &RpcClient,
144    program_id: &str,
145    elf: &[u8],
146) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
147    let program_addr: Address =
148        program_id
149            .parse()
150            .map_err(|_| ProgramModError::InvalidProgramId {
151                id: program_id.to_string(),
152            })?;
153    let programdata_addr = solana_loader_v3_interface::get_program_data_address(&program_addr);
154
155    let strategy = ExponentialBackoff::from_millis(MODIFY_RPC_BACKOFF_BASE)
156        .factor(MODIFY_RPC_BACKOFF_FACTOR_MS)
157        .max_delay(MODIFY_RPC_MAX_DELAY)
158        .map(jitter)
159        .take(MODIFY_RPC_RETRIES);
160
161    Retry::start(strategy, || async {
162        modify_program_via_rpc_once(rpc, programdata_addr, elf)
163            .await
164            .inspect_err(|e| {
165                warn!(
166                    program_id,
167                    error = %err_chain(e),
168                    "modify_program_via_rpc attempt failed"
169                )
170            })
171    })
172    .await
173}
174
175async fn modify_program_via_rpc_once(
176    rpc: &RpcClient,
177    programdata_addr: Address,
178    elf: &[u8],
179) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
180    let slot = rpc.get_slot().await.map_err(|e| ProgramModError::Rpc {
181        source: Box::new(e),
182    })?;
183    let deploy_slot = slot.saturating_sub(1);
184
185    let existing = rpc
186        .get_account(&programdata_addr)
187        .await
188        .map_err(|e| ProgramModError::Rpc {
189            source: Box::new(e),
190        })?;
191
192    let upgrade_authority = if existing.data.get(12).copied() == Some(1) {
193        existing.data.get(13..45).and_then(|b| {
194            let bytes: [u8; 32] = b.try_into().ok()?;
195            Some(Address::from(bytes))
196        })
197    } else {
198        None
199    };
200
201    let data_len = upgrade_authority.map_or(13, |_| 45) + elf.len();
202    let lamports = rpc
203        .get_minimum_balance_for_rent_exemption(data_len)
204        .await
205        .map_err(|e| ProgramModError::Rpc {
206            source: Box::new(e),
207        })?;
208
209    Ok(build_program_injection(
210        programdata_addr,
211        elf,
212        deploy_slot,
213        upgrade_authority,
214        lamports,
215    ))
216}