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