1use alloc::vec::Vec;
19
20#[cfg(not(substrate_runtime))]
21use tracing;
22
23#[cfg(not(substrate_runtime))]
24use sp_core::{
25 crypto::Pair,
26 hexdisplay::HexDisplay,
27 offchain::{OffchainDbExt, OffchainWorkerExt, TransactionPoolExt},
28 storage::ChildInfo,
29};
30#[cfg(not(substrate_runtime))]
31use sp_keystore::KeystoreExt;
32
33#[cfg(feature = "bandersnatch-experimental")]
34use sp_core::bandersnatch;
35use sp_core::{
36 crypto::KeyTypeId,
37 ecdsa, ed25519,
38 offchain::{
39 HttpError, HttpRequestId, HttpRequestStatus, OpaqueNetworkState, StorageKind, Timestamp,
40 },
41 sr25519,
42 storage::StateVersion,
43 LogLevelFilter, OpaquePeerId, RuntimeInterfaceLogLevel, H256,
44};
45
46#[cfg(feature = "bls-experimental")]
47use sp_core::{bls381, ecdsa_bls381};
48
49#[cfg(not(substrate_runtime))]
50use sp_trie::{LayoutV0, LayoutV1, TrieConfiguration};
51
52use sp_runtime_interface::{
53 pass_by::{
54 AllocateAndReturnByCodec, AllocateAndReturnFatPointer, AllocateAndReturnPointer, PassAs,
55 PassFatPointerAndDecode, PassFatPointerAndDecodeSlice, PassFatPointerAndRead,
56 PassFatPointerAndReadWrite, PassPointerAndRead, PassPointerAndReadCopy, ReturnAs,
57 },
58 runtime_interface, Pointer,
59};
60
61use codec::{Decode, Encode};
62
63#[cfg(not(substrate_runtime))]
64use secp256k1::{
65 ecdsa::{RecoverableSignature, RecoveryId},
66 Message,
67};
68
69#[cfg(not(substrate_runtime))]
70use sp_externalities::{Externalities, ExternalitiesExt};
71
72pub use sp_externalities::MultiRemovalResults;
73
74#[cfg(not(substrate_runtime))]
75const LOG_TARGET: &str = "runtime::io";
76
77#[derive(Encode, Decode)]
79pub enum EcdsaVerifyError {
80 BadRS,
82 BadV,
84 BadSignature,
86}
87
88#[derive(Encode, Decode)]
91pub enum KillStorageResult {
92 AllRemoved(u32),
95 SomeRemaining(u32),
98}
99
100impl From<MultiRemovalResults> for KillStorageResult {
101 fn from(r: MultiRemovalResults) -> Self {
102 match r.maybe_cursor {
106 None => Self::AllRemoved(r.loops),
107 Some(..) => Self::SomeRemaining(r.loops),
108 }
109 }
110}
111
112#[runtime_interface]
114pub trait Storage {
115 fn get(
117 &mut self,
118 key: PassFatPointerAndRead<&[u8]>,
119 ) -> AllocateAndReturnByCodec<Option<bytes::Bytes>> {
120 self.storage(key).map(|s| bytes::Bytes::from(s.to_vec()))
121 }
122
123 fn read(
129 &mut self,
130 key: PassFatPointerAndRead<&[u8]>,
131 value_out: PassFatPointerAndReadWrite<&mut [u8]>,
132 value_offset: u32,
133 ) -> AllocateAndReturnByCodec<Option<u32>> {
134 self.storage(key).map(|value| {
135 let value_offset = value_offset as usize;
136 let data = &value[value_offset.min(value.len())..];
137 let written = core::cmp::min(data.len(), value_out.len());
138 value_out[..written].copy_from_slice(&data[..written]);
139 data.len() as u32
140 })
141 }
142
143 fn set(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<&[u8]>) {
145 self.set_storage(key.to_vec(), value.to_vec());
146 }
147
148 fn clear(&mut self, key: PassFatPointerAndRead<&[u8]>) {
150 self.clear_storage(key)
151 }
152
153 fn exists(&mut self, key: PassFatPointerAndRead<&[u8]>) -> bool {
155 self.exists_storage(key)
156 }
157
158 fn clear_prefix(&mut self, prefix: PassFatPointerAndRead<&[u8]>) {
160 let _ = Externalities::clear_prefix(*self, prefix, None, None);
161 }
162
163 #[version(2)]
189 fn clear_prefix(
190 &mut self,
191 prefix: PassFatPointerAndRead<&[u8]>,
192 limit: PassFatPointerAndDecode<Option<u32>>,
193 ) -> AllocateAndReturnByCodec<KillStorageResult> {
194 Externalities::clear_prefix(*self, prefix, limit, None).into()
195 }
196
197 #[version(3, register_only)]
229 fn clear_prefix(
230 &mut self,
231 maybe_prefix: PassFatPointerAndRead<&[u8]>,
232 maybe_limit: PassFatPointerAndDecode<Option<u32>>,
233 maybe_cursor: PassFatPointerAndDecode<Option<Vec<u8>>>, ) -> AllocateAndReturnByCodec<MultiRemovalResults> {
236 Externalities::clear_prefix(
237 *self,
238 maybe_prefix,
239 maybe_limit,
240 maybe_cursor.as_ref().map(|x| &x[..]),
241 )
242 .into()
243 }
244
245 fn append(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<Vec<u8>>) {
254 self.storage_append(key.to_vec(), value);
255 }
256
257 #[version(2, register_only)]
273 fn append(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<Vec<u8>>) {
274 self.storage_append_v2(key.to_vec(), value);
275 }
276
277 fn root(&mut self) -> AllocateAndReturnFatPointer<Vec<u8>> {
283 self.storage_root_with_version(StateVersion::V0)
284 }
285
286 #[version(2)]
292 fn root(&mut self, version: PassAs<StateVersion, u8>) -> AllocateAndReturnFatPointer<Vec<u8>> {
293 self.storage_root_with_version(version)
294 }
295
296 fn changes_root(
298 &mut self,
299 _parent_hash: PassFatPointerAndRead<&[u8]>,
300 ) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
301 None
302 }
303
304 fn next_key(
306 &mut self,
307 key: PassFatPointerAndRead<&[u8]>,
308 ) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
309 self.next_storage_key(key)
310 }
311
312 fn start_transaction(&mut self) {
325 self.storage_start_transaction();
326 }
327
328 fn rollback_transaction(&mut self) {
336 self.storage_rollback_transaction()
337 .expect("No open transaction that can be rolled back.");
338 }
339
340 fn commit_transaction(&mut self) {
348 self.storage_commit_transaction()
349 .expect("No open transaction that can be committed.");
350 }
351}
352
353#[runtime_interface]
356pub trait DefaultChildStorage {
357 fn get(
362 &mut self,
363 storage_key: PassFatPointerAndRead<&[u8]>,
364 key: PassFatPointerAndRead<&[u8]>,
365 ) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
366 let child_info = ChildInfo::new_default(storage_key);
367 self.child_storage(&child_info, key).map(|s| s.to_vec())
368 }
369
370 fn read(
378 &mut self,
379 storage_key: PassFatPointerAndRead<&[u8]>,
380 key: PassFatPointerAndRead<&[u8]>,
381 value_out: PassFatPointerAndReadWrite<&mut [u8]>,
382 value_offset: u32,
383 ) -> AllocateAndReturnByCodec<Option<u32>> {
384 let child_info = ChildInfo::new_default(storage_key);
385 self.child_storage(&child_info, key).map(|value| {
386 let value_offset = value_offset as usize;
387 let data = &value[value_offset.min(value.len())..];
388 let written = core::cmp::min(data.len(), value_out.len());
389 value_out[..written].copy_from_slice(&data[..written]);
390 data.len() as u32
391 })
392 }
393
394 fn set(
398 &mut self,
399 storage_key: PassFatPointerAndRead<&[u8]>,
400 key: PassFatPointerAndRead<&[u8]>,
401 value: PassFatPointerAndRead<&[u8]>,
402 ) {
403 let child_info = ChildInfo::new_default(storage_key);
404 self.set_child_storage(&child_info, key.to_vec(), value.to_vec());
405 }
406
407 fn clear(
411 &mut self,
412 storage_key: PassFatPointerAndRead<&[u8]>,
413 key: PassFatPointerAndRead<&[u8]>,
414 ) {
415 let child_info = ChildInfo::new_default(storage_key);
416 self.clear_child_storage(&child_info, key);
417 }
418
419 fn storage_kill(&mut self, storage_key: PassFatPointerAndRead<&[u8]>) {
424 let child_info = ChildInfo::new_default(storage_key);
425 let _ = self.kill_child_storage(&child_info, None, None);
426 }
427
428 #[version(2)]
432 fn storage_kill(
433 &mut self,
434 storage_key: PassFatPointerAndRead<&[u8]>,
435 limit: PassFatPointerAndDecode<Option<u32>>,
436 ) -> bool {
437 let child_info = ChildInfo::new_default(storage_key);
438 let r = self.kill_child_storage(&child_info, limit, None);
439 r.maybe_cursor.is_none()
440 }
441
442 #[version(3)]
446 fn storage_kill(
447 &mut self,
448 storage_key: PassFatPointerAndRead<&[u8]>,
449 limit: PassFatPointerAndDecode<Option<u32>>,
450 ) -> AllocateAndReturnByCodec<KillStorageResult> {
451 let child_info = ChildInfo::new_default(storage_key);
452 self.kill_child_storage(&child_info, limit, None).into()
453 }
454
455 #[version(4, register_only)]
459 fn storage_kill(
460 &mut self,
461 storage_key: PassFatPointerAndRead<&[u8]>,
462 maybe_limit: PassFatPointerAndDecode<Option<u32>>,
463 maybe_cursor: PassFatPointerAndDecode<Option<Vec<u8>>>,
464 ) -> AllocateAndReturnByCodec<MultiRemovalResults> {
465 let child_info = ChildInfo::new_default(storage_key);
466 self.kill_child_storage(&child_info, maybe_limit, maybe_cursor.as_ref().map(|x| &x[..]))
467 .into()
468 }
469
470 fn exists(
474 &mut self,
475 storage_key: PassFatPointerAndRead<&[u8]>,
476 key: PassFatPointerAndRead<&[u8]>,
477 ) -> bool {
478 let child_info = ChildInfo::new_default(storage_key);
479 self.exists_child_storage(&child_info, key)
480 }
481
482 fn clear_prefix(
486 &mut self,
487 storage_key: PassFatPointerAndRead<&[u8]>,
488 prefix: PassFatPointerAndRead<&[u8]>,
489 ) {
490 let child_info = ChildInfo::new_default(storage_key);
491 let _ = self.clear_child_prefix(&child_info, prefix, None, None);
492 }
493
494 #[version(2)]
498 fn clear_prefix(
499 &mut self,
500 storage_key: PassFatPointerAndRead<&[u8]>,
501 prefix: PassFatPointerAndRead<&[u8]>,
502 limit: PassFatPointerAndDecode<Option<u32>>,
503 ) -> AllocateAndReturnByCodec<KillStorageResult> {
504 let child_info = ChildInfo::new_default(storage_key);
505 self.clear_child_prefix(&child_info, prefix, limit, None).into()
506 }
507
508 #[version(3, register_only)]
512 fn clear_prefix(
513 &mut self,
514 storage_key: PassFatPointerAndRead<&[u8]>,
515 prefix: PassFatPointerAndRead<&[u8]>,
516 maybe_limit: PassFatPointerAndDecode<Option<u32>>,
517 maybe_cursor: PassFatPointerAndDecode<Option<Vec<u8>>>,
518 ) -> AllocateAndReturnByCodec<MultiRemovalResults> {
519 let child_info = ChildInfo::new_default(storage_key);
520 self.clear_child_prefix(
521 &child_info,
522 prefix,
523 maybe_limit,
524 maybe_cursor.as_ref().map(|x| &x[..]),
525 )
526 .into()
527 }
528
529 fn root(
536 &mut self,
537 storage_key: PassFatPointerAndRead<&[u8]>,
538 ) -> AllocateAndReturnFatPointer<Vec<u8>> {
539 let child_info = ChildInfo::new_default(storage_key);
540 self.child_storage_root_with_version(&child_info, StateVersion::V0)
541 }
542
543 #[version(2)]
550 fn root(
551 &mut self,
552 storage_key: PassFatPointerAndRead<&[u8]>,
553 version: PassAs<StateVersion, u8>,
554 ) -> AllocateAndReturnFatPointer<Vec<u8>> {
555 let child_info = ChildInfo::new_default(storage_key);
556 self.child_storage_root_with_version(&child_info, version)
557 }
558
559 #[version(3, register_only)]
576 fn root(
577 &mut self,
578 storage_key: PassFatPointerAndRead<&[u8]>,
579 ) -> AllocateAndReturnFatPointer<Vec<u8>> {
580 let child_info = ChildInfo::new_default(storage_key);
581 self.child_storage_root_v3(&child_info)
582 }
583
584 fn next_key(
588 &mut self,
589 storage_key: PassFatPointerAndRead<&[u8]>,
590 key: PassFatPointerAndRead<&[u8]>,
591 ) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
592 let child_info = ChildInfo::new_default(storage_key);
593 self.next_child_storage_key(&child_info, key)
594 }
595}
596
597#[runtime_interface]
599pub trait Trie {
600 fn blake2_256_root(
602 input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
603 ) -> AllocateAndReturnPointer<H256, 32> {
604 LayoutV0::<sp_core::Blake2Hasher>::trie_root(input)
605 }
606
607 #[version(2)]
609 fn blake2_256_root(
610 input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
611 version: PassAs<StateVersion, u8>,
612 ) -> AllocateAndReturnPointer<H256, 32> {
613 match version {
614 StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::trie_root(input),
615 StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::trie_root(input),
616 }
617 }
618
619 fn blake2_256_ordered_root(
621 input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
622 ) -> AllocateAndReturnPointer<H256, 32> {
623 LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input)
624 }
625
626 #[version(2)]
628 fn blake2_256_ordered_root(
629 input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
630 version: PassAs<StateVersion, u8>,
631 ) -> AllocateAndReturnPointer<H256, 32> {
632 match version {
633 StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input),
634 StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::ordered_trie_root(input),
635 }
636 }
637
638 fn keccak_256_root(
640 input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
641 ) -> AllocateAndReturnPointer<H256, 32> {
642 LayoutV0::<sp_core::KeccakHasher>::trie_root(input)
643 }
644
645 #[version(2)]
647 fn keccak_256_root(
648 input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
649 version: PassAs<StateVersion, u8>,
650 ) -> AllocateAndReturnPointer<H256, 32> {
651 match version {
652 StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::trie_root(input),
653 StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::trie_root(input),
654 }
655 }
656
657 fn keccak_256_ordered_root(
659 input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
660 ) -> AllocateAndReturnPointer<H256, 32> {
661 LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input)
662 }
663
664 #[version(2)]
666 fn keccak_256_ordered_root(
667 input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
668 version: PassAs<StateVersion, u8>,
669 ) -> AllocateAndReturnPointer<H256, 32> {
670 match version {
671 StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input),
672 StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::ordered_trie_root(input),
673 }
674 }
675
676 fn blake2_256_verify_proof(
678 root: PassPointerAndReadCopy<H256, 32>,
679 proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
680 key: PassFatPointerAndRead<&[u8]>,
681 value: PassFatPointerAndRead<&[u8]>,
682 ) -> bool {
683 sp_trie::verify_trie_proof::<LayoutV0<sp_core::Blake2Hasher>, _, _, _>(
684 &root,
685 proof,
686 &[(key, Some(value))],
687 )
688 .is_ok()
689 }
690
691 #[version(2)]
693 fn blake2_256_verify_proof(
694 root: PassPointerAndReadCopy<H256, 32>,
695 proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
696 key: PassFatPointerAndRead<&[u8]>,
697 value: PassFatPointerAndRead<&[u8]>,
698 version: PassAs<StateVersion, u8>,
699 ) -> bool {
700 match version {
701 StateVersion::V0 => sp_trie::verify_trie_proof::<
702 LayoutV0<sp_core::Blake2Hasher>,
703 _,
704 _,
705 _,
706 >(&root, proof, &[(key, Some(value))])
707 .is_ok(),
708 StateVersion::V1 => sp_trie::verify_trie_proof::<
709 LayoutV1<sp_core::Blake2Hasher>,
710 _,
711 _,
712 _,
713 >(&root, proof, &[(key, Some(value))])
714 .is_ok(),
715 }
716 }
717
718 fn keccak_256_verify_proof(
720 root: PassPointerAndReadCopy<H256, 32>,
721 proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
722 key: PassFatPointerAndRead<&[u8]>,
723 value: PassFatPointerAndRead<&[u8]>,
724 ) -> bool {
725 sp_trie::verify_trie_proof::<LayoutV0<sp_core::KeccakHasher>, _, _, _>(
726 &root,
727 proof,
728 &[(key, Some(value))],
729 )
730 .is_ok()
731 }
732
733 #[version(2)]
735 fn keccak_256_verify_proof(
736 root: PassPointerAndReadCopy<H256, 32>,
737 proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
738 key: PassFatPointerAndRead<&[u8]>,
739 value: PassFatPointerAndRead<&[u8]>,
740 version: PassAs<StateVersion, u8>,
741 ) -> bool {
742 match version {
743 StateVersion::V0 => sp_trie::verify_trie_proof::<
744 LayoutV0<sp_core::KeccakHasher>,
745 _,
746 _,
747 _,
748 >(&root, proof, &[(key, Some(value))])
749 .is_ok(),
750 StateVersion::V1 => sp_trie::verify_trie_proof::<
751 LayoutV1<sp_core::KeccakHasher>,
752 _,
753 _,
754 _,
755 >(&root, proof, &[(key, Some(value))])
756 .is_ok(),
757 }
758 }
759}
760
761#[runtime_interface]
764pub trait Misc {
765 fn print_num(val: u64) {
770 log::debug!(target: "runtime", "{}", val);
771 }
772
773 fn print_utf8(utf8: PassFatPointerAndRead<&[u8]>) {
775 if let Ok(data) = core::str::from_utf8(utf8) {
776 log::debug!(target: "runtime", "{}", data)
777 }
778 }
779
780 fn print_hex(data: PassFatPointerAndRead<&[u8]>) {
782 log::debug!(target: "runtime", "{}", HexDisplay::from(&data));
783 }
784
785 fn runtime_version(
801 &mut self,
802 wasm: PassFatPointerAndRead<&[u8]>,
803 ) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
804 use sp_core::traits::ReadRuntimeVersionExt;
805
806 let mut ext = sp_state_machine::BasicExternalities::default();
807
808 match self
809 .extension::<ReadRuntimeVersionExt>()
810 .expect("No `ReadRuntimeVersionExt` associated for the current context!")
811 .read_runtime_version(wasm, &mut ext)
812 {
813 Ok(v) => Some(v),
814 Err(err) => {
815 log::debug!(
816 target: LOG_TARGET,
817 "cannot read version from the given runtime: {}",
818 err,
819 );
820 None
821 },
822 }
823 }
824}
825
826#[cfg(not(substrate_runtime))]
827sp_externalities::decl_extension! {
828 pub struct UseDalekExt;
845}
846
847#[cfg(not(substrate_runtime))]
848impl Default for UseDalekExt {
849 fn default() -> Self {
850 Self
851 }
852}
853
854#[runtime_interface]
856pub trait Crypto {
857 fn ed25519_public_keys(
859 &mut self,
860 id: PassPointerAndReadCopy<KeyTypeId, 4>,
861 ) -> AllocateAndReturnByCodec<Vec<ed25519::Public>> {
862 self.extension::<KeystoreExt>()
863 .expect("No `keystore` associated for the current context!")
864 .ed25519_public_keys(id)
865 }
866
867 fn ed25519_generate(
874 &mut self,
875 id: PassPointerAndReadCopy<KeyTypeId, 4>,
876 seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
877 ) -> AllocateAndReturnPointer<ed25519::Public, 32> {
878 let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
879 self.extension::<KeystoreExt>()
880 .expect("No `keystore` associated for the current context!")
881 .ed25519_generate_new(id, seed)
882 .expect("`ed25519_generate` failed")
883 }
884
885 fn ed25519_sign(
890 &mut self,
891 id: PassPointerAndReadCopy<KeyTypeId, 4>,
892 pub_key: PassPointerAndRead<&ed25519::Public, 32>,
893 msg: PassFatPointerAndRead<&[u8]>,
894 ) -> AllocateAndReturnByCodec<Option<ed25519::Signature>> {
895 self.extension::<KeystoreExt>()
896 .expect("No `keystore` associated for the current context!")
897 .ed25519_sign(id, pub_key, msg)
898 .ok()
899 .flatten()
900 }
901
902 fn ed25519_verify(
906 sig: PassPointerAndRead<&ed25519::Signature, 64>,
907 msg: PassFatPointerAndRead<&[u8]>,
908 pub_key: PassPointerAndRead<&ed25519::Public, 32>,
909 ) -> bool {
910 if sp_externalities::with_externalities(|mut e| e.extension::<UseDalekExt>().is_some())
914 .unwrap_or_default()
915 {
916 use ed25519_dalek::Verifier;
917
918 let Ok(public_key) = ed25519_dalek::VerifyingKey::from_bytes(&pub_key.0) else {
919 return false;
920 };
921
922 let sig = ed25519_dalek::Signature::from_bytes(&sig.0);
923
924 public_key.verify(msg, &sig).is_ok()
925 } else {
926 ed25519::Pair::verify(sig, msg, pub_key)
927 }
928 }
929
930 #[version(1, register_only)]
944 fn ed25519_batch_verify(
945 &mut self,
946 sig: PassPointerAndRead<&ed25519::Signature, 64>,
947 msg: PassFatPointerAndRead<&[u8]>,
948 pub_key: PassPointerAndRead<&ed25519::Public, 32>,
949 ) -> bool {
950 let res = ed25519_verify(sig, msg, pub_key);
951
952 if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
953 ext.0 &= res;
954 }
955
956 res
957 }
958
959 #[version(2)]
963 fn sr25519_verify(
964 sig: PassPointerAndRead<&sr25519::Signature, 64>,
965 msg: PassFatPointerAndRead<&[u8]>,
966 pub_key: PassPointerAndRead<&sr25519::Public, 32>,
967 ) -> bool {
968 sr25519::Pair::verify(sig, msg, pub_key)
969 }
970
971 #[version(1, register_only)]
985 fn sr25519_batch_verify(
986 &mut self,
987 sig: PassPointerAndRead<&sr25519::Signature, 64>,
988 msg: PassFatPointerAndRead<&[u8]>,
989 pub_key: PassPointerAndRead<&sr25519::Public, 32>,
990 ) -> bool {
991 let res = sr25519_verify(sig, msg, pub_key);
992
993 if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
994 ext.0 &= res;
995 }
996
997 res
998 }
999
1000 #[version(1, register_only)]
1007 fn start_batch_verify(&mut self) {
1008 self.register_extension(VerificationExtDeprecated(true))
1009 .expect("Failed to register required extension: `VerificationExt`");
1010 }
1011
1012 #[version(1, register_only)]
1024 fn finish_batch_verify(&mut self) -> bool {
1025 let result = self
1026 .extension::<VerificationExtDeprecated>()
1027 .expect("`finish_batch_verify` should only be called after `start_batch_verify`")
1028 .0;
1029
1030 self.deregister_extension::<VerificationExtDeprecated>()
1031 .expect("No verification extension in current context!");
1032
1033 result
1034 }
1035
1036 fn sr25519_public_keys(
1038 &mut self,
1039 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1040 ) -> AllocateAndReturnByCodec<Vec<sr25519::Public>> {
1041 self.extension::<KeystoreExt>()
1042 .expect("No `keystore` associated for the current context!")
1043 .sr25519_public_keys(id)
1044 }
1045
1046 fn sr25519_generate(
1053 &mut self,
1054 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1055 seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1056 ) -> AllocateAndReturnPointer<sr25519::Public, 32> {
1057 let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1058 self.extension::<KeystoreExt>()
1059 .expect("No `keystore` associated for the current context!")
1060 .sr25519_generate_new(id, seed)
1061 .expect("`sr25519_generate` failed")
1062 }
1063
1064 fn sr25519_sign(
1069 &mut self,
1070 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1071 pub_key: PassPointerAndRead<&sr25519::Public, 32>,
1072 msg: PassFatPointerAndRead<&[u8]>,
1073 ) -> AllocateAndReturnByCodec<Option<sr25519::Signature>> {
1074 self.extension::<KeystoreExt>()
1075 .expect("No `keystore` associated for the current context!")
1076 .sr25519_sign(id, pub_key, msg)
1077 .ok()
1078 .flatten()
1079 }
1080
1081 fn sr25519_verify(
1086 sig: PassPointerAndRead<&sr25519::Signature, 64>,
1087 msg: PassFatPointerAndRead<&[u8]>,
1088 pubkey: PassPointerAndRead<&sr25519::Public, 32>,
1089 ) -> bool {
1090 sr25519::Pair::verify_deprecated(sig, msg, pubkey)
1091 }
1092
1093 fn ecdsa_public_keys(
1095 &mut self,
1096 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1097 ) -> AllocateAndReturnByCodec<Vec<ecdsa::Public>> {
1098 self.extension::<KeystoreExt>()
1099 .expect("No `keystore` associated for the current context!")
1100 .ecdsa_public_keys(id)
1101 }
1102
1103 fn ecdsa_generate(
1110 &mut self,
1111 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1112 seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1113 ) -> AllocateAndReturnPointer<ecdsa::Public, 33> {
1114 let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1115 self.extension::<KeystoreExt>()
1116 .expect("No `keystore` associated for the current context!")
1117 .ecdsa_generate_new(id, seed)
1118 .expect("`ecdsa_generate` failed")
1119 }
1120
1121 fn ecdsa_sign(
1126 &mut self,
1127 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1128 pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1129 msg: PassFatPointerAndRead<&[u8]>,
1130 ) -> AllocateAndReturnByCodec<Option<ecdsa::Signature>> {
1131 self.extension::<KeystoreExt>()
1132 .expect("No `keystore` associated for the current context!")
1133 .ecdsa_sign(id, pub_key, msg)
1134 .ok()
1135 .flatten()
1136 }
1137
1138 fn ecdsa_sign_prehashed(
1143 &mut self,
1144 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1145 pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1146 msg: PassPointerAndRead<&[u8; 32], 32>,
1147 ) -> AllocateAndReturnByCodec<Option<ecdsa::Signature>> {
1148 self.extension::<KeystoreExt>()
1149 .expect("No `keystore` associated for the current context!")
1150 .ecdsa_sign_prehashed(id, pub_key, msg)
1151 .ok()
1152 .flatten()
1153 }
1154
1155 fn ecdsa_verify(
1164 sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1165 msg: PassFatPointerAndRead<&[u8]>,
1166 pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1167 ) -> bool {
1168 #[allow(deprecated)]
1169 ecdsa::Pair::verify_deprecated(sig, msg, pub_key)
1170 }
1171
1172 #[version(2)]
1180 fn ecdsa_verify(
1181 sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1182 msg: PassFatPointerAndRead<&[u8]>,
1183 pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1184 ) -> bool {
1185 ecdsa::Pair::verify(sig, msg, pub_key)
1186 }
1187
1188 fn ecdsa_verify_prehashed(
1196 sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1197 msg: PassPointerAndRead<&[u8; 32], 32>,
1198 pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1199 ) -> bool {
1200 ecdsa::Pair::verify_prehashed(sig, msg, pub_key)
1201 }
1202
1203 #[version(1, register_only)]
1217 fn ecdsa_batch_verify(
1218 &mut self,
1219 sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1220 msg: PassFatPointerAndRead<&[u8]>,
1221 pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1222 ) -> bool {
1223 let res = ecdsa_verify(sig, msg, pub_key);
1224
1225 if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
1226 ext.0 &= res;
1227 }
1228
1229 res
1230 }
1231
1232 fn secp256k1_ecdsa_recover(
1245 sig: PassPointerAndRead<&[u8; 65], 65>,
1246 msg: PassPointerAndRead<&[u8; 32], 32>,
1247 ) -> AllocateAndReturnByCodec<Result<[u8; 64], EcdsaVerifyError>> {
1248 let rid = libsecp256k1::RecoveryId::parse(
1249 if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
1250 )
1251 .map_err(|_| EcdsaVerifyError::BadV)?;
1252 let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[..64])
1253 .map_err(|_| EcdsaVerifyError::BadRS)?;
1254 let msg = libsecp256k1::Message::parse(msg);
1255 let pubkey =
1256 libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
1257 let mut res = [0u8; 64];
1258 res.copy_from_slice(&pubkey.serialize()[1..65]);
1259 Ok(res)
1260 }
1261
1262 #[version(2)]
1274 fn secp256k1_ecdsa_recover(
1275 sig: PassPointerAndRead<&[u8; 65], 65>,
1276 msg: PassPointerAndRead<&[u8; 32], 32>,
1277 ) -> AllocateAndReturnByCodec<Result<[u8; 64], EcdsaVerifyError>> {
1278 let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
1279 .map_err(|_| EcdsaVerifyError::BadV)?;
1280 let sig = RecoverableSignature::from_compact(&sig[..64], rid)
1281 .map_err(|_| EcdsaVerifyError::BadRS)?;
1282 let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
1283 #[cfg(feature = "std")]
1284 let ctx = secp256k1::SECP256K1;
1285 #[cfg(not(feature = "std"))]
1286 let ctx = secp256k1::Secp256k1::<secp256k1::VerifyOnly>::gen_new();
1287 let pubkey = ctx.recover_ecdsa(&msg, &sig).map_err(|_| EcdsaVerifyError::BadSignature)?;
1288 let mut res = [0u8; 64];
1289 res.copy_from_slice(&pubkey.serialize_uncompressed()[1..]);
1290 Ok(res)
1291 }
1292
1293 fn secp256k1_ecdsa_recover_compressed(
1304 sig: PassPointerAndRead<&[u8; 65], 65>,
1305 msg: PassPointerAndRead<&[u8; 32], 32>,
1306 ) -> AllocateAndReturnByCodec<Result<[u8; 33], EcdsaVerifyError>> {
1307 let rid = libsecp256k1::RecoveryId::parse(
1308 if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
1309 )
1310 .map_err(|_| EcdsaVerifyError::BadV)?;
1311 let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[0..64])
1312 .map_err(|_| EcdsaVerifyError::BadRS)?;
1313 let msg = libsecp256k1::Message::parse(msg);
1314 let pubkey =
1315 libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
1316 Ok(pubkey.serialize_compressed())
1317 }
1318
1319 #[version(2)]
1330 fn secp256k1_ecdsa_recover_compressed(
1331 sig: PassPointerAndRead<&[u8; 65], 65>,
1332 msg: PassPointerAndRead<&[u8; 32], 32>,
1333 ) -> AllocateAndReturnByCodec<Result<[u8; 33], EcdsaVerifyError>> {
1334 let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
1335 .map_err(|_| EcdsaVerifyError::BadV)?;
1336 let sig = RecoverableSignature::from_compact(&sig[..64], rid)
1337 .map_err(|_| EcdsaVerifyError::BadRS)?;
1338 let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
1339 #[cfg(feature = "std")]
1340 let ctx = secp256k1::SECP256K1;
1341 #[cfg(not(feature = "std"))]
1342 let ctx = secp256k1::Secp256k1::<secp256k1::VerifyOnly>::gen_new();
1343 let pubkey = ctx.recover_ecdsa(&msg, &sig).map_err(|_| EcdsaVerifyError::BadSignature)?;
1344 Ok(pubkey.serialize())
1345 }
1346
1347 #[cfg(feature = "bls-experimental")]
1354 fn bls381_generate(
1355 &mut self,
1356 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1357 seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1358 ) -> AllocateAndReturnPointer<bls381::Public, 144> {
1359 let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1360 self.extension::<KeystoreExt>()
1361 .expect("No `keystore` associated for the current context!")
1362 .bls381_generate_new(id, seed)
1363 .expect("`bls381_generate` failed")
1364 }
1365
1366 #[cfg(feature = "bls-experimental")]
1371 fn bls381_generate_proof_of_possession(
1372 &mut self,
1373 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1374 pub_key: PassPointerAndRead<&bls381::Public, 144>,
1375 owner: PassFatPointerAndRead<&[u8]>,
1376 ) -> AllocateAndReturnByCodec<Option<bls381::ProofOfPossession>> {
1377 self.extension::<KeystoreExt>()
1378 .expect("No `keystore` associated for the current context!")
1379 .bls381_generate_proof_of_possession(id, pub_key, owner)
1380 .ok()
1381 .flatten()
1382 }
1383
1384 #[cfg(feature = "bls-experimental")]
1391 fn ecdsa_bls381_generate(
1392 &mut self,
1393 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1394 seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1395 ) -> AllocateAndReturnPointer<ecdsa_bls381::Public, { 144 + 33 }> {
1396 let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1397 self.extension::<KeystoreExt>()
1398 .expect("No `keystore` associated for the current context!")
1399 .ecdsa_bls381_generate_new(id, seed)
1400 .expect("`ecdsa_bls381_generate` failed")
1401 }
1402
1403 #[cfg(feature = "bandersnatch-experimental")]
1410 fn bandersnatch_generate(
1411 &mut self,
1412 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1413 seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1414 ) -> AllocateAndReturnPointer<bandersnatch::Public, 32> {
1415 let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1416 self.extension::<KeystoreExt>()
1417 .expect("No `keystore` associated for the current context!")
1418 .bandersnatch_generate_new(id, seed)
1419 .expect("`bandernatch_generate` failed")
1420 }
1421
1422 #[cfg(feature = "bandersnatch-experimental")]
1427 fn bandersnatch_sign(
1428 &mut self,
1429 id: PassPointerAndReadCopy<KeyTypeId, 4>,
1430 pub_key: PassPointerAndRead<&bandersnatch::Public, 32>,
1431 msg: PassFatPointerAndRead<&[u8]>,
1432 ) -> AllocateAndReturnByCodec<Option<bandersnatch::Signature>> {
1433 self.extension::<KeystoreExt>()
1434 .expect("No `keystore` associated for the current context!")
1435 .bandersnatch_sign(id, pub_key, msg)
1436 .ok()
1437 .flatten()
1438 }
1439}
1440
1441#[runtime_interface]
1443pub trait Hashing {
1444 fn keccak_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1446 sp_crypto_hashing::keccak_256(data)
1447 }
1448
1449 fn keccak_512(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 64], 64> {
1451 sp_crypto_hashing::keccak_512(data)
1452 }
1453
1454 fn sha2_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1456 sp_crypto_hashing::sha2_256(data)
1457 }
1458
1459 fn blake2_128(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 16], 16> {
1461 sp_crypto_hashing::blake2_128(data)
1462 }
1463
1464 fn blake2_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1466 sp_crypto_hashing::blake2_256(data)
1467 }
1468
1469 fn twox_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1471 sp_crypto_hashing::twox_256(data)
1472 }
1473
1474 fn twox_128(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 16], 16> {
1476 sp_crypto_hashing::twox_128(data)
1477 }
1478
1479 fn twox_64(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 8], 8> {
1481 sp_crypto_hashing::twox_64(data)
1482 }
1483}
1484
1485#[runtime_interface]
1487pub trait TransactionIndex {
1488 fn index(
1490 &mut self,
1491 extrinsic: u32,
1492 size: u32,
1493 context_hash: PassPointerAndReadCopy<[u8; 32], 32>,
1494 ) {
1495 self.storage_index_transaction(extrinsic, &context_hash, size);
1496 }
1497
1498 fn renew(&mut self, extrinsic: u32, context_hash: PassPointerAndReadCopy<[u8; 32], 32>) {
1501 self.storage_renew_transaction_index(extrinsic, &context_hash);
1502 }
1503}
1504
1505#[runtime_interface]
1507pub trait OffchainIndex {
1508 fn set(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<&[u8]>) {
1510 self.set_offchain_storage(key, Some(value));
1511 }
1512
1513 fn clear(&mut self, key: PassFatPointerAndRead<&[u8]>) {
1515 self.set_offchain_storage(key, None);
1516 }
1517}
1518
1519#[cfg(not(substrate_runtime))]
1520sp_externalities::decl_extension! {
1521 struct VerificationExtDeprecated(bool);
1525}
1526
1527#[runtime_interface]
1531pub trait Offchain {
1532 fn is_validator(&mut self) -> bool {
1537 self.extension::<OffchainWorkerExt>()
1538 .expect("is_validator can be called only in the offchain worker context")
1539 .is_validator()
1540 }
1541
1542 fn submit_transaction(
1546 &mut self,
1547 data: PassFatPointerAndRead<Vec<u8>>,
1548 ) -> AllocateAndReturnByCodec<Result<(), ()>> {
1549 self.extension::<TransactionPoolExt>()
1550 .expect(
1551 "submit_transaction can be called only in the offchain call context with
1552 TransactionPool capabilities enabled",
1553 )
1554 .submit_transaction(data)
1555 }
1556
1557 fn network_state(&mut self) -> AllocateAndReturnByCodec<Result<OpaqueNetworkState, ()>> {
1559 self.extension::<OffchainWorkerExt>()
1560 .expect("network_state can be called only in the offchain worker context")
1561 .network_state()
1562 }
1563
1564 fn timestamp(&mut self) -> ReturnAs<Timestamp, u64> {
1566 self.extension::<OffchainWorkerExt>()
1567 .expect("timestamp can be called only in the offchain worker context")
1568 .timestamp()
1569 }
1570
1571 fn sleep_until(&mut self, deadline: PassAs<Timestamp, u64>) {
1573 self.extension::<OffchainWorkerExt>()
1574 .expect("sleep_until can be called only in the offchain worker context")
1575 .sleep_until(deadline)
1576 }
1577
1578 fn random_seed(&mut self) -> AllocateAndReturnPointer<[u8; 32], 32> {
1583 self.extension::<OffchainWorkerExt>()
1584 .expect("random_seed can be called only in the offchain worker context")
1585 .random_seed()
1586 }
1587
1588 fn local_storage_set(
1593 &mut self,
1594 kind: PassAs<StorageKind, u32>,
1595 key: PassFatPointerAndRead<&[u8]>,
1596 value: PassFatPointerAndRead<&[u8]>,
1597 ) {
1598 self.extension::<OffchainDbExt>()
1599 .expect(
1600 "local_storage_set can be called only in the offchain call context with
1601 OffchainDb extension",
1602 )
1603 .local_storage_set(kind, key, value)
1604 }
1605
1606 fn local_storage_clear(
1611 &mut self,
1612 kind: PassAs<StorageKind, u32>,
1613 key: PassFatPointerAndRead<&[u8]>,
1614 ) {
1615 self.extension::<OffchainDbExt>()
1616 .expect(
1617 "local_storage_clear can be called only in the offchain call context with
1618 OffchainDb extension",
1619 )
1620 .local_storage_clear(kind, key)
1621 }
1622
1623 fn local_storage_compare_and_set(
1633 &mut self,
1634 kind: PassAs<StorageKind, u32>,
1635 key: PassFatPointerAndRead<&[u8]>,
1636 old_value: PassFatPointerAndDecode<Option<Vec<u8>>>,
1637 new_value: PassFatPointerAndRead<&[u8]>,
1638 ) -> bool {
1639 self.extension::<OffchainDbExt>()
1640 .expect(
1641 "local_storage_compare_and_set can be called only in the offchain call context
1642 with OffchainDb extension",
1643 )
1644 .local_storage_compare_and_set(kind, key, old_value.as_deref(), new_value)
1645 }
1646
1647 fn local_storage_get(
1653 &mut self,
1654 kind: PassAs<StorageKind, u32>,
1655 key: PassFatPointerAndRead<&[u8]>,
1656 ) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
1657 self.extension::<OffchainDbExt>()
1658 .expect(
1659 "local_storage_get can be called only in the offchain call context with
1660 OffchainDb extension",
1661 )
1662 .local_storage_get(kind, key)
1663 }
1664
1665 fn http_request_start(
1670 &mut self,
1671 method: PassFatPointerAndRead<&str>,
1672 uri: PassFatPointerAndRead<&str>,
1673 meta: PassFatPointerAndRead<&[u8]>,
1674 ) -> AllocateAndReturnByCodec<Result<HttpRequestId, ()>> {
1675 self.extension::<OffchainWorkerExt>()
1676 .expect("http_request_start can be called only in the offchain worker context")
1677 .http_request_start(method, uri, meta)
1678 }
1679
1680 fn http_request_add_header(
1682 &mut self,
1683 request_id: PassAs<HttpRequestId, u16>,
1684 name: PassFatPointerAndRead<&str>,
1685 value: PassFatPointerAndRead<&str>,
1686 ) -> AllocateAndReturnByCodec<Result<(), ()>> {
1687 self.extension::<OffchainWorkerExt>()
1688 .expect("http_request_add_header can be called only in the offchain worker context")
1689 .http_request_add_header(request_id, name, value)
1690 }
1691
1692 fn http_request_write_body(
1699 &mut self,
1700 request_id: PassAs<HttpRequestId, u16>,
1701 chunk: PassFatPointerAndRead<&[u8]>,
1702 deadline: PassFatPointerAndDecode<Option<Timestamp>>,
1703 ) -> AllocateAndReturnByCodec<Result<(), HttpError>> {
1704 self.extension::<OffchainWorkerExt>()
1705 .expect("http_request_write_body can be called only in the offchain worker context")
1706 .http_request_write_body(request_id, chunk, deadline)
1707 }
1708
1709 fn http_response_wait(
1717 &mut self,
1718 ids: PassFatPointerAndDecodeSlice<&[HttpRequestId]>,
1719 deadline: PassFatPointerAndDecode<Option<Timestamp>>,
1720 ) -> AllocateAndReturnByCodec<Vec<HttpRequestStatus>> {
1721 self.extension::<OffchainWorkerExt>()
1722 .expect("http_response_wait can be called only in the offchain worker context")
1723 .http_response_wait(ids, deadline)
1724 }
1725
1726 fn http_response_headers(
1731 &mut self,
1732 request_id: PassAs<HttpRequestId, u16>,
1733 ) -> AllocateAndReturnByCodec<Vec<(Vec<u8>, Vec<u8>)>> {
1734 self.extension::<OffchainWorkerExt>()
1735 .expect("http_response_headers can be called only in the offchain worker context")
1736 .http_response_headers(request_id)
1737 }
1738
1739 fn http_response_read_body(
1748 &mut self,
1749 request_id: PassAs<HttpRequestId, u16>,
1750 buffer: PassFatPointerAndReadWrite<&mut [u8]>,
1751 deadline: PassFatPointerAndDecode<Option<Timestamp>>,
1752 ) -> AllocateAndReturnByCodec<Result<u32, HttpError>> {
1753 self.extension::<OffchainWorkerExt>()
1754 .expect("http_response_read_body can be called only in the offchain worker context")
1755 .http_response_read_body(request_id, buffer, deadline)
1756 .map(|r| r as u32)
1757 }
1758
1759 fn set_authorized_nodes(
1761 &mut self,
1762 nodes: PassFatPointerAndDecode<Vec<OpaquePeerId>>,
1763 authorized_only: bool,
1764 ) {
1765 self.extension::<OffchainWorkerExt>()
1766 .expect("set_authorized_nodes can be called only in the offchain worker context")
1767 .set_authorized_nodes(nodes, authorized_only)
1768 }
1769}
1770
1771#[runtime_interface(wasm_only)]
1773pub trait Allocator {
1774 fn malloc(&mut self, size: u32) -> Pointer<u8> {
1776 self.allocate_memory(size).expect("Failed to allocate memory")
1777 }
1778
1779 fn free(&mut self, ptr: Pointer<u8>) {
1781 self.deallocate_memory(ptr).expect("Failed to deallocate memory")
1782 }
1783}
1784
1785#[runtime_interface(wasm_only)]
1788pub trait PanicHandler {
1789 #[trap_on_return]
1791 fn abort_on_panic(&mut self, message: PassFatPointerAndRead<&str>) {
1792 self.register_panic_error_message(message);
1793 }
1794}
1795
1796#[runtime_interface]
1798pub trait Logging {
1799 fn log(
1806 level: PassAs<RuntimeInterfaceLogLevel, u8>,
1807 target: PassFatPointerAndRead<&str>,
1808 message: PassFatPointerAndRead<&[u8]>,
1809 ) {
1810 if let Ok(message) = core::str::from_utf8(message) {
1811 log::log!(target: target, log::Level::from(level), "{}", message)
1812 }
1813 }
1814
1815 fn max_level() -> ReturnAs<LogLevelFilter, u8> {
1817 log::max_level().into()
1818 }
1819}
1820
1821#[runtime_interface(wasm_only, no_tracing)]
1824pub trait WasmTracing {
1825 fn enabled(&mut self, metadata: PassFatPointerAndDecode<sp_tracing::WasmMetadata>) -> bool {
1835 let metadata: &tracing_core::metadata::Metadata<'static> = (&metadata).into();
1836 tracing::dispatcher::get_default(|d| d.enabled(metadata))
1837 }
1838
1839 fn enter_span(
1846 &mut self,
1847 span: PassFatPointerAndDecode<sp_tracing::WasmEntryAttributes>,
1848 ) -> u64 {
1849 let span: tracing::Span = span.into();
1850 match span.id() {
1851 Some(id) => tracing::dispatcher::get_default(|d| {
1852 let final_id = d.clone_span(&id);
1855 d.enter(&final_id);
1856 final_id.into_u64()
1857 }),
1858 _ => 0,
1859 }
1860 }
1861
1862 fn event(&mut self, event: PassFatPointerAndDecode<sp_tracing::WasmEntryAttributes>) {
1864 event.emit();
1865 }
1866
1867 fn exit(&mut self, span: u64) {
1870 tracing::dispatcher::get_default(|d| {
1871 let id = tracing_core::span::Id::from_u64(span);
1872 d.exit(&id);
1873 });
1874 }
1875}
1876
1877#[cfg(all(substrate_runtime, feature = "with-tracing"))]
1878mod tracing_setup {
1879 use super::wasm_tracing;
1880 use core::sync::atomic::{AtomicBool, Ordering};
1881 use tracing_core::{
1882 dispatcher::{set_global_default, Dispatch},
1883 span::{Attributes, Id, Record},
1884 Event, Metadata,
1885 };
1886
1887 static TRACING_SET: AtomicBool = AtomicBool::new(false);
1888
1889 struct PassingTracingSubscriber;
1892
1893 impl tracing_core::Subscriber for PassingTracingSubscriber {
1894 fn enabled(&self, metadata: &Metadata<'_>) -> bool {
1895 wasm_tracing::enabled(metadata.into())
1896 }
1897 fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1898 Id::from_u64(wasm_tracing::enter_span(attrs.into()))
1899 }
1900 fn enter(&self, _: &Id) {
1901 }
1903 fn record(&self, _: &Id, _: &Record<'_>) {
1906 unimplemented! {} }
1908 fn record_follows_from(&self, _: &Id, _: &Id) {
1911 unimplemented! {} }
1913 fn event(&self, event: &Event<'_>) {
1914 wasm_tracing::event(event.into())
1915 }
1916 fn exit(&self, span: &Id) {
1917 wasm_tracing::exit(span.into_u64())
1918 }
1919 }
1920
1921 pub fn init_tracing() {
1925 if TRACING_SET.load(Ordering::Relaxed) == false {
1926 set_global_default(Dispatch::new(PassingTracingSubscriber {}))
1927 .expect("We only ever call this once");
1928 TRACING_SET.store(true, Ordering::Relaxed);
1929 }
1930 }
1931}
1932
1933#[cfg(not(all(substrate_runtime, feature = "with-tracing")))]
1934mod tracing_setup {
1935 pub fn init_tracing() {}
1938}
1939
1940pub use tracing_setup::init_tracing;
1941
1942pub fn unreachable() -> ! {
1947 #[cfg(target_family = "wasm")]
1948 {
1949 core::arch::wasm32::unreachable();
1950 }
1951
1952 #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
1953 unsafe {
1954 core::arch::asm!("unimp", options(noreturn));
1955 }
1956
1957 #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64", target_family = "wasm")))]
1958 unreachable!();
1959}
1960
1961#[cfg(all(not(feature = "disable_panic_handler"), substrate_runtime))]
1963#[panic_handler]
1964pub fn panic(info: &core::panic::PanicInfo) -> ! {
1965 let message = alloc::format!("{}", info);
1966 #[cfg(feature = "improved_panic_error_reporting")]
1967 {
1968 panic_handler::abort_on_panic(&message);
1969 }
1970 #[cfg(not(feature = "improved_panic_error_reporting"))]
1971 {
1972 logging::log(RuntimeInterfaceLogLevel::Error, "runtime", message.as_bytes());
1973 unreachable();
1974 }
1975}
1976
1977#[cfg(all(not(feature = "disable_oom"), enable_alloc_error_handler))]
1979#[alloc_error_handler]
1980pub fn oom(_: core::alloc::Layout) -> ! {
1981 #[cfg(feature = "improved_panic_error_reporting")]
1982 {
1983 panic_handler::abort_on_panic("Runtime memory exhausted.");
1984 }
1985 #[cfg(not(feature = "improved_panic_error_reporting"))]
1986 {
1987 logging::log(
1988 RuntimeInterfaceLogLevel::Error,
1989 "runtime",
1990 b"Runtime memory exhausted. Aborting",
1991 );
1992 unreachable();
1993 }
1994}
1995
1996#[cfg(feature = "std")] pub type TestExternalities = sp_state_machine::TestExternalities<sp_core::Blake2Hasher>;
1999
2000#[docify::export]
2004#[cfg(not(substrate_runtime))]
2005pub type SubstrateHostFunctions = (
2006 storage::HostFunctions,
2007 default_child_storage::HostFunctions,
2008 misc::HostFunctions,
2009 wasm_tracing::HostFunctions,
2010 offchain::HostFunctions,
2011 crypto::HostFunctions,
2012 hashing::HostFunctions,
2013 allocator::HostFunctions,
2014 panic_handler::HostFunctions,
2015 logging::HostFunctions,
2016 trie::HostFunctions,
2017 offchain_index::HostFunctions,
2018 transaction_index::HostFunctions,
2019);
2020
2021#[cfg(test)]
2022mod tests {
2023 use super::*;
2024 use sp_core::{crypto::UncheckedInto, map, storage::Storage};
2025 use sp_state_machine::BasicExternalities;
2026
2027 #[test]
2028 fn storage_works() {
2029 let mut t = BasicExternalities::default();
2030 t.execute_with(|| {
2031 assert_eq!(storage::get(b"hello"), None);
2032 storage::set(b"hello", b"world");
2033 assert_eq!(storage::get(b"hello"), Some(b"world".to_vec().into()));
2034 assert_eq!(storage::get(b"foo"), None);
2035 storage::set(b"foo", &[1, 2, 3][..]);
2036 });
2037
2038 t = BasicExternalities::new(Storage {
2039 top: map![b"foo".to_vec() => b"bar".to_vec()],
2040 children_default: map![],
2041 });
2042
2043 t.execute_with(|| {
2044 assert_eq!(storage::get(b"hello"), None);
2045 assert_eq!(storage::get(b"foo"), Some(b"bar".to_vec().into()));
2046 });
2047
2048 let value = vec![7u8; 35];
2049 let storage =
2050 Storage { top: map![b"foo00".to_vec() => value.clone()], children_default: map![] };
2051 t = BasicExternalities::new(storage);
2052
2053 t.execute_with(|| {
2054 assert_eq!(storage::get(b"hello"), None);
2055 assert_eq!(storage::get(b"foo00"), Some(value.clone().into()));
2056 });
2057 }
2058
2059 #[test]
2060 fn read_storage_works() {
2061 let value = b"\x0b\0\0\0Hello world".to_vec();
2062 let mut t = BasicExternalities::new(Storage {
2063 top: map![b":test".to_vec() => value.clone()],
2064 children_default: map![],
2065 });
2066
2067 t.execute_with(|| {
2068 let mut v = [0u8; 4];
2069 assert_eq!(storage::read(b":test", &mut v[..], 0).unwrap(), value.len() as u32);
2070 assert_eq!(v, [11u8, 0, 0, 0]);
2071 let mut w = [0u8; 11];
2072 assert_eq!(storage::read(b":test", &mut w[..], 4).unwrap(), value.len() as u32 - 4);
2073 assert_eq!(&w, b"Hello world");
2074 });
2075 }
2076
2077 #[test]
2078 fn clear_prefix_works() {
2079 let mut t = BasicExternalities::new(Storage {
2080 top: map![
2081 b":a".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
2082 b":abcd".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
2083 b":abc".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
2084 b":abdd".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
2085 ],
2086 children_default: map![],
2087 });
2088
2089 t.execute_with(|| {
2090 assert!(matches!(
2096 storage::clear_prefix(b":abc", None),
2097 KillStorageResult::AllRemoved(2),
2098 ));
2099
2100 assert!(storage::get(b":a").is_some());
2101 assert!(storage::get(b":abdd").is_some());
2102 assert!(storage::get(b":abcd").is_none());
2103 assert!(storage::get(b":abc").is_none());
2104
2105 assert!(matches!(
2111 storage::clear_prefix(b":abc", None),
2112 KillStorageResult::AllRemoved(0),
2113 ));
2114 });
2115 }
2116
2117 fn zero_ed_pub() -> ed25519::Public {
2118 [0u8; 32].unchecked_into()
2119 }
2120
2121 fn zero_ed_sig() -> ed25519::Signature {
2122 ed25519::Signature::from_raw([0u8; 64])
2123 }
2124
2125 #[test]
2126 fn use_dalek_ext_works() {
2127 let mut ext = BasicExternalities::default();
2128 ext.register_extension(UseDalekExt);
2129
2130 ext.execute_with(|| {
2132 assert!(!crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
2133 });
2134
2135 BasicExternalities::default().execute_with(|| {
2137 assert!(crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
2138 })
2139 }
2140
2141 #[test]
2142 fn dalek_should_not_panic_on_invalid_signature() {
2143 let mut ext = BasicExternalities::default();
2144 ext.register_extension(UseDalekExt);
2145
2146 ext.execute_with(|| {
2147 let mut bytes = [0u8; 64];
2148 bytes[63] = 0b1110_0000;
2150
2151 assert!(!crypto::ed25519_verify(
2152 &ed25519::Signature::from_raw(bytes),
2153 &Vec::new(),
2154 &zero_ed_pub()
2155 ));
2156 });
2157 }
2158
2159 #[test]
2160 fn secp256k1_ecdsa_recover_valid_signature() {
2161 let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2162 let msg = sp_crypto_hashing::blake2_256(b"test message");
2163 let sig = pair.sign_prehashed(&msg);
2164
2165 assert!(ecdsa::is_signature_normalized(&sig.0));
2166
2167 let result = crypto::secp256k1_ecdsa_recover(&sig.0, &msg);
2168 assert!(result.is_ok());
2169 let recovered = ecdsa::Public::from_full(&result.ok().unwrap()).unwrap();
2170 assert_eq!(recovered, pair.public());
2171 }
2172
2173 #[test]
2174 fn secp256k1_ecdsa_recover_compressed_valid_signature() {
2175 let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2176 let msg = sp_crypto_hashing::blake2_256(b"test message");
2177 let sig = pair.sign_prehashed(&msg);
2178
2179 let result = crypto::secp256k1_ecdsa_recover_compressed(&sig.0, &msg);
2180 assert!(result.is_ok());
2181 assert_eq!(&result.ok().unwrap()[..], &pair.public().0[..]);
2182 }
2183
2184 #[test]
2185 fn ecdsa_verify_valid_signature() {
2186 let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2187 let message = b"test message";
2188 let sig = pair.sign(message);
2189
2190 assert!(ecdsa::is_signature_normalized(&sig.0));
2191 assert!(crypto::ecdsa_verify(&sig, message, &pair.public()));
2192 }
2193
2194 #[test]
2195 fn ecdsa_verify_prehashed_valid_signature() {
2196 let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2197 let msg = sp_crypto_hashing::blake2_256(b"test message");
2198 let sig = pair.sign_prehashed(&msg);
2199
2200 assert!(crypto::ecdsa_verify_prehashed(&sig, &msg, &pair.public()));
2201 }
2202
2203 #[test]
2204 fn ecdsa_verify_accepts_high_s_signatures() {
2205 fn make_high_s(sig: &ecdsa::Signature) -> ecdsa::Signature {
2206 let order: [u8; 32] = [
2207 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2208 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c,
2209 0xd0, 0x36, 0x41, 0x41,
2210 ];
2211 let s: [u8; 32] = sig.0[32..64].try_into().expect("slice has fixed length");
2212 let mut high_s = [0u8; 32];
2213 let mut borrow = 0i16;
2214 for i in (0..32).rev() {
2215 let diff = order[i] as i16 - s[i] as i16 - borrow;
2216 if diff < 0 {
2217 high_s[i] = (diff + 256) as u8;
2218 borrow = 1;
2219 } else {
2220 high_s[i] = diff as u8;
2221 borrow = 0;
2222 }
2223 }
2224
2225 let mut result = sig.0;
2226 result[32..64].copy_from_slice(&high_s);
2227 result[64] ^= 1;
2228 ecdsa::Signature::from_raw(result)
2229 }
2230
2231 let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2232 let message = b"test message";
2233 let signature = make_high_s(&pair.sign(message));
2234 assert!(!ecdsa::is_signature_normalized(&signature.0));
2235 assert!(crypto::ecdsa_verify(&signature, message, &pair.public()));
2236
2237 let prehash = sp_crypto_hashing::blake2_256(message);
2238 let signature = make_high_s(&pair.sign_prehashed(&prehash));
2239 assert!(!ecdsa::is_signature_normalized(&signature.0));
2240 assert!(crypto::ecdsa_verify_prehashed(&signature, &prehash, &pair.public()));
2241 }
2242
2243 #[test]
2244 fn storage_root_uses_passed_version() {
2245 let value = vec![42u8; 64];
2249 let mut ext =
2250 TestExternalities::new_with_state_version(Storage::default(), StateVersion::V1);
2251
2252 ext.execute_with(|| {
2253 storage::set(b"key", &value);
2254
2255 let top = vec![(b":code".to_vec(), Vec::new()), (b"key".to_vec(), value.clone())];
2257 assert_eq!(
2258 storage::root(StateVersion::V0),
2259 LayoutV0::<sp_core::Blake2Hasher>::trie_root(top.clone()).as_ref().to_vec()
2260 );
2261 assert_eq!(
2262 storage::root(StateVersion::V1),
2263 LayoutV1::<sp_core::Blake2Hasher>::trie_root(top).as_ref().to_vec()
2264 );
2265
2266 default_child_storage::set(b"child", b"ck", &value);
2267 let child = vec![(b"ck".to_vec(), value.clone())];
2268 assert_eq!(
2269 default_child_storage::root(b"child", StateVersion::V0),
2270 LayoutV0::<sp_core::Blake2Hasher>::trie_root(child.clone()).as_ref().to_vec()
2271 );
2272 assert_eq!(
2273 default_child_storage::root(b"child", StateVersion::V1),
2274 LayoutV1::<sp_core::Blake2Hasher>::trie_root(child).as_ref().to_vec()
2275 );
2276 });
2277 }
2278}