      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
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838

    // Copyright 2015-2017 Parity Technologies (UK) Ltd.
    // This file is part of Parity.

    // Parity 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 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.  If not, see <http://www.gnu.org/licenses/>.

    use ethash::{quick_get_difficulty, slow_get_seedhash, EthashManager};
    use util::*;
    use block::*;
    use builtin::Builtin;
    use env_info::EnvInfo;
    use error::{BlockError, TransactionError, Error};
    use header::Header;
    use state::CleanupMode;
    use spec::CommonParams;
    use transaction::UnverifiedTransaction;
    use engines::Engine;
    use evm::Schedule;
    use ethjson;
    use rlp::{self, UntrustedRlp, View};

    /// Parity tries to round block.gas_limit to multiple of this constant
    pub const PARITY_GAS_LIMIT_DETERMINANT: U256 = U256([37, 0, 0, 0]);

    /// Ethash params.
    #[derive(Debug, PartialEq)]
    pub struct EthashParams {
    	/// Gas limit divisor.
    	pub gas_limit_bound_divisor: U256,
    	/// Minimum difficulty.
    	pub minimum_difficulty: U256,
    	/// Difficulty bound divisor.
    	pub difficulty_bound_divisor: U256,
    	/// Difficulty increment divisor.
    	pub difficulty_increment_divisor: u64,
    	/// Block duration.
    	pub duration_limit: u64,
    	/// Block reward.
    	pub block_reward: U256,
    	/// Namereg contract address.
    	pub registrar: Address,
    	/// Homestead transition block number.
    	pub homestead_transition: u64,
    	/// DAO hard-fork transition block (X).
    	pub dao_hardfork_transition: u64,
    	/// DAO hard-fork refund contract address (C).
    	pub dao_hardfork_beneficiary: Address,
    	/// DAO hard-fork DAO accounts list (L)
    	pub dao_hardfork_accounts: Vec<Address>,
    	/// Transition block for a change of difficulty params (currently just bound_divisor).
    	pub difficulty_hardfork_transition: u64,
    	/// Difficulty param after the difficulty transition.
    	pub difficulty_hardfork_bound_divisor: U256,
    	/// Block on which there is no additional difficulty from the exponential bomb.
    	pub bomb_defuse_transition: u64,
    	/// Number of first block where EIP-150 rules begin.
    	pub eip150_transition: u64,
    	/// Number of first block where EIP-155 rules begin.
    	pub eip155_transition: u64,
    	/// Number of first block where EIP-160 rules begin.
    	pub eip160_transition: u64,
    	/// Number of first block where EIP-161.abc begin.
    	pub eip161abc_transition: u64,
    	/// Number of first block where EIP-161.d begins.
    	pub eip161d_transition: u64,
    	/// Number of first block where ECIP-1010 begins.
    	pub ecip1010_pause_transition: u64,
    	/// Number of first block where ECIP-1010 ends.
    	pub ecip1010_continue_transition: u64,
    	/// Maximum amount of code that can be deploying into a contract.
    	pub max_code_size: u64,
    }

    impl From<ethjson::spec::EthashParams> for EthashParams {
    	fn from(p: ethjson::spec::EthashParams) -> Self {
    		EthashParams {
    			gas_limit_bound_divisor: p.gas_limit_bound_divisor.into(),
    			minimum_difficulty: p.minimum_difficulty.into(),
    			difficulty_bound_divisor: p.difficulty_bound_divisor.into(),
    			difficulty_increment_divisor: p.difficulty_increment_divisor.map_or(10, Into::into),
    			duration_limit: p.duration_limit.into(),
    			block_reward: p.block_reward.into(),
    			registrar: p.registrar.map_or_else(Address::new, Into::into),
    			homestead_transition: p.homestead_transition.map_or(0, Into::into),
    			dao_hardfork_transition: p.dao_hardfork_transition.map_or(u64::max_value(), Into::into),
    			dao_hardfork_beneficiary: p.dao_hardfork_beneficiary.map_or_else(Address::new, Into::into),
    			dao_hardfork_accounts: p.dao_hardfork_accounts.unwrap_or_else(Vec::new).into_iter().map(Into::into).collect(),
    			difficulty_hardfork_transition: p.difficulty_hardfork_transition.map_or(u64::max_value(), Into::into),
    			difficulty_hardfork_bound_divisor: p.difficulty_hardfork_bound_divisor.map_or(p.difficulty_bound_divisor.into(), Into::into),
    			bomb_defuse_transition: p.bomb_defuse_transition.map_or(u64::max_value(), Into::into),
    			eip150_transition: p.eip150_transition.map_or(0, Into::into),
    			eip155_transition: p.eip155_transition.map_or(0, Into::into),
    			eip160_transition: p.eip160_transition.map_or(0, Into::into),
    			eip161abc_transition: p.eip161abc_transition.map_or(0, Into::into),
    			eip161d_transition: p.eip161d_transition.map_or(u64::max_value(), Into::into),
    			ecip1010_pause_transition: p.ecip1010_pause_transition.map_or(u64::max_value(), Into::into),
    			ecip1010_continue_transition: p.ecip1010_continue_transition.map_or(u64::max_value(), Into::into),
    			max_code_size: p.max_code_size.map_or(u64::max_value(), Into::into),
    		}
    	}
    }

    /// Engine using Ethash proof-of-work consensus algorithm, suitable for Ethereum
    /// mainnet chains in the Olympic, Frontier and Homestead eras.
    pub struct Ethash {
    	params: CommonParams,
    	ethash_params: EthashParams,
    	builtins: BTreeMap<Address, Builtin>,
    	pow: EthashManager,
    }

    impl Ethash {
    	/// Create a new instance of Ethash engine
    	pub fn new(params: CommonParams, ethash_params: EthashParams, builtins: BTreeMap<Address, Builtin>) -> Self {
    		Ethash {
    			params: params,
    			ethash_params: ethash_params,
    			builtins: builtins,
    			pow: EthashManager::new(),
    		}
    	}
    }

    impl Engine for Ethash {
    	fn name(&self) -> &str { "Ethash" }
    	fn version(&self) -> SemanticVersion { SemanticVersion::new(1, 0, 0) }
    	// Two fields - mix
    	fn seal_fields(&self) -> usize { 2 }

    	fn params(&self) -> &CommonParams { &self.params }
    	fn additional_params(&self) -> HashMap<String, String> { hash_map!["registrar".to_owned() => self.ethash_params.registrar.hex()] }

    	fn builtins(&self) -> &BTreeMap<Address, Builtin> {
    		&self.builtins
    	}

    	/// Additional engine-specific information for the user/developer concerning `header`.
    	fn extra_info(&self, header: &Header) -> BTreeMap<String, String> {
    		map!["nonce".to_owned() => format!("0x{}", header.nonce().hex()), "mixHash".to_owned() => format!("0x{}", header.mix_hash().hex())]
    	}

    	fn schedule(&self, env_info: &EnvInfo) -> Schedule {
    		trace!(target: "client", "Creating schedule. fCML={}, bGCML={}", self.ethash_params.homestead_transition, self.ethash_params.eip150_transition);

    		if env_info.number < self.ethash_params.homestead_transition {
    			Schedule::new_frontier()
    		} else if env_info.number < self.ethash_params.eip150_transition {
    			Schedule::new_homestead()
    		} else {
    			Schedule::new_post_eip150(
    				self.ethash_params.max_code_size as usize,
    				env_info.number >= self.ethash_params.eip160_transition,
    				env_info.number >= self.ethash_params.eip161abc_transition,
    				env_info.number >= self.ethash_params.eip161d_transition
    			)
    		}
    	}

    	fn signing_network_id(&self, env_info: &EnvInfo) -> Option<u64> {
    		if env_info.number >= self.ethash_params.eip155_transition {
    			Some(self.params().chain_id)
    		} else {
    			None
    		}
    	}

    	fn populate_from_parent(&self, header: &mut Header, parent: &Header, gas_floor_target: U256, gas_ceil_target: U256) {
    		let difficulty = self.calculate_difficulty(header, parent);
    		let gas_limit = {
    			let gas_limit = parent.gas_limit().clone();
    			let bound_divisor = self.ethash_params.gas_limit_bound_divisor;
    			let lower_limit = gas_limit - gas_limit / bound_divisor + 1.into();
    			let upper_limit = gas_limit + gas_limit / bound_divisor - 1.into();
    			let gas_limit = if gas_limit < gas_floor_target {
    				let gas_limit = min(gas_floor_target, upper_limit);
    				round_block_gas_limit(gas_limit, lower_limit, upper_limit)
    			} else if gas_limit > gas_ceil_target {
    				let gas_limit = max(gas_ceil_target, lower_limit);
    				round_block_gas_limit(gas_limit, lower_limit, upper_limit)
    			} else {
    				let total_lower_limit = max(lower_limit, gas_floor_target);
    				let total_upper_limit = min(upper_limit, gas_ceil_target);
    				let gas_limit = max(gas_floor_target, min(total_upper_limit,
    					lower_limit + (header.gas_used().clone() * 6.into() / 5.into()) / bound_divisor));
    				round_block_gas_limit(gas_limit, total_lower_limit, total_upper_limit)
    			};
    			// ensure that we are not violating protocol limits
    			debug_assert!(gas_limit >= lower_limit);
    			debug_assert!(gas_limit <= upper_limit);
    			gas_limit
    		};
    		header.set_difficulty(difficulty);
    		header.set_gas_limit(gas_limit);
    		if header.number() >= self.ethash_params.dao_hardfork_transition &&
    			header.number() <= self.ethash_params.dao_hardfork_transition + 9 {
    			header.set_extra_data(b"dao-hard-fork"[..].to_owned());
    		}
    		header.note_dirty();
    //		info!("ethash: populate_from_parent #{}: difficulty={} and gas_limit={}", header.number(), header.difficulty(), header.gas_limit());
    	}

    	fn on_new_block(&self, block: &mut ExecutedBlock) {
    		if block.fields().header.number() == self.ethash_params.dao_hardfork_transition {
    			// TODO: enable trigger function maybe?
    //			if block.fields().header.gas_limit() <= 4_000_000.into() {
    				let mut state = block.fields_mut().state;
    				for child in &self.ethash_params.dao_hardfork_accounts {
    					let b = state.balance(child);
    					state.transfer_balance(child, &self.ethash_params.dao_hardfork_beneficiary, &b, CleanupMode::NoEmpty);
    				}
    //			}
    		}
    	}

    	/// Apply the block reward on finalisation of the block.
    	/// This assumes that all uncles are valid uncles (i.e. of at least one generation before the current).
    	fn on_close_block(&self, block: &mut ExecutedBlock) {
    		let reward = self.ethash_params.block_reward;
    		let fields = block.fields_mut();

    		// Bestow block reward
    		fields.state.add_balance(fields.header.author(), &(reward + reward / U256::from(32) * U256::from(fields.uncles.len())), CleanupMode::NoEmpty);

    		// Bestow uncle rewards
    		let current_number = fields.header.number();
    		for u in fields.uncles.iter() {
    			fields.state.add_balance(u.author(), &(reward * U256::from(8 + u.number() - current_number) / U256::from(8)), CleanupMode::NoEmpty);
    		}

    		// Commit state so that we can actually figure out the state root.
    		if let Err(e) = fields.state.commit() {
    			warn!("Encountered error on state commit: {}", e);
    		}
    	}

    	fn verify_block_basic(&self, header: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> {
    		// check the seal fields.
    		if header.seal().len() != self.seal_fields() {
    			return Err(From::from(BlockError::InvalidSealArity(
    				Mismatch { expected: self.seal_fields(), found: header.seal().len() }
    			)));
    		}
    		UntrustedRlp::new(&header.seal()[0]).as_val::<H256>()?;
    		UntrustedRlp::new(&header.seal()[1]).as_val::<H64>()?;

    		// TODO: consider removing these lines.
    		let min_difficulty = self.ethash_params.minimum_difficulty;
    		if header.difficulty() < &min_difficulty {
    			return Err(From::from(BlockError::DifficultyOutOfBounds(OutOfBounds { min: Some(min_difficulty), max: None, found: header.difficulty().clone() })))
    		}

    		let difficulty = Ethash::boundary_to_difficulty(&H256(quick_get_difficulty(
    			&header.bare_hash().0,
    			header.nonce().low_u64(),
    			&header.mix_hash().0
    		)));
    		if &difficulty < header.difficulty() {
    			return Err(From::from(BlockError::InvalidProofOfWork(OutOfBounds { min: Some(header.difficulty().clone()), max: None, found: difficulty })));
    		}

    		if header.number() >= self.ethash_params.dao_hardfork_transition &&
    			header.number() <= self.ethash_params.dao_hardfork_transition + 9 &&
    			header.extra_data()[..] != b"dao-hard-fork"[..] {
    			return Err(From::from(BlockError::ExtraDataOutOfBounds(OutOfBounds { min: None, max: None, found: 0 })));
    		}

    		if header.gas_limit() > &0x7fffffffffffffffu64.into() {
    			return Err(From::from(BlockError::InvalidGasLimit(OutOfBounds { min: None, max: Some(0x7fffffffffffffffu64.into()), found: header.gas_limit().clone() })));
    		}

    		Ok(())
    	}

    	fn verify_block_unordered(&self, header: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> {
    		if header.seal().len() != self.seal_fields() {
    			return Err(From::from(BlockError::InvalidSealArity(
    				Mismatch { expected: self.seal_fields(), found: header.seal().len() }
    			)));
    		}
    		let result = self.pow.compute_light(header.number() as u64, &header.bare_hash().0, header.nonce().low_u64());
    		let mix = H256(result.mix_hash);
    		let difficulty = Ethash::boundary_to_difficulty(&H256(result.value));
    		trace!(target: "miner", "num: {}, seed: {}, h: {}, non: {}, mix: {}, res: {}" , header.number() as u64, H256(slow_get_seedhash(header.number() as u64)), header.bare_hash(), header.nonce().low_u64(), H256(result.mix_hash), H256(result.value));
    		if mix != header.mix_hash() {
    			return Err(From::from(BlockError::MismatchedH256SealElement(Mismatch { expected: mix, found: header.mix_hash() })));
    		}
    		if &difficulty < header.difficulty() {
    			return Err(From::from(BlockError::InvalidProofOfWork(OutOfBounds { min: Some(header.difficulty().clone()), max: None, found: difficulty })));
    		}
    		Ok(())
    	}

    	fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> {
    		// we should not calculate difficulty for genesis blocks
    		if header.number() == 0 {
    			return Err(From::from(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() })));
    		}

    		// Check difficulty is correct given the two timestamps.
    		let expected_difficulty = self.calculate_difficulty(header, parent);
    		if header.difficulty() != &expected_difficulty {
    			return Err(From::from(BlockError::InvalidDifficulty(Mismatch { expected: expected_difficulty, found: header.difficulty().clone() })))
    		}
    		let gas_limit_divisor = self.ethash_params.gas_limit_bound_divisor;
    		let min_gas = parent.gas_limit().clone() - parent.gas_limit().clone() / gas_limit_divisor;
    		let max_gas = parent.gas_limit().clone() + parent.gas_limit().clone() / gas_limit_divisor;
    		if header.gas_limit() <= &min_gas || header.gas_limit() >= &max_gas {
    			return Err(From::from(BlockError::InvalidGasLimit(OutOfBounds { min: Some(min_gas), max: Some(max_gas), found: header.gas_limit().clone() })));
    		}
    		Ok(())
    	}

    	fn verify_transaction_basic(&self, t: &UnverifiedTransaction, header: &Header) -> result::Result<(), Error> {
    		if header.number() >= self.ethash_params.homestead_transition {
    			t.check_low_s()?;
    		}

    		if let Some(n) = t.network_id() {
    			if header.number() < self.ethash_params.eip155_transition || n != self.params().chain_id {
    				return Err(TransactionError::InvalidNetworkId.into())
    			}
    		}

    		Ok(())
    	}
    }

    // Try to round gas_limit a bit so that:
    // 1) it will still be in desired range
    // 2) it will be a nearest (with tendency to increase) multiple of PARITY_GAS_LIMIT_DETERMINANT
    fn round_block_gas_limit(gas_limit: U256, lower_limit: U256, upper_limit: U256) -> U256 {
    	let increased_gas_limit = gas_limit + (PARITY_GAS_LIMIT_DETERMINANT - gas_limit % PARITY_GAS_LIMIT_DETERMINANT);
    	if increased_gas_limit > upper_limit {
    		let decreased_gas_limit = increased_gas_limit - PARITY_GAS_LIMIT_DETERMINANT;
    		if decreased_gas_limit < lower_limit {
    			gas_limit
    		} else {
    			decreased_gas_limit
    		}
    	} else {
    		increased_gas_limit
    	}
    }

    #[cfg_attr(feature="dev", allow(wrong_self_convention))]
    impl Ethash {
    	fn calculate_difficulty(&self, header: &Header, parent: &Header) -> U256 {
    		const EXP_DIFF_PERIOD: u64 = 100000;
    		if header.number() == 0 {
    			panic!("Can't calculate genesis block difficulty");
    		}

    		let min_difficulty = self.ethash_params.minimum_difficulty;
    		let difficulty_hardfork = header.number() >= self.ethash_params.difficulty_hardfork_transition;
    		let difficulty_bound_divisor = match difficulty_hardfork {
    			true => self.ethash_params.difficulty_hardfork_bound_divisor,
    			false => self.ethash_params.difficulty_bound_divisor,
    		};
    		let duration_limit = self.ethash_params.duration_limit;
    		let frontier_limit = self.ethash_params.homestead_transition;

    		let mut target = if header.number() < frontier_limit {
    			if header.timestamp() >= parent.timestamp() + duration_limit {
    				parent.difficulty().clone() - (parent.difficulty().clone() / difficulty_bound_divisor)
    			} else {
    				parent.difficulty().clone() + (parent.difficulty().clone() / difficulty_bound_divisor)
    			}
    		}
    		else {
    			trace!(target: "ethash", "Calculating difficulty parent.difficulty={}, header.timestamp={}, parent.timestamp={}", parent.difficulty(), header.timestamp(), parent.timestamp());
    			//block_diff = parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99)
    			let diff_inc = (header.timestamp() - parent.timestamp()) / self.ethash_params.difficulty_increment_divisor;
    			if diff_inc <= 1 {
    				parent.difficulty().clone() + parent.difficulty().clone() / From::from(difficulty_bound_divisor) * From::from(1 - diff_inc)
    			} else {
    				parent.difficulty().clone() - parent.difficulty().clone() / From::from(difficulty_bound_divisor) * From::from(min(diff_inc - 1, 99))
    			}
    		};
    		target = max(min_difficulty, target);
    		if header.number() < self.ethash_params.bomb_defuse_transition {
    			if header.number() < self.ethash_params.ecip1010_pause_transition {
    				let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize;
    				if period > 1 {
    					target = max(min_difficulty, target + (U256::from(1) << (period - 2)));
    				}
    			}
    			else if header.number() < self.ethash_params.ecip1010_continue_transition {
    				let fixed_difficulty = ((self.ethash_params.ecip1010_pause_transition / EXP_DIFF_PERIOD) - 2) as usize;
    				target = max(min_difficulty, target + (U256::from(1) << fixed_difficulty));
    			}
    			else {
    				let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize;
    				let delay = ((self.ethash_params.ecip1010_continue_transition - self.ethash_params.ecip1010_pause_transition) / EXP_DIFF_PERIOD) as usize;
    				target = max(min_difficulty, target + (U256::from(1) << (period - delay - 2)));
    			}
    		}
    		target
    	}

    	/// Convert an Ethash boundary to its original difficulty. Basically just `f(x) = 2^256 / x`.
    	pub fn boundary_to_difficulty(boundary: &H256) -> U256 {
    		let d = U256::from(*boundary);
    		if d <= U256::one() {
    			U256::max_value()
    		} else {
    			((U256::one() << 255) / d) << 1
    		}
    	}

    	/// Convert an Ethash difficulty to the target boundary. Basically just `f(x) = 2^256 / x`.
    	pub fn difficulty_to_boundary(difficulty: &U256) -> H256 {
    		if *difficulty <= U256::one() {
    			U256::max_value().into()
    		} else {
    			(((U256::one() << 255) / *difficulty) << 1).into()
    		}
    	}
    }

    impl Header {
    	/// Get the none field of the header.
    	pub fn nonce(&self) -> H64 {
    		rlp::decode(&self.seal()[1])
    	}

    	/// Get the mix hash field of the header.
    	pub fn mix_hash(&self) -> H256 {
    		rlp::decode(&self.seal()[0])
    	}

    	/// Set the nonce and mix hash fields of the header.
    	pub fn set_nonce_and_mix_hash(&mut self, nonce: &H64, mix_hash: &H256) {
    		self.set_seal(vec![rlp::encode(mix_hash).to_vec(), rlp::encode(nonce).to_vec()]);
    	}
    }

    #[cfg(test)]
    mod tests {
    	use util::*;
    	use block::*;
    	use tests::helpers::*;
    	use engines::Engine;
    	use env_info::EnvInfo;
    	use error::{BlockError, Error};
    	use header::Header;
    	use super::super::{new_morden, new_homestead_test};
    	use super::{Ethash, EthashParams, PARITY_GAS_LIMIT_DETERMINANT};
    	use rlp;

    	#[test]
    	fn on_close_block() {
    		let spec = new_morden();
    		let engine = &*spec.engine;
    		let genesis_header = spec.genesis_header();
    		let mut db_result = get_temp_state_db();
    		let db = spec.ensure_db_good(db_result.take(), &Default::default()).unwrap();
    		let last_hashes = Arc::new(vec![genesis_header.hash()]);
    		let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![]).unwrap();
    		let b = b.close();
    		assert_eq!(b.state().balance(&Address::zero()), U256::from_str("4563918244f40000").unwrap());
    	}

    	#[test]
    	fn on_close_block_with_uncle() {
    		let spec = new_morden();
    		let engine = &*spec.engine;
    		let genesis_header = spec.genesis_header();
    		let mut db_result = get_temp_state_db();
    		let db = spec.ensure_db_good(db_result.take(), &Default::default()).unwrap();
    		let last_hashes = Arc::new(vec![genesis_header.hash()]);
    		let mut b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![]).unwrap();
    		let mut uncle = Header::new();
    		let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
    		uncle.set_author(uncle_author);
    		b.push_uncle(uncle).unwrap();

    		let b = b.close();
    		assert_eq!(b.state().balance(&Address::zero()), "478eae0e571ba000".into());
    		assert_eq!(b.state().balance(&uncle_author), "3cb71f51fc558000".into());
    	}

    	#[test]
    	fn has_valid_metadata() {
    		let engine = new_morden().engine;
    		assert!(!engine.name().is_empty());
    		assert!(engine.version().major >= 1);
    	}

    	#[test]
    	fn can_return_schedule() {
    		let engine = new_morden().engine;
    		let schedule = engine.schedule(&EnvInfo {
    			number: 10000000,
    			author: 0.into(),
    			timestamp: 0,
    			difficulty: 0.into(),
    			last_hashes: Arc::new(vec![]),
    			gas_used: 0.into(),
    			gas_limit: 0.into(),
    		});

    		assert!(schedule.stack_limit > 0);

    		let schedule = engine.schedule(&EnvInfo {
    			number: 100,
    			author: 0.into(),
    			timestamp: 0,
    			difficulty: 0.into(),
    			last_hashes: Arc::new(vec![]),
    			gas_used: 0.into(),
    			gas_limit: 0.into(),
    		});

    		assert!(!schedule.have_delegate_call);
    	}

    	#[test]
    	fn can_do_seal_verification_fail() {
    		let engine = new_morden().engine;
    		//let engine = Ethash::new_test(new_morden());
    		let header: Header = Header::default();

    		let verify_result = engine.verify_block_basic(&header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::InvalidSealArity(_))) => {},
    			Err(_) => { panic!("should be block seal-arity mismatch error (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_do_difficulty_verification_fail() {
    		let engine = new_morden().engine;
    		let mut header: Header = Header::default();
    		header.set_seal(vec![rlp::encode(&H256::zero()).to_vec(), rlp::encode(&H64::zero()).to_vec()]);

    		let verify_result = engine.verify_block_basic(&header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::DifficultyOutOfBounds(_))) => {},
    			Err(_) => { panic!("should be block difficulty error (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_do_proof_of_work_verification_fail() {
    		let engine = new_morden().engine;
    		let mut header: Header = Header::default();
    		header.set_seal(vec![rlp::encode(&H256::zero()).to_vec(), rlp::encode(&H64::zero()).to_vec()]);
    		header.set_difficulty(U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffaaaaaaaaaaaaaaaaaaaa").unwrap());

    		let verify_result = engine.verify_block_basic(&header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::InvalidProofOfWork(_))) => {},
    			Err(_) => { panic!("should be invalid proof of work error (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_do_seal_unordered_verification_fail() {
    		let engine = new_morden().engine;
    		let header: Header = Header::default();

    		let verify_result = engine.verify_block_unordered(&header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::InvalidSealArity(_))) => {},
    			Err(_) => { panic!("should be block seal-arity mismatch error (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_do_seal256_verification_fail() {
    		let engine = new_morden().engine;
    		let mut header: Header = Header::default();
    		header.set_seal(vec![rlp::encode(&H256::zero()).to_vec(), rlp::encode(&H64::zero()).to_vec()]);
    		let verify_result = engine.verify_block_unordered(&header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::MismatchedH256SealElement(_))) => {},
    			Err(_) => { panic!("should be invalid 256-bit seal fail (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_do_proof_of_work_unordered_verification_fail() {
    		let engine = new_morden().engine;
    		let mut header: Header = Header::default();
    		header.set_seal(vec![rlp::encode(&H256::from("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d")).to_vec(), rlp::encode(&H64::zero()).to_vec()]);
    		header.set_difficulty(U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffaaaaaaaaaaaaaaaaaaaa").unwrap());

    		let verify_result = engine.verify_block_unordered(&header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::InvalidProofOfWork(_))) => {},
    			Err(_) => { panic!("should be invalid proof-of-work fail (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_verify_block_family_genesis_fail() {
    		let engine = new_morden().engine;
    		let header: Header = Header::default();
    		let parent_header: Header = Header::default();

    		let verify_result = engine.verify_block_family(&header, &parent_header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::RidiculousNumber(_))) => {},
    			Err(_) => { panic!("should be invalid block number fail (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_verify_block_family_difficulty_fail() {
    		let engine = new_morden().engine;
    		let mut header: Header = Header::default();
    		header.set_number(2);
    		let mut parent_header: Header = Header::default();
    		parent_header.set_number(1);

    		let verify_result = engine.verify_block_family(&header, &parent_header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::InvalidDifficulty(_))) => {},
    			Err(_) => { panic!("should be invalid difficulty fail (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn can_verify_block_family_gas_fail() {
    		let engine = new_morden().engine;
    		let mut header: Header = Header::default();
    		header.set_number(2);
    		header.set_difficulty(U256::from_str("0000000000000000000000000000000000000000000000000000000000020000").unwrap());
    		let mut parent_header: Header = Header::default();
    		parent_header.set_number(1);

    		let verify_result = engine.verify_block_family(&header, &parent_header, None);

    		match verify_result {
    			Err(Error::Block(BlockError::InvalidGasLimit(_))) => {},
    			Err(_) => { panic!("should be invalid difficulty fail (got {:?})", verify_result); },
    			_ => { panic!("Should be error, got Ok"); },
    		}
    	}

    	#[test]
    	fn test_difficulty_to_boundary() {
    		// result of f(0) is undefined, so do not assert the result
    		let _ = Ethash::difficulty_to_boundary(&U256::from(0));
    		assert_eq!(Ethash::difficulty_to_boundary(&U256::from(1)), H256::from(U256::max_value()));
    		assert_eq!(Ethash::difficulty_to_boundary(&U256::from(2)), H256::from_str("8000000000000000000000000000000000000000000000000000000000000000").unwrap());
    		assert_eq!(Ethash::difficulty_to_boundary(&U256::from(4)), H256::from_str("4000000000000000000000000000000000000000000000000000000000000000").unwrap());
    		assert_eq!(Ethash::difficulty_to_boundary(&U256::from(32)), H256::from_str("0800000000000000000000000000000000000000000000000000000000000000").unwrap());
    	}

    	#[test]
    	fn difficulty_frontier() {
    		let spec = new_homestead_test();
    		let ethparams = get_default_ethash_params();
    		let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new());

    		let mut parent_header = Header::default();
    		parent_header.set_number(1000000);
    		parent_header.set_difficulty(U256::from_str("b69de81a22b").unwrap());
    		parent_header.set_timestamp(1455404053);
    		let mut header = Header::default();
    		header.set_number(parent_header.number() + 1);
    		header.set_timestamp(1455404058);

    		let difficulty = ethash.calculate_difficulty(&header, &parent_header);
    		assert_eq!(U256::from_str("b6b4bbd735f").unwrap(), difficulty);
    	}

    	#[test]
    	fn difficulty_homestead() {
    		let spec = new_homestead_test();
    		let ethparams = get_default_ethash_params();
    		let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new());

    		let mut parent_header = Header::default();
    		parent_header.set_number(1500000);
    		parent_header.set_difficulty(U256::from_str("1fd0fd70792b").unwrap());
    		parent_header.set_timestamp(1463003133);
    		let mut header = Header::default();
    		header.set_number(parent_header.number() + 1);
    		header.set_timestamp(1463003177);

    		let difficulty = ethash.calculate_difficulty(&header, &parent_header);
    		assert_eq!(U256::from_str("1fc50f118efe").unwrap(), difficulty);
    	}

    	#[test]
    	fn difficulty_classic_bomb_delay() {
    		let spec = new_homestead_test();
    		let ethparams = EthashParams {
    			ecip1010_pause_transition: 3000000,
    			..get_default_ethash_params()
    		};
    		let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new());

    		let mut parent_header = Header::default();
    		parent_header.set_number(3500000);
    		parent_header.set_difficulty(U256::from_str("6F62EAF8D3C").unwrap());
    		parent_header.set_timestamp(1452838500);
    		let mut header = Header::default();
    		header.set_number(parent_header.number() + 1);

    		header.set_timestamp(parent_header.timestamp() + 20);
    		assert_eq!(
    			U256::from_str("6F55FE9B74B").unwrap(),
    			ethash.calculate_difficulty(&header, &parent_header)
    		);
    		header.set_timestamp(parent_header.timestamp() + 5);
    		assert_eq!(
    			U256::from_str("6F71D75632D").unwrap(),
    			ethash.calculate_difficulty(&header, &parent_header)
    		);
    		header.set_timestamp(parent_header.timestamp() + 80);
    		assert_eq!(
    			U256::from_str("6F02746B3A5").unwrap(),
    			ethash.calculate_difficulty(&header, &parent_header)
    		);
    	}

    	#[test]
    	fn test_difficulty_bomb_continue() {
    		let spec = new_homestead_test();
    		let ethparams = EthashParams {
    			ecip1010_pause_transition: 3000000,
    			ecip1010_continue_transition: 5000000,
    			..get_default_ethash_params()
    		};
    		let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new());

    		let mut parent_header = Header::default();
    		parent_header.set_number(5000102);
    		parent_header.set_difficulty(U256::from_str("14944397EE8B").unwrap());
    		parent_header.set_timestamp(1513175023);
    		let mut header = Header::default();
    		header.set_number(parent_header.number() + 1);
    		header.set_timestamp(parent_header.timestamp() + 6);
    		assert_eq!(
    			U256::from_str("1496E6206188").unwrap(),
    			ethash.calculate_difficulty(&header, &parent_header)
    		);
    		parent_header.set_number(5100123);
    		parent_header.set_difficulty(U256::from_str("14D24B39C7CF").unwrap());
    		parent_header.set_timestamp(1514609324);
    		header.set_number(parent_header.number() + 1);
    		header.set_timestamp(parent_header.timestamp() + 41);
    		assert_eq!(
    			U256::from_str("14CA9C5D9227").unwrap(),
    			ethash.calculate_difficulty(&header, &parent_header)
    		);
    		parent_header.set_number(6150001);
    		parent_header.set_difficulty(U256::from_str("305367B57227").unwrap());
    		parent_header.set_timestamp(1529664575);
    		header.set_number(parent_header.number() + 1);
    		header.set_timestamp(parent_header.timestamp() + 105);
    		assert_eq!(
    			U256::from_str("309D09E0C609").unwrap(),
    			ethash.calculate_difficulty(&header, &parent_header)
    		);
    		parent_header.set_number(8000000);
    		parent_header.set_difficulty(U256::from_str("1180B36D4CE5B6A").unwrap());
    		parent_header.set_timestamp(1535431724);
    		header.set_number(parent_header.number() + 1);
    		header.set_timestamp(parent_header.timestamp() + 420);
    		assert_eq!(
    			U256::from_str("5126FFD5BCBB9E7").unwrap(),
    			ethash.calculate_difficulty(&header, &parent_header)
    		);
    	}

    	#[test]
    	fn gas_limit_is_multiple_of_determinant() {
    		let spec = new_homestead_test();
    		let ethash = Ethash::new(spec.params, get_default_ethash_params(), BTreeMap::new());
    		let mut parent = Header::new();
    		let mut header = Header::new();
    		header.set_number(1);

    		// this test will work for this constant only
    		assert_eq!(PARITY_GAS_LIMIT_DETERMINANT, U256::from(37));

    		// when parent.gas_limit < gas_floor_target:
    		parent.set_gas_limit(U256::from(50_000));
    		ethash.populate_from_parent(&mut header, &parent, U256::from(100_000), U256::from(200_000));
    		assert_eq!(*header.gas_limit(), U256::from(50_024));

    		// when parent.gas_limit > gas_ceil_target:
    		parent.set_gas_limit(U256::from(250_000));
    		ethash.populate_from_parent(&mut header, &parent, U256::from(100_000), U256::from(200_000));
    		assert_eq!(*header.gas_limit(), U256::from(249_787));

    		// when parent.gas_limit is in miner's range
    		header.set_gas_used(U256::from(150_000));
    		parent.set_gas_limit(U256::from(150_000));
    		ethash.populate_from_parent(&mut header, &parent, U256::from(100_000), U256::from(200_000));
    		assert_eq!(*header.gas_limit(), U256::from(150_035));

    		// when parent.gas_limit is in miner's range
    		// && we can NOT increase it to be multiple of constant
    		header.set_gas_used(U256::from(150_000));
    		parent.set_gas_limit(U256::from(150_000));
    		ethash.populate_from_parent(&mut header, &parent, U256::from(100_000), U256::from(150_002));
    		assert_eq!(*header.gas_limit(), U256::from(149_998));

    		// when parent.gas_limit is in miner's range
    		// && we can NOT increase it to be multiple of constant
    		// && we can NOT decrease it to be multiple of constant
    		header.set_gas_used(U256::from(150_000));
    		parent.set_gas_limit(U256::from(150_000));
    		ethash.populate_from_parent(&mut header, &parent, U256::from(150_000), U256::from(150_002));
    		assert_eq!(*header.gas_limit(), U256::from(150_002));
    	}
    }

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)