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
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

// FIXME: What's the proper way to express: 1) Proof not available;
// FIXME: 2) What if Intermediate Delta Root is MERKLE_NULL_NODE.
// TODO: Maybe create a new class for special situation when
// TODO: a full node does not have full state proof, but it
// TODO: could provide a shortcut proof with snapshot_proof
// TODO: at intermediate_epoch_id with delta_proof.
#[derive(Clone, Debug, Default, PartialEq, RlpEncodable, RlpDecodable)]
pub struct StateProof {
    pub delta_proof: Option<TrieProof>,
    pub intermediate_proof: Option<TrieProof>,
    pub snapshot_proof: Option<TrieProof>,
}

impl StateProof {
    pub fn with_delta(
        &mut self, maybe_delta_proof: Option<TrieProof>,
    ) -> &mut Self {
        self.delta_proof = maybe_delta_proof;
        self
    }

    pub fn with_intermediate(
        &mut self, maybe_intermediate_proof: Option<TrieProof>,
    ) -> &mut Self {
        self.intermediate_proof = maybe_intermediate_proof;
        self
    }

    pub fn with_snapshot(
        &mut self, maybe_snapshot_proof: Option<TrieProof>,
    ) -> &mut Self {
        self.snapshot_proof = maybe_snapshot_proof;
        self
    }

    pub fn is_valid_kv(
        &self, key: &Vec<u8>, value: Option<&[u8]>, root: StateRoot,
        maybe_intermediate_padding: Option<DeltaMptKeyPadding>,
    ) -> bool {
        // Something is wrong when intermediate_proof exists but we are not able
        // to get a intermediate padding.
        if self.intermediate_proof.is_some()
            && maybe_intermediate_padding.is_none()
        {
            return false;
        }

        let delta_root = &root.delta_root;
        let intermediate_root = &root.intermediate_delta_root;
        let snapshot_root = &root.snapshot_root;

        let delta_mpt_padding = StorageKeyWithSpace::delta_mpt_padding(
            &snapshot_root,
            &intermediate_root,
        );

        let storage_key =
            match StorageKeyWithSpace::from_key_bytes::<CheckInput>(&key) {
                Ok(k) => k,
                Err(e) => {
                    warn!("Checking proof with invalid key: {:?}", e);
                    return false;
                }
            };

        let delta_mpt_key =
            storage_key.to_delta_mpt_key_bytes(&delta_mpt_padding);
        let maybe_intermediate_mpt_key = maybe_intermediate_padding
            .as_ref()
            .map(|p| storage_key.to_delta_mpt_key_bytes(p));

        let tombstone_value = MptValue::<Box<[u8]>>::TombStone.unwrap();
        let delta_value = if value.is_some() {
            // Actual value.
            value.clone()
        } else {
            // Tombstone value.
            Some(&*tombstone_value)
        };

        // The delta proof must prove the key-value or key non-existence.
        match &self.delta_proof {
            Some(proof) => {
                // Existence proof.
                if proof.is_valid_kv(&delta_mpt_key, delta_value, delta_root) {
                    return true;
                }
                // Non-existence proof.
                if !proof.is_valid_kv(&delta_mpt_key, None, delta_root) {
                    return false;
                }
            }
            None => {
                // When delta trie exists, the proof can't be empty.
                if delta_root.ne(&MERKLE_NULL_NODE) {
                    return false;
                }
            }
        }

        // Now check intermediate_proof since it's required. Same logic applies.
        match &self.intermediate_proof {
            Some(proof) => {
                if proof.is_valid_kv(
                    // It's guaranteed that
                    // maybe_intermediate_mpt_key.is_some().
                    maybe_intermediate_mpt_key.as_ref().unwrap(),
                    delta_value,
                    intermediate_root,
                ) {
                    return true;
                }
                if !proof.is_valid_kv(
                    maybe_intermediate_mpt_key.as_ref().unwrap(),
                    None,
                    intermediate_root,
                ) {
                    return false;
                }
            }
            None => {
                // When intermediate trie exists, the proof can't be empty.
                if intermediate_root.ne(&MERKLE_NULL_NODE) {
                    return false;
                }
            }
        }

        // At last, check snapshot
        match &self.snapshot_proof {
            None => false,
            Some(proof) => proof.is_valid_kv(key, value, snapshot_root),
        }
    }
}

use crate::impls::merkle_patricia_trie::TrieProof;
use primitives::{
    CheckInput, DeltaMptKeyPadding, MptValue, StateRoot, StorageKeyWithSpace,
    MERKLE_NULL_NODE,
};
use rlp_derive::{RlpDecodable, RlpEncodable};