1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
// Copyright (C) 2021 Subspace Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Primitives for domains pallet.

#![cfg_attr(not(feature = "std"), no_std)]

pub mod bundle_producer_election;
pub mod core_api;
pub mod extrinsics;
pub mod merkle_tree;
pub mod proof_provider_and_verifier;
pub mod storage;
#[cfg(test)]
mod tests;
pub mod valued_trie;

#[cfg(not(feature = "std"))]
extern crate alloc;

use crate::storage::{RawGenesis, StorageKey};
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeSet;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use bundle_producer_election::{BundleProducerElectionParams, ProofOfElectionError};
use core::num::ParseIntError;
use core::ops::{Add, Sub};
use core::str::FromStr;
use domain_runtime_primitives::{calculate_max_bundle_weight, MultiAccountId};
use frame_support::storage::storage_prefix;
use frame_support::{Blake2_128Concat, StorageHasher};
use hexlit::hex;
use parity_scale_codec::{Codec, Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
use sp_core::crypto::KeyTypeId;
use sp_core::sr25519::vrf::VrfSignature;
#[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
use sp_core::sr25519::vrf::{VrfPreOutput, VrfProof};
use sp_core::H256;
use sp_runtime::generic::OpaqueDigestItemId;
use sp_runtime::traits::{
    BlakeTwo256, Block as BlockT, CheckedAdd, Hash as HashT, Header as HeaderT, NumberFor, Zero,
};
use sp_runtime::{Digest, DigestItem, OpaqueExtrinsic, Percent};
use sp_runtime_interface::pass_by;
use sp_runtime_interface::pass_by::PassBy;
use sp_std::collections::btree_map::BTreeMap;
use sp_std::fmt::{Display, Formatter};
use sp_trie::TrieLayout;
use sp_version::RuntimeVersion;
use sp_weights::Weight;
#[cfg(feature = "std")]
use std::collections::BTreeSet;
use subspace_core_primitives::crypto::blake3_hash;
use subspace_core_primitives::{bidirectional_distance, Blake3Hash, PotOutput, Randomness, U256};
use subspace_runtime_primitives::{Balance, Moment};

/// Key type for Operator.
pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"oper");

/// Extrinsics shuffling seed
pub const DOMAIN_EXTRINSICS_SHUFFLING_SEED_SUBJECT: &[u8] = b"extrinsics-shuffling-seed";

mod app {
    use super::KEY_TYPE;
    use sp_application_crypto::{app_crypto, sr25519};

    app_crypto!(sr25519, KEY_TYPE);
}

// TODO: this runtime constant is not support to update, see https://github.com/autonomys/subspace/issues/2712
// for more detail about the problem and what we need to do to support it.
//
// The domain storage fee multiplier used to charge a higher storage fee to the domain
// transaction to even out the duplicated/illegal domain transaction storage cost, which
// can not be eliminated right now.
pub const DOMAIN_STORAGE_FEE_MULTIPLIER: Balance = 3;

/// An operator authority signature.
pub type OperatorSignature = app::Signature;

/// An operator authority keypair. Necessarily equivalent to the schnorrkel public key used in
/// the main executor module. If that ever changes, then this must, too.
#[cfg(feature = "std")]
pub type OperatorPair = app::Pair;

/// An operator authority identifier.
pub type OperatorPublicKey = app::Public;

/// A type that implements `BoundToRuntimeAppPublic`, used for operator signing key.
pub struct OperatorKey;

impl sp_runtime::BoundToRuntimeAppPublic for OperatorKey {
    type Public = OperatorPublicKey;
}

/// Stake weight in the domain bundle election.
///
/// Derived from the Balance and can't be smaller than u128.
pub type StakeWeight = u128;

/// The Trie root of all extrinsics included in a bundle.
pub type ExtrinsicsRoot = H256;

/// Type alias for Header Hashing.
pub type HeaderHashingFor<Header> = <Header as HeaderT>::Hashing;
/// Type alias for Header number.
pub type HeaderNumberFor<Header> = <Header as HeaderT>::Number;
/// Type alias for Header hash.
pub type HeaderHashFor<Header> = <Header as HeaderT>::Hash;

/// Unique identifier of a domain.
#[derive(
    Clone,
    Copy,
    Debug,
    Hash,
    Default,
    Eq,
    PartialEq,
    Ord,
    PartialOrd,
    Encode,
    Decode,
    TypeInfo,
    Serialize,
    Deserialize,
    MaxEncodedLen,
)]
pub struct DomainId(u32);

impl From<u32> for DomainId {
    #[inline]
    fn from(x: u32) -> Self {
        Self(x)
    }
}

impl From<DomainId> for u32 {
    #[inline]
    fn from(domain_id: DomainId) -> Self {
        domain_id.0
    }
}

impl FromStr for DomainId {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<u32>().map(Into::into)
    }
}

impl Add<DomainId> for DomainId {
    type Output = Self;

    fn add(self, other: DomainId) -> Self {
        Self(self.0 + other.0)
    }
}

impl Sub<DomainId> for DomainId {
    type Output = Self;

    fn sub(self, other: DomainId) -> Self {
        Self(self.0 - other.0)
    }
}

impl CheckedAdd for DomainId {
    fn checked_add(&self, rhs: &Self) -> Option<Self> {
        self.0.checked_add(rhs.0).map(Self)
    }
}

impl DomainId {
    /// Creates a [`DomainId`].
    pub const fn new(id: u32) -> Self {
        Self(id)
    }

    /// Converts the inner integer to little-endian bytes.
    pub fn to_le_bytes(&self) -> [u8; 4] {
        self.0.to_le_bytes()
    }
}

impl Display for DomainId {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)
    }
}

impl PassBy for DomainId {
    type PassBy = pass_by::Codec<Self>;
}

/// Identifier of a chain.
#[derive(
    Clone,
    Copy,
    Debug,
    Hash,
    Eq,
    PartialEq,
    Ord,
    PartialOrd,
    Encode,
    Decode,
    TypeInfo,
    Serialize,
    Deserialize,
    MaxEncodedLen,
)]
pub enum ChainId {
    Consensus,
    Domain(DomainId),
}

impl ChainId {
    #[inline]
    pub fn consensus_chain_id() -> Self {
        Self::Consensus
    }

    #[inline]
    pub fn is_consensus_chain(&self) -> bool {
        match self {
            ChainId::Consensus => true,
            ChainId::Domain(_) => false,
        }
    }

    #[inline]
    pub fn maybe_domain_chain(&self) -> Option<DomainId> {
        match self {
            ChainId::Consensus => None,
            ChainId::Domain(domain_id) => Some(*domain_id),
        }
    }
}

impl From<u32> for ChainId {
    #[inline]
    fn from(x: u32) -> Self {
        Self::Domain(DomainId::new(x))
    }
}

impl From<DomainId> for ChainId {
    #[inline]
    fn from(x: DomainId) -> Self {
        Self::Domain(x)
    }
}

#[derive(Clone, Debug, Decode, Default, Encode, Eq, PartialEq, TypeInfo)]
pub struct BlockFees<Balance> {
    /// The consensus chain storage fee
    pub consensus_storage_fee: Balance,
    /// The domain execution fee including the storage and compute fee on domain chain,
    /// tip, and the XDM reward.
    pub domain_execution_fee: Balance,
    /// Burned balances on domain chain
    pub burned_balance: Balance,
    /// Rewards for the chain.
    // TODO: remove this before mainnet. Skipping to maintain compatibility with Gemini
    #[codec(skip)]
    pub chain_rewards: BTreeMap<ChainId, Balance>,
}

impl<Balance> BlockFees<Balance>
where
    Balance: CheckedAdd,
{
    pub fn new(
        domain_execution_fee: Balance,
        consensus_storage_fee: Balance,
        burned_balance: Balance,
        chain_rewards: BTreeMap<ChainId, Balance>,
    ) -> Self {
        BlockFees {
            consensus_storage_fee,
            domain_execution_fee,
            burned_balance,
            chain_rewards,
        }
    }

    /// Returns the total fees that was collected and burned on the Domain.
    pub fn total_fees(&self) -> Option<Balance> {
        self.consensus_storage_fee
            .checked_add(&self.domain_execution_fee)
            .and_then(|balance| balance.checked_add(&self.burned_balance))
    }
}

/// Type that holds the transfers(in/out) for a given chain.
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone, Default)]
pub struct Transfers<Balance> {
    /// Total transfers that came into the domain.
    pub transfers_in: BTreeMap<ChainId, Balance>,
    /// Total transfers that went out of the domain.
    pub transfers_out: BTreeMap<ChainId, Balance>,
    /// Total transfers from this domain that were reverted.
    pub rejected_transfers_claimed: BTreeMap<ChainId, Balance>,
    /// Total transfers to this domain that were rejected.
    pub transfers_rejected: BTreeMap<ChainId, Balance>,
}

impl<Balance> Transfers<Balance> {
    pub fn is_valid(&self, chain_id: ChainId) -> bool {
        !self.transfers_rejected.contains_key(&chain_id)
            && !self.transfers_in.contains_key(&chain_id)
            && !self.transfers_out.contains_key(&chain_id)
            && !self.rejected_transfers_claimed.contains_key(&chain_id)
    }
}

// TODO: this runtime constant is not support to update, see https://github.com/autonomys/subspace/issues/2712
// for more detail about the problem and what we need to do to support it.
//
/// Initial tx range = U256::MAX / INITIAL_DOMAIN_TX_RANGE.
pub const INITIAL_DOMAIN_TX_RANGE: u64 = 3;

#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct BundleHeader<Number, Hash, DomainHeader: HeaderT, Balance> {
    /// Proof of bundle producer election.
    pub proof_of_election: ProofOfElection<Hash>,
    /// Execution receipt that should extend the receipt chain or add confirmations
    /// to the head receipt.
    pub receipt: ExecutionReceipt<
        Number,
        Hash,
        HeaderNumberFor<DomainHeader>,
        HeaderHashFor<DomainHeader>,
        Balance,
    >,
    /// The total (estimated) weight of all extrinsics in the bundle.
    ///
    /// Used to prevent overloading the bundle with compute.
    pub estimated_bundle_weight: Weight,
    /// The Merkle root of all new extrinsics included in this bundle.
    pub bundle_extrinsics_root: HeaderHashFor<DomainHeader>,
}

impl<Number: Encode, Hash: Encode, DomainHeader: HeaderT, Balance: Encode>
    BundleHeader<Number, Hash, DomainHeader, Balance>
{
    /// Returns the hash of this header.
    pub fn hash(&self) -> HeaderHashFor<DomainHeader> {
        HeaderHashingFor::<DomainHeader>::hash_of(self)
    }
}

/// Header of bundle.
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct SealedBundleHeader<Number, Hash, DomainHeader: HeaderT, Balance> {
    /// Unsealed header.
    pub header: BundleHeader<Number, Hash, DomainHeader, Balance>,
    /// Signature of the bundle.
    pub signature: OperatorSignature,
}

impl<Number: Encode, Hash: Encode, DomainHeader: HeaderT, Balance: Encode>
    SealedBundleHeader<Number, Hash, DomainHeader, Balance>
{
    /// Constructs a new instance of [`SealedBundleHeader`].
    pub fn new(
        header: BundleHeader<Number, Hash, DomainHeader, Balance>,
        signature: OperatorSignature,
    ) -> Self {
        Self { header, signature }
    }

    /// Returns the hash of the inner unsealed header.
    pub fn pre_hash(&self) -> HeaderHashFor<DomainHeader> {
        self.header.hash()
    }

    /// Returns the hash of this header.
    pub fn hash(&self) -> HeaderHashFor<DomainHeader> {
        HeaderHashingFor::<DomainHeader>::hash_of(self)
    }

    pub fn slot_number(&self) -> u64 {
        self.header.proof_of_election.slot_number
    }
}

/// Domain bundle.
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct Bundle<Extrinsic, Number, Hash, DomainHeader: HeaderT, Balance> {
    /// Sealed bundle header.
    pub sealed_header: SealedBundleHeader<Number, Hash, DomainHeader, Balance>,
    /// The accompanying extrinsics.
    pub extrinsics: Vec<Extrinsic>,
}

impl<Extrinsic: Encode, Number: Encode, Hash: Encode, DomainHeader: HeaderT, Balance: Encode>
    Bundle<Extrinsic, Number, Hash, DomainHeader, Balance>
{
    /// Returns the hash of this bundle.
    pub fn hash(&self) -> H256 {
        BlakeTwo256::hash_of(self)
    }

    /// Returns the domain_id of this bundle.
    pub fn domain_id(&self) -> DomainId {
        self.sealed_header.header.proof_of_election.domain_id
    }

    /// Return the `bundle_extrinsics_root`
    pub fn extrinsics_root(&self) -> HeaderHashFor<DomainHeader> {
        self.sealed_header.header.bundle_extrinsics_root
    }

    /// Return the `operator_id`
    pub fn operator_id(&self) -> OperatorId {
        self.sealed_header.header.proof_of_election.operator_id
    }

    /// Return a reference of the execution receipt.
    pub fn receipt(
        &self,
    ) -> &ExecutionReceipt<
        Number,
        Hash,
        HeaderNumberFor<DomainHeader>,
        HeaderHashFor<DomainHeader>,
        Balance,
    > {
        &self.sealed_header.header.receipt
    }

    /// Consumes [`Bundle`] to extract the execution receipt.
    pub fn into_receipt(
        self,
    ) -> ExecutionReceipt<
        Number,
        Hash,
        HeaderNumberFor<DomainHeader>,
        HeaderHashFor<DomainHeader>,
        Balance,
    > {
        self.sealed_header.header.receipt
    }

    /// Return the bundle size (include header and body) in bytes
    pub fn size(&self) -> u32 {
        self.encoded_size() as u32
    }

    /// Return the bundle body size in bytes
    pub fn body_size(&self) -> u32 {
        self.extrinsics
            .iter()
            .map(|tx| tx.encoded_size() as u32)
            .sum::<u32>()
    }

    pub fn estimated_weight(&self) -> Weight {
        self.sealed_header.header.estimated_bundle_weight
    }

    pub fn slot_number(&self) -> u64 {
        self.sealed_header.header.proof_of_election.slot_number
    }
}

/// Bundle with opaque extrinsics.
pub type OpaqueBundle<Number, Hash, DomainHeader, Balance> =
    Bundle<OpaqueExtrinsic, Number, Hash, DomainHeader, Balance>;

/// List of [`OpaqueBundle`].
pub type OpaqueBundles<Block, DomainHeader, Balance> =
    Vec<OpaqueBundle<NumberFor<Block>, <Block as BlockT>::Hash, DomainHeader, Balance>>;

impl<Extrinsic: Encode, Number, Hash, DomainHeader: HeaderT, Balance>
    Bundle<Extrinsic, Number, Hash, DomainHeader, Balance>
{
    /// Convert a bundle with generic extrinsic to a bundle with opaque extrinsic.
    pub fn into_opaque_bundle(self) -> OpaqueBundle<Number, Hash, DomainHeader, Balance> {
        let Bundle {
            sealed_header,
            extrinsics,
        } = self;
        let opaque_extrinsics = extrinsics
            .into_iter()
            .map(|xt| {
                OpaqueExtrinsic::from_bytes(&xt.encode())
                    .expect("We have just encoded a valid extrinsic; qed")
            })
            .collect();
        OpaqueBundle {
            sealed_header,
            extrinsics: opaque_extrinsics,
        }
    }
}

#[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
pub fn dummy_opaque_bundle<
    Number: Encode,
    Hash: Default + Encode,
    DomainHeader: HeaderT,
    Balance: Encode,
>(
    domain_id: DomainId,
    operator_id: OperatorId,
    receipt: ExecutionReceipt<
        Number,
        Hash,
        HeaderNumberFor<DomainHeader>,
        HeaderHashFor<DomainHeader>,
        Balance,
    >,
) -> OpaqueBundle<Number, Hash, DomainHeader, Balance> {
    use sp_core::crypto::UncheckedFrom;

    let header = BundleHeader {
        proof_of_election: ProofOfElection::dummy(domain_id, operator_id),
        receipt,
        estimated_bundle_weight: Default::default(),
        bundle_extrinsics_root: Default::default(),
    };
    let signature = OperatorSignature::unchecked_from([0u8; 64]);

    OpaqueBundle {
        sealed_header: SealedBundleHeader::new(header, signature),
        extrinsics: Vec::new(),
    }
}

/// A digest of the bundle
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct BundleDigest<Hash> {
    /// The hash of the bundle header
    pub header_hash: Hash,
    /// The Merkle root of all new extrinsics included in this bundle.
    pub extrinsics_root: Hash,
    /// The size of the bundle body in bytes.
    pub size: u32,
}

/// Receipt of a domain block execution.
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct ExecutionReceipt<Number, Hash, DomainNumber, DomainHash, Balance> {
    /// The index of the current domain block that forms the basis of this ER.
    pub domain_block_number: DomainNumber,
    /// The block hash corresponding to `domain_block_number`.
    pub domain_block_hash: DomainHash,
    /// Extrinsic root field of the header of domain block referenced by this ER.
    pub domain_block_extrinsic_root: DomainHash,
    /// The hash of the ER for the last domain block.
    pub parent_domain_block_receipt_hash: DomainHash,
    /// A pointer to the consensus block index which contains all of the bundles that were used to derive and
    /// order all extrinsics executed by the current domain block for this ER.
    pub consensus_block_number: Number,
    /// The block hash corresponding to `consensus_block_number`.
    pub consensus_block_hash: Hash,
    /// All the bundles that being included in the consensus block.
    pub inboxed_bundles: Vec<InboxedBundle<DomainHash>>,
    /// The final state root for the current domain block reflected by this ER.
    ///
    /// Used for verifying storage proofs for domains.
    pub final_state_root: DomainHash,
    /// List of storage roots collected during the domain block execution.
    pub execution_trace: Vec<DomainHash>,
    /// The Merkle root of the execution trace for the current domain block.
    ///
    /// Used for verifying fraud proofs.
    pub execution_trace_root: H256,
    /// Compute and Domain storage fees are shared across operators and Consensus
    /// storage fees are given to the consensus block author.
    pub block_fees: BlockFees<Balance>,
    /// List of transfers from this Domain to other chains
    pub transfers: Transfers<Balance>,
}

impl<Number, Hash, DomainNumber, DomainHash, Balance>
    ExecutionReceipt<Number, Hash, DomainNumber, DomainHash, Balance>
{
    pub fn bundles_extrinsics_roots(&self) -> Vec<&DomainHash> {
        self.inboxed_bundles
            .iter()
            .map(|b| &b.extrinsics_root)
            .collect()
    }

    pub fn valid_bundle_digest_at(&self, index: usize) -> Option<DomainHash>
    where
        DomainHash: Copy,
    {
        match self.inboxed_bundles.get(index).map(|ib| &ib.bundle) {
            Some(BundleValidity::Valid(bundle_digest_hash)) => Some(*bundle_digest_hash),
            _ => None,
        }
    }

    pub fn valid_bundle_digests(&self) -> Vec<DomainHash>
    where
        DomainHash: Copy,
    {
        self.inboxed_bundles
            .iter()
            .filter_map(|b| match b.bundle {
                BundleValidity::Valid(bundle_digest_hash) => Some(bundle_digest_hash),
                BundleValidity::Invalid(_) => None,
            })
            .collect()
    }

    pub fn valid_bundle_indexes(&self) -> Vec<u32> {
        self.inboxed_bundles
            .iter()
            .enumerate()
            .filter_map(|(index, b)| match b.bundle {
                BundleValidity::Valid(_) => Some(index as u32),
                BundleValidity::Invalid(_) => None,
            })
            .collect()
    }
}

impl<
        Number: Encode + Zero,
        Hash: Encode + Default,
        DomainNumber: Encode + Zero,
        DomainHash: Clone + Encode + Default,
        Balance: Encode + Zero + Default,
    > ExecutionReceipt<Number, Hash, DomainNumber, DomainHash, Balance>
{
    /// Returns the hash of this execution receipt.
    pub fn hash<DomainHashing: HashT<Output = DomainHash>>(&self) -> DomainHash {
        DomainHashing::hash_of(self)
    }

    pub fn genesis(
        genesis_state_root: DomainHash,
        genesis_extrinsic_root: DomainHash,
        genesis_domain_block_hash: DomainHash,
    ) -> Self {
        ExecutionReceipt {
            domain_block_number: Zero::zero(),
            domain_block_hash: genesis_domain_block_hash,
            domain_block_extrinsic_root: genesis_extrinsic_root,
            parent_domain_block_receipt_hash: Default::default(),
            consensus_block_hash: Default::default(),
            consensus_block_number: Zero::zero(),
            inboxed_bundles: Vec::new(),
            final_state_root: genesis_state_root.clone(),
            execution_trace: sp_std::vec![genesis_state_root],
            execution_trace_root: Default::default(),
            block_fees: Default::default(),
            transfers: Default::default(),
        }
    }

    #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
    pub fn dummy<DomainHashing>(
        consensus_block_number: Number,
        consensus_block_hash: Hash,
        domain_block_number: DomainNumber,
        parent_domain_block_receipt_hash: DomainHash,
    ) -> ExecutionReceipt<Number, Hash, DomainNumber, DomainHash, Balance>
    where
        DomainHashing: HashT<Output = DomainHash>,
    {
        let execution_trace = sp_std::vec![Default::default(), Default::default()];
        let execution_trace_root = {
            let trace: Vec<[u8; 32]> = execution_trace
                .iter()
                .map(|r: &DomainHash| r.encode().try_into().expect("H256 must fit into [u8; 32]"))
                .collect();
            crate::merkle_tree::MerkleTree::from_leaves(trace.as_slice())
                .root()
                .expect("Compute merkle root of trace should success")
                .into()
        };
        ExecutionReceipt {
            domain_block_number,
            domain_block_hash: Default::default(),
            domain_block_extrinsic_root: Default::default(),
            parent_domain_block_receipt_hash,
            consensus_block_number,
            consensus_block_hash,
            inboxed_bundles: sp_std::vec![InboxedBundle::dummy(Default::default())],
            final_state_root: Default::default(),
            execution_trace,
            execution_trace_root,
            block_fees: Default::default(),
            transfers: Default::default(),
        }
    }
}

#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct ProofOfElection<CHash> {
    /// Domain id.
    pub domain_id: DomainId,
    /// The slot number.
    pub slot_number: u64,
    /// The PoT output for `slot_number`.
    pub proof_of_time: PotOutput,
    /// VRF signature.
    pub vrf_signature: VrfSignature,
    /// Operator index in the OperatorRegistry.
    pub operator_id: OperatorId,
    /// TODO: this field is only used in the bundle equivocation FP which is removed,
    /// also this field is problematic see <https://github.com/autonomys/subspace/issues/2737>
    /// so remove this field before next network
    ///
    /// Consensus block hash at which proof of election was derived.
    pub consensus_block_hash: CHash,
}

impl<CHash> ProofOfElection<CHash> {
    pub fn verify_vrf_signature(
        &self,
        operator_signing_key: &OperatorPublicKey,
    ) -> Result<(), ProofOfElectionError> {
        let global_challenge = self
            .proof_of_time
            .derive_global_randomness()
            .derive_global_challenge(self.slot_number);
        bundle_producer_election::verify_vrf_signature(
            self.domain_id,
            operator_signing_key,
            &self.vrf_signature,
            &global_challenge,
        )
    }

    /// Computes the VRF hash.
    pub fn vrf_hash(&self) -> Blake3Hash {
        let mut bytes = self.vrf_signature.pre_output.encode();
        bytes.append(&mut self.vrf_signature.proof.encode());
        blake3_hash(&bytes)
    }

    pub fn slot_number(&self) -> u64 {
        self.slot_number
    }
}

impl<CHash: Default> ProofOfElection<CHash> {
    #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
    pub fn dummy(domain_id: DomainId, operator_id: OperatorId) -> Self {
        let output_bytes = sp_std::vec![0u8; VrfPreOutput::max_encoded_len()];
        let proof_bytes = sp_std::vec![0u8; VrfProof::max_encoded_len()];
        let vrf_signature = VrfSignature {
            pre_output: VrfPreOutput::decode(&mut output_bytes.as_slice()).unwrap(),
            proof: VrfProof::decode(&mut proof_bytes.as_slice()).unwrap(),
        };
        Self {
            domain_id,
            slot_number: 0u64,
            proof_of_time: PotOutput::default(),
            vrf_signature,
            operator_id,
            consensus_block_hash: Default::default(),
        }
    }
}

/// Singleton receipt submit along when there is a gap between `domain_best_number`
/// and `HeadReceiptNumber`
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct SingletonReceipt<Number, Hash, DomainHeader: HeaderT, Balance> {
    /// Proof of receipt producer election.
    pub proof_of_election: ProofOfElection<Hash>,
    /// The receipt to submit
    pub receipt: ExecutionReceipt<
        Number,
        Hash,
        HeaderNumberFor<DomainHeader>,
        HeaderHashFor<DomainHeader>,
        Balance,
    >,
}

impl<Number: Encode, Hash: Encode, DomainHeader: HeaderT, Balance: Encode>
    SingletonReceipt<Number, Hash, DomainHeader, Balance>
{
    pub fn hash(&self) -> HeaderHashFor<DomainHeader> {
        HeaderHashingFor::<DomainHeader>::hash_of(&self)
    }
}

#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct SealedSingletonReceipt<Number, Hash, DomainHeader: HeaderT, Balance> {
    /// A collection of the receipt.
    pub singleton_receipt: SingletonReceipt<Number, Hash, DomainHeader, Balance>,
    /// Signature of the receipt bundle.
    pub signature: OperatorSignature,
}

impl<Number: Encode, Hash: Encode, DomainHeader: HeaderT, Balance: Encode>
    SealedSingletonReceipt<Number, Hash, DomainHeader, Balance>
{
    /// Returns the `domain_id`
    pub fn domain_id(&self) -> DomainId {
        self.singleton_receipt.proof_of_election.domain_id
    }

    /// Return the `operator_id`
    pub fn operator_id(&self) -> OperatorId {
        self.singleton_receipt.proof_of_election.operator_id
    }

    /// Return the `slot_number` of the `proof_of_election`
    pub fn slot_number(&self) -> u64 {
        self.singleton_receipt.proof_of_election.slot_number
    }

    /// Return the receipt
    pub fn receipt(
        &self,
    ) -> &ExecutionReceipt<
        Number,
        Hash,
        HeaderNumberFor<DomainHeader>,
        HeaderHashFor<DomainHeader>,
        Balance,
    > {
        &self.singleton_receipt.receipt
    }

    /// Consume this `SealedSingletonReceipt` and return the receipt
    pub fn into_receipt(
        self,
    ) -> ExecutionReceipt<
        Number,
        Hash,
        HeaderNumberFor<DomainHeader>,
        HeaderHashFor<DomainHeader>,
        Balance,
    > {
        self.singleton_receipt.receipt
    }

    /// Returns the hash of `SingletonReceipt`
    pub fn pre_hash(&self) -> HeaderHashFor<DomainHeader> {
        HeaderHashingFor::<DomainHeader>::hash_of(&self.singleton_receipt)
    }

    /// Return the encode size of `SealedSingletonReceipt`
    pub fn size(&self) -> u32 {
        self.encoded_size() as u32
    }
}

/// Type that represents an operator allow list for Domains.
#[derive(TypeInfo, Debug, Encode, Decode, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum OperatorAllowList<AccountId: Ord> {
    /// Anyone can operate for this domain.
    Anyone,
    /// Only the specific operators are allowed to operate the domain.
    /// This essentially makes the domain permissioned.
    Operators(BTreeSet<AccountId>),
}

impl<AccountId: Ord> OperatorAllowList<AccountId> {
    /// Returns true if the allow list is either `Anyone` or the operator is part of the allowed operator list.
    pub fn is_operator_allowed(&self, operator: &AccountId) -> bool {
        match self {
            OperatorAllowList::Anyone => true,
            OperatorAllowList::Operators(allowed_operators) => allowed_operators.contains(operator),
        }
    }
}

/// Permissioned actions allowed by either specific accounts or anyone.
#[derive(TypeInfo, Encode, Decode, Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum PermissionedActionAllowedBy<AccountId: Codec + Clone> {
    Accounts(Vec<AccountId>),
    Anyone,
}

impl<AccountId: Codec + PartialEq + Clone> PermissionedActionAllowedBy<AccountId> {
    pub fn is_allowed(&self, who: &AccountId) -> bool {
        match self {
            PermissionedActionAllowedBy::Accounts(accounts) => accounts.contains(who),
            PermissionedActionAllowedBy::Anyone => true,
        }
    }
}

#[derive(TypeInfo, Debug, Encode, Decode, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GenesisDomain<AccountId: Ord, Balance> {
    // Domain runtime items
    pub runtime_name: String,
    pub runtime_type: RuntimeType,
    pub runtime_version: RuntimeVersion,
    pub raw_genesis_storage: Vec<u8>,

    // Domain config items
    pub owner_account_id: AccountId,
    pub domain_name: String,
    pub max_block_size: u32,
    pub max_block_weight: Weight,
    pub bundle_slot_probability: (u64, u64),
    pub target_bundles_per_block: u32,
    pub operator_allow_list: OperatorAllowList<AccountId>,

    // Genesis operator
    pub signing_key: OperatorPublicKey,
    pub minimum_nominator_stake: Balance,
    pub nomination_tax: Percent,

    // initial balances
    pub initial_balances: Vec<(MultiAccountId, Balance)>,
}

/// Types of runtime pallet domains currently supports
#[derive(
    Debug, Default, Encode, Decode, TypeInfo, Clone, PartialEq, Eq, Serialize, Deserialize,
)]
pub enum RuntimeType {
    #[default]
    Evm,
    AutoId,
}

/// Type representing the runtime ID.
pub type RuntimeId = u32;

/// Type representing domain epoch.
pub type EpochIndex = u32;

/// Type representing operator ID
pub type OperatorId = u64;

/// Staking specific hold identifier
#[derive(
    PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
)]
pub enum StakingHoldIdentifier {
    /// Holds all the currently staked funds to an Operator.
    Staked(OperatorId),
}

/// Channel identity.
pub type ChannelId = sp_core::U256;

/// Messenger specific hold identifier
#[derive(
    PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
)]
pub enum MessengerHoldIdentifier {
    /// Holds the current reserved balance for channel opening
    Channel((ChainId, ChannelId)),
}

/// Domains specific Identifier for Balances holds.
#[derive(
    PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
)]
pub enum DomainsHoldIdentifier {
    Staking(StakingHoldIdentifier),
    DomainInstantiation(DomainId),
    StorageFund(OperatorId),
}

/// Domains specific digest item.
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
pub enum DomainDigestItem {
    DomainRuntimeUpgraded(RuntimeId),
    DomainInstantiated(DomainId),
}

/// Domains specific digest items.
pub trait DomainsDigestItem {
    fn domain_runtime_upgrade(runtime_id: RuntimeId) -> Self;
    fn as_domain_runtime_upgrade(&self) -> Option<RuntimeId>;

    fn domain_instantiation(domain_id: DomainId) -> Self;
    fn as_domain_instantiation(&self) -> Option<DomainId>;
}

impl DomainsDigestItem for DigestItem {
    fn domain_runtime_upgrade(runtime_id: RuntimeId) -> Self {
        Self::Other(DomainDigestItem::DomainRuntimeUpgraded(runtime_id).encode())
    }

    fn as_domain_runtime_upgrade(&self) -> Option<RuntimeId> {
        match self.try_to::<DomainDigestItem>(OpaqueDigestItemId::Other) {
            Some(DomainDigestItem::DomainRuntimeUpgraded(runtime_id)) => Some(runtime_id),
            _ => None,
        }
    }

    fn domain_instantiation(domain_id: DomainId) -> Self {
        Self::Other(DomainDigestItem::DomainInstantiated(domain_id).encode())
    }

    fn as_domain_instantiation(&self) -> Option<DomainId> {
        match self.try_to::<DomainDigestItem>(OpaqueDigestItemId::Other) {
            Some(DomainDigestItem::DomainInstantiated(domain_id)) => Some(domain_id),
            _ => None,
        }
    }
}

/// EVM chain Id storage key.
///
/// This and next function should ideally use Host function to fetch the storage key
/// from the domain runtime. But since the Host function is not available at Genesis, we have to
/// assume the storage keys.
/// TODO: once the chain is launched in mainnet, we should use the Host function for all domain instances.
pub(crate) fn evm_chain_id_storage_key() -> StorageKey {
    StorageKey(
        storage_prefix(
            // This is the name used for the `pallet_evm_chain_id` in the `construct_runtime` macro
            // i.e. `EVMChainId: pallet_evm_chain_id = 82,`
            "EVMChainId".as_bytes(),
            // This is the storage item name used inside the `pallet_evm_chain_id`
            "ChainId".as_bytes(),
        )
        .to_vec(),
    )
}

/// Total issuance storage for Domains.
///
/// This function should ideally use Host function to fetch the storage key
/// from the domain runtime. But since the Host function is not available at Genesis, we have to
/// assume the storage keys.
/// TODO: once the chain is launched in mainnet, we should use the Host function for all domain instances.
pub fn domain_total_issuance_storage_key() -> StorageKey {
    StorageKey(
        storage_prefix(
            // This is the name used for the `pallet_balances` in the `construct_runtime` macro
            "Balances".as_bytes(),
            // This is the storage item name used inside the `pallet_balances`
            "TotalIssuance".as_bytes(),
        )
        .to_vec(),
    )
}

/// Account info on frame_system on Domains
///
/// This function should ideally use Host function to fetch the storage key
/// from the domain runtime. But since the Host function is not available at Genesis, we have to
/// assume the storage keys.
/// TODO: once the chain is launched in mainnet, we should use the Host function for all domain instances.
pub fn domain_account_storage_key<AccountId: Encode>(who: AccountId) -> StorageKey {
    let storage_prefix = storage_prefix("System".as_bytes(), "Account".as_bytes());
    let key_hashed = who.using_encoded(Blake2_128Concat::hash);

    let mut final_key = Vec::with_capacity(storage_prefix.len() + key_hashed.len());

    final_key.extend_from_slice(&storage_prefix);
    final_key.extend_from_slice(key_hashed.as_ref());

    StorageKey(final_key)
}

/// The storage key of the `SelfDomainId` storage item in the `pallet-domain-id`
///
/// Any change to the storage item name or the `pallet-domain-id` name used in the `construct_runtime`
/// macro must be reflected here.
pub fn self_domain_id_storage_key() -> StorageKey {
    StorageKey(
        frame_support::storage::storage_prefix(
            // This is the name used for the `pallet-domain-id` in the `construct_runtime` macro
            // i.e. `SelfDomainId: pallet_domain_id = 90`
            "SelfDomainId".as_bytes(),
            // This is the storage item name used inside the `pallet-domain-id`
            "SelfDomainId".as_bytes(),
        )
        .to_vec(),
    )
}

/// `DomainInstanceData` is used to construct the genesis storage of domain instance chain
#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
pub struct DomainInstanceData {
    pub runtime_type: RuntimeType,
    pub raw_genesis: RawGenesis,
}

#[derive(Debug, Decode, Encode, TypeInfo, Clone)]
pub struct DomainBlockLimit {
    /// The max block size for the domain.
    pub max_block_size: u32,
    /// The max block weight for the domain.
    pub max_block_weight: Weight,
}

#[derive(Debug, Decode, Encode, TypeInfo, Clone)]
pub struct DomainBundleLimit {
    /// The max bundle size for the domain.
    pub max_bundle_size: u32,
    /// The max bundle weight for the domain.
    pub max_bundle_weight: Weight,
}

/// Calculates the max bundle weight and size
// See https://forum.subspace.network/t/on-bundle-weight-limits-sum/2277 for more details
// about the formula
pub fn calculate_max_bundle_weight_and_size(
    max_domain_block_size: u32,
    max_domain_block_weight: Weight,
    consensus_slot_probability: (u64, u64),
    bundle_slot_probability: (u64, u64),
) -> Option<DomainBundleLimit> {
    let (expected_bundles_per_block, max_bundle_weight) = calculate_max_bundle_weight(
        max_domain_block_weight,
        consensus_slot_probability,
        bundle_slot_probability,
    )?;
    let max_bundle_size = (max_domain_block_size as u64).checked_div(expected_bundles_per_block)?;

    Some(DomainBundleLimit {
        max_bundle_size: max_bundle_size as u32,
        max_bundle_weight,
    })
}

/// Checks if the signer Id hash is within the tx range
pub fn signer_in_tx_range(bundle_vrf_hash: &U256, signer_id_hash: &U256, tx_range: &U256) -> bool {
    let distance_from_vrf_hash = bidirectional_distance(bundle_vrf_hash, signer_id_hash);
    distance_from_vrf_hash <= (*tx_range / 2)
}

/// Receipt invalidity type.
#[derive(Debug, Decode, Encode, TypeInfo, Clone, PartialEq, Eq)]
pub enum InvalidReceipt {
    /// The field `invalid_bundles` in [`ExecutionReceipt`] is invalid.
    InvalidBundles,
}

#[derive(Debug, Decode, Encode, TypeInfo, Clone, PartialEq, Eq)]
pub enum ReceiptValidity {
    Valid,
    Invalid(InvalidReceipt),
}

/// Bundle invalidity type
///
/// Each type contains the index of the first invalid extrinsic within the bundle
#[derive(Debug, Decode, Encode, TypeInfo, Clone, PartialEq, Eq)]
pub enum InvalidBundleType {
    /// Failed to decode the opaque extrinsic.
    #[codec(index = 0)]
    UndecodableTx(u32),
    /// Transaction is out of the tx range.
    #[codec(index = 1)]
    OutOfRangeTx(u32),
    /// Transaction is illegal (unable to pay the fee, etc).
    #[codec(index = 2)]
    IllegalTx(u32),
    /// Transaction is an invalid XDM.
    #[codec(index = 3)]
    InvalidXDM(u32),
    /// Transaction is an inherent extrinsic.
    #[codec(index = 4)]
    InherentExtrinsic(u32),
    /// The `estimated_bundle_weight` in the bundle header is invalid
    #[codec(index = 5)]
    InvalidBundleWeight,
}

impl InvalidBundleType {
    // Return the checking order of the invalid type
    pub fn checking_order(&self) -> u64 {
        // A bundle can contains multiple invalid extrinsics thus consider the first invalid extrinsic
        // as the invalid type
        let extrinsic_order = match self {
            Self::UndecodableTx(i) => *i,
            Self::OutOfRangeTx(i) => *i,
            Self::IllegalTx(i) => *i,
            Self::InvalidXDM(i) => *i,
            Self::InherentExtrinsic(i) => *i,
            // NOTE: the `InvalidBundleWeight` is targeting the whole bundle not a specific
            // single extrinsic, as `extrinsic_index` is used as the order to check the extrinsic
            // in the bundle returning `u32::MAX` indicate `InvalidBundleWeight` is checked after
            // all the extrinsic in the bundle is checked.
            Self::InvalidBundleWeight => u32::MAX,
        };

        // The extrinsic can be considered as invalid due to multiple `invalid_type` (i.e. an extrinsic
        // can be `OutOfRangeTx` and `IllegalTx` at the same time) thus use the following checking order
        // and consider the first check as the invalid type
        //
        // NOTE: Use explicit number as the order instead of the enum discriminant
        // to avoid changing the order accidentally
        let rule_order = match self {
            Self::UndecodableTx(_) => 1,
            Self::OutOfRangeTx(_) => 2,
            Self::InherentExtrinsic(_) => 3,
            Self::InvalidXDM(_) => 4,
            Self::IllegalTx(_) => 5,
            Self::InvalidBundleWeight => 6,
        };

        // The checking order is a combination of the `extrinsic_order` and `rule_order`
        // it presents as an `u64` where the first 32 bits is the `extrinsic_order` and
        // last 32 bits is the `rule_order` meaning the `extrinsic_order` is checked first
        // then the `rule_order`.
        ((extrinsic_order as u64) << 32) | (rule_order as u64)
    }

    // Return the index of the extrinsic that the invalid type points to
    //
    // NOTE: `InvalidBundleWeight` will return `None` since it is targeting the whole bundle not a
    // specific single extrinsic
    pub fn extrinsic_index(&self) -> Option<u32> {
        match self {
            Self::UndecodableTx(i) => Some(*i),
            Self::OutOfRangeTx(i) => Some(*i),
            Self::IllegalTx(i) => Some(*i),
            Self::InvalidXDM(i) => Some(*i),
            Self::InherentExtrinsic(i) => Some(*i),
            Self::InvalidBundleWeight => None,
        }
    }
}

#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub enum BundleValidity<Hash> {
    // The invalid bundle was originally included in the consensus block but subsequently
    // excluded from execution as invalid and holds the `InvalidBundleType`
    Invalid(InvalidBundleType),
    // The valid bundle's hash of `Vec<(tx_signer, tx_hash)>` of all domain extrinsic being
    // included in the bundle.
    // TODO remove this and use host function to fetch above mentioned data
    Valid(Hash),
}

/// [`InboxedBundle`] represents a bundle that was successfully submitted to the consensus chain
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub struct InboxedBundle<Hash> {
    pub bundle: BundleValidity<Hash>,
    // TODO remove this as the root is already present in the `ExecutionInbox` storage
    pub extrinsics_root: Hash,
}

impl<Hash> InboxedBundle<Hash> {
    pub fn valid(bundle_digest_hash: Hash, extrinsics_root: Hash) -> Self {
        InboxedBundle {
            bundle: BundleValidity::Valid(bundle_digest_hash),
            extrinsics_root,
        }
    }

    pub fn invalid(invalid_bundle_type: InvalidBundleType, extrinsics_root: Hash) -> Self {
        InboxedBundle {
            bundle: BundleValidity::Invalid(invalid_bundle_type),
            extrinsics_root,
        }
    }

    pub fn is_invalid(&self) -> bool {
        matches!(self.bundle, BundleValidity::Invalid(_))
    }

    pub fn invalid_extrinsic_index(&self) -> Option<u32> {
        match &self.bundle {
            BundleValidity::Invalid(invalid_bundle_type) => invalid_bundle_type.extrinsic_index(),
            BundleValidity::Valid(_) => None,
        }
    }

    #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
    pub fn dummy(extrinsics_root: Hash) -> Self
    where
        Hash: Default,
    {
        InboxedBundle {
            bundle: BundleValidity::Valid(Hash::default()),
            extrinsics_root,
        }
    }
}

/// Empty extrinsics root.
pub const EMPTY_EXTRINSIC_ROOT: ExtrinsicsRoot = ExtrinsicsRoot {
    0: hex!("03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314"),
};

pub fn derive_domain_block_hash<DomainHeader: HeaderT>(
    domain_block_number: DomainHeader::Number,
    extrinsics_root: DomainHeader::Hash,
    state_root: DomainHeader::Hash,
    parent_domain_block_hash: DomainHeader::Hash,
    digest: Digest,
) -> DomainHeader::Hash {
    let domain_header = DomainHeader::new(
        domain_block_number,
        extrinsics_root,
        state_root,
        parent_domain_block_hash,
        digest,
    );

    domain_header.hash()
}

/// Represents the extrinsic either as full data or hash of the data.
#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq, TypeInfo)]
pub enum ExtrinsicDigest {
    /// Actual extrinsic data that is inlined since it is less than 33 bytes.
    Data(Vec<u8>),
    /// Extrinsic Hash.
    Hash(H256),
}

impl ExtrinsicDigest {
    pub fn new<Layout: TrieLayout>(ext: Vec<u8>) -> Self
    where
        Layout::Hash: HashT,
        <Layout::Hash as HashT>::Output: Into<H256>,
    {
        if let Some(threshold) = Layout::MAX_INLINE_VALUE {
            if ext.len() >= threshold as usize {
                ExtrinsicDigest::Hash(Layout::Hash::hash(&ext).into())
            } else {
                ExtrinsicDigest::Data(ext)
            }
        } else {
            ExtrinsicDigest::Data(ext)
        }
    }
}

/// Trait that tracks the balances on Domains.
pub trait DomainsTransfersTracker<Balance> {
    type Error;

    /// Initializes the domain balance
    fn initialize_domain_balance(domain_id: DomainId, amount: Balance) -> Result<(), Self::Error>;

    /// Notes a transfer between chains.
    /// Balance on from_chain_id is reduced if it is a domain chain
    fn note_transfer(
        from_chain_id: ChainId,
        to_chain_id: ChainId,
        amount: Balance,
    ) -> Result<(), Self::Error>;

    /// Confirms a transfer between chains.
    fn confirm_transfer(
        from_chain_id: ChainId,
        to_chain_id: ChainId,
        amount: Balance,
    ) -> Result<(), Self::Error>;

    /// Claims a rejected transfer between chains.
    fn claim_rejected_transfer(
        from_chain_id: ChainId,
        to_chain_id: ChainId,
        amount: Balance,
    ) -> Result<(), Self::Error>;

    /// Rejects a initiated transfer between chains.
    fn reject_transfer(
        from_chain_id: ChainId,
        to_chain_id: ChainId,
        amount: Balance,
    ) -> Result<(), Self::Error>;

    /// Reduces a given amount from the domain balance
    fn reduce_domain_balance(domain_id: DomainId, amount: Balance) -> Result<(), Self::Error>;
}

/// Trait to check domain owner.
pub trait DomainOwner<AccountId> {
    /// Returns true if the account is the domain owner.
    fn is_domain_owner(domain_id: DomainId, acc: AccountId) -> bool;
}

impl<AccountId> DomainOwner<AccountId> for () {
    fn is_domain_owner(_domain_id: DomainId, _acc: AccountId) -> bool {
        false
    }
}

/// Post hook to know if the domain had bundle submitted in the previous block.
pub trait DomainBundleSubmitted {
    /// Called in the next block initialisation if there was a domain bundle in the previous block.
    /// This hook if called for domain represents that there is a new domain block for parent consensus block.
    fn domain_bundle_submitted(domain_id: DomainId);
}

impl DomainBundleSubmitted for () {
    fn domain_bundle_submitted(_domain_id: DomainId) {}
}

/// A hook to call after a domain is instantiated
pub trait OnDomainInstantiated {
    fn on_domain_instantiated(domain_id: DomainId);
}

impl OnDomainInstantiated for () {
    fn on_domain_instantiated(_domain_id: DomainId) {}
}

pub type ExecutionReceiptFor<DomainHeader, CBlock, Balance> = ExecutionReceipt<
    NumberFor<CBlock>,
    <CBlock as BlockT>::Hash,
    <DomainHeader as HeaderT>::Number,
    <DomainHeader as HeaderT>::Hash,
    Balance,
>;

/// Domain chains allowlist updates.
#[derive(Default, Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
pub struct DomainAllowlistUpdates {
    /// Chains that are allowed to open channel with this chain.
    pub allow_chains: BTreeSet<ChainId>,
    /// Chains that are not allowed to open channel with this chain.
    pub remove_chains: BTreeSet<ChainId>,
}

impl DomainAllowlistUpdates {
    pub fn is_empty(&self) -> bool {
        self.allow_chains.is_empty() && self.remove_chains.is_empty()
    }

    pub fn clear(&mut self) {
        self.allow_chains.clear();
        self.remove_chains.clear();
    }
}

/// Domain Sudo runtime call.
/// This structure exists because we need to generate a storage proof for FP
/// and Storage shouldn't be None. So each domain must always hold this value even if
/// there is an empty runtime call inside
#[derive(Default, Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
pub struct DomainSudoCall {
    pub maybe_call: Option<Vec<u8>>,
}

impl DomainSudoCall {
    pub fn clear(&mut self) {
        self.maybe_call.take();
    }
}

#[derive(TypeInfo, Debug, Encode, Decode, Clone, PartialEq, Eq)]
pub struct RuntimeObject<Number, Hash> {
    pub runtime_name: String,
    pub runtime_type: RuntimeType,
    pub runtime_upgrades: u32,
    pub instance_count: u32,
    pub hash: Hash,
    // The raw genesis storage that contains the runtime code.
    // NOTE: don't use this field directly but `into_complete_raw_genesis` instead
    pub raw_genesis: RawGenesis,
    pub version: RuntimeVersion,
    pub created_at: Number,
    pub updated_at: Number,
}

/// Digest storage key in frame_system.
/// Unfortunately, the digest storage is private and not possible to derive the key from it directly.
pub fn system_digest_final_key() -> Vec<u8> {
    frame_support::storage::storage_prefix("System".as_ref(), "Digest".as_ref()).to_vec()
}

// TODO: This is used to keep compatible with gemini-3h, remove before next network
/// This is a representation of actual Block Fees storage in pallet-block-fees.
/// Any change in key or value there should be changed here accordingly.
pub fn operator_block_fees_final_key() -> Vec<u8> {
    frame_support::storage::storage_prefix("BlockFees".as_ref(), "CollectedBlockFees".as_ref())
        .to_vec()
}

/// Preimage to verify the proof of ownership of Operator Signing key.
/// Operator owner is used to ensure the signature is used by anyone except
/// the owner of the Signing key pair.
#[derive(Debug, Encode)]
pub struct OperatorSigningKeyProofOfOwnershipData<AccountId> {
    pub operator_owner: AccountId,
}

/// Hook to handle chain rewards.
pub trait OnChainRewards<Balance> {
    fn on_chain_rewards(chain_id: ChainId, reward: Balance);
}

impl<Balance> OnChainRewards<Balance> for () {
    fn on_chain_rewards(_chain_id: ChainId, _reward: Balance) {}
}

sp_api::decl_runtime_apis! {
    /// API necessary for domains pallet.
    #[api_version(6)]
    pub trait DomainsApi<DomainHeader: HeaderT> {
        /// Submits the transaction bundle via an unsigned extrinsic.
        fn submit_bundle_unsigned(opaque_bundle: OpaqueBundle<NumberFor<Block>, Block::Hash, DomainHeader, Balance>);

        // Submit singleton receipt via an unsigned extrinsic.
        fn submit_receipt_unsigned(singleton_receipt: SealedSingletonReceipt<NumberFor<Block>, Block::Hash, DomainHeader, Balance>);

        /// Extract the bundles stored successfully from the given extrinsics.
        fn extract_successful_bundles(
            domain_id: DomainId,
            extrinsics: Vec<Block::Extrinsic>,
        ) -> OpaqueBundles<Block, DomainHeader, Balance>;

        /// Extract bundle from the extrinsic if the extrinsic is `submit_bundle`.
        fn extract_bundle(extrinsic: Block::Extrinsic) -> Option<OpaqueBundle<NumberFor<Block>, Block::Hash, DomainHeader, Balance>>;

        /// Extract the execution receipt stored successfully from the given extrinsics.
        fn extract_receipts(
            domain_id: DomainId,
            extrinsics: Vec<Block::Extrinsic>,
        ) -> Vec<ExecutionReceiptFor<DomainHeader, Block, Balance>>;

        /// Generates a randomness seed for extrinsics shuffling.
        fn extrinsics_shuffling_seed() -> Randomness;

        /// Returns the WASM bundle for given `domain_id`.
        fn domain_runtime_code(domain_id: DomainId) -> Option<Vec<u8>>;

        /// Returns the runtime id for given `domain_id`.
        fn runtime_id(domain_id: DomainId) -> Option<RuntimeId>;

        /// Returns the domain instance data for given `domain_id`.
        fn domain_instance_data(domain_id: DomainId) -> Option<(DomainInstanceData, NumberFor<Block>)>;

        /// Returns the current timestamp at given height.
        fn timestamp() -> Moment;

        /// Returns the current Tx range for the given domain Id.
        fn domain_tx_range(domain_id: DomainId) -> U256;

        /// Return the genesis state root if not pruned
        fn genesis_state_root(domain_id: DomainId) -> Option<H256>;

        /// Returns the best execution chain number.
        fn head_receipt_number(domain_id: DomainId) -> HeaderNumberFor<DomainHeader>;

        /// Returns the block number of oldest unconfirmed execution receipt.
        fn oldest_unconfirmed_receipt_number(domain_id: DomainId) -> Option<HeaderNumberFor<DomainHeader>>;

        /// Returns the domain block limit of the given domain.
        fn domain_block_limit(domain_id: DomainId) -> Option<DomainBlockLimit>;

        /// Returns the domain bundle limit of the given domain.
        fn domain_bundle_limit(domain_id: DomainId) -> Option<DomainBundleLimit>;

        /// Returns true if there are any ERs in the challenge period with non empty extrinsics.
        fn non_empty_er_exists(domain_id: DomainId) -> bool;

        /// Returns the current best number of the domain.
        fn domain_best_number(domain_id: DomainId) -> Option<HeaderNumberFor<DomainHeader>>;

        /// Returns the execution receipt
        fn execution_receipt(receipt_hash: HeaderHashFor<DomainHeader>) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>>;

        /// Returns the current epoch and the next epoch operators of the given domain
        fn domain_operators(domain_id: DomainId) -> Option<(BTreeMap<OperatorId, Balance>, Vec<OperatorId>)>;

        /// Get operator id by signing key
        fn operator_id_by_signing_key(signing_key: OperatorPublicKey) -> Option<OperatorId>;

        /// Returns the execution receipt hash of the given domain and domain block number
        fn receipt_hash(domain_id: DomainId, domain_number: HeaderNumberFor<DomainHeader>) -> Option<HeaderHashFor<DomainHeader>>;

        /// Return the consensus chain byte fee that will used to charge the domain transaction for consensus
        /// chain storage fee
        fn consensus_chain_byte_fee() -> Balance;

        /// Returns the latest confirmed domain block number and hash
        fn latest_confirmed_domain_block(domain_id: DomainId) -> Option<(HeaderNumberFor<DomainHeader>, HeaderHashFor<DomainHeader>)>;

        /// Return if the receipt is exist and pending to prune
        fn is_bad_er_pending_to_prune(domain_id: DomainId, receipt_hash: HeaderHashFor<DomainHeader>) -> bool;

        /// Return the balance of the storage fund account
        fn storage_fund_account_balance(operator_id: OperatorId) -> Balance;

        /// Return if the domain runtime code is upgraded since `at`
        // TODO: change from `is_domain_runtime_updraded_since` to `is_domain_runtime_upgraded_since`
        //  before next network
        fn is_domain_runtime_updraded_since(domain_id: DomainId, at: NumberFor<Block>) -> Option<bool>;

        /// Return domain sudo call.
        fn domain_sudo_call(domain_id: DomainId) -> Option<Vec<u8>>;

        /// Return last confirmed domain block execution receipt.
        fn last_confirmed_domain_block_receipt(domain_id: DomainId) ->Option<ExecutionReceiptFor<DomainHeader, Block, Balance>>;
}

    pub trait BundleProducerElectionApi<Balance: Encode + Decode> {
        fn bundle_producer_election_params(domain_id: DomainId) -> Option<BundleProducerElectionParams<Balance>>;

        fn operator(operator_id: OperatorId) -> Option<(OperatorPublicKey, Balance)>;
    }
}