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
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0

//! Module contains the implementation of chunked Random Oracle input

use std::fmt::Display;

use ark_ff::{fields::PrimeField, BigInteger, BigInteger256, Zero};
use bitvec::prelude::*;
use mina_hasher::{Fp, ROInput};
use o1_utils::FieldHelpers;

/// Trait that converts a struct to [ChunkedROInput]
pub trait ToChunkedROInput {
    fn to_chunked_roinput(&self) -> ChunkedROInput;

    fn roinput(&self) -> ROInput {
        self.to_chunked_roinput().into()
    }
}

/// Chunked Random Oracle input
#[derive(Default, Debug, Clone, Eq, PartialEq)]
pub struct ChunkedROInput {
    pub fields: Vec<Fp>,
    pub packed: Vec<(Fp, u32)>,
}

impl ChunkedROInput {
    /// Create a new empty random oracle input
    pub fn new() -> Self {
        Default::default()
    }

    /// Append another random oracle input
    pub fn append(mut self, other: Self) -> Self {
        self.fields.extend(other.fields.into_iter());
        self.packed.extend(other.packed.into_iter());
        self
    }

    /// Append [ToChunkedROInput]
    pub fn append_chunked(self, other: &impl ToChunkedROInput) -> Self {
        self.append(other.to_chunked_roinput())
    }

    /// Append a base field element
    pub fn append_field(mut self, f: Fp) -> Self {
        self.fields.push(f);
        self
    }

    /// Append a base field element
    pub fn append_packed(mut self, f: Fp, max_bits: u32) -> Self {
        self.packed.push((f, max_bits));
        self
    }

    /// Append bytes
    pub fn append_bytes(mut self, bytes: &[u8]) -> Self {
        for b in bytes.as_bits::<Lsb0>().to_bitvec() {
            self = self.append_bool(b);
        }
        self
    }

    /// Append a single bit
    pub fn append_bool(self, b: bool) -> Self {
        let f = {
            let mut bits = BitVec::with_capacity(1);
            bits.push(b);
            Self::bits_to_fp_unsafe(bits)
        };
        self.append_packed(f, 1)
    }

    /// Append a 32-bit unsigned integer
    pub fn append_u32(self, x: u32) -> Self {
        let f = {
            let bits = x.to_le_bytes().as_bits::<Lsb0>().to_bitvec();
            Self::bits_to_fp_unsafe(bits)
        };
        self.append_packed(f, u32::BITS)
    }

    /// Append a 64-bit unsigned integer
    pub fn append_u64(self, x: u64) -> Self {
        let f = {
            let bits = x.to_le_bytes().as_bits::<Lsb0>().to_bitvec();
            Self::bits_to_fp_unsafe(bits)
        };
        self.append_packed(f, u64::BITS)
    }

    /// Serialize random oracle input to vector of base field elements
    pub fn into_fields(self) -> Vec<Fp> {
        fn shl(f: Fp, n: u32) -> Fp {
            if n == 0 {
                f
            } else {
                let mut big: BigInteger256 = f.into();
                big.muln(n);
                big.into()
            }
        }
        let size_in_bits = Fp::size_in_bits() as u32;
        let mut fields = self.fields;
        let mut acc_bits = 0;
        let mut sum = Fp::zero();
        for (f, n_bits) in self.packed.into_iter() {
            if acc_bits + n_bits < size_in_bits {
                sum = shl(sum, n_bits) + f;
                acc_bits += n_bits;
            } else {
                fields.push(sum);
                acc_bits = n_bits;
                sum = f;
            }
        }
        if acc_bits > 0 {
            fields.push(sum);
        }
        fields
    }

    /// Convert [BitVec] to [Fp]
    /// Note this is a temparory solution before chunked roinput is
    /// supported in proof-systems, use [anyhow::Result] for convinience
    pub fn bits_to_fp(mut bits: BitVec<u8>) -> anyhow::Result<Fp> {
        let size_in_bits = Fp::size_in_bits();
        anyhow::ensure!(
            bits.len() <= size_in_bits,
            "Input should not be greater than {size_in_bits} bits",
        );
        bits.resize(size_in_bits, false);
        Ok(Fp::from_bytes(&bits.into_vec())?)
    }

    /// Convert [BitVec] to [Fp], panics when any error occurs
    pub fn bits_to_fp_unsafe(bits: BitVec<u8>) -> Fp {
        Self::bits_to_fp(bits).expect("Failed to create base field element")
    }
}

impl From<ChunkedROInput> for ROInput {
    fn from(i: ChunkedROInput) -> Self {
        let mut roi = ROInput::new();
        for f in i.into_fields() {
            roi = roi.append_field(f);
        }
        roi
    }
}

impl Display for ChunkedROInput {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fn fp_to_str(fp: Fp) -> String {
            let big256: BigInteger256 = fp.into();
            let big: num::BigUint = big256.into();
            big.to_str_radix(10)
        }
        writeln!(f, "fields ({}):", self.fields.len())?;
        for fp in &self.fields {
            writeln!(f, "\t{}", fp_to_str(*fp))?;
        }
        writeln!(f, "packed: ({}):", self.packed.len())?;
        for (fp, l) in &self.packed {
            writeln!(f, "\t{l}:{}", fp_to_str(*fp))?;
        }
        Ok(())
    }
}