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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// Remove feature once zk ops syscalls are enabled on all networks
#[cfg(feature = "zk-ops")]
use solana_zk_token_sdk::zk_token_elgamal::ops as syscall;
use {
    crate::{
        check_program_account, check_zk_token_proof_program_account,
        error::TokenError,
        extension::{
            confidential_transfer::{
                instruction::{
                    CiphertextCiphertextEqualityProofContext,
                    CiphertextCiphertextEqualityProofData, ProofContextState, ProofInstruction,
                    ProofType,
                },
                ConfidentialTransferAccount, DecryptableBalance,
            },
            confidential_transfer_fee::{
                instruction::{
                    ConfidentialTransferFeeInstruction,
                    InitializeConfidentialTransferFeeConfigData,
                    WithdrawWithheldTokensFromAccountsData, WithdrawWithheldTokensFromMintData,
                },
                ConfidentialTransferFeeAmount, ConfidentialTransferFeeConfig,
                EncryptedWithheldAmount,
            },
            transfer_fee::TransferFeeConfig,
            BaseStateWithExtensions, BaseStateWithExtensionsMut, PodStateWithExtensionsMut,
        },
        instruction::{decode_instruction_data, decode_instruction_type},
        pod::{PodAccount, PodMint},
        processor::Processor,
        proof::decode_proof_instruction_context,
        solana_zk_token_sdk::zk_token_elgamal::pod::ElGamalPubkey,
    },
    bytemuck::Zeroable,
    solana_program::{
        account_info::{next_account_info, AccountInfo},
        entrypoint::ProgramResult,
        msg,
        program_error::ProgramError,
        pubkey::Pubkey,
        sysvar::instructions::get_instruction_relative,
    },
    spl_pod::{bytemuck::pod_from_bytes, optional_keys::OptionalNonZeroPubkey},
};

/// Processes an [InitializeConfidentialTransferFeeConfig] instruction.
fn process_initialize_confidential_transfer_fee_config(
    accounts: &[AccountInfo],
    authority: &OptionalNonZeroPubkey,
    withdraw_withheld_authority_elgamal_pubkey: &ElGamalPubkey,
) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let mint_account_info = next_account_info(account_info_iter)?;

    let mut mint_data = mint_account_info.data.borrow_mut();
    let mut mint = PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut mint_data)?;
    let extension = mint.init_extension::<ConfidentialTransferFeeConfig>(true)?;
    extension.authority = *authority;
    extension.withdraw_withheld_authority_elgamal_pubkey =
        *withdraw_withheld_authority_elgamal_pubkey;
    extension.harvest_to_mint_enabled = true.into();
    extension.withheld_amount = EncryptedWithheldAmount::zeroed();

    Ok(())
}

/// Processes a [WithdrawWithheldTokensFromMint] instruction.
#[cfg(feature = "zk-ops")]
fn process_withdraw_withheld_tokens_from_mint(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    new_decryptable_available_balance: &DecryptableBalance,
    proof_instruction_offset: i64,
) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let mint_account_info = next_account_info(account_info_iter)?;
    let destination_account_info = next_account_info(account_info_iter)?;

    // zero-knowledge proof certifies that the exact withheld amount is credited to
    // the destination account.
    let proof_context = verify_ciphertext_ciphertext_equality_proof(
        next_account_info(account_info_iter)?,
        proof_instruction_offset,
    )?;

    let authority_info = next_account_info(account_info_iter)?;
    let authority_info_data_len = authority_info.data_len();

    // unnecessary check, but helps for clarity
    check_program_account(mint_account_info.owner)?;
    let mut mint_data = mint_account_info.data.borrow_mut();
    let mut mint = PodStateWithExtensionsMut::<PodMint>::unpack(&mut mint_data)?;

    // mint must be extended for fees
    {
        let transfer_fee_config = mint.get_extension::<TransferFeeConfig>()?;
        let withdraw_withheld_authority =
            Option::<Pubkey>::from(transfer_fee_config.withdraw_withheld_authority)
                .ok_or(TokenError::NoAuthorityExists)?;
        Processor::validate_owner(
            program_id,
            &withdraw_withheld_authority,
            authority_info,
            authority_info_data_len,
            account_info_iter.as_slice(),
        )?;
    } // free `transfer_fee_config` to borrow `confidential_transfer_fee_config` as
      // mutable

    // mint must also be extended for confidential transfers, but forgo an explicit
    // check since it is not possible to initialize a confidential transfer mint
    // without it

    let confidential_transfer_fee_config =
        mint.get_extension_mut::<ConfidentialTransferFeeConfig>()?;

    // basic checks for the destination account - must be extended for confidential
    // transfers
    let mut destination_account_data = destination_account_info.data.borrow_mut();
    let mut destination_account =
        PodStateWithExtensionsMut::<PodAccount>::unpack(&mut destination_account_data)?;

    if destination_account.base.mint != *mint_account_info.key {
        return Err(TokenError::MintMismatch.into());
    }
    if destination_account.base.is_frozen() {
        return Err(TokenError::AccountFrozen.into());
    }
    let destination_confidential_transfer_account =
        destination_account.get_extension_mut::<ConfidentialTransferAccount>()?;
    destination_confidential_transfer_account.valid_as_destination()?;

    // The funds are moved from the mint to a destination account. Here, the
    // `source` equates to the withdraw withheld authority associated in the
    // mint.

    // Check that the withdraw authority ElGamal public key associated with the mint
    // is consistent with what was actually used to generate the zkp.
    if proof_context.source_pubkey
        != confidential_transfer_fee_config.withdraw_withheld_authority_elgamal_pubkey
    {
        return Err(TokenError::ConfidentialTransferElGamalPubkeyMismatch.into());
    }
    // Check that the ElGamal public key associated with the destination account is
    // consistent with what was actually used to generate the zkp.
    if proof_context.destination_pubkey != destination_confidential_transfer_account.elgamal_pubkey
    {
        return Err(TokenError::ConfidentialTransferElGamalPubkeyMismatch.into());
    }
    // Check that the withheld amount ciphertext is consistent with the ciphertext
    // data that was actually used to generate the zkp.
    if proof_context.source_ciphertext != confidential_transfer_fee_config.withheld_amount {
        return Err(TokenError::ConfidentialTransferBalanceMismatch.into());
    }

    // The proof data contains the mint withheld amount encrypted under the
    // destination ElGamal pubkey. Add this amount to the available balance.
    destination_confidential_transfer_account.available_balance = syscall::add(
        &destination_confidential_transfer_account.available_balance,
        &proof_context.destination_ciphertext,
    )
    .ok_or(ProgramError::InvalidInstructionData)?;

    destination_confidential_transfer_account.decryptable_available_balance =
        *new_decryptable_available_balance;

    // Fee is now withdrawn, so zero out the mint withheld amount.
    confidential_transfer_fee_config.withheld_amount = EncryptedWithheldAmount::zeroed();

    Ok(())
}

/// Verify zero-knowledge proof needed for a [WithdrawWithheldTokensFromMint]
/// instruction or a `[WithdrawWithheldTokensFromAccounts]` and return the
/// corresponding proof context.
fn verify_ciphertext_ciphertext_equality_proof(
    account_info: &AccountInfo<'_>,
    proof_instruction_offset: i64,
) -> Result<CiphertextCiphertextEqualityProofContext, ProgramError> {
    if proof_instruction_offset == 0 {
        // interpret `account_info` as a context state account
        check_zk_token_proof_program_account(account_info.owner)?;
        let context_state_account_data = account_info.data.borrow();
        let context_state = pod_from_bytes::<
            ProofContextState<CiphertextCiphertextEqualityProofContext>,
        >(&context_state_account_data)?;

        if context_state.proof_type != ProofType::CiphertextCiphertextEquality.into() {
            return Err(ProgramError::InvalidInstructionData);
        }

        Ok(context_state.proof_context)
    } else {
        // interpret `account_info` as a sysvar
        let zkp_instruction = get_instruction_relative(proof_instruction_offset, account_info)?;
        Ok(*decode_proof_instruction_context::<
            CiphertextCiphertextEqualityProofData,
            CiphertextCiphertextEqualityProofContext,
        >(
            ProofInstruction::VerifyCiphertextCiphertextEquality,
            &zkp_instruction,
        )?)
    }
}

/// Processes a [WithdrawWithheldTokensFromAccounts] instruction.
#[cfg(feature = "zk-ops")]
fn process_withdraw_withheld_tokens_from_accounts(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    num_token_accounts: u8,
    new_decryptable_available_balance: &DecryptableBalance,
    proof_instruction_offset: i64,
) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let mint_account_info = next_account_info(account_info_iter)?;
    let destination_account_info = next_account_info(account_info_iter)?;

    // zero-knowledge proof certifies that the exact aggregate withheld amount is
    // credited to the destination account.
    let proof_context = verify_ciphertext_ciphertext_equality_proof(
        next_account_info(account_info_iter)?,
        proof_instruction_offset,
    )?;

    let authority_info = next_account_info(account_info_iter)?;
    let authority_info_data_len = authority_info.data_len();
    let account_infos = account_info_iter.as_slice();
    let num_signers = account_infos
        .len()
        .saturating_sub(num_token_accounts as usize);

    // unnecessary check, but helps for clarity
    check_program_account(mint_account_info.owner)?;
    let mut mint_data = mint_account_info.data.borrow_mut();
    let mut mint = PodStateWithExtensionsMut::<PodMint>::unpack(&mut mint_data)?;

    // mint must be extended for fees
    let transfer_fee_config = mint.get_extension::<TransferFeeConfig>()?;
    let withdraw_withheld_authority =
        Option::<Pubkey>::from(transfer_fee_config.withdraw_withheld_authority)
            .ok_or(TokenError::NoAuthorityExists)?;
    Processor::validate_owner(
        program_id,
        &withdraw_withheld_authority,
        authority_info,
        authority_info_data_len,
        &account_infos[..num_signers],
    )?;

    let mut destination_account_data = destination_account_info.data.borrow_mut();
    let mut destination_account =
        PodStateWithExtensionsMut::<PodAccount>::unpack(&mut destination_account_data)?;
    if destination_account.base.mint != *mint_account_info.key {
        return Err(TokenError::MintMismatch.into());
    }
    if destination_account.base.is_frozen() {
        return Err(TokenError::AccountFrozen.into());
    }

    // Sum up the withheld amounts in all the accounts.
    let mut aggregate_withheld_amount = EncryptedWithheldAmount::zeroed();
    for account_info in &account_infos[num_signers..] {
        // self-harvest, can't double-borrow the underlying data
        if account_info.key == destination_account_info.key {
            let destination_confidential_transfer_fee_amount = destination_account
                .get_extension_mut::<ConfidentialTransferFeeAmount>()
                .map_err(|_| TokenError::InvalidState)?;

            aggregate_withheld_amount = syscall::add(
                &aggregate_withheld_amount,
                &destination_confidential_transfer_fee_amount.withheld_amount,
            )
            .ok_or(ProgramError::InvalidInstructionData)?;

            destination_confidential_transfer_fee_amount.withheld_amount =
                EncryptedWithheldAmount::zeroed();
        } else {
            match harvest_from_account(mint_account_info.key, account_info) {
                Ok(encrypted_withheld_amount) => {
                    aggregate_withheld_amount =
                        syscall::add(&aggregate_withheld_amount, &encrypted_withheld_amount)
                            .ok_or(ProgramError::InvalidInstructionData)?;
                }
                Err(e) => {
                    msg!("Error harvesting from {}: {}", account_info.key, e);
                }
            }
        }
    }

    let destination_confidential_transfer_account =
        destination_account.get_extension_mut::<ConfidentialTransferAccount>()?;
    destination_confidential_transfer_account.valid_as_destination()?;

    // The funds are moved from the accounts to a destination account. Here, the
    // `source` equates to the withdraw withheld authority associated in the
    // mint.

    // Checks that the withdraw authority ElGamal public key associated with the
    // mint is consistent with what was actually used to generate the zkp.
    let confidential_transfer_fee_config =
        mint.get_extension_mut::<ConfidentialTransferFeeConfig>()?;
    if proof_context.source_pubkey
        != confidential_transfer_fee_config.withdraw_withheld_authority_elgamal_pubkey
    {
        return Err(TokenError::ConfidentialTransferElGamalPubkeyMismatch.into());
    }
    // Checks that the ElGamal public key associated with the destination account is
    // consistent with what was actually used to generate the zkp.
    if proof_context.destination_pubkey != destination_confidential_transfer_account.elgamal_pubkey
    {
        return Err(TokenError::ConfidentialTransferElGamalPubkeyMismatch.into());
    }
    // Checks that the withheld amount ciphertext is consistent with the ciphertext
    // data that was actually used to generate the zkp.
    if proof_context.source_ciphertext != aggregate_withheld_amount {
        return Err(TokenError::ConfidentialTransferBalanceMismatch.into());
    }

    // The proof data contains the mint withheld amount encrypted under the
    // destination ElGamal pubkey. This amount is added to the destination
    // available balance.
    destination_confidential_transfer_account.available_balance = syscall::add(
        &destination_confidential_transfer_account.available_balance,
        &proof_context.destination_ciphertext,
    )
    .ok_or(ProgramError::InvalidInstructionData)?;

    destination_confidential_transfer_account.decryptable_available_balance =
        *new_decryptable_available_balance;

    Ok(())
}

#[cfg(feature = "zk-ops")]
fn harvest_from_account<'b>(
    mint_key: &'b Pubkey,
    token_account_info: &'b AccountInfo<'_>,
) -> Result<EncryptedWithheldAmount, TokenError> {
    let mut token_account_data = token_account_info.data.borrow_mut();
    let mut token_account =
        PodStateWithExtensionsMut::<PodAccount>::unpack(&mut token_account_data)
            .map_err(|_| TokenError::InvalidState)?;
    if token_account.base.mint != *mint_key {
        return Err(TokenError::MintMismatch);
    }
    check_program_account(token_account_info.owner).map_err(|_| TokenError::InvalidState)?;

    let confidential_transfer_token_account = token_account
        .get_extension_mut::<ConfidentialTransferFeeAmount>()
        .map_err(|_| TokenError::InvalidState)?;

    let withheld_amount = confidential_transfer_token_account.withheld_amount;
    confidential_transfer_token_account.withheld_amount = EncryptedWithheldAmount::zeroed();

    Ok(withheld_amount)
}

/// Process a [HarvestWithheldTokensToMint] instruction.
#[cfg(feature = "zk-ops")]
fn process_harvest_withheld_tokens_to_mint(accounts: &[AccountInfo]) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let mint_account_info = next_account_info(account_info_iter)?;
    let token_account_infos = account_info_iter.as_slice();

    let mut mint_data = mint_account_info.data.borrow_mut();
    let mut mint = PodStateWithExtensionsMut::<PodMint>::unpack(&mut mint_data)?;
    mint.get_extension::<TransferFeeConfig>()?;
    let confidential_transfer_fee_mint =
        mint.get_extension_mut::<ConfidentialTransferFeeConfig>()?;

    let harvest_to_mint_enabled: bool = confidential_transfer_fee_mint
        .harvest_to_mint_enabled
        .into();
    if !harvest_to_mint_enabled {
        return Err(TokenError::HarvestToMintDisabled.into());
    }

    for token_account_info in token_account_infos {
        match harvest_from_account(mint_account_info.key, token_account_info) {
            Ok(withheld_amount) => {
                let new_mint_withheld_amount = syscall::add(
                    &confidential_transfer_fee_mint.withheld_amount,
                    &withheld_amount,
                )
                .ok_or(ProgramError::InvalidInstructionData)?;

                confidential_transfer_fee_mint.withheld_amount = new_mint_withheld_amount;
            }
            Err(e) => {
                msg!("Error harvesting from {}: {}", token_account_info.key, e);
            }
        }
    }
    Ok(())
}

/// Process a [EnableHarvestToMint] instruction.
fn process_enable_harvest_to_mint(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let mint_info = next_account_info(account_info_iter)?;
    let authority_info = next_account_info(account_info_iter)?;
    let authority_info_data_len = authority_info.data_len();

    check_program_account(mint_info.owner)?;
    let mint_data = &mut mint_info.data.borrow_mut();
    let mut mint = PodStateWithExtensionsMut::<PodMint>::unpack(mint_data)?;
    let confidential_transfer_fee_mint =
        mint.get_extension_mut::<ConfidentialTransferFeeConfig>()?;

    let maybe_confidential_transfer_fee_authority: Option<Pubkey> =
        confidential_transfer_fee_mint.authority.into();
    let confidential_transfer_fee_authority =
        maybe_confidential_transfer_fee_authority.ok_or(TokenError::NoAuthorityExists)?;

    Processor::validate_owner(
        program_id,
        &confidential_transfer_fee_authority,
        authority_info,
        authority_info_data_len,
        account_info_iter.as_slice(),
    )?;

    confidential_transfer_fee_mint.harvest_to_mint_enabled = true.into();
    Ok(())
}

/// Process a [DisableHarvestToMint] instruction.
fn process_disable_harvest_to_mint(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let mint_info = next_account_info(account_info_iter)?;
    let authority_info = next_account_info(account_info_iter)?;
    let authority_info_data_len = authority_info.data_len();

    check_program_account(mint_info.owner)?;
    let mint_data = &mut mint_info.data.borrow_mut();
    let mut mint = PodStateWithExtensionsMut::<PodMint>::unpack(mint_data)?;
    let confidential_transfer_fee_mint =
        mint.get_extension_mut::<ConfidentialTransferFeeConfig>()?;

    let maybe_confidential_transfer_fee_authority: Option<Pubkey> =
        confidential_transfer_fee_mint.authority.into();
    let confidential_transfer_fee_authority =
        maybe_confidential_transfer_fee_authority.ok_or(TokenError::NoAuthorityExists)?;

    Processor::validate_owner(
        program_id,
        &confidential_transfer_fee_authority,
        authority_info,
        authority_info_data_len,
        account_info_iter.as_slice(),
    )?;

    confidential_transfer_fee_mint.harvest_to_mint_enabled = false.into();
    Ok(())
}

#[allow(dead_code)]
pub(crate) fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    input: &[u8],
) -> ProgramResult {
    check_program_account(program_id)?;

    match decode_instruction_type(input)? {
        ConfidentialTransferFeeInstruction::InitializeConfidentialTransferFeeConfig => {
            msg!("ConfidentialTransferFeeInstruction::InitializeConfidentialTransferFeeConfig");
            let data =
                decode_instruction_data::<InitializeConfidentialTransferFeeConfigData>(input)?;
            process_initialize_confidential_transfer_fee_config(
                accounts,
                &data.authority,
                &data.withdraw_withheld_authority_elgamal_pubkey,
            )
        }
        ConfidentialTransferFeeInstruction::WithdrawWithheldTokensFromMint => {
            msg!("ConfidentialTransferFeeInstruction::WithdrawWithheldTokensFromMint");
            #[cfg(feature = "zk-ops")]
            {
                let data = decode_instruction_data::<WithdrawWithheldTokensFromMintData>(input)?;
                process_withdraw_withheld_tokens_from_mint(
                    program_id,
                    accounts,
                    &data.new_decryptable_available_balance,
                    data.proof_instruction_offset as i64,
                )
            }
            #[cfg(not(feature = "zk-ops"))]
            {
                Err(ProgramError::InvalidInstructionData)
            }
        }
        ConfidentialTransferFeeInstruction::WithdrawWithheldTokensFromAccounts => {
            msg!("ConfidentialTransferFeeInstruction::WithdrawWithheldTokensFromAccounts");
            #[cfg(feature = "zk-ops")]
            {
                let data =
                    decode_instruction_data::<WithdrawWithheldTokensFromAccountsData>(input)?;
                process_withdraw_withheld_tokens_from_accounts(
                    program_id,
                    accounts,
                    data.num_token_accounts,
                    &data.new_decryptable_available_balance,
                    data.proof_instruction_offset as i64,
                )
            }
            #[cfg(not(feature = "zk-ops"))]
            {
                Err(ProgramError::InvalidInstructionData)
            }
        }
        ConfidentialTransferFeeInstruction::HarvestWithheldTokensToMint => {
            msg!("ConfidentialTransferFeeInstruction::HarvestWithheldTokensToMint");
            #[cfg(feature = "zk-ops")]
            {
                process_harvest_withheld_tokens_to_mint(accounts)
            }
            #[cfg(not(feature = "zk-ops"))]
            {
                Err(ProgramError::InvalidInstructionData)
            }
        }
        ConfidentialTransferFeeInstruction::EnableHarvestToMint => {
            msg!("ConfidentialTransferFeeInstruction::EnableHarvestToMint");
            process_enable_harvest_to_mint(program_id, accounts)
        }
        ConfidentialTransferFeeInstruction::DisableHarvestToMint => {
            msg!("ConfidentialTransferFeeInstruction::DisableHarvestToMint");
            process_disable_harvest_to_mint(program_id, accounts)
        }
    }
}