Skip to main content

zebra_chain/serialization/
arbitrary.rs

1//! Arbitrary data generation for serialization proptests
2
3use chrono::{DateTime, TimeZone, Utc};
4use proptest::prelude::*;
5
6use super::{
7    CompactSizeMessage, DateTime32, TrustedPreallocate, ZcashSerialize, MAX_PROTOCOL_MESSAGE_LEN,
8};
9
10impl Arbitrary for DateTime32 {
11    type Parameters = ();
12
13    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
14        any::<u32>().prop_map(Into::into).boxed()
15    }
16
17    type Strategy = BoxedStrategy<Self>;
18}
19
20/// Returns a strategy that produces an arbitrary [`chrono::DateTime<Utc>`],
21/// based on the full valid range of the type.
22///
23/// Both the seconds and nanoseconds values are randomised, including leap seconds:
24/// <https://docs.rs/chrono/0.4.19/chrono/naive/struct.NaiveTime.html#leap-second-handling>
25///
26/// Wherever possible, Zebra should handle leap seconds by:
27/// - making durations and intervals 3 seconds or longer,
28/// - avoiding complex time-based calculations, and
29/// - avoiding relying on subsecond precision or time order.
30///
31/// When monotonic times are needed, use the opaque `std::time::Instant` type.
32///
33/// # Usage
34///
35/// Zebra uses these times internally, typically via [`Utc::now`].
36///
37/// Some parts of the Zcash network protocol (`Version` messages) also use times
38/// with an 8-byte seconds value. Unlike this function, they have zero
39/// nanoseconds values. (So they never have `chrono` leap seconds.)
40pub fn datetime_full() -> impl Strategy<Value = chrono::DateTime<Utc>> {
41    (
42        // TODO: should we be subtracting 1 from the maximum timestamp?
43        DateTime::<Utc>::MIN_UTC.timestamp()..=DateTime::<Utc>::MAX_UTC.timestamp(),
44        // > The nanosecond part can exceed 1,000,000,000 in order to represent a leap second,
45        // > but only when secs % 60 == 59. (The true "UNIX timestamp" cannot represent a leap second
46        // > unambiguously.)
47        //
48        // https://docs.rs/chrono/latest/chrono/offset/trait.TimeZone.html#method.timestamp_opt
49        //
50        // We use `1_000_000_000` as the right side of the range to avoid that issue.
51        0..1_000_000_000_u32,
52    )
53        .prop_map(|(secs, nsecs)| {
54            Utc.timestamp_opt(secs, nsecs)
55                .single()
56                .expect("in-range number of seconds and valid nanosecond")
57        })
58}
59
60/// Returns a strategy that produces an arbitrary time from a [`u32`] number
61/// of seconds past the epoch.
62///
63/// The nanoseconds value is always zero.
64///
65/// The Zcash protocol typically uses 4-byte seconds values, except for the
66/// `Version` message.
67///
68/// TODO: replace this strategy with `any::<DateTime32>()`.
69pub fn datetime_u32() -> impl Strategy<Value = chrono::DateTime<Utc>> {
70    any::<DateTime32>().prop_map(Into::into)
71}
72
73impl Arbitrary for CompactSizeMessage {
74    type Parameters = ();
75
76    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
77        (0..=MAX_PROTOCOL_MESSAGE_LEN)
78            .prop_map(|size| {
79                size.try_into()
80                    .expect("MAX_PROTOCOL_MESSAGE_LEN fits in CompactSizeMessage")
81            })
82            .boxed()
83    }
84
85    type Strategy = BoxedStrategy<Self>;
86}
87
88/// Calculate the serialized lengths of maximum-sized vectors of identical `item`s.
89///
90/// Returns the following calculations on `item`:
91///   smallest_disallowed_vec_len
92///   smallest_disallowed_serialized_len
93///   largest_allowed_vec_len
94///   largest_allowed_serialized_len
95///
96/// For variable-size types, `largest_allowed_serialized_len` might not fit within
97/// `MAX_PROTOCOL_MESSAGE_LEN` or `MAX_BLOCK_SIZE`.
98pub fn max_allocation_is_big_enough<T>(item: T) -> (usize, usize, usize, usize)
99where
100    T: TrustedPreallocate + ZcashSerialize,
101{
102    let max_allocation: usize = T::max_allocation().try_into().unwrap();
103    let item_len = item.zcash_serialized_size();
104
105    // A vector writes its CompactSize count followed by each item. All items are identical,
106    // so serialize just one instead of cloning and serializing it thousands of times.
107    let serialized_len = |count: usize| {
108        let prefix = CompactSizeMessage::try_from(count).expect("count fits in the message limit");
109        prefix.zcash_serialized_size() + count * item_len
110    };
111
112    (
113        max_allocation + 1,
114        serialized_len(max_allocation + 1),
115        max_allocation,
116        serialized_len(max_allocation),
117    )
118}