catbuffer_rust/
account_state_builder.rs

1/*
2 * // Copyright (c) 2016-2019, Jaguar0625, gimre, BloodyRookie, Tech Bureau, Corp.
3 * // Copyright (c) 2020-present, Jaguar0625, gimre, BloodyRookie.
4 * // All rights reserved.
5 * //
6 * // This file is part of Catapult.
7 * //
8 * // Catapult is free software: you can redistribute it and/or modify
9 * // it under the terms of the GNU Lesser General Public License as published by
10 * // the Free Software Foundation, either version 3 of the License, or
11 * // (at your option) any later version.
12 * //
13 * // Catapult is distributed in the hope that it will be useful,
14 * // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * // GNU Lesser General Public License for more details.
17 * //
18 * // You should have received a copy of the GNU Lesser General Public License
19 * // along with Catapult. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22use super::account_key_type_flags_dto::*;
23use super::account_state_format_dto::*;
24use super::account_type_dto::*;
25use super::address_dto::*;
26use super::generator_utils::*;
27use super::height_activity_buckets_builder::*;
28use super::height_dto::*;
29use super::importance_snapshot_builder::*;
30use super::key_dto::*;
31use super::mosaic_builder::*;
32use super::pinned_voting_key_builder::*;
33use super::state_header_builder::*;
34
35/// Binary layout for non-historical account state.
36#[derive(Debug, Clone)]
37pub struct AccountStateBuilder {
38    /// State header.
39    super_object: StateHeaderBuilder,
40    /// Address of account.
41    address: AddressDto,
42    /// Height at which address has been obtained.
43    address_height: HeightDto,
44    /// Public key of account.
45    public_key: KeyDto,
46    /// Height at which public key has been obtained.
47    public_key_height: HeightDto,
48    /// Type of account.
49    account_type: AccountTypeDto,
50    /// Account format.
51    format: AccountStateFormatDto,
52    /// Mask of supplemental public key flags.
53    supplemental_public_keys_mask: Vec<AccountKeyTypeFlagsDto>,
54    /// Linked account public key.
55    linked_public_key: Option<KeyDto>,
56    /// Node public key.
57    node_public_key: Option<KeyDto>,
58    /// Vrf public key.
59    vrf_public_key: Option<KeyDto>,
60    /// Voting public keys.
61    voting_public_keys: Vec<PinnedVotingKeyBuilder>,
62    /// Current importance snapshot of the account.
63    importance_snapshots: Option<ImportanceSnapshotBuilder>,
64    /// Activity buckets of the account.
65    activity_buckets: Option<HeightActivityBucketsBuilder>,
66    /// Balances of account.
67    balances: Vec<MosaicBuilder>,
68}
69
70
71impl AccountStateBuilder {
72    /// Creates an instance of AccountStateBuilder from binary payload.
73    /// payload: Byte payload to use to serialize the object.
74    /// # Returns
75    /// A AccountStateBuilder.
76    pub fn from_binary(_bytes: &[u8]) -> Self {
77        let super_object = StateHeaderBuilder::from_binary(_bytes);
78        let mut _bytes = _bytes[super_object.get_size()..].to_vec();
79        let address = AddressDto::from_binary(&_bytes); // kind:CUSTOM1
80        let mut _bytes = _bytes[address.get_size()..].to_vec();
81        let address_height = HeightDto::from_binary(&_bytes); // kind:CUSTOM1
82        let mut _bytes = _bytes[address_height.get_size()..].to_vec();
83        let public_key = KeyDto::from_binary(&_bytes); // kind:CUSTOM1
84        let mut _bytes = _bytes[public_key.get_size()..].to_vec();
85        let public_key_height = HeightDto::from_binary(&_bytes); // kind:CUSTOM1
86        let mut _bytes = _bytes[public_key_height.get_size()..].to_vec();
87        let account_type = AccountTypeDto::from_binary(&_bytes); // kind:CUSTOM2
88        let mut _bytes = _bytes[account_type.get_size()..].to_vec();
89        let format = AccountStateFormatDto::from_binary(&_bytes); // kind:CUSTOM2
90        let mut _bytes = _bytes[format.get_size()..].to_vec();
91        let supplemental_public_keys_mask = AccountKeyTypeFlagsDto::bytes_to_flags(&_bytes[..1]); // kind:FLAGS
92        let mut _bytes = (&_bytes[1..]).to_vec();
93        let buf = fixed_bytes::<1>(&_bytes);
94        let votingPublicKeysCount = u8::from_le_bytes(buf); // kind:SIZE_FIELD
95        let mut _bytes = (&_bytes[1..]).to_vec();
96        let mut linked_public_key = None;
97        if supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::LINKED) {
98            let raw_linked_public_key = KeyDto::from_binary(&_bytes);
99            _bytes = (&_bytes[raw_linked_public_key.get_size()..]).to_vec();
100            linked_public_key = Some(raw_linked_public_key); // kind:CUSTOM1
101        }
102        let mut node_public_key = None;
103        if supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::NODE) {
104            let raw_node_public_key = KeyDto::from_binary(&_bytes);
105            _bytes = (&_bytes[raw_node_public_key.get_size()..]).to_vec();
106            node_public_key = Some(raw_node_public_key); // kind:CUSTOM1
107        }
108        let mut vrf_public_key = None;
109        if supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::VRF) {
110            let raw_vrf_public_key = KeyDto::from_binary(&_bytes);
111            _bytes = (&_bytes[raw_vrf_public_key.get_size()..]).to_vec();
112            vrf_public_key = Some(raw_vrf_public_key); // kind:CUSTOM1
113        }
114        let mut voting_public_keys: Vec<PinnedVotingKeyBuilder> = vec![]; // kind:ARRAY
115        let mut _bytes = _bytes.to_vec();
116        for _ in 0..votingPublicKeysCount {
117            let item = PinnedVotingKeyBuilder::from_binary(&_bytes);
118            voting_public_keys.push(item.clone());
119            _bytes = (&_bytes[item.get_size()..]).to_vec();
120        }
121        let mut importance_snapshots = None;
122        if format == AccountStateFormatDto::HIGH_VALUE {
123            let raw_importance_snapshots = ImportanceSnapshotBuilder::from_binary(&_bytes);
124            _bytes = (&_bytes[raw_importance_snapshots.get_size()..]).to_vec();
125            importance_snapshots = Some(raw_importance_snapshots); // kind:CUSTOM1
126        }
127        let mut activity_buckets = None;
128        if format == AccountStateFormatDto::HIGH_VALUE {
129            let raw_activity_buckets = HeightActivityBucketsBuilder::from_binary(&_bytes);
130            _bytes = (&_bytes[raw_activity_buckets.get_size()..]).to_vec();
131            activity_buckets = Some(raw_activity_buckets); // kind:CUSTOM1
132        }
133        let buf = fixed_bytes::<2>(&_bytes);
134        let balancesCount = u16::from_le_bytes(buf); // kind:SIZE_FIELD
135        let mut _bytes = (&_bytes[2..]).to_vec();
136        let mut balances: Vec<MosaicBuilder> = vec![]; // kind:ARRAY
137        let mut _bytes = _bytes.to_vec();
138        for _ in 0..balancesCount {
139            let item = MosaicBuilder::from_binary(&_bytes);
140            balances.push(item.clone());
141            _bytes = (&_bytes[item.get_size()..]).to_vec();
142        }
143        AccountStateBuilder { super_object, address, address_height, public_key, public_key_height, account_type, format, supplemental_public_keys_mask, linked_public_key, node_public_key, vrf_public_key, voting_public_keys, importance_snapshots, activity_buckets, balances }
144    }
145
146    /// Gets address of account.
147    ///
148    /// # Returns
149    /// A Address of account.
150    pub fn get_address(&self) -> AddressDto {
151        self.address.clone()
152    }
153
154    /// Gets height at which address has been obtained.
155    ///
156    /// # Returns
157    /// A Height at which address has been obtained.
158    pub fn get_address_height(&self) -> HeightDto {
159        self.address_height.clone()
160    }
161
162    /// Gets public key of account.
163    ///
164    /// # Returns
165    /// A Public key of account.
166    pub fn get_public_key(&self) -> KeyDto {
167        self.public_key.clone()
168    }
169
170    /// Gets height at which public key has been obtained.
171    ///
172    /// # Returns
173    /// A Height at which public key has been obtained.
174    pub fn get_public_key_height(&self) -> HeightDto {
175        self.public_key_height.clone()
176    }
177
178    /// Gets type of account.
179    ///
180    /// # Returns
181    /// A Type of account.
182    pub fn get_account_type(&self) -> AccountTypeDto {
183        self.account_type.clone()
184    }
185
186    /// Gets account format.
187    ///
188    /// # Returns
189    /// A Account format.
190    pub fn get_format(&self) -> AccountStateFormatDto {
191        self.format.clone()
192    }
193
194    /// Gets mask of supplemental public key flags.
195    ///
196    /// # Returns
197    /// A Mask of supplemental public key flags.
198    pub fn get_supplemental_public_keys_mask(&self) -> Vec<AccountKeyTypeFlagsDto> {
199        self.supplemental_public_keys_mask.clone()
200    }
201
202    /// Gets linked account public key.
203    ///
204    /// # Returns
205    /// A Linked account public key.
206    pub fn get_linked_public_key(&self) -> Option<KeyDto> {
207        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::LINKED) {
208            panic!("supplementalPublicKeysMask is not set to LINKED.")
209        };
210        self.linked_public_key.clone()
211    }
212
213    /// Gets node public key.
214    ///
215    /// # Returns
216    /// A Node public key.
217    pub fn get_node_public_key(&self) -> Option<KeyDto> {
218        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::NODE) {
219            panic!("supplementalPublicKeysMask is not set to NODE.")
220        };
221        self.node_public_key.clone()
222    }
223
224    /// Gets vrf public key.
225    ///
226    /// # Returns
227    /// A Vrf public key.
228    pub fn get_vrf_public_key(&self) -> Option<KeyDto> {
229        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::VRF) {
230            panic!("supplementalPublicKeysMask is not set to VRF.")
231        };
232        self.vrf_public_key.clone()
233    }
234
235    /// Gets voting public keys.
236    ///
237    /// # Returns
238    /// A Voting public keys.
239    pub fn get_voting_public_keys(&self) -> Vec<PinnedVotingKeyBuilder> {
240        self.voting_public_keys.clone() // ARRAY or FILL_ARRAY
241    }
242
243    /// Gets current importance snapshot of the account.
244    ///
245    /// # Returns
246    /// A Current importance snapshot of the account.
247    pub fn get_importance_snapshots(&self) -> Option<ImportanceSnapshotBuilder> {
248        if self.format != AccountStateFormatDto::HIGH_VALUE {
249            panic!("format is not set to HIGH_VALUE.")
250        };
251        self.importance_snapshots.clone()
252    }
253
254    /// Gets activity buckets of the account.
255    ///
256    /// # Returns
257    /// A Activity buckets of the account.
258    pub fn get_activity_buckets(&self) -> Option<HeightActivityBucketsBuilder> {
259        if self.format != AccountStateFormatDto::HIGH_VALUE {
260            panic!("format is not set to HIGH_VALUE.")
261        };
262        self.activity_buckets.clone()
263    }
264
265    /// Gets balances of account.
266    ///
267    /// # Returns
268    /// A Balances of account.
269    pub fn get_balances(&self) -> Vec<MosaicBuilder> {
270        self.balances.clone() // ARRAY or FILL_ARRAY
271    }
272
273    /// Gets the size of the type.
274    ///
275    /// Returns:
276    /// A size in bytes.
277    pub fn get_size(&self) -> usize {
278        let mut size = self.super_object.get_size();
279        size += self.address.get_size(); // address;
280        size += self.address_height.get_size(); // address_height;
281        size += self.public_key.get_size(); // public_key;
282        size += self.public_key_height.get_size(); // public_key_height;
283        size += self.account_type.get_size(); // account_type;
284        size += self.format.get_size(); // format;
285        size += 1; // supplemental_public_keys_mask;
286        size += 1; // voting_public_keys_count;
287        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::LINKED) {
288            size += self.linked_public_key.as_ref().unwrap().get_size(); // linked_public_key
289        }
290        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::NODE) {
291            size += self.node_public_key.as_ref().unwrap().get_size(); // node_public_key
292        }
293        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::VRF) {
294            size += self.vrf_public_key.as_ref().unwrap().get_size(); // vrf_public_key
295        }
296        size += self.voting_public_keys.iter().map(|item| item.get_size()).sum::<usize>(); // array or fill_array;
297        if self.format == AccountStateFormatDto::HIGH_VALUE {
298            size += self.importance_snapshots.as_ref().unwrap().get_size(); // importance_snapshots
299        }
300        if self.format == AccountStateFormatDto::HIGH_VALUE {
301            size += self.activity_buckets.as_ref().unwrap().get_size(); // activity_buckets
302        }
303        size += 2; // balances_count;
304        size += self.balances.iter().map(|item| item.get_size()).sum::<usize>(); // array or fill_array;
305        size
306    }
307
308    /// Serializes self to bytes.
309    ///
310    /// # Returns
311    /// A Serialized bytes.
312    pub fn serializer(&self) -> Vec<u8> {
313        let mut buf: Vec<u8> = vec![];
314        buf.append(&mut self.super_object.serializer());
315        buf.append(&mut self.address.serializer()); // kind:CUSTOM
316        buf.append(&mut self.address_height.serializer()); // kind:CUSTOM
317        buf.append(&mut self.public_key.serializer()); // kind:CUSTOM
318        buf.append(&mut self.public_key_height.serializer()); // kind:CUSTOM
319        buf.append(&mut self.account_type.serializer()); // kind:CUSTOM
320        buf.append(&mut self.format.serializer()); // kind:CUSTOM
321        buf.append(&mut AccountKeyTypeFlagsDto::flags_to_int(self.get_supplemental_public_keys_mask()).to_le_bytes().to_vec()); // kind:FLAGS
322        buf.append(&mut (self.get_voting_public_keys().len() as u8).to_le_bytes().to_vec()); // kind:SIZE_FIELD
323        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::LINKED) {
324            buf.append(&mut self.linked_public_key.as_ref().unwrap().serializer()); // kind:CUSTOM
325        };
326        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::NODE) {
327            buf.append(&mut self.node_public_key.as_ref().unwrap().serializer()); // kind:CUSTOM
328        };
329        if self.supplemental_public_keys_mask.iter().any(|&i| i == AccountKeyTypeFlagsDto::VRF) {
330            buf.append(&mut self.vrf_public_key.as_ref().unwrap().serializer()); // kind:CUSTOM
331        };
332        for i in &self.voting_public_keys {
333            buf.append(&mut i.serializer()); // kind:ARRAY|FILL_ARRAY
334        }
335        if self.format == AccountStateFormatDto::HIGH_VALUE {
336            buf.append(&mut self.importance_snapshots.as_ref().unwrap().serializer()); // kind:CUSTOM
337        };
338        if self.format == AccountStateFormatDto::HIGH_VALUE {
339            buf.append(&mut self.activity_buckets.as_ref().unwrap().serializer()); // kind:CUSTOM
340        };
341        buf.append(&mut (self.get_balances().len() as u16).to_le_bytes().to_vec()); // kind:SIZE_FIELD
342        for i in &self.balances {
343            buf.append(&mut i.serializer()); // kind:ARRAY|FILL_ARRAY
344        }
345        buf
346    }
347}
348