This repository has been archived by the owner on Jul 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathwriter_methods.go
345 lines (296 loc) · 12 KB
/
writer_methods.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
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: LGPL-3.0-only
package ethereum
import (
"context"
"errors"
"math/big"
"time"
utils "github.com/ChainSafe/ChainBridge/shared/ethereum"
"github.com/ChainSafe/chainbridge-utils/msg"
log "github.com/ChainSafe/log15"
)
// Number of blocks to wait for an finalization event
const ExecuteBlockWatchLimit = 100
// Time between retrying a failed tx
const TxRetryInterval = time.Second * 2
// Maximum number of tx retries before exiting
const TxRetryLimit = 10
var ErrNonceTooLow = errors.New("nonce too low")
var ErrTxUnderpriced = errors.New("replacement transaction underpriced")
var ErrFatalTx = errors.New("submission of transaction failed")
var ErrFatalQuery = errors.New("query of chain state failed")
// proposalIsComplete returns true if the proposal state is either Passed, Transferred or Cancelled
func (w *writer) proposalIsComplete(srcId msg.ChainId, nonce msg.Nonce, dataHash [32]byte) bool {
prop, err := w.bridgeContract.GetProposal(w.conn.CallOpts(), uint8(srcId), uint64(nonce), dataHash)
if err != nil {
w.log.Error("Failed to check proposal existence", "err", err)
return false
}
return prop.Status == PassedStatus || prop.Status == TransferredStatus || prop.Status == CancelledStatus
}
// proposalIsComplete returns true if the proposal state is Transferred or Cancelled
func (w *writer) proposalIsFinalized(srcId msg.ChainId, nonce msg.Nonce, dataHash [32]byte) bool {
prop, err := w.bridgeContract.GetProposal(w.conn.CallOpts(), uint8(srcId), uint64(nonce), dataHash)
if err != nil {
w.log.Error("Failed to check proposal existence", "err", err)
return false
}
return prop.Status == TransferredStatus || prop.Status == CancelledStatus // Transferred (3)
}
func (w *writer) proposalIsPassed(srcId msg.ChainId, nonce msg.Nonce, dataHash [32]byte) bool {
prop, err := w.bridgeContract.GetProposal(w.conn.CallOpts(), uint8(srcId), uint64(nonce), dataHash)
if err != nil {
w.log.Error("Failed to check proposal existence", "err", err)
return false
}
return prop.Status == PassedStatus
}
// hasVoted checks if this relayer has already voted
func (w *writer) hasVoted(srcId msg.ChainId, nonce msg.Nonce, dataHash [32]byte) bool {
hasVoted, err := w.bridgeContract.HasVotedOnProposal(w.conn.CallOpts(), utils.IDAndNonce(srcId, nonce), dataHash, w.conn.Opts().From)
if err != nil {
w.log.Error("Failed to check proposal existence", "err", err)
return false
}
return hasVoted
}
func (w *writer) shouldVote(m msg.Message, dataHash [32]byte) bool {
// Check if proposal has passed and skip if Passed or Transferred
if w.proposalIsComplete(m.Source, m.DepositNonce, dataHash) {
w.log.Info("Proposal complete, not voting", "src", m.Source, "nonce", m.DepositNonce)
return false
}
// Check if relayer has previously voted
if w.hasVoted(m.Source, m.DepositNonce, dataHash) {
w.log.Info("Relayer has already voted, not voting", "src", m.Source, "nonce", m.DepositNonce)
return false
}
return true
}
// createErc20Proposal creates an Erc20 proposal.
// Returns true if the proposal is successfully created or is complete
func (w *writer) createErc20Proposal(m msg.Message) bool {
w.log.Info("Creating erc20 proposal", "src", m.Source, "nonce", m.DepositNonce)
data := ConstructErc20ProposalData(m.Payload[0].([]byte), m.Payload[1].([]byte))
dataHash := utils.Hash(append(w.cfg.erc20HandlerContract.Bytes(), data...))
if !w.shouldVote(m, dataHash) {
if w.proposalIsPassed(m.Source, m.DepositNonce, dataHash) {
// We should not vote for this proposal but it is ready to be executed
w.executeProposal(m, data, dataHash)
return true
} else {
return false
}
}
// Capture latest block so when know where to watch from
latestBlock, err := w.conn.LatestBlock()
if err != nil {
w.log.Error("Unable to fetch latest block", "err", err)
return false
}
// watch for execution event
go w.watchThenExecute(m, data, dataHash, latestBlock)
w.voteProposal(m, dataHash)
return true
}
// createErc721Proposal creates an Erc721 proposal.
// Returns true if the proposal is succesfully created or is complete
func (w *writer) createErc721Proposal(m msg.Message) bool {
w.log.Info("Creating erc721 proposal", "src", m.Source, "nonce", m.DepositNonce)
data := ConstructErc721ProposalData(m.Payload[0].([]byte), m.Payload[1].([]byte), m.Payload[2].([]byte))
dataHash := utils.Hash(append(w.cfg.erc721HandlerContract.Bytes(), data...))
if !w.shouldVote(m, dataHash) {
if w.proposalIsPassed(m.Source, m.DepositNonce, dataHash) {
// We should not vote for this proposal but it is ready to be executed
w.executeProposal(m, data, dataHash)
return true
} else {
return false
}
}
// Capture latest block so we know where to watch from
latestBlock, err := w.conn.LatestBlock()
if err != nil {
w.log.Error("Unable to fetch latest block", "err", err)
return false
}
// watch for execution event
go w.watchThenExecute(m, data, dataHash, latestBlock)
w.voteProposal(m, dataHash)
return true
}
// createGenericDepositProposal creates a generic proposal
// returns true if the proposal is complete or is succesfully created
func (w *writer) createGenericDepositProposal(m msg.Message) bool {
w.log.Info("Creating generic proposal", "src", m.Source, "nonce", m.DepositNonce)
metadata := m.Payload[0].([]byte)
data := ConstructGenericProposalData(metadata)
toHash := append(w.cfg.genericHandlerContract.Bytes(), data...)
dataHash := utils.Hash(toHash)
if !w.shouldVote(m, dataHash) {
if w.proposalIsPassed(m.Source, m.DepositNonce, dataHash) {
// We should not vote for this proposal but it is ready to be executed
w.executeProposal(m, data, dataHash)
return true
} else {
return false
}
}
// Capture latest block so when know where to watch from
latestBlock, err := w.conn.LatestBlock()
if err != nil {
w.log.Error("Unable to fetch latest block", "err", err)
return false
}
// watch for execution event
go w.watchThenExecute(m, data, dataHash, latestBlock)
w.voteProposal(m, dataHash)
return true
}
// watchThenExecute watches for the latest block and executes once the matching finalized event is found
func (w *writer) watchThenExecute(m msg.Message, data []byte, dataHash [32]byte, latestBlock *big.Int) {
w.log.Info("Watching for finalization event", "src", m.Source, "nonce", m.DepositNonce)
// watching for the latest block, querying and matching the finalized event will be retried up to ExecuteBlockWatchLimit times
for i := 0; i < ExecuteBlockWatchLimit; i++ {
select {
case <-w.stop:
return
default:
// watch for the lastest block, retry up to BlockRetryLimit times
for waitRetrys := 0; waitRetrys < BlockRetryLimit; waitRetrys++ {
err := w.conn.WaitForBlock(latestBlock, w.cfg.blockConfirmations)
if err != nil {
w.log.Error("Waiting for block failed", "err", err)
// Exit if retries exceeded
if waitRetrys+1 == BlockRetryLimit {
w.log.Error("Waiting for block retries exceeded, shutting down")
w.sysErr <- ErrFatalQuery
return
}
} else {
break
}
}
// query for logs
query := buildQuery(w.cfg.bridgeContract, utils.ProposalEvent, latestBlock, latestBlock)
evts, err := w.conn.Client().FilterLogs(context.Background(), query)
if err != nil {
w.log.Error("Failed to fetch logs", "err", err)
return
}
// execute the proposal once we find the matching finalized event
for _, evt := range evts {
sourceId := evt.Topics[1].Big().Uint64()
depositNonce := evt.Topics[2].Big().Uint64()
status := evt.Topics[3].Big().Uint64()
if m.Source == msg.ChainId(sourceId) &&
m.DepositNonce.Big().Uint64() == depositNonce &&
utils.IsFinalized(uint8(status)) {
w.executeProposal(m, data, dataHash)
return
} else {
w.log.Trace("Ignoring event", "src", sourceId, "nonce", depositNonce)
}
}
w.log.Trace("No finalization event found in current block", "block", latestBlock, "src", m.Source, "nonce", m.DepositNonce)
latestBlock = latestBlock.Add(latestBlock, big.NewInt(1))
}
}
log.Warn("Block watch limit exceeded, skipping execution", "source", m.Source, "dest", m.Destination, "nonce", m.DepositNonce)
}
// voteProposal submits a vote proposal
// a vote proposal will try to be submitted up to the TxRetryLimit times
func (w *writer) voteProposal(m msg.Message, dataHash [32]byte) {
for i := 0; i < TxRetryLimit; i++ {
select {
case <-w.stop:
return
default:
err := w.conn.LockAndUpdateOpts()
if err != nil {
w.log.Error("Failed to update tx opts", "err", err)
continue
}
// These store the gas limit and price before a transaction is sent for logging in case of a failure
// This declaration is necessary as tx will be nil in the case of an error when sending VoteProposal()
// We must also declare variables instead of using w.conn.Opts() directly as the opts are currently locked
// here but for all the logging after line 272 the w.conn.Opts() is unlocked and could be changed by another process
gasLimit := w.conn.Opts().GasLimit
gasPrice := w.conn.Opts().GasPrice
tx, err := w.bridgeContract.VoteProposal(
w.conn.Opts(),
uint8(m.Source),
uint64(m.DepositNonce),
m.ResourceId,
dataHash,
)
w.conn.UnlockOpts()
if err == nil {
w.log.Info("Submitted proposal vote", "tx", tx.Hash(), "src", m.Source, "depositNonce", m.DepositNonce, "gasPrice", tx.GasPrice().String())
if w.metrics != nil {
w.metrics.VotesSubmitted.Inc()
}
return
} else if err.Error() == ErrNonceTooLow.Error() || err.Error() == ErrTxUnderpriced.Error() {
w.log.Debug("Nonce too low, will retry")
time.Sleep(TxRetryInterval)
} else {
w.log.Warn("Voting failed", "source", m.Source, "dest", m.Destination, "depositNonce", m.DepositNonce, "gasLimit", gasLimit, "gasPrice", gasPrice, "err", err)
time.Sleep(TxRetryInterval)
}
// Verify proposal is still open for voting, otherwise no need to retry
if w.proposalIsComplete(m.Source, m.DepositNonce, dataHash) {
w.log.Info("Proposal voting complete on chain", "src", m.Source, "dst", m.Destination, "nonce", m.DepositNonce)
return
}
}
}
w.log.Error("Submission of Vote transaction failed", "source", m.Source, "dest", m.Destination, "depositNonce", m.DepositNonce)
w.sysErr <- ErrFatalTx
}
// executeProposal executes the proposal
func (w *writer) executeProposal(m msg.Message, data []byte, dataHash [32]byte) {
for i := 0; i < TxRetryLimit; i++ {
select {
case <-w.stop:
return
default:
err := w.conn.LockAndUpdateOpts()
if err != nil {
w.log.Error("Failed to update nonce", "err", err)
return
}
// These store the gas limit and price before a transaction is sent for logging in case of a failure
// This is necessary as tx will be nil in the case of an error when sending VoteProposal()
gasLimit := w.conn.Opts().GasLimit
gasPrice := w.conn.Opts().GasPrice
tx, err := w.bridgeContract.ExecuteProposal(
w.conn.Opts(),
uint8(m.Source),
uint64(m.DepositNonce),
data,
m.ResourceId,
)
w.conn.UnlockOpts()
if err == nil {
w.log.Info("Submitted proposal execution", "tx", tx.Hash(), "src", m.Source, "dst", m.Destination, "nonce", m.DepositNonce, "gasPrice", tx.GasPrice().String())
return
} else if err.Error() == ErrNonceTooLow.Error() || err.Error() == ErrTxUnderpriced.Error() {
w.log.Error("Nonce too low, will retry")
time.Sleep(TxRetryInterval)
} else {
w.log.Warn("Execution failed, proposal may already be complete", "gasLimit", gasLimit, "gasPrice", gasPrice, "err", err)
time.Sleep(TxRetryInterval)
}
// Verify proposal is still open for execution, tx will fail if we aren't the first to execute,
// but there is no need to retry
if w.proposalIsFinalized(m.Source, m.DepositNonce, dataHash) {
w.log.Info("Proposal finalized on chain", "src", m.Source, "dst", m.Destination, "nonce", m.DepositNonce)
return
}
}
}
w.log.Error("Submission of Execute transaction failed", "source", m.Source, "dest", m.Destination, "depositNonce", m.DepositNonce)
w.sysErr <- ErrFatalTx
}