referrerpolicy=no-referrer-when-downgrade

sc_rpc/chain/
mod.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Substrate blockchain API.
20
21mod chain_full;
22
23#[cfg(test)]
24mod tests;
25
26use std::sync::Arc;
27
28use crate::SubscriptionTaskExecutor;
29
30use jsonrpsee::{core::async_trait, PendingSubscriptionSink};
31use sc_client_api::BlockchainEvents;
32use sp_rpc::{list::ListOrValue, number::NumberOrHex};
33use sp_runtime::{
34	generic::SignedBlock,
35	traits::{Block as BlockT, NumberFor},
36};
37
38use self::error::Error;
39
40use sc_client_api::BlockBackend;
41pub use sc_rpc_api::chain::*;
42use sp_blockchain::HeaderBackend;
43
44/// Blockchain backend API
45#[async_trait]
46trait ChainBackend<Client, Block: BlockT>: Send + Sync + 'static
47where
48	Block: BlockT + 'static,
49	Block::Header: Unpin,
50	Client: HeaderBackend<Block> + BlockchainEvents<Block> + 'static,
51{
52	/// Get client reference.
53	fn client(&self) -> &Arc<Client>;
54
55	/// Tries to unwrap passed block hash, or uses best block hash otherwise.
56	fn unwrap_or_best(&self, hash: Option<Block::Hash>) -> Block::Hash {
57		match hash {
58			None => self.client().info().best_hash,
59			Some(hash) => hash,
60		}
61	}
62
63	/// Get header of a block.
64	fn header(&self, hash: Option<Block::Hash>) -> Result<Option<Block::Header>, Error>;
65
66	/// Get header and body of a block.
67	fn block(&self, hash: Option<Block::Hash>) -> Result<Option<SignedBlock<Block>>, Error>;
68
69	/// Get hash of the n-th block in the canon chain.
70	///
71	/// By default returns latest block hash.
72	fn block_hash(&self, number: Option<NumberOrHex>) -> Result<Option<Block::Hash>, Error> {
73		match number {
74			None => Ok(Some(self.client().info().best_hash)),
75			Some(num_or_hex) => {
76				// FIXME <2329>: Database seems to limit the block number to u32 for no reason
77				let block_num: u32 = num_or_hex.try_into().map_err(|_| {
78					Error::Other(format!(
79						"`{:?}` > u32::MAX, the max block number is u32.",
80						num_or_hex
81					))
82				})?;
83				let block_num = <NumberFor<Block>>::from(block_num);
84				self.client().hash(block_num).map_err(client_err)
85			},
86		}
87	}
88
89	/// Get hash of the last finalized block in the canon chain.
90	fn finalized_head(&self) -> Result<Block::Hash, Error> {
91		Ok(self.client().info().finalized_hash)
92	}
93
94	/// All new head subscription
95	fn subscribe_all_heads(&self, pending: PendingSubscriptionSink);
96
97	/// New best head subscription
98	fn subscribe_new_heads(&self, pending: PendingSubscriptionSink);
99
100	/// Finalized head subscription
101	fn subscribe_finalized_heads(&self, pending: PendingSubscriptionSink);
102}
103
104/// Create new state API that works on full node.
105pub fn new_full<Block: BlockT, Client>(
106	client: Arc<Client>,
107	executor: SubscriptionTaskExecutor,
108) -> Chain<Block, Client>
109where
110	Block: BlockT + 'static,
111	Block::Header: Unpin,
112	Client: BlockBackend<Block> + HeaderBackend<Block> + BlockchainEvents<Block> + 'static,
113{
114	Chain { backend: Box::new(self::chain_full::FullChain::new(client, executor)) }
115}
116
117/// Chain API with subscriptions support.
118pub struct Chain<Block: BlockT, Client> {
119	backend: Box<dyn ChainBackend<Client, Block>>,
120}
121
122#[async_trait]
123impl<Block, Client> ChainApiServer<NumberFor<Block>, Block::Hash, Block::Header, SignedBlock<Block>>
124	for Chain<Block, Client>
125where
126	Block: BlockT + 'static,
127	Block::Header: Unpin,
128	Client: HeaderBackend<Block> + BlockchainEvents<Block> + 'static,
129{
130	fn header(&self, hash: Option<Block::Hash>) -> Result<Option<Block::Header>, Error> {
131		self.backend.header(hash)
132	}
133
134	fn block(&self, hash: Option<Block::Hash>) -> Result<Option<SignedBlock<Block>>, Error> {
135		self.backend.block(hash)
136	}
137
138	fn block_hash(
139		&self,
140		number: Option<ListOrValue<NumberOrHex>>,
141	) -> Result<ListOrValue<Option<Block::Hash>>, Error> {
142		match number {
143			None => self.backend.block_hash(None).map(ListOrValue::Value),
144			Some(ListOrValue::Value(number)) => self
145				.backend
146				.block_hash(Some(number))
147				.map(ListOrValue::Value)
148				.map_err(Into::into),
149			Some(ListOrValue::List(list)) => Ok(ListOrValue::List(
150				list.into_iter()
151					.map(|number| self.backend.block_hash(Some(number)))
152					.collect::<Result<_, _>>()?,
153			)),
154		}
155	}
156
157	fn finalized_head(&self) -> Result<Block::Hash, Error> {
158		self.backend.finalized_head()
159	}
160
161	fn subscribe_all_heads(&self, pending: PendingSubscriptionSink) {
162		self.backend.subscribe_all_heads(pending);
163	}
164
165	fn subscribe_new_heads(&self, pending: PendingSubscriptionSink) {
166		self.backend.subscribe_new_heads(pending)
167	}
168
169	fn subscribe_finalized_heads(&self, pending: PendingSubscriptionSink) {
170		self.backend.subscribe_finalized_heads(pending)
171	}
172}
173
174fn client_err(err: sp_blockchain::Error) -> Error {
175	Error::Client(Box::new(err))
176}