-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
1356 lines (1284 loc) · 46.6 KB
/
main.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
// ZooBC Copyright (C) 2020 Quasisoft Limited - Hong Kong
// This file is part of ZooBC <https://github.com/zoobc/zoobc-core>
//
// ZooBC is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ZooBC is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ZooBC. If not, see <http://www.gnu.org/licenses/>.
//
// Additional Permission Under GNU GPL Version 3 section 7.
// As the special exception permitted under Section 7b, c and e,
// in respect with the Author’s copyright, please refer to this section:
//
// 1. You are free to convey this Program according to GNU GPL Version 3,
// as long as you respect and comply with the Author’s copyright by
// showing in its user interface an Appropriate Notice that the derivate
// program and its source code are “powered by ZooBC”.
// This is an acknowledgement for the copyright holder, ZooBC,
// as the implementation of appreciation of the exclusive right of the
// creator and to avoid any circumvention on the rights under trademark
// law for use of some trade names, trademarks, or service marks.
//
// 2. Complying to the GNU GPL Version 3, you may distribute
// the program without any permission from the Author.
// However a prior notification to the authors will be appreciated.
//
// ZooBC is architected by Roberto Capodieci & Barton Johnston
// contact us at roberto.capodieci[at]blockchainzoo.com
// and barton.johnston[at]blockchainzoo.com
//
// Core developers that contributed to the current implementation of the
// software are:
// Ahmad Ali Abdilah ahmad.abdilah[at]blockchainzoo.com
// Allan Bintoro allan.bintoro[at]blockchainzoo.com
// Andy Herman
// Gede Sukra
// Ketut Ariasa
// Nawi Kartini nawi.kartini[at]blockchainzoo.com
// Stefano Galassi stefano.galassi[at]blockchainzoo.com
//
// IMPORTANT: The above copyright notice and this permission notice
// shall be included in all copies or substantial portions of the Software.
package main
import (
"crypto/sha256"
"database/sql"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"path/filepath"
"runtime"
"sort"
"syscall"
"time"
"github.com/zoobc/zoobc-core/common/queue"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/takama/daemon"
"github.com/ugorji/go/codec"
"github.com/zoobc/zoobc-core/api"
"github.com/zoobc/zoobc-core/common/accounttype"
"github.com/zoobc/zoobc-core/common/auth"
"github.com/zoobc/zoobc-core/common/blocker"
"github.com/zoobc/zoobc-core/common/chaintype"
"github.com/zoobc/zoobc-core/common/constant"
"github.com/zoobc/zoobc-core/common/crypto"
"github.com/zoobc/zoobc-core/common/database"
"github.com/zoobc/zoobc-core/common/fee"
"github.com/zoobc/zoobc-core/common/feedbacksystem"
"github.com/zoobc/zoobc-core/common/model"
"github.com/zoobc/zoobc-core/common/monitoring"
"github.com/zoobc/zoobc-core/common/query"
"github.com/zoobc/zoobc-core/common/signaturetype"
"github.com/zoobc/zoobc-core/common/storage"
"github.com/zoobc/zoobc-core/common/transaction"
"github.com/zoobc/zoobc-core/common/util"
"github.com/zoobc/zoobc-core/core/blockchainsync"
"github.com/zoobc/zoobc-core/core/scheduler"
"github.com/zoobc/zoobc-core/core/service"
"github.com/zoobc/zoobc-core/core/smith"
blockSmithStrategy "github.com/zoobc/zoobc-core/core/smith/strategy"
coreUtil "github.com/zoobc/zoobc-core/core/util"
"github.com/zoobc/zoobc-core/observer"
"github.com/zoobc/zoobc-core/p2p"
"github.com/zoobc/zoobc-core/p2p/client"
p2pStrategy "github.com/zoobc/zoobc-core/p2p/strategy"
p2pUtil "github.com/zoobc/zoobc-core/p2p/util"
)
var (
config *model.Config
dbInstance *database.SqliteDB
db *sql.DB
nodeShardStorage, mainBlockStateStorage, spineBlockStateStorage storage.CacheStorageInterface
nextNodeAdmissionStorage, mempoolStorage, receiptReminderStorage storage.CacheStorageInterface
mempoolBackupStorage, batchReceiptCacheStorage storage.CacheStorageInterface
activeNodeRegistryCacheStorage, pendingNodeRegistryCacheStorage storage.CacheStorageInterface
nodeAddressInfoStorage storage.CacheStorageInterface
scrambleNodeStorage, mainBlocksStorage, spineBlocksStorage storage.CacheStackStorageInterface
blockStateStorages = make(map[int32]storage.CacheStorageInterface)
snapshotChunkUtil util.ChunkUtilInterface
p2pServiceInstance p2p.Peer2PeerServiceInterface
queryExecutor *query.Executor
observerInstance *observer.Observer
schedulerInstance *util.Scheduler
snapshotSchedulers *scheduler.SnapshotScheduler
blockServices = make(map[int32]service.BlockServiceInterface)
snapshotBlockServices = make(map[int32]service.SnapshotBlockServiceInterface)
mainchainBlockService *service.BlockService
spinePublicKeyService *service.BlockSpinePublicKeyService
mainBlockSnapshotChunkStrategy service.SnapshotChunkStrategyInterface
spinechainBlockService *service.BlockSpineService
fileDownloader p2p.FileDownloaderInterface
mempoolServices = make(map[int32]service.MempoolServiceInterface)
blockIncompleteQueueService service.BlockIncompleteQueueServiceInterface
receiptService service.ReceiptServiceInterface
peerServiceClient client.PeerServiceClientInterface
peerExplorer p2pStrategy.PeerExplorerStrategyInterface
nodeRegistrationService service.NodeRegistrationServiceInterface
nodeAuthValidationService auth.NodeAuthValidationInterface
mainchainProcessor smith.BlockchainProcessorInterface
spinechainProcessor smith.BlockchainProcessorInterface
loggerAPIService, loggerCoreService, loggerP2PService, loggerScheduler *log.Logger
spinechainSynchronizer, mainchainSynchronizer blockchainsync.BlockchainSyncServiceInterface
spineBlockManifestService service.SpineBlockManifestServiceInterface
snapshotService service.SnapshotServiceInterface
transactionUtil transaction.UtilInterface
receiptUtil coreUtil.ReceiptUtilInterface
transactionCoreServiceIns service.TransactionCoreServiceInterface
pendingTransactionServiceIns service.PendingTransactionServiceInterface
fileService service.FileServiceInterface
mainchain = &chaintype.MainChain{}
spinechain = &chaintype.SpineChain{}
blockchainStatusService service.BlockchainStatusServiceInterface
nodeConfigurationService service.NodeConfigurationServiceInterface
nodeAddressInfoService service.NodeAddressInfoServiceInterface
mempoolService service.MempoolServiceInterface
mainchainPublishedReceiptService service.PublishedReceiptServiceInterface
mainchainPublishedReceiptUtil coreUtil.PublishedReceiptUtilInterface
mainchainCoinbaseService service.CoinbaseServiceInterface
mainchainBlocksmithService service.BlocksmithServiceInterface
mainchainParticipationScoreService service.ParticipationScoreServiceInterface
scrambleNodeService service.ScrambleNodeServiceInterface
actionSwitcher transaction.TypeActionSwitcher
feeScaleService fee.FeeScaleServiceInterface
mainchainDownloader, spinechainDownloader blockchainsync.BlockchainDownloadInterface
mainchainForkProcessor, spinechainForkProcessor blockchainsync.ForkingProcessorInterface
cliMonitoring monitoring.CLIMonitoringInteface
feedbackStrategy feedbacksystem.FeedbackStrategyInterface
blocksmithStrategyMain blockSmithStrategy.BlocksmithStrategyInterface
blocksmithStrategySpine blockSmithStrategy.BlocksmithStrategyInterface
priorityPreferenceLock queue.PriorityLock
)
var (
flagConfigPath, flagConfigPostfix, flagResourcePath string
flagDebugMode, flagProfiling, flagUseEnv bool
daemonCommand = &cobra.Command{
Use: "daemon",
Short: "Run node on daemon service, which mean running in the background. Similar to launchd or systemd",
Example: "daemon install | start | stop | remove | status",
SuggestFor: []string{"up", "stats", "delete", "deamon", "demon"},
}
runCommand = &cobra.Command{
Use: "run",
Short: "Run node without daemon.",
}
rootCmd *cobra.Command
)
// goDaemon instance that needed to implement whole method of daemon
type goDaemon struct {
daemon.Daemon
}
// initiateMainInstance initiation all instance that must be needed and exists before running the node
func initiateMainInstance() {
var (
err error
encodedAccountAddress string
)
// load config for default value to be feed to viper
config, err = util.LoadConfig(flagConfigPath, "config"+flagConfigPostfix, "toml", flagResourcePath)
if err != nil {
if ok := errors.As(err, &viper.ConfigFileNotFoundError{}); ok && flagUseEnv {
config.ConfigFileExist = true
}
} else {
config.ConfigFileExist = true
}
// decode owner account address
if config.OwnerAccountAddressHex != "" {
config.OwnerAccountAddress, err = hex.DecodeString(config.OwnerAccountAddressHex)
if err != nil {
log.Errorf("Invalid OwnerAccountAddress in config. It must be in hex format: %s", err)
os.Exit(1)
}
// double check that the decoded account address is valid
accType, err := accounttype.NewAccountTypeFromAccount(config.OwnerAccountAddress)
if err != nil {
log.Error(err)
os.Exit(1)
}
// TODO: move to crypto package in a function
switch accType.GetTypeInt() {
case 0:
ed25519 := signaturetype.NewEd25519Signature()
encodedAccountAddress, err = ed25519.GetAddressFromPublicKey(accType.GetAccountPrefix(), accType.GetAccountPublicKey())
if err != nil {
log.Error(err)
os.Exit(1)
}
case 1:
bitcoinSignature := signaturetype.NewBitcoinSignature(signaturetype.DefaultBitcoinNetworkParams(), signaturetype.DefaultBitcoinCurve())
encodedAccountAddress, err = bitcoinSignature.GetAddressFromPublicKey(accType.GetAccountPublicKey())
if err != nil {
log.Error(err)
os.Exit(1)
}
case 3:
estoniaEidAccountType := &accounttype.EstoniaEidAccountType{}
estoniaEidAccountType.SetAccountPublicKey(accType.GetAccountPublicKey())
encodedAccountAddress, err = estoniaEidAccountType.GetEncodedAddress()
if err != nil {
log.Error(err)
os.Exit(1)
}
default:
log.Error("Invalid Owner Account Type")
os.Exit(1)
}
config.OwnerEncodedAccountAddress = encodedAccountAddress
config.OwnerAccountAddressTypeInt = accType.GetTypeInt()
}
// early init configuration service
nodeConfigurationService = service.NewNodeConfigurationService(loggerCoreService)
// check and validate configurations
err = util.NewSetupNode(config).CheckConfig()
if err != nil {
log.Errorf("Unknown error occurred - error: %s", err.Error())
os.Exit(1)
}
nodeAdminKeysService := service.NewNodeAdminService(nil, nil, nil, nil,
filepath.Join(config.ResourcePath, config.NodeKeyFileName))
if len(config.NodeKey.Seed) > 0 {
config.NodeKey.PublicKey, err = nodeAdminKeysService.GenerateNodeKey(config.NodeKey.Seed)
if err != nil {
log.Error("Fail to generate node key")
os.Exit(1)
}
} else {
// setup wizard don't set node key, meaning ./resource/node_keys.json exist
nodeKeys, err := nodeAdminKeysService.ParseKeysFile()
if err != nil {
log.Error("existing node keys has wrong format, please fix it or delete it, then re-run the application")
os.Exit(1)
}
config.NodeKey = nodeAdminKeysService.GetLastNodeKey(nodeKeys)
}
knownPeersResult, err := p2pUtil.ParseKnownPeers(config.WellknownPeers)
if err != nil {
log.Errorf("ParseKnownPeers Err: %s", err.Error())
os.Exit(1)
}
nodeConfigurationService.SetHost(p2pUtil.NewHost(config.MyAddress, config.PeerPort, knownPeersResult,
constant.ApplicationVersion, constant.ApplicationCodeName))
nodeConfigurationService.SetIsMyAddressDynamic(config.IsNodeAddressDynamic)
if config.NodeKey.Seed == "" {
log.Error("node seed is empty")
os.Exit(1)
}
nodeConfigurationService.SetNodeSeed(config.NodeKey.Seed)
if config.OwnerAccountAddress == nil {
// todo: andy-shi88 refactor this
signature := crypto.NewSignature()
_, _, _, config.OwnerEncodedAccountAddress, config.OwnerAccountAddress, err = signature.GenerateAccountFromSeed(
&accounttype.ZbcAccountType{},
config.NodeKey.Seed,
true,
)
if err != nil {
log.Error("error generating node owner account")
os.Exit(1)
}
config.OwnerAccountAddressHex = hex.EncodeToString(config.OwnerAccountAddress)
err = util.SaveConfig(config, flagConfigPath)
if err != nil {
log.Error("Fail to save new configuration")
os.Exit(1)
}
}
initLogInstance(fmt.Sprintf("%s/.log", config.ResourcePath))
if config.AntiSpamFilter {
feedbackStrategy = feedbacksystem.NewAntiSpamStrategy(
loggerCoreService,
config.AntiSpamCPULimitPercentage,
config.AntiSpamP2PRequestLimit,
)
} else {
// no filtering: turn antispam filter off
feedbackStrategy = feedbacksystem.NewDummyFeedbackStrategy()
}
cliMonitoring = monitoring.NewCLIMonitoring(config)
monitoring.SetCLIMonitoring(cliMonitoring)
// break
// initialize/open db and queryExecutor
dbInstance = database.NewSqliteDB()
if err = dbInstance.InitializeDB(config.ResourcePath, config.DatabaseFileName); err != nil {
loggerCoreService.Fatal(err)
}
db, err = dbInstance.OpenDB(
config.ResourcePath,
config.DatabaseFileName,
constant.SQLMaxOpenConnetion,
constant.SQLMaxIdleConnections,
constant.SQLMaxConnectionLifetime,
)
if err != nil {
loggerCoreService.Fatal(err)
}
queryExecutor = query.NewQueryExecutor(db, priorityPreferenceLock)
// initialize cache storage
mainBlockStateStorage = storage.NewBlockStateStorage()
spineBlockStateStorage = storage.NewBlockStateStorage()
blockStateStorages[mainchain.GetTypeInt()] = mainBlockStateStorage
blockStateStorages[spinechain.GetTypeInt()] = spineBlockStateStorage
nextNodeAdmissionStorage = storage.NewNodeAdmissionTimestampStorage()
nodeShardStorage = storage.NewNodeShardCacheStorage()
mempoolStorage = storage.NewMempoolStorage()
scrambleNodeStorage = storage.NewScrambleCacheStackStorage()
receiptReminderStorage = storage.NewReceiptReminderStorage()
mempoolBackupStorage = storage.NewMempoolBackupStorage()
batchReceiptCacheStorage = storage.NewReceiptPoolCacheStorage()
nodeAddressInfoStorage = storage.NewNodeAddressInfoStorage()
mainBlocksStorage = storage.NewBlocksStorage(monitoring.TypeMainBlocksCacheStorage)
spineBlocksStorage = storage.NewBlocksStorage(monitoring.TypeSpineBlocksCacheStorage)
// store current active node registry (not in queue)
activeNodeRegistryCacheStorage = storage.NewNodeRegistryCacheStorage(
monitoring.TypeActiveNodeRegistryStorage,
func(registries []storage.NodeRegistry) {
sort.SliceStable(registries, func(i, j int) bool {
// sort by nodeID lowest - highest
return registries[i].Node.GetNodeID() < registries[j].Node.GetNodeID()
})
})
// store pending node registry
pendingNodeRegistryCacheStorage = storage.NewNodeRegistryCacheStorage(
monitoring.TypePendingNodeRegistryStorage,
func(registries []storage.NodeRegistry) {
sort.SliceStable(registries, func(i, j int) bool {
// sort by locked balance highest - lowest
return registries[i].Node.GetLockedBalance() > registries[j].Node.GetLockedBalance()
})
},
)
// initialize services
blockchainStatusService = service.NewBlockchainStatusService(true, loggerCoreService)
feeScaleService = fee.NewFeeScaleService(query.NewFeeScaleQuery(), mainBlockStateStorage, queryExecutor)
transactionUtil = &transaction.Util{
FeeScaleService: feeScaleService,
MempoolCacheStorage: mempoolStorage,
QueryExecutor: queryExecutor,
AccountDatasetQuery: query.NewAccountDatasetsQuery(),
}
// initialize Observer
observerInstance = observer.NewObserver()
schedulerInstance = util.NewScheduler(loggerScheduler)
snapshotChunkUtil = util.NewChunkUtil(sha256.Size, nodeShardStorage, loggerScheduler)
nodeAuthValidationService = auth.NewNodeAuthValidation(
crypto.NewSignature(),
)
txNodeAddressInfoStorage, ok := nodeAddressInfoStorage.(storage.TransactionalCache)
if !ok {
log.Error("FailToCastNodeAddressInfoStorageAsTransactionalCacheInterface")
os.Exit(1)
}
txActiveNodeRegistryStorage, ok := activeNodeRegistryCacheStorage.(storage.TransactionalCache)
if !ok {
log.Error("FailToCastActiveNodeRegistryStorageAsTransactionalCacheInterface")
os.Exit(1)
}
txPendingNodeRegistryStorage, ok := pendingNodeRegistryCacheStorage.(storage.TransactionalCache)
if !ok {
log.Error("FailToCastPendingNodeRegistryStorageAsTransactionalCacheInterface")
os.Exit(1)
}
actionSwitcher = &transaction.TypeSwitcher{
Executor: queryExecutor,
MempoolCacheStorage: mempoolStorage,
NodeAuthValidation: nodeAuthValidationService,
NodeAddressInfoStorage: txNodeAddressInfoStorage,
ActiveNodeRegistryStorage: txActiveNodeRegistryStorage,
PendingNodeRegistryStorage: txPendingNodeRegistryStorage,
FeeScaleService: feeScaleService,
}
nodeAddressInfoService = service.NewNodeAddressInfoService(
queryExecutor,
query.NewNodeAddressInfoQuery(),
query.NewNodeRegistrationQuery(),
query.NewBlockQuery(mainchain),
crypto.NewSignature(),
nodeAddressInfoStorage,
mainBlockStateStorage,
activeNodeRegistryCacheStorage,
mainBlocksStorage,
loggerCoreService,
)
nodeRegistrationService = service.NewNodeRegistrationService(
queryExecutor,
query.NewAccountBalanceQuery(),
query.NewNodeRegistrationQuery(),
query.NewParticipationScoreQuery(),
query.NewNodeAdmissionTimestampQuery(),
loggerCoreService,
blockchainStatusService,
nodeAddressInfoService,
nextNodeAdmissionStorage,
activeNodeRegistryCacheStorage,
pendingNodeRegistryCacheStorage,
)
scrambleNodeService = service.NewScrambleNodeService(
nodeRegistrationService,
nodeAddressInfoService,
queryExecutor,
query.NewBlockQuery(mainchain),
scrambleNodeStorage,
)
receiptUtil = coreUtil.NewReceiptUtil(
nodeAddressInfoStorage,
)
receiptService = service.NewReceiptService(
query.NewBatchReceiptQuery(),
query.NewMerkleTreeQuery(),
query.NewNodeRegistrationQuery(),
query.NewBlockQuery(mainchain),
query.NewTransactionQuery(mainchain),
queryExecutor,
nodeRegistrationService,
crypto.NewSignature(),
query.NewPublishedReceiptQuery(),
receiptUtil,
mainBlockStateStorage,
receiptReminderStorage,
batchReceiptCacheStorage,
scrambleNodeService,
mainBlocksStorage,
util.NewMerkleRoot(),
nodeConfigurationService,
loggerCoreService,
)
spineBlockManifestService = service.NewSpineBlockManifestService(
queryExecutor,
query.NewSpineBlockManifestQuery(),
query.NewBlockQuery(spinechain),
loggerCoreService,
)
fileService = service.NewFileService(
loggerCoreService,
new(codec.CborHandle),
config.SnapshotPath,
)
mainBlockSnapshotChunkStrategy = service.NewSnapshotBasicChunkStrategy(
constant.SnapshotChunkSize,
fileService,
)
blocksmithStrategyMain = blockSmithStrategy.NewBlocksmithStrategyMain(
loggerCoreService,
config.NodeKey.PublicKey,
activeNodeRegistryCacheStorage,
query.NewSkippedBlocksmithQuery(mainchain),
query.NewBlockQuery(mainchain),
mainBlocksStorage,
query.NewSpinePublicKeyQuery(),
queryExecutor,
crypto.NewRandomNumberGenerator(),
mainchain,
)
blocksmithStrategySpine = blockSmithStrategy.NewBlocksmithStrategySpine(
loggerCoreService,
config.NodeKey.PublicKey,
activeNodeRegistryCacheStorage,
query.NewSkippedBlocksmithQuery(spinechain),
query.NewBlockQuery(spinechain),
spineBlocksStorage,
queryExecutor,
crypto.NewRandomNumberGenerator(),
spinechain,
query.NewSpinePublicKeyQuery(),
)
blockIncompleteQueueService = service.NewBlockIncompleteQueueService(
mainchain,
observerInstance,
)
mainchainBlockPool := service.NewBlockPoolService()
mainchainBlocksmithService = service.NewBlocksmithService(
query.NewAccountBalanceQuery(),
query.NewAccountLedgerQuery(),
query.NewNodeRegistrationQuery(),
queryExecutor,
mainchain,
)
mainchainCoinbaseService = service.NewCoinbaseService(
query.NewNodeRegistrationQuery(),
queryExecutor,
mainchain,
crypto.NewRandomNumberGenerator(),
)
mainchainParticipationScoreService = service.NewParticipationScoreService(
query.NewParticipationScoreQuery(),
queryExecutor,
)
mainchainPublishedReceiptUtil = coreUtil.NewPublishedReceiptUtil(
query.NewPublishedReceiptQuery(),
queryExecutor,
)
mainchainPublishedReceiptService = service.NewPublishedReceiptService(
query.NewPublishedReceiptQuery(),
receiptUtil,
mainchainPublishedReceiptUtil,
receiptService,
queryExecutor,
)
transactionCoreServiceIns = service.NewTransactionCoreService(
loggerCoreService,
queryExecutor,
actionSwitcher,
transactionUtil,
query.NewTransactionQuery(mainchain),
query.NewEscrowTransactionQuery(),
query.NewLiquidPaymentTransactionQuery(),
)
pendingTransactionServiceIns = service.NewPendingTransactionService(
loggerCoreService,
queryExecutor,
actionSwitcher,
transactionUtil,
query.NewTransactionQuery(mainchain),
query.NewPendingTransactionQuery(),
)
mempoolService = service.NewMempoolService(
transactionUtil,
mainchain,
queryExecutor,
query.NewMempoolQuery(mainchain),
query.NewMerkleTreeQuery(),
actionSwitcher,
query.NewAccountBalanceQuery(),
query.NewTransactionQuery(mainchain),
crypto.NewSignature(),
observerInstance,
loggerCoreService,
receiptUtil,
receiptService,
transactionCoreServiceIns,
mainBlocksStorage,
mempoolStorage,
mempoolBackupStorage,
)
mainchainBlockService = service.NewBlockMainService(
mainchain,
queryExecutor,
query.NewBlockQuery(mainchain),
query.NewMempoolQuery(mainchain),
query.NewTransactionQuery(mainchain),
query.NewSkippedBlocksmithQuery(mainchain),
crypto.NewSignature(),
mempoolService,
receiptService,
nodeRegistrationService,
nodeAddressInfoService,
actionSwitcher,
query.NewAccountBalanceQuery(),
query.NewParticipationScoreQuery(),
query.NewNodeRegistrationQuery(),
query.NewFeeVoteRevealVoteQuery(),
observerInstance,
blocksmithStrategyMain,
loggerCoreService,
query.NewAccountLedgerQuery(),
blockIncompleteQueueService,
transactionUtil, receiptUtil,
mainchainPublishedReceiptUtil,
transactionCoreServiceIns,
pendingTransactionServiceIns,
mainchainBlockPool,
mainchainBlocksmithService,
mainchainCoinbaseService,
mainchainParticipationScoreService,
mainchainPublishedReceiptService,
feeScaleService,
query.GetPruneQuery(mainchain),
mainBlockStateStorage,
mainBlocksStorage,
blockchainStatusService,
scrambleNodeService,
)
snapshotBlockServices[mainchain.GetTypeInt()] = service.NewSnapshotMainBlockService(
config.SnapshotPath,
queryExecutor,
loggerCoreService,
mainBlockSnapshotChunkStrategy,
query.NewAccountBalanceQuery(),
query.NewNodeRegistrationQuery(),
query.NewParticipationScoreQuery(),
query.NewAccountDatasetsQuery(),
query.NewEscrowTransactionQuery(),
query.NewPublishedReceiptQuery(),
query.NewPendingTransactionQuery(),
query.NewPendingSignatureQuery(),
query.NewMultisignatureInfoQuery(),
query.NewMultiSignatureParticipantQuery(),
query.NewSkippedBlocksmithQuery(mainchain),
query.NewFeeScaleQuery(),
query.NewFeeVoteCommitmentVoteQuery(),
query.NewFeeVoteRevealVoteQuery(),
query.NewLiquidPaymentTransactionQuery(),
query.NewNodeAdmissionTimestampQuery(),
query.NewBlockQuery(mainchain),
query.GetSnapshotQuery(mainchain),
query.GetBlocksmithSafeQuery(mainchain),
query.GetDerivedQuery(mainchain),
transactionUtil,
actionSwitcher,
mainchainBlockService,
nodeRegistrationService,
scrambleNodeService,
)
spinePublicKeyService = service.NewBlockSpinePublicKeyService(
crypto.NewSignature(),
queryExecutor,
query.NewNodeRegistrationQuery(),
query.NewSpinePublicKeyQuery(),
loggerCoreService,
)
snapshotService = service.NewSnapshotService(
spineBlockManifestService,
spinePublicKeyService,
blockchainStatusService,
snapshotBlockServices,
snapshotChunkUtil,
loggerCoreService,
)
spinechainBlocksmithService := service.NewBlocksmithService(
query.NewAccountBalanceQuery(),
query.NewAccountLedgerQuery(),
query.NewNodeRegistrationQuery(),
queryExecutor,
spinechain,
)
initP2pInstance()
spinechainBlockService = service.NewBlockSpineService(
spinechain,
queryExecutor,
query.NewBlockQuery(spinechain),
query.NewSkippedBlocksmithQuery(spinechain),
crypto.NewSignature(),
observerInstance,
blocksmithStrategySpine,
loggerCoreService,
query.NewSpineBlockManifestQuery(),
spinechainBlocksmithService,
snapshotBlockServices[mainchain.GetTypeInt()],
spineBlockStateStorage,
blockchainStatusService,
spinePublicKeyService,
mainchainBlockService,
spineBlocksStorage,
)
/*
Snapshot Scheduler initiate
*/
snapshotSchedulers = scheduler.NewSnapshotScheduler(
spineBlockManifestService,
fileService,
snapshotChunkUtil,
nodeShardStorage,
mainBlockStateStorage,
blockServices[0],
&service.BlockSpinePublicKeyService{
Signature: crypto.NewSignature(),
QueryExecutor: queryExecutor,
NodeRegistrationQuery: query.NewNodeRegistrationQuery(),
SpinePublicKeyQuery: query.NewSpinePublicKeyQuery(),
Logger: loggerCoreService,
},
nodeConfigurationService,
fileDownloader,
)
// assign chain services to the map
mempoolServices[mainchain.GetTypeInt()] = mempoolService
blockServices[mainchain.GetTypeInt()] = mainchainBlockService
blockServices[spinechain.GetTypeInt()] = spinechainBlockService
// register event listeners
initObserverListeners()
}
func initLogInstance(logPath string) {
var (
err error
logLevels = viper.GetStringSlice("logLevels")
t = time.Now().Format("01-02-2006_")
)
if loggerAPIService, err = util.InitLogger(logPath, t+"APIdebug.log", logLevels, config.LogOnCli); err != nil {
panic(err)
}
if loggerCoreService, err = util.InitLogger(logPath, t+"Coredebug.log", logLevels, config.LogOnCli); err != nil {
panic(err)
}
if loggerP2PService, err = util.InitLogger(logPath, t+"P2Pdebug.log", logLevels, config.LogOnCli); err != nil {
panic(err)
}
if loggerScheduler, err = util.InitLogger(logPath, t+"Scheduler.log", logLevels, config.LogOnCli); err != nil {
panic(err)
}
}
func initP2pInstance() {
// initialize peer client service
peerServiceClient = client.NewPeerServiceClient(
queryExecutor, query.NewBatchReceiptQuery(),
config.NodeKey.PublicKey,
nodeRegistrationService,
query.NewMerkleTreeQuery(),
receiptService,
nodeConfigurationService,
nodeAuthValidationService,
feedbackStrategy,
loggerP2PService,
)
// peer discovery strategy
peerExplorer = p2pStrategy.NewPriorityStrategy(
peerServiceClient,
nodeRegistrationService,
nodeAddressInfoService,
mainchainBlockService,
loggerP2PService,
p2pStrategy.NewPeerStrategyHelper(),
nodeConfigurationService,
blockchainStatusService,
crypto.NewSignature(),
scrambleNodeService,
)
p2pServiceInstance, _ = p2p.NewP2PService(
peerServiceClient,
peerExplorer,
loggerP2PService,
transactionUtil,
fileService,
nodeRegistrationService,
nodeConfigurationService,
feedbackStrategy,
)
fileDownloader = p2p.NewFileDownloader(
p2pServiceInstance,
fileService,
blockchainStatusService,
spinePublicKeyService,
snapshotChunkUtil,
loggerP2PService,
)
}
func initObserverListeners() {
// init observer listeners
// broadcast block will be different than other listener implementation, since there are few exception condition
observerInstance.AddListener(observer.BroadcastBlock, p2pServiceInstance.SendBlockListener())
observerInstance.AddListener(observer.TransactionAdded, p2pServiceInstance.SendTransactionListener())
// only smithing nodes generate snapshots
if config.Smithing {
observerInstance.AddListener(observer.BlockPushed, snapshotService.StartSnapshotListener())
observerInstance.AddListener(observer.BlockPushed, batchReceiptCacheStorage.CacheRegularCleaningListener())
observerInstance.AddListener(observer.BlockPushed, receiptService.GenerateReceiptsMerkleRootListener())
}
observerInstance.AddListener(observer.BlockRequestTransactions, p2pServiceInstance.RequestBlockTransactionsListener())
observerInstance.AddListener(observer.ReceivedBlockTransactionsValidated, mainchainBlockService.ReceivedValidatedBlockTransactionsListener())
observerInstance.AddListener(observer.BlockTransactionsRequested, mainchainBlockService.BlockTransactionsRequestedListener())
observerInstance.AddListener(observer.SendBlockTransactions, p2pServiceInstance.SendBlockTransactionsListener())
}
func startServices() {
p2pServiceInstance.StartP2P(
config.MyAddress,
config.OwnerAccountAddress,
config.PeerPort,
config.NodeKey.Seed,
queryExecutor,
blockServices,
mempoolServices,
fileService,
nodeRegistrationService,
nodeConfigurationService,
nodeAddressInfoService,
observerInstance,
feedbackStrategy,
scrambleNodeStorage,
)
api.Start(
queryExecutor,
p2pServiceInstance,
blockServices,
nodeRegistrationService,
nodeAddressInfoService,
mempoolService,
scrambleNodeService,
transactionUtil,
actionSwitcher,
blockStateStorages,
config.RPCAPIPort,
config.HTTPAPIPort,
config.OwnerAccountAddress,
filepath.Join(config.ResourcePath, config.NodeKeyFileName),
loggerAPIService,
flagDebugMode,
config.APICertFile,
config.APIKeyFile,
config.MaxAPIRequestPerSecond,
config.NodeKey.PublicKey,
feedbackStrategy,
)
}
func startNodeMonitoring() {
log.Infof("starting node monitoring at port:%d...", config.MonitoringPort)
monitoring.SetMonitoringActive(true)
monitoring.SetNodePublicKey(config.NodeKey.PublicKey)
go func() {
mux := http.NewServeMux()
mux.Handle("/metrics", monitoring.Handler())
err := http.ListenAndServe(fmt.Sprintf(":%d", config.MonitoringPort), mux)
if err != nil {
panic(fmt.Sprintf("failed to start monitoring service: %s", err))
}
}()
// populate node address info counter when node starts
if nodeCount, err := nodeAddressInfoService.CountRegistredNodeAddressWithAddressInfo(); err == nil {
monitoring.SetNodeAddressInfoCount(nodeCount)
}
if cna, err := nodeAddressInfoService.CountNodesAddressByStatus(); err == nil {
for status, counter := range cna {
monitoring.SetNodeAddressStatusCount(counter, status)
}
}
}
func startMainchain() {
var (
lastBlockAtStart *model.Block
err error
sleepPeriod = constant.MainChainSmithIdlePeriod
)
monitoring.SetBlockchainStatus(mainchain, constant.BlockchainStatusIdle)
exist, errGenesis := mainchainBlockService.CheckGenesis()
if errGenesis != nil {
loggerCoreService.Fatal(errGenesis)
os.Exit(1)
}
if !exist { // Add genesis if not exist
// genesis account will be inserted in the very beginning
if err = service.AddGenesisAccount(queryExecutor); err != nil {
loggerCoreService.Fatal("Fail to add genesis account")
os.Exit(1)
}
// genesis next node admission timestamp will be inserted in the very beginning
if err = service.AddGenesisNextNodeAdmission(
queryExecutor,
mainchain.GetGenesisBlockTimestamp(),
nextNodeAdmissionStorage,
); err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
if err = mainchainBlockService.AddGenesis(); err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
}
// set all needed cache
err = mainchainBlockService.UpdateLastBlockCache(nil)
if err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
err = mainchainBlockService.InitializeBlocksCache()
if err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
err = nodeRegistrationService.UpdateNextNodeAdmissionCache(nil)
if err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
err = nodeAddressInfoService.ClearUpdateNodeAddressInfoCache()
if err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
lastBlockAtStart, err = mainchainBlockService.GetLastBlock()
if err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
err = mempoolService.InitMempoolTransaction()
if err != nil {
loggerCoreService.Fatal(err)
os.Exit(1)
}
monitoring.SetLastBlock(mainchain, lastBlockAtStart)
// TODO: Check computer/node local time. Comparing with last block timestamp
// initialize node registry cache
err = nodeRegistrationService.InitializeCache()
if err != nil {
loggerCoreService.Fatalf("InitializeNodeRegistryCacheFail - %v", err)
os.Exit(1)
}
// initialize scrambled nodes
err = scrambleNodeService.InitializeScrambleCache(lastBlockAtStart.GetHeight())
if err != nil {
loggerCoreService.Fatalf("InitializeScrambleNodeFail - %v", err)
os.Exit(1)
}
err = receiptService.Initialize()
if err != nil {
// error when initializing last merkle root
loggerCoreService.Fatalf("Fail to read last receipt merkle root: %v", err)
os.Exit(0)
}
if len(config.NodeKey.Seed) > 0 && config.Smithing {
node, err := nodeRegistrationService.GetNodeRegistrationByNodePublicKey(config.NodeKey.PublicKey)
if err != nil {
// no nodes registered with current node public key, only warn the user but we keep running smithing goroutine
// so it immediately start when register+admitted to the registry
loggerCoreService.Error(
"Current node is not in node registry and won't be able to smith until registered!",
)
}
// register node config public key, so node registration service can detect if node has been admitted
nodeRegistrationService.SetCurrentNodePublicKey(config.NodeKey.PublicKey)
// default to isBlocksmith=true
blockchainStatusService.SetIsBlocksmith(true)
mainchainProcessor = smith.NewBlockchainProcessor(
mainchainBlockService.GetChainType(),
model.NewBlocksmith(config.NodeKey.Seed, config.NodeKey.PublicKey, node.GetNodeID()),
mainchainBlockService,
loggerCoreService,
blockchainStatusService,
nodeRegistrationService,
blocksmithStrategyMain,