stack_epic_core 3.6.0

Chain implementation for epic, a simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format.
Documentation
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
// Copyright 2018 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! core consensus.rs tests (separated to de-clutter consensus.rs)
use epic_core as core;

use self::core::consensus::*;
use self::core::core::block::HeaderVersion;
use self::core::global;
use self::core::pow::{Difficulty, PoWType};
use chrono::prelude::Utc;
use std::fmt::{self, Display};
use self::core::core::hash::ZERO_HASH;

/// Last n blocks for difficulty calculation purposes
/// (copied from stats in server crate)
#[derive(Clone, Debug)]
pub struct DiffBlock {
	/// Block number (can be negative for a new chain)
	pub block_number: i64,
	/// Block network difficulty
	pub difficulty: u64,
	/// Time block was found (epoch seconds)
	pub time: u64,
	/// Duration since previous block (epoch seconds)
	pub duration: u64,
}

/// Stats on the last WINDOW blocks and the difficulty calculation
/// (Copied from stats in server crate)
#[derive(Clone)]
pub struct DiffStats {
	/// latest height
	pub height: u64,
	/// Last WINDOW block data
	pub last_blocks: Vec<DiffBlock>,
	/// Average block time for last WINDOW blocks
	pub average_block_time: u64,
	/// Average WINDOW difficulty
	pub average_difficulty: u64,
	/// WINDOW size
	pub window_size: u64,
	/// Block time sum
	pub block_time_sum: u64,
	/// Block diff sum
	pub block_diff_sum: u64,
	/// latest ts
	pub latest_ts: u64,
	/// earliest ts
	pub earliest_ts: u64,
	/// ts delta
	pub ts_delta: u64,
}

impl Display for DiffBlock {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let output = format!(
			"Block Number: {} Difficulty: {}, Time: {}, Duration: {}",
			self.block_number, self.difficulty, self.time, self.duration
		);
		Display::fmt(&output, f)
	}
}

// Builds an iterator for next difficulty calculation with the provided
// constant time interval, difficulty and total length.
fn repeat(interval: u64, diff: HeaderInfo, len: u64, cur_time: Option<u64>) -> Vec<HeaderInfo> {
	let cur_time = match cur_time {
		Some(t) => t,
		None => Utc::now().timestamp() as u64,
	};
	// watch overflow here, length shouldn't be ridiculous anyhow
	assert!(len < std::usize::MAX as u64);
	let diffs = vec![diff.difficulty.clone(); len as usize];
	let times = (0..(len as usize)).map(|n| n * interval as usize).rev();
	let pairs = times.zip(diffs.iter());
	pairs
		.map(|(t, d)| {
			HeaderInfo::new(
				ZERO_HASH,
				cur_time + t as u64,
				d.clone(),
				diff.secondary_scaling,
				diff.is_secondary,
				interval,
			)
		})
		.collect::<Vec<_>>()
}

// Creates a new chain with a genesis at a simulated difficulty
fn create_chain_sim(diff: u64) -> Vec<(HeaderInfo, DiffStats)> {
	println!(
		"adding create: {}, {}",
		Utc::now().timestamp(),
		Difficulty::from_num(diff)
	);
	let return_vec = vec![HeaderInfo::from_ts_diff(
		Utc::now().timestamp() as u64,
		Difficulty::from_num(diff),
	)];
	let diff_stats = get_diff_stats(&return_vec);
	vec![(
		HeaderInfo::from_ts_diff(Utc::now().timestamp() as u64, Difficulty::from_num(diff)),
		diff_stats,
	)]
}

fn get_diff_stats(chain_sim: &Vec<HeaderInfo>) -> DiffStats {
	// Fill out some difficulty stats for convenience
	let diff_iter = chain_sim.clone();
	let last_blocks: Vec<HeaderInfo> =
		global::difficulty_data_to_vector(diff_iter.iter().cloned(), DIFFICULTY_ADJUST_WINDOW);

	let mut last_time = last_blocks[0].timestamp;
	let tip_height = chain_sim.len();
	let earliest_block_height = tip_height as i64 - last_blocks.len() as i64;

	let earliest_ts = last_blocks[0].timestamp;
	let latest_ts = last_blocks[last_blocks.len() - 1].timestamp;

	let mut i = 1;

	let sum_blocks: Vec<HeaderInfo> =
		global::difficulty_data_to_vector(diff_iter.iter().cloned(), DIFFICULTY_ADJUST_WINDOW)
			.into_iter()
			.take(DIFFICULTY_ADJUST_WINDOW as usize)
			.collect();

	let sum_entries: Vec<DiffBlock> = sum_blocks
		.iter()
		//.skip(1)
		.map(|n| {
			let dur = n.timestamp - last_time;
			let height = earliest_block_height + i + 1;
			i += 1;
			last_time = n.timestamp;
			DiffBlock {
				block_number: height,
				difficulty: n.difficulty.to_num(PoWType::Cuckatoo),
				time: n.timestamp,
				duration: dur,
			}
		})
		.collect();

	let block_time_sum = sum_entries.iter().fold(0, |sum, t| sum + t.duration);
	let block_diff_sum = sum_entries.iter().fold(0, |sum, d| sum + d.difficulty);

	i = 1;
	last_time = last_blocks[0].clone().timestamp;

	let diff_entries: Vec<DiffBlock> = last_blocks
		.iter()
		.skip(1)
		.map(|n| {
			let dur = n.timestamp - last_time;
			let height = earliest_block_height + i;
			i += 1;
			last_time = n.timestamp;
			DiffBlock {
				block_number: height,
				difficulty: n.difficulty.to_num(PoWType::Cuckatoo),
				time: n.timestamp,
				duration: dur,
			}
		})
		.collect();

	DiffStats {
		height: tip_height as u64,
		last_blocks: diff_entries,
		average_block_time: block_time_sum / (DIFFICULTY_ADJUST_WINDOW),
		average_difficulty: block_diff_sum / (DIFFICULTY_ADJUST_WINDOW),
		window_size: DIFFICULTY_ADJUST_WINDOW,
		block_time_sum: block_time_sum,
		block_diff_sum: block_diff_sum,
		latest_ts: latest_ts,
		earliest_ts: earliest_ts,
		ts_delta: latest_ts - earliest_ts,
	}
}

// Adds another 'block' to the iterator, so to speak, with difficulty calculated
// from the difficulty adjustment at interval seconds from the previous block
fn add_block(
	interval: u64,
	chain_sim: Vec<(HeaderInfo, DiffStats)>,
) -> Vec<(HeaderInfo, DiffStats)> {
	let mut ret_chain_sim = chain_sim.clone();
	let mut return_chain: Vec<HeaderInfo> = chain_sim.clone().iter().map(|e| e.0.clone()).collect();
	// get last interval
	let diff = next_difficulty(1, PoWType::Cuckatoo, return_chain.clone());
	let last_elem = chain_sim.first().unwrap().clone().0;
	let time = last_elem.timestamp + interval;
	return_chain.insert(0, HeaderInfo::from_ts_diff(time, diff.difficulty.clone()));
	let diff_stats = get_diff_stats(&return_chain);
	ret_chain_sim.insert(
		0,
		(HeaderInfo::from_ts_diff(time, diff.difficulty), diff_stats),
	);
	ret_chain_sim
}

// Adds another n 'blocks' to the iterator, with difficulty calculated
fn add_block_repeated(
	interval: u64,
	chain_sim: Vec<(HeaderInfo, DiffStats)>,
	iterations: usize,
) -> Vec<(HeaderInfo, DiffStats)> {
	let mut return_chain = chain_sim.clone();
	for _ in 0..iterations {
		return_chain = add_block(interval, return_chain.clone());
	}
	return_chain
}

// Prints the contents of the iterator and its difficulties.. useful for
// tweaking
fn print_chain_sim(chain_sim: Vec<(HeaderInfo, DiffStats)>) {
	let mut chain_sim = chain_sim.clone();
	chain_sim.reverse();
	let mut last_time = 0;
	let mut first = true;
	println!("Constants");
	println!("DIFFICULTY_ADJUST_WINDOW: {}", DIFFICULTY_ADJUST_WINDOW);
	println!("BLOCK_TIME_WINDOW: {}", BLOCK_TIME_WINDOW);
	println!("CLAMP_FACTOR: {}", CLAMP_FACTOR);
	println!("DAMP_FACTOR: {}", DIFFICULTY_DAMP_FACTOR);
	chain_sim.iter().enumerate().for_each(|(i, b)| {
		let block = b.0.clone();
		let stats = b.1.clone();
		if first {
			last_time = block.timestamp;
			first = false;
		}
		println!(
			"Height: {}, Time: {}, Interval: {}, Network difficulty:{}, Average Block Time: {}, Average Difficulty {}, Block Time Sum: {}, Block Diff Sum: {}, Latest Timestamp: {}, Earliest Timestamp: {}, Timestamp Delta: {}",
			i,
			block.timestamp,
			block.timestamp - last_time,
			block.difficulty,
			stats.average_block_time,
			stats.average_difficulty,
			stats.block_time_sum,
			stats.block_diff_sum,
			stats.latest_ts,
			stats.earliest_ts,
			stats.ts_delta,
		);
		let mut sb = stats.last_blocks.clone();
		sb.reverse();
		for i in sb {
			println!("   {}", i);
		}
		last_time = block.timestamp;
	});
}

fn repeat_offs(from: u64, interval: u64, diff: u64, len: u64) -> Vec<HeaderInfo> {
	repeat(
		interval,
		HeaderInfo::from_ts_diff(1, Difficulty::from_num(diff)),
		len,
		Some(from),
	)
}

/// Checks different next_target adjustments and difficulty boundaries
#[test]
fn adjustment_scenarios() {
	// Use production parameters for genesis diff
	global::set_mining_mode(global::ChainTypes::Mainnet);

	// Genesis block with initial diff
	let chain_sim = create_chain_sim(global::initial_block_difficulty());
	// Scenario 1) Hash power is massively over estimated, first block takes an hour
	let chain_sim = add_block_repeated(3600, chain_sim, 2);
	let chain_sim = add_block_repeated(1800, chain_sim, 2);
	let chain_sim = add_block_repeated(900, chain_sim, 10);
	let chain_sim = add_block_repeated(450, chain_sim, 30);
	let chain_sim = add_block_repeated(400, chain_sim, 30);
	let chain_sim = add_block_repeated(300, chain_sim, 30);

	println!("*********************************************************");
	println!("Scenario 1) Grossly over-estimated genesis difficulty ");
	println!("*********************************************************");
	print_chain_sim(chain_sim);
	println!("*********************************************************");

	// Under-estimated difficulty
	let chain_sim = create_chain_sim(global::initial_block_difficulty());
	let chain_sim = add_block_repeated(1, chain_sim, 5);
	let chain_sim = add_block_repeated(20, chain_sim, 5);
	let chain_sim = add_block_repeated(30, chain_sim, 20);

	println!("*********************************************************");
	println!("Scenario 2) Grossly under-estimated genesis difficulty ");
	println!("*********************************************************");
	print_chain_sim(chain_sim);
	println!("*********************************************************");
	let just_enough = (DIFFICULTY_ADJUST_WINDOW) as usize;

	// Steady difficulty for a good while, then a sudden drop
	let chain_sim = create_chain_sim(global::initial_block_difficulty());
	let chain_sim = add_block_repeated(60, chain_sim, just_enough as usize);
	let chain_sim = add_block_repeated(600, chain_sim, 60);

	println!("");
	println!("*********************************************************");
	println!("Scenario 3) Sudden drop in hashpower");
	println!("*********************************************************");
	print_chain_sim(chain_sim);
	println!("*********************************************************");

	// Sudden increase
	let chain_sim = create_chain_sim(global::initial_block_difficulty());
	let chain_sim = add_block_repeated(60, chain_sim, just_enough as usize);
	let chain_sim = add_block_repeated(10, chain_sim, 10);

	println!("");
	println!("*********************************************************");
	println!("Scenario 4) Sudden increase in hashpower");
	println!("*********************************************************");
	print_chain_sim(chain_sim);
	println!("*********************************************************");

	// Oscillations
	let chain_sim = create_chain_sim(global::initial_block_difficulty());
	let chain_sim = add_block_repeated(60, chain_sim, just_enough as usize);
	let chain_sim = add_block_repeated(10, chain_sim, 10);
	let chain_sim = add_block_repeated(60, chain_sim, 20);
	let chain_sim = add_block_repeated(10, chain_sim, 10);

	println!("");
	println!("*********************************************************");
	println!("Scenario 5) Oscillations in hashpower");
	println!("*********************************************************");
	print_chain_sim(chain_sim);
	println!("*********************************************************");
}

/// Checks different next_target adjustments and difficulty boundaries
#[test]
fn next_target_adjustment() {
	global::set_mining_mode(global::ChainTypes::AutomatedTesting);
	let cur_time = Utc::now().timestamp() as u64;
	let diff_min = Difficulty::min();

	// Check we don't get stuck on difficulty <= MIN_DIFFICULTY (at 4x faster blocks at least)
	let mut hi = HeaderInfo::from_diff_scaling(diff_min.clone(), AR_SCALE_DAMP_FACTOR as u32);
	hi.is_secondary = false;
	let hinext = next_difficulty(
		1,
		PoWType::Cuckatoo,
		repeat(
			BLOCK_TIME_SEC / 4,
			hi.clone(),
			DIFFICULTY_ADJUST_WINDOW,
			None,
		),
	);

	assert_ne!(
		hinext.difficulty.to_num(PoWType::Cuckatoo),
		diff_min.to_num(PoWType::Cuckatoo)
	);

	// Check we don't get stuck on scale MIN_DIFFICULTY, when primary frequency is too high
	assert_ne!(hinext.secondary_scaling, MIN_DIFFICULTY as u32);

	// just enough data, right interval, should stay constant
	let just_enough = DIFFICULTY_ADJUST_WINDOW + 1;
	hi.difficulty = Difficulty::from_num(10000);
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(BLOCK_TIME_SEC, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(10000).to_num(PoWType::Cuckatoo)
	);

	// check pre difficulty_data_to_vector effect on retargetting
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			vec![HeaderInfo::from_ts_diff(42, hi.difficulty)]
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(14913).to_num(PoWType::Cuckatoo)
	);

	// checking averaging works
	hi.difficulty = Difficulty::from_num(500);
	let sec = DIFFICULTY_ADJUST_WINDOW / 2;
	let mut s1 = repeat(BLOCK_TIME_SEC, hi.clone(), sec, Some(cur_time));
	let mut s2 = repeat_offs(
		cur_time + (sec * BLOCK_TIME_SEC) as u64,
		BLOCK_TIME_SEC,
		1500,
		DIFFICULTY_ADJUST_WINDOW / 2,
	);
	s2.append(&mut s1);
	assert_eq!(
		next_difficulty(1, PoWType::Cuckatoo, s2)
			.difficulty
			.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(1000).to_num(PoWType::Cuckatoo)
	);

	// too slow, diff goes down
	hi.difficulty = Difficulty::from_num(1000);
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(90, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(857).to_num(PoWType::Cuckatoo)
	);
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(120, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(750).to_num(PoWType::Cuckatoo)
	);

	// too fast, diff goes up
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(55, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(1028).to_num(PoWType::Cuckatoo)
	);
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(45, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(1090).to_num(PoWType::Cuckatoo)
	);
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(30, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(1200).to_num(PoWType::Cuckatoo)
	);

	// hitting lower time bound, should always get the same result below
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(0, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(1500).to_num(PoWType::Cuckatoo)
	);

	// hitting higher time bound, should always get the same result above
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(300, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(500).to_num(PoWType::Cuckatoo)
	);
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(400, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::from_num(500).to_num(PoWType::Cuckatoo)
	);

	// We should never drop below minimum
	hi.difficulty = Difficulty::zero();
	assert_eq!(
		next_difficulty(
			1,
			PoWType::Cuckatoo,
			repeat(90, hi.clone(), just_enough, None)
		)
		.difficulty
		.to_num(PoWType::Cuckatoo),
		Difficulty::min().to_num(PoWType::Cuckatoo)
	);
}

#[test]
fn test_secondary_pow_ratio() {
	// Tests for mainnet chain type.
	{
		global::set_mining_mode(global::ChainTypes::Mainnet);
		assert_eq!(global::is_floonet(), false);

		assert_eq!(secondary_pow_ratio(1), 90);
		assert_eq!(secondary_pow_ratio(89), 90);
		assert_eq!(secondary_pow_ratio(90), 90);
		assert_eq!(secondary_pow_ratio(91), 90);
		assert_eq!(secondary_pow_ratio(179), 90);
		assert_eq!(secondary_pow_ratio(180), 90);
		assert_eq!(secondary_pow_ratio(181), 90);

		let one_week = 60 * 24 * 7;
		assert_eq!(secondary_pow_ratio(one_week - 1), 90);
		assert_eq!(secondary_pow_ratio(one_week), 90);
		assert_eq!(secondary_pow_ratio(one_week + 1), 90);

		let two_weeks = one_week * 2;
		assert_eq!(secondary_pow_ratio(two_weeks - 1), 89);
		assert_eq!(secondary_pow_ratio(two_weeks), 89);
		assert_eq!(secondary_pow_ratio(two_weeks + 1), 89);

		let t4_fork_height = 64_000;
		assert_eq!(secondary_pow_ratio(t4_fork_height - 1), 85);
		assert_eq!(secondary_pow_ratio(t4_fork_height), 85);
		assert_eq!(secondary_pow_ratio(t4_fork_height + 1), 85);

		let one_year = one_week * 52;
		assert_eq!(secondary_pow_ratio(one_year), 45);

		let ninety_one_weeks = one_week * 91;
		assert_eq!(secondary_pow_ratio(ninety_one_weeks - 1), 12);
		assert_eq!(secondary_pow_ratio(ninety_one_weeks), 12);
		assert_eq!(secondary_pow_ratio(ninety_one_weeks + 1), 12);

		let two_year = one_year * 2;
		assert_eq!(secondary_pow_ratio(two_year - 1), 1);
		assert_eq!(secondary_pow_ratio(two_year), 0);
		assert_eq!(secondary_pow_ratio(two_year + 1), 0);
	}

	// Tests for testnet4 chain type (covers pre and post hardfork).
	{
		global::set_mining_mode(global::ChainTypes::Floonet);
		assert_eq!(global::is_floonet(), true);

		assert_eq!(secondary_pow_ratio(1), 90);
		assert_eq!(secondary_pow_ratio(89), 90);
		assert_eq!(secondary_pow_ratio(90), 90);
		assert_eq!(secondary_pow_ratio(91), 90);
		assert_eq!(secondary_pow_ratio(179), 90);
		assert_eq!(secondary_pow_ratio(180), 90);
		assert_eq!(secondary_pow_ratio(181), 90);

		let one_week = 60 * 24 * 7;
		assert_eq!(secondary_pow_ratio(one_week - 1), 90);
		assert_eq!(secondary_pow_ratio(one_week), 90);
		assert_eq!(secondary_pow_ratio(one_week + 1), 90);

		let two_weeks = one_week * 2;
		assert_eq!(secondary_pow_ratio(two_weeks - 1), 89);
		assert_eq!(secondary_pow_ratio(two_weeks), 89);
		assert_eq!(secondary_pow_ratio(two_weeks + 1), 89);

		let t4_fork_height = 64_000;
		assert_eq!(secondary_pow_ratio(t4_fork_height - 1), 85);
		assert_eq!(secondary_pow_ratio(t4_fork_height), 85);
		assert_eq!(secondary_pow_ratio(t4_fork_height + 1), 85);

		let one_year = one_week * 52;
		assert_eq!(secondary_pow_ratio(one_year), 45);

		let ninety_one_weeks = one_week * 91;
		assert_eq!(secondary_pow_ratio(ninety_one_weeks - 1), 12);
		assert_eq!(secondary_pow_ratio(ninety_one_weeks), 12);
		assert_eq!(secondary_pow_ratio(ninety_one_weeks + 1), 12);

		let two_year = one_year * 2;
		assert_eq!(secondary_pow_ratio(two_year - 1), 1);
		assert_eq!(secondary_pow_ratio(two_year), 0);
		assert_eq!(secondary_pow_ratio(two_year + 1), 0);
	}
}

#[test]
fn test_secondary_pow_scale() {
	let window = DIFFICULTY_ADJUST_WINDOW;
	let mut hi = HeaderInfo::from_diff_scaling(Difficulty::from_num(10), 100);

	// mainnet testing
	{
		global::set_mining_mode(global::ChainTypes::Mainnet);
		assert_eq!(global::is_floonet(), false);

		// all primary, factor should increase so it becomes easier to find a high
		// difficulty block
		hi.is_secondary = false;
		assert_eq!(
			secondary_pow_scaling(1, &(0..window).map(|_| hi.clone()).collect::<Vec<_>>()),
			108
		);
		// all secondary on 90%, factor should go down a bit
		hi.is_secondary = true;
		assert_eq!(
			secondary_pow_scaling(1, &(0..window).map(|_| hi.clone()).collect::<Vec<_>>()),
			99
		);
		// all secondary on 1%, factor should go down to bound (divide by 2)
		assert_eq!(
			secondary_pow_scaling(
				2 * YEAR_HEIGHT * 83 / 90,
				&(0..window).map(|_| hi.clone()).collect::<Vec<_>>()
			),
			50
		);
		// same as above, testing lowest bound
		let mut low_hi =
			HeaderInfo::from_diff_scaling(Difficulty::from_num(10), MIN_AR_SCALE as u32);
		low_hi.is_secondary = true;
		assert_eq!(
			secondary_pow_scaling(
				2 * YEAR_HEIGHT,
				&(0..window).map(|_| low_hi.clone()).collect::<Vec<_>>()
			),
			MIN_AR_SCALE as u32
		);
		// the right ratio of 95% secondary
		let mut primary_hi = HeaderInfo::from_diff_scaling(Difficulty::from_num(10), 50);
		primary_hi.is_secondary = false;
		assert_eq!(
			secondary_pow_scaling(
				1,
				&(0..(window / 10))
					.map(|_| primary_hi.clone())
					.chain((0..(window * 9 / 10)).map(|_| hi.clone()))
					.collect::<Vec<_>>()
			),
			95, // avg ar_scale of 10% * 50 + 90% * 100
		);
		// 95% secondary, should come down based on 97.5 average
		assert_eq!(
			secondary_pow_scaling(
				1,
				&(0..(window / 20))
					.map(|_| primary_hi.clone())
					.chain((0..(window * 95 / 100)).map(|_| hi.clone()))
					.collect::<Vec<_>>()
			),
			97
		);
		// 40% secondary, should come up based on 70 average
		assert_eq!(
			secondary_pow_scaling(
				1,
				&(0..(window * 6 / 10))
					.map(|_| primary_hi.clone())
					.chain((0..(window * 4 / 10)).map(|_| hi.clone()))
					.collect::<Vec<_>>()
			),
			73
		);
	}
}

#[test]
fn hard_forks() {
	global::set_mining_mode(global::ChainTypes::AutomatedTesting);
	assert!(!valid_header_version(199, HeaderVersion(6)));
	assert!(valid_header_version(200, HeaderVersion(7)));
	assert!(valid_header_version(YEAR_HEIGHT / 2 - 1, HeaderVersion(7)));
}

// #[test]
// fn hard_fork_2() {
// 	assert!(valid_header_version(0, 1));
// 	assert!(valid_header_version(10, 1));
// 	assert!(valid_header_version(10, 2));
// 	assert!(valid_header_version(250_000, 1));
// 	assert!(!valid_header_version(250_001, 1));
// 	assert!(!valid_header_version(500_000, 1));
// 	assert!(valid_header_version(250_001, 2));
// 	assert!(valid_header_version(500_000, 2));
// 	assert!(!valid_header_version(500_001, 2));
// }