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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
mod authority_round;
mod basic_authority;
mod instant_seal;
mod null_engine;
mod signer;
mod tendermint;
mod transition;
mod validator_set;
mod vote_collector;
pub mod block_reward;
pub mod epoch;
pub use self::authority_round::AuthorityRound;
pub use self::basic_authority::BasicAuthority;
pub use self::epoch::{EpochVerifier, Transition as EpochTransition};
pub use self::instant_seal::InstantSeal;
pub use self::null_engine::NullEngine;
pub use self::tendermint::Tendermint;
use std::sync::{Weak, Arc};
use std::collections::{BTreeMap, HashMap};
use std::{fmt, error};
use self::epoch::PendingTransition;
use account_provider::AccountProvider;
use builtin::Builtin;
use vm::{EnvInfo, Schedule, CreateContractAddress};
use error::Error;
use header::{Header, BlockNumber};
use snapshot::SnapshotComponents;
use spec::CommonParams;
use transaction::{self, UnverifiedTransaction, SignedTransaction};
use ethkey::Signature;
use parity_machine::{Machine, LocalizedMachine as Localized, TotalScoredHeader};
use ethereum_types::{H256, U256, Address};
use unexpected::{Mismatch, OutOfBounds};
use bytes::Bytes;
use types::ancestry_action::AncestryAction;
pub const DEFAULT_BLOCKHASH_CONTRACT: &'static str = "73fffffffffffffffffffffffffffffffffffffffe33141561006a5760014303600035610100820755610100810715156100455760003561010061010083050761010001555b6201000081071515610064576000356101006201000083050761020001555b5061013e565b4360003512151561008457600060405260206040f361013d565b61010060003543031315156100a857610100600035075460605260206060f361013c565b6101006000350715156100c55762010000600035430313156100c8565b60005b156100ea576101006101006000350507610100015460805260206080f361013b565b620100006000350715156101095763010000006000354303131561010c565b60005b1561012f57610100620100006000350507610200015460a052602060a0f361013a565b600060c052602060c0f35b5b5b5b5b";
#[derive(Debug, PartialEq, Eq)]
pub enum ForkChoice {
New,
Old,
}
#[derive(Debug)]
pub enum EngineError {
NotAuthorized(Address),
DoubleVote(Address),
NotProposer(Mismatch<Address>),
UnexpectedMessage,
BadSealFieldSize(OutOfBounds<usize>),
InsufficientProof(String),
FailedSystemCall(String),
MalformedMessage(String),
RequiresClient,
}
impl fmt::Display for EngineError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::EngineError::*;
let msg = match *self {
DoubleVote(ref address) => format!("Author {} issued too many blocks.", address),
NotProposer(ref mis) => format!("Author is not a current proposer: {}", mis),
NotAuthorized(ref address) => format!("Signer {} is not authorized.", address),
UnexpectedMessage => "This Engine should not be fed messages.".into(),
BadSealFieldSize(ref oob) => format!("Seal field has an unexpected length: {}", oob),
InsufficientProof(ref msg) => format!("Insufficient validation proof: {}", msg),
FailedSystemCall(ref msg) => format!("Failed to make system call: {}", msg),
MalformedMessage(ref msg) => format!("Received malformed consensus message: {}", msg),
RequiresClient => format!("Call requires client but none registered"),
};
f.write_fmt(format_args!("Engine error ({})", msg))
}
}
impl error::Error for EngineError {
fn description(&self) -> &str {
"Engine error"
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Seal {
Proposal(Vec<Bytes>),
Regular(Vec<Bytes>),
None,
}
pub type SystemCall<'a> = FnMut(Address, Vec<u8>) -> Result<Vec<u8>, String> + 'a;
pub type Headers<'a, H> = Fn(H256) -> Option<H> + 'a;
pub type PendingTransitionStore<'a> = Fn(H256) -> Option<PendingTransition> + 'a;
pub trait StateDependentProof<M: Machine>: Send + Sync {
fn generate_proof<'a>(&self, state: &<M as Localized<'a>>::StateContext) -> Result<Vec<u8>, String>;
fn check_proof(&self, machine: &M, proof: &[u8]) -> Result<(), String>;
}
pub enum Proof<M: Machine> {
Known(Vec<u8>),
WithState(Arc<StateDependentProof<M>>),
}
pub enum ConstructedVerifier<'a, M: Machine> {
Trusted(Box<EpochVerifier<M>>),
Unconfirmed(Box<EpochVerifier<M>>, &'a [u8], H256),
Err(Error),
}
impl<'a, M: Machine> ConstructedVerifier<'a, M> {
pub fn known_confirmed(self) -> Result<Box<EpochVerifier<M>>, Error> {
match self {
ConstructedVerifier::Trusted(v) | ConstructedVerifier::Unconfirmed(v, _, _) => Ok(v),
ConstructedVerifier::Err(e) => Err(e),
}
}
}
pub enum EpochChange<M: Machine> {
Unsure(M::AuxiliaryRequest),
No,
Yes(Proof<M>),
}
pub trait Engine<M: Machine>: Sync + Send {
fn name(&self) -> &str;
fn machine(&self) -> &M;
fn seal_fields(&self, _header: &M::Header) -> usize { 0 }
fn extra_info(&self, _header: &M::Header) -> BTreeMap<String, String> { BTreeMap::new() }
fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 0 }
fn maximum_uncle_age(&self) -> usize { 6 }
fn on_new_block(
&self,
_block: &mut M::LiveBlock,
_epoch_begin: bool,
_ancestry: &mut Iterator<Item=M::ExtendedHeader>,
) -> Result<(), M::Error> {
Ok(())
}
fn on_close_block(&self, _block: &mut M::LiveBlock) -> Result<(), M::Error> {
Ok(())
}
fn seals_internally(&self) -> Option<bool> { None }
fn generate_seal(&self, _block: &M::LiveBlock, _parent: &M::Header) -> Seal { Seal::None }
fn verify_local_seal(&self, header: &M::Header) -> Result<(), M::Error>;
fn verify_block_basic(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) }
fn verify_block_unordered(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) }
fn verify_block_family(&self, _header: &M::Header, _parent: &M::Header) -> Result<(), M::Error> { Ok(()) }
fn verify_block_external(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) }
fn genesis_epoch_data<'a>(&self, _header: &M::Header, _state: &<M as Localized<'a>>::StateContext) -> Result<Vec<u8>, String> { Ok(Vec::new()) }
fn signals_epoch_end<'a>(&self, _header: &M::Header, _aux: <M as Localized<'a>>::AuxiliaryData)
-> EpochChange<M>
{
EpochChange::No
}
fn is_epoch_end(
&self,
_chain_head: &M::Header,
_chain: &Headers<M::Header>,
_transition_store: &PendingTransitionStore,
) -> Option<Vec<u8>> {
None
}
fn epoch_verifier<'a>(&self, _header: &M::Header, _proof: &'a [u8]) -> ConstructedVerifier<'a, M> {
ConstructedVerifier::Trusted(Box::new(self::epoch::NoOp))
}
fn populate_from_parent(&self, _header: &mut M::Header, _parent: &M::Header) { }
fn handle_message(&self, _message: &[u8]) -> Result<(), EngineError> { Err(EngineError::UnexpectedMessage) }
fn is_proposal(&self, _verified_header: &M::Header) -> bool { false }
fn set_signer(&self, _account_provider: Arc<AccountProvider>, _address: Address, _password: String) {}
fn sign(&self, _hash: H256) -> Result<Signature, M::Error> { unimplemented!() }
fn register_client(&self, _client: Weak<M::EngineClient>) {}
fn step(&self) {}
fn stop(&self) {}
fn snapshot_components(&self) -> Option<Box<SnapshotComponents>> {
None
}
fn supports_warp(&self) -> bool {
self.snapshot_components().is_some()
}
fn open_block_header_timestamp(&self, parent_timestamp: u64) -> u64 {
use std::{time, cmp};
let now = time::SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap_or_default();
cmp::max(now.as_secs() as u64, parent_timestamp + 1)
}
fn is_timestamp_valid(&self, header_timestamp: u64, parent_timestamp: u64) -> bool {
header_timestamp > parent_timestamp
}
fn ancestry_actions(&self, _block: &M::LiveBlock, _ancestry: &mut Iterator<Item=M::ExtendedHeader>) -> Vec<AncestryAction> {
Vec::new()
}
fn fork_choice(&self, new: &M::ExtendedHeader, best: &M::ExtendedHeader) -> ForkChoice;
}
pub fn total_difficulty_fork_choice<T: TotalScoredHeader>(new: &T, best: &T) -> ForkChoice where <T as TotalScoredHeader>::Value: Ord {
if new.total_score() > best.total_score() {
ForkChoice::New
} else {
ForkChoice::Old
}
}
pub trait EthEngine: Engine<::machine::EthereumMachine> {
fn params(&self) -> &CommonParams {
self.machine().params()
}
fn schedule(&self, block_number: BlockNumber) -> Schedule {
self.machine().schedule(block_number)
}
fn builtins(&self) -> &BTreeMap<Address, Builtin> {
self.machine().builtins()
}
fn builtin(&self, a: &Address, block_number: BlockNumber) -> Option<&Builtin> {
self.machine().builtin(a, block_number)
}
fn maximum_extra_data_size(&self) -> usize {
self.machine().maximum_extra_data_size()
}
fn account_start_nonce(&self, block: BlockNumber) -> U256 {
self.machine().account_start_nonce(block)
}
fn signing_chain_id(&self, env_info: &EnvInfo) -> Option<u64> {
self.machine().signing_chain_id(env_info)
}
fn create_address_scheme(&self, number: BlockNumber) -> CreateContractAddress {
self.machine().create_address_scheme(number)
}
fn verify_transaction_unordered(&self, t: UnverifiedTransaction, header: &Header) -> Result<SignedTransaction, transaction::Error> {
self.machine().verify_transaction_unordered(t, header)
}
fn verify_transaction_basic(&self, t: &UnverifiedTransaction, header: &Header) -> Result<(), transaction::Error> {
self.machine().verify_transaction_basic(t, header)
}
fn additional_params(&self) -> HashMap<String, String> {
self.machine().additional_params()
}
fn decode_transaction(&self, transaction: &[u8]) -> Result<UnverifiedTransaction, transaction::Error> {
self.machine().decode_transaction(transaction)
}
}
impl<T> EthEngine for T where T: Engine<::machine::EthereumMachine> { }