Skip to main content

thru_base/
compression.rs

1//! Unsigned builders for the current managed compression program (u32 tags).
2//! The legacy system-test builders in `txn_tools` have a different wire format.
3use crate::tn_account::{TN_ACCOUNT_DATA_SZ_MAX, TN_ACCOUNT_META_FOOTPRINT, TnAccountMeta};
4use crate::{
5    StateProof, StateProofType, Transaction, TransactionBuilder, txn_tools::account_state_units,
6};
7
8pub const COMPRESSION_TRANSACTION_MAX_BYTES: usize = 32_768;
9pub use crate::bootstrap_addresses::COMPRESSION_PROGRAM_BYTES as COMPRESSION_PROGRAM;
10
11#[derive(Debug, thiserror::Error, PartialEq, Eq)]
12pub enum DecompressionBuildError {
13    #[error("invalid archived account metadata or data length")]
14    InvalidImage,
15    #[error("decompression requires a complete existing-account proof")]
16    InvalidProof,
17    #[error(
18        "inline decompression requires {actual} transaction bytes; maximum is {limit}; large-account upload staging is not supported"
19    )]
20    SizeLimit { actual: usize, limit: usize },
21    #[error(
22        "the target must differ from the payer and program; a compressed payer requires another active funded payer"
23    )]
24    InvalidTarget,
25}
26
27impl TransactionBuilder {
28    /// Build an unsigned inline restore for the current compression program.
29    /// Pass `COMPRESSION_PROGRAM` for the canonical deployment. Callers own
30    /// chain-aware signing, nonce coordination, submission and confirmation.
31    pub fn build_compression_decompress(
32        fee_payer: [u8; 32],
33        program: [u8; 32],
34        target: [u8; 32],
35        account_meta: &[u8],
36        account_data: &[u8],
37        proof: &[u8],
38        fee: u64,
39        nonce: u64,
40        start_slot: u64,
41    ) -> Result<Transaction, DecompressionBuildError> {
42        if target == fee_payer || target == program || fee_payer == program {
43            return Err(DecompressionBuildError::InvalidTarget);
44        }
45        if account_meta.len() != TN_ACCOUNT_META_FOOTPRINT
46            || account_data.len() > TN_ACCOUNT_DATA_SZ_MAX
47            || TnAccountMeta::from_wire(account_meta)
48                .is_none_or(|meta| meta.data_sz as usize != account_data.len())
49        {
50            return Err(DecompressionBuildError::InvalidImage);
51        }
52        let parsed = StateProof::from_wire(proof).ok_or(DecompressionBuildError::InvalidProof)?;
53        if proof.len() < 40
54            || proof[7] >> 6 != 0
55            || parsed.header.proof_type != StateProofType::Existing
56            || parsed.to_wire() != proof
57        {
58            return Err(DecompressionBuildError::InvalidProof);
59        }
60        // Header (112), target (32), signature (64), tag/index/length/meta (78).
61        let actual = 112 + 32 + 64 + 78 + account_data.len() + proof.len();
62        if actual > COMPRESSION_TRANSACTION_MAX_BYTES {
63            return Err(DecompressionBuildError::SizeLimit {
64                actual,
65                limit: COMPRESSION_TRANSACTION_MAX_BYTES,
66            });
67        }
68        let mut instruction = Vec::with_capacity(78 + account_data.len() + proof.len());
69        instruction.extend_from_slice(&2u32.to_le_bytes());
70        instruction.extend_from_slice(&2u16.to_le_bytes());
71        instruction.extend_from_slice(&(account_data.len() as u64).to_le_bytes());
72        instruction.extend_from_slice(account_meta);
73        instruction.extend_from_slice(account_data);
74        instruction.extend_from_slice(proof);
75        let tx = Transaction::new(fee_payer, program, fee, nonce)
76            .with_start_slot(start_slot)
77            .with_expiry_after(100)
78            .with_compute_units(100_300 + account_data.len() as u32 * 2)
79            .with_memory_units(10_000)
80            .with_state_units(
81                account_state_units(account_data.len() as u64)
82                    .map_err(|_| DecompressionBuildError::InvalidImage)?,
83            )
84            .add_rw_account(target)
85            .with_instructions(instruction);
86        Ok(tx)
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    fn build(size: usize) -> Result<Transaction, DecompressionBuildError> {
94        let mut meta = [0; 64];
95        meta[4..8].copy_from_slice(&(size as u32).to_le_bytes());
96        TransactionBuilder::build_compression_decompress(
97            [1; 32],
98            COMPRESSION_PROGRAM,
99            [2; 32],
100            &meta,
101            &vec![7; size],
102            &[0; 40],
103            0,
104            9,
105            600,
106        )
107    }
108    #[test]
109    fn current_abi_and_unsigned_wire_boundary() {
110        let tx = build(4033).unwrap();
111        assert!(tx.signature.is_none());
112        assert_eq!(tx.req_state_units, 2);
113        assert_eq!(tx.nonce, 9);
114        let ix = tx.instructions.as_ref().unwrap();
115        assert_eq!(&ix[..4], &2u32.to_le_bytes());
116        assert_eq!(&ix[4..6], &2u16.to_le_bytes());
117        assert_eq!(&ix[6..14], &4033u64.to_le_bytes());
118        assert_eq!(&ix[78..78 + 4033], vec![7; 4033].as_slice());
119        let max_data = COMPRESSION_TRANSACTION_MAX_BYTES - (112 + 32 + 64 + 78 + 40);
120        assert_eq!(
121            build(max_data).unwrap().to_wire().len(),
122            COMPRESSION_TRANSACTION_MAX_BYTES
123        );
124        assert_eq!(
125            build(max_data + 1).unwrap_err(),
126            DecompressionBuildError::SizeLimit {
127                actual: 32769,
128                limit: 32768
129            }
130        );
131    }
132    #[test]
133    fn invalid_images_proofs_and_payer_target_are_rejected() {
134        let mut proof = vec![0; 40];
135        proof[8] = 1;
136        assert_eq!(
137            TransactionBuilder::build_compression_decompress(
138                [1; 32],
139                COMPRESSION_PROGRAM,
140                [2; 32],
141                &[0; 64],
142                &[],
143                &proof,
144                0,
145                0,
146                0
147            )
148            .unwrap_err(),
149            DecompressionBuildError::InvalidProof
150        );
151        assert!(matches!(
152            TransactionBuilder::build_compression_decompress(
153                [1; 32],
154                COMPRESSION_PROGRAM,
155                [2; 32],
156                &[0; 64],
157                &[1],
158                &[0; 40],
159                0,
160                0,
161                0
162            ),
163            Err(DecompressionBuildError::InvalidImage)
164        ));
165        assert!(matches!(
166            TransactionBuilder::build_compression_decompress(
167                [1; 32],
168                COMPRESSION_PROGRAM,
169                [1; 32],
170                &[0; 64],
171                &[],
172                &[0; 40],
173                0,
174                0,
175                0
176            ),
177            Err(DecompressionBuildError::InvalidTarget)
178        ));
179    }
180}