-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathblock_state.rs
More file actions
378 lines (335 loc) · 12.8 KB
/
Copy pathblock_state.rs
File metadata and controls
378 lines (335 loc) · 12.8 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//! This module contains the [`BlockState`] which provides an implementation of [`BlockStateOperations`].
use crate::block_state::blob_store::{BlobStoreLoad, BlobStoreStore, Loadable, Storable};
use crate::block_state::cacheable::Cacheable;
use crate::block_state::external::{ExternalBlockStateOperations, ExternalBlockStateQuery};
use crate::block_state::hash::Hashable;
use crate::block_state::state::protocol_level_tokens::{
ProtocolLevelTokens, SimplisticTokenKeyValueState,
};
use crate::block_state::types::AccountWithCanonicalAddress;
use crate::block_state::types::protocol_level_tokens::{
TokenAccountState, TokenConfiguration, TokenIndex, TokenStateKey, TokenStateValue,
};
use crate::block_state_interface::{
AccountNotFoundByAddressError, AccountNotFoundByIndexError, BlockStateOperations,
BlockStateQuery, BlockStateResult, OverflowError, RawTokenAmountDelta, TokenNotFoundByIdError,
};
use concordium_base::base::{AccountIndex, ProtocolVersion};
use concordium_base::common::Buffer;
use concordium_base::contracts_common::AccountAddress;
use concordium_base::hashes::Hash;
use concordium_base::protocol_level_tokens::TokenId;
use plt_scheduler_types::types::tokens::RawTokenAmount;
use std::io::Read;
use std::mem;
pub mod blob_reference;
pub mod blob_store;
pub mod cacheable;
pub mod external;
pub mod hash;
pub mod lfmb_tree;
mod state;
pub mod types;
pub mod utils;
/// Immutable block state. The block state is immutable in the sense,
/// that the state it represents never changes during the lifetime of values of type [`BlockState`].
/// In order to perform mutating operations on the block state, a new [`BlockState`]
/// must be created.
///
/// The internal representation in [`BlockState`] may change during the lifetime via interior mutability.
/// This happens if state are cached, stored or hashes are lazily calculated.
#[derive(Debug, Clone, Default)]
pub struct BlockState {
/// Protocol-level tokens
tokens: ProtocolLevelTokens,
}
impl BlockState {
/// Construct an empty block state.
pub fn empty() -> Self {
BlockState {
tokens: ProtocolLevelTokens::empty(),
}
}
/// Consume the immutable block state and create a mutable block state.
pub fn into_mutable(self) -> MutableBlockState {
MutableBlockState::new(self)
}
/// Migrate the PLT block state from one blob store to another.
pub fn migrate(&self, _loader: &impl BlobStoreLoad, _storer: &mut impl BlobStoreStore) -> Self {
// todo implement as part of https://linear.app/concordium/issue/PSR-67/implement-p10-to-p11-migration-for-plt-state
todo!()
}
}
impl Loadable for BlockState {
fn load_from_buffer(
mut buffer: impl Read,
loader: &impl BlobStoreLoad,
) -> BlockStateResult<Self> {
let tokens = Loadable::load_from_buffer(&mut buffer, loader)?;
Ok(Self { tokens })
}
}
impl Storable for BlockState {
fn store_to_buffer(&self, mut buffer: impl Buffer, storer: &mut impl BlobStoreStore) {
self.tokens.store_to_buffer(&mut buffer, storer);
}
}
impl Cacheable for BlockState {
fn cache_reference_values(&self, loader: &impl BlobStoreLoad) -> BlockStateResult<()> {
self.tokens.cache_reference_values(loader)?;
Ok(())
}
}
impl Hashable for BlockState {
fn hash(&self, loader: &impl BlobStoreLoad) -> BlockStateResult<Hash> {
self.tokens.hash(loader)
}
}
/// Mutable block state. In contrast to the immutable block state [`BlockState`],
/// operations on the mutable block state changes the state that
/// the value represents.
#[derive(Debug, Clone)]
pub struct MutableBlockState {
/// Immutable block state value. The block state represented by [`MutableBlockState`] is
/// mutated simply by setting a new value for the immutable block state [`BlockState`].
immutable_state: BlockState,
}
impl MutableBlockState {
/// Create mutable block state from immutable block state.
fn new(mutable_state: BlockState) -> Self {
Self {
immutable_state: mutable_state,
}
}
/// Consume the mutable block state and create an immutable block state.
pub fn into_immutable(self) -> BlockState {
self.immutable_state
}
/// Update the block state using `update` closure and return
/// the additional value of type `T` returned by the closure.
fn update_block_state<T>(
&mut self,
update: impl FnOnce(BlockState) -> BlockStateResult<(T, BlockState)>,
) -> BlockStateResult<T> {
let ret;
(ret, self.immutable_state) = update(mem::take(&mut self.immutable_state))?;
Ok(ret)
}
/// Update the block state using `update` closure.
fn update_block_state_(
&mut self,
update: impl FnOnce(BlockState) -> BlockStateResult<BlockState>,
) -> BlockStateResult<()> {
self.immutable_state = update(mem::take(&mut self.immutable_state))?;
Ok(())
}
}
/// Runtime/execution state relevant for providing an implementation of
/// [`BlockStateQuery`] and [`BlockStateOperations`].
///
/// In addition to the PLT block state, this type contains callbacks
/// for the parts of the state that is managed on the Haskell side.
#[derive(Debug)]
pub struct ExecutionTimeBlockState<IntState, Load, ExtState> {
/// The protocol version of the block state.
pub protocol_version: ProtocolVersion,
/// The library block state implementation.
pub internal_block_state: IntState,
/// External function for reading from the blob store.
pub blob_store_load: Load,
/// Part of block state that is managed externally.
pub external_block_state: ExtState,
}
/// Provides access needed for querying block state (but not to do operations on the block state).
trait HasBlockState {
fn block_state(&self) -> &BlockState;
}
impl HasBlockState for &BlockState {
fn block_state(&self) -> &BlockState {
self
}
}
impl HasBlockState for MutableBlockState {
fn block_state(&self) -> &BlockState {
&self.immutable_state
}
}
impl<IntState: HasBlockState, Load: BlobStoreLoad, ExtState: ExternalBlockStateQuery>
BlockStateQuery for ExecutionTimeBlockState<IntState, Load, ExtState>
{
type TokenKeyValueState = SimplisticTokenKeyValueState;
type Account = AccountIndex;
type Token = TokenIndex;
fn plt_list(&self) -> impl ExactSizeIterator<Item = TokenId> {
// todo propagate block state error as part of https://linear.app/concordium/issue/COR-2346/push-blockstateerror-to-scheduler-code
self.internal_block_state
.block_state()
.tokens
.plt_list(&self.blob_store_load)
.map(|item| item.unwrap())
}
fn token_by_id(&self, token_id: &TokenId) -> Result<Self::Token, TokenNotFoundByIdError> {
self.internal_block_state
.block_state()
.tokens
.token_by_id(token_id)
.ok_or_else(|| TokenNotFoundByIdError(token_id.clone()))
}
fn mutable_token_key_value_state(&self, token: &TokenIndex) -> Self::TokenKeyValueState {
// todo propagate block state error as part of https://linear.app/concordium/issue/COR-2346/push-blockstateerror-to-scheduler-code
self.internal_block_state
.block_state()
.tokens
.mutable_token_key_value_state(&self.blob_store_load, *token)
.unwrap()
}
fn token_configuration(&self, token: &Self::Token) -> TokenConfiguration {
// todo propagate block state error as part of https://linear.app/concordium/issue/COR-2346/push-blockstateerror-to-scheduler-code
self.internal_block_state
.block_state()
.tokens
.token_configuration(&self.blob_store_load, *token)
.unwrap()
}
fn token_circulating_supply(&self, token: &Self::Token) -> RawTokenAmount {
// todo propagate block state error as part of https://linear.app/concordium/issue/COR-2346/push-blockstateerror-to-scheduler-code
self.internal_block_state
.block_state()
.tokens
.token_circulating_supply(&self.blob_store_load, *token)
.unwrap()
}
fn lookup_token_state_value(
&self,
token_key_value_state: &Self::TokenKeyValueState,
key: &TokenStateKey,
) -> Option<TokenStateValue> {
token_key_value_state.lookup_value(key)
}
fn update_token_state_value(
&self,
token_key_value_state: &mut Self::TokenKeyValueState,
key: &TokenStateKey,
value: Option<TokenStateValue>,
) {
token_key_value_state.update_value(key, value)
}
fn account_by_address(
&self,
address: &AccountAddress,
) -> Result<Self::Account, AccountNotFoundByAddressError> {
let index = self
.external_block_state
.account_index_by_account_address(address)?;
Ok(index)
}
fn account_by_index(
&self,
index: AccountIndex,
) -> Result<AccountWithCanonicalAddress<Self::Account>, AccountNotFoundByIndexError> {
let canonical_account_address = self
.external_block_state
.account_canonical_address_by_account_index(index)?;
Ok(AccountWithCanonicalAddress {
account: index,
canonical_account_address,
})
}
fn account_index(&self, account: &Self::Account) -> AccountIndex {
*account
}
fn account_token_balance(
&self,
account: &Self::Account,
token: &Self::Token,
) -> RawTokenAmount {
self.external_block_state
.read_token_account_balance(*account, *token)
}
fn token_account_states(
&self,
account: &Self::Account,
) -> impl Iterator<Item = (Self::Token, TokenAccountState)> {
self.external_block_state
.token_account_states(*account)
.into_iter()
}
fn protocol_version(&self) -> ProtocolVersion {
self.protocol_version
}
fn iter_token_state_prefix<'a>(
&self,
token_key_value_state: &'a Self::TokenKeyValueState,
prefix: TokenStateKey,
) -> impl Iterator<Item = (&'a TokenStateKey, &'a TokenStateValue)> {
token_key_value_state.iter_prefix(prefix)
}
}
impl<Load: BlobStoreLoad, ExtState: ExternalBlockStateOperations> BlockStateOperations
for ExecutionTimeBlockState<MutableBlockState, Load, ExtState>
{
fn set_token_circulating_supply(
&mut self,
token: &Self::Token,
circulating_supply: RawTokenAmount,
) {
// todo propagate block state error as part of https://linear.app/concordium/issue/COR-2346/push-blockstateerror-to-scheduler-code
self.internal_block_state
.update_block_state_(|state| {
Ok(BlockState {
tokens: state.tokens.set_token_circulating_supply(
&self.blob_store_load,
*token,
circulating_supply,
)?,
})
})
.unwrap();
}
fn create_token(&mut self, configuration: TokenConfiguration) -> Self::Token {
// todo propagate block state error as part of https://linear.app/concordium/issue/COR-2346/push-blockstateerror-to-scheduler-code
self.internal_block_state
.update_block_state(|state| {
let (token_index, tokens) = state
.tokens
.create_token(&self.blob_store_load, configuration)?;
Ok((token_index, BlockState { tokens }))
})
.unwrap()
}
fn update_token_account_balance(
&mut self,
token: &Self::Token,
account: &Self::Account,
amount_delta: RawTokenAmountDelta,
) -> Result<(), OverflowError> {
self.external_block_state
.update_token_account_balance(*account, *token, amount_delta)
}
fn touch_token_account(&mut self, token: &Self::Token, account: &Self::Account) {
self.external_block_state
.touch_token_account(*account, *token);
}
fn increment_plt_update_instruction_sequence_number(&mut self) {
self.external_block_state
.increment_plt_update_sequence_number();
}
fn set_token_key_value_state(
&mut self,
token: &Self::Token,
token_key_value_state: Self::TokenKeyValueState,
) {
// todo propagate block state error as part of https://linear.app/concordium/issue/COR-2346/push-blockstateerror-to-scheduler-code
self.internal_block_state
.update_block_state_(|state| {
Ok(BlockState {
tokens: state.tokens.set_token_key_value_state(
&self.blob_store_load,
*token,
token_key_value_state,
)?,
})
})
.unwrap();
}
}