-
Notifications
You must be signed in to change notification settings - Fork 32
/
contractwatcher_test.go
205 lines (176 loc) · 6.44 KB
/
contractwatcher_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
package watcher_test
import (
"context"
"math/big"
"os"
"reflect"
"sync"
"testing"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
"github.com/pkg/errors"
. "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/synapsecns/sanguine/ethergo/chain/chainwatcher"
watcherMocks "github.com/synapsecns/sanguine/ethergo/chain/chainwatcher/mocks"
chainMocks "github.com/synapsecns/sanguine/ethergo/chain/mocks"
"github.com/synapsecns/sanguine/ethergo/chain/watcher"
"github.com/synapsecns/sanguine/ethergo/mocks"
"golang.org/x/sync/semaphore"
)
// filterLogsTracker tracks various calls attempted on filterLogs() mock.
type filterLogsTracker struct {
tb testing.TB
maxCalledHeight uint64
numberOfCalls uint64
calledBlocks []uint64
mux sync.Mutex
}
// newFilterLogsTracker creates a filter logs tracker.
func newFilterLogsTracker(tb testing.TB) filterLogsTracker {
tb.Helper()
return filterLogsTracker{
tb: tb,
maxCalledHeight: 0,
numberOfCalls: 0,
}
}
// update updates the filter logs tracker and performs some basic assertions.
func (f *filterLogsTracker) update(query ethereum.FilterQuery) {
f.mux.Lock()
defer f.mux.Unlock()
True(f.tb, query.ToBlock.Uint64() >= query.FromBlock.Uint64())
f.numberOfCalls++
f.maxCalledHeight = query.ToBlock.Uint64()
f.calledBlocks = append(f.calledBlocks, query.ToBlock.Uint64())
}
func (s *WatcherSuite) TestContractWatcherRetry() {
if os.Getenv("CI") != "" {
s.T().Skip("this flakes on ci. TODO fix this. This should never fail locally.")
}
const requiredConfs = 3
logTracker := newFilterLogsTracker(s.T())
mockBlockSubscription := NewMockBlockSubscriber(s.GetTestContext(), *big.NewInt(0))
blockSubscriber := chainwatcher.NewBlockHeightWatcher(s.GetTestContext(), 0, mockBlockSubscription)
mockEvmClient := new(chainMocks.Chain)
mockEvmClient.On("GetBigChainID").Return(params.AllEthashProtocolChanges.ChainID)
mockContract := mocks.MockAddress()
eventLog := make(chan interface{})
contractWatcher := watcher.NewTestContractWatcher(s.GetTestContext(), s.T(), mockEvmClient, blockSubscriber, requiredConfs)
err := contractWatcher.ListenOnContract(s.GetTestContext(), mockContract.String(), eventLog)
Nil(s.T(), err)
// let's push some heights where nothing happens and mmake sure it doesn't call more than required confs
mockEvmClient.On("FilterLogs", mock.Anything, mock.MatchedBy(func(filterQuery ethereum.FilterQuery) bool {
shouldReturn := filterQuery.ToBlock.Uint64() <= 10 || filterQuery.ToBlock.Uint64() == 12
if shouldReturn {
logTracker.update(filterQuery)
}
return shouldReturn
})).Return([]types.Log{}, nil)
producedHeights := 10
mockBlockSubscription.PushHeights(producedHeights)
s.Eventually(func() bool {
return logTracker.maxCalledHeight == uint64(producedHeights-requiredConfs)
})
// push up to the 10 and wait til we get there
mockBlockSubscription.PushHeights(requiredConfs)
s.Eventually(func() bool {
return logTracker.maxCalledHeight == uint64(producedHeights)
})
hasSentErr := false
mockEvmClient.On("FilterLogs", mock.Anything, mock.MatchedBy(func(filterQuery ethereum.FilterQuery) bool {
hasSentErr = true
shouldReturn := filterQuery.ToBlock.Uint64() == 11
if shouldReturn {
logTracker.update(filterQuery)
}
return shouldReturn
})).Return([]types.Log{}, errors.New("I'm an error")).Once()
// produce an error on the 11th block and make sure we recover
mockBlockSubscription.PushHeights(2)
// on subsequent calls produce successfully
mockEvmClient.On("FilterLogs", mock.Anything, mock.MatchedBy(func(filterQuery ethereum.FilterQuery) bool {
if !hasSentErr {
return false
}
shouldReturn := filterQuery.ToBlock.Uint64() == 11
if shouldReturn {
logTracker.update(filterQuery)
}
return shouldReturn
})).Return([]types.Log{{Address: mockContract}}, nil)
s.Eventually(func() bool {
return logTracker.maxCalledHeight == 12
})
}
// TestListeners tests a scenario with more than 1 listener listening to the contract observer.
//
//nolint:gocognit,cyclop
func (s *WatcherSuite) TestListeners() {
// timeout the test after thie period
ctx, cancel := context.WithTimeout(s.GetTestContext(), 30*time.Second)
defer cancel()
contractWatcher := watcher.NewTestContractWatcher(ctx, s.T(), new(chainMocks.Chain), new(watcherMocks.BlockHeightWatcher), 0)
mockContract := mocks.MockAddress()
// eventCount is how many events to listen for
const eventCount = 30
// listener count is how many listeners to create
const listenerCount = 10
// testEvents are the producerChan produces and the listener verify happened
testEvents := mocks.GetMockLogs(s.T(), eventCount)
initializationSemaphore := semaphore.NewWeighted(listenerCount)
// use a waitgroup to manage the listeners
var wg sync.WaitGroup
// create the listeners
for i := 0; i < listenerCount; i++ {
Nil(s.T(), initializationSemaphore.Acquire(ctx, 1))
wg.Add(1)
go func() {
defer wg.Done()
// verificationSlice is a copy of test events used to verify the listener received all logs
verificationSlice := make([]types.Log, len(testEvents))
copy(verificationSlice, testEvents)
listener := make(chan interface{})
contractWatcher.AddListener(mockContract, listener)
initializationSemaphore.Release(1)
for {
select {
case <-ctx.Done():
Nil(s.T(), ctx.Err())
return
case rawEvent := <-listener:
// convert the raw event to an event
event, ok := rawEvent.(types.Log)
if !ok {
s.T().Error("could not decode event from channel")
}
// verify the event is in the verification slice
for i, verifiedEvent := range verificationSlice {
if reflect.DeepEqual(verifiedEvent, event) {
// remove the event from the verification slice
verificationSlice = append(verificationSlice[:i], verificationSlice[i+1:]...)
break
}
}
// all events have been verified
if len(verificationSlice) == 0 {
return
}
}
}
}()
}
// wait until all the listeners are initialized
Nil(s.T(), initializationSemaphore.Acquire(ctx, listenerCount))
producerChan := make(chan types.Log)
err := contractWatcher.AddProducer(ctx, mockContract, producerChan)
Nil(s.T(), err)
for _, event := range testEvents {
producerChan <- event
}
// attempt to add another producer to the same contract
NotNil(s.T(), contractWatcher.AddProducer(ctx, mockContract, producerChan))
wg.Wait()
}