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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use {
    crate::{
        instruction::ProgramInstruction,
        state::{
            AddressLookupTable, LookupTableMeta, LookupTableStatus, ProgramState,
            LOOKUP_TABLE_MAX_ADDRESSES, LOOKUP_TABLE_META_SIZE,
        },
    },
    solana_program_runtime::{ic_msg, invoke_context::InvokeContext},
    solana_sdk::{
        clock::Slot,
        instruction::InstructionError,
        program_utils::limited_deserialize,
        pubkey::{Pubkey, PUBKEY_BYTES},
        system_instruction,
    },
    std::convert::TryFrom,
};

pub fn process_instruction(
    _first_instruction_account: usize,
    invoke_context: &mut InvokeContext,
) -> Result<(), InstructionError> {
    let transaction_context = &invoke_context.transaction_context;
    let instruction_context = transaction_context.get_current_instruction_context()?;
    let instruction_data = instruction_context.get_instruction_data();
    match limited_deserialize(instruction_data)? {
        ProgramInstruction::CreateLookupTable {
            recent_slot,
            bump_seed,
        } => Processor::create_lookup_table(invoke_context, recent_slot, bump_seed),
        ProgramInstruction::FreezeLookupTable => Processor::freeze_lookup_table(invoke_context),
        ProgramInstruction::ExtendLookupTable { new_addresses } => {
            Processor::extend_lookup_table(invoke_context, new_addresses)
        }
        ProgramInstruction::DeactivateLookupTable => {
            Processor::deactivate_lookup_table(invoke_context)
        }
        ProgramInstruction::CloseLookupTable => Processor::close_lookup_table(invoke_context),
    }
}

fn checked_add(a: usize, b: usize) -> Result<usize, InstructionError> {
    a.checked_add(b).ok_or(InstructionError::ArithmeticOverflow)
}

pub struct Processor;
impl Processor {
    fn create_lookup_table(
        invoke_context: &mut InvokeContext,
        untrusted_recent_slot: Slot,
        bump_seed: u8,
    ) -> Result<(), InstructionError> {
        let transaction_context = &invoke_context.transaction_context;
        let instruction_context = transaction_context.get_current_instruction_context()?;

        let lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        let lookup_table_lamports = lookup_table_account.get_lamports();
        let table_key = *lookup_table_account.get_key();
        if !lookup_table_account.get_data().is_empty() {
            ic_msg!(invoke_context, "Table account must not be allocated");
            return Err(InstructionError::AccountAlreadyInitialized);
        }
        drop(lookup_table_account);

        let authority_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 1)?;
        let authority_key = *authority_account.get_key();
        if !authority_account.is_signer() {
            ic_msg!(invoke_context, "Authority account must be a signer");
            return Err(InstructionError::MissingRequiredSignature);
        }
        drop(authority_account);

        let payer_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 2)?;
        let payer_key = *payer_account.get_key();
        if !payer_account.is_signer() {
            ic_msg!(invoke_context, "Payer account must be a signer");
            return Err(InstructionError::MissingRequiredSignature);
        }
        drop(payer_account);

        let derivation_slot = {
            let slot_hashes = invoke_context.get_sysvar_cache().get_slot_hashes()?;
            if slot_hashes.get(&untrusted_recent_slot).is_some() {
                Ok(untrusted_recent_slot)
            } else {
                ic_msg!(
                    invoke_context,
                    "{} is not a recent slot",
                    untrusted_recent_slot
                );
                Err(InstructionError::InvalidInstructionData)
            }
        }?;

        // Use a derived address to ensure that an address table can never be
        // initialized more than once at the same address.
        let derived_table_key = Pubkey::create_program_address(
            &[
                authority_key.as_ref(),
                &derivation_slot.to_le_bytes(),
                &[bump_seed],
            ],
            &crate::id(),
        )?;

        if table_key != derived_table_key {
            ic_msg!(
                invoke_context,
                "Table address must match derived address: {}",
                derived_table_key
            );
            return Err(InstructionError::InvalidArgument);
        }

        let table_account_data_len = LOOKUP_TABLE_META_SIZE;
        let rent = invoke_context.get_sysvar_cache().get_rent()?;
        let required_lamports = rent
            .minimum_balance(table_account_data_len)
            .max(1)
            .saturating_sub(lookup_table_lamports);

        if required_lamports > 0 {
            invoke_context.native_invoke(
                system_instruction::transfer(&payer_key, &table_key, required_lamports),
                &[payer_key],
            )?;
        }

        invoke_context.native_invoke(
            system_instruction::allocate(&table_key, table_account_data_len as u64),
            &[table_key],
        )?;

        invoke_context.native_invoke(
            system_instruction::assign(&table_key, &crate::id()),
            &[table_key],
        )?;

        let transaction_context = &invoke_context.transaction_context;
        let instruction_context = transaction_context.get_current_instruction_context()?;
        let mut lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        lookup_table_account.set_state(&ProgramState::LookupTable(LookupTableMeta::new(
            authority_key,
        )))?;

        Ok(())
    }

    fn freeze_lookup_table(invoke_context: &mut InvokeContext) -> Result<(), InstructionError> {
        let transaction_context = &invoke_context.transaction_context;
        let instruction_context = transaction_context.get_current_instruction_context()?;

        let lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        if *lookup_table_account.get_owner() != crate::id() {
            return Err(InstructionError::InvalidAccountOwner);
        }
        drop(lookup_table_account);

        let authority_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 1)?;
        let authority_key = *authority_account.get_key();
        if !authority_account.is_signer() {
            ic_msg!(invoke_context, "Authority account must be a signer");
            return Err(InstructionError::MissingRequiredSignature);
        }
        drop(authority_account);

        let mut lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        let lookup_table_data = lookup_table_account.get_data();
        let lookup_table = AddressLookupTable::deserialize(lookup_table_data)?;

        if lookup_table.meta.authority.is_none() {
            ic_msg!(invoke_context, "Lookup table is already frozen");
            return Err(InstructionError::Immutable);
        }
        if lookup_table.meta.authority != Some(authority_key) {
            return Err(InstructionError::IncorrectAuthority);
        }
        if lookup_table.meta.deactivation_slot != Slot::MAX {
            ic_msg!(invoke_context, "Deactivated tables cannot be frozen");
            return Err(InstructionError::InvalidArgument);
        }
        if lookup_table.addresses.is_empty() {
            ic_msg!(invoke_context, "Empty lookup tables cannot be frozen");
            return Err(InstructionError::InvalidInstructionData);
        }

        let mut lookup_table_meta = lookup_table.meta;
        lookup_table_meta.authority = None;
        AddressLookupTable::overwrite_meta_data(
            lookup_table_account.get_data_mut()?,
            lookup_table_meta,
        )?;

        Ok(())
    }

    fn extend_lookup_table(
        invoke_context: &mut InvokeContext,
        new_addresses: Vec<Pubkey>,
    ) -> Result<(), InstructionError> {
        let transaction_context = &invoke_context.transaction_context;
        let instruction_context = transaction_context.get_current_instruction_context()?;

        let lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        let table_key = *lookup_table_account.get_key();
        if *lookup_table_account.get_owner() != crate::id() {
            return Err(InstructionError::InvalidAccountOwner);
        }
        drop(lookup_table_account);

        let authority_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 1)?;
        let authority_key = *authority_account.get_key();
        if !authority_account.is_signer() {
            ic_msg!(invoke_context, "Authority account must be a signer");
            return Err(InstructionError::MissingRequiredSignature);
        }
        drop(authority_account);

        let mut lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        let lookup_table_data = lookup_table_account.get_data();
        let lookup_table_lamports = lookup_table_account.get_lamports();
        let mut lookup_table = AddressLookupTable::deserialize(lookup_table_data)?;

        if lookup_table.meta.authority.is_none() {
            return Err(InstructionError::Immutable);
        }
        if lookup_table.meta.authority != Some(authority_key) {
            return Err(InstructionError::IncorrectAuthority);
        }
        if lookup_table.meta.deactivation_slot != Slot::MAX {
            ic_msg!(invoke_context, "Deactivated tables cannot be extended");
            return Err(InstructionError::InvalidArgument);
        }
        if lookup_table.addresses.len() >= LOOKUP_TABLE_MAX_ADDRESSES {
            ic_msg!(
                invoke_context,
                "Lookup table is full and cannot contain more addresses"
            );
            return Err(InstructionError::InvalidArgument);
        }

        if new_addresses.is_empty() {
            ic_msg!(invoke_context, "Must extend with at least one address");
            return Err(InstructionError::InvalidInstructionData);
        }

        let new_table_addresses_len = lookup_table
            .addresses
            .len()
            .saturating_add(new_addresses.len());
        if new_table_addresses_len > LOOKUP_TABLE_MAX_ADDRESSES {
            ic_msg!(
                invoke_context,
                "Extended lookup table length {} would exceed max capacity of {}",
                new_table_addresses_len,
                LOOKUP_TABLE_MAX_ADDRESSES
            );
            return Err(InstructionError::InvalidInstructionData);
        }

        let clock = invoke_context.get_sysvar_cache().get_clock()?;
        if clock.slot != lookup_table.meta.last_extended_slot {
            lookup_table.meta.last_extended_slot = clock.slot;
            lookup_table.meta.last_extended_slot_start_index =
                u8::try_from(lookup_table.addresses.len()).map_err(|_| {
                    // This is impossible as long as the length of new_addresses
                    // is non-zero and LOOKUP_TABLE_MAX_ADDRESSES == u8::MAX + 1.
                    InstructionError::InvalidAccountData
                })?;
        }

        let lookup_table_meta = lookup_table.meta;
        let new_table_data_len = checked_add(
            LOOKUP_TABLE_META_SIZE,
            new_table_addresses_len.saturating_mul(PUBKEY_BYTES),
        )?;

        {
            let mut table_data = lookup_table_account.get_data_mut()?.to_vec();
            AddressLookupTable::overwrite_meta_data(&mut table_data, lookup_table_meta)?;
            for new_address in new_addresses {
                table_data.extend_from_slice(new_address.as_ref());
            }
            lookup_table_account.set_data(&table_data)?;
        }
        drop(lookup_table_account);

        let rent = invoke_context.get_sysvar_cache().get_rent()?;
        let required_lamports = rent
            .minimum_balance(new_table_data_len)
            .max(1)
            .saturating_sub(lookup_table_lamports);

        if required_lamports > 0 {
            let payer_account =
                instruction_context.try_borrow_instruction_account(transaction_context, 2)?;
            let payer_key = *payer_account.get_key();
            if !payer_account.is_signer() {
                ic_msg!(invoke_context, "Payer account must be a signer");
                return Err(InstructionError::MissingRequiredSignature);
            }
            drop(payer_account);

            invoke_context.native_invoke(
                system_instruction::transfer(&payer_key, &table_key, required_lamports),
                &[payer_key],
            )?;
        }

        Ok(())
    }

    fn deactivate_lookup_table(invoke_context: &mut InvokeContext) -> Result<(), InstructionError> {
        let transaction_context = &invoke_context.transaction_context;
        let instruction_context = transaction_context.get_current_instruction_context()?;

        let lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        if *lookup_table_account.get_owner() != crate::id() {
            return Err(InstructionError::InvalidAccountOwner);
        }
        drop(lookup_table_account);

        let authority_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 1)?;
        let authority_key = *authority_account.get_key();
        if !authority_account.is_signer() {
            ic_msg!(invoke_context, "Authority account must be a signer");
            return Err(InstructionError::MissingRequiredSignature);
        }
        drop(authority_account);

        let mut lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        let lookup_table_data = lookup_table_account.get_data();
        let lookup_table = AddressLookupTable::deserialize(lookup_table_data)?;

        if lookup_table.meta.authority.is_none() {
            ic_msg!(invoke_context, "Lookup table is frozen");
            return Err(InstructionError::Immutable);
        }
        if lookup_table.meta.authority != Some(authority_key) {
            return Err(InstructionError::IncorrectAuthority);
        }
        if lookup_table.meta.deactivation_slot != Slot::MAX {
            ic_msg!(invoke_context, "Lookup table is already deactivated");
            return Err(InstructionError::InvalidArgument);
        }

        let mut lookup_table_meta = lookup_table.meta;
        let clock = invoke_context.get_sysvar_cache().get_clock()?;
        lookup_table_meta.deactivation_slot = clock.slot;

        AddressLookupTable::overwrite_meta_data(
            lookup_table_account.get_data_mut()?,
            lookup_table_meta,
        )?;

        Ok(())
    }

    fn close_lookup_table(invoke_context: &mut InvokeContext) -> Result<(), InstructionError> {
        let transaction_context = &invoke_context.transaction_context;
        let instruction_context = transaction_context.get_current_instruction_context()?;

        let lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        if *lookup_table_account.get_owner() != crate::id() {
            return Err(InstructionError::InvalidAccountOwner);
        }
        drop(lookup_table_account);

        let authority_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 1)?;
        let authority_key = *authority_account.get_key();
        if !authority_account.is_signer() {
            ic_msg!(invoke_context, "Authority account must be a signer");
            return Err(InstructionError::MissingRequiredSignature);
        }
        drop(authority_account);

        instruction_context.check_number_of_instruction_accounts(3)?;
        if instruction_context.get_index_of_instruction_account_in_transaction(0)?
            == instruction_context.get_index_of_instruction_account_in_transaction(2)?
        {
            ic_msg!(
                invoke_context,
                "Lookup table cannot be the recipient of reclaimed lamports"
            );
            return Err(InstructionError::InvalidArgument);
        }

        let lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        let withdrawn_lamports = lookup_table_account.get_lamports();
        let lookup_table_data = lookup_table_account.get_data();
        let lookup_table = AddressLookupTable::deserialize(lookup_table_data)?;

        if lookup_table.meta.authority.is_none() {
            ic_msg!(invoke_context, "Lookup table is frozen");
            return Err(InstructionError::Immutable);
        }
        if lookup_table.meta.authority != Some(authority_key) {
            return Err(InstructionError::IncorrectAuthority);
        }

        let sysvar_cache = invoke_context.get_sysvar_cache();
        let clock = sysvar_cache.get_clock()?;
        let slot_hashes = sysvar_cache.get_slot_hashes()?;

        match lookup_table.meta.status(clock.slot, &slot_hashes) {
            LookupTableStatus::Activated => {
                ic_msg!(invoke_context, "Lookup table is not deactivated");
                Err(InstructionError::InvalidArgument)
            }
            LookupTableStatus::Deactivating { remaining_blocks } => {
                ic_msg!(
                    invoke_context,
                    "Table cannot be closed until it's fully deactivated in {} blocks",
                    remaining_blocks
                );
                Err(InstructionError::InvalidArgument)
            }
            LookupTableStatus::Deactivated => Ok(()),
        }?;
        drop(lookup_table_account);

        let mut recipient_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 2)?;
        recipient_account.checked_add_lamports(withdrawn_lamports)?;
        drop(recipient_account);

        let mut lookup_table_account =
            instruction_context.try_borrow_instruction_account(transaction_context, 0)?;
        lookup_table_account.set_data(&[])?;
        lookup_table_account.set_lamports(0)?;

        Ok(())
    }
}