-
Notifications
You must be signed in to change notification settings - Fork 11
/
lib.rs
2359 lines (2038 loc) · 88.1 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)]
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays},
ensure,
log::info,
pallet_prelude::DispatchResult,
traits::{
Currency, EnsureOrigin, ExistenceRequirement, ExistenceRequirement::KeepAlive, Get,
LockableCurrency, OnUnbalanced, WithdrawReasons,
},
transactional, BoundedVec,
};
use frame_system::{
self as system, ensure_signed,
offchain::{AppCrypto, CreateSignedTransaction, SendSignedTransaction, Signer},
};
pub use pallet::*;
use pallet_authorship;
use pallet_tfgrid;
use pallet_tfgrid::pallet::{InterfaceOf, LocationOf, SerialNumberOf, TfgridNode};
use pallet_tfgrid::types as pallet_tfgrid_types;
use pallet_timestamp as timestamp;
use sp_core::crypto::KeyTypeId;
use sp_runtime::{
traits::{CheckedSub, Convert, SaturatedConversion},
Perbill,
};
use sp_std::prelude::*;
use substrate_fixed::types::U64F64;
use system::offchain::SignMessage;
use tfchain_support::{
traits::{ChangeNode, PublicIpModifier},
types::PublicIP,
};
pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"aura");
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod test_utils;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub mod crypto {
use crate::KEY_TYPE;
use sp_core::sr25519::Signature as Sr25519Signature;
use sp_runtime::{
app_crypto::{app_crypto, sr25519},
traits::Verify,
MultiSignature, MultiSigner,
};
use sp_std::convert::TryFrom;
app_crypto!(sr25519, KEY_TYPE);
pub struct AuthId;
// implemented for ocw-runtime
impl frame_system::offchain::AppCrypto<MultiSigner, MultiSignature> for AuthId {
type RuntimeAppPublic = Public;
type GenericSignature = sp_core::sr25519::Signature;
type GenericPublic = sp_core::sr25519::Public;
}
// implemented for mock runtime in test
impl frame_system::offchain::AppCrypto<<Sr25519Signature as Verify>::Signer, Sr25519Signature>
for AuthId
{
type RuntimeAppPublic = Public;
type GenericSignature = sp_core::sr25519::Signature;
type GenericPublic = sp_core::sr25519::Public;
}
}
pub mod cost;
pub mod migrations;
pub mod name_contract;
pub mod types;
pub mod weights;
#[frame_support::pallet]
pub mod pallet {
use super::types::*;
use super::weights::WeightInfo;
use super::*;
use codec::FullCodec;
use frame_support::pallet_prelude::*;
use frame_support::traits::Hooks;
use frame_support::traits::{Currency, Get, LockIdentifier, LockableCurrency, OnUnbalanced};
use frame_system::pallet_prelude::*;
use sp_core::H256;
use sp_std::{
convert::{TryFrom, TryInto},
fmt::Debug,
vec::Vec,
};
use tfchain_support::traits::{ChangeNode, PublicIpModifier};
pub type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as system::Config>::AccountId>>::Balance;
pub type NegativeImbalanceOf<T> =
<<T as Config>::Currency as Currency<<T as system::Config>::AccountId>>::NegativeImbalance;
pub const GRID_LOCK_ID: LockIdentifier = *b"gridlock";
#[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 CONTRACT_VERSION: u32 = 4;
pub type BillingReferencePeriod<T> = <T as Config>::BillingReferencePeriod;
pub type MaxNodeContractPublicIPs<T> = <T as Config>::MaxNodeContractPublicIps;
pub type MaxDeploymentDataLength<T> = <T as Config>::MaxDeploymentDataLength;
pub type DeploymentDataInput<T> = BoundedVec<u8, MaxDeploymentDataLength<T>>;
pub type DeploymentHash = H256;
pub type NameContractNameOf<T> = <T as Config>::NameContractName;
#[pallet::storage]
#[pallet::getter(fn contracts)]
pub type Contracts<T: Config> = StorageMap<_, Blake2_128Concat, u64, Contract<T>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn contract_billing_information_by_id)]
pub type ContractBillingInformationByID<T: Config> =
StorageMap<_, Blake2_128Concat, u64, ContractBillingInformation, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn node_contract_resources)]
pub type NodeContractResources<T: Config> =
StorageMap<_, Blake2_128Concat, u64, ContractResources, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn node_contract_by_hash)]
pub type ContractIDByNodeIDAndHash<T: Config> =
StorageDoubleMap<_, Blake2_128Concat, u32, Blake2_128Concat, HexHash, u64, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn active_node_contracts)]
// A list of Contract ID's for a given node.
// In this list, all the active contracts are kept for a node.
pub type ActiveNodeContracts<T: Config> =
StorageMap<_, Blake2_128Concat, u32, Vec<u64>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn contract_to_bill_at_block)]
pub type ContractsToBillAt<T: Config> =
StorageMap<_, Blake2_128Concat, u64, Vec<u64>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn contract_number_of_cylces_billed)]
pub type ContractLock<T: Config> =
StorageMap<_, Blake2_128Concat, u64, types::ContractLock<BalanceOf<T>>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn contract_id_by_name_registration)]
pub type ContractIDByNameRegistration<T: Config> =
StorageMap<_, Blake2_128Concat, T::NameContractName, u64, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn active_rent_contracts)]
// A mapping between a Node ID and Contract ID
// If there is an active Rent Contract for a node, the value will be the contract ID
pub type ActiveRentContractForNode<T: Config> =
StorageMap<_, Blake2_128Concat, u32, u64, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn contract_id)]
pub type ContractID<T> = StorageValue<_, u64, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn solution_providers)]
pub type SolutionProviders<T: Config> =
StorageMap<_, Blake2_128Concat, u64, types::SolutionProvider<T::AccountId>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn solution_provider_id)]
pub type SolutionProviderID<T> = StorageValue<_, u64, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn pallet_version)]
pub type PalletVersion<T> = StorageValue<_, types::StorageVersion, ValueQuery>;
#[pallet::type_value]
pub fn DefaultBillingFrequency<T: Config>() -> u64 {
T::BillingFrequency::get()
}
#[pallet::storage]
#[pallet::getter(fn billing_frequency)]
pub type BillingFrequency<T> = StorageValue<_, u64, ValueQuery, DefaultBillingFrequency<T>>;
#[pallet::storage]
#[pallet::getter(fn service_contracts)]
pub type ServiceContracts<T: Config> =
StorageMap<_, Blake2_128Concat, u64, ServiceContract, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn service_contract_id)]
pub type ServiceContractID<T> = StorageValue<_, u64, ValueQuery>;
#[pallet::config]
pub trait Config:
CreateSignedTransaction<Call<Self>>
+ frame_system::Config
+ pallet_timestamp::Config
+ pallet_balances::Config
+ pallet_tfgrid::Config
+ pallet_tft_price::Config
+ pallet_authorship::Config
+ pallet_session::Config
{
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type Currency: LockableCurrency<Self::AccountId>;
/// Handler for the unbalanced decrement when slashing (burning collateral)
type Burn: OnUnbalanced<NegativeImbalanceOf<Self>>;
type StakingPoolAccount: Get<Self::AccountId>;
type BillingFrequency: Get<u64>;
type BillingReferencePeriod: Get<u64>;
type DistributionFrequency: Get<u16>;
type GracePeriod: Get<u64>;
type WeightInfo: WeightInfo;
type NodeChanged: ChangeNode<LocationOf<Self>, InterfaceOf<Self>, SerialNumberOf<Self>>;
type PublicIpModifier: PublicIpModifier;
type AuthorityId: AppCrypto<Self::Public, Self::Signature>;
type Call: From<Call<Self>>;
#[pallet::constant]
type MaxNameContractNameLength: Get<u32>;
#[pallet::constant]
type MaxDeploymentDataLength: Get<u32>;
#[pallet::constant]
type MaxNodeContractPublicIps: Get<u32>;
/// The type of a name contract name.
type NameContractName: FullCodec
+ Debug
+ PartialEq
+ Eq
+ Clone
+ TypeInfo
+ TryFrom<Vec<u8>, Error = Error<Self>>
+ MaxEncodedLen;
type RestrictedOrigin: EnsureOrigin<Self::RuntimeOrigin>;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A contract got created
ContractCreated(types::Contract<T>),
/// A contract was updated
ContractUpdated(types::Contract<T>),
/// A Node contract is canceled
NodeContractCanceled {
contract_id: u64,
node_id: u32,
twin_id: u32,
},
/// A Name contract is canceled
NameContractCanceled {
contract_id: u64,
},
/// IP got reserved by a Node contract
IPsReserved {
contract_id: u64,
public_ips: BoundedVec<PublicIP, MaxNodeContractPublicIPs<T>>,
},
/// IP got freed by a Node contract
IPsFreed {
contract_id: u64,
// public ip as a string
public_ips: BoundedVec<PublicIP, MaxNodeContractPublicIPs<T>>,
},
/// Deprecated event
ContractDeployed(u64, T::AccountId),
/// Deprecated event
ConsumptionReportReceived(types::Consumption),
ContractBilled(types::ContractBill),
/// A certain amount of tokens got burned by a contract
TokensBurned {
contract_id: u64,
amount: BalanceOf<T>,
},
/// Contract resources got updated
UpdatedUsedResources(types::ContractResources),
/// Network resources report received for contract
NruConsumptionReportReceived(types::NruConsumption),
/// a Rent contract is canceled
RentContractCanceled {
contract_id: u64,
},
/// A Contract grace period is triggered
ContractGracePeriodStarted {
contract_id: u64,
node_id: u32,
twin_id: u32,
block_number: u64,
},
/// A Contract grace period was ended
ContractGracePeriodEnded {
contract_id: u64,
node_id: u32,
twin_id: u32,
},
SolutionProviderCreated(types::SolutionProvider<T::AccountId>),
SolutionProviderApproved(u64, bool),
/// A Service contract is created
ServiceContractCreated(types::ServiceContract),
/// A Service contract metadata is set
ServiceContractMetadataSet(types::ServiceContract),
/// A Service contract fees are set
ServiceContractFeesSet(types::ServiceContract),
/// A Service contract is approved
ServiceContractApproved(types::ServiceContract),
/// A Service contract is canceled
ServiceContractCanceled {
service_contract_id: u64,
cause: types::Cause,
},
/// A Service contract is billed
ServiceContractBilled {
service_contract: types::ServiceContract,
bill: types::ServiceContractBill,
amount: BalanceOf<T>,
},
BillingFrequencyChanged(u64),
}
#[pallet::error]
pub enum Error<T> {
TwinNotExists,
NodeNotExists,
FarmNotExists,
FarmHasNotEnoughPublicIPs,
FarmHasNotEnoughPublicIPsFree,
FailedToReserveIP,
FailedToFreeIPs,
ContractNotExists,
TwinNotAuthorizedToUpdateContract,
TwinNotAuthorizedToCancelContract,
NodeNotAuthorizedToDeployContract,
NodeNotAuthorizedToComputeReport,
PricingPolicyNotExists,
ContractIsNotUnique,
NameExists,
NameNotValid,
InvalidContractType,
TFTPriceValueError,
NotEnoughResourcesOnNode,
NodeNotAuthorizedToReportResources,
MethodIsDeprecated,
NodeHasActiveContracts,
NodeHasRentContract,
NodeIsNotDedicated,
NodeNotAvailableToDeploy,
CannotUpdateContractInGraceState,
NumOverflow,
OffchainSignedTxCannotSign,
OffchainSignedTxAlreadySent,
OffchainSignedTxNoLocalAccountAvailable,
NameContractNameTooShort,
NameContractNameTooLong,
InvalidProviderConfiguration,
NoSuchSolutionProvider,
SolutionProviderNotApproved,
TwinNotAuthorized,
ServiceContractNotExists,
ServiceContractCreationNotAllowed,
ServiceContractModificationNotAllowed,
ServiceContractApprovalNotAllowed,
ServiceContractRejectionNotAllowed,
ServiceContractBillingNotApprovedByBoth,
ServiceContractBillingVariableAmountTooHigh,
ServiceContractBillMetadataTooLong,
ServiceContractMetadataTooLong,
ServiceContractNotEnoughFundsToPayBill,
CanOnlyIncreaseFrequency,
IsNotAnAuthority,
WrongAuthority,
}
#[pallet::genesis_config]
pub struct GenesisConfig {
pub billing_frequency: u64,
}
// The default value for the genesis config type.
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self {
billing_frequency: 600,
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
BillingFrequency::<T>::put(self.billing_frequency);
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::create_node_contract())]
pub fn create_node_contract(
origin: OriginFor<T>,
node_id: u32,
deployment_hash: HexHash,
deployment_data: DeploymentDataInput<T>,
public_ips: u32,
solution_provider_id: Option<u64>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_create_node_contract(
account_id,
node_id,
deployment_hash,
deployment_data,
public_ips,
solution_provider_id,
)
}
#[pallet::call_index(1)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn update_node_contract(
origin: OriginFor<T>,
contract_id: u64,
deployment_hash: HexHash,
deployment_data: DeploymentDataInput<T>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_update_node_contract(account_id, contract_id, deployment_hash, deployment_data)
}
#[pallet::call_index(2)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn cancel_contract(
origin: OriginFor<T>,
contract_id: u64,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_cancel_contract(account_id, contract_id, types::Cause::CanceledByUser)
}
// DEPRECATED
#[pallet::call_index(3)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn add_reports(
_origin: OriginFor<T>,
_reports: Vec<types::Consumption>,
) -> DispatchResultWithPostInfo {
// return error
Err(DispatchErrorWithPostInfo::from(Error::<T>::MethodIsDeprecated).into())
}
#[pallet::call_index(4)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn create_name_contract(
origin: OriginFor<T>,
name: Vec<u8>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_create_name_contract(account_id, name)
}
#[pallet::call_index(5)]
#[pallet::weight(<T as Config>::WeightInfo::add_nru_reports())]
pub fn add_nru_reports(
origin: OriginFor<T>,
reports: Vec<types::NruConsumption>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_compute_reports(account_id, reports)
}
#[pallet::call_index(6)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn report_contract_resources(
origin: OriginFor<T>,
contract_resources: Vec<types::ContractResources>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_report_contract_resources(account_id, contract_resources)
}
#[pallet::call_index(7)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn create_rent_contract(
origin: OriginFor<T>,
node_id: u32,
solution_provider_id: Option<u64>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_create_rent_contract(account_id, node_id, solution_provider_id)
}
#[pallet::call_index(8)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn create_solution_provider(
origin: OriginFor<T>,
description: Vec<u8>,
link: Vec<u8>,
providers: Vec<types::Provider<T::AccountId>>,
) -> DispatchResultWithPostInfo {
ensure_signed(origin)?;
Self::_create_solution_provider(description, link, providers)
}
#[pallet::call_index(9)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn approve_solution_provider(
origin: OriginFor<T>,
solution_provider_id: u64,
approve: bool,
) -> DispatchResultWithPostInfo {
<T as Config>::RestrictedOrigin::ensure_origin(origin)?;
Self::_approve_solution_provider(solution_provider_id, approve)
}
#[pallet::call_index(10)]
#[pallet::weight(<T as Config>::WeightInfo::bill_contract_for_block())]
pub fn bill_contract_for_block(
origin: OriginFor<T>,
contract_id: u64,
) -> DispatchResultWithPostInfo {
let _account_id = ensure_signed(origin)?;
Self::bill_contract(contract_id)
}
#[pallet::call_index(11)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn service_contract_create(
origin: OriginFor<T>,
service_account: T::AccountId,
consumer_account: T::AccountId,
) -> DispatchResultWithPostInfo {
let caller_account = ensure_signed(origin)?;
Self::_service_contract_create(caller_account, service_account, consumer_account)
}
#[pallet::call_index(12)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn service_contract_set_metadata(
origin: OriginFor<T>,
service_contract_id: u64,
metadata: Vec<u8>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_service_contract_set_metadata(account_id, service_contract_id, metadata)
}
#[pallet::call_index(13)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn service_contract_set_fees(
origin: OriginFor<T>,
service_contract_id: u64,
base_fee: u64,
variable_fee: u64,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_service_contract_set_fees(
account_id,
service_contract_id,
base_fee,
variable_fee,
)
}
#[pallet::call_index(14)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn service_contract_approve(
origin: OriginFor<T>,
service_contract_id: u64,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_service_contract_approve(account_id, service_contract_id)
}
#[pallet::call_index(15)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn service_contract_reject(
origin: OriginFor<T>,
service_contract_id: u64,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_service_contract_reject(account_id, service_contract_id)
}
#[pallet::call_index(16)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn service_contract_cancel(
origin: OriginFor<T>,
service_contract_id: u64,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
let twin_id = pallet_tfgrid::TwinIdByAccountID::<T>::get(&account_id)
.ok_or(Error::<T>::TwinNotExists)?;
Self::_service_contract_cancel(
twin_id,
service_contract_id,
types::Cause::CanceledByUser,
)
}
#[pallet::call_index(17)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time())]
pub fn service_contract_bill(
origin: OriginFor<T>,
service_contract_id: u64,
variable_amount: u64,
metadata: Vec<u8>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
Self::_service_contract_bill(account_id, service_contract_id, variable_amount, metadata)
}
#[pallet::call_index(18)]
#[pallet::weight(10_000 + T::DbWeight::get().writes(1).ref_time() + T::DbWeight::get().reads(1).ref_time())]
pub fn change_billing_frequency(
origin: OriginFor<T>,
frequency: u64,
) -> DispatchResultWithPostInfo {
<T as Config>::RestrictedOrigin::ensure_origin(origin)?;
Self::_change_billing_frequency(frequency)
}
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn offchain_worker(block_number: T::BlockNumber) {
// Let offchain worker check if there are contracts on the map at current index
// Index being current block number % (mod) Billing Frequency
let current_index: u64 =
block_number.saturated_into::<u64>() % BillingFrequency::<T>::get();
let contracts = ContractsToBillAt::<T>::get(current_index);
if contracts.is_empty() {
log::info!(
"No contracts to bill at block {:?}, index: {:?}",
block_number,
current_index
);
return;
}
log::info!(
"{:?} contracts to bill at block {:?}",
contracts,
block_number
);
for contract_id in contracts {
let _res = Self::bill_contract_using_signed_transaction(contract_id);
}
}
}
}
use crate::types::HexHash;
use pallet::NameContractNameOf;
use sp_std::convert::{TryFrom, TryInto};
// Internal functions of the pallet
impl<T: Config> Pallet<T> {
pub fn _create_node_contract(
account_id: T::AccountId,
node_id: u32,
deployment_hash: HexHash,
deployment_data: DeploymentDataInput<T>,
public_ips: u32,
solution_provider_id: Option<u64>,
) -> DispatchResultWithPostInfo {
let twin_id = pallet_tfgrid::TwinIdByAccountID::<T>::get(&account_id)
.ok_or(Error::<T>::TwinNotExists)?;
let node = pallet_tfgrid::Nodes::<T>::get(node_id).ok_or(Error::<T>::NodeNotExists)?;
let farm = pallet_tfgrid::Farms::<T>::get(node.farm_id).ok_or(Error::<T>::FarmNotExists)?;
if farm.dedicated_farm && !ActiveRentContractForNode::<T>::contains_key(node_id) {
return Err(Error::<T>::NodeNotAvailableToDeploy.into());
}
// If the user is trying to deploy on a node that has an active rent contract
// only allow the user who created the rent contract to actually deploy a node contract on it
if let Some(contract_id) = ActiveRentContractForNode::<T>::get(node_id) {
let rent_contract =
Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;
if rent_contract.twin_id != twin_id {
return Err(Error::<T>::NodeHasRentContract.into());
}
}
// If the contract with hash and node id exists and it's in any other state then
// contractState::Deleted then we don't allow the creation of it.
// If it exists we allow the user to "restore" this contract
if ContractIDByNodeIDAndHash::<T>::contains_key(node_id, &deployment_hash) {
let contract_id = ContractIDByNodeIDAndHash::<T>::get(node_id, &deployment_hash);
let contract = Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;
if !contract.is_state_delete() {
return Err(Error::<T>::ContractIsNotUnique.into());
}
}
let public_ips_list: BoundedVec<PublicIP, MaxNodeContractPublicIPs<T>> =
vec![].try_into().unwrap();
// Prepare NodeContract struct
let node_contract = types::NodeContract {
node_id,
deployment_hash: deployment_hash.clone(),
deployment_data,
public_ips,
public_ips_list,
};
// Create contract
let contract = Self::_create_contract(
twin_id,
types::ContractData::NodeContract(node_contract.clone()),
solution_provider_id,
)?;
let now = <timestamp::Pallet<T>>::get().saturated_into::<u64>() / 1000;
let contract_billing_information = types::ContractBillingInformation {
last_updated: now,
amount_unbilled: 0,
previous_nu_reported: 0,
};
ContractBillingInformationByID::<T>::insert(
contract.contract_id,
contract_billing_information,
);
// Insert contract id by (node_id, hash)
ContractIDByNodeIDAndHash::<T>::insert(node_id, deployment_hash, contract.contract_id);
// Insert contract into active contracts map
let mut node_contracts = ActiveNodeContracts::<T>::get(&node_contract.node_id);
node_contracts.push(contract.contract_id);
ActiveNodeContracts::<T>::insert(&node_contract.node_id, &node_contracts);
Self::deposit_event(Event::ContractCreated(contract));
Ok(().into())
}
pub fn _create_rent_contract(
account_id: T::AccountId,
node_id: u32,
solution_provider_id: Option<u64>,
) -> DispatchResultWithPostInfo {
ensure!(
!ActiveRentContractForNode::<T>::contains_key(node_id),
Error::<T>::NodeHasRentContract
);
let node = pallet_tfgrid::Nodes::<T>::get(node_id).ok_or(Error::<T>::NodeNotExists)?;
ensure!(
pallet_tfgrid::Farms::<T>::contains_key(node.farm_id),
Error::<T>::FarmNotExists
);
let active_node_contracts = ActiveNodeContracts::<T>::get(node_id);
let farm = pallet_tfgrid::Farms::<T>::get(node.farm_id).ok_or(Error::<T>::FarmNotExists)?;
ensure!(
farm.dedicated_farm || active_node_contracts.is_empty(),
Error::<T>::NodeNotAvailableToDeploy
);
// Create contract
let twin_id = pallet_tfgrid::TwinIdByAccountID::<T>::get(&account_id)
.ok_or(Error::<T>::TwinNotExists)?;
let contract = Self::_create_contract(
twin_id,
types::ContractData::RentContract(types::RentContract { node_id }),
solution_provider_id,
)?;
// Insert active rent contract for node
ActiveRentContractForNode::<T>::insert(node_id, contract.contract_id);
Self::deposit_event(Event::ContractCreated(contract));
Ok(().into())
}
// Registers a DNS name for a Twin
// Ensures uniqueness and also checks if it's a valid DNS name
pub fn _create_name_contract(
source: T::AccountId,
name: Vec<u8>,
) -> DispatchResultWithPostInfo {
ensure!(
pallet_tfgrid::TwinIdByAccountID::<T>::contains_key(&source),
Error::<T>::TwinNotExists
);
let twin_id =
pallet_tfgrid::TwinIdByAccountID::<T>::get(&source).ok_or(Error::<T>::TwinNotExists)?;
let valid_name =
NameContractNameOf::<T>::try_from(name).map_err(DispatchErrorWithPostInfo::from)?;
// Validate name uniqueness
ensure!(
!ContractIDByNameRegistration::<T>::contains_key(&valid_name),
Error::<T>::NameExists
);
let name_contract = types::NameContract {
name: valid_name.clone(),
};
let contract = Self::_create_contract(
twin_id,
types::ContractData::NameContract(name_contract),
None,
)?;
ContractIDByNameRegistration::<T>::insert(valid_name, &contract.contract_id);
Self::deposit_event(Event::ContractCreated(contract));
Ok(().into())
}
fn _create_contract(
twin_id: u32,
mut contract_type: types::ContractData<T>,
solution_provider_id: Option<u64>,
) -> Result<types::Contract<T>, DispatchErrorWithPostInfo> {
// Get the Contract ID map and increment
let mut id = ContractID::<T>::get();
id = id + 1;
if let types::ContractData::NodeContract(ref mut nc) = contract_type {
Self::_reserve_ip(id, nc)?;
};
Self::validate_solution_provider(solution_provider_id)?;
let contract = types::Contract {
version: CONTRACT_VERSION,
twin_id,
contract_id: id,
state: types::ContractState::Created,
contract_type,
solution_provider_id,
};
// Start billing frequency loop
// Will always be block now + frequency
Self::insert_contract_to_bill(id);
// insert into contracts map
Contracts::<T>::insert(id, &contract);
// Update Contract ID
ContractID::<T>::put(id);
let now = <timestamp::Pallet<T>>::get().saturated_into::<u64>() / 1000;
let mut contract_lock = types::ContractLock::default();
contract_lock.lock_updated = now;
ContractLock::<T>::insert(id, contract_lock);
Ok(contract)
}
pub fn _update_node_contract(
account_id: T::AccountId,
contract_id: u64,
deployment_hash: HexHash,
deployment_data: DeploymentDataInput<T>,
) -> DispatchResultWithPostInfo {
let mut contract = Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;
let twin =
pallet_tfgrid::Twins::<T>::get(contract.twin_id).ok_or(Error::<T>::TwinNotExists)?;
ensure!(
twin.account_id == account_id,
Error::<T>::TwinNotAuthorizedToUpdateContract
);
// Don't allow updates for contracts that are in grace state
let is_grace_state = matches!(contract.state, types::ContractState::GracePeriod(_));
ensure!(
!is_grace_state,
Error::<T>::CannotUpdateContractInGraceState
);
let mut node_contract = Self::get_node_contract(&contract.clone())?;
// remove and reinsert contract id by node id and hash because that hash can have changed
ContractIDByNodeIDAndHash::<T>::remove(
node_contract.node_id,
node_contract.deployment_hash,
);
ContractIDByNodeIDAndHash::<T>::insert(
node_contract.node_id,
&deployment_hash,
contract_id,
);
node_contract.deployment_hash = deployment_hash;
node_contract.deployment_data = deployment_data;
// override values
contract.contract_type = types::ContractData::NodeContract(node_contract);
let state = contract.state.clone();
Self::_update_contract_state(&mut contract, &state)?;
Self::deposit_event(Event::ContractUpdated(contract));
Ok(().into())
}
pub fn _cancel_contract(
account_id: T::AccountId,
contract_id: u64,
cause: types::Cause,
) -> DispatchResultWithPostInfo {
let mut contract = Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;
let twin =
pallet_tfgrid::Twins::<T>::get(contract.twin_id).ok_or(Error::<T>::TwinNotExists)?;
ensure!(
twin.account_id == account_id,
Error::<T>::TwinNotAuthorizedToCancelContract
);
// If it's a rent contract and it still has active workloads, don't allow cancellation.
if matches!(
&contract.contract_type,
types::ContractData::RentContract(_)
) {
let rent_contract = Self::get_rent_contract(&contract)?;
let active_node_contracts = ActiveNodeContracts::<T>::get(rent_contract.node_id);
ensure!(
active_node_contracts.len() == 0,
Error::<T>::NodeHasActiveContracts
);
}
Self::_update_contract_state(&mut contract, &types::ContractState::Deleted(cause))?;
Self::bill_contract(contract.contract_id)?;
// Remove all associated storage
Self::remove_contract(contract.contract_id);
Ok(().into())
}
pub fn _report_contract_resources(
source: T::AccountId,
contract_resources: Vec<types::ContractResources>,
) -> DispatchResultWithPostInfo {
ensure!(
pallet_tfgrid::TwinIdByAccountID::<T>::contains_key(&source),
Error::<T>::TwinNotExists
);
let twin_id =
pallet_tfgrid::TwinIdByAccountID::<T>::get(&source).ok_or(Error::<T>::TwinNotExists)?;
ensure!(
pallet_tfgrid::NodeIdByTwinID::<T>::contains_key(twin_id),
Error::<T>::NodeNotExists
);
let node_id = pallet_tfgrid::NodeIdByTwinID::<T>::get(twin_id);
for contract_resource in contract_resources {
// we know contract exists, fetch it
// if the node is trying to send garbage data we can throw an error here
if let Some(contract) = Contracts::<T>::get(contract_resource.contract_id) {
let node_contract = Self::get_node_contract(&contract)?;
ensure!(
node_contract.node_id == node_id,
Error::<T>::NodeNotAuthorizedToComputeReport
);
// Do insert
NodeContractResources::<T>::insert(
contract_resource.contract_id,
&contract_resource,
);
// deposit event
Self::deposit_event(Event::UpdatedUsedResources(contract_resource));
}