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
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![allow(clippy::unit_arg)]

use crate::{
    account_address::AccountAddress,
    account_config::get_account_resource_or_default,
    ledger_info::LedgerInfo,
    proof::{verify_account_state, AccountStateProof},
    transaction::Version,
};
use canonical_serialization::{SimpleDeserializer, SimpleSerializer};
use crypto::{
    hash::{AccountStateBlobHasher, CryptoHash, CryptoHasher},
    HashValue,
};
use failure::prelude::*;
use proptest_derive::Arbitrary;
use proto_conv::{FromProto, IntoProto};
use std::{collections::BTreeMap, convert::TryFrom, fmt};

#[derive(Arbitrary, Clone, Eq, PartialEq, FromProto, IntoProto)]
#[ProtoType(crate::proto::account_state_blob::AccountStateBlob)]
pub struct AccountStateBlob {
    blob: Vec<u8>,
}

impl fmt::Debug for AccountStateBlob {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let decoded = get_account_resource_or_default(&Some(self.clone()))
            .map(|resource| format!("{:#?}", resource))
            .unwrap_or_else(|_| String::from("[fail]"));

        write!(
            f,
            "AccountStateBlob {{ \n \
             Raw: 0x{} \n \
             Decoded: {} \n \
             }}",
            hex::encode(&self.blob),
            decoded,
        )
    }
}

impl AsRef<[u8]> for AccountStateBlob {
    fn as_ref(&self) -> &[u8] {
        &self.blob
    }
}

impl From<AccountStateBlob> for Vec<u8> {
    fn from(account_state_blob: AccountStateBlob) -> Vec<u8> {
        account_state_blob.blob
    }
}

impl From<Vec<u8>> for AccountStateBlob {
    fn from(blob: Vec<u8>) -> AccountStateBlob {
        AccountStateBlob { blob }
    }
}

impl TryFrom<&BTreeMap<Vec<u8>, Vec<u8>>> for AccountStateBlob {
    type Error = failure::Error;

    fn try_from(map: &BTreeMap<Vec<u8>, Vec<u8>>) -> Result<Self> {
        Ok(Self {
            blob: SimpleSerializer::serialize(map)?,
        })
    }
}

impl TryFrom<&AccountStateBlob> for BTreeMap<Vec<u8>, Vec<u8>> {
    type Error = failure::Error;

    fn try_from(account_state_blob: &AccountStateBlob) -> Result<Self> {
        SimpleDeserializer::deserialize(&account_state_blob.blob)
    }
}

impl CryptoHash for AccountStateBlob {
    type Hasher = AccountStateBlobHasher;

    fn hash(&self) -> HashValue {
        let mut hasher = Self::Hasher::default();
        hasher.write(&self.blob);
        hasher.finish()
    }
}

#[derive(Arbitrary, Clone, Debug, Eq, PartialEq)]
pub struct AccountStateWithProof {
    /// The transaction version at which this account state is seen.
    pub version: Version,
    /// Blob value representing the account state. If this field is not set, it
    /// means the account does not exist.
    pub blob: Option<AccountStateBlob>,
    /// The proof the client can use to authenticate the value.
    pub proof: AccountStateProof,
}

impl AccountStateWithProof {
    /// Constructor.
    pub fn new(version: Version, blob: Option<AccountStateBlob>, proof: AccountStateProof) -> Self {
        Self {
            version,
            blob,
            proof,
        }
    }

    /// Verifies the the account state blob with the proof, both carried by `self`.
    ///
    /// Two things are ensured if no error is raised:
    ///   1. This account state exists in the ledger represented by `ledger_info`.
    ///   2. It belongs to account of `address` and is seen at the time the transaction at version
    /// `state_version` is just committed. To make sure this is the latest state, pass in
    /// `ledger_info.version()` as `state_version`.
    pub fn verify(
        &self,
        ledger_info: &LedgerInfo,
        version: Version,
        address: AccountAddress,
    ) -> Result<()> {
        ensure!(
            self.version == version,
            "State version ({}) is not expected ({}).",
            self.version,
            version,
        );

        verify_account_state(
            ledger_info,
            version,
            address.hash(),
            &self.blob,
            &self.proof,
        )
    }
}

impl FromProto for AccountStateWithProof {
    type ProtoType = crate::proto::account_state_blob::AccountStateWithProof;

    fn from_proto(mut object: Self::ProtoType) -> Result<Self> {
        Ok(AccountStateWithProof {
            version: object.get_version(),
            blob: object
                .blob
                .take()
                .map(AccountStateBlob::from_proto)
                .transpose()?,
            proof: AccountStateProof::from_proto(object.take_proof())?,
        })
    }
}

impl IntoProto for AccountStateWithProof {
    type ProtoType = crate::proto::account_state_blob::AccountStateWithProof;

    fn into_proto(self) -> Self::ProtoType {
        let mut out = Self::ProtoType::new();
        out.set_version(self.version);
        if let Some(blob) = self.blob {
            out.set_blob(blob.into_proto());
        }
        out.set_proof(self.proof.into_proto());
        out
    }
}

#[cfg(test)]
mod account_state_blob_test;