forked from 0xakk0r0kamui/constant-chain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
1712 lines (1561 loc) · 56.9 KB
/
server.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 main
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/incognitochain/incognito-chain/blockchain/btc"
"github.com/incognitochain/incognito-chain/memcache"
"github.com/incognitochain/incognito-chain/metrics"
"github.com/incognitochain/incognito-chain/pubsub"
"golang.org/x/net/context"
"google.golang.org/api/option"
"cloud.google.com/go/storage"
"github.com/incognitochain/incognito-chain/addrmanager"
"github.com/incognitochain/incognito-chain/blockchain"
"github.com/incognitochain/incognito-chain/common"
"github.com/incognitochain/incognito-chain/connmanager"
"github.com/incognitochain/incognito-chain/metadata"
"github.com/incognitochain/incognito-chain/transaction"
"github.com/incognitochain/incognito-chain/consensus/mubft"
"github.com/incognitochain/incognito-chain/database"
"github.com/incognitochain/incognito-chain/databasemp"
"github.com/incognitochain/incognito-chain/incognitokey"
"github.com/incognitochain/incognito-chain/mempool"
"github.com/incognitochain/incognito-chain/netsync"
"github.com/incognitochain/incognito-chain/peer"
"github.com/incognitochain/incognito-chain/rpccaller"
"github.com/incognitochain/incognito-chain/rpcserver"
"github.com/incognitochain/incognito-chain/wallet"
"github.com/incognitochain/incognito-chain/wire"
libp2p "github.com/libp2p/go-libp2p-peer"
)
type Server struct {
started int32
startupTime int64
protocolVersion string
isEnableMining bool
chainParams *blockchain.Params
connManager *connmanager.ConnManager
blockChain *blockchain.BlockChain
dataBase database.DatabaseInterface
memCache *memcache.MemoryCache
rpcServer *rpcserver.RpcServer
memPool *mempool.TxPool
tempMemPool *mempool.TxPool
beaconPool *mempool.BeaconPool
shardPool map[byte]blockchain.ShardPool
shardToBeaconPool *mempool.ShardToBeaconPool
crossShardPool map[byte]blockchain.CrossShardPool
waitGroup sync.WaitGroup
netSync *netsync.NetSync
addrManager *addrmanager.AddrManager
userKeySet *incognitokey.KeySet
wallet *wallet.Wallet
consensusEngine *mubft.Engine
blockgen *blockchain.BlockGenerator
pusubManager *pubsub.PubSubManager
// The fee estimator keeps track of how long transactions are left in
// the mempool before they are mined into blocks.
feeEstimator map[byte]*mempool.FeeEstimator
cQuit chan struct{}
cNewPeers chan *peer.Peer
}
// setupRPCListeners returns a slice of listeners that are configured for use
// with the RPC server depending on the configuration settings for listen
// addresses and TLS.
func (serverObj *Server) setupRPCListeners() ([]net.Listener, error) {
// Setup TLS if not disabled.
listenFunc := net.Listen
if !cfg.DisableTLS {
Logger.log.Debug("Disable TLS for RPC is false")
// Generate the TLS cert and key file if both don't already
// exist.
if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
err := rpcserver.GenCertPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
}
keyPair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{keyPair},
MinVersion: tls.VersionTLS12,
}
// Change the standard net.Listen function to the tls one.
listenFunc = func(net string, laddr string) (net.Listener, error) {
return tls.Listen(net, laddr, &tlsConfig)
}
} else {
Logger.log.Debug("Disable TLS for RPC is true")
}
netAddrs, err := common.ParseListeners(cfg.RPCListeners, "tcp")
if err != nil {
return nil, err
}
listeners := make([]net.Listener, 0, len(netAddrs))
for _, addr := range netAddrs {
listener, err := listenFunc(addr.Network(), addr.String())
if err != nil {
log.Printf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
return listeners, nil
}
func (serverObj *Server) setupRPCWsListeners() ([]net.Listener, error) {
// Setup TLS if not disabled.
listenFunc := net.Listen
if !cfg.DisableTLS {
Logger.log.Debug("Disable TLS for RPC is false")
// Generate the TLS cert and key file if both don't already
// exist.
if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
err := rpcserver.GenCertPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
}
keyPair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{keyPair},
MinVersion: tls.VersionTLS12,
}
// Change the standard net.Listen function to the tls one.
listenFunc = func(net string, laddr string) (net.Listener, error) {
return tls.Listen(net, laddr, &tlsConfig)
}
} else {
Logger.log.Debug("Disable TLS for RPC is true")
}
netAddrs, err := common.ParseListeners(cfg.RPCWSListeners, "tcp")
if err != nil {
return nil, err
}
listeners := make([]net.Listener, 0, len(netAddrs))
for _, addr := range netAddrs {
listener, err := listenFunc(addr.Network(), addr.String())
if err != nil {
log.Printf("Can't listen on %s: %v", addr, err)
continue
}
listeners = append(listeners, listener)
}
return listeners, nil
}
/*
NewServer - create server object which control all process of node
*/
func (serverObj *Server) NewServer(listenAddrs string, db database.DatabaseInterface, dbmp databasemp.DatabaseInterface, chainParams *blockchain.Params, protocolVer string, interrupt <-chan struct{}) error {
// Init data for Server
serverObj.protocolVersion = protocolVer
serverObj.chainParams = chainParams
serverObj.cQuit = make(chan struct{})
serverObj.cNewPeers = make(chan *peer.Peer)
serverObj.dataBase = db
serverObj.memCache = memcache.New()
//Init channel
cPendingTxs := make(chan metadata.Transaction, 500)
cRemovedTxs := make(chan metadata.Transaction, 500)
var err error
// init an pubsub manager
var pubsubManager = pubsub.NewPubSubManager()
serverObj.userKeySet, err = cfg.GetUserKeySet()
if err != nil {
if cfg.NodeMode == common.NODEMODE_AUTO || cfg.NodeMode == common.NODEMODE_BEACON || cfg.NodeMode == common.NODEMODE_SHARD {
Logger.log.Critical(err)
return err
} else {
Logger.log.Error(err)
}
}
serverObj.pusubManager = pubsubManager
serverObj.beaconPool = mempool.GetBeaconPool()
serverObj.shardToBeaconPool = mempool.GetShardToBeaconPool()
serverObj.crossShardPool = make(map[byte]blockchain.CrossShardPool)
serverObj.shardPool = make(map[byte]blockchain.ShardPool)
serverObj.blockChain = &blockchain.BlockChain{}
serverObj.isEnableMining = cfg.EnableMining
relayShards := []byte{}
if cfg.RelayShards == "all" {
for index := 0; index < common.MAX_SHARD_NUMBER; index++ {
relayShards = append(relayShards, byte(index))
}
} else {
var validPath = regexp.MustCompile(`(?s)[[:digit:]]+`)
relayShardsStr := validPath.FindAllString(cfg.RelayShards, -1)
for index := 0; index < len(relayShardsStr); index++ {
s, err := strconv.Atoi(relayShardsStr[index])
if err == nil {
relayShards = append(relayShards, byte(s))
}
}
}
var randomClient btc.RandomClient
if cfg.BtcClient == 0 {
randomClient = &btc.BlockCypherClient{}
} else {
if cfg.BtcClientIP == common.EmptyString || cfg.BtcClientUsername == common.EmptyString || cfg.BtcClientPassword == common.EmptyString {
Logger.log.Error("Please input Bitcoin Client Ip, Username, password. Otherwise, set btcclient is 0 or leave it to default value")
os.Exit(2)
}
randomClient = btc.NewBTCClient(cfg.BtcClientUsername, cfg.BtcClientPassword, cfg.BtcClientIP, cfg.BtcClientPort)
}
err = serverObj.blockChain.Init(&blockchain.Config{
ChainParams: serverObj.chainParams,
DataBase: serverObj.dataBase,
MemCache: serverObj.memCache,
//MemCache: nil,
Interrupt: interrupt,
RelayShards: relayShards,
BeaconPool: serverObj.beaconPool,
ShardPool: serverObj.shardPool,
ShardToBeaconPool: serverObj.shardToBeaconPool,
CrossShardPool: serverObj.crossShardPool,
Server: serverObj,
UserKeySet: serverObj.userKeySet,
NodeMode: cfg.NodeMode,
FeeEstimator: make(map[byte]blockchain.FeeEstimator),
PubSubManager: pubsubManager,
RandomClient: randomClient,
})
serverObj.blockChain.InitChannelBlockchain(cRemovedTxs)
if err != nil {
return err
}
//init beacon pol
mempool.InitBeaconPool(serverObj.pusubManager)
//init shard pool
mempool.InitShardPool(serverObj.shardPool, serverObj.pusubManager)
//init cross shard pool
mempool.InitCrossShardPool(serverObj.crossShardPool, db)
//init shard to beacon bool
mempool.InitShardToBeaconPool()
// or if it cannot be loaded, create a new one.
if cfg.FastStartup {
Logger.log.Debug("Load chain dependencies from DB")
serverObj.feeEstimator = make(map[byte]*mempool.FeeEstimator)
for shardID, bestState := range serverObj.blockChain.BestState.Shard {
_ = bestState
feeEstimatorData, err := serverObj.dataBase.GetFeeEstimator(shardID)
if err == nil && len(feeEstimatorData) > 0 {
feeEstimator, err := mempool.RestoreFeeEstimator(feeEstimatorData)
if err != nil {
Logger.log.Errorf("Failed to restore fee estimator %v", err)
Logger.log.Debug("Init NewFeeEstimator")
serverObj.feeEstimator[shardID] = mempool.NewFeeEstimator(
mempool.DefaultEstimateFeeMaxRollback,
mempool.DefaultEstimateFeeMinRegisteredBlocks,
cfg.LimitFee, cfg.LimitFeeToken)
} else {
serverObj.feeEstimator[shardID] = feeEstimator
}
} else {
Logger.log.Errorf("Failed to get fee estimator from DB %v", err)
Logger.log.Debug("Init NewFeeEstimator")
serverObj.feeEstimator[shardID] = mempool.NewFeeEstimator(
mempool.DefaultEstimateFeeMaxRollback,
mempool.DefaultEstimateFeeMinRegisteredBlocks,
cfg.LimitFee, cfg.LimitFeeToken)
}
}
} else {
err := serverObj.dataBase.CleanCommitments()
if err != nil {
Logger.log.Error(err)
return err
}
err = serverObj.dataBase.CleanSerialNumbers()
if err != nil {
Logger.log.Error(err)
return err
}
err = serverObj.dataBase.CleanFeeEstimator()
if err != nil {
Logger.log.Error(err)
return err
}
serverObj.feeEstimator = make(map[byte]*mempool.FeeEstimator)
}
for shardID, feeEstimator := range serverObj.feeEstimator {
serverObj.blockChain.SetFeeEstimator(feeEstimator, shardID)
}
// create mempool tx
serverObj.memPool = &mempool.TxPool{}
serverObj.memPool.Init(&mempool.Config{
BlockChain: serverObj.blockChain,
DataBase: serverObj.dataBase,
ChainParams: chainParams,
FeeEstimator: serverObj.feeEstimator,
TxLifeTime: cfg.TxPoolTTL,
MaxTx: cfg.TxPoolMaxTx,
DataBaseMempool: dbmp,
IsLoadFromMempool: cfg.LoadMempool,
PersistMempool: cfg.PersistMempool,
RelayShards: relayShards,
UserKeyset: serverObj.userKeySet,
PubSubManager: serverObj.pusubManager,
})
serverObj.memPool.AnnouncePersisDatabaseMempool()
//add tx pool
serverObj.blockChain.AddTxPool(serverObj.memPool)
serverObj.memPool.InitChannelMempool(cPendingTxs, cRemovedTxs)
//==============Temp mem pool only used for validation
serverObj.tempMemPool = &mempool.TxPool{}
serverObj.tempMemPool.Init(&mempool.Config{
BlockChain: serverObj.blockChain,
DataBase: serverObj.dataBase,
ChainParams: chainParams,
FeeEstimator: serverObj.feeEstimator,
MaxTx: cfg.TxPoolMaxTx,
PubSubManager: pubsubManager,
})
serverObj.blockChain.AddTempTxPool(serverObj.tempMemPool)
//===============
serverObj.addrManager = addrmanager.NewAddrManager(cfg.DataDir, common.HashH(common.Uint32ToBytes(activeNetParams.Params.Net))) // use network param Net as key for storage
// Init block template generator
serverObj.blockgen, err = blockchain.NewBlockGenerator(serverObj.memPool, serverObj.blockChain, serverObj.shardToBeaconPool, serverObj.crossShardPool, cPendingTxs, cRemovedTxs)
if err != nil {
return err
}
// Init consensus engine
serverObj.consensusEngine, err = mubft.Engine{}.Init(&mubft.EngineConfig{
CrossShardPool: serverObj.crossShardPool,
ShardToBeaconPool: serverObj.shardToBeaconPool,
ChainParams: serverObj.chainParams,
BlockChain: serverObj.blockChain,
Server: serverObj,
BlockGen: serverObj.blockgen,
NodeMode: cfg.NodeMode,
UserKeySet: serverObj.userKeySet,
PubSubManager: serverObj.pusubManager,
})
if err != nil {
return err
}
// Init Net Sync manager to process messages
serverObj.netSync = &netsync.NetSync{}
serverObj.netSync.Init(&netsync.NetSyncConfig{
BlockChain: serverObj.blockChain,
ChainParam: chainParams,
TxMemPool: serverObj.memPool,
Server: serverObj,
Consensus: serverObj.consensusEngine,
ShardToBeaconPool: serverObj.shardToBeaconPool,
CrossShardPool: serverObj.crossShardPool,
PubSubManager: serverObj.pusubManager,
RelayShard: relayShards,
RoleInCommittees: -1,
})
// Create a connection manager.
var listenPeer *peer.Peer
if !cfg.DisableListen {
var err error
// this is initializing our listening peer
listenPeer, err = serverObj.InitListenerPeer(serverObj.addrManager, listenAddrs)
if err != nil {
Logger.log.Error(err)
return err
}
}
isRelayNodeForConsensus := cfg.Accelerator
if isRelayNodeForConsensus {
cfg.MaxPeersSameShard = 9999
cfg.MaxPeersOtherShard = 9999
cfg.MaxPeersOther = 9999
cfg.MaxPeersNoShard = 0
cfg.MaxPeersBeacon = 9999
}
connManager := connmanager.New(&connmanager.Config{
OnInboundAccept: serverObj.InboundPeerConnected,
OnOutboundConnection: serverObj.OutboundPeerConnected,
ListenerPeer: listenPeer,
DiscoverPeers: cfg.DiscoverPeers,
DiscoverPeersAddress: cfg.DiscoverPeersAddress,
ExternalAddress: cfg.ExternalAddress,
// config for connection of shard
MaxPeersSameShard: cfg.MaxPeersSameShard,
MaxPeersOtherShard: cfg.MaxPeersOtherShard,
MaxPeersOther: cfg.MaxPeersOther,
MaxPeersNoShard: cfg.MaxPeersNoShard,
MaxPeersBeacon: cfg.MaxPeersBeacon,
})
serverObj.connManager = connManager
// Start up persistent peers.
permanentPeers := cfg.ConnectPeers
if len(permanentPeers) == 0 {
permanentPeers = cfg.AddPeers
}
for _, addr := range permanentPeers {
go serverObj.connManager.Connect(addr, "", nil)
}
if !cfg.DisableRPC {
// Setup listeners for the configured RPC listen addresses and
// TLS settings.
fmt.Println("settingup RPCListeners")
httpListeners, err := serverObj.setupRPCListeners()
wsListeners, err := serverObj.setupRPCWsListeners()
if err != nil {
return err
}
if len(httpListeners) == 0 && len(wsListeners) == 0 {
return errors.New("RPCS: No valid listen address")
}
miningPubkeyB58 := ""
if serverObj.userKeySet != nil {
miningPubkeyB58 = serverObj.userKeySet.GetPublicKeyInBase58CheckEncode()
}
rpcConfig := rpcserver.RpcServerConfig{
HttpListenters: httpListeners,
WsListenters: wsListeners,
RPCQuirks: cfg.RPCQuirks,
RPCMaxClients: cfg.RPCMaxClients,
RPCMaxWSClients: cfg.RPCMaxWSClients,
ChainParams: chainParams,
BlockChain: serverObj.blockChain,
TxMemPool: serverObj.memPool,
Server: serverObj,
Wallet: serverObj.wallet,
ConnMgr: serverObj.connManager,
AddrMgr: serverObj.addrManager,
RPCUser: cfg.RPCUser,
RPCPass: cfg.RPCPass,
RPCLimitUser: cfg.RPCLimitUser,
RPCLimitPass: cfg.RPCLimitPass,
DisableAuth: cfg.RPCDisableAuth,
NodeMode: cfg.NodeMode,
FeeEstimator: serverObj.feeEstimator,
ProtocolVersion: serverObj.protocolVersion,
Database: &serverObj.dataBase,
MiningPubKeyB58: miningPubkeyB58,
NetSync: serverObj.netSync,
PubSubManager: pubsubManager,
}
serverObj.rpcServer = &rpcserver.RpcServer{}
serverObj.rpcServer.Init(&rpcConfig)
// init rpc client instance and stick to Blockchain object
// in order to communicate to external services (ex. eth light node)
serverObj.blockgen.SetRPCClientChain(rpccaller.NewRPCClient())
// Signal process shutdown when the RPC server requests it.
go func() {
<-serverObj.rpcServer.RequestedProcessShutdown()
shutdownRequestChannel <- struct{}{}
}()
}
//Init Metric Tool
if cfg.MetricUrl != "" {
grafana := metrics.NewGrafana(cfg.MetricUrl)
metrics.InitMetricTool(&grafana)
}
return nil
}
/*
// InboundPeerConnected is invoked by the connection manager when a new
// inbound connection is established.
*/
func (serverObj *Server) InboundPeerConnected(peerConn *peer.PeerConn) {
Logger.log.Debug("inbound connected")
}
/*
// outboundPeerConnected is invoked by the connection manager when a new
// outbound connection is established. It initializes a new outbound server
// peer instance, associates it with the relevant state such as the connection
// request instance and the connection itserverObj, and finally notifies the address
// manager of the attempt.
*/
func (serverObj *Server) OutboundPeerConnected(peerConn *peer.PeerConn) {
Logger.log.Debug("Outbound PEER connected with PEER Id - " + peerConn.GetRemotePeerID().Pretty())
err := serverObj.PushVersionMessage(peerConn)
if err != nil {
Logger.log.Error(err)
}
}
/*
// WaitForShutdown blocks until the main listener and peer handlers are stopped.
*/
func (serverObj *Server) WaitForShutdown() {
serverObj.waitGroup.Wait()
}
/*
// Stop gracefully shuts down the connection manager.
*/
func (serverObj *Server) Stop() error {
// stop connManager
errStopConnManager := serverObj.connManager.Stop()
if errStopConnManager != nil {
Logger.log.Error(errStopConnManager)
}
// Shutdown the RPC server if it's not disabled.
if !cfg.DisableRPC && serverObj.rpcServer != nil {
serverObj.rpcServer.Stop()
}
// Save fee estimator in the db
for shardID, feeEstimator := range serverObj.feeEstimator {
feeEstimatorData := feeEstimator.Save()
if len(feeEstimatorData) > 0 {
err := serverObj.dataBase.StoreFeeEstimator(feeEstimatorData, shardID)
if err != nil {
Logger.log.Errorf("Can't save fee estimator data on chain #%d: %v", shardID, err)
} else {
Logger.log.Debugf("Save fee estimator data on chain #%d", shardID)
}
}
}
err := serverObj.consensusEngine.Stop()
if err != nil {
Logger.log.Error(err)
}
// Signal the remaining goroutines to cQuit.
close(serverObj.cQuit)
return nil
}
/*
// peerHandler is used to handle peer operations such as adding and removing
// peers to and from the server, banning peers, and broadcasting messages to
// peers. It must be run in a goroutine.
*/
func (serverObj *Server) peerHandler() {
// Start the address manager and sync manager, both of which are needed
// by peers. This is done here since their lifecycle is closely tied
// to this handler and rather than adding more channels to sychronize
// things, it's easier and slightly faster to simply start and stop them
// in this handler.
serverObj.addrManager.Start()
serverObj.netSync.Start()
Logger.log.Debug("Start peer handler")
if len(cfg.ConnectPeers) == 0 {
for _, addr := range serverObj.addrManager.AddressCache() {
go serverObj.connManager.Connect(addr.GetRawAddress(), addr.GetPublicKey(), nil)
}
}
go serverObj.connManager.Start(cfg.DiscoverPeersAddress)
out:
for {
select {
case p := <-serverObj.cNewPeers:
serverObj.handleAddPeerMsg(p)
case <-serverObj.cQuit:
{
break out
}
}
}
serverObj.netSync.Stop()
errStopAddrManager := serverObj.addrManager.Stop()
if errStopAddrManager != nil {
Logger.log.Error(errStopAddrManager)
}
errStopConnManager := serverObj.connManager.Stop()
if errStopAddrManager != nil {
Logger.log.Error(errStopConnManager)
}
}
/*
// Start begins accepting connections from peers.
*/
func (serverObj Server) Start() {
// Already started?
if atomic.AddInt32(&serverObj.started, 1) != 1 {
return
}
Logger.log.Debug("Starting server")
if common.CheckForce {
serverObj.CheckForceUpdateSourceCode()
}
if cfg.TestNet {
Logger.log.Critical("************************" +
"* Testnet is active *" +
"************************")
}
// Server startup time. Used for the uptime command for uptime calculation.
serverObj.startupTime = time.Now().Unix()
// Start the peer handler which in turn starts the address and block
// managers.
serverObj.waitGroup.Add(1)
go serverObj.peerHandler()
if !cfg.DisableRPC && serverObj.rpcServer != nil {
serverObj.waitGroup.Add(1)
// Start the rebroadcastHandler, which ensures user tx received by
// the RPC server are rebroadcast until being included in a block.
//go serverObj.rebroadcastHandler()
serverObj.rpcServer.Start()
}
go serverObj.blockChain.Synker.Start()
if cfg.NodeMode != common.NODEMODE_RELAY {
err := serverObj.consensusEngine.Start()
if err != nil {
Logger.log.Error(err)
go serverObj.Stop()
return
}
serverObj.memPool.IsBlockGenStarted = true
serverObj.blockChain.SetIsBlockGenStarted(true)
for _, shardPool := range serverObj.shardPool {
go shardPool.Start(serverObj.cQuit)
}
go serverObj.beaconPool.Start(serverObj.cQuit)
}
if serverObj.memPool != nil {
err := serverObj.memPool.LoadOrResetDatabaseMempool()
if err != nil {
Logger.log.Error(err)
}
go serverObj.TransactionPoolBroadcastLoop()
go serverObj.memPool.Start(serverObj.cQuit)
}
go serverObj.pusubManager.Start()
}
func (serverObj *Server) TransactionPoolBroadcastLoop() {
<-time.Tick(serverObj.memPool.ScanTime)
serverObj.memPool.LockPool()
txDescs := serverObj.memPool.GetPool()
for _, txDesc := range txDescs {
<-time.Tick(50 * time.Millisecond)
if !txDesc.IsFowardMessage {
tx := txDesc.Desc.Tx
switch tx.GetType() {
case common.TxNormalType:
{
txMsg, err := wire.MakeEmptyMessage(wire.CmdTx)
if err != nil {
continue
}
normalTx := tx.(*transaction.Tx)
txMsg.(*wire.MessageTx).Transaction = normalTx
err = serverObj.PushMessageToAll(txMsg)
if err == nil {
serverObj.memPool.MarkForwardedTransaction(*tx.Hash())
}
}
case common.TxCustomTokenType:
{
txMsg, err := wire.MakeEmptyMessage(wire.CmdCustomToken)
if err != nil {
continue
}
customTokenTx := tx.(*transaction.TxCustomToken)
txMsg.(*wire.MessageTxToken).Transaction = customTokenTx
err = serverObj.PushMessageToAll(txMsg)
if err == nil {
serverObj.memPool.MarkForwardedTransaction(*tx.Hash())
}
}
case common.TxCustomTokenPrivacyType:
{
txMsg, err := wire.MakeEmptyMessage(wire.CmdPrivacyCustomToken)
if err != nil {
continue
}
customPrivacyTokenTx := tx.(*transaction.TxCustomTokenPrivacy)
txMsg.(*wire.MessageTxPrivacyToken).Transaction = customPrivacyTokenTx
err = serverObj.PushMessageToAll(txMsg)
if err == nil {
serverObj.memPool.MarkForwardedTransaction(*tx.Hash())
}
}
}
}
}
serverObj.memPool.UnlockPool()
}
// CheckForceUpdateSourceCode - loop to check current version with update version is equal
// Force source code to be updated and remove data
func (serverObject Server) CheckForceUpdateSourceCode() {
go func() {
ctx := context.Background()
myClient, err := storage.NewClient(ctx, option.WithoutAuthentication())
if err != nil {
Logger.log.Error(err)
}
for {
reader, err := myClient.Bucket("incognito").Object("version-chain.json").NewReader(ctx)
if err != nil {
Logger.log.Error(err)
time.Sleep(10 * time.Second)
continue
}
defer reader.Close()
type VersionChain struct {
Version string `json:"Version"`
Note string `json:"Note"`
RemoveData bool `json:"RemoveData"`
}
versionChain := VersionChain{}
currentVersion := version()
body, err := ioutil.ReadAll(reader)
if err != nil {
Logger.log.Error(err)
time.Sleep(10 * time.Second)
continue
}
err = json.Unmarshal(body, &versionChain)
if err != nil {
Logger.log.Error(err)
time.Sleep(10 * time.Second)
continue
}
force := currentVersion != versionChain.Version
if force {
Logger.log.Error("\n*********************************************************************************\n" +
versionChain.Note +
"\n*********************************************************************************\n")
Logger.log.Error("\n*********************************************************************************\n You're running version: " +
currentVersion +
"\n*********************************************************************************\n")
Logger.log.Error("\n*********************************************************************************\n" +
versionChain.Note +
"\n*********************************************************************************\n")
Logger.log.Error("\n*********************************************************************************\n New version: " +
versionChain.Version +
"\n*********************************************************************************\n")
Logger.log.Error("\n*********************************************************************************\n" +
"We're exited because having a force update on this souce code." +
"\nPlease Update source code at https://github.com/incognitochain/incognito-chain" +
"\n*********************************************************************************\n")
if versionChain.RemoveData {
serverObject.Stop()
os.RemoveAll(cfg.DataDir)
}
os.Exit(common.ExitCodeForceUpdate)
}
time.Sleep(10 * time.Second)
}
}()
}
/*
// initListeners initializes the configured net listeners and adds any bound
// addresses to the address manager. Returns the listeners and a NAT interface,
// which is non-nil if UPnP is in use.
*/
func (serverObj *Server) InitListenerPeer(amgr *addrmanager.AddrManager, listenAddrs string) (*peer.Peer, error) {
netAddr, err := common.ParseListener(listenAddrs, "ip")
if err != nil {
return nil, err
}
// use keycache to save listener peer into file, this will make peer id of listener not change after turn off node
kc := KeyCache{}
kc.Load(filepath.Join(cfg.DataDir, "listenerpeer.json"))
// load seed of libp2p from keycache file, if not exist -> save a new data into keycache file
seed := int64(0)
seedC, _ := strconv.ParseInt(os.Getenv("LISTENER_PEER_SEED"), 10, 64)
if seedC == 0 {
key := "LISTENER_PEER_SEED"
seedT := kc.Get(key)
if seedT == nil {
seed = common.RandInt64()
kc.Set(key, seed)
} else {
seed = int64(seedT.(float64))
}
} else {
seed = seedC
}
peer := peer.Peer{}
peer.SetSeed(seed)
peer.SetListeningAddress(*netAddr)
peer.SetPeerConns(nil)
peer.SetPendingPeers(nil)
peer.SetConfig(*serverObj.NewPeerConfig())
err = peer.Init()
if err != nil {
return nil, err
}
kc.Save()
return &peer, nil
}
/*
// newPeerConfig returns the configuration for the listening RemotePeer.
*/
func (serverObj *Server) NewPeerConfig() *peer.Config {
KeySetUser := serverObj.userKeySet
config := &peer.Config{
MessageListeners: peer.MessageListeners{
OnBlockShard: serverObj.OnBlockShard,
OnBlockBeacon: serverObj.OnBlockBeacon,
OnCrossShard: serverObj.OnCrossShard,
OnShardToBeacon: serverObj.OnShardToBeacon,
OnTx: serverObj.OnTx,
OnTxToken: serverObj.OnTxToken,
OnTxPrivacyToken: serverObj.OnTxPrivacyToken,
OnVersion: serverObj.OnVersion,
OnGetBlockBeacon: serverObj.OnGetBlockBeacon,
OnGetBlockShard: serverObj.OnGetBlockShard,
OnGetCrossShard: serverObj.OnGetCrossShard,
OnGetShardToBeacon: serverObj.OnGetShardToBeacon,
OnVerAck: serverObj.OnVerAck,
OnGetAddr: serverObj.OnGetAddr,
OnAddr: serverObj.OnAddr,
//mubft
OnBFTMsg: serverObj.OnBFTMsg,
// OnInvalidBlock: serverObj.OnInvalidBlock,
OnPeerState: serverObj.OnPeerState,
//
PushRawBytesToShard: serverObj.PushRawBytesToShard,
PushRawBytesToBeacon: serverObj.PushRawBytesToBeacon,
GetCurrentRoleShard: serverObj.GetCurrentRoleShard,
},
MaxInPeers: cfg.MaxInPeers,
MaxPeers: cfg.MaxPeers,
MaxOutPeers: cfg.MaxOutPeers,
}
if KeySetUser != nil && len(KeySetUser.PrivateKey) != 0 {
config.UserKeySet = KeySetUser
}
return config
}
func (serverObj *Server) GetUserKeySet() *incognitokey.KeySet {
k, _ := cfg.GetUserKeySet()
return k
}
// OnBlock is invoked when a peer receives a block message. It
// blocks until the coin block has been fully processed.
func (serverObj *Server) OnBlockShard(p *peer.PeerConn,
msg *wire.MessageBlockShard) {
Logger.log.Debug("Receive a new blockshard START")
var txProcessed chan struct{}
serverObj.netSync.QueueBlock(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a new blockshard END")
}
func (serverObj *Server) OnBlockBeacon(p *peer.PeerConn,
msg *wire.MessageBlockBeacon) {
Logger.log.Debug("Receive a new blockbeacon START")
var txProcessed chan struct{}
serverObj.netSync.QueueBlock(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a new blockbeacon END")
}
func (serverObj *Server) OnCrossShard(p *peer.PeerConn,
msg *wire.MessageCrossShard) {
Logger.log.Debug("Receive a new crossshard START")
var txProcessed chan struct{}
serverObj.netSync.QueueBlock(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a new crossshard END")
}
func (serverObj *Server) OnShardToBeacon(p *peer.PeerConn,
msg *wire.MessageShardToBeacon) {
Logger.log.Debug("Receive a new shardToBeacon START")
var txProcessed chan struct{}
serverObj.netSync.QueueBlock(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a new shardToBeacon END")
}
func (serverObj *Server) OnGetBlockBeacon(_ *peer.PeerConn, msg *wire.MessageGetBlockBeacon) {
Logger.log.Debug("Receive a " + msg.MessageType() + " message START")
var txProcessed chan struct{}
serverObj.netSync.QueueGetBlockBeacon(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a " + msg.MessageType() + " message END")
}
func (serverObj *Server) OnGetBlockShard(_ *peer.PeerConn, msg *wire.MessageGetBlockShard) {
Logger.log.Debug("Receive a " + msg.MessageType() + " message START")
var txProcessed chan struct{}
serverObj.netSync.QueueGetBlockShard(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a " + msg.MessageType() + " message END")
}
func (serverObj *Server) OnGetCrossShard(_ *peer.PeerConn, msg *wire.MessageGetCrossShard) {
Logger.log.Debug("Receive a getcrossshard START")
var txProcessed chan struct{}
serverObj.netSync.QueueMessage(nil, msg, txProcessed)
Logger.log.Debug("Receive a getcrossshard END")
}
func (serverObj *Server) OnGetShardToBeacon(_ *peer.PeerConn, msg *wire.MessageGetShardToBeacon) {
Logger.log.Debug("Receive a getshardtobeacon START")
var txProcessed chan struct{}
serverObj.netSync.QueueMessage(nil, msg, txProcessed)
Logger.log.Debug("Receive a getshardtobeacon END")
}
// OnTx is invoked when a peer receives a tx message. It blocks
// until the transaction has been fully processed. Unlock the block
// handler this does not serialize all transactions through a single thread
// transactions don't rely on the previous one in a linear fashion like blocks.
func (serverObj *Server) OnTx(peer *peer.PeerConn, msg *wire.MessageTx) {
Logger.log.Debug("Receive a new transaction START")
var txProcessed chan struct{}
serverObj.netSync.QueueTx(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a new transaction END")
}
func (serverObj *Server) OnTxToken(peer *peer.PeerConn, msg *wire.MessageTxToken) {
Logger.log.Debug("Receive a new transaction(normal token) START")
var txProcessed chan struct{}
serverObj.netSync.QueueTxToken(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a new transaction(normal token) END")
}
func (serverObj *Server) OnTxPrivacyToken(peer *peer.PeerConn, msg *wire.MessageTxPrivacyToken) {
Logger.log.Debug("Receive a new transaction(privacy token) START")
var txProcessed chan struct{}
serverObj.netSync.QueueTxPrivacyToken(nil, msg, txProcessed)
//<-txProcessed
Logger.log.Debug("Receive a new transaction(privacy token) END")
}