jam-std-common 0.1.26

Common datatypes and utilities for the JAM nodes and tooling
Documentation
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
use super::{
	crypto::hashing::hash_raw,
	extrinsic::WorkReport,
	node::{
		BlockDesc, ChainSub, ChainSubUpdate, Error as NodeError, Node, NodeResult, SyncState,
		SyncStatus, VersionedParameters, WorkPackageStatus,
	},
};
use bytes::Bytes;
use codec::{DecodeAll, Encode};
use futures::{stream::BoxStream, Stream, StreamExt};
use jam_types::{
	AnyBytes, AnyHash, AnyVec, CoreIndex, ExtrinsicHash, Hash, HeaderHash, MmrPeakHash, Segment,
	SegmentTreeRoot, ServiceId, Slot, StateRootHash, WorkPackage, WorkPackageHash, WorkReportHash,
	WrappedSegment,
};
use jsonrpsee::{
	core::{ClientError, RpcResult, SubscriptionResult},
	proc_macros::rpc,
	types::{ErrorObject, ErrorObjectOwned},
	PendingSubscriptionSink, SubscriptionMessage,
};

pub mod error_codes {
	pub const OTHER: i32 = 0;
	pub const BLOCK_UNAVAILABLE: i32 = 1;
	pub const WORK_REPORT_UNAVAILABLE: i32 = 2;
	pub const SEGMENT_UNAVAILABLE: i32 = 3;
}

/// JAM node RPC interface.
///
/// `RpcServer` is not intended to be implemented directly. Instead of implementing `RpcServer`,
/// implement `Node` and use the blanket implementation of `RpcServer` for `Node` types.
///
/// Similarly, instead of using the `RpcClient` trait directly, use the `Node` trait; this is
/// implemented for all `RpcClient` types and it is also directly implemented by eg PolkaJam.
#[rpc(client, server)]
pub trait Rpc {
	/// Returns the chain parameters.
	#[method(name = "parameters")]
	async fn parameters(&self) -> RpcResult<VersionedParameters>;

	/// Returns the header hash and slot of the head of the "best" chain.
	#[method(name = "bestBlock")]
	async fn best_block(&self) -> RpcResult<BlockDesc>;

	/// Subscribe to updates of the head of the "best" chain, as returned by `bestBlock`.
	#[subscription(name = "subscribeBestBlock", item = BlockDesc)]
	async fn subscribe_best_block(&self) -> SubscriptionResult;

	/// Returns the header hash and slot of the latest finalized block.
	#[method(name = "finalizedBlock")]
	async fn finalized_block(&self) -> RpcResult<BlockDesc>;

	/// Subscribe to updates of the latest finalized block, as returned by `finalizedBlock`.
	#[subscription(name = "subscribeFinalizedBlock", item = BlockDesc)]
	async fn subscribe_finalized_block(&self) -> SubscriptionResult;

	/// Returns the header hash and slot of the parent of the block with the given header hash.
	#[method(name = "parent")]
	async fn parent(&self, header_hash: HeaderHash) -> RpcResult<BlockDesc>;

	/// Returns the posterior state root of the block with the given header hash.
	#[method(name = "stateRoot")]
	async fn state_root(&self, header_hash: HeaderHash) -> RpcResult<StateRootHash>;

	/// Returns the BEEFY root of the block with the given header hash.
	#[method(name = "beefyRoot")]
	async fn beefy_root(&self, header_hash: HeaderHash) -> RpcResult<MmrPeakHash>;

	/// Returns the activity statistics stored in the posterior state of the block with the given
	/// header hash.
	///
	/// The statistics are encoded as per the GP.
	#[method(name = "statistics")]
	async fn statistics(&self, header_hash: HeaderHash) -> RpcResult<AnyBytes>;

	/// Subscribe to updates of the activity statistics stored in chain state.
	///
	/// The statistics are encoded as per the GP.
	#[subscription(name = "subscribeStatistics", item = ChainSubUpdate<AnyBytes>)]
	async fn subscribe_statistics(&self, finalized: bool) -> SubscriptionResult;

	/// Returns the storage data for the service with the given ID.
	///
	/// The data are encoded as per the GP. `None` is returned if there is no service with the
	/// given ID.
	#[method(name = "serviceData")]
	async fn service_data(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
	) -> RpcResult<Option<AnyBytes>>;

	/// Subscribe to updates of the storage data for the service with the given ID.
	///
	/// The `value` field of updates will contain service data encoded as per the GP. It will be
	/// `None` when there is no service with the given ID.
	#[subscription(name = "subscribeServiceData", item = ChainSubUpdate<Option<AnyBytes>>)]
	async fn subscribe_service_data(&self, id: ServiceId, finalized: bool) -> SubscriptionResult;

	/// Returns the value associated with the given service ID and key in the posterior state of
	/// the block with the given header hash.
	///
	/// `None` is returned if there is no value associated with the given service ID and key.
	///
	/// This method can be used to query arbitrary key-value pairs set by service accumulation
	/// logic.
	#[method(name = "serviceValue")]
	async fn service_value(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		key: AnyVec,
	) -> RpcResult<Option<AnyBytes>>;

	/// Subscribe to updates of the value associated with the given service ID and key.
	///
	/// The `value` field of updates will be `None` when there is no value associated with the
	/// given service ID and key.
	#[subscription(name = "subscribeServiceValue", item = ChainSubUpdate<Option<AnyBytes>>)]
	async fn subscribe_service_value(
		&self,
		id: ServiceId,
		key: AnyVec,
		finalized: bool,
	) -> SubscriptionResult;

	/// Returns the preimage of the given hash, if it has been provided to the given service in the
	/// posterior state of the block with the given header hash.
	///
	/// `None` is returned if the preimage has not been provided to the given service.
	#[method(name = "servicePreimage")]
	async fn service_preimage(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		hash: AnyHash,
	) -> RpcResult<Option<AnyBytes>>;

	/// Subscribe to updates of the preimage associated with the given service ID and hash.
	///
	/// The `value` field of updates will be `None` if the preimage has not been provided to the
	/// service. Otherwise, it will be the preimage of the given hash.
	#[subscription(name = "subscribeServicePreimage", item = ChainSubUpdate<Option<AnyBytes>>)]
	async fn subscribe_service_preimage(
		&self,
		id: ServiceId,
		hash: AnyHash,
		finalized: bool,
	) -> SubscriptionResult;

	/// Returns the preimage request associated with the given service ID and hash/length in the
	/// posterior state of the block with the given header hash.
	///
	/// `None` is returned if the preimage with the given hash/length has neither been requested by
	/// nor provided to the given service. An empty list is returned if the preimage has been
	/// requested, but not yet provided. A non-empty list means that the preimage has been
	/// provided; the meaning of the slots in the list is as follows:
	///
	/// - The first slot is the slot in which the preimage was provided.
	/// - The second slot, if present, is the slot in which the preimage was "forgotten".
	/// - The third slot, if present, is the slot in which the preimage was requested again.
	#[method(name = "serviceRequest")]
	async fn service_request(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		hash: AnyHash,
		len: u32,
	) -> RpcResult<Option<Vec<Slot>>>;

	/// Subscribe to updates of the preimage request associated with the given service ID and
	/// hash/length.
	///
	/// The `value` field of updates will either be `None` or a list of slots, with the same
	/// semantics as `serviceRequest` return values.
	#[subscription(name = "subscribeServiceRequest", item = ChainSubUpdate<Option<Vec<Slot>>>)]
	async fn subscribe_service_request(
		&self,
		id: ServiceId,
		hash: AnyHash,
		len: u32,
		finalized: bool,
	) -> SubscriptionResult;

	/// Returns the work-report with the given hash.
	///
	/// The work-report is encoded as per the GP.
	#[method(name = "workReport")]
	async fn work_report(&self, hash: WorkReportHash) -> RpcResult<AnyBytes>;

	/// Submit a work-package to the guarantors currently assigned to the given core.
	#[method(name = "submitWorkPackage")]
	async fn submit_work_package(
		&self,
		core: CoreIndex,
		package: AnyBytes,
		extrinsics: Vec<AnyBytes>,
	) -> RpcResult<()>;

	/// Submit a work-package bundle to the guarantors currently assigned to the given core.
	#[method(name = "submitWorkPackageBundle")]
	async fn submit_work_package_bundle(&self, core: CoreIndex, bundle: AnyBytes) -> RpcResult<()>;

	/// Returns the status of the given work-package following execution of the block with the
	/// given header hash.
	///
	/// If `anchor` does not match the anchor of the work-package then an error or an incorrect
	/// status may be returned. An error may be returned if `anchor` is too old.
	#[method(name = "workPackageStatus")]
	async fn work_package_status(
		&self,
		header_hash: HeaderHash,
		hash: WorkPackageHash,
		anchor: HeaderHash,
	) -> RpcResult<WorkPackageStatus>;

	/// Subscribe to status updates for the given work-package.
	///
	/// If `anchor` does not match the anchor of the work-package then the subscription may fail or
	/// yield incorrect statuses. The subscription may fail if `anchor` is too old.
	#[subscription(name = "subscribeWorkPackageStatus", item = ChainSubUpdate<WorkPackageStatus>)]
	async fn subscribe_work_package_status(
		&self,
		hash: WorkPackageHash,
		anchor: HeaderHash,
		finalized: bool,
	) -> SubscriptionResult;

	/// Submit a preimage which is being requested by the given service.
	///
	/// Note that this method does not wait for the preimage to be distributed or integrated
	/// on-chain; it returns immediately.
	#[method(name = "submitPreimage")]
	async fn submit_preimage(&self, requester: ServiceId, preimage: AnyBytes) -> RpcResult<()>;

	/// Returns a list of all services currently known to be on JAM.
	///
	/// This is a best-effort list and may not reflect the true state. Nodes could e.g. reasonably
	/// hide services which are not recently active from this list.
	#[method(name = "listServices")]
	async fn list_services(&self, header_hash: HeaderHash) -> RpcResult<Vec<ServiceId>>;

	/// Fetches a list of segments from the DA layer, exported by the work-package with the given
	/// hash.
	#[method(name = "fetchWorkPackageSegments")]
	async fn fetch_work_package_segments(
		&self,
		wp_hash: WorkPackageHash,
		indices: Vec<u16>,
	) -> RpcResult<Vec<WrappedSegment>>;

	/// Fetches a list of segments from the DA layer, exported by a work-package with the given
	/// segment root hash.
	#[method(name = "fetchSegments")]
	async fn fetch_segments(
		&self,
		segment_root: SegmentTreeRoot,
		indices: Vec<u16>,
	) -> RpcResult<Vec<WrappedSegment>>;

	/// Returns the sync status of the node.
	#[method(name = "syncState")]
	async fn sync_state(&self) -> RpcResult<SyncState>;

	/// Subscribe to changes in sync status.
	#[subscription(name = "subscribeSyncStatus", item = SyncStatus)]
	async fn subscribe_sync_status(&self) -> SubscriptionResult;
}

impl From<ClientError> for NodeError {
	fn from(err: ClientError) -> Self {
		if let ClientError::Call(err) = &err {
			match err.code() {
				error_codes::BLOCK_UNAVAILABLE =>
					if let Some(data) = err.data() {
						if let Ok(hash) = serde_json::from_str(data.get()) {
							return NodeError::BlockUnavailable(hash)
						}
					},
				error_codes::WORK_REPORT_UNAVAILABLE =>
					if let Some(data) = err.data() {
						if let Ok(hash) = serde_json::from_str(data.get()) {
							return NodeError::WorkReportUnavailable(hash)
						}
					},
				error_codes::SEGMENT_UNAVAILABLE => return NodeError::SegmentUnavailable,
				_ => (),
			}
		}
		NodeError::Other(err.to_string())
	}
}

impl From<serde_json::Error> for NodeError {
	fn from(err: serde_json::Error) -> Self {
		NodeError::Other(err.to_string())
	}
}

#[async_trait::async_trait]
impl<T: RpcClient + Send + Sync> Node for T {
	async fn parameters(&self) -> NodeResult<VersionedParameters> {
		Ok(<T as RpcClient>::parameters(self).await?)
	}

	async fn best_block(&self) -> NodeResult<BlockDesc> {
		Ok(<T as RpcClient>::best_block(self).await?)
	}

	async fn subscribe_best_block(&self) -> NodeResult<BoxStream<NodeResult<BlockDesc>>> {
		let sub = <T as RpcClient>::subscribe_best_block(self).await?;
		Ok(sub.map(|res| Ok(res?)).boxed())
	}

	async fn finalized_block(&self) -> NodeResult<BlockDesc> {
		Ok(<T as RpcClient>::finalized_block(self).await?)
	}

	async fn subscribe_finalized_block(&self) -> NodeResult<BoxStream<NodeResult<BlockDesc>>> {
		let sub = <T as RpcClient>::subscribe_finalized_block(self).await?;
		Ok(sub.map(|res| Ok(res?)).boxed())
	}

	async fn parent(&self, header_hash: HeaderHash) -> NodeResult<BlockDesc> {
		Ok(<T as RpcClient>::parent(self, header_hash).await?)
	}

	async fn state_root(&self, header_hash: HeaderHash) -> NodeResult<StateRootHash> {
		Ok(<T as RpcClient>::state_root(self, header_hash).await?)
	}

	async fn beefy_root(&self, header_hash: HeaderHash) -> NodeResult<MmrPeakHash> {
		Ok(<T as RpcClient>::beefy_root(self, header_hash).await?)
	}

	async fn encoded_statistics(&self, header_hash: HeaderHash) -> NodeResult<Bytes> {
		Ok(<T as RpcClient>::statistics(self, header_hash).await?.into())
	}

	async fn subscribe_encoded_statistics(&self, finalized: bool) -> NodeResult<ChainSub<Bytes>> {
		let sub = <T as RpcClient>::subscribe_statistics(self, finalized).await?;
		Ok(sub.map(|res| Ok(res?.map(Into::into))).boxed())
	}

	async fn encoded_service_data(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
	) -> NodeResult<Option<Bytes>> {
		Ok(<T as RpcClient>::service_data(self, header_hash, id).await?.map(Into::into))
	}

	async fn subscribe_encoded_service_data(
		&self,
		id: ServiceId,
		finalized: bool,
	) -> NodeResult<ChainSub<Option<Bytes>>> {
		let sub = <T as RpcClient>::subscribe_service_data(self, id, finalized).await?;
		Ok(sub.map(|res| Ok(res?.map_some(Into::into))).boxed())
	}

	async fn service_value(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		key: &[u8],
	) -> NodeResult<Option<Bytes>> {
		Ok(<T as RpcClient>::service_value(self, header_hash, id, key.to_vec().into())
			.await?
			.map(Into::into))
	}

	async fn subscribe_service_value(
		&self,
		id: ServiceId,
		key: &[u8],
		finalized: bool,
	) -> NodeResult<ChainSub<Option<Bytes>>> {
		let sub =
			<T as RpcClient>::subscribe_service_value(self, id, key.to_vec().into(), finalized)
				.await?;
		Ok(sub.map(|res| Ok(res?.map_some(Into::into))).boxed())
	}

	async fn service_preimage(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		hash: Hash,
	) -> NodeResult<Option<Bytes>> {
		Ok(<T as RpcClient>::service_preimage(self, header_hash, id, hash.into())
			.await?
			.map(Into::into))
	}

	async fn subscribe_service_preimage(
		&self,
		id: ServiceId,
		hash: Hash,
		finalized: bool,
	) -> NodeResult<ChainSub<Option<Bytes>>> {
		let sub =
			<T as RpcClient>::subscribe_service_preimage(self, id, hash.into(), finalized).await?;
		Ok(sub.map(|res| Ok(res?.map_some(Into::into))).boxed())
	}

	async fn service_request(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		hash: Hash,
		len: u32,
	) -> NodeResult<Option<Vec<Slot>>> {
		Ok(<T as RpcClient>::service_request(self, header_hash, id, hash.into(), len).await?)
	}

	async fn subscribe_service_request(
		&self,
		id: ServiceId,
		hash: Hash,
		len: u32,
		finalized: bool,
	) -> NodeResult<ChainSub<Option<Vec<Slot>>>> {
		let sub =
			<T as RpcClient>::subscribe_service_request(self, id, hash.into(), len, finalized)
				.await?;
		Ok(sub.map(|res| Ok(res?)).boxed())
	}

	async fn work_report(&self, hash: WorkReportHash) -> NodeResult<WorkReport> {
		let encoded = <T as RpcClient>::work_report(self, hash).await?;
		Ok(WorkReport::decode_all(&mut &encoded[..])?)
	}

	async fn submit_encoded_work_package(
		&self,
		core: CoreIndex,
		package: Bytes,
		extrinsics: &[Bytes],
	) -> NodeResult<()> {
		Ok(<T as RpcClient>::submit_work_package(
			self,
			core,
			package.into(),
			extrinsics.iter().cloned().map(Into::into).collect(),
		)
		.await?)
	}

	async fn submit_encoded_work_package_bundle(
		&self,
		core: CoreIndex,
		bundle: Bytes,
	) -> NodeResult<()> {
		Ok(<T as RpcClient>::submit_work_package_bundle(self, core, bundle.into()).await?)
	}

	async fn work_package_status(
		&self,
		header_hash: HeaderHash,
		hash: WorkPackageHash,
		anchor: HeaderHash,
	) -> NodeResult<WorkPackageStatus> {
		Ok(<T as RpcClient>::work_package_status(self, header_hash, hash, anchor).await?)
	}

	async fn subscribe_work_package_status(
		&self,
		hash: WorkPackageHash,
		anchor: HeaderHash,
		finalized: bool,
	) -> NodeResult<ChainSub<WorkPackageStatus>> {
		let sub =
			<T as RpcClient>::subscribe_work_package_status(self, hash, anchor, finalized).await?;
		Ok(sub.map(|res| Ok(res?)).boxed())
	}

	async fn submit_preimage(&self, requester: ServiceId, preimage: Bytes) -> NodeResult<()> {
		Ok(<T as RpcClient>::submit_preimage(self, requester, preimage.into()).await?)
	}

	async fn list_services(&self, header_hash: HeaderHash) -> NodeResult<Vec<ServiceId>> {
		Ok(<T as RpcClient>::list_services(self, header_hash).await?)
	}

	async fn fetch_work_package_segments(
		&self,
		wp_hash: WorkPackageHash,
		indices: Vec<u16>,
	) -> NodeResult<Vec<Segment>> {
		// The into_iter().map(Into::into).collect() here _should_ be a no-op!
		Ok(<T as RpcClient>::fetch_work_package_segments(self, wp_hash, indices)
			.await?
			.into_iter()
			.map(Into::into)
			.collect())
	}

	async fn fetch_segments(
		&self,
		segment_root: SegmentTreeRoot,
		indices: Vec<u16>,
	) -> NodeResult<Vec<Segment>> {
		// The into_iter().map(Into::into).collect() here _should_ be a no-op!
		Ok(<T as RpcClient>::fetch_segments(self, segment_root, indices)
			.await?
			.into_iter()
			.map(Into::into)
			.collect())
	}

	async fn sync_state(&self) -> NodeResult<SyncState> {
		Ok(<T as RpcClient>::sync_state(self).await?)
	}

	async fn subscribe_sync_status(&self) -> NodeResult<BoxStream<NodeResult<SyncStatus>>> {
		let sub = <T as RpcClient>::subscribe_sync_status(self).await?;
		Ok(sub.map(|res| Ok(res?)).boxed())
	}
}

impl From<NodeError> for ErrorObjectOwned {
	fn from(err: NodeError) -> Self {
		match err {
			NodeError::Other(message) =>
				ErrorObject::owned(error_codes::OTHER, message, None::<()>),
			NodeError::BlockUnavailable(hash) =>
				ErrorObject::owned(error_codes::BLOCK_UNAVAILABLE, err.to_string(), Some(hash)),
			NodeError::WorkReportUnavailable(hash) => ErrorObject::owned(
				error_codes::WORK_REPORT_UNAVAILABLE,
				err.to_string(),
				Some(hash),
			),
			NodeError::SegmentUnavailable =>
				ErrorObject::owned(error_codes::SEGMENT_UNAVAILABLE, err.to_string(), None::<()>),
		}
	}
}

async fn relay_subscription<T: serde::Serialize>(
	sub: NodeResult<impl Stream<Item = NodeResult<T>> + Unpin>,
	pending: PendingSubscriptionSink,
) -> SubscriptionResult {
	let mut sub = match sub {
		Ok(sub) => sub,
		Err(err) => {
			pending.reject(err).await;
			return Ok(())
		},
	};
	let sink = pending.accept().await?;
	while let Some(res) = sub.next().await {
		let item: T = res?;
		let msg = SubscriptionMessage::from_json(&item)?;
		sink.send(msg).await?;
	}
	Ok(())
}

/// Returns `Ok` iff `extrinsics` matches the extrinsic specs in `package`.
fn check_extrinsics(package: &WorkPackage, extrinsics: &[Bytes]) -> NodeResult<()> {
	let num_specs = package.extrinsic_count();
	if extrinsics.len() != (num_specs as usize) {
		return Err(NodeError::Other(format!(
			"{} extrinsics provided, package specifies {num_specs}",
			extrinsics.len()
		)))
	}

	for (i, (spec, extrinsic)) in package
		.items
		.iter()
		.flat_map(|item| item.extrinsics.iter())
		.zip(extrinsics.iter())
		.enumerate()
	{
		if extrinsic.len() != (spec.len as usize) {
			return Err(NodeError::Other(format!(
				"Extrinsic {i} has length {}, package specifies length {}",
				extrinsic.len(),
				spec.len
			)));
		}

		let hash: ExtrinsicHash = hash_raw(extrinsic).into();
		if hash != spec.hash {
			return Err(NodeError::Other(format!(
				"Extrinsic {i} has hash {hash}, package specifies hash {}",
				spec.hash
			)));
		}
	}

	Ok(())
}

fn check_package(mut package: &[u8], extrinsics: &[Bytes]) -> NodeResult<()> {
	let package = WorkPackage::decode_all(&mut package)?;
	check_extrinsics(&package, extrinsics)
}

#[async_trait::async_trait]
impl<T: Node + 'static> RpcServer for T {
	async fn parameters(&self) -> RpcResult<VersionedParameters> {
		Ok(<T as Node>::parameters(self).await?)
	}

	async fn best_block(&self) -> RpcResult<BlockDesc> {
		Ok(<T as Node>::best_block(self).await?)
	}

	async fn subscribe_best_block(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
		relay_subscription::<BlockDesc>(<T as Node>::subscribe_best_block(self).await, pending)
			.await
	}

	async fn finalized_block(&self) -> RpcResult<BlockDesc> {
		Ok(<T as Node>::finalized_block(self).await?)
	}

	async fn subscribe_finalized_block(
		&self,
		pending: PendingSubscriptionSink,
	) -> SubscriptionResult {
		relay_subscription::<BlockDesc>(<T as Node>::subscribe_finalized_block(self).await, pending)
			.await
	}

	async fn parent(&self, header_hash: HeaderHash) -> RpcResult<BlockDesc> {
		Ok(<T as Node>::parent(self, header_hash).await?)
	}

	async fn state_root(&self, header_hash: HeaderHash) -> RpcResult<StateRootHash> {
		Ok(<T as Node>::state_root(self, header_hash).await?)
	}

	async fn beefy_root(&self, header_hash: HeaderHash) -> RpcResult<MmrPeakHash> {
		Ok(<T as Node>::beefy_root(self, header_hash).await?)
	}

	async fn statistics(&self, header_hash: HeaderHash) -> RpcResult<AnyBytes> {
		Ok(<T as Node>::encoded_statistics(self, header_hash).await?.into())
	}

	async fn subscribe_statistics(
		&self,
		pending: PendingSubscriptionSink,
		finalized: bool,
	) -> SubscriptionResult {
		relay_subscription::<ChainSubUpdate<AnyBytes>>(
			<T as Node>::subscribe_encoded_statistics(self, finalized)
				.await
				.map(|sub| sub.map(|res| Ok(res?.map(Into::into)))),
			pending,
		)
		.await
	}

	async fn service_data(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
	) -> RpcResult<Option<AnyBytes>> {
		Ok(<T as Node>::encoded_service_data(self, header_hash, id).await?.map(Into::into))
	}

	async fn subscribe_service_data(
		&self,
		pending: PendingSubscriptionSink,
		id: ServiceId,
		finalized: bool,
	) -> SubscriptionResult {
		relay_subscription::<ChainSubUpdate<Option<AnyBytes>>>(
			<T as Node>::subscribe_encoded_service_data(self, id, finalized)
				.await
				.map(|sub| sub.map(|res| Ok(res?.map_some(Into::into)))),
			pending,
		)
		.await
	}

	async fn service_value(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		key: AnyVec,
	) -> RpcResult<Option<AnyBytes>> {
		Ok(<T as Node>::service_value(self, header_hash, id, &key).await?.map(Into::into))
	}

	async fn subscribe_service_value(
		&self,
		pending: PendingSubscriptionSink,
		id: ServiceId,
		key: AnyVec,
		finalized: bool,
	) -> SubscriptionResult {
		relay_subscription::<ChainSubUpdate<Option<AnyBytes>>>(
			<T as Node>::subscribe_service_value(self, id, &key, finalized)
				.await
				.map(|sub| sub.map(|res| Ok(res?.map_some(Into::into)))),
			pending,
		)
		.await
	}

	async fn service_preimage(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		hash: AnyHash,
	) -> RpcResult<Option<AnyBytes>> {
		Ok(<T as Node>::service_preimage(self, header_hash, id, hash.into())
			.await?
			.map(Into::into))
	}

	async fn subscribe_service_preimage(
		&self,
		pending: PendingSubscriptionSink,
		id: ServiceId,
		hash: AnyHash,
		finalized: bool,
	) -> SubscriptionResult {
		relay_subscription::<ChainSubUpdate<Option<AnyBytes>>>(
			<T as Node>::subscribe_service_preimage(self, id, hash.into(), finalized)
				.await
				.map(|sub| sub.map(|res| Ok(res?.map_some(Into::into)))),
			pending,
		)
		.await
	}

	async fn service_request(
		&self,
		header_hash: HeaderHash,
		id: ServiceId,
		hash: AnyHash,
		len: u32,
	) -> RpcResult<Option<Vec<Slot>>> {
		Ok(<T as Node>::service_request(self, header_hash, id, hash.into(), len).await?)
	}

	async fn subscribe_service_request(
		&self,
		pending: PendingSubscriptionSink,
		id: ServiceId,
		hash: AnyHash,
		len: u32,
		finalized: bool,
	) -> SubscriptionResult {
		relay_subscription::<ChainSubUpdate<Option<Vec<Slot>>>>(
			<T as Node>::subscribe_service_request(self, id, hash.into(), len, finalized).await,
			pending,
		)
		.await
	}

	async fn work_report(&self, hash: WorkReportHash) -> RpcResult<AnyBytes> {
		let report = <T as Node>::work_report(self, hash).await?;
		Ok(Bytes::from(report.encode()).into())
	}

	async fn submit_work_package(
		&self,
		core: CoreIndex,
		package: AnyBytes,
		extrinsics: Vec<AnyBytes>,
	) -> RpcResult<()> {
		// This _should_ be a no-op!
		let extrinsics: Vec<Bytes> = extrinsics.into_iter().map(Into::into).collect();
		check_package(&package, &extrinsics)?;
		Ok(<T as Node>::submit_encoded_work_package(self, core, package.into(), &extrinsics)
			.await?)
	}

	async fn submit_work_package_bundle(&self, core: CoreIndex, bundle: AnyBytes) -> RpcResult<()> {
		Ok(<T as Node>::submit_encoded_work_package_bundle(self, core, bundle.into()).await?)
	}

	async fn work_package_status(
		&self,
		header_hash: HeaderHash,
		hash: WorkPackageHash,
		anchor: HeaderHash,
	) -> RpcResult<WorkPackageStatus> {
		Ok(<T as Node>::work_package_status(self, header_hash, hash, anchor).await?)
	}

	async fn subscribe_work_package_status(
		&self,
		pending: PendingSubscriptionSink,
		hash: WorkPackageHash,
		anchor: HeaderHash,
		finalized: bool,
	) -> SubscriptionResult {
		relay_subscription::<ChainSubUpdate<WorkPackageStatus>>(
			<T as Node>::subscribe_work_package_status(self, hash, anchor, finalized).await,
			pending,
		)
		.await
	}

	async fn submit_preimage(&self, requester: ServiceId, preimage: AnyBytes) -> RpcResult<()> {
		Ok(<T as Node>::submit_preimage(self, requester, preimage.into()).await?)
	}

	async fn list_services(&self, header_hash: HeaderHash) -> RpcResult<Vec<ServiceId>> {
		Ok(<T as Node>::list_services(self, header_hash).await?)
	}

	async fn fetch_work_package_segments(
		&self,
		wp_hash: WorkPackageHash,
		indices: Vec<u16>,
	) -> RpcResult<Vec<WrappedSegment>> {
		// The into_iter().map(Into::into).collect() here _should_ be a no-op!
		Ok(<T as Node>::fetch_work_package_segments(self, wp_hash, indices)
			.await?
			.into_iter()
			.map(Into::into)
			.collect())
	}

	async fn fetch_segments(
		&self,
		segment_root: SegmentTreeRoot,
		indices: Vec<u16>,
	) -> RpcResult<Vec<WrappedSegment>> {
		// The into_iter().map(Into::into).collect() here _should_ be a no-op!
		Ok(<T as Node>::fetch_segments(self, segment_root, indices)
			.await?
			.into_iter()
			.map(Into::into)
			.collect())
	}

	async fn sync_state(&self) -> RpcResult<SyncState> {
		Ok(<T as Node>::sync_state(self).await?)
	}

	async fn subscribe_sync_status(&self, pending: PendingSubscriptionSink) -> SubscriptionResult {
		relay_subscription::<SyncStatus>(<T as Node>::subscribe_sync_status(self).await, pending)
			.await
	}
}