tari_crypto 0.23.0

Tari Cryptography library
Documentation
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
// Copyright 2021. The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use alloc::vec::Vec;
use core::{
    cmp::Ordering,
    hash::{Hash, Hasher},
    ops::{Add, Mul},
};

use rand_core::{CryptoRng, Rng};
use snafu::prelude::*;
use tari_utilities::ByteArray;

use crate::{
    alloc::borrow::ToOwned,
    commitment::{HomomorphicCommitment, HomomorphicCommitmentFactory},
    keys::{PublicKey, SecretKey},
    signatures::SchnorrSignature,
};

/// An error when creating a commitment signature
#[derive(Clone, Debug, Snafu, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[allow(missing_docs)]
pub enum CommitmentAndPublicKeySignatureError {
    #[snafu(display("An invalid challenge was provided"))]
    InvalidChallenge,
}

/// # Commitment and public key (CAPK) signatures
///
/// Given a commitment `commitment = a*H + x*G` and group element `pubkey = y*G`, a CAPK signature is based on
/// a representation proof of both openings: `(a, x)` and `y`. It additionally binds to arbitrary message data `m`
/// via the challenge to produce a signature construction.
///
/// It is used in Tari protocols as part of transaction authorization.
///
/// The construction works as follows:
/// - Sample scalar nonces `r_a, r_x, r_y` uniformly at random.
/// - Compute ephemeral values `ephemeral_commitment = r_a*H + r_x*G` and `ephemeral_pubkey = r_y*G`.
/// - Use strong Fiat-Shamir to produce a challenge `e`. If `e == 0` (this is unlikely), abort and start over.
/// - Compute the responses `u_a = r_a + e*a` and `u_x = r_x + e*x` and `u_y = r_y + e*y`.
///
/// The signature is the tuple `(ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y)`.
///
/// To verify:
/// - The verifier computes the challenge `e` and rejects the signature if `e == 0` (this is unlikely).
/// - Verification succeeds if and only if the following equations hold: `u_a*H + u*x*G == ephemeral_commitment +
///   e*commitment` `u_y*G == ephemeral_pubkey + e*pubkey`
///
/// We note that it is possible to make verification slightly more efficient. To do so, the verifier selects a nonzero
/// scalar weight `w` uniformly at random (not through Fiat-Shamir!) and accepts the signature if and only if the
/// following equation holds:
///     `u_a*H + (u_x + w*u_y)*G - ephemeral_commitment - w*ephemeral_pubkey - e*commitment - (w*e)*pubkey == 0`
/// The use of efficient multiscalar multiplication algorithms may also be useful for efficiency.
/// The use of precomputation tables for `G` and `H` may also be useful for efficiency.

#[derive(Debug, Clone)]
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CommitmentAndPublicKeySignature<P, K> {
    pub(crate) ephemeral_commitment: HomomorphicCommitment<P>,
    pub(crate) ephemeral_pubkey: P,
    pub(crate) u_a: K,
    pub(crate) u_x: K,
    pub(crate) u_y: K,
}

impl<P, K> CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    K: SecretKey,
{
    /// Creates a new [CommitmentSignature]
    pub fn new(ephemeral_commitment: HomomorphicCommitment<P>, ephemeral_pubkey: P, u_a: K, u_x: K, u_y: K) -> Self {
        CommitmentAndPublicKeySignature {
            ephemeral_commitment,
            ephemeral_pubkey,
            u_a,
            u_x,
            u_y,
        }
    }

    /// Complete a signature using the given challenge. The challenge is provided by the caller to support the
    /// multiparty use case. It is _very important_ that it be computed using strong Fiat-Shamir! Further, the
    /// values `r_a, r_x, r_y` are nonces, must be sampled uniformly at random, and must never be reused.
    #[allow(clippy::too_many_arguments)]
    pub fn sign<C>(
        a: &K,
        x: &K,
        y: &K,
        r_a: &K,
        r_x: &K,
        r_y: &K,
        challenge: &[u8],
        factory: &C,
    ) -> Result<Self, CommitmentAndPublicKeySignatureError>
    where
        K: Mul<P, Output = P>,
        for<'a> &'a K: Add<&'a K, Output = K>,
        for<'a> &'a K: Mul<&'a K, Output = K>,
        C: HomomorphicCommitmentFactory<P = P>,
    {
        // The challenge is computed by wide reduction
        let e = match K::from_uniform_bytes(challenge) {
            Ok(e) => e,
            Err(_) => return Err(CommitmentAndPublicKeySignatureError::InvalidChallenge),
        };

        // The challenge cannot be zero
        if e == K::default() {
            return Err(CommitmentAndPublicKeySignatureError::InvalidChallenge);
        }

        // Compute the response values
        let ea = &e * a;
        let ex = &e * x;
        let ey = &e * y;

        let u_a = r_a + &ea;
        let u_x = r_x + &ex;
        let u_y = r_y + &ey;

        // Compute the initial values
        let ephemeral_commitment = factory.commit(r_x, r_a);
        let ephemeral_pubkey = P::from_secret_key(r_y);

        Ok(Self::new(ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y))
    }

    /// Verify a signature on a commitment and group element statement using a given challenge (as a byte array)
    pub fn verify_challenge<'a, C, R>(
        &self,
        commitment: &'a HomomorphicCommitment<P>,
        pubkey: &'a P,
        challenge: &[u8],
        factory: &C,
        rng: &mut R,
    ) -> bool
    where
        for<'b> &'a HomomorphicCommitment<P>: Mul<&'b K, Output = HomomorphicCommitment<P>>,
        for<'b> &'b P: Mul<&'b K, Output = P>,
        for<'b> &'b HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
        for<'b> &'b P: Add<&'b P, Output = P>,
        for<'b> &'b K: Mul<&'b K, Output = K>,
        for<'b> &'b K: Add<&'b K, Output = K>,
        C: HomomorphicCommitmentFactory<P = P>,
        R: Rng + CryptoRng,
    {
        // The challenge is computed by wide reduction
        let e = match K::from_uniform_bytes(challenge) {
            Ok(e) => e,
            Err(_) => return false,
        };

        self.verify(commitment, pubkey, &e, factory, rng)
    }

    /// Verify a signature on a commitment and group element statement using a given challenge (as a scalar)
    pub fn verify<'a, C, R>(
        &self,
        commitment: &'a HomomorphicCommitment<P>,
        pubkey: &'a P,
        challenge: &K,
        factory: &C,
        rng: &mut R,
    ) -> bool
    where
        for<'b> &'a HomomorphicCommitment<P>: Mul<&'b K, Output = HomomorphicCommitment<P>>,
        for<'b> &'b P: Mul<&'b K, Output = P>,
        for<'b> &'b HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
        for<'b> &'b P: Add<&'b P, Output = P>,
        for<'b> &'b K: Mul<&'b K, Output = K>,
        for<'b> &'b K: Add<&'b K, Output = K>,
        C: HomomorphicCommitmentFactory<P = P>,
        R: Rng + CryptoRng,
    {
        // Reject a zero commitment and public key
        if commitment.as_public_key() == &P::default() || pubkey == &P::default() {
            return false;
        }

        // The challenge cannot be zero
        if *challenge == K::default() {
            return false;
        }

        // Use a single weighted equation for verification to avoid unnecessary group operations
        // For now, we use naive multiscalar multiplication, but offload the commitment computation
        // This allows for the use of precomputation within the commitment itself, which is more efficient
        let w = K::random(rng); // must be random and not Fiat-Shamir!

        // u_a*H + (u_x + w*u_y)*G == ephemeral_commitment + w*ephemeral_pubkey + e*commitment + (w*e)*pubkey
        let verifier_lhs = factory
            .commit(&(&self.u_x + &(&w * &self.u_y)), &self.u_a)
            .as_public_key()
            .to_owned();
        let verifier_rhs_unweighted =
            self.ephemeral_commitment.as_public_key() + (commitment * challenge).as_public_key();
        let verifier_rhs_weighted = &self.ephemeral_pubkey * &w + pubkey * &(&w * challenge);

        verifier_lhs == verifier_rhs_unweighted + verifier_rhs_weighted
    }

    /// Get the signature tuple `(ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y)`
    pub fn complete_signature_tuple(&self) -> (&HomomorphicCommitment<P>, &P, &K, &K, &K) {
        (
            &self.ephemeral_commitment,
            &self.ephemeral_pubkey,
            &self.u_a,
            &self.u_x,
            &self.u_y,
        )
    }

    /// Get the response value `u_a`
    pub fn u_a(&self) -> &K {
        &self.u_a
    }

    /// Get the response value `u_x`
    pub fn u_x(&self) -> &K {
        &self.u_x
    }

    /// Get the response value `u_y`
    pub fn u_y(&self) -> &K {
        &self.u_y
    }

    /// Get the ephemeral commitment `ephemeral_commitment`
    pub fn ephemeral_commitment(&self) -> &HomomorphicCommitment<P> {
        &self.ephemeral_commitment
    }

    /// Get the ephemeral public key `ephemeral_pubkey`
    pub fn ephemeral_pubkey(&self) -> &P {
        &self.ephemeral_pubkey
    }

    /// Produce a canonical byte representation of the commitment signature
    pub fn to_vec(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(2 * P::key_length() + 3 * K::key_length());
        buf.extend_from_slice(self.ephemeral_commitment().as_bytes());
        buf.extend_from_slice(self.ephemeral_pubkey().as_bytes());
        buf.extend_from_slice(self.u_a().as_bytes());
        buf.extend_from_slice(self.u_x().as_bytes());
        buf.extend_from_slice(self.u_y().as_bytes());
        buf
    }
}

impl<'a, 'b, P, K> Add<&'b CommitmentAndPublicKeySignature<P, K>> for &'a CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    &'a HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
    &'a P: Add<&'b P, Output = P>,
    K: SecretKey,
    &'a K: Add<&'b K, Output = K>,
{
    type Output = CommitmentAndPublicKeySignature<P, K>;

    fn add(self, rhs: &'b CommitmentAndPublicKeySignature<P, K>) -> CommitmentAndPublicKeySignature<P, K> {
        let ephemeral_commitment_sum = self.ephemeral_commitment() + rhs.ephemeral_commitment();
        let ephemeral_pubkey_sum_sum = self.ephemeral_pubkey() + rhs.ephemeral_pubkey();
        let u_a_sum = self.u_a() + rhs.u_a();
        let u_x_sum = self.u_x() + rhs.u_x();
        let u_y_sum = self.u_y() + rhs.u_y();

        CommitmentAndPublicKeySignature::new(
            ephemeral_commitment_sum,
            ephemeral_pubkey_sum_sum,
            u_a_sum,
            u_x_sum,
            u_y_sum,
        )
    }
}

impl<'a, P, K> Add<CommitmentAndPublicKeySignature<P, K>> for &'a CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    for<'b> &'a HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
    for<'b> &'a P: Add<&'b P, Output = P>,
    K: SecretKey,
    for<'b> &'a K: Add<&'b K, Output = K>,
{
    type Output = CommitmentAndPublicKeySignature<P, K>;

    fn add(self, rhs: CommitmentAndPublicKeySignature<P, K>) -> CommitmentAndPublicKeySignature<P, K> {
        let ephemeral_commitment_sum = self.ephemeral_commitment() + rhs.ephemeral_commitment();
        let ephemeral_pubkey_sum_sum = self.ephemeral_pubkey() + rhs.ephemeral_pubkey();
        let u_a_sum = self.u_a() + rhs.u_a();
        let u_x_sum = self.u_x() + rhs.u_x();
        let u_y_sum = self.u_y() + rhs.u_y();

        CommitmentAndPublicKeySignature::new(
            ephemeral_commitment_sum,
            ephemeral_pubkey_sum_sum,
            u_a_sum,
            u_x_sum,
            u_y_sum,
        )
    }
}

impl<'a, 'b, P, K> Add<&'b SchnorrSignature<P, K>> for &'a CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    &'a HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
    &'a P: Add<&'b P, Output = P>,
    K: SecretKey,
    &'a K: Add<&'b K, Output = K>,
{
    type Output = CommitmentAndPublicKeySignature<P, K>;

    fn add(self, rhs: &'b SchnorrSignature<P, K>) -> CommitmentAndPublicKeySignature<P, K> {
        let ephemeral_commitment_sum = self.ephemeral_commitment().clone();
        let ephemeral_pubkey_sum_sum = self.ephemeral_pubkey() + rhs.get_public_nonce();
        let u_a_sum = self.u_a().clone();
        let u_x_sum = self.u_x().clone();
        let u_y_sum = self.u_y() + rhs.get_signature();

        CommitmentAndPublicKeySignature::new(
            ephemeral_commitment_sum,
            ephemeral_pubkey_sum_sum,
            u_a_sum,
            u_x_sum,
            u_y_sum,
        )
    }
}

impl<'a, P, K> Add<SchnorrSignature<P, K>> for &'a CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    for<'b> &'a HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
    for<'b> &'a P: Add<&'b P, Output = P>,
    K: SecretKey,
    for<'b> &'a K: Add<&'b K, Output = K>,
{
    type Output = CommitmentAndPublicKeySignature<P, K>;

    fn add(self, rhs: SchnorrSignature<P, K>) -> CommitmentAndPublicKeySignature<P, K> {
        let ephemeral_commitment_sum = self.ephemeral_commitment().clone();
        let ephemeral_pubkey_sum_sum = self.ephemeral_pubkey() + rhs.get_public_nonce();
        let u_a_sum = self.u_a().clone();
        let u_x_sum = self.u_x().clone();
        let u_y_sum = self.u_y() + rhs.get_signature();

        CommitmentAndPublicKeySignature::new(
            ephemeral_commitment_sum,
            ephemeral_pubkey_sum_sum,
            u_a_sum,
            u_x_sum,
            u_y_sum,
        )
    }
}

impl<P, K> Default for CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    K: SecretKey,
{
    fn default() -> Self {
        CommitmentAndPublicKeySignature::new(
            HomomorphicCommitment::<P>::default(),
            P::default(),
            K::default(),
            K::default(),
            K::default(),
        )
    }
}

/// Provide a canonical ordering for commitment signatures. We use byte representations of all values in this order:
/// `ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y`
impl<P, K> Ord for CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    K: SecretKey,
{
    fn cmp(&self, other: &Self) -> Ordering {
        let mut compare = self.ephemeral_commitment().cmp(other.ephemeral_commitment());
        if compare != Ordering::Equal {
            return compare;
        }

        compare = self.ephemeral_pubkey().cmp(other.ephemeral_pubkey());
        if compare != Ordering::Equal {
            return compare;
        }

        compare = self.u_a().as_bytes().cmp(other.u_a().as_bytes());
        if compare != Ordering::Equal {
            return compare;
        }

        compare = self.u_x().as_bytes().cmp(other.u_x().as_bytes());
        if compare != Ordering::Equal {
            return compare;
        }

        self.u_y().as_bytes().cmp(other.u_y().as_bytes())
    }
}

impl<P, K> PartialOrd for CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    K: SecretKey,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<P, K> PartialEq for CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    K: SecretKey,
{
    fn eq(&self, other: &Self) -> bool {
        self.ephemeral_commitment().eq(other.ephemeral_commitment()) &&
            self.ephemeral_pubkey().eq(other.ephemeral_pubkey()) &&
            self.u_a().eq(other.u_a()) &&
            self.u_x().eq(other.u_x()) &&
            self.u_y().eq(other.u_y())
    }
}

impl<P, K> Eq for CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    K: SecretKey,
{
}

impl<P, K> Hash for CommitmentAndPublicKeySignature<P, K>
where
    P: PublicKey<K = K>,
    K: SecretKey,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write(&self.to_vec())
    }
}