Files
biguint
chain_spec_builder
compact
fixed_point
fork_tree
frame_benchmarking
frame_benchmarking_cli
frame_election_provider_support
frame_executive
frame_metadata
frame_support
frame_support_procedural
frame_support_procedural_tools
frame_support_procedural_tools_derive
frame_support_test
frame_support_test_pallet
frame_system
frame_system_benchmarking
frame_system_rpc_runtime_api
frame_try_runtime
multiply_by_rational
node_bench
node_browser_testing
node_cli
node_executor
node_inspect
node_primitives
node_rpc
node_rpc_client
node_runtime
node_template
node_template_runtime
node_testing
normalize
pallet_assets
pallet_atomic_swap
pallet_aura
pallet_authority_discovery
pallet_authorship
pallet_babe
pallet_balances
pallet_bounties
pallet_collective
pallet_contracts
pallet_contracts_primitives
pallet_contracts_proc_macro
pallet_contracts_rpc
pallet_contracts_rpc_runtime_api
pallet_democracy
pallet_election_provider_multi_phase
pallet_elections
pallet_elections_phragmen
pallet_example
pallet_example_offchain_worker
pallet_example_parallel
pallet_gilt
pallet_grandpa
pallet_identity
pallet_im_online
pallet_indices
pallet_lottery
pallet_membership
pallet_mmr
pallet_mmr_primitives
pallet_mmr_rpc
pallet_multisig
pallet_nicks
pallet_node_authorization
pallet_offences
pallet_offences_benchmarking
pallet_proxy
pallet_randomness_collective_flip
pallet_recovery
pallet_scheduler
pallet_scored_pool
pallet_session
pallet_session_benchmarking
pallet_society
pallet_staking
pallet_staking_reward_curve
pallet_staking_reward_fn
pallet_sudo
pallet_template
pallet_timestamp
pallet_tips
pallet_transaction_payment
pallet_transaction_payment_rpc
pallet_transaction_payment_rpc_runtime_api
pallet_transaction_storage
pallet_treasury
pallet_uniques
pallet_utility
pallet_vesting
per_thing_rational
phragmen_balancing
phragmen_pjr
phragmms_balancing
reduce
remote_externalities
sc_allocator
sc_authority_discovery
sc_basic_authorship
sc_block_builder
sc_chain_spec
sc_chain_spec_derive
sc_cli
sc_client_api
sc_client_db
sc_consensus
sc_consensus_aura
sc_consensus_babe
sc_consensus_babe_rpc
sc_consensus_epochs
sc_consensus_manual_seal
sc_consensus_pow
sc_consensus_slots
sc_consensus_uncles
sc_executor
sc_executor_common
sc_executor_wasmi
sc_executor_wasmtime
sc_finality_grandpa
sc_finality_grandpa_rpc
sc_informant
sc_keystore
sc_light
sc_network
sc_network_gossip
sc_network_test
sc_offchain
sc_peerset
sc_proposer_metrics
sc_rpc
sc_rpc_api
sc_rpc_server
sc_runtime_test
sc_service
sc_service_test
sc_state_db
sc_sync_state_rpc
sc_telemetry
sc_tracing
sc_tracing_proc_macro
sc_transaction_pool
sc_transaction_pool_api
sp_api
sp_api_proc_macro
sp_application_crypto
sp_application_crypto_test
sp_arithmetic
sp_authority_discovery
sp_authorship
sp_block_builder
sp_blockchain
sp_consensus
sp_consensus_aura
sp_consensus_babe
sp_consensus_pow
sp_consensus_slots
sp_consensus_vrf
sp_core
sp_database
sp_debug_derive
sp_externalities
sp_finality_grandpa
sp_inherents
sp_io
sp_keyring
sp_keystore
sp_maybe_compressed_blob
sp_npos_elections
sp_npos_elections_solution_type
sp_offchain
sp_panic_handler
sp_rpc
sp_runtime
sp_runtime_interface
sp_runtime_interface_proc_macro
sp_runtime_interface_test
sp_runtime_interface_test_wasm
sp_runtime_interface_test_wasm_deprecated
sp_sandbox
sp_serializer
sp_session
sp_staking
sp_state_machine
sp_std
sp_storage
sp_tasks
sp_test_primitives
sp_timestamp
sp_tracing
sp_transaction_pool
sp_transaction_storage_proof
sp_trie
sp_utils
sp_version
sp_version_proc_macro
sp_wasm_interface
subkey
substrate
substrate_browser_utils
substrate_build_script_utils
substrate_frame_cli
substrate_frame_rpc_support
substrate_frame_rpc_system
substrate_prometheus_endpoint
substrate_test_client
substrate_test_runtime
substrate_test_runtime_client
substrate_test_runtime_transaction_pool
substrate_test_utils
substrate_test_utils_derive
substrate_test_utils_test_crate
substrate_wasm_builder
test_runner
test_runner_example
try_runtime_cli
  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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
// This file is part of Substrate.

// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program 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.

// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.

//! State API backend for light nodes.

use codec::Decode;
use futures::{
	channel::oneshot::{channel, Sender},
	future::{ready, Either},
	FutureExt, StreamExt as _, TryFutureExt, TryStreamExt as _,
};
use hash_db::Hasher;
use jsonrpc_pubsub::{manager::SubscriptionManager, typed::Subscriber, SubscriptionId};
use log::warn;
use parking_lot::Mutex;
use rpc::{
	futures::{
		future::{result, Future},
		stream::Stream,
		Sink,
	},
	Result as RpcResult,
};
use std::{
	collections::{hash_map::Entry, HashMap, HashSet},
	sync::Arc,
};

use sc_client_api::{
	light::{
		future_header, Fetcher, RemoteBlockchain, RemoteCallRequest, RemoteReadChildRequest,
		RemoteReadRequest,
	},
	BlockchainEvents,
};
use sc_rpc_api::state::ReadProof;
use sp_blockchain::{Error as ClientError, HeaderBackend};
use sp_core::{
	storage::{PrefixedStorageKey, StorageChangeSet, StorageData, StorageKey},
	Bytes, OpaqueMetadata,
};
use sp_runtime::{
	generic::BlockId,
	traits::{Block as BlockT, HashFor},
};
use sp_version::RuntimeVersion;

use super::{
	client_err,
	error::{Error, FutureResult},
	ChildStateBackend, StateBackend,
};

/// Storage data map of storage keys => (optional) storage value.
type StorageMap = HashMap<StorageKey, Option<StorageData>>;

/// State API backend for light nodes.
#[derive(Clone)]
pub struct LightState<Block: BlockT, F: Fetcher<Block>, Client> {
	client: Arc<Client>,
	subscriptions: SubscriptionManager,
	version_subscriptions: SimpleSubscriptions<Block::Hash, RuntimeVersion>,
	storage_subscriptions: Arc<Mutex<StorageSubscriptions<Block>>>,
	remote_blockchain: Arc<dyn RemoteBlockchain<Block>>,
	fetcher: Arc<F>,
}

/// Shared requests container.
trait SharedRequests<Hash, V>: Clone + Send + Sync {
	/// Tries to listen for already issued request, or issues request.
	///
	/// Returns true if requests has been issued.
	fn listen_request(&self, block: Hash, sender: Sender<Result<V, ()>>) -> bool;

	/// Returns (and forgets) all listeners for given request.
	fn on_response_received(&self, block: Hash) -> Vec<Sender<Result<V, ()>>>;
}

/// Storage subscriptions data.
struct StorageSubscriptions<Block: BlockT> {
	/// Active storage requests.
	active_requests: HashMap<Block::Hash, Vec<Sender<Result<StorageMap, ()>>>>,
	/// Map of subscription => keys that this subscription watch for.
	keys_by_subscription: HashMap<SubscriptionId, HashSet<StorageKey>>,
	/// Map of key => set of subscriptions that watch this key.
	subscriptions_by_key: HashMap<StorageKey, HashSet<SubscriptionId>>,
}

impl<Block: BlockT> SharedRequests<Block::Hash, StorageMap>
	for Arc<Mutex<StorageSubscriptions<Block>>>
{
	fn listen_request(&self, block: Block::Hash, sender: Sender<Result<StorageMap, ()>>) -> bool {
		let mut subscriptions = self.lock();
		let active_requests_at = subscriptions.active_requests.entry(block).or_default();
		active_requests_at.push(sender);
		active_requests_at.len() == 1
	}

	fn on_response_received(&self, block: Block::Hash) -> Vec<Sender<Result<StorageMap, ()>>> {
		self.lock().active_requests.remove(&block).unwrap_or_default()
	}
}

/// Simple, maybe shared, subscription data that shares per block requests.
type SimpleSubscriptions<Hash, V> = Arc<Mutex<HashMap<Hash, Vec<Sender<Result<V, ()>>>>>>;

impl<Hash, V> SharedRequests<Hash, V> for SimpleSubscriptions<Hash, V>
where
	Hash: Send + Eq + std::hash::Hash,
	V: Send,
{
	fn listen_request(&self, block: Hash, sender: Sender<Result<V, ()>>) -> bool {
		let mut subscriptions = self.lock();
		let active_requests_at = subscriptions.entry(block).or_default();
		active_requests_at.push(sender);
		active_requests_at.len() == 1
	}

	fn on_response_received(&self, block: Hash) -> Vec<Sender<Result<V, ()>>> {
		self.lock().remove(&block).unwrap_or_default()
	}
}

impl<Block: BlockT, F: Fetcher<Block> + 'static, Client> LightState<Block, F, Client>
where
	Block: BlockT,
	Client: HeaderBackend<Block> + Send + Sync + 'static,
{
	/// Create new state API backend for light nodes.
	pub fn new(
		client: Arc<Client>,
		subscriptions: SubscriptionManager,
		remote_blockchain: Arc<dyn RemoteBlockchain<Block>>,
		fetcher: Arc<F>,
	) -> Self {
		Self {
			client,
			subscriptions,
			version_subscriptions: Arc::new(Mutex::new(HashMap::new())),
			storage_subscriptions: Arc::new(Mutex::new(StorageSubscriptions {
				active_requests: HashMap::new(),
				keys_by_subscription: HashMap::new(),
				subscriptions_by_key: HashMap::new(),
			})),
			remote_blockchain,
			fetcher,
		}
	}

	/// Returns given block hash or best block hash if None is passed.
	fn block_or_best(&self, hash: Option<Block::Hash>) -> Block::Hash {
		hash.unwrap_or_else(|| self.client.info().best_hash)
	}
}

impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Client>
where
	Block: BlockT,
	Client: BlockchainEvents<Block> + HeaderBackend<Block> + Send + Sync + 'static,
	F: Fetcher<Block> + 'static,
{
	fn call(
		&self,
		block: Option<Block::Hash>,
		method: String,
		call_data: Bytes,
	) -> FutureResult<Bytes> {
		Box::new(
			call(
				&*self.remote_blockchain,
				self.fetcher.clone(),
				self.block_or_best(block),
				method,
				call_data,
			)
			.boxed()
			.compat(),
		)
	}

	fn storage_keys(
		&self,
		_block: Option<Block::Hash>,
		_prefix: StorageKey,
	) -> FutureResult<Vec<StorageKey>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn storage_pairs(
		&self,
		_block: Option<Block::Hash>,
		_prefix: StorageKey,
	) -> FutureResult<Vec<(StorageKey, StorageData)>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn storage_keys_paged(
		&self,
		_block: Option<Block::Hash>,
		_prefix: Option<StorageKey>,
		_count: u32,
		_start_key: Option<StorageKey>,
	) -> FutureResult<Vec<StorageKey>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn storage_size(&self, _: Option<Block::Hash>, _: StorageKey) -> FutureResult<Option<u64>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn storage(
		&self,
		block: Option<Block::Hash>,
		key: StorageKey,
	) -> FutureResult<Option<StorageData>> {
		Box::new(
			storage(
				&*self.remote_blockchain,
				self.fetcher.clone(),
				self.block_or_best(block),
				vec![key.0.clone()],
			)
			.boxed()
			.compat()
			.map(move |mut values| {
				values
					.remove(&key)
					.expect("successful request has entries for all requested keys; qed")
			}),
		)
	}

	fn storage_hash(
		&self,
		block: Option<Block::Hash>,
		key: StorageKey,
	) -> FutureResult<Option<Block::Hash>> {
		Box::new(StateBackend::storage(self, block, key).and_then(|maybe_storage| {
			result(Ok(maybe_storage.map(|storage| HashFor::<Block>::hash(&storage.0))))
		}))
	}

	fn metadata(&self, block: Option<Block::Hash>) -> FutureResult<Bytes> {
		let metadata =
			self.call(block, "Metadata_metadata".into(), Bytes(Vec::new()))
				.and_then(|metadata| {
					OpaqueMetadata::decode(&mut &metadata.0[..]).map(Into::into).map_err(
						|decode_err| {
							client_err(ClientError::CallResultDecode(
								"Unable to decode metadata",
								decode_err,
							))
						},
					)
				});

		Box::new(metadata)
	}

	fn runtime_version(&self, block: Option<Block::Hash>) -> FutureResult<RuntimeVersion> {
		Box::new(
			runtime_version(
				&*self.remote_blockchain,
				self.fetcher.clone(),
				self.block_or_best(block),
			)
			.boxed()
			.compat(),
		)
	}

	fn query_storage(
		&self,
		_from: Block::Hash,
		_to: Option<Block::Hash>,
		_keys: Vec<StorageKey>,
	) -> FutureResult<Vec<StorageChangeSet<Block::Hash>>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn query_storage_at(
		&self,
		_keys: Vec<StorageKey>,
		_at: Option<Block::Hash>,
	) -> FutureResult<Vec<StorageChangeSet<Block::Hash>>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn read_proof(
		&self,
		_block: Option<Block::Hash>,
		_keys: Vec<StorageKey>,
	) -> FutureResult<ReadProof<Block::Hash>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn subscribe_storage(
		&self,
		_meta: crate::Metadata,
		subscriber: Subscriber<StorageChangeSet<Block::Hash>>,
		keys: Option<Vec<StorageKey>>,
	) {
		let keys = match keys {
			Some(keys) if !keys.is_empty() => keys,
			_ => {
				warn!("Cannot subscribe to all keys on light client. Subscription rejected.");
				return
			},
		};

		let keys = keys.iter().cloned().collect::<HashSet<_>>();
		let keys_to_check = keys.iter().map(|k| k.0.clone()).collect::<HashSet<_>>();
		let subscription_id = self.subscriptions.add(subscriber, move |sink| {
			let fetcher = self.fetcher.clone();
			let remote_blockchain = self.remote_blockchain.clone();
			let storage_subscriptions = self.storage_subscriptions.clone();
			let initial_block = self.block_or_best(None);
			let initial_keys = keys_to_check.iter().cloned().collect::<Vec<_>>();

			let changes_stream = subscription_stream::<Block, _, _, _, _, _, _, _, _>(
				storage_subscriptions.clone(),
				self.client
					.import_notification_stream()
					.map(|notification| Ok::<_, ()>(notification.hash))
					.compat(),
				display_error(
					storage(&*remote_blockchain, fetcher.clone(), initial_block, initial_keys)
						.map(move |r| r.map(|r| (initial_block, r))),
				),
				move |block| {
					// there'll be single request per block for all active subscriptions
					// with all subscribed keys
					let keys = storage_subscriptions
						.lock()
						.subscriptions_by_key
						.keys()
						.map(|k| k.0.clone())
						.collect();

					storage(&*remote_blockchain, fetcher.clone(), block, keys)
				},
				move |block, old_value, new_value| {
					// let's only select keys which are valid for this subscription
					let new_value = new_value
						.iter()
						.filter(|(k, _)| keys_to_check.contains(&k.0))
						.map(|(k, v)| (k.clone(), v.clone()))
						.collect::<HashMap<_, _>>();
					let value_differs = old_value
						.as_ref()
						.map(|old_value| **old_value != new_value)
						.unwrap_or(true);
					match value_differs {
						true => Some(StorageChangeSet {
							block,
							changes: new_value
								.iter()
								.map(|(k, v)| (k.clone(), v.clone()))
								.collect(),
						}),
						false => None,
					}
				},
			);

			sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
				.send_all(changes_stream.map(|changes| Ok(changes)))
				// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
				.map(|_| ())
		});

		// remember keys associated with this subscription
		let mut storage_subscriptions = self.storage_subscriptions.lock();
		storage_subscriptions
			.keys_by_subscription
			.insert(subscription_id.clone(), keys.clone());
		for key in keys {
			storage_subscriptions
				.subscriptions_by_key
				.entry(key)
				.or_default()
				.insert(subscription_id.clone());
		}
	}

	fn unsubscribe_storage(
		&self,
		_meta: Option<crate::Metadata>,
		id: SubscriptionId,
	) -> RpcResult<bool> {
		if !self.subscriptions.cancel(id.clone()) {
			return Ok(false)
		}

		// forget subscription keys
		let mut storage_subscriptions = self.storage_subscriptions.lock();
		let keys = storage_subscriptions.keys_by_subscription.remove(&id);
		for key in keys.into_iter().flat_map(|keys| keys.into_iter()) {
			match storage_subscriptions.subscriptions_by_key.entry(key) {
				Entry::Vacant(_) => unreachable!(
					"every key from keys_by_subscription has\
					corresponding entry in subscriptions_by_key; qed"
				),
				Entry::Occupied(mut entry) => {
					entry.get_mut().remove(&id);
					if entry.get().is_empty() {
						entry.remove();
					}
				},
			}
		}

		Ok(true)
	}

	fn subscribe_runtime_version(
		&self,
		_meta: crate::Metadata,
		subscriber: Subscriber<RuntimeVersion>,
	) {
		self.subscriptions.add(subscriber, move |sink| {
			let fetcher = self.fetcher.clone();
			let remote_blockchain = self.remote_blockchain.clone();
			let version_subscriptions = self.version_subscriptions.clone();
			let initial_block = self.block_or_best(None);

			let versions_stream = subscription_stream::<Block, _, _, _, _, _, _, _, _>(
				version_subscriptions,
				self.client
					.import_notification_stream()
					.map(|notification| Ok::<_, ()>(notification.hash))
					.compat(),
				display_error(
					runtime_version(&*remote_blockchain, fetcher.clone(), initial_block)
						.map(move |r| r.map(|r| (initial_block, r))),
				),
				move |block| runtime_version(&*remote_blockchain, fetcher.clone(), block),
				|_, old_version, new_version| {
					let version_differs = old_version
						.as_ref()
						.map(|old_version| *old_version != new_version)
						.unwrap_or(true);
					match version_differs {
						true => Some(new_version.clone()),
						false => None,
					}
				},
			);

			sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
				.send_all(versions_stream.map(|version| Ok(version)))
				// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
				.map(|_| ())
		});
	}

	fn unsubscribe_runtime_version(
		&self,
		_meta: Option<crate::Metadata>,
		id: SubscriptionId,
	) -> RpcResult<bool> {
		Ok(self.subscriptions.cancel(id))
	}

	fn trace_block(
		&self,
		_block: Block::Hash,
		_targets: Option<String>,
		_storage_keys: Option<String>,
	) -> FutureResult<sp_rpc::tracing::TraceBlockResponse> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}
}

impl<Block, F, Client> ChildStateBackend<Block, Client> for LightState<Block, F, Client>
where
	Block: BlockT,
	Client: BlockchainEvents<Block> + HeaderBackend<Block> + Send + Sync + 'static,
	F: Fetcher<Block> + 'static,
{
	fn read_child_proof(
		&self,
		_block: Option<Block::Hash>,
		_storage_key: PrefixedStorageKey,
		_keys: Vec<StorageKey>,
	) -> FutureResult<ReadProof<Block::Hash>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn storage_keys(
		&self,
		_block: Option<Block::Hash>,
		_storage_key: PrefixedStorageKey,
		_prefix: StorageKey,
	) -> FutureResult<Vec<StorageKey>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn storage_keys_paged(
		&self,
		_block: Option<Block::Hash>,
		_storage_key: PrefixedStorageKey,
		_prefix: Option<StorageKey>,
		_count: u32,
		_start_key: Option<StorageKey>,
	) -> FutureResult<Vec<StorageKey>> {
		Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
	}

	fn storage(
		&self,
		block: Option<Block::Hash>,
		storage_key: PrefixedStorageKey,
		key: StorageKey,
	) -> FutureResult<Option<StorageData>> {
		let block = self.block_or_best(block);
		let fetcher = self.fetcher.clone();
		let child_storage =
			resolve_header(&*self.remote_blockchain, &*self.fetcher, block).then(move |result| {
				match result {
					Ok(header) => Either::Left(
						fetcher
							.remote_read_child(RemoteReadChildRequest {
								block,
								header,
								storage_key,
								keys: vec![key.0.clone()],
								retry_count: Default::default(),
							})
							.then(move |result| {
								ready(
									result
										.map(|mut data| {
											data.remove(&key.0)
												.expect(
													"successful result has entry for all keys; qed",
												)
												.map(StorageData)
										})
										.map_err(client_err),
								)
							}),
					),
					Err(error) => Either::Right(ready(Err(error))),
				}
			});

		Box::new(child_storage.boxed().compat())
	}

	fn storage_hash(
		&self,
		block: Option<Block::Hash>,
		storage_key: PrefixedStorageKey,
		key: StorageKey,
	) -> FutureResult<Option<Block::Hash>> {
		Box::new(ChildStateBackend::storage(self, block, storage_key, key).and_then(
			|maybe_storage| {
				result(Ok(maybe_storage.map(|storage| HashFor::<Block>::hash(&storage.0))))
			},
		))
	}
}

/// Resolve header by hash.
fn resolve_header<Block: BlockT, F: Fetcher<Block>>(
	remote_blockchain: &dyn RemoteBlockchain<Block>,
	fetcher: &F,
	block: Block::Hash,
) -> impl std::future::Future<Output = Result<Block::Header, Error>> {
	let maybe_header = future_header(remote_blockchain, fetcher, BlockId::Hash(block));

	maybe_header.then(move |result| {
		ready(
			result
				.and_then(|maybe_header| {
					maybe_header.ok_or_else(|| ClientError::UnknownBlock(format!("{}", block)))
				})
				.map_err(client_err),
		)
	})
}

/// Call runtime method at given block
fn call<Block: BlockT, F: Fetcher<Block>>(
	remote_blockchain: &dyn RemoteBlockchain<Block>,
	fetcher: Arc<F>,
	block: Block::Hash,
	method: String,
	call_data: Bytes,
) -> impl std::future::Future<Output = Result<Bytes, Error>> {
	resolve_header(remote_blockchain, &*fetcher, block).then(move |result| match result {
		Ok(header) => Either::Left(
			fetcher
				.remote_call(RemoteCallRequest {
					block,
					header,
					method,
					call_data: call_data.0,
					retry_count: Default::default(),
				})
				.then(|result| ready(result.map(Bytes).map_err(client_err))),
		),
		Err(error) => Either::Right(ready(Err(error))),
	})
}

/// Get runtime version at given block.
fn runtime_version<Block: BlockT, F: Fetcher<Block>>(
	remote_blockchain: &dyn RemoteBlockchain<Block>,
	fetcher: Arc<F>,
	block: Block::Hash,
) -> impl std::future::Future<Output = Result<RuntimeVersion, Error>> {
	call(remote_blockchain, fetcher, block, "Core_version".into(), Bytes(Vec::new())).then(
		|version| {
			ready(version.and_then(|version| {
				Decode::decode(&mut &version.0[..])
					.map_err(|e| client_err(ClientError::VersionInvalid(e.to_string())))
			}))
		},
	)
}

/// Get storage value at given key at given block.
fn storage<Block: BlockT, F: Fetcher<Block>>(
	remote_blockchain: &dyn RemoteBlockchain<Block>,
	fetcher: Arc<F>,
	block: Block::Hash,
	keys: Vec<Vec<u8>>,
) -> impl std::future::Future<Output = Result<HashMap<StorageKey, Option<StorageData>>, Error>> {
	resolve_header(remote_blockchain, &*fetcher, block).then(move |result| match result {
		Ok(header) => Either::Left(
			fetcher
				.remote_read(RemoteReadRequest {
					block,
					header,
					keys,
					retry_count: Default::default(),
				})
				.then(|result| {
					ready(
						result
							.map(|result| {
								result
									.into_iter()
									.map(|(key, value)| (StorageKey(key), value.map(StorageData)))
									.collect()
							})
							.map_err(client_err),
					)
				}),
		),
		Err(error) => Either::Right(ready(Err(error))),
	})
}

/// Returns subscription stream that issues request on every imported block and
/// if value has changed from previous block, emits (stream) item.
fn subscription_stream<
	Block,
	Requests,
	FutureBlocksStream,
	V,
	N,
	InitialRequestFuture,
	IssueRequest,
	IssueRequestFuture,
	CompareValues,
>(
	shared_requests: Requests,
	future_blocks_stream: FutureBlocksStream,
	initial_request: InitialRequestFuture,
	issue_request: IssueRequest,
	compare_values: CompareValues,
) -> impl Stream<Item = N, Error = ()>
where
	Block: BlockT,
	Requests: 'static + SharedRequests<Block::Hash, V>,
	FutureBlocksStream: Stream<Item = Block::Hash, Error = ()>,
	V: Send + 'static + Clone,
	InitialRequestFuture:
		std::future::Future<Output = Result<(Block::Hash, V), ()>> + Send + 'static,
	IssueRequest: 'static + Fn(Block::Hash) -> IssueRequestFuture,
	IssueRequestFuture: std::future::Future<Output = Result<V, Error>> + Send + 'static,
	CompareValues: Fn(Block::Hash, Option<&V>, &V) -> Option<N>,
{
	// we need to send initial value first, then we'll only be sending if value has changed
	let previous_value = Arc::new(Mutex::new(None));

	// prepare 'stream' of initial values
	let initial_value_stream = ignore_error(initial_request).boxed().compat().into_stream();

	// prepare stream of future values
	//
	// we do not want to stop stream if single request fails
	// (the warning should have been already issued by the request issuer)
	let future_values_stream = future_blocks_stream.and_then(move |block| {
		ignore_error(
			maybe_share_remote_request::<Block, _, _, _, _>(
				shared_requests.clone(),
				block,
				&issue_request,
			)
			.map(move |r| r.map(|v| (block, v))),
		)
		.boxed()
		.compat()
	});

	// now let's return changed values for selected blocks
	initial_value_stream
		.chain(future_values_stream)
		.filter_map(move |block_and_new_value| {
			block_and_new_value.and_then(|(block, new_value)| {
				let mut previous_value = previous_value.lock();
				compare_values(block, previous_value.as_ref(), &new_value).map(
					|notification_value| {
						*previous_value = Some(new_value);
						notification_value
					},
				)
			})
		})
		.map_err(|_| ())
}

/// Request some data from remote node, probably reusing response from already
/// (in-progress) existing request.
fn maybe_share_remote_request<Block: BlockT, Requests, V, IssueRequest, IssueRequestFuture>(
	shared_requests: Requests,
	block: Block::Hash,
	issue_request: &IssueRequest,
) -> impl std::future::Future<Output = Result<V, ()>>
where
	V: Clone,
	Requests: SharedRequests<Block::Hash, V>,
	IssueRequest: Fn(Block::Hash) -> IssueRequestFuture,
	IssueRequestFuture: std::future::Future<Output = Result<V, Error>>,
{
	let (sender, receiver) = channel();
	let need_issue_request = shared_requests.listen_request(block, sender);

	// if that isn't the first request - just listen for existing request' response
	if !need_issue_request {
		return Either::Right(receiver.then(|r| ready(r.unwrap_or(Err(())))))
	}

	// that is the first request - issue remote request + notify all listeners on
	// completion
	Either::Left(display_error(issue_request(block)).then(move |remote_result| {
		let listeners = shared_requests.on_response_received(block);
		// skip first element, because this future is the first element
		for receiver in listeners.into_iter().skip(1) {
			if let Err(_) = receiver.send(remote_result.clone()) {
				// we don't care if receiver has been dropped already
			}
		}

		ready(remote_result)
	}))
}

/// Convert successful future result into Ok(result) and error into Err(()),
/// displaying warning.
fn display_error<F, T>(future: F) -> impl std::future::Future<Output = Result<T, ()>>
where
	F: std::future::Future<Output = Result<T, Error>>,
{
	future.then(|result| {
		ready(result.or_else(|err| {
			warn!("Remote request for subscription data has failed with: {:?}", err);
			Err(())
		}))
	})
}

/// Convert successful future result into Ok(Some(result)) and error into Ok(None),
/// displaying warning.
fn ignore_error<F, T>(future: F) -> impl std::future::Future<Output = Result<Option<T>, ()>>
where
	F: std::future::Future<Output = Result<T, ()>>,
{
	future.then(|result| {
		ready(match result {
			Ok(result) => Ok(Some(result)),
			Err(()) => Ok(None),
		})
	})
}

#[cfg(test)]
mod tests {
	use super::*;
	use rpc::futures::stream::futures_ordered;
	use sp_core::H256;
	use substrate_test_runtime_client::runtime::Block;

	#[test]
	fn subscription_stream_works() {
		let stream = subscription_stream::<Block, _, _, _, _, _, _, _, _>(
			SimpleSubscriptions::default(),
			futures_ordered(vec![result(Ok(H256::from([2; 32]))), result(Ok(H256::from([3; 32])))]),
			ready(Ok((H256::from([1; 32]), 100))),
			|block| match block[0] {
				2 => ready(Ok(100)),
				3 => ready(Ok(200)),
				_ => unreachable!("should not issue additional requests"),
			},
			|_, old_value, new_value| match old_value == Some(new_value) {
				true => None,
				false => Some(new_value.clone()),
			},
		);

		assert_eq!(stream.collect().wait(), Ok(vec![100, 200]));
	}

	#[test]
	fn subscription_stream_ignores_failed_requests() {
		let stream = subscription_stream::<Block, _, _, _, _, _, _, _, _>(
			SimpleSubscriptions::default(),
			futures_ordered(vec![result(Ok(H256::from([2; 32]))), result(Ok(H256::from([3; 32])))]),
			ready(Ok((H256::from([1; 32]), 100))),
			|block| match block[0] {
				2 => ready(Err(client_err(ClientError::NotAvailableOnLightClient))),
				3 => ready(Ok(200)),
				_ => unreachable!("should not issue additional requests"),
			},
			|_, old_value, new_value| match old_value == Some(new_value) {
				true => None,
				false => Some(new_value.clone()),
			},
		);

		assert_eq!(stream.collect().wait(), Ok(vec![100, 200]));
	}

	#[test]
	fn maybe_share_remote_request_shares_request() {
		type UnreachableFuture = futures::future::Ready<Result<u32, Error>>;

		let shared_requests = SimpleSubscriptions::default();

		// let's 'issue' requests for B1
		shared_requests.lock().insert(H256::from([1; 32]), vec![channel().0]);

		// make sure that no additional requests are issued when we're asking for B1
		let _ = maybe_share_remote_request::<Block, _, _, _, UnreachableFuture>(
			shared_requests.clone(),
			H256::from([1; 32]),
			&|_| unreachable!("no duplicate requests issued"),
		);

		// make sure that additional requests is issued when we're asking for B2
		let request_issued = Arc::new(Mutex::new(false));
		let _ = maybe_share_remote_request::<Block, _, _, _, UnreachableFuture>(
			shared_requests.clone(),
			H256::from([2; 32]),
			&|_| {
				*request_issued.lock() = true;
				ready(Ok(Default::default()))
			},
		);
		assert!(*request_issued.lock());
	}
}