trident_fuzz/
transaction_executor.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
use std::{cell::RefCell, collections::HashMap};

use anchor_lang::InstructionData;
use solana_sdk::{
    instruction::Instruction, signature::Keypair, signer::Signer, transaction::Transaction,
};

use crate::{
    config::Config,
    error::{FuzzClientErrorWithOrigin, Origin},
    fuzz_client::FuzzClient,
    fuzz_stats::FuzzingStatistics,
    ix_ops::IxOps,
    snapshot::Snapshot,
};

pub struct TransactionExecutor;

impl TransactionExecutor {
    #[allow(clippy::too_many_arguments)]
    pub fn process_transaction_honggfuzz<'info, I>(
        instruction_name: &str,
        client: &mut impl FuzzClient,
        ix: &'info I,
        snapshot: &'info mut Snapshot<'info, I>,
        sent_txs: &mut HashMap<anchor_lang::solana_program::hash::Hash, ()>,
        config: &Config,
        accounts: &RefCell<I::IxAccounts>,
    ) -> core::result::Result<(), FuzzClientErrorWithOrigin>
    where
        I: IxOps<'info>,
    {
        let program_id = ix.get_program_id();

        let (mut signers, account_metas) = ix
            .get_accounts(client, &mut accounts.borrow_mut())
            .map_err(|e| e.with_origin(Origin::Instruction(instruction_name.to_owned())))
            .expect("Accounts calculation expect");

        let data = ix
            .get_data(client, &mut accounts.borrow_mut())
            .map_err(|e| e.with_origin(Origin::Instruction(instruction_name.to_owned())))
            .expect("Data calculation expect");

        snapshot.add_metas(&account_metas);

        snapshot.capture_before(client).unwrap();

        let ixx = Instruction {
            program_id,
            accounts: account_metas,
            data: data.data(),
        };

        let mut transaction = Transaction::new_with_payer(&[ixx], Some(&client.payer().pubkey()));

        signers.push(client.payer().insecure_clone());
        let sig: Vec<&Keypair> = signers.iter().collect();
        transaction.sign(&sig, client.get_last_blockhash());

        let duplicate_tx = if config.get_allow_duplicate_txs() {
            None
        } else {
            let message_hash = transaction.message().hash();
            sent_txs.insert(message_hash, ())
        };

        match duplicate_tx {
            Some(_) => eprintln!(
                "\x1b[1;93mWarning\x1b[0m: Skipping duplicate instruction `{}`",
                instruction_name.to_owned()
            ),
            None => {
                if config.get_fuzzing_with_stats() {
                    let mut stats_logger = FuzzingStatistics::new();

                    stats_logger.increase_invoked(instruction_name.to_owned());

                    let tx_result = client.process_transaction(transaction).map_err(|e| {
                        e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                    });
                    match tx_result {
                        Ok(_) => {
                            stats_logger.increase_successful(instruction_name.to_owned());

                            snapshot.capture_after(client).unwrap();
                            let (acc_before, acc_after) = snapshot
                                .get_snapshot()
                                .map_err(|e| {
                                    e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                                })
                                .expect("Snapshot deserialization expect"); // we want to panic if we cannot unwrap to cause a crash

                            if let Err(e) = ix.check(acc_before, acc_after, data).map_err(|e| {
                                e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                            }) {
                                stats_logger.increase_failed_check(instruction_name.to_owned());
                                stats_logger.output_serialized();

                                eprintln!("\x1b[31mCRASH DETECTED!\x1b[0m Custom check after the {} instruction did not pass!",instruction_name.to_owned());
                                panic!("{}", e)
                            }
                            stats_logger.output_serialized();
                        }
                        Err(e) => {
                            stats_logger.increase_failed(instruction_name.to_owned());
                            stats_logger.output_serialized();

                            let mut raw_accounts = snapshot.get_raw_pre_ix_accounts();
                            ix.tx_error_handler(e, data, &mut raw_accounts)?
                        }
                    }
                } else {
                    let tx_result = client.process_transaction(transaction).map_err(|e| {
                        e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                    });
                    match tx_result {
                        Ok(_) => {
                            snapshot.capture_after(client).unwrap();
                            let (acc_before, acc_after) = snapshot
                                .get_snapshot()
                                .map_err(|e| {
                                    e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                                })
                                .expect("Snapshot deserialization expect"); // we want to panic if we cannot unwrap to cause a crash

                            if let Err(e) = ix.check(acc_before, acc_after, data).map_err(|e| {
                                e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                            }) {
                                eprintln!("\x1b[31mCRASH DETECTED!\x1b[0m Custom check after the {} instruction did not pass!",instruction_name.to_owned());
                                panic!("{}", e)
                            }
                        }
                        Err(e) => {
                            let mut raw_accounts = snapshot.get_raw_pre_ix_accounts();
                            ix.tx_error_handler(e, data, &mut raw_accounts)?
                        }
                    }
                }
            }
        }
        Ok(())
    }
    #[allow(clippy::too_many_arguments)]
    pub fn process_transaction_afl<'info, I>(
        instruction_name: &str,
        client: &mut impl FuzzClient,
        ix: &'info I,
        snapshot: &'info mut Snapshot<'info, I>,
        sent_txs: &mut HashMap<anchor_lang::solana_program::hash::Hash, ()>,
        config: &Config,
        accounts: &RefCell<I::IxAccounts>,
    ) -> core::result::Result<(), FuzzClientErrorWithOrigin>
    where
        I: IxOps<'info>,
    {
        let program_id = ix.get_program_id();

        let (mut signers, account_metas) = ix
            .get_accounts(client, &mut accounts.borrow_mut())
            .map_err(|e| e.with_origin(Origin::Instruction(instruction_name.to_owned())))
            .expect("Accounts calculation expect");

        let data = ix
            .get_data(client, &mut accounts.borrow_mut())
            .map_err(|e| e.with_origin(Origin::Instruction(instruction_name.to_owned())))
            .expect("Data calculation expect");

        snapshot.add_metas(&account_metas);

        snapshot.capture_before(client).unwrap();

        let ixx = Instruction {
            program_id,
            accounts: account_metas,
            data: data.data(),
        };

        let mut transaction = Transaction::new_with_payer(&[ixx], Some(&client.payer().pubkey()));

        signers.push(client.payer().insecure_clone());
        let sig: Vec<&Keypair> = signers.iter().collect();
        transaction.sign(&sig, client.get_last_blockhash());

        let duplicate_tx = if config.get_allow_duplicate_txs() {
            None
        } else {
            let message_hash = transaction.message().hash();
            sent_txs.insert(message_hash, ())
        };

        match duplicate_tx {
            Some(_) => eprintln!(
                "\x1b[1;93mWarning\x1b[0m: Skipping duplicate instruction `{}`",
                instruction_name.to_owned()
            ),
            None => {
                let tx_result = client
                    .process_transaction(transaction)
                    .map_err(|e| e.with_origin(Origin::Instruction(instruction_name.to_owned())));
                match tx_result {
                    Ok(_) => {
                        snapshot.capture_after(client).unwrap();
                        let (acc_before, acc_after) = snapshot
                            .get_snapshot()
                            .map_err(|e| {
                                e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                            })
                            .expect("Snapshot deserialization expect"); // we want to panic if we cannot unwrap to cause a crash

                        if let Err(e) = ix.check(acc_before, acc_after, data).map_err(|e| {
                            e.with_origin(Origin::Instruction(instruction_name.to_owned()))
                        }) {
                            eprintln!("\x1b[31mCRASH DETECTED!\x1b[0m Custom check after the {} instruction did not pass!",instruction_name.to_owned());
                            panic!("{}", e)
                        }
                    }
                    Err(e) => {
                        let mut raw_accounts = snapshot.get_raw_pre_ix_accounts();
                        ix.tx_error_handler(e, data, &mut raw_accounts)?
                    }
                }
            }
        }
        Ok(())
    }
}