Skip to main content

simulator_client/
injection.rs

1//! Program overrides: swap a program's binary for your own ELF in a running session.
2//!
3//! [`modify_program_via_rpc`] reads the deploy slot, the existing upgrade authority and the
4//! rent-exempt minimum from the session's RPC endpoint, then returns an account override to send
5//! in a [`Continue`](crate::Continue). It retries failed RPC calls up to 10 times with jittered
6//! exponential backoff, at most 10 s apart. [`build_program_injection`] builds the same
7//! override offline when you already know those values.
8
9use std::{collections::BTreeMap, time::Duration};
10
11use simulator_api::{AccountData, BinaryEncoding, EncodedBinary};
12use solana_address::{ADDRESS_BYTES, Address};
13use solana_client::nonblocking::rpc_client::RpcClient;
14use solana_loader_v3_interface::state::UpgradeableLoaderState;
15use solana_sdk_ids::bpf_loader_upgradeable;
16use thiserror::Error;
17use tokio_retry::{
18    Retry,
19    strategy::{ExponentialBackoff, jitter},
20};
21use tracing::warn;
22
23use crate::error::err_chain;
24
25const MODIFY_RPC_RETRIES: usize = 10;
26// `ExponentialBackoff::from_millis(base)` multiplies `current` by `base` each
27// step, so naive `from_millis(500)` blows up to multi-minute waits within a
28// few iterations. Use `from_millis(2).factor(500)` for a 2x ramp scaled to
29// 1s/2s/4s/8s..., capped by `MODIFY_RPC_MAX_DELAY` so total worst-case wait
30// stays well under the server's session disconnect timeout.
31const MODIFY_RPC_BACKOFF_BASE: u64 = 2;
32const MODIFY_RPC_BACKOFF_FACTOR_MS: u64 = 500;
33const MODIFY_RPC_MAX_DELAY: Duration = Duration::from_secs(10);
34
35/// Error returned by [`modify_program_via_rpc`].
36#[derive(Debug, Error)]
37#[allow(missing_docs)]
38pub enum ProgramModError {
39    /// The session has no RPC endpoint. Every created session has one.
40    #[error("session has no rpc_endpoint (was the session created?)")]
41    NoRpcEndpoint,
42
43    /// The program ID is not a base58 address. Stop: fix the ID.
44    #[error("invalid program id `{id}`")]
45    InvalidProgramId { id: String },
46
47    /// An RPC call still failed after every retry, for example because the program has no
48    /// `ProgramData` account in the session.
49    #[error("RPC error: {source}")]
50    Rpc {
51        /// The last RPC error.
52        #[source]
53        source: Box<dyn std::error::Error + Send + Sync>,
54    },
55}
56
57/// Build a BPF Loader Upgradeable `ProgramData` account override from raw ELF bytes.
58///
59/// Returns a map of `{programdata_address: AccountData}` ready to pass to
60/// [`Continue::builder().modify_accounts(...)`](crate::Continue).
61///
62/// The ELF is wrapped in the standard `ProgramData` header, always
63/// `UpgradeableLoaderState::size_of_programdata_metadata()` (45) bytes because the loader
64/// reads the ELF from that fixed offset:
65/// ```text
66/// [0..4]    variant = 3  (u32 LE, UpgradeableLoaderState::ProgramData)
67/// [4..12]   deploy_slot  (u64 LE)
68/// [12]      upgrade_authority discriminant (0 = None, 1 = Some)
69/// [13..45]  upgrade_authority pubkey bytes (zeroed when None)
70/// [45..]    ELF program binary
71/// ```
72///
73/// `deploy_slot` should be set to `start_slot.saturating_sub(1)` so the program
74/// appears deployed *before* the first executed slot. Deploying at `start_slot`
75/// itself triggers the SVM's same-slot restriction, marking the program unloaded.
76///
77/// `lamports` must be at least rent-exempt for the resulting `45 + elf.len()` bytes.
78/// Fetch the exact minimum with
79/// `rpc.get_minimum_balance_for_rent_exemption(data_len).await?`.
80///
81/// ## Example
82///
83/// ```no_run
84/// use simulator_client::{Address, build_program_injection};
85///
86/// let program_id: Address = "YourProgramId...".parse().unwrap();
87/// // Compute the programdata PDA using solana_loader_v3_interface::get_program_data_address,
88/// // then convert to Address.
89/// let programdata_addr: Address = "ProgramDataAddr...".parse().unwrap();
90/// let elf = std::fs::read("my_program.so").unwrap();
91/// let deploy_slot = 399_834_991; // start_slot - 1
92///
93/// let mods = build_program_injection(programdata_addr, &elf, deploy_slot, None, 10_000_000_000);
94/// // Pass mods to Continue::builder().modify_accounts(mods).build()
95/// ```
96pub fn build_program_injection(
97    programdata_address: Address,
98    elf: &[u8],
99    deploy_slot: u64,
100    upgrade_authority: Option<Address>,
101    lamports: u64,
102) -> BTreeMap<Address, AccountData> {
103    let data = build_programdata_bytes(elf, deploy_slot, upgrade_authority.as_ref());
104
105    let account = AccountData {
106        space: data.len() as u64,
107        data: EncodedBinary::from_bytes(&data, BinaryEncoding::Base64),
108        executable: false,
109        lamports,
110        owner: bpf_loader_upgradeable::ID,
111    };
112
113    let mut map = BTreeMap::new();
114    map.insert(programdata_address, account);
115    map
116}
117
118/// Serialize ELF bytes into a `ProgramData` account data blob.
119///
120/// Exposed as a building block if you need to construct the account yourself
121/// (e.g. to set a custom lamport amount after calling
122/// `rpc.get_minimum_balance_for_rent_exemption`).
123pub fn build_programdata_bytes(
124    elf: &[u8],
125    deploy_slot: u64,
126    upgrade_authority: Option<&Address>,
127) -> Vec<u8> {
128    let mut data = Vec::with_capacity(UpgradeableLoaderState::size_of_programdata(elf.len()));
129
130    // variant = 3 (UpgradeableLoaderState::ProgramData)
131    data.extend_from_slice(&3u32.to_le_bytes());
132    // deployment slot
133    data.extend_from_slice(&deploy_slot.to_le_bytes());
134
135    match upgrade_authority {
136        None => {
137            data.push(0); // Option::None
138            data.extend_from_slice(&[0; ADDRESS_BYTES]);
139        }
140        Some(authority) => {
141            data.push(1); // Option::Some
142            data.extend_from_slice(authority.as_ref());
143        }
144    }
145
146    data.extend_from_slice(elf);
147    data
148}
149
150/// Build a program-data account override, fetching the deploy slot and rent
151/// exemption from the given RPC client.
152///
153/// Pass any RPC client that can see the current cluster state, such as
154/// [`ManagedBacktestSession::rpc`](crate::ManagedBacktestSession::rpc).
155///
156/// # Errors
157///
158/// [`ProgramModError::InvalidProgramId`] at once, or [`ProgramModError::Rpc`] once the
159/// retries run out.
160pub async fn modify_program_via_rpc(
161    rpc: &RpcClient,
162    program_id: &str,
163    elf: &[u8],
164) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
165    let program_addr: Address =
166        program_id
167            .parse()
168            .map_err(|_| ProgramModError::InvalidProgramId {
169                id: program_id.to_string(),
170            })?;
171    let programdata_addr = solana_loader_v3_interface::get_program_data_address(&program_addr);
172
173    let strategy = ExponentialBackoff::from_millis(MODIFY_RPC_BACKOFF_BASE)
174        .factor(MODIFY_RPC_BACKOFF_FACTOR_MS)
175        .max_delay(MODIFY_RPC_MAX_DELAY)
176        .map(jitter)
177        .take(MODIFY_RPC_RETRIES);
178
179    Retry::start(strategy, || async {
180        modify_program_via_rpc_once(rpc, programdata_addr, elf)
181            .await
182            .inspect_err(|e| {
183                warn!(
184                    program_id,
185                    error = %err_chain(e),
186                    "modify_program_via_rpc attempt failed"
187                )
188            })
189    })
190    .await
191}
192
193async fn modify_program_via_rpc_once(
194    rpc: &RpcClient,
195    programdata_addr: Address,
196    elf: &[u8],
197) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
198    let slot = rpc.get_slot().await.map_err(|e| ProgramModError::Rpc {
199        source: Box::new(e),
200    })?;
201    let deploy_slot = slot.saturating_sub(1);
202
203    let existing = rpc
204        .get_account(&programdata_addr)
205        .await
206        .map_err(|e| ProgramModError::Rpc {
207            source: Box::new(e),
208        })?;
209
210    let upgrade_authority = if existing.data.get(12).copied() == Some(1) {
211        existing.data.get(13..45).and_then(|b| {
212            let bytes: [u8; 32] = b.try_into().ok()?;
213            Some(Address::from(bytes))
214        })
215    } else {
216        None
217    };
218
219    let data_len = UpgradeableLoaderState::size_of_programdata(elf.len());
220    let lamports = rpc
221        .get_minimum_balance_for_rent_exemption(data_len)
222        .await
223        .map_err(|e| ProgramModError::Rpc {
224            source: Box::new(e),
225        })?;
226
227    Ok(build_program_injection(
228        programdata_addr,
229        elf,
230        deploy_slot,
231        upgrade_authority,
232        lamports,
233    ))
234}
235
236#[cfg(test)]
237mod tests {
238    use std::net::Ipv4Addr;
239
240    use axum::{Json, Router, routing::post};
241    use base64::{Engine, prelude::BASE64_STANDARD};
242    use rstest::rstest;
243    use serde_json::{Value, json};
244    use solana_account_decoder::parse_bpf_loader::{
245        BpfUpgradeableLoaderAccountType, UiProgramData, parse_bpf_upgradeable_loader,
246    };
247
248    use super::*;
249
250    const ELF: &[u8] = b"\x7fELF program bytes";
251    const DEPLOY_SLOT: u64 = 399_834_991;
252    const AUTHORITY: Address = Address::new_from_array([7; 32]);
253    const PROGRAMDATA: Address = Address::new_from_array([9; 32]);
254
255    #[rstest]
256    #[case::no_authority(None)]
257    #[case::authority(Some(AUTHORITY))]
258    fn programdata_holds_the_elf_at_the_loaders_offset(#[case] authority: Option<Address>) {
259        let data = build_programdata_bytes(ELF, DEPLOY_SLOT, authority.as_ref());
260
261        let Ok(BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
262            slot,
263            authority: parsed_authority,
264            ..
265        })) = parse_bpf_upgradeable_loader(&data)
266        else {
267            panic!("not a ProgramData account");
268        };
269        assert_eq!(slot, DEPLOY_SLOT);
270        assert_eq!(parsed_authority, authority.map(|a| a.to_string()));
271        assert_eq!(
272            data.get(UpgradeableLoaderState::size_of_programdata_metadata()..),
273            Some(ELF)
274        );
275    }
276
277    /// A JSON-RPC node holding `programdata` whose rent for a data length is that length.
278    async fn start_stub_rpc(programdata: Vec<u8>) -> RpcClient {
279        let account = json!({
280            "data": [BASE64_STANDARD.encode(programdata), "base64"],
281            "executable": false,
282            "lamports": 1,
283            "owner": bpf_loader_upgradeable::ID.to_string(),
284            "rentEpoch": 0,
285        });
286        let answer = move |Json(request): Json<Value>| {
287            let result = match request["method"].as_str() {
288                Some("getSlot") => json!(DEPLOY_SLOT),
289                Some("getAccountInfo") => json!({ "context": { "slot": 1 }, "value": account }),
290                Some("getMinimumBalanceForRentExemption") => request["params"][0].clone(),
291                method => panic!("unexpected RPC call {method:?}"),
292            };
293            async move { Json(json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })) }
294        };
295        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
296            .await
297            .expect("bind stub RPC");
298        let address = listener.local_addr().expect("stub address");
299        tokio::spawn(async move {
300            let _ = axum::serve(listener, Router::new().route("/", post(answer))).await;
301        });
302        RpcClient::new(format!("http://{address}"))
303    }
304
305    #[tokio::test]
306    async fn rpc_injection_is_rent_exempt_for_its_own_size() {
307        let rpc = start_stub_rpc(build_programdata_bytes(ELF, 0, None)).await;
308
309        let injection = modify_program_via_rpc_once(&rpc, PROGRAMDATA, ELF)
310            .await
311            .expect("build the injection");
312
313        let account = &injection[&PROGRAMDATA];
314        assert_eq!(account.lamports, account.space);
315    }
316}