forked from loomnetwork/loomchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
75 lines (58 loc) · 2.04 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package loomchain
import (
"github.com/gogo/protobuf/proto"
"github.com/loomnetwork/go-loom/types"
)
type Transaction = types.Transaction
type TxRouter struct {
deliverTxRoutes map[uint32]RouteHandler
checkTxRoutes map[uint32]RouteHandler
}
type RouteHandler func(txID uint32, state State, txBytes []byte, isCheckTx bool) (TxHandlerResult, error)
type RouteConditionFunc func(txID uint32, state State, txBytes []byte, isCheckTx bool) bool
var GeneratePassthroughRouteHandler = func(txHandler TxHandler) RouteHandler {
return func(txID uint32, state State, txBytes []byte, isCheckTx bool) (TxHandlerResult, error) {
return txHandler.ProcessTx(state, txBytes, isCheckTx)
}
}
func GenerateConditionalRouteHandler(conditionFn RouteConditionFunc, onTrue TxHandler, onFalse TxHandler) RouteHandler {
return RouteHandler(func(txId uint32, state State, txBytes []byte, isCheckTx bool) (TxHandlerResult, error) {
if conditionFn(txId, state, txBytes, isCheckTx) {
return onTrue.ProcessTx(state, txBytes, isCheckTx)
}
return onFalse.ProcessTx(state, txBytes, isCheckTx)
})
}
func NewTxRouter() *TxRouter {
return &TxRouter{
deliverTxRoutes: make(map[uint32]RouteHandler),
checkTxRoutes: make(map[uint32]RouteHandler),
}
}
func (r *TxRouter) HandleDeliverTx(txID uint32, handler RouteHandler) {
if _, ok := r.deliverTxRoutes[txID]; ok {
panic("handler for transaction already registered")
}
r.deliverTxRoutes[txID] = handler
}
func (r *TxRouter) HandleCheckTx(txID uint32, handler RouteHandler) {
if _, ok := r.checkTxRoutes[txID]; ok {
panic("handler for transaction already registered")
}
r.checkTxRoutes[txID] = handler
}
func (r *TxRouter) ProcessTx(state State, txBytes []byte, isCheckTx bool) (TxHandlerResult, error) {
var res TxHandlerResult
var tx Transaction
err := proto.Unmarshal(txBytes, &tx)
if err != nil {
return res, err
}
var routeHandler RouteHandler
if isCheckTx {
routeHandler = r.checkTxRoutes[tx.Id]
} else {
routeHandler = r.deliverTxRoutes[tx.Id]
}
return routeHandler(tx.Id, state, tx.Data, isCheckTx)
}