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
//! A library for composing transactions.

use crate::hash::Hash;
use crate::pubkey::Pubkey;
use crate::signature::KeypairUtil;
use crate::transaction::{Instruction, Transaction};
use itertools::Itertools;

pub type BuilderInstruction = Instruction<Pubkey, (Pubkey, bool)>;

fn position(keys: &[Pubkey], key: &Pubkey) -> u8 {
    keys.iter().position(|k| k == key).unwrap() as u8
}

fn compile_instruction(
    ix: &BuilderInstruction,
    keys: &[Pubkey],
    program_ids: &[Pubkey],
) -> Instruction<u8, u8> {
    let accounts: Vec<_> = ix.accounts.iter().map(|(k, _)| position(keys, k)).collect();
    Instruction {
        program_ids_index: position(program_ids, &ix.program_ids_index),
        userdata: ix.userdata.clone(),
        accounts,
    }
}

fn compile_instructions(
    ixs: &[BuilderInstruction],
    keys: &[Pubkey],
    program_ids: &[Pubkey],
) -> Vec<Instruction<u8, u8>> {
    ixs.iter()
        .map(|ix| compile_instruction(ix, keys, program_ids))
        .collect()
}

/// A utility for constructing transactions
#[derive(Default)]
pub struct TransactionBuilder {
    fee: u64,
    instructions: Vec<BuilderInstruction>,
}

impl TransactionBuilder {
    /// Create a new TransactionBuilder.
    pub fn new(fee: u64) -> Self {
        Self {
            fee,
            instructions: vec![],
        }
    }

    /// Add an instruction.
    pub fn push(&mut self, instruction: BuilderInstruction) -> &mut Self {
        self.instructions.push(instruction);
        self
    }

    /// Return pubkeys referenced by all instructions, with the ones needing signatures first.
    /// No duplicates and order is preserved.
    fn keys(&self) -> (Vec<Pubkey>, Vec<Pubkey>) {
        let mut keys_and_signed: Vec<_> = self
            .instructions
            .iter()
            .flat_map(|ix| ix.accounts.iter())
            .collect();
        keys_and_signed.sort_by(|x, y| y.1.cmp(&x.1));

        let mut signed_keys = vec![];
        let mut unsigned_keys = vec![];
        for (key, signed) in keys_and_signed.into_iter().unique_by(|x| x.0) {
            if *signed {
                signed_keys.push(*key);
            } else {
                unsigned_keys.push(*key);
            }
        }
        (signed_keys, unsigned_keys)
    }

    /// Return program ids referenced by all instructions.  No duplicates and order is preserved.
    fn program_ids(&self) -> Vec<Pubkey> {
        self.instructions
            .iter()
            .map(|ix| ix.program_ids_index)
            .unique()
            .collect()
    }

    /// Return an unsigned transaction with space for requires signatures.
    pub fn compile(&self) -> Transaction {
        let program_ids = self.program_ids();
        let (mut signed_keys, unsigned_keys) = self.keys();
        let signed_len = signed_keys.len();
        signed_keys.extend(&unsigned_keys);
        let instructions = compile_instructions(&self.instructions, &signed_keys, &program_ids);
        Transaction {
            signatures: Vec::with_capacity(signed_len),
            account_keys: signed_keys,
            recent_blockhash: Hash::default(),
            fee: self.fee,
            program_ids,
            instructions,
        }
    }

    /// Return a signed transaction.
    pub fn sign<T: KeypairUtil>(&self, keypairs: &[&T], recent_blockhash: Hash) -> Transaction {
        let mut tx = self.compile();
        tx.sign_checked(keypairs, recent_blockhash);
        tx
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::signature::{Keypair, KeypairUtil};

    #[test]
    fn test_transaction_builder_unique_program_ids() {
        let program_id0 = Pubkey::default();
        let program_ids = TransactionBuilder::default()
            .push(Instruction::new(program_id0, &0, vec![]))
            .push(Instruction::new(program_id0, &0, vec![]))
            .program_ids();
        assert_eq!(program_ids, vec![program_id0]);
    }

    #[test]
    fn test_transaction_builder_unique_program_ids_not_adjacent() {
        let program_id0 = Pubkey::default();
        let program_id1 = Keypair::new().pubkey();
        let program_ids = TransactionBuilder::default()
            .push(Instruction::new(program_id0, &0, vec![]))
            .push(Instruction::new(program_id1, &0, vec![]))
            .push(Instruction::new(program_id0, &0, vec![]))
            .program_ids();
        assert_eq!(program_ids, vec![program_id0, program_id1]);
    }

    #[test]
    fn test_transaction_builder_unique_program_ids_order_preserved() {
        let program_id0 = Keypair::new().pubkey();
        let program_id1 = Pubkey::default(); // Key less than program_id0
        let program_ids = TransactionBuilder::default()
            .push(Instruction::new(program_id0, &0, vec![]))
            .push(Instruction::new(program_id1, &0, vec![]))
            .push(Instruction::new(program_id0, &0, vec![]))
            .program_ids();
        assert_eq!(program_ids, vec![program_id0, program_id1]);
    }

    #[test]
    fn test_transaction_builder_unique_keys_both_signed() {
        let program_id = Pubkey::default();
        let id0 = Pubkey::default();
        let keys = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, true)]))
            .push(Instruction::new(program_id, &0, vec![(id0, true)]))
            .keys();
        assert_eq!(keys, (vec![id0], vec![]));
    }

    #[test]
    fn test_transaction_builder_unique_keys_one_signed() {
        let program_id = Pubkey::default();
        let id0 = Pubkey::default();
        let keys = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, false)]))
            .push(Instruction::new(program_id, &0, vec![(id0, true)]))
            .keys();
        assert_eq!(keys, (vec![id0], vec![]));
    }

    #[test]
    fn test_transaction_builder_unique_keys_order_preserved() {
        let program_id = Pubkey::default();
        let id0 = Keypair::new().pubkey();
        let id1 = Pubkey::default(); // Key less than id0
        let keys = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, false)]))
            .push(Instruction::new(program_id, &0, vec![(id1, false)]))
            .keys();
        assert_eq!(keys, (vec![], vec![id0, id1]));
    }

    #[test]
    fn test_transaction_builder_unique_keys_not_adjacent() {
        let program_id = Pubkey::default();
        let id0 = Pubkey::default();
        let id1 = Keypair::new().pubkey();
        let keys = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, false)]))
            .push(Instruction::new(program_id, &0, vec![(id1, false)]))
            .push(Instruction::new(program_id, &0, vec![(id0, true)]))
            .keys();
        assert_eq!(keys, (vec![id0], vec![id1]));
    }

    #[test]
    fn test_transaction_builder_signed_keys_first() {
        let program_id = Pubkey::default();
        let id0 = Pubkey::default();
        let id1 = Keypair::new().pubkey();
        let keys = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, false)]))
            .push(Instruction::new(program_id, &0, vec![(id1, true)]))
            .keys();
        assert_eq!(keys, (vec![id1], vec![id0]));
    }

    #[test]
    // Ensure there's a way to calculate the number of required signatures.
    fn test_transaction_builder_signed_keys_len() {
        let program_id = Pubkey::default();
        let id0 = Pubkey::default();
        let tx = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, false)]))
            .compile();
        assert_eq!(tx.signatures.capacity(), 0);

        let tx = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, true)]))
            .compile();
        assert_eq!(tx.signatures.capacity(), 1);
    }

    #[test]
    #[should_panic]
    fn test_transaction_builder_missing_key() {
        let keypair = Keypair::new();
        TransactionBuilder::default().sign(&[&keypair], Hash::default());
    }

    #[test]
    #[should_panic]
    fn test_transaction_builder_missing_keypair() {
        let program_id = Pubkey::default();
        let keypair0 = Keypair::new();
        let id0 = keypair0.pubkey();
        TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, true)]))
            .sign(&Vec::<&Keypair>::new(), Hash::default());
    }

    #[test]
    #[should_panic]
    fn test_transaction_builder_wrong_key() {
        let program_id = Pubkey::default();
        let keypair0 = Keypair::new();
        let wrong_id = Pubkey::default();
        TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(wrong_id, true)]))
            .sign(&[&keypair0], Hash::default());
    }

    #[test]
    fn test_transaction_builder_correct_key() {
        let program_id = Pubkey::default();
        let keypair0 = Keypair::new();
        let id0 = keypair0.pubkey();
        let tx = TransactionBuilder::default()
            .push(Instruction::new(program_id, &0, vec![(id0, true)]))
            .sign(&[&keypair0], Hash::default());
        assert_eq!(tx.instructions[0], Instruction::new(0, &0, vec![0]));
    }

    #[test]
    fn test_transaction_builder_fee() {
        let tx = TransactionBuilder::new(42).sign(&Vec::<&Keypair>::new(), Hash::default());
        assert_eq!(tx.fee, 42);
    }

    #[test]
    fn test_transaction_builder_kitchen_sink() {
        let program_id0 = Pubkey::default();
        let program_id1 = Keypair::new().pubkey();
        let id0 = Pubkey::default();
        let keypair1 = Keypair::new();
        let id1 = keypair1.pubkey();
        let tx = TransactionBuilder::default()
            .push(Instruction::new(program_id0, &0, vec![(id0, false)]))
            .push(Instruction::new(program_id1, &0, vec![(id1, true)]))
            .push(Instruction::new(program_id0, &0, vec![(id1, false)]))
            .sign(&[&keypair1], Hash::default());
        assert_eq!(tx.instructions[0], Instruction::new(0, &0, vec![1]));
        assert_eq!(tx.instructions[1], Instruction::new(1, &0, vec![0]));
        assert_eq!(tx.instructions[2], Instruction::new(0, &0, vec![0]));
    }
}