Skip to main content

thru_base/
program_abi.rs

1//! Program + official ABI deploys in one Multicall transaction.
2//!
3//! The Public Manager and the ABI Manager both read their new contents from
4//! uploader buffers. These builders put the program change and the official
5//! ABI change into a single Multicall instruction so both land or neither
6//! does. The authority is always the fee payer (account index 0), which the
7//! callee programs treat as authorized.
8
9use anyhow::{Result, bail};
10
11use crate::txn_lib::{TnPubkey, Transaction};
12use crate::txn_tools::{
13    ABI_ACCOUNT_HEADER_SIZE, ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL,
14    ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_PERMANENT,
15    ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_EPHEMERAL,
16    ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_PERMANENT, MANAGER_INSTRUCTION_CREATE_EPHEMERAL,
17    MANAGER_INSTRUCTION_CREATE_PERMANENT, account_state_units,
18    build_abi_manager_create_abi_official_instruction,
19    build_abi_manager_create_meta_official_instruction,
20    build_abi_manager_upgrade_abi_official_instruction, build_manager_create_instruction,
21    build_manager_upgrade_instruction,
22};
23
24/// Transaction MTU; a Multicall instruction must fit inside it.
25const TXN_MTU: usize = 32_768;
26
27/// Compute budget for a combined deploy (both managers copy buffers).
28pub const PROGRAM_ABI_COMPUTE_UNITS: u32 = 500_000_000;
29
30/// Memory budget for a combined deploy, matching the TypeScript SDK.
31pub const PROGRAM_ABI_MEMORY_UNITS: u16 = 10_000;
32
33/// Encode Multicall instruction data: a u16 call count, then for each call
34/// the u16 account index of the callee program, the u64 length of its
35/// instruction data, and the data itself (all little-endian).
36pub fn build_multicall_instruction(calls: &[(u16, Vec<u8>)]) -> Result<Vec<u8>> {
37    if calls.is_empty() {
38        bail!("multicall needs at least one call");
39    }
40    let count = u16::try_from(calls.len())?;
41    let mut out = Vec::new();
42    out.extend_from_slice(&count.to_le_bytes());
43    for (program_idx, data) in calls {
44        out.extend_from_slice(&program_idx.to_le_bytes());
45        out.extend_from_slice(&(data.len() as u64).to_le_bytes());
46        out.extend_from_slice(data);
47    }
48    if out.len() > TXN_MTU {
49        bail!(
50            "multicall instruction is {} bytes, over the {} byte transaction limit",
51            out.len(),
52            TXN_MTU
53        );
54    }
55    Ok(out)
56}
57
58/// Accounts touched by a program + official ABI deploy.
59#[derive(Debug, Clone, Copy)]
60pub struct ProgramAbiAccounts {
61    pub manager_program: TnPubkey,
62    pub abi_manager_program: TnPubkey,
63    pub program_meta: TnPubkey,
64    pub program: TnPubkey,
65    pub abi_meta: TnPubkey,
66    pub abi: TnPubkey,
67    pub program_buffer: TnPubkey,
68    pub abi_buffer: TnPubkey,
69}
70
71/// What happens to the managed program.
72#[derive(Debug, Clone)]
73pub enum ProgramStep<'a> {
74    /// Create a new managed program from `seed`. Proofs are required for a
75    /// permanent program and must be absent for an ephemeral one.
76    Create {
77        seed: &'a [u8],
78        meta_proof: Option<&'a [u8]>,
79        program_proof: Option<&'a [u8]>,
80    },
81    /// Upgrade an existing managed program.
82    Upgrade,
83}
84
85/// What happens to the program's official ABI.
86#[derive(Debug, Clone)]
87pub enum AbiStep<'a> {
88    /// Create the ABI meta account and the ABI account.
89    CreateMetaAndAbi {
90        meta_proof: Option<&'a [u8]>,
91        abi_proof: Option<&'a [u8]>,
92    },
93    /// The ABI meta account exists; create the ABI account.
94    CreateAbi { abi_proof: Option<&'a [u8]> },
95    /// Upgrade the existing ABI account.
96    Upgrade,
97}
98
99/// SHA-256 of the new program image and of the new ABI content. Each manager
100/// instruction commits to its digest and installs only buffer bytes that hash
101/// to it, so the buffers cannot be swapped after the transaction (or a
102/// multisig request) is built.
103#[derive(Debug, Clone, Copy)]
104pub struct ProgramAbiDigests {
105    pub program: [u8; 32],
106    pub abi: [u8; 32],
107}
108
109/// Sizes used to size the deploy's state-unit budget.
110#[derive(Debug, Clone, Copy)]
111pub struct ProgramAbiSizes {
112    /// New program image size.
113    pub program: u32,
114    /// New ABI content size.
115    pub abi: u32,
116    /// Current program account data size (upgrades only).
117    pub current_program_data: Option<u64>,
118    /// Current ABI content size (ABI upgrades only).
119    pub current_abi: Option<u64>,
120}
121
122/// State units the deploy needs: new pages for created accounts, and the
123/// page growth of upgraded accounts.
124pub fn program_abi_state_units(
125    program_step: &ProgramStep<'_>,
126    abi_step: &AbiStep<'_>,
127    sizes: &ProgramAbiSizes,
128) -> Result<u16> {
129    let pages = |bytes: u64| -> Result<u64> { Ok(u64::from(account_state_units(bytes)?)) };
130    let mut units: u64 = 0;
131    match program_step {
132        // Program account plus the one-page manager meta account.
133        ProgramStep::Create { .. } => units += pages(u64::from(sizes.program) + 4096)?,
134        ProgramStep::Upgrade => {
135            let current = sizes
136                .current_program_data
137                .unwrap_or(u64::from(sizes.program));
138            units += pages(u64::from(sizes.program))?.saturating_sub(pages(current)?);
139        }
140    }
141    let abi_bytes = u64::from(sizes.abi) + ABI_ACCOUNT_HEADER_SIZE;
142    match abi_step {
143        AbiStep::CreateMetaAndAbi { .. } => units += 1 + pages(abi_bytes)?,
144        AbiStep::CreateAbi { .. } => units += pages(abi_bytes)?,
145        AbiStep::Upgrade => {
146            let current =
147                sizes.current_abi.unwrap_or(u64::from(sizes.abi)) + ABI_ACCOUNT_HEADER_SIZE;
148            units += pages(abi_bytes)?.saturating_sub(pages(current)?);
149        }
150    }
151    Ok(u16::try_from(units)?)
152}
153
154/// Sorted account layout: index 0 is the fee payer, 1 the Multicall
155/// program, then read-write accounts and read-only accounts, each sorted.
156struct Layout {
157    rw: Vec<TnPubkey>,
158    ro: Vec<TnPubkey>,
159}
160
161impl Layout {
162    fn new(mut rw: Vec<TnPubkey>, mut ro: Vec<TnPubkey>) -> Result<Self> {
163        rw.sort();
164        ro.sort();
165        let mut all: Vec<TnPubkey> = rw.iter().chain(ro.iter()).copied().collect();
166        let total = all.len();
167        all.sort();
168        all.dedup();
169        if all.len() != total {
170            bail!("program and ABI deploy accounts must be distinct");
171        }
172        Ok(Self { rw, ro })
173    }
174
175    fn idx(&self, key: &TnPubkey) -> Result<u16> {
176        let pos = self
177            .rw
178            .iter()
179            .chain(self.ro.iter())
180            .position(|k| k == key)
181            .ok_or_else(|| anyhow::anyhow!("account missing from deploy layout"))?;
182        Ok(u16::try_from(pos + 2)?)
183    }
184}
185
186/// Build the Multicall instruction calls for a program + official ABI
187/// deploy against `idx`, which maps each account to its transaction index.
188/// `authority_idx` is the index of the program authority (0 when the fee
189/// payer signs directly).
190#[allow(clippy::too_many_arguments)]
191pub fn build_program_abi_calls(
192    idx: &dyn Fn(&TnPubkey) -> Result<u16>,
193    accounts: &ProgramAbiAccounts,
194    program_step: &ProgramStep<'_>,
195    abi_step: &AbiStep<'_>,
196    program_size: u32,
197    abi_size: u32,
198    digests: &ProgramAbiDigests,
199    authority_idx: u16,
200    ephemeral: bool,
201) -> Result<Vec<(u16, Vec<u8>)>> {
202    let manager_idx = idx(&accounts.manager_program)?;
203    let abi_manager_idx = idx(&accounts.abi_manager_program)?;
204    let program_meta_idx = idx(&accounts.program_meta)?;
205    let program_idx = idx(&accounts.program)?;
206    let abi_meta_idx = idx(&accounts.abi_meta)?;
207    let abi_idx = idx(&accounts.abi)?;
208    let program_buffer_idx = idx(&accounts.program_buffer)?;
209    let abi_buffer_idx = idx(&accounts.abi_buffer)?;
210
211    let mut calls = Vec::with_capacity(3);
212    match program_step {
213        ProgramStep::Create {
214            seed,
215            meta_proof,
216            program_proof,
217        } => {
218            let proof = match (meta_proof, program_proof) {
219                (Some(meta), Some(program)) if !ephemeral => {
220                    let mut proof = Vec::with_capacity(meta.len() + program.len());
221                    proof.extend_from_slice(meta);
222                    proof.extend_from_slice(program);
223                    Some(proof)
224                }
225                (None, None) if ephemeral => None,
226                _ => bail!(
227                    "program creation proofs must be given exactly when the program is permanent"
228                ),
229            };
230            let discriminant = if ephemeral {
231                MANAGER_INSTRUCTION_CREATE_EPHEMERAL
232            } else {
233                MANAGER_INSTRUCTION_CREATE_PERMANENT
234            };
235            calls.push((
236                manager_idx,
237                build_manager_create_instruction(
238                    discriminant,
239                    program_meta_idx,
240                    program_idx,
241                    program_buffer_idx,
242                    authority_idx,
243                    0,
244                    program_size,
245                    digests.program,
246                    seed,
247                    proof.as_deref(),
248                )?,
249            ));
250        }
251        ProgramStep::Upgrade => calls.push((
252            manager_idx,
253            build_manager_upgrade_instruction(
254                program_meta_idx,
255                program_idx,
256                program_buffer_idx,
257                0,
258                program_size,
259                digests.program,
260            )?,
261        )),
262    }
263
264    let check_proof = |proof: &Option<&[u8]>, what: &str| -> Result<()> {
265        if proof.is_some() == ephemeral {
266            bail!("{what} creation proof must be given exactly when the ABI is permanent");
267        }
268        Ok(())
269    };
270    let create_abi = |proof: Option<&[u8]>| -> Result<(u16, Vec<u8>)> {
271        let discriminant = if ephemeral {
272            ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL
273        } else {
274            ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_PERMANENT
275        };
276        Ok((
277            abi_manager_idx,
278            build_abi_manager_create_abi_official_instruction(
279                discriminant,
280                abi_meta_idx,
281                program_meta_idx,
282                abi_idx,
283                abi_buffer_idx,
284                0,
285                abi_size,
286                digests.abi,
287                authority_idx,
288                proof,
289            )?,
290        ))
291    };
292    match abi_step {
293        AbiStep::CreateMetaAndAbi {
294            meta_proof,
295            abi_proof,
296        } => {
297            check_proof(meta_proof, "ABI meta")?;
298            check_proof(abi_proof, "ABI")?;
299            let discriminant = if ephemeral {
300                ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_EPHEMERAL
301            } else {
302                ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_PERMANENT
303            };
304            calls.push((
305                abi_manager_idx,
306                build_abi_manager_create_meta_official_instruction(
307                    discriminant,
308                    abi_meta_idx,
309                    program_meta_idx,
310                    authority_idx,
311                    *meta_proof,
312                )?,
313            ));
314            calls.push(create_abi(*abi_proof)?);
315        }
316        AbiStep::CreateAbi { abi_proof } => {
317            check_proof(abi_proof, "ABI")?;
318            calls.push(create_abi(*abi_proof)?);
319        }
320        AbiStep::Upgrade => calls.push((
321            abi_manager_idx,
322            build_abi_manager_upgrade_abi_official_instruction(
323                abi_meta_idx,
324                program_meta_idx,
325                abi_idx,
326                abi_buffer_idx,
327                0,
328                abi_size,
329                digests.abi,
330                authority_idx,
331            )?,
332        )),
333    }
334    Ok(calls)
335}
336
337/// Which accounts the deploy writes and which it only reads.
338pub fn program_abi_account_access(
339    accounts: &ProgramAbiAccounts,
340    abi_step: &AbiStep<'_>,
341) -> (Vec<TnPubkey>, Vec<TnPubkey>) {
342    let mut rw = vec![accounts.program_meta, accounts.program, accounts.abi];
343    let mut ro = vec![
344        accounts.manager_program,
345        accounts.abi_manager_program,
346        accounts.program_buffer,
347        accounts.abi_buffer,
348    ];
349    match abi_step {
350        AbiStep::CreateMetaAndAbi { .. } => rw.push(accounts.abi_meta),
351        AbiStep::CreateAbi { .. } | AbiStep::Upgrade => ro.push(accounts.abi_meta),
352    }
353    (rw, ro)
354}
355
356/// Build a fee-payer-signed transaction that creates or upgrades a managed
357/// program and creates or upgrades its official ABI in one Multicall.
358#[allow(clippy::too_many_arguments)]
359pub fn build_program_abi_transaction(
360    fee_payer: TnPubkey,
361    multicall_program: TnPubkey,
362    accounts: &ProgramAbiAccounts,
363    program_step: &ProgramStep<'_>,
364    abi_step: &AbiStep<'_>,
365    sizes: &ProgramAbiSizes,
366    digests: &ProgramAbiDigests,
367    ephemeral: bool,
368    fee: u64,
369    nonce: u64,
370    start_slot: u64,
371) -> Result<Transaction> {
372    let (rw, ro) = program_abi_account_access(accounts, abi_step);
373    let layout = Layout::new(rw, ro)?;
374    let calls = build_program_abi_calls(
375        &|key| layout.idx(key),
376        accounts,
377        program_step,
378        abi_step,
379        sizes.program,
380        sizes.abi,
381        digests,
382        0,
383        ephemeral,
384    )?;
385    let instructions = build_multicall_instruction(&calls)?;
386    let state_units = program_abi_state_units(program_step, abi_step, sizes)?;
387
388    Ok(Transaction::new(fee_payer, multicall_program, fee, nonce)
389        .with_start_slot(start_slot)
390        .with_expiry_after(10000)
391        .with_compute_units(PROGRAM_ABI_COMPUTE_UNITS)
392        .with_memory_units(PROGRAM_ABI_MEMORY_UNITS)
393        .with_state_units(state_units)
394        .with_rw_accounts(layout.rw)
395        .with_r_accounts(layout.ro)
396        .with_instructions(instructions))
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    fn key(b: u8) -> TnPubkey {
404        [b; 32]
405    }
406
407    const DIGESTS: ProgramAbiDigests = ProgramAbiDigests {
408        program: [0xA1; 32],
409        abi: [0xB2; 32],
410    };
411
412    fn accounts() -> ProgramAbiAccounts {
413        ProgramAbiAccounts {
414            manager_program: key(10),
415            abi_manager_program: key(11),
416            program_meta: key(5),
417            program: key(4),
418            abi_meta: key(3),
419            abi: key(2),
420            program_buffer: key(9),
421            abi_buffer: key(8),
422        }
423    }
424
425    /// Split multicall data back into (program index, instruction data).
426    fn decode(data: &[u8]) -> Vec<(u16, Vec<u8>)> {
427        let count = u16::from_le_bytes([data[0], data[1]]) as usize;
428        let mut off = 2;
429        let mut out = Vec::new();
430        for _ in 0..count {
431            let idx = u16::from_le_bytes([data[off], data[off + 1]]);
432            let len = u64::from_le_bytes(data[off + 2..off + 10].try_into().unwrap()) as usize;
433            out.push((idx, data[off + 10..off + 10 + len].to_vec()));
434            off += 10 + len;
435        }
436        assert_eq!(off, data.len());
437        out
438    }
439
440    #[test]
441    fn multicall_encoding_round_trips() {
442        let data = build_multicall_instruction(&[(3, vec![1, 2]), (7, vec![])]).unwrap();
443        assert_eq!(decode(&data), vec![(3, vec![1, 2]), (7, vec![])]);
444        assert!(build_multicall_instruction(&[]).is_err());
445        assert!(build_multicall_instruction(&[(2, vec![0; TXN_MTU])]).is_err());
446    }
447
448    #[test]
449    fn create_matches_individual_instructions() {
450        let a = accounts();
451        let seed = b"my_seed";
452        let (mp, pp, amp, ap) = (
453            vec![1u8; 104],
454            vec![2u8; 136],
455            vec![3u8; 104],
456            vec![4u8; 104],
457        );
458        let program_step = ProgramStep::Create {
459            seed,
460            meta_proof: Some(&mp),
461            program_proof: Some(&pp),
462        };
463        let abi_step = AbiStep::CreateMetaAndAbi {
464            meta_proof: Some(&amp),
465            abi_proof: Some(&ap),
466        };
467        let sizes = ProgramAbiSizes {
468            program: 5000,
469            abi: 300,
470            current_program_data: None,
471            current_abi: None,
472        };
473        let tx = build_program_abi_transaction(
474            key(1),
475            key(12),
476            &a,
477            &program_step,
478            &abi_step,
479            &sizes,
480            &DIGESTS,
481            false,
482            0,
483            7,
484            100,
485        )
486        .unwrap();
487
488        // rw sorted: abi(2) abi_meta(3) program(4) program_meta(5);
489        // ro sorted: abi_buffer(8) program_buffer(9) manager(10) abi_manager(11).
490        let (rw, ro) = (tx.rw_accs.clone().unwrap(), tx.r_accs.clone().unwrap());
491        assert_eq!(rw, vec![key(2), key(3), key(4), key(5)]);
492        assert_eq!(ro, vec![key(8), key(9), key(10), key(11)]);
493
494        let calls = decode(tx.instructions.as_ref().unwrap());
495        assert_eq!(calls.len(), 3);
496        let mut proof = mp.clone();
497        proof.extend_from_slice(&pp);
498        assert_eq!(
499            calls[0],
500            (
501                8,
502                build_manager_create_instruction(
503                    MANAGER_INSTRUCTION_CREATE_PERMANENT,
504                    5,
505                    4,
506                    7,
507                    0,
508                    0,
509                    5000,
510                    DIGESTS.program,
511                    seed,
512                    Some(&proof)
513                )
514                .unwrap()
515            )
516        );
517        assert_eq!(
518            calls[1],
519            (
520                9,
521                build_abi_manager_create_meta_official_instruction(
522                    ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_PERMANENT,
523                    3,
524                    5,
525                    0,
526                    Some(&amp)
527                )
528                .unwrap()
529            )
530        );
531        assert_eq!(
532            calls[2],
533            (
534                9,
535                build_abi_manager_create_abi_official_instruction(
536                    ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_PERMANENT,
537                    3,
538                    5,
539                    2,
540                    6,
541                    0,
542                    300,
543                    DIGESTS.abi,
544                    0,
545                    Some(&ap)
546                )
547                .unwrap()
548            )
549        );
550        // Program + manager meta (3 pages) + ABI meta (1) + ABI (1).
551        assert_eq!(tx.req_state_units, 3 + 1 + 1);
552    }
553
554    #[test]
555    fn upgrade_reads_abi_meta_and_charges_growth_only() {
556        let a = accounts();
557        let sizes = ProgramAbiSizes {
558            program: 9000,
559            abi: 100,
560            current_program_data: Some(5000),
561            current_abi: Some(4000),
562        };
563        let tx = build_program_abi_transaction(
564            key(1),
565            key(12),
566            &a,
567            &ProgramStep::Upgrade,
568            &AbiStep::Upgrade,
569            &sizes,
570            &DIGESTS,
571            false,
572            0,
573            1,
574            1,
575        )
576        .unwrap();
577        assert_eq!(tx.rw_accs.clone().unwrap(), vec![key(2), key(4), key(5)]);
578        assert_eq!(
579            tx.r_accs.clone().unwrap(),
580            vec![key(3), key(8), key(9), key(10), key(11)]
581        );
582        let calls = decode(tx.instructions.as_ref().unwrap());
583        assert_eq!(
584            calls,
585            vec![
586                (
587                    8,
588                    build_manager_upgrade_instruction(4, 3, 7, 0, 9000, DIGESTS.program).unwrap()
589                ),
590                (
591                    9,
592                    build_abi_manager_upgrade_abi_official_instruction(5, 4, 2, 6, 0, 100, DIGESTS.abi, 0)
593                        .unwrap()
594                ),
595            ]
596        );
597        // Program grows 2 -> 3 pages; ABI shrinks, which costs nothing.
598        assert_eq!(tx.req_state_units, 1);
599    }
600
601    #[test]
602    fn proofs_must_match_permanence() {
603        let a = accounts();
604        let sizes = ProgramAbiSizes {
605            program: 10,
606            abi: 10,
607            current_program_data: Some(10),
608            current_abi: None,
609        };
610        let missing = AbiStep::CreateAbi { abi_proof: None };
611        assert!(
612            build_program_abi_transaction(
613                key(1),
614                key(12),
615                &a,
616                &ProgramStep::Upgrade,
617                &missing,
618                &sizes,
619                &DIGESTS,
620                false,
621                0,
622                1,
623                1
624            )
625            .is_err()
626        );
627        assert!(
628            build_program_abi_transaction(
629                key(1),
630                key(12),
631                &a,
632                &ProgramStep::Upgrade,
633                &missing,
634                &sizes,
635                &DIGESTS,
636                true,
637                0,
638                1,
639                1
640            )
641            .is_ok()
642        );
643    }
644
645    #[test]
646    fn duplicate_accounts_are_rejected() {
647        let mut a = accounts();
648        a.abi_buffer = a.program_buffer;
649        let sizes = ProgramAbiSizes {
650            program: 10,
651            abi: 10,
652            current_program_data: Some(10),
653            current_abi: Some(10),
654        };
655        assert!(
656            build_program_abi_transaction(
657                key(1),
658                key(12),
659                &a,
660                &ProgramStep::Upgrade,
661                &AbiStep::Upgrade,
662                &sizes,
663                &DIGESTS,
664                false,
665                0,
666                1,
667                1
668            )
669            .is_err()
670        );
671    }
672}