simulator_client/
injection.rs1use 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;
17const 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#[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
42pub 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
104pub 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 data.extend_from_slice(&3u32.to_le_bytes());
119 data.extend_from_slice(&deploy_slot.to_le_bytes());
121
122 match upgrade_authority {
123 None => {
124 data.push(0); }
126 Some(authority) => {
127 data.push(1); data.extend_from_slice(authority.as_ref());
129 }
130 }
131
132 data.extend_from_slice(elf);
133 data
134}
135
136pub 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}