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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
 * AquaVM Workflow Engine
 *
 * Copyright (C) 2024 Fluence DAO
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

pub use super::errors::DataVerifierError;
use crate::CanonResult;
use crate::CidInfo;
use crate::ExecutedState;
use crate::ExecutionTrace;
use crate::InterpreterData;

use air_interpreter_cid::{CidRef, CID};
use air_interpreter_signatures::PublicKey;
use air_interpreter_signatures::Signature;
use air_interpreter_signatures::SignatureStore;

use std::collections::HashMap;
use std::rc::Rc;

const CANNOT_HAPPEN_IN_VERIFIED_CID_STORE: &str = "cannot happen in a checked CID store";

/// An util for verificating particular data's signatures.
pub struct DataVerifier<'data> {
    // a map from peer_id to peer's info (public key, signature, CIDS)
    grouped_cids: HashMap<Box<str>, PeerInfo<'data>>,
    salt: &'data str,
}

impl<'data> DataVerifier<'data> {
    // it can be further optimized if only required parts are passed;
    // SignatureStore is not used elsewhere
    pub fn new(data: &'data InterpreterData, salt: &'data str) -> Result<Self, DataVerifierError> {
        // validate key algoritms
        for (public_key, _) in data.signatures.iter() {
            public_key
                .validate()
                .map_err(|error| DataVerifierError::MalformedKey {
                    error,
                    key: public_key.to_string(),
                })?;
        }

        // it contains signature too; if we try to add a value to a peer w/o signature, it is an immediate error
        let mut grouped_cids: HashMap<Box<str>, PeerInfo<'data>> = data
            .signatures
            .iter()
            .map(|(public_key, signature)| {
                (
                    public_key
                        .to_peer_id()
                        .expect("cannot happen, was verifeid before")
                        .to_string()
                        .into(),
                    PeerInfo::new(public_key, signature),
                )
            })
            .collect();

        // fill PeerInfo's `cids` field, checking for peer IDs without a key
        collect_peers_cids_from_trace(&data.trace, &data.cid_info, &mut grouped_cids)?;

        // sort cids for canonicalization
        for peer_info in grouped_cids.values_mut() {
            peer_info.cids.sort_unstable();
        }

        Ok(Self { grouped_cids, salt })
    }

    /// Verify each peers' signatures.
    pub fn verify(&self) -> Result<(), DataVerifierError> {
        for peer_info in self.grouped_cids.values() {
            peer_info
                .public_key
                .verify(&peer_info.cids, self.salt, peer_info.signature)
                .map_err(|error| DataVerifierError::SignatureMismatch {
                    error: error.into(),
                    cids: peer_info.cids.clone(),
                    peer_id: peer_info
                        .public_key
                        .to_peer_id()
                        .expect("cannot happen, was verified before")
                        .to_string(),
                })?;
        }
        Ok(())
    }

    /// For each peer, merge previous and current CID multisets by determining the largest set.
    ///
    /// This code uses an invariant: peer's multiset of produced CIDs is always a superset of
    /// previous invocation's multiset:
    ///
    /// A_0 ⊆ A_1 ⊆ ... ⊆ A_n.
    ///
    /// So, the largest multiset is selected as the result of merging, the invariant is checked,
    /// and a error is returned if it is violated.
    ///
    /// If the multisets are of same size, they have to be equal.
    // TODO enforce merging only verified sets
    // The result is same regardless argument order, so "prevous/current" terminology
    // is not used deliberately.
    pub fn merge(mut self, other: Self) -> Result<SignatureStore, DataVerifierError> {
        use std::collections::hash_map::Entry::*;

        for (other_peer_pk, mut other_info) in other.grouped_cids {
            let our_info = self.grouped_cids.entry(other_peer_pk);
            match our_info {
                Occupied(mut our_info_ent) => {
                    debug_assert_eq!(other_info.public_key, our_info_ent.get().public_key);

                    if our_info_ent.get().cids.len() < other_info.cids.len() {
                        // the merged map contains the largest set for each peer_id
                        //
                        // this code assumes that a peer only adds CIDs to its set, so CID multisets
                        //   are growing-only; but it is additionally checked below
                        // so, we get a largest set as merged one
                        std::mem::swap(our_info_ent.get_mut(), &mut other_info);
                    }
                    // nb: if length are equal, sets should be equal, and any of them
                    // should be used; if they are not equal, check_cid_multiset_consistency
                    // will detect it.

                    let larger_info = our_info_ent.get();
                    let smaller_info = &other_info;
                    check_cid_multiset_invariant(larger_info, smaller_info)?;
                }
                Vacant(ent) => {
                    ent.insert(other_info);
                }
            }
        }
        let mut store = SignatureStore::new();
        for peer_info in self.grouped_cids.into_values() {
            store.put(peer_info.public_key.clone(), peer_info.signature.clone())
        }
        Ok(store)
    }
}

fn collect_peers_cids_from_trace<'data>(
    trace: &'data ExecutionTrace,
    cid_info: &'data CidInfo,
    grouped_cids: &mut HashMap<Box<str>, PeerInfo<'data>>,
) -> Result<(), DataVerifierError> {
    for elt in trace {
        match elt {
            ExecutedState::Call(ref call) => {
                let cid = call.get_cid();
                if let Some(cid) = cid {
                    // TODO refactor
                    let service_result = cid_info
                        .service_result_store
                        .get(cid)
                        .expect(CANNOT_HAPPEN_IN_VERIFIED_CID_STORE);
                    let tetraplet = cid_info
                        .tetraplet_store
                        .get(&service_result.tetraplet_cid)
                        .expect(CANNOT_HAPPEN_IN_VERIFIED_CID_STORE);

                    let peer_pk = tetraplet.peer_pk.as_str();
                    try_push_cid(grouped_cids, peer_pk, cid)?;
                }
            }
            ExecutedState::Canon(CanonResult::Executed(ref cid)) => {
                // TODO refactor
                let canon_result = cid_info
                    .canon_result_store
                    .get(cid)
                    .expect(CANNOT_HAPPEN_IN_VERIFIED_CID_STORE);
                let tetraplet = cid_info
                    .tetraplet_store
                    .get(&canon_result.tetraplet)
                    .expect(CANNOT_HAPPEN_IN_VERIFIED_CID_STORE);

                let peer_pk = tetraplet.peer_pk.as_str();
                try_push_cid(grouped_cids, peer_pk, cid)?;
            }
            _ => {}
        };
    }
    Ok(())
}

fn try_push_cid<T>(
    grouped_cids: &mut HashMap<Box<str>, PeerInfo<'_>>,
    peer_pk: &str,
    cid: &CID<T>,
) -> Result<(), DataVerifierError> {
    match grouped_cids.get_mut(peer_pk) {
        Some(peer_info) => {
            peer_info.cids.push(cid.get_inner());
            Ok(())
        }
        None => Err(DataVerifierError::PeerIdNotFound(peer_pk.into())),
    }
}

/// Safety check for malicious peer that returns inconsistent CID multisets,
/// i.e. non-increasing multisets.
fn check_cid_multiset_invariant(
    larger_pair: &PeerInfo<'_>,
    smaller_pair: &PeerInfo<'_>,
) -> Result<(), DataVerifierError> {
    let larger_cids = &larger_pair.cids;
    let smaller_cids = &smaller_pair.cids;

    let larger_count_map = to_count_map(larger_cids);
    let smaller_count_map = to_count_map(smaller_cids);

    if is_multisubset(larger_count_map, smaller_count_map) {
        Ok(())
    } else {
        let peer_id = smaller_pair
            .public_key
            .to_peer_id()
            .expect("cannot happen, was verified before")
            .to_string();
        Err(DataVerifierError::MergeMismatch {
            peer_id,
            larger_cids: larger_cids.clone(),
            smaller_cids: smaller_cids.clone(),
        })
    }
}

fn to_count_map(cids: &Vec<Rc<CidRef>>) -> HashMap<&str, usize> {
    let mut count_map = HashMap::<_, usize>::new();
    for cid in cids {
        // the counter can't overflow, the memory will overflow first
        *count_map.entry(&**cid).or_default() += 1;
    }
    count_map
}

fn is_multisubset(
    larger_count_set: HashMap<&str, usize>,
    smaller_count_set: HashMap<&str, usize>,
) -> bool {
    for (cid, &smaller_count) in &smaller_count_set {
        debug_assert!(smaller_count > 0);

        let larger_count = larger_count_set.get(cid).cloned().unwrap_or_default();
        if larger_count < smaller_count {
            return false;
        }
    }
    true
}

struct PeerInfo<'data> {
    /// A peer's public key.
    public_key: &'data PublicKey,
    /// A peer's signature.
    signature: &'data Signature,
    /// Sorted vector of CIDs that belong to the peer.
    cids: Vec<Rc<CidRef>>,
}

impl<'data> PeerInfo<'data> {
    fn new(public_key: &'data PublicKey, signature: &'data Signature) -> Self {
        Self {
            public_key,
            signature,
            cids: vec![],
        }
    }
}