threefoldtech / tfchain

Threefold Chain.
Apache License 2.0
15 stars 11 forks source link

During the grace period, the NU consumption may be incorrectly accumulated #994

Open sameh-farouk opened 2 months ago

sameh-farouk commented 2 months ago

During the grace period, the NU consumption may be incorrectly accumulated because:

Here are the Details

1. NU Consumption Accumulation

Here, we call calculate_contract_cost_tft() https://github.com/threefoldtech/tfchain/blob/622e7d255b9c76203fba8a316b84b280b59fbba7/substrate-node/pallets/pallet-smart-contract/src/billing.rs#L132-L133

This function calculates the contract cost, then read the NU consumption and adding it to the contract's amount due for the current billing cycle. https://github.com/threefoldtech/tfchain/blob/622e7d255b9c76203fba8a316b84b280b59fbba7/substrate-node/pallets/pallet-smart-contract/src/cost.rs#L88

2. Early Return During Grace Period

If the contract enters a grace period, the function returns early after adding the amount due to the contract lock. However, the ContractBillingInformation (which holds the unbilled NU consumption) is not reset at this point. https://github.com/threefoldtech/tfchain/blob/622e7d255b9c76203fba8a316b84b280b59fbba7/substrate-node/pallets/pallet-smart-contract/src/billing.rs#L177-L182

3. Resetting Unbilled NU Consumption

The unbilled NU consumption is reset in the bill_contract() function, but this reset occurs after the grace period condition has already triggered an early return in the flow. Therefore, the unbilled NU consumption is not reset if the contract is in the grace period, causing the same NU consumption to be added again in the next cycle. https://github.com/threefoldtech/tfchain/blob/622e7d255b9c76203fba8a316b84b280b59fbba7/substrate-node/pallets/pallet-smart-contract/src/billing.rs#L201-L210

sameh-farouk commented 2 months ago

Update: The fix has been implemented as part of a major refactor to the billing. The PR is awaiting review.