1use codec::{Decode, DecodeAll, Encode};
21
22use crate::{
23 best_justification, find_scheduled_change, AuthoritySetChanges, AuthoritySetHardFork,
24 BlockNumberOps, GrandpaJustification, SharedAuthoritySet,
25};
26use sc_client_api::Backend as ClientBackend;
27use sc_network_sync::strategy::warp::{
28 EncodedProof, VerificationResult, Verifier, WarpSyncProvider,
29};
30use sp_blockchain::{Backend as BlockchainBackend, HeaderBackend};
31use sp_consensus_grandpa::{AuthorityList, SetId, GRANDPA_ENGINE_ID};
32use sp_runtime::{
33 generic::BlockId,
34 traits::{Block as BlockT, Header as HeaderT, NumberFor, One},
35 Justifications,
36};
37
38use std::{collections::HashMap, sync::Arc};
39
40#[derive(Debug, thiserror::Error)]
42pub enum Error {
43 #[error("Failed to decode block hash: {0}.")]
45 DecodeScale(#[from] codec::Error),
46 #[error("{0}")]
48 Client(#[from] sp_blockchain::Error),
49 #[error("{0}")]
51 InvalidRequest(String),
52 #[error("{0}")]
54 InvalidProof(String),
55 #[error("Missing required data to be able to answer request.")]
57 MissingData,
58}
59
60pub(super) const MAX_WARP_SYNC_PROOF_SIZE: usize = 8 * 1024 * 1024;
62
63#[derive(Decode, Encode, Debug)]
65pub struct WarpSyncFragment<Block: BlockT> {
66 pub header: Block::Header,
69 pub justification: GrandpaJustification<Block>,
72}
73
74#[derive(Decode, Encode)]
76pub struct WarpSyncProof<Block: BlockT> {
77 proofs: Vec<WarpSyncFragment<Block>>,
78 is_finished: bool,
79}
80
81impl<Block: BlockT> WarpSyncProof<Block> {
82 fn generate<Backend>(
86 backend: &Backend,
87 begin: Block::Hash,
88 set_changes: &AuthoritySetChanges<NumberFor<Block>>,
89 ) -> Result<WarpSyncProof<Block>, Error>
90 where
91 Backend: ClientBackend<Block>,
92 {
93 let blockchain = backend.blockchain();
95
96 let begin_number = blockchain
97 .block_number_from_id(&BlockId::Hash(begin))?
98 .ok_or_else(|| Error::InvalidRequest("Missing start block".to_string()))?;
99
100 if begin_number > blockchain.info().finalized_number {
101 return Err(Error::InvalidRequest("Start block is not finalized".to_string()));
102 }
103
104 let canon_hash = blockchain.hash(begin_number)?.expect(
105 "begin number is lower than finalized number; \
106 all blocks below finalized number must have been imported; \
107 qed.",
108 );
109
110 if canon_hash != begin {
111 return Err(Error::InvalidRequest(
112 "Start block is not in the finalized chain".to_string(),
113 ));
114 }
115
116 let mut proofs = Vec::new();
117 let mut proofs_encoded_len = 0;
118 let mut proof_limit_reached = false;
119
120 let set_changes = set_changes.iter_from(begin_number).ok_or(Error::MissingData)?;
121
122 for (_, last_block) in set_changes {
123 let hash = blockchain.block_hash_from_id(&BlockId::Number(*last_block))?
124 .expect("header number comes from previously applied set changes; corresponding hash must exist in db; qed.");
125
126 let header = blockchain
127 .header(hash)?
128 .expect("header hash obtained from header number exists in db; corresponding header must exist in db too; qed.");
129
130 if find_scheduled_change::<Block>(&header).is_none() {
133 break;
137 }
138
139 let justification = blockchain
140 .justifications(header.hash())?
141 .and_then(|just| just.into_justification(GRANDPA_ENGINE_ID))
142 .ok_or_else(|| Error::MissingData)?;
143
144 let justification = GrandpaJustification::<Block>::decode_all(&mut &justification[..])?;
145
146 let proof = WarpSyncFragment { header: header.clone(), justification };
147 let proof_size = proof.encoded_size();
148
149 if proofs_encoded_len + proof_size >= MAX_WARP_SYNC_PROOF_SIZE - 50 {
153 proof_limit_reached = true;
154 break;
155 }
156
157 proofs_encoded_len += proof_size;
158 proofs.push(proof);
159 }
160
161 let is_finished = if proof_limit_reached {
162 false
163 } else {
164 let latest_justification = best_justification(backend)?.filter(|justification| {
165 let limit = proofs
170 .last()
171 .map(|proof| proof.justification.target().0 + One::one())
172 .unwrap_or(begin_number);
173
174 justification.target().0 >= limit
175 });
176
177 if let Some(latest_justification) = latest_justification {
178 let header = blockchain.header(latest_justification.target().1)?
179 .expect("header hash corresponds to a justification in db; must exist in db as well; qed.");
180
181 let proof = WarpSyncFragment { header, justification: latest_justification };
182
183 if proofs_encoded_len + proof.encoded_size() >= MAX_WARP_SYNC_PROOF_SIZE - 50 {
187 false
188 } else {
189 proofs.push(proof);
190 true
191 }
192 } else {
193 true
194 }
195 };
196
197 let final_outcome = WarpSyncProof { proofs, is_finished };
198 debug_assert!(final_outcome.encoded_size() <= MAX_WARP_SYNC_PROOF_SIZE);
199 Ok(final_outcome)
200 }
201
202 fn verify(
206 &self,
207 set_id: SetId,
208 authorities: AuthorityList,
209 hard_forks: &HashMap<(Block::Hash, NumberFor<Block>), (SetId, AuthorityList)>,
210 ) -> Result<(SetId, AuthorityList), Error>
211 where
212 NumberFor<Block>: BlockNumberOps,
213 {
214 let mut current_set_id = set_id;
215 let mut current_authorities = authorities;
216
217 for (fragment_num, proof) in self.proofs.iter().enumerate() {
218 let hash = proof.header.hash();
219 let number = *proof.header.number();
220
221 let is_target = fragment_num == self.proofs.len() - 1 && self.is_finished;
222
223 if let Some((set_id, list)) = hard_forks
224 .get(&(hash, number))
225 .filter(|(set_id, _)| *set_id > current_set_id && !is_target)
226 {
227 current_set_id = *set_id;
228 current_authorities = list.clone();
229 } else {
230 proof
231 .justification
232 .verify(current_set_id, ¤t_authorities)
233 .map_err(|err| Error::InvalidProof(err.to_string()))?;
234
235 if proof.justification.target().1 != hash {
236 return Err(Error::InvalidProof(
237 "Mismatch between header and justification".to_owned(),
238 ));
239 }
240
241 if let Some(scheduled_change) = find_scheduled_change::<Block>(&proof.header) {
242 current_authorities = scheduled_change.next_authorities;
243 current_set_id += 1;
244 } else if !is_target {
245 return Err(Error::InvalidProof(
248 "Header is missing authority set change digest".to_string(),
249 ));
250 }
251 }
252 }
253 Ok((current_set_id, current_authorities))
254 }
255}
256
257pub struct NetworkProvider<Block: BlockT, Backend: ClientBackend<Block>>
259where
260 NumberFor<Block>: BlockNumberOps,
261{
262 backend: Arc<Backend>,
263 authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>,
264 hard_forks: HashMap<(Block::Hash, NumberFor<Block>), (SetId, AuthorityList)>,
265}
266
267impl<Block: BlockT, Backend: ClientBackend<Block>> NetworkProvider<Block, Backend>
268where
269 NumberFor<Block>: BlockNumberOps,
270{
271 pub fn new(
273 backend: Arc<Backend>,
274 authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>,
275 hard_forks: Vec<AuthoritySetHardFork<Block>>,
276 ) -> Self {
277 NetworkProvider {
278 backend,
279 authority_set,
280 hard_forks: hard_forks
281 .into_iter()
282 .map(|fork| (fork.block, (fork.set_id, fork.authorities)))
283 .collect(),
284 }
285 }
286}
287
288struct VerifierState<Block: BlockT> {
290 set_id: SetId,
291 authorities: AuthorityList,
292 next_proof_context: Block::Hash,
293}
294
295struct GrandpaVerifier<Block: BlockT> {
297 state: VerifierState<Block>,
298 hard_forks: HashMap<(Block::Hash, NumberFor<Block>), (SetId, AuthorityList)>,
299 eras_synced: u64,
300}
301
302impl<Block: BlockT> Verifier<Block> for GrandpaVerifier<Block>
303where
304 NumberFor<Block>: BlockNumberOps,
305{
306 fn verify(
307 &mut self,
308 proof: &EncodedProof,
309 ) -> Result<VerificationResult<Block>, Box<dyn std::error::Error + Send + Sync>> {
310 let EncodedProof(proof) = proof;
311 let proof = WarpSyncProof::<Block>::decode_all(&mut proof.as_slice())
312 .map_err(|e| format!("Proof decoding error: {:?}", e))?;
313 let last_header = proof
314 .proofs
315 .last()
316 .map(|p| p.header.clone())
317 .ok_or_else(|| "Empty proof".to_string())?;
318
319 let (current_set_id, current_authorities) =
320 (self.state.set_id, self.state.authorities.clone());
321
322 let (next_set_id, next_authorities) = proof
323 .verify(current_set_id, current_authorities, &self.hard_forks)
324 .map_err(Box::new)?;
325
326 self.state = VerifierState {
327 set_id: next_set_id,
328 authorities: next_authorities,
329 next_proof_context: last_header.hash(),
330 };
331
332 self.eras_synced += proof.proofs.len() as u64;
334
335 let justifications = proof
336 .proofs
337 .into_iter()
338 .map(|p| {
339 let justifications =
340 Justifications::new(vec![(GRANDPA_ENGINE_ID, p.justification.encode())]);
341 (p.header, justifications)
342 })
343 .collect::<Vec<_>>();
344
345 if proof.is_finished {
346 Ok(VerificationResult::Complete(last_header, justifications))
347 } else {
348 Ok(VerificationResult::Partial(justifications))
349 }
350 }
351
352 fn next_proof_context(&self) -> Block::Hash {
353 self.state.next_proof_context
354 }
355
356 fn status(&self) -> Option<String> {
357 Some(format!("{} eras synced", self.eras_synced))
358 }
359}
360
361impl<Block: BlockT, Backend: ClientBackend<Block>> WarpSyncProvider<Block>
362 for NetworkProvider<Block, Backend>
363where
364 NumberFor<Block>: BlockNumberOps,
365{
366 fn generate(
367 &self,
368 start: Block::Hash,
369 ) -> Result<EncodedProof, Box<dyn std::error::Error + Send + Sync>> {
370 let proof = WarpSyncProof::<Block>::generate(
371 &*self.backend,
372 start,
373 &self.authority_set.authority_set_changes(),
374 )
375 .map_err(Box::new)?;
376 Ok(EncodedProof(proof.encode()))
377 }
378
379 fn create_verifier(&self) -> Box<dyn Verifier<Block>> {
380 let authority_set = self.authority_set.inner();
381 let genesis_hash = self.backend.blockchain().info().genesis_hash;
382 Box::new(GrandpaVerifier {
383 state: VerifierState {
384 set_id: authority_set.set_id,
385 authorities: authority_set.current_authorities.clone(),
386 next_proof_context: genesis_hash,
387 },
388 hard_forks: self.hard_forks.clone(),
389 eras_synced: 0,
390 })
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::WarpSyncProof;
397 use crate::{AuthoritySetChanges, GrandpaJustification};
398 use codec::Encode;
399 use rand::prelude::*;
400 use sc_block_builder::BlockBuilderBuilder;
401 use sp_blockchain::HeaderBackend;
402 use sp_consensus::BlockOrigin;
403 use sp_consensus_grandpa::GRANDPA_ENGINE_ID;
404 use sp_keyring::Ed25519Keyring;
405 use std::sync::Arc;
406 use substrate_test_runtime_client::{
407 BlockBuilderExt, ClientBlockImportExt, ClientExt, DefaultTestClientBuilderExt,
408 TestClientBuilder, TestClientBuilderExt,
409 };
410
411 #[test]
412 fn warp_sync_proof_generate_verify() {
413 let mut rng = rand::rngs::StdRng::from_seed([0; 32]);
414 let builder = TestClientBuilder::new();
415 let backend = builder.backend();
416 let client = Arc::new(builder.build());
417
418 let available_authorities = Ed25519Keyring::iter().collect::<Vec<_>>();
419 let genesis_authorities = vec![(Ed25519Keyring::Alice.public().into(), 1)];
420
421 let mut current_authorities = vec![Ed25519Keyring::Alice];
422 let mut current_set_id = 0;
423 let mut authority_set_changes = Vec::new();
424
425 for n in 1..=100 {
426 let mut builder = BlockBuilderBuilder::new(&*client)
427 .on_parent_block(client.chain_info().best_hash)
428 .with_parent_block_number(client.chain_info().best_number)
429 .build()
430 .unwrap();
431 let mut new_authorities = None;
432
433 if n != 0 && n % 10 == 0 {
435 let n_authorities = rng.gen_range(1..available_authorities.len());
437 let next_authorities = available_authorities
438 .choose_multiple(&mut rng, n_authorities)
439 .cloned()
440 .collect::<Vec<_>>();
441
442 new_authorities = Some(next_authorities.clone());
443
444 let next_authorities = next_authorities
445 .iter()
446 .map(|keyring| (keyring.public().into(), 1))
447 .collect::<Vec<_>>();
448
449 let digest = sp_runtime::generic::DigestItem::Consensus(
450 sp_consensus_grandpa::GRANDPA_ENGINE_ID,
451 sp_consensus_grandpa::ConsensusLog::ScheduledChange(
452 sp_consensus_grandpa::ScheduledChange { delay: 0u64, next_authorities },
453 )
454 .encode(),
455 );
456
457 builder.push_deposit_log_digest_item(digest).unwrap();
458 }
459
460 let block = builder.build().unwrap().block;
461
462 futures::executor::block_on(client.import(BlockOrigin::Own, block)).unwrap();
463
464 if let Some(new_authorities) = new_authorities {
465 let (target_hash, target_number) = {
468 let info = client.info();
469 (info.best_hash, info.best_number)
470 };
471
472 let mut precommits = Vec::new();
473 for keyring in ¤t_authorities {
474 let precommit = finality_grandpa::Precommit { target_hash, target_number };
475
476 let msg = finality_grandpa::Message::Precommit(precommit.clone());
477 let encoded = sp_consensus_grandpa::localized_payload(42, current_set_id, &msg);
478 let signature = keyring.sign(&encoded[..]).into();
479
480 let precommit = finality_grandpa::SignedPrecommit {
481 precommit,
482 signature,
483 id: keyring.public().into(),
484 };
485
486 precommits.push(precommit);
487 }
488
489 let commit = finality_grandpa::Commit { target_hash, target_number, precommits };
490
491 let justification = GrandpaJustification::from_commit(&client, 42, commit).unwrap();
492
493 client
494 .finalize_block(target_hash, Some((GRANDPA_ENGINE_ID, justification.encode())))
495 .unwrap();
496
497 authority_set_changes.push((current_set_id, n));
498
499 current_set_id += 1;
500 current_authorities = new_authorities;
501 }
502 }
503
504 let authority_set_changes = AuthoritySetChanges::from(authority_set_changes);
505
506 let genesis_hash = client.hash(0).unwrap().unwrap();
508
509 let warp_sync_proof =
510 WarpSyncProof::generate(&*backend, genesis_hash, &authority_set_changes).unwrap();
511
512 let (new_set_id, new_authorities) =
514 warp_sync_proof.verify(0, genesis_authorities, &Default::default()).unwrap();
515
516 let expected_authorities = current_authorities
517 .iter()
518 .map(|keyring| (keyring.public().into(), 1))
519 .collect::<Vec<_>>();
520
521 assert_eq!(new_set_id, current_set_id);
522 assert_eq!(new_authorities, expected_authorities);
523 }
524
525 #[test]
526 fn warp_sync_proof_hard_fork_must_advance_set_and_not_be_target() {
527 use super::WarpSyncFragment;
528 use sp_runtime::traits::Header as _;
529 use substrate_test_runtime_client::runtime::{Block, Header};
530
531 let header = Header::new(
532 1,
533 Default::default(),
534 Default::default(),
535 Default::default(),
536 Default::default(),
537 );
538 let justification: GrandpaJustification<Block> =
539 sp_consensus_grandpa::GrandpaJustification {
540 round: 1,
541 commit: finality_grandpa::Commit {
542 target_hash: header.hash(),
543 target_number: 1,
544 precommits: Vec::new(),
545 },
546 votes_ancestries: Vec::new(),
547 }
548 .into();
549 let authorities = vec![(Ed25519Keyring::Alice.public().into(), 1)];
550 let hard_forks: std::collections::HashMap<_, _> =
551 [((header.hash(), 1), (5, authorities.clone()))].into_iter().collect();
552 let proof = |is_finished| WarpSyncProof::<Block> {
553 proofs: vec![WarpSyncFragment {
554 header: header.clone(),
555 justification: justification.clone(),
556 }],
557 is_finished,
558 };
559
560 assert_eq!(
561 proof(false).verify(2, authorities.clone(), &hard_forks).unwrap(),
562 (5, authorities.clone())
563 );
564 assert!(proof(false).verify(5, authorities.clone(), &hard_forks).is_err());
565 assert!(proof(false).verify(9, authorities.clone(), &hard_forks).is_err());
566 assert!(proof(true).verify(2, authorities.clone(), &hard_forks).is_err());
567
568 let next = Header::new(
570 2,
571 Default::default(),
572 Default::default(),
573 header.hash(),
574 Default::default(),
575 );
576 let mut hard_forks = hard_forks;
577 hard_forks.insert((next.hash(), 2), (6, authorities.clone()));
578 let proof = |headers: [&Header; 2]| WarpSyncProof::<Block> {
579 proofs: headers
580 .into_iter()
581 .map(|header| WarpSyncFragment {
582 header: header.clone(),
583 justification: justification.clone(),
584 })
585 .collect(),
586 is_finished: false,
587 };
588 assert_eq!(
589 proof([&header, &next]).verify(2, authorities.clone(), &hard_forks).unwrap(),
590 (6, authorities.clone())
591 );
592 assert!(proof([&next, &header]).verify(2, authorities.clone(), &hard_forks).is_err());
593 }
594}