Skip to main content

midnight_onchain_state/
state.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 base_crypto::cost_model::RunningCost;
15use base_crypto::fab::{
16    Aligned, AlignedValue, Alignment, AlignmentAtom, AlignmentSegment, FIELD_BYTE_LIMIT, ValueAtom,
17};
18use base_crypto::hash::{HashOutput, persistent_commit};
19use base_crypto::repr::MemWrite;
20use coin_structure::coin::TokenType;
21use derive_where::derive_where;
22use fake::Dummy;
23use hex::ToHex;
24#[cfg(feature = "proptest")]
25use proptest::arbitrary::Arbitrary;
26#[cfg(feature = "proptest")]
27use proptest_derive::Arbitrary;
28use rand::Rng;
29use rand::distributions::{Distribution, Standard};
30use serde::{
31    Deserialize, Deserializer, Serialize, Serializer, de, de::MapAccess, de::SeqAccess,
32    de::Visitor, ser::SerializeStruct,
33};
34#[cfg(feature = "proptest")]
35use serialize::NoStrategy;
36#[cfg(feature = "proptest")]
37use serialize::randomised_serialization_test;
38#[cfg(feature = "proptest")]
39use serialize::simple_arbitrary;
40use serialize::{self, Deserializable, Serializable, Tagged, tag_enforcement_test};
41use std::borrow::Borrow;
42use std::fmt::{self, Debug, Formatter};
43use std::hash::Hash;
44use std::io::{self, Read, Write};
45use std::marker::PhantomData;
46use std::ops::Deref;
47use storage::Storable;
48use storage::arena::Sp;
49use storage::dag_memo::DagMemo;
50use storage::db::{DB, InMemoryDB};
51use storage::delta_tracking::{incremental_write_delete_costs, initial_write_delete_costs};
52use storage::{
53    arena::ArenaKey,
54    delta_tracking::RcMap,
55    storable::Loader,
56    storage::{Array, HashMap},
57};
58use transient_crypto::curve::Fr;
59use transient_crypto::merkle_tree::MerkleTree;
60use transient_crypto::proofs::VerifierKey;
61use transient_crypto::repr::FieldRepr;
62
63/// The size limit for Cell's. Currently 32 kiB
64pub const CELL_BOUND: usize = 1 << 15;
65
66// Trait for possible cell values / map keys to allow using both `AlignedValue` and
67// `AlignedValueChecked` in different generic instantiations of `StateValue`.
68pub trait AlignedValueKind<D: DB>: ExpectFromAligned + Serializable + Storable<D> + Clone + Eq + Ord + Hash + Serialize + FieldRepr + Debug + for<'de> Deserialize<'de> {
69    fn additional_invariant_checks(value: &StateValue<D, Self>) -> io::Result<()>;
70}
71
72// Separate from `AlignedValueKind` because its signature does not mention `D`, which would then
73// be uninferable at call sites such as `stval!`.
74pub trait ExpectFromAligned: Sized {
75    fn expect_from<T: Into<AlignedValue>>(value: T, msg: &str) -> Self;
76}
77
78impl ExpectFromAligned for AlignedValue {
79    fn expect_from<T: Into<AlignedValue>>(value: T, _msg: &str) -> Self {
80        value.into()
81    }
82}
83
84impl ExpectFromAligned for AlignedValueChecked {
85    fn expect_from<T: Into<AlignedValue>>(value: T, msg: &str) -> Self {
86        AlignedValueChecked::try_from(value.into()).expect(msg)
87    }
88}
89
90impl<D: DB> AlignedValueKind<D> for AlignedValue {
91    fn additional_invariant_checks(_: &StateValue<D, Self>) -> io::Result<()> {
92        Ok(())
93    }
94}
95impl<D: DB> AlignedValueKind<D> for AlignedValueChecked {
96    fn additional_invariant_checks(value: &StateValue<D, Self>) -> io::Result<()> {
97        if let StateValue::BoundedMerkleTree(bmt) = value && bmt != &MerkleTree::blank(bmt.height()) {
98            return Err(std::io::Error::new(
99                std::io::ErrorKind::InvalidData,
100                "Checked-context Merkle trees must be empty",
101            ));
102        }
103        Ok(())
104    }
105}
106
107#[derive(Default, Storable)]
108#[derive_where(Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
109#[storable(db = D, invariant = StateValue::invariant)]
110#[tag = "impact-state-value[v2]"]
111#[non_exhaustive]
112pub enum StateValue<D: DB = InMemoryDB, V: AlignedValueKind<D> = AlignedValue> {
113    #[default]
114    Null,
115    Cell(#[storable(child)] Sp<V, D>),
116    Map(HashMap<V, StateValue<D, V>, D>),
117    /// A fixed size array, with `0 <= len <= 16`. The upper 5 bits of the
118    /// argument to the `new` opcode specify the length at creation time. The
119    /// underlying `storage::Array` type is not fixed length, but in the VM we
120    /// only allow size preserving operations.
121    Array(Array<StateValue<D, V>, D>),
122    /// Merkle tree with `0 < height <= 32`.
123    BoundedMerkleTree(MerkleTree<(), D>),
124}
125tag_enforcement_test!(StateValue);
126
127// Not derived: the derive cannot express the `Standard: Distribution<V>` bound that the container
128// strategies need, and those strategies do not shrink anyway.
129#[cfg(feature = "proptest")]
130impl<D: DB, V: AlignedValueKind<D>> Arbitrary for StateValue<D, V>
131where
132    Standard: Distribution<V>,
133{
134    type Parameters = ();
135    type Strategy = NoStrategy<StateValue<D, V>>;
136
137    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
138        NoStrategy(PhantomData)
139    }
140}
141
142/// Mirror of [AlignedValue] with additional checks. These check that field-aligned atoms are in
143/// fact within the field modulus, rejecting aligned values that would alias to to the same field
144/// representation via modular reduction.
145#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Storable, FieldRepr)]
146#[storable(base)]
147pub struct AlignedValueChecked(AlignedValue);
148
149impl Distribution<AlignedValueChecked> for Standard {
150    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> AlignedValueChecked {
151        // The base sampler fills `Field` atoms with up to 64 random bytes, which usually exceed
152        // the modulus; reduce them so every sample is canonical.
153        fn reduce_field_atoms<'a>(
154            segments: &[AlignmentSegment],
155            atoms: &mut impl Iterator<Item = &'a mut ValueAtom>,
156        ) {
157            for segment in segments {
158                match segment {
159                    AlignmentSegment::Atom(AlignmentAtom::Field) => {
160                        let atom = atoms.next().expect("sampled value should fit its alignment");
161                        let mut bytes = [0u8; FIELD_BYTE_LIMIT];
162                        bytes[..atom.0.len()].copy_from_slice(&atom.0);
163                        *atom = Fr::from_uniform_bytes(&bytes).into();
164                    }
165                    AlignmentSegment::Atom(_) => {
166                        atoms.next();
167                    }
168                    AlignmentSegment::Option(options) => {
169                        let discriminant = atoms.next().expect("sampled value should fit its alignment");
170                        let choice = u16::try_from(&*discriminant)
171                            .expect("sampled discriminant should decode");
172                        reduce_field_atoms(&options[choice as usize].0, atoms);
173                    }
174                }
175            }
176        }
177        let mut value: AlignedValue = self.sample(rng);
178        reduce_field_atoms(&value.alignment.0, &mut value.value.0.iter_mut());
179        AlignedValueChecked::try_from(value).expect("reduced sample should be canonical")
180    }
181}
182
183#[cfg(feature = "proptest")]
184simple_arbitrary!(AlignedValueChecked);
185
186impl From<AlignedValueChecked> for AlignedValue {
187    fn from(value: AlignedValueChecked) -> Self {
188        value.0
189    }
190}
191
192impl TryFrom<AlignedValue> for AlignedValueChecked {
193    type Error = ();
194    fn try_from(value: AlignedValue) -> Result<Self, Self::Error> {
195        if value.alignment.fits_field_check(&value.value, |atom| Fr::try_from(atom).is_ok()) {
196            Ok(AlignedValueChecked(value))
197        } else {
198            Err(())
199        }
200    }
201}
202
203impl From<u8> for AlignedValueChecked {
204    fn from(value: u8) -> Self {
205        AlignedValueChecked(AlignedValue::from(value))
206    }
207}
208
209// O(1), as `Push` costs are flat: both leaf kinds share one binary representation, so the top-level
210// node is re-read as the unchecked type, leaving its children lazy. The re-read goes through the
211// trusted loader and skips invariants, which is sound as every checked value is a valid unchecked
212// one.
213impl<D: DB> From<StateValue<D, AlignedValueChecked>> for StateValue<D, AlignedValue> {
214    fn from(value: StateValue<D, AlignedValueChecked>) -> Self {
215        let checked = Sp::<_, D>::new(value);
216        let unchecked: Sp<StateValue<D, AlignedValue>, D> = checked
217            .arena
218            .get_lazy(&checked.child_repr.clone().into())
219            .expect("lazy arena lookup should not fail");
220        (*unchecked).clone()
221    }
222}
223
224// A named method rather than a `TryFrom` impl: a second `TryFrom` candidate breaks inference for
225// untyped literals such as `StateValue::Null.try_into()` in the generated program fragments.
226impl<D: DB> StateValue<D, AlignedValue> {
227    /// Converts this state value into its checked form, failing if it contains a non-canonical
228    /// field encoding or a non-empty Merkle tree.
229    ///
230    /// Must not be used on the critical path: this walks the value as a tree, so a value with
231    /// shared (deduplicated) children takes time exponential in its serialized size.
232    #[allow(clippy::result_unit_err)]
233    pub fn try_into_checked(&self) -> Result<StateValue<D, AlignedValueChecked>, ()> {
234        let res = match self {
235            StateValue::Null => StateValue::Null,
236            StateValue::Cell(v) => {
237                StateValue::Cell(Sp::new(AlignedValueChecked::try_from((**v).clone())?))
238            }
239            StateValue::Map(m) => StateValue::Map(
240                m.iter()
241                    .map(|kv| {
242                        Ok((
243                            AlignedValueChecked::try_from((*kv.0).clone())?,
244                            kv.1.try_into_checked()?,
245                        ))
246                    })
247                    .collect::<Result<_, ()>>()?,
248            ),
249            StateValue::Array(arr) => StateValue::Array(
250                arr.iter()
251                    .map(|v| v.try_into_checked())
252                    .collect::<Result<_, ()>>()?,
253            ),
254            StateValue::BoundedMerkleTree(t) => StateValue::BoundedMerkleTree(t.clone()),
255        };
256        <AlignedValueChecked as AlignedValueKind<D>>::additional_invariant_checks(&res)
257            .map_err(|_| ())?;
258        Ok(res)
259    }
260}
261
262impl Debug for AlignedValueChecked {
263    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
264        self.0.fmt(f)
265    }
266}
267
268impl Serialize for AlignedValueChecked {
269    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
270    where
271        S: Serializer
272    {
273        Serialize::serialize(&self.0, serializer)
274    }
275}
276
277impl<'de> Deserialize<'de> for AlignedValueChecked {
278    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
279    where
280        D: Deserializer<'de>
281    {
282        let value: AlignedValue = Deserialize::deserialize(deserializer)?;
283        if value.alignment.fits_field_check(&value.value, |atom| Fr::try_from(atom).is_ok()) {
284            Ok(AlignedValueChecked(value))
285        } else {
286            Err(<D::Error as serde::de::Error>::custom("value failed field alignment check"))
287        }
288    }
289}
290
291impl Serializable for AlignedValueChecked {
292    fn serialize(&self, writer: &mut impl Write) -> std::io::Result<()> {
293        Serializable::serialize(&self.0, writer)
294    }
295    fn serialized_size(&self) -> usize {
296        self.0.serialized_size()
297    }
298}
299
300impl Deserializable for AlignedValueChecked {
301    fn deserialize(reader: &mut impl Read, recursion_depth: u32) -> std::io::Result<Self> {
302        let val: AlignedValue = Deserializable::deserialize(reader, recursion_depth)?;
303        if !val.alignment.fits_field_check(&val.value, |atom| Fr::try_from(atom).is_ok()) {
304            return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "deserialized AlignedValue is not aligned with field check"));
305        }
306        Ok(AlignedValueChecked(val))
307    }
308}
309
310// NOTE: Shared tag with AlignedValue to not change the serialization contract for security fix.
311impl Tagged for AlignedValueChecked {
312    fn tag() -> std::borrow::Cow<'static, str> {
313        AlignedValue::tag()
314    }
315    fn tag_unique_factor() -> String {
316        AlignedValue::tag_unique_factor()
317    }
318}
319tag_enforcement_test!(AlignedValueChecked);
320
321impl<D: DB> From<u64> for StateValue<D> {
322    fn from(value: u64) -> Self {
323        StateValue::Cell(Sp::new(value.into()))
324    }
325}
326
327// We need to manually implement `Drop` to avoid implicit unbounded recursion, which could lead to
328// stack overflows. See https://rust-unofficial.github.io/too-many-lists/first-drop.html.
329impl<D: DB, V: AlignedValueKind<D>> Drop for StateValue<D, V> {
330    fn drop(&mut self) {
331        // Early return for non-recursive types. This ensures that we have a base-case for Drop,
332        // as we'll end up recursing at least once otherwise, because we keep a queue of state
333        // values otherwise.
334        match self {
335            StateValue::Null | StateValue::Cell(_) | StateValue::BoundedMerkleTree(_) => return,
336            StateValue::Map(m) if m.size() == 0 => return,
337            StateValue::Array(a) if a.is_empty() => return,
338            _ => {}
339        }
340        // This allows us to escape from the &mut to a owned reference
341        // Note that this relies on the `Default` of `Null` falling into our base case.
342        let mut frontier = vec![std::mem::take(self)];
343        while let Some(mut curr) = frontier.pop() {
344            match &mut curr {
345                StateValue::Map(m) => {
346                    let mut tmp = HashMap::new();
347                    std::mem::swap(m, &mut tmp);
348                    frontier.extend(tmp.into_inner_for_drop().flat_map(|(_, v)| v.into_iter()));
349                }
350                StateValue::Array(a) => {
351                    let mut tmp = Array::new();
352                    std::mem::swap(a, &mut tmp);
353                    frontier.extend(tmp.into_inner_for_drop());
354                }
355                _ => {}
356            }
357            // It is now safe to drop curr, as this has an empty map/array in it.
358            drop(curr);
359        }
360    }
361}
362
363impl<D: DB, V: AlignedValueKind<D>> Distribution<StateValue<D, V>> for Standard
364    where Standard: Distribution<V>
365{
366    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> StateValue<D, V> {
367        let disc = rng.gen_range(0..40);
368        // Converges because:
369        // - 38/40 cases do not recurse
370        // - 1/40 (Map) samples randomly between 0..8 children (-> expected 3.5 recursive calls)
371        // - 1/40 (Array) samples randomly between 0..=16 children (-> expected 8 recursive calls)
372        // => 11.5 / 40 expected recursive calls < 1
373        match disc {
374            20..=35 => StateValue::Cell(Sp::new(rng.r#gen())),
375            36..=37 => {
376                let mut mt: MerkleTree<(), D> = rng.r#gen::<MerkleTree<(), D>>();
377                // The `Serializable::unversioned_serialize` impl requires this.
378                while mt.height() == 0 || mt.height() > 32 {
379                    mt = rng.r#gen::<MerkleTree<(), D>>();
380                }
381                let height = mt.height();
382                let res = StateValue::BoundedMerkleTree(mt);
383                // Checked instantiations only admit blank trees.
384                if V::additional_invariant_checks(&res).is_ok() {
385                    res
386                } else {
387                    StateValue::BoundedMerkleTree(MerkleTree::blank(height))
388                }
389            }
390            38 => StateValue::Map(rng.r#gen::<HashMap<V, StateValue<D, V>, D>>()),
391            39 => {
392                let len = rng.gen_range(0..=16);
393                let arr = (0..len).fold(Array::<StateValue<D, V>, D>::new(), |arr, _| arr.push(rng.r#gen::<StateValue<D, V>>()));
394                StateValue::Array(arr)
395            }
396            _ => StateValue::Null,
397        }
398    }
399}
400
401impl<D: DB, V: AlignedValueKind<D>> FieldRepr for StateValue<D, V> {
402    fn field_repr<W: MemWrite<Fr>>(&self, writer: &mut W) {
403        use StateValue::*;
404        match self {
405            Null => writer.write(&[0.into()]),
406            Cell(v) => {
407                writer.write(&[1.into()]);
408                v.field_repr(writer);
409            }
410            Map(m) => {
411                writer.write(&[(2u128 | ((m.size() as u128) << 4)).into()]);
412                let mut sorted = m.iter().collect::<Vec<_>>();
413                sorted.sort();
414                for kv in sorted.into_iter() {
415                    kv.0.field_repr(writer);
416                    kv.1.field_repr(writer);
417                }
418            }
419            Array(arr) => {
420                writer.write(&[(3u64 | ((arr.len() as u64) << 4)).into()]);
421                for elem in arr.iter() {
422                    elem.field_repr(writer);
423                }
424            }
425            BoundedMerkleTree(t) => {
426                let entries = t.iter().collect::<Vec<_>>();
427                writer.write(&[(4u128
428                    | ((t.height() as u128) << 4)
429                    | ((entries.len() as u128) << 12))
430                    .into()]);
431                for entry in entries.into_iter() {
432                    entry.field_repr(writer);
433                }
434            }
435        }
436    }
437
438    fn field_size(&self) -> usize {
439        self.field_size_memoized(&mut DagMemo::new())
440    }
441}
442
443impl<D: DB, V: AlignedValueKind<D>> StateValue<D, V> {
444    /// [`FieldRepr::field_size`], saturating, visiting each distinct node once
445    /// across every value sharing `memo`.
446    pub fn field_size_memoized(&self, memo: &mut DagMemo<usize, D>) -> usize {
447        use StateValue::*;
448        let child = |memo: &mut DagMemo<usize, D>, v: &Sp<StateValue<D, V>, D>| {
449            memo.get_or_compute(v, |memo, v| v.field_size_memoized(memo))
450        };
451        1usize.saturating_add(match self {
452            Null => 0,
453            Cell(v) => v.field_size(),
454            Map(m) => m.fold(memo, |memo, k, v| {
455                k.field_size().saturating_add(child(memo, v))
456            }),
457            Array(arr) => arr.fold(memo, child),
458            BoundedMerkleTree(t) => {
459                t.fold(memo, |_, hash, _| 1usize.saturating_add(hash.field_size()))
460            }
461        })
462    }
463}
464
465impl<D: DB, V: AlignedValueKind<D>> Serialize for StateValue<D, V> {
466    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
467        match self {
468            StateValue::Null => {
469                let mut ser = ser.serialize_struct("StateValue", 1)?;
470                ser.serialize_field("tag", "null")?;
471                ser.end()
472            }
473            StateValue::Cell(val) => {
474                let mut ser = ser.serialize_struct("StateValue", 2)?;
475                ser.serialize_field("tag", "cell")?;
476                ser.serialize_field("content", &**val)?;
477                ser.end()
478            }
479            StateValue::Map(val) => {
480                let mut ser = ser.serialize_struct("StateValue", 2)?;
481                ser.serialize_field("tag", "map")?;
482                ser.serialize_field("content", val)?;
483                ser.end()
484            }
485            StateValue::Array(val) => {
486                let mut ser = ser.serialize_struct("StateValue", 2)?;
487                ser.serialize_field("tag", "array")?;
488                ser.serialize_field("content", val)?;
489                ser.end()
490            }
491            StateValue::BoundedMerkleTree(val) => {
492                let mut ser = ser.serialize_struct("StateValue", 2)?;
493                ser.serialize_field("tag", "boundedMerkleTree")?;
494                ser.serialize_field("content", val)?;
495                ser.end()
496            }
497        }
498    }
499}
500
501struct StateValueVisitor<D: DB, V: AlignedValueKind<D>>(PhantomData<(D, V)>);
502
503impl<'de, D: DB, V: AlignedValueKind<D>> Visitor<'de> for StateValueVisitor<D, V> {
504    type Value = StateValue<D, V>;
505    fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
506        write!(formatter, "a state value")
507    }
508
509    fn visit_seq<V2: SeqAccess<'de>>(self, mut seq: V2) -> Result<StateValue<D, V>, V2::Error> {
510        let tag: String = seq
511            .next_element()?
512            .ok_or_else(|| de::Error::invalid_length(0, &self))?;
513        match &tag[..] {
514            "null" => Ok(StateValue::Null),
515            "cell" => Ok(StateValue::Cell(Sp::new(
516                seq.next_element()?
517                    .ok_or_else(|| de::Error::invalid_length(1, &self))?,
518            ))),
519            "map" => Ok(StateValue::Map(
520                seq.next_element()?
521                    .ok_or_else(|| de::Error::invalid_length(1, &self))?,
522            )),
523            "array" => Ok(StateValue::Array(
524                seq.next_element()?
525                    .ok_or_else(|| de::Error::invalid_length(1, &self))?,
526            )),
527            "boundedMerkleTree" => Ok(StateValue::BoundedMerkleTree(
528                seq.next_element()?
529                    .ok_or_else(|| de::Error::invalid_length(1, &self))?,
530            )),
531            tag => Err(de::Error::unknown_variant(
532                tag,
533                &["null", "cell", "map", "array", "boundedMerkleTree"],
534            )),
535        }
536    }
537
538    fn visit_map<V2: MapAccess<'de>>(self, mut map: V2) -> Result<StateValue<D, V>, V2::Error> {
539        let first_key: String = map
540            .next_key()?
541            .ok_or_else(|| de::Error::missing_field("tag"))?;
542        match &first_key[..] {
543            "tag" => {
544                let tag: String = map.next_value()?;
545                fn get_content<'de2, V: MapAccess<'de2>, T: Deserialize<'de2>>(
546                    map: &mut V,
547                ) -> Result<T, V::Error> {
548                    let entry: (String, T) = map
549                        .next_entry()?
550                        .ok_or_else(|| de::Error::missing_field("content"))?;
551                    if &entry.0[..] == "content" {
552                        Ok(entry.1)
553                    } else {
554                        Err(de::Error::unknown_field(&entry.0[..], &["tag", "content"]))
555                    }
556                }
557                match &tag[..] {
558                    "null" => Ok(StateValue::Null),
559                    "cell" => Ok(StateValue::Cell(Sp::new(get_content(&mut map)?))),
560                    "map" => Ok(StateValue::Map(get_content(&mut map)?)),
561                    "array" => Ok(StateValue::Array(get_content(&mut map)?)),
562                    "boundedMerkleTree" => {
563                        Ok(StateValue::BoundedMerkleTree(get_content(&mut map)?))
564                    }
565                    tag => Err(de::Error::unknown_variant(
566                        tag,
567                        &["null", "cell", "map", "array", "boundedMerkleTree"],
568                    )),
569                }
570            }
571            "content" => Err(de::Error::custom(
572                "limitation of current deserialization: StateValue tag must preceed contents",
573            )),
574            field => Err(de::Error::unknown_field(field, &["tag", "content"])),
575        }
576    }
577}
578
579impl<'de, D1: DB, V: AlignedValueKind<D1>> Deserialize<'de> for StateValue<D1, V> {
580    fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
581        let v = de.deserialize_struct(
582            "StateValue",
583            &["tag", "content"],
584            StateValueVisitor(PhantomData),
585        )?;
586        v.invariant().map_err(serde::de::Error::custom)?;
587        Ok(v)
588    }
589}
590
591#[macro_export]
592macro_rules! stval {
593    (null) => {
594        StateValue::Null
595    };
596    (($val:expr_2021)) => {
597        StateValue::Cell(Sp::new($crate::state::ExpectFromAligned::expect_from($val, "`stval!` macro invocation should be within legal conversion space")))
598    };
599    ({MT($height:expr_2021) {$($key:expr_2021 => $val:expr_2021),*}}) => {
600        StateValue::BoundedMerkleTree(MerkleTree::blank($height)$(.try_update_hash($key, $val, ()).expect("updating hash on `StateValue` should always succeed, as these should not be collapsed"))*.rehash())
601    };
602    ({$($key:expr_2021 => $val:tt),*}) => {
603        StateValue::Map(HashMap::new()$(.insert($crate::state::ExpectFromAligned::expect_from($key, "`stval!` macro invocation should be within legal conversion space"), stval!($val)))*)
604    };
605    ({$key:expr_2021 => $val:tt}; $n:expr_2021) => {
606        {
607            StateValue::Map((0..$n).into_iter().map(|x| {
608                ($crate::state::ExpectFromAligned::expect_from($key + x as u32, "`stval!` macro invocation should be within legal conversion space"), stval!($val))
609            }).collect())
610        }
611    };
612    ([$($val:tt),*]) => {
613        StateValue::Array(vec![$(stval!($val)),*].into())
614    };
615    ([$elem:tt; $n:expr_2021]) => {
616        StateValue::Array(vec![stval!($elem); $n].into())
617    };
618}
619
620pub use stval;
621
622impl<D: DB, V: AlignedValueKind<D>> Debug for StateValue<D, V> {
623    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
624        use StateValue::*;
625        match self {
626            Null => write!(formatter, "null"),
627            Cell(v) => write!(formatter, "{v:?}"),
628            Map(m) => {
629                write!(formatter, "Map ")?;
630                formatter
631                    .debug_map()
632                    .entries(m.iter().map(|kv| (kv.0.clone(), kv.1.clone())))
633                    .finish()
634            }
635            Array(arr) => {
636                write!(formatter, "Array({}) ", arr.len())?;
637                formatter.debug_list().entries(arr.iter()).finish()
638            }
639            BoundedMerkleTree(t) => {
640                write!(formatter, "MerkleTree({}) ", t.height())?;
641                formatter.debug_map().entries(t.iter()).finish()
642            }
643        }
644    }
645}
646
647impl<D: DB, V: AlignedValueKind<D>> StateValue<D, V> {
648    fn invariant(&self) -> std::io::Result<()> {
649        // NOTE: must be kept as a subset of `StateValueChecked::invariant`.
650        match self {
651            StateValue::Null | StateValue::Map(_) => {}
652            StateValue::Cell(v) => {
653                if (**v).serialized_size() > CELL_BOUND {
654                    return Err(std::io::Error::new(
655                        std::io::ErrorKind::InvalidData,
656                        format!("Cell exceeded maximum bound of {CELL_BOUND}"),
657                    ));
658                }
659            }
660            StateValue::Array(arr) => {
661                if arr.len() > 16 {
662                    return Err(std::io::Error::new(
663                        std::io::ErrorKind::InvalidData,
664                        "Array eceeded maximum length of 16",
665                    ));
666                }
667            }
668            StateValue::BoundedMerkleTree(bmt) => {
669                if bmt.height() > 32 {
670                    return Err(std::io::Error::new(
671                        std::io::ErrorKind::InvalidData,
672                        "BMT exceeded maximum height of 32",
673                    ));
674                }
675                if bmt.height() == 0 {
676                    return Err(std::io::Error::new(
677                        std::io::ErrorKind::InvalidData,
678                        "BMT has invalid height of 0",
679                    ));
680                }
681                if bmt.root().is_none() {
682                    return Err(std::io::Error::new(
683                        std::io::ErrorKind::InvalidData,
684                        "BMT must be rehashed",
685                    ));
686                }
687            }
688        }
689        V::additional_invariant_checks(self)?;
690        Ok(())
691    }
692
693    pub fn log_size(&self) -> usize {
694        use StateValue::*;
695        match self {
696            Null => 0,
697            Cell(a) => {
698                // TODO: this is O(n), but probably needs to be O(1).
699                //
700                // Possible fixes: cache the size of the AlignedValue in the
701                // constructor. Not sure if this "size" necessarily needs to be the serialized
702                // size.
703                <V as Serializable>::serialized_size(&**a)
704                    .next_power_of_two()
705                    .ilog2() as usize
706            }
707            Map(m) => (m.size() as u128).next_power_of_two().ilog2() as usize,
708            Array(a) => (a.len() as u128).next_power_of_two().ilog2() as usize,
709            BoundedMerkleTree(t) => t.height() as usize,
710        }
711    }
712}
713
714impl<D: DB> From<AlignedValue> for StateValue<D> {
715    fn from(val: AlignedValue) -> StateValue<D> {
716        StateValue::Cell(Sp::new(val))
717    }
718}
719
720pub fn write_int<W: Write>(writer: &mut W, int: u64) -> io::Result<()> {
721    match int {
722        0..=0x7F => writer.write_all(&[int as u8][..]),
723        0x80..=0x3FFF => writer.write_all(&[0x80 | (int % 0x80) as u8, (int >> 7) as u8][..]),
724        0x4000..=0x1FFFFF => writer.write_all(
725            &[
726                0x80 | (int % 0x80) as u8,
727                0x80 | ((int >> 7) % 0x80) as u8,
728                (int >> 14) as u8,
729            ][..],
730        ),
731        _ => Err(io::Error::new(
732            io::ErrorKind::InvalidData,
733            "too many entries to serialize state value length!",
734        )),
735    }
736}
737
738pub fn int_size(int: u64) -> usize {
739    match int {
740        0..=0x7F => 1,
741        0x80..=0x3FFF => 2,
742        0x4000..=0x1FFFFF => 3,
743        _ => 4,
744    }
745}
746
747pub fn read_int<R: Read>(reader: &mut R) -> io::Result<u64> {
748    let mut buf = [0u8; 3];
749    reader.read_exact(&mut buf[0..1])?;
750    if (buf[0] & 0x80) == 0 {
751        return Ok(buf[0] as u64);
752    }
753    reader.read_exact(&mut buf[1..2])?;
754    if (buf[1] & 0x80) == 0 {
755        return Ok((buf[0] & 0x7f) as u64 | ((buf[1] as u64) << 7));
756    }
757    reader.read_exact(&mut buf[2..3])?;
758    if (buf[2] & 0x80) == 0 {
759        Ok((buf[0] & 0x7f) as u64 | (((buf[1] & 0x7f) as u64) << 7) | ((buf[2] as u64) << 14))
760    } else {
761        Err(io::Error::new(
762            io::ErrorKind::InvalidData,
763            "reserved range for deserializing state value length",
764        ))
765    }
766}
767
768enum MaybeStr<'a> {
769    Str(&'a str),
770    Bytes(&'a [u8]),
771}
772
773struct MaybeStrVisitor<T>(PhantomData<T>);
774
775impl<'de, T: From<Vec<u8>>> serde::de::Visitor<'de> for MaybeStrVisitor<T> {
776    type Value = T;
777    fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
778        formatter.write_str("[byte]string")
779    }
780
781    fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
782        self.visit_string(v.to_owned())
783    }
784
785    fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
786        Ok(v.into_bytes().into())
787    }
788
789    fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
790        self.visit_byte_buf(v.to_vec())
791    }
792
793    fn visit_byte_buf<E: serde::de::Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
794        Ok(v.into())
795    }
796    // Required for serde_json compatibility. See
797    // https://github.com/serde-rs/json/pull/557
798    fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
799        let mut res = Vec::new();
800        while let Some(byte) = seq.next_element()? {
801            res.push(byte);
802        }
803        Ok(res.into())
804    }
805}
806
807fn maybe_str(buf: &[u8]) -> MaybeStr<'_> {
808    // For alphanumeric characters, as well as the following: '+-_":/\?#$%^*&.
809    // we will use a string as-is. For others, we will use byte enocding.
810    // This is to permit arbitrary bytes, while presenting strings to users
811    // where sensible.
812    fn permitted(c: u8) -> bool {
813        c.is_ascii_alphanumeric() || b"'+-_\":/\\?#$^*&.".contains(&c)
814    }
815    if buf.iter().copied().all(permitted)
816        && let Ok(s) = std::str::from_utf8(buf)
817    {
818        return MaybeStr::Str(s);
819    }
820    MaybeStr::Bytes(buf)
821}
822
823macro_rules! idty {
824    ($refty:ident, $bufty:ident) => {
825        pub type $refty<'a> = &'a [u8];
826
827        #[derive(
828            FieldRepr, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serializable, Dummy, Storable,
829        )]
830        #[storable(base)]
831        #[cfg_attr(feature = "proptest", derive(Arbitrary))]
832        pub struct $bufty(pub Vec<u8>);
833
834        impl Serialize for $bufty {
835            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
836                match maybe_str(&self.0) {
837                    MaybeStr::Str(s) => serializer.serialize_str(s),
838                    MaybeStr::Bytes(b) => serializer.serialize_bytes(b),
839                }
840            }
841        }
842
843        impl From<Vec<u8>> for $bufty {
844            fn from(vec: Vec<u8>) -> $bufty {
845                $bufty(vec)
846            }
847        }
848
849        impl<'de> Deserialize<'de> for $bufty {
850            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
851                deserializer.deserialize_any(MaybeStrVisitor(PhantomData))
852            }
853        }
854
855        impl Debug for $bufty {
856            fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
857                match maybe_str(&self.0) {
858                    MaybeStr::Str(s) => formatter.write_str(s),
859                    MaybeStr::Bytes(b) => formatter.write_str(&b.encode_hex::<String>()),
860                }
861            }
862        }
863
864        impl Deref for $bufty {
865            type Target = [u8];
866            fn deref(&self) -> &[u8] {
867                &self.0
868            }
869        }
870
871        impl Borrow<[u8]> for $bufty {
872            fn borrow(&self) -> &[u8] {
873                &self.0
874            }
875        }
876
877        impl From<&[u8]> for $bufty {
878            fn from(e: &[u8]) -> $bufty {
879                $bufty(e.to_owned())
880            }
881        }
882    };
883}
884
885idty!(EntryPoint, EntryPointBuf);
886#[cfg(feature = "proptest")]
887randomised_serialization_test!(EntryPointBuf);
888
889impl Distribution<EntryPointBuf> for Standard {
890    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> EntryPointBuf {
891        let length = rng.gen_range(0..10);
892        EntryPointBuf(
893            vec![0; length]
894                .iter()
895                .map(|_| rng.r#gen::<u8>())
896                .collect::<Vec<u8>>()
897                .to_owned(),
898        )
899    }
900}
901
902impl Tagged for EntryPointBuf {
903    fn tag() -> std::borrow::Cow<'static, str> {
904        "entry-point".into()
905    }
906    fn tag_unique_factor() -> String {
907        "vec(u8)".into()
908    }
909}
910tag_enforcement_test!(EntryPointBuf);
911
912impl EntryPointBuf {
913    pub fn ep_hash(&self) -> HashOutput {
914        persistent_commit(
915            &self[..],
916            HashOutput(*b"midnight:entry-point\0\0\0\0\0\0\0\0\0\0\0\0"),
917        )
918    }
919}
920
921impl Aligned for EntryPointBuf {
922    fn alignment() -> Alignment {
923        Alignment::singleton(AlignmentAtom::Compress)
924    }
925}
926
927#[derive(
928    Clone,
929    Debug,
930    PartialEq,
931    Eq,
932    PartialOrd,
933    Ord,
934    Hash,
935    Serializable,
936    Storable,
937    Serialize,
938    Deserialize,
939)]
940#[storable(base)]
941#[tag = "contract-maintenance-authority[v2]"]
942#[cfg_attr(feature = "proptest", derive(Arbitrary))]
943pub struct ContractMaintenanceAuthority {
944    pub committee: Vec<ContractMaintenanceVerifyingKey>,
945    pub threshold: u32,
946    pub counter: u32,
947}
948tag_enforcement_test!(ContractMaintenanceAuthority);
949
950#[derive(
951    Clone,
952    Debug,
953    PartialEq,
954    Eq,
955    PartialOrd,
956    Ord,
957    Hash,
958    Serializable,
959    Storable,
960    Serialize,
961    Deserialize,
962)]
963#[storable(base)]
964#[tag = "contract-maintenance-verifying-key[v1]"]
965#[cfg_attr(feature = "proptest", derive(Arbitrary))]
966#[serde(tag = "tag", content = "value")]
967#[serde(rename_all = "kebab-case")]
968pub enum ContractMaintenanceVerifyingKey {
969    Schnorr(base_crypto::schnorr::VerifyingKey),
970    #[serde(rename = "ecdsa")]
971    ECDSA(base_crypto::ecdsa::VerifyingKey),
972}
973
974impl ContractMaintenanceAuthority {
975    pub fn new() -> Self {
976        ContractMaintenanceAuthority {
977            committee: vec![],
978            threshold: 1,
979            counter: 0,
980        }
981    }
982}
983
984impl Default for ContractMaintenanceAuthority {
985    fn default() -> Self {
986        Self::new()
987    }
988}
989
990#[derive(Storable)]
991#[derive_where(Clone, PartialEq, Eq)]
992#[storable(db = D)]
993#[cfg_attr(feature = "proptest", derive(Arbitrary))]
994#[tag = "contract-state[v8]"]
995pub struct ContractState<D: DB> {
996    pub data: ChargedState<D>,
997    pub operations: HashMap<EntryPointBuf, ContractOperation, D>,
998    pub maintenance_authority: ContractMaintenanceAuthority,
999    pub balance: HashMap<TokenType, u128, D>,
1000}
1001tag_enforcement_test!(ContractState<InMemoryDB>);
1002
1003#[derive(Storable)]
1004#[derive_where(Clone, PartialEq, Eq)]
1005#[storable(db = D)]
1006#[cfg_attr(feature = "proptest", derive(Arbitrary))]
1007#[tag = "charged-state[v1]"]
1008pub struct ChargedState<D: DB> {
1009    #[cfg(feature = "public-internal-structure")]
1010    pub state: Sp<StateValue<D>, D>,
1011    #[cfg(not(feature = "public-internal-structure"))]
1012    pub(crate) state: Sp<StateValue<D>, D>,
1013    // TODO: it would be better to generate charged keys from `data`, since it's
1014    // an invariant that the chargable contract state is always a subset of the
1015    // `charged_keys`. I assume this implies a manual `Arbitrary`
1016    // implementation, but maybe this is some `proptest` magic that supports
1017    // deriving this ...
1018    #[cfg(feature = "public-internal-structure")]
1019    #[cfg_attr(feature = "proptest", proptest(value = "RcMap::default()"))]
1020    pub charged_keys: RcMap<D>,
1021    #[cfg_attr(feature = "proptest", proptest(value = "RcMap::default()"))]
1022    #[cfg(not(feature = "public-internal-structure"))]
1023    pub(crate) charged_keys: RcMap<D>,
1024}
1025tag_enforcement_test!(ChargedState<InMemoryDB>);
1026
1027impl<D: DB> Debug for ChargedState<D> {
1028    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1029        self.state.fmt(f)
1030    }
1031}
1032
1033impl<D: DB> ChargedState<D> {
1034    /// Creates a new charged state from a given state value. This assumes that
1035    /// this state's storage is paid for elsewhere, and therefore the resulting
1036    /// `ChargedState` *is* accounted for in its storage usage.
1037    ///
1038    /// Specifically, for contract deployments, the happens with a manual
1039    /// `tree_copy` costing of `ContractDeploy` operations.
1040    pub fn new(state: StateValue<D>) -> Self {
1041        let state = Sp::new(state);
1042        let charged_keys =
1043            initial_write_delete_costs(&[state.as_child()].into_iter().collect(), |_, _| {
1044                Default::default()
1045            })
1046            .updated_charged_keys;
1047        ChargedState {
1048            state,
1049            charged_keys,
1050        }
1051    }
1052
1053    pub fn get(&self) -> Sp<StateValue<D>, D> {
1054        self.state.clone()
1055    }
1056
1057    pub fn get_ref(&self) -> &StateValue<D> {
1058        &self.state
1059    }
1060
1061    pub fn update(
1062        &self,
1063        new_state: StateValue<D>,
1064        cpu_cost: impl Fn(u64, u64) -> RunningCost,
1065        gc_limit: impl FnOnce(RunningCost) -> usize,
1066    ) -> (Self, RunningCost) {
1067        // WARNING: Need to be sure the old and new StateValue state is in the
1068        // backend before doing calcs over their keys. The old state is already
1069        // in the backend, because contract states get persisted after contract
1070        // calls. But the new state we're working with now has not been
1071        // persisted yet, indeed, it may never be, e.g. if we run out of gas
1072        // when we cost its writes+deletes.
1073        //
1074        // This sp creation here should be cheap, since we quickly run into sps
1075        // under the covers. However, the top level of the StateValue state is
1076        // *not* an sp. Another solution would be to require the top-level of
1077        // the StateValue state itself be an sp, e.g. by wrapping all fields of
1078        // the ContractState in sps.
1079        let new_state = Sp::new(new_state);
1080        let results = incremental_write_delete_costs(
1081            &self.charged_keys,
1082            &[new_state.as_child()].into_iter().collect(),
1083            cpu_cost,
1084            gc_limit,
1085        );
1086        let cost = results.running_cost();
1087        let state = ChargedState {
1088            state: new_state,
1089            charged_keys: results.updated_charged_keys,
1090        };
1091        (state, cost)
1092    }
1093}
1094
1095impl<D: DB> ContractState<D> {
1096    pub fn new(
1097        data: StateValue<D>,
1098        operations: HashMap<EntryPointBuf, ContractOperation, D>,
1099        maintenance_authority: ContractMaintenanceAuthority,
1100    ) -> Self {
1101        ContractState {
1102            data: ChargedState::new(data),
1103            operations,
1104            maintenance_authority,
1105            balance: HashMap::default(),
1106        }
1107    }
1108}
1109
1110impl<D: DB> Debug for ContractState<D> {
1111    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
1112        write!(formatter, "ContractState (")?;
1113        self.data.state.fmt(formatter)?;
1114        self.operations.fmt(formatter)?;
1115        write!(formatter, "ContractState )")?;
1116        Ok(())
1117    }
1118}
1119
1120impl<D: DB> Default for ContractState<D> {
1121    fn default() -> Self {
1122        Self::new(
1123            StateValue::Null,
1124            HashMap::new(),
1125            ContractMaintenanceAuthority::default(),
1126        )
1127    }
1128}
1129
1130#[derive(
1131    Serializable, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Storable,
1132)]
1133#[storable(base)]
1134#[tag = "contract-operation[v6]"]
1135#[non_exhaustive]
1136pub struct ContractOperation {
1137    /// v1 (zk-stdlib v1) verifier key.
1138    pub v2: Option<transient_crypto_old::proofs::VerifierKey>,
1139    /// v2 (zk-stdlib v2) verifier key.
1140    pub v3: Option<VerifierKey>,
1141    /// The IR associated with this contract operation.
1142    pub ir: Option<Sp<IrBuf>>,
1143}
1144tag_enforcement_test!(ContractOperation);
1145
1146impl ContractOperation {
1147    pub fn new(vk: Option<VerifierKey>, ir: Option<Sp<IrBuf>>) -> Self {
1148        ContractOperation {
1149            v2: None,
1150            ir,
1151            v3: vk,
1152        }
1153    }
1154
1155    /// Returns the latest (v3) verifier key.
1156    pub fn latest(&self) -> Option<&VerifierKey> {
1157        self.v3.as_ref()
1158    }
1159
1160    pub fn latest_mut(&mut self) -> &mut Option<VerifierKey> {
1161        &mut self.v3
1162    }
1163
1164    /// Returns the v2 verifier key.
1165    pub fn v2_vk(&self) -> Option<&transient_crypto_old::proofs::VerifierKey> {
1166        self.v2.as_ref()
1167    }
1168
1169    /// Returns the v3 verifier key.
1170    pub fn v3_vk(&self) -> Option<&VerifierKey> {
1171        self.v3.as_ref()
1172    }
1173}
1174
1175#[cfg(feature = "proptest")]
1176simple_arbitrary!(ContractOperation);
1177#[cfg(feature = "proptest")]
1178randomised_serialization_test!(ContractOperation);
1179
1180impl Distribution<ContractOperation> for Standard {
1181    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ContractOperation {
1182        let some: bool = rng.r#gen();
1183        if some {
1184            ContractOperation {
1185                v2: Some(rng.r#gen()),
1186                ir: None,
1187                v3: None,
1188            }
1189        } else {
1190            ContractOperation {
1191                v2: None,
1192                ir: None,
1193                v3: None,
1194            }
1195        }
1196    }
1197}
1198
1199impl FieldRepr for ContractOperation {
1200    fn field_repr<W: MemWrite<Fr>>(&self, writer: &mut W) {
1201        match self.v2 {
1202            Some(ref vk) => {
1203                writer.write(&[0x01.into()]);
1204                let mut bytes: Vec<u8> = Vec::new();
1205                <transient_crypto_old::proofs::VerifierKey as Serializable>::serialize(
1206                    vk, &mut bytes,
1207                )
1208                .expect("VerifierKey is serializable");
1209                bytes.field_repr(writer);
1210            }
1211            None => writer.write(&[0x00.into()]),
1212        }
1213    }
1214
1215    fn field_size(&self) -> usize {
1216        match self.v2 {
1217            Some(ref vk) => {
1218                let mut bytes: Vec<u8> = Vec::new();
1219                <transient_crypto_old::proofs::VerifierKey as Serializable>::serialize(
1220                    vk, &mut bytes,
1221                )
1222                .expect("VerifierKey is serializable");
1223                1 + bytes.into_iter().fold(0, |acc, b| acc + b.field_size())
1224            }
1225            None => 1,
1226        }
1227    }
1228}
1229
1230impl Debug for ContractOperation {
1231    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
1232        write!(formatter, "<verifier key>")
1233    }
1234}
1235
1236impl<F> Dummy<F> for ContractOperation {
1237    fn dummy_with_rng<R: rand::Rng + ?Sized>(_config: &F, _rng: &mut R) -> Self {
1238        ContractOperation {
1239            v2: None,
1240            ir: None,
1241            v3: None,
1242        }
1243    }
1244}
1245
1246idty!(Ir, IrBuf);
1247impl Tagged for IrBuf {
1248    fn tag() -> std::borrow::Cow<'static, str> {
1249        "ir-buf".into()
1250    }
1251    fn tag_unique_factor() -> String {
1252        "vec(u8)".into()
1253    }
1254}
1255tag_enforcement_test!(IrBuf);
1256
1257#[cfg(test)]
1258mod tests {
1259    use storage::db::InMemoryDB;
1260
1261    use super::*;
1262
1263    fn test_compact_int(x: u64) {
1264        let mut bytes = Vec::new();
1265        write_int(&mut bytes, x).unwrap();
1266        let ptr = &mut &bytes[..];
1267        let y = read_int(ptr).unwrap();
1268        assert_eq!(x, y);
1269        assert!(ptr.is_empty());
1270    }
1271
1272    #[test]
1273    fn test_ints() {
1274        test_compact_int(0x0);
1275        test_compact_int(0x1);
1276        test_compact_int(0x42);
1277        test_compact_int(0x80);
1278        test_compact_int(0xff);
1279        test_compact_int(0x100);
1280        test_compact_int(0x1000);
1281        test_compact_int(0x10000);
1282    }
1283
1284    #[test]
1285    fn test_nested_drop() {
1286        let mut sv: StateValue<InMemoryDB> = StateValue::Null;
1287        for i in 0..12_000 {
1288            sv = StateValue::Array(vec![sv].into());
1289            //sv = StateValue::Map(default_storage().new_map().insert(0u8.into(), sv));
1290            if i % 100 == 0 {
1291                dbg!(i);
1292            }
1293        }
1294        drop(sv);
1295        println!("drop(sv) finished!");
1296    }
1297
1298    fn test_ser<T: Serializable + Deserializable + Eq + Debug>(val: T) {
1299        dbg!(&val);
1300        let mut bytes = Vec::new();
1301        T::serialize(&val, &mut bytes).unwrap();
1302        assert_eq!(bytes.len(), T::serialized_size(&val));
1303        let mut b = bytes.as_slice();
1304        let copy = T::deserialize(&mut b, 0).unwrap();
1305        assert_eq!(b.bytes().count(), 0);
1306        assert_eq!(val, copy);
1307    }
1308
1309    /// The scalar field modulus `p`, little-endian, with `x` added, giving the non-canonical
1310    /// byte encoding of `x + p`. Checks the constant against `Fr` itself, so a wrong modulus
1311    /// fails loudly instead of silently weakening the test.
1312    fn field_alias(x: u8) -> AlignedValue {
1313        let mut bytes = hex::decode("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")
1314            .unwrap();
1315        bytes.reverse();
1316        assert!(Fr::from_le_bytes(&bytes).is_none(), "p itself must not be a field element");
1317        let mut carry = x as u16;
1318        for b in bytes.iter_mut() {
1319            let sum = *b as u16 + carry;
1320            *b = sum as u8;
1321            carry = sum >> 8;
1322        }
1323        assert_eq!(carry, 0);
1324        let atom = ValueAtom(bytes);
1325        assert!(atom.is_in_normal_form());
1326        AlignedValue::new(
1327            base_crypto::fab::Value(vec![atom]),
1328            Alignment::singleton(AlignmentAtom::Field),
1329        )
1330        .expect("`x + p` fits `Field` in the unchecked encoding")
1331    }
1332
1333    fn canonical_field(x: u8) -> AlignedValue {
1334        AlignedValue::new(
1335            base_crypto::fab::Value(vec![ValueAtom(vec![x])]),
1336            Alignment::singleton(AlignmentAtom::Field),
1337        )
1338        .unwrap()
1339    }
1340
1341    #[test]
1342    fn field_alias_is_rejected_in_checked_context() {
1343        let canonical = canonical_field(5);
1344        let alias = field_alias(5);
1345
1346        // The premise of the attack: distinct values, identical proof representation.
1347        assert_ne!(canonical, alias);
1348        let mut canonical_repr = Vec::<Fr>::new();
1349        canonical.field_repr(&mut canonical_repr);
1350        let mut alias_repr = Vec::<Fr>::new();
1351        alias.field_repr(&mut alias_repr);
1352        assert_eq!(canonical_repr, alias_repr);
1353
1354        // The canonical value is accepted, the alias is not.
1355        assert!(AlignedValueChecked::try_from(canonical.clone()).is_ok());
1356        assert!(AlignedValueChecked::try_from(alias.clone()).is_err());
1357
1358        // Binary deserialization enforces the same.
1359        let mut bytes = Vec::new();
1360        Serializable::serialize(&alias, &mut bytes).unwrap();
1361        assert!(
1362            <AlignedValueChecked as Deserializable>::deserialize(&mut bytes.as_slice(), 0).is_err()
1363        );
1364        let mut bytes = Vec::new();
1365        Serializable::serialize(&canonical, &mut bytes).unwrap();
1366        assert!(
1367            <AlignedValueChecked as Deserializable>::deserialize(&mut bytes.as_slice(), 0).is_ok()
1368        );
1369    }
1370
1371    #[test]
1372    fn field_alias_map_key_is_rejected_when_checking_state_values() {
1373        // A `Set<Field>` replay guard holding the canonical key and its alias.
1374        let cell = || StateValue::<InMemoryDB>::Cell(Sp::new(canonical_field(1)));
1375        let canonical_only = StateValue::<InMemoryDB>::Map(
1376            HashMap::new().insert(canonical_field(5), cell()),
1377        );
1378        let with_alias = StateValue::<InMemoryDB>::Map(
1379            HashMap::new()
1380                .insert(canonical_field(5), cell())
1381                .insert(field_alias(5), cell()),
1382        );
1383        assert!(canonical_only.try_into_checked().is_ok());
1384        assert!(with_alias.try_into_checked().is_err());
1385        // Nested inside an array, and as a cell value, too.
1386        assert!(
1387            StateValue::<InMemoryDB>::Array(Array::new().push(with_alias.clone()))
1388                .try_into_checked()
1389                .is_err()
1390        );
1391        assert!(
1392            StateValue::<InMemoryDB>::Cell(Sp::new(field_alias(5)))
1393                .try_into_checked()
1394                .is_err()
1395        );
1396    }
1397
1398    #[test]
1399    fn test_state_ser() {
1400        let cs = ChargedState::<InMemoryDB>::new(StateValue::Null);
1401        test_ser::<RcMap<InMemoryDB>>(cs.charged_keys);
1402        test_ser::<ContractState<InMemoryDB>>(ContractState::default());
1403        test_ser::<StateValue<InMemoryDB>>(stval!((512u64)));
1404        test_ser::<StateValue<InMemoryDB>>(stval!({ 512u64 => (12u64) }));
1405        test_ser::<StateValue<InMemoryDB>>(stval!([(512u64)]));
1406        test_ser::<StateValue<InMemoryDB>>(stval!(null));
1407        test_ser::<StateValue<InMemoryDB>>(stval!({MT(12) {}}));
1408    }
1409
1410    #[test]
1411    fn test_log_size() {
1412        use transient_crypto::merkle_tree::MerkleTree;
1413
1414        // Like stval, but force database param to be InMemoryDB
1415        macro_rules! s {
1416            ($($tt:tt)*) => {
1417                {
1418                    let sv: StateValue<InMemoryDB> = stval!($($tt)*);
1419                    sv
1420                }
1421            };
1422        }
1423
1424        assert_eq!(s!(null).log_size(), 0);
1425
1426        assert_eq!(s!((0u8)).log_size(), 1);
1427        assert_eq!(s!((0u16)).log_size(), 1);
1428        assert_eq!(s!((0u32)).log_size(), 1);
1429        assert_eq!(s!((0u64)).log_size(), 1);
1430
1431        assert_eq!(s!({}).log_size(), 0);
1432        assert_eq!(s!({ 0u32 => (1u32) }; 3).log_size(), 2);
1433        assert_eq!(s!({ 0u32 => (1u32) }; 4).log_size(), 2);
1434        assert_eq!(s!({ 0u32 => (1u32) }; 5).log_size(), 3);
1435        assert_eq!(s!({ 0u32 => (1u32) }; 7).log_size(), 3);
1436        assert_eq!(s!({ 0u32 => (1u32) }; 8).log_size(), 3);
1437        assert_eq!(s!({ 0u32 => (1u32) }; 9).log_size(), 4);
1438
1439        assert_eq!(s!([]).log_size(), 0);
1440        assert_eq!(s!([(1u32); 3]).log_size(), 2);
1441        assert_eq!(s!([(1u32); 4]).log_size(), 2);
1442        assert_eq!(s!([(1u32); 7]).log_size(), 3);
1443        assert_eq!(s!([(1u32); 8]).log_size(), 3);
1444        assert_eq!(s!([(1u32); 15]).log_size(), 4);
1445        assert_eq!(s!([(1u32); 16]).log_size(), 4);
1446
1447        for h in 0..16 {
1448            assert_eq!(s!({MT(h) {}}).log_size(), h as usize);
1449        }
1450    }
1451}