casper_types/system/
caller.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
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
310
311
312
313
pub mod call_stack_elements;

use alloc::{collections::BTreeMap, vec::Vec};

use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::FromPrimitive;

use crate::{
    account::AccountHash,
    bytesrepr::{self, FromBytes, ToBytes, U8_SERIALIZED_LENGTH},
    package::PackageHash,
    CLType, CLTyped, CLValue, CLValueError, EntityAddr, HashAddr,
};

use crate::{
    bytesrepr::Error,
    contracts::{ContractHash, ContractPackageHash},
};
pub use call_stack_elements::CallStackElement;

/// Tag representing variants of CallerTag for purposes of serialization.
#[derive(FromPrimitive, ToPrimitive)]
#[repr(u8)]
pub enum CallerTag {
    /// Initiator tag.
    Initiator = 0,
    /// Entity tag.
    Entity,
    /// Smart contract tag.
    SmartContract,
}

const ACCOUNT: u8 = 0;
const PACKAGE: u8 = 1;
const CONTRACT_PACKAGE: u8 = 2;
const ENTITY: u8 = 3;
const CONTRACT: u8 = 4;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallerInfo {
    kind: u8,
    fields: BTreeMap<u8, CLValue>,
}

impl CLTyped for CallerInfo {
    fn cl_type() -> CLType {
        CLType::Any
    }
}

impl CallerInfo {
    pub fn kind(&self) -> u8 {
        self.kind
    }

    pub fn get_field_by_index(&self, index: u8) -> Option<&CLValue> {
        self.fields.get(&index)
    }
}

impl ToBytes for CallerInfo {
    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
        let mut result = bytesrepr::allocate_buffer(self)?;
        result.append(&mut self.kind.to_bytes()?);
        result.append(&mut self.fields.to_bytes()?);
        Ok(result)
    }

    fn serialized_length(&self) -> usize {
        U8_SERIALIZED_LENGTH + self.fields.serialized_length()
    }
}

impl FromBytes for CallerInfo {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
        let (kind, remainder) = u8::from_bytes(bytes)?;
        let (fields, remainder) = BTreeMap::from_bytes(remainder)?;
        Ok((CallerInfo { kind, fields }, remainder))
    }
}

impl TryFrom<Caller> for CallerInfo {
    type Error = CLValueError;

    fn try_from(value: Caller) -> Result<Self, Self::Error> {
        match value {
            Caller::Initiator { account_hash } => {
                let kind = ACCOUNT;

                let mut ret = BTreeMap::new();
                ret.insert(ACCOUNT, CLValue::from_t(Some(account_hash))?);
                ret.insert(PACKAGE, CLValue::from_t(Option::<PackageHash>::None)?);
                ret.insert(
                    CONTRACT_PACKAGE,
                    CLValue::from_t(Option::<ContractPackageHash>::None)?,
                );
                ret.insert(ENTITY, CLValue::from_t(Option::<EntityAddr>::None)?);
                ret.insert(CONTRACT, CLValue::from_t(Option::<ContractHash>::None)?);
                Ok(CallerInfo { kind, fields: ret })
            }
            Caller::Entity {
                package_hash,
                entity_addr,
            } => {
                let kind = ENTITY;

                let mut ret = BTreeMap::new();
                ret.insert(ACCOUNT, CLValue::from_t(Option::<AccountHash>::None)?);
                ret.insert(PACKAGE, CLValue::from_t(Some(package_hash))?);
                ret.insert(
                    CONTRACT_PACKAGE,
                    CLValue::from_t(Option::<ContractPackageHash>::None)?,
                );
                ret.insert(ENTITY, CLValue::from_t(Some(entity_addr))?);
                ret.insert(CONTRACT, CLValue::from_t(Option::<ContractHash>::None)?);
                Ok(CallerInfo { kind, fields: ret })
            }
            Caller::SmartContract {
                contract_package_hash,
                contract_hash,
            } => {
                let kind = CONTRACT;

                let mut ret = BTreeMap::new();
                ret.insert(ACCOUNT, CLValue::from_t(Option::<AccountHash>::None)?);
                ret.insert(PACKAGE, CLValue::from_t(Option::<PackageHash>::None)?);
                ret.insert(
                    CONTRACT_PACKAGE,
                    CLValue::from_t(Some(contract_package_hash))?,
                );

                ret.insert(ENTITY, CLValue::from_t(Option::<EntityAddr>::None)?);
                ret.insert(CONTRACT, CLValue::from_t(Some(contract_hash))?);
                Ok(CallerInfo { kind, fields: ret })
            }
        }
    }
}

/// Identity of a calling entity.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Caller {
    /// Initiator (calling account)
    Initiator {
        /// The account hash of the caller
        account_hash: AccountHash,
    },
    /// Entity (smart contract / system contract)
    Entity {
        /// The package hash
        package_hash: PackageHash,
        /// The entity addr.
        entity_addr: EntityAddr,
    },
    SmartContract {
        /// The contract package hash.
        contract_package_hash: ContractPackageHash,
        /// The contract hash.
        contract_hash: ContractHash,
    },
}

impl Caller {
    /// Creates a [`Caller::Initiator`]. This represents a call into session code, and
    /// should only ever happen once in a call stack.
    pub fn initiator(account_hash: AccountHash) -> Self {
        Caller::Initiator { account_hash }
    }

    /// Creates a [`'Caller::Entity`]. This represents a call into a contract with
    /// `EntryPointType::Called`.
    pub fn entity(package_hash: PackageHash, entity_addr: EntityAddr) -> Self {
        Caller::Entity {
            package_hash,
            entity_addr,
        }
    }

    pub fn smart_contract(
        contract_package_hash: ContractPackageHash,
        contract_hash: ContractHash,
    ) -> Self {
        Caller::SmartContract {
            contract_package_hash,
            contract_hash,
        }
    }

    /// Gets the tag from self.
    pub fn tag(&self) -> CallerTag {
        match self {
            Caller::Initiator { .. } => CallerTag::Initiator,
            Caller::Entity { .. } => CallerTag::Entity,
            Caller::SmartContract { .. } => CallerTag::SmartContract,
        }
    }

    /// Gets the [`HashAddr`] for both stored session and stored contract variants.
    pub fn contract_hash(&self) -> Option<HashAddr> {
        match self {
            Caller::Initiator { .. } => None,
            Caller::Entity { entity_addr, .. } => Some(entity_addr.value()),
            Caller::SmartContract { contract_hash, .. } => Some(contract_hash.value()),
        }
    }
}

impl ToBytes for Caller {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut result = bytesrepr::allocate_buffer(self)?;
        result.push(self.tag() as u8);
        match self {
            Caller::Initiator { account_hash } => result.append(&mut account_hash.to_bytes()?),

            Caller::Entity {
                package_hash,
                entity_addr,
            } => {
                result.append(&mut package_hash.to_bytes()?);
                result.append(&mut entity_addr.to_bytes()?);
            }
            Caller::SmartContract {
                contract_package_hash,
                contract_hash,
            } => {
                result.append(&mut contract_package_hash.to_bytes()?);
                result.append(&mut contract_hash.to_bytes()?);
            }
        };
        Ok(result)
    }

    fn serialized_length(&self) -> usize {
        U8_SERIALIZED_LENGTH
            + match self {
                Caller::Initiator { account_hash } => account_hash.serialized_length(),
                Caller::Entity {
                    package_hash,
                    entity_addr,
                } => package_hash.serialized_length() + entity_addr.serialized_length(),
                Caller::SmartContract {
                    contract_package_hash,
                    contract_hash,
                } => contract_package_hash.serialized_length() + contract_hash.serialized_length(),
            }
    }
}

impl FromBytes for Caller {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (tag, remainder): (u8, &[u8]) = FromBytes::from_bytes(bytes)?;
        let tag = CallerTag::from_u8(tag).ok_or(bytesrepr::Error::Formatting)?;
        match tag {
            CallerTag::Initiator => {
                let (account_hash, remainder) = AccountHash::from_bytes(remainder)?;
                Ok((Caller::Initiator { account_hash }, remainder))
            }
            CallerTag::Entity => {
                let (package_hash, remainder) = PackageHash::from_bytes(remainder)?;
                let (entity_addr, remainder) = EntityAddr::from_bytes(remainder)?;
                Ok((
                    Caller::Entity {
                        package_hash,
                        entity_addr,
                    },
                    remainder,
                ))
            }
            CallerTag::SmartContract => {
                let (contract_package_hash, remainder) =
                    ContractPackageHash::from_bytes(remainder)?;
                let (contract_hash, remainder) = ContractHash::from_bytes(remainder)?;
                Ok((
                    Caller::SmartContract {
                        contract_package_hash,
                        contract_hash,
                    },
                    remainder,
                ))
            }
        }
    }
}

impl CLTyped for Caller {
    fn cl_type() -> CLType {
        CLType::Any
    }
}

impl From<&Caller> for CallStackElement {
    fn from(caller: &Caller) -> Self {
        match caller {
            Caller::Initiator { account_hash } => CallStackElement::Session {
                account_hash: *account_hash,
            },
            Caller::Entity {
                package_hash,
                entity_addr: entity_hash,
            } => CallStackElement::StoredContract {
                contract_package_hash: ContractPackageHash::new(package_hash.value()),
                contract_hash: ContractHash::new(entity_hash.value()),
            },
            Caller::SmartContract {
                contract_package_hash,
                contract_hash,
            } => CallStackElement::StoredContract {
                contract_package_hash: *contract_package_hash,
                contract_hash: *contract_hash,
            },
        }
    }
}