arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/test/ethclient.go
test/ethclient.goRaw
 1package test
 2
 3import (
 4	"context"
 5	"math/big"
 6	"time"
 7
 8	"github.com/ethereum/go-ethereum/core/types"
 9	"github.com/hermeznetwork/hermez-node/common"
10	"github.com/hermeznetwork/hermez-node/log"
11)
12
13// Client implements the eth.IClient interface, allowing to manipulate the
14// values for testing, working with deterministic results.
15type Client struct {
16	log      bool
17	blockNum *big.Int
18}
19
20// NewTestEthClient returns a new test Client that implements the eth.IClient
21// interface, at the given initialBlockNumber.
22func NewTestEthClient(l bool, initialBlockNumber int64) *Client {
23	return &Client{
24		log:      l,
25		blockNum: big.NewInt(initialBlockNumber),
26	}
27}
28
29// Advance moves one block forward
30func (c *Client) Advance() {
31	c.blockNum = c.blockNum.Add(c.blockNum, big.NewInt(1))
32	if c.log {
33		log.Debugf("TestEthClient blockNum advanced: %d", c.blockNum)
34	}
35}
36
37// SetBlockNum sets the Client.blockNum to the given blockNum
38func (c *Client) SetBlockNum(blockNum *big.Int) {
39	c.blockNum = blockNum
40	if c.log {
41		log.Debugf("TestEthClient blockNum set to: %d", c.blockNum)
42	}
43}
44
45// CurrentBlock returns the current blockNum
46func (c *Client) CurrentBlock() (*big.Int, error) {
47	return c.blockNum, nil
48}
49
50func newHeader(number *big.Int) *types.Header {
51	return &types.Header{
52		Number: number,
53		Time:   uint64(number.Int64()),
54	}
55}
56
57// HeaderByNumber returns the *types.Header for the given block number in a
58// deterministic way.
59func (c *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
60	return newHeader(number), nil
61}
62
63// BlockByNumber returns the *common.Block for the given block number in a
64// deterministic way.
65func (c *Client) BlockByNumber(ctx context.Context, number *big.Int) (*common.Block, error) {
66	header := newHeader(number)
67
68	return &common.Block{
69		EthBlockNum: uint64(number.Int64()),
70		Timestamp:   time.Unix(number.Int64(), 0),
71		Hash:        header.Hash(),
72	}, nil
73}
74
75// ForgeCall send the *common.CallDataForge to the Forge method of the mock
76// smart contract
77func (c *Client) ForgeCall(*common.CallDataForge) ([]byte, error) {
78	return nil, nil
79}