diff --git a/pkg/accounting/accounting.go b/pkg/accounting/accounting.go index 0bae58ee9e0..d910c222a60 100644 --- a/pkg/accounting/accounting.go +++ b/pkg/accounting/accounting.go @@ -30,6 +30,7 @@ var ( // fraction of the refresh rate that is the minimum for monetary settlement // this value is chosen so that tiny payments are prevented while still allowing small payments in environments with lower payment thresholds minimumPaymentDivisor = int64(5) + zero = big.NewInt(0) ) // Interface is the Accounting interface. @@ -282,6 +283,17 @@ func (a *Accounting) Credit(peer swarm.Address, price uint64, originated bool) e a.logger.Tracef("crediting peer %v with price %d, new originated balance is %d", peer, price, nextOriginBalance) + // only consider negative balance for limiting originated balance + if nextBalance.Cmp(zero) > 0 { + nextBalance.Set(zero) + } + + // If originated balance is more into the negative domain, set it to balance + if nextOriginBalance.Cmp(nextBalance) < 0 { + nextOriginBalance.Set(nextBalance) + a.logger.Tracef("decreasing originated balance to peer %v to current balance %d", peer, nextOriginBalance) + } + err = a.store.Put(originatedBalanceKey(peer), nextOriginBalance) if err != nil { return fmt.Errorf("failed to persist originated balance: %w", err) diff --git a/pkg/accounting/accounting_test.go b/pkg/accounting/accounting_test.go index 955c5cdfa6b..0b5562626cf 100644 --- a/pkg/accounting/accounting_test.go +++ b/pkg/accounting/accounting_test.go @@ -138,7 +138,7 @@ func TestAccountingAddOriginatedBalance(t *testing.T) { // inconsequential debit because originated balance is in the positive domain {peer: peer1Addr, price: 100, expectedBalance: 200, originatedBalance: 100}, // originated credit moving the originated balance back into the negative domain, should be limited to the expectedbalance - {peer: peer1Addr, price: -300, expectedBalance: -100, originatedBalance: -200, originatedCredit: true}, + {peer: peer1Addr, price: -300, expectedBalance: -100, originatedBalance: -100, originatedCredit: true}, } for i, booking := range bookings {