-
Notifications
You must be signed in to change notification settings - Fork 11
/
lib.rs
2493 lines (2077 loc) · 88.9 KB
/
lib.rs
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)]
/// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// https://substrate.dev/docs/en/knowledgebase/runtime/frame
use sp_std::prelude::*;
use codec::Encode;
use frame_support::dispatch::DispatchErrorWithPostInfo;
use frame_support::{
dispatch::Pays, ensure, pallet_prelude::DispatchResultWithPostInfo, traits::EnsureOrigin,
BoundedVec,
};
use frame_system::{self as system, ensure_signed};
use hex::FromHex;
use pallet_timestamp as timestamp;
use sp_runtime::SaturatedConversion;
use tfchain_support::{
resources::Resources,
types::{Interface, NodePower as NodePowerType, Power, PowerState, PublicIP},
};
// Re-export pallet items so that they can be accessed from the crate namespace.
pub use pallet::*;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub mod weights;
pub mod types;
pub mod farm;
pub mod interface;
// pub mod ip;
pub mod migrations;
pub mod node;
pub mod terms_cond;
// Definition of the pallet logic, to be aggregated at runtime definition
// through `construct_runtime`.
#[frame_support::pallet]
pub mod pallet {
use super::types;
use super::weights::WeightInfo;
use super::*;
use frame_support::{pallet_prelude::*, Blake2_128Concat};
use frame_support::{traits::ConstU32, BoundedVec};
use frame_system::pallet_prelude::*;
use pallet_timestamp as timestamp;
use sp_std::{convert::TryInto, fmt::Debug, vec::Vec};
use tfchain_support::{
resources::Resources,
traits::{ChangeNode, PublicIpModifier},
types::{
Farm, FarmCertification, FarmingPolicyLimit, Interface, Node, NodeCertification,
PublicConfig, PublicIP, IP4, MAX_DOMAIN_NAME_LENGTH, MAX_GW4_LENGTH, MAX_GW6_LENGTH,
MAX_IP4_LENGTH, MAX_IP6_LENGTH,
},
};
use codec::FullCodec;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
// Version constant that referenced the struct version
pub const TFGRID_ENTITY_VERSION: u32 = 1;
pub const TFGRID_FARM_VERSION: u32 = 4;
pub const TFGRID_TWIN_VERSION: u32 = 1;
pub const TFGRID_NODE_VERSION: u32 = 5;
pub const TFGRID_PRICING_POLICY_VERSION: u32 = 2;
pub const TFGRID_CERTIFICATION_CODE_VERSION: u32 = 1;
pub const TFGRID_FARMING_POLICY_VERSION: u32 = 2;
// Input type for Farm Name
pub type FarmNameInput<T> = BoundedVec<u8, <T as Config>::MaxFarmNameLength>;
// Concrete Farm Name type
pub type FarmNameOf<T> = <T as Config>::FarmName;
// Input type for IP4 (IP & GW)
pub type Ip4Input = BoundedVec<u8, ConstU32<{ MAX_IP4_LENGTH }>>;
pub type Gw4Input = BoundedVec<u8, ConstU32<{ MAX_GW4_LENGTH }>>;
// Input type for IP6 (IP & GW)
pub type Ip6Input = BoundedVec<u8, ConstU32<{ MAX_IP6_LENGTH }>>;
pub type Gw6Input = BoundedVec<u8, ConstU32<{ MAX_GW6_LENGTH }>>;
// Input type for public ip list
pub type PublicIpListInput<T> = BoundedVec<IP4, <T as Config>::MaxFarmPublicIps>;
// Concrete type for public ip list type
pub type PublicIpListOf = BoundedVec<PublicIP, ConstU32<256>>;
// Farm information type
pub type FarmInfoOf<T> = Farm<<T as Config>::FarmName>;
#[pallet::storage]
#[pallet::getter(fn farms)]
pub type Farms<T: Config> = StorageMap<_, Blake2_128Concat, u32, FarmInfoOf<T>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn nodes_by_farm_id)]
pub type NodesByFarmID<T: Config> = StorageMap<_, Blake2_128Concat, u32, Vec<u32>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn farms_by_name_id)]
pub type FarmIdByName<T: Config> = StorageMap<_, Blake2_128Concat, Vec<u8>, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn farm_payout_address_by_farm_id)]
pub type FarmPayoutV2AddressByFarmID<T: Config> =
StorageMap<_, Blake2_128Concat, u32, Vec<u8>, ValueQuery>;
pub type DomainInput = BoundedVec<u8, ConstU32<{ MAX_DOMAIN_NAME_LENGTH }>>;
// Input type for interfaces
pub type InterfaceNameInput = BoundedVec<u8, ConstU32<{ interface::MAX_INTF_NAME_LENGTH }>>;
pub type InterfaceMacInput = BoundedVec<u8, ConstU32<{ interface::INTERFACE_MAC_LENGTH }>>;
pub type InterfaceIpInput = BoundedVec<u8, ConstU32<{ interface::MAX_INTERFACE_IP_LENGTH }>>;
pub type InterfaceIpsInput<T> =
BoundedVec<InterfaceIpInput, <T as Config>::MaxInterfacesLength>;
pub type InterfaceInput<T> = BoundedVec<
Interface<InterfaceNameInput, InterfaceMacInput, InterfaceIpsInput<T>>,
<T as Config>::MaxInterfaceIpsLength,
>;
// Concrete type for interfaces
pub type InterfaceNameOf<T> = <T as Config>::InterfaceName;
pub type InterfaceMacOf<T> = <T as Config>::InterfaceMac;
pub type InterfaceIpOf<T> = <T as Config>::InterfaceIP;
pub type InterfaceIpsOf<T> = BoundedVec<InterfaceIpOf<T>, <T as Config>::MaxInterfaceIpsLength>;
pub type InterfaceOf<T> = Interface<InterfaceNameOf<T>, InterfaceMacOf<T>, InterfaceIpsOf<T>>;
// Input type for location
pub type CityNameInput = BoundedVec<u8, ConstU32<{ node::MAX_CITY_NAME_LENGTH }>>;
pub type CountryNameInput = BoundedVec<u8, ConstU32<{ node::MAX_COUNTRY_NAME_LENGTH }>>;
pub type LatitudeInput = BoundedVec<u8, ConstU32<{ node::MAX_LATITUDE_LENGTH }>>;
pub type LongitudeInput = BoundedVec<u8, ConstU32<{ node::MAX_LONGITUDE_LENGTH }>>;
pub type LocationInput =
types::LocationInput<CityNameInput, CountryNameInput, LatitudeInput, LongitudeInput>;
// Concrete type for location
pub type CityNameOf<T> = <T as Config>::CityName;
pub type CountryNameOf<T> = <T as Config>::CountryName;
pub type LocationOf<T> = <T as Config>::Location;
// Input type for serial number
pub type SerialNumberInput = BoundedVec<u8, ConstU32<{ node::MAX_SERIAL_NUMBER_LENGTH }>>;
// Concrete type for location
pub type SerialNumberOf<T> = <T as Config>::SerialNumber;
// Input type for resources
pub type ResourcesInput = Resources;
// Input type for terms and conditions
pub type DocumentLinkInput = BoundedVec<u8, ConstU32<{ terms_cond::MAX_DOCUMENT_LINK_LENGTH }>>;
pub type DocumentHashInput = BoundedVec<u8, ConstU32<{ terms_cond::MAX_DOCUMENT_HASH_LENGTH }>>;
pub type TermsAndConditionsInput<T> =
types::TermsAndConditionsInput<AccountIdOf<T>, DocumentLinkInput, DocumentHashInput>;
// Concrete type for node
pub type TfgridNode<T> = Node<LocationOf<T>, InterfaceOf<T>, SerialNumberOf<T>>;
// Concrete type for entity
pub type TfgridEntity<T> = types::Entity<AccountIdOf<T>, CityNameOf<T>, CountryNameOf<T>>;
#[pallet::storage]
#[pallet::getter(fn nodes)]
pub type Nodes<T> = StorageMap<_, Blake2_128Concat, u32, TfgridNode<T>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn node_by_twin_id)]
pub type NodeIdByTwinID<T> = StorageMap<_, Blake2_128Concat, u32, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn entities)]
pub type Entities<T: Config> =
StorageMap<_, Blake2_128Concat, u32, TfgridEntity<T>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn entities_by_pubkey_id)]
pub type EntityIdByAccountID<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, u32, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn entities_by_name_id)]
pub type EntityIdByName<T> = StorageMap<_, Blake2_128Concat, Vec<u8>, u32, ValueQuery>;
pub type TwinIndex = u32;
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
type TwinInfoOf<T> = types::Twin<AccountIdOf<T>>;
pub type RelayInput = Option<BoundedVec<u8, ConstU32<{ types::MAX_RELAY_LENGTH }>>>;
pub type PkInput = Option<BoundedVec<u8, ConstU32<{ types::MAX_PK_LENGTH }>>>;
#[pallet::storage]
#[pallet::getter(fn twins)]
pub type Twins<T: Config> =
StorageMap<_, Blake2_128Concat, TwinIndex, TwinInfoOf<T>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn twin_ids_by_pubkey)]
pub type TwinIdByAccountID<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, u32, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn twin_bonded_account)]
pub type TwinBoundedAccountID<T: Config> =
StorageMap<_, Blake2_128Concat, u32, T::AccountId, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn pricing_policies)]
pub type PricingPolicies<T: Config> =
StorageMap<_, Blake2_128Concat, u32, types::PricingPolicy<T::AccountId>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn pricing_policies_by_name_id)]
pub type PricingPolicyIdByName<T> = StorageMap<_, Blake2_128Concat, Vec<u8>, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn farming_policies_map)]
pub type FarmingPoliciesMap<T: Config> =
StorageMap<_, Blake2_128Concat, u32, types::FarmingPolicy<T::BlockNumber>, ValueQuery>;
// Concrete type for location
pub type TermsAndConditionsOf<T> = <T as Config>::TermsAndConditions;
#[pallet::storage]
#[pallet::getter(fn users_terms_and_condition)]
pub type UsersTermsAndConditions<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, Vec<TermsAndConditionsOf<T>>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn allowed_node_certifiers)]
pub type AllowedNodeCertifiers<T: Config> = StorageValue<_, Vec<T::AccountId>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn connection_price)]
pub type ConnectionPrice<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn farm_id)]
pub type FarmID<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn node_id)]
pub type NodeID<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn entity_id)]
pub type EntityID<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn twin_id)]
pub type TwinID<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn pricing_policy_id)]
pub type PricingPolicyID<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn farming_policy_id)]
pub type FarmingPolicyID<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn pallet_version)]
pub type PalletVersion<T> = StorageValue<_, types::StorageVersion, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn zos_version)]
pub type ZosVersion<T> = StorageValue<_, Vec<u8>, ValueQuery>;
// This storage map maps a node ID to a power state, they node can modify this state
// to indicate that it has shut down or came back alive
#[pallet::storage]
#[pallet::getter(fn node_power_state)]
pub type NodePower<T: Config> =
StorageMap<_, Blake2_128Concat, u32, NodePowerType<T::BlockNumber>, ValueQuery>;
#[pallet::config]
pub trait Config: frame_system::Config + pallet_timestamp::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Origin for restricted extrinsics
/// Can be the root or another origin configured in the runtime
type RestrictedOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
type NodeChanged: ChangeNode<
super::LocationOf<Self>,
super::InterfaceOf<Self>,
super::SerialNumberOf<Self>,
>;
type PublicIpModifier: PublicIpModifier;
/// The type of terms and conditions.
type TermsAndConditions: FullCodec
+ Debug
+ PartialEq
+ Clone
+ TypeInfo
+ TryFrom<TermsAndConditionsInput<Self>, Error = Error<Self>>
+ MaxEncodedLen;
/// The type of a farm name.
type FarmName: FullCodec
+ Debug
+ PartialEq
+ Clone
+ TypeInfo
+ TryFrom<FarmNameInput<Self>, Error = Error<Self>>
+ Into<Vec<u8>>
+ MaxEncodedLen;
/// The type of an interface name.
type InterfaceName: FullCodec
+ Debug
+ PartialEq
+ Eq
+ Clone
+ TypeInfo
+ TryFrom<InterfaceNameInput, Error = Error<Self>>
+ MaxEncodedLen;
/// The type of an interface mac address.
type InterfaceMac: FullCodec
+ Debug
+ PartialEq
+ Eq
+ Clone
+ TypeInfo
+ TryFrom<InterfaceMacInput, Error = Error<Self>>
+ MaxEncodedLen;
/// The type of an interface IP.
type InterfaceIP: FullCodec
+ Debug
+ PartialEq
+ Eq
+ Clone
+ TypeInfo
+ TryFrom<InterfaceIpInput, Error = Error<Self>>
+ MaxEncodedLen;
/// The type of a city name.
type CityName: FullCodec
+ Debug
+ Default
+ PartialEq
+ Clone
+ TypeInfo
+ TryFrom<CityNameInput, Error = Error<Self>>
+ MaxEncodedLen;
/// The type of a country name.
type CountryName: FullCodec
+ Debug
+ Default
+ PartialEq
+ Clone
+ TypeInfo
+ TryFrom<CountryNameInput, Error = Error<Self>>
+ MaxEncodedLen;
/// The type of a location.
type Location: FullCodec
+ Debug
+ Default
+ PartialEq
+ Clone
+ TypeInfo
+ TryFrom<LocationInput, Error = Error<Self>>
+ MaxEncodedLen;
/// The type of a serial number.
type SerialNumber: FullCodec
+ Debug
+ Default
+ PartialEq
+ Clone
+ TypeInfo
+ TryFrom<SerialNumberInput, Error = Error<Self>>
+ MaxEncodedLen;
#[pallet::constant]
type MaxFarmNameLength: Get<u32>;
#[pallet::constant]
type MaxFarmPublicIps: Get<u32>;
#[pallet::constant]
type MaxInterfacesLength: Get<u32>;
#[pallet::constant]
type MaxInterfaceIpsLength: Get<u32>;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
FarmStored(FarmInfoOf<T>),
FarmUpdated(FarmInfoOf<T>),
FarmDeleted(u32),
NodeStored(TfgridNode<T>),
NodeUpdated(TfgridNode<T>),
NodeDeleted(u32),
NodeUptimeReported(u32, u64, u64),
NodePublicConfigStored(u32, Option<pallet::PublicConfig>),
EntityStored(TfgridEntity<T>),
EntityUpdated(TfgridEntity<T>),
EntityDeleted(u32),
TwinStored(types::Twin<T::AccountId>),
TwinUpdated(types::Twin<T::AccountId>),
TwinEntityStored(u32, u32, Vec<u8>),
TwinEntityRemoved(u32, u32),
TwinDeleted(u32),
TwinAccountBounded(u32, T::AccountId),
PricingPolicyStored(types::PricingPolicy<T::AccountId>),
// CertificationCodeStored(types::CertificationCodes),
FarmingPolicyStored(types::FarmingPolicy<T::BlockNumber>),
FarmPayoutV2AddressRegistered(u32, Vec<u8>),
FarmMarkedAsDedicated(u32),
ConnectionPriceSet(u32),
NodeCertificationSet(u32, NodeCertification),
NodeCertifierAdded(T::AccountId),
NodeCertifierRemoved(T::AccountId),
FarmingPolicyUpdated(types::FarmingPolicy<T::BlockNumber>),
FarmingPolicySet(u32, Option<FarmingPolicyLimit>),
FarmCertificationSet(u32, FarmCertification),
ZosVersionUpdated(Vec<u8>),
/// Send an event to zero os to change its state
PowerTargetChanged {
farm_id: u32,
node_id: u32,
power_target: Power,
},
PowerStateChanged {
farm_id: u32,
node_id: u32,
power_state: PowerState<T::BlockNumber>,
},
}
#[pallet::error]
pub enum Error<T> {
NoneValue,
StorageOverflow,
CannotCreateNode,
NodeNotExists,
NodeWithTwinIdExists,
CannotDeleteNode,
NodeDeleteNotAuthorized,
NodeUpdateNotAuthorized,
FarmExists,
FarmNotExists,
CannotCreateFarmWrongTwin,
CannotUpdateFarmWrongTwin,
CannotDeleteFarm,
CannotDeleteFarmWithPublicIPs,
CannotDeleteFarmWithNodesAssigned,
CannotDeleteFarmWrongTwin,
IpExists,
IpNotExists,
EntityWithNameExists,
EntityWithPubkeyExists,
EntityNotExists,
EntitySignatureDoesNotMatch,
EntityWithSignatureAlreadyExists,
CannotUpdateEntity,
CannotDeleteEntity,
SignatureLengthIsIncorrect,
TwinExists,
TwinNotExists,
TwinWithPubkeyExists,
CannotCreateTwin,
UnauthorizedToUpdateTwin,
TwinCannotBoundToItself,
PricingPolicyExists,
PricingPolicyNotExists,
PricingPolicyWithDifferentIdExists,
CertificationCodeExists,
FarmingPolicyAlreadyExists,
FarmPayoutAdressAlreadyRegistered,
FarmerDoesNotHaveEnoughFunds,
UserDidNotSignTermsAndConditions,
FarmerDidNotSignTermsAndConditions,
FarmerNotAuthorized,
InvalidFarmName,
AlreadyCertifier,
NotCertifier,
NotAllowedToCertifyNode,
FarmingPolicyNotExists,
RelayTooShort,
RelayTooLong,
InvalidRelay,
FarmNameTooShort,
FarmNameTooLong,
InvalidPublicIP,
PublicIPTooShort,
PublicIPTooLong,
GatewayIPTooShort,
GatewayIPTooLong,
IP4TooShort,
IP4TooLong,
InvalidIP4,
GW4TooShort,
GW4TooLong,
InvalidGW4,
IP6TooShort,
IP6TooLong,
InvalidIP6,
GW6TooShort,
GW6TooLong,
InvalidGW6,
DomainTooShort,
DomainTooLong,
InvalidDomain,
MethodIsDeprecated,
InterfaceNameTooShort,
InterfaceNameTooLong,
InvalidInterfaceName,
InterfaceMacTooShort,
InterfaceMacTooLong,
InvalidMacAddress,
InterfaceIpTooShort,
InterfaceIpTooLong,
InvalidInterfaceIP,
InvalidZosVersion,
FarmingPolicyExpired,
InvalidHRUInput,
InvalidSRUInput,
InvalidCRUInput,
InvalidMRUInput,
LatitudeInputTooShort,
LatitudeInputTooLong,
InvalidLatitudeInput,
LongitudeInputTooShort,
LongitudeInputTooLong,
InvalidLongitudeInput,
CountryNameTooShort,
CountryNameTooLong,
InvalidCountryName,
CityNameTooShort,
CityNameTooLong,
InvalidCityName,
InvalidCountryCityPair,
SerialNumberTooShort,
SerialNumberTooLong,
InvalidSerialNumber,
DocumentLinkInputTooShort,
DocumentLinkInputTooLong,
InvalidDocumentLinkInput,
DocumentHashInputTooShort,
DocumentHashInputTooLong,
InvalidDocumentHashInput,
InvalidPublicConfig,
UnauthorizedToChangePowerTarget,
InvalidRelayAddress,
}
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub su_price_value: u32,
pub su_price_unit: u32,
pub nu_price_value: u32,
pub nu_price_unit: u32,
pub ipu_price_value: u32,
pub ipu_price_unit: u32,
pub cu_price_value: u32,
pub cu_price_unit: u32,
pub domain_name_price_value: u32,
pub unique_name_price_value: u32,
pub foundation_account: Option<T::AccountId>,
pub sales_account: Option<T::AccountId>,
pub discount_for_dedication_nodes: u8,
pub farming_policy_diy_cu: u32,
pub farming_policy_diy_nu: u32,
pub farming_policy_diy_su: u32,
pub farming_policy_diy_ipu: u32,
pub farming_policy_diy_minimal_uptime: u16,
pub farming_policy_certified_cu: u32,
pub farming_policy_certified_nu: u32,
pub farming_policy_certified_su: u32,
pub farming_policy_certified_ipu: u32,
pub farming_policy_certified_minimal_uptime: u16,
pub connection_price: u32,
}
// The default value for the genesis config type.
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
su_price_value: Default::default(),
su_price_unit: Default::default(),
nu_price_value: Default::default(),
nu_price_unit: Default::default(),
ipu_price_value: Default::default(),
ipu_price_unit: Default::default(),
cu_price_value: Default::default(),
cu_price_unit: Default::default(),
domain_name_price_value: Default::default(),
unique_name_price_value: Default::default(),
foundation_account: None,
sales_account: None,
discount_for_dedication_nodes: Default::default(),
farming_policy_diy_cu: Default::default(),
farming_policy_diy_nu: Default::default(),
farming_policy_diy_su: Default::default(),
farming_policy_diy_ipu: Default::default(),
farming_policy_diy_minimal_uptime: Default::default(),
farming_policy_certified_cu: Default::default(),
farming_policy_certified_nu: Default::default(),
farming_policy_certified_su: Default::default(),
farming_policy_certified_ipu: Default::default(),
farming_policy_certified_minimal_uptime: Default::default(),
connection_price: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
let su = types::Policy {
value: self.su_price_value,
unit: types::Unit::from_u32(self.su_price_unit),
};
let cu = types::Policy {
value: self.cu_price_value,
unit: types::Unit::from_u32(self.cu_price_unit),
};
let nu = types::Policy {
value: self.nu_price_value,
unit: types::Unit::from_u32(self.nu_price_unit),
};
let ipu = types::Policy {
value: self.ipu_price_value,
unit: types::Unit::from_u32(self.ipu_price_unit),
};
let unique_name = types::Policy {
value: self.unique_name_price_value,
unit: types::Unit::default(),
};
let domain_name = types::Policy {
value: self.domain_name_price_value,
unit: types::Unit::default(),
};
match &self.foundation_account {
Some(foundation_account) => match &self.sales_account {
Some(certified_sales_account) => {
let p_policy = types::PricingPolicy {
version: 1,
id: 1,
name: "threefold_default_pricing_policy".as_bytes().to_vec(),
su,
cu,
nu,
ipu,
unique_name,
domain_name,
foundation_account: foundation_account.clone(),
certified_sales_account: certified_sales_account.clone(),
discount_for_dedication_nodes: self.discount_for_dedication_nodes,
};
PricingPolicies::<T>::insert(1, p_policy);
PricingPolicyID::<T>::put(1);
}
None => (),
},
None => (),
};
FarmingPoliciesMap::<T>::insert(
1,
types::FarmingPolicy {
version: 1,
id: 1,
name: "threefold_default_diy_farming_policy".as_bytes().to_vec(),
su: self.farming_policy_diy_su,
cu: self.farming_policy_diy_cu,
nu: self.farming_policy_diy_nu,
ipv4: self.farming_policy_diy_ipu,
minimal_uptime: self.farming_policy_diy_minimal_uptime,
policy_created: T::BlockNumber::from(0 as u32),
policy_end: T::BlockNumber::from(0 as u32),
immutable: false,
default: true,
node_certification: NodeCertification::Diy,
farm_certification: FarmCertification::NotCertified,
},
);
FarmingPoliciesMap::<T>::insert(
2,
types::FarmingPolicy {
version: 1,
id: 2,
name: "threefold_default_certified_farming_policy"
.as_bytes()
.to_vec(),
su: self.farming_policy_certified_su,
cu: self.farming_policy_certified_cu,
nu: self.farming_policy_certified_nu,
ipv4: self.farming_policy_certified_ipu,
minimal_uptime: self.farming_policy_certified_minimal_uptime,
policy_created: T::BlockNumber::from(0 as u32),
policy_end: T::BlockNumber::from(0 as u32),
immutable: false,
default: true,
node_certification: NodeCertification::Certified,
farm_certification: FarmCertification::NotCertified,
},
);
FarmingPolicyID::<T>::put(2);
ConnectionPrice::<T>::put(self.connection_price)
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn set_storage_version(
origin: OriginFor<T>,
version: types::StorageVersion,
) -> DispatchResultWithPostInfo {
T::RestrictedOrigin::ensure_origin(origin)?;
PalletVersion::<T>::set(version);
Ok(().into())
}
#[pallet::call_index(1)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn create_farm(
origin: OriginFor<T>,
name: FarmNameInput<T>,
public_ips: PublicIpListInput<T>,
) -> DispatchResultWithPostInfo {
let address = ensure_signed(origin)?;
let mut id = FarmID::<T>::get();
id = id + 1;
let twin_id = TwinIdByAccountID::<T>::get(&address).ok_or(Error::<T>::TwinNotExists)?;
let twin = Twins::<T>::get(twin_id).ok_or(Error::<T>::TwinNotExists)?;
ensure!(
twin.account_id == address,
Error::<T>::CannotCreateFarmWrongTwin
);
ensure!(
!FarmIdByName::<T>::contains_key(name.clone()),
Error::<T>::FarmExists
);
let farm_name = Self::get_farm_name(name.clone())?;
let public_ips_list = Self::get_public_ips(public_ips)?;
let new_farm = Farm {
version: TFGRID_FARM_VERSION,
id,
twin_id,
name: farm_name,
pricing_policy_id: 1,
certification: FarmCertification::NotCertified,
public_ips: public_ips_list,
dedicated_farm: false,
farming_policy_limits: None,
};
Farms::<T>::insert(id, &new_farm);
FarmIdByName::<T>::insert(name.to_vec(), id);
FarmID::<T>::put(id);
Self::deposit_event(Event::FarmStored(new_farm));
Ok(().into())
}
#[pallet::call_index(2)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(3).ref_time() + T::DbWeight::get().reads(2).ref_time())]
pub fn update_farm(
origin: OriginFor<T>,
id: u32,
name: FarmNameInput<T>,
) -> DispatchResultWithPostInfo {
let address = ensure_signed(origin)?;
let new_farm_name = Self::get_farm_name(name.clone())?;
let twin_id = TwinIdByAccountID::<T>::get(&address).ok_or(Error::<T>::TwinNotExists)?;
let mut stored_farm = Farms::<T>::get(id).ok_or(Error::<T>::FarmNotExists)?;
ensure!(
stored_farm.twin_id == twin_id,
Error::<T>::CannotUpdateFarmWrongTwin
);
if FarmIdByName::<T>::contains_key(name.clone()) {
let farm_id_by_new_name = FarmIdByName::<T>::get(name.clone());
// if the user picks a new name but it is taken by another farmer, don't allow it
if farm_id_by_new_name != id {
return Err(Error::<T>::InvalidFarmName.into());
}
}
let name: Vec<u8> = stored_farm.name.into();
// Remove stored farm by name and insert new one
FarmIdByName::<T>::remove(name.clone());
stored_farm.name = new_farm_name;
Farms::<T>::insert(id, &stored_farm);
FarmIdByName::<T>::insert(name, stored_farm.id);
Self::deposit_event(Event::FarmUpdated(stored_farm));
Ok(().into())
}
#[pallet::call_index(3)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time() + T::DbWeight::get().reads(2).ref_time())]
pub fn add_stellar_payout_v2address(
origin: OriginFor<T>,
farm_id: u32,
stellar_address: Vec<u8>,
) -> DispatchResultWithPostInfo {
let address = ensure_signed(origin)?;
let twin_id = TwinIdByAccountID::<T>::get(&address).ok_or(Error::<T>::TwinNotExists)?;
let farm = Farms::<T>::get(farm_id).ok_or(Error::<T>::FarmNotExists)?;
ensure!(
farm.twin_id == twin_id,
Error::<T>::CannotUpdateFarmWrongTwin
);
FarmPayoutV2AddressByFarmID::<T>::insert(&farm_id, &stellar_address);
Self::deposit_event(Event::FarmPayoutV2AddressRegistered(
farm_id,
stellar_address,
));
Ok(().into())
}
#[pallet::call_index(4)]
#[pallet::weight(100_000_000 + T::DbWeight::get().writes(1).ref_time() + T::DbWeight::get().reads(1).ref_time())]
pub fn set_farm_certification(
origin: OriginFor<T>,
farm_id: u32,
certification: FarmCertification,
) -> DispatchResultWithPostInfo {
T::RestrictedOrigin::ensure_origin(origin)?;
let mut stored_farm = Farms::<T>::get(farm_id).ok_or(Error::<T>::FarmNotExists)?;
stored_farm.certification = certification;
Farms::<T>::insert(farm_id, &stored_farm);
Self::deposit_event(Event::FarmCertificationSet(farm_id, certification));
Ok(().into())
}
#[pallet::call_index(5)]
#[pallet::weight(100_000_000 + T::DbWeight::get().writes(1).ref_time() + T::DbWeight::get().reads(2).ref_time())]
pub fn add_farm_ip(
origin: OriginFor<T>,
id: u32,
ip: Ip4Input,
gw: Gw4Input,
) -> DispatchResultWithPostInfo {
let address = ensure_signed(origin)?;
let mut stored_farm = Farms::<T>::get(id).ok_or(Error::<T>::FarmNotExists)?;
let twin = Twins::<T>::get(stored_farm.twin_id).ok_or(Error::<T>::TwinNotExists)?;
ensure!(
twin.account_id == address,
Error::<T>::CannotUpdateFarmWrongTwin
);
// Check if it's a valid IP4
let ip4 = IP4 { ip, gw };
ip4.is_valid().map_err(|_| Error::<T>::InvalidPublicIP)?;
let new_ip = PublicIP {
ip: ip4.ip,
gateway: ip4.gw,
contract_id: 0,
};
match stored_farm
.public_ips
.iter()
.position(|public_ip| public_ip.ip == new_ip.ip)
{
Some(_) => return Err(Error::<T>::IpExists.into()),
None => {
stored_farm
.public_ips
.try_push(new_ip)
.map_err(|_| Error::<T>::InvalidPublicIP)?;
Farms::<T>::insert(stored_farm.id, &stored_farm);
Self::deposit_event(Event::FarmUpdated(stored_farm));
return Ok(().into());
}
};
}
#[pallet::call_index(6)]
#[pallet::weight(100_000_000 + T::DbWeight::get().writes(1).ref_time() + T::DbWeight::get().reads(2).ref_time())]
pub fn remove_farm_ip(
origin: OriginFor<T>,
id: u32,
ip: Ip4Input,
) -> DispatchResultWithPostInfo {
let address = ensure_signed(origin)?;
let mut stored_farm = Farms::<T>::get(id).ok_or(Error::<T>::FarmNotExists)?;
let twin = Twins::<T>::get(stored_farm.twin_id).ok_or(Error::<T>::TwinNotExists)?;
ensure!(
twin.account_id == address,
Error::<T>::CannotUpdateFarmWrongTwin
);
match stored_farm
.public_ips
.iter()
.position(|pubip| pubip.ip == ip && pubip.contract_id == 0)
{
Some(index) => {
stored_farm.public_ips.remove(index);
Farms::<T>::insert(stored_farm.id, &stored_farm);
Self::deposit_event(Event::FarmUpdated(stored_farm));
Ok(().into())
}
None => Err(Error::<T>::IpNotExists.into()),
}
}
#[pallet::call_index(8)]
#[pallet::weight(<T as Config>::WeightInfo::create_node())]
pub fn create_node(
origin: OriginFor<T>,
farm_id: u32,
resources: ResourcesInput,
location: LocationInput,
interfaces: InterfaceInput<T>,
secure_boot: bool,
virtualized: bool,
serial_number: Option<SerialNumberInput>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
ensure!(Farms::<T>::contains_key(farm_id), Error::<T>::FarmNotExists);
ensure!(
TwinIdByAccountID::<T>::contains_key(&account_id),
Error::<T>::TwinNotExists
);