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
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "bench", feature(test))]
#[cfg(feature = "bench")]
extern crate test;
#[doc(hidden)]
pub use codec;
#[doc(hidden)]
pub use scale_info;
#[cfg(feature = "std")]
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
pub use sp_std;
#[doc(hidden)]
pub use paste;
#[doc(hidden)]
pub use sp_application_crypto as app_crypto;
#[cfg(feature = "std")]
pub use sp_core::storage::{Storage, StorageChild};
use sp_core::{
crypto::{self, Public},
ecdsa, ed25519,
hash::{H256, H512},
sr25519,
};
use sp_std::{convert::TryFrom, prelude::*};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
pub mod curve;
pub mod generic;
mod multiaddress;
pub mod offchain;
pub mod runtime_logger;
mod runtime_string;
#[cfg(feature = "std")]
pub mod testing;
pub mod traits;
pub mod transaction_validity;
pub use crate::runtime_string::*;
pub use multiaddress::MultiAddress;
pub use generic::{Digest, DigestItem};
pub use sp_application_crypto::{BoundToRuntimeAppPublic, RuntimeAppPublic};
pub use sp_core::{
crypto::{key_types, AccountId32, CryptoType, CryptoTypeId, KeyTypeId},
TypeId,
};
pub use sp_core::RuntimeDebug;
pub use sp_arithmetic::biguint;
pub use sp_arithmetic::helpers_128bit;
pub use sp_arithmetic::{
traits::SaturatedConversion, FixedI128, FixedI64, FixedPointNumber, FixedPointOperand,
FixedU128, InnerOf, PerThing, PerU16, Perbill, Percent, Permill, Perquintill, Rational128,
UpperOf,
};
pub use either::Either;
pub type Justification = (ConsensusEngineId, EncodedJustification);
pub type EncodedJustification = Vec<u8>;
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
pub struct Justifications(Vec<Justification>);
impl Justifications {
pub fn iter(&self) -> impl Iterator<Item = &Justification> {
self.0.iter()
}
pub fn append(&mut self, justification: Justification) -> bool {
if self.get(justification.0).is_some() {
return false
}
self.0.push(justification);
true
}
pub fn get(&self, engine_id: ConsensusEngineId) -> Option<&EncodedJustification> {
self.iter().find(|j| j.0 == engine_id).map(|j| &j.1)
}
pub fn into_justification(self, engine_id: ConsensusEngineId) -> Option<EncodedJustification> {
self.into_iter().find(|j| j.0 == engine_id).map(|j| j.1)
}
}
impl IntoIterator for Justifications {
type Item = Justification;
type IntoIter = sp_std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl From<Justification> for Justifications {
fn from(justification: Justification) -> Self {
Self(vec![justification])
}
}
use traits::{Lazy, Verify};
use crate::traits::IdentifyAccount;
#[cfg(feature = "std")]
pub use serde::{de::DeserializeOwned, Deserialize, Serialize};
#[cfg(feature = "std")]
pub trait BuildStorage {
fn build_storage(&self) -> Result<sp_core::storage::Storage, String> {
let mut storage = Default::default();
self.assimilate_storage(&mut storage)?;
Ok(storage)
}
fn assimilate_storage(&self, storage: &mut sp_core::storage::Storage) -> Result<(), String>;
}
#[cfg(feature = "std")]
pub trait BuildModuleGenesisStorage<T, I>: Sized {
fn build_module_genesis_storage(
&self,
storage: &mut sp_core::storage::Storage,
) -> Result<(), String>;
}
#[cfg(feature = "std")]
impl BuildStorage for sp_core::storage::Storage {
fn assimilate_storage(&self, storage: &mut sp_core::storage::Storage) -> Result<(), String> {
storage.top.extend(self.top.iter().map(|(k, v)| (k.clone(), v.clone())));
for (k, other_map) in self.children_default.iter() {
let k = k.clone();
if let Some(map) = storage.children_default.get_mut(&k) {
map.data.extend(other_map.data.iter().map(|(k, v)| (k.clone(), v.clone())));
if !map.child_info.try_update(&other_map.child_info) {
return Err("Incompatible child info update".to_string())
}
} else {
storage.children_default.insert(k, other_map.clone());
}
}
Ok(())
}
}
#[cfg(feature = "std")]
impl BuildStorage for () {
fn assimilate_storage(&self, _: &mut sp_core::storage::Storage) -> Result<(), String> {
Err("`assimilate_storage` not implemented for `()`".into())
}
}
pub type ConsensusEngineId = [u8; 4];
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Eq, PartialEq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub enum MultiSignature {
Ed25519(ed25519::Signature),
Sr25519(sr25519::Signature),
Ecdsa(ecdsa::Signature),
}
impl From<ed25519::Signature> for MultiSignature {
fn from(x: ed25519::Signature) -> Self {
Self::Ed25519(x)
}
}
impl TryFrom<MultiSignature> for ed25519::Signature {
type Error = ();
fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
if let MultiSignature::Ed25519(x) = m {
Ok(x)
} else {
Err(())
}
}
}
impl From<sr25519::Signature> for MultiSignature {
fn from(x: sr25519::Signature) -> Self {
Self::Sr25519(x)
}
}
impl TryFrom<MultiSignature> for sr25519::Signature {
type Error = ();
fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
if let MultiSignature::Sr25519(x) = m {
Ok(x)
} else {
Err(())
}
}
}
impl From<ecdsa::Signature> for MultiSignature {
fn from(x: ecdsa::Signature) -> Self {
Self::Ecdsa(x)
}
}
impl TryFrom<MultiSignature> for ecdsa::Signature {
type Error = ();
fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
if let MultiSignature::Ecdsa(x) = m {
Ok(x)
} else {
Err(())
}
}
}
impl Default for MultiSignature {
fn default() -> Self {
Self::Ed25519(Default::default())
}
}
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum MultiSigner {
Ed25519(ed25519::Public),
Sr25519(sr25519::Public),
Ecdsa(ecdsa::Public),
}
impl Default for MultiSigner {
fn default() -> Self {
Self::Ed25519(Default::default())
}
}
impl<T: Into<H256>> crypto::UncheckedFrom<T> for MultiSigner {
fn unchecked_from(x: T) -> Self {
ed25519::Public::unchecked_from(x.into()).into()
}
}
impl AsRef<[u8]> for MultiSigner {
fn as_ref(&self) -> &[u8] {
match *self {
Self::Ed25519(ref who) => who.as_ref(),
Self::Sr25519(ref who) => who.as_ref(),
Self::Ecdsa(ref who) => who.as_ref(),
}
}
}
impl traits::IdentifyAccount for MultiSigner {
type AccountId = AccountId32;
fn into_account(self) -> AccountId32 {
match self {
Self::Ed25519(who) => <[u8; 32]>::from(who).into(),
Self::Sr25519(who) => <[u8; 32]>::from(who).into(),
Self::Ecdsa(who) => sp_io::hashing::blake2_256(who.as_ref()).into(),
}
}
}
impl From<ed25519::Public> for MultiSigner {
fn from(x: ed25519::Public) -> Self {
Self::Ed25519(x)
}
}
impl TryFrom<MultiSigner> for ed25519::Public {
type Error = ();
fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
if let MultiSigner::Ed25519(x) = m {
Ok(x)
} else {
Err(())
}
}
}
impl From<sr25519::Public> for MultiSigner {
fn from(x: sr25519::Public) -> Self {
Self::Sr25519(x)
}
}
impl TryFrom<MultiSigner> for sr25519::Public {
type Error = ();
fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
if let MultiSigner::Sr25519(x) = m {
Ok(x)
} else {
Err(())
}
}
}
impl From<ecdsa::Public> for MultiSigner {
fn from(x: ecdsa::Public) -> Self {
Self::Ecdsa(x)
}
}
impl TryFrom<MultiSigner> for ecdsa::Public {
type Error = ();
fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
if let MultiSigner::Ecdsa(x) = m {
Ok(x)
} else {
Err(())
}
}
}
#[cfg(feature = "std")]
impl std::fmt::Display for MultiSigner {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
Self::Ed25519(ref who) => write!(fmt, "ed25519: {}", who),
Self::Sr25519(ref who) => write!(fmt, "sr25519: {}", who),
Self::Ecdsa(ref who) => write!(fmt, "ecdsa: {}", who),
}
}
}
impl Verify for MultiSignature {
type Signer = MultiSigner;
fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &AccountId32) -> bool {
match (self, signer) {
(Self::Ed25519(ref sig), who) =>
sig.verify(msg, &ed25519::Public::from_slice(who.as_ref())),
(Self::Sr25519(ref sig), who) =>
sig.verify(msg, &sr25519::Public::from_slice(who.as_ref())),
(Self::Ecdsa(ref sig), who) => {
let m = sp_io::hashing::blake2_256(msg.get());
match sp_io::crypto::secp256k1_ecdsa_recover_compressed(sig.as_ref(), &m) {
Ok(pubkey) =>
&sp_io::hashing::blake2_256(pubkey.as_ref()) ==
<dyn AsRef<[u8; 32]>>::as_ref(who),
_ => false,
}
},
}
}
}
#[derive(Eq, PartialEq, Clone, Default, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct AnySignature(H512);
impl Verify for AnySignature {
type Signer = sr25519::Public;
fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sr25519::Public) -> bool {
let msg = msg.get();
sr25519::Signature::try_from(self.0.as_fixed_bytes().as_ref())
.map(|s| s.verify(msg, signer))
.unwrap_or(false) ||
ed25519::Signature::try_from(self.0.as_fixed_bytes().as_ref())
.map(|s| s.verify(msg, &ed25519::Public::from_slice(signer.as_ref())))
.unwrap_or(false)
}
}
impl From<sr25519::Signature> for AnySignature {
fn from(s: sr25519::Signature) -> Self {
Self(s.into())
}
}
impl From<ed25519::Signature> for AnySignature {
fn from(s: ed25519::Signature) -> Self {
Self(s.into())
}
}
impl From<DispatchError> for DispatchOutcome {
fn from(err: DispatchError) -> Self {
Err(err)
}
}
pub type DispatchResult = sp_std::result::Result<(), DispatchError>;
pub type DispatchResultWithInfo<T> = sp_std::result::Result<T, DispatchErrorWithPostInfo<T>>;
#[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum DispatchError {
Other(
#[codec(skip)]
#[cfg_attr(feature = "std", serde(skip_deserializing))]
&'static str,
),
CannotLookup,
BadOrigin,
Module {
index: u8,
error: u8,
#[codec(skip)]
#[cfg_attr(feature = "std", serde(skip_deserializing))]
message: Option<&'static str>,
},
ConsumerRemaining,
NoProviders,
Token(TokenError),
Arithmetic(ArithmeticError),
}
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, RuntimeDebug)]
pub struct DispatchErrorWithPostInfo<Info>
where
Info: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable,
{
pub post_info: Info,
pub error: DispatchError,
}
impl DispatchError {
pub fn stripped(self) -> Self {
match self {
DispatchError::Module { index, error, message: Some(_) } =>
DispatchError::Module { index, error, message: None },
m => m,
}
}
}
impl<T, E> From<E> for DispatchErrorWithPostInfo<T>
where
T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable + Default,
E: Into<DispatchError>,
{
fn from(error: E) -> Self {
Self { post_info: Default::default(), error: error.into() }
}
}
impl From<crate::traits::LookupError> for DispatchError {
fn from(_: crate::traits::LookupError) -> Self {
Self::CannotLookup
}
}
impl From<crate::traits::BadOrigin> for DispatchError {
fn from(_: crate::traits::BadOrigin) -> Self {
Self::BadOrigin
}
}
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum TokenError {
NoFunds,
WouldDie,
BelowMinimum,
CannotCreate,
UnknownAsset,
Frozen,
Unsupported,
}
impl From<TokenError> for &'static str {
fn from(e: TokenError) -> &'static str {
match e {
TokenError::NoFunds => "Funds are unavailable",
TokenError::WouldDie => "Account that must exist would die",
TokenError::BelowMinimum => "Account cannot exist with the funds that would be given",
TokenError::CannotCreate => "Account cannot be created",
TokenError::UnknownAsset => "The asset in question is unknown",
TokenError::Frozen => "Funds exist but are frozen",
TokenError::Unsupported => "Operation is not supported by the asset",
}
}
}
impl From<TokenError> for DispatchError {
fn from(e: TokenError) -> DispatchError {
Self::Token(e)
}
}
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum ArithmeticError {
Underflow,
Overflow,
DivisionByZero,
}
impl From<ArithmeticError> for &'static str {
fn from(e: ArithmeticError) -> &'static str {
match e {
ArithmeticError::Underflow => "An underflow would occur",
ArithmeticError::Overflow => "An overflow would occur",
ArithmeticError::DivisionByZero => "Division by zero",
}
}
}
impl From<ArithmeticError> for DispatchError {
fn from(e: ArithmeticError) -> DispatchError {
Self::Arithmetic(e)
}
}
impl From<&'static str> for DispatchError {
fn from(err: &'static str) -> DispatchError {
Self::Other(err)
}
}
impl From<DispatchError> for &'static str {
fn from(err: DispatchError) -> &'static str {
match err {
DispatchError::Other(msg) => msg,
DispatchError::CannotLookup => "Cannot lookup",
DispatchError::BadOrigin => "Bad origin",
DispatchError::Module { message, .. } => message.unwrap_or("Unknown module error"),
DispatchError::ConsumerRemaining => "Consumer remaining",
DispatchError::NoProviders => "No providers",
DispatchError::Token(e) => e.into(),
DispatchError::Arithmetic(e) => e.into(),
}
}
}
impl<T> From<DispatchErrorWithPostInfo<T>> for &'static str
where
T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable,
{
fn from(err: DispatchErrorWithPostInfo<T>) -> &'static str {
err.error.into()
}
}
impl traits::Printable for DispatchError {
fn print(&self) {
"DispatchError".print();
match self {
Self::Other(err) => err.print(),
Self::CannotLookup => "Cannot lookup".print(),
Self::BadOrigin => "Bad origin".print(),
Self::Module { index, error, message } => {
index.print();
error.print();
if let Some(msg) = message {
msg.print();
}
},
Self::ConsumerRemaining => "Consumer remaining".print(),
Self::NoProviders => "No providers".print(),
Self::Token(e) => {
"Token error: ".print();
<&'static str>::from(*e).print();
},
Self::Arithmetic(e) => {
"Arithmetic error: ".print();
<&'static str>::from(*e).print();
},
}
}
}
impl<T> traits::Printable for DispatchErrorWithPostInfo<T>
where
T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable,
{
fn print(&self) {
self.error.print();
"PostInfo: ".print();
self.post_info.print();
}
}
impl PartialEq for DispatchError {
fn eq(&self, other: &Self) -> bool {
use DispatchError::*;
match (self, other) {
(CannotLookup, CannotLookup) |
(BadOrigin, BadOrigin) |
(ConsumerRemaining, ConsumerRemaining) |
(NoProviders, NoProviders) => true,
(Token(l), Token(r)) => l == r,
(Other(l), Other(r)) => l == r,
(Arithmetic(l), Arithmetic(r)) => l == r,
(
Module { index: index_l, error: error_l, .. },
Module { index: index_r, error: error_r, .. },
) => (index_l == index_r) && (error_l == error_r),
_ => false,
}
}
}
pub type DispatchOutcome = Result<(), DispatchError>;
pub type ApplyExtrinsicResult =
Result<DispatchOutcome, transaction_validity::TransactionValidityError>;
pub type ApplyExtrinsicResultWithInfo<T> =
Result<DispatchResultWithInfo<T>, transaction_validity::TransactionValidityError>;
pub fn verify_encoded_lazy<V: Verify, T: codec::Encode>(
sig: &V,
item: &T,
signer: &<V::Signer as IdentifyAccount>::AccountId,
) -> bool {
struct LazyEncode<F> {
inner: F,
encoded: Option<Vec<u8>>,
}
impl<F: Fn() -> Vec<u8>> traits::Lazy<[u8]> for LazyEncode<F> {
fn get(&mut self) -> &[u8] {
self.encoded.get_or_insert_with(&self.inner).as_slice()
}
}
sig.verify(LazyEncode { inner: || item.encode(), encoded: None }, signer)
}
#[macro_export]
#[cfg(feature = "std")]
macro_rules! assert_eq_error_rate {
($x:expr, $y:expr, $error:expr $(,)?) => {
assert!(
($x) >= (($y) - ($error)) && ($x) <= (($y) + ($error)),
"{:?} != {:?} (with error rate {:?})",
$x,
$y,
$error,
);
};
}
#[derive(PartialEq, Eq, Clone, Default, Encode, Decode)]
pub struct OpaqueExtrinsic(Vec<u8>);
impl OpaqueExtrinsic {
pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, codec::Error> {
Self::decode(&mut bytes)
}
}
#[cfg(feature = "std")]
impl parity_util_mem::MallocSizeOf for OpaqueExtrinsic {
fn size_of(&self, ops: &mut parity_util_mem::MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
impl sp_std::fmt::Debug for OpaqueExtrinsic {
#[cfg(feature = "std")]
fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
write!(fmt, "{}", sp_core::hexdisplay::HexDisplay::from(&self.0))
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
Ok(())
}
}
#[cfg(feature = "std")]
impl ::serde::Serialize for OpaqueExtrinsic {
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
codec::Encode::using_encoded(&self.0, |bytes| ::sp_core::bytes::serialize(bytes, seq))
}
}
#[cfg(feature = "std")]
impl<'a> ::serde::Deserialize<'a> for OpaqueExtrinsic {
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'a>,
{
let r = ::sp_core::bytes::deserialize(de)?;
Decode::decode(&mut &r[..])
.map_err(|e| ::serde::de::Error::custom(format!("Decode error: {}", e)))
}
}
impl traits::Extrinsic for OpaqueExtrinsic {
type Call = ();
type SignaturePayload = ();
}
pub fn print(print: impl traits::Printable) {
print.print();
}
#[must_use = "`verify()` needs to be called to finish batch signature verification!"]
pub struct SignatureBatching(bool);
impl SignatureBatching {
pub fn start() -> Self {
sp_io::crypto::start_batch_verify();
SignatureBatching(false)
}
#[must_use]
pub fn verify(mut self) -> bool {
self.0 = true;
sp_io::crypto::finish_batch_verify()
}
}
impl Drop for SignatureBatching {
fn drop(&mut self) {
if !self.0 && !sp_std::thread::panicking() {
panic!("Signature verification has not been called before `SignatureBatching::drop`")
}
}
}
pub enum TransactionOutcome<R> {
Commit(R),
Rollback(R),
}
impl<R> TransactionOutcome<R> {
pub fn into_inner(self) -> R {
match self {
Self::Commit(r) => r,
Self::Rollback(r) => r,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use codec::{Decode, Encode};
use sp_core::crypto::Pair;
#[test]
fn opaque_extrinsic_serialization() {
let ex = super::OpaqueExtrinsic(vec![1, 2, 3, 4]);
assert_eq!(serde_json::to_string(&ex).unwrap(), "\"0x1001020304\"".to_owned());
}
#[test]
fn dispatch_error_encoding() {
let error = DispatchError::Module { index: 1, error: 2, message: Some("error message") };
let encoded = error.encode();
let decoded = DispatchError::decode(&mut &encoded[..]).unwrap();
assert_eq!(encoded, vec![3, 1, 2]);
assert_eq!(decoded, DispatchError::Module { index: 1, error: 2, message: None });
}
#[test]
fn dispatch_error_equality() {
use DispatchError::*;
let variants = vec![
Other("foo"),
Other("bar"),
CannotLookup,
BadOrigin,
Module { index: 1, error: 1, message: None },
Module { index: 1, error: 2, message: None },
Module { index: 2, error: 1, message: None },
ConsumerRemaining,
NoProviders,
Token(TokenError::NoFunds),
Token(TokenError::WouldDie),
Token(TokenError::BelowMinimum),
Token(TokenError::CannotCreate),
Token(TokenError::UnknownAsset),
Token(TokenError::Frozen),
Arithmetic(ArithmeticError::Overflow),
Arithmetic(ArithmeticError::Underflow),
Arithmetic(ArithmeticError::DivisionByZero),
];
for (i, variant) in variants.iter().enumerate() {
for (j, other_variant) in variants.iter().enumerate() {
if i == j {
assert_eq!(variant, other_variant);
} else {
assert_ne!(variant, other_variant);
}
}
}
assert_eq!(
Module { index: 1, error: 1, message: Some("foo") },
Module { index: 1, error: 1, message: None },
);
}
#[test]
fn multi_signature_ecdsa_verify_works() {
let msg = &b"test-message"[..];
let (pair, _) = ecdsa::Pair::generate();
let signature = pair.sign(&msg);
assert!(ecdsa::Pair::verify(&signature, msg, &pair.public()));
let multi_sig = MultiSignature::from(signature);
let multi_signer = MultiSigner::from(pair.public());
assert!(multi_sig.verify(msg, &multi_signer.into_account()));
let multi_signer = MultiSigner::from(pair.public());
assert!(multi_sig.verify(msg, &multi_signer.into_account()));
}
#[test]
#[should_panic(expected = "Signature verification has not been called")]
fn batching_still_finishes_when_not_called_directly() {
let mut ext = sp_state_machine::BasicExternalities::default();
ext.register_extension(sp_core::traits::TaskExecutorExt::new(
sp_core::testing::TaskExecutor::new(),
));
ext.execute_with(|| {
let _batching = SignatureBatching::start();
sp_io::crypto::sr25519_verify(&Default::default(), &Vec::new(), &Default::default());
});
}
#[test]
#[should_panic(expected = "Hey, I'm an error")]
fn batching_does_not_panic_while_thread_is_already_panicking() {
let mut ext = sp_state_machine::BasicExternalities::default();
ext.register_extension(sp_core::traits::TaskExecutorExt::new(
sp_core::testing::TaskExecutor::new(),
));
ext.execute_with(|| {
let _batching = SignatureBatching::start();
panic!("Hey, I'm an error");
});
}
}