-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathgrid_contract.rs
829 lines (708 loc) · 30.6 KB
/
grid_contract.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
use crate::*;
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays},
ensure,
pallet_prelude::TypeInfo,
BoundedVec, RuntimeDebugNoBound,
};
use pallet_tfgrid::pallet::{InterfaceOf, LocationOf, SerialNumberOf, TfgridNode};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use sp_std::{marker::PhantomData, vec, vec::Vec};
use tfchain_support::{
traits::{ChangeNode, NodeActiveContracts, PublicIpModifier},
types::PublicIP,
};
impl<T: Config> Pallet<T> {
pub fn _create_node_contract(
account_id: T::AccountId,
node_id: u32,
deployment_hash: types::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)?;
// Don't deploy if node is (or is switched to) standby
let node_power = pallet_tfgrid::NodePower::<T>::get(node_id);
ensure!(
!node_power.is_standby_phase(),
Error::<T>::NodeNotAvailableToDeploy
);
let farm = pallet_tfgrid::Farms::<T>::get(node.farm_id).ok_or(Error::<T>::FarmNotExists)?;
// A node is dedicated (can only be used under a rent contract)
// if it has a dedicated node extra fee or if the farm is dedicated
let node_is_dedicated =
DedicatedNodesExtraFee::<T>::get(node_id) > 0 || farm.dedicated_farm;
// In case there is a rent contract:
// 1. Ensure only the contract owner can deploy, and
// 2. The rent contract is in the 'created' state
// If not, allow to deploy only if node is not dedicated
match ActiveRentContractForNode::<T>::get(node_id) {
Some(contract_id) => {
let rent_contract =
Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;
if rent_contract.twin_id != twin_id || !matches!(rent_contract.state, types::ContractState::Created) {
return Err(Error::<T>::NodeNotAvailableToDeploy.into());
}
}
None => {
if node_is_dedicated {
return Err(Error::<T>::NodeNotAvailableToDeploy.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 = Self::get_current_timestamp_in_secs();
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)?;
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)?;
// Contract is inserted in billing loop ONLY once at contract creation
Self::insert_contract_in_billing_loop(id);
let contract = types::Contract {
version: CONTRACT_VERSION,
twin_id,
contract_id: id,
state: types::ContractState::Created,
contract_type,
solution_provider_id,
};
// insert into contracts map
Contracts::<T>::insert(id, &contract);
// Update Contract ID
ContractID::<T>::put(id);
let now = Self::get_current_timestamp_in_secs();
let mut contract_payment_state = types::ContractPaymentState::default();
contract_payment_state.last_updated_seconds = now;
ContractPaymentState::<T>::insert(id, contract_payment_state);
Ok(contract)
}
pub fn _update_node_contract(
account_id: T::AccountId,
contract_id: u64,
deployment_hash: types::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
);
Self::do_cancel_contract(&mut contract, cause)
}
pub fn _cancel_contract_collective(
contract_id: u64,
cause: types::Cause,
) -> DispatchResultWithPostInfo {
let mut contract = Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;
Self::do_cancel_contract(&mut contract, cause)
}
fn do_cancel_contract(
contract: &mut types::Contract<T>,
cause: types::Cause,
) -> DispatchResultWithPostInfo {
// 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.is_empty(),
Error::<T>::NodeHasActiveContracts
);
}
Self::update_contract_state(contract, &types::ContractState::Deleted(cause))?;
log::debug!(
"Billing for contract {} kicked in due to cancel request",
contract.contract_id
);
Self::bill_contract(contract.contract_id)?;
Ok(().into())
}
pub fn remove_contract(contract_id: u64) -> DispatchResultWithPostInfo {
let contract = Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;
log::debug!("removing contract {}", contract_id);
match contract.contract_type.clone() {
types::ContractData::NodeContract(mut node_contract) => {
if node_contract.public_ips > 0 {
match Self::free_ip(contract_id, &mut node_contract) {
Ok(_) => (),
Err(e) => {
log::info!("error while freeing ips: {:?}", e);
}
}
}
// remove associated storage items
Self::remove_active_node_contract(node_contract.node_id, contract_id);
ContractIDByNodeIDAndHash::<T>::remove(
node_contract.node_id,
&node_contract.deployment_hash,
);
NodeContractResources::<T>::remove(contract_id);
ContractBillingInformationByID::<T>::remove(contract_id);
Self::deposit_event(Event::NodeContractCanceled {
contract_id,
node_id: node_contract.node_id,
twin_id: contract.twin_id,
});
}
types::ContractData::NameContract(name_contract) => {
ContractIDByNameRegistration::<T>::remove(name_contract.name);
Self::deposit_event(Event::NameContractCanceled { contract_id });
}
types::ContractData::RentContract(rent_contract) => {
ActiveRentContractForNode::<T>::remove(rent_contract.node_id);
// Remove all associated active node contracts
let active_node_contracts = ActiveNodeContracts::<T>::get(rent_contract.node_id);
for node_contract in active_node_contracts {
Self::remove_contract(node_contract)?;
}
Self::deposit_event(Event::RentContractCanceled { contract_id });
}
};
Contracts::<T>::remove(contract_id);
ContractPaymentState::<T>::remove(contract_id);
// Clean up contract from billing loop
// This is the only place it should be done
log::debug!(
"cleaning up deleted contract {} from billing loop",
contract_id
);
Self::remove_contract_from_billing_loop(contract_id)?;
Ok(().into())
}
fn remove_active_node_contract(node_id: u32, contract_id: u64) {
let mut contracts = ActiveNodeContracts::<T>::get(&node_id);
match contracts.iter().position(|id| id == &contract_id) {
Some(index) => {
contracts.remove(index);
}
None => (),
};
ActiveNodeContracts::<T>::insert(&node_id, &contracts);
}
// Helper function that updates the contract state and manages storage accordingly
pub fn update_contract_state(
contract: &mut types::Contract<T>,
state: &types::ContractState,
) -> DispatchResultWithPostInfo {
// update the state and save the contract
contract.state = state.clone();
Contracts::<T>::insert(&contract.contract_id, contract.clone());
// if the contract is a name or rent contract, nothing to do left here
match contract.contract_type {
types::ContractData::NameContract(_) => return Ok(().into()),
types::ContractData::RentContract(_) => return Ok(().into()),
_ => (),
};
// if the contract is a node contract
// manage the ActiveNodeContracts map accordingly
let node_contract = Self::get_node_contract(contract)?;
let mut contracts = ActiveNodeContracts::<T>::get(&node_contract.node_id);
match contracts.iter().position(|id| id == &contract.contract_id) {
Some(index) => {
// if the new contract state is delete, remove the contract id from the map
if contract.is_state_delete() {
contracts.remove(index);
}
}
None => {
// if the contract is not present add it to the active contracts map
if state == &types::ContractState::Created {
contracts.push(contract.contract_id);
}
}
};
ActiveNodeContracts::<T>::insert(&node_contract.node_id, &contracts);
Ok(().into())
}
pub fn get_node_contract(
contract: &types::Contract<T>,
) -> Result<types::NodeContract<T>, DispatchErrorWithPostInfo> {
match contract.contract_type.clone() {
types::ContractData::NodeContract(c) => Ok(c),
_ => {
return Err(DispatchErrorWithPostInfo::from(
Error::<T>::InvalidContractType,
))
}
}
}
pub fn get_rent_contract(
contract: &types::Contract<T>,
) -> Result<types::RentContract, DispatchErrorWithPostInfo> {
match contract.contract_type.clone() {
types::ContractData::RentContract(c) => Ok(c),
_ => {
return Err(DispatchErrorWithPostInfo::from(
Error::<T>::InvalidContractType,
))
}
}
}
fn reserve_ip(
contract_id: u64,
node_contract: &mut types::NodeContract<T>,
) -> DispatchResultWithPostInfo {
if node_contract.public_ips == 0 {
return Ok(().into());
}
let node = pallet_tfgrid::Nodes::<T>::get(node_contract.node_id)
.ok_or(Error::<T>::NodeNotExists)?;
let mut farm =
pallet_tfgrid::Farms::<T>::get(node.farm_id).ok_or(Error::<T>::FarmNotExists)?;
log::debug!(
"Number of farm ips {:?}, number of ips to reserve: {:?}",
farm.public_ips.len(),
node_contract.public_ips as usize
);
ensure!(
farm.public_ips.len() >= node_contract.public_ips as usize,
Error::<T>::FarmHasNotEnoughPublicIPs
);
let mut ips: BoundedVec<PublicIP, MaxNodeContractPublicIPs<T>> = vec![].try_into().unwrap();
for i in 0..farm.public_ips.len() {
if ips.len() == node_contract.public_ips as usize {
break;
}
// if an ip has contract id 0 it means it's not reserved
// reserve it now
if farm.public_ips[i].contract_id == 0 {
let mut ip = farm.public_ips[i].clone();
ip.contract_id = contract_id;
farm.public_ips[i] = ip.clone();
ips.try_push(ip).or_else(|_| {
return Err(DispatchErrorWithPostInfo::from(
Error::<T>::FailedToReserveIP,
));
})?;
}
}
// Safeguard check if we actually have the amount of ips we wanted to reserve
ensure!(
ips.len() == node_contract.public_ips as usize,
Error::<T>::FarmHasNotEnoughPublicIPsFree
);
node_contract.public_ips_list = ips.try_into().or_else(|_| {
return Err(DispatchErrorWithPostInfo::from(
Error::<T>::FailedToReserveIP,
));
})?;
// Update the farm with the reserved ips
pallet_tfgrid::Farms::<T>::insert(farm.id, farm);
Ok(().into())
}
fn free_ip(
contract_id: u64,
node_contract: &mut types::NodeContract<T>,
) -> DispatchResultWithPostInfo {
let node = pallet_tfgrid::Nodes::<T>::get(node_contract.node_id)
.ok_or(Error::<T>::NodeNotExists)?;
let mut farm =
pallet_tfgrid::Farms::<T>::get(node.farm_id).ok_or(Error::<T>::FarmNotExists)?;
let mut public_ips: BoundedVec<PublicIP, MaxNodeContractPublicIPs<T>> =
vec![].try_into().unwrap();
for i in 0..farm.public_ips.len() {
// if an ip has contract id 0 it means it's not reserved
// reserve it now
if farm.public_ips[i].contract_id == contract_id {
let mut ip = farm.public_ips[i].clone();
ip.contract_id = 0;
farm.public_ips[i] = ip.clone();
public_ips.try_push(ip).or_else(|_| {
return Err(DispatchErrorWithPostInfo::from(Error::<T>::FailedToFreeIPs));
})?;
}
}
pallet_tfgrid::Farms::<T>::insert(farm.id, farm);
// Emit an event containing the IP's freed for this contract
Self::deposit_event(Event::IPsFreed {
contract_id,
public_ips,
});
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.contract_id, &contract_resource);
// deposit event
Self::deposit_event(Event::UpdatedUsedResources(contract_resource));
}
}
Ok(Pays::No.into())
}
pub fn _compute_reports(
source: T::AccountId,
reports: Vec<types::NruConsumption>,
) -> DispatchResultWithPostInfo {
let twin_id =
pallet_tfgrid::TwinIdByAccountID::<T>::get(&source).ok_or(Error::<T>::TwinNotExists)?;
// fetch the node from the source account (signee)
let node_id = pallet_tfgrid::NodeIdByTwinID::<T>::get(&twin_id);
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)?;
let pricing_policy = pallet_tfgrid::PricingPolicies::<T>::get(farm.pricing_policy_id)
.ok_or(Error::<T>::PricingPolicyNotExists)?;
// validation
for report in &reports {
if !Contracts::<T>::contains_key(report.contract_id) {
continue;
}
if !ContractBillingInformationByID::<T>::contains_key(report.contract_id) {
continue;
}
// we know contract exists, fetch it
// if the node is trying to send garbage data we can throw an error here
let contract =
Contracts::<T>::get(report.contract_id).ok_or(Error::<T>::ContractNotExists)?;
let node_contract = Self::get_node_contract(&contract)?;
ensure!(
node_contract.node_id == node_id,
Error::<T>::NodeNotAuthorizedToComputeReport
);
report.calculate_report_cost_units_usd::<T>(&pricing_policy);
Self::deposit_event(Event::NruConsumptionReportReceived(report.clone()));
}
Ok(Pays::No.into())
}
pub fn _set_dedicated_node_extra_fee(
account_id: T::AccountId,
node_id: u32,
extra_fee: u64,
) -> DispatchResultWithPostInfo {
// Make sure only the farmer that owns this node can set the extra fee
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)?;
ensure!(
twin_id == farm.twin_id,
Error::<T>::UnauthorizedToSetExtraFee
);
// Make sure there is no active node or rent contract on this node
ensure!(
Self::node_has_no_active_contracts(node_id),
Error::<T>::NodeHasActiveContracts
);
// Set fee in mUSD
DedicatedNodesExtraFee::<T>::insert(node_id, extra_fee);
Self::deposit_event(Event::NodeExtraFeeSet { node_id, extra_fee });
Ok(().into())
}
}
impl<T: Config> PublicIpModifier for Pallet<T> {
fn ip_removed(ip: &PublicIP) {
if let Some(mut contract) = Contracts::<T>::get(ip.contract_id) {
match contract.contract_type {
types::ContractData::NodeContract(mut node_contract) => {
if node_contract.public_ips > 0 {
if let Err(e) = Self::free_ip(ip.contract_id, &mut node_contract) {
log::error!("error while freeing ips: {:?}", e);
}
}
contract.contract_type = types::ContractData::NodeContract(node_contract);
Contracts::<T>::insert(ip.contract_id, &contract);
}
_ => {}
}
}
}
}
impl<T: Config> ChangeNode<LocationOf<T>, InterfaceOf<T>, SerialNumberOf<T>> for Pallet<T> {
fn node_changed(_node: Option<&TfgridNode<T>>, _new_node: &TfgridNode<T>) {}
fn node_deleted(node: &TfgridNode<T>) {
// Clean up all active contracts
let active_node_contracts = ActiveNodeContracts::<T>::get(node.id);
for node_contract_id in active_node_contracts {
if let Some(mut contract) = Contracts::<T>::get(node_contract_id) {
// Bill contract
let _ = Self::update_contract_state(
&mut contract,
&types::ContractState::Deleted(types::Cause::CanceledByUser),
);
log::debug!(
"Billing for node contract {} kicked in due to node deletion",
contract.contract_id
);
let res = Self::bill_contract(node_contract_id);
if let Err(e) = res {
log::error!("error in node_deleted hook while billing contract {:?}: {:?}. Contract could be in dirty state", node_contract_id, e);
}
}
}
// First clean up rent contract if it exists
if let Some(rc_id) = ActiveRentContractForNode::<T>::get(node.id) {
if let Some(mut contract) = Contracts::<T>::get(rc_id) {
// Bill contract
let _ = Self::update_contract_state(
&mut contract,
&types::ContractState::Deleted(types::Cause::CanceledByUser),
);
log::debug!(
"Billing for rent contract {} kicked in due to node deletion",
contract.contract_id
);
let res = Self::bill_contract(contract.contract_id);
if let Err(e) = res {
log::error!("error in node_deleted hook while billing contract id {:?}: {:?}. Contract could be in dirty state", rc_id, e);
}
}
}
}
fn node_power_state_changed(node: &TfgridNode<T>) {
// Avoid billing rent contract for standby period
// So update contract lock timestamp when node power state comes back to Up
let node_power = pallet_tfgrid::NodePower::<T>::get(node.id);
if !node_power.is_standby() {
if let Some(rc_id) = ActiveRentContractForNode::<T>::get(node.id) {
let Some(mut contract_payment_state) = ContractPaymentState::<T>::get(rc_id) else {
log::warn!("Contract payment state not exists for contract_id {}", rc_id);
return;
};
let now = Self::get_current_timestamp_in_secs();
contract_payment_state.last_updated_seconds = now;
ContractPaymentState::<T>::insert(rc_id, &contract_payment_state);
log::debug!("Rented node {} is back up, updated contract contract_payment_state for contract {}", node.id, rc_id);
}
}
}
}
impl<T: Config> NodeActiveContracts for Pallet<T> {
fn node_has_no_active_contracts(node_id: u32) -> bool {
ActiveNodeContracts::<T>::get(node_id).is_empty()
&& ActiveRentContractForNode::<T>::get(node_id).is_none()
}
}
/// A Name Contract Name.
#[derive(Encode, Decode, RuntimeDebugNoBound, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
#[codec(mel_bound())]
pub struct NameContractName<T: Config>(
pub(crate) BoundedVec<u8, T::MaxNameContractNameLength>,
PhantomData<(T, T::MaxNameContractNameLength)>,
);
pub const MIN_NAME_LENGTH: u32 = 3;
impl<T: Config> TryFrom<Vec<u8>> for NameContractName<T> {
type Error = Error<T>;
/// Fallible initialization from a provided byte vector if it is below the
/// minimum or exceeds the maximum allowed length or contains invalid ASCII
/// characters.
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
ensure!(
value.len() >= MIN_NAME_LENGTH as usize,
Self::Error::NameContractNameTooShort
);
let bounded_vec: BoundedVec<u8, T::MaxNameContractNameLength> =
BoundedVec::try_from(value).map_err(|_| Self::Error::NameContractNameTooLong)?;
ensure!(
is_valid_name_contract_name(&bounded_vec),
Self::Error::NameNotValid
);
Ok(Self(bounded_vec, PhantomData))
}
}
/// Verify that a given slice can be used as a name contract name.
fn is_valid_name_contract_name(input: &[u8]) -> bool {
input
.iter()
.all(|c| matches!(c, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_'))
}
impl<T: Config> From<NameContractName<T>> for Vec<u8> {
fn from(value: NameContractName<T>) -> Self {
value.0.to_vec()
}
}
// FIXME: did not find a way to automatically implement this.
impl<T: Config> PartialEq for NameContractName<T> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T: Config> Eq for NameContractName<T> {}
// FIXME: did not find a way to automatically implement this.
impl<T: Config> Clone for NameContractName<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1)
}
}