jam-pvm-common 0.1.28

Common logic for JAM PVM crates including services and authorizers
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
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
use crate::{
	imports,
	result::{ApiResult, IntoApiOption as _, IntoApiResult as _, IntoInvokeResult as _},
	ApiError, InvokeOutcome,
};
use alloc::{vec, vec::Vec};
use codec::Encode;
use core::{
	mem::{size_of, size_of_val, MaybeUninit},
	ptr,
};
use jam_types::*;

/// Check whether a preimage is available for lookup in the service.
///
/// - `hash`: The hash of the preimage to check availability.
///
/// Returns `true` if the preimage is available, `false` otherwise.
///
/// NOTE: Internally this uses the `historical_lookup` host call.
pub fn is_historical_available(hash: &[u8; 32]) -> bool {
	raw_foreign_historical_lookup_into(u64::MAX, hash, &mut []).is_some()
}

/// Check whether a preimage is available for lookup in another service.
///
/// - `service_id`: The service in whose preimage store to check availability.
/// - `hash`: The hash of the preimage to check availability.
///
/// Returns `true` if the preimage is available, `false` otherwise.
///
/// NOTE: Internally this uses the `historical_lookup` host call.
pub fn is_foreign_historical_available(service_id: ServiceId, hash: &[u8; 32]) -> bool {
	raw_foreign_historical_lookup_into(service_id as _, hash, &mut []).is_some()
}

/// Make a lookup into the service's preimage store without allocating.
///
/// - `hash`: The hash of the preimage to look up.
/// - `output`: The buffer to write the preimage into.
///
/// Returns the number of bytes written into the output buffer or `None` if the preimage was not
/// available.
///
/// NOTE: Internally this uses the `historical_lookup` host call.
pub fn historical_lookup_into(hash: &[u8; 32], output: &mut [u8]) -> Option<usize> {
	raw_foreign_historical_lookup_into(u64::MAX, hash, output)
}

/// Make a lookup into another service's preimage store without allocating.
///
/// - `service_id`: The service in whose preimage store to find the preimage.
/// - `hash`: The hash of the preimage to look up.
/// - `output`: The buffer to write the preimage into.
///
/// Returns the number of bytes written into the output buffer or `None` if the preimage was not
/// available.
///
/// NOTE: Internally this uses the `historical_lookup` host call.
pub fn foreign_historical_lookup_into(
	service_id: ServiceId,
	hash: &[u8; 32],
	output: &mut [u8],
) -> Option<usize> {
	raw_foreign_historical_lookup_into(service_id as _, hash, output)
}

/// Make a lookup into the service's preimage store.
///
/// - `hash`: The hash of the preimage to look up.
///
/// Returns the preimage or `None` if the preimage was not available.
///
/// NOTE: Internally this uses the `historical_lookup` host call.
pub fn historical_lookup(hash: &[u8; 32]) -> Option<Vec<u8>> {
	raw_foreign_historical_lookup(u64::MAX, hash)
}

/// Make a lookup into another service's preimage store.
///
/// - `service_id`: The service in whose preimage store to find the preimage.
/// - `hash`: The hash of the preimage to look up.
///
/// Returns the preimage or `None` if the preimage was not available.
///
/// NOTE: Internally this uses the `historical_lookup` host call.
pub fn foreign_historical_lookup(service_id: ServiceId, hash: &[u8; 32]) -> Option<Vec<u8>> {
	raw_foreign_historical_lookup(service_id as _, hash)
}

/// A definition of data to be fetched.
#[derive(Copy, Clone, Debug)]
pub enum Fetch {
	/// Protocol parameters.
	ProtocolParameters,
	/// Entropy.
	Entropy,
	/// Output from the parameterized authorizer code.
	AuthTrace,
	/// A particular extrinsic of a given work-item.
	AnyExtrinsic {
		/// The index of the work-item whose extrinsic should be fetched.
		work_item: usize,
		/// The index of the work-item's extrinsic to be fetched.
		index: usize,
	},
	/// A particular extrinsic of the executing work-item.
	OurExtrinsic(usize),
	/// A particular import-segment of a given work-item.
	AnyImport {
		/// The index of the work-item whose import-segment should be fetched.
		work_item: usize,
		/// The index of the work-item's import-segment to be fetched.
		index: usize,
	},
	/// A particular import-segment of the executing work-item.
	OurImport(usize),
	/// Current work-package.
	WorkPackage,
	/// Work package authorization config blob.
	AuthConfig,
	/// Input provided to the parameterized authorizer code.
	AuthToken,
	/// Refine context.
	RefineContext,
	/// All work items summary.
	ItemsSummary,
	/// A particular work item summary.
	AnyItemSummary(usize),
	/// A particular work item payload.
	AnyPayload(usize),
	/// All accumulate items.
	AccumulateItems,
	/// A particular accumulate item.
	AnyAccumulateItem(usize),
}

impl Fetch {
	const fn args(self) -> (u64, u64, u64) {
		use Fetch::*;
		match self {
			ProtocolParameters => (FetchKind::ProtocolParameters as _, 0, 0),
			Entropy => (FetchKind::Entropy as _, 0, 0),
			AuthTrace => (FetchKind::AuthTrace as _, 0, 0),
			AnyExtrinsic { work_item, index } =>
				(FetchKind::AnyExtrinsic as _, work_item as _, index as _),
			OurExtrinsic(index) => (FetchKind::OurExtrinsic as _, index as _, 0),
			AnyImport { work_item, index } =>
				(FetchKind::AnyImport as _, work_item as _, index as _),
			OurImport(index) => (FetchKind::OurImport as _, index as _, 0),
			WorkPackage => (FetchKind::WorkPackage as _, 0, 0),
			AuthConfig => (FetchKind::AuthConfig as _, 0, 0),
			AuthToken => (FetchKind::AuthToken as _, 0, 0),
			RefineContext => (FetchKind::RefineContext as _, 0, 0),
			ItemsSummary => (FetchKind::ItemsSummary as _, 0, 0),
			AnyItemSummary(index) => (FetchKind::AnyItemSummary as _, index as _, 0),
			AnyPayload(index) => (FetchKind::AnyPayload as _, index as _, 0),
			AccumulateItems => (FetchKind::AccumulateItems as _, 0, 0),
			AnyAccumulateItem(index) => (FetchKind::AnyAccumulateItem as _, index as _, 0),
		}
	}

	/// Fetch the data defined by this [Fetch] into the given target buffer.
	///
	/// - `target`: The buffer to write the fetched data into.
	/// - `skip`: The number of bytes to skip from the start of the data to be fetched.
	///
	/// Returns the full length of the data which is being fetched. If this is smaller than the
	/// `target`'s length, then some of the buffer will not be written to. If the request does not
	/// identify any data to be fetched (e.g. because an index is out of range) then returns `None`.
	pub fn fetch_into(self, target: &mut [u8], skip: usize) -> Option<usize> {
		let (kind, a, b) = self.args();
		let target_ptr = if target.is_empty() { ptr::null_mut() } else { target.as_mut_ptr() };
		unsafe { imports::fetch(target_ptr, skip as _, target.len() as _, kind as _, a, b) }
			.into_api_option()
	}

	/// Fetch the length of the data defined by this [Fetch].
	///
	/// Returns the length of the data which is being fetched. If the request does not identify any
	/// data to be fetched (e.g. because an index is out of range) then returns `None`.
	#[allow(clippy::len_without_is_empty)]
	pub fn len(self) -> Option<usize> {
		self.fetch_into(&mut [], 0)
	}

	/// Fetch the data defined by this [Fetch] into a newly allocated [Vec].
	///
	/// Returns a [Vec] containing the data identified by the value of `self`. If the request does
	/// not identify any data to be fetched (e.g. because an index is out of range) then returns
	/// `None`.
	pub fn fetch(self) -> Option<Vec<u8>> {
		let len = self.len()?;
		let mut incoming = vec![0u8; len];
		self.fetch_into(&mut incoming, 0)?;
		Some(incoming)
	}

	/// Fetch the data defined by this [Fetch] and decode it as type `T`.
	fn fetch_as<T: Decode>(self) -> Option<T> {
		self.fetch().map(|bytes| {
			T::decode(&mut bytes.as_slice()).expect("host call returns correct type; qed")
		})
	}
}

pub(crate) mod fetch_wrappers {
	use super::*;

	/// Fetch the protocol parameters.
	pub fn protocol_parameters() -> ProtocolParameters {
		Fetch::ProtocolParameters.fetch_as().expect("item must be available; qed")
	}

	/// Fetch the entropy value.
	pub fn entropy() -> [u8; 32] {
		let mut res = [0_u8; 32];
		Fetch::Entropy
			.fetch_into(res.as_mut(), 0)
			.map(|_| res)
			.expect("item must be available; qed")
	}

	/// Fetch the output from the parameterized authorizer code.
	pub fn auth_trace() -> AuthTrace {
		Fetch::AuthTrace.fetch().expect("item must be available; qed").into()
	}

	/// Fetch the current work-package.
	pub fn work_package() -> WorkPackage {
		Fetch::WorkPackage.fetch_as().expect("item must be available; qed")
	}

	/// Fetch the work package authorizer config blob.
	pub fn auth_config() -> AuthConfig {
		Fetch::AuthConfig.fetch_as().expect("item must be available; qed")
	}

	/// Fetch the input provided to the authorizer code.
	pub fn auth_token() -> Authorization {
		Fetch::AuthToken.fetch().expect("item must be available; qed").into()
	}

	/// Fetch the refine context.
	pub fn refine_context() -> RefineContext {
		Fetch::RefineContext.fetch_as().expect("item must be available; qed")
	}

	/// Fetch all work items summary.
	pub fn work_items_summary() -> Vec<WorkItemSummary> {
		Fetch::ItemsSummary.fetch_as().expect("item must be available; qed")
	}

	/// Fetch a particular work item summary.
	///
	/// Returns `None` if fewer work items are available than the requested index.
	pub fn work_item_summary(index: usize) -> Option<WorkItemSummary> {
		Fetch::AnyItemSummary(index).fetch_as()
	}

	/// Fetch a particular work item payload.
	///
	/// Returns `None` if fewer work items are available than the requested index.
	pub fn work_item_payload(index: usize) -> Option<Vec<u8>> {
		Fetch::AnyPayload(index).fetch()
	}

	/// Fetch all accumulate items.
	pub fn accumulate_items() -> Vec<AccumulateItem> {
		Fetch::AccumulateItems.fetch_as().expect("item must be available; qed")
	}

	/// Fetch a particular accumulate item.
	///
	/// Returns `None` if fewer accumulate items are available than the requested index.
	pub fn accumulate_item(index: usize) -> Option<AccumulateItem> {
		Fetch::AnyAccumulateItem(index).fetch_as()
	}

	/// Fetch an extrinsic of our Work Item.
	///
	/// - `index`: The index of the extrinsic.
	///
	/// Returns `Some` extrinsic or `None` depending on whether the index references an extrinsic.
	pub fn extrinsic(index: usize) -> Option<Vec<u8>> {
		Fetch::OurExtrinsic(index).fetch()
	}

	/// Fetch a partial extrinsic of our Work Item.
	///
	/// - `index`: The index of the extrinsic.
	/// - `offset`: Offset into the extrinsic data.
	/// - `len`: Number or bytes to read.
	///
	/// Returns `Some` with the portion of the data that was actually read or `None` if the index is
	/// invalid.
	pub fn extrinsic_slice(index: usize, offset: usize, len: usize) -> Option<Vec<u8>> {
		let mut incoming = vec![0u8; len];
		let full_len = Fetch::OurExtrinsic(index).fetch_into(&mut incoming, offset)?;
		if offset + len > full_len {
			incoming.truncate(full_len.saturating_sub(offset));
		}
		Some(incoming)
	}

	/// Fetch an extrinsic of a given Work Item.
	///
	/// - `work_item`: The index of the work item to fetch an extrinsic of.
	/// - `index`: The index of the extrinsic.
	///
	/// Returns `Some` extrinsic or `None` depending on whether the index references an extrinsic.
	pub fn any_extrinsic(work_item: usize, index: usize) -> Option<Vec<u8>> {
		Fetch::AnyExtrinsic { work_item, index }.fetch()
	}

	/// Fetch a segment of data specified in the Work Item's import manifest.
	///
	/// - `index`: The index of the segment within the Work Items's import manifest to import.
	///
	/// Returns `Some` segment or `None` depending on whether the index references an import or not.
	pub fn import(index: usize) -> Option<Segment> {
		let mut incoming = Segment::default();
		Fetch::OurImport(index).fetch_into(incoming.as_mut(), 0).map(|_| incoming)
	}

	/// Fetch a segment of data specified in a given Work Item's import manifest.
	///
	/// - `work_item`: The index of the work item to fetch an imported segment of.
	/// - `index`: The index of the segment within the Work Items's import manifest to import.
	///
	/// Returns `Some` segment or `None` depending on whether the indices reference an import or
	/// not.
	pub fn any_import(work_item: usize, index: usize) -> Option<Segment> {
		let mut incoming = Segment::default();
		Fetch::AnyImport { work_item, index }
			.fetch_into(incoming.as_mut(), 0)
			.map(|_| incoming)
	}
}

/// Export a segment of data into the JAM Data Lake.
///
/// - `segment`: The segment of data to export.
///
/// Returns the export index or `Err` if the export was unsuccessful.
pub fn export(segment: &Segment) -> ApiResult<u64> {
	unsafe { imports::export(segment.as_slice().as_ptr(), segment.len() as u64) }.into_api_result()
}

/// Export a slice of data into the JAM Data Lake.
///
/// - `segment`: The slice of data to export, which may be no longer than [jam_types::SEGMENT_LEN].
///   If it's shorter, the rest of of the bytes are zeroed.
///
/// Returns the export index or `Err` if the export was unsuccessful.
pub fn export_slice(segment: &[u8]) -> ApiResult<u64> {
	unsafe { imports::export(segment.as_ptr(), segment.len() as u64) }.into_api_result()
}

/// Create a new instance of a PVM.
///
/// - `code`: The code of the PVM.
/// - `program_counter`: The initial program counter value of the PVM.
///
/// Returns the handle of the PVM or `Err` if the creation was unsuccessful.
pub fn machine(code: &[u8], program_counter: u64) -> ApiResult<u64> {
	unsafe { imports::machine(code.as_ptr(), code.len() as u64, program_counter) }.into_api_result()
}

/// Inspect the raw memory of an inner PVM.
///
/// - `vm_handle`: The handle of the PVM whose memory to inspect.
/// - `inner_src`: The address in the PVM's memory to start reading from.
/// - `len`: The number of bytes to read.
///
/// Returns the data in the PVM `vm_handle` at memory `inner_src` or `Err` if the inspection failed.
pub fn peek(vm_handle: u64, inner_src: u64, len: u64) -> ApiResult<Vec<u8>> {
	let mut incoming = vec![0; len as usize];
	unsafe { imports::peek(vm_handle, incoming.as_mut_ptr(), inner_src, len) }
		.into_api_result()
		.map(|()| incoming)
}

/// Inspect the raw memory of an inner PVM.
///
/// - `vm_handle`: The handle of the PVM whose memory to inspect.
/// - `outer_dst`: The buffer to write the memory into.
/// - `inner_src`: The address in the PVM's memory to start reading from.
///
/// Returns `Ok` on success or `Err` if the inspection failed.
pub fn peek_into(vm_handle: u64, outer_dst: &mut [u8], inner_src: u64) -> ApiResult<()> {
	unsafe {
		imports::peek(vm_handle, outer_dst.as_mut_ptr(), inner_src, size_of_val(outer_dst) as u64)
	}
	.into_api_result()
}

/// Inspect a plain-old-data value in the memory of an inner PVM.
///
/// - `vm_handle`: The handle of the PVM whose memory to inspect.
/// - `inner_src`: The address in the PVM's memory to inspect a value of type `T`.
///
/// Returns the value of type `T` at `inner_src` of the PVM `vm_handle` or `Err` if the inspection
/// failed.
///
/// NOTE: This will only work with types `T` which have exactly the same memory layout in the host
/// and the inner PVM. Avoid things like references.
pub fn peek_value<T>(vm_handle: u64, inner_src: u64) -> ApiResult<T> {
	let mut t = MaybeUninit::<T>::uninit();
	unsafe {
		imports::peek(vm_handle, t.as_mut_ptr() as *mut u8, inner_src, size_of::<T>() as u64)
			.into_api_result()
			.map(|()| t.assume_init())
	}
}

/// Copy some data into the memory of an inner PVM.
///
/// - `vm_handle`: The handle of the PVM whose memory to mutate.
/// - `outer_src`: The data to be copied.
/// - `inner_dst`: The address in memory of inner PVM `vm_handle` to copy the data to.
///
/// Returns `Ok` on success or `Err` if the inspection failed.
pub fn poke(vm_handle: u64, outer_src: &[u8], inner_dst: u64) -> ApiResult<()> {
	unsafe { imports::poke(vm_handle, outer_src.as_ptr(), inner_dst, outer_src.len() as u64) }
		.into_api_result()
}

/// Copy a plain-old-data value into the memory of an inner PVM.
///
/// - `vm_handle`: The handle of the PVM whose memory to mutate.
/// - `outer_src`: The value whose memory representation is to be copied.
/// - `inner_dst`: The address in memory of inner PVM `vm_handle` to copy the value to.
///
/// Returns `Ok` on success or `Err` if the inspection failed.
pub fn poke_value<T>(vm_handle: u64, outer_src: &T, inner_dst: u64) -> ApiResult<()> {
	unsafe {
		imports::poke(
			vm_handle,
			outer_src as *const T as *const u8,
			inner_dst,
			size_of_val(outer_src) as u64,
		)
	}
	.into_api_result()
}

/// Initialize memory pages in an inner PVM with zeros, allocating if needed.
///
/// - `vm_handle`: The handle of the PVM whose memory to mutate.
/// - `page`: The index of the first page of inner PVM `vm_handle` to initialize.
/// - `count`: The number of pages to initialize.
/// - `mode`: Memory access mode.
///
/// Returns `Ok` on success or `Err` if the operation failed.
///
/// Pages are initialized to be filled with zeroes. If the pages are not yet allocated, they will
/// be allocated.
pub fn zero(vm_handle: u64, page: u64, count: u64, mode: PageMode) -> ApiResult<()> {
	unsafe { imports::pages(vm_handle, page, count, PageOperation::Alloc(mode).into()) }
		.into_api_result()
}

/// Deallocate memory pages in an inner PVM.
///
/// - `vm_handle`: The handle of the PVM whose memory to mutate.
/// - `page`: The index of the first page of inner PVM `vm_handle` to deallocate.
/// - `count`: The number of pages to deallocate.
///
/// Returns `Ok` on success or `Err` if the operation failed.
pub fn void(vm_handle: u64, page: u64, count: u64) -> ApiResult<()> {
	unsafe { imports::pages(vm_handle, page, count, PageOperation::Free.into()) }.into_api_result()
}

/// Set memory pages access mode.
///
/// - `vm_handle`: The handle of the PVM whose memory to mutate.
/// - `page`: The index of the first page of inner PVM `vm_handle` to initialize.
/// - `count`: The number of pages to initialize.
/// - `mode`: Memory access mode.
///
/// Returns `Ok` on success or `Err` if the operation failed.
///
/// Pages need to be initialized with [`zero`] for this operation to succeed.
pub fn protect(vm_handle: u64, page: u64, count: u64, mode: PageMode) -> ApiResult<()> {
	unsafe { imports::pages(vm_handle, page, count, PageOperation::SetMode(mode).into()) }
		.into_api_result()
}

/// Invoke an inner PVM.
///
/// - `vm_handle`: The handle of the PVM to invoke.
/// - `gas`: The maximum amount of gas which the inner PVM may use in this invocation.
/// - `regs`: The initial register values of the inner PVM.
///
/// Returns the outcome of the invocation, together with any remaining gas, and the final register
/// values.
pub fn invoke(
	vm_handle: u64,
	gas: SignedGas,
	regs: [u64; 13],
) -> ApiResult<(InvokeOutcome, SignedGas, [u64; 13])> {
	let mut args = InvokeArgs { gas, regs };
	let outcome = unsafe { imports::invoke(vm_handle, core::ptr::from_mut(&mut args).cast()) }
		.into_invoke_result()?;
	Ok((outcome, args.gas, args.regs))
}

/// Delete an inner PVM instance, freeing any associated resources.
///
/// - `vm_handle`: The handle of the PVM to delete.
///
/// Returns the inner PVM's final instruction counter value on success or `Err` if the operation
/// failed.
pub fn expunge(vm_handle: u64) -> ApiResult<u64> {
	unsafe { imports::expunge(vm_handle) }.into_api_result()
}

/// Inspect the gas meter.
///
/// Returns the post-hostcall gas meter value.
pub fn gas() -> UnsignedGas {
	unsafe { imports::gas() }
}

/// Check whether a preimage is available for lookup.
///
/// - `hash`: The hash of the preimage to check availability.
///
/// Returns `true` if the preimage is available, `false` otherwise.
///
/// NOTE: Internally this uses the `lookup` host call.
pub fn is_available(hash: &[u8; 32]) -> bool {
	raw_foreign_lookup_into(u64::MAX, hash, &mut []).is_some()
}

/// Check whether a preimage is available for foreign lookup.
///
/// - `service_id`: The service in whose preimage store to check availability.
/// - `hash`: The hash of the preimage to check availability.
///
/// Returns `true` if the preimage is available, `false` otherwise.
///
/// NOTE: Internally this uses the `lookup` host call.
pub fn is_foreign_available(service_id: ServiceId, hash: &[u8; 32]) -> bool {
	raw_foreign_lookup_into(service_id as _, hash, &mut []).is_some()
}

/// Make a lookup into the service's preimage store without allocating.
///
/// - `hash`: The hash of the preimage to look up.
/// - `output`: The buffer to write the preimage into.
///
/// Returns the number of bytes written into the output buffer or `None` if the preimage was not
/// available.
///
/// NOTE: Internally this uses the `lookup` host call.
pub fn lookup_into(hash: &[u8; 32], output: &mut [u8]) -> Option<usize> {
	raw_foreign_lookup_into(u64::MAX, hash, output)
}

/// Make a lookup into another service's preimage store without allocating.
///
/// - `service_id`: The service in whose preimage store to find the preimage.
/// - `hash`: The hash of the preimage to look up.
/// - `output`: The buffer to write the preimage into.
///
/// Returns the number of bytes written into the output buffer or `None` if the preimage was not
/// available.
///
/// NOTE: Internally this uses the `lookup` host call.
pub fn foreign_lookup_into(
	service_id: ServiceId,
	hash: &[u8; 32],
	output: &mut [u8],
) -> Option<usize> {
	raw_foreign_lookup_into(service_id as _, hash, output)
}

/// Make a lookup into the service's preimage store.
///
/// - `hash`: The hash of the preimage to look up.
///
/// Returns the preimage or `None` if the preimage was not available.
///
/// NOTE: Internally this uses the `lookup` host call.
pub fn lookup(hash: &[u8; 32]) -> Option<Vec<u8>> {
	raw_foreign_lookup(u64::MAX, hash)
}

/// Make a lookup into another service's preimage store.
///
/// - `service_id`: The service in whose preimage store to find the preimage.
/// - `hash`: The hash of the preimage to look up.
///
/// Returns the preimage or `None` if the preimage was not available.
///
/// NOTE: Internally this uses the `lookup` host call.
pub fn foreign_lookup(service_id: ServiceId, hash: &[u8; 32]) -> Option<Vec<u8>> {
	raw_foreign_lookup(service_id as _, hash)
}

/// The status of a lookup request.
#[derive(Debug)]
pub enum LookupRequestStatus {
	/// The request has never had its preimage provided; corresponds to an empty GP array.
	Unprovided,
	/// The requested preimage is provided; corresponds to a single-item GP array.
	Provided {
		/// The slot at which the preimage was provided.
		since: Slot,
	},
	/// The request was provided and has since been unrequested; corresponds to a two-item GP
	/// array.
	Unrequested {
		/// The slot at which the preimage was provided.
		provided_since: Slot,
		/// The slot at which the preimage was unrequested.
		unrequested_since: Slot,
	},
	/// The request was provided, was since unrequested and is now requested again. Corresponds to
	/// a three-item GP array.
	Rerequested {
		/// The slot at which the preimage was provided.
		provided_since: Slot,
		/// The slot at which the preimage was unrequested.
		unrequested_at: Slot,
		/// The slot at which the preimage was requested again.
		rerequested_since: Slot,
	},
}

/// A summary of the implication of calling `forget` on a preimage request.
#[derive(Debug)]
pub enum ForgetImplication {
	/// The request will be dropped altogether since it was never provided. The deposit criteria
	/// will be lifted.
	Drop,
	/// The preimage will be unrequested and unavailable for lookup. No change in the deposit
	/// criteria.
	Unrequest,
	/// The preimage remain unavailable and be expunged from the state. The deposit criteria
	/// will be lifted.
	Expunge,
	/// The `forget` call is invalid and no change in state will be made.
	///
	/// If called in future, after `success_after`, it will be have the effect of `Unrequest`.
	NotYetUnrequest {
		/// The earliest slot at which a call to `forget` can succeed.
		success_after: Slot,
	},
	/// The `forget` call is invalid and no change in state will be made.
	///
	/// If called in future, after `success_after`, it will be have the effect of `Expunge`.
	NotYetExpunge {
		/// The earliest slot at which a call to `forget` can succeed.
		success_after: Slot,
	},
}

impl LookupRequestStatus {
	/// Return the implication of calling `forget` on the current state of the preimage request
	/// given the current timeslot is `now`.
	pub fn forget_implication(&self, now: Slot) -> ForgetImplication {
		match self {
			Self::Unprovided => ForgetImplication::Drop,
			Self::Provided { .. } => ForgetImplication::Unrequest,
			Self::Unrequested { unrequested_since, .. }
				if now > unrequested_since + min_turnaround_period() =>
				ForgetImplication::Drop,
			Self::Unrequested { unrequested_since, .. } => ForgetImplication::NotYetExpunge {
				success_after: unrequested_since + min_turnaround_period(),
			},
			Self::Rerequested { unrequested_at, .. }
				if now > unrequested_at + min_turnaround_period() =>
				ForgetImplication::Unrequest,
			Self::Rerequested { unrequested_at, .. } => ForgetImplication::NotYetUnrequest {
				success_after: unrequested_at + min_turnaround_period(),
			},
		}
	}
}

/// Query the status of a preimage.
///
/// - `hash`: The hash of the preimage to be queried.
/// - `len`: The length of the preimage to be queried.
///
/// Returns `Some` if `hash`/`len` has an active solicitation outstanding or `None` if not.
pub fn query(hash: &[u8; 32], len: usize) -> Option<LookupRequestStatus> {
	let (r0, r1): (u64, u64) = unsafe { imports::query(hash.as_ptr(), len as u64) };
	let n = r0 as u32;
	let x = (r0 >> 32) as Slot;
	let y = r1 as Slot;
	Some(match n {
		0 => LookupRequestStatus::Unprovided,
		1 => LookupRequestStatus::Provided { since: x },
		2 => LookupRequestStatus::Unrequested { provided_since: x, unrequested_since: y },
		3 => LookupRequestStatus::Rerequested {
			provided_since: x,
			unrequested_at: y,
			rerequested_since: (r1 >> 32) as Slot,
		},
		_ => return None,
	})
}

/// Request that preimage data be available for lookup.
///
/// - `hash`: The hash of the preimage to be made available.
/// - `len`: The length of the preimage to be made available.
///
/// Returns `Ok` on success or `Err` if the request failed.
///
/// [is_available] may be used to determine availability; once available, the preimage may be
/// fetched with [lookup] or its variants.
///
/// A preimage may only be solicited once for any service and soliciting a preimage raises the
/// minimum balance required to be held by the service.
pub fn solicit(hash: &[u8; 32], len: usize) -> Result<(), ApiError> {
	unsafe { imports::solicit(hash.as_ptr(), len as u64) }.into_api_result()
}

/// No longer request that preimage data be available for lookup, or drop preimage data once time
/// limit has passed.
///
/// - `hash`: The hash of the preimage to be forgotten.
/// - `len`: The length of the preimage to be forgotten.
///
/// Returns `Ok` on success or `Err` if the request failed.
///
/// This function is used twice in the lifetime of a requested preimage; once to indicate that the
/// preimage is no longer needed and again to "clean up" the preimage once the required duration
/// has passed. Whether it does one or the other is determined by the current state of the preimage
/// request.
pub fn forget(hash: &[u8; 32], len: usize) -> Result<(), ApiError> {
	unsafe { imports::forget(hash.as_ptr(), len as u64) }.into_api_result()
}

/// Set the default result hash of Accumulation.
///
/// - `hash`: The hash to be used as the Accumulation result.
///
/// This value will be returned from Accumulation on success. It may be overridden by further
/// calls to this function or by explicitly returning `Some` value from the
/// [crate::Service::accumulate] function. The [checkpoint] function may be used after a call to
/// this function to ensure that this value is returned in the case of an irregular termination.
pub fn yield_hash(hash: &[u8; 32]) {
	unsafe { imports::yield_hash(hash.as_ptr()) }
		.into_api_result()
		.expect("Cannot fail except for memory access; we provide a good address; qed")
}

/// Provide a requested preimage to any service.
pub fn provide(service_id: ServiceId, preimage: &[u8]) -> Result<(), ApiError> {
	unsafe { imports::provide(service_id as u64, preimage.as_ptr(), preimage.len() as _) }
		.into_api_result()
}

/// Fetch raw data from the service's key/value store.
///
/// - `key`: The key of the data to fetch.
///
/// Returns the data associated with the key or `None` if the key is not present.
pub fn get_storage(key: &[u8]) -> Option<Vec<u8>> {
	raw_get_foreign_storage(u64::MAX, key)
}

/// Fetch raw data from the service's key/value store into a buffer.
///
/// - `key`: The key of the data to fetch.
/// - `value`: The buffer to write the data into; on success, this is overwritten with the value
///   associated with `key` in the service's store, leaving any portions unchanged if the buffer is
///   longer than the value.
///
/// Returns the size of the data associated with the key or `None` if the key is not present.
pub fn get_storage_into(key: &[u8], value: &mut [u8]) -> Option<usize> {
	raw_get_foreign_storage_into(u64::MAX, key, value)
}

/// Fetch raw data from another service's key/value store.
///
/// - `id`: The ID of the service whose key/value store to fetch from.
/// - `key`: The key of the data to fetch.
///
/// Returns the data associated with the key in the key/value store of service `id` or `None` if
/// the key is not present.
pub fn get_foreign_storage(id: ServiceId, key: &[u8]) -> Option<Vec<u8>> {
	raw_get_foreign_storage(id as u64, key)
}

/// Fetch raw data from another service's key/value store into a buffer.
///
/// - `id`: The ID of the service whose key/value store to fetch from.
/// - `key`: The key of the data to fetch.
/// - `value`: The buffer to write the data into; on success, this is overwritten with the value
///   associated with `key` in said service's store, leaving any portions unchanged if the buffer is
///   longer than the value.
///
/// Returns the size of the data associated with the key in the key/value store of service `id` or
/// `None` if the key is not present.
pub fn get_foreign_storage_into(id: ServiceId, key: &[u8], value: &mut [u8]) -> Option<usize> {
	raw_get_foreign_storage_into(id as u64, key, value)
}

/// Fetch typed data from the service's key/value store.
///
/// - `key`: A value, whose encoded representation is the the key of the data to fetch.
///
/// Returns the decoded data associated with the key or `None` if the key is not present or the data
/// cannot be decoded into the type `R`.
pub fn get<R: Decode>(key: impl Encode) -> Option<R> {
	Decode::decode(&mut &key.using_encoded(get_storage)?[..]).ok()
}

/// Fetch typed data from another service's key/value store.
///
/// - `id`: The ID of the service whose key/value store to fetch from.
/// - `key`: A value, whose encoded representation is the the key of the data to fetch.
///
/// Returns the decoded data associated with the key in the key/value store of service `id` or
/// `None` if the key is not present or the data cannot be decoded into the type `R`.
pub fn get_foreign<R: Decode>(id: ServiceId, key: impl Encode) -> Option<R> {
	Decode::decode(&mut &key.using_encoded(|k| get_foreign_storage(id, k))?[..]).ok()
}

/// Set the value of a key to raw data in the service's key/value store.
///
/// - `key`: The key to be set.
/// - `data`: The data to be associated with the key.
///
/// Returns the previous value's length, which can be `None` if no value was associated
/// with the given `key`, or `Err` if the operation failed.
///
/// NOTE: If this key was not previously set or if the data is larger than the previous value, then
/// the minimum balance which the service must hold is raised and if the service has too little
/// balance then the call with fail with [ApiError::StorageFull].
pub fn set_storage(key: &[u8], data: &[u8]) -> Result<Option<usize>, ApiError> {
	unsafe { imports::write(key.as_ptr(), key.len() as u64, data.as_ptr(), data.len() as u64) }
		.into_api_result()
}

/// Remove a pair from the service's key/value store.
///
/// - `key`: The key to be removed.
///
/// Returns `Some` on success with the previous value's length, or `None` if the key does not exist.
///
/// NOTE: If the key does not exist, then the operation is a no-op.
pub fn remove_storage(key: &[u8]) -> Option<usize> {
	unsafe { imports::write(key.as_ptr(), key.len() as u64, ptr::null(), 0) }
		.into_api_result()
		.expect("Cannot fail except for memory access; we provide a good address; qed")
}

/// Set the value of a typed key to typed data in the service's key/value store.
///
/// - `key`: The value of an encodable type whose encoding is the key to be set.
/// - `value`: The value of an encodable type whose encoding be associated with said key.
///
/// Returns `Ok` on success or `Err` if the operation failed.
///
/// NOTE: If this key was not previously set or if the data is larger than the previous value, then
/// the minimum balance which the service must hold is raised and if the service has too little
/// balance then the call with fail with [ApiError::StorageFull].
pub fn set(key: impl Encode, value: impl Encode) -> Result<(), ApiError> {
	value.using_encoded(|v| key.using_encoded(|k| set_storage(k, v).map(|_| ())))
}

/// Remove a typed key from the service's key/value store.
///
/// - `key`: The value of an encodable type whose encoding is the key to be removed.
///
/// NOTE: If the key does not exist, then the operation is a no-op.
pub fn remove(key: impl Encode) {
	let _ = key.using_encoded(remove_storage);
}

/// Get information on the service.
///
/// Returns the value of [ServiceInfo] which describes the current state of the service.
pub fn my_info() -> ServiceInfo {
	raw_service_info(u64::MAX).expect("Current service must exist; qed")
}

/// Get information on another service.
///
/// - `id`: The ID of the service to get information on.
///
/// Returns the value of [ServiceInfo] which describes the current state of service `id`.
pub fn service_info(id: ServiceId) -> Option<ServiceInfo> {
	raw_service_info(id as _)
}

#[doc(hidden)]
pub fn raw_service_info_field<T: Decode, const N: usize>(service: u64, offset: u64) -> Option<T> {
	let mut buffer = [0u8; N];
	let maybe_ok: Option<()> =
		unsafe { imports::info(service as _, buffer.as_mut_ptr(), offset, N as u64) }
			.into_api_result()
			.expect("Cannot fail except for memory access; we provide a good address; qed");
	maybe_ok?;
	T::decode(&mut &buffer[..]).ok()
}

#[doc(hidden)]
#[rustfmt::skip]
#[macro_export]
macro_rules! service_info_field_type {
    (code_hash) => {::jam_types::CodeHash};
    (balance) => {::jam_types::Balance};
    (threshold) => {::jam_types::Balance};
    (min_item_gas) => {::jam_types::UnsignedGas};
    (min_memo_gas) => {::jam_types::UnsignedGas};
    (bytes) => {u64};
    (items) => {u32};
    (deposit_offset) => {::jam_types::Balance};
    (creation_slot) => {::jam_types::Slot};
    (last_accumulation_slot) => {::jam_types::Slot};
    (parent_service) => {::jam_types::ServiceId};
}

#[doc(hidden)]
#[rustfmt::skip]
#[macro_export]
macro_rules! service_info_field_offset {
    (code_hash) => {::jam_types::ServiceInfo::CODE_HASH_OFFSET};
    (balance) => {::jam_types::ServiceInfo::BALANCE_OFFSET};
    (threshold) => {::jam_types::ServiceInfo::THRESHOLD_OFFSET};
    (min_item_gas) => {::jam_types::ServiceInfo::MIN_ITEM_GAS_OFFSET};
    (min_memo_gas) => {::jam_types::ServiceInfo::MIN_MEMO_GAS_OFFSET};
    (bytes) => {::jam_types::ServiceInfo::BYTES_OFFSET};
    (items) => {::jam_types::ServiceInfo::ITEMS_OFFSET};
    (deposit_offset) => {::jam_types::ServiceInfo::DEPOSIT_OFFSET_OFFSET};
    (creation_slot) => {::jam_types::ServiceInfo::CREATION_SLOT_OFFSET};
    (last_accumulation_slot) => {::jam_types::ServiceInfo::LAST_ACCUMULATION_SLOT_OFFSET};
    (parent_service) => {::jam_types::ServiceInfo::PARENT_SERVICE_OFFSET};
}

/// Get specific field from a another service info.
#[macro_export]
macro_rules! service_info_field {
	($service: expr, $field: ident) => {{
		type T = $crate::service_info_field_type!($field);
		const OFFSET: usize = $crate::service_info_field_offset!($field);
		const LEN: usize = ::core::mem::size_of::<T>();
		$crate::internal::raw_service_info_field::<T, LEN>($service, OFFSET as u64)
	}};
}

/// Get specific field of the current service info.
#[macro_export]
macro_rules! my_info_field {
	($field: ident) => {
		$crate::service_info_field!(u64::MAX, $field).expect("Current service must exist; qed")
	};
}

/// Create a new service.
///
/// This is a convenience function that calls [`create_service_ext`] with no `deposit_offset`
/// and no requirements for `new_service_id`.
///
/// Returns the new service ID or `Err` if the operation failed.
pub fn create_service(
	code_hash: &CodeHash,
	code_len: usize,
	min_item_gas: UnsignedGas,
	min_memo_gas: UnsignedGas,
) -> Result<ServiceId, ApiError> {
	create_service_ext(code_hash, code_len, min_item_gas, min_memo_gas, None, None)
}

/// Create a new service with extended options.
///
/// - `code_hash`: The hash of the code of the service to create. The preimage of this hash will be
///   solicited by the new service and its according minimum balance will be transferred from the
///   executing service to the new service in order to fund it.
/// - `code_len`: The length of the code of the service to create.
/// - `min_item_gas`: The minimum gas required to be set aside for the accumulation of a single Work
///   Item in the new service.
/// - `min_memo_gas`: The minimum gas required to be set aside for any single transfer of funds and
///   corresponding processing of a memo in the new service.
/// - `deposit_offset`: The deposit offset for the new service. This represents gratis storage up to
///   the amount allowed by `deposit_offset`. Setting a non-zero value requires the caller to have
///   "manager" privileges.
/// - `new_service_id`: The desired service ID for the new service. This allows to request for a new
///   service ID in the reserved low range (< S, with S prescribed by the GP). Requesting such low
///   ID requires the caller to have "registrar" privileges.
///
/// Returns the new service ID or `Err` if the operation failed.
///
/// NOTE: This operation requires a balance transfer from the executing service to the new service
/// in order to succeed; if this would reduce the balance to below the minimum balance required,
/// then it will fail.
///
/// NOTE: This commits to the code of the new service but does not yet instantiate it; the code
/// preimage must be provided before the first Work Items of the new service can be processed.
pub fn create_service_ext(
	code_hash: &CodeHash,
	code_len: usize,
	min_item_gas: UnsignedGas,
	min_memo_gas: UnsignedGas,
	deposit_offset: Option<Balance>,
	new_service_id: Option<ServiceId>,
) -> Result<ServiceId, ApiError> {
	unsafe {
		imports::new(
			code_hash.as_ptr(),
			code_len as u64,
			min_item_gas,
			min_memo_gas,
			deposit_offset.unwrap_or_default(),
			new_service_id.unwrap_or(ServiceId::MAX) as u64,
		)
		.into_api_result()
	}
}

/// Upgrade the code of the service.
///
/// - `code_hash`: The hash of the code to upgrade to, to be found in the service's preimage store.
/// - `min_item_gas`: The minimum gas required to be set aside for the accumulation of a single Work
///   Item in the new service.
/// - `min_memo_gas`: The minimum gas required to be set aside for any single transfer of funds and
///   corresponding processing of a memo in the new service.
///
/// NOTE: This commits to the new code of the service but does not yet instantiate it; the new code
/// preimage must be provided before the first Work Items of the new service can be processed.
/// Generally you should use [solicit] and [is_available] to ensure that the new code is already
/// in the service's preimage store and call this only as the final step in the process.
pub fn upgrade(code_hash: &CodeHash, min_item_gas: UnsignedGas, min_memo_gas: UnsignedGas) {
	unsafe { imports::upgrade(code_hash.as_ptr(), min_item_gas, min_memo_gas) }
		.into_api_result()
		.expect("Failure only in case of bad memory; it is good; qed")
}

/// "Upgrade" the service into an unexecutable zombie.
///
/// - `ejector`: The index of the service which will be able to call [eject] on the caller service
///   in order to finally delete it.
///
/// NOTE: This only sets the new code hash of the service but does not clear storage/preimages nor
/// [forget] the current code hash. Do these first!
pub fn zombify(ejector: ServiceId) {
	(ejector, [0; 28]).using_encoded(|data| {
		unsafe { imports::upgrade(data.as_ptr(), 0, 0) }
			.into_api_result()
			.expect("Failure only in case of bad memory; it is good; qed")
	})
}

/// Transfer data and/or funds to another service asynchronously.
///
/// - `destination`: The ID of the service to transfer to. This service must exist at present.
/// - `amount`: The amount of funds to transfer to the `destination` service. Reducing the services
///   balance by this amount must not result in it falling below the minimum balance required.
/// - `gas_limit`: The amount of gas to set aside for the processing of the transfer by the
///   `destination` service. This must be at least the service's [ServiceInfo::min_memo_gas]. The
///   effective gas cost of this call is increased by this amount.
/// - `memo`: A piece of data to give the `destination` service.
///
/// Returns `Ok` on success or `Err` if the operation failed.
///
/// NOTE: All transfers are deferred; they are guaranteed to be received by the destination service
/// in same time slot, but will not be processed synchronously with this call.
pub fn transfer(
	destination: ServiceId,
	amount: Balance,
	gas_limit: UnsignedGas,
	memo: &Memo,
) -> Result<(), ApiError> {
	unsafe {
		imports::transfer(destination as _, amount, gas_limit, memo.as_ref().as_ptr())
			.into_api_result()
	}
}

/// Remove the `target` zombie service, drop its final preimage item `code_hash` and transfer
/// remaining balance to this service.
///
/// - `target`: The ID of a zombie service which nominated the caller service as its ejector.
/// - `code_hash`: The hash of the only preimage item of the `target` service. It must be
///   unrequested and droppable.
///
/// Target must therefore satisfy several requirements:
/// - it should have a code hash which is simply the LE32-encoding of the caller service's ID;
/// - it should have only one preimage lookup item, `code_hash`;
/// - it should have nothing in its storage.
///
/// Returns `Ok` on success or `Err` if the operation failed.
pub fn eject(target: ServiceId, code_hash: &CodeHash) -> Result<(), ApiError> {
	unsafe { imports::eject(target as _, code_hash.as_ref().as_ptr()) }.into_api_result()
}

/// Reset the privileged services.
///
/// - `manager`: The ID of the service which may effectually call [bless] in the future.
/// - `assigner`: The ID of the service which may effectually call [assign] in the future. NOTE: All
///   cores are assigned to this service.
/// - `designator`: The ID of the service which may effectually call [designate] in the future.
/// - `registrar`: The ID of the service which may register new service ids in the reserved range.
/// - `always_acc`: The list of service IDs which accumulate at least once in every JAM block,
///   together with the baseline gas they get for accumulation. This may be supplemented with
///   additional gas should there be Work Items for the service.
///
/// Returns `Ok` on success or `Err` if the operation failed.
///
/// NOTE: This call fails if, according to the state snapshot taken at the start of service
/// accumulation, this service is not the _manager_. As service accumulation proceeds, a prior
/// `bless` may update the state to bless a different service as manager. In that case, any
/// subsequent `bless` attempt by this service will also fail.
pub fn bless<'a>(
	manager: ServiceId,
	assigner: ServiceId,
	designator: ServiceId,
	registrar: ServiceId,
	always_acc: impl IntoIterator<Item = &'a (ServiceId, UnsignedGas)>,
) {
	let mut aa_count = 0;
	let aa_data: Vec<u8> = always_acc
		.into_iter()
		.flat_map(|x| {
			aa_count += 1;
			x.encode()
		})
		.collect();
	let assigners_data = FixedVec::<ServiceId, CoreCount>::new(assigner).encode();
	unsafe {
		imports::bless(
			manager as _,
			assigners_data.as_ptr() as _,
			designator as _,
			registrar as _,
			aa_data.as_ptr(),
			aa_count,
		)
	}
	.into_api_result()
	.expect("Failure only in case of bad memory or bad service ID; both are good; qed")
}

/// Assign a series of authorizers to a core.
///
/// - `core`: The index of the core to assign the authorizers to.
/// - `auth_queue`: The authorizer-queue to assign to the core. These are a series of
///   [AuthorizerHash] values, which determine what kinds of Work Packages are allowed to be
///   executed on the core.
/// - `assigner`: The ID of the service which may call [`assign`] in the future.
///
/// Returns `Ok` on success or `Err` if the operation failed.
///
/// NOTE: This call fails if, according to the state snapshot taken at the start of service
/// accumulation, this service is not the _assigner_ for the given `core`. As service accumulation
/// proceeds, a prior `assign` may update the state to assign the core to a different service. In
/// that case, any subsequent `assign` attempt by this service will also fail.
pub fn assign(
	core: CoreIndex,
	auth_queue: &AuthQueue,
	assigner: ServiceId,
) -> Result<(), ApiError> {
	auth_queue
		.using_encoded(|d| unsafe { imports::assign(core as _, d.as_ptr(), assigner as _) })
		.into_api_result()
}

/// Designate the new validator keys.
///
/// - `keys`: The new validator keys.
///
/// Returns `Ok` on success or `Err` if the operation failed.
///
/// NOTE: This call fails if, according to the state snapshot taken at the start of service
/// accumulation, this service is not the _designator_. As service accumulation proceeds, a prior
/// `designate` may update the state to assign the designator privilege to a different service. In
/// that case, any subsequent `designate` attempt by this service will also fail.
pub fn designate(keys: &OpaqueValKeysets) -> Result<(), ApiError> {
	keys.using_encoded(|d| unsafe { imports::designate(d.as_ptr()) })
		.into_api_result()
}

/// Checkpoint the state of the accumulation at present.
///
/// In the case that accumulation runs out of gas or otherwise terminates unexpectedly, all
/// changes extrinsic to the machine state, such as storage writes and transfers, will be rolled
/// back to the most recent call to [checkpoint], or the beginning of the accumulation if no
/// checkpoint has been made.
///
/// Returns the post-hostcall gas meter value.
pub fn checkpoint() -> UnsignedGas {
	unsafe { imports::checkpoint() }
}

fn raw_foreign_lookup(service_id: u64, hash: &[u8; 32]) -> Option<Vec<u8>> {
	let maybe_len: Option<u64> =
		unsafe { imports::lookup(service_id, hash.as_ptr(), ptr::null_mut(), 0, 0) }
			.into_api_result()
			.expect("Cannot fail except for memory access; we provide a good address; qed");
	let len = maybe_len?;
	let mut incoming = vec![0; len as usize];
	unsafe {
		imports::lookup(service_id, hash.as_ptr(), incoming.as_mut_ptr(), 0, len);
	}
	Some(incoming)
}

fn raw_foreign_lookup_into(service_id: u64, hash: &[u8; 32], output: &mut [u8]) -> Option<usize> {
	let maybe_len: Option<u64> = unsafe {
		imports::lookup(service_id, hash.as_ptr(), output.as_mut_ptr(), 0, output.len() as u64)
	}
	.into_api_result()
	.expect("Cannot fail except for memory access; we provide a good address; qed");
	Some(maybe_len? as usize)
}

fn raw_foreign_historical_lookup(service_id: u64, hash: &[u8; 32]) -> Option<Vec<u8>> {
	let maybe_len: Option<u64> =
		unsafe { imports::historical_lookup(service_id, hash.as_ptr(), ptr::null_mut(), 0, 0) }
			.into_api_result()
			.expect("Cannot fail except for memory access; we provide a good address; qed");
	let len = maybe_len?;
	let mut incoming = vec![0; len as usize];
	unsafe {
		imports::historical_lookup(service_id, hash.as_ptr(), incoming.as_mut_ptr(), 0, len);
	}
	Some(incoming)
}

fn raw_foreign_historical_lookup_into(
	service_id: u64,
	hash: &[u8; 32],
	output: &mut [u8],
) -> Option<usize> {
	let maybe_len: Option<u64> = unsafe {
		imports::historical_lookup(
			service_id,
			hash.as_ptr(),
			output.as_mut_ptr(),
			0,
			output.len() as u64,
		)
	}
	.into_api_result()
	.expect("Cannot fail except for memory access; we provide a good address; qed");
	Some(maybe_len? as usize)
}

fn raw_service_info(service: u64) -> Option<ServiceInfo> {
	let mut buffer = [0u8; ServiceInfo::ENCODED_LEN];
	let maybe_ok: Option<()> =
		unsafe { imports::info(service as _, buffer.as_mut_ptr(), 0, buffer.len() as u64) }
			.into_api_result()
			.expect("Cannot fail except for memory access; we provide a good address; qed");
	maybe_ok?;
	ServiceInfo::decode(&mut &buffer[..]).ok()
}

fn raw_get_foreign_storage(id: u64, key: &[u8]) -> Option<Vec<u8>> {
	let maybe_len: Option<u64> =
		unsafe { imports::read(id as _, key.as_ptr(), key.len() as u64, ptr::null_mut(), 0, 0) }
			.into_api_result()
			.expect("Cannot fail except for memory access; we provide a good address; qed");
	let len = maybe_len?;
	if len == 0 {
		Some(vec![])
	} else {
		let mut incoming = vec![0; len as usize];
		unsafe {
			imports::read(id as _, key.as_ptr(), key.len() as u64, incoming.as_mut_ptr(), 0, len);
		}
		Some(incoming)
	}
}

fn raw_get_foreign_storage_into(id: u64, key: &[u8], value: &mut [u8]) -> Option<usize> {
	let r: ApiResult<Option<u64>> = unsafe {
		imports::read(
			id as _,
			key.as_ptr(),
			key.len() as _,
			value.as_mut_ptr(),
			0,
			value.len() as _,
		)
	}
	.into_api_result();
	Some(r.expect("Only fail is memory access; address is good; qed")? as usize)
}