-
Notifications
You must be signed in to change notification settings - Fork 338
/
accounting.go
1555 lines (1255 loc) · 53.2 KB
/
accounting.go
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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package accounting provides functionalities needed
// to do per-peer accounting.
package accounting
import (
"context"
"errors"
"fmt"
"math/big"
"strings"
"sync"
"time"
"github.com/ethersphere/bee/pkg/log"
"github.com/ethersphere/bee/pkg/p2p"
"github.com/ethersphere/bee/pkg/pricing"
"github.com/ethersphere/bee/pkg/settlement/pseudosettle"
"github.com/ethersphere/bee/pkg/storage"
"github.com/ethersphere/bee/pkg/swarm"
)
// loggerName is the tree path name of the logger for this package.
const loggerName = "accounting"
const (
linearCheckpointNumber = 1800
linearCheckpointStep = 100
)
var (
_ Interface = (*Accounting)(nil)
balancesPrefix = "accounting_balance_"
balancesSurplusPrefix = "accounting_surplusbalance_"
balancesOriginatedPrefix = "accounting_originatedbalance_"
// 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)
failedSettlementInterval = int64(10) // seconds
)
// Interface is the Accounting interface.
type Interface interface {
// PrepareCredit action to prevent overspending in case of concurrent requests.
PrepareCredit(ctx context.Context, peer swarm.Address, price uint64, originated bool) (Action, error)
// PrepareDebit returns an accounting Action for the later debit to be executed on and to implement shadowing a possibly credited part of reserve on the other side.
PrepareDebit(ctx context.Context, peer swarm.Address, price uint64) (Action, error)
// Balance returns the current balance for the given peer.
Balance(peer swarm.Address) (*big.Int, error)
// SurplusBalance returns the current surplus balance for the given peer.
SurplusBalance(peer swarm.Address) (*big.Int, error)
// Balances returns balances for all known peers.
Balances() (map[string]*big.Int, error)
// CompensatedBalance returns the current balance deducted by current surplus balance for the given peer.
CompensatedBalance(peer swarm.Address) (*big.Int, error)
// CompensatedBalances returns the compensated balances for all known peers.
CompensatedBalances() (map[string]*big.Int, error)
// PeerAccounting returns the associated values for all known peers
PeerAccounting() (map[string]PeerInfo, error)
}
// Action represents an accounting action that can be applied
type Action interface {
// Cleanup cleans up an action. Must be called whether it was applied or not.
Cleanup()
// Apply applies an action
Apply() error
}
// debitAction represents a future debit
type debitAction struct {
accounting *Accounting
price *big.Int
peer swarm.Address
accountingPeer *accountingPeer
applied bool
}
// creditAction represents a future debit
type creditAction struct {
accounting *Accounting
price *big.Int
peer swarm.Address
accountingPeer *accountingPeer
originated bool
applied bool
}
// PayFunc is the function used for async monetary settlement
type PayFunc func(context.Context, swarm.Address, *big.Int)
// RefreshFunc is the function used for sync time-based settlement
type RefreshFunc func(context.Context, swarm.Address, *big.Int)
// Mutex is a drop in replacement for the sync.Mutex
// it will not lock if the context is expired
type Mutex struct {
mu chan struct{}
}
func NewMutex() *Mutex {
return &Mutex{
mu: make(chan struct{}, 1), // unlocked by default
}
}
var ErrFailToLock = errors.New("failed to lock")
func (m *Mutex) TryLock(ctx context.Context) error {
select {
case m.mu <- struct{}{}:
return nil // locked
case <-ctx.Done():
return fmt.Errorf("%w: %w", ctx.Err(), ErrFailToLock)
}
}
func (m *Mutex) Lock() {
m.mu <- struct{}{}
}
func (m *Mutex) Unlock() {
<-m.mu
}
// accountingPeer holds all in-memory accounting information for one peer.
type accountingPeer struct {
lock *Mutex // lock to be held during any accounting action for this peer
reservedBalance *big.Int // amount currently reserved for active peer interaction
shadowReservedBalance *big.Int // amount potentially to be debited for active peer interaction
refreshReservedBalance *big.Int // amount debt potentially decreased during an ongoing refreshment
ghostBalance *big.Int // amount potentially could have been debited for but was not
paymentThreshold *big.Int // the threshold at which the peer expects us to pay
earlyPayment *big.Int // individual early payment threshold calculated from from payment threshold and early payment percentage
paymentThresholdForPeer *big.Int // individual payment threshold at which the peer is expected to pay
disconnectLimit *big.Int // individual disconnect threshold calculated from tolerance and payment threshold for peer
refreshTimestampMilliseconds int64 // last time we attempted and succeeded time-based settlement
refreshReceivedTimestamp int64 // last time we accepted time-based settlement
paymentOngoing bool // indicate if we are currently settling with the peer
refreshOngoing bool // indicates if we are currently refreshing with the peer
lastSettlementFailureTimestamp int64 // time of last unsuccessful attempt to issue a cheque
connected bool // indicates whether the peer is currently connected
fullNode bool // the peer connected as full node or light node
totalDebtRepay *big.Int // since being connected, amount of cumulative debt settled by the peer
thresholdGrowAt *big.Int // cumulative debt to be settled by the peer in order to give threshold upgrade
}
// Accounting is the main implementation of the accounting interface.
type Accounting struct {
// Mutex for accessing the accountingPeers map.
accountingPeersMu sync.Mutex
accountingPeers map[string]*accountingPeer
logger log.Logger
store storage.StateStorer
// The payment threshold in BZZ we communicate to our peers.
paymentThreshold *big.Int
// The amount in percent we let peers exceed the payment threshold before we
// disconnect them.
paymentTolerance int64
// Start settling when reserve plus debt reaches this close to threshold in percent.
earlyPayment int64
// Limit to disconnect peer after going in debt over
disconnectLimit *big.Int
// function used for monetary settlement
payFunction PayFunc
// function used for time settlement
refreshFunction RefreshFunc
// allowance based on time used in pseudo settle
refreshRate *big.Int
lightRefreshRate *big.Int
// lower bound for the value of issued cheques
minimumPayment *big.Int
pricing pricing.Interface
metrics metrics
wg sync.WaitGroup
p2p p2p.Service
timeNow func() time.Time
thresholdGrowStep *big.Int
thresholdGrowChange *big.Int
// light node counterparts
lightPaymentThreshold *big.Int
lightDisconnectLimit *big.Int
lightThresholdGrowStep *big.Int
lightThresholdGrowChange *big.Int
}
var (
// ErrOverdraft denotes the expected debt in Reserve would exceed the payment thresholds.
ErrOverdraft = errors.New("attempted overdraft")
// ErrDisconnectThresholdExceeded denotes a peer has exceeded the disconnect threshold.
ErrDisconnectThresholdExceeded = errors.New("disconnect threshold exceeded")
// ErrPeerNoBalance is the error returned if no balance in store exists for a peer
ErrPeerNoBalance = errors.New("no balance for peer")
// ErrInvalidValue denotes an invalid value read from store
ErrInvalidValue = errors.New("invalid value")
// ErrOverRelease
ErrOverRelease = errors.New("attempting to release more balance than was reserved for peer")
// ErrEnforceRefresh
ErrEnforceRefresh = errors.New("allowance expectation refused")
)
// NewAccounting creates a new Accounting instance with the provided options.
func NewAccounting(
PaymentThreshold *big.Int,
PaymentTolerance,
EarlyPayment int64,
logger log.Logger,
Store storage.StateStorer,
Pricing pricing.Interface,
refreshRate *big.Int,
lightFactor int64,
p2pService p2p.Service,
) (*Accounting, error) {
lightPaymentThreshold := new(big.Int).Div(PaymentThreshold, big.NewInt(lightFactor))
lightRefreshRate := new(big.Int).Div(refreshRate, big.NewInt(lightFactor))
return &Accounting{
accountingPeers: make(map[string]*accountingPeer),
paymentThreshold: new(big.Int).Set(PaymentThreshold),
paymentTolerance: PaymentTolerance,
earlyPayment: EarlyPayment,
disconnectLimit: percentOf(100+PaymentTolerance, PaymentThreshold),
logger: logger.WithName(loggerName).Register(),
store: Store,
pricing: Pricing,
metrics: newMetrics(),
refreshRate: new(big.Int).Set(refreshRate),
lightRefreshRate: new(big.Int).Div(refreshRate, big.NewInt(lightFactor)),
timeNow: time.Now,
minimumPayment: new(big.Int).Div(refreshRate, big.NewInt(minimumPaymentDivisor)),
p2p: p2pService,
thresholdGrowChange: new(big.Int).Mul(refreshRate, big.NewInt(linearCheckpointNumber)),
thresholdGrowStep: new(big.Int).Mul(refreshRate, big.NewInt(linearCheckpointStep)),
lightPaymentThreshold: new(big.Int).Set(lightPaymentThreshold),
lightDisconnectLimit: percentOf(100+PaymentTolerance, lightPaymentThreshold),
lightThresholdGrowChange: new(big.Int).Mul(lightRefreshRate, big.NewInt(linearCheckpointNumber)),
lightThresholdGrowStep: new(big.Int).Mul(lightRefreshRate, big.NewInt(linearCheckpointStep)),
}, nil
}
func (a *Accounting) getIncreasedExpectedDebt(peer swarm.Address, accountingPeer *accountingPeer, bigPrice *big.Int) (*big.Int, *big.Int, error) {
nextReserved := new(big.Int).Add(accountingPeer.reservedBalance, bigPrice)
currentBalance, err := a.Balance(peer)
if err != nil && !errors.Is(err, ErrPeerNoBalance) {
return nil, nil, fmt.Errorf("failed to load balance: %w", err)
}
currentDebt := new(big.Int).Neg(currentBalance)
if currentDebt.Cmp(big.NewInt(0)) < 0 {
currentDebt.SetInt64(0)
}
// debt if all reserved operations are successfully credited excluding debt created by surplus balance
expectedDebt := new(big.Int).Add(currentDebt, nextReserved)
// additionalDebt is debt created by incoming payments which we don't consider debt for monetary settlement purposes
additionalDebt, err := a.SurplusBalance(peer)
if err != nil {
return nil, nil, fmt.Errorf("failed to load surplus balance: %w", err)
}
// debt if all reserved operations are successfully credited including debt created by surplus balance
return new(big.Int).Add(expectedDebt, additionalDebt), currentBalance, nil
}
func (a *Accounting) PrepareCredit(ctx context.Context, peer swarm.Address, price uint64, originated bool) (Action, error) {
accountingPeer := a.getAccountingPeer(peer)
if err := accountingPeer.lock.TryLock(ctx); err != nil {
a.logger.Debug("failed to acquire lock when preparing credit", "error", err)
return nil, err
}
defer accountingPeer.lock.Unlock()
if !accountingPeer.connected {
return nil, errors.New("connection not initialized yet")
}
a.metrics.AccountingReserveCount.Inc()
bigPrice := new(big.Int).SetUint64(price)
threshold := accountingPeer.earlyPayment
// debt if all reserved operations are successfully credited including debt created by surplus balance
increasedExpectedDebt, currentBalance, err := a.getIncreasedExpectedDebt(peer, accountingPeer, bigPrice)
if err != nil {
return nil, err
}
// debt if all reserved operations are successfully credited and all shadow reserved operations are debited including debt created by surplus balance
// in other words this the debt the other node sees if everything pending is successful
increasedExpectedDebtReduced := new(big.Int).Sub(increasedExpectedDebt, accountingPeer.shadowReservedBalance)
// If our expected debt reduced by what could have been credited on the other side already is less than earlyPayment away from our payment threshold
// and we are actually in debt, trigger settlement.
// we pay early to avoid needlessly blocking request later when concurrent requests occur and we are already close to the payment threshold.
if increasedExpectedDebtReduced.Cmp(threshold) >= 0 && currentBalance.Cmp(big.NewInt(0)) < 0 {
err = a.settle(peer, accountingPeer)
if err != nil {
a.metrics.SettleErrorCount.Inc()
return nil, fmt.Errorf("failed to settle with peer %v: %w", peer, err)
}
increasedExpectedDebt, _, err = a.getIncreasedExpectedDebt(peer, accountingPeer, bigPrice)
if err != nil {
return nil, err
}
}
timeElapsedInSeconds := (a.timeNow().UnixMilli() - accountingPeer.refreshTimestampMilliseconds) / 1000
if timeElapsedInSeconds > 1 {
timeElapsedInSeconds = 1
}
refreshDue := new(big.Int).Mul(big.NewInt(timeElapsedInSeconds), a.refreshRate)
overdraftLimit := new(big.Int).Add(accountingPeer.paymentThreshold, refreshDue)
// if expectedDebt would still exceed the paymentThreshold at this point block this request
// this can happen if there is a large number of concurrent requests to the same peer
if increasedExpectedDebt.Cmp(overdraftLimit) > 0 {
a.metrics.AccountingBlocksCount.Inc()
return nil, ErrOverdraft
}
accountingPeer.reservedBalance = new(big.Int).Add(accountingPeer.reservedBalance, bigPrice)
return &creditAction{
accounting: a,
price: bigPrice,
peer: peer,
accountingPeer: accountingPeer,
originated: originated,
}, nil
}
func (c *creditAction) Apply() error {
loggerV2 := c.accounting.logger.V(2).Register()
c.accountingPeer.lock.Lock()
defer c.accountingPeer.lock.Unlock()
// debt if all reserved operations are successfully credited including debt created by surplus balance
increasedExpectedDebt, currentBalance, err := c.accounting.getIncreasedExpectedDebt(c.peer, c.accountingPeer, c.price)
if err != nil {
if !errors.Is(err, ErrPeerNoBalance) {
return fmt.Errorf("failed to load balance: %w", err)
}
}
// Calculate next balance by decreasing current balance with the price we credit
nextBalance := new(big.Int).Sub(currentBalance, c.price)
loggerV2.Debug("credit action apply", "crediting_peer_address", c.peer, "price", c.price, "new_balance", nextBalance)
err = c.accounting.store.Put(peerBalanceKey(c.peer), nextBalance)
if err != nil {
return fmt.Errorf("failed to persist balance: %w", err)
}
c.accounting.metrics.TotalCreditedAmount.Add(float64(c.price.Int64()))
c.accounting.metrics.CreditEventsCount.Inc()
if c.price.Cmp(c.accountingPeer.reservedBalance) > 0 {
c.accounting.logger.Error(nil, "attempting to release more balance than was reserved for peer", "peer_address", c.peer)
c.accountingPeer.reservedBalance.SetUint64(0)
} else {
c.accountingPeer.reservedBalance.Sub(c.accountingPeer.reservedBalance, c.price)
}
c.applied = true
if !c.originated {
// debt if all reserved operations are successfully credited and all shadow reserved operations are debited including debt created by surplus balance
// in other words this the debt the other node sees if everything pending is successful
increasedExpectedDebtReduced := new(big.Int).Sub(increasedExpectedDebt, c.accountingPeer.shadowReservedBalance)
if increasedExpectedDebtReduced.Cmp(c.accountingPeer.earlyPayment) > 0 {
err = c.accounting.settle(c.peer, c.accountingPeer)
if err != nil {
c.accounting.logger.Error(err, "failed to settle with credited peer", "peer_address", c.peer)
}
}
return nil
}
originBalance, err := c.accounting.OriginatedBalance(c.peer)
if err != nil && !errors.Is(err, ErrPeerNoBalance) {
return fmt.Errorf("failed to load originated balance: %w", err)
}
// Calculate next balance by decreasing current balance with the price we credit
nextOriginBalance := new(big.Int).Sub(originBalance, c.price)
loggerV2.Debug("credit action apply", "crediting_peer_address", c.peer, "price", c.price, "new_originated_balance", nextOriginBalance)
zero := big.NewInt(0)
// 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)
loggerV2.Debug("credit action apply; decreasing originated balance", "crediting_peer_address", c.peer, "current_balance", nextOriginBalance)
}
err = c.accounting.store.Put(originatedBalanceKey(c.peer), nextOriginBalance)
if err != nil {
return fmt.Errorf("failed to persist originated balance: %w", err)
}
c.accounting.metrics.TotalOriginatedCreditedAmount.Add(float64(c.price.Int64()))
c.accounting.metrics.OriginatedCreditEventsCount.Inc()
// debt if all reserved operations are successfully credited and all shadow reserved operations are debited including debt created by surplus balance
// in other words this the debt the other node sees if everything pending is successful
increasedExpectedDebtReduced := new(big.Int).Sub(increasedExpectedDebt, c.accountingPeer.shadowReservedBalance)
if increasedExpectedDebtReduced.Cmp(c.accountingPeer.earlyPayment) > 0 {
err = c.accounting.settle(c.peer, c.accountingPeer)
if err != nil {
c.accounting.logger.Error(err, "failed to settle with credited peer", "peer_address", c.peer)
}
}
return nil
}
func (c *creditAction) Cleanup() {
if c.applied {
return
}
c.accountingPeer.lock.Lock()
defer c.accountingPeer.lock.Unlock()
if c.price.Cmp(c.accountingPeer.reservedBalance) > 0 {
c.accounting.logger.Error(nil, "attempting to release more balance than was reserved for peer", "peer_address", c.peer)
c.accountingPeer.reservedBalance.SetUint64(0)
} else {
c.accountingPeer.reservedBalance.Sub(c.accountingPeer.reservedBalance, c.price)
}
}
// Settle all debt with a peer. The lock on the accountingPeer must be held when
// called.
func (a *Accounting) settle(peer swarm.Address, balance *accountingPeer) error {
now := a.timeNow()
timeElapsedInMilliseconds := now.UnixMilli() - balance.refreshTimestampMilliseconds
// get debt towards peer decreased by any amount that is to be debited soon
paymentAmount, err := a.shadowBalance(peer, balance)
if err != nil {
return err
}
// Don't do anything if there is not enough actual debt
// This might be the case if the peer owes us and the total reserve for a peer exceeds the payment threshold.
// Minimum amount to trigger settlement for is 1 * refresh rate to avoid ineffective use of refreshments
if paymentAmount.Cmp(a.refreshRate) >= 0 {
// Only trigger refreshment if last refreshment finished at least 1000 milliseconds ago
// This is to avoid a peer refusing refreshment because not enough time passed since last refreshment
if timeElapsedInMilliseconds > 999 {
if !balance.refreshOngoing {
balance.refreshOngoing = true
go a.refreshFunction(context.Background(), peer, paymentAmount)
}
}
if a.payFunction != nil && !balance.paymentOngoing {
// if a settlement failed recently, wait until failedSettlementInterval before trying again
differenceInSeconds := now.Unix() - balance.lastSettlementFailureTimestamp
if differenceInSeconds > failedSettlementInterval {
// if there is no monetary settlement happening, check if there is something to settle
// compute debt excluding debt created by incoming payments
originatedBalance, err := a.OriginatedBalance(peer)
if err != nil {
if !errors.Is(err, ErrPeerNoBalance) {
return fmt.Errorf("failed to load originated balance to settle: %w", err)
}
}
paymentAmount := new(big.Int).Neg(originatedBalance)
if paymentAmount.Cmp(a.minimumPayment) >= 0 {
timeElapsedInSeconds := (a.timeNow().UnixMilli() - balance.refreshTimestampMilliseconds) / 1000
refreshDue := new(big.Int).Mul(big.NewInt(timeElapsedInSeconds), a.refreshRate)
currentBalance, err := a.Balance(peer)
if err != nil && !errors.Is(err, ErrPeerNoBalance) {
return fmt.Errorf("failed to load balance: %w", err)
}
debt := new(big.Int).Neg(currentBalance)
decreasedDebt := new(big.Int).Sub(debt, refreshDue)
expectedDecreasedDebt := new(big.Int).Sub(decreasedDebt, balance.shadowReservedBalance)
if paymentAmount.Cmp(expectedDecreasedDebt) > 0 {
paymentAmount.Set(expectedDecreasedDebt)
}
// if the remaining debt is still larger than some minimum amount, trigger monetary settlement
if paymentAmount.Cmp(a.minimumPayment) >= 0 {
balance.paymentOngoing = true
// add settled amount to shadow reserve before sending it
balance.shadowReservedBalance.Add(balance.shadowReservedBalance, paymentAmount)
// if a refreshment is ongoing, add this amount sent to cumulative potential debt decrease during refreshment
if balance.refreshOngoing {
balance.refreshReservedBalance = new(big.Int).Add(balance.refreshReservedBalance, paymentAmount)
}
a.wg.Add(1)
go a.payFunction(context.Background(), peer, paymentAmount)
}
}
}
}
}
return nil
}
// Balance returns the current balance for the given peer.
func (a *Accounting) Balance(peer swarm.Address) (balance *big.Int, err error) {
err = a.store.Get(peerBalanceKey(peer), &balance)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return big.NewInt(0), ErrPeerNoBalance
}
return nil, err
}
return balance, nil
}
// OriginatedBalance returns the current balance for the given peer.
func (a *Accounting) OriginatedBalance(peer swarm.Address) (balance *big.Int, err error) {
err = a.store.Get(originatedBalanceKey(peer), &balance)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return big.NewInt(0), ErrPeerNoBalance
}
return nil, err
}
return balance, nil
}
// SurplusBalance returns the current balance for the given peer.
func (a *Accounting) SurplusBalance(peer swarm.Address) (balance *big.Int, err error) {
err = a.store.Get(peerSurplusBalanceKey(peer), &balance)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return big.NewInt(0), nil
}
return nil, err
}
if balance.Cmp(big.NewInt(0)) < 0 {
return nil, ErrInvalidValue
}
return balance, nil
}
// CompensatedBalance returns balance decreased by surplus balance
func (a *Accounting) CompensatedBalance(peer swarm.Address) (compensated *big.Int, err error) {
surplus, err := a.SurplusBalance(peer)
if err != nil {
return nil, err
}
balance, err := a.Balance(peer)
if err != nil {
if !errors.Is(err, ErrPeerNoBalance) {
return nil, err
}
}
// if surplus is 0 and peer has no balance, propagate ErrPeerNoBalance
if surplus.Cmp(big.NewInt(0)) == 0 && errors.Is(err, ErrPeerNoBalance) {
return nil, err
}
// Compensated balance is balance decreased by surplus balance
compensated = new(big.Int).Sub(balance, surplus)
return compensated, nil
}
// peerBalanceKey returns the balance storage key for the given peer.
func peerBalanceKey(peer swarm.Address) string {
return fmt.Sprintf("%s%s", balancesPrefix, peer.String())
}
// peerSurplusBalanceKey returns the surplus balance storage key for the given peer
func peerSurplusBalanceKey(peer swarm.Address) string {
return fmt.Sprintf("%s%s", balancesSurplusPrefix, peer.String())
}
func originatedBalanceKey(peer swarm.Address) string {
return fmt.Sprintf("%s%s", balancesOriginatedPrefix, peer.String())
}
// getAccountingPeer returns the accountingPeer for a given swarm address.
// If not found in memory it will initialize it.
func (a *Accounting) getAccountingPeer(peer swarm.Address) *accountingPeer {
a.accountingPeersMu.Lock()
defer a.accountingPeersMu.Unlock()
peerData, ok := a.accountingPeers[peer.String()]
if !ok {
peerData = &accountingPeer{
lock: NewMutex(),
reservedBalance: big.NewInt(0),
refreshReservedBalance: big.NewInt(0),
shadowReservedBalance: big.NewInt(0),
ghostBalance: big.NewInt(0),
totalDebtRepay: big.NewInt(0),
paymentThreshold: new(big.Int).Set(a.paymentThreshold),
paymentThresholdForPeer: new(big.Int).Set(a.paymentThreshold),
disconnectLimit: new(big.Int).Set(a.disconnectLimit),
thresholdGrowAt: new(big.Int).Set(a.thresholdGrowStep),
// initially assume the peer has the same threshold as us
earlyPayment: percentOf(100-a.earlyPayment, a.paymentThreshold),
connected: false,
}
a.accountingPeers[peer.String()] = peerData
}
return peerData
}
// notifyPaymentThresholdUpgrade is used when cumulative debt settled by peer reaches current checkpoint,
// to set the next checkpoint and increase the payment threshold given by 1 * refreshment rate
// must be called under accountingPeer lock
func (a *Accounting) notifyPaymentThresholdUpgrade(peer swarm.Address, accountingPeer *accountingPeer) {
// get appropriate linear growth limit based on whether the peer is a full node or a light node
thresholdGrowChange := new(big.Int).Set(a.thresholdGrowChange)
if !accountingPeer.fullNode {
thresholdGrowChange.Set(a.lightThresholdGrowChange)
}
// if current checkpoint already passed linear growth limit, set next checkpoint exponentially
if accountingPeer.thresholdGrowAt.Cmp(thresholdGrowChange) >= 0 {
accountingPeer.thresholdGrowAt = new(big.Int).Mul(accountingPeer.thresholdGrowAt, big.NewInt(2))
} else {
// otherwise set next linear checkpoint
if accountingPeer.fullNode {
accountingPeer.thresholdGrowAt = new(big.Int).Add(accountingPeer.thresholdGrowAt, a.thresholdGrowStep)
} else {
accountingPeer.thresholdGrowAt = new(big.Int).Add(accountingPeer.thresholdGrowAt, a.lightThresholdGrowStep)
}
}
// get appropriate refresh rate
refreshRate := new(big.Int).Set(a.refreshRate)
if !accountingPeer.fullNode {
refreshRate = new(big.Int).Set(a.lightRefreshRate)
}
// increase given threshold by refresh rate
accountingPeer.paymentThresholdForPeer = new(big.Int).Add(accountingPeer.paymentThresholdForPeer, refreshRate)
// recalculate disconnectLimit for peer
accountingPeer.disconnectLimit = percentOf(100+a.paymentTolerance, accountingPeer.paymentThresholdForPeer)
// announce new payment threshold to peer
err := a.pricing.AnnouncePaymentThreshold(context.Background(), peer, accountingPeer.paymentThresholdForPeer)
if err != nil {
a.logger.Error(err, "announcing increased payment threshold", "value", accountingPeer.paymentThresholdForPeer, "peer_address", peer)
}
}
// Balances gets balances for all peers from store.
func (a *Accounting) Balances() (map[string]*big.Int, error) {
s := make(map[string]*big.Int)
err := a.store.Iterate(balancesPrefix, func(key, val []byte) (stop bool, err error) {
addr, err := balanceKeyPeer(key)
if err != nil {
return false, fmt.Errorf("parse address from key: %s: %w", string(key), err)
}
if _, ok := s[addr.String()]; !ok {
var storevalue *big.Int
err = a.store.Get(peerBalanceKey(addr), &storevalue)
if err != nil {
return false, fmt.Errorf("get peer %s balance: %w", addr.String(), err)
}
s[addr.String()] = storevalue
}
return false, nil
})
if err != nil {
return nil, err
}
return s, nil
}
type PeerInfo struct {
Balance *big.Int
ConsumedBalance *big.Int
ThresholdReceived *big.Int
ThresholdGiven *big.Int
CurrentThresholdReceived *big.Int
CurrentThresholdGiven *big.Int
SurplusBalance *big.Int
ReservedBalance *big.Int
ShadowReservedBalance *big.Int
GhostBalance *big.Int
}
func (a *Accounting) PeerAccounting() (map[string]PeerInfo, error) {
s := make(map[string]PeerInfo)
a.accountingPeersMu.Lock()
accountingPeersList := make(map[string]*accountingPeer)
for peer, accountingPeer := range a.accountingPeers {
accountingPeersList[peer] = accountingPeer
}
a.accountingPeersMu.Unlock()
for peer, accountingPeer := range accountingPeersList {
peerAddress := swarm.MustParseHexAddress(peer)
balance, err := a.Balance(peerAddress)
if errors.Is(err, ErrPeerNoBalance) {
balance = big.NewInt(0)
} else if err != nil {
return nil, err
}
surplusBalance, err := a.SurplusBalance(peerAddress)
if err != nil {
return nil, err
}
accountingPeer.lock.Lock()
t := a.timeNow()
timeElapsedInSeconds := t.Unix() - accountingPeer.refreshReceivedTimestamp
if timeElapsedInSeconds > 1 {
timeElapsedInSeconds = 1
}
// get appropriate refresh rate
refreshRate := new(big.Int).Set(a.refreshRate)
if !accountingPeer.fullNode {
refreshRate = new(big.Int).Set(a.lightRefreshRate)
}
refreshDue := new(big.Int).Mul(big.NewInt(timeElapsedInSeconds), refreshRate)
currentThresholdGiven := new(big.Int).Add(accountingPeer.disconnectLimit, refreshDue)
timeElapsedInSeconds = (t.UnixMilli() - accountingPeer.refreshTimestampMilliseconds) / 1000
if timeElapsedInSeconds > 1 {
timeElapsedInSeconds = 1
}
// get appropriate refresh rate
refreshDue = new(big.Int).Mul(big.NewInt(timeElapsedInSeconds), a.refreshRate)
currentThresholdReceived := new(big.Int).Add(accountingPeer.paymentThreshold, refreshDue)
s[peer] = PeerInfo{
Balance: new(big.Int).Sub(balance, surplusBalance),
ConsumedBalance: new(big.Int).Set(balance),
ThresholdReceived: new(big.Int).Set(accountingPeer.paymentThreshold),
CurrentThresholdReceived: currentThresholdReceived,
CurrentThresholdGiven: currentThresholdGiven,
ThresholdGiven: new(big.Int).Set(accountingPeer.paymentThresholdForPeer),
SurplusBalance: new(big.Int).Set(surplusBalance),
ReservedBalance: new(big.Int).Set(accountingPeer.reservedBalance),
ShadowReservedBalance: new(big.Int).Set(accountingPeer.shadowReservedBalance),
GhostBalance: new(big.Int).Set(accountingPeer.ghostBalance),
}
accountingPeer.lock.Unlock()
}
return s, nil
}
// CompensatedBalances gets balances for all peers from store.
func (a *Accounting) CompensatedBalances() (map[string]*big.Int, error) {
s := make(map[string]*big.Int)
err := a.store.Iterate(balancesPrefix, func(key, val []byte) (stop bool, err error) {
addr, err := balanceKeyPeer(key)
if err != nil {
return false, fmt.Errorf("parse address from key: %s: %w", string(key), err)
}
if _, ok := s[addr.String()]; !ok {
value, err := a.CompensatedBalance(addr)
if err != nil {
return false, fmt.Errorf("get peer %s balance: %w", addr.String(), err)
}
s[addr.String()] = value
}
return false, nil
})
if err != nil {
return nil, err
}
err = a.store.Iterate(balancesSurplusPrefix, func(key, val []byte) (stop bool, err error) {
addr, err := surplusBalanceKeyPeer(key)
if err != nil {
return false, fmt.Errorf("parse address from key: %s: %w", string(key), err)
}
if _, ok := s[addr.String()]; !ok {
value, err := a.CompensatedBalance(addr)
if err != nil {
return false, fmt.Errorf("get peer %s balance: %w", addr.String(), err)
}
s[addr.String()] = value
}
return false, nil
})
if err != nil {
return nil, err
}
return s, nil
}
// balanceKeyPeer returns the embedded peer from the balance storage key.
func balanceKeyPeer(key []byte) (swarm.Address, error) {
k := string(key)
split := strings.SplitAfter(k, balancesPrefix)
if len(split) != 2 {
return swarm.ZeroAddress, errors.New("no peer in key")
}
addr, err := swarm.ParseHexAddress(split[1])
if err != nil {
return swarm.ZeroAddress, err
}
return addr, nil
}
func surplusBalanceKeyPeer(key []byte) (swarm.Address, error) {
k := string(key)
split := strings.SplitAfter(k, balancesSurplusPrefix)
if len(split) != 2 {
return swarm.ZeroAddress, errors.New("no peer in key")
}
addr, err := swarm.ParseHexAddress(split[1])
if err != nil {
return swarm.ZeroAddress, err
}
return addr, nil
}
// PeerDebt returns the positive part of the sum of the outstanding balance and the shadow reserve
func (a *Accounting) PeerDebt(peer swarm.Address) (*big.Int, error) {
accountingPeer := a.getAccountingPeer(peer)
accountingPeer.lock.Lock()
defer accountingPeer.lock.Unlock()
balance := new(big.Int)
zero := big.NewInt(0)
err := a.store.Get(peerBalanceKey(peer), &balance)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
return nil, err
}
balance = big.NewInt(0)
}
peerDebt := new(big.Int).Add(balance, accountingPeer.shadowReservedBalance)
if peerDebt.Cmp(zero) < 0 {
return zero, nil
}
return peerDebt, nil
}
// peerLatentDebt returns the sum of the positive part of the outstanding balance, shadow reserve and the ghost balance
func (a *Accounting) peerLatentDebt(peer swarm.Address) (*big.Int, error) {
accountingPeer := a.getAccountingPeer(peer)
balance := new(big.Int)
zero := big.NewInt(0)
err := a.store.Get(peerBalanceKey(peer), &balance)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
return nil, err
}
balance = big.NewInt(0)
}
if balance.Cmp(zero) < 0 {
balance.Set(zero)
}
peerDebt := new(big.Int).Add(balance, accountingPeer.shadowReservedBalance)
peerLatentDebt := new(big.Int).Add(peerDebt, accountingPeer.ghostBalance)
if peerLatentDebt.Cmp(zero) < 0 {
return zero, nil
}
return peerLatentDebt, nil
}
// shadowBalance returns the current debt reduced by any potentially debitable amount stored in shadowReservedBalance
// this represents how much less our debt could potentially be seen by the other party if it's ahead with processing credits corresponding to our shadow reserve
func (a *Accounting) shadowBalance(peer swarm.Address, accountingPeer *accountingPeer) (shadowBalance *big.Int, err error) {
balance := new(big.Int)
zero := big.NewInt(0)
err = a.store.Get(peerBalanceKey(peer), &balance)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return zero, nil
}
return nil, err
}
if balance.Cmp(zero) >= 0 {
return zero, nil
}
negativeBalance := new(big.Int).Neg(balance)
surplusBalance, err := a.SurplusBalance(peer)
if err != nil {
return nil, err
}
debt := new(big.Int).Add(negativeBalance, surplusBalance)
if debt.Cmp(accountingPeer.shadowReservedBalance) < 0 {
return zero, nil
}
shadowBalance = new(big.Int).Sub(negativeBalance, accountingPeer.shadowReservedBalance)
return shadowBalance, nil
}
// NotifyPaymentSent is triggered by async monetary settlement to update our balance and remove it's price from the shadow reserve
func (a *Accounting) NotifyPaymentSent(peer swarm.Address, amount *big.Int, receivedError error) {
loggerV2 := a.logger.V(2).Register()
defer a.wg.Done()
accountingPeer := a.getAccountingPeer(peer)
accountingPeer.lock.Lock()
defer accountingPeer.lock.Unlock()
accountingPeer.paymentOngoing = false
// decrease shadow reserve by payment value
accountingPeer.shadowReservedBalance.Sub(accountingPeer.shadowReservedBalance, amount)
if receivedError != nil {
accountingPeer.lastSettlementFailureTimestamp = a.timeNow().Unix()
a.metrics.PaymentErrorCount.Inc()
a.logger.Warning("payment failure", "error", receivedError)
return
}
currentBalance, err := a.Balance(peer)
if err != nil {
if !errors.Is(err, ErrPeerNoBalance) {
a.logger.Error(err, "notify payment sent; failed to persist balance")
return
}
}
// Get nextBalance by increasing current balance with price
nextBalance := new(big.Int).Add(currentBalance, amount)
loggerV2.Debug("registering payment sent", "peer_address", peer, "amount", amount, "new_balance", nextBalance)
err = a.store.Put(peerBalanceKey(peer), nextBalance)
if err != nil {