Skip to content

Commit

Permalink
Fix race condition in fee calculation
Browse files Browse the repository at this point in the history
Decimal's Pow function is not thread-safe, so we need to lock it manually.
This is a workaround, we need to remove the lock after Decimal will be fixed
or find a better solution.
shopspring/decimal#368
  • Loading branch information
shermike committed Jan 31, 2025
1 parent 2202b95 commit 4c61a9d
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions nil/internal/execution/fee.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ package execution

import (
"fmt"
"sync"

"github.com/NilFoundation/nil/nil/internal/types"
"github.com/shopspring/decimal"
)

var lock sync.Mutex

func (es *ExecutionState) UpdateBaseFee() error {
acc, err := es.shardAccessor.GetBlock().ByHash(es.PrevBlock)
if err != nil {
Expand Down Expand Up @@ -88,12 +91,22 @@ func toPercentage(gasUsedPrevious, gasLimitAbsolute decimal.Decimal) decimal.Dec

func sigmoid1(gasUsedPercentage, centerSigmoid, smoothingFactor decimal.Decimal) decimal.Decimal {
n := gasUsedPercentage.Sub(centerSigmoid).Div(smoothingFactor)
// Decimal's Pow function is not thread-safe, so we need to lock it
// https://github.com/shopspring/decimal/issues/368
// TODO: This is a workaround, we should find a better solution
lock.Lock()
exp := eNumber.Pow(n)
lock.Unlock()
return decimal.NewFromInt(1).Div(decimal.NewFromInt(1).Add(exp))
}

func sigmoid2(gasUsedPercentage, centerSigmoid, smoothingFactor decimal.Decimal) decimal.Decimal {
n := gasUsedPercentage.Sub(centerSigmoid).Neg().Div(smoothingFactor)
// Decimal's Pow function is not thread-safe, so we need to lock it
// https://github.com/shopspring/decimal/issues/368
// TODO: This is a workaround, we should find a better solution
lock.Lock()
exp := eNumber.Pow(n)
lock.Unlock()
return decimal.NewFromInt(1).Div(decimal.NewFromInt(1).Add(exp))
}

0 comments on commit 4c61a9d

Please sign in to comment.