forked from ChainSafe/chainbridge-utils
/
router.go
55 lines (45 loc) · 1.4 KB
/
router.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
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: LGPL-3.0-only
package core
import (
"fmt"
"sync"
"github.com/Satosh-J/scallopbridge-utils/msg"
log "github.com/ChainSafe/log15"
)
// Writer consumes a message and makes the requried on-chain interactions.
type Writer interface {
ResolveMessage(message msg.Message) bool
}
// Router forwards messages from their source to their destination
type Router struct {
registry map[msg.ChainId]Writer
lock *sync.RWMutex
log log.Logger
}
func NewRouter(log log.Logger) *Router {
return &Router{
registry: make(map[msg.ChainId]Writer),
lock: &sync.RWMutex{},
log: log,
}
}
// Send passes a message to the destination Writer if it exists
func (r *Router) Send(msg msg.Message) error {
r.lock.Lock()
defer r.lock.Unlock()
r.log.Trace("Routing message", "src", msg.Source, "dest", msg.Destination, "nonce", msg.DepositNonce, "rId", msg.ResourceId.Hex())
w := r.registry[msg.Destination]
if w == nil {
return fmt.Errorf("unknown destination chainId: %d", msg.Destination)
}
go w.ResolveMessage(msg)
return nil
}
// Listen registers a Writer with a ChainId which Router.Send can then use to propagate messages
func (r *Router) Listen(id msg.ChainId, w Writer) {
r.lock.Lock()
defer r.lock.Unlock()
r.log.Debug("Registering new chain in router", "id", id)
r.registry[id] = w
}