/
chequestore.go
418 lines (343 loc) · 13 KB
/
chequestore.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
package cheque
import (
"context"
"errors"
"fmt"
"math/big"
"strings"
"sync"
"github.com/FavorLabs/favorX/pkg/crypto"
"github.com/FavorLabs/favorX/pkg/storage"
"github.com/ethereum/go-ethereum/common"
)
var (
// ErrNoCheque is the error returned if there is no prior cheque for a chainAddress or beneficiary.
ErrNoCheque = errors.New("no cheque")
// ErrChequeNotIncreasing is the error returned if the cheque amount is the same or lower.
ErrChequeNotIncreasing = errors.New("cheque cumulativePayout is not increasing")
// ErrChequeInvalid is the error returned if the cheque itself is invalid.
ErrChequeInvalid = errors.New("invalid cheque")
// ErrWrongBeneficiary is the error returned if the cheque has the wrong beneficiary.
ErrWrongBeneficiary = errors.New("wrong beneficiary")
// ErrBouncingCheque is the error returned if the chainAddress is demonstrably illiquid.
ErrBouncingCheque = errors.New("bouncing cheque")
ErrCashOut = errors.New("cashout not completing")
lastReceivedChequePrefix = "traffic_last_received_cheque_"
lastSendChequePrefix = "traffic_last_send_cheque_"
retrievedTrafficPrefix = "retrieved_traffic_"
transferredTrafficPrefix = "transferred_traffic_"
chainRetrievedTrafficPrefix = "chain_retrieved_traffic_"
chainTransferredTrafficPrefix = "chain_transferred_traffic_"
)
// ChequeStore handles the verification and storage of received cheques
type ChequeStore interface {
// ReceiveCheque verifies and stores a cheque. It returns the totam amount earned.
ReceiveCheque(ctx context.Context, cheque *SignedCheque) (*big.Int, error)
VerifyCheque(cheque *SignedCheque, chaindID int64) (common.Address, error)
PutSendCheque(ctx context.Context, cheque *Cheque, chainAddress common.Address) error
PutReceivedCheques(chainAddress common.Address, cheque SignedCheque) error
// LastReceivedCheque returns the last cheque we received from a specific chainAddress.
LastReceivedCheque(chainAddress common.Address) (*SignedCheque, error)
// LastReceivedCheques returns the last received cheques from every known chainAddress.
LastReceivedCheques() (map[common.Address]*SignedCheque, error)
LastSendCheque(chainAddress common.Address) (*Cheque, error)
LastSendCheques() (map[common.Address]*Cheque, error)
PutRetrieveTraffic(chainAddress common.Address, traffic *big.Int) error
PutTransferTraffic(chainAddress common.Address, traffic *big.Int) error
GetRetrieveTraffic(chainAddress common.Address) (traffic *big.Int, err error)
GetTransferTraffic(chainAddress common.Address) (traffic *big.Int, err error)
PutChainRetrieveTraffic(chainAddress common.Address, traffic *big.Int) error
PutChainTransferTraffic(chainAddress common.Address, traffic *big.Int) error
GetChainRetrieveTraffic(chainAddress common.Address) (traffic *big.Int, err error)
GetChainTransferTraffic(chainAddress common.Address) (traffic *big.Int, err error)
// GetAllRetrieveTransferAddresses return all addresses that we have transferred or retrieved traffic
GetAllRetrieveTransferAddresses() (map[common.Address]struct{}, error)
}
type chequeStore struct {
lock sync.Mutex
store storage.StateStorer
recipient common.Address // the beneficiary we expect in cheques sent to us
recoverChequeFunc RecoverChequeFunc
chainID int64
}
type RecoverChequeFunc func(cheque *SignedCheque, chainID int64) (common.Address, error)
// NewChequeStore creates new ChequeStore
func NewChequeStore(
store storage.StateStorer,
recipient common.Address,
recoverChequeFunc RecoverChequeFunc,
chainID int64) ChequeStore {
return &chequeStore{
store: store,
recipient: recipient,
recoverChequeFunc: recoverChequeFunc,
chainID: chainID,
}
}
// lastTransferredTrafficChequeKey computes the key where to store the last cheque received from a chainAddress.
func lastReceivedChequeKey(chainAddress common.Address) string {
return fmt.Sprintf("%s_%x", lastReceivedChequePrefix, chainAddress)
}
func lastSendChequeKey(chainAddress common.Address) string {
return fmt.Sprintf("%s_%x", lastSendChequePrefix, chainAddress)
}
func retrievedTraffic(chainAddress common.Address) string {
return fmt.Sprintf("%s_%x", retrievedTrafficPrefix, chainAddress)
}
func transferredTraffic(chainAddress common.Address) string {
return fmt.Sprintf("%s_%x", transferredTrafficPrefix, chainAddress)
}
func chainRetrievedTraffic(chainAddress common.Address) string {
return fmt.Sprintf("%s_%x", chainRetrievedTrafficPrefix, chainAddress)
}
func chainTransferredTraffic(chainAddress common.Address) string {
return fmt.Sprintf("%s_%x", chainTransferredTrafficPrefix, chainAddress)
}
// LastReceivedCheque returns the last cheque we received from a specific chainAddress.
func (s *chequeStore) LastReceivedCheque(chainAddress common.Address) (*SignedCheque, error) {
var cheque *SignedCheque
err := s.store.Get(lastReceivedChequeKey(chainAddress), &cheque)
if err != nil {
if err != storage.ErrNotFound {
return nil, err
}
return &SignedCheque{
Cheque: Cheque{
Recipient: common.Address{},
Beneficiary: common.Address{},
CumulativePayout: big.NewInt(0),
},
}, ErrNoCheque
}
return cheque, nil
}
// ReceiveCheque verifies and stores a cheque. It returns the totam amount earned.
func (s *chequeStore) ReceiveCheque(ctx context.Context, cheque *SignedCheque) (*big.Int, error) {
// verify we are the beneficiary
if cheque.Recipient != s.recipient {
return nil, ErrWrongBeneficiary
}
// verify the cheque signature
issuer, err := s.recoverChequeFunc(cheque, s.chainID)
if err != nil {
return nil, err
}
if issuer != cheque.Beneficiary {
return nil, ErrChequeInvalid
}
// don't allow concurrent processing of cheques
// this would be sufficient on a per chainAddress basis
s.lock.Lock()
defer s.lock.Unlock()
// load the lastCumulativePayout for the cheques chainAddress
var lastCumulativePayout *big.Int
var lastReceivedCheque *SignedCheque
err = s.store.Get(lastReceivedChequeKey(cheque.Beneficiary), &lastReceivedCheque)
if err != nil {
if err != storage.ErrNotFound {
return nil, err
}
lastCumulativePayout = big.NewInt(0)
} else {
lastCumulativePayout = lastReceivedCheque.CumulativePayout
}
// check this cheque is actually increasing in value
amount := big.NewInt(0).Sub(cheque.CumulativePayout, lastCumulativePayout)
if amount.Cmp(big.NewInt(0)) <= 0 {
return nil, ErrChequeNotIncreasing
}
// store the accepted cheque
err = s.store.Put(lastReceivedChequeKey(cheque.Beneficiary), cheque)
if err != nil {
return nil, err
}
return amount, nil
}
func (s *chequeStore) PutSendCheque(ctx context.Context, cheque *Cheque, chainAddress common.Address) error {
return s.store.Put(lastSendChequeKey(chainAddress), cheque)
}
// RecoverCheque recovers the issuer ethereum address from a signed cheque
func RecoverCheque(cheque *SignedCheque, chaindID int64) (common.Address, error) {
eip712Data := eip712DataForCheque(&cheque.Cheque, chaindID)
pubkey, err := crypto.RecoverEIP712(cheque.Signature, eip712Data)
if err != nil {
return common.Address{}, err
}
ethAddr, err := crypto.NewEthereumAddress(*pubkey)
if err != nil {
return common.Address{}, err
}
var issuer common.Address
copy(issuer[:], ethAddr)
return issuer, nil
}
// keyChequebook computes the chainAddress a store entry is for.
func keyChainAddress(key []byte, prefix string) (chainAddress common.Address, err error) {
k := string(key)
split := strings.SplitAfter(k, prefix)
if len(split) != 2 {
return common.Address{}, errors.New("no peer in key")
}
return common.HexToAddress(split[1]), nil
}
// LastReceivedCheques returns the last received cheques from every known chainAddress.
func (s *chequeStore) LastReceivedCheques() (map[common.Address]*SignedCheque, error) {
result := make(map[common.Address]*SignedCheque)
err := s.store.Iterate(lastReceivedChequePrefix, func(key, val []byte) (stop bool, err error) {
addr, err := keyChainAddress(key, lastReceivedChequePrefix+"_")
if err != nil {
return false, fmt.Errorf("parse address from key: %s: %w", string(key), err)
}
if _, ok := result[addr]; !ok {
lastCheque, err := s.LastReceivedCheque(addr)
if err != nil && err != ErrNoCheque {
return false, err
} else if err == ErrNoCheque {
return false, nil
}
result[addr] = lastCheque
}
return false, nil
})
if err != nil {
return nil, err
}
return result, nil
}
func (s *chequeStore) LastSendCheque(chainAddress common.Address) (*Cheque, error) {
var cheque *Cheque
err := s.store.Get(lastSendChequeKey(chainAddress), &cheque)
if err != nil {
if err != storage.ErrNotFound {
return nil, err
}
return &Cheque{
Recipient: common.Address{},
Beneficiary: common.Address{},
CumulativePayout: new(big.Int).SetInt64(0),
}, ErrNoCheque
}
return cheque, nil
}
func (s *chequeStore) LastSendCheques() (map[common.Address]*Cheque, error) {
result := make(map[common.Address]*Cheque)
err := s.store.Iterate(lastSendChequePrefix, func(key, val []byte) (stop bool, err error) {
addr, err := keyChainAddress(key, lastSendChequePrefix+"_")
if err != nil {
return false, fmt.Errorf("parse address from key: %s: %w", string(key), err)
}
if _, ok := result[addr]; !ok {
lastCheque, err := s.LastSendCheque(addr)
if err != nil && err != ErrNoCheque {
return false, err
} else if err == ErrNoCheque {
return false, nil
}
result[addr] = lastCheque
}
return false, nil
})
if err != nil {
return nil, err
}
return result, nil
}
func (s *chequeStore) PutRetrieveTraffic(chainAddress common.Address, traffic *big.Int) error {
return s.store.Put(retrievedTraffic(chainAddress), traffic)
}
func (s *chequeStore) PutTransferTraffic(chainAddress common.Address, traffic *big.Int) error {
return s.store.Put(transferredTraffic(chainAddress), traffic)
}
func (s *chequeStore) PutReceivedCheques(chainAddress common.Address, cheque SignedCheque) error {
return s.store.Put(lastReceivedChequeKey(chainAddress), cheque)
}
func (s *chequeStore) GetRetrieveTraffic(chainAddress common.Address) (traffic *big.Int, err error) {
err = s.store.Get(retrievedTraffic(chainAddress), &traffic)
if err != nil {
if err != storage.ErrNotFound {
return big.NewInt(0), err
}
return big.NewInt(0), nil
}
return traffic, nil
}
func (s *chequeStore) GetTransferTraffic(chainAddress common.Address) (traffic *big.Int, err error) {
err = s.store.Get(transferredTraffic(chainAddress), &traffic)
if err != nil {
if err != storage.ErrNotFound {
return big.NewInt(0), err
}
return big.NewInt(0), nil
}
return traffic, nil
}
// RecoverCheque recovers the issuer ethereum address from a signed cheque
func (s *chequeStore) RecoverCheque(cheque *SignedCheque, chainID int64) (common.Address, error) {
eip712Data := eip712DataForCheque(&cheque.Cheque, chainID)
pubkey, err := crypto.RecoverEIP712(cheque.Signature, eip712Data)
if err != nil {
return common.Address{}, err
}
ethAddr, err := crypto.NewEthereumAddress(*pubkey)
if err != nil {
return common.Address{}, err
}
var issuer common.Address
copy(issuer[:], ethAddr)
return issuer, nil
}
func (s *chequeStore) VerifyCheque(cheque *SignedCheque, chaindID int64) (common.Address, error) {
return s.recoverChequeFunc(cheque, chaindID)
}
func (s *chequeStore) PutChainRetrieveTraffic(chainAddress common.Address, traffic *big.Int) error {
return s.store.Put(chainRetrievedTraffic(chainAddress), traffic)
}
func (s *chequeStore) PutChainTransferTraffic(chainAddress common.Address, traffic *big.Int) error {
return s.store.Put(chainTransferredTraffic(chainAddress), traffic)
}
func (s *chequeStore) GetChainRetrieveTraffic(chainAddress common.Address) (traffic *big.Int, err error) {
err = s.store.Get(chainRetrievedTraffic(chainAddress), &traffic)
if err != nil {
if err != storage.ErrNotFound {
return big.NewInt(0), err
}
return big.NewInt(0), nil
}
return traffic, nil
}
func (s *chequeStore) GetChainTransferTraffic(chainAddress common.Address) (traffic *big.Int, err error) {
err = s.store.Get(chainTransferredTraffic(chainAddress), &traffic)
if err != nil {
if err != storage.ErrNotFound {
return big.NewInt(0), err
}
return big.NewInt(0), nil
}
return traffic, nil
}
func (s *chequeStore) GetAllRetrieveTransferAddresses() (map[common.Address]struct{}, error) {
result := make(map[common.Address]struct{})
err := s.store.Iterate(retrievedTrafficPrefix, func(key, val []byte) (stop bool, err error) {
addr, err := keyChainAddress(key, retrievedTrafficPrefix+"_")
if err != nil {
return false, fmt.Errorf("parse address from key: %s: %w", string(key), err)
}
result[addr] = struct{}{}
return false, nil
})
if err != nil {
return nil, err
}
err = s.store.Iterate(transferredTrafficPrefix, func(key, val []byte) (stop bool, err error) {
addr, err := keyChainAddress(key, transferredTrafficPrefix+"_")
if err != nil {
return false, fmt.Errorf("parse address from key: %s: %w", string(key), err)
}
result[addr] = struct{}{}
return false, nil
})
if err != nil {
return nil, err
}
return result, nil
}