-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlib.rs
More file actions
1566 lines (1379 loc) · 58 KB
/
lib.rs
File metadata and controls
1566 lines (1379 loc) · 58 KB
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
//! The substrate runtime for the Humanode network.
#![recursion_limit = "256"]
// TODO(#66): switch back to warn
#![allow(missing_docs, clippy::missing_docs_in_private_items)]
// Either generate code at stadard mode, or `no_std`, based on the `std` feature presence.
#![cfg_attr(not(feature = "std"), no_std)]
// If we're in standard compilation mode, embed the build-script generated code that pulls in
// the WASM portion of the runtime, so that it is invocable from the native (aka host) side code.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
// A few exports that help ease life for downstream crates.
use codec::{alloc::string::ToString, Decode, Encode, MaxEncodedLen};
use fp_rpc::TransactionStatus;
use frame_support::traits::LockIdentifier;
pub use frame_support::{
construct_runtime, parameter_types,
traits::{
ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, FindAuthor, Get,
KeyOwnerProofSystem, Randomness,
},
weights::{
constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
},
Weight,
},
ConsensusEngineId, PalletId, StorageValue, WeakBoundedVec,
};
pub use frame_system::Call as SystemCall;
use keystore_bioauth_account_id::KeystoreBioauthAccountId;
pub use pallet_balances::Call as BalancesCall;
use pallet_bioauth::AuthTicket;
use pallet_ethereum::{
Call::transact, PostLogContent as EthereumPostLogContent, Transaction as EthereumTransaction,
};
use pallet_evm::FeeCalculator;
use pallet_evm::{Account as EVMAccount, Runner};
use pallet_grandpa::{
fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_session::historical as pallet_session_historical;
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_token_claims as token_claims;
use primitives_auth_ticket::OpaqueAuthTicket;
pub use primitives_ethereum::EthereumAddress;
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_api::impl_runtime_apis;
use sp_consensus_babe::AuthorityId as BabeId;
use sp_core::{
crypto::{AccountId32, KeyTypeId},
OpaqueMetadata, H160, H256, U256,
};
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{
AccountIdLookup, BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable,
IdentifyAccount, Identity, NumberFor, One, OpaqueKeys, PostDispatchInfoOf, StaticLookup,
Verify,
},
transaction_validity::{
TransactionPriority, TransactionSource, TransactionValidity, TransactionValidityError,
},
ApplyExtrinsicResult, MultiSignature,
};
pub use sp_runtime::{Perbill, Permill};
use sp_std::prelude::*;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
mod frontier_precompiles;
mod vesting;
use frontier_precompiles::FrontierPrecompiles;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
mod constants;
mod currency_swap;
#[cfg(test)]
mod dev_utils;
mod display_moment;
pub mod eth_sig;
mod find_author;
mod fixed_supply;
pub mod robonode;
#[cfg(test)]
mod tests;
mod weights;
pub mod utils;
pub use constants::{
babe::{BABE_GENESIS_EPOCH_CONFIG, EPOCH_DURATION_IN_SLOTS, MAX_AUTHORITIES, SLOT_DURATION},
bioauth::{AUTHENTICATIONS_EXPIRE_AFTER, MAX_AUTHENTICATIONS, MAX_NONCES},
block_time::MILLISECS_PER_BLOCK,
equivocation::REPORT_LONGEVITY,
im_online::{MAX_KEYS, MAX_PEER_DATA_ENCODING_SIZE, MAX_PEER_IN_HEARTBEATS},
};
/// An index to a block.
pub type BlockNumber = u32;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// Some way of identifying an account on the chain.
///
/// We do not define this type via signing scheme because we effectively need this type to be able
/// to hold the values that are beyond the standard signing facilities.
/// Overall, the [`AccountId`] type must be sufficient to hold the following kinds of addresses
/// (non-exhaustive list):
///
/// - all the standard [`Signature`] account identifiers:
/// - the Ed25519 public key
/// - the Sr25519 public key
/// - the Blake2 hash of the compressed ECDSA public key
/// - pot account addresses - they are still addresses but can't be a subject to signing because
/// they don't belong to an asymmetric keypair at all;
/// - multisig account address - this is an address type that is driven by the multisig pallet, and
/// also technically does not correspond to an asymmetric keypair;
/// - EVM addresses - the addresses used by EVM, of which we have to possible variants:
/// - EVM ECDSA addresses - these are the last 20 bytes of the Keccak (`keccak_256`) hash of
/// the uncompressed ECDSA public key, as used in Ethereum; this has nothing to do with
/// the [`sp_runtime::MultiSigner::Ecdsa`] - because that one is built differently, however
/// the underlying asymmetric keypair can be the same. The signatures won't match however,
/// because for the [`MultiSignature::Ecdsa`] variant, [`MultiSignature::verify`] computes
/// the message to verify the signature against in a different way to how Ethereum does it -
/// Substrate uses Blake2 and Ethereum uses Keccak;
/// - EVM code address - this in an address for an EVM smart contract, which can be any 20 bytes
/// really; it is usually constructed using the last 20 bytes of using the Keccak hash somehow
/// obtained from of the contract code, the address of whoever creates the contract and some
/// salt/nonce; note that there are currently multiple simultaneously supported algorithms for
/// how the contract addresses can be constructed by the EVM, and new might be introduced in
/// the future.
/// Both of the 20-byte EVM address types are stored with a certain format in a wider 32-byte
/// [`AccountId32`] type, that enables us to distinguish them from other address types; there's
/// a certain chance that a non-EVM address would just so happen to be matching the EVM address
/// encoding format we use for EVM accounts, which would mess things up.
///
/// We acknowledge that there is largely a limitation of the Substrate's core architecture that does
/// not permit for a more explicit value kind differentiation.
/// Although we can alter the [`AccountId`] to be a more explicit enum, and tweak
/// the [`frame_system::Config::Lookup`] the amount of work at the surrounding ecosystem
/// (i.e. Polkadot.js) is beyond the reasonable effort for us now.
pub type AccountId = AccountId32;
/// Evm account identifier.
pub type EvmAccountId = H160;
// Ensure that the `AccountId` it equivalent to the public key of our transaction signing scheme.
static_assertions::assert_type_eq_all!(
AccountId,
<<Signature as Verify>::Signer as IdentifyAccount>::AccountId
);
/// Consensus identity used to tie the consensus signatures to the bioauth identity
/// via session pallet's key ownership logic.
pub type BioauthConsensusId = BabeId;
/// The bioauth identity of a human.
pub type BioauthId = AccountId;
/// Balance of an account.
pub type Balance = u128;
/// Index of a transaction in the chain.
pub type Index = u32;
/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
use super::*;
/// Opaque block header type.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Opaque block type.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// Opaque block identifier type.
pub type BlockId = generic::BlockId<Block>;
impl_opaque_keys! {
pub struct SessionKeys {
pub babe: Babe,
pub grandpa: Grandpa,
pub im_online: ImOnline,
}
}
}
// https://docs.substrate.io/build/upgrade-the-runtime
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("humanode"),
impl_name: create_runtime_str!("humanode"),
authoring_version: 1,
// The version of the runtime specification. A full node will not attempt to use its native
// runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`,
// `spec_version`, and `authoring_version` are the same between Wasm and native.
// This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use
// the compatible custom types.
spec_version: 106,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 1,
};
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
}
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
const MAX_BLOCK_LENGTH: u32 = 5 * 1024 * 1024;
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
/// We allow for 2 seconds of compute with a 6 second average block time.
pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights
::with_sensible_defaults(Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX), NORMAL_DISPATCH_RATIO);
pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
::max_with_normal_ratio(MAX_BLOCK_LENGTH, NORMAL_DISPATCH_RATIO);
pub SS58Prefix: u16 = ChainProperties::ss58_prefix();
}
// Configure FRAME pallets to include in runtime.
impl frame_system::Config for Runtime {
/// The basic call filter to use in dispatchable.
type BaseCallFilter = frame_support::traits::Everything;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = BlockWeights;
/// The maximum length of a block (in bytes).
type BlockLength = BlockLength;
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// The index type for storing how many extrinsics an account has signed.
type Index = Index;
/// The index type for blocks.
type BlockNumber = BlockNumber;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = BlakeTwo256;
/// The header type.
type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = ConstU32<2400>;
/// The weight of database operations that the runtime can invoke.
type DbWeight = RocksDbWeight;
/// Version of the runtime.
type Version = Version;
/// Converts a module to the index of the module in `construct_runtime!`.
///
/// This type is being generated by `construct_runtime!`.
type PalletInfo = PalletInfo;
/// What to do if a new account is created.
type OnNewAccount = ();
/// What to do if an account is fully reaped from the system.
type OnKilledAccount = ();
/// The data to be stored in an account.
type AccountData = pallet_balances::AccountData<Balance>;
/// Weight information for the extrinsics of this pallet.
type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
/// The Humande prefix is defined at pallet-chain-properties. It allows us to set up
/// it easy in genesis before launching the chain without changing the code itself.
type SS58Prefix = SS58Prefix;
/// The set code logic, just the default since we're not a parachain.
type OnSetCode = ();
/// The maximum number of consumers allowed on a single account.
type MaxConsumers = ConstU32<16>;
}
impl pallet_babe::Config for Runtime {
type EpochDuration = ConstU64<EPOCH_DURATION_IN_SLOTS>;
type ExpectedBlockTime = ConstU64<MILLISECS_PER_BLOCK>;
type EpochChangeTrigger = pallet_babe::ExternalTrigger;
type DisabledValidators = Session;
type KeyOwnerProofSystem = Historical;
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, BabeId)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
BabeId,
)>>::IdentificationTuple;
type HandleEquivocation = pallet_babe::EquivocationHandler<
Self::KeyOwnerIdentification,
Offences,
ConstU64<REPORT_LONGEVITY>,
>;
type WeightInfo = (); // TODO(#578): babe weights are broken
type MaxAuthorities = ConstU32<MAX_AUTHORITIES>;
}
/// A link between the [`AccountId`] as in what we use to sign extrinsics in the system
/// to the [`BioauthId`] as in what we use to identify to the robonode and tie the biometrics to.
pub struct IdentityValidatorIdOf;
impl sp_runtime::traits::Convert<AccountId, Option<BioauthId>> for IdentityValidatorIdOf {
fn convert(account_id: AccountId) -> Option<BioauthId> {
Some(account_id)
}
}
impl pallet_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorId = BioauthId;
type ValidatorIdOf = IdentityValidatorIdOf;
type ShouldEndSession = Babe;
type NextSessionRotation = Babe;
type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, HumanodeSession>;
type SessionHandler = <opaque::SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = opaque::SessionKeys;
type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
}
impl pallet_session::historical::Config for Runtime {
type FullIdentification = pallet_humanode_session::IdentificationFor<Self>;
type FullIdentificationOf = pallet_humanode_session::CurrentSessionIdentificationOf<Self>;
}
impl pallet_grandpa::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type KeyOwnerProofSystem = Historical;
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
GrandpaId,
)>>::IdentificationTuple;
type HandleEquivocation = pallet_grandpa::EquivocationHandler<
Self::KeyOwnerIdentification,
Offences,
ConstU64<REPORT_LONGEVITY>,
>;
type WeightInfo = (); // TODO(#578): grandpa weights are broken
type MaxAuthorities = ConstU32<MAX_AUTHORITIES>;
type MaxSetIdSessionEntries = ConstU64<REPORT_LONGEVITY>;
}
/// A timestamp: milliseconds since the unix epoch.
pub type UnixMilliseconds = u64;
impl pallet_timestamp::Config for Runtime {
type Moment = UnixMilliseconds;
type OnTimestampSet = Babe;
type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
}
impl pallet_chain_start_moment::Config for Runtime {
type Time = Timestamp;
}
impl pallet_authorship::Config for Runtime {
type FindAuthor = find_author::FindAuthorFromSession<find_author::FindAuthorBabe, BabeId>;
type EventHandler = (ImOnline,);
}
parameter_types! {
pub const TreasuryPotPalletId: PalletId = PalletId(*b"hmnd/tr1");
pub const FeesPotPalletId: PalletId = PalletId(*b"hmnd/fe1");
pub const TokenClaimsPotPalletId: PalletId = PalletId(*b"hmnd/tc1");
pub const NativeToEvmSwapBridgePotPalletId: PalletId = PalletId(*b"hmcs/ne1");
pub const EvmToNativeSwapBridgePotPalletId: PalletId = PalletId(*b"hmcs/en1");
}
type PotInstanceTreasury = pallet_pot::Instance1;
type PotInstanceFees = pallet_pot::Instance2;
type PotInstanceTokenClaims = pallet_pot::Instance3;
type PotInstanceNativeToEvmSwapBridge = pallet_pot::Instance4;
type PotInstanceEvmToNativeSwapBridge = pallet_pot::Instance5;
impl pallet_pot::Config<PotInstanceTreasury> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountId = AccountId;
type PalletId = TreasuryPotPalletId;
type Currency = Balances;
}
impl pallet_pot::Config<PotInstanceFees> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountId = AccountId;
type PalletId = FeesPotPalletId;
type Currency = Balances;
}
impl pallet_pot::Config<PotInstanceTokenClaims> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountId = AccountId;
type PalletId = TokenClaimsPotPalletId;
type Currency = Balances;
}
impl pallet_pot::Config<PotInstanceNativeToEvmSwapBridge> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountId = AccountId;
type PalletId = NativeToEvmSwapBridgePotPalletId;
type Currency = Balances;
}
impl pallet_pot::Config<PotInstanceEvmToNativeSwapBridge> for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountId = EvmAccountId;
type PalletId = EvmToNativeSwapBridgePotPalletId;
type Currency = EvmBalances;
}
impl pallet_balances::Config for Runtime {
type MaxLocks = ConstU32<50>;
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = TreasuryPot;
type ExistentialDeposit = ConstU128<500>;
type AccountStore = System;
type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
}
parameter_types! {
pub FeeMultiplier: pallet_transaction_payment::Multiplier = pallet_transaction_payment::Multiplier::one();
}
impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, FeesPot>;
type OperationalFeeMultiplier = ConstU8<5>;
type WeightToFee = frame_support::weights::ConstantMultiplier<
Balance,
ConstU128<{ constants::fees::WEIGHT_TO_FEE }>,
>;
type LengthToFee = frame_support::weights::ConstantMultiplier<
Balance,
ConstU128<{ constants::fees::LENGTH_TO_FEE }>,
>;
type FeeMultiplierUpdate = pallet_transaction_payment::ConstFeeMultiplier<FeeMultiplier>;
}
impl pallet_sudo::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
}
pub struct PrimitiveAuthTicketConverter;
pub enum PrimitiveAuthTicketConverterError {
Ticket(codec::Error),
PublicKey(()),
}
impl pallet_bioauth::TryConvert<OpaqueAuthTicket, pallet_bioauth::AuthTicket<BioauthId>>
for PrimitiveAuthTicketConverter
{
type Error = PrimitiveAuthTicketConverterError;
fn try_convert(
value: OpaqueAuthTicket,
) -> Result<pallet_bioauth::AuthTicket<BioauthId>, Self::Error> {
#[allow(clippy::needless_borrow)]
let primitives_auth_ticket::AuthTicket {
public_key,
authentication_nonce: nonce,
} = (&value)
.try_into()
.map_err(PrimitiveAuthTicketConverterError::Ticket)?;
let public_key = public_key
.as_slice()
.try_into()
.map_err(PrimitiveAuthTicketConverterError::PublicKey)?;
Ok(AuthTicket { public_key, nonce })
}
}
pub struct CurrentMoment;
impl pallet_bioauth::CurrentMoment<UnixMilliseconds> for CurrentMoment {
fn now() -> UnixMilliseconds {
pallet_timestamp::Pallet::<Runtime>::now()
}
}
impl pallet_bioauth::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RobonodePublicKey = robonode::PublicKey;
type RobonodeSignature = Vec<u8>;
type ValidatorPublicKey = BioauthId;
type OpaqueAuthTicket = primitives_auth_ticket::OpaqueAuthTicket;
type AuthTicketCoverter = PrimitiveAuthTicketConverter;
type ValidatorSetUpdater = ();
type Moment = UnixMilliseconds;
type DisplayMoment = display_moment::DisplayMoment;
type CurrentMoment = CurrentMoment;
type AuthenticationsExpireAfter = ConstU64<AUTHENTICATIONS_EXPIRE_AFTER>;
type WeightInfo = weights::pallet_bioauth::WeightInfo<Runtime>;
type MaxAuthentications = ConstU32<MAX_AUTHENTICATIONS>;
type MaxNonces = ConstU32<MAX_NONCES>;
type BeforeAuthHook = ();
type AfterAuthHook = ();
}
#[cfg(feature = "runtime-benchmarks")]
impl pallet_bioauth::benchmarking::AuthTicketBuilder for Runtime {
fn build(
public_key: Vec<u8>,
authentication_nonce: Vec<u8>,
) -> <Self as pallet_bioauth::Config>::OpaqueAuthTicket {
OpaqueAuthTicket::from(&primitives_auth_ticket::AuthTicket {
public_key,
authentication_nonce,
})
}
}
impl pallet_bootnodes::Config for Runtime {
type BootnodeId = AccountId;
type MaxBootnodes = ConstU32<16>;
}
impl pallet_humanode_session::Config for Runtime {
type ValidatorPublicKeyOf = IdentityValidatorIdOf;
type BootnodeIdOf = sp_runtime::traits::Identity;
type MaxBootnodeValidators = <Runtime as pallet_bootnodes::Config>::MaxBootnodes;
type MaxBioauthValidators = <Runtime as pallet_bioauth::Config>::MaxAuthentications;
}
pub struct OffenceSlasher;
impl
sp_staking::offence::OnOffenceHandler<
AccountId,
pallet_im_online::IdentificationTuple<Runtime>,
Weight,
> for OffenceSlasher
{
fn on_offence(
offenders: &[sp_staking::offence::OffenceDetails<
AccountId,
pallet_im_online::IdentificationTuple<Runtime>,
>],
_slash_fraction: &[Perbill],
_session: sp_staking::SessionIndex,
disable_strategy: sp_staking::offence::DisableStrategy,
) -> Weight {
if disable_strategy == sp_staking::offence::DisableStrategy::Never {
return Weight::zero();
}
let mut weight: Weight = Weight::zero();
let weights = <Runtime as frame_system::Config>::DbWeight::get();
for details in offenders {
let (_offender, identity) = &details.offender;
match identity {
pallet_humanode_session::Identification::Bioauth(authentication) => {
let has_deauthenticated = Bioauth::deauthenticate(&authentication.public_key);
weight = weight
.saturating_add(weights.reads_writes(1, u64::from(has_deauthenticated)));
}
pallet_humanode_session::Identification::Bootnode(..) => {
// Never slash the bootnodes.
}
}
}
weight
}
}
impl pallet_im_online::Config for Runtime {
type AuthorityId = ImOnlineId;
type RuntimeEvent = RuntimeEvent;
type NextSessionRotation = Babe;
type ValidatorSet = Historical;
type ReportUnresponsiveness = Offences;
type UnsignedPriority = ConstU64<{ TransactionPriority::MAX }>;
type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
type MaxKeys = ConstU32<MAX_KEYS>;
type MaxPeerInHeartbeats = ConstU32<MAX_PEER_IN_HEARTBEATS>;
type MaxPeerDataEncodingSize = ConstU32<MAX_PEER_DATA_ENCODING_SIZE>;
}
impl pallet_offences::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
type OnOffenceHandler = OffenceSlasher;
}
const BLOCK_GAS_LIMIT: u64 = 75_000_000;
const WEIGHT_MILLISECS_PER_BLOCK: u64 = 2000;
parameter_types! {
pub BlockGasLimit: U256 = U256::from(BLOCK_GAS_LIMIT);
pub PrecompilesValue: FrontierPrecompiles<Runtime> = FrontierPrecompiles::<_>::default();
pub WeightPerGas: Weight = Weight::from_ref_time(fp_evm::weight_per_gas(BLOCK_GAS_LIMIT, NORMAL_DISPATCH_RATIO, WEIGHT_MILLISECS_PER_BLOCK));
}
impl pallet_evm_system::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountId = EvmAccountId;
type Index = Index;
type AccountData = pallet_evm_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
}
impl pallet_evm_balances::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountId = EvmAccountId;
type Balance = Balance;
type ExistentialDeposit = ConstU128<500>;
type AccountStore = EvmSystem;
type DustRemoval = currency_swap::TreasuryPotProxy;
}
impl pallet_currency_swap::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountIdTo = EvmAccountId;
type CurrencySwap = currency_swap::NativeToEvmOneToOne;
type WeightInfo = ();
}
impl pallet_evm::Config for Runtime {
type AccountProvider = EvmSystem;
type FeeCalculator = BaseFee;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
type CallOrigin = pallet_evm::EnsureAddressNever<EvmAccountId>;
type WithdrawOrigin = pallet_evm::EnsureAddressNever<EvmAccountId>;
type AddressMapping = pallet_evm::IdentityAddressMapping;
type Currency = EvmBalances;
type RuntimeEvent = RuntimeEvent;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type PrecompilesType = FrontierPrecompiles<Self>;
type PrecompilesValue = PrecompilesValue;
type ChainId = EthereumChainId;
type BlockGasLimit = BlockGasLimit;
type OnChargeTransaction =
fixed_supply::EvmTransactionCharger<EvmBalances, currency_swap::FeesPotProxy>;
type OnCreate = ();
type FindAuthor = find_author::FindAuthorTruncated<
find_author::FindAuthorFromSession<find_author::FindAuthorBabe, BabeId>,
>;
}
parameter_types! {
pub const PostBlockAndTxnHashes: EthereumPostLogContent = EthereumPostLogContent::BlockAndTxnHashes;
}
impl pallet_ethereum::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
type PostLogContent = PostBlockAndTxnHashes;
}
parameter_types! {
pub BoundDivision: U256 = U256::from(1024);
}
impl pallet_dynamic_fee::Config for Runtime {
type MinGasPriceBoundDivisor = BoundDivision;
}
parameter_types! {
pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000);
pub DefaultElasticity: Permill = Permill::from_parts(125_000);
}
pub struct BaseFeeThreshold;
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
fn lower() -> Permill {
Permill::zero()
}
fn ideal() -> Permill {
Permill::from_parts(500_000)
}
fn upper() -> Permill {
Permill::from_parts(1_000_000)
}
}
impl pallet_base_fee::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Threshold = BaseFeeThreshold;
type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
type DefaultElasticity = DefaultElasticity;
}
impl pallet_chain_properties::Config for Runtime {}
impl pallet_ethereum_chain_id::Config for Runtime {}
impl pallet_evm_accounts_mapping::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Verifier = eth_sig::AccountClaimVerifier;
type WeightInfo = weights::pallet_evm_accounts_mapping::WeightInfo<Runtime>;
}
parameter_types! {
pub TokenClaimsPotAccountId: AccountId = TokenClaimsPot::account_id();
}
impl pallet_token_claims::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type PotAccountId = TokenClaimsPotAccountId;
type VestingSchedule = <Self as pallet_vesting::Config>::Schedule;
type VestingInterface = vesting::TokenClaimsInterface;
type EthereumSignatureVerifier = eth_sig::TokenClaimVerifier;
type WeightInfo = weights::pallet_token_claims::WeightInfo<Runtime>;
}
parameter_types! {
pub VestingLockId: LockIdentifier = *b"hmnd/vs1";
}
impl pallet_vesting::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type LockId = VestingLockId;
type Schedule = vesting::Schedule;
type SchedulingDriver = vesting::SchedulingDriver;
type WeightInfo = weights::pallet_vesting::WeightInfo<Runtime>;
}
impl pallet_multisig::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type DepositBase = ConstU128<1>;
type DepositFactor = ConstU128<1>;
type MaxSignatories = ConstU32<128>;
type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
}
impl pallet_utility::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PalletsOrigin = OriginCaller;
type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
}
parameter_types! {
pub const NativeToEvmSwapBridgePalletId: PalletId = PalletId(*b"hmsb/ne1");
pub const EvmToNativeSwapBridgePalletId: PalletId = PalletId(*b"hmsb/en1");
}
parameter_types! {
pub NativeToEvmSwapBridgePotAccountId: AccountId = NativeToEvmSwapBridgePot::account_id();
pub EvmToNativeSwapBridgePotAccountId: EvmAccountId = EvmToNativeSwapBridgePot::account_id();
}
type BridgeInstanceNativeToEvmSwap = pallet_bridge_pot_currency_swap::Instance1;
type BridgeInstanceEvmToNativeSwap = pallet_bridge_pot_currency_swap::Instance2;
impl pallet_bridge_pot_currency_swap::Config<BridgeInstanceNativeToEvmSwap> for Runtime {
type AccountIdFrom = AccountId;
type AccountIdTo = EvmAccountId;
type CurrencyFrom = Balances;
type CurrencyTo = EvmBalances;
type BalanceConverter = Identity;
type PotFrom = NativeToEvmSwapBridgePotAccountId;
type PotTo = EvmToNativeSwapBridgePotAccountId;
type GenesisVerifier = currency_swap::GenesisVerifier;
}
impl pallet_bridge_pot_currency_swap::Config<BridgeInstanceEvmToNativeSwap> for Runtime {
type AccountIdFrom = EvmAccountId;
type AccountIdTo = AccountId;
type CurrencyFrom = EvmBalances;
type CurrencyTo = Balances;
type BalanceConverter = Identity;
type PotFrom = EvmToNativeSwapBridgePotAccountId;
type PotTo = NativeToEvmSwapBridgePotAccountId;
type GenesisVerifier = currency_swap::GenesisVerifier;
}
parameter_types! {
pub TreasuryPotAccountId: AccountId = TreasuryPot::account_id();
}
impl pallet_balanced_currency_swap_bridges_initializer::Config for Runtime {
type EvmAccountId = EvmAccountId;
type NativeCurrency = Balances;
type EvmCurrency = EvmBalances;
type BalanceConverterEvmToNative = Identity;
type BalanceConverterNativeToEvm = Identity;
type NativeEvmBridgePot = NativeToEvmSwapBridgePotAccountId;
type NativeTreasuryPot = TreasuryPotAccountId;
type EvmNativeBridgePot = EvmToNativeSwapBridgePotAccountId;
type WeightInfo = ();
}
// Create the runtime by composing the FRAME pallets that were previously
// configured.
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = opaque::Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
System: frame_system = 0,
Timestamp: pallet_timestamp = 2,
ChainStartMoment: pallet_chain_start_moment = 3,
Bootnodes: pallet_bootnodes = 4,
Bioauth: pallet_bioauth = 5,
// Must be before session.
Babe: pallet_babe = 6,
// Authorship must be before session.
Authorship: pallet_authorship = 7,
Balances: pallet_balances = 8,
TreasuryPot: pallet_pot::<Instance1> = 9,
FeesPot: pallet_pot::<Instance2> = 10,
TokenClaimsPot: pallet_pot::<Instance3> = 11,
TransactionPayment: pallet_transaction_payment = 12,
Session: pallet_session = 13,
Offences: pallet_offences = 14,
Historical: pallet_session_historical = 15,
HumanodeSession: pallet_humanode_session = 16,
ChainProperties: pallet_chain_properties = 17,
EthereumChainId: pallet_ethereum_chain_id = 18,
Sudo: pallet_sudo = 19,
Grandpa: pallet_grandpa = 20,
Ethereum: pallet_ethereum = 21,
EVM: pallet_evm = 22,
DynamicFee: pallet_dynamic_fee = 23,
BaseFee: pallet_base_fee = 24,
ImOnline: pallet_im_online = 25,
EvmAccountsMapping: pallet_evm_accounts_mapping = 26,
TokenClaims: pallet_token_claims = 27,
Vesting: pallet_vesting = 28,
Multisig: pallet_multisig = 29,
Utility: pallet_utility = 30,
EvmSystem: pallet_evm_system = 31,
EvmBalances: pallet_evm_balances = 32,
NativeToEvmSwapBridgePot: pallet_pot::<Instance4> = 33,
EvmToNativeSwapBridgePot: pallet_pot::<Instance5> = 34,
CurrencySwap: pallet_currency_swap = 35,
BalancedCurrencySwapBridgesInitializer: pallet_balanced_currency_swap_bridges_initializer = 36,
NativeToEvmSwapBridge: pallet_bridge_pot_currency_swap::<Instance1> = 37,
EvmToNativeSwapBridge: pallet_bridge_pot_currency_swap::<Instance2> = 38,
}
);
/// The address format for describing accounts.
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// The generic version of the `Extra` component of the [`UncheckedExtrinsic`] and
/// the [`SignedPayload`] of the current runtime implementation, but abstract around the runtime
/// config. Used internally to ensure we implement utilities in the generic fashion.
/// See [`SignedExtra`].
type GenericSignedExtra<R> = (
frame_system::CheckSpecVersion<R>,
frame_system::CheckTxVersion<R>,
frame_system::CheckGenesis<R>,
frame_system::CheckEra<R>,
frame_system::CheckNonce<R>,
frame_system::CheckWeight<R>,
pallet_bioauth::CheckBioauthTx<R>,
pallet_transaction_payment::ChargeTransactionPayment<R>,
pallet_token_claims::CheckTokenClaim<R>,
);
/// The `Extra` component of the [`UncheckedExtrinsic`] and the [`SignedPayload`].
/// Effectively, additional data carried besides the call within the signed transactions.
pub type SignedExtra = GenericSignedExtra<Runtime>;
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
>;
impl frame_system::offchain::CreateSignedTransaction<RuntimeCall> for Runtime {
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
call: Self::RuntimeCall,
public: <Self::Signature as sp_runtime::traits::Verify>::Signer,
account: Self::AccountId,
nonce: Self::Index,
) -> Option<(
Self::RuntimeCall,
<Self::Extrinsic as sp_runtime::traits::Extrinsic>::SignaturePayload,
)> {
let tip = 0;
let era = utils::current_era::<Self>();
let extra = utils::create_extra::<Self>(nonce, era, tip);
let raw_payload = SignedPayload::new(call, extra).ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let address = Self::Lookup::unlookup(account);
let (call, extra, _) = raw_payload.deconstruct();
Some((call, (address, signature, extra)))
}
}
impl frame_system::offchain::SigningTypes for Runtime {
type Public = <Signature as sp_runtime::traits::Verify>::Signer;
type Signature = Signature;
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
RuntimeCall: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = RuntimeCall;
}
impl fp_self_contained::SelfContainedCall for RuntimeCall {
type SignedInfo = H160;
fn is_self_contained(&self) -> bool {
match self {
RuntimeCall::Ethereum(call) => call.is_self_contained(),
_ => false,
}
}
fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
match self {
RuntimeCall::Ethereum(call) => call.check_self_contained(),
_ => None,
}
}
fn validate_self_contained(
&self,
info: &Self::SignedInfo,
dispatch_info: &DispatchInfoOf<RuntimeCall>,
len: usize,
) -> Option<TransactionValidity> {
match self {
RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
_ => None,
}
}
fn pre_dispatch_self_contained(
&self,
info: &Self::SignedInfo,
dispatch_info: &DispatchInfoOf<RuntimeCall>,
len: usize,
) -> Option<Result<(), TransactionValidityError>> {
match self {
RuntimeCall::Ethereum(call) => {
call.pre_dispatch_self_contained(info, dispatch_info, len)
}
_ => None,
}
}
fn apply_self_contained(