1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use {
    crate::{
        parse_account_data::{ParsableAccount, ParseAccountError},
        UiAccountData, UiAccountEncoding,
    },
    base64::{prelude::BASE64_STANDARD, Engine},
    bincode::{deserialize, serialized_size},
    solana_sdk::{bpf_loader_upgradeable::UpgradeableLoaderState, pubkey::Pubkey},
};

pub fn parse_bpf_upgradeable_loader(
    data: &[u8],
) -> Result<BpfUpgradeableLoaderAccountType, ParseAccountError> {
    let account_state: UpgradeableLoaderState = deserialize(data).map_err(|_| {
        ParseAccountError::AccountNotParsable(ParsableAccount::BpfUpgradeableLoader)
    })?;
    let parsed_account = match account_state {
        UpgradeableLoaderState::Uninitialized => BpfUpgradeableLoaderAccountType::Uninitialized,
        UpgradeableLoaderState::Buffer { authority_address } => {
            let offset = if authority_address.is_some() {
                UpgradeableLoaderState::size_of_buffer_metadata()
            } else {
                // This case included for code completeness; in practice, a Buffer account will
                // always have authority_address.is_some()
                UpgradeableLoaderState::size_of_buffer_metadata()
                    - serialized_size(&Pubkey::default()).unwrap() as usize
            };
            BpfUpgradeableLoaderAccountType::Buffer(UiBuffer {
                authority: authority_address.map(|pubkey| pubkey.to_string()),
                data: UiAccountData::Binary(
                    BASE64_STANDARD.encode(&data[offset..]),
                    UiAccountEncoding::Base64,
                ),
            })
        }
        UpgradeableLoaderState::Program {
            programdata_address,
        } => BpfUpgradeableLoaderAccountType::Program(UiProgram {
            program_data: programdata_address.to_string(),
        }),
        UpgradeableLoaderState::ProgramData {
            slot,
            upgrade_authority_address,
        } => {
            let offset = if upgrade_authority_address.is_some() {
                UpgradeableLoaderState::size_of_programdata_metadata()
            } else {
                UpgradeableLoaderState::size_of_programdata_metadata()
                    - serialized_size(&Pubkey::default()).unwrap() as usize
            };
            BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
                slot,
                authority: upgrade_authority_address.map(|pubkey| pubkey.to_string()),
                data: UiAccountData::Binary(
                    BASE64_STANDARD.encode(&data[offset..]),
                    UiAccountEncoding::Base64,
                ),
            })
        }
    };
    Ok(parsed_account)
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", tag = "type", content = "info")]
pub enum BpfUpgradeableLoaderAccountType {
    Uninitialized,
    Buffer(UiBuffer),
    Program(UiProgram),
    ProgramData(UiProgramData),
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct UiBuffer {
    pub authority: Option<String>,
    pub data: UiAccountData,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct UiProgram {
    pub program_data: String,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct UiProgramData {
    pub slot: u64,
    pub authority: Option<String>,
    pub data: UiAccountData,
}

#[cfg(test)]
mod test {
    use {super::*, bincode::serialize, solana_sdk::pubkey::Pubkey};

    #[test]
    fn test_parse_bpf_upgradeable_loader_accounts() {
        let bpf_loader_state = UpgradeableLoaderState::Uninitialized;
        let account_data = serialize(&bpf_loader_state).unwrap();
        assert_eq!(
            parse_bpf_upgradeable_loader(&account_data).unwrap(),
            BpfUpgradeableLoaderAccountType::Uninitialized
        );

        let program = vec![7u8; 64]; // Arbitrary program data

        let authority = Pubkey::new_unique();
        let bpf_loader_state = UpgradeableLoaderState::Buffer {
            authority_address: Some(authority),
        };
        let mut account_data = serialize(&bpf_loader_state).unwrap();
        account_data.extend_from_slice(&program);
        assert_eq!(
            parse_bpf_upgradeable_loader(&account_data).unwrap(),
            BpfUpgradeableLoaderAccountType::Buffer(UiBuffer {
                authority: Some(authority.to_string()),
                data: UiAccountData::Binary(
                    BASE64_STANDARD.encode(&program),
                    UiAccountEncoding::Base64
                ),
            })
        );

        // This case included for code completeness; in practice, a Buffer account will always have
        // authority_address.is_some()
        let bpf_loader_state = UpgradeableLoaderState::Buffer {
            authority_address: None,
        };
        let mut account_data = serialize(&bpf_loader_state).unwrap();
        account_data.extend_from_slice(&program);
        assert_eq!(
            parse_bpf_upgradeable_loader(&account_data).unwrap(),
            BpfUpgradeableLoaderAccountType::Buffer(UiBuffer {
                authority: None,
                data: UiAccountData::Binary(
                    BASE64_STANDARD.encode(&program),
                    UiAccountEncoding::Base64
                ),
            })
        );

        let programdata_address = Pubkey::new_unique();
        let bpf_loader_state = UpgradeableLoaderState::Program {
            programdata_address,
        };
        let account_data = serialize(&bpf_loader_state).unwrap();
        assert_eq!(
            parse_bpf_upgradeable_loader(&account_data).unwrap(),
            BpfUpgradeableLoaderAccountType::Program(UiProgram {
                program_data: programdata_address.to_string(),
            })
        );

        let authority = Pubkey::new_unique();
        let slot = 42;
        let bpf_loader_state = UpgradeableLoaderState::ProgramData {
            slot,
            upgrade_authority_address: Some(authority),
        };
        let mut account_data = serialize(&bpf_loader_state).unwrap();
        account_data.extend_from_slice(&program);
        assert_eq!(
            parse_bpf_upgradeable_loader(&account_data).unwrap(),
            BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
                slot,
                authority: Some(authority.to_string()),
                data: UiAccountData::Binary(
                    BASE64_STANDARD.encode(&program),
                    UiAccountEncoding::Base64
                ),
            })
        );

        let bpf_loader_state = UpgradeableLoaderState::ProgramData {
            slot,
            upgrade_authority_address: None,
        };
        let mut account_data = serialize(&bpf_loader_state).unwrap();
        account_data.extend_from_slice(&program);
        assert_eq!(
            parse_bpf_upgradeable_loader(&account_data).unwrap(),
            BpfUpgradeableLoaderAccountType::ProgramData(UiProgramData {
                slot,
                authority: None,
                data: UiAccountData::Binary(
                    BASE64_STANDARD.encode(&program),
                    UiAccountEncoding::Base64
                ),
            })
        );
    }
}