-
Notifications
You must be signed in to change notification settings - Fork 387
Expand file tree
/
Copy pathcontract.go
More file actions
572 lines (473 loc) · 14.8 KB
/
Copy pathcontract.go
File metadata and controls
572 lines (473 loc) · 14.8 KB
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// 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"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethersphere/bee/v2/pkg/postage"
"github.com/ethersphere/bee/v2/pkg/sctx"
"github.com/ethersphere/bee/v2/pkg/transaction"
"github.com/ethersphere/bee/v2/pkg/util/abiutil"
"github.com/ethersphere/go-sw3-abi/sw3abi"
)
var (
BucketDepth = uint8(16)
erc20ABI = abiutil.MustParseABI(sw3abi.ERC20ABIv0_6_9)
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")
ErrInsufficientValidity = errors.New("insufficient validity")
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)
Paused(ctx context.Context) (bool, error)
PostageBatchExpirer
}
type PostageBatchExpirer interface {
ExpireBatches(ctx context.Context) error
}
type postageContract struct {
owner common.Address
postageStampContractAddress common.Address
postageStampContractABI abi.ABI
bzzTokenAddress common.Address
transactionService transaction.Service
postageService postage.Service
postageStorer postage.Storer
// Cached postage stamp contract event topics.
batchCreatedTopic common.Hash
batchTopUpTopic common.Hash
batchDepthIncreaseTopic common.Hash
gasLimit uint64
}
func New(
owner common.Address,
postageStampContractAddress common.Address,
postageStampContractABI abi.ABI,
bzzTokenAddress common.Address,
transactionService transaction.Service,
postageService postage.Service,
postageStorer postage.Storer,
chainEnabled bool,
gasLimit uint64,
) Interface {
if !chainEnabled {
return new(noOpPostageContract)
}
return &postageContract{
owner: owner,
postageStampContractAddress: postageStampContractAddress,
postageStampContractABI: postageStampContractABI,
bzzTokenAddress: bzzTokenAddress,
transactionService: transactionService,
postageService: postageService,
postageStorer: postageStorer,
batchCreatedTopic: postageStampContractABI.Events["BatchCreated"].ID,
batchTopUpTopic: postageStampContractABI.Events["BatchTopUp"].ID,
batchDepthIncreaseTopic: postageStampContractABI.Events["BatchDepthIncrease"].ID,
gasLimit: gasLimit,
}
}
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(25))
if err != nil {
return fmt.Errorf("expire limited batches: %w", err)
}
}
return nil
}
func (c *postageContract) expiredBatchesExists(ctx context.Context) (bool, error) {
callData, err := c.postageStampContractABI.Pack("expiredBatchesExist")
if err != nil {
return false, err
}
result, err := c.transactionService.Call(ctx, &transaction.TxRequest{
To: &c.postageStampContractAddress,
Data: callData,
})
if err != nil {
return false, err
}
results, err := c.postageStampContractABI.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 := c.postageStampContractABI.Pack("expireLimited", count)
if err != nil {
return err
}
_, err = c.sendTransaction(ctx, callData, "expire limited batches")
if err != nil {
return err
}
return nil
}
func (c *postageContract) sendApproveTransaction(ctx context.Context, amount *big.Int) (receipt *types.Receipt, err error) {
callData, err := erc20ABI.Pack("approve", c.postageStampContractAddress, amount)
if err != nil {
return nil, err
}
request := &transaction.TxRequest{
To: &c.bzzTokenAddress,
Data: callData,
GasPrice: sctx.GetGasPrice(ctx),
GasLimit: max(sctx.GetGasLimit(ctx), c.gasLimit),
Value: big.NewInt(0),
Description: approveDescription,
}
defer func() {
err = c.transactionService.UnwrapABIError(
ctx,
request,
err,
c.postageStampContractABI.Errors,
)
}()
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) sendTransaction(ctx context.Context, callData []byte, desc string) (receipt *types.Receipt, err error) {
request := &transaction.TxRequest{
To: &c.postageStampContractAddress,
Data: callData,
GasPrice: sctx.GetGasPrice(ctx),
GasLimit: max(sctx.GetGasLimit(ctx), c.gasLimit),
Value: big.NewInt(0),
Description: desc,
}
defer func() {
err = c.transactionService.UnwrapABIError(
ctx,
request,
err,
c.postageStampContractABI.Errors,
)
}()
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 := c.postageStampContractABI.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 := c.postageStampContractABI.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 := c.postageStampContractABI.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) getProperty(ctx context.Context, propertyName string, out any) error {
callData, err := c.postageStampContractABI.Pack(propertyName)
if err != nil {
return err
}
result, err := c.transactionService.Call(ctx, &transaction.TxRequest{
To: &c.postageStampContractAddress,
Data: callData,
})
if err != nil {
return err
}
results, err := c.postageStampContractABI.Unpack(propertyName, result)
if err != nil {
return err
}
if len(results) == 0 {
return errors.New("unexpected empty results")
}
abi.ConvertType(results[0], out)
return nil
}
func (c *postageContract) getMinInitialBalance(ctx context.Context) (uint64, error) {
var lastPrice uint64
err := c.getProperty(ctx, "lastPrice", &lastPrice)
if err != nil {
return 0, err
}
var minimumValidityBlocks uint64
err = c.getProperty(ctx, "minimumValidityBlocks", &minimumValidityBlocks)
if err != nil {
return 0, err
}
return lastPrice * minimumValidityBlocks, 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 = fmt.Errorf("insufficient balance. amount %d, balance %d: %w", totalAmount, balance, ErrInsufficientFunds)
return
}
minInitialBalance, err := c.getMinInitialBalance(ctx)
if err != nil {
return
}
if initialBalance.Cmp(big.NewInt(int64(minInitialBalance))) <= 0 {
err = fmt.Errorf("insufficient initial balance for 24h minimum validity. balance %d, minimum amount: %d: %w", initialBalance, minInitialBalance, ErrInsufficientValidity)
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
}
for _, ev := range receipt.Logs {
if ev.Address == c.postageStampContractAddress && len(ev.Topics) > 0 && ev.Topics[0] == c.batchCreatedTopic {
var createdEvent batchCreatedEvent
err = transaction.ParseEvent(&c.postageStampContractABI, "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
}
txHash = receipt.TxHash
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 {
return
}
for _, ev := range receipt.Logs {
if ev.Address == c.postageStampContractAddress && len(ev.Topics) > 0 && ev.Topics[0] == c.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
}
for _, ev := range receipt.Logs {
if ev.Address == c.postageStampContractAddress && len(ev.Topics) > 0 && ev.Topics[0] == c.batchDepthIncreaseTopic {
txHash = receipt.TxHash
return
}
}
err = ErrBatchDilute
return
}
func (c *postageContract) Paused(ctx context.Context) (bool, error) {
callData, err := c.postageStampContractABI.Pack("paused")
if err != nil {
return false, err
}
result, err := c.transactionService.Call(ctx, &transaction.TxRequest{
To: &c.postageStampContractAddress,
Data: callData,
})
if err != nil {
return false, err
}
results, err := c.postageStampContractABI.Unpack("paused", result)
if err != nil {
return false, err
}
if len(results) == 0 {
return false, errors.New("unexpected empty results")
}
return results[0].(bool), nil
}
type batchCreatedEvent struct {
BatchId [32]byte
TotalAmount *big.Int
NormalisedBalance *big.Int
Owner common.Address
Depth uint8
BucketDepth uint8
ImmutableFlag bool
}
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) Paused(context.Context) (bool, error) {
return false, nil
}
func (m *noOpPostageContract) ExpireBatches(context.Context) error {
return ErrChainDisabled
}
func LookupERC20Address(ctx context.Context, transactionService transaction.Service, postageStampContractAddress common.Address, postageStampContractABI abi.ABI, chainEnabled bool) (common.Address, error) {
if !chainEnabled {
return common.Address{}, nil
}
callData, err := postageStampContractABI.Pack("bzzToken")
if err != nil {
return common.Address{}, err
}
request := &transaction.TxRequest{
To: &postageStampContractAddress,
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
}