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_BYTES, Address};
5use solana_client::nonblocking::rpc_client::RpcClient;
6use solana_loader_v3_interface::state::UpgradeableLoaderState;
7use solana_sdk_ids::bpf_loader_upgradeable;
8use thiserror::Error;
9use tokio_retry::{
10    Retry,
11    strategy::{ExponentialBackoff, jitter},
12};
13use tracing::warn;
14
15use crate::error::err_chain;
16
17const MODIFY_RPC_RETRIES: usize = 10;
18// `ExponentialBackoff::from_millis(base)` multiplies `current` by `base` each
19// step, so naive `from_millis(500)` blows up to multi-minute waits within a
20// few iterations. Use `from_millis(2).factor(500)` for a 2x ramp scaled to
21// 1s/2s/4s/8s..., capped by `MODIFY_RPC_MAX_DELAY` so total worst-case wait
22// stays well under the server's session disconnect timeout.
23const MODIFY_RPC_BACKOFF_BASE: u64 = 2;
24const MODIFY_RPC_BACKOFF_FACTOR_MS: u64 = 500;
25const MODIFY_RPC_MAX_DELAY: Duration = Duration::from_secs(10);
26
27/// Error returned by [`BacktestSession::modify_program`](crate::BacktestSession::modify_program).
28#[derive(Debug, Error)]
29pub enum ProgramModError {
30    #[error("session has no rpc_endpoint (was the session created?)")]
31    NoRpcEndpoint,
32
33    #[error("invalid program id `{id}`")]
34    InvalidProgramId { id: String },
35
36    #[error("RPC error: {source}")]
37    Rpc {
38        #[source]
39        source: Box<dyn std::error::Error + Send + Sync>,
40    },
41}
42
43/// Build a BPF Loader Upgradeable `ProgramData` account modification from raw ELF bytes.
44///
45/// Returns a map of `{programdata_address: AccountData}` ready to pass to
46/// [`Continue::builder().modify_accounts(...)`](crate::Continue).
47///
48/// The ELF is wrapped in the standard `ProgramData` header, always
49/// `UpgradeableLoaderState::size_of_programdata_metadata()` (45) bytes because the loader
50/// reads the ELF from that fixed offset:
51/// ```text
52/// [0..4]    variant = 3  (u32 LE, UpgradeableLoaderState::ProgramData)
53/// [4..12]   deploy_slot  (u64 LE)
54/// [12]      upgrade_authority discriminant (0 = None, 1 = Some)
55/// [13..45]  upgrade_authority pubkey bytes (zeroed when None)
56/// [45..]    ELF bytecode
57/// ```
58///
59/// `deploy_slot` should be set to `start_slot.saturating_sub(1)` so the program
60/// appears deployed *before* the first executed slot. Deploying at `start_slot`
61/// itself triggers the SVM's same-slot restriction, marking the program unloaded.
62///
63/// `lamports` must be at least rent-exempt for the resulting `45 + elf.len()` bytes.
64/// Fetch the exact minimum with
65/// `rpc.get_minimum_balance_for_rent_exemption(data_len).await?`.
66///
67/// ## Example
68///
69/// ```no_run
70/// use simulator_client::build_program_injection;
71/// use solana_address::Address;
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 modification, fetching the deploy slot and rent
138/// exemption from the given RPC client.
139///
140/// Equivalent to [`BacktestSession::modify_program`](crate::BacktestSession::modify_program)
141/// but usable without holding a session — pass any RPC client that can see the
142/// current cluster state.
143pub async fn modify_program_via_rpc(
144    rpc: &RpcClient,
145    program_id: &str,
146    elf: &[u8],
147) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
148    let program_addr: Address =
149        program_id
150            .parse()
151            .map_err(|_| ProgramModError::InvalidProgramId {
152                id: program_id.to_string(),
153            })?;
154    let programdata_addr = solana_loader_v3_interface::get_program_data_address(&program_addr);
155
156    let strategy = ExponentialBackoff::from_millis(MODIFY_RPC_BACKOFF_BASE)
157        .factor(MODIFY_RPC_BACKOFF_FACTOR_MS)
158        .max_delay(MODIFY_RPC_MAX_DELAY)
159        .map(jitter)
160        .take(MODIFY_RPC_RETRIES);
161
162    Retry::start(strategy, || async {
163        modify_program_via_rpc_once(rpc, programdata_addr, elf)
164            .await
165            .inspect_err(|e| {
166                warn!(
167                    program_id,
168                    error = %err_chain(e),
169                    "modify_program_via_rpc attempt failed"
170                )
171            })
172    })
173    .await
174}
175
176async fn modify_program_via_rpc_once(
177    rpc: &RpcClient,
178    programdata_addr: Address,
179    elf: &[u8],
180) -> Result<BTreeMap<Address, AccountData>, ProgramModError> {
181    let slot = rpc.get_slot().await.map_err(|e| ProgramModError::Rpc {
182        source: Box::new(e),
183    })?;
184    let deploy_slot = slot.saturating_sub(1);
185
186    let existing = rpc
187        .get_account(&programdata_addr)
188        .await
189        .map_err(|e| ProgramModError::Rpc {
190            source: Box::new(e),
191        })?;
192
193    let upgrade_authority = if existing.data.get(12).copied() == Some(1) {
194        existing.data.get(13..45).and_then(|b| {
195            let bytes: [u8; 32] = b.try_into().ok()?;
196            Some(Address::from(bytes))
197        })
198    } else {
199        None
200    };
201
202    let data_len = UpgradeableLoaderState::size_of_programdata(elf.len());
203    let lamports = rpc
204        .get_minimum_balance_for_rent_exemption(data_len)
205        .await
206        .map_err(|e| ProgramModError::Rpc {
207            source: Box::new(e),
208        })?;
209
210    Ok(build_program_injection(
211        programdata_addr,
212        elf,
213        deploy_slot,
214        upgrade_authority,
215        lamports,
216    ))
217}
218
219#[cfg(test)]
220mod tests {
221    use std::net::Ipv4Addr;
222
223    use axum::{Json, Router, routing::post};
224    use base64::{Engine, prelude::BASE64_STANDARD};
225    use rstest::rstest;
226    use serde_json::{Value, json};
227    use solana_account_decoder::parse_bpf_loader::{
228        BpfUpgradeableLoaderAccountType, UiProgramData, parse_bpf_upgradeable_loader,
229    };
230
231    use super::*;
232
233    const ELF: &[u8] = b"\x7fELF program bytes";
234    const DEPLOY_SLOT: u64 = 399_834_991;
235    const AUTHORITY: Address = Address::new_from_array([7; 32]);
236    const PROGRAMDATA: Address = Address::new_from_array([9; 32]);
237
238    #[rstest]
239    #[case::no_authority(None)]
240    #[case::authority(Some(AUTHORITY))]
241    fn programdata_holds_the_elf_at_the_loaders_offset(#[case] authority: Option<Address>) {
242        let data = build_programdata_bytes(ELF, DEPLOY_SLOT, authority.as_ref());
243
244        let Ok(BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
245            slot,
246            authority: parsed_authority,
247            ..
248        })) = parse_bpf_upgradeable_loader(&data)
249        else {
250            panic!("not a ProgramData account");
251        };
252        assert_eq!(slot, DEPLOY_SLOT);
253        assert_eq!(parsed_authority, authority.map(|a| a.to_string()));
254        assert_eq!(
255            data.get(UpgradeableLoaderState::size_of_programdata_metadata()..),
256            Some(ELF)
257        );
258    }
259
260    /// A JSON-RPC node holding `programdata` whose rent for a data length is that length.
261    async fn start_stub_rpc(programdata: Vec<u8>) -> RpcClient {
262        let account = json!({
263            "data": [BASE64_STANDARD.encode(programdata), "base64"],
264            "executable": false,
265            "lamports": 1,
266            "owner": bpf_loader_upgradeable::ID.to_string(),
267            "rentEpoch": 0,
268        });
269        let answer = move |Json(request): Json<Value>| {
270            let result = match request["method"].as_str() {
271                Some("getSlot") => json!(DEPLOY_SLOT),
272                Some("getAccountInfo") => json!({ "context": { "slot": 1 }, "value": account }),
273                Some("getMinimumBalanceForRentExemption") => request["params"][0].clone(),
274                method => panic!("unexpected RPC call {method:?}"),
275            };
276            async move { Json(json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })) }
277        };
278        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
279            .await
280            .expect("bind stub RPC");
281        let address = listener.local_addr().expect("stub address");
282        tokio::spawn(async move {
283            let _ = axum::serve(listener, Router::new().route("/", post(answer))).await;
284        });
285        RpcClient::new(format!("http://{address}"))
286    }
287
288    #[tokio::test]
289    async fn rpc_injection_is_rent_exempt_for_its_own_size() {
290        let rpc = start_stub_rpc(build_programdata_bytes(ELF, 0, None)).await;
291
292        let injection = modify_program_via_rpc_once(&rpc, PROGRAMDATA, ELF)
293            .await
294            .expect("build the injection");
295
296        let account = &injection[&PROGRAMDATA];
297        assert_eq!(account.lamports, account.space);
298    }
299}