-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathutil_test.go
402 lines (342 loc) · 11.6 KB
/
util_test.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
package submitter_test
import (
"context"
"fmt"
"math/big"
"math/rand"
"sort"
"sync"
"testing"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/synapsecns/sanguine/core"
"github.com/synapsecns/sanguine/core/testsuite"
"github.com/synapsecns/sanguine/ethergo/backends/simulated"
"github.com/synapsecns/sanguine/ethergo/mocks"
"github.com/synapsecns/sanguine/ethergo/submitter"
"github.com/synapsecns/sanguine/ethergo/submitter/db"
"github.com/synapsecns/sanguine/ethergo/util"
"go.opentelemetry.io/otel/attribute"
"gotest.tools/assert"
)
func TestCopyTransactOpts(t *testing.T) {
// Test case 1: All fields populated
opts1 := &bind.TransactOpts{
From: common.HexToAddress("0x1234567890123456789012345678901234567890"),
Nonce: big.NewInt(1),
Signer: nil,
Value: big.NewInt(100),
GasPrice: big.NewInt(200),
GasFeeCap: big.NewInt(300),
GasTipCap: big.NewInt(400),
GasLimit: 500,
Context: context.Background(),
NoSend: true,
}
copyOpts1 := submitter.CopyTransactOpts(opts1)
assertTransactOptsEquality(t, opts1, copyOpts1)
// Test case 2: Some fields populated, others nil
opts2 := &bind.TransactOpts{
Nonce: nil,
Signer: nil,
Value: nil,
GasPrice: nil,
GasFeeCap: big.NewInt(300),
GasTipCap: big.NewInt(400),
GasLimit: 500,
Context: context.Background(),
NoSend: true,
}
copyOpts2 := submitter.CopyTransactOpts(opts2)
assertTransactOptsEquality(t, opts2, copyOpts2)
// Test case 3: All fields nil
opts3 := &bind.TransactOpts{
Nonce: nil,
Signer: nil,
Value: nil,
GasPrice: nil,
GasFeeCap: nil,
GasTipCap: nil,
GasLimit: 0,
Context: nil,
NoSend: true,
}
copyOpts3 := submitter.CopyTransactOpts(opts3)
assertTransactOptsEquality(t, opts3, copyOpts3)
}
func assertTransactOptsEquality(tb testing.TB, toA, toB *bind.TransactOpts) {
tb.Helper()
// Check that the pointer values of the big integer fields are different
assertBigIntsCopiedEqual(tb, toA.Nonce, toB.Nonce, "Nonce")
assertBigIntsCopiedEqual(tb, toA.Value, toB.Value, "Value")
assertBigIntsCopiedEqual(tb, toA.GasPrice, toB.GasPrice, "GasPrice")
assertBigIntsCopiedEqual(tb, toA.GasFeeCap, toB.GasFeeCap, "GasFeeCap")
assertBigIntsCopiedEqual(tb, toA.GasTipCap, toB.GasTipCap, "GasFeeCap")
assert.DeepEqual(tb, toA, toB, testsuite.BigIntComparer(), cmp.AllowUnexported(context.Background()))
}
// assertBigIntsCopiedEqual checks that the given big.Ints are equal and that
// they have different pointers.
func assertBigIntsCopiedEqual(tb testing.TB, original *big.Int, newVal *big.Int, fieldName string) {
tb.Helper()
if original == nil && newVal == nil {
return
}
if core.ArePointersEqual(original, newVal) {
tb.Errorf("%s has same pointer as original", fieldName)
}
if original.Cmp(newVal) != 0 {
tb.Errorf("%s is not equal", fieldName)
}
}
func TestAddressPtrToString(t *testing.T) {
// Test case 1: Address is nil
var address *common.Address
assert.Equal(t, submitter.AddressPtrToString(address), submitter.NullFieldAttribute)
// Test case 2: Address is not nil
address = core.PtrTo[common.Address](common.HexToAddress("0x1234567890123456789012345678901234567890"))
assert.Equal(t, submitter.AddressPtrToString(address), "0x1234567890123456789012345678901234567890")
}
func TestBigPtrToString(t *testing.T) {
// Test case: num is nil
var num *big.Int
expected := submitter.NullFieldAttribute
result := submitter.BigPtrToString(num)
if result != expected {
t.Errorf("bigPtrToString(nil) = %q; want %q", result, expected)
}
// Test case: num is an integer
num = big.NewInt(123)
expected = "123"
result = submitter.BigPtrToString(num)
if result != expected {
t.Errorf("bigPtrToString(123) = %q; want %q", result, expected)
}
}
func (s *SubmitterSuite) TestTxToAttributesNullFields() {
s.checkEmptyTx(types.NewTx(&types.DynamicFeeTx{}))
s.checkEmptyTx(types.NewTx(&types.LegacyTx{}))
}
func (s *SubmitterSuite) checkEmptyTx(rawTx *types.Transaction) {
tx := makeAttrMap(rawTx, uuid.New().String())
s.Require().Equal(tx[submitter.HashAttr].AsString(), rawTx.Hash().Hex())
s.Require().Equal(tx[submitter.NonceAttr].AsInt64(), int64(0))
s.Require().Equal(tx[submitter.GasLimitAttr].AsInt64(), int64(0))
s.Require().Equal(tx[submitter.ToAttr].AsString(), submitter.NullFieldAttribute)
s.Require().Equal(tx[submitter.ValueAttr].AsString(), "0")
s.Require().Equal(tx[submitter.DataAttr].AsString(), "")
if rawTx.Type() == types.DynamicFeeTxType {
s.Require().Equal(tx[submitter.GasTipCapAttr].AsString(), "0")
s.Require().Equal(tx[submitter.GasFeeCapAttr].AsString(), "0")
}
if rawTx.Type() == types.LegacyTxType {
s.Require().Equal(tx[submitter.GasPriceAttr].AsString(), "0")
}
}
func (s *SubmitterSuite) TestTxToAttributesLegacyTX() {
mockTX := mocks.GetMockTxes(s.GetTestContext(), s.T(), 1, types.LegacyTxType)[0]
mapAttr := makeAttrMap(mockTX, uuid.New().String())
s.Require().Equal(mapAttr[submitter.HashAttr].AsString(), mockTX.Hash().String())
s.Require().Equal(mapAttr[submitter.NonceAttr].AsInt64(), int64(mockTX.Nonce()))
s.Require().Equal(mapAttr[submitter.GasLimitAttr].AsInt64(), int64(mockTX.Gas()))
s.Require().Equal(mapAttr[submitter.ToAttr].AsString(), mockTX.To().String())
s.Require().Equal(mapAttr[submitter.ValueAttr].AsString(), mockTX.Value().String())
s.Require().Equal(mapAttr[submitter.DataAttr].AsString(), "")
s.Require().Equal(mapAttr[submitter.GasPriceAttr].AsString(), mockTX.GasPrice().String())
_, hasFeeCap := mapAttr[submitter.GasFeeCapAttr]
_, hasTipCap := mapAttr[submitter.GasTipCapAttr]
s.Require().False(hasFeeCap)
s.Require().False(hasTipCap)
s.Require().NotNil(mapAttr[submitter.FromAttr])
}
func (s *SubmitterSuite) TestTxToAttributesDynamicTX() {
mockTX := mocks.GetMockTxes(s.GetTestContext(), s.T(), 1, types.DynamicFeeTxType)[0]
mapAttr := makeAttrMap(mockTX, uuid.New().String())
s.Require().Equal(mapAttr[submitter.HashAttr].AsString(), mockTX.Hash().String())
s.Require().Equal(mapAttr[submitter.NonceAttr].AsInt64(), int64(mockTX.Nonce()))
s.Require().Equal(mapAttr[submitter.GasLimitAttr].AsInt64(), int64(mockTX.Gas()))
s.Require().Equal(mapAttr[submitter.ToAttr].AsString(), mockTX.To().String())
s.Require().Equal(mapAttr[submitter.ValueAttr].AsString(), mockTX.Value().String())
s.Require().Equal(mapAttr[submitter.DataAttr].AsString(), "")
s.Require().Equal(mapAttr[submitter.GasFeeCapAttr].AsString(), mockTX.GasFeeCap().String())
s.Require().Equal(mapAttr[submitter.GasTipCapAttr].AsString(), mockTX.GasTipCap().String())
_, hasGasPrice := mapAttr[submitter.GasPriceAttr]
s.Require().False(hasGasPrice)
s.Require().NotNil(mapAttr[submitter.FromAttr])
}
func (s *SubmitterSuite) TestSortTxes() {
expected := make(map[uint64][]*types.Transaction)
var allTxes []db.TX
var mapMux sync.Mutex
var sliceMux sync.Mutex
chainIDS := []int64{1, 2, 3, 4, 5}
var wg sync.WaitGroup
wg.Add(len(chainIDS))
for i := range chainIDS {
chainID := big.NewInt(chainIDS[i])
go func() {
defer wg.Done()
backend := simulated.NewSimulatedBackendWithChainID(s.GetTestContext(), s.T(), chainID)
testAddress := backend.GetTxContext(s.GetTestContext(), nil)
testKey := &keystore.Key{PrivateKey: testAddress.PrivateKey, Address: testAddress.From}
for i := 0; i < 50; i++ {
mockTX := mocks.MockTx(s.GetTestContext(), s.T(), backend, testKey, types.DynamicFeeTxType)
// add to map in order
mapMux.Lock()
expected[chainID.Uint64()] = append(expected[chainID.Uint64()], mockTX)
mapMux.Unlock()
sliceMux.Lock()
tx := db.TX{
Transaction: mockTX,
Status: db.Stored,
}
tx.UnsafeSetCreationTime(time.Now())
allTxes = append(allTxes, tx)
// shuffle the slice each time
rand.Shuffle(len(allTxes), func(i, j int) {
allTxes[i], allTxes[j] = allTxes[j], allTxes[i]
})
sliceMux.Unlock()
}
}()
}
wg.Wait()
sorted := submitter.SortTxes(allTxes, 50)
assert.Equal(s.T(), len(sorted), len(expected))
for chainID, txes := range expected {
for i := range txes {
assert.Equal(s.T(), sorted[chainID][i].Hash(), txes[i].Hash())
}
}
// check tx cap
numTxes := 10
sorted = submitter.SortTxes(allTxes, numTxes)
assert.Equal(s.T(), len(sorted), len(expected))
for chainID, txes := range expected {
chainTxes := txes[:numTxes]
for i := range chainTxes {
assert.Equal(s.T(), sorted[chainID][i].Hash(), txes[i].Hash())
}
}
}
func (s *SubmitterSuite) TestGroupTxesByNonce() {
ogTx := mocks.GetMockTxes(s.GetTestContext(), s.T(), 1, types.LegacyTxType)[0]
var txes []db.TX
// generate 1,000 txes with 100 different nonces
for nonce := 0; nonce < 100; nonce++ {
copiedTX, err := util.CopyTX(ogTx, util.WithNonce(uint64(nonce)))
s.Require().NoError(err)
for i := 0; i < 10; i++ {
newTX, err := util.CopyTX(copiedTX, util.WithGasPrice(big.NewInt(int64(i))))
s.Require().NoError(err)
txes = append(txes, db.TX{
Transaction: newTX,
Status: db.Pending,
})
}
}
nonceMap := submitter.GroupTxesByNonce(txes)
for i := 0; i < 100; i++ {
txList := nonceMap[uint64(i)]
for _, tx := range txList {
if tx.Nonce() != uint64(i) {
s.Require().NoError(fmt.Errorf("expected nonce %d, got %d", i, tx.Nonce()))
}
}
}
}
func makeAttrMap(tx *types.Transaction, UUID string) map[string]attribute.Value {
mapAttr := make(map[string]attribute.Value)
attr := submitter.TxToAttributes(tx, UUID)
for _, a := range attr {
mapAttr[string(a.Key)] = a.Value
}
return mapAttr
}
// Test for the outersection function.
func TestOutersection(t *testing.T) {
set := []*big.Int{
big.NewInt(2),
big.NewInt(4),
}
superset := []*big.Int{
big.NewInt(1),
big.NewInt(2),
big.NewInt(3),
big.NewInt(4),
big.NewInt(5),
}
expected := []*big.Int{
big.NewInt(1),
big.NewInt(3),
big.NewInt(5),
}
result := submitter.Outersection(set, superset)
if len(result) != len(expected) {
t.Fatalf("Expected %d elements, but got %d", len(expected), len(result))
}
for i, v := range result {
if v.Cmp(expected[i]) != 0 {
t.Errorf("Expected %s but got %s at index %d", expected[i], v, i)
}
}
}
// bigIntSlice is a type for sorting []*big.Int.
type bigIntSlice []*big.Int
func (p bigIntSlice) Len() int { return len(p) }
func (p bigIntSlice) Less(i, j int) bool { return p[i].Cmp(p[j]) < 0 }
func (p bigIntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// Test for the MapToBigIntSlice function with generics.
func TestMapToBigIntSlice(t *testing.T) {
m := map[uint64]struct{}{
1: {},
2: {},
3: {},
}
expected := []*big.Int{
big.NewInt(1),
big.NewInt(2),
big.NewInt(3),
}
result := submitter.MapToBigIntSlice(m)
if len(result) != len(expected) {
t.Fatalf("Expected %d elements, but got %d", len(expected), len(result))
}
sort.Sort(bigIntSlice(result))
sort.Sort(bigIntSlice(expected))
for i, v := range result {
if v.Cmp(expected[i]) != 0 {
t.Errorf("Expected %s but got %s at index %d", expected[i], v, i)
}
}
}
func TestMapToBigIntSliceWithStruct(t *testing.T) {
type MyStruct struct {
Value int
}
m := map[uint64]MyStruct{
1: {Value: 10},
2: {Value: 20},
3: {Value: 30},
}
expected := []*big.Int{
big.NewInt(1),
big.NewInt(2),
big.NewInt(3),
}
result := submitter.MapToBigIntSlice(m)
if len(result) != len(expected) {
t.Fatalf("Expected %d elements, but got %d", len(expected), len(result))
}
sort.Sort(bigIntSlice(result))
sort.Sort(bigIntSlice(expected))
for i, v := range result {
if v.Cmp(expected[i]) != 0 {
t.Errorf("Expected %s but got %s at index %d", expected[i], v, i)
}
}
}