-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathinbounds.go
383 lines (355 loc) · 14.8 KB
/
inbounds.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
package evm
import (
"bytes"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
sdkmath "cosmossdk.io/math"
ethcommon "github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/onrik/ethrpc"
"github.com/pkg/errors"
"github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol"
"github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.non-eth.sol"
"github.com/zeta-chain/zetacore/pkg/chains"
"github.com/zeta-chain/zetacore/pkg/coin"
"github.com/zeta-chain/zetacore/pkg/constant"
"github.com/zeta-chain/zetacore/x/crosschain/types"
"github.com/zeta-chain/zetacore/zetaclient/compliance"
"github.com/zeta-chain/zetacore/zetaclient/config"
corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context"
clienttypes "github.com/zeta-chain/zetacore/zetaclient/types"
"github.com/zeta-chain/zetacore/zetaclient/zetabridge"
"golang.org/x/net/context"
)
// WatchIntxTracker gets a list of Inbound tracker suggestions from zeta-core at each tick and tries to check if the in-tx was confirmed.
// If it was, it tries to broadcast the confirmation vote. If this zeta client has previously broadcast the vote, the tx would be rejected
func (ob *ChainClient) WatchIntxTracker() {
ticker, err := clienttypes.NewDynamicTicker(
fmt.Sprintf("EVM_WatchIntxTracker_%d", ob.chain.ChainId),
ob.GetChainParams().InTxTicker,
)
if err != nil {
ob.logger.InTx.Err(err).Msg("error creating ticker")
return
}
defer ticker.Stop()
ob.logger.InTx.Info().Msgf("Intx tracker watcher started for chain %d", ob.chain.ChainId)
for {
select {
case <-ticker.C():
if !corecontext.IsInboundObservationEnabled(ob.coreContext, ob.GetChainParams()) {
continue
}
err := ob.ObserveIntxTrackers()
if err != nil {
ob.logger.InTx.Err(err).Msg("ObserveTrackerSuggestions error")
}
ticker.UpdateInterval(ob.GetChainParams().InTxTicker, ob.logger.InTx)
case <-ob.stop:
ob.logger.InTx.Info().Msg("ExternalChainWatcher for inboundTrackerSuggestions stopped")
return
}
}
}
// ObserveIntxTrackers observes the inbound trackers for the chain
func (ob *ChainClient) ObserveIntxTrackers() error {
trackers, err := ob.zetaBridge.GetInboundTrackersForChain(ob.chain.ChainId)
if err != nil {
return err
}
for _, tracker := range trackers {
// query tx and receipt
tx, _, err := ob.TransactionByHash(tracker.TxHash)
if err != nil {
return errors.Wrapf(err, "error getting transaction for intx %s chain %d", tracker.TxHash, ob.chain.ChainId)
}
receipt, err := ob.evmClient.TransactionReceipt(context.Background(), ethcommon.HexToHash(tracker.TxHash))
if err != nil {
return errors.Wrapf(err, "error getting receipt for intx %s chain %d", tracker.TxHash, ob.chain.ChainId)
}
ob.logger.InTx.Info().Msgf("checking tracker for intx %s chain %d", tracker.TxHash, ob.chain.ChainId)
// check and vote on inbound tx
switch tracker.CoinType {
case coin.CoinType_Zeta:
_, err = ob.CheckAndVoteInboundTokenZeta(tx, receipt, true)
case coin.CoinType_ERC20:
_, err = ob.CheckAndVoteInboundTokenERC20(tx, receipt, true)
case coin.CoinType_Gas:
_, err = ob.CheckAndVoteInboundTokenGas(tx, receipt, true)
default:
return fmt.Errorf("unknown coin type %s for intx %s chain %d", tracker.CoinType, tx.Hash, ob.chain.ChainId)
}
if err != nil {
return errors.Wrapf(err, "error checking and voting for intx %s chain %d", tx.Hash, ob.chain.ChainId)
}
}
return nil
}
// CheckAndVoteInboundTokenZeta checks and votes on the given inbound Zeta token
func (ob *ChainClient) CheckAndVoteInboundTokenZeta(tx *ethrpc.Transaction, receipt *ethtypes.Receipt, vote bool) (string, error) {
// check confirmations
if confirmed := ob.HasEnoughConfirmations(receipt, ob.GetLastBlockHeight()); !confirmed {
return "", fmt.Errorf("intx %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64())
}
// get zeta connector contract
addrConnector, connector, err := ob.GetConnectorContract()
if err != nil {
return "", err
}
// build inbound vote message and post vote
var msg *types.MsgVoteOnObservedInboundTx
for _, log := range receipt.Logs {
event, err := connector.ParseZetaSent(*log)
if err == nil && event != nil {
// sanity check tx event
err = ValidateEvmTxLog(&event.Raw, addrConnector, tx.Hash, TopicsZetaSent)
if err == nil {
msg = ob.BuildInboundVoteMsgForZetaSentEvent(event)
} else {
ob.logger.InTx.Error().Err(err).Msgf("CheckEvmTxLog error on intx %s chain %d", tx.Hash, ob.chain.ChainId)
return "", err
}
break // only one event is allowed per tx
}
}
if msg == nil {
// no event, restricted tx, etc.
ob.logger.InTx.Info().Msgf("no ZetaSent event found for intx %s chain %d", tx.Hash, ob.chain.ChainId)
return "", nil
}
if vote {
return ob.PostVoteInbound(msg, coin.CoinType_Zeta, zetabridge.PostVoteInboundMessagePassingExecutionGasLimit)
}
return msg.Digest(), nil
}
// CheckAndVoteInboundTokenERC20 checks and votes on the given inbound ERC20 token
func (ob *ChainClient) CheckAndVoteInboundTokenERC20(tx *ethrpc.Transaction, receipt *ethtypes.Receipt, vote bool) (string, error) {
// check confirmations
if confirmed := ob.HasEnoughConfirmations(receipt, ob.GetLastBlockHeight()); !confirmed {
return "", fmt.Errorf("intx %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64())
}
// get erc20 custody contract
addrCustory, custody, err := ob.GetERC20CustodyContract()
if err != nil {
return "", err
}
sender := ethcommon.HexToAddress(tx.From)
// build inbound vote message and post vote
var msg *types.MsgVoteOnObservedInboundTx
for _, log := range receipt.Logs {
zetaDeposited, err := custody.ParseDeposited(*log)
if err == nil && zetaDeposited != nil {
// sanity check tx event
err = ValidateEvmTxLog(&zetaDeposited.Raw, addrCustory, tx.Hash, TopicsDeposited)
if err == nil {
msg = ob.BuildInboundVoteMsgForDepositedEvent(zetaDeposited, sender)
} else {
ob.logger.InTx.Error().Err(err).Msgf("CheckEvmTxLog error on intx %s chain %d", tx.Hash, ob.chain.ChainId)
return "", err
}
break // only one event is allowed per tx
}
}
if msg == nil {
// no event, donation, restricted tx, etc.
ob.logger.InTx.Info().Msgf("no Deposited event found for intx %s chain %d", tx.Hash, ob.chain.ChainId)
return "", nil
}
if vote {
return ob.PostVoteInbound(msg, coin.CoinType_ERC20, zetabridge.PostVoteInboundExecutionGasLimit)
}
return msg.Digest(), nil
}
// CheckAndVoteInboundTokenGas checks and votes on the given inbound gas token
func (ob *ChainClient) CheckAndVoteInboundTokenGas(tx *ethrpc.Transaction, receipt *ethtypes.Receipt, vote bool) (string, error) {
// check confirmations
if confirmed := ob.HasEnoughConfirmations(receipt, ob.GetLastBlockHeight()); !confirmed {
return "", fmt.Errorf("intx %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64())
}
// checks receiver and tx status
if ethcommon.HexToAddress(tx.To) != ob.Tss.EVMAddress() {
return "", fmt.Errorf("tx.To %s is not TSS address", tx.To)
}
if receipt.Status != ethtypes.ReceiptStatusSuccessful {
return "", errors.New("not a successful tx")
}
sender := ethcommon.HexToAddress(tx.From)
// build inbound vote message and post vote
msg := ob.BuildInboundVoteMsgForTokenSentToTSS(tx, sender, receipt.BlockNumber.Uint64())
if msg == nil {
// donation, restricted tx, etc.
ob.logger.InTx.Info().Msgf("no vote message built for intx %s chain %d", tx.Hash, ob.chain.ChainId)
return "", nil
}
if vote {
return ob.PostVoteInbound(msg, coin.CoinType_Gas, zetabridge.PostVoteInboundExecutionGasLimit)
}
return msg.Digest(), nil
}
// PostVoteInbound posts a vote for the given vote message
func (ob *ChainClient) PostVoteInbound(msg *types.MsgVoteOnObservedInboundTx, coinType coin.CoinType, retryGasLimit uint64) (string, error) {
txHash := msg.InTxHash
chainID := ob.chain.ChainId
zetaHash, ballot, err := ob.zetaBridge.PostVoteInbound(zetabridge.PostVoteInboundGasLimit, retryGasLimit, msg)
if err != nil {
ob.logger.InTx.Err(err).Msgf("intx detected: error posting vote for chain %d token %s intx %s", chainID, coinType, txHash)
return "", err
} else if zetaHash != "" {
ob.logger.InTx.Info().Msgf("intx detected: chain %d token %s intx %s vote %s ballot %s", chainID, coinType, txHash, zetaHash, ballot)
} else {
ob.logger.InTx.Info().Msgf("intx detected: chain %d token %s intx %s already voted on ballot %s", chainID, coinType, txHash, ballot)
}
return ballot, err
}
// HasEnoughConfirmations checks if the given receipt has enough confirmations
func (ob *ChainClient) HasEnoughConfirmations(receipt *ethtypes.Receipt, lastHeight uint64) bool {
confHeight := receipt.BlockNumber.Uint64() + ob.GetChainParams().ConfirmationCount
return lastHeight >= confHeight
}
// BuildInboundVoteMsgForDepositedEvent builds a inbound vote message for a Deposited event
func (ob *ChainClient) BuildInboundVoteMsgForDepositedEvent(event *erc20custody.ERC20CustodyDeposited, sender ethcommon.Address) *types.MsgVoteOnObservedInboundTx {
// compliance check
maybeReceiver := ""
parsedAddress, _, err := chains.ParseAddressAndData(hex.EncodeToString(event.Message))
if err == nil && parsedAddress != (ethcommon.Address{}) {
maybeReceiver = parsedAddress.Hex()
}
if config.ContainRestrictedAddress(sender.Hex(), clienttypes.BytesToEthHex(event.Recipient), maybeReceiver) {
compliance.PrintComplianceLog(ob.logger.InTx, ob.logger.Compliance,
false, ob.chain.ChainId, event.Raw.TxHash.Hex(), sender.Hex(), clienttypes.BytesToEthHex(event.Recipient), "ERC20")
return nil
}
// donation check
if bytes.Equal(event.Message, []byte(constant.DonationMessage)) {
ob.logger.InTx.Info().Msgf("thank you rich folk for your donation! tx %s chain %d", event.Raw.TxHash.Hex(), ob.chain.ChainId)
return nil
}
message := hex.EncodeToString(event.Message)
ob.logger.InTx.Info().Msgf("ERC20CustodyDeposited inTx detected on chain %d tx %s block %d from %s value %s message %s",
ob.chain.ChainId, event.Raw.TxHash.Hex(), event.Raw.BlockNumber, sender.Hex(), event.Amount.String(), message)
return zetabridge.GetInBoundVoteMessage(
sender.Hex(),
ob.chain.ChainId,
"",
clienttypes.BytesToEthHex(event.Recipient),
ob.zetaBridge.ZetaChain().ChainId,
sdkmath.NewUintFromBigInt(event.Amount),
hex.EncodeToString(event.Message),
event.Raw.TxHash.Hex(),
event.Raw.BlockNumber,
1_500_000,
coin.CoinType_ERC20,
event.Asset.String(),
ob.zetaBridge.GetKeys().GetOperatorAddress().String(),
event.Raw.Index,
)
}
// BuildInboundVoteMsgForZetaSentEvent builds a inbound vote message for a ZetaSent event
func (ob *ChainClient) BuildInboundVoteMsgForZetaSentEvent(event *zetaconnector.ZetaConnectorNonEthZetaSent) *types.MsgVoteOnObservedInboundTx {
destChain := chains.GetChainFromChainID(event.DestinationChainId.Int64())
if destChain == nil {
ob.logger.InTx.Warn().Msgf("chain id not supported %d", event.DestinationChainId.Int64())
return nil
}
destAddr := clienttypes.BytesToEthHex(event.DestinationAddress)
// compliance check
sender := event.ZetaTxSenderAddress.Hex()
if config.ContainRestrictedAddress(sender, destAddr, event.SourceTxOriginAddress.Hex()) {
compliance.PrintComplianceLog(ob.logger.InTx, ob.logger.Compliance,
false, ob.chain.ChainId, event.Raw.TxHash.Hex(), sender, destAddr, "Zeta")
return nil
}
if !destChain.IsZetaChain() {
paramsDest, found := ob.coreContext.GetEVMChainParams(destChain.ChainId)
if !found {
ob.logger.InTx.Warn().Msgf("chain id not present in EVMChainParams %d", event.DestinationChainId.Int64())
return nil
}
if strings.EqualFold(destAddr, paramsDest.ZetaTokenContractAddress) {
ob.logger.InTx.Warn().Msgf("potential attack attempt: %s destination address is ZETA token contract address %s", destChain, destAddr)
return nil
}
}
message := base64.StdEncoding.EncodeToString(event.Message)
ob.logger.InTx.Info().Msgf("ZetaSent inTx detected on chain %d tx %s block %d from %s value %s message %s",
ob.chain.ChainId, event.Raw.TxHash.Hex(), event.Raw.BlockNumber, sender, event.ZetaValueAndGas.String(), message)
return zetabridge.GetInBoundVoteMessage(
sender,
ob.chain.ChainId,
event.SourceTxOriginAddress.Hex(),
destAddr,
destChain.ChainId,
sdkmath.NewUintFromBigInt(event.ZetaValueAndGas),
message,
event.Raw.TxHash.Hex(),
event.Raw.BlockNumber,
event.DestinationGasLimit.Uint64(),
coin.CoinType_Zeta,
"",
ob.zetaBridge.GetKeys().GetOperatorAddress().String(),
event.Raw.Index,
)
}
// BuildInboundVoteMsgForTokenSentToTSS builds a inbound vote message for a token sent to TSS
func (ob *ChainClient) BuildInboundVoteMsgForTokenSentToTSS(tx *ethrpc.Transaction, sender ethcommon.Address, blockNumber uint64) *types.MsgVoteOnObservedInboundTx {
message := tx.Input
// compliance check
maybeReceiver := ""
parsedAddress, _, err := chains.ParseAddressAndData(message)
if err == nil && parsedAddress != (ethcommon.Address{}) {
maybeReceiver = parsedAddress.Hex()
}
if config.ContainRestrictedAddress(sender.Hex(), maybeReceiver) {
compliance.PrintComplianceLog(ob.logger.InTx, ob.logger.Compliance,
false, ob.chain.ChainId, tx.Hash, sender.Hex(), sender.Hex(), "Gas")
return nil
}
// donation check
// #nosec G703 err is already checked
data, _ := hex.DecodeString(message)
if bytes.Equal(data, []byte(constant.DonationMessage)) {
ob.logger.InTx.Info().Msgf("thank you rich folk for your donation! tx %s chain %d", tx.Hash, ob.chain.ChainId)
return nil
}
ob.logger.InTx.Info().Msgf("TSS inTx detected on chain %d tx %s block %d from %s value %s message %s",
ob.chain.ChainId, tx.Hash, blockNumber, sender.Hex(), tx.Value.String(), message)
return zetabridge.GetInBoundVoteMessage(
sender.Hex(),
ob.chain.ChainId,
sender.Hex(),
sender.Hex(),
ob.zetaBridge.ZetaChain().ChainId,
sdkmath.NewUintFromBigInt(&tx.Value),
message,
tx.Hash,
blockNumber,
90_000,
coin.CoinType_Gas,
"",
ob.zetaBridge.GetKeys().GetOperatorAddress().String(),
0, // not a smart contract call
)
}
// ObserveTSSReceiveInBlock queries the incoming gas asset to TSS address in a single block and posts votes
func (ob *ChainClient) ObserveTSSReceiveInBlock(blockNumber uint64) error {
block, err := ob.GetBlockByNumberCached(blockNumber)
if err != nil {
return errors.Wrapf(err, "error getting block %d for chain %d", blockNumber, ob.chain.ChainId)
}
for i := range block.Transactions {
tx := block.Transactions[i]
if ethcommon.HexToAddress(tx.To) == ob.Tss.EVMAddress() {
receipt, err := ob.evmClient.TransactionReceipt(context.Background(), ethcommon.HexToHash(tx.Hash))
if err != nil {
return errors.Wrapf(err, "error getting receipt for intx %s chain %d", tx.Hash, ob.chain.ChainId)
}
_, err = ob.CheckAndVoteInboundTokenGas(&tx, receipt, true)
if err != nil {
return errors.Wrapf(err, "error checking and voting inbound gas asset for intx %s chain %d", tx.Hash, ob.chain.ChainId)
}
}
}
return nil
}