Skip to main content

midnight_onchain_runtime/
transcript.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::context::Effects;
15use crate::ops::Op;
16use crate::result_mode::ResultModeVerify;
17use base_crypto::cost_model::RunningCost;
18use derive_where::derive_where;
19use serialize::tag_enforcement_test;
20use serialize::{Deserializable, Serializable, Tagged};
21use storage::Storable;
22use storage::arena::{ArenaKey, Sp};
23use storage::dag_memo::DagMemo;
24use storage::db::DB;
25use storage::storable::Loader;
26// #[cfg(feature = "proptest")] TODO WG
27// use proptest_derive::Arbitrary;
28use serde::{Deserialize, Serialize};
29
30#[derive(Storable, Serialize, Deserialize, Serializable, Clone, PartialEq, Eq, Debug)]
31#[storable(base)]
32#[tag = "contract-transcript-version"]
33pub struct TranscriptVersion {
34    pub major: u8,
35    pub minor: u8,
36}
37tag_enforcement_test!(TranscriptVersion);
38
39// #[cfg_attr(feature = "proptest", derive(Arbitrary))] TODO WG
40#[derive(Storable, Serialize, Deserialize)]
41#[serde(bound(serialize = "", deserialize = ""))]
42#[derive_where(Clone, PartialEq, Eq, Debug)]
43#[storable(db = D)]
44#[tag = "contract-transcript[v4]"]
45pub struct Transcript<D: DB> {
46    pub gas: RunningCost,
47    pub effects: Effects<D>,
48    pub program: storage::storage::Array<Op<ResultModeVerify, D>, D>,
49    pub version: Option<Sp<TranscriptVersion, D>>,
50}
51tag_enforcement_test!(Transcript<storage::db::InMemoryDB>);
52
53// TODO WG
54// #[cfg(feature = "proptest")]
55// impl<D: DB> rand::distributions::Distribution<Transcript<D>> for rand::distributions::Standard {
56//     fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Transcript<D> {
57//         Transcript {
58//             gas: rng.gen(),
59//             effects: rng.gen(),
60//             program: storage::storage::Vec::from_std_vec(vec![]),
61//             version: rng.gen(),
62//         }
63//     }
64// }
65
66/// The largest number of public inputs a single contract call may declare.
67///
68/// A call's public inputs are two fixed elements (the binding input and the
69/// communication commitment) followed by the field representation of its
70/// guaranteed and fallible transcripts' programs; see
71/// [`Transcript::public_inputs_len`].
72///
73/// This is a backstop against `Op::Noop { n }`, the one opcode whose
74/// public-input footprint is not proportional to its own encoding: `n` is a
75/// `u32` carried in a 9-byte op, and each unit of it contributes a 32-byte
76/// field element, so an uncapped `n` turns a 77-byte contract call into a
77/// 128 GiB allocation. Every other opcode contributes a number of elements
78/// bounded by its own size, and hence by the transaction byte limit.
79///
80/// The value is anchored on the verifier parameters: `PARAMS_VERIFIER` is a
81/// 2^14 setup, so no circuit the ledger can verify against -- and therefore no
82/// statement it accepts -- exceeds 2^14 rows. This leaves 4x headroom over
83/// that, and caps a single call's public inputs at 2 MiB.
84///
85/// Anything that materializes a call's public inputs from an untrusted
86/// transcript should check its count against this first.
87pub const MAX_CALL_PUBLIC_INPUTS: usize = 1 << 16;
88
89impl<D: DB> Transcript<D> {
90    pub const VERSION: TranscriptVersion = TranscriptVersion { major: 2, minor: 3 };
91
92    /// The number of field elements this transcript's program contributes to
93    /// a contract call's public inputs, computed without materializing them.
94    ///
95    /// Saturates rather than overflowing, so it is safe to call on untrusted
96    /// programs.
97    pub fn public_inputs_len(&self) -> usize {
98        self.public_inputs_len_memoized(&mut DagMemo::new())
99    }
100
101    /// As [`Self::public_inputs_len`], visiting each distinct op and pushed
102    /// node once across every transcript sharing `memo`.
103    pub fn public_inputs_len_memoized(&self, memo: &mut DagMemo<usize, D>) -> usize {
104        self.program.fold(memo, |memo, op| {
105            memo.get_or_compute(op, |memo, op| op.field_size_memoized(memo))
106        })
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use storage::db::InMemoryDB;
114    use transient_crypto::repr::FieldRepr;
115
116    fn transcript(program: Vec<Op<ResultModeVerify, InMemoryDB>>) -> Transcript<InMemoryDB> {
117        Transcript {
118            gas: Default::default(),
119            effects: Default::default(),
120            program: program.into(),
121            version: None,
122        }
123    }
124
125    #[test]
126    fn public_inputs_len_matches_field_repr() {
127        let t = transcript(vec![Op::Noop { n: 300 }, Op::Add, Op::Jmp { skip: 1 }]);
128        let materialized: usize = t.program.iter().map(|op| op.field_vec().len()).sum();
129        assert_eq!(t.public_inputs_len(), materialized);
130        assert_eq!(t.public_inputs_len(), 300 + 1 + 2);
131    }
132
133    #[test]
134    fn public_inputs_len_does_not_materialize() {
135        let t = transcript(vec![Op::Noop { n: u32::MAX }, Op::Add, Op::Noop { n: u32::MAX }]);
136        assert_eq!(t.public_inputs_len(), 2 * u32::MAX as usize + 1);
137        assert!(t.public_inputs_len() > MAX_CALL_PUBLIC_INPUTS);
138    }
139}