-
Notifications
You must be signed in to change notification settings - Fork 339
/
contract.go
465 lines (386 loc) · 11.9 KB
/
contract.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Copyright 2021 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 postagecontract
import (
"context"
"crypto/rand"
"errors"
"fmt"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethersphere/bee/pkg/postage"
"github.com/ethersphere/bee/pkg/sctx"
"github.com/ethersphere/bee/pkg/transaction"
"github.com/ethersphere/go-sw3-abi/sw3abi"
)
var (
BucketDepth = uint8(16)
postageStampABI = parseABI(PostageABI)
erc20ABI = parseABI(sw3abi.ERC20ABIv0_3_1)
batchCreatedTopic = postageStampABI.Events["BatchCreated"].ID
batchTopUpTopic = postageStampABI.Events["BatchTopUp"].ID
batchDiluteTopic = postageStampABI.Events["BatchDepthIncrease"].ID
ErrBatchCreate = errors.New("batch creation failed")
ErrInsufficientFunds = errors.New("insufficient token balance")
ErrInvalidDepth = errors.New("invalid depth")
ErrBatchTopUp = errors.New("batch topUp failed")
ErrBatchDilute = errors.New("batch dilute failed")
ErrChainDisabled = errors.New("chain disabled")
ErrNotImplemented = errors.New("not implemented")
approveDescription = "Approve tokens for postage operations"
createBatchDescription = "Postage batch creation"
topUpBatchDescription = "Postage batch top up"
diluteBatchDescription = "Postage batch dilute"
)
type Interface interface {
CreateBatch(ctx context.Context, initialBalance *big.Int, depth uint8, immutable bool, label string) (common.Hash, []byte, error)
TopUpBatch(ctx context.Context, batchID []byte, topupBalance *big.Int) (common.Hash, error)
DiluteBatch(ctx context.Context, batchID []byte, newDepth uint8) (common.Hash, error)
PostageBatchExpirer
}
type PostageBatchExpirer interface {
ExpireBatches(ctx context.Context) error
}
type postageContract struct {
owner common.Address
postageContractAddress common.Address
bzzTokenAddress common.Address
transactionService transaction.Service
postageService postage.Service
postageStorer postage.Storer
}
func New(
owner,
postageContractAddress,
bzzTokenAddress common.Address,
transactionService transaction.Service,
postageService postage.Service,
postageStorer postage.Storer,
chainEnabled bool,
) Interface {
if !chainEnabled {
return new(noOpPostageContract)
}
return &postageContract{
owner: owner,
postageContractAddress: postageContractAddress,
bzzTokenAddress: bzzTokenAddress,
transactionService: transactionService,
postageService: postageService,
postageStorer: postageStorer,
}
}
func (c *postageContract) ExpireBatches(ctx context.Context) error {
for {
exists, err := c.expiredBatchesExists(ctx)
if err != nil {
return fmt.Errorf("expired batches exist: %w", err)
}
if !exists {
break
}
err = c.expireLimitedBatches(ctx, big.NewInt(50))
if err != nil {
return fmt.Errorf("expire limited batches: %w", err)
}
}
return nil
}
func (c *postageContract) expiredBatchesExists(ctx context.Context) (bool, error) {
callData, err := postageStampABI.Pack("expiredBatchesExist")
if err != nil {
return false, err
}
result, err := c.transactionService.Call(ctx, &transaction.TxRequest{
To: &c.postageContractAddress,
Data: callData,
})
if err != nil {
return false, err
}
results, err := postageStampABI.Unpack("expiredBatchesExist", result)
if err != nil {
return false, err
}
return results[0].(bool), nil
}
func (c *postageContract) expireLimitedBatches(ctx context.Context, count *big.Int) error {
callData, err := postageStampABI.Pack("expireLimited", count)
if err != nil {
return err
}
_, err = c.sendTransaction(sctx.SetGasLimit(ctx, 1_100_000), callData, "expire limited batches")
if err != nil {
return err
}
return nil
}
func (c *postageContract) sendApproveTransaction(ctx context.Context, amount *big.Int) (*types.Receipt, error) {
callData, err := erc20ABI.Pack("approve", c.postageContractAddress, amount)
if err != nil {
return nil, err
}
txHash, err := c.transactionService.Send(ctx, &transaction.TxRequest{
To: &c.bzzTokenAddress,
Data: callData,
GasPrice: sctx.GetGasPrice(ctx),
GasLimit: 65000,
Value: big.NewInt(0),
Description: approveDescription,
}, transaction.DefaultTipBoostPercent)
if err != nil {
return nil, err
}
receipt, err := c.transactionService.WaitForReceipt(ctx, txHash)
if err != nil {
return nil, err
}
if receipt.Status == 0 {
return nil, transaction.ErrTransactionReverted
}
return receipt, nil
}
func (c *postageContract) sendTransaction(ctx context.Context, callData []byte, desc string) (*types.Receipt, error) {
request := &transaction.TxRequest{
To: &c.postageContractAddress,
Data: callData,
GasPrice: sctx.GetGasPrice(ctx),
GasLimit: sctx.GetGasLimitWithDefault(ctx, 1_000_000),
Value: big.NewInt(0),
Description: desc,
}
txHash, err := c.transactionService.Send(ctx, request, transaction.DefaultTipBoostPercent)
if err != nil {
return nil, err
}
receipt, err := c.transactionService.WaitForReceipt(ctx, txHash)
if err != nil {
return nil, err
}
if receipt.Status == 0 {
return nil, transaction.ErrTransactionReverted
}
return receipt, nil
}
func (c *postageContract) sendCreateBatchTransaction(ctx context.Context, owner common.Address, initialBalance *big.Int, depth uint8, nonce common.Hash, immutable bool) (*types.Receipt, error) {
callData, err := postageStampABI.Pack("createBatch", owner, initialBalance, depth, BucketDepth, nonce, immutable)
if err != nil {
return nil, err
}
receipt, err := c.sendTransaction(ctx, callData, createBatchDescription)
if err != nil {
return nil, fmt.Errorf("create batch: depth %d bucketDepth %d immutable %t: %w", depth, BucketDepth, immutable, err)
}
return receipt, nil
}
func (c *postageContract) sendTopUpBatchTransaction(ctx context.Context, batchID []byte, topUpAmount *big.Int) (*types.Receipt, error) {
callData, err := postageStampABI.Pack("topUp", common.BytesToHash(batchID), topUpAmount)
if err != nil {
return nil, err
}
receipt, err := c.sendTransaction(ctx, callData, topUpBatchDescription)
if err != nil {
return nil, fmt.Errorf("topup batch: amount %d: %w", topUpAmount.Int64(), err)
}
return receipt, nil
}
func (c *postageContract) sendDiluteTransaction(ctx context.Context, batchID []byte, newDepth uint8) (*types.Receipt, error) {
callData, err := postageStampABI.Pack("increaseDepth", common.BytesToHash(batchID), newDepth)
if err != nil {
return nil, err
}
receipt, err := c.sendTransaction(ctx, callData, diluteBatchDescription)
if err != nil {
return nil, fmt.Errorf("dilute batch: new depth %d: %w", newDepth, err)
}
return receipt, nil
}
func (c *postageContract) getBalance(ctx context.Context) (*big.Int, error) {
callData, err := erc20ABI.Pack("balanceOf", c.owner)
if err != nil {
return nil, err
}
result, err := c.transactionService.Call(ctx, &transaction.TxRequest{
To: &c.bzzTokenAddress,
Data: callData,
})
if err != nil {
return nil, err
}
results, err := erc20ABI.Unpack("balanceOf", result)
if err != nil {
return nil, err
}
return abi.ConvertType(results[0], new(big.Int)).(*big.Int), nil
}
func (c *postageContract) CreateBatch(ctx context.Context, initialBalance *big.Int, depth uint8, immutable bool, label string) (txHash common.Hash, batchID []byte, err error) {
if depth <= BucketDepth {
err = ErrInvalidDepth
return
}
totalAmount := big.NewInt(0).Mul(initialBalance, big.NewInt(int64(1<<depth)))
balance, err := c.getBalance(ctx)
if err != nil {
return
}
if balance.Cmp(totalAmount) < 0 {
err = ErrInsufficientFunds
return
}
err = c.ExpireBatches(ctx)
if err != nil {
return
}
_, err = c.sendApproveTransaction(ctx, totalAmount)
if err != nil {
return
}
nonce := make([]byte, 32)
_, err = rand.Read(nonce)
if err != nil {
return
}
receipt, err := c.sendCreateBatchTransaction(ctx, c.owner, initialBalance, depth, common.BytesToHash(nonce), immutable)
if err != nil {
return
}
txHash = receipt.TxHash
for _, ev := range receipt.Logs {
if ev.Address == c.postageContractAddress && len(ev.Topics) > 0 && ev.Topics[0] == batchCreatedTopic {
var createdEvent batchCreatedEvent
err = transaction.ParseEvent(&postageStampABI, "BatchCreated", &createdEvent, *ev)
if err != nil {
return
}
batchID = createdEvent.BatchId[:]
err = c.postageService.Add(postage.NewStampIssuer(
label,
c.owner.Hex(),
batchID,
initialBalance,
createdEvent.Depth,
createdEvent.BucketDepth,
ev.BlockNumber,
createdEvent.ImmutableFlag,
))
if err != nil {
return
}
return
}
}
err = ErrBatchCreate
return
}
func (c *postageContract) TopUpBatch(ctx context.Context, batchID []byte, topupBalance *big.Int) (txHash common.Hash, err error) {
batch, err := c.postageStorer.Get(batchID)
if err != nil {
return
}
totalAmount := big.NewInt(0).Mul(topupBalance, big.NewInt(int64(1<<batch.Depth)))
balance, err := c.getBalance(ctx)
if err != nil {
return
}
if balance.Cmp(totalAmount) < 0 {
err = ErrInsufficientFunds
return
}
_, err = c.sendApproveTransaction(ctx, totalAmount)
if err != nil {
return
}
receipt, err := c.sendTopUpBatchTransaction(ctx, batch.ID, topupBalance)
if err != nil {
txHash = receipt.TxHash
return
}
for _, ev := range receipt.Logs {
if ev.Address == c.postageContractAddress && len(ev.Topics) > 0 && ev.Topics[0] == batchTopUpTopic {
txHash = receipt.TxHash
return
}
}
err = ErrBatchTopUp
return
}
func (c *postageContract) DiluteBatch(ctx context.Context, batchID []byte, newDepth uint8) (txHash common.Hash, err error) {
batch, err := c.postageStorer.Get(batchID)
if err != nil {
return
}
if batch.Depth > newDepth {
err = fmt.Errorf("new depth should be greater: %w", ErrInvalidDepth)
return
}
err = c.ExpireBatches(ctx)
if err != nil {
return
}
receipt, err := c.sendDiluteTransaction(ctx, batch.ID, newDepth)
if err != nil {
return
}
txHash = receipt.TxHash
for _, ev := range receipt.Logs {
if ev.Address == c.postageContractAddress && len(ev.Topics) > 0 && ev.Topics[0] == batchDiluteTopic {
return
}
}
err = ErrBatchDilute
return
}
type batchCreatedEvent struct {
BatchId [32]byte
TotalAmount *big.Int
NormalisedBalance *big.Int
Owner common.Address
Depth uint8
BucketDepth uint8
ImmutableFlag bool
}
func parseABI(json string) abi.ABI {
cabi, err := abi.JSON(strings.NewReader(json))
if err != nil {
panic(fmt.Sprintf("error creating ABI for postage contract: %v", err))
}
return cabi
}
func LookupERC20Address(ctx context.Context, transactionService transaction.Service, postageContractAddress common.Address, chainEnabled bool) (common.Address, error) {
if !chainEnabled {
return common.Address{}, nil
}
callData, err := postageStampABI.Pack("bzzToken")
if err != nil {
return common.Address{}, err
}
request := &transaction.TxRequest{
To: &postageContractAddress,
Data: callData,
GasPrice: nil,
GasLimit: 0,
Value: big.NewInt(0),
}
data, err := transactionService.Call(ctx, request)
if err != nil {
return common.Address{}, err
}
return common.BytesToAddress(data), nil
}
type noOpPostageContract struct{}
func (m *noOpPostageContract) CreateBatch(context.Context, *big.Int, uint8, bool, string) (common.Hash, []byte, error) {
return common.Hash{}, nil, nil
}
func (m *noOpPostageContract) TopUpBatch(context.Context, []byte, *big.Int) (common.Hash, error) {
return common.Hash{}, ErrChainDisabled
}
func (m *noOpPostageContract) DiluteBatch(context.Context, []byte, uint8) (common.Hash, error) {
return common.Hash{}, ErrChainDisabled
}
func (m *noOpPostageContract) ExpireBatches(context.Context) error {
return ErrChainDisabled
}