trident_fuzz/accounts_storage/
pda_store.rs

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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
use solana_sdk::{
    account::{AccountSharedData, WritableAccount},
    clock::{Clock, Epoch},
    native_token::LAMPORTS_PER_SOL,
    program_option::COption,
    program_pack::Pack,
    pubkey::Pubkey,
    rent::Rent,
    stake::stake_flags::StakeFlags,
};
use solana_stake_program::stake_state::{
    Authorized, Delegation, Lockup, Meta, Stake, StakeStateV2,
};
use solana_vote_program::vote_state::{VoteInit, VoteState, VoteStateVersions};
use spl_token::state::Mint;

use crate::{fuzz_client::FuzzClient, AccountId};

use super::AccountsStorage;

pub struct PdaStore {
    pub pubkey: Pubkey,
    pub seeds: (Vec<Vec<u8>>, Pubkey),
}
impl PdaStore {
    pub fn pubkey(&self) -> Pubkey {
        self.pubkey
    }
}

impl From<Pubkey> for PdaStore {
    fn from(pubkey: Pubkey) -> Self {
        PdaStore {
            pubkey,
            seeds: (Vec::new(), Pubkey::default()), // Note: This creates empty seeds
        }
    }
}

impl AccountsStorage<PdaStore> {
    pub fn get_or_create_account(
        &mut self,
        account_id: AccountId,
        client: &mut impl FuzzClient,
        seeds: &[&[u8]],
        program_id: &Pubkey,
    ) -> Pubkey {
        match self.accounts.get(&account_id) {
            Some(v) => v.pubkey,
            None => {
                if let Some((key, _)) = Pubkey::try_find_program_address(seeds, program_id) {
                    let seeds_vec: Vec<_> = seeds.iter().map(|&s| s.to_vec()).collect();
                    let pda_store = PdaStore {
                        pubkey: key,
                        seeds: (seeds_vec, *program_id),
                    };
                    self.accounts.insert(account_id, pda_store);

                    // this returns default if account does not exists
                    let account = client.get_account(&key);

                    // so set account to default if it does not exists, or overwrite
                    // with what is already set.
                    client.set_account_custom(&key, &account);
                    key
                } else {
                    Pubkey::new_unique()
                }
            }
        }
    }
    /// Get Initialized or Create new Token Account
    #[allow(clippy::too_many_arguments)]
    pub fn get_or_create_token_account(
        &mut self,
        account_id: AccountId,
        client: &mut impl FuzzClient,
        seeds: &[&[u8]],
        program_id: &Pubkey,
        mint: Pubkey,
        owner: Pubkey,
        amount: u64,
        delegate: Option<Pubkey>,
        is_native: Option<u64>,
        delegated_amount: u64,
        close_authority: Option<Pubkey>,
    ) -> Pubkey {
        let key = self.accounts.entry(account_id).or_insert_with(|| {
            let address = derive_pda(seeds, program_id);

            let delegate = match delegate {
                Some(a) => COption::Some(a),
                _ => COption::None,
            };

            let is_native = match is_native {
                Some(a) => COption::Some(a),
                _ => COption::None,
            };

            let close_authority = match close_authority {
                Some(a) => COption::Some(a),
                _ => COption::None,
            };

            let r = Rent::default();
            let lamports = r.minimum_balance(spl_token::state::Account::LEN);

            let mut account =
                AccountSharedData::new(lamports, spl_token::state::Account::LEN, &spl_token::id());

            let token_account_ = spl_token::state::Account {
                mint,
                owner,
                amount,
                delegate,
                state: spl_token::state::AccountState::Initialized,
                is_native,
                delegated_amount,
                close_authority,
            };

            let mut data = vec![0u8; spl_token::state::Account::LEN];
            spl_token::state::Account::pack(token_account_, &mut data[..]).unwrap();
            account.set_data_from_slice(&data);

            client.set_account_custom(&address.0, &account);

            let seeds_vec: Vec<_> = seeds.iter().map(|&s| s.to_vec()).collect();
            PdaStore {
                pubkey: address.0,
                seeds: (seeds_vec, *program_id),
            }
        });
        key.pubkey
    }
    /// Get Initialized or Create new Mint Account
    #[allow(clippy::too_many_arguments)]
    pub fn get_or_create_mint_account(
        &mut self,
        account_id: AccountId,
        client: &mut impl FuzzClient,
        seeds: &[&[u8]],
        program_id: &Pubkey,
        decimals: u8,
        owner: &Pubkey,
        freeze_authority: Option<Pubkey>,
    ) -> Pubkey {
        let key = self.accounts.entry(account_id).or_insert_with(|| {
            let address = derive_pda(seeds, program_id);

            let authority = match freeze_authority {
                Some(a) => COption::Some(a),
                _ => COption::None,
            };

            let r = Rent::default();
            let lamports = r.minimum_balance(Mint::LEN);

            let mut account = AccountSharedData::new(lamports, Mint::LEN, &spl_token::id());

            let mint = Mint {
                is_initialized: true,
                mint_authority: COption::Some(*owner),
                freeze_authority: authority,
                decimals,
                ..Default::default()
            };

            let mut data = vec![0u8; Mint::LEN];
            Mint::pack(mint, &mut data[..]).unwrap();
            account.set_data_from_slice(&data);

            client.set_account_custom(&address.0, &account);

            let seeds_vec: Vec<_> = seeds.iter().map(|&s| s.to_vec()).collect();
            PdaStore {
                pubkey: address.0,
                seeds: (seeds_vec, *program_id),
            }
        });
        key.pubkey
    }
    /// Get Initialized or Create new Delegated Stake Account
    #[allow(clippy::too_many_arguments)]
    pub fn get_or_create_delegated_account(
        &mut self,
        account_id: AccountId,
        client: &mut impl FuzzClient,
        seeds: &[&[u8]],
        program_id: &Pubkey,
        voter_pubkey: Pubkey,
        staker: Pubkey,
        withdrawer: Pubkey,
        stake: u64,
        activation_epoch: Epoch,
        deactivation_epoch: Option<Epoch>,
        lockup: Option<Lockup>,
    ) -> Pubkey {
        let key = self.accounts.entry(account_id).or_insert_with(|| {
            let address = derive_pda(seeds, program_id);

            let rent = Rent::default();
            let rent_exempt_lamports = rent.minimum_balance(StakeStateV2::size_of());
            let minimum_delegation = LAMPORTS_PER_SOL; // TODO: a way to get minimum delegation with feature set?
            let minimum_lamports = rent_exempt_lamports.saturating_add(minimum_delegation);

            let stake_state = StakeStateV2::Stake(
                Meta {
                    authorized: Authorized { staker, withdrawer },
                    lockup: lockup.unwrap_or_default(),
                    rent_exempt_reserve: rent_exempt_lamports,
                },
                Stake {
                    delegation: Delegation {
                        stake,
                        activation_epoch,
                        voter_pubkey,
                        deactivation_epoch: if let Some(epoch) = deactivation_epoch {
                            epoch
                        } else {
                            u64::MAX
                        },
                        ..Delegation::default()
                    },
                    ..Stake::default()
                },
                StakeFlags::default(),
            );
            let account = AccountSharedData::new_data_with_space(
                if stake > minimum_lamports {
                    stake
                } else {
                    minimum_lamports
                },
                &stake_state,
                StakeStateV2::size_of(),
                &solana_sdk::stake::program::ID,
            )
            .unwrap();

            client.set_account_custom(&address.0, &account);

            let seeds_vec: Vec<_> = seeds.iter().map(|&s| s.to_vec()).collect();
            PdaStore {
                pubkey: address.0,
                seeds: (seeds_vec, *program_id),
            }
        });
        key.pubkey
    }
    #[allow(clippy::too_many_arguments)]
    /// Get Initialized or Create new Initialized Stake Account
    pub fn get_or_create_initialized_account(
        &mut self,
        account_id: AccountId,
        client: &mut impl FuzzClient,
        seeds: &[&[u8]],
        program_id: &Pubkey,
        staker: Pubkey,
        withdrawer: Pubkey,
        lockup: Option<Lockup>,
    ) -> Pubkey {
        let key = self.accounts.entry(account_id).or_insert_with(|| {
            let address = derive_pda(seeds, program_id);

            let rent = Rent::default();
            let rent_exempt_lamports = rent.minimum_balance(StakeStateV2::size_of());

            let stake_state = StakeStateV2::Initialized(Meta {
                authorized: Authorized { staker, withdrawer },
                lockup: lockup.unwrap_or_default(),
                rent_exempt_reserve: rent_exempt_lamports,
            });
            let account = AccountSharedData::new_data_with_space(
                rent_exempt_lamports,
                &stake_state,
                StakeStateV2::size_of(),
                &solana_sdk::stake::program::ID,
            )
            .unwrap();
            client.set_account_custom(&address.0, &account);

            let seeds_vec: Vec<_> = seeds.iter().map(|&s| s.to_vec()).collect();
            PdaStore {
                pubkey: address.0,
                seeds: (seeds_vec, *program_id),
            }
        });
        key.pubkey
    }
    /// Get Initialized or Create new Vote Account
    #[allow(clippy::too_many_arguments)]
    pub fn get_or_create_vote_account(
        &mut self,
        account_id: AccountId,
        client: &mut impl FuzzClient,
        seeds: &[&[u8]],
        program_id: &Pubkey,
        node_pubkey: &Pubkey,
        authorized_voter: &Pubkey,
        authorized_withdrawer: &Pubkey,
        commission: u8,
        clock: &Clock,
    ) -> Pubkey {
        let key = self.accounts.entry(account_id).or_insert_with(|| {
            let address = derive_pda(seeds, program_id);

            let rent = Rent::default();
            let lamports = rent.minimum_balance(VoteState::size_of());
            let mut account = AccountSharedData::new(
                lamports,
                VoteState::size_of(),
                &solana_sdk::vote::program::ID,
            );

            let vote_state = VoteState::new(
                &VoteInit {
                    node_pubkey: *node_pubkey,
                    authorized_voter: *authorized_voter,
                    authorized_withdrawer: *authorized_withdrawer,
                    commission,
                },
                clock,
            );

            VoteState::serialize(
                &VoteStateVersions::Current(Box::new(vote_state)),
                account.data_as_mut_slice(),
            )
            .unwrap();

            client.set_account_custom(&address.0, &account);

            let seeds_vec: Vec<_> = seeds.iter().map(|&s| s.to_vec()).collect();
            PdaStore {
                pubkey: address.0,
                seeds: (seeds_vec, *program_id),
            }
        });
        key.pubkey
    }
    pub fn get(&self, account_id: AccountId) -> Pubkey {
        match self.accounts.get(&account_id) {
            Some(v) => v.pubkey,
            None => Pubkey::new_unique(),
        }
    }
}

fn derive_pda(seeds: &[&[u8]], program_id: &Pubkey) -> (Pubkey, u8) {
    if let Some(address) = Pubkey::try_find_program_address(seeds, program_id) {
        address
    } else {
        panic!("PDA Store, seeds did not create valid PDA address")
    }
}