forked from ChainSafe/chainbridge-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
relayer.go
221 lines (192 loc) · 7.32 KB
/
relayer.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
// Copyright 2021 ChainSafe Systems
// SPDX-License-Identifier: LGPL-3.0-only
package relayer
import (
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/meterio/chainbridge-core/relayer/message"
"github.com/meterio/chainbridge-core/types"
"github.com/meterio/chainbridge-core/util"
"github.com/rs/zerolog/log"
"go.opentelemetry.io/otel/attribute"
)
type Metrics interface {
TrackDepositMessage(m *message.Message)
}
type RelayedChain interface {
PollEvents(stop <-chan struct{}, sysErr chan<- error, eventsChan chan *message.Message)
HandleEvent(sourceID, destID uint8, nonce uint64, resourceID types.ResourceID, calldata, handlerResponse []byte) (*message.Message, error)
DomainID() uint8
RelayId() uint8
ChainID() (*big.Int, error)
BridgeContractAddress() *common.Address
SyncBlockLabels() []attribute.KeyValue
HeadBlockLabels() []attribute.KeyValue
GetSignatures(message *message.Message) ([][]byte, error)
Get(message *message.Message) (bool, error)
VoteOnDest(message *message.Message) error
VoteOnRelay(message *message.Message, chainID *big.Int, address *common.Address) error
ExecOnDest(message *message.Message, data [][]byte, sleepDuration *big.Int) error
SignatureSubmit() bool
}
func NewRelayer(chains []RelayedChain, metrics Metrics, messageProcessors ...message.MessageProcessor) *Relayer {
return &Relayer{relayedChains: chains, messageProcessors: messageProcessors, metrics: metrics}
}
type Relayer struct {
metrics Metrics
relayedChains []RelayedChain
registry map[uint8]RelayedChain
messageProcessors []message.MessageProcessor
}
// Start function starts the relayer. Relayer routine is starting all the chains
// and passing them with a channel that accepts unified cross chain message format
func (r *Relayer) Start(stop <-chan struct{}, sysErr chan error) {
log.Debug().Msgf("Starting relayer")
messagesChannel := make(chan *message.Message)
for _, c := range r.relayedChains {
log.Debug().Msgf("Starting chain %v", c.DomainID())
r.addRelayedChain(c)
go c.PollEvents(stop, sysErr, messagesChannel)
}
for {
select {
case m := <-messagesChannel:
go r.route(m, messagesChannel)
continue
case <-stop:
return
}
}
}
// Route function winds destination writer by mapping DestinationID from message to registered writer.
func (r *Relayer) route(m *message.Message, msgCh chan *message.Message) {
//r.metrics.TrackDepositMessage(m)
sourceChain, ok := r.registry[m.Source]
if !ok {
log.Error().Msgf("no resolver for sourceID %v to send message registered", m.Destination)
return
}
middleId := sourceChain.RelayId() // if zero?, use old logic.
var middleChain RelayedChain
if middleId != 0 {
middleChain, ok = r.registry[middleId]
if !ok {
log.Error().Msgf("no resolver for middleID %v to send message registered", m.Destination)
return
}
}
destChain, ok := r.registry[m.Destination]
if !ok {
log.Error().Msgf("no resolver for destID %v to send message registered", m.Destination)
return
}
destChainID, err := destChain.ChainID()
if err != nil {
log.Error().Err(fmt.Errorf("error getting chainId: %w on dest chain %v", err, m.Destination))
}
if middleChain != nil {
// relay chain enabled
// scenario #1: SignaturePass event received on relay chain
// submit merged signature to destination chain directly
if m.Type == message.SignaturePass || m.Type == message.ArtificialPass {
if middleChain.SignatureSubmit() {
var mm *message.Message
var err error
for i := 0; i < 5; i++ {
mm, err = destChain.HandleEvent(m.Source, m.Destination, m.DepositNonce, m.ResourceId, m.Data, []byte{})
if err != nil {
log.Error().Msgf("could not handle SigPass: %v", err)
// panic("help")
} else {
break
}
log.Info().Msgf("Sleep for %d seconds, hopefully it could resolve the handling issue", (i+1)*5)
time.Sleep(time.Duration((i+1)*5) * time.Second)
log.Info().Msgf("Retry No. %d", i)
}
if err != nil {
log.Error().Msgf("could not handle SigPass after 5 retries: %v", err)
log.Error().Msgf("SigPass(Source:%v, Dest:%v, DepositNonce:%v, ResourceId:%v, Data:%v)", m.Source, m.Destination, m.DepositNonce, m.ResourceId, m.Data)
// panic("help")
return
}
mm.Type = m.Type
sigs, err := middleChain.GetSignatures(m) // getSignatures
if err != nil {
log.Error().Str("msg", m.ID()).Err(fmt.Errorf("error getting signatures: %w", err))
}
log.Info().Str("relay", "enabled").Str("call", "execOnDest").Uint64("block", m.BlockNumber).Msgf("Recv: %v", m)
err = destChain.ExecOnDest(mm, sigs, big.NewInt(1)) // voteProposals
if err != nil {
log.Error().Str("msg", mm.ID()).Err(fmt.Errorf("error exec on dest chain: %w", err))
}
return
} else {
log.Info().Str("relay", "enabledWOSubmit").Uint64("block", m.BlockNumber).Msgf("Recv: %v, skip processing ...", m)
return
}
}
// scenario #2: Deposit event received on source chain, and relay chain is enabled
// submit signature to relay chain
log.Info().Str("relay", "enabled").Str("call", "voteOnRelay").Uint64("block", m.BlockNumber).Msgf("Recv: %v", m)
err = middleChain.VoteOnRelay(m, destChainID, destChain.BridgeContractAddress()) // submitSignature
if err != nil {
if err == util.ErrAlreadyPassed {
m.Type = message.ArtificialPass
log.Info().Str("msg", m.ID()).Msgf("generate an ArtificialPass")
msgCh <- m
}
log.Error().Str("msg", m.ID()).Err(fmt.Errorf("error vote on relay chain: %w", err))
}
return
}
// // special case for polis network
// blackList := []string{
// "0x8cafd0397e1b09199A1B1239030Cc6b011AE696d",
// }
// blackMap := make(map[string]bool) // key: address in lower case without 0x-prefix, value: true
// for _, b := range blackList {
// blackMap[strings.ToLower(strings.ReplaceAll(b, "0x", ""))] = true
// }
// // whiteList := []string{}
// // whiteMap := make(map[string]bool)
// // for _, w := range whiteList {
// // whiteMap[strings.ToLower(strings.ReplaceAll(w, "0x", ""))] = true
// // }
// if len(m.Payload) >= 2 && m.Source == 7 {
// raddr := m.Payload[1].([]byte)
// recipientAddr := strings.ToLower(hex.EncodeToString(raddr))
// // return if it's black listed
// if _, blacked := blackMap[recipientAddr]; blacked {
// log.Warn().Msgf("recipient address %v is black listed, won't process this Deposit %v", recipientAddr, m)
// return
// }
// // return if it's not white listed
// // if _, whited := whiteMap[recipientAddr]; !whited {
// // log.Warn().Msgf("recipient address %v is not white listed, won't process this Deposit %v", recipientAddr, m)
// // return
// // }
// }
// scenario #3: Deposit event received and middle chain is not enabled
// submit signature to dest chain directly
log.Debug().Str("relay", "disabled").Str("call", "voteOnDest").Uint64("block", m.BlockNumber).Msgf("Recv: %v", m)
for _, mp := range r.messageProcessors {
if err := mp(m); err != nil {
log.Error().Str("msg", m.ID()).Err(fmt.Errorf("error processing: %w ", err))
return
}
}
if err := destChain.VoteOnDest(m); err != nil { // voteProposal
log.Error().Str("msg", m.ID()).Err(err).Msgf("error vote on dest chain: %w", err)
return
}
}
func (r *Relayer) addRelayedChain(c RelayedChain) {
if r.registry == nil {
r.registry = make(map[uint8]RelayedChain)
}
domainID := c.DomainID()
r.registry[domainID] = c
}