fuel_core_executor/refs/
contract.rs

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
use core::fmt;
use fuel_core_storage::{
    not_found,
    tables::ContractsLatestUtxo,
    Error as StorageError,
    Mappable,
    MerkleRoot,
    StorageAsRef,
    StorageInspect,
};
use fuel_core_types::{
    fuel_crypto::Hasher,
    fuel_types::{
        Bytes32,
        ContractId,
    },
    services::executor::{
        Error as ExecutorError,
        Result as ExecutorResult,
    },
};

#[cfg(feature = "std")]
use std::borrow::Cow;

#[cfg(not(feature = "std"))]
use alloc::borrow::Cow;

#[cfg(feature = "smt")]
pub use smt::*;

#[cfg(not(feature = "smt"))]
pub use not_smt::*;

/// The wrapper around `contract_id` to simplify work with `Contract` in the database.
pub struct ContractRef<Database> {
    database: Database,
    contract_id: ContractId,
}

impl<Database> ContractRef<Database> {
    pub fn new(database: Database, contract_id: ContractId) -> Self {
        Self {
            database,
            contract_id,
        }
    }

    pub fn contract_id(&self) -> &ContractId {
        &self.contract_id
    }

    pub fn database(&self) -> &Database {
        &self.database
    }

    pub fn database_mut(&mut self) -> &mut Database {
        &mut self.database
    }
}

impl<Database> ContractRef<Database>
where
    Database: StorageInspect<ContractsLatestUtxo>,
    ExecutorError: From<Database::Error>,
{
    pub fn utxo(
        &self,
    ) -> Result<
        Option<Cow<'_, <ContractsLatestUtxo as Mappable>::OwnedValue>>,
        Database::Error,
    > {
        self.database.storage().get(&self.contract_id)
    }
}

impl<Database> ContractRef<Database>
where
    Database: StorageInspect<ContractsLatestUtxo>,
    ExecutorError: From<Database::Error>,
{
    pub fn validated_utxo(
        &self,
        utxo_validation: bool,
    ) -> ExecutorResult<<ContractsLatestUtxo as Mappable>::OwnedValue> {
        let maybe_utxo_id = self.utxo()?.map(|utxo| utxo.into_owned());
        let expected_utxo_id = if utxo_validation {
            maybe_utxo_id.ok_or(ExecutorError::ContractUtxoMissing(self.contract_id))?
        } else {
            maybe_utxo_id.unwrap_or_default()
        };
        Ok(expected_utxo_id)
    }
}

#[cfg(feature = "smt")]
mod smt {
    use super::*;
    use fuel_core_storage::{
        tables::{
            ContractsAssets,
            ContractsState,
        },
        MerkleRootStorage,
    };

    impl<Database> ContractRef<Database>
    where
        Database: ContractStorageTrait,
    {
        pub fn balance_root(
            &self,
        ) -> Result<Bytes32, <Database as StorageInspect<ContractsAssets>>::Error>
        {
            <Database as MerkleRootStorage<ContractId, ContractsAssets>>::root(
                &self.database,
                &self.contract_id,
            )
            .map(Into::into)
        }

        pub fn state_root(
            &self,
        ) -> Result<Bytes32, <Database as StorageInspect<ContractsState>>::Error>
        {
            <Database as MerkleRootStorage<ContractId, ContractsState>>::root(
                &self.database,
                &self.contract_id,
            )
            .map(Into::into)
        }
    }

    pub trait ContractStorageTrait:
        StorageInspect<ContractsLatestUtxo, Error = Self::InnerError>
        + MerkleRootStorage<ContractId, ContractsState, Error = Self::InnerError>
        + MerkleRootStorage<ContractId, ContractsAssets, Error = Self::InnerError>
    {
        type InnerError: fmt::Debug + fmt::Display + Send + Sync + 'static;
    }

    impl<D, E> ContractStorageTrait for D
    where
        D: StorageInspect<ContractsLatestUtxo, Error = E>
            + MerkleRootStorage<ContractId, ContractsState, Error = E>
            + MerkleRootStorage<ContractId, ContractsAssets, Error = E>,
        E: fmt::Debug + fmt::Display + Send + Sync + 'static,
    {
        type InnerError = E;
    }
}

#[cfg(not(feature = "smt"))]
mod not_smt {
    use super::*;
    use fuel_core_storage::Error as StorageError;

    impl<Database> ContractRef<Database> {
        pub fn balance_root(&self) -> Result<Bytes32, StorageError> {
            Ok(Bytes32::zeroed())
        }
    }

    impl<Database> ContractRef<Database> {
        pub fn state_root(&self) -> Result<Bytes32, StorageError> {
            Ok(Bytes32::zeroed())
        }
    }

    pub trait ContractStorageTrait:
        StorageInspect<ContractsLatestUtxo, Error = Self::InnerError>
    {
        type InnerError: fmt::Debug + fmt::Display + Send + Sync + 'static;
    }

    impl<D, E> ContractStorageTrait for D
    where
        D: StorageInspect<ContractsLatestUtxo, Error = E>,
        E: fmt::Debug + fmt::Display + Send + Sync + 'static,
    {
        type InnerError = E;
    }
}

impl<'a, Database> ContractRef<&'a Database>
where
    &'a Database: ContractStorageTrait<InnerError = StorageError>,
{
    /// Returns the state root of the whole contract.
    pub fn root(&self) -> anyhow::Result<MerkleRoot> {
        let contract_id = *self.contract_id();
        let utxo = *self
            .database()
            .storage::<ContractsLatestUtxo>()
            .get(&contract_id)?
            .ok_or(not_found!(ContractsLatestUtxo))?
            .into_owned()
            .utxo_id();

        let state_root = self.state_root()?;

        let balance_root = self.balance_root()?;

        let contract_hash = *Hasher::default()
            // `ContractId` already is based on contract's code and salt so we don't need it.
            .chain(contract_id.as_ref())
            .chain(utxo.tx_id().as_ref())
            .chain(utxo.output_index().to_be_bytes())
            .chain(state_root.as_slice())
            .chain(balance_root.as_slice())
            .finalize();

        Ok(contract_hash)
    }
}