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
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.

// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity Bridges Common 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 General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common.  If not, see <http://www.gnu.org/licenses/>.

//! Logic for checking Substrate storage proofs.

use hash_db::{HashDB, Hasher, EMPTY_PREFIX};
use sp_runtime::RuntimeDebug;
use sp_std::vec::Vec;
use sp_trie::{read_trie_value, LayoutV1, MemoryDB, StorageProof};

/// This struct is used to read storage values from a subset of a Merklized database. The "proof"
/// is a subset of the nodes in the Merkle structure of the database, so that it provides
/// authentication against a known Merkle root as well as the values in the database themselves.
pub struct StorageProofChecker<H>
where
    H: Hasher,
{
    root: H::Out,
    db: MemoryDB<H>,
}

impl<H> StorageProofChecker<H>
where
    H: Hasher,
{
    /// Constructs a new storage proof checker.
    ///
    /// This returns an error if the given proof is invalid with respect to the given root.
    pub fn new(root: H::Out, proof: StorageProof) -> Result<Self, Error> {
        let db = proof.into_memory_db();
        if !db.contains(&root, EMPTY_PREFIX) {
            return Err(Error::StorageRootMismatch)
        }

        let checker = StorageProofChecker { root, db };
        Ok(checker)
    }

    /// Reads a value from the available subset of storage. If the value cannot be read due to an
    /// incomplete or otherwise invalid proof, this returns an error.
    pub fn read_value(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Error> {
        // LayoutV1 or LayoutV0 is identical for proof that only read values.
        read_trie_value::<LayoutV1<H>, _>(&self.db, &self.root, key, None, None) // FIXME: can optimise with new fields
            .map_err(|_| Error::StorageValueUnavailable)
    }
}

#[derive(RuntimeDebug, PartialEq, Eq)]
pub enum Error {
    StorageRootMismatch,
    StorageValueUnavailable,
}

/// Return valid storage proof and state root.
///
/// NOTE: This should only be used for **testing**.
#[cfg(feature = "std")]
pub fn craft_valid_storage_proof() -> (sp_core::H256, StorageProof) {
    use sp_state_machine::{backend::Backend, prove_read, InMemoryBackend};
    use sp_std::vec;
    let state_version = sp_runtime::StateVersion::default();

    // construct storage proof
    let backend = <InMemoryBackend<sp_core::Blake2Hasher>>::from((
        vec![
            (None, vec![(b"key1".to_vec(), Some(b"value1".to_vec()))]),
            (None, vec![(b"key2".to_vec(), Some(b"value2".to_vec()))]),
            (None, vec![(b"key3".to_vec(), Some(b"value3".to_vec()))]),
            // Value is too big to fit in a branch node
            (None, vec![(b"key11".to_vec(), Some(vec![0u8; 32]))]),
        ],
        state_version,
    ));
    let root = backend.storage_root(sp_std::iter::empty(), state_version).0;
    let proof = StorageProof::new(
        prove_read(backend, &[&b"key1"[..], &b"key2"[..], &b"key22"[..]])
            .unwrap()
            .into_iter_nodes(),
    );

    (root, proof)
}

#[cfg(test)]
pub mod tests {
    use super::*;

    #[test]
    fn storage_proof_check() {
        let (root, proof) = craft_valid_storage_proof();

        // check proof in runtime
        let checker =
            <StorageProofChecker<sp_core::Blake2Hasher>>::new(root, proof.clone()).unwrap();
        assert_eq!(checker.read_value(b"key1"), Ok(Some(b"value1".to_vec())));
        assert_eq!(checker.read_value(b"key2"), Ok(Some(b"value2".to_vec())));
        assert_eq!(
            checker.read_value(b"key11111"),
            Err(Error::StorageValueUnavailable)
        );
        assert_eq!(checker.read_value(b"key22"), Ok(None));

        // checking proof against invalid commitment fails
        assert_eq!(
            <StorageProofChecker<sp_core::Blake2Hasher>>::new(sp_core::H256::random(), proof).err(),
            Some(Error::StorageRootMismatch)
        );
    }
}