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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use crate::account::account::Account;
use crate::common::address::Address;
use crate::common::block::Block;
use crate::common::header::Header;
use crate::common::signed_tx::SignedTx;
use crate::consensus::worldstate::WorldState;
use crate::database::block_db::BlockDB;
use crate::traits::{BlockHeader, Encode, Exception, Proto, Transaction};
use crate::util::strict_math::StrictU64;
use secp256k1::{RecoverableSignature, RecoveryId};
use std::collections::{BTreeMap, HashSet};
use std::error::Error;
use std::sync::{Arc, Mutex};
const MAX_STATE_CACHE_SIZE: usize = 5000;
type StateProcessorResult<T> = Result<T, Box<Error>>;
pub struct StateProcessor<BlockDBType = BlockDB, WorldStateType = WorldState> {
worldstate: WorldStateType,
block_db: Arc<Mutex<BlockDBType>>,
state_cache: Vec<Vec<u8>>,
}
impl StateProcessor {
pub fn new(
block_db: Arc<Mutex<BlockDB>>,
worldstate: WorldState,
) -> StateProcessor<BlockDB, WorldState> {
let state_cache = Vec::with_capacity(MAX_STATE_CACHE_SIZE);
StateProcessor {
worldstate,
block_db,
state_cache,
}
}
fn prune(&mut self) -> Result<(), Box<Error>> {
if self.state_cache.len() <= MAX_STATE_CACHE_SIZE {
return Ok(());
}
for i in (0..self.state_cache.len() - MAX_STATE_CACHE_SIZE).rev() {
self.worldstate.remove(self.state_cache[i].as_ref())?;
self.state_cache.remove(i);
}
Ok(())
}
fn regenerate(&mut self, height: u32) -> StateProcessorResult<()> {
let block_tip = self
.block_db
.lock()
.map_err(|_| Exception::new("Poison error"))?
.get_block_tip_hash()?;
let block = self
.block_db
.lock()
.map_err(|_| Exception::new("Poison error"))?
.get_block::<Block<Header, SignedTx>, Header>(&block_tip)?;
let tip_height;
if let Some(m) = block.meta {
tip_height = m.height;
} else {
return Err(Box::new(Exception::new("Block tip does not have height")));
}
if tip_height - height <= MAX_STATE_CACHE_SIZE as u32 {
return Ok(());
}
return Err(Box::new(Exception::new("Not Implemented")));
}
pub fn generate_transition<HeaderType, TransactionType>(
&self,
blocks: Vec<&Block<HeaderType, TransactionType>>,
) -> StateProcessorResult<BTreeMap<Address, Account>>
where
HeaderType: BlockHeader + Encode + Proto + Clone,
TransactionType: Transaction<Address, RecoverableSignature, RecoveryId>,
{
let mut address_list: Vec<Address> = Vec::with_capacity(8192);
let mut address_set = HashSet::new();
for block in &blocks {
if let Some(ref txs) = block.txs {
for tx in txs {
if let Some(from) = tx.get_from() {
if !address_set.contains(&from) {
address_list.insert(0, from);
address_set.insert(from);
}
}
if let Some(to) = tx.get_to() {
if !address_set.contains(&to) {
address_list.insert(0, to);
address_set.insert(to);
}
}
}
}
}
address_list.sort();
let mut address_keys = Vec::with_capacity(address_list.len());
for i in 0..address_list.len() {
address_keys.push(&address_list[i])
}
let mut account_map = BTreeMap::new();
if self.state_cache.len() > 0 {
let mut accounts = self
.worldstate
.get(&self.state_cache[self.state_cache.len() - 1], &address_keys)?;
for i in (0..accounts.len()).rev() {
if let Some(account) = accounts.remove(i) {
account_map.insert(address_list[i], account.1);
} else {
account_map.insert(address_list[i], Account::default());
}
}
} else {
for i in 0..address_list.len() {
account_map.insert(address_list[i], Account::default());
}
}
for block in &blocks {
let mut revert = false;
let mut processed_txs: usize = 0;
if let Some(ref txs) = block.txs {
let miner = block.header.get_miner();
let genesis;
if let Some(_) = miner {
genesis = false;
} else {
genesis = true;
}
for tx in txs {
if let Err(_) =
StateProcessor::generate_tx_transition(tx, &mut account_map, miner, genesis)
{
revert = true;
break;
}
processed_txs += 1;
}
}
if revert {
match block.txs {
Some(ref txs) => {
for i in 0..processed_txs {
StateProcessor::revert_tx_transition(
&txs[i],
&mut account_map,
block.header.get_miner(),
)?;
}
}
None => {
return Err(Box::new(Exception::new(
"Should be impossible to reach, txs have disappeared",
)));
}
}
break;
}
}
return Ok(account_map);
}
fn generate_tx_transition<TxType>(
tx: &TxType,
account_map: &mut BTreeMap<Address, Account>,
miner: Option<&Address>,
genesis: bool,
) -> StateProcessorResult<()>
where
TxType: Transaction<Address, RecoverableSignature, RecoveryId>,
{
if genesis {
if let Some(to) = tx.get_to() {
let nonce;
if let Some(n) = tx.get_nonce() {
nonce = n;
} else {
nonce = 0;
}
if let Some(to_account) = account_map.get_mut(&to) {
to_account.balance = tx.get_amount();
to_account.nonce = nonce;
} else {
return Err(Box::new(Exception::new(
"Invalid Tx: Tx to account does not exist",
)));
}
} else {
return Err(Box::new(Exception::new(
"Invalid Tx: Tx is missing to field",
)));
}
return Ok(());
}
let miner_address;
if let Some(addr) = miner {
miner_address = addr;
} else {
return Err(Box::new(Exception::new("No miner address was supplied")));
}
let prev_miner_balance;
let prev_from_balance;
let prev_from_nonce;
let fee;
let nonce;
if let Some(a) = account_map.get(miner_address) {
prev_miner_balance = StrictU64::new(a.balance);
} else {
return Err(Box::new(Exception::new(
"Block miner not found in account map",
)));
}
let from;
if let Some(f) = tx.get_from() {
from = f;
if let Some(a) = account_map.get(&from) {
prev_from_balance = StrictU64::new(a.balance);
prev_from_nonce = a.nonce;
} else {
return Err(Box::new(Exception::new(
"Invalid Tx: Tx is missing from account",
)));
}
} else {
return Err(Box::new(Exception::new("Invalid Tx: Tx is missing from")));
}
if let Some(f) = tx.get_fee() {
fee = StrictU64::new(f);
} else {
return Err(Box::new(Exception::new("Invalid Tx: Tx is missing fee")));
}
if let Some(n) = tx.get_nonce() {
nonce = n;
} else {
return Err(Box::new(Exception::new("Invalid Tx: Tx is missing nonce")));
}
if nonce != prev_from_nonce {
return Err(Box::new(Exception::new(&format!(
"Invalid Tx:\n Expected nonce: {}\n Supplied nonce: {}",
prev_from_nonce, nonce
))));
}
let amount = StrictU64::new(tx.get_amount());
let total = (amount + fee)?;
let new_from_balance = (prev_from_balance - total)?;
let new_miner_balance = (prev_miner_balance + fee)?;
let new_from_nonce = prev_from_nonce + 1;
if let Some(to) = tx.get_to() {
if let Some(to_account) = account_map.get_mut(&to) {
let prev_to_balance = StrictU64::new(to_account.balance);
let new_to_balance = (prev_to_balance + amount)?;
to_account.balance = u64::from(new_to_balance);
} else {
return Err(Box::new(Exception::new(
"Invalid Tx: Tx to account does not exist",
)));
}
}
if let Some(from_account) = account_map.get_mut(&from) {
from_account.balance = u64::from(new_from_balance);
from_account.nonce = new_from_nonce;
} else {
return Err(Box::new(Exception::new("Corrupt account map")));
}
if let Some(miner_account) = account_map.get_mut(miner_address) {
miner_account.balance = u64::from(new_miner_balance);
} else {
return Err(Box::new(Exception::new("Corrupt account map")));
}
return Ok(());
}
pub fn revert_tx_transition<TxType>(
tx: &TxType,
account_map: &mut BTreeMap<Address, Account>,
miner: Option<&Address>,
) -> StateProcessorResult<()>
where
TxType: Transaction<Address, RecoverableSignature, RecoveryId>,
{
let miner_address;
if let Some(addr) = miner {
miner_address = addr;
} else {
return Err(Box::new(Exception::new("No miner address was supplied")));
}
let prev_miner_balance;
let prev_from_balance;
let prev_from_nonce;
let fee;
if let Some(a) = account_map.get(miner_address) {
prev_miner_balance = StrictU64::new(a.balance);
} else {
return Err(Box::new(Exception::new(
"Block miner not found in account map",
)));
}
let from;
if let Some(f) = tx.get_from() {
from = f;
if let Some(a) = account_map.get(&from) {
prev_from_balance = StrictU64::new(a.balance);
prev_from_nonce = a.nonce;
} else {
return Err(Box::new(Exception::new(
"Invalid Tx: Tx is missing from account",
)));
}
} else {
return Err(Box::new(Exception::new("Invalid Tx: Tx is missing from")));
}
if let Some(f) = tx.get_fee() {
fee = StrictU64::new(f);
} else {
return Err(Box::new(Exception::new("Invalid Tx: Tx is missing fee")));
}
let amount = StrictU64::new(tx.get_amount());
let total = (amount + fee)?;
let new_from_balance = (prev_from_balance + total)?;
let new_miner_balance = (prev_miner_balance - fee)?;
let new_from_nonce = prev_from_nonce - 1;
if let Some(to) = tx.get_to() {
if let Some(to_account) = account_map.get_mut(&to) {
let prev_to_balance = StrictU64::new(to_account.balance);
let new_to_balance = (prev_to_balance - amount)?;
to_account.balance = u64::from(new_to_balance);
} else {
return Err(Box::new(Exception::new(
"Invalid Tx: Tx to account does not exist",
)));
}
}
if let Some(from_account) = account_map.get_mut(&from) {
from_account.balance = u64::from(new_from_balance);
from_account.nonce = new_from_nonce;
} else {
return Err(Box::new(Exception::new("Corrupt account map")));
}
if let Some(miner_account) = account_map.get_mut(miner_address) {
miner_account.balance = u64::from(new_miner_balance);
} else {
return Err(Box::new(Exception::new("Corrupt account map")));
}
return Ok(());
}
pub fn apply_transition(
&mut self,
transition: BTreeMap<Address, Account>,
root: Option<&[u8]>,
) -> StateProcessorResult<Vec<u8>> {
let mut addresses = Vec::with_capacity(transition.len());
let mut accounts = Vec::with_capacity(transition.len());
for (key, value) in transition.iter() {
addresses.push(key);
accounts.push(*value);
}
let new_root = self
.worldstate
.insert(root, addresses, accounts.as_slice())?;
self.state_cache.push(new_root.clone());
Ok(new_root)
}
}
#[cfg(test)]
mod tests {}