-
Notifications
You must be signed in to change notification settings - Fork 337
/
chain.go
434 lines (384 loc) · 13.7 KB
/
chain.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
// 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 node
import (
"context"
"encoding/hex"
"errors"
"fmt"
"math/big"
"strings"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"github.com/ethersphere/bee/pkg/config"
"github.com/ethersphere/bee/pkg/crypto"
"github.com/ethersphere/bee/pkg/log"
"github.com/ethersphere/bee/pkg/p2p/libp2p"
"github.com/ethersphere/bee/pkg/postage/postagecontract"
"github.com/ethersphere/bee/pkg/sctx"
"github.com/ethersphere/bee/pkg/settlement"
"github.com/ethersphere/bee/pkg/settlement/swap"
"github.com/ethersphere/bee/pkg/settlement/swap/chequebook"
"github.com/ethersphere/bee/pkg/settlement/swap/erc20"
"github.com/ethersphere/bee/pkg/settlement/swap/priceoracle"
"github.com/ethersphere/bee/pkg/settlement/swap/swapprotocol"
"github.com/ethersphere/bee/pkg/storage"
"github.com/ethersphere/bee/pkg/transaction"
"github.com/ethersphere/bee/pkg/transaction/wrapped"
"github.com/ethersphere/go-sw3-abi/sw3abi"
"github.com/prometheus/client_golang/prometheus"
)
const (
maxDelay = 1 * time.Minute
cancellationDepth = 12
additionalConfirmations = 2
)
// InitChain will initialize the Ethereum backend at the given endpoint and
// set up the Transaction Service to interact with it using the provided signer.
func InitChain(
ctx context.Context,
logger log.Logger,
stateStore storage.StateStorer,
endpoint string,
oChainID int64,
signer crypto.Signer,
pollingInterval time.Duration,
chainEnabled bool,
) (transaction.Backend, common.Address, int64, transaction.Monitor, transaction.Service, error) {
var backend transaction.Backend = &noOpChainBackend{
chainID: oChainID,
}
if chainEnabled {
// connect to the real one
rpcClient, err := rpc.DialContext(ctx, endpoint)
if err != nil {
return nil, common.Address{}, 0, nil, nil, fmt.Errorf("dial eth client: %w", err)
}
var versionString string
err = rpcClient.CallContext(ctx, &versionString, "web3_clientVersion")
if err != nil {
logger.Info("could not connect to backend; in a swap-enabled network a working blockchain node (for xdai network in production, goerli in testnet) is required; check your node or specify another node using --swap-endpoint.", "backend_endpoint", endpoint)
return nil, common.Address{}, 0, nil, nil, fmt.Errorf("eth client get version: %w", err)
}
logger.Info("connected to ethereum backend", "version", versionString)
backend = wrapped.NewBackend(ethclient.NewClient(rpcClient))
}
chainID, err := backend.ChainID(ctx)
if err != nil {
return nil, common.Address{}, 0, nil, nil, fmt.Errorf("get chain id: %w", err)
}
overlayEthAddress, err := signer.EthereumAddress()
if err != nil {
return nil, common.Address{}, 0, nil, nil, fmt.Errorf("eth address: %w", err)
}
transactionMonitor := transaction.NewMonitor(logger, backend, overlayEthAddress, pollingInterval, cancellationDepth)
transactionService, err := transaction.NewService(logger, backend, signer, stateStore, chainID, transactionMonitor)
if err != nil {
return nil, common.Address{}, 0, nil, nil, fmt.Errorf("new transaction service: %w", err)
}
return backend, overlayEthAddress, chainID.Int64(), transactionMonitor, transactionService, nil
}
// InitChequebookFactory will initialize the chequebook factory with the given
// chain backend.
func InitChequebookFactory(
logger log.Logger,
backend transaction.Backend,
chainID int64,
transactionService transaction.Service,
factoryAddress string,
legacyFactoryAddresses []string,
) (chequebook.Factory, error) {
var currentFactory common.Address
var legacyFactories []common.Address
chainCfg, found := config.GetByChainID(chainID)
foundFactory, foundLegacyFactories := chainCfg.CurrentFactoryAddress, chainCfg.LegacyFactoryAddresses
if factoryAddress == "" {
if !found {
return nil, fmt.Errorf("no known factory address for this network (chain id: %d)", chainID)
}
currentFactory = foundFactory
logger.Info("using default factory address", "chain_id", chainID, "factory_address", currentFactory)
} else if !common.IsHexAddress(factoryAddress) {
return nil, errors.New("malformed factory address")
} else {
currentFactory = common.HexToAddress(factoryAddress)
logger.Info("using custom factory address", "factory_address", currentFactory)
}
if len(legacyFactoryAddresses) == 0 {
if found {
legacyFactories = foundLegacyFactories
}
} else {
for _, legacyAddress := range legacyFactoryAddresses {
if !common.IsHexAddress(legacyAddress) {
return nil, errors.New("malformed factory address")
}
legacyFactories = append(legacyFactories, common.HexToAddress(legacyAddress))
}
}
return chequebook.NewFactory(
backend,
transactionService,
currentFactory,
legacyFactories,
), nil
}
// InitChequebookService will initialize the chequebook service with the given
// chequebook factory and chain backend.
func InitChequebookService(
ctx context.Context,
logger log.Logger,
stateStore storage.StateStorer,
signer crypto.Signer,
chainID int64,
backend transaction.Backend,
overlayEthAddress common.Address,
transactionService transaction.Service,
chequebookFactory chequebook.Factory,
initialDeposit string,
deployGasPrice string,
erc20Service erc20.Service,
) (chequebook.Service, error) {
chequeSigner := chequebook.NewChequeSigner(signer, chainID)
deposit, ok := new(big.Int).SetString(initialDeposit, 10)
if !ok {
return nil, fmt.Errorf("initial swap deposit \"%s\" cannot be parsed", initialDeposit)
}
if deployGasPrice != "" {
gasPrice, ok := new(big.Int).SetString(deployGasPrice, 10)
if !ok {
return nil, fmt.Errorf("deploy gas price \"%s\" cannot be parsed", deployGasPrice)
}
ctx = sctx.SetGasPrice(ctx, gasPrice)
}
chequebookService, err := chequebook.Init(
ctx,
chequebookFactory,
stateStore,
logger,
deposit,
transactionService,
backend,
chainID,
overlayEthAddress,
chequeSigner,
erc20Service,
)
if err != nil {
return nil, fmt.Errorf("chequebook init: %w", err)
}
return chequebookService, nil
}
func initChequeStoreCashout(
stateStore storage.StateStorer,
swapBackend transaction.Backend,
chequebookFactory chequebook.Factory,
chainID int64,
overlayEthAddress common.Address,
transactionService transaction.Service,
) (chequebook.ChequeStore, chequebook.CashoutService) {
chequeStore := chequebook.NewChequeStore(
stateStore,
chequebookFactory,
chainID,
overlayEthAddress,
transactionService,
chequebook.RecoverCheque,
)
cashout := chequebook.NewCashoutService(
stateStore,
swapBackend,
transactionService,
chequeStore,
)
return chequeStore, cashout
}
// InitSwap will initialize and register the swap service.
func InitSwap(
p2ps *libp2p.Service,
logger log.Logger,
stateStore storage.StateStorer,
networkID uint64,
overlayEthAddress common.Address,
chequebookService chequebook.Service,
chequeStore chequebook.ChequeStore,
cashoutService chequebook.CashoutService,
accounting settlement.Accounting,
priceOracleAddress string,
chainID int64,
transactionService transaction.Service,
) (*swap.Service, priceoracle.Service, error) {
var currentPriceOracleAddress common.Address
if priceOracleAddress == "" {
chainCfg, found := config.GetByChainID(chainID)
currentPriceOracleAddress = chainCfg.SwapPriceOracleAddress
if !found {
return nil, nil, errors.New("no known price oracle address for this network")
}
} else {
currentPriceOracleAddress = common.HexToAddress(priceOracleAddress)
}
priceOracle := priceoracle.New(logger, currentPriceOracleAddress, transactionService, 300)
priceOracle.Start()
swapProtocol := swapprotocol.New(p2ps, logger, overlayEthAddress, priceOracle)
swapAddressBook := swap.NewAddressbook(stateStore)
cashoutAddress := overlayEthAddress
if chequebookService != nil {
cashoutAddress = chequebookService.Address()
}
swapService := swap.New(
swapProtocol,
logger,
stateStore,
chequebookService,
chequeStore,
swapAddressBook,
networkID,
cashoutService,
accounting,
cashoutAddress,
)
swapProtocol.SetSwap(swapService)
err := p2ps.AddProtocol(swapProtocol.Protocol())
if err != nil {
return nil, nil, err
}
return swapService, priceOracle, nil
}
func GetTxHash(stateStore storage.StateStorer, logger log.Logger, trxString string) ([]byte, error) {
if trxString != "" {
txHashTrimmed := strings.TrimPrefix(trxString, "0x")
if len(txHashTrimmed) != 64 {
return nil, errors.New("invalid length")
}
txHash, err := hex.DecodeString(txHashTrimmed)
if err != nil {
return nil, err
}
logger.Info("using the provided transaction hash", "tx_hash", txHashTrimmed)
return txHash, nil
}
var txHash common.Hash
key := chequebook.ChequebookDeploymentKey
if err := stateStore.Get(key, &txHash); err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, errors.New("chequebook deployment transaction hash not found, please specify the transaction hash manually")
}
return nil, err
}
logger.Info("using the chequebook transaction hash", "tx_hash", txHash)
return txHash.Bytes(), nil
}
func GetTxNextBlock(ctx context.Context, logger log.Logger, backend transaction.Backend, monitor transaction.Monitor, duration time.Duration, trx []byte, blockHash string) ([]byte, error) {
if blockHash != "" {
blockHashTrimmed := strings.TrimPrefix(blockHash, "0x")
if len(blockHashTrimmed) != 64 {
return nil, errors.New("invalid length")
}
blockHash, err := hex.DecodeString(blockHashTrimmed)
if err != nil {
return nil, err
}
logger.Info("using the provided block hash", "block_hash", hex.EncodeToString(blockHash))
return blockHash, nil
}
block, err := transaction.WaitBlockAfterTransaction(ctx, backend, duration, common.BytesToHash(trx), additionalConfirmations)
if err != nil {
return nil, err
}
hash := block.Hash()
hashBytes := hash.Bytes()
logger.Info("using the next block hash from the blockchain", "block_hash", hex.EncodeToString(hashBytes))
return hashBytes, nil
}
// noOpChequebookService is a noOp implementation for chequebook.Service interface.
type noOpChequebookService struct{}
func (m *noOpChequebookService) Deposit(context.Context, *big.Int) (hash common.Hash, err error) {
return hash, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) Withdraw(context.Context, *big.Int) (hash common.Hash, err error) {
return hash, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) WaitForDeposit(context.Context, common.Hash) error {
return postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) Balance(context.Context) (*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) AvailableBalance(context.Context) (*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) Address() common.Address {
return common.Address{}
}
func (m *noOpChequebookService) Issue(context.Context, common.Address, *big.Int, chequebook.SendChequeFunc) (*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) LastCheque(common.Address) (*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) LastCheques() (map[common.Address]*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
// noOpChainBackend is a noOp implementation for transaction.Backend interface.
type noOpChainBackend struct {
chainID int64
}
func (m noOpChainBackend) Metrics() []prometheus.Collector {
return nil
}
func (m noOpChainBackend) CodeAt(context.Context, common.Address, *big.Int) ([]byte, error) {
return common.FromHex(sw3abi.SimpleSwapFactoryDeployedBinv0_4_0), nil
}
func (m noOpChainBackend) CallContract(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error) {
return nil, errors.New("disabled chain backend")
}
func (m noOpChainBackend) HeaderByNumber(context.Context, *big.Int) (*types.Header, error) {
h := new(types.Header)
h.Time = uint64(time.Now().Unix())
return h, nil
}
func (m noOpChainBackend) PendingNonceAt(context.Context, common.Address) (uint64, error) {
panic("chain no op: PendingNonceAt")
}
func (m noOpChainBackend) SuggestGasPrice(context.Context) (*big.Int, error) {
panic("chain no op: SuggestGasPrice")
}
func (m noOpChainBackend) SuggestGasTipCap(context.Context) (*big.Int, error) {
panic("chain no op: SuggestGasPrice")
}
func (m noOpChainBackend) EstimateGas(context.Context, ethereum.CallMsg) (uint64, error) {
panic("chain no op: EstimateGas")
}
func (m noOpChainBackend) SendTransaction(context.Context, *types.Transaction) error {
panic("chain no op: SendTransaction")
}
func (m noOpChainBackend) TransactionReceipt(context.Context, common.Hash) (*types.Receipt, error) {
r := new(types.Receipt)
r.BlockNumber = big.NewInt(1)
return r, nil
}
func (m noOpChainBackend) TransactionByHash(context.Context, common.Hash) (tx *types.Transaction, isPending bool, err error) {
panic("chain no op: TransactionByHash")
}
func (m noOpChainBackend) BlockNumber(context.Context) (uint64, error) {
return 4, nil
}
func (m noOpChainBackend) BalanceAt(context.Context, common.Address, *big.Int) (*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m noOpChainBackend) NonceAt(context.Context, common.Address, *big.Int) (uint64, error) {
panic("chain no op: NonceAt")
}
func (m noOpChainBackend) FilterLogs(context.Context, ethereum.FilterQuery) ([]types.Log, error) {
panic("chain no op: FilterLogs")
}
func (m noOpChainBackend) ChainID(context.Context) (*big.Int, error) {
return big.NewInt(m.chainID), nil
}
func (m noOpChainBackend) Close() {}