referrerpolicy=no-referrer-when-downgrade
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
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! A generic runtime api subsystem mockup suitable to be used in benchmarks.

use futures::FutureExt;
use itertools::Itertools;
use polkadot_node_subsystem::{
	messages::ChainApiMessage, overseer, SpawnedSubsystem, SubsystemError,
};
use polkadot_node_subsystem_types::OverseerSignal;
use polkadot_primitives::Header;
use sp_core::H256;
use std::collections::HashMap;

const LOG_TARGET: &str = "subsystem-bench::chain-api-mock";

/// State used to respond to `BlockHeader` requests.
pub struct ChainApiState {
	pub block_headers: HashMap<H256, Header>,
}

pub struct MockChainApi {
	state: ChainApiState,
}

impl ChainApiState {
	fn get_header_by_number(&self, requested_number: u32) -> Option<&Header> {
		self.block_headers.values().find(|header| header.number == requested_number)
	}
}

impl MockChainApi {
	pub fn new(state: ChainApiState) -> MockChainApi {
		Self { state }
	}
}

#[overseer::subsystem(ChainApi, error=SubsystemError, prefix=self::overseer)]
impl<Context> MockChainApi {
	fn start(self, ctx: Context) -> SpawnedSubsystem {
		let future = self.run(ctx).map(|_| Ok(())).boxed();

		SpawnedSubsystem { name: "test-environment", future }
	}
}

#[overseer::contextbounds(ChainApi, prefix = self::overseer)]
impl MockChainApi {
	async fn run<Context>(self, mut ctx: Context) {
		loop {
			let msg = ctx.recv().await.expect("Overseer never fails us");

			match msg {
				orchestra::FromOrchestra::Signal(signal) =>
					if signal == OverseerSignal::Conclude {
						return
					},
				orchestra::FromOrchestra::Communication { msg } => {
					gum::debug!(target: LOG_TARGET, msg=?msg, "recv message");

					match msg {
						ChainApiMessage::BlockHeader(hash, response_channel) => {
							let _ = response_channel.send(Ok(Some(
								self.state
									.block_headers
									.get(&hash)
									.cloned()
									.expect("Relay chain block hashes are known"),
							)));
						},
						ChainApiMessage::FinalizedBlockNumber(val) => {
							val.send(Ok(0)).unwrap();
						},
						ChainApiMessage::FinalizedBlockHash(requested_number, sender) => {
							let hash = self
								.state
								.get_header_by_number(requested_number)
								.expect("Unknown block number")
								.hash();
							sender.send(Ok(Some(hash))).unwrap();
						},
						ChainApiMessage::BlockNumber(requested_hash, sender) => {
							sender
								.send(Ok(Some(
									self.state
										.block_headers
										.get(&requested_hash)
										.expect("Unknown block hash")
										.number,
								)))
								.unwrap();
						},
						ChainApiMessage::Ancestors { hash, k: _, response_channel } => {
							let block_number = self
								.state
								.block_headers
								.get(&hash)
								.expect("Unknown block hash")
								.number;
							let ancestors = self
								.state
								.block_headers
								.iter()
								.filter(|(_, header)| header.number < block_number)
								.sorted_by(|a, b| a.1.number.cmp(&b.1.number))
								.map(|(hash, _)| *hash)
								.collect_vec();
							response_channel.send(Ok(ancestors)).unwrap();
						},
						_ => {
							unimplemented!("Unexpected chain-api message")
						},
					}
				},
			}
		}
	}
}