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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use std::convert::TryFrom;

use jsonrpc_lite::JsonRpc;
use thiserror::Error;

use casper_execution_engine::{
    core, core::ValidationError, storage::trie::merkle_proof::TrieMerkleProof,
};
use casper_hashing::Digest;
use casper_node::{
    rpcs::{
        chain::{BlockIdentifier, EraSummary, GetEraInfoResult},
        state::GlobalStateIdentifier,
    },
    types::{
        json_compatibility, Block, BlockHeader, BlockValidationError, JsonBlock, JsonBlockHeader,
    },
};
use casper_types::{bytesrepr, Key, StoredValue, U512};

const GET_ITEM_RESULT_BALANCE_VALUE: &str = "balance_value";
const GET_ITEM_RESULT_STORED_VALUE: &str = "stored_value";
const GET_ITEM_RESULT_MERKLE_PROOF: &str = "merkle_proof";
const QUERY_GLOBAL_STATE_BLOCK_HEADER: &str = "block_header";

/// Error that can be returned when validating a block returned from a JSON-RPC method.
#[derive(Error, Debug)]
pub enum ValidateResponseError {
    /// Failed to marshall value.
    #[error("Failed to marshall value {0}")]
    BytesRepr(bytesrepr::Error),

    /// Error from serde.
    #[error(transparent)]
    Serde(#[from] serde_json::Error),

    /// Failed to parse JSON.
    #[error("validate_response failed to parse")]
    ValidateResponseFailedToParse,

    /// Failed to validate Merkle proofs.
    #[error(transparent)]
    ValidationError(#[from] ValidationError),

    /// Failed to validate a block.
    #[error("Block validation error {0}")]
    BlockValidationError(BlockValidationError),

    /// Serialized value not contained in proof.
    #[error("serialized value not contained in proof")]
    SerializedValueNotContainedInProof,

    /// No block in response.
    #[error("no block in response")]
    NoBlockInResponse,

    /// Block hash requested does not correspond to response.
    #[error("block hash requested does not correspond to response")]
    UnexpectedBlockHash,

    /// Block height was not as requested.
    #[error("block height was not as requested")]
    UnexpectedBlockHeight,

    /// An invalid combination of state identifier and block header response
    #[error("Invalid combination of state identifier and block header in response")]
    InvalidGlobalStateResponse,
}

impl From<bytesrepr::Error> for ValidateResponseError {
    fn from(e: bytesrepr::Error) -> Self {
        ValidateResponseError::BytesRepr(e)
    }
}

impl From<BlockValidationError> for ValidateResponseError {
    fn from(e: BlockValidationError) -> Self {
        ValidateResponseError::BlockValidationError(e)
    }
}

pub(crate) fn validate_get_era_info_response(
    response: &JsonRpc,
) -> Result<(), ValidateResponseError> {
    let value = response
        .get_result()
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;

    let result: GetEraInfoResult = serde_json::from_value(value.to_owned())?;

    match result.era_summary {
        Some(EraSummary {
            state_root_hash,
            era_id,
            merkle_proof,
            stored_value,
            ..
        }) => {
            let proof_bytes = hex::decode(merkle_proof)
                .map_err(|_| ValidateResponseError::ValidateResponseFailedToParse)?;
            let proofs: Vec<TrieMerkleProof<Key, StoredValue>> =
                bytesrepr::deserialize(proof_bytes)?;
            let key = Key::EraInfo(era_id);
            let path = &[];

            let proof_value = match stored_value {
                json_compatibility::StoredValue::EraInfo(era_info) => {
                    StoredValue::EraInfo(era_info)
                }
                _ => return Err(ValidateResponseError::ValidateResponseFailedToParse),
            };

            core::validate_query_proof(
                &state_root_hash.to_owned(),
                &proofs,
                &key,
                path,
                &proof_value,
            )
            .map_err(Into::into)
        }
        None => Ok(()),
    }
}

pub(crate) fn validate_query_response(
    response: &JsonRpc,
    state_root_hash: &Digest,
    key: &Key,
    path: &[String],
) -> Result<(), ValidateResponseError> {
    let value = response
        .get_result()
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;

    let object = value
        .as_object()
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;

    let proofs: Vec<TrieMerkleProof<Key, StoredValue>> = {
        let proof = object
            .get(GET_ITEM_RESULT_MERKLE_PROOF)
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        let proof_str = proof
            .as_str()
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        let proof_bytes = hex::decode(proof_str)
            .map_err(|_| ValidateResponseError::ValidateResponseFailedToParse)?;
        bytesrepr::deserialize(proof_bytes)?
    };

    let proof_value: &StoredValue = {
        let last_proof = proofs
            .last()
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        last_proof.value()
    };

    // Here we need to validate that JSON `stored_value` is contained in the proof.
    //
    // Possible to deserialize that field into a `StoredValue` and pass below to
    // `validate_query_proof` instead of using this approach?
    {
        let value: json_compatibility::StoredValue = {
            let value = object
                .get(GET_ITEM_RESULT_STORED_VALUE)
                .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
            serde_json::from_value(value.to_owned())?
        };
        match json_compatibility::StoredValue::try_from(proof_value.clone()) {
            Ok(json_proof_value) if json_proof_value == value => (),
            _ => return Err(ValidateResponseError::SerializedValueNotContainedInProof),
        }
    }

    core::validate_query_proof(&state_root_hash.to_owned(), &proofs, key, path, proof_value)
        .map_err(Into::into)
}

pub(crate) fn validate_query_global_state(
    response: &JsonRpc,
    state_identifier: GlobalStateIdentifier,
    key: &Key,
    path: &[String],
) -> Result<(), ValidateResponseError> {
    let value = response
        .get_result()
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;

    let object = value
        .as_object()
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;

    let proofs: Vec<TrieMerkleProof<Key, StoredValue>> = {
        let proof = object
            .get(GET_ITEM_RESULT_MERKLE_PROOF)
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        let proof_str = proof
            .as_str()
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        let proof_bytes = hex::decode(proof_str)
            .map_err(|_| ValidateResponseError::ValidateResponseFailedToParse)?;
        bytesrepr::deserialize(proof_bytes)?
    };

    let proof_value: &StoredValue = {
        let last_proof = proofs
            .last()
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        last_proof.value()
    };

    let json_block_header_value = object
        .get(QUERY_GLOBAL_STATE_BLOCK_HEADER)
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
    let maybe_json_block_header: Option<JsonBlockHeader> =
        serde_json::from_value(json_block_header_value.to_owned())?;

    let state_root_hash = match (state_identifier, maybe_json_block_header) {
        (GlobalStateIdentifier::BlockHash(_), None)
        | (GlobalStateIdentifier::StateRootHash(_), Some(_)) => {
            return Err(ValidateResponseError::InvalidGlobalStateResponse);
        }
        (GlobalStateIdentifier::BlockHash(_), Some(json_header)) => {
            let block_header = BlockHeader::from(json_header);
            *block_header.state_root_hash()
        }
        (GlobalStateIdentifier::StateRootHash(hash), None) => hash,
    };

    core::validate_query_proof(&state_root_hash.to_owned(), &proofs, key, path, proof_value)
        .map_err(Into::into)
}

pub(crate) fn validate_get_balance_response(
    response: &JsonRpc,
    state_root_hash: &Digest,
    key: &Key,
) -> Result<(), ValidateResponseError> {
    let value = response
        .get_result()
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;

    let object = value
        .as_object()
        .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;

    let balance_proof: TrieMerkleProof<Key, StoredValue> = {
        let proof = object
            .get(GET_ITEM_RESULT_MERKLE_PROOF)
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        let proof_str = proof
            .as_str()
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        let proof_bytes = hex::decode(proof_str)
            .map_err(|_| ValidateResponseError::ValidateResponseFailedToParse)?;
        bytesrepr::deserialize(proof_bytes)?
    };

    let balance: U512 = {
        let value = object
            .get(GET_ITEM_RESULT_BALANCE_VALUE)
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        let value_str = value
            .as_str()
            .ok_or(ValidateResponseError::ValidateResponseFailedToParse)?;
        U512::from_dec_str(value_str)
            .map_err(|_| ValidateResponseError::ValidateResponseFailedToParse)?
    };

    core::validate_balance_proof(&state_root_hash.to_owned(), &balance_proof, *key, &balance)
        .map_err(Into::into)
}

pub(crate) fn validate_get_block_response(
    response: &JsonRpc,
    maybe_block_identifier: &Option<BlockIdentifier>,
) -> Result<(), ValidateResponseError> {
    let maybe_result = response.get_result();
    let json_block_value = maybe_result
        .and_then(|value| value.get("block"))
        .ok_or(ValidateResponseError::NoBlockInResponse)?;
    let maybe_json_block: Option<JsonBlock> = serde_json::from_value(json_block_value.to_owned())?;
    let json_block = if let Some(json_block) = maybe_json_block {
        json_block
    } else {
        return Ok(());
    };
    let block = Block::from(json_block);
    block.verify()?;
    match maybe_block_identifier {
        Some(BlockIdentifier::Hash(block_hash)) => {
            if block_hash != block.hash() {
                return Err(ValidateResponseError::UnexpectedBlockHash);
            }
        }
        Some(BlockIdentifier::Height(height)) => {
            // More is necessary here to mitigate a MITM attack
            if height != &block.height() {
                return Err(ValidateResponseError::UnexpectedBlockHeight);
            }
        }
        // More is necessary here to mitigate a MITM attack. In this case we would want to validate
        // `block.proofs()` to make sure that 1/3 of the validator weight signed the block, and we
        // would have to know the latest validators through some trustworthy means
        None => (),
    }
    Ok(())
}