-
Notifications
You must be signed in to change notification settings - Fork 337
/
swap.go
439 lines (372 loc) · 13.1 KB
/
swap.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
// 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 swap
import (
"context"
"errors"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/log"
"github.com/ethersphere/bee/pkg/postage/postagecontract"
"github.com/ethersphere/bee/pkg/settlement"
"github.com/ethersphere/bee/pkg/settlement/swap/chequebook"
"github.com/ethersphere/bee/pkg/settlement/swap/swapprotocol"
"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 = "swap"
var (
// ErrWrongChequebook is the error if a peer uses a different chequebook from before.
ErrWrongChequebook = errors.New("wrong chequebook")
// ErrUnknownBeneficary is the error if a peer has never announced a beneficiary.
ErrUnknownBeneficary = errors.New("unknown beneficiary for peer")
// ErrChequeValueTooLow is the error a peer issued a cheque not covering 1 accounting credit
ErrChequeValueTooLow = errors.New("cheque value too low")
ErrNoChequebook = errors.New("no chequebook")
)
type Interface interface {
settlement.Interface
// LastSentCheque returns the last sent cheque for the peer
LastSentCheque(peer swarm.Address) (*chequebook.SignedCheque, error)
// LastSentCheques returns the list of last sent cheques for all peers
LastSentCheques() (map[string]*chequebook.SignedCheque, error)
// LastReceivedCheque returns the last received cheque for the peer
LastReceivedCheque(peer swarm.Address) (*chequebook.SignedCheque, error)
// LastReceivedCheques returns the list of last received cheques for all peers
LastReceivedCheques() (map[string]*chequebook.SignedCheque, error)
// CashCheque sends a cashing transaction for the last cheque of the peer
CashCheque(ctx context.Context, peer swarm.Address) (common.Hash, error)
// CashoutStatus gets the status of the latest cashout transaction for the peers chequebook
CashoutStatus(ctx context.Context, peer swarm.Address) (*chequebook.CashoutStatus, error)
}
// Service is the implementation of the swap settlement layer.
type Service struct {
proto swapprotocol.Interface
logger log.Logger
store storage.StateStorer
accounting settlement.Accounting
metrics metrics
chequebook chequebook.Service
chequeStore chequebook.ChequeStore
cashout chequebook.CashoutService
addressbook Addressbook
networkID uint64
cashoutAddress common.Address
}
// New creates a new swap Service.
func New(proto swapprotocol.Interface, logger log.Logger, store storage.StateStorer, chequebook chequebook.Service, chequeStore chequebook.ChequeStore, addressbook Addressbook, networkID uint64, cashout chequebook.CashoutService, accounting settlement.Accounting, cashoutAddress common.Address) *Service {
return &Service{
proto: proto,
logger: logger.WithName(loggerName).Register(),
store: store,
metrics: newMetrics(),
chequebook: chequebook,
chequeStore: chequeStore,
addressbook: addressbook,
networkID: networkID,
cashout: cashout,
accounting: accounting,
cashoutAddress: cashoutAddress,
}
}
// ReceiveCheque is called by the swap protocol if a cheque is received.
func (s *Service) ReceiveCheque(ctx context.Context, peer swarm.Address, cheque *chequebook.SignedCheque, exchangeRate, deduction *big.Int) (err error) {
// check this is the same chequebook for this peer as previously
expectedChequebook, known, err := s.addressbook.Chequebook(peer)
if err != nil {
return err
}
if known && expectedChequebook != cheque.Chequebook {
return ErrWrongChequebook
}
receivedAmount, err := s.chequeStore.ReceiveCheque(ctx, cheque, exchangeRate, deduction)
if err != nil {
s.metrics.ChequesRejected.Inc()
return fmt.Errorf("rejecting cheque: %w", err)
}
if deduction.Cmp(big.NewInt(0)) > 0 {
err = s.addressbook.AddDeductionFor(peer)
if err != nil {
return err
}
}
decreasedAmount := new(big.Int).Sub(receivedAmount, deduction)
amount := new(big.Int).Div(decreasedAmount, exchangeRate)
if !known {
err = s.addressbook.PutChequebook(peer, cheque.Chequebook)
if err != nil {
return err
}
}
tot, _ := big.NewFloat(0).SetInt(receivedAmount).Float64()
s.metrics.TotalReceived.Add(tot)
s.metrics.ChequesReceived.Inc()
return s.accounting.NotifyPaymentReceived(peer, amount)
}
// Pay initiates a payment to the given peer
func (s *Service) Pay(ctx context.Context, peer swarm.Address, amount *big.Int) {
var err error
defer func() {
if err != nil {
s.accounting.NotifyPaymentSent(peer, amount, err)
}
}()
if s.chequebook == nil {
err = ErrNoChequebook
return
}
beneficiary, known, err := s.addressbook.Beneficiary(peer)
if err != nil {
return
}
if !known {
err = ErrUnknownBeneficary
return
}
balance, err := s.proto.EmitCheque(ctx, peer, beneficiary, amount, s.chequebook.Issue)
if err != nil {
return
}
bal, _ := big.NewFloat(0).SetInt(balance).Float64()
s.metrics.AvailableBalance.Set(bal)
s.accounting.NotifyPaymentSent(peer, amount, nil)
amountFloat, _ := big.NewFloat(0).SetInt(amount).Float64()
s.metrics.TotalSent.Add(amountFloat)
s.metrics.ChequesSent.Inc()
}
func (s *Service) SetAccounting(accounting settlement.Accounting) {
s.accounting = accounting
}
// TotalSent returns the total amount sent to a peer
func (s *Service) TotalSent(peer swarm.Address) (totalSent *big.Int, err error) {
beneficiary, known, err := s.addressbook.Beneficiary(peer)
if err != nil {
return nil, err
}
if !known {
return nil, settlement.ErrPeerNoSettlements
}
if s.chequebook == nil {
return big.NewInt(0), nil
}
cheque, err := s.chequebook.LastCheque(beneficiary)
if err != nil {
if err == chequebook.ErrNoCheque {
return nil, settlement.ErrPeerNoSettlements
}
return nil, err
}
return cheque.CumulativePayout, nil
}
// TotalReceived returns the total amount received from a peer
func (s *Service) TotalReceived(peer swarm.Address) (totalReceived *big.Int, err error) {
chequebookAddress, known, err := s.addressbook.Chequebook(peer)
if err != nil {
return nil, err
}
if !known {
return nil, settlement.ErrPeerNoSettlements
}
cheque, err := s.chequeStore.LastCheque(chequebookAddress)
if err != nil {
if err == chequebook.ErrNoCheque {
return nil, settlement.ErrPeerNoSettlements
}
return nil, err
}
return cheque.CumulativePayout, nil
}
// SettlementsSent returns sent settlements for each individual known peer
func (s *Service) SettlementsSent() (map[string]*big.Int, error) {
result := make(map[string]*big.Int)
if s.chequebook == nil {
return result, nil
}
cheques, err := s.chequebook.LastCheques()
if err != nil {
return nil, err
}
for beneficiary, cheque := range cheques {
peer, known, err := s.addressbook.BeneficiaryPeer(beneficiary)
if err != nil {
return nil, err
}
if !known {
continue
}
result[peer.String()] = cheque.CumulativePayout
}
return result, nil
}
// SettlementsReceived returns received settlements for each individual known peer.
func (s *Service) SettlementsReceived() (map[string]*big.Int, error) {
result := make(map[string]*big.Int)
cheques, err := s.chequeStore.LastCheques()
if err != nil {
return nil, err
}
for chequebook, cheque := range cheques {
peer, known, err := s.addressbook.ChequebookPeer(chequebook)
if err != nil {
return nil, err
}
if !known {
continue
}
result[peer.String()] = cheque.CumulativePayout
}
return result, err
}
// Handshake is called by the swap protocol when a handshake is received.
func (s *Service) Handshake(peer swarm.Address, beneficiary common.Address) error {
loggerV1 := s.logger.V(1).Register()
oldPeer, known, err := s.addressbook.BeneficiaryPeer(beneficiary)
if err != nil {
return err
}
if known && !peer.Equal(oldPeer) {
s.logger.Debug("migrating swap addresses", "old_peer_address", oldPeer, "new_peer_address", peer)
return s.addressbook.MigratePeer(oldPeer, peer)
}
_, known, err = s.addressbook.Beneficiary(peer)
if err != nil {
return err
}
if !known {
loggerV1.Debug("initial swap handshake", "peer_address", peer, "beneficiary_address", beneficiary)
return s.addressbook.PutBeneficiary(peer, beneficiary)
}
return nil
}
// LastSentCheque returns the last sent cheque for the peer
func (s *Service) LastSentCheque(peer swarm.Address) (*chequebook.SignedCheque, error) {
common, known, err := s.addressbook.Beneficiary(peer)
if err != nil {
return nil, err
}
if !known {
return nil, chequebook.ErrNoCheque
}
if s.chequebook == nil {
return nil, ErrNoChequebook
}
return s.chequebook.LastCheque(common)
}
// LastReceivedCheque returns the last received cheque for the peer
func (s *Service) LastReceivedCheque(peer swarm.Address) (*chequebook.SignedCheque, error) {
common, known, err := s.addressbook.Chequebook(peer)
if err != nil {
return nil, err
}
if !known {
return nil, chequebook.ErrNoCheque
}
return s.chequeStore.LastCheque(common)
}
// LastSentCheques returns the list of last sent cheques for all peers
func (s *Service) LastSentCheques() (map[string]*chequebook.SignedCheque, error) {
if s.chequebook == nil {
return nil, ErrNoChequebook
}
lastcheques, err := s.chequebook.LastCheques()
if err != nil {
return nil, err
}
resultmap := make(map[string]*chequebook.SignedCheque, len(lastcheques))
for i, j := range lastcheques {
addr, known, err := s.addressbook.BeneficiaryPeer(i)
if err == nil && known {
resultmap[addr.String()] = j
}
}
return resultmap, nil
}
// LastReceivedCheques returns the list of last received cheques for all peers
func (s *Service) LastReceivedCheques() (map[string]*chequebook.SignedCheque, error) {
lastcheques, err := s.chequeStore.LastCheques()
if err != nil {
return nil, err
}
resultmap := make(map[string]*chequebook.SignedCheque, len(lastcheques))
for i, j := range lastcheques {
addr, known, err := s.addressbook.ChequebookPeer(i)
if err == nil && known {
resultmap[addr.String()] = j
}
}
return resultmap, nil
}
// CashCheque sends a cashing transaction for the last cheque of the peer
func (s *Service) CashCheque(ctx context.Context, peer swarm.Address) (common.Hash, error) {
chequebookAddress, known, err := s.addressbook.Chequebook(peer)
if err != nil {
return common.Hash{}, err
}
if !known {
return common.Hash{}, chequebook.ErrNoCheque
}
return s.cashout.CashCheque(ctx, chequebookAddress, s.cashoutAddress)
}
// CashoutStatus gets the status of the latest cashout transaction for the peers chequebook
func (s *Service) CashoutStatus(ctx context.Context, peer swarm.Address) (*chequebook.CashoutStatus, error) {
chequebookAddress, known, err := s.addressbook.Chequebook(peer)
if err != nil {
return nil, err
}
if !known {
return nil, chequebook.ErrNoCheque
}
return s.cashout.CashoutStatus(ctx, chequebookAddress)
}
func (s *Service) GetDeductionForPeer(peer swarm.Address) (bool, error) {
return s.addressbook.GetDeductionFor(peer)
}
func (s *Service) GetDeductionByPeer(peer swarm.Address) (bool, error) {
return s.addressbook.GetDeductionBy(peer)
}
func (s *Service) AddDeductionByPeer(peer swarm.Address) error {
return s.addressbook.AddDeductionBy(peer)
}
type NoOpSwap struct {
}
func (*NoOpSwap) TotalSent(peer swarm.Address) (totalSent *big.Int, err error) {
return nil, postagecontract.ErrChainDisabled
}
// TotalReceived returns the total amount received from a peer
func (*NoOpSwap) TotalReceived(peer swarm.Address) (totalSent *big.Int, err error) {
return nil, postagecontract.ErrChainDisabled
}
// SettlementsSent returns sent settlements for each individual known peer
func (*NoOpSwap) SettlementsSent() (map[string]*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
// SettlementsReceived returns received settlements for each individual known peer
func (*NoOpSwap) SettlementsReceived() (map[string]*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (*NoOpSwap) LastSentCheque(peer swarm.Address) (*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
// LastSentCheques returns the list of last sent cheques for all peers
func (*NoOpSwap) LastSentCheques() (map[string]*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
// LastReceivedCheque returns the last received cheque for the peer
func (*NoOpSwap) LastReceivedCheque(peer swarm.Address) (*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
// LastReceivedCheques returns the list of last received cheques for all peers
func (*NoOpSwap) LastReceivedCheques() (map[string]*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
// CashCheque sends a cashing transaction for the last cheque of the peer
func (*NoOpSwap) CashCheque(ctx context.Context, peer swarm.Address) (common.Hash, error) {
return common.Hash{}, postagecontract.ErrChainDisabled
}
// CashoutStatus gets the status of the latest cashout transaction for the peers chequebook
func (*NoOpSwap) CashoutStatus(ctx context.Context, peer swarm.Address) (*chequebook.CashoutStatus, error) {
return nil, postagecontract.ErrChainDisabled
}