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