forked from openethereum/parity-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod.rs
562 lines (472 loc) · 17.8 KB
/
mod.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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
mod signer_snapshot;
mod step_service;
mod params;
use rlp::{encode_list, encode, Decodable, DecoderError, Encodable, RlpStream, Rlp};
use std::time::Duration;
use itertools::Itertools;
use std::sync::{Weak, Arc};
use std::collections::{BTreeMap, HashMap};
use std::{fmt, error};
use std::str::FromStr;
use hash::keccak;
use self::params::CliqueParams;
use self::step_service::StepService;
use super::epoch::{PendingTransition, EpochVerifier, NoOp};
use account_provider::AccountProvider;
use builtin::Builtin;
use vm::{EnvInfo, Schedule, CreateContractAddress, CallType, ActionValue};
use error::Error;
use header::{Header, BlockNumber, ExtendedHeader};
use snapshot::SnapshotComponents;
use spec::CommonParams;
use transaction::{self, UnverifiedTransaction, SignedTransaction};
use parking_lot::RwLock;
use block::*;
use io::IoService;
use ethkey::{Password, Signature, recover as ec_recover, public_to_address};
use parity_machine::{Machine, LocalizedMachine as Localized, TotalScoredHeader};
use ethereum_types::{H256, U256, Address, Public};
use unexpected::{Mismatch, OutOfBounds};
use bytes::Bytes;
use types::ancestry_action::AncestryAction;
use engines::{Engine, Seal, EngineError, ConstructedVerifier, Headers, PendingTransitionStore};
use super::signer::EngineSigner;
use machine::{Call, AuxiliaryData, EthereumMachine};
use self::signer_snapshot::{CliqueState, SignerAuthorization, SnapshotState, NONCE_AUTH_VOTE, NONCE_DROP_VOTE, NULL_AUTHOR, DIFF_INTURN, DIFF_NOT_INTURN};
pub const SIGNER_VANITY_LENGTH: u32 = 32;
// Fixed number of extra-data prefix bytes reserved for signer vanity
//const EXTRA_DATA_POST_LENGTH: u32 = 128;
pub const SIGNER_SIG_LENGTH: u32 = 65; // Fixed number of extra-data suffix bytes reserved for signer seal
use client::{EngineClient, BlockId};
pub struct Clique {
client: RwLock<Option<Weak<EngineClient>>>,
state: RwLock<CliqueState>,
//signers: RwLock<Option<Vec<Address>>>,
machine: EthereumMachine,
signer: RwLock<EngineSigner>,
step_service: IoService<Duration>,
epoch_length: u64,
period: u64,
}
/*
* only sign over non-signature bytes (vanity data). There shouldn't be a signature here to sign
* yet.
*/
pub fn sig_hash(header: &Header) -> Result<H256, Error> {
if header.extra_data().len() >= SIGNER_VANITY_LENGTH as usize {
let extra_data = header.extra_data().clone();
let mut reduced_header = header.clone();
reduced_header.set_extra_data(
extra_data[..extra_data.len() - SIGNER_SIG_LENGTH as usize].to_vec());
Ok(reduced_header.hash())
} else {
Ok(header.hash())
}
}
fn recover(header: &Header) -> Result<Public, Error> {
let data = header.extra_data();
let mut sig: [u8; 65] = [0; 65];
sig.copy_from_slice(&data[(data.len() - SIGNER_SIG_LENGTH as usize)..]);
let msg = sig_hash(header).unwrap();
let pubkey = ec_recover(&Signature::from(sig), &msg).unwrap();
Ok(pubkey)
}
const step_time: Duration = Duration::from_millis(100);
impl Clique {
pub fn new(our_params: CliqueParams, machine: EthereumMachine) -> Result<Arc<Self>, Error> {
// don't let there be any duplicate signers
//length of signers must be greater than 1
//
trace!(target: "engine", "epoch length: {}, period: {}", our_params.epoch, our_params.period);
/*
let snapshot = SignerSnapshot {
bn: 0,
signers: vec![],
epoch_length: our_params.epoch,
votes: HashMap::<Address, (bool, Address)>::new(),
};
*/
let engine = Arc::new(
Clique {
client: RwLock::new(Option::default()),
state: RwLock::new(CliqueState::new(our_params.epoch)),
machine: machine,
epoch_length: our_params.epoch,
step_service: IoService::<Duration>::start()?,
period: our_params.period,
signer: Default::default()
});
let handler = StepService::new(Arc::downgrade(&engine) as Weak<Engine<_>>, step_time);
engine.step_service.register_handler(Arc::new(handler))?;
return Ok(engine);
}
fn sign_header(&self, header: &Header) -> Result<(Signature, H256), Error> {
let digest = sig_hash(header)?;
match (*self.signer.read()).sign(digest) {
Ok(sig) => { Ok((sig, digest)) },
Err(e) => { Err(From::from("failed to sign header")) }
}
}
fn state(&self, parent: &Header) -> Option<SnapshotState> {
let mut state = self.state.write();
match state.state(&parent.hash()) {
Some(st) => Some(st),
None => {
let client = self.client.read();
if let Some(c) = client.as_ref().and_then(|w|{ w.upgrade()}) {
let last_checkpoint_number = (parent.number() / self.epoch_length as u64) * self.epoch_length;
let mut chain: &mut Vec<Header> = &mut Vec::new();
chain.push(parent.clone());
// populate chain to last checkpoint
let mut last = chain.last().unwrap().clone();
while last.number() != last_checkpoint_number +1 {
if let Some(next) = c.block_header(BlockId::Hash(*last.parent_hash())) {
chain.push(next.decode().unwrap().clone());
last = chain.last().unwrap().clone();
} else {
trace!(target: "engine", "no parent state for {}", &parent.hash());
return None;
}
}
// Get the last checkpoint header
if let Some(last_checkpoint_header) = c.block_header(BlockId::Hash(*chain.last().unwrap().parent_hash())) {
if let Err(_) = state.apply_checkpoint(&last_checkpoint_header.decode().unwrap()) {
trace!(target: "engine", "failed to apply checkpoint");
return None;
}
}
// Catching up state.
chain.reverse();
trace!(target: "engine",
"verify_block_family backfilling state. last_checkpoint: {}, chain: {:?}.",
last_checkpoint_number, chain);
for item in chain {
if let Err(_) = state.apply(item) {
trace!(target: "engine", "failed to apply item");
return None;
}
}
return state.state(&parent.hash());
} else {
trace!(target: "engine", "failed to upgrade client");
return None;
}
}
}
}
}
impl Engine<EthereumMachine> for Clique {
fn name(&self) -> &str { "Clique" }
// nonce + mixHash + extraData
fn seal_fields(&self, _header: &Header) -> usize { 2 }
fn machine(&self) -> &EthereumMachine { &self.machine }
fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 0 }
fn seal_header(&self, header: &mut Header) {
trace!(target: "seal", "sealed header");
let mut state = self.state.write();
match state.proposer_authorization(header) {
SignerAuthorization::InTurn => {
header.set_difficulty(U256::from(DIFF_INTURN));
},
SignerAuthorization::OutOfTurn => {
header.set_difficulty(U256::from(DIFF_NOT_INTURN));
},
SignerAuthorization::Unauthorized => {
panic!("sealed header should be authorized to sign");
}
}
let signers = state.state(&header.parent_hash()).unwrap().signers;
let mut seal: Vec<u8> = vec![0; SIGNER_VANITY_LENGTH as usize + SIGNER_SIG_LENGTH as usize];
let mut sig_offset = SIGNER_VANITY_LENGTH as usize;
if header.number() % self.epoch_length == 0 {
sig_offset += 20 * signers.len();
for i in 0..signers.len() {
seal[SIGNER_VANITY_LENGTH as usize + i * 20..SIGNER_VANITY_LENGTH as usize + (i + 1) * 20].clone_from_slice(&signers[i]);
}
}
header.set_extra_data(seal.clone());
let (sig, msg) = self.sign_header(&header).expect("should be able to sign header");
seal[sig_offset..].copy_from_slice(&sig[..]);
header.set_extra_data(seal.clone());
state.apply(&header).unwrap();
}
//
//
// {
// let signers = self.state.get_signers();
// trace!(target: "engine", "applied. found {} signers", signers.len());
//
// //let mut v: Vec<u8> = vec![0; SIGNER_VANITY_LENGTH as usize+SIGNER_SIG_LENGTH as usize];
// let mut sig_offset = SIGNER_VANITY_LENGTH as usize;
//
// if _header.number() % self.epoch_length == 0 {
// sig_offset += 20 * signers.len();
//
// for i in 0..signers.len() {
// v[SIGNER_VANITY_LENGTH as usize + i * 20..SIGNER_VANITY_LENGTH as usize + (i + 1) * 20].clone_from_slice(&signers[i]);
// }
// }
//
// h.set_extra_data(v.clone());
//
// let (sig, msg) = self.sign_header(&h).expect("should be able to sign header");
// v[sig_offset..].copy_from_slice(&sig[..]);
//
// trace!(target: "engine", "header hash: {}", h.hash());
// trace!(target: "engine", "Sig: {}", sig);
// trace!(target: "engine", "Message: {:02x}", msg.iter().format(""));
//
// //trace!(target: "engine", "we are {}", self.signer.read().address().unwrap());
// }
//
// return Some(v);
// }
fn step(&self) {
if let Some(ref weak) = *self.client.read() {
if let Some(c) = weak.upgrade() {
c.update_sealing();
}
}
}
fn set_signer(&self, ap: Arc<AccountProvider>, address: Address, password: Password) {
trace!(target: "engine", "called set_signer");
self.signer.write().set(ap, address, password);
self.state.write().set_signer_address(address.clone());
}
/// None means that it requires external input (e.g. PoW) to seal a block.
/// /// Some(true) means the engine is currently prime for seal generation (i.e. node
/// is the current validator).
/// /// Some(false) means that the node might seal internally but is not qualified
/// now.
///
fn seals_internally(&self) -> Option<bool> {
Some(true)
}
/// Attempt to seal generate a proposal seal.
///
/// This operation is synchronous and may (quite reasonably) not be available, in which case
/// `Seal::None` will be returned.
fn generate_seal(&self, block: &ExecutedBlock, _parent: &Header) -> Seal {
trace!(target: "engine", "tried to generate seal");
//
// let mut header = block.header.clone();
//
// trace!(target: "engine", "attempting to seal...");
//
// // don't seal the genesis block
if block.header.number() == 0 {
trace!(target: "engine", "attempted to seal genesis block");
return Seal::None;
}
// // if sealing period is 0, refuse to seal
if self.epoch_length == 0 {
return Seal::None;
}
//
// let vote_snapshot = self.snapshot.get(bh);
//
// // if we are not authorized to sign, don't seal
//
// // if we signed recently, don't seal
//
if block.header.timestamp() <= _parent.timestamp() + self.period {
return Seal::None;
}
if self.state(&_parent).is_none() {
panic!("could not recover voting state when sealing on block {}", _parent.number() + 1 );
}
let mut state = self.state.write();
match state.proposer_authorization(&block.header) {
SignerAuthorization::Unauthorized => {
trace!(target: "engine", "tried to seal: not authorized");
return Seal::None;
},
SignerAuthorization::InTurn => {
trace!(target: "engine", "seal generated for {}", block.header.number());
return Seal::Regular(vec![encode(&vec![0; 32]), encode(&vec![0; 8])]);
},
SignerAuthorization::OutOfTurn => {
if state.turn_delay(&block.header) {
trace!(target: "engine", "seal generated for {}", block.header.number());
return Seal::Regular(vec![encode(&vec![0; 32]), encode(&vec![0; 8])]);
} else {
trace!(target: "engine", "not in turn. seal delayed for {}", block.header.number());
return Seal::None;
}
}
}
}
fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> {
/*
* TODO:
if not checkpoint block:
if the block was successfully sealed, then grab the signature from the seal data and
append it to the block extraData
*/
// trace!(target: "engine", "closing block {}...", block.header().number());
Ok(())
}
fn on_new_block(
&self,
_block: &mut ExecutedBlock,
_epoch_begin: bool,
_ancestry: &mut Iterator<Item=ExtendedHeader>,
) -> Result<(), Error> {
//trace!(target: "engine", "new block {}", _block.header().number());
/*
if let Some(ref mut snapshot) = *self.snapshot.write() {
snapshot.rollback();
} else {
panic!("could not get write access to snapshot");
}
*/
/*
if let Some(ref mut snapshot) = *self.snapshot.write() {
snapshot.apply(_block.header());
}
*/
Ok(())
}
fn executive_author(&self, header: &Header) -> Address {
// if self.is_signer_proposer(header.number()) {
// return self.snapshot.signer_address().unwrap();
// } else {
return public_to_address(
&recover(header).unwrap());
// }
}
fn verify_block_basic(&self, _header: &Header) -> Result<(), Error> {
//trace!(target: "engine", "called verify_block_basic for block {}", _header.number());
// Ignore genisis block.
if _header.number() == 0 {
return Ok(());
}
// don't allow blocks from the future
// Checkpoint blocks need to enforce zero beneficiary
if _header.number() % self.epoch_length == 0 {
if _header.author() != &[0; 20].into() {
return Err(Box::new("Checkpoint blocks need to enforce zero beneficiary").into());
}
let nonce = _header.decode_seal::<Vec<&[u8]>>().unwrap()[1];
if nonce != &NONCE_DROP_VOTE[..] {
return Err(Box::new("Seal nonce zeros enforced on checkpoints").into());
}
} else {
// TODO
// - ensure header extraData has length SIGNER_VANITY_LENGTH + SIGNER_SIG_LENGTH
// - ensure header signature corresponds to the right validator for the turn-ness of the
// block
}
// Nonces must be 0x00..0 or 0xff..f, zeroes enforced on checkpoints
// Check that the extra-data contains both the vanity and signature
// Ensure that the extra-data contains a signer list on checkpoint, but none otherwise
// Ensure that the mix digest is zero as we don't have fork protection currently
// Ensure that the block doesn't contain any uncles which are meaningless in PoA
// Ensure that the block's difficulty is meaningful
// ...
Ok(())
}
// fn on_block_applied(&self, header: &Header) -> Result<(), Error> {
// self.snapshot.apply(&header);
// self.snapshot.commit();
//
// Ok(())
// }
fn verify_block_unordered(&self, _header: &Header) -> Result<(), Error> {
// Verifying the genesis block is not supported
// Retrieve the snapshot needed to verify this header and cache it
// Resolve the authorization key and check against signers
// Ensure that the difficulty corresponds to the turn-ness of the signer
Ok(())
}
fn verify_block_family(&self, header: &Header, parent: &Header) -> Result<(), Error> {
/*
trace!(target: "engine",
"verify_block_family for {}: current state: {:?}.",
header.number(), *self.state.read());
*/
if self.state(&parent).is_none() {
return Err(From::from(format!("could not parse parent state for {}", &parent.hash())));
}
let mut state = self.state.write();
if (header.number() % self.epoch_length == 0) {
// TODO: we may still need to validate checkpoint state
state.apply_checkpoint(header);
} else {
state.apply(header)?;
}
Ok(())
}
fn signals_epoch_end(&self, header: &Header, aux: AuxiliaryData)
-> super::EpochChange<EthereumMachine>
{
super::EpochChange::No
}
fn is_epoch_end(
&self,
chain_head: &Header,
_finalized: &[H256],
_chain: &Headers<Header>,
_transition_store: &PendingTransitionStore,
) -> Option<Vec<u8>> {
None
}
fn epoch_verifier<'a>(&self, _header: &Header, proof: &'a [u8]) -> ConstructedVerifier<'a, EthereumMachine> {
ConstructedVerifier::Trusted(Box::new(super::epoch::NoOp))
}
fn stop(&self) {}
fn verify_local_seal(&self, header: &Header) -> Result<(), Error> { Ok(()) }
fn fork_choice(&self, new: &ExtendedHeader, current: &ExtendedHeader) -> super::ForkChoice {
super::total_difficulty_fork_choice(new, current)
}
/*
* Extract signer addresses from header extraData
*/
fn genesis_epoch_data(&self, header: &Header, call: &Call) -> Result<Vec<u8>, String> {
// extract signer list from genesis extradata
trace!(target: "engine", "genesis_epoch_data received.");
{
let mut state = self.state.write();
state.apply_checkpoint(header).expect("Error processing genesis block");
trace!(target: "engine", "current state: {:?}", *state);
}
Ok(Vec::new())
}
fn is_timestamp_valid(&self, header_timestamp: u64, parent_timestamp: u64) -> bool {
header_timestamp >= parent_timestamp + self.period
}
// /// Check if current signer is the current proposer.
// fn is_signer_proposer(&self, bn: u64) -> bool {
// let mut authorized = false;
//
// let address = match self.snapshot.signer_address() {
// Some(addr) => { addr }
// None => { return false; }
// };
//
// let signers = self.snapshot.get_signers();
//
// let authorized = if let Some(pos) = signers.iter().position(|x| self.snapshot.signer_address().unwrap() == *x) {
// bn % signers.len() as u64 == pos as u64
// } else {
// false
// };
// return authorized;
// }
fn register_client(&self, client: Weak<EngineClient>) {
trace!(target: "engine", "client regsitered.");
*self.client.write() = Some(client.clone());
}
}