-
Notifications
You must be signed in to change notification settings - Fork 11
/
monitor.go
235 lines (219 loc) · 5.52 KB
/
monitor.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
package ethmonitor
import (
"context"
"errors"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/sirupsen/logrus"
"math/big"
"sync"
"time"
)
type Monitor interface {
Run()
Cancel()
}
var FieldTag = "monitor"
type Options struct {
RpcUrl string // eth节点url
AbiStr string // 组合abi,可以监控多个智能合约
Handler TxHandler // 业务处理handler
Logger logrus.FieldLogger
}
type monitor struct {
ctx context.Context
cancel context.CancelFunc
cli *ethclient.Client
hScan HeightScanner
decoder *abiDecoder
handler TxHandler
logger logrus.FieldLogger
sync.RWMutex
}
// 基本参数验证
func (opt *Options) check() error {
if opt == nil {
return errors.New("options nil reference")
}
if opt.RpcUrl == "" || opt.AbiStr == "" {
return errors.New("rpcUrl and abiStr can't be empty")
}
if opt.Handler == nil {
return errors.New("handler nil reference")
}
if opt.Logger == nil {
opt.Logger = logrus.New()
}
return nil
}
// New 初始化eth 监控器
func New(opt *Options) (Monitor, error) {
if err := opt.check(); err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
cli, err := ethclient.DialContext(ctx, opt.RpcUrl)
if err != nil {
cancel()
return nil, err
}
m := &monitor{
ctx: ctx,
cancel: cancel,
cli: cli,
decoder: newAbiDecoder(opt.AbiStr),
hScan: opt.Handler,
handler: opt.Handler,
logger: opt.Logger,
}
return m, nil
}
// HeightScanner 高度扫描器
type HeightScanner interface {
// SaveHeight 持久化最新块高
SaveHeight(ctx context.Context, height *BlockHeight) error
// LoadLastHeight 加载上一次块高
LoadLastHeight(ctx context.Context) (*BlockHeight, error)
}
// TxHandler 业务tx句柄
type TxHandler interface {
HeightScanner
// Do 处理命中的tx
Do(ctx context.Context, info *TxInfo)
// ContainContact 是否包含指定合约地址
// NOTE: 如果不满足也放行会在decode中抛出error "illegal tx"
// 如果是多智能合约监听,可以使用map维护多个
// 配套的,需要把这些合约的abi合并后在monitor初始化时赋值给AbiStr,注意去重
ContainContact(ctx context.Context, address ContractAddress) bool
}
func (m *monitor) Run() {
lastBlockHeight, err := m.hScan.LoadLastHeight(m.ctx)
if err != nil {
panic(err)
}
ticker := time.NewTicker(time.Second)
for {
select {
case <-ticker.C:
curIndex, _, err := m.getBlockHeight()
if err != nil {
m.logger.WithField(FieldTag, "getBlockHeight").Error(err)
continue
}
if curIndex.Cmp(lastBlockHeight) == 0 {
continue
}
if lastBlockHeight.Cmp(big.NewInt(0)) == 0 {
lastBlockHeight.Set(curIndex)
continue
}
start := big.NewInt(0).Set(lastBlockHeight)
end := big.NewInt(0).Set(curIndex)
m.blockListen(start, end)
lastBlockHeight.Set(curIndex)
err = m.hScan.SaveHeight(m.ctx, curIndex)
if err != nil {
m.logger.WithField(FieldTag, "saveHeight").Error(err)
}
case <-m.ctx.Done():
m.logger.WithField(FieldTag, "close").Info()
return
}
}
}
func (m *monitor) Cancel() {
m.cancel()
}
func (m *monitor) getBlockHeight() (cur, highest *BlockHeight, err error) {
sync, err := m.cli.SyncProgress(m.ctx)
if err != nil {
return nil, nil, err
}
if sync == nil {
block, err := m.cli.HeaderByNumber(context.Background(), nil)
if err != nil {
return nil, nil, err
}
return block.Number, block.Number, nil
} else {
return big.NewInt(0).SetUint64(sync.CurrentBlock), big.NewInt(0).SetUint64(sync.HighestBlock), nil
}
}
func (m *monitor) blockListen(start, end *BlockHeight) {
for i := big.NewInt(0).Set(start); i.Cmp(end) < 0; i.Add(i, big.NewInt(1)) {
var (
block *types.Block
err error
)
for { // 失败阻塞,等待节点修复
block, err = m.cli.BlockByNumber(context.Background(), i)
if err != nil {
m.logger.WithField(FieldTag, "blockByNumber").Errorf("height:%v error:%s", i.String(), err)
time.Sleep(time.Second)
continue
}
break
}
if block.Transactions().Len() > 0 {
m.analyzeBlock(block)
}
}
}
func (m *monitor) analyzeBlock(block *types.Block) {
for _, v := range block.Transactions() {
signer := types.NewLondonSigner(v.ChainId())
msg, err := v.AsMessage(signer, nil)
if err != nil {
m.logger.WithField(FieldTag, "asMessage").Error(err)
continue
}
if msg.To() == nil {
continue
}
if m.handler.ContainContact(m.ctx, msg.To().Hex()) {
txInfo, err := m.analyzeTx(v.Hash(), &msg)
if err != nil {
m.logger.WithField(FieldTag, "analyzeTx").Error(err)
continue
}
if txInfo != nil {
m.handler.Do(m.ctx, txInfo)
}
}
}
}
func (m *monitor) analyzeTx(txHash common.Hash, msg *Message) (*TxInfo, error) {
defer func() {
if err := recover(); err != nil {
m.logger.WithField(FieldTag, "analyzeTx").Errorf("panic cover err:%v", err)
}
}()
txInfo, isPending, err := m.cli.TransactionByHash(context.Background(), txHash)
if err != nil {
return nil, err
}
if isPending {
return nil, nil
}
txRe, errTxRe := m.cli.TransactionReceipt(context.Background(), txHash)
fee := big.NewInt(0)
if errTxRe == nil && txRe != nil {
fee = fee.SetUint64(txRe.GasUsed)
fee = fee.Mul(fee, txInfo.GasPrice())
}
act, err := m.decoder.DecodeTxData(msg.Data())
if err != nil {
return nil, err
}
ti := &TxInfo{
Message: msg,
Receipt: txRe,
Action: act,
TxHash: txHash.Hex(),
Fee: fee,
Height: txRe.BlockNumber,
Status: txRe.Status == 1,
}
return ti, nil
}