-
Notifications
You must be signed in to change notification settings - Fork 1
/
swap.go
349 lines (305 loc) · 10.6 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
// Copyright 2020 The Penguin 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/penguintop/penguin_bsc/pkg/crypto"
"github.com/penguintop/penguin_bsc/pkg/logging"
"github.com/penguintop/penguin_bsc/pkg/p2p"
"github.com/penguintop/penguin_bsc/pkg/penguin"
"github.com/penguintop/penguin_bsc/pkg/settlement"
"github.com/penguintop/penguin_bsc/pkg/settlement/swap/chequebook"
"github.com/penguintop/penguin_bsc/pkg/settlement/swap/swapprotocol"
"github.com/penguintop/penguin_bsc/pkg/storage"
)
var (
// ErrWrongChequebook is the error if a peer uses a different chequebook from before.
ErrWrongChequebook = errors.New("wrong chequebook")
// ErrWrongBeneficiary is the error if a peer uses a different beneficiary than expected.
ErrWrongBeneficiary = errors.New("wrong beneficiary")
// ErrUnknownBeneficary is the error if a peer has never announced a beneficiary.
ErrUnknownBeneficary = errors.New("unknown beneficiary for peer")
)
type Interface interface {
settlement.Interface
// LastSentCheque returns the last sent cheque for the peer
LastSentCheque(peer penguin.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 penguin.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 penguin.Address) (common.Hash, error)
// CashoutStatus gets the status of the latest cashout transaction for the peers chequebook
CashoutStatus(ctx context.Context, peer penguin.Address) (*chequebook.CashoutStatus, error)
}
// Service is the implementation of the swap settlement layer.
type Service struct {
proto swapprotocol.Interface
logger logging.Logger
store storage.StateStorer
accounting settlement.Accounting
metrics metrics
chequebook chequebook.Service
chequeStore chequebook.ChequeStore
cashout chequebook.CashoutService
p2pService p2p.Service
addressbook Addressbook
networkID uint64
}
// New creates a new swap Service.
func New(proto swapprotocol.Interface, logger logging.Logger, store storage.StateStorer, chequebook chequebook.Service, chequeStore chequebook.ChequeStore, addressbook Addressbook, networkID uint64, cashout chequebook.CashoutService, p2pService p2p.Service, accounting settlement.Accounting) *Service {
return &Service{
proto: proto,
logger: logger,
store: store,
metrics: newMetrics(),
chequebook: chequebook,
chequeStore: chequeStore,
addressbook: addressbook,
networkID: networkID,
cashout: cashout,
p2pService: p2pService,
accounting: accounting,
}
}
// ReceiveCheque is called by the swap protocol if a cheque is received.
func (s *Service) ReceiveCheque(ctx context.Context, peer penguin.Address, cheque *chequebook.SignedCheque) (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
}
amount, err := s.chequeStore.ReceiveCheque(ctx, cheque)
if err != nil {
s.metrics.ChequesRejected.Inc()
return fmt.Errorf("rejecting cheque: %w", err)
}
if !known {
err = s.addressbook.PutChequebook(peer, cheque.Chequebook)
if err != nil {
return err
}
}
tot, _ := big.NewFloat(0).SetInt(amount).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 penguin.Address, amount *big.Int) {
var err error
defer func() {
if err != nil {
s.accounting.NotifyPaymentSent(peer, amount, err)
}
}()
beneficiary, known, err := s.addressbook.Beneficiary(peer)
if err != nil {
return
}
if !known {
s.logger.Warningf("disconnecting non-swap peer %v", peer)
err = s.p2pService.Disconnect(peer)
if err != nil {
return
}
err = ErrUnknownBeneficary
return
}
balance, err := s.chequebook.Issue(ctx, beneficiary, amount, func(signedCheque *chequebook.SignedCheque) error {
return s.proto.EmitCheque(ctx, peer, signedCheque)
})
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 penguin.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
}
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 penguin.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)
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 penguin.Address, beneficiary common.Address) error {
// check that the overlay address was derived from the beneficiary (implying they have the same private key)
// while this is not strictly necessary for correct functionality we need to ensure no two peers use the same beneficiary
// as long as we enforce this we might not need the handshake message if the p2p layer exposed the overlay public key
expectedOverlay := crypto.NewOverlayFromEthereumAddress(beneficiary[:], s.networkID)
if !expectedOverlay.Equal(peer) {
return ErrWrongBeneficiary
}
storedBeneficiary, known, err := s.addressbook.Beneficiary(peer)
if err != nil {
return err
}
if !known {
s.logger.Tracef("initial swap handshake peer: %v beneficiary: %x", peer, beneficiary)
return s.addressbook.PutBeneficiary(peer, beneficiary)
}
if storedBeneficiary != beneficiary {
return ErrWrongBeneficiary
}
return nil
}
// LastSentCheque returns the last sent cheque for the peer
func (s *Service) LastSentCheque(peer penguin.Address) (*chequebook.SignedCheque, error) {
common, known, err := s.addressbook.Beneficiary(peer)
if err != nil {
return nil, err
}
if !known {
return nil, chequebook.ErrNoCheque
}
return s.chequebook.LastCheque(common)
}
// LastReceivedCheque returns the last received cheque for the peer
func (s *Service) LastReceivedCheque(peer penguin.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) {
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 penguin.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.chequebook.Address())
}
// CashoutStatus gets the status of the latest cashout transaction for the peers chequebook
func (s *Service) CashoutStatus(ctx context.Context, peer penguin.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)
}