1use std::fmt::Debug;
22
23use codec::{Decode, Encode};
24use finality_grandpa::round::State as RoundState;
25use log::{info, warn};
26
27use fork_tree::ForkTree;
28use sc_client_api::backend::AuxStore;
29use sp_blockchain::{Error as ClientError, Result as ClientResult};
30use sp_consensus_grandpa::{AuthorityList, RoundNumber, SetId};
31use sp_runtime::traits::{Block as BlockT, NumberFor};
32
33use crate::{
34 authorities::{
35 AuthoritySet, AuthoritySetChanges, DelayKind, PendingChange, SharedAuthoritySet,
36 },
37 environment::{
38 CompletedRound, CompletedRounds, CurrentRounds, HasVoted, SharedVoterSetState,
39 VoterSetState,
40 },
41 GrandpaJustification, NewAuthoritySet, LOG_TARGET,
42};
43
44const VERSION_KEY: &[u8] = b"grandpa_schema_version";
45const SET_STATE_KEY: &[u8] = b"grandpa_completed_round";
46const AUTHORITY_SET_KEY: &[u8] = b"grandpa_voters";
47const BEST_JUSTIFICATION: &[u8] = b"grandpa_best_justification";
48
49const CURRENT_VERSION: u32 = 3;
50
51#[derive(Debug, Clone, Encode, Decode)]
53#[cfg_attr(test, derive(PartialEq))]
54pub enum V1VoterSetState<H, N> {
55 Paused(RoundNumber, RoundState<H, N>),
57 Live(RoundNumber, RoundState<H, N>),
59}
60
61type V0VoterSetState<H, N> = (RoundNumber, RoundState<H, N>);
62
63#[derive(Debug, Clone, Encode, Decode, PartialEq)]
64struct V0PendingChange<H, N> {
65 next_authorities: AuthorityList,
66 delay: N,
67 canon_height: N,
68 canon_hash: H,
69}
70
71#[derive(Debug, Clone, Encode, Decode, PartialEq)]
72struct V0AuthoritySet<H, N> {
73 current_authorities: AuthorityList,
74 set_id: SetId,
75 pending_changes: Vec<V0PendingChange<H, N>>,
76}
77
78impl<H, N> Into<AuthoritySet<H, N>> for V0AuthoritySet<H, N>
79where
80 H: Clone + Debug + PartialEq,
81 N: Clone + Debug + Ord,
82{
83 fn into(self) -> AuthoritySet<H, N> {
84 let mut pending_standard_changes = ForkTree::new();
85
86 for old_change in self.pending_changes {
87 let new_change = PendingChange {
88 next_authorities: old_change.next_authorities,
89 delay: old_change.delay,
90 canon_height: old_change.canon_height,
91 canon_hash: old_change.canon_hash,
92 delay_kind: DelayKind::Finalized,
93 };
94
95 if let Err(err) = pending_standard_changes.import::<_, ClientError>(
96 new_change.canon_hash.clone(),
97 new_change.canon_height.clone(),
98 new_change,
99 &|_, _| Ok(false),
101 ) {
102 warn!(target: LOG_TARGET, "Error migrating pending authority set change: {}", err);
103 warn!(target: LOG_TARGET, "Node is in a potentially inconsistent state.");
104 }
105 }
106
107 let authority_set = AuthoritySet::new(
108 self.current_authorities,
109 self.set_id,
110 pending_standard_changes,
111 Vec::new(),
112 AuthoritySetChanges::empty(),
113 );
114
115 authority_set.expect("current_authorities is non-empty and weights are non-zero; qed.")
116 }
117}
118
119impl<H, N> Into<AuthoritySet<H, N>> for V2AuthoritySet<H, N>
120where
121 H: Clone + Debug + PartialEq,
122 N: Clone + Debug + Ord,
123{
124 fn into(self) -> AuthoritySet<H, N> {
125 AuthoritySet::new(
126 self.current_authorities,
127 self.set_id,
128 self.pending_standard_changes,
129 self.pending_forced_changes,
130 AuthoritySetChanges::empty(),
131 )
132 .expect("current_authorities is non-empty and weights are non-zero; qed.")
133 }
134}
135
136#[derive(Debug, Clone, Encode, Decode, PartialEq)]
137struct V2AuthoritySet<H, N> {
138 current_authorities: AuthorityList,
139 set_id: u64,
140 pending_standard_changes: ForkTree<H, N, PendingChange<H, N>>,
141 pending_forced_changes: Vec<PendingChange<H, N>>,
142}
143
144pub(crate) fn load_decode<B: AuxStore, T: Decode>(
145 backend: &B,
146 key: &[u8],
147) -> ClientResult<Option<T>> {
148 match backend.get_aux(key)? {
149 None => Ok(None),
150 Some(t) => T::decode(&mut &t[..])
151 .map_err(|e| ClientError::Backend(format!("GRANDPA DB is corrupted: {}", e)))
152 .map(Some),
153 }
154}
155
156pub(crate) struct PersistentData<Block: BlockT> {
158 pub(crate) authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>,
159 pub(crate) set_state: SharedVoterSetState<Block>,
160}
161
162fn migrate_from_version0<Block: BlockT, B, G>(
163 backend: &B,
164 genesis_round: &G,
165) -> ClientResult<Option<(AuthoritySet<Block::Hash, NumberFor<Block>>, VoterSetState<Block>)>>
166where
167 B: AuxStore,
168 G: Fn() -> RoundState<Block::Hash, NumberFor<Block>>,
169{
170 CURRENT_VERSION.using_encoded(|s| backend.insert_aux(&[(VERSION_KEY, s)], &[]))?;
171
172 if let Some(old_set) =
173 load_decode::<_, V0AuthoritySet<Block::Hash, NumberFor<Block>>>(backend, AUTHORITY_SET_KEY)?
174 {
175 let new_set: AuthoritySet<Block::Hash, NumberFor<Block>> = old_set.into();
176 backend.insert_aux(&[(AUTHORITY_SET_KEY, new_set.encode().as_slice())], &[])?;
177
178 let (last_round_number, last_round_state) = match load_decode::<
179 _,
180 V0VoterSetState<Block::Hash, NumberFor<Block>>,
181 >(backend, SET_STATE_KEY)?
182 {
183 Some((number, state)) => (number, state),
184 None => (0, genesis_round()),
185 };
186
187 let set_id = new_set.set_id;
188
189 let base = last_round_state.prevote_ghost.expect(
190 "state is for completed round; completed rounds must have a prevote ghost; qed.",
191 );
192
193 let mut current_rounds = CurrentRounds::<Block>::new();
194 current_rounds.insert(last_round_number + 1, HasVoted::No);
195
196 let set_state = VoterSetState::Live {
197 completed_rounds: CompletedRounds::new(
198 CompletedRound {
199 number: last_round_number,
200 state: last_round_state,
201 votes: Vec::new(),
202 base,
203 },
204 set_id,
205 &new_set,
206 ),
207 current_rounds,
208 };
209
210 backend.insert_aux(&[(SET_STATE_KEY, set_state.encode().as_slice())], &[])?;
211
212 return Ok(Some((new_set, set_state)));
213 }
214
215 Ok(None)
216}
217
218fn migrate_from_version1<Block: BlockT, B, G>(
219 backend: &B,
220 genesis_round: &G,
221) -> ClientResult<Option<(AuthoritySet<Block::Hash, NumberFor<Block>>, VoterSetState<Block>)>>
222where
223 B: AuxStore,
224 G: Fn() -> RoundState<Block::Hash, NumberFor<Block>>,
225{
226 CURRENT_VERSION.using_encoded(|s| backend.insert_aux(&[(VERSION_KEY, s)], &[]))?;
227
228 if let Some(set) =
229 load_decode::<_, AuthoritySet<Block::Hash, NumberFor<Block>>>(backend, AUTHORITY_SET_KEY)?
230 {
231 let set_id = set.set_id;
232
233 let completed_rounds = |number, state, base| {
234 CompletedRounds::new(
235 CompletedRound { number, state, votes: Vec::new(), base },
236 set_id,
237 &set,
238 )
239 };
240
241 let set_state = match load_decode::<_, V1VoterSetState<Block::Hash, NumberFor<Block>>>(
242 backend,
243 SET_STATE_KEY,
244 )? {
245 Some(V1VoterSetState::Paused(last_round_number, set_state)) => {
246 let base = set_state.prevote_ghost
247 .expect("state is for completed round; completed rounds must have a prevote ghost; qed.");
248
249 VoterSetState::Paused {
250 completed_rounds: completed_rounds(last_round_number, set_state, base),
251 }
252 },
253 Some(V1VoterSetState::Live(last_round_number, set_state)) => {
254 let base = set_state.prevote_ghost
255 .expect("state is for completed round; completed rounds must have a prevote ghost; qed.");
256
257 let mut current_rounds = CurrentRounds::<Block>::new();
258 current_rounds.insert(last_round_number + 1, HasVoted::No);
259
260 VoterSetState::Live {
261 completed_rounds: completed_rounds(last_round_number, set_state, base),
262 current_rounds,
263 }
264 },
265 None => {
266 let set_state = genesis_round();
267 let base = set_state.prevote_ghost
268 .expect("state is for completed round; completed rounds must have a prevote ghost; qed.");
269
270 VoterSetState::live(set_id, &set, base)
271 },
272 };
273
274 backend.insert_aux(&[(SET_STATE_KEY, set_state.encode().as_slice())], &[])?;
275
276 return Ok(Some((set, set_state)));
277 }
278
279 Ok(None)
280}
281
282fn migrate_from_version2<Block: BlockT, B, G>(
283 backend: &B,
284 genesis_round: &G,
285) -> ClientResult<Option<(AuthoritySet<Block::Hash, NumberFor<Block>>, VoterSetState<Block>)>>
286where
287 B: AuxStore,
288 G: Fn() -> RoundState<Block::Hash, NumberFor<Block>>,
289{
290 CURRENT_VERSION.using_encoded(|s| backend.insert_aux(&[(VERSION_KEY, s)], &[]))?;
291
292 if let Some(old_set) =
293 load_decode::<_, V2AuthoritySet<Block::Hash, NumberFor<Block>>>(backend, AUTHORITY_SET_KEY)?
294 {
295 let new_set: AuthoritySet<Block::Hash, NumberFor<Block>> = old_set.into();
296 backend.insert_aux(&[(AUTHORITY_SET_KEY, new_set.encode().as_slice())], &[])?;
297
298 let set_state = match load_decode::<_, VoterSetState<Block>>(backend, SET_STATE_KEY)? {
299 Some(state) => state,
300 None => {
301 let state = genesis_round();
302 let base = state.prevote_ghost
303 .expect("state is for completed round; completed rounds must have a prevote ghost; qed.");
304
305 VoterSetState::live(new_set.set_id, &new_set, base)
306 },
307 };
308
309 return Ok(Some((new_set, set_state)));
310 }
311
312 Ok(None)
313}
314
315pub(crate) fn load_persistent<Block: BlockT, B, G>(
317 backend: &B,
318 genesis_hash: Block::Hash,
319 genesis_number: NumberFor<Block>,
320 genesis_authorities: G,
321) -> ClientResult<PersistentData<Block>>
322where
323 B: AuxStore,
324 G: FnOnce() -> ClientResult<AuthorityList>,
325{
326 let version: Option<u32> = load_decode(backend, VERSION_KEY)?;
327
328 let make_genesis_round = move || RoundState::genesis((genesis_hash, genesis_number));
329
330 match version {
331 None => {
332 if let Some((new_set, set_state)) =
333 migrate_from_version0::<Block, _, _>(backend, &make_genesis_round)?
334 {
335 return Ok(PersistentData {
336 authority_set: new_set.into(),
337 set_state: set_state.into(),
338 });
339 }
340 },
341 Some(1) => {
342 if let Some((new_set, set_state)) =
343 migrate_from_version1::<Block, _, _>(backend, &make_genesis_round)?
344 {
345 return Ok(PersistentData {
346 authority_set: new_set.into(),
347 set_state: set_state.into(),
348 });
349 }
350 },
351 Some(2) => {
352 if let Some((new_set, set_state)) =
353 migrate_from_version2::<Block, _, _>(backend, &make_genesis_round)?
354 {
355 return Ok(PersistentData {
356 authority_set: new_set.into(),
357 set_state: set_state.into(),
358 });
359 }
360 },
361 Some(3) => {
362 if let Some(set) = load_decode::<_, AuthoritySet<Block::Hash, NumberFor<Block>>>(
363 backend,
364 AUTHORITY_SET_KEY,
365 )? {
366 let set_state =
367 match load_decode::<_, VoterSetState<Block>>(backend, SET_STATE_KEY)? {
368 Some(state) => state,
369 None => {
370 let state = make_genesis_round();
371 let base = state.prevote_ghost
372 .expect("state is for completed round; completed rounds must have a prevote ghost; qed.");
373
374 VoterSetState::live(set.set_id, &set, base)
375 },
376 };
377
378 return Ok(PersistentData {
379 authority_set: set.into(),
380 set_state: set_state.into(),
381 });
382 }
383 },
384 Some(other) => {
385 return Err(ClientError::Backend(format!(
386 "Unsupported GRANDPA DB version: {:?}",
387 other
388 )))
389 },
390 }
391
392 info!(
394 target: LOG_TARGET,
395 "👴 Loading GRANDPA authority set \
396 from genesis on what appears to be first startup."
397 );
398
399 let genesis_authorities = genesis_authorities()?;
400 let genesis_set = AuthoritySet::genesis(genesis_authorities)
401 .expect("genesis authorities is non-empty; all weights are non-zero; qed.");
402 let state = make_genesis_round();
403 let base = state
404 .prevote_ghost
405 .expect("state is for completed round; completed rounds must have a prevote ghost; qed.");
406
407 let genesis_state = VoterSetState::live(0, &genesis_set, base);
408
409 backend.insert_aux(
410 &[
411 (AUTHORITY_SET_KEY, genesis_set.encode().as_slice()),
412 (SET_STATE_KEY, genesis_state.encode().as_slice()),
413 ],
414 &[],
415 )?;
416
417 Ok(PersistentData { authority_set: genesis_set.into(), set_state: genesis_state.into() })
418}
419
420pub(crate) fn update_authority_set<Block: BlockT, F, R>(
426 set: &AuthoritySet<Block::Hash, NumberFor<Block>>,
427 new_set: Option<&NewAuthoritySet<Block::Hash, NumberFor<Block>>>,
428 write_aux: F,
429) -> R
430where
431 F: FnOnce(&[(&'static [u8], &[u8])]) -> R,
432{
433 let encoded_set = set.encode();
435
436 if let Some(new_set) = new_set {
437 let set_state = VoterSetState::<Block>::live(
441 new_set.set_id,
442 set,
443 (new_set.canon_hash, new_set.canon_number),
444 );
445 let encoded = set_state.encode();
446
447 write_aux(&[(AUTHORITY_SET_KEY, &encoded_set[..]), (SET_STATE_KEY, &encoded[..])])
448 } else {
449 write_aux(&[(AUTHORITY_SET_KEY, &encoded_set[..])])
450 }
451}
452
453pub(crate) fn update_best_justification<Block: BlockT, F, R>(
459 justification: &GrandpaJustification<Block>,
460 write_aux: F,
461) -> R
462where
463 F: FnOnce(&[(&'static [u8], &[u8])]) -> R,
464{
465 let encoded_justification = justification.encode();
466 write_aux(&[(BEST_JUSTIFICATION, &encoded_justification[..])])
467}
468
469pub fn best_justification<B, Block>(
471 backend: &B,
472) -> ClientResult<Option<GrandpaJustification<Block>>>
473where
474 B: AuxStore,
475 Block: BlockT,
476{
477 load_decode::<_, GrandpaJustification<Block>>(backend, BEST_JUSTIFICATION)
478}
479
480pub(crate) fn write_voter_set_state<Block: BlockT, B: AuxStore>(
482 backend: &B,
483 state: &VoterSetState<Block>,
484) -> ClientResult<()> {
485 backend.insert_aux(&[(SET_STATE_KEY, state.encode().as_slice())], &[])
486}
487
488#[cfg(test)]
489pub(crate) fn load_authorities<B: AuxStore, H: Decode, N: Decode + Clone + Ord>(
490 backend: &B,
491) -> Option<AuthoritySet<H, N>> {
492 load_decode::<_, AuthoritySet<H, N>>(backend, AUTHORITY_SET_KEY).expect("backend error")
493}
494
495#[cfg(test)]
496mod test {
497 use super::*;
498 use sp_consensus_grandpa::AuthorityId;
499 use sp_core::{crypto::UncheckedFrom, H256};
500 use substrate_test_runtime_client::{self, runtime::Block};
501
502 fn dummy_id() -> AuthorityId {
503 AuthorityId::unchecked_from([1; 32])
504 }
505
506 #[test]
507 fn load_decode_from_v0_migrates_data_format() {
508 let client = substrate_test_runtime_client::new();
509
510 let authorities = vec![(dummy_id(), 100)];
511 let set_id = 3;
512 let round_number: RoundNumber = 42;
513 let round_state = RoundState::<H256, u64> {
514 prevote_ghost: Some((H256::random(), 32)),
515 finalized: None,
516 estimate: None,
517 completable: false,
518 };
519
520 {
521 let authority_set = V0AuthoritySet::<H256, u64> {
522 current_authorities: authorities.clone(),
523 pending_changes: Vec::new(),
524 set_id,
525 };
526
527 let voter_set_state = (round_number, round_state.clone());
528
529 client
530 .insert_aux(
531 &[
532 (AUTHORITY_SET_KEY, authority_set.encode().as_slice()),
533 (SET_STATE_KEY, voter_set_state.encode().as_slice()),
534 ],
535 &[],
536 )
537 .unwrap();
538 }
539
540 assert_eq!(load_decode::<_, u32>(&client, VERSION_KEY).unwrap(), None);
541
542 load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
544 &client,
545 H256::random(),
546 0,
547 || unreachable!(),
548 )
549 .unwrap();
550
551 assert_eq!(load_decode::<_, u32>(&client, VERSION_KEY).unwrap(), Some(3));
552
553 let PersistentData { authority_set, set_state, .. } =
554 load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
555 &client,
556 H256::random(),
557 0,
558 || unreachable!(),
559 )
560 .unwrap();
561
562 assert_eq!(
563 *authority_set.inner(),
564 AuthoritySet::new(
565 authorities.clone(),
566 set_id,
567 ForkTree::new(),
568 Vec::new(),
569 AuthoritySetChanges::empty(),
570 )
571 .unwrap(),
572 );
573
574 let mut current_rounds = CurrentRounds::<Block>::new();
575 current_rounds.insert(round_number + 1, HasVoted::No);
576
577 assert_eq!(
578 &*set_state.read(),
579 &VoterSetState::Live {
580 completed_rounds: CompletedRounds::new(
581 CompletedRound {
582 number: round_number,
583 state: round_state.clone(),
584 base: round_state.prevote_ghost.unwrap(),
585 votes: vec![],
586 },
587 set_id,
588 &*authority_set.inner(),
589 ),
590 current_rounds,
591 },
592 );
593 }
594
595 #[test]
596 fn load_decode_from_v1_migrates_data_format() {
597 let client = substrate_test_runtime_client::new();
598
599 let authorities = vec![(dummy_id(), 100)];
600 let set_id = 3;
601 let round_number: RoundNumber = 42;
602 let round_state = RoundState::<H256, u64> {
603 prevote_ghost: Some((H256::random(), 32)),
604 finalized: None,
605 estimate: None,
606 completable: false,
607 };
608
609 {
610 let authority_set = AuthoritySet::<H256, u64>::new(
611 authorities.clone(),
612 set_id,
613 ForkTree::new(),
614 Vec::new(),
615 AuthoritySetChanges::empty(),
616 )
617 .unwrap();
618
619 let voter_set_state = V1VoterSetState::Live(round_number, round_state.clone());
620
621 client
622 .insert_aux(
623 &[
624 (AUTHORITY_SET_KEY, authority_set.encode().as_slice()),
625 (SET_STATE_KEY, voter_set_state.encode().as_slice()),
626 (VERSION_KEY, 1u32.encode().as_slice()),
627 ],
628 &[],
629 )
630 .unwrap();
631 }
632
633 assert_eq!(load_decode::<_, u32>(&client, VERSION_KEY).unwrap(), Some(1));
634
635 load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
637 &client,
638 H256::random(),
639 0,
640 || unreachable!(),
641 )
642 .unwrap();
643
644 assert_eq!(load_decode::<_, u32>(&client, VERSION_KEY).unwrap(), Some(3));
645
646 let PersistentData { authority_set, set_state, .. } =
647 load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
648 &client,
649 H256::random(),
650 0,
651 || unreachable!(),
652 )
653 .unwrap();
654
655 assert_eq!(
656 *authority_set.inner(),
657 AuthoritySet::new(
658 authorities.clone(),
659 set_id,
660 ForkTree::new(),
661 Vec::new(),
662 AuthoritySetChanges::empty(),
663 )
664 .unwrap(),
665 );
666
667 let mut current_rounds = CurrentRounds::<Block>::new();
668 current_rounds.insert(round_number + 1, HasVoted::No);
669
670 assert_eq!(
671 &*set_state.read(),
672 &VoterSetState::Live {
673 completed_rounds: CompletedRounds::new(
674 CompletedRound {
675 number: round_number,
676 state: round_state.clone(),
677 base: round_state.prevote_ghost.unwrap(),
678 votes: vec![],
679 },
680 set_id,
681 &*authority_set.inner(),
682 ),
683 current_rounds,
684 },
685 );
686 }
687
688 #[test]
689 fn load_decode_from_v2_migrates_data_format() {
690 let client = substrate_test_runtime_client::new();
691
692 let authorities = vec![(dummy_id(), 100)];
693 let set_id = 3;
694
695 {
696 let authority_set = V2AuthoritySet::<H256, u64> {
697 current_authorities: authorities.clone(),
698 set_id,
699 pending_standard_changes: ForkTree::new(),
700 pending_forced_changes: Vec::new(),
701 };
702
703 let genesis_state = (H256::random(), 32);
704 let voter_set_state: VoterSetState<substrate_test_runtime_client::runtime::Block> =
705 VoterSetState::live(
706 set_id,
707 &authority_set.clone().into(), genesis_state,
709 );
710
711 client
712 .insert_aux(
713 &[
714 (AUTHORITY_SET_KEY, authority_set.encode().as_slice()),
715 (SET_STATE_KEY, voter_set_state.encode().as_slice()),
716 (VERSION_KEY, 2u32.encode().as_slice()),
717 ],
718 &[],
719 )
720 .unwrap();
721 }
722
723 assert_eq!(load_decode::<_, u32>(&client, VERSION_KEY).unwrap(), Some(2));
724
725 load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
727 &client,
728 H256::random(),
729 0,
730 || unreachable!(),
731 )
732 .unwrap();
733
734 assert_eq!(load_decode::<_, u32>(&client, VERSION_KEY).unwrap(), Some(3));
735
736 let PersistentData { authority_set, .. } = load_persistent::<
737 substrate_test_runtime_client::runtime::Block,
738 _,
739 _,
740 >(
741 &client, H256::random(), 0, || unreachable!()
742 )
743 .unwrap();
744
745 assert_eq!(
746 *authority_set.inner(),
747 AuthoritySet::new(
748 authorities.clone(),
749 set_id,
750 ForkTree::new(),
751 Vec::new(),
752 AuthoritySetChanges::empty(),
753 )
754 .unwrap(),
755 );
756 }
757}