solana_zk_token_sdk/zk_token_elgamal/
ops.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
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
use crate::{
    curve25519::{
        ristretto::{add_ristretto, multiply_ristretto, subtract_ristretto, PodRistrettoPoint},
        scalar::PodScalar,
    },
    zk_token_elgamal::pod,
};

const SHIFT_BITS: usize = 16;

const G: PodRistrettoPoint = PodRistrettoPoint([
    226, 242, 174, 10, 106, 188, 78, 113, 168, 132, 169, 97, 197, 0, 81, 95, 88, 227, 11, 106, 165,
    130, 221, 141, 182, 166, 89, 69, 224, 141, 45, 118,
]);

/// Add two ElGamal ciphertexts
pub fn add(
    left_ciphertext: &pod::ElGamalCiphertext,
    right_ciphertext: &pod::ElGamalCiphertext,
) -> Option<pod::ElGamalCiphertext> {
    let (left_commitment, left_handle): (pod::PedersenCommitment, pod::DecryptHandle) =
        (*left_ciphertext).into();
    let (right_commitment, right_handle): (pod::PedersenCommitment, pod::DecryptHandle) =
        (*right_ciphertext).into();

    let result_commitment: pod::PedersenCommitment =
        add_ristretto(&left_commitment.into(), &right_commitment.into())?.into();
    let result_handle: pod::DecryptHandle =
        add_ristretto(&left_handle.into(), &right_handle.into())?.into();

    Some((result_commitment, result_handle).into())
}

/// Multiply an ElGamal ciphertext by a scalar
pub fn multiply(
    scalar: &PodScalar,
    ciphertext: &pod::ElGamalCiphertext,
) -> Option<pod::ElGamalCiphertext> {
    let (commitment, handle): (pod::PedersenCommitment, pod::DecryptHandle) = (*ciphertext).into();

    let commitment_point: PodRistrettoPoint = commitment.into();
    let handle_point: PodRistrettoPoint = handle.into();

    let result_commitment: pod::PedersenCommitment =
        multiply_ristretto(scalar, &commitment_point)?.into();
    let result_handle: pod::DecryptHandle = multiply_ristretto(scalar, &handle_point)?.into();

    Some((result_commitment, result_handle).into())
}

/// Compute `left_ciphertext + (right_ciphertext_lo + 2^16 * right_ciphertext_hi)`
pub fn add_with_lo_hi(
    left_ciphertext: &pod::ElGamalCiphertext,
    right_ciphertext_lo: &pod::ElGamalCiphertext,
    right_ciphertext_hi: &pod::ElGamalCiphertext,
) -> Option<pod::ElGamalCiphertext> {
    let shift_scalar = to_scalar(1_u64 << SHIFT_BITS);
    let shifted_right_ciphertext_hi = multiply(&shift_scalar, right_ciphertext_hi)?;
    let combined_right_ciphertext = add(right_ciphertext_lo, &shifted_right_ciphertext_hi)?;
    add(left_ciphertext, &combined_right_ciphertext)
}

/// Subtract two ElGamal ciphertexts
pub fn subtract(
    left_ciphertext: &pod::ElGamalCiphertext,
    right_ciphertext: &pod::ElGamalCiphertext,
) -> Option<pod::ElGamalCiphertext> {
    let (left_commitment, left_handle): (pod::PedersenCommitment, pod::DecryptHandle) =
        (*left_ciphertext).into();
    let (right_commitment, right_handle): (pod::PedersenCommitment, pod::DecryptHandle) =
        (*right_ciphertext).into();

    let result_commitment: pod::PedersenCommitment =
        subtract_ristretto(&left_commitment.into(), &right_commitment.into())?.into();
    let result_handle: pod::DecryptHandle =
        subtract_ristretto(&left_handle.into(), &right_handle.into())?.into();

    Some((result_commitment, result_handle).into())
}

/// Compute `left_ciphertext - (right_ciphertext_lo + 2^16 * right_ciphertext_hi)`
pub fn subtract_with_lo_hi(
    left_ciphertext: &pod::ElGamalCiphertext,
    right_ciphertext_lo: &pod::ElGamalCiphertext,
    right_ciphertext_hi: &pod::ElGamalCiphertext,
) -> Option<pod::ElGamalCiphertext> {
    let shift_scalar = to_scalar(1_u64 << SHIFT_BITS);
    let shifted_right_ciphertext_hi = multiply(&shift_scalar, right_ciphertext_hi)?;
    let combined_right_ciphertext = add(right_ciphertext_lo, &shifted_right_ciphertext_hi)?;
    subtract(left_ciphertext, &combined_right_ciphertext)
}

/// Add a constant amount to a ciphertext
pub fn add_to(ciphertext: &pod::ElGamalCiphertext, amount: u64) -> Option<pod::ElGamalCiphertext> {
    let amount_scalar = to_scalar(amount);
    let amount_point = multiply_ristretto(&amount_scalar, &G)?;

    let (commitment, handle): (pod::PedersenCommitment, pod::DecryptHandle) = (*ciphertext).into();
    let commitment_point: PodRistrettoPoint = commitment.into();

    let result_commitment: pod::PedersenCommitment =
        add_ristretto(&commitment_point, &amount_point)?.into();
    Some((result_commitment, handle).into())
}

/// Subtract a constant amount to a ciphertext
pub fn subtract_from(
    ciphertext: &pod::ElGamalCiphertext,
    amount: u64,
) -> Option<pod::ElGamalCiphertext> {
    let amount_scalar = to_scalar(amount);
    let amount_point = multiply_ristretto(&amount_scalar, &G)?;

    let (commitment, handle): (pod::PedersenCommitment, pod::DecryptHandle) = (*ciphertext).into();
    let commitment_point: PodRistrettoPoint = commitment.into();

    let result_commitment: pod::PedersenCommitment =
        subtract_ristretto(&commitment_point, &amount_point)?.into();
    Some((result_commitment, handle).into())
}

/// Convert a `u64` amount into a curve25519 scalar
fn to_scalar(amount: u64) -> PodScalar {
    let mut bytes = [0u8; 32];
    bytes[..8].copy_from_slice(&amount.to_le_bytes());
    PodScalar(bytes)
}

#[cfg(test)]
mod tests {
    use {
        crate::{
            encryption::{
                elgamal::{ElGamalCiphertext, ElGamalKeypair},
                pedersen::{Pedersen, PedersenOpening},
            },
            instruction::transfer::split_u64,
            zk_token_elgamal::{ops, pod},
        },
        bytemuck::Zeroable,
        curve25519_dalek::scalar::Scalar,
        std::convert::TryInto,
    };

    const TWO_16: u64 = 65536;

    #[test]
    fn test_zero_ct() {
        let spendable_balance = pod::ElGamalCiphertext::zeroed();
        let spendable_ct: ElGamalCiphertext = spendable_balance.try_into().unwrap();

        // spendable_ct should be an encryption of 0 for any public key when
        // `PedersenOpen::default()` is used
        let keypair = ElGamalKeypair::new_rand();
        let public = keypair.pubkey();
        let balance: u64 = 0;
        assert_eq!(
            spendable_ct,
            public.encrypt_with(balance, &PedersenOpening::default())
        );

        // homomorphism should work like any other ciphertext
        let open = PedersenOpening::new_rand();
        let transfer_amount_ct = public.encrypt_with(55_u64, &open);
        let transfer_amount_pod: pod::ElGamalCiphertext = transfer_amount_ct.into();

        let sum = ops::add(&spendable_balance, &transfer_amount_pod).unwrap();

        let expected: pod::ElGamalCiphertext = public.encrypt_with(55_u64, &open).into();
        assert_eq!(expected, sum);
    }

    #[test]
    fn test_add_to() {
        let spendable_balance = pod::ElGamalCiphertext::zeroed();

        let added_ct = ops::add_to(&spendable_balance, 55).unwrap();

        let keypair = ElGamalKeypair::new_rand();
        let public = keypair.pubkey();
        let expected: pod::ElGamalCiphertext = public
            .encrypt_with(55_u64, &PedersenOpening::default())
            .into();

        assert_eq!(expected, added_ct);
    }

    #[test]
    fn test_subtract_from() {
        let amount = 77_u64;
        let keypair = ElGamalKeypair::new_rand();
        let public = keypair.pubkey();
        let open = PedersenOpening::new_rand();
        let encrypted_amount: pod::ElGamalCiphertext = public.encrypt_with(amount, &open).into();

        let subtracted_ct = ops::subtract_from(&encrypted_amount, 55).unwrap();

        let expected: pod::ElGamalCiphertext = public.encrypt_with(22_u64, &open).into();

        assert_eq!(expected, subtracted_ct);
    }

    #[test]
    fn test_transfer_arithmetic() {
        // transfer amount
        let transfer_amount: u64 = 55;
        let (amount_lo, amount_hi) = split_u64(transfer_amount, 16);

        // generate public keys
        let source_keypair = ElGamalKeypair::new_rand();
        let source_pk = source_keypair.pubkey();

        let dest_keypair = ElGamalKeypair::new_rand();
        let dest_pk = dest_keypair.pubkey();

        let auditor_keypair = ElGamalKeypair::new_rand();
        let auditor_pk = auditor_keypair.pubkey();

        // commitments associated with TransferRangeProof
        let (comm_lo, open_lo) = Pedersen::new(amount_lo);
        let (comm_hi, open_hi) = Pedersen::new(amount_hi);

        let comm_lo: pod::PedersenCommitment = comm_lo.into();
        let comm_hi: pod::PedersenCommitment = comm_hi.into();

        // decryption handles associated with TransferValidityProof
        let handle_source_lo: pod::DecryptHandle = source_pk.decrypt_handle(&open_lo).into();
        let handle_dest_lo: pod::DecryptHandle = dest_pk.decrypt_handle(&open_lo).into();
        let _handle_auditor_lo: pod::DecryptHandle = auditor_pk.decrypt_handle(&open_lo).into();

        let handle_source_hi: pod::DecryptHandle = source_pk.decrypt_handle(&open_hi).into();
        let handle_dest_hi: pod::DecryptHandle = dest_pk.decrypt_handle(&open_hi).into();
        let _handle_auditor_hi: pod::DecryptHandle = auditor_pk.decrypt_handle(&open_hi).into();

        // source spendable and recipient pending
        let source_open = PedersenOpening::new_rand();
        let dest_open = PedersenOpening::new_rand();

        let source_spendable_ct: pod::ElGamalCiphertext =
            source_pk.encrypt_with(77_u64, &source_open).into();
        let dest_pending_ct: pod::ElGamalCiphertext =
            dest_pk.encrypt_with(77_u64, &dest_open).into();

        // program arithmetic for the source account
        let source_lo_ct: pod::ElGamalCiphertext = (comm_lo, handle_source_lo).into();
        let source_hi_ct: pod::ElGamalCiphertext = (comm_hi, handle_source_hi).into();

        let final_source_spendable =
            ops::subtract_with_lo_hi(&source_spendable_ct, &source_lo_ct, &source_hi_ct).unwrap();

        let final_source_open =
            source_open - (open_lo.clone() + open_hi.clone() * Scalar::from(TWO_16));
        let expected_source: pod::ElGamalCiphertext =
            source_pk.encrypt_with(22_u64, &final_source_open).into();
        assert_eq!(expected_source, final_source_spendable);

        // program arithmetic for the destination account
        let dest_lo_ct: pod::ElGamalCiphertext = (comm_lo, handle_dest_lo).into();
        let dest_hi_ct: pod::ElGamalCiphertext = (comm_hi, handle_dest_hi).into();

        let final_dest_pending =
            ops::add_with_lo_hi(&dest_pending_ct, &dest_lo_ct, &dest_hi_ct).unwrap();

        let final_dest_open = dest_open + (open_lo + open_hi * Scalar::from(TWO_16));
        let expected_dest_ct: pod::ElGamalCiphertext =
            dest_pk.encrypt_with(132_u64, &final_dest_open).into();
        assert_eq!(expected_dest_ct, final_dest_pending);
    }
}