Files
addr2line
adler
aead
aes
aes_gcm
aes_soft
ahash
aho_corasick
ansi_term
anyhow
approx
arrayref
arrayvec
asn1_der
asn1_der_derive
async_channel
async_executor
async_global_executor
async_io
async_lock
async_mutex
async_process
async_std
collections
fs
future
io
net
option
os
path
pin
result
rt
stream
string
sync
task
unit
vec
async_task
async_trait
asynchronous_codec
atomic
atomic_waker
atty
backtrace
base58
base64
base_x
bincode
bip39
bitflags
bitvec
blake2
blake2_rfc
blake2b_simd
blake2s_simd
blake3
block_buffer
block_cipher
block_padding
blocking
bs58
bstr
bumpalo
byte_slice_cast
byteorder
bytes
cache_padded
cfg_if
chacha20
chacha20poly1305
chrono
cid
cipher
clap
concurrent_queue
constant_time_eq
convert_case
cpp_demangle
cpuid_bool
cranelift_bforest
cranelift_codegen
cranelift_codegen_shared
cranelift_entity
cranelift_frontend
cranelift_native
cranelift_wasm
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
crunchy
crypto_mac
ct_logs
ctor
cuckoofilter
curve25519_dalek
data_encoding
data_encoding_macro
data_encoding_macro_internal
derive_more
digest
directories
directories_next
dirs_sys
dirs_sys_next
dns_parser
dyn_clonable
dyn_clonable_impl
dyn_clone
ed25519
ed25519_dalek
either
env_logger
environmental
erased_serde
errno
event_listener
exit_future
failure
failure_derive
fallible_iterator
fastrand
fdlimit
file_per_thread_logger
finality_grandpa
fixed_hash
flate2
fnv
fork_tree
form_urlencoded
frame_benchmarking
frame_benchmarking_cli
frame_executive
frame_metadata
frame_support
frame_support_procedural
frame_support_procedural_tools
frame_support_procedural_tools_derive
frame_system
frame_system_rpc_runtime_api
fs2
fs_swap
funty
futures
futures_channel
futures_core
futures_diagnose
futures_executor
futures_io
futures_lite
futures_macro
futures_rustls
futures_sink
futures_task
futures_timer
futures_util
async_await
compat
future
io
lock
sink
stream
task
generic_array
getrandom
ghash
gimli
globset
governance_os_node
governance_os_pallet_bylaws
governance_os_pallet_coin_voting
governance_os_pallet_compat
governance_os_pallet_conviction_voting
governance_os_pallet_organizations
governance_os_pallet_plcr_voting
governance_os_pallet_tokens
governance_os_primitives
governance_os_runtime
governance_os_support
h2
handlebars
hash256_std_hasher
hash_db
hashbrown
heck
hex
hex_fmt
hmac
hmac_drbg
http
http_body
httparse
httpdate
humantime
hyper
hyper_rustls
idna
if_watch
impl_codec
impl_serde
impl_trait_for_tuples
indexmap
inflector
cases
camelcase
case
classcase
kebabcase
pascalcase
screamingsnakecase
sentencecase
snakecase
tablecase
titlecase
traincase
numbers
deordinalize
ordinalize
string
constants
deconstantize
demodulize
pluralize
singularize
suffix
foreignkey
instant
integer_sqrt
intervalier
iovec
ip_network
ipnet
itertools
itoa
js_sys
jsonrpc_client_transports
jsonrpc_core
jsonrpc_core_client
jsonrpc_derive
jsonrpc_http_server
jsonrpc_ipc_server
jsonrpc_pubsub
jsonrpc_server_utils
jsonrpc_ws_server
keccak
kv_log_macro
kvdb
kvdb_memorydb
kvdb_rocksdb
lazy_static
lazycell
leb128
libc
libm
libp2p
libp2p_core
libp2p_core_derive
libp2p_deflate
libp2p_dns
libp2p_floodsub
libp2p_gossipsub
libp2p_identify
libp2p_kad
libp2p_mdns
libp2p_mplex
libp2p_noise
libp2p_ping
libp2p_plaintext
libp2p_pnet
libp2p_request_response
libp2p_swarm
libp2p_tcp
libp2p_uds
libp2p_wasm_ext
libp2p_websocket
libp2p_yamux
librocksdb_sys
libz_sys
linked_hash_map
linked_hash_set
linregress
lock_api
log
lru
maplit
matchers
matches
matrixmultiply
memchr
memmap2
memoffset
memory_db
memory_units
merlin
minicbor
minicbor_derive
miniz_oxide
mio
mio_extras
mio_named_pipes
mio_uds
miow
more_asserts
multibase
multihash
multihash_derive
multistream_select
nalgebra
base
geometry
linalg
names
nb_connect
net2
nohash_hasher
num_bigint
num_complex
num_cpus
num_integer
num_rational
num_traits
object
once_cell
opaque_debug
openssl_probe
owning_ref
pallet_aura
pallet_authorship
pallet_grandpa
pallet_randomness_collective_flip
pallet_session
pallet_timestamp
pallet_transaction_payment
pallet_transaction_payment_rpc
pallet_transaction_payment_rpc_runtime_api
parity_db
parity_multiaddr
parity_scale_codec
parity_scale_codec_derive
parity_send_wrapper
parity_tokio_ipc
parity_util_mem
parity_util_mem_derive
parity_wasm
parity_ws
parking
parking_lot
parking_lot_core
paste
paste_impl
pbkdf2
pdqselect
percent_encoding
pest
pest_derive
pest_generator
pest_meta
pin_project
pin_project_lite
pin_utils
polling
poly1305
polyval
ppv_lite86
primitive_types
proc_macro2
proc_macro_crate
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
prometheus
prost
prost_derive
psm
pwasm_utils
quick_error
quicksink
quote
radium
rand
rand_chacha
rand_core
rand_distr
raw_cpuid
rawpointer
rayon
rayon_core
ref_cast
ref_cast_impl
regalloc
regex
regex_automata
regex_syntax
region
remove_dir_all
retain_mut
ring
rocksdb
rpassword
rustc_demangle
rustc_hash
rustc_hex
rustls
rustls_native_certs
rw_stream_sink
ryu
safe_mix
salsa20
sc_basic_authorship
sc_block_builder
sc_chain_spec
sc_chain_spec_derive
sc_cli
sc_client_api
sc_client_db
sc_consensus
sc_consensus_aura
sc_consensus_babe
sc_consensus_epochs
sc_consensus_slots
sc_consensus_uncles
sc_executor
sc_executor_common
sc_executor_wasmi
sc_executor_wasmtime
sc_finality_grandpa
sc_informant
sc_keystore
sc_light
sc_network
sc_network_gossip
sc_offchain
sc_peerset
sc_proposer_metrics
sc_rpc
sc_rpc_api
sc_rpc_server
sc_service
sc_state_db
sc_telemetry
sc_tracing
sc_tracing_proc_macro
sc_transaction_graph
sc_transaction_pool
schnorrkel
scoped_tls
scopeguard
scroll
scroll_derive
sct
secp256k1
secrecy
serde
serde_derive
serde_json
sha1
sha2
sha3
sharded_slab
signal_hook
signal_hook_registry
signature
simba
slab
smallvec
snow
socket2
soketto
sp_allocator
sp_api
sp_api_proc_macro
sp_application_crypto
sp_arithmetic
sp_authorship
sp_block_builder
sp_blockchain
sp_chain_spec
sp_consensus
sp_consensus_aura
sp_consensus_babe
sp_consensus_slots
sp_consensus_vrf
sp_core
sp_database
sp_debug_derive
sp_externalities
sp_finality_grandpa
sp_inherents
sp_io
sp_keyring
sp_keystore
sp_offchain
sp_panic_handler
sp_rpc
sp_runtime
sp_runtime_interface
sp_runtime_interface_proc_macro
sp_serializer
sp_session
sp_staking
sp_state_machine
sp_std
sp_storage
sp_tasks
sp_timestamp
sp_tracing
sp_transaction_pool
sp_trie
sp_utils
sp_version
sp_wasm_interface
spin
stable_deref_trait
static_assertions
statrs
stream_cipher
strsim
structopt
structopt_derive
strum
strum_macros
substrate_bip39
substrate_frame_rpc_system
substrate_prometheus_endpoint
subtle
syn
synstructure
take_mut
tap
target_lexicon
tempfile
termcolor
textwrap
thiserror
thiserror_impl
thread_local
threadpool
time
tiny_keccak
tinyvec
tinyvec_macros
tokio
future
io
loom
macros
net
park
runtime
signal
stream
sync
task
time
util
tokio_codec
tokio_executor
tokio_io
tokio_named_pipes
tokio_reactor
tokio_rustls
tokio_service
tokio_sync
tokio_uds
tokio_util
toml
tower_service
tracing
tracing_attributes
tracing_core
tracing_futures
tracing_log
tracing_serde
tracing_subscriber
trie_db
trie_root
try_lock
twox_hash
typenum
ucd_trie
uint
unicase
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
universal_hash
unsigned_varint
untrusted
url
value_bag
vec_arena
vec_map
void
waker_fn
want
wasm_bindgen
wasm_bindgen_backend
wasm_bindgen_futures
wasm_bindgen_macro
wasm_bindgen_macro_support
wasm_bindgen_shared
wasm_timer
wasmi
wasmi_validation
wasmparser
wasmtime
wasmtime_cache
wasmtime_cranelift
wasmtime_debug
wasmtime_environ
wasmtime_jit
wasmtime_obj
wasmtime_profiling
wasmtime_runtime
wast
wat
webpki
webpki_roots
winapi
wyz
x25519_dalek
yamux
zeroize
zeroize_derive
zstd
zstd_safe
zstd_sys
  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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
// Copyright 2018-2019 Parity Technologies (UK) Ltd
//
// 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.

//! Logic for a single round of GRANDPA.

mod context;

use context::{Context, VoteNode, Vote};

#[cfg(feature = "derive-codec")]
use parity_scale_codec::{Encode, Decode};

use crate::std::{
	self,
	collections::btree_map::{BTreeMap, Entry},
	fmt,
	vec::Vec,
};
use crate::vote_graph::VoteGraph;
use crate::voter_set::{VoterSet, VoterInfo};
use crate::weights::{VoteWeight, VoterWeight};

use super::{Equivocation, Prevote, Precommit, Chain, BlockNumberOps, HistoricalVotes, Message, SignedMessage};

/// The (voting) phases of a round, each corresponding to the type of
/// votes cast in that phase.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Phase {
	/// The prevote phase in which [`Prevote`]s are cast.
	Prevote,
	/// The precommit phase in which [`Precommit`]s are cast.
	Precommit
}

/// The observed vote from a single voter.
enum VoteMultiplicity<Vote, Signature> {
	/// A single vote has been observed from the voter.
	Single(Vote, Signature),
 	/// At least two votes have been observed from the voter,
	/// i.e. an equivocation.
	Equivocated((Vote, Signature), (Vote, Signature)),
}

impl<Vote: Eq, Signature: Eq> VoteMultiplicity<Vote, Signature> {
	fn contains(&self, vote: &Vote, signature: &Signature) -> bool {
		match self {
			VoteMultiplicity::Single(v, s) =>
				v == vote && s == signature,
			VoteMultiplicity::Equivocated((v1, s1), (v2, s2)) => {
				v1 == vote && s1 == signature ||
					v2 == vote && s2 == signature
			},
		}
	}
}

struct VoteTracker<Id: Ord + Eq, Vote, Signature> {
	votes: BTreeMap<Id, VoteMultiplicity<Vote, Signature>>,
	current_weight: VoteWeight
}

/// Result of adding a vote.
pub(crate) struct AddVoteResult<'a, Vote, Signature> {
	multiplicity: Option<&'a VoteMultiplicity<Vote, Signature>>,
	duplicated: bool,
}

impl<Id: Ord + Eq + Clone, Vote: Clone + Eq, Signature: Clone + Eq> VoteTracker<Id, Vote, Signature> {
	fn new() -> Self {
		VoteTracker {
			votes: BTreeMap::new(),
			current_weight: VoteWeight(0),
		}
	}

	// track a vote, returning a value containing the multiplicity of all votes from this ID
	// and a bool indicating if the vote is duplicated.
	// if the vote is the first equivocation, returns a value indicating
	// it as such (the new vote is always the last in the multiplicity).
	//
	// if the vote is a further equivocation, it is ignored and there is nothing
	// to do.
	//
	// since this struct doesn't track the round-number of votes, that must be set
	// by the caller.
	fn add_vote(&mut self, id: Id, vote: Vote, signature: Signature, weight: VoterWeight)
		-> AddVoteResult<Vote, Signature>
	{
		match self.votes.entry(id) {
			Entry::Vacant(vacant) => {
				self.current_weight = self.current_weight + weight;
				let multiplicity = vacant.insert(VoteMultiplicity::Single(vote, signature));

				AddVoteResult {
					multiplicity: Some(multiplicity),
					duplicated: false,
				}
			}
			Entry::Occupied(mut occupied) => {
				if occupied.get().contains(&vote, &signature) {
					return AddVoteResult { multiplicity: None, duplicated: true };
				}

				// import, but ignore further equivocations.
				let new_val = match *occupied.get_mut() {
					VoteMultiplicity::Single(ref v, ref s) =>
						VoteMultiplicity::Equivocated((v.clone(), s.clone()), (vote, signature)),
					VoteMultiplicity::Equivocated(_, _) => {
						return AddVoteResult { multiplicity: None, duplicated: false }
					}
				};

				*occupied.get_mut() = new_val;

				AddVoteResult {
					multiplicity: Some(&*occupied.into_mut()),
					duplicated: false
				}
			}
		}
	}

	// Returns all imported votes.
	fn votes(&self) -> Vec<(Id, Vote, Signature)> {
		let mut votes = Vec::new();

		for (id, vote) in &self.votes {
			match vote {
				VoteMultiplicity::Single(v, s) => {
					votes.push((id.clone(), v.clone(), s.clone()))
				},
				VoteMultiplicity::Equivocated((v1, s1), (v2, s2)) => {
					votes.push((id.clone(), v1.clone(), s1.clone()));
					votes.push((id.clone(), v2.clone(), s2.clone()));
				},
			}
		}

		votes
	}

	// Current vote weight and number of participants.
	fn participation(&self) -> (VoteWeight, usize) {
		(self.current_weight, self.votes.len())
	}
}

/// State of the round.
#[derive(PartialEq, Clone)]
#[cfg_attr(any(feature = "std", test), derive(Debug))]
#[cfg_attr(feature = "derive-codec", derive(Encode, Decode))]
pub struct State<H, N> {
	/// The prevote-GHOST block.
	pub prevote_ghost: Option<(H, N)>,
	/// The finalized block.
	pub finalized: Option<(H, N)>,
	/// The new round-estimate.
	pub estimate: Option<(H, N)>,
	/// Whether the round is completable.
	pub completable: bool,
}

impl<H: Clone, N: Clone> State<H, N> {
	/// Genesis state.
	pub fn genesis(genesis: (H, N)) -> Self {
		State {
			prevote_ghost: Some(genesis.clone()),
			finalized: Some(genesis.clone()),
			estimate: Some(genesis),
			completable: true,
		}
	}
}

/// Parameters for starting a round.
pub struct RoundParams<Id: Ord + Eq, H, N> {
	/// The round number for votes.
	pub round_number: u64,
	/// Actors and weights in the round.
	pub voters: VoterSet<Id>,
	/// The base block to build on.
	pub base: (H, N),
}

/// Stores data for a round.
pub struct Round<Id: Ord + Eq, H: Ord + Eq, N, Signature> {
	round_number: u64,
	context: Context<Id>,
	graph: VoteGraph<H, N, VoteNode>, // DAG of blocks which have been voted on.
	prevote: VoteTracker<Id, Prevote<H, N>, Signature>, // tracks prevotes that have been counted
	precommit: VoteTracker<Id, Precommit<H, N>, Signature>, // tracks precommits
	historical_votes: HistoricalVotes<H, N, Signature, Id>,
	prevote_ghost: Option<(H, N)>, // current memoized prevote-GHOST block
	precommit_ghost: Option<(H, N)>, // current memoized precommit-GHOST block
	finalized: Option<(H, N)>, // best finalized block in this round.
	estimate: Option<(H, N)>, // current memoized round-estimate
	completable: bool, // whether the round is completable
}

/// Result of importing a Prevote or Precommit.
pub(crate) struct ImportResult<Id, P, Signature> {
	/// Indicates if the voter is part of the voter set.
	pub(crate) valid_voter: bool,
	/// Indicates if the vote is duplicated.
	pub(crate) duplicated: bool,
	/// An equivocation proof, if the vote is an equivocation.
	pub(crate) equivocation: Option<Equivocation<Id, P, Signature>>,
}

impl<Id, P, Signature> Default for ImportResult<Id, P, Signature> {
	fn default() -> Self {
		ImportResult {
			valid_voter: false,
			duplicated: false,
			equivocation: None,
		}
	}
}

impl<Id, H, N, Signature> Round<Id, H, N, Signature> where
	Id: Ord + Clone + Eq + fmt::Debug,
	H: Ord + Clone + Eq + Ord + fmt::Debug,
	N: Copy + fmt::Debug + BlockNumberOps,
	Signature: Eq + Clone,
{
	/// Create a new round accumulator for given round number and with given weight.
	pub fn new(round_params: RoundParams<Id, H, N>) -> Self {
		let (base_hash, base_number) = round_params.base;

		Round {
			round_number: round_params.round_number,
			context: Context::new(round_params.voters),
			graph: VoteGraph::new(base_hash, base_number, VoteNode::default()),
			prevote: VoteTracker::new(),
			precommit: VoteTracker::new(),
			historical_votes: HistoricalVotes::new(),
			prevote_ghost: None,
			precommit_ghost: None,
			finalized: None,
			estimate: None,
			completable: false,
		}
	}

	/// Return the round number.
	pub fn number(&self) -> u64 {
		self.round_number
	}

	/// Import a prevote. Returns an equivocation proof, if the vote is an equivocation,
	/// and a bool indicating if the vote is duplicated (see `ImportResult`).
	///
	/// Ignores duplicate prevotes (not equivocations).
	#[cfg_attr(not(feature = "std"), allow(unused))]
	pub(crate) fn import_prevote<C: Chain<H, N>>(
		&mut self,
		chain: &C,
		prevote: Prevote<H, N>,
		signer: Id,
		signature: Signature,
	) -> Result<ImportResult<Id, Prevote<H, N>, Signature>, crate::Error> {
		let mut import_result = ImportResult::default();

		let info = match self.context.voters().get(&signer) {
			Some(info) => info.clone(),
			None => return Ok(import_result),
		};

		import_result.valid_voter = true;
		let weight = info.weight();

		let equivocation = {
			let multiplicity = match self.prevote.add_vote(signer.clone(), prevote.clone(), signature.clone(), weight) {
				AddVoteResult { multiplicity: Some(m), .. } => m,
				AddVoteResult { duplicated, .. } => {
					import_result.duplicated = duplicated;
					return Ok(import_result)
				},
			};
			let round_number = self.round_number;

			match multiplicity {
				VoteMultiplicity::Single(single_vote, _) => {
					let vote = Vote::new(&info, Phase::Prevote);

					self.graph.insert(
						single_vote.target_hash.clone(),
						single_vote.target_number,
						vote,
						chain,
					)?;

					// Push the vote into HistoricalVotes.
					let message = Message::Prevote(prevote);
					let signed_message = SignedMessage { id: signer, signature, message };
					self.historical_votes.push_vote(signed_message);

					None
				}
				VoteMultiplicity::Equivocated(ref first, ref second) => {
					// mark the equivocator as such. no need to "undo" the first vote.
					self.context.equivocated(&info, Phase::Prevote);

					// Push the vote into HistoricalVotes.
					let message = Message::Prevote(prevote);
					let signed_message = SignedMessage { id: signer.clone(), signature, message };
					self.historical_votes.push_vote(signed_message);

					Some(Equivocation {
						round_number,
						identity: signer,
						first: first.clone(),
						second: second.clone(),
					})
				}
			}
		};

		// update prevote-GHOST
		let threshold = self.threshold();
		if self.prevote.current_weight >= threshold {
			self.prevote_ghost = self.graph.find_ghost(
				self.prevote_ghost.take(),
				|v| self.context.weight(v, Phase::Prevote) >= threshold,
			);
		}

		self.update();
		import_result.equivocation = equivocation;
		Ok(import_result)
	}

	/// Import a precommit. Returns an equivocation proof, if the vote is an
	/// equivocation, and a bool indicating if the vote is duplicated (see `ImportResult`).
	///
	/// Ignores duplicate precommits (not equivocations).
	pub(crate) fn import_precommit<C: Chain<H, N>>(
		&mut self,
		chain: &C,
		precommit: Precommit<H, N>,
		signer: Id,
		signature: Signature,
	) -> Result<ImportResult<Id, Precommit<H, N>, Signature>, crate::Error> {
		let mut import_result = ImportResult::default();

		let info = match self.context.voters().get(&signer) {
			Some(info) => info.clone(),
			None => return Ok(import_result),
		};
		import_result.valid_voter = true;
		let weight = info.weight();

		let equivocation = {
			let multiplicity = match self.precommit.add_vote(signer.clone(), precommit.clone(), signature.clone(), weight) {
				AddVoteResult { multiplicity: Some(m), .. } => m,
				AddVoteResult { duplicated, .. } => {
					import_result.duplicated = duplicated;
					return Ok(import_result)
				},
			};

			let round_number = self.round_number;

			match multiplicity {
				VoteMultiplicity::Single(single_vote, _) => {
					let vote = Vote::new(&info, Phase::Precommit);

					self.graph.insert(
						single_vote.target_hash.clone(),
						single_vote.target_number,
						vote,
						chain,
					)?;

					let message = Message::Precommit(precommit);
					let signed_message = SignedMessage { id: signer, signature, message };
					self.historical_votes.push_vote(signed_message);

					None
				},
				VoteMultiplicity::Equivocated(ref first, ref second) => {
					// mark the equivocator as such. no need to "undo" the first vote.
					self.context.equivocated(&info, Phase::Precommit);

					// Push the vote into HistoricalVotes.
					let message = Message::Precommit(precommit);
					let signed_message = SignedMessage { id: signer.clone(), signature, message };
					self.historical_votes.push_vote(signed_message);

					Some(Equivocation {
						round_number,
						identity: signer,
						first: first.clone(),
						second: second.clone(),
					})
				},
			}
		};

		self.update();
		import_result.equivocation = equivocation;
		Ok(import_result)
	}

	/// Return the current state.
	pub fn state(&self) -> State<H, N> {
		State {
			prevote_ghost: self.prevote_ghost.clone(),
			finalized: self.finalized.clone(),
			estimate: self.estimate.clone(),
			completable: self.completable,
		}
	}

	/// Compute and cache the precommit-GHOST.
	pub fn precommit_ghost(&mut self) -> Option<(H, N)> {
		// update precommit-GHOST
		let threshold = self.threshold();
		if self.precommit.current_weight >= threshold {
			self.precommit_ghost = self.graph.find_ghost(
				self.precommit_ghost.take(),
				|v| self.context.weight(v, Phase::Precommit) >= threshold,
			);
		}

		self.precommit_ghost.clone()
	}

	/// Returns an iterator of all precommits targeting the finalized hash.
	///
	/// Only returns `None` if no block has been finalized in this round.
	pub fn finalizing_precommits<'a, C: 'a + Chain<H, N>>(&'a mut self, chain: &'a C)
		-> Option<impl Iterator<Item=crate::SignedPrecommit<H, N, Signature, Id>> + 'a>
	{
		struct YieldVotes<'b, V: 'b, S: 'b> {
			yielded: usize,
			multiplicity: &'b VoteMultiplicity<V, S>,
		}

		impl<'b, V: 'b + Clone, S: 'b + Clone> Iterator for YieldVotes<'b, V, S> {
			type Item = (V, S);

			fn next(&mut self) -> Option<(V, S)> {
				match self.multiplicity {
					VoteMultiplicity::Single(ref v, ref s) => {
						if self.yielded == 0 {
							self.yielded += 1;
							Some((v.clone(), s.clone()))
						} else {
							None
						}
					}
					VoteMultiplicity::Equivocated(ref a, ref b) => {
						let res = match self.yielded {
							0 => Some(a.clone()),
							1 => Some(b.clone()),
							_ => None,
						};

						self.yielded += 1;
						res
					}
				}
			}
		}

		let (f_hash, _f_num) = self.finalized.clone()?;
		let find_valid_precommits = self.precommit.votes.iter()
			.filter(move |&(_id, multiplicity)| {
				if let VoteMultiplicity::Single(ref v, _) = *multiplicity {
					// if there is a single vote from this voter, we only include it
					// if it branches off of the target.
					chain.is_equal_or_descendent_of(f_hash.clone(), v.target_hash.clone())
				} else {
					// equivocations count for everything, so we always include them.
					true
				}
			})
			.flat_map(|(id, multiplicity)| {
				let yield_votes = YieldVotes { yielded: 0, multiplicity };

				yield_votes.map(move |(v, s)| crate::SignedPrecommit {
					precommit: v,
					signature: s,
					id: id.clone(),
				})
			});

		Some(find_valid_precommits)
	}

	// update the round-estimate and whether the round is completable.
	fn update(&mut self) {
		let threshold = self.threshold();

		if self.prevote.current_weight < threshold {
			return
		}

		let (g_hash, g_num) = match self.prevote_ghost.clone() {
			None => return,
			Some(x) => x,
		};

		let ctx = &self.context;

		// anything new finalized? finalized blocks are those which have both
		// 2/3+ prevote and precommit weight.
		let current_precommits = self.precommit.current_weight;
		if current_precommits >= self.threshold() {
			self.finalized = self.graph.find_ancestor(
				g_hash.clone(),
				g_num,
				|v| ctx.weight(v, Phase::Precommit) >= threshold,
			);
		};

		// figuring out whether a block can still be committed for is
		// not straightforward because we have to account for all possible future
		// equivocations and thus cannot discount weight from validators who
		// have already voted.
		let possible_to_precommit = {
			// find how many more equivocations we could still get.
			//
			// it is only important to consider the voters whose votes
			// we have already seen, because we are assuming any votes we
			// haven't seen will target this block.
			let tolerated_equivocations = ctx.voters().total_weight() - threshold;
			let current_equivocations = ctx.equivocation_weight(Phase::Precommit);
			let additional_equiv = tolerated_equivocations - current_equivocations;
			let remaining_commit_votes = ctx.voters().total_weight() - self.precommit.current_weight;

			move |node: &VoteNode| {
				// total precommits for this block, including equivocations.
				let precommitted_for = ctx.weight(node, Phase::Precommit);

				// equivocations we could still get are out of those who
				// have already voted, but not on this block.
				let possible_equivocations = std::cmp::min(
					current_precommits - precommitted_for,
					additional_equiv,
				);

				// all the votes already applied on this block,
				// assuming all remaining actors commit to this block,
				// and that we get further equivocations
				let full_possible_weight = precommitted_for
					+ remaining_commit_votes
					+ possible_equivocations;

				full_possible_weight >= threshold
			}
		};

		// until we have threshold precommits, any new block could get supermajority
		// precommits because there are at least f + 1 precommits remaining and then
		// f equivocations.
		//
		// once it's at least that level, we only need to consider blocks
		// already referenced in the graph, because no new leaf nodes
		// could ever have enough precommits.
		//
		// the round-estimate is the highest block in the chain with head
		// `prevote_ghost` that could have supermajority-commits.
		if self.precommit.current_weight >= threshold {
			self.estimate = self.graph.find_ancestor(
				g_hash.clone(),
				g_num,
				possible_to_precommit,
			);
		} else {
			self.estimate = Some((g_hash, g_num));
			return;
		}

		self.completable = self.estimate.clone().map_or(false, |(b_hash, b_num)| {
			b_hash != g_hash || {
				// round-estimate is the same as the prevote-ghost.
				// this round is still completable if no further blocks
				// could have commit-supermajority.
				self.graph.find_ghost(Some((b_hash, b_num)), possible_to_precommit)
					.map_or(true, |x| x == (g_hash, g_num))
			}
		})
	}

	/// Fetch the "round-estimate": the best block which might have been finalized
	/// in this round.
	///
	/// Returns `None` when new new blocks could have been finalized in this round,
	/// according to our estimate.
	pub fn estimate(&self) -> Option<&(H, N)> {
		self.estimate.as_ref()
	}

	/// Fetch the most recently finalized block.
	pub fn finalized(&self) -> Option<&(H, N)> {
		self.finalized.as_ref()
	}

	/// Returns `true` when the round is completable.
	///
	/// This is the case when the round-estimate is an ancestor of the prevote-ghost head,
	/// or when they are the same block _and_ none of its children could possibly have
	/// enough precommits.
	pub fn completable(&self) -> bool {
		self.completable
	}

	/// Threshold weight for supermajority.
	pub fn threshold(&self) -> VoterWeight {
		self.context.voters().threshold()
	}

	/// Return the round base.
	pub fn base(&self) -> (H, N) {
		self.graph.base()
	}

	/// Return the round voters and weights.
	pub fn voters(&self) -> &VoterSet<Id> {
		self.context.voters()
	}

	/// Return the primary voter of the round.
	pub fn primary_voter(&self) -> (&Id, &VoterInfo) {
		self.context.voters().nth_mod(self.round_number as usize)
	}

	/// Get the current weight and number of voters who have participated in prevoting.
	pub fn prevote_participation(&self) -> (VoteWeight, usize) {
		self.prevote.participation()
	}

	/// Get the current weight and number of voters who have participated in precommitting.
	pub fn precommit_participation(&self) -> (VoteWeight, usize) {
		self.precommit.participation()
	}

	/// Return all imported prevotes.
	pub fn prevotes(&self) -> Vec<(Id, Prevote<H, N>, Signature)> {
		self.prevote.votes()
	}

	/// Return all imported precommits.
	pub fn precommits(&self) -> Vec<(Id, Precommit<H, N>, Signature)> {
		self.precommit.votes()
	}

	/// Return all votes for the round (prevotes and precommits), sorted by
	/// imported order and indicating the indices where we voted. At most two
	/// prevotes and two precommits per voter are present, further equivocations
	/// are not stored (as they are redundant).
	pub fn historical_votes(&self) -> &HistoricalVotes<H, N, Signature, Id> {
		&self.historical_votes
	}

	/// Set the number of prevotes and precommits received at the moment of prevoting.
	/// It should be called inmediatly after prevoting.
	pub fn set_prevoted_index(&mut self) {
		self.historical_votes.set_prevoted_idx()
	}

	/// Set the number of prevotes and precommits received at the moment of precommiting.
	/// It should be called inmediatly after precommiting.
	pub fn set_precommitted_index(&mut self) {
		self.historical_votes.set_precommitted_idx()
	}

	/// Get the number of prevotes and precommits received at the moment of prevoting.
	/// Returns None if the prevote wasn't realized.
	pub fn prevoted_index(&self) -> Option<u64> {
		self.historical_votes.prevote_idx
	}

	/// Get the number of prevotes and precommits received at the moment of precommiting.
	/// Returns None if the precommit wasn't realized.
	pub fn precommitted_index(&self) -> Option<u64> {
		self.historical_votes.precommit_idx
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::testing::chain::{GENESIS_HASH, DummyChain};

	fn voters() -> VoterSet<&'static str> {
		VoterSet::new([
			("Alice", 4),
			("Bob", 7),
			("Eve", 3),
		].iter().cloned()).expect("nonempty")
	}

	#[derive(PartialEq, Eq, Clone, Debug)]
	struct Signature(&'static str);

	#[test]
	fn estimate_is_valid() {
		let mut chain = DummyChain::new();
		chain.push_blocks(GENESIS_HASH, &["A", "B", "C", "D", "E", "F"]);
		chain.push_blocks("E", &["EA", "EB", "EC", "ED"]);
		chain.push_blocks("F", &["FA", "FB", "FC"]);

		let mut round = Round::new(RoundParams {
			round_number: 1,
			voters: voters(),
			base: ("C", 4),
		});

		round.import_prevote(
			&chain,
			Prevote::new("FC", 10),
			"Alice",
			Signature("Alice"),
		).unwrap();

		round.import_prevote(
			&chain,
			Prevote::new("ED", 10),
			"Bob",
			Signature("Bob"),
		).unwrap();

		assert_eq!(round.prevote_ghost, Some(("E", 6)));
		assert_eq!(round.estimate(), Some(&("E", 6)));
		assert!(!round.completable());

		round.import_prevote(
			&chain,
			Prevote::new("F", 7),
			"Eve",
			Signature("Eve"),
		).unwrap();

		assert_eq!(round.prevote_ghost, Some(("E", 6)));
		assert_eq!(round.estimate(), Some(&("E", 6)));
	}

	#[test]
	fn finalization() {
		let mut chain = DummyChain::new();
		chain.push_blocks(GENESIS_HASH, &["A", "B", "C", "D", "E", "F"]);
		chain.push_blocks("E", &["EA", "EB", "EC", "ED"]);
		chain.push_blocks("F", &["FA", "FB", "FC"]);

		let mut round = Round::new(RoundParams {
			round_number: 1,
			voters: voters(),
			base: ("C", 4),
		});

		round.import_precommit(
			&chain,
			Precommit::new("FC", 10),
			"Alice",
			Signature("Alice"),
		).unwrap();

		round.import_precommit(
			&chain,
			Precommit::new("ED", 10),
			"Bob",
			Signature("Bob"),
		).unwrap();

		assert_eq!(round.finalized, None);

		// import some prevotes.
		{
			round.import_prevote(
				&chain,
				Prevote::new("FC", 10),
				"Alice",
				Signature("Alice"),
			).unwrap();

			round.import_prevote(
				&chain,
				Prevote::new("ED", 10),
				"Bob",
				Signature("Bob"),
			).unwrap();

			round.import_prevote(
				&chain,
				Prevote::new("EA", 7),
				"Eve",
				Signature("Eve"),
			).unwrap();

			assert_eq!(round.finalized, Some(("E", 6)));
		}

		round.import_precommit(
			&chain,
			Precommit::new("EA", 7),
			"Eve",
			Signature("Eve"),
		).unwrap();

		assert_eq!(round.finalized, Some(("EA", 7)));
	}

	#[test]
	fn equivocate_does_not_double_count() {
		let mut chain = DummyChain::new();
		chain.push_blocks(GENESIS_HASH, &["A", "B", "C", "D", "E", "F"]);
		chain.push_blocks("E", &["EA", "EB", "EC", "ED"]);
		chain.push_blocks("F", &["FA", "FB", "FC"]);

		let mut round = Round::new(RoundParams {
			round_number: 1,
			voters: voters(),
			base: ("C", 4),
		});

		// first prevote by eve
		assert!(round.import_prevote(
			&chain,
			Prevote::new("FC", 10),
			"Eve", // 3 on F, E
			Signature("Eve-1"),
		).unwrap().equivocation.is_none());


		assert!(round.prevote_ghost.is_none());

		// second prevote by eve: comes with equivocation proof
		assert!(round.import_prevote(
			&chain,
			Prevote::new("ED", 10),
			"Eve", // still 3 on E
			Signature("Eve-2"),
		).unwrap().equivocation.is_some());

		// third prevote: returns nothing.
		assert!(round.import_prevote(
			&chain,
			Prevote::new("F", 7),
			"Eve", // still 3 on F and E
			Signature("Eve-2"),
		).unwrap().equivocation.is_none());

		// three eves together would be enough.

		assert!(round.prevote_ghost.is_none());

		assert!(round.import_prevote(
			&chain,
			Prevote::new("FA", 8),
			"Bob", // add 7 to FA and you get FA.
			Signature("Bob-1"),
		).unwrap().equivocation.is_none());

		assert_eq!(round.prevote_ghost, Some(("FA", 8)));
	}

	#[test]
	fn historical_votes_works() {
		let mut chain = DummyChain::new();
		chain.push_blocks(GENESIS_HASH, &["A", "B", "C", "D", "E", "F"]);
		chain.push_blocks("E", &["EA", "EB", "EC", "ED"]);
		chain.push_blocks("F", &["FA", "FB", "FC"]);

		let mut round = Round::new(RoundParams {
			round_number: 1,
			voters: voters(),
			base: ("C", 4),
		});

		round.import_prevote(
			&chain,
			Prevote::new("FC", 10),
			"Alice",
			Signature("Alice"),
		).unwrap();

		round.set_prevoted_index();

		round.import_prevote(
			&chain,
			Prevote::new("EA", 7),
			"Eve",
			Signature("Eve"),
		).unwrap();

		round.import_precommit(
			&chain,
			Precommit::new("EA", 7),
			"Eve",
			Signature("Eve"),
		).unwrap();

		round.import_prevote(
			&chain,
			Prevote::new("EC", 10),
			"Alice",
			Signature("Alice"),
		).unwrap();

		round.set_precommitted_index();

		assert_eq!(round.historical_votes(), &HistoricalVotes::new_with(
			vec![
				SignedMessage {
					message: Message::Prevote(
						Prevote { target_hash: "FC", target_number: 10 }
					),
					signature: Signature("Alice"),
					id: "Alice"
				},
				SignedMessage {
					message: Message::Prevote(
						Prevote { target_hash: "EA", target_number: 7 }
					),
					signature: Signature("Eve"),
					id: "Eve"
				},
				SignedMessage {
					message: Message::Precommit(
						Precommit { target_hash: "EA", target_number: 7 }
					),
					signature: Signature("Eve"),
					id: "Eve"
				},
				SignedMessage {
					message: Message::Prevote(
						Prevote { target_hash: "EC", target_number: 10 }
					),
					signature: Signature("Alice"),
					id: "Alice"
				},
			],
			Some(1),
			Some(4),
		));
	}
}