1#![allow(deprecated)]
2
3use std::{path::Path, str::FromStr, sync::Arc, time::Duration};
4
5use anyhow::{anyhow, bail, Context, Result};
6use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
7use serde_json::{json, Value};
8use solana_client::nonblocking::rpc_client::RpcClient;
9use solana_commitment_config::CommitmentConfig;
10use solana_loader_v3_interface::{instruction as loader_v3, state::UpgradeableLoaderState};
11use solana_sdk::{
12 instruction::Instruction,
13 message::Message,
14 pubkey::Pubkey,
15 signature::{Keypair, Signature},
16 signer::Signer,
17 transaction::Transaction,
18};
19
20const WRITE_CHUNK_SIZE: usize = 900;
21const BPF_LOADER_UPGRADEABLE: Pubkey =
22 solana_sdk::pubkey!("BPFLoaderUpgradeab1e11111111111111111111111");
23
24pub struct DeployConfig<'a> {
25 pub kora_url: &'a str,
26 pub rpc_url: &'a str,
27 pub program_so: &'a Path,
28 pub user_id: String,
29}
30
31pub struct DeployResult {
32 pub kora_pubkey: Pubkey,
33 pub program: Pubkey,
34 pub program_data: Pubkey,
35 pub buffer: Pubkey,
36}
37
38pub async fn deploy(cfg: &DeployConfig<'_>) -> Result<DeployResult> {
39 let http = reqwest::Client::builder().timeout(Duration::from_secs(60)).build()?;
40 let rpc = Arc::new(RpcClient::new_with_commitment(
41 cfg.rpc_url.to_string(),
42 CommitmentConfig::confirmed(),
43 ));
44
45 let kora_pubkey = fetch_kora_pubkey(&http, cfg.kora_url).await?;
46 let program = Keypair::new();
47 let buffer = Keypair::new();
48 let bytes = std::fs::read(cfg.program_so)
49 .with_context(|| format!("reading {}", cfg.program_so.display()))?;
50 let program_data = derive_program_data_address(&program.pubkey());
51
52 let buffer_lamports = rpc
53 .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::size_of_buffer(bytes.len()))
54 .await?;
55 let create_buf = loader_v3::create_buffer(
56 &kora_pubkey,
57 &buffer.pubkey(),
58 &kora_pubkey,
59 buffer_lamports,
60 bytes.len(),
61 )?;
62 submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &create_buf, &[&buffer]).await?;
63
64 let chunk_count = bytes.len().div_ceil(WRITE_CHUNK_SIZE);
65 for (i, chunk) in bytes.chunks(WRITE_CHUNK_SIZE).enumerate() {
66 let offset = (i * WRITE_CHUNK_SIZE) as u32;
67 let ix = loader_v3::write(&buffer.pubkey(), &kora_pubkey, offset, chunk.to_vec());
68 submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &[ix], &[]).await?;
69 if (i + 1) % 25 == 0 || i + 1 == chunk_count {
70 log::info!("wrote chunk {}/{}", i + 1, chunk_count);
71 }
72 }
73
74 let program_lamports = rpc
75 .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::size_of_program())
76 .await?;
77 let deploy_ixs = loader_v3::deploy_with_max_program_len(
78 &kora_pubkey,
79 &program.pubkey(),
80 &buffer.pubkey(),
81 &kora_pubkey,
82 program_lamports,
83 bytes.len(),
84 )?;
85 submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &deploy_ixs, &[&program]).await?;
86
87 Ok(DeployResult {
88 kora_pubkey,
89 program: program.pubkey(),
90 program_data,
91 buffer: buffer.pubkey(),
92 })
93}
94
95pub async fn verify_upgrade_authority(
96 rpc_url: &str,
97 program_data: &Pubkey,
98 expected: &Pubkey,
99) -> Result<()> {
100 let rpc = RpcClient::new_with_commitment(rpc_url.to_string(), CommitmentConfig::confirmed());
101 let pdata_account = rpc.get_account(program_data).await?;
102 let state: UpgradeableLoaderState = bincode::deserialize(
103 &pdata_account.data[..UpgradeableLoaderState::size_of_programdata_metadata()],
104 )?;
105 match state {
106 UpgradeableLoaderState::ProgramData { upgrade_authority_address, .. } => {
107 if upgrade_authority_address != Some(*expected) {
108 bail!("upgrade_authority is {upgrade_authority_address:?}, expected {expected}");
109 }
110 }
111 other => bail!("expected ProgramData, got {other:?}"),
112 }
113 Ok(())
114}
115
116pub async fn close(
117 rpc_url: &str,
118 kora_url: &str,
119 user_id: &str,
120 kora_pubkey: &Pubkey,
121 program: &Pubkey,
122 program_data: &Pubkey,
123) -> Result<Signature> {
124 let http = reqwest::Client::builder().timeout(Duration::from_secs(60)).build()?;
125 let rpc = Arc::new(RpcClient::new_with_commitment(
126 rpc_url.to_string(),
127 CommitmentConfig::confirmed(),
128 ));
129 wait_for_next_slot(&rpc).await?;
130 let close_ix =
131 loader_v3::close_any(program_data, kora_pubkey, Some(kora_pubkey), Some(program));
132 submit_returning_signature(&http, kora_url, user_id, &rpc, kora_pubkey, &[close_ix], &[]).await
133}
134
135async fn fetch_kora_pubkey(http: &reqwest::Client, url: &str) -> Result<Pubkey> {
136 let resp: Value = http
137 .post(url)
138 .json(&json!({"jsonrpc":"2.0","id":1,"method":"getPayerSigner","params":[]}))
139 .send()
140 .await?
141 .error_for_status()?
142 .json()
143 .await?;
144 Pubkey::from_str(
145 resp["result"]["signer_address"]
146 .as_str()
147 .ok_or_else(|| anyhow!("getPayerSigner missing signer_address: {resp}"))?,
148 )
149 .context("parsing kora pubkey")
150}
151
152fn derive_program_data_address(program: &Pubkey) -> Pubkey {
153 Pubkey::find_program_address(&[program.as_ref()], &BPF_LOADER_UPGRADEABLE).0
154}
155
156async fn build_b64_tx(
157 rpc: &RpcClient,
158 fee_payer: &Pubkey,
159 ixs: &[Instruction],
160 extra_signers: &[&Keypair],
161) -> Result<String> {
162 let blockhash = rpc.get_latest_blockhash().await?;
163 let msg = Message::new_with_blockhash(ixs, Some(fee_payer), &blockhash);
164 let mut tx = Transaction::new_unsigned(msg);
165 if !extra_signers.is_empty() {
166 tx.partial_sign(extra_signers, blockhash);
167 }
168 Ok(B64.encode(bincode::serialize(&tx)?))
169}
170
171async fn submit(
172 http: &reqwest::Client,
173 kora_url: &str,
174 user_id: &str,
175 rpc: &RpcClient,
176 fee_payer: &Pubkey,
177 ixs: &[Instruction],
178 extra_signers: &[&Keypair],
179) -> Result<()> {
180 submit_returning_signature(http, kora_url, user_id, rpc, fee_payer, ixs, extra_signers)
181 .await
182 .map(|_| ())
183}
184
185async fn submit_returning_signature(
186 http: &reqwest::Client,
187 kora_url: &str,
188 user_id: &str,
189 rpc: &RpcClient,
190 fee_payer: &Pubkey,
191 ixs: &[Instruction],
192 extra_signers: &[&Keypair],
193) -> Result<Signature> {
194 let tx_b64 = build_b64_tx(rpc, fee_payer, ixs, extra_signers).await?;
195 let resp: Value = http
196 .post(kora_url)
197 .json(&json!({
198 "jsonrpc":"2.0","id":1,
199 "method":"signAndSendTransaction",
200 "params":{"transaction": tx_b64, "user_id": user_id}
201 }))
202 .send()
203 .await?
204 .error_for_status()?
205 .json()
206 .await?;
207 if let Some(err) = resp.get("error") {
208 bail!("Kora rejected: {err}");
209 }
210 let sig_str = resp["result"]["signature"]
211 .as_str()
212 .ok_or_else(|| anyhow!("response missing signature: {resp}"))?;
213 let sig = Signature::from_str(sig_str)?;
214 await_tx(rpc, &sig).await?;
215 Ok(sig)
216}
217
218async fn await_tx(rpc: &RpcClient, sig: &Signature) -> Result<()> {
219 for _ in 0..120 {
220 if rpc.confirm_transaction_with_commitment(sig, CommitmentConfig::confirmed()).await?.value
221 {
222 return Ok(());
223 }
224 tokio::time::sleep(Duration::from_millis(500)).await;
225 }
226 bail!("timed out waiting for {sig}")
227}
228
229async fn wait_for_next_slot(rpc: &RpcClient) -> Result<()> {
230 let start = rpc.get_slot().await?;
231 for _ in 0..40 {
232 if rpc.get_slot().await? > start {
233 return Ok(());
234 }
235 tokio::time::sleep(Duration::from_millis(200)).await;
236 }
237 bail!("slot never advanced past {start}")
238}