-
Notifications
You must be signed in to change notification settings - Fork 3
/
node.go
1433 lines (1283 loc) · 48.2 KB
/
node.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package node
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"math/big"
"os"
"runtime/pprof"
"strings"
"sync"
"time"
"github.com/PositionExchange/posichain/consensus/engine"
harmonyconfig "github.com/PositionExchange/posichain/internal/configs/harmony"
"github.com/PositionExchange/posichain/internal/shardchain/tikv_manage"
"github.com/PositionExchange/posichain/internal/tikv"
"github.com/PositionExchange/posichain/internal/tikv/redis_helper"
"github.com/PositionExchange/posichain/internal/utils/crosslinks"
"github.com/ethereum/go-ethereum/rlp"
bls_core "github.com/PositionExchange/bls/ffi/go/bls"
"github.com/ethereum/go-ethereum/common"
protobuf "github.com/golang/protobuf/proto"
"github.com/harmony-one/abool"
lru "github.com/hashicorp/golang-lru"
libp2p_peer "github.com/libp2p/go-libp2p-core/peer"
libp2p_pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/rcrowley/go-metrics"
"golang.org/x/sync/semaphore"
"github.com/PositionExchange/posichain/api/proto"
msg_pb "github.com/PositionExchange/posichain/api/proto/message"
proto_node "github.com/PositionExchange/posichain/api/proto/node"
"github.com/PositionExchange/posichain/api/service"
"github.com/PositionExchange/posichain/api/service/legacysync"
"github.com/PositionExchange/posichain/api/service/legacysync/downloader"
"github.com/PositionExchange/posichain/consensus"
"github.com/PositionExchange/posichain/core"
"github.com/PositionExchange/posichain/core/rawdb"
"github.com/PositionExchange/posichain/core/types"
"github.com/PositionExchange/posichain/crypto/bls"
nodeconfig "github.com/PositionExchange/posichain/internal/configs/node"
"github.com/PositionExchange/posichain/internal/params"
"github.com/PositionExchange/posichain/internal/shardchain"
"github.com/PositionExchange/posichain/internal/utils"
"github.com/PositionExchange/posichain/node/worker"
"github.com/PositionExchange/posichain/p2p"
"github.com/PositionExchange/posichain/shard"
"github.com/PositionExchange/posichain/shard/committee"
"github.com/PositionExchange/posichain/staking/reward"
"github.com/PositionExchange/posichain/staking/slash"
staking "github.com/PositionExchange/posichain/staking/types"
"github.com/PositionExchange/posichain/webhooks"
)
const (
// NumTryBroadCast is the number of times trying to broadcast
NumTryBroadCast = 3
// MsgChanBuffer is the buffer of consensus message handlers.
MsgChanBuffer = 1024
)
const (
maxBroadcastNodes = 10 // broadcast at most maxBroadcastNodes peers that need in sync
broadcastTimeout int64 = 60 * 1000000000 // 1 mins
//SyncIDLength is the length of bytes for syncID
SyncIDLength = 20
)
// use to push new block to outofsync node
type syncConfig struct {
timestamp int64
client *downloader.Client
// Determine to send encoded BlockWithSig or Block
withSig bool
}
// Node represents a protocol-participating node in the network
type Node struct {
Consensus *consensus.Consensus // Consensus object containing all Consensus related data (e.g. committee members, signatures, commits)
BlockChannel chan *types.Block // The channel to send newly proposed blocks
ConfirmedBlockChannel chan *types.Block // The channel to send confirmed blocks
BeaconBlockChannel chan *types.Block // The channel to send beacon blocks for non-beaconchain nodes
pendingCXReceipts map[string]*types.CXReceiptsProof // All the receipts received but not yet processed for Consensus
pendingCXMutex sync.Mutex
crosslinks *crosslinks.Crosslinks // Memory storage for crosslink processing.
// Shard databases
shardChains shardchain.Collection
SelfPeer p2p.Peer
stateMutex sync.Mutex // mutex for change node state
TxPool *core.TxPool
CxPool *core.CxPool // pool for missing cross shard receipts resend
Worker *worker.Worker
downloaderServer *downloader.Server
// Syncing component.
syncID [SyncIDLength]byte // a unique ID for the node during the state syncing process with peers
stateSync *legacysync.StateSync
epochSync *legacysync.EpochSync
peerRegistrationRecord map[string]*syncConfig // record registration time (unixtime) of peers begin in syncing
SyncingPeerProvider SyncingPeerProvider
// The p2p host used to send/receive p2p messages
host p2p.Host
// Service manager.
serviceManager *service.Manager
ContractDeployerCurrentNonce uint64 // The nonce of the deployer contract at current block
ContractAddresses []common.Address
// Channel to notify consensus service to really start consensus
startConsensus chan struct{}
HarmonyConfig *harmonyconfig.HarmonyConfig
// node configuration, including group ID, shard ID, etc
NodeConfig *nodeconfig.ConfigType
// Chain configuration.
chainConfig params.ChainConfig
unixTimeAtNodeStart int64
// KeysToAddrs holds the addresses of bls keys run by the node
KeysToAddrs map[string]common.Address
keysToAddrsEpoch *big.Int
keysToAddrsMutex sync.Mutex
// TransactionErrorSink contains error messages for any failed transaction, in memory only
TransactionErrorSink *types.TransactionErrorSink
// BroadcastInvalidTx flag is considered when adding pending tx to tx-pool
BroadcastInvalidTx bool
// InSync flag indicates the node is in-sync or not
IsInSync *abool.AtomicBool
proposedBlock map[uint64]*types.Block
deciderCache *lru.Cache
committeeCache *lru.Cache
Metrics metrics.Registry
// context control for pub-sub handling
psCtx context.Context
psCancel func()
}
// Blockchain returns the blockchain for the node's current shard.
func (node *Node) Blockchain() core.BlockChain {
shardID := node.NodeConfig.ShardID
bc, err := node.shardChains.ShardChain(shardID)
if err != nil {
utils.Logger().Error().
Uint32("shardID", shardID).
Err(err).
Msg("cannot get shard chain")
}
return bc
}
// Beaconchain returns the beaconchain from node.
func (node *Node) Beaconchain() core.BlockChain {
// tikv mode not have the BeaconChain storage
if node.HarmonyConfig != nil && node.HarmonyConfig.General.RunElasticMode && node.HarmonyConfig.General.ShardID != shard.BeaconChainShardID {
return nil
}
return node.chain(shard.BeaconChainShardID, core.Options{})
}
func (node *Node) chain(shardID uint32, options core.Options) core.BlockChain {
bc, err := node.shardChains.ShardChain(shardID, options)
if err != nil {
utils.Logger().Error().Err(err).Msg("cannot get beaconchain")
}
// only available in validator node and shard 1-3
isEnablePruneBeaconChain := node.HarmonyConfig != nil && node.HarmonyConfig.General.EnablePruneBeaconChain
isNotBeaconChainValidator := node.NodeConfig.Role() == nodeconfig.Validator && node.NodeConfig.ShardID != shard.BeaconChainShardID
if isEnablePruneBeaconChain && isNotBeaconChainValidator {
bc.EnablePruneBeaconChainFeature()
} else if isEnablePruneBeaconChain && !isNotBeaconChainValidator {
utils.Logger().Info().Msg("`IsEnablePruneBeaconChain` only available in validator node and shard 1-3")
}
return bc
}
// EpochChain returns the epoch chain from node. Epoch chain is the same as BeaconChain,
// but with differences in behaviour.
func (node *Node) EpochChain() core.BlockChain {
return node.chain(shard.BeaconChainShardID, core.Options{
EpochChain: true,
})
}
// TODO: make this batch more transactions
func (node *Node) tryBroadcast(tx *types.Transaction) {
msg := proto_node.ConstructTransactionListMessageAccount(types.Transactions{tx})
shardGroupID := nodeconfig.NewGroupIDByShardID(nodeconfig.ShardID(tx.ShardID()))
utils.Logger().Info().Str("shardGroupID", string(shardGroupID)).Msg("tryBroadcast")
for attempt := 0; attempt < NumTryBroadCast; attempt++ {
if err := node.host.SendMessageToGroups([]nodeconfig.GroupID{shardGroupID},
p2p.ConstructMessage(msg)); err != nil && attempt < NumTryBroadCast {
utils.Logger().Error().Int("attempt", attempt).Msg("Error when trying to broadcast tx")
} else {
break
}
}
}
func (node *Node) tryBroadcastStaking(stakingTx *staking.StakingTransaction) {
msg := proto_node.ConstructStakingTransactionListMessageAccount(staking.StakingTransactions{stakingTx})
shardGroupID := nodeconfig.NewGroupIDByShardID(
nodeconfig.ShardID(shard.BeaconChainShardID),
) // broadcast to beacon chain
utils.Logger().Info().Str("shardGroupID", string(shardGroupID)).Msg("tryBroadcastStaking")
for attempt := 0; attempt < NumTryBroadCast; attempt++ {
if err := node.host.SendMessageToGroups([]nodeconfig.GroupID{shardGroupID},
p2p.ConstructMessage(msg)); err != nil && attempt < NumTryBroadCast {
utils.Logger().Error().Int("attempt", attempt).Msg("Error when trying to broadcast staking tx")
} else {
break
}
}
}
// Add new transactions to the pending transaction list.
func (node *Node) addPendingTransactions(newTxs types.Transactions) []error {
// if inSync, _, _ := node.SyncStatus(node.Blockchain().ShardID()); !inSync && node.NodeConfig.GetNetworkType() == nodeconfig.Mainnet {
// utils.Logger().Debug().
// Int("length of newTxs", len(newTxs)).
// Msg("[addPendingTransactions] Node out of sync, ignoring transactions")
// return nil
// }
poolTxs := types.PoolTransactions{}
errs := []error{}
acceptCx := node.Blockchain().Config().AcceptsCrossTx(node.Blockchain().CurrentHeader().Epoch())
for _, tx := range newTxs {
if tx.ShardID() != tx.ToShardID() && !acceptCx {
errs = append(errs, errors.WithMessage(errInvalidEpoch, "cross-shard tx not accepted yet"))
continue
}
if tx.IsEthCompatible() && !node.Blockchain().Config().IsEthCompatible(node.Blockchain().CurrentBlock().Epoch()) {
errs = append(errs, errors.WithMessage(errInvalidEpoch, "ethereum tx not accepted yet"))
continue
}
poolTxs = append(poolTxs, tx)
}
errs = append(errs, node.TxPool.AddRemotes(poolTxs)...)
pendingCount, queueCount := node.TxPool.Stats()
utils.Logger().Debug().
Interface("err", errs).
Int("length of newTxs", len(newTxs)).
Int("totalPending", pendingCount).
Int("totalQueued", queueCount).
Msg("[addPendingTransactions] Adding more transactions")
return errs
}
// Add new staking transactions to the pending staking transaction list.
func (node *Node) addPendingStakingTransactions(newStakingTxs staking.StakingTransactions) []error {
if node.IsRunningBeaconChain() {
if node.Blockchain().Config().IsPreStaking(node.Blockchain().CurrentHeader().Epoch()) {
poolTxs := types.PoolTransactions{}
for _, tx := range newStakingTxs {
poolTxs = append(poolTxs, tx)
}
errs := node.TxPool.AddRemotes(poolTxs)
pendingCount, queueCount := node.TxPool.Stats()
utils.Logger().Info().
Int("length of newStakingTxs", len(poolTxs)).
Int("totalPending", pendingCount).
Int("totalQueued", queueCount).
Msg("Got more staking transactions")
return errs
}
return []error{
errors.WithMessage(errInvalidEpoch, "staking txs not accepted yet"),
}
}
return []error{
errors.WithMessage(errInvalidShard, fmt.Sprintf("txs only valid on shard %v", shard.BeaconChainShardID)),
}
}
// AddPendingStakingTransaction staking transactions
func (node *Node) AddPendingStakingTransaction(
newStakingTx *staking.StakingTransaction,
) error {
if node.IsRunningBeaconChain() {
errs := node.addPendingStakingTransactions(staking.StakingTransactions{newStakingTx})
var err error
for i := range errs {
if errs[i] != nil {
utils.Logger().Info().
Err(errs[i]).
Msg("[AddPendingStakingTransaction] Failed adding new staking transaction")
err = errs[i]
break
}
}
if err == nil || node.BroadcastInvalidTx {
utils.Logger().Info().
Str("Hash", newStakingTx.Hash().Hex()).
Msg("Broadcasting Staking Tx")
node.tryBroadcastStaking(newStakingTx)
}
return err
}
return nil
}
// AddPendingTransaction adds one new transaction to the pending transaction list.
// This is only called from SDK.
func (node *Node) AddPendingTransaction(newTx *types.Transaction) error {
if newTx.ShardID() == node.NodeConfig.ShardID {
errs := node.addPendingTransactions(types.Transactions{newTx})
var err error
for i := range errs {
if errs[i] != nil {
utils.Logger().Info().Err(errs[i]).Msg("[AddPendingTransaction] Failed adding new transaction")
err = errs[i]
break
}
}
if err == nil || node.BroadcastInvalidTx {
utils.Logger().Info().Str("Hash", newTx.Hash().Hex()).Str("HashByType", newTx.HashByType().Hex()).Msg("Broadcasting Tx")
node.tryBroadcast(newTx)
}
return err
}
return errors.Errorf("shard do not match, txShard: %d, nodeShard: %d", newTx.ShardID(), node.NodeConfig.ShardID)
}
// AddPendingReceipts adds one receipt message to pending list.
func (node *Node) AddPendingReceipts(receipts *types.CXReceiptsProof) {
node.pendingCXMutex.Lock()
defer node.pendingCXMutex.Unlock()
if receipts.ContainsEmptyField() {
utils.Logger().Info().
Int("totalPendingReceipts", len(node.pendingCXReceipts)).
Msg("CXReceiptsProof contains empty field")
return
}
blockNum := receipts.Header.Number().Uint64()
shardID := receipts.Header.ShardID()
// Sanity checks
if err := node.Blockchain().Validator().ValidateCXReceiptsProof(receipts); err != nil {
if !strings.Contains(err.Error(), rawdb.MsgNoShardStateFromDB) {
utils.Logger().Error().Err(err).Msg("[AddPendingReceipts] Invalid CXReceiptsProof")
return
}
}
// cross-shard receipt should not be coming from our shard
if s := node.Consensus.ShardID; s == shardID {
utils.Logger().Info().
Uint32("my-shard", s).
Uint32("receipt-shard", shardID).
Msg("ShardID of incoming receipt was same as mine")
return
}
if e := receipts.Header.Epoch(); blockNum == 0 ||
!node.Blockchain().Config().AcceptsCrossTx(e) {
utils.Logger().Info().
Uint64("incoming-epoch", e.Uint64()).
Msg("Incoming receipt had meaningless epoch")
return
}
key := utils.GetPendingCXKey(shardID, blockNum)
// DDoS protection
const maxCrossTxnSize = 4096
if s := len(node.pendingCXReceipts); s >= maxCrossTxnSize {
utils.Logger().Info().
Int("pending-cx-receipts-size", s).
Int("pending-cx-receipts-limit", maxCrossTxnSize).
Msg("Current pending cx-receipts reached size limit")
return
}
if _, ok := node.pendingCXReceipts[key]; ok {
utils.Logger().Info().
Int("totalPendingReceipts", len(node.pendingCXReceipts)).
Msg("Already Got Same Receipt message")
return
}
node.pendingCXReceipts[key] = receipts
utils.Logger().Info().
Int("totalPendingReceipts", len(node.pendingCXReceipts)).
Msg("Got ONE more receipt message")
}
type withError struct {
err error
payload interface{}
}
var (
errNotRightKeySize = errors.New("key received over wire is wrong size")
errNoSenderPubKey = errors.New("no sender public BLS key in message")
errViewIDTooOld = errors.New("view id too old")
errWrongSizeOfBitmap = errors.New("wrong size of sender bitmap")
errWrongShardID = errors.New("wrong shard id")
errInvalidNodeMsg = errors.New("invalid node message")
errIgnoreBeaconMsg = errors.New("ignore beacon sync block")
errInvalidEpoch = errors.New("invalid epoch for transaction")
errInvalidShard = errors.New("invalid shard")
)
const beaconBlockHeightTolerance = 2
// validateNodeMessage validate node message
func (node *Node) validateNodeMessage(ctx context.Context, payload []byte) (
[]byte, proto_node.MessageType, error) {
// length of payload must > p2pNodeMsgPrefixSize
// reject huge node messages
if len(payload) >= types.MaxP2PNodeDataSize {
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "invalid_oversized"}).Inc()
return nil, 0, core.ErrOversizedData
}
// just ignore payload[0], which is MsgCategoryType (consensus/node)
msgType := proto_node.MessageType(payload[proto.MessageCategoryBytes])
switch msgType {
case proto_node.Transaction:
// nothing much to validate transaction message unless decode the RLP
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "tx"}).Inc()
case proto_node.Staking:
// nothing much to validate staking message unless decode the RLP
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "staking_tx"}).Inc()
case proto_node.Block:
switch proto_node.BlockMessageType(payload[p2pNodeMsgPrefixSize]) {
case proto_node.Sync:
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "block_sync"}).Inc()
// in tikv mode, not need BeaconChain message
if node.HarmonyConfig.General.RunElasticMode && node.HarmonyConfig.General.ShardID != shard.BeaconChainShardID {
return nil, 0, errIgnoreBeaconMsg
}
// checks whether the beacon block is larger than current block number
blocksPayload := payload[p2pNodeMsgPrefixSize+1:]
var blocks []*types.Block
if err := rlp.DecodeBytes(blocksPayload, &blocks); err != nil {
return nil, 0, errors.Wrap(err, "block decode error")
}
curBeaconHeight := node.Beaconchain().CurrentBlock().NumberU64()
for _, block := range blocks {
// Ban blocks number that is smaller than tolerance
if block.NumberU64()+beaconBlockHeightTolerance <= curBeaconHeight {
utils.Logger().Debug().Uint64("receivedNum", block.NumberU64()).
Uint64("currentNum", curBeaconHeight).Msg("beacon block sync message rejected")
return nil, 0, errors.New("beacon block height smaller than current height beyond tolerance")
} else if block.NumberU64()-beaconBlockHeightTolerance > curBeaconHeight {
utils.Logger().Debug().Uint64("receivedNum", block.NumberU64()).
Uint64("currentNum", curBeaconHeight).Msg("beacon block sync message rejected")
return nil, 0, errors.New("beacon block height too much higher than current height beyond tolerance")
} else if block.NumberU64() <= curBeaconHeight {
utils.Logger().Debug().Uint64("receivedNum", block.NumberU64()).
Uint64("currentNum", curBeaconHeight).Msg("beacon block sync message ignored")
return nil, 0, errIgnoreBeaconMsg
}
}
// only non-beacon nodes process the beacon block sync messages
if node.Blockchain().ShardID() == shard.BeaconChainShardID {
return nil, 0, errIgnoreBeaconMsg
}
case proto_node.SlashCandidate:
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "slash"}).Inc()
// only beacon chain node process slash candidate messages
if !node.IsRunningBeaconChain() {
return nil, 0, errIgnoreBeaconMsg
}
case proto_node.Receipt:
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "node_receipt"}).Inc()
case proto_node.CrossLink:
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "crosslink"}).Inc()
if node.NodeConfig.Role() == nodeconfig.ExplorerNode {
return nil, 0, errIgnoreBeaconMsg
}
case proto_node.CrosslinkHeartbeat:
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "crosslink_heartbeat"}).Inc()
// only non beacon chain processes cross link heartbeat
if node.IsRunningBeaconChain() {
return nil, 0, errInvalidShard
}
default:
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "invalid_block_type"}).Inc()
return nil, 0, errInvalidNodeMsg
}
default:
nodeNodeMessageCounterVec.With(prometheus.Labels{"type": "invalid_node_type"}).Inc()
return nil, 0, errInvalidNodeMsg
}
return payload[p2pNodeMsgPrefixSize:], msgType, nil
}
// validateShardBoundMessage validate consensus message
// validate shardID
// validate public key size
// verify message signature
func (node *Node) validateShardBoundMessage(
ctx context.Context, payload []byte,
) (*msg_pb.Message, *bls.SerializedPublicKey, bool, error) {
var (
m msg_pb.Message
)
if err := protobuf.Unmarshal(payload, &m); err != nil {
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "invalid_unmarshal"}).Inc()
return nil, nil, true, errors.WithStack(err)
}
// ignore messages not intended for explorer
if node.NodeConfig.Role() == nodeconfig.ExplorerNode {
switch m.Type {
case
msg_pb.MessageType_ANNOUNCE,
msg_pb.MessageType_PREPARE,
msg_pb.MessageType_COMMIT,
msg_pb.MessageType_VIEWCHANGE,
msg_pb.MessageType_NEWVIEW:
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "ignored"}).Inc()
return nil, nil, true, nil
}
}
// when node is in ViewChanging mode, it still accepts normal messages into FBFTLog
// in order to avoid possible trap forever but drop PREPARE and COMMIT
// which are message types specifically for a node acting as leader
// so we just ignore those messages
if node.Consensus.IsViewChangingMode() {
switch m.Type {
case msg_pb.MessageType_PREPARE, msg_pb.MessageType_COMMIT:
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "ignored"}).Inc()
return nil, nil, true, nil
}
} else {
// ignore viewchange/newview message if the node is not in viewchanging mode
switch m.Type {
case msg_pb.MessageType_NEWVIEW, msg_pb.MessageType_VIEWCHANGE:
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "ignored"}).Inc()
return nil, nil, true, nil
}
}
// ignore message not intended for leader, but still forward them to the network
if node.Consensus.IsLeader() {
switch m.Type {
case msg_pb.MessageType_ANNOUNCE, msg_pb.MessageType_PREPARED, msg_pb.MessageType_COMMITTED:
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "ignored"}).Inc()
return nil, nil, true, nil
}
}
maybeCon, maybeVC := m.GetConsensus(), m.GetViewchange()
senderKey := []byte{}
senderBitmap := []byte{}
if maybeCon != nil {
if maybeCon.ShardId != node.Consensus.ShardID {
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "invalid_shard"}).Inc()
return nil, nil, true, errors.WithStack(errWrongShardID)
}
senderKey = maybeCon.SenderPubkey
if len(maybeCon.SenderPubkeyBitmap) > 0 {
senderBitmap = maybeCon.SenderPubkeyBitmap
}
// If the viewID is too old, reject the message.
if maybeCon.ViewId+5 < node.Consensus.GetCurBlockViewID() {
return nil, nil, true, errors.WithStack(errViewIDTooOld)
}
} else if maybeVC != nil {
if maybeVC.ShardId != node.Consensus.ShardID {
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "invalid_shard"}).Inc()
return nil, nil, true, errors.WithStack(errWrongShardID)
}
senderKey = maybeVC.SenderPubkey
// If the viewID is too old, reject the message.
if maybeVC.ViewId+5 < node.Consensus.GetViewChangingID() {
return nil, nil, true, errors.WithStack(errViewIDTooOld)
}
} else {
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "invalid"}).Inc()
return nil, nil, true, errors.WithStack(errNoSenderPubKey)
}
// ignore mesage not intended for validator
// but still forward them to the network
if !node.Consensus.IsLeader() {
switch m.Type {
case msg_pb.MessageType_PREPARE, msg_pb.MessageType_COMMIT:
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "ignored"}).Inc()
return nil, nil, true, nil
}
}
serializedKey := bls.SerializedPublicKey{}
if len(senderKey) > 0 {
if len(senderKey) != bls.PublicKeySizeInBytes {
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "invalid_key_size"}).Inc()
return nil, nil, true, errors.WithStack(errNotRightKeySize)
}
copy(serializedKey[:], senderKey)
if !node.Consensus.IsValidatorInCommittee(serializedKey) {
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "invalid_committee"}).Inc()
return nil, nil, true, errors.WithStack(shard.ErrValidNotInCommittee)
}
} else {
count := node.Consensus.Decider.ParticipantsCount()
if (count+7)>>3 != int64(len(senderBitmap)) {
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "invalid_participant_count"}).Inc()
return nil, nil, true, errors.WithStack(errWrongSizeOfBitmap)
}
}
nodeConsensusMessageCounterVec.With(prometheus.Labels{"type": "valid"}).Inc()
// serializedKey will be empty for multiSig sender
return &m, &serializedKey, false, nil
}
var (
errMsgHadNoHMYPayLoadAssumption = errors.New("did not have sufficient size for hmy msg")
errConsensusMessageOnUnexpectedTopic = errors.New("received consensus on wrong topic")
)
// StartPubSub kicks off the node message handling
func (node *Node) StartPubSub() error {
node.psCtx, node.psCancel = context.WithCancel(context.Background())
// groupID and whether this topic is used for consensus
type t struct {
tp nodeconfig.GroupID
isCon bool
}
groups := map[nodeconfig.GroupID]bool{}
// three topic subscribed by each validator
for _, t := range []t{
{node.NodeConfig.GetShardGroupID(), true},
{node.NodeConfig.GetClientGroupID(), false},
} {
if _, ok := groups[t.tp]; !ok {
groups[t.tp] = t.isCon
}
}
type u struct {
p2p.NamedTopic
consensusBound bool
}
var allTopics []u
utils.Logger().Debug().
Interface("topics-ended-up-with", groups).
Uint32("shard-id", node.Consensus.ShardID).
Msg("starting with these topics")
if !node.NodeConfig.IsOffline {
for key, isCon := range groups {
topicHandle, err := node.host.GetOrJoin(string(key))
if err != nil {
return err
}
allTopics = append(
allTopics, u{
NamedTopic: p2p.NamedTopic{Name: string(key), Topic: topicHandle},
consensusBound: isCon,
},
)
}
}
pubsub := node.host.PubSub()
ownID := node.host.GetID()
errChan := make(chan withError, 100)
// p2p consensus message handler function
type p2pHandlerConsensus func(
ctx context.Context,
msg *msg_pb.Message,
key *bls.SerializedPublicKey,
) error
// other p2p message handler function
type p2pHandlerElse func(
ctx context.Context,
rlpPayload []byte,
actionType proto_node.MessageType,
) error
// interface pass to p2p message validator
type validated struct {
consensusBound bool
handleC p2pHandlerConsensus
handleCArg *msg_pb.Message
handleE p2pHandlerElse
handleEArg []byte
senderPubKey *bls.SerializedPublicKey
actionType proto_node.MessageType
}
isThisNodeAnExplorerNode := node.NodeConfig.Role() == nodeconfig.ExplorerNode
nodeStringCounterVec.WithLabelValues("peerid", nodeconfig.GetPeerID().String()).Inc()
for i := range allTopics {
sub, err := allTopics[i].Topic.Subscribe()
if err != nil {
return err
}
topicNamed := allTopics[i].Name
isConsensusBound := allTopics[i].consensusBound
utils.Logger().Info().
Str("topic", topicNamed).
Msg("enabled topic validation pubsub messages")
// register topic validator for each topic
if err := pubsub.RegisterTopicValidator(
topicNamed,
// this is the validation function called to quickly validate every p2p message
func(ctx context.Context, peer libp2p_peer.ID, msg *libp2p_pubsub.Message) libp2p_pubsub.ValidationResult {
nodeP2PMessageCounterVec.With(prometheus.Labels{"type": "total"}).Inc()
hmyMsg := msg.GetData()
// first to validate the size of the p2p message
if len(hmyMsg) < p2pMsgPrefixSize {
// TODO (lc): block peers sending empty messages
nodeP2PMessageCounterVec.With(prometheus.Labels{"type": "invalid_size"}).Inc()
return libp2p_pubsub.ValidationReject
}
openBox := hmyMsg[p2pMsgPrefixSize:]
// validate message category
switch proto.MessageCategory(openBox[proto.MessageCategoryBytes-1]) {
case proto.Consensus:
// received consensus message in non-consensus bound topic
if !isConsensusBound {
nodeP2PMessageCounterVec.With(prometheus.Labels{"type": "invalid_bound"}).Inc()
errChan <- withError{
errors.WithStack(errConsensusMessageOnUnexpectedTopic), msg,
}
return libp2p_pubsub.ValidationReject
}
nodeP2PMessageCounterVec.With(prometheus.Labels{"type": "consensus_total"}).Inc()
// validate consensus message
validMsg, senderPubKey, ignore, err := node.validateShardBoundMessage(
context.TODO(), openBox[proto.MessageCategoryBytes:],
)
if err != nil {
errChan <- withError{err, msg.GetFrom()}
return libp2p_pubsub.ValidationReject
}
// ignore the further processing of the p2p messages as it is not intended for this node
if ignore {
return libp2p_pubsub.ValidationAccept
}
msg.ValidatorData = validated{
consensusBound: true,
handleC: node.Consensus.HandleMessageUpdate,
handleCArg: validMsg,
senderPubKey: senderPubKey,
}
return libp2p_pubsub.ValidationAccept
case proto.Node:
// node message is almost empty
if len(openBox) <= p2pNodeMsgPrefixSize {
nodeP2PMessageCounterVec.With(prometheus.Labels{"type": "invalid_size"}).Inc()
return libp2p_pubsub.ValidationReject
}
nodeP2PMessageCounterVec.With(prometheus.Labels{"type": "node_total"}).Inc()
validMsg, actionType, err := node.validateNodeMessage(
context.TODO(), openBox,
)
if err != nil {
switch err {
case errIgnoreBeaconMsg:
// ignore the further processing of the ignored messages as it is not intended for this node
// but propogate the messages to other nodes
return libp2p_pubsub.ValidationAccept
default:
// TODO (lc): block peers sending error messages
errChan <- withError{err, msg.GetFrom()}
return libp2p_pubsub.ValidationReject
}
}
msg.ValidatorData = validated{
consensusBound: false,
handleE: node.HandleNodeMessage,
handleEArg: validMsg,
actionType: actionType,
}
return libp2p_pubsub.ValidationAccept
default:
// ignore garbled messages
nodeP2PMessageCounterVec.With(prometheus.Labels{"type": "ignored"}).Inc()
return libp2p_pubsub.ValidationReject
}
},
// WithValidatorTimeout is an option that sets a timeout for an (asynchronous) topic validator. By default there is no timeout in asynchronous validators.
// TODO: Currently this timeout is useless. Verify me.
libp2p_pubsub.WithValidatorTimeout(250*time.Millisecond),
// WithValidatorConcurrency set the concurernt validator, default is 1024
libp2p_pubsub.WithValidatorConcurrency(p2p.SetAsideForConsensus),
// WithValidatorInline is an option that sets the validation disposition to synchronous:
// it will be executed inline in validation front-end, without spawning a new goroutine.
// This is suitable for simple or cpu-bound validators that do not block.
libp2p_pubsub.WithValidatorInline(true),
); err != nil {
return err
}
semConsensus := semaphore.NewWeighted(p2p.SetAsideForConsensus)
msgChanConsensus := make(chan validated, MsgChanBuffer)
// goroutine to handle consensus messages
go func() {
for {
select {
case <-node.psCtx.Done():
return
case m := <-msgChanConsensus:
// should not take more than 30 seconds to process one message
ctx, cancel := context.WithTimeout(node.psCtx, 30*time.Second)
msg := m
go func() {
defer cancel()
if semConsensus.TryAcquire(1) {
defer semConsensus.Release(1)
if isThisNodeAnExplorerNode {
if err := node.explorerMessageHandler(
ctx, msg.handleCArg,
); err != nil {
errChan <- withError{err, nil}
}
} else {
if err := msg.handleC(ctx, msg.handleCArg, msg.senderPubKey); err != nil {
errChan <- withError{err, msg.senderPubKey}
}
}
}
select {
// FIXME: wrong use of context. This message have already passed handle actually.
case <-ctx.Done():
if errors.Is(ctx.Err(), context.DeadlineExceeded) ||
errors.Is(ctx.Err(), context.Canceled) {
utils.Logger().Warn().
Str("topic", topicNamed).Msg("[context] exceeded consensus message handler deadline")
}
errChan <- withError{errors.WithStack(ctx.Err()), nil}
default:
return
}
}()
}
}
}()
semNode := semaphore.NewWeighted(p2p.SetAsideOtherwise)
msgChanNode := make(chan validated, MsgChanBuffer)
// goroutine to handle node messages
go func() {
for {
select {
case m := <-msgChanNode:
ctx, cancel := context.WithTimeout(node.psCtx, 10*time.Second)
msg := m
go func() {
defer cancel()
if semNode.TryAcquire(1) {
defer semNode.Release(1)
if err := msg.handleE(ctx, msg.handleEArg, msg.actionType); err != nil {
errChan <- withError{err, nil}
}
}
select {
case <-ctx.Done():
if errors.Is(ctx.Err(), context.DeadlineExceeded) ||
errors.Is(ctx.Err(), context.Canceled) {
utils.Logger().Warn().
Str("topic", topicNamed).Msg("[context] exceeded node message handler deadline")
}
errChan <- withError{errors.WithStack(ctx.Err()), nil}
default:
return
}
}()
case <-node.psCtx.Done():
return
}
}
}()
go func() {
for {
nextMsg, err := sub.Next(node.psCtx)
if err != nil {
if err == context.Canceled {
return
}
errChan <- withError{errors.WithStack(err), nil}
continue
}
if nextMsg.GetFrom() == ownID {
continue
}
if validatedMessage, ok := nextMsg.ValidatorData.(validated); ok {
if validatedMessage.consensusBound {
msgChanConsensus <- validatedMessage
} else {
msgChanNode <- validatedMessage
}
} else {
// continue if ValidatorData is nil
if nextMsg.ValidatorData == nil {
continue
}
}
}
}()
}
go func() {
for {
select {
case <-node.psCtx.Done():
return
case e := <-errChan:
utils.SampledLogger().Info().
Interface("item", e.payload).
Msgf("[p2p]: issue while handling incoming p2p message: %v", e.err)
}
}
}()
node.TraceLoopForExplorer()
return nil
}
// StopPubSub stops the pubsub handling
func (node *Node) StopPubSub() {
if node.psCancel != nil {
node.psCancel()
}
}
// GetSyncID returns the syncID of this node
func (node *Node) GetSyncID() [SyncIDLength]byte {
return node.syncID
}
// New creates a new node.
func New(
host p2p.Host,
consensusObj *consensus.Consensus,
engine engine.Engine,
collection *shardchain.CollectionImpl,
blacklist map[common.Address]struct{},
allowedTxs map[common.Address]core.AllowedTxData,
localAccounts []common.Address,
isArchival map[uint32]bool,
harmonyconfig *harmonyconfig.HarmonyConfig,
) *Node {
node := Node{}
node.unixTimeAtNodeStart = time.Now().Unix()
node.TransactionErrorSink = types.NewTransactionErrorSink()
node.crosslinks = crosslinks.New()
// Get the node config that's created in the harmony.go program.
if consensusObj != nil {
node.NodeConfig = nodeconfig.GetShardConfig(consensusObj.ShardID)
} else {