Skip to main content

kora_deploy/
lib.rs

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::{AccountMeta, 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");
23const SYSTEM_PROGRAM: Pubkey = solana_sdk::pubkey!("11111111111111111111111111111111");
24
25pub const DEFAULT_REGISTRY_PROGRAM: Pubkey =
26    solana_sdk::pubkey!("CPoBCCbvawmR2S6joHjXgfFkh9pGqzSixBe2BaBwbVkx");
27const REGISTRY_IX_REGISTER: u8 = 0;
28const REGISTRY_IX_CLOSE_ENTRY: u8 = 1;
29const REGISTRY_ENTRY_LEN: usize = 65;
30
31pub struct DeployConfig<'a> {
32    pub kora_url: &'a str,
33    pub rpc_url: &'a str,
34    pub program_so: &'a Path,
35    pub user_id: String,
36    /// When set, the deploy transaction registers this wallet as the program's owner in the
37    /// deploy registry, allowing future upgrades signed by it. Without a wallet the program
38    /// is immutable through the paymaster.
39    pub wallet: Option<&'a Keypair>,
40}
41
42pub struct UpgradeConfig<'a> {
43    pub kora_url: &'a str,
44    pub rpc_url: &'a str,
45    pub program_so: &'a Path,
46    pub user_id: String,
47    pub program: Pubkey,
48    pub wallet: &'a Keypair,
49}
50
51pub struct DeployResult {
52    pub kora_pubkey: Pubkey,
53    pub program: Pubkey,
54    pub program_data: Pubkey,
55    pub buffer: Pubkey,
56}
57
58pub async fn deploy(cfg: &DeployConfig<'_>) -> Result<DeployResult> {
59    let http = reqwest::Client::builder().timeout(Duration::from_secs(60)).build()?;
60    let rpc = Arc::new(RpcClient::new_with_commitment(
61        cfg.rpc_url.to_string(),
62        CommitmentConfig::confirmed(),
63    ));
64
65    let kora_pubkey = fetch_kora_pubkey(&http, cfg.kora_url).await?;
66    let program = Keypair::new();
67    let buffer = Keypair::new();
68    let bytes = std::fs::read(cfg.program_so)
69        .with_context(|| format!("reading {}", cfg.program_so.display()))?;
70    let program_data = derive_program_data_address(&program.pubkey());
71
72    let buffer_lamports = rpc
73        .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::size_of_buffer(bytes.len()))
74        .await?;
75    let create_buf = loader_v3::create_buffer(
76        &kora_pubkey,
77        &buffer.pubkey(),
78        &kora_pubkey,
79        buffer_lamports,
80        bytes.len(),
81    )?;
82    submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &create_buf, &[&buffer]).await?;
83
84    let chunk_count = bytes.len().div_ceil(WRITE_CHUNK_SIZE);
85    for (i, chunk) in bytes.chunks(WRITE_CHUNK_SIZE).enumerate() {
86        let offset = (i * WRITE_CHUNK_SIZE) as u32;
87        let ix = loader_v3::write(&buffer.pubkey(), &kora_pubkey, offset, chunk.to_vec());
88        submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &[ix], &[]).await?;
89        if (i + 1) % 25 == 0 || i + 1 == chunk_count {
90            log::info!("wrote chunk {}/{}", i + 1, chunk_count);
91        }
92    }
93
94    let program_lamports = rpc
95        .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::size_of_program())
96        .await?;
97    let mut deploy_ixs = loader_v3::deploy_with_max_program_len(
98        &kora_pubkey,
99        &program.pubkey(),
100        &buffer.pubkey(),
101        &kora_pubkey,
102        program_lamports,
103        bytes.len(),
104    )?;
105    let mut deploy_signers: Vec<&Keypair> = vec![&program];
106    if let Some(wallet) = cfg.wallet {
107        deploy_ixs.push(register_ix(
108            &DEFAULT_REGISTRY_PROGRAM,
109            &kora_pubkey,
110            &program.pubkey(),
111            &wallet.pubkey(),
112        ));
113        deploy_signers.push(wallet);
114    }
115    submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &deploy_ixs, &deploy_signers)
116        .await?;
117
118    Ok(DeployResult {
119        kora_pubkey,
120        program: program.pubkey(),
121        program_data,
122        buffer: buffer.pubkey(),
123    })
124}
125
126pub async fn upgrade(cfg: &UpgradeConfig<'_>) -> Result<Signature> {
127    let http = reqwest::Client::builder().timeout(Duration::from_secs(60)).build()?;
128    let rpc = Arc::new(RpcClient::new_with_commitment(
129        cfg.rpc_url.to_string(),
130        CommitmentConfig::confirmed(),
131    ));
132
133    let kora_pubkey = fetch_kora_pubkey(&http, cfg.kora_url).await?;
134    assert_registered_owner(&rpc, &DEFAULT_REGISTRY_PROGRAM, &cfg.program, &cfg.wallet.pubkey())
135        .await?;
136    let bytes = std::fs::read(cfg.program_so)
137        .with_context(|| format!("reading {}", cfg.program_so.display()))?;
138
139    let buffer = Keypair::new();
140    let buffer_lamports = rpc
141        .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::size_of_buffer(bytes.len()))
142        .await?;
143    let create_buf = loader_v3::create_buffer(
144        &kora_pubkey,
145        &buffer.pubkey(),
146        &kora_pubkey,
147        buffer_lamports,
148        bytes.len(),
149    )?;
150    submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &create_buf, &[&buffer]).await?;
151
152    let chunk_count = bytes.len().div_ceil(WRITE_CHUNK_SIZE);
153    for (i, chunk) in bytes.chunks(WRITE_CHUNK_SIZE).enumerate() {
154        let offset = (i * WRITE_CHUNK_SIZE) as u32;
155        let ix = loader_v3::write(&buffer.pubkey(), &kora_pubkey, offset, chunk.to_vec());
156        submit(&http, cfg.kora_url, &cfg.user_id, &rpc, &kora_pubkey, &[ix], &[]).await?;
157        if (i + 1) % 25 == 0 || i + 1 == chunk_count {
158            log::info!("wrote chunk {}/{}", i + 1, chunk_count);
159        }
160    }
161
162    let mut upgrade_ix =
163        loader_v3::upgrade(&cfg.program, &buffer.pubkey(), &kora_pubkey, &kora_pubkey);
164    upgrade_ix.accounts.push(AccountMeta::new_readonly(cfg.wallet.pubkey(), true));
165    submit_returning_signature(
166        &http,
167        cfg.kora_url,
168        &cfg.user_id,
169        &rpc,
170        &kora_pubkey,
171        &[upgrade_ix],
172        &[cfg.wallet],
173    )
174    .await
175}
176
177/// A program is live when its programdata account exists; the reaper's close removes it
178/// while the 36-byte program account survives forever.
179pub async fn program_is_live(rpc_url: &str, program: &Pubkey) -> Result<bool> {
180    let rpc = RpcClient::new_with_commitment(rpc_url.to_string(), CommitmentConfig::confirmed());
181    let program_data = derive_program_data_address(program);
182    Ok(rpc
183        .get_account_with_commitment(&program_data, CommitmentConfig::confirmed())
184        .await?
185        .value
186        .is_some())
187}
188
189pub fn registry_entry_address(registry_program: &Pubkey, program: &Pubkey) -> Pubkey {
190    Pubkey::find_program_address(&[program.as_ref()], registry_program).0
191}
192
193pub fn register_ix(
194    registry_program: &Pubkey,
195    payer: &Pubkey,
196    program: &Pubkey,
197    owner: &Pubkey,
198) -> Instruction {
199    Instruction::new_with_bytes(
200        *registry_program,
201        &[REGISTRY_IX_REGISTER],
202        vec![
203            AccountMeta::new(*payer, true),
204            AccountMeta::new_readonly(*program, true),
205            AccountMeta::new_readonly(*owner, true),
206            AccountMeta::new(registry_entry_address(registry_program, program), false),
207            AccountMeta::new_readonly(SYSTEM_PROGRAM, false),
208        ],
209    )
210}
211
212/// Permissionless once the program's programdata account is gone; rent returns to the
213/// stored payer, which must be passed as `recipient`.
214pub fn close_entry_ix(
215    registry_program: &Pubkey,
216    program: &Pubkey,
217    recipient: &Pubkey,
218) -> Instruction {
219    Instruction::new_with_bytes(
220        *registry_program,
221        &[REGISTRY_IX_CLOSE_ENTRY],
222        vec![
223            AccountMeta::new(registry_entry_address(registry_program, program), false),
224            AccountMeta::new_readonly(*program, false),
225            AccountMeta::new_readonly(derive_program_data_address(program), false),
226            AccountMeta::new(*recipient, false),
227        ],
228    )
229}
230
231async fn assert_registered_owner(
232    rpc: &RpcClient,
233    registry_program: &Pubkey,
234    program: &Pubkey,
235    wallet: &Pubkey,
236) -> Result<()> {
237    let entry_address = registry_entry_address(registry_program, program);
238    let entry = rpc
239        .get_account_with_commitment(&entry_address, CommitmentConfig::confirmed())
240        .await?
241        .value
242        .ok_or_else(|| {
243            anyhow!(
244                "program {program} has no deploy-registry entry (deployed without a wallet?); \
245                 it cannot be upgraded through the paymaster"
246            )
247        })?;
248    if entry.owner != *registry_program || entry.data.len() != REGISTRY_ENTRY_LEN {
249        bail!("registry entry {entry_address} is malformed");
250    }
251    let owner = Pubkey::try_from(&entry.data[..32])
252        .map_err(|_| anyhow!("registry entry {entry_address} has an invalid owner"))?;
253    if owner != *wallet {
254        bail!(
255            "program {program} is registered to {owner}, but the provided wallet is {wallet}; \
256             sign with the registered wallet to upgrade"
257        );
258    }
259    Ok(())
260}
261
262pub async fn verify_upgrade_authority(
263    rpc_url: &str,
264    program_data: &Pubkey,
265    expected: &Pubkey,
266) -> Result<()> {
267    let rpc = RpcClient::new_with_commitment(rpc_url.to_string(), CommitmentConfig::confirmed());
268    let pdata_account = rpc.get_account(program_data).await?;
269    let state: UpgradeableLoaderState = bincode::deserialize(
270        &pdata_account.data[..UpgradeableLoaderState::size_of_programdata_metadata()],
271    )?;
272    match state {
273        UpgradeableLoaderState::ProgramData { upgrade_authority_address, .. } => {
274            if upgrade_authority_address != Some(*expected) {
275                bail!("upgrade_authority is {upgrade_authority_address:?}, expected {expected}");
276            }
277        }
278        other => bail!("expected ProgramData, got {other:?}"),
279    }
280    Ok(())
281}
282
283#[allow(clippy::too_many_arguments)]
284pub async fn close(
285    rpc_url: &str,
286    kora_url: &str,
287    user_id: &str,
288    kora_pubkey: &Pubkey,
289    program: &Pubkey,
290    program_data: &Pubkey,
291    wallet: Option<&Keypair>,
292) -> Result<Signature> {
293    let http = reqwest::Client::builder().timeout(Duration::from_secs(60)).build()?;
294    let rpc = Arc::new(RpcClient::new_with_commitment(
295        rpc_url.to_string(),
296        CommitmentConfig::confirmed(),
297    ));
298    wait_for_next_slot(&rpc).await?;
299    let mut close_ix =
300        loader_v3::close_any(program_data, kora_pubkey, Some(kora_pubkey), Some(program));
301    let mut signers: Vec<&Keypair> = Vec::new();
302    if let Some(wallet) = wallet {
303        close_ix.accounts.push(AccountMeta::new_readonly(wallet.pubkey(), true));
304        signers.push(wallet);
305    }
306    submit_returning_signature(&http, kora_url, user_id, &rpc, kora_pubkey, &[close_ix], &signers)
307        .await
308}
309
310async fn fetch_kora_pubkey(http: &reqwest::Client, url: &str) -> Result<Pubkey> {
311    let resp: Value = http
312        .post(url)
313        .json(&json!({"jsonrpc":"2.0","id":1,"method":"getPayerSigner","params":[]}))
314        .send()
315        .await?
316        .error_for_status()?
317        .json()
318        .await?;
319    Pubkey::from_str(
320        resp["result"]["signer_address"]
321            .as_str()
322            .ok_or_else(|| anyhow!("getPayerSigner missing signer_address: {resp}"))?,
323    )
324    .context("parsing kora pubkey")
325}
326
327fn derive_program_data_address(program: &Pubkey) -> Pubkey {
328    Pubkey::find_program_address(&[program.as_ref()], &BPF_LOADER_UPGRADEABLE).0
329}
330
331async fn build_b64_tx(
332    rpc: &RpcClient,
333    fee_payer: &Pubkey,
334    ixs: &[Instruction],
335    extra_signers: &[&Keypair],
336) -> Result<String> {
337    let blockhash = rpc.get_latest_blockhash().await?;
338    let msg = Message::new_with_blockhash(ixs, Some(fee_payer), &blockhash);
339    let mut tx = Transaction::new_unsigned(msg);
340    if !extra_signers.is_empty() {
341        tx.partial_sign(extra_signers, blockhash);
342    }
343    Ok(B64.encode(bincode::serialize(&tx)?))
344}
345
346async fn submit(
347    http: &reqwest::Client,
348    kora_url: &str,
349    user_id: &str,
350    rpc: &RpcClient,
351    fee_payer: &Pubkey,
352    ixs: &[Instruction],
353    extra_signers: &[&Keypair],
354) -> Result<()> {
355    submit_returning_signature(http, kora_url, user_id, rpc, fee_payer, ixs, extra_signers)
356        .await
357        .map(|_| ())
358}
359
360async fn submit_returning_signature(
361    http: &reqwest::Client,
362    kora_url: &str,
363    user_id: &str,
364    rpc: &RpcClient,
365    fee_payer: &Pubkey,
366    ixs: &[Instruction],
367    extra_signers: &[&Keypair],
368) -> Result<Signature> {
369    let tx_b64 = build_b64_tx(rpc, fee_payer, ixs, extra_signers).await?;
370    let resp: Value = http
371        .post(kora_url)
372        .json(&json!({
373            "jsonrpc":"2.0","id":1,
374            "method":"signAndSendTransaction",
375            "params":{"transaction": tx_b64, "user_id": user_id}
376        }))
377        .send()
378        .await?
379        .error_for_status()?
380        .json()
381        .await?;
382    if let Some(err) = resp.get("error") {
383        bail!("Kora rejected: {err}");
384    }
385    let sig_str = resp["result"]["signature"]
386        .as_str()
387        .ok_or_else(|| anyhow!("response missing signature: {resp}"))?;
388    let sig = Signature::from_str(sig_str)?;
389    await_tx(rpc, &sig).await?;
390    Ok(sig)
391}
392
393async fn await_tx(rpc: &RpcClient, sig: &Signature) -> Result<()> {
394    for _ in 0..120 {
395        if rpc.confirm_transaction_with_commitment(sig, CommitmentConfig::confirmed()).await?.value
396        {
397            return Ok(());
398        }
399        tokio::time::sleep(Duration::from_millis(500)).await;
400    }
401    bail!("timed out waiting for {sig}")
402}
403
404async fn wait_for_next_slot(rpc: &RpcClient) -> Result<()> {
405    let start = rpc.get_slot().await?;
406    for _ in 0..40 {
407        if rpc.get_slot().await? > start {
408            return Ok(());
409        }
410        tokio::time::sleep(Duration::from_millis(200)).await;
411    }
412    bail!("slot never advanced past {start}")
413}