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
//! Interpreter with enhanced functionality to prove statements.

mod context_extension;
mod prover_result;

use std::rc::Rc;

pub use context_extension::*;
pub use prover_result::*;

use super::{
    dlog_protocol,
    fiat_shamir::{fiat_shamir_hash_fn, fiat_shamir_tree_to_bytes},
    private_input::PrivateInput,
    sig_serializer::serialize_sig,
    unchecked_tree::UncheckedSchnorr,
    Challenge, ProofTree, SigmaBoolean, SigmaProofOfKnowledgeTree, UncheckedSigmaTree,
    UncheckedTree, UnprovenLeaf, UnprovenSchnorr, UnprovenTree,
};
use crate::ergo_tree::{ErgoTree, ErgoTreeParsingError};
use crate::eval::context::Context;
use crate::eval::{Env, EvalError, Evaluator};
use thiserror::Error;

/// Prover errors
#[derive(Error, PartialEq, Eq, Debug, Clone)]
pub enum ProverError {
    /// Failed to parse ErgoTree
    #[error("Ergo tree error: {0}")]
    ErgoTreeError(ErgoTreeParsingError),
    /// Failed to evaluate ErgoTree
    #[error("Evaluation error: {0}")]
    EvalError(EvalError),
    /// Script reduced to false
    #[error("Script reduced to false")]
    ReducedToFalse,
    /// Failed on step2(prover does not have enough witnesses to perform the proof)
    #[error("Failed on step2(prover does not have enough witnesses to perform the proof)")]
    TreeRootIsNotReal,
    /// Simulated leaf does not have challenge
    #[error("Simulated leaf does not have challenge")]
    SimulatedLeafWithoutChallenge,
    /// Lacking challenge on step 9 for "real" unproven tree
    #[error("Lacking challenge on step 9 for \"real\" unproven tree")]
    RealUnprovenTreeWithoutChallenge,
    /// Cannot find a secret for "real" unproven leaf
    #[error("Cannot find a secret for \"real\" unproven leaf")]
    SecretNotFound,
}

impl From<ErgoTreeParsingError> for ProverError {
    fn from(err: ErgoTreeParsingError) -> Self {
        ProverError::ErgoTreeError(err)
    }
}

/// Prover
pub trait Prover: Evaluator {
    /// Secrets of the prover
    fn secrets(&self) -> &[PrivateInput];

    /**
     * The comments in this section are taken from the algorithm for the
     * Sigma-protocol prover as described in the ErgoScript white-paper
     * https://ergoplatform.org/docs/ErgoScript.pdf , Appendix A
     *
     * Generate proofs for the given message for ErgoTree reduced to Sigma boolean expression
     */
    fn prove(
        &self,
        tree: &ErgoTree,
        env: &Env,
        ctx: Rc<Context>,
        message: &[u8],
    ) -> Result<ProverResult, ProverError> {
        let expr = tree.proposition()?;
        let proof = self
            .reduce_to_crypto(expr.as_ref(), env, ctx)
            .map_err(ProverError::EvalError)
            .and_then(|v| match v.sigma_prop {
                SigmaBoolean::TrivialProp(true) => Ok(UncheckedTree::NoProof),
                SigmaBoolean::TrivialProp(false) => Err(ProverError::ReducedToFalse),
                sb => {
                    let tree = convert_to_unproven(sb);
                    let unchecked_tree = self.prove_to_unchecked(tree, message)?;
                    Ok(UncheckedTree::UncheckedSigmaTree(unchecked_tree))
                }
            });
        proof.map(|v| ProverResult {
            proof: serialize_sig(v),
            extension: ContextExtension::empty(),
        })
    }

    /// The comments in this section are taken from the algorithm for the
    /// Sigma-protocol prover as described in the white paper
    /// https://ergoplatform.org/docs/ErgoScript.pdf (Appendix A)
    fn prove_to_unchecked(
        &self,
        unproven_tree: UnprovenTree,
        message: &[u8],
    ) -> Result<UncheckedSigmaTree, ProverError> {
        // Prover Step 1: Mark as real everything the prover can prove
        let step1 = self.mark_real(unproven_tree);

        // Prover Step 2: If the root of the tree is marked "simulated" then the prover does not have enough witnesses
        // to perform the proof. Abort.
        if !step1.is_real() {
            return Err(ProverError::TreeRootIsNotReal);
        }

        // Prover Step 3: Change some "real" nodes to "simulated" to make sure each node
        // has the right number of simulated children.

        // skipped, since it leaves UnprovenSchnorr untouched
        // let step3 = self.polish_simulated(step1);

        // Prover Steps 4, 5, and 6 together: find challenges for simulated nodes; simulate simulated leaves;
        // compute commitments for real leaves
        let step6 = self.simulate_and_commit(step1)?;

        // Prover Steps 7: convert the relevant information in the tree (namely, tree structure, node types,
        // the statements being proven and commitments at the leaves)
        // to a string
        let var_name = fiat_shamir_tree_to_bytes(&step6);
        let mut s = var_name;

        // Prover Step 8: compute the challenge for the root of the tree as the Fiat-Shamir hash of s
        // and the message being signed.
        s.append(&mut message.to_vec());
        let root_challenge: Challenge = fiat_shamir_hash_fn(s.as_slice()).into();
        let step8 = step6.with_challenge(root_challenge);

        // Prover Step 9: complete the proof by computing challenges at real nodes and additionally responses at real leaves
        let step9 = self.proving(step8)?;

        // Prover Step 10: output the right information into the proof
        match step9 {
            ProofTree::UncheckedTree(UncheckedTree::UncheckedSigmaTree(tree)) => Ok(tree),
            _ => todo!(),
        }
    }

    /**
     Prover Step 1: This step will mark as "real" every node for which the prover can produce a real proof.
     This step may mark as "real" more nodes than necessary if the prover has more than the minimal
     necessary number of witnesses (for example, more than one child of an OR).
     This will be corrected in the next step.
     In a bottom-up traversal of the tree, do the following for each node:
    */
    fn mark_real(&self, unproven_tree: UnprovenTree) -> UnprovenTree {
        match unproven_tree {
            UnprovenTree::UnprovenLeaf(UnprovenLeaf::UnprovenSchnorr(us)) => {
                let secret_known = self.secrets().iter().any(|s| match s {
                    PrivateInput::DlogProverInput(dl) => dl.public_image() == us.proposition,
                    _ => false,
                });
                UnprovenSchnorr {
                    simulated: !secret_known,
                    ..us
                }
                .into()
            }
        }
    }

    /**
     Prover Step 3: This step will change some "real" nodes to "simulated" to make sure each node has
     the right number of simulated children.
     In a top-down traversal of the tree, do the following for each node:
    */
    fn polish_simulated(&self, _unproven_tree: UnprovenTree) -> UnprovenTree {
        todo!()
    }

    /**
     Prover Step 4: In a top-down traversal of the tree, compute the challenges e for simulated children of every node
     Prover Step 5: For every leaf marked "simulated", use the simulator of the Sigma-protocol for that leaf
     to compute the commitment $a$ and the response z, given the challenge e that is already stored in the leaf.
     Prover Step 6: For every leaf marked "real", use the first prover step of the Sigma-protocol for that leaf to
     compute the commitment a.
    */
    fn simulate_and_commit(&self, tree: UnprovenTree) -> Result<ProofTree, ProverError> {
        match tree {
            UnprovenTree::UnprovenLeaf(UnprovenLeaf::UnprovenSchnorr(us)) => {
                if us.simulated {
                    // Step 5 (simulated leaf -- complete the simulation)
                    if let Some(challenge) = us.challenge_opt {
                        let (fm, sm) = dlog_protocol::interactive_prover::simulate(
                            &us.proposition,
                            &challenge,
                        );
                        Ok(ProofTree::UncheckedTree(
                            UncheckedSchnorr {
                                proposition: us.proposition,
                                commitment_opt: Some(fm),
                                challenge,
                                second_message: sm,
                            }
                            .into(),
                        ))
                    } else {
                        Err(ProverError::SimulatedLeafWithoutChallenge)
                    }
                } else {
                    // Step 6 (real leaf -- compute the commitment a)
                    let (r, commitment) = dlog_protocol::interactive_prover::first_message();
                    Ok(ProofTree::UnprovenTree(
                        UnprovenSchnorr {
                            commitment_opt: Some(commitment),
                            randomness_opt: Some(r),
                            ..us
                        }
                        .into(),
                    ))
                }
            }
        }
    }

    /**
     Prover Step 9: Perform a top-down traversal of only the portion of the tree marked "real" in order to compute
     the challenge e for every node marked "real" below the root and, additionally, the response z for every leaf
     marked "real"
    */
    fn proving(&self, tree: ProofTree) -> Result<ProofTree, ProverError> {
        // If the node is a leaf marked "real", compute its response according to the second prover step
        // of the Sigma-protocol given the commitment, challenge, and witness
        match tree {
            ProofTree::UncheckedTree(_) => Ok(tree),
            ProofTree::UnprovenTree(unproven_tree) => match unproven_tree {
                UnprovenTree::UnprovenLeaf(UnprovenLeaf::UnprovenSchnorr(us))
                    if unproven_tree.is_real() =>
                {
                    if let Some(challenge) = us.challenge_opt.clone() {
                        if let Some(priv_key) = self
                            .secrets()
                            .iter()
                            .flat_map(|s| match s {
                                PrivateInput::DlogProverInput(dl) => vec![dl],
                                _ => vec![],
                            })
                            .find(|prover_input| prover_input.public_image() == us.proposition)
                        {
                            let z = dlog_protocol::interactive_prover::second_message(
                                &priv_key,
                                us.randomness_opt.unwrap(),
                                &challenge,
                            );
                            Ok(UncheckedSchnorr {
                                proposition: us.proposition,
                                commitment_opt: None,
                                challenge,
                                second_message: z,
                            }
                            .into())
                        } else {
                            Err(ProverError::SecretNotFound)
                        }
                    } else {
                        Err(ProverError::RealUnprovenTreeWithoutChallenge)
                    }
                }
                _ => todo!(),
            },
        }
    }
}

fn convert_to_unproven(ergo_lib: SigmaBoolean) -> UnprovenTree {
    match ergo_lib {
        // TODO: why it's even here? Make another SigmaBoolean without trivial props?
        SigmaBoolean::TrivialProp(_) => todo!(),
        SigmaBoolean::ProofOfKnowledge(pok) => match pok {
            SigmaProofOfKnowledgeTree::ProveDHTuple(_) => todo!(),
            SigmaProofOfKnowledgeTree::ProveDlog(prove_dlog) => UnprovenSchnorr {
                proposition: prove_dlog,
                commitment_opt: None,
                randomness_opt: None,
                challenge_opt: None,
                simulated: false,
            }
            .into(),
        },
        SigmaBoolean::CAND(_) => todo!(),
    }
}

/// Test prover implementation
pub struct TestProver {
    /// secrets to be used in proofs generation
    pub secrets: Vec<PrivateInput>,
}

impl Evaluator for TestProver {}
impl Prover for TestProver {
    fn secrets(&self) -> &[PrivateInput] {
        self.secrets.as_ref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::constant::Constant;
    use crate::ast::expr::Expr;
    use crate::ast::value::Value;
    use crate::sigma_protocol::private_input::DlogProverInput;
    use crate::types::stype::SType;
    use std::rc::Rc;

    #[test]
    fn test_prove_true_prop() {
        let bool_true_tree = ErgoTree::from(Rc::new(Expr::Const(
            Constant {
                tpe: SType::SBoolean,
                v: Value::Boolean(true),
            }
            .into(),
        )));
        let message = vec![0u8; 100];

        let prover = TestProver { secrets: vec![] };
        let res = prover.prove(
            &bool_true_tree,
            &Env::empty(),
            Rc::new(Context::dummy()),
            message.as_slice(),
        );
        assert!(res.is_ok());
        assert_eq!(res.unwrap().proof, ProofBytes::Empty);
    }

    #[test]
    fn test_prove_false_prop() {
        let bool_false_tree = ErgoTree::from(Rc::new(Expr::Const(
            Constant {
                tpe: SType::SBoolean,
                v: Value::Boolean(false),
            }
            .into(),
        )));
        let message = vec![0u8; 100];

        let prover = TestProver { secrets: vec![] };
        let res = prover.prove(
            &bool_false_tree,
            &Env::empty(),
            Rc::new(Context::dummy()),
            message.as_slice(),
        );
        assert!(res.is_err());
        assert_eq!(res.err().unwrap(), ProverError::ReducedToFalse);
    }

    #[test]
    fn test_prove_pk_prop() {
        let secret = DlogProverInput::random();
        let pk = secret.public_image();
        let tree = ErgoTree::from(Rc::new(Expr::Const(
            Constant {
                tpe: SType::SSigmaProp,
                v: pk.into(),
            }
            .into(),
        )));
        let message = vec![0u8; 100];

        let prover = TestProver {
            secrets: vec![PrivateInput::DlogProverInput(secret)],
        };
        let res = prover.prove(
            &tree,
            &Env::empty(),
            Rc::new(Context::dummy()),
            message.as_slice(),
        );
        assert!(res.is_ok());
        assert_ne!(res.unwrap().proof, ProofBytes::Empty);
    }
}