-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing.go
273 lines (218 loc) · 5.51 KB
/
testing.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
package tests
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"math/big"
"net"
"testing"
"time"
"github.com/golang/protobuf/ptypes/any"
libp2pCrypto "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/umbracle/ethgo"
"github.com/esportzvio/frietorchain/crypto"
txpoolOp "github.com/esportzvio/frietorchain/txpool/proto"
"github.com/esportzvio/frietorchain/types"
"github.com/stretchr/testify/assert"
"github.com/umbracle/ethgo/jsonrpc"
empty "google.golang.org/protobuf/types/known/emptypb"
)
var (
ErrTimeout = errors.New("timeout")
)
func GenerateKeyAndAddr(t *testing.T) (*ecdsa.PrivateKey, types.Address) {
t.Helper()
key, err := crypto.GenerateECDSAKey()
assert.NoError(t, err)
addr := crypto.PubKeyToAddress(&key.PublicKey)
return key, addr
}
func GenerateTestMultiAddr(t *testing.T) multiaddr.Multiaddr {
t.Helper()
priv, _, err := libp2pCrypto.GenerateKeyPair(libp2pCrypto.Secp256k1, 256)
if err != nil {
t.Fatalf("Unable to generate key pair, %v", err)
}
nodeID, err := peer.IDFromPrivateKey(priv)
assert.NoError(t, err)
port, portErr := GetFreePort()
if portErr != nil {
t.Fatalf("Unable to fetch free port, %v", portErr)
}
addr, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d/p2p/%s", port, nodeID))
assert.NoError(t, err)
return addr
}
func RetryUntilTimeout(ctx context.Context, f func() (interface{}, bool)) (interface{}, error) {
type result struct {
data interface{}
err error
}
resCh := make(chan result, 1)
go func() {
defer close(resCh)
for {
select {
case <-ctx.Done():
resCh <- result{nil, ErrTimeout}
return
default:
res, retry := f()
if !retry {
resCh <- result{res, nil}
return
}
}
time.Sleep(time.Second)
}
}()
res := <-resCh
return res.data, res.err
}
// WaitUntilTxPoolEmpty waits until node has 0 transactions in txpool,
// otherwise returns timeout
func WaitUntilTxPoolEmpty(
ctx context.Context,
client txpoolOp.TxnPoolOperatorClient,
) (
*txpoolOp.TxnPoolStatusResp,
error,
) {
res, err := RetryUntilTimeout(ctx, func() (interface{}, bool) {
subCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
res, _ := client.Status(subCtx, &empty.Empty{})
if res != nil && res.Length == 0 {
return res, false
}
return nil, true
})
if err != nil {
return nil, err
}
status, ok := res.(*txpoolOp.TxnPoolStatusResp)
if !ok {
return nil, errors.New("invalid type assertion to txpool status response")
}
return status, nil
}
func WaitForNonce(
ctx context.Context,
ethClient *jsonrpc.Eth,
addr ethgo.Address,
expectedNonce uint64,
) (
interface{},
error,
) {
type result struct {
nonce uint64
err error
}
resObj, err := RetryUntilTimeout(ctx, func() (interface{}, bool) {
nonce, err := ethClient.GetNonce(addr, ethgo.Latest)
if err != nil {
// error -> stop retrying
return result{nonce, err}, false
}
if nonce >= expectedNonce {
// match -> return result
return result{nonce, nil}, false
}
// continue retrying
return nil, true
})
if err != nil {
return nil, err
}
res, ok := resObj.(result)
if !ok {
return nil, errors.New("invalid type assertion")
}
return res.nonce, res.err
}
// WaitForReceipt waits transaction receipt
func WaitForReceipt(ctx context.Context, client *jsonrpc.Eth, hash ethgo.Hash) (*ethgo.Receipt, error) {
type result struct {
receipt *ethgo.Receipt
err error
}
res, err := RetryUntilTimeout(ctx, func() (interface{}, bool) {
receipt, err := client.GetTransactionReceipt(hash)
if err != nil && err.Error() != "not found" {
return result{receipt, err}, false
}
if receipt != nil {
return result{receipt, nil}, false
}
return nil, true
})
if err != nil {
return nil, err
}
data, ok := res.(result)
if !ok {
return nil, errors.New("invalid type assertion")
}
return data.receipt, data.err
}
// GetFreePort asks the kernel for a free open port that is ready to use
func GetFreePort() (port int, err error) {
var addr *net.TCPAddr
if addr, err = net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
var l *net.TCPListener
if l, err = net.ListenTCP("tcp", addr); err == nil {
defer func(l *net.TCPListener) {
_ = l.Close()
}(l)
netAddr, ok := l.Addr().(*net.TCPAddr)
if !ok {
return 0, errors.New("invalid type assert to TCPAddr")
}
return netAddr.Port, nil
}
}
return
}
type GenerateTxReqParams struct {
Nonce uint64
ReferenceAddr types.Address
ReferenceKey *ecdsa.PrivateKey
ToAddress types.Address
GasPrice *big.Int
Value *big.Int
Input []byte
}
func generateTx(params GenerateTxReqParams) (*types.Transaction, error) {
signer := crypto.NewEIP155Signer(100, true)
signedTx, signErr := signer.SignTx(&types.Transaction{
Nonce: params.Nonce,
From: params.ReferenceAddr,
To: ¶ms.ToAddress,
GasPrice: params.GasPrice,
Gas: 1000000,
Value: params.Value,
Input: params.Input,
V: big.NewInt(27), // it is necessary to encode in rlp
}, params.ReferenceKey)
if signErr != nil {
return nil, fmt.Errorf("unable to sign transaction, %w", signErr)
}
return signedTx, nil
}
func GenerateAddTxnReq(params GenerateTxReqParams) (*txpoolOp.AddTxnReq, error) {
txn, err := generateTx(params)
if err != nil {
return nil, err
}
msg := &txpoolOp.AddTxnReq{
Raw: &any.Any{
Value: txn.MarshalRLP(),
},
From: types.ZeroAddress.String(),
}
return msg, nil
}