solana_zk_token_sdk/instruction/
zero_balance.rs#[cfg(not(target_os = "solana"))]
use {
crate::{
encryption::elgamal::{ElGamalCiphertext, ElGamalKeypair},
errors::{ProofGenerationError, ProofVerificationError},
sigma_proofs::zero_balance_proof::ZeroBalanceProof,
transcript::TranscriptProtocol,
},
merlin::Transcript,
std::convert::TryInto,
};
use {
crate::{
instruction::{ProofType, ZkProofData},
zk_token_elgamal::pod,
},
bytemuck_derive::{Pod, Zeroable},
};
#[derive(Clone, Copy, Pod, Zeroable)]
#[repr(C)]
pub struct ZeroBalanceProofData {
pub context: ZeroBalanceProofContext, pub proof: pod::ZeroBalanceProof, }
#[derive(Clone, Copy, Pod, Zeroable)]
#[repr(C)]
pub struct ZeroBalanceProofContext {
pub pubkey: pod::ElGamalPubkey, pub ciphertext: pod::ElGamalCiphertext, }
#[cfg(not(target_os = "solana"))]
impl ZeroBalanceProofData {
pub fn new(
keypair: &ElGamalKeypair,
ciphertext: &ElGamalCiphertext,
) -> Result<Self, ProofGenerationError> {
let pod_pubkey = pod::ElGamalPubkey(keypair.pubkey().into());
let pod_ciphertext = pod::ElGamalCiphertext(ciphertext.to_bytes());
let context = ZeroBalanceProofContext {
pubkey: pod_pubkey,
ciphertext: pod_ciphertext,
};
let mut transcript = context.new_transcript();
let proof = ZeroBalanceProof::new(keypair, ciphertext, &mut transcript).into();
Ok(ZeroBalanceProofData { context, proof })
}
}
impl ZkProofData<ZeroBalanceProofContext> for ZeroBalanceProofData {
const PROOF_TYPE: ProofType = ProofType::ZeroBalance;
fn context_data(&self) -> &ZeroBalanceProofContext {
&self.context
}
#[cfg(not(target_os = "solana"))]
fn verify_proof(&self) -> Result<(), ProofVerificationError> {
let mut transcript = self.context.new_transcript();
let pubkey = self.context.pubkey.try_into()?;
let ciphertext = self.context.ciphertext.try_into()?;
let proof: ZeroBalanceProof = self.proof.try_into()?;
proof
.verify(&pubkey, &ciphertext, &mut transcript)
.map_err(|e| e.into())
}
}
#[allow(non_snake_case)]
#[cfg(not(target_os = "solana"))]
impl ZeroBalanceProofContext {
fn new_transcript(&self) -> Transcript {
let mut transcript = Transcript::new(b"ZeroBalanceProof");
transcript.append_pubkey(b"pubkey", &self.pubkey);
transcript.append_ciphertext(b"ciphertext", &self.ciphertext);
transcript
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_zero_balance_proof_instruction_correctness() {
let keypair = ElGamalKeypair::new_rand();
let ciphertext = keypair.pubkey().encrypt(0_u64);
let zero_balance_proof_data = ZeroBalanceProofData::new(&keypair, &ciphertext).unwrap();
assert!(zero_balance_proof_data.verify_proof().is_ok());
let ciphertext = keypair.pubkey().encrypt(1_u64);
let zero_balance_proof_data = ZeroBalanceProofData::new(&keypair, &ciphertext).unwrap();
assert!(zero_balance_proof_data.verify_proof().is_err());
}
}