sp_consensus/select_chain.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use crate::error::Error;
19use sp_runtime::traits::{Block as BlockT, NumberFor};
20
21/// The SelectChain trait defines the strategy upon which the head is chosen
22/// if multiple forks are present for an opaque definition of "best" in the
23/// specific chain build.
24///
25/// The Strategy can be customized for the two use cases of authoring new blocks
26/// upon the best chain or which fork to finalize. Unless implemented differently
27/// by default finalization methods fall back to use authoring, so as a minimum
28/// `_authoring`-functions must be implemented.
29///
30/// Any particular user must make explicit, however, whether they intend to finalize
31/// or author through the using the right function call, as these might differ in
32/// some implementations.
33///
34/// Non-deterministically finalizing chains may only use the `_authoring` functions.
35#[async_trait::async_trait]
36pub trait SelectChain<Block: BlockT>: Sync + Send + Clone {
37 /// Get all leaves of the chain, i.e. block hashes that have no children currently.
38 /// Leaves that can never be finalized will not be returned.
39 async fn leaves(&self) -> Result<Vec<<Block as BlockT>::Hash>, Error>;
40
41 /// Among those `leaves` deterministically pick one chain as the generally
42 /// best chain to author new blocks upon and probably (but not necessarily)
43 /// finalize.
44 async fn best_chain(&self) -> Result<<Block as BlockT>::Header, Error>;
45
46 /// Get the best descendent of `base_hash` that we should attempt to
47 /// finalize next, if any. It is valid to return the given `base_hash`
48 /// itself if no better descendent exists.
49 async fn finality_target(
50 &self,
51 base_hash: <Block as BlockT>::Hash,
52 _maybe_max_number: Option<NumberFor<Block>>,
53 ) -> Result<<Block as BlockT>::Hash, Error> {
54 Ok(base_hash)
55 }
56}