-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathlib.rs
More file actions
1175 lines (1032 loc) · 47.6 KB
/
Copy pathlib.rs
File metadata and controls
1175 lines (1032 loc) · 47.6 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
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub mod apis;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarks;
pub mod configs;
pub mod weights;
extern crate alloc;
use alloc::vec::Vec;
use frame_support::traits::{fungible::Mutate, OnRuntimeUpgrade};
use pallet_revive::evm::runtime::EthExtra;
use quip_transaction_crypto::HybridTxSignature;
use sp_runtime::{
generic, impl_opaque_keys,
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiAddress,
};
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
pub use frame_system::Call as SystemCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_timestamp::Call as TimestampCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub mod genesis_config_presets;
/// 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 {
use super::*;
use sp_runtime::{
generic,
traits::{BlakeTwo256, Hash as HashT},
};
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
/// 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>;
/// Opaque block hash type.
pub type Hash = <BlakeTwo256 as HashT>::Output;
}
impl_opaque_keys! {
pub struct SessionKeys {
pub babe: Babe,
pub grandpa: Grandpa,
}
}
/// Heap-boxed session keys keep `pallet_session::Call::set_keys` from making
/// the entire `RuntimeCall` enum larger than Utility's 1 KiB batching limit.
/// `Box<T>` and this single-field wrapper are SCALE-transparent, so the
/// existing `Session.set_keys` wire encoding is unchanged.
#[derive(
Clone,
PartialEq,
Eq,
codec::Encode,
codec::Decode,
codec::DecodeWithMemTracking,
scale_info::TypeInfo,
serde::Serialize,
serde::Deserialize,
Debug,
)]
pub struct BoxedSessionKeys(alloc::boxed::Box<SessionKeys>);
impl From<SessionKeys> for BoxedSessionKeys {
fn from(keys: SessionKeys) -> Self {
Self(alloc::boxed::Box::new(keys))
}
}
impl sp_runtime::traits::OpaqueKeys for BoxedSessionKeys {
type KeyTypeIdProviders = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
fn key_ids() -> &'static [sp_core::crypto::KeyTypeId] {
SessionKeys::key_ids()
}
fn get_raw(&self, key_type: sp_core::crypto::KeyTypeId) -> &[u8] {
self.0.get_raw(key_type)
}
fn ownership_proof_is_valid(&self, owner: &[u8], proof: &[u8]) -> bool {
self.0.ownership_proof_is_valid(owner, proof)
}
}
#[cfg(test)]
mod boxed_session_keys_tests {
use super::{BoxedSessionKeys, SessionKeys};
use codec::Encode;
use quip_crypto_primitives::substrate::{
ed25519_fndsa512::Pair as HybridGrandpaPair, sr25519_fndsa512::Pair as HybridBabePair,
};
use sp_core::Pair as _;
#[test]
fn boxed_session_keys_preserve_scale_wire_encoding() {
let keys = SessionKeys {
babe: HybridBabePair::from_string("//Alice", None)
.expect("Alice BABE seed is valid")
.public()
.into(),
grandpa: HybridGrandpaPair::from_string("//Alice", None)
.expect("Alice GRANDPA seed is valid")
.public()
.into(),
};
let original_encoding = keys.encode();
let boxed_encoding = BoxedSessionKeys::from(keys).encode();
assert_eq!(boxed_encoding, original_encoding);
}
}
// To learn more about runtime versioning, see:
// https://docs.substrate.io/main-docs/build/upgrade#runtime-versioning
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: alloc::borrow::Cow::Borrowed("quip"),
impl_name: alloc::borrow::Cow::Borrowed("quip"),
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.
// Bumped to 101 (and `transaction_version` to 2) when the signed-extrinsic
// wire format switched from `MultiSignature` to the hybrid envelope. Without
// these bumps, peers/clients could treat the new format as the old one.
// Bumped to 102 for v0.2.0: adds `pallet_faucet_ops` (idx 11) and
// `pallet_session` (idx 12). New dispatchables, events, and storage entries
// change the runtime metadata; the signed-extrinsic wire format is
// unchanged, so `transaction_version` stays at 2.
// Bumped to 103 for QUI-567: adds the canonical default plain Ising job
// spec, root-gates `QuantumComputeMempool::register_job_spec`, and changes
// that call's argument encoding, so `transaction_version` moves to 3.
// Bumped to 104 for the topology-upgrade path: adds
// `QuantumPow::set_default_topology` (call_index 5) and makes the
// difficulty energy curve spec-aware (h/J magnitudes derived from the
// default topology's allowed-value specs instead of hardcoded ternary-h /
// binary-J). Existing call encodings are unchanged, so
// `transaction_version` stays at 3.
// Bumped to 105 for indexer-free quantum reads: adds monotonic qblock ids,
// qblock/hardness runtime APIs, and the mempool open-order recovery index.
// Existing call encodings are unchanged, so `transaction_version` stays at
// 3.
// Bumped to 106 for on-chain miner descriptors and qblock participation:
// adds `MinerRegistry` (idx 13) with descriptor/participation calls,
// events, and storage. Existing call encodings are unchanged, so
// `transaction_version` stays at 3.
// Bumped to 107 for the participants-per-qblock reverse index
// (`ParticipantsByQBlock`, `ParticipantCountByQBlock`) and the
// `MinerRegistryApi` runtime API. Call encodings are unchanged, so
// `transaction_version` stays at 3.
// Bumped to 108 for per-topology difficulty + the mineable-topology
// whitelist: `QuantumPow.Difficulty` (global StorageValue) becomes
// `Difficulties` (StorageMap keyed by topology hash), `MineableTopologies`
// is added, `set_difficulty` gains a `topology_hash` argument, and
// `add_mineable_topology`/`remove_mineable_topology` (call_index 6/7) are
// added. `set_difficulty`'s argument encoding changed, so
// `transaction_version` moves to 4. Pallet storage version 2 → 3 with a
// carry-forward migration.
// Bumped to 109 to restore on-chain `system_info`: `MinerRegistry` adds a
// schema-v2 descriptor input (`NodeDescriptorInput::V2`) carrying an
// optional typed hardware survey, plus a v1 → v2 storage migration that
// drops existing descriptors (miners re-file on restart). The V1 call
// variant keeps index 0 and encodes identically, so `transaction_version`
// stays at 4. MinerRegistry pallet storage version 1 → 2.
// Bumped to 110 to add the optional `runtime` block (node software identity:
// python / quip_version / protocol_version / in_docker / docker_image) to
// the MinerRegistry V2 descriptor. Additive trailing field on the V2 input;
// V1 is unaffected and V2 was not yet deployed, so `transaction_version`
// stays at 4 and no new migration is needed (the v1 → v2 migration already
// wipes descriptors; pallet storage version stays 2).
// Bumped to 111 (110 had already shipped in v0.2.1-rc11 when these
// landed) for two QuantumPow changes — this is what the chain deployed:
// - `QBlock` gains a trailing `topology_hash` so a block records which
// topology it was mined against. This changes the persisted `QBlocks`
// value layout, so QuantumPow pallet storage version goes 3 → 4 with a
// v3 → v4 migration that re-encodes existing entries, backfilling
// `topology_hash` with the default topology. Read-only runtime API
// shape change (`QBlock`/`QBlockWithNonce`). Includes the sudo-only
// per-topology curve `c` override (`set_topology_curve`, new call).
// - `submit_proof` weight becomes dimension-scaled (QIP-03): charged
// weight now depends on the registered topology's node/edge counts and
// the proof's solution count instead of a flat 60M placeholder.
// No call encodings changed in 111, so `transaction_version` stayed at 4.
// Bumped to 112 (111 was already deployed when this landed):
// `QuantumProof` gains a trailing `device_access_time_us: u64`
// (miner-reported compute time: QPU access time for QPU wins, wall clock
// for CPU/GPU), carried through `ProofRecord` and persisted as a trailing
// field on `QBlock`. QuantumPow pallet storage version goes 4 → 5: the
// deployed-v4 path appends `device_access_time_us = 0` preserving each
// block's stored `topology_hash`; the pre-v4 path re-encodes from the
// 7-field layout backfilling both trailing fields. Read-only runtime API
// shape change (`QBlock`/`QBlockWithNonce`). `submit_proof`'s argument
// encoding changed, so `transaction_version` moves to 5.
// Bumped for pallet-revive (idx 14), its Ethereum runtime APIs, EVM-aware
// unchecked-extrinsic wrapper, and `EthSetOrigin` transaction extension.
// The extension set and accepted extrinsic forms change, so
// `transaction_version` moves to 6. First shipped as 114 in the v0.2.2-rc
// tags (113 was only an intermediate branch value and never released).
// Bumped to 115 for the post-tag main build after the benchmark weight
// regeneration. No call encodings changed, so `transaction_version` stays
// at 6. 115 has not shipped. Later storage-only changes (pallet-evm-chain-id)
// stay on 115 until a 115 runtime is live.
// Bumped to 116 for the H2/H4 chain-wipe relaunch and to publish Metadata
// V16 from the legacy metadata runtime API (`state_getMetadata`), which
// previously returned the V14 inherent default. The versioned metadata API
// keeps serving 14/15/16. The H1/H3 (ML-DSA-44) to H2/H4 (FN-DSA-512)
// scheme change uses new public-key and signature encodings, so old signed
// extrinsics are incompatible and `transaction_version` moves to 7.
// Bumped to 117 to hard-invalidate 116 nodes: the crates.io pqhybridsign
// rc5 switch and repins carry no interface change, but a spec bump makes
// any node still on 116 refuse the new runtime outright.
// Extended 117 with custody pallets starting at index 16. This unreleased
// runtime keeps the existing extrinsic format, so transaction version 7
// remains unchanged.
spec_version: 117,
impl_version: 1,
apis: apis::RUNTIME_API_VERSIONS,
transaction_version: 7,
system_version: 1,
};
mod block_times {
/// This determines the average expected block time that we are targeting. Blocks will be
/// produced at a minimum duration defined by `SLOT_DURATION`. `SLOT_DURATION` is picked up by
/// `pallet_timestamp` which is in turn picked up by `pallet_babe`.
///
/// Change this to adjust the block time.
pub const MILLI_SECS_PER_BLOCK: u64 = 6000;
// NOTE: Currently it is not possible to change the slot duration after the chain has started.
// Attempting to do so will brick block production.
pub const SLOT_DURATION: u64 = MILLI_SECS_PER_BLOCK;
}
pub use block_times::*;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLI_SECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
pub const BLOCK_HASH_COUNT: BlockNumber = 2400;
// Unit = the base number of indivisible units for balances
pub const UNIT: Balance = 1_000_000_000_000;
pub const MILLI_UNIT: Balance = 1_000_000_000;
pub const MICRO_UNIT: Balance = 1_000_000;
/// Existential deposit.
pub const EXISTENTIAL_DEPOSIT: Balance = MILLI_UNIT;
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
sp_consensus_babe::BabeEpochConfiguration {
c: (1, 4),
allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
};
/// 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(),
}
}
/// Hybrid transaction signature used for runtime extrinsics.
pub type Signature = HybridTxSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Balance of an account.
pub type Balance = u128;
/// Index of a transaction in the chain.
pub type Nonce = u32;
/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;
/// An index to a block.
pub type BlockNumber = u32;
/// The address format for describing accounts.
pub type Address = 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>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The `TransactionExtension` to the basic transaction logic.
pub type TxExtension = (
frame_system::AuthorizeCall<Runtime>,
frame_system::CheckNonZeroSender<Runtime>,
frame_system::CheckSpecVersion<Runtime>,
frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
frame_system::WeightReclaim<Runtime>,
);
fn tx_extension(
era: generic::Era,
nonce: Nonce,
tip: Balance,
revive_origin: pallet_revive::evm::tx_extension::SetOrigin<Runtime>,
) -> TxExtension {
(
frame_system::AuthorizeCall::<Runtime>::new(),
frame_system::CheckNonZeroSender::<Runtime>::new(),
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckEra::<Runtime>::from(era),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
frame_metadata_hash_extension::CheckMetadataHash::<Runtime>::new(false),
revive_origin,
frame_system::WeightReclaim::<Runtime>::new(),
)
}
/// Construct the extension tuple used by Quip's native signed transactions.
/// Keeping this in the runtime prevents node-side transaction builders from
/// drifting when the ordered extension set changes.
pub fn native_tx_extension(era: generic::Era, nonce: Nonce, tip: Balance) -> TxExtension {
tx_extension(era, nonce, tip, Default::default())
}
/// Builds the normal transaction extensions used by an Ethereum transaction
/// after Revive has recovered and validated its secp256k1 signer.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct EthExtraImpl;
impl EthExtra for EthExtraImpl {
type Config = Runtime;
type Extension = TxExtension;
fn get_eth_extension(nonce: u32, tip: Balance) -> Self::Extension {
tx_extension(
generic::Era::Immortal,
nonce,
tip,
pallet_revive::evm::tx_extension::SetOrigin::<Runtime>::new_from_eth_transaction(),
)
}
}
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
pallet_revive::evm::runtime::UncheckedExtrinsic<Address, Signature, EthExtraImpl>;
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
/// Runtime storage migrations, run on upgrade before every pallet's
/// `on_runtime_upgrade`.
pub type Migrations = (
pallet_miner_registry::migrations::v2::MigrateToV2<Runtime>,
InitializeReviveAccount,
);
/// Reproduces Revive's genesis-time pallet-account initialization when the
/// pallet is introduced to an already-running chain by runtime upgrade.
///
/// The account-existence guard makes this safe and idempotent on later
/// upgrades and on chains whose genesis already included Revive.
pub struct InitializeReviveAccount;
impl OnRuntimeUpgrade for InitializeReviveAccount {
fn on_runtime_upgrade() -> frame_support::weights::Weight {
let account = Revive::account_id();
let db_weight = <Runtime as frame_system::Config>::DbWeight::get();
if System::account_exists(&account) {
return db_weight.reads(1);
}
let minimum_balance =
<Balances as frame_support::traits::fungible::Inspect<AccountId>>::minimum_balance();
assert!(
<Balances as Mutate<AccountId>>::mint_into(&account, minimum_balance).is_ok(),
"Revive pallet account must be initialized during runtime upgrade",
);
// Account-existence check plus balance-account and total-issuance
// reads; minting writes the latter two storage entries.
db_weight.reads_writes(3, 2)
}
}
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
Migrations,
>;
#[cfg(test)]
mod tests {
use super::*;
use codec::Encode;
use quip_transaction_crypto::{account_id_from_public, HybridPair, HybridTxSignature};
use sp_core::Pair as _;
use sp_runtime::{traits::Checkable, transaction_validity::InvalidTransaction, BuildStorage};
fn signed_test_extrinsic(
sender: &HybridPair,
address: Address,
call: RuntimeCall,
nonce: u32,
) -> UncheckedExtrinsic {
let tx_ext = native_tx_extension(generic::Era::Immortal, nonce, 0);
let payload = SignedPayload::new(call.clone(), tx_ext.clone()).unwrap();
let signature = payload.using_encoded(|encoded| HybridTxSignature::sign(sender, encoded));
generic::UncheckedExtrinsic::new_signed(call, address, signature, tx_ext).into()
}
#[test]
fn hybrid_signed_extrinsic_checks_successfully() {
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
System::set_block_number(1);
let sender = HybridPair::from_string("//Alice", None).unwrap();
let account_id = account_id_from_public(&sender.public());
let xt = signed_test_extrinsic(
&sender,
account_id.clone().into(),
SystemCall::remark { remark: vec![] }.into(),
0,
);
let lookup = frame_system::ChainContext::<Runtime>::default();
let checked =
<UncheckedExtrinsic as Checkable<frame_system::ChainContext<Runtime>>>::check(
xt, &lookup,
);
assert!(checked.is_ok());
});
}
/// Confirms the runtime's `CanonicalDefaultIsingSpecId` resolves to the
/// same hash that the pallet's mock test pins. SDKs and downstream docs
/// embed this hash; a mock-vs-runtime divergence would silently break
/// every client that hardcodes it.
#[test]
fn default_ising_spec_id_matches_pinned_hash() {
use frame_support::traits::Get as _;
let id = <Runtime as pallet_quantum_compute_mempool::Config>::DefaultIsingSpecId::get();
assert_eq!(
format!("{id:?}"),
"0x8f46f3a31321d1d093314fc769c42cbe7a83d71a0b69e6571a0f68e2a04067f0",
);
}
#[test]
fn hybrid_signed_extrinsic_rejects_wrong_account() {
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
System::set_block_number(1);
let sender = HybridPair::from_string("//Alice", None).unwrap();
let wrong = HybridPair::from_string("//Bob", None).unwrap();
let wrong_account = account_id_from_public(&wrong.public());
let xt = signed_test_extrinsic(
&sender,
wrong_account.into(),
SystemCall::remark { remark: vec![] }.into(),
0,
);
let lookup = frame_system::ChainContext::<Runtime>::default();
let checked =
<UncheckedExtrinsic as Checkable<frame_system::ChainContext<Runtime>>>::check(
xt, &lookup,
);
assert_eq!(checked.unwrap_err(), InvalidTransaction::BadProof.into());
});
}
#[test]
fn balances_support_plain_reserve_round_trip() {
use frame_support::traits::{Currency, ReservableCurrency};
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
let account =
account_id_from_public(&HybridPair::from_string("//Alice", None).unwrap().public());
let reserve = 5 * UNIT;
<Balances as Currency<AccountId>>::make_free_balance_be(&account, 10 * UNIT);
assert!(Balances::reserve(&account, reserve).is_ok());
assert_eq!(Balances::reserved_balance(&account), reserve);
assert_eq!(Balances::unreserve(&account, reserve), 0);
assert_eq!(Balances::reserved_balance(&account), 0);
});
}
#[test]
fn h4_multisig_uses_hash_approval_then_executes_full_call() {
use frame_support::{dispatch::GetDispatchInfo, traits::Currency, weights::Weight};
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
System::set_block_number(1);
let alice = HybridPair::from_string("//Alice", None).unwrap();
let bob = HybridPair::from_string("//Bob", None).unwrap();
let charlie = HybridPair::from_string("//Charlie", None).unwrap();
let target = account_id_from_public(
&HybridPair::from_string("//Dave", None).unwrap().public(),
);
let mut signatories = vec![
account_id_from_public(&alice.public()),
account_id_from_public(&bob.public()),
account_id_from_public(&charlie.public()),
];
signatories.sort();
for account in &signatories {
<Balances as Currency<AccountId>>::make_free_balance_be(account, 100 * UNIT);
}
let multisig = Multisig::multi_account_id(&signatories, 2);
<Balances as Currency<AccountId>>::make_free_balance_be(&multisig, 10 * UNIT);
let inner: RuntimeCall = BalancesCall::transfer_allow_death {
dest: Address::Id(target.clone()),
value: 3 * UNIT,
}
.into();
let call_hash = sp_io::hashing::blake2_256(&inner.encode());
let first_account = account_id_from_public(&alice.public());
let mut first_others = signatories
.iter()
.filter(|account| **account != first_account)
.cloned()
.collect::<Vec<_>>();
first_others.sort();
let approval: RuntimeCall = pallet_multisig::Call::approve_as_multi {
threshold: 2,
other_signatories: first_others,
maybe_timepoint: None,
call_hash,
max_weight: Weight::zero(),
}
.into();
let approval_xt = signed_test_extrinsic(
&alice,
Address::Id(first_account),
approval,
0,
);
let approval_size = approval_xt.encode().len();
assert!(Executive::apply_extrinsic(approval_xt).unwrap().is_ok());
let timepoint = pallet_multisig::Multisigs::<Runtime>::get(&multisig, call_hash)
.expect("first approval creates multisig state")
.when;
let final_account = account_id_from_public(&bob.public());
let mut final_others = signatories
.iter()
.filter(|account| **account != final_account)
.cloned()
.collect::<Vec<_>>();
final_others.sort();
let final_call: RuntimeCall = pallet_multisig::Call::as_multi {
threshold: 2,
other_signatories: final_others,
maybe_timepoint: Some(timepoint),
max_weight: inner.get_dispatch_info().call_weight,
call: alloc::boxed::Box::new(inner),
}
.into();
let final_xt =
signed_test_extrinsic(&bob, Address::Id(final_account), final_call, 0);
let final_size = final_xt.encode().len();
assert!(Executive::apply_extrinsic(final_xt).unwrap().is_ok());
eprintln!(
"H4 multisig extrinsic sizes: approve_as_multi={approval_size}, as_multi={final_size}"
);
assert_eq!(Balances::free_balance(target), 3 * UNIT);
assert!(pallet_multisig::Multisigs::<Runtime>::get(&multisig, call_hash).is_none());
});
}
#[test]
fn h4_utility_batch_all_and_derivative_transfer_work() {
use frame_support::traits::Currency;
use sp_core::crypto::Ss58Codec;
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
System::set_block_number(1);
let alice = HybridPair::from_string("//Alice", None).unwrap();
let alice_account = account_id_from_public(&alice.public());
<Balances as Currency<AccountId>>::make_free_balance_be(&alice_account, 100 * UNIT);
let recipients = ["//Bob", "//Charlie", "//Dave"].map(|uri| {
account_id_from_public(&HybridPair::from_string(uri, None).unwrap().public())
});
let calls = recipients
.iter()
.enumerate()
.map(|(index, recipient)| {
BalancesCall::transfer_allow_death {
dest: Address::Id(recipient.clone()),
value: (index as Balance + 1) * UNIT,
}
.into()
})
.collect();
let batch: RuntimeCall = pallet_utility::Call::batch_all { calls }.into();
let batch_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account.clone()), batch, 0);
assert!(Executive::apply_extrinsic(batch_xt).unwrap().is_ok());
assert_eq!(Balances::free_balance(&recipients[0]), UNIT);
assert_eq!(Balances::free_balance(&recipients[1]), 2 * UNIT);
assert_eq!(Balances::free_balance(&recipients[2]), 3 * UNIT);
let derivative = pallet_utility::derivative_account_id(alice_account.clone(), 7);
<Balances as Currency<AccountId>>::make_free_balance_be(&derivative, 5 * UNIT);
let derivative_target =
account_id_from_public(&HybridPair::from_string("//Eve", None).unwrap().public());
let derivative_call: RuntimeCall = pallet_utility::Call::as_derivative {
index: 7,
call: alloc::boxed::Box::new(
BalancesCall::transfer_allow_death {
dest: Address::Id(derivative_target.clone()),
value: 2 * UNIT,
}
.into(),
),
}
.into();
let derivative_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account), derivative_call, 1);
assert!(Executive::apply_extrinsic(derivative_xt).unwrap().is_ok());
eprintln!(
"utility derivative index 7 address: {}",
derivative.to_ss58check()
);
assert_eq!(Balances::free_balance(derivative_target), 2 * UNIT);
});
}
#[test]
fn runtime_call_fits_utility_batching_limit() {
assert!(core::mem::size_of::<RuntimeCall>() <= 1024);
}
#[test]
fn h4_multisig_can_execute_utility_batch() {
use frame_support::{dispatch::GetDispatchInfo, traits::Currency, weights::Weight};
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
System::set_block_number(1);
let alice = HybridPair::from_string("//Alice", None).unwrap();
let bob = HybridPair::from_string("//Bob", None).unwrap();
let charlie = HybridPair::from_string("//Charlie", None).unwrap();
let mut signatories = vec![
account_id_from_public(&alice.public()),
account_id_from_public(&bob.public()),
account_id_from_public(&charlie.public()),
];
signatories.sort();
for account in &signatories {
<Balances as Currency<AccountId>>::make_free_balance_be(account, 100 * UNIT);
}
let multisig = Multisig::multi_account_id(&signatories, 2);
<Balances as Currency<AccountId>>::make_free_balance_be(&multisig, 10 * UNIT);
let recipients = ["//Dave", "//Eve"].map(|uri| {
account_id_from_public(&HybridPair::from_string(uri, None).unwrap().public())
});
let inner: RuntimeCall = pallet_utility::Call::batch_all {
calls: recipients
.iter()
.map(|recipient| {
BalancesCall::transfer_allow_death {
dest: Address::Id(recipient.clone()),
value: 2 * UNIT,
}
.into()
})
.collect(),
}
.into();
let call_hash = sp_io::hashing::blake2_256(&inner.encode());
let alice_account = account_id_from_public(&alice.public());
let mut alice_others = signatories
.iter()
.filter(|account| **account != alice_account)
.cloned()
.collect::<Vec<_>>();
alice_others.sort();
let approval: RuntimeCall = pallet_multisig::Call::approve_as_multi {
threshold: 2,
other_signatories: alice_others,
maybe_timepoint: None,
call_hash,
max_weight: Weight::zero(),
}
.into();
let approval_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account), approval, 0);
assert!(Executive::apply_extrinsic(approval_xt).unwrap().is_ok());
let timepoint = pallet_multisig::Multisigs::<Runtime>::get(&multisig, call_hash)
.expect("first approval creates multisig state")
.when;
let bob_account = account_id_from_public(&bob.public());
let mut bob_others = signatories
.iter()
.filter(|account| **account != bob_account)
.cloned()
.collect::<Vec<_>>();
bob_others.sort();
let execution: RuntimeCall = pallet_multisig::Call::as_multi {
threshold: 2,
other_signatories: bob_others,
maybe_timepoint: Some(timepoint),
max_weight: inner.get_dispatch_info().call_weight,
call: alloc::boxed::Box::new(inner),
}
.into();
let execution_xt = signed_test_extrinsic(&bob, Address::Id(bob_account), execution, 0);
assert!(Executive::apply_extrinsic(execution_xt).unwrap().is_ok());
assert_eq!(Balances::free_balance(&recipients[0]), 2 * UNIT);
assert_eq!(Balances::free_balance(&recipients[1]), 2 * UNIT);
});
}
#[test]
fn h4_proxy_filters_calls_rejects_announcements_and_creates_pure_accounts() {
use frame_support::traits::Currency;
use sp_runtime::traits::{BlakeTwo256, Hash as _};
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
System::set_block_number(1);
let alice = HybridPair::from_string("//Alice", None).unwrap();
let bob = HybridPair::from_string("//Bob", None).unwrap();
let charlie = HybridPair::from_string("//Charlie", None).unwrap();
let alice_account = account_id_from_public(&alice.public());
let bob_account = account_id_from_public(&bob.public());
let charlie_account = account_id_from_public(&charlie.public());
for account in [&alice_account, &bob_account, &charlie_account] {
<Balances as Currency<AccountId>>::make_free_balance_be(account, 100 * UNIT);
}
let add_immediate: RuntimeCall = pallet_proxy::Call::add_proxy {
delegate: Address::Id(bob_account.clone()),
proxy_type: configs::ProxyType::TransferOnly,
delay: 0,
}
.into();
let add_immediate_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account.clone()), add_immediate, 0);
assert!(Executive::apply_extrinsic(add_immediate_xt)
.unwrap()
.is_ok());
let recipient =
account_id_from_public(&HybridPair::from_string("//Dave", None).unwrap().public());
let transfer: RuntimeCall = BalancesCall::transfer_allow_death {
dest: Address::Id(recipient.clone()),
value: 4 * UNIT,
}
.into();
let proxied_transfer: RuntimeCall = pallet_proxy::Call::proxy {
real: Address::Id(alice_account.clone()),
force_proxy_type: Some(configs::ProxyType::TransferOnly),
call: alloc::boxed::Box::new(transfer),
}
.into();
let transfer_xt =
signed_test_extrinsic(&bob, Address::Id(bob_account.clone()), proxied_transfer, 0);
assert!(Executive::apply_extrinsic(transfer_xt).unwrap().is_ok());
assert_eq!(Balances::free_balance(&recipient), 4 * UNIT);
let rejected: RuntimeCall = pallet_proxy::Call::proxy {
real: Address::Id(alice_account.clone()),
force_proxy_type: Some(configs::ProxyType::TransferOnly),
call: alloc::boxed::Box::new(SystemCall::remark { remark: vec![1] }.into()),
}
.into();
let rejected_xt =
signed_test_extrinsic(&bob, Address::Id(bob_account.clone()), rejected, 1);
assert!(Executive::apply_extrinsic(rejected_xt).unwrap().is_ok());
assert!(System::events().iter().any(|record| matches!(
&record.event,
RuntimeEvent::Proxy(pallet_proxy::Event::ProxyExecuted { result: Err(_) })
)));
let add_delayed: RuntimeCall = pallet_proxy::Call::add_proxy {
delegate: Address::Id(charlie_account.clone()),
proxy_type: configs::ProxyType::TransferOnly,
delay: 3,
}
.into();
let add_delayed_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account.clone()), add_delayed, 1);
assert!(Executive::apply_extrinsic(add_delayed_xt).unwrap().is_ok());
let delayed_call: RuntimeCall = BalancesCall::transfer_keep_alive {
dest: Address::Id(recipient),
value: UNIT,
}
.into();
let delayed_hash = BlakeTwo256::hash_of(&alloc::boxed::Box::new(delayed_call.clone()));
let announce: RuntimeCall = pallet_proxy::Call::announce {
real: Address::Id(alice_account.clone()),
call_hash: delayed_hash,
}
.into();
let announce_xt =
signed_test_extrinsic(&charlie, Address::Id(charlie_account.clone()), announce, 0);
assert!(Executive::apply_extrinsic(announce_xt).unwrap().is_ok());
assert_eq!(
pallet_proxy::Announcements::<Runtime>::get(&charlie_account)
.0
.len(),
1
);
// The real account can reject the announced call immediately,
// before the three-block execution delay has elapsed.
let reject: RuntimeCall = pallet_proxy::Call::reject_announcement {
delegate: Address::Id(charlie_account.clone()),
call_hash: delayed_hash,
}
.into();
let reject_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account.clone()), reject, 2);
assert!(Executive::apply_extrinsic(reject_xt).unwrap().is_ok());
assert!(
pallet_proxy::Announcements::<Runtime>::get(&charlie_account)
.0
.is_empty()
);
let create_pure: RuntimeCall = pallet_proxy::Call::create_pure {
proxy_type: configs::ProxyType::TransferOnly,
delay: 0,
index: 9,
}
.into();
let create_pure_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account.clone()), create_pure, 3);
assert!(Executive::apply_extrinsic(create_pure_xt).unwrap().is_ok());
let pure = System::events()
.iter()
.find_map(|record| match &record.event {
RuntimeEvent::Proxy(pallet_proxy::Event::PureCreated { pure, .. }) => {
Some(pure.clone())
}
_ => None,
})
.expect("create_pure emits the custody account");
assert!(pallet_proxy::Proxies::<Runtime>::contains_key(pure));
});
}
#[test]
fn h4_multisig_account_can_delegate_to_transfer_proxy() {
use frame_support::{dispatch::GetDispatchInfo, traits::Currency, weights::Weight};
let mut ext =
sp_io::TestExternalities::new(RuntimeGenesisConfig::default().build_storage().unwrap());
ext.execute_with(|| {
System::set_block_number(1);
let alice = HybridPair::from_string("//Alice", None).unwrap();
let bob = HybridPair::from_string("//Bob", None).unwrap();
let charlie = HybridPair::from_string("//Charlie", None).unwrap();
let delegate = HybridPair::from_string("//Dave", None).unwrap();
let mut signatories = vec![
account_id_from_public(&alice.public()),
account_id_from_public(&bob.public()),
account_id_from_public(&charlie.public()),
];
signatories.sort();
for account in &signatories {
<Balances as Currency<AccountId>>::make_free_balance_be(account, 100 * UNIT);
}
let delegate_account = account_id_from_public(&delegate.public());
<Balances as Currency<AccountId>>::make_free_balance_be(&delegate_account, 100 * UNIT);
let multisig = Multisig::multi_account_id(&signatories, 2);
<Balances as Currency<AccountId>>::make_free_balance_be(&multisig, 20 * UNIT);
let add_proxy: RuntimeCall = pallet_proxy::Call::add_proxy {
delegate: Address::Id(delegate_account.clone()),
proxy_type: configs::ProxyType::TransferOnly,
delay: 0,
}
.into();
let call_hash = sp_io::hashing::blake2_256(&add_proxy.encode());
let alice_account = account_id_from_public(&alice.public());
let mut alice_others = signatories
.iter()
.filter(|account| **account != alice_account)
.cloned()
.collect::<Vec<_>>();
alice_others.sort();
let approval: RuntimeCall = pallet_multisig::Call::approve_as_multi {
threshold: 2,
other_signatories: alice_others,
maybe_timepoint: None,
call_hash,
max_weight: Weight::zero(),
}
.into();
let approval_xt =
signed_test_extrinsic(&alice, Address::Id(alice_account), approval, 0);
assert!(Executive::apply_extrinsic(approval_xt).unwrap().is_ok());
let timepoint = pallet_multisig::Multisigs::<Runtime>::get(&multisig, call_hash)
.expect("first approval creates multisig state")
.when;
let bob_account = account_id_from_public(&bob.public());
let mut bob_others = signatories
.iter()
.filter(|account| **account != bob_account)
.cloned()
.collect::<Vec<_>>();
bob_others.sort();
let execute_add: RuntimeCall = pallet_multisig::Call::as_multi {
threshold: 2,
other_signatories: bob_others,
maybe_timepoint: Some(timepoint),
max_weight: add_proxy.get_dispatch_info().call_weight,
call: alloc::boxed::Box::new(add_proxy),
}