-
Notifications
You must be signed in to change notification settings - Fork 2
/
swapprotocol.go
250 lines (208 loc) · 7.01 KB
/
swapprotocol.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
// 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 swapprotocol
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethsana/sana/pkg/logging"
"github.com/ethsana/sana/pkg/p2p"
"github.com/ethsana/sana/pkg/p2p/protobuf"
"github.com/ethsana/sana/pkg/settlement/swap/chequebook"
swap "github.com/ethsana/sana/pkg/settlement/swap/headers"
"github.com/ethsana/sana/pkg/settlement/swap/priceoracle"
"github.com/ethsana/sana/pkg/settlement/swap/swapprotocol/pb"
"github.com/ethsana/sana/pkg/swarm"
)
const (
protocolName = "swap"
protocolVersion = "1.0.0"
streamName = "swap" // stream for cheques
)
var (
ErrNegotiateRate = errors.New("exchange rates mismatch")
ErrNegotiateDeduction = errors.New("deduction values mismatch")
ErrHaveDeduction = errors.New("received deduction not zero")
)
type SendChequeFunc chequebook.SendChequeFunc
type IssueFunc func(ctx context.Context, beneficiary common.Address, amount *big.Int, sendChequeFunc chequebook.SendChequeFunc) (*big.Int, error)
// (context.Context, common.Address, *big.Int, chequebook.SendChequeFunc) (*big.Int, error)
// Interface is the main interface to send messages over swap protocol.
type Interface interface {
// EmitCheque sends a signed cheque to a peer.
EmitCheque(ctx context.Context, peer swarm.Address, beneficiary common.Address, amount *big.Int, issue IssueFunc) (balance *big.Int, err error)
}
// Swap is the interface the settlement layer should implement to receive cheques.
type Swap interface {
// ReceiveCheque is called by the swap protocol if a cheque is received.
ReceiveCheque(ctx context.Context, peer swarm.Address, cheque *chequebook.SignedCheque, exchangeRate, deduction *big.Int) error
// Handshake is called by the swap protocol when a handshake is received.
Handshake(peer swarm.Address, beneficiary common.Address) error
GetDeductionForPeer(peer swarm.Address) (bool, error)
GetDeductionByPeer(peer swarm.Address) (bool, error)
AddDeductionByPeer(peer swarm.Address) error
}
// Service is the main implementation of the swap protocol.
type Service struct {
streamer p2p.Streamer
logger logging.Logger
swap Swap
priceOracle priceoracle.Service
beneficiary common.Address
}
// New creates a new swap protocol Service.
func New(streamer p2p.Streamer, logger logging.Logger, beneficiary common.Address, priceOracle priceoracle.Service) *Service {
return &Service{
streamer: streamer,
logger: logger,
beneficiary: beneficiary,
priceOracle: priceOracle,
}
}
// SetSwap sets the swap to notify.
func (s *Service) SetSwap(swap Swap) {
s.swap = swap
}
func (s *Service) Protocol() p2p.ProtocolSpec {
return p2p.ProtocolSpec{
Name: protocolName,
Version: protocolVersion,
StreamSpecs: []p2p.StreamSpec{
{
Name: streamName,
Handler: s.handler,
Headler: s.headler,
},
},
ConnectOut: s.init,
ConnectIn: s.init,
}
}
// init is called on outgoing connections and triggers handshake exchange
func (s *Service) init(ctx context.Context, p p2p.Peer) error {
beneficiary := common.BytesToAddress(p.EthereumAddress)
return s.swap.Handshake(p.Address, beneficiary)
}
func (s *Service) handler(ctx context.Context, p p2p.Peer, stream p2p.Stream) (err error) {
r := protobuf.NewReader(stream)
defer func() {
if err != nil {
_ = stream.Reset()
} else {
_ = stream.FullClose()
}
}()
var req pb.EmitCheque
if err := r.ReadMsgWithContext(ctx, &req); err != nil {
return fmt.Errorf("read request from peer %v: %w", p.Address, err)
}
responseHeaders := stream.ResponseHeaders()
exchangeRate, deduction, err := swap.ParseSettlementResponseHeaders(responseHeaders)
if err != nil {
if !errors.Is(err, swap.ErrNoDeductionHeader) {
return err
}
deduction = big.NewInt(0)
}
var signedCheque *chequebook.SignedCheque
err = json.Unmarshal(req.Cheque, &signedCheque)
if err != nil {
return err
}
// signature validation
return s.swap.ReceiveCheque(ctx, p.Address, signedCheque, exchangeRate, deduction)
}
func (s *Service) headler(receivedHeaders p2p.Headers, peerAddress swarm.Address) (returnHeaders p2p.Headers) {
exchangeRate, deduction, err := s.priceOracle.CurrentRates()
if err != nil {
return p2p.Headers{}
}
checkPeer, err := s.swap.GetDeductionForPeer(peerAddress)
if err != nil {
return p2p.Headers{}
}
if checkPeer {
deduction = big.NewInt(0)
}
returnHeaders = swap.MakeSettlementHeaders(exchangeRate, deduction)
return
}
// InitiateCheque attempts to send a cheque to a peer.
func (s *Service) EmitCheque(ctx context.Context, peer swarm.Address, beneficiary common.Address, amount *big.Int, issue IssueFunc) (balance *big.Int, err error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
stream, err := s.streamer.NewStream(ctx, peer, nil, protocolName, protocolVersion, streamName)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
_ = stream.Reset()
} else {
_ = stream.FullClose()
}
}()
// reading exchangeRated headers
returnedHeaders := stream.Headers()
exchangeRate, deduction, err := swap.ParseSettlementResponseHeaders(returnedHeaders)
if err != nil {
if !errors.Is(err, swap.ErrNoDeductionHeader) {
return nil, err
}
deduction = big.NewInt(0)
}
// comparing received headers to known truth
// get whether peer have deducted in the past
checkPeer, err := s.swap.GetDeductionByPeer(peer)
if err != nil {
return nil, err
}
// if peer is not entitled for deduction but sent non zero deduction value, return with error
if checkPeer && deduction.Cmp(big.NewInt(0)) != 0 {
return nil, ErrHaveDeduction
}
// get current global exchangeRate rate and deduction
checkExchangeRate, checkDeduction, err := s.priceOracle.CurrentRates()
if err != nil {
return nil, err
}
// exchangeRate rates should match
if exchangeRate.Cmp(checkExchangeRate) != 0 {
return nil, ErrNegotiateRate
}
// deduction values should match or be zero
if deduction.Cmp(checkDeduction) != 0 && deduction.Cmp(big.NewInt(0)) != 0 {
return nil, ErrNegotiateDeduction
}
paymentAmount := new(big.Int).Mul(amount, exchangeRate)
sentAmount := new(big.Int).Add(paymentAmount, deduction)
// issue cheque call with provided callback for sending cheque to finish transaction
balance, err = issue(ctx, beneficiary, sentAmount, func(cheque *chequebook.SignedCheque) error {
// for simplicity we use json marshaller. can be replaced by a binary encoding in the future.
encodedCheque, err := json.Marshal(cheque)
if err != nil {
return err
}
// sending cheque
s.logger.Tracef("sending cheque message to peer %v (%v)", peer, cheque)
w := protobuf.NewWriter(stream)
return w.WriteMsgWithContext(ctx, &pb.EmitCheque{
Cheque: encodedCheque,
})
})
if err != nil {
return nil, err
}
if deduction.Cmp(big.NewInt(0)) != 0 {
err = s.swap.AddDeductionByPeer(peer)
if err != nil {
return nil, err
}
}
return balance, nil
}