2021-11-23 11:05:38 +00:00
|
|
|
package swap
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/libp2p/go-libp2p-core/protocol"
|
2022-01-18 18:17:06 +00:00
|
|
|
"go.uber.org/zap"
|
2021-11-23 11:05:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
SoftMode int = 0
|
|
|
|
MockMode int = 1
|
|
|
|
HardMode int = 2
|
|
|
|
)
|
|
|
|
|
|
|
|
const WakuSwapID_v200 = protocol.ID("/vac/waku/swap/2.0.0-beta1")
|
|
|
|
|
|
|
|
type WakuSwap struct {
|
|
|
|
params *SwapParameters
|
|
|
|
|
2022-01-18 18:17:06 +00:00
|
|
|
log *zap.SugaredLogger
|
|
|
|
|
2021-11-23 11:05:38 +00:00
|
|
|
Accounting map[string]int
|
|
|
|
accountingMutex sync.RWMutex
|
|
|
|
}
|
|
|
|
|
2022-01-18 18:17:06 +00:00
|
|
|
func NewWakuSwap(log *zap.SugaredLogger, opts ...SwapOption) *WakuSwap {
|
2021-11-23 11:05:38 +00:00
|
|
|
params := &SwapParameters{}
|
|
|
|
|
|
|
|
optList := DefaultOptions()
|
|
|
|
optList = append(optList, opts...)
|
|
|
|
for _, opt := range optList {
|
|
|
|
opt(params)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &WakuSwap{
|
|
|
|
params: params,
|
2022-01-18 18:17:06 +00:00
|
|
|
log: log.Named("swap"),
|
2021-11-23 11:05:38 +00:00
|
|
|
Accounting: make(map[string]int),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *WakuSwap) sendCheque(peerId string) {
|
2022-01-18 18:17:06 +00:00
|
|
|
s.log.Debug("not yet implemented")
|
2021-11-23 11:05:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *WakuSwap) applyPolicy(peerId string) {
|
|
|
|
if s.Accounting[peerId] <= s.params.disconnectThreshold {
|
2022-01-18 18:17:06 +00:00
|
|
|
s.log.Warnf("Disconnect threshhold has been reached for %s at %d", peerId, s.Accounting[peerId])
|
2021-11-23 11:05:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if s.Accounting[peerId] >= s.params.paymentThreshold {
|
2022-01-18 18:17:06 +00:00
|
|
|
s.log.Warnf("Disconnect threshhold has been reached for %s at %d", peerId, s.Accounting[peerId])
|
2021-11-23 11:05:38 +00:00
|
|
|
if s.params.mode != HardMode {
|
|
|
|
s.sendCheque(peerId)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *WakuSwap) Credit(peerId string, n int) {
|
|
|
|
s.accountingMutex.Lock()
|
|
|
|
defer s.accountingMutex.Unlock()
|
|
|
|
|
|
|
|
s.Accounting[peerId] -= n
|
|
|
|
s.applyPolicy(peerId)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *WakuSwap) Debit(peerId string, n int) {
|
|
|
|
s.accountingMutex.Lock()
|
|
|
|
defer s.accountingMutex.Unlock()
|
|
|
|
|
|
|
|
s.Accounting[peerId] += n
|
|
|
|
s.applyPolicy(peerId)
|
|
|
|
}
|