-
Notifications
You must be signed in to change notification settings - Fork 3
/
node_explorer.go
334 lines (300 loc) · 10 KB
/
node_explorer.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
package node
import (
"context"
"encoding/json"
"sync"
msg_pb "github.com/PositionExchange/posichain/api/proto/message"
"github.com/PositionExchange/posichain/api/service"
"github.com/PositionExchange/posichain/api/service/explorer"
"github.com/PositionExchange/posichain/consensus"
"github.com/PositionExchange/posichain/consensus/signature"
"github.com/PositionExchange/posichain/core"
"github.com/PositionExchange/posichain/core/types"
"github.com/PositionExchange/posichain/internal/tikv"
"github.com/PositionExchange/posichain/internal/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
"github.com/pkg/errors"
)
var once sync.Once
var (
errBlockBeforeCommit = errors.New(
"explorer hasnt received the block before the committed msg",
)
errFailVerifyMultiSign = errors.New(
"explorer failed to verify the multi signature for commit phase",
)
errFailFindingValidCommit = errors.New(
"explorer failed finding a valid committed message",
)
)
// explorerMessageHandler passes received message in node_handler to explorer service
func (node *Node) explorerMessageHandler(ctx context.Context, msg *msg_pb.Message) error {
if msg.Type == msg_pb.MessageType_COMMITTED {
recvMsg, err := node.Consensus.ParseFBFTMessage(msg)
if err != nil {
utils.Logger().Error().Err(err).
Msg("[Explorer] onCommitted unable to parse msg")
return err
}
aggSig, mask, err := node.Consensus.ReadSignatureBitmapPayload(
recvMsg.Payload, 0,
)
if err != nil {
utils.Logger().Error().Err(err).
Msg("[Explorer] readSignatureBitmapPayload failed")
return err
}
if !node.Consensus.Decider.IsQuorumAchievedByMask(mask) {
utils.Logger().Error().Msg("[Explorer] not have enough signature power")
return nil
}
block := node.Consensus.FBFTLog.GetBlockByHash(recvMsg.BlockHash)
if block == nil {
utils.Logger().Info().
Uint64("msgBlock", recvMsg.BlockNum).
Msg("[Explorer] Haven't received the block before the committed msg")
node.Consensus.FBFTLog.AddVerifiedMessage(recvMsg)
return errBlockBeforeCommit
}
commitPayload := signature.ConstructCommitPayload(node.Blockchain(),
block.Epoch(), block.Hash(), block.Number().Uint64(), block.Header().ViewID().Uint64())
if !aggSig.VerifyHash(mask.AggregatePublic, commitPayload) {
utils.Logger().
Error().Err(err).
Uint64("msgBlock", recvMsg.BlockNum).
Msg("[Explorer] Failed to verify the multi signature for commit phase")
return errFailVerifyMultiSign
}
block.SetCurrentCommitSig(recvMsg.Payload)
node.AddNewBlockForExplorer(block)
node.commitBlockForExplorer(block)
} else if msg.Type == msg_pb.MessageType_PREPARED {
recvMsg, err := node.Consensus.ParseFBFTMessage(msg)
if err != nil {
utils.Logger().Error().Err(err).Msg("[Explorer] Unable to parse Prepared msg")
return err
}
block, blockObj := recvMsg.Block, &types.Block{}
if err := rlp.DecodeBytes(block, blockObj); err != nil {
utils.Logger().Error().Err(err).Msg("explorer could not rlp decode block")
return err
}
// Add the block into FBFT log.
node.Consensus.FBFTLog.AddBlock(blockObj)
// Try to search for MessageType_COMMITTED message from pbft log.
msgs := node.Consensus.FBFTLog.GetMessagesByTypeSeqHash(
msg_pb.MessageType_COMMITTED,
blockObj.NumberU64(),
blockObj.Hash(),
)
// If found, then add the new block into blockchain db.
if len(msgs) > 0 {
var committedMsg *consensus.FBFTMessage
for i := range msgs {
if blockObj.Hash() != msgs[i].BlockHash {
continue
}
committedMsg = msgs[i]
break
}
if committedMsg == nil {
utils.Logger().Error().Err(err).Msg("[Explorer] Failed finding a valid committed message.")
return errFailFindingValidCommit
}
blockObj.SetCurrentCommitSig(committedMsg.Payload)
node.AddNewBlockForExplorer(blockObj)
node.commitBlockForExplorer(blockObj)
}
}
return nil
}
func (node *Node) TraceLoopForExplorer() {
if !node.HarmonyConfig.General.TraceEnable {
return
}
ch := make(chan core.TraceEvent)
subscribe := node.Blockchain().SubscribeTraceEvent(ch)
go func() {
loop:
select {
case ev := <-ch:
if exp, err := node.getExplorerService(); err == nil {
storage := ev.Tracer.GetStorage()
exp.DumpTraceResult(storage)
}
goto loop
case <-subscribe.Err():
//subscribe.Unsubscribe()
break
}
}()
}
// AddNewBlockForExplorer add new block for explorer.
func (node *Node) AddNewBlockForExplorer(block *types.Block) {
if node.HarmonyConfig.General.RunElasticMode && node.HarmonyConfig.TiKV.Role == tikv.RoleReader {
node.Consensus.FBFTLog.DeleteBlockByNumber(block.NumberU64())
return
}
utils.Logger().Info().Uint64("blockHeight", block.NumberU64()).Msg("[Explorer] Adding new block for explorer node")
if _, err := node.Blockchain().InsertChain([]*types.Block{block}, false); err == nil {
if block.IsLastBlockInEpoch() {
node.Consensus.UpdateConsensusInformation()
}
// Clean up the blocks to avoid OOM.
node.Consensus.FBFTLog.DeleteBlockByNumber(block.NumberU64())
// if in tikv mode, only master writer node need dump all explorer block
if !node.HarmonyConfig.General.RunElasticMode || node.Blockchain().IsTikvWriterMaster() {
// Do dump all blocks from state syncing for explorer one time
// TODO: some blocks can be dumped before state syncing finished.
// And they would be dumped again here. Please fix it.
once.Do(func() {
utils.Logger().Info().Int64("starting height", int64(block.NumberU64())-1).
Msg("[Explorer] Populating explorer data from state synced blocks")
go func() {
exp, err := node.getExplorerService()
if err != nil {
// shall be unreachable
utils.Logger().Fatal().Err(err).Msg("critical error in explorer node")
}
if block.NumberU64() == 0 {
return
}
// get checkpoint bitmap and flip all bit
bitmap := exp.GetCheckpointBitmap()
bitmap.Flip(0, block.NumberU64())
// find all not processed block and dump it
iterator := bitmap.ReverseIterator()
for iterator.HasNext() {
exp.DumpCatchupBlock(node.Blockchain().GetBlockByNumber(iterator.Next()))
}
}()
})
}
} else {
utils.Logger().Error().Err(err).Msg("[Explorer] Error when adding new block for explorer node")
}
}
// ExplorerMessageHandler passes received message in node_handler to explorer service.
func (node *Node) commitBlockForExplorer(block *types.Block) {
// if in tikv mode, only master writer node need dump explorer block
if !node.HarmonyConfig.General.RunElasticMode || (node.HarmonyConfig.TiKV.Role == tikv.RoleWriter && node.Blockchain().IsTikvWriterMaster()) {
if block.ShardID() != node.NodeConfig.ShardID {
return
}
// Dump new block into level db.
utils.Logger().Info().Uint64("blockNum", block.NumberU64()).Msg("[Explorer] Committing block into explorer DB")
exp, err := node.getExplorerService()
if err != nil {
// shall be unreachable
utils.Logger().Fatal().Err(err).Msg("critical error in explorer node")
}
exp.DumpNewBlock(block)
}
curNum := block.NumberU64()
if curNum-100 > 0 {
node.Consensus.FBFTLog.DeleteBlocksLessThan(curNum - 100)
node.Consensus.FBFTLog.DeleteMessagesLessThan(curNum - 100)
}
}
// GetTransactionsHistory returns list of transactions hashes of address.
func (node *Node) GetTransactionsHistory(address, txType, order string) ([]common.Hash, error) {
exp, err := node.getExplorerService()
if err != nil {
return nil, err
}
allTxs, tts, err := exp.GetNormalTxHashesByAccount(address)
if err != nil {
return nil, err
}
txs := getTargetTxHashes(allTxs, tts, txType)
if order == "DESC" {
reverseTxs(txs)
}
return txs, nil
}
// GetStakingTransactionsHistory returns list of staking transactions hashes of address.
func (node *Node) GetStakingTransactionsHistory(address, txType, order string) ([]common.Hash, error) {
exp, err := node.getExplorerService()
if err != nil {
return nil, err
}
allTxs, tts, err := exp.GetStakingTxHashesByAccount(address)
if err != nil {
return nil, err
}
txs := getTargetTxHashes(allTxs, tts, txType)
if order == "DESC" {
reverseTxs(txs)
}
return txs, nil
}
// GetTransactionsCount returns the number of regular transactions hashes of address for input type.
func (node *Node) GetTransactionsCount(address, txType string) (uint64, error) {
exp, err := node.getExplorerService()
if err != nil {
return 0, err
}
_, tts, err := exp.GetNormalTxHashesByAccount(address)
if err != nil {
return 0, err
}
count := uint64(0)
for _, tt := range tts {
if isTargetTxType(tt, txType) {
count++
}
}
return count, nil
}
// GetStakingTransactionsCount returns the number of staking transactions hashes of address for input type.
func (node *Node) GetStakingTransactionsCount(address, txType string) (uint64, error) {
exp, err := node.getExplorerService()
if err != nil {
return 0, err
}
_, tts, err := exp.GetStakingTxHashesByAccount(address)
if err != nil {
return 0, err
}
count := uint64(0)
for _, tt := range tts {
if isTargetTxType(tt, txType) {
count++
}
}
return count, nil
}
// GetStakingTransactionsCount returns the number of staking transactions hashes of address for input type.
func (node *Node) GetTraceResultByHash(hash common.Hash) (json.RawMessage, error) {
exp, err := node.getExplorerService()
if err != nil {
return nil, err
}
return exp.GetTraceResultByHash(hash)
}
func (node *Node) getExplorerService() (*explorer.Service, error) {
rawService := node.serviceManager.GetService(service.SupportExplorer)
if rawService == nil {
return nil, errors.New("explorer service not started")
}
return rawService.(*explorer.Service), nil
}
func isTargetTxType(tt explorer.TxType, target string) bool {
return target == "" || target == "ALL" || target == tt.String()
}
func getTargetTxHashes(txs []common.Hash, tts []explorer.TxType, target string) []common.Hash {
var res []common.Hash
for i, tx := range txs {
if isTargetTxType(tts[i], target) {
res = append(res, tx)
}
}
return res
}
func reverseTxs(txs []common.Hash) {
for i := 0; i < len(txs)/2; i++ {
j := len(txs) - i - 1
txs[i], txs[j] = txs[j], txs[i]
}
}