Skip to main content

midnight_ledger_v9/
prove.rs

1// This file is part of midnight-ledger.
2// Copyright (C) Midnight Foundation
3// SPDX-License-Identifier: Apache-2.0
4// Licensed under the Apache License, Version 2.0 (the "License");
5// You may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7// http://www.apache.org/licenses/LICENSE-2.0
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14use crate::dust::DustResolver;
15use crate::error::TransactionProvingError;
16use crate::structure::{
17    ContractAction, ContractCall, Intent, ProofMarker, ProofPreimageMarker, ProofPreimageVersioned,
18    ProofVersioned, SignatureKind, StandardTransaction, Transaction,
19};
20use base_crypto::cost_model::{CostDuration, RunningCost};
21use futures::future::join_all;
22use onchain_runtime::cost_model::{CostModel, INITIAL_COST_MODEL};
23use onchain_runtime::ops::Op;
24use onchain_runtime::transcript::Transcript;
25use rand::SeedableRng;
26use rand::rngs::StdRng;
27use serialize::peek_tag;
28use std::future::Future;
29use std::io;
30use std::ops::Deref;
31use std::pin::Pin;
32use storage::arena::Sp;
33use storage::db::DB;
34use tokio::runtime::Handle;
35use transient_crypto::commitment::PedersenRandomness;
36use transient_crypto::commitment::{Pedersen, PureGeneratorPedersen};
37use transient_crypto::proofs::{KeyLocation, ParamsProverProvider, Resolver as ResolverT};
38use transient_crypto::proofs::{ProvingError, ProvingKeyMaterial, ProvingProvider};
39use zswap::prove::ZswapResolver;
40
41pub type ExternalResolver = Box<
42    dyn Fn(
43            KeyLocation,
44        )
45            -> Pin<Box<dyn Future<Output = io::Result<Option<ProvingKeyMaterial>>> + Send + Sync>>
46        + Send
47        + Sync,
48>;
49
50pub struct Resolver {
51    pub zswap_resolver: ZswapResolver,
52    pub dust_resolver: DustResolver,
53    #[allow(clippy::type_complexity)]
54    pub external_resolver: ExternalResolver,
55}
56
57impl Resolver {
58    #[allow(clippy::type_complexity)]
59    pub fn new(
60        zswap_resolver: ZswapResolver,
61        dust_resolver: DustResolver,
62        external_resolver: ExternalResolver,
63    ) -> Self {
64        Resolver {
65            zswap_resolver,
66            dust_resolver,
67            external_resolver,
68        }
69    }
70}
71
72impl ParamsProverProvider for Resolver {
73    async fn get_params(&self, k: u8) -> io::Result<transient_crypto::proofs::ParamsProver> {
74        self.zswap_resolver.get_params(k).await
75    }
76}
77
78impl transient_crypto::proofs::Resolver for Resolver {
79    async fn resolve_key(&self, key: KeyLocation) -> io::Result<Option<ProvingKeyMaterial>> {
80        if let Some(res) = self.zswap_resolver.resolve_key(key.clone()).await? {
81            return Ok(Some(res));
82        }
83        if let Some(res) = self.dust_resolver.resolve_key(key.clone()).await? {
84            return Ok(Some(res));
85        }
86        (self.external_resolver)(key.clone()).await
87    }
88}
89
90#[instrument(skip(prover, cost_model))]
91#[allow(clippy::type_complexity)]
92async fn prove_intents<D: DB, S: SignatureKind<D>>(
93    intents: &storage::storage::HashMap<
94        u16,
95        Intent<S, ProofPreimageMarker, PedersenRandomness, D>,
96        D,
97    >,
98    mut prover: impl ProvingProvider,
99    cost_model: &CostModel,
100) -> Result<
101    storage::storage::HashMap<u16, Intent<S, ProofMarker, PedersenRandomness, D>, D>,
102    ProvingError,
103> {
104    let res = join_all(intents.iter().map(|seg_x_intent| {
105        let split_prover = prover.split();
106        async move {
107            seg_x_intent
108                .1
109                .deref()
110                .prove(*seg_x_intent.0.deref(), split_prover, cost_model)
111                .await
112        }
113    }))
114    .await
115    .into_iter()
116    .collect::<Result<storage::storage::HashMap<_, _, _>, _>>()?;
117
118    Ok(res)
119}
120
121impl<S: SignatureKind<D>, D: DB> Transaction<S, ProofPreimageMarker, PedersenRandomness, D> {
122    /// Mocks proving, producing a 'proven' transaction that, while it will
123    /// *not* verify, is accurate for fee computation purposes.
124    ///
125    /// Due to the variability in proof sizes, this *only* works for
126    /// transactions that do not contain unproven contract calls.
127    pub fn mock_prove(
128        &self,
129    ) -> Result<Transaction<S, ProofMarker, PureGeneratorPedersen, D>, TransactionProvingError<D>>
130    {
131        let tokio_handle = Handle::try_current();
132        let _guard = tokio_handle.as_ref().map(Handle::enter);
133        let mut proven = futures::executor::block_on(self.prove(MockProver, &INITIAL_COST_MODEL))?
134            .seal(StdRng::seed_from_u64(0x00));
135        if let Transaction::Standard(ref mut stx) = proven {
136            let intents = stx
137                .intents
138                .iter()
139                .map(|segintent| {
140                    let mut intent = (*segintent.1).clone();
141                    intent.binding_commitment = PureGeneratorPedersen::largest_representable();
142                    (*segintent.0, intent)
143                })
144                .collect();
145            stx.intents = intents;
146        }
147        Ok(proven)
148    }
149
150    #[instrument(skip(self, prover, cost_model))]
151    pub async fn prove(
152        &self,
153        mut prover: impl ProvingProvider,
154        cost_model: &CostModel,
155    ) -> Result<Transaction<S, ProofMarker, PedersenRandomness, D>, TransactionProvingError<D>>
156    {
157        match self {
158            Transaction::Standard(stx) => {
159                let coin_vec: Vec<_> = stx.fallible_coins.clone().into_iter().collect();
160                let coin_provers: Vec<_> = coin_vec.iter().map(|_| prover.split()).collect();
161
162                let fallible_coins_future =
163                    join_all(coin_vec.into_iter().zip(coin_provers.into_iter()).map(
164                        |((s_id, o), coin_prover)| async move { o.prove(coin_prover, s_id).await },
165                    ));
166
167                let (intents, guaranteed_coins, fallible_coins) = futures::join!(
168                    prove_intents(&stx.intents, prover.split(), cost_model),
169                    futures::future::OptionFuture::from(
170                        stx.guaranteed_coins
171                            .as_ref()
172                            .map(|o| { o.prove(prover.split(), 0) })
173                    ),
174                    fallible_coins_future
175                );
176
177                Ok(Transaction::Standard(StandardTransaction {
178                    network_id: stx.network_id.clone(),
179                    intents: intents?,
180                    guaranteed_coins: guaranteed_coins
181                        .transpose()
182                        .map_err(TransactionProvingError::Proving)?
183                        .as_ref()
184                        .map(|x| Sp::new(x.clone().1)),
185                    fallible_coins: fallible_coins
186                        .into_iter()
187                        .collect::<Result<storage::storage::HashMap<_, _, D>, _>>()
188                        .map_err(TransactionProvingError::Proving)?,
189                    binding_randomness: stx.binding_randomness,
190                }))
191            }
192            Transaction::ClaimRewards(rewards) => Ok(Transaction::ClaimRewards(rewards.clone())),
193        }
194    }
195}
196
197impl<S: SignatureKind<D>, D: DB> Intent<S, ProofPreimageMarker, PedersenRandomness, D> {
198    #[instrument(skip(self, prover, cost_model))]
199    #[allow(clippy::type_complexity)]
200    pub async fn prove(
201        &self,
202        segment_id: u16,
203        mut prover: impl ProvingProvider,
204        cost_model: &CostModel,
205    ) -> Result<(u16, Intent<S, ProofMarker, PedersenRandomness, D>), ProvingError> {
206        let actions =
207            join_all(self.actions.iter_deref().map(|call| {
208                call.prove(prover.split(), self.binding_commitment.into(), cost_model)
209            }))
210            .await
211            .into_iter()
212            .collect::<Result<Vec<_>, _>>()?;
213        let dust_actions = match self.dust_actions.as_ref() {
214            Some(da) => Some(Sp::new(
215                da.prove(prover.split(), segment_id, self.binding_commitment.into())
216                    .await?,
217            )),
218            None => None,
219        };
220
221        let intent = Intent {
222            guaranteed_unshielded_offer: self.guaranteed_unshielded_offer.clone(),
223            fallible_unshielded_offer: self.fallible_unshielded_offer.clone(),
224            actions: actions.into(),
225            dust_actions,
226            ttl: self.ttl,
227            binding_commitment: self.binding_commitment,
228        };
229
230        Ok((segment_id, intent))
231    }
232}
233
234impl<D: DB> ContractAction<ProofPreimageMarker, D> {
235    async fn prove(
236        &self,
237        prover: impl ProvingProvider,
238        binding_commitment: Pedersen,
239        cost_model: &CostModel,
240    ) -> Result<ContractAction<ProofMarker, D>, TransactionProvingError<D>> {
241        use ContractAction::*;
242        Ok(match self {
243            Call(call) => Call(Sp::new(
244                call.prove(prover, binding_commitment, cost_model).await?,
245            )),
246            Deploy(deploy) => Deploy(deploy.clone()),
247            Maintain(upd) => Maintain(upd.clone()),
248        })
249    }
250}
251
252impl<D: DB> ContractCall<ProofPreimageMarker, D> {
253    async fn prove(
254        &self,
255        prover: impl ProvingProvider,
256        binding_commitment: Pedersen,
257        cost_model: &CostModel,
258    ) -> Result<ContractCall<ProofMarker, D>, TransactionProvingError<D>> {
259        let active_calls = match &self.proof {
260            ProofPreimageVersioned::V2(proof) => prover.check(proof).await?,
261        };
262        let mut remaining_active_calls = &active_calls[..];
263
264        // Process the transcript programs, inserting noops in inactive segments
265        let mut guaranteed_prog = Vec::new();
266        let mut fallible_prog = Vec::new();
267        for (old_transcript, transcript) in [
268            self.guaranteed_transcript
269                .as_ref()
270                .map(|t| (t.program.iter_deref(), &mut guaranteed_prog)),
271            self.fallible_transcript
272                .as_ref()
273                .map(|t| (t.program.iter_deref(), &mut fallible_prog)),
274        ]
275        .into_iter()
276        .flatten()
277        {
278            for op in old_transcript {
279                while let Some(Some(skip)) = remaining_active_calls.first() {
280                    transcript.push(Op::Noop { n: *skip as u32 });
281                    remaining_active_calls = &remaining_active_calls[1..];
282                }
283                transcript.push(op.clone());
284                remaining_active_calls = &remaining_active_calls[1..];
285            }
286            while let Some(Some(skip)) = remaining_active_calls.first() {
287                transcript.push(Op::Noop { n: *skip as u32 });
288                remaining_active_calls = &remaining_active_calls[1..];
289            }
290        }
291        // Combine adjacent noops, and count their cost.
292        let mut guaranteed_noop_gas_cost = CostDuration::ZERO;
293        let mut fallible_noop_gas_cost = CostDuration::ZERO;
294        for (prog, gas_cost) in [
295            (&mut guaranteed_prog, &mut guaranteed_noop_gas_cost),
296            (&mut fallible_prog, &mut fallible_noop_gas_cost),
297        ]
298        .into_iter()
299        {
300            // Marks the current write head
301            let mut i = 0;
302            // The current chain of noops
303            let mut n = 0;
304            // Marks the current read head
305            for j in 0..prog.len() {
306                match prog[j].clone() {
307                    Op::Noop { n: n2 } => n += n2,
308                    op => {
309                        if n != 0 {
310                            prog[i] = Op::Noop { n };
311                            *gas_cost +=
312                                cost_model.noop_constant + cost_model.noop_coeff_arg * n as u64;
313                            i += 1;
314                            n = 0;
315                        }
316                        prog[i] = op;
317                        i += 1;
318                    }
319                }
320            }
321            if n != 0 {
322                prog[i] = Op::Noop { n };
323                *gas_cost += cost_model.noop_constant + cost_model.noop_coeff_arg * n as u64;
324                i += 1;
325            }
326            prog.truncate(i);
327        }
328        let guaranteed_transcript = self.guaranteed_transcript.as_ref().map(|t| Transcript {
329            gas: RunningCost {
330                compute_time: guaranteed_noop_gas_cost + t.gas.compute_time,
331                ..t.gas
332            },
333            effects: t.effects.clone(),
334            program: guaranteed_prog.into(),
335            version: t.version.clone(),
336        });
337        let fallible_transcript = self.fallible_transcript.as_ref().map(|t| Transcript {
338            gas: RunningCost {
339                compute_time: fallible_noop_gas_cost + t.gas.compute_time,
340                ..t.gas
341            },
342            effects: t.effects.clone(),
343            program: fallible_prog.into(),
344            version: t.version.clone(),
345        });
346
347        let intermediate_call: ContractCall<ProofPreimageMarker, D> = ContractCall {
348            address: self.address,
349            entry_point: self.entry_point.clone(),
350            guaranteed_transcript: guaranteed_transcript.clone().map(Sp::new),
351            fallible_transcript: fallible_transcript.clone().map(Sp::new),
352            communication_commitment: self.communication_commitment,
353            proof: self.proof.clone(),
354        };
355
356        let proof = match &self.proof {
357            ProofPreimageVersioned::V2(preimage) => {
358                let vk = prover
359                    .resolver()
360                    .resolve_key(preimage.key_location.clone())
361                    .await
362                    .map_err(TransactionProvingError::Tokio)?
363                    .ok_or_else(|| {
364                        TransactionProvingError::MissingKeyset(preimage.key_location.clone())
365                    })?
366                    .verifier_key;
367                let proof = prover
368                    .prove(
369                        preimage,
370                        Some(intermediate_call.binding_input(binding_commitment)),
371                    )
372                    .await?;
373                let tag = peek_tag(&mut std::io::Cursor::new(&vk))
374                    .map_err(TransactionProvingError::Tokio)?;
375                match tag.as_str() {
376                    "verifier-key[v6]" => ProofVersioned::V2(proof),
377                    "verifier-key[v7]" => ProofVersioned::V3(proof),
378                    _ => return Err(TransactionProvingError::UnknownVerifierKeyVersion(tag)),
379                }
380            }
381        };
382
383        // Assemble the final call
384        Ok(ContractCall {
385            address: self.address,
386            entry_point: self.entry_point.clone(),
387            guaranteed_transcript: guaranteed_transcript.map(Sp::new),
388            fallible_transcript: fallible_transcript.map(Sp::new),
389            communication_commitment: self.communication_commitment,
390            proof,
391        })
392    }
393}
394
395pub(crate) struct MockProver;
396
397const BUILTIN_KEYS: &[&str] = &[
398    "midnight/zswap/spend",
399    "midnight/zswap/output",
400    "midnight/dust/spend",
401];
402
403impl ProvingProvider for MockProver {
404    async fn check(
405        &self,
406        preimage: &transient_crypto::proofs::ProofPreimage,
407    ) -> Result<Vec<Option<usize>>, anyhow::Error> {
408        if BUILTIN_KEYS.contains(&preimage.key_location.0.as_ref()) {
409            Ok(vec![])
410        } else {
411            anyhow::bail!("cannot mock prove non-builtin circuit")
412        }
413    }
414    async fn prove(
415        self,
416        preimage: &transient_crypto::proofs::ProofPreimage,
417        _overwrite_binding_input: Option<transient_crypto::curve::Fr>,
418    ) -> Result<transient_crypto::proofs::Proof, anyhow::Error> {
419        let size = match preimage.key_location.0.as_ref() {
420            "midnight/zswap/spend" => zswap::INPUT_PROOF_SIZE,
421            "midnight/zswap/output" => zswap::OUTPUT_PROOF_SIZE,
422            "midnight/dust/spend" => crate::dust::DUST_SPEND_PROOF_SIZE,
423            _ => anyhow::bail!("cannot mock prove non-builtin circuit"),
424        };
425        let nonsense_data = std::iter::repeat([0xde, 0xad, 0xc0, 0xde])
426            .flat_map(|v| v.into_iter())
427            .take(size)
428            .collect::<Vec<_>>();
429        let mock_proof = transient_crypto::proofs::Proof(nonsense_data);
430        Ok(mock_proof)
431    }
432    fn split(&mut self) -> Self {
433        MockProver
434    }
435    fn resolver(&self) -> &impl ResolverT {
436        self
437    }
438}
439
440impl ResolverT for MockProver {
441    async fn resolve_key(&self, _key: KeyLocation) -> io::Result<Option<ProvingKeyMaterial>> {
442        Ok(None)
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use base_crypto::data_provider::{self, MidnightDataProvider};
449    use storage::db::InMemoryDB;
450    use zswap::ZSWAP_EXPECTED_FILES;
451
452    use crate::{
453        dust::DUST_EXPECTED_FILES,
454        structure::{Signature, Transaction},
455    };
456
457    #[test]
458    fn test_mock_proving() {
459        let tx = Transaction::<Signature, _, _, InMemoryDB>::new(
460            "local-test",
461            Default::default(),
462            Default::default(),
463            Default::default(),
464        );
465        tx.mock_prove().unwrap();
466    }
467
468    #[tokio::test]
469    async fn test_mock_proving_tokio() {
470        let tx = Transaction::<Signature, _, _, InMemoryDB>::new(
471            "local-test",
472            Default::default(),
473            Default::default(),
474            Default::default(),
475        );
476        tx.mock_prove().unwrap();
477    }
478
479    #[tokio::test]
480    async fn test_resolver_resolves() {
481        if option_env!("NIX_ENFORCE_PURITY").is_some() {
482            // We can't run this test in the nix sandbox, due to not having internet!
483            // That's okay, we'll test it outside of it.
484            return;
485        }
486        let tmpdir = std::env::temp_dir().join("midnight-resolver-test");
487        let files = ZSWAP_EXPECTED_FILES
488            .iter()
489            .chain(DUST_EXPECTED_FILES.iter())
490            .copied()
491            .collect::<Vec<_>>();
492        let provider = MidnightDataProvider {
493            fetch_mode: data_provider::FetchMode::OnDemand,
494            base_url: data_provider::BASE_URL.clone(),
495            output_mode: data_provider::OutputMode::Log,
496            expected_data: files.clone(),
497            dir: tmpdir.clone(),
498        };
499        let mut results = vec![];
500        for (name, _, _) in files.iter() {
501            results.push(provider.fetch(name).await);
502        }
503        std::fs::remove_dir_all(tmpdir).unwrap();
504        if results.iter().any(|res| res.is_err()) {
505            println!("resolver fails to resolve the following keys:");
506            for (name, err) in files
507                .iter()
508                .zip(results.iter())
509                .filter_map(|((name, _, _), res)| match res {
510                    Ok(_) => None,
511                    Err(e) => Some((name, e)),
512                })
513            {
514                println!("  '{name}': {err}");
515            }
516            panic!();
517        }
518    }
519}