-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
957 lines (828 loc) · 28.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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package node defines the concept of a Bee node
// by bootstrapping and injecting all necessary
// dependencies.
package node
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"io"
"log"
"math/big"
"net"
"net/http"
"os"
"path/filepath"
"sync"
"syscall"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/hashicorp/go-multierror"
ma "github.com/multiformats/go-multiaddr"
"github.com/newswarm-lab/new-bee/pkg/accounting"
"github.com/newswarm-lab/new-bee/pkg/addressbook"
"github.com/newswarm-lab/new-bee/pkg/api"
"github.com/newswarm-lab/new-bee/pkg/bonus"
"github.com/newswarm-lab/new-bee/pkg/config"
"github.com/newswarm-lab/new-bee/pkg/crypto"
"github.com/newswarm-lab/new-bee/pkg/debugapi"
"github.com/newswarm-lab/new-bee/pkg/feeds/factory"
"github.com/newswarm-lab/new-bee/pkg/hive"
"github.com/newswarm-lab/new-bee/pkg/localstore"
"github.com/newswarm-lab/new-bee/pkg/logging"
"github.com/newswarm-lab/new-bee/pkg/metrics"
"github.com/newswarm-lab/new-bee/pkg/netstore"
"github.com/newswarm-lab/new-bee/pkg/p2p"
"github.com/newswarm-lab/new-bee/pkg/p2p/libp2p"
"github.com/newswarm-lab/new-bee/pkg/pingpong"
"github.com/newswarm-lab/new-bee/pkg/pinning"
"github.com/newswarm-lab/new-bee/pkg/postage"
"github.com/newswarm-lab/new-bee/pkg/postage/batchservice"
"github.com/newswarm-lab/new-bee/pkg/postage/batchstore"
"github.com/newswarm-lab/new-bee/pkg/postage/listener"
"github.com/newswarm-lab/new-bee/pkg/postage/postagecontract"
"github.com/newswarm-lab/new-bee/pkg/pricer"
"github.com/newswarm-lab/new-bee/pkg/pricing"
"github.com/newswarm-lab/new-bee/pkg/pss"
"github.com/newswarm-lab/new-bee/pkg/puller"
"github.com/newswarm-lab/new-bee/pkg/pullsync"
"github.com/newswarm-lab/new-bee/pkg/pullsync/pullstorage"
"github.com/newswarm-lab/new-bee/pkg/pusher"
"github.com/newswarm-lab/new-bee/pkg/pushsync"
"github.com/newswarm-lab/new-bee/pkg/recovery"
"github.com/newswarm-lab/new-bee/pkg/resolver/multiresolver"
"github.com/newswarm-lab/new-bee/pkg/retrieval"
"github.com/newswarm-lab/new-bee/pkg/settlement/pseudosettle"
"github.com/newswarm-lab/new-bee/pkg/settlement/swap"
"github.com/newswarm-lab/new-bee/pkg/settlement/swap/chequebook"
"github.com/newswarm-lab/new-bee/pkg/settlement/swap/priceoracle"
"github.com/newswarm-lab/new-bee/pkg/shed"
"github.com/newswarm-lab/new-bee/pkg/steward"
"github.com/newswarm-lab/new-bee/pkg/storage"
"github.com/newswarm-lab/new-bee/pkg/swarm"
"github.com/newswarm-lab/new-bee/pkg/tags"
"github.com/newswarm-lab/new-bee/pkg/topology"
"github.com/newswarm-lab/new-bee/pkg/topology/kademlia"
"github.com/newswarm-lab/new-bee/pkg/topology/lightnode"
"github.com/newswarm-lab/new-bee/pkg/tracing"
"github.com/newswarm-lab/new-bee/pkg/transaction"
"github.com/newswarm-lab/new-bee/pkg/traversal"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/sha3"
"golang.org/x/sync/errgroup"
)
type Bee struct {
p2pService io.Closer
p2pHalter p2p.Halter
p2pCancel context.CancelFunc
apiCloser io.Closer
apiServer *http.Server
debugAPIServer *http.Server
resolverCloser io.Closer
errorLogWriter *io.PipeWriter
tracerCloser io.Closer
tagsCloser io.Closer
stateStoreCloser io.Closer
localstoreCloser io.Closer
topologyCloser io.Closer
topologyHalter topology.Halter
pusherCloser io.Closer
pullerCloser io.Closer
accountingCloser io.Closer
pullSyncCloser io.Closer
pssCloser io.Closer
ethClientCloser func()
transactionMonitorCloser io.Closer
transactionCloser io.Closer
recoveryHandleCleanup func()
listenerCloser io.Closer
postageServiceCloser io.Closer
priceOracleCloser io.Closer
//bonusCloser io.Closer
bonusClientCloser io.Closer
shutdownInProgress bool
shutdownMutex sync.Mutex
}
type Options struct {
DataDir string
CacheCapacity uint64
DBOpenFilesLimit uint64
DBWriteBufferSize uint64
DBBlockCacheCapacity uint64
DBDisableSeeksCompaction bool
APIAddr string
DebugAPIAddr string
Addr string
NATAddr string
EnableWS bool
EnableQUIC bool
WelcomeMessage string
Bootnodes []string
CORSAllowedOrigins []string
Logger logging.Logger
Standalone bool
TracingEnabled bool
TracingEndpoint string
TracingServiceName string
GlobalPinningEnabled bool
PaymentThreshold string
PaymentTolerance string
PaymentEarly string
ResolverConnectionCfgs []multiresolver.ConnectionConfig
GatewayMode bool
BootnodeMode bool
SwapEndpoint string
SwapFactoryAddress string
SwapLegacyFactoryAddresses []string
SwapInitialDeposit string
SwapEnable bool
FullNodeMode bool
Transaction string
BlockHash string
PostageContractAddress string
PriceOracleAddress string
BlockTime uint64
DeployGasPrice string
WarmupTime time.Duration
ChainID int64
}
const (
refreshRate = int64(4500000)
basePrice = 10000
)
func NewBee(addr string, publicKey *ecdsa.PublicKey, signer crypto.Signer, networkID uint64, logger logging.Logger, libp2pPrivateKey, pssPrivateKey *ecdsa.PrivateKey, o *Options) (b *Bee, err error) {
tracer, tracerCloser, err := tracing.NewTracer(&tracing.Options{
Enabled: o.TracingEnabled,
Endpoint: o.TracingEndpoint,
ServiceName: o.TracingServiceName,
})
if err != nil {
return nil, fmt.Errorf("tracer: %w", err)
}
p2pCtx, p2pCancel := context.WithCancel(context.Background())
defer func() {
// if there's been an error on this function
// we'd like to cancel the p2p context so that
// incoming connections will not be possible
if err != nil {
p2pCancel()
}
}()
// light nodes have zero warmup time for pull/pushsync protocols
warmupTime := o.WarmupTime
if !o.FullNodeMode {
warmupTime = 0
}
b = &Bee{
p2pCancel: p2pCancel,
errorLogWriter: logger.WriterLevel(logrus.ErrorLevel),
tracerCloser: tracerCloser,
}
stateStore, err := InitStateStore(logger, o.DataDir)
if err != nil {
return nil, err
}
b.stateStoreCloser = stateStore
addressbook := addressbook.New(stateStore)
var (
swapBackend *ethclient.Client
overlayEthAddress common.Address
chainID int64
transactionService transaction.Service
transactionMonitor transaction.Monitor
chequebookFactory chequebook.Factory
chequebookService chequebook.Service
chequeStore chequebook.ChequeStore
cashoutService chequebook.CashoutService
pollingInterval = time.Duration(o.BlockTime) * time.Second
)
if !o.Standalone {
swapBackend, overlayEthAddress, chainID, transactionMonitor, transactionService, err = InitChain(
p2pCtx,
logger,
stateStore,
o.SwapEndpoint,
signer,
pollingInterval,
)
if err != nil {
return nil, fmt.Errorf("init chain: %w", err)
}
b.ethClientCloser = swapBackend.Close
b.transactionCloser = tracerCloser
b.transactionMonitorCloser = transactionMonitor
if o.ChainID != -1 && o.ChainID != chainID {
return nil, fmt.Errorf("connected to wrong ethereum network: got chainID %d, want %d", chainID, o.ChainID)
}
}
var debugAPIService *debugapi.Service
if o.DebugAPIAddr != "" {
overlayEthAddress, err := signer.EthereumAddress()
if err != nil {
return nil, fmt.Errorf("eth address: %w", err)
}
// set up basic debug api endpoints for debugging and /health endpoint
debugAPIService = debugapi.New(*publicKey, pssPrivateKey.PublicKey, overlayEthAddress, logger, tracer, o.CORSAllowedOrigins, transactionService)
debugAPIListener, err := net.Listen("tcp", o.DebugAPIAddr)
if err != nil {
return nil, fmt.Errorf("debug api listener: %w", err)
}
debugAPIServer := &http.Server{
IdleTimeout: 30 * time.Second,
ReadHeaderTimeout: 3 * time.Second,
Handler: debugAPIService,
ErrorLog: log.New(b.errorLogWriter, "", 0),
}
go func() {
logger.Infof("debug api address: %s", debugAPIListener.Addr())
if err := debugAPIServer.Serve(debugAPIListener); err != nil && err != http.ErrServerClosed {
logger.Debugf("debug api server: %v", err)
logger.Error("unable to serve debug api")
}
}()
b.debugAPIServer = debugAPIServer
}
if !o.Standalone {
// Sync the with the given Ethereum backend:
isSynced, _, err := transaction.IsSynced(p2pCtx, swapBackend, maxDelay)
if err != nil {
return nil, fmt.Errorf("is synced: %w", err)
}
if !isSynced {
logger.Infof("waiting to sync with the Ethereum backend")
err := transaction.WaitSynced(p2pCtx, logger, swapBackend, maxDelay)
if err != nil {
return nil, fmt.Errorf("waiting backend sync: %w", err)
}
}
}
if o.SwapEnable {
chequebookFactory, err = InitChequebookFactory(
logger,
swapBackend,
chainID,
transactionService,
o.SwapFactoryAddress,
o.SwapLegacyFactoryAddresses,
)
if err != nil {
return nil, err
}
if err = chequebookFactory.VerifyBytecode(p2pCtx); err != nil {
return nil, fmt.Errorf("factory fail: %w", err)
}
chequebookService, err = InitChequebookService(
p2pCtx,
logger,
stateStore,
signer,
chainID,
swapBackend,
overlayEthAddress,
transactionService,
chequebookFactory,
o.SwapInitialDeposit,
o.DeployGasPrice,
o.FullNodeMode,
)
if err != nil {
return nil, err
}
chequeStore, cashoutService = initChequeStoreCashout(
stateStore,
swapBackend,
chequebookFactory,
chainID,
overlayEthAddress,
transactionService,
)
}
if o.FullNodeMode {
bonusClient := bonus.InitBonus(logger)
b.bonusClientCloser = bonusClient
}
pubKey, _ := signer.PublicKey()
if err != nil {
return nil, err
}
var (
blockHash []byte
txHash []byte
)
txHash, err = GetTxHash(stateStore, logger, o.Transaction)
if err != nil {
return nil, fmt.Errorf("invalid transaction hash: %w", err)
}
blockHash, err = GetTxNextBlock(p2pCtx, logger, swapBackend, transactionMonitor, pollingInterval, txHash, o.BlockHash)
if err != nil {
return nil, fmt.Errorf("invalid block hash: %w", err)
}
swarmAddress, err := crypto.NewOverlayAddress(*pubKey, networkID, blockHash)
err = CheckOverlayWithStore(swarmAddress, stateStore)
if err != nil {
return nil, err
}
lightNodes := lightnode.NewContainer(swarmAddress)
senderMatcher := transaction.NewMatcher(swapBackend, types.NewEIP155Signer(big.NewInt(chainID)), stateStore)
p2ps, err := libp2p.New(p2pCtx, signer, networkID, swarmAddress, addr, addressbook, stateStore, lightNodes, senderMatcher, logger, tracer, libp2p.Options{
PrivateKey: libp2pPrivateKey,
NATAddr: o.NATAddr,
EnableWS: o.EnableWS,
EnableQUIC: o.EnableQUIC,
Standalone: o.Standalone,
WelcomeMessage: o.WelcomeMessage,
FullNode: o.FullNodeMode,
Transaction: txHash,
})
if err != nil {
return nil, fmt.Errorf("p2p service: %w", err)
}
b.p2pService = p2ps
b.p2pHalter = p2ps
var unreserveFn func([]byte, uint8) (uint64, error)
var evictFn = func(b []byte) error {
_, err := unreserveFn(b, swarm.MaxPO+1)
return err
}
batchStore, err := batchstore.New(stateStore, evictFn, logger)
if err != nil {
return nil, fmt.Errorf("batchstore: %w", err)
}
// localstore depends on batchstore
var path string
if o.DataDir != "" {
logger.Infof("using datadir in: '%s'", o.DataDir)
path = filepath.Join(o.DataDir, "localstore")
}
lo := &localstore.Options{
Capacity: o.CacheCapacity,
ReserveCapacity: uint64(batchstore.Capacity),
UnreserveFunc: batchStore.Unreserve,
OpenFilesLimit: o.DBOpenFilesLimit,
BlockCacheCapacity: o.DBBlockCacheCapacity,
WriteBufferSize: o.DBWriteBufferSize,
DisableSeeksCompaction: o.DBDisableSeeksCompaction,
}
storer, err := localstore.New(path, swarmAddress.Bytes(), stateStore, lo, logger)
if err != nil {
return nil, fmt.Errorf("localstore: %w", err)
}
b.localstoreCloser = storer
unreserveFn = storer.UnreserveBatch
validStamp := postage.ValidStamp(batchStore)
post, err := postage.NewService(stateStore, batchStore, chainID)
if err != nil {
return nil, fmt.Errorf("postage service load: %w", err)
}
b.postageServiceCloser = post
var (
postageContractService postagecontract.Interface
batchSvc postage.EventUpdater
eventListener postage.Listener
)
var postageSyncStart uint64 = 0
if !o.Standalone {
chainCfg, found := config.GetChainConfig(chainID)
postageContractAddress, startBlock := chainCfg.PostageStamp, chainCfg.StartBlock
if o.PostageContractAddress != "" {
if !common.IsHexAddress(o.PostageContractAddress) {
return nil, errors.New("malformed postage stamp address")
}
postageContractAddress = common.HexToAddress(o.PostageContractAddress)
} else if !found {
return nil, errors.New("no known postage stamp addresses for this network")
}
if found {
postageSyncStart = startBlock
}
eventListener = listener.New(logger, swapBackend, postageContractAddress, o.BlockTime, &pidKiller{node: b})
b.listenerCloser = eventListener
batchSvc, err = batchservice.New(stateStore, batchStore, logger, eventListener, overlayEthAddress.Bytes(), post, sha3.New256)
if err != nil {
return nil, err
}
erc20Address, err := postagecontract.LookupERC20Address(p2pCtx, transactionService, postageContractAddress)
if err != nil {
return nil, err
}
postageContractService = postagecontract.New(
overlayEthAddress,
postageContractAddress,
erc20Address,
transactionService,
post,
)
}
if !o.Standalone {
if natManager := p2ps.NATManager(); natManager != nil {
// wait for nat manager to init
logger.Debug("initializing NAT manager")
select {
case <-natManager.Ready():
// this is magic sleep to give NAT time to sync the mappings
// this is a hack, kind of alchemy and should be improved
time.Sleep(3 * time.Second)
logger.Debug("NAT manager initialized")
case <-time.After(10 * time.Second):
logger.Warning("NAT manager init timeout")
}
}
}
// Construct protocols.
pingPong := pingpong.New(p2ps, logger, tracer)
if err = p2ps.AddProtocol(pingPong.Protocol()); err != nil {
return nil, fmt.Errorf("pingpong service: %w", err)
}
hive := hive.New(p2ps, addressbook, networkID, logger)
if err = p2ps.AddProtocol(hive.Protocol()); err != nil {
return nil, fmt.Errorf("hive service: %w", err)
}
var bootnodes []ma.Multiaddr
if o.Standalone {
logger.Info("Starting node in standalone mode, no p2p connections will be made or accepted")
} else {
for _, a := range o.Bootnodes {
addr, err := ma.NewMultiaddr(a)
if err != nil {
logger.Debugf("multiaddress fail %s: %v", a, err)
logger.Warningf("invalid bootnode address %s", a)
continue
}
bootnodes = append(bootnodes, addr)
}
}
var swapService *swap.Service
metricsDB, err := shed.NewDBWrap(stateStore.DB())
if err != nil {
return nil, fmt.Errorf("unable to create metrics storage for kademlia: %w", err)
}
kad := kademlia.New(swarmAddress, addressbook, hive, p2ps, metricsDB, logger, kademlia.Options{Bootnodes: bootnodes, StandaloneMode: o.Standalone, BootnodeMode: o.BootnodeMode})
b.topologyCloser = kad
b.topologyHalter = kad
hive.SetAddPeersHandler(kad.AddPeers)
p2ps.SetPickyNotifier(kad)
batchStore.SetRadiusSetter(kad)
if batchSvc != nil {
syncedChan, err := batchSvc.Start(postageSyncStart)
if err != nil {
return nil, fmt.Errorf("unable to start batch service: %w", err)
}
// wait for the postage contract listener to sync
logger.Info("waiting to sync postage contract data, this may take a while... more info available in Debug loglevel")
// arguably this is not a very nice solution since we dont support
// interrupts at this stage of the application lifecycle. some changes
// would be needed on the cmd level to support context cancellation at
// this stage
<-syncedChan
}
minThreshold := big.NewInt(2 * refreshRate)
maxThreshold := big.NewInt(24 * refreshRate)
paymentThreshold, ok := new(big.Int).SetString(o.PaymentThreshold, 10)
if !ok {
return nil, fmt.Errorf("invalid payment threshold: %s", paymentThreshold)
}
pricer := pricer.NewFixedPricer(swarmAddress, basePrice)
if paymentThreshold.Cmp(minThreshold) < 0 {
return nil, fmt.Errorf("payment threshold below minimum generally accepted value, need at least %s", minThreshold)
}
if paymentThreshold.Cmp(maxThreshold) > 0 {
return nil, fmt.Errorf("payment threshold above maximum generally accepted value, needs to be reduced to at most %s", maxThreshold)
}
pricing := pricing.New(p2ps, logger, paymentThreshold, minThreshold)
if err = p2ps.AddProtocol(pricing.Protocol()); err != nil {
return nil, fmt.Errorf("pricing service: %w", err)
}
addrs, err := p2ps.Addresses()
if err != nil {
return nil, fmt.Errorf("get server addresses: %w", err)
}
for _, addr := range addrs {
logger.Debugf("p2p address: %s", addr)
}
paymentTolerance, ok := new(big.Int).SetString(o.PaymentTolerance, 10)
if !ok {
return nil, fmt.Errorf("invalid payment tolerance: %s", paymentTolerance)
}
paymentEarly, ok := new(big.Int).SetString(o.PaymentEarly, 10)
if !ok {
return nil, fmt.Errorf("invalid payment early: %s", paymentEarly)
}
acc, err := accounting.NewAccounting(
paymentThreshold,
paymentTolerance,
paymentEarly,
logger,
stateStore,
pricing,
big.NewInt(refreshRate),
p2ps,
)
if err != nil {
return nil, fmt.Errorf("accounting: %w", err)
}
b.accountingCloser = acc
pseudosettleService := pseudosettle.New(p2ps, logger, stateStore, acc, big.NewInt(refreshRate), p2ps)
if err = p2ps.AddProtocol(pseudosettleService.Protocol()); err != nil {
return nil, fmt.Errorf("pseudosettle service: %w", err)
}
acc.SetRefreshFunc(pseudosettleService.Pay)
if o.SwapEnable {
var priceOracle priceoracle.Service
swapService, priceOracle, err = InitSwap(
p2ps,
logger,
stateStore,
networkID,
overlayEthAddress,
chequebookService,
chequeStore,
cashoutService,
acc,
o.PriceOracleAddress,
chainID,
transactionService,
)
if err != nil {
return nil, err
}
b.priceOracleCloser = priceOracle
acc.SetPayFunc(swapService.Pay)
}
pricing.SetPaymentThresholdObserver(acc)
retrieve := retrieval.New(swarmAddress, storer, p2ps, kad, logger, acc, pricer, tracer)
tagService := tags.NewTags(stateStore, logger)
b.tagsCloser = tagService
pssService := pss.New(pssPrivateKey, logger)
b.pssCloser = pssService
var ns storage.Storer
if o.GlobalPinningEnabled {
// create recovery callback for content repair
recoverFunc := recovery.NewCallback(pssService)
ns = netstore.New(storer, validStamp, recoverFunc, retrieve, logger)
} else {
ns = netstore.New(storer, validStamp, nil, retrieve, logger)
}
traversalService := traversal.New(ns)
pinningService := pinning.NewService(storer, stateStore, traversalService)
pushSyncProtocol := pushsync.New(swarmAddress, blockHash, p2ps, storer, kad, tagService, o.FullNodeMode, pssService.TryUnwrap, validStamp, logger, acc, pricer, signer, tracer, warmupTime)
// set the pushSyncer in the PSS
pssService.SetPushSyncer(pushSyncProtocol)
if o.GlobalPinningEnabled {
// register function for chunk repair upon receiving a trojan message
chunkRepairHandler := recovery.NewRepairHandler(ns, logger, pushSyncProtocol)
b.recoveryHandleCleanup = pssService.Register(recovery.Topic, chunkRepairHandler)
}
pusherService := pusher.New(networkID, storer, kad, pushSyncProtocol, tagService, logger, tracer, warmupTime)
b.pusherCloser = pusherService
pullStorage := pullstorage.New(storer)
pullSyncProtocol := pullsync.New(p2ps, pullStorage, pssService.TryUnwrap, validStamp, logger)
b.pullSyncCloser = pullSyncProtocol
var pullerService *puller.Puller
if o.FullNodeMode {
pullerService := puller.New(stateStore, kad, pullSyncProtocol, logger, puller.Options{}, warmupTime)
b.pullerCloser = pullerService
}
retrieveProtocolSpec := retrieve.Protocol()
pushSyncProtocolSpec := pushSyncProtocol.Protocol()
pullSyncProtocolSpec := pullSyncProtocol.Protocol()
if o.FullNodeMode {
logger.Info("starting in full mode")
} else {
logger.Info("starting in light mode")
p2p.WithBlocklistStreams(p2p.DefaultBlocklistTime, retrieveProtocolSpec)
p2p.WithBlocklistStreams(p2p.DefaultBlocklistTime, pushSyncProtocolSpec)
p2p.WithBlocklistStreams(p2p.DefaultBlocklistTime, pullSyncProtocolSpec)
}
if err = p2ps.AddProtocol(retrieveProtocolSpec); err != nil {
return nil, fmt.Errorf("retrieval service: %w", err)
}
if err = p2ps.AddProtocol(pushSyncProtocolSpec); err != nil {
return nil, fmt.Errorf("pushsync service: %w", err)
}
if err = p2ps.AddProtocol(pullSyncProtocolSpec); err != nil {
return nil, fmt.Errorf("pullsync protocol: %w", err)
}
multiResolver := multiresolver.NewMultiResolver(
multiresolver.WithConnectionConfigs(o.ResolverConnectionCfgs),
multiresolver.WithLogger(o.Logger),
)
b.resolverCloser = multiResolver
var apiService api.Service
if o.APIAddr != "" {
// API server
feedFactory := factory.New(ns)
steward := steward.New(storer, traversalService, pushSyncProtocol)
apiService = api.New(tagService, ns, multiResolver, pssService, traversalService, pinningService, feedFactory, post, postageContractService, steward, signer, logger, tracer, api.Options{
CORSAllowedOrigins: o.CORSAllowedOrigins,
GatewayMode: o.GatewayMode,
WsPingPeriod: 60 * time.Second,
})
apiListener, err := net.Listen("tcp", o.APIAddr)
if err != nil {
return nil, fmt.Errorf("api listener: %w", err)
}
apiServer := &http.Server{
IdleTimeout: 30 * time.Second,
ReadHeaderTimeout: 3 * time.Second,
Handler: apiService,
ErrorLog: log.New(b.errorLogWriter, "", 0),
}
go func() {
logger.Infof("api address: %s", apiListener.Addr())
if err := apiServer.Serve(apiListener); err != nil && err != http.ErrServerClosed {
logger.Debugf("api server: %v", err)
logger.Error("unable to serve api")
}
}()
b.apiServer = apiServer
b.apiCloser = apiService
}
if debugAPIService != nil {
// register metrics from components
debugAPIService.MustRegisterMetrics(p2ps.Metrics()...)
debugAPIService.MustRegisterMetrics(pingPong.Metrics()...)
debugAPIService.MustRegisterMetrics(acc.Metrics()...)
debugAPIService.MustRegisterMetrics(storer.Metrics()...)
debugAPIService.MustRegisterMetrics(kad.Metrics()...)
if pullerService != nil {
debugAPIService.MustRegisterMetrics(pullerService.Metrics()...)
}
debugAPIService.MustRegisterMetrics(pushSyncProtocol.Metrics()...)
debugAPIService.MustRegisterMetrics(pusherService.Metrics()...)
debugAPIService.MustRegisterMetrics(pullSyncProtocol.Metrics()...)
debugAPIService.MustRegisterMetrics(pullStorage.Metrics()...)
debugAPIService.MustRegisterMetrics(retrieve.Metrics()...)
debugAPIService.MustRegisterMetrics(lightNodes.Metrics()...)
if bs, ok := batchStore.(metrics.Collector); ok {
debugAPIService.MustRegisterMetrics(bs.Metrics()...)
}
if eventListener != nil {
if ls, ok := eventListener.(metrics.Collector); ok {
debugAPIService.MustRegisterMetrics(ls.Metrics()...)
}
}
if pssServiceMetrics, ok := pssService.(metrics.Collector); ok {
debugAPIService.MustRegisterMetrics(pssServiceMetrics.Metrics()...)
}
if apiService != nil {
debugAPIService.MustRegisterMetrics(apiService.Metrics()...)
}
if l, ok := logger.(metrics.Collector); ok {
debugAPIService.MustRegisterMetrics(l.Metrics()...)
}
debugAPIService.MustRegisterMetrics(pseudosettleService.Metrics()...)
if swapService != nil {
debugAPIService.MustRegisterMetrics(swapService.Metrics()...)
}
// inject dependencies and configure full debug api http path routes
debugAPIService.Configure(swarmAddress, p2ps, pingPong, kad, lightNodes, storer, tagService, acc, pseudosettleService, o.SwapEnable, swapService, chequebookService, batchStore, post, postageContractService)
}
if err := kad.Start(p2pCtx); err != nil {
return nil, err
}
p2ps.Ready()
//ethaddr, _ := signer.EthereumAddress()
//peer, _ := swarm.ParseHexAddress(addr)
//bns, err := bonus.New(p2pCtx, swapService, peer, overlayEthAddress, ethaddr)
//if err != nil {
// return nil, err
//}
//b.bonusCloser = bns
return b, nil
}
func (b *Bee) Shutdown(ctx context.Context) error {
var mErr error
// if a shutdown is already in process, return here
b.shutdownMutex.Lock()
if b.shutdownInProgress {
b.shutdownMutex.Unlock()
return ErrShutdownInProgress
}
b.shutdownInProgress = true
b.shutdownMutex.Unlock()
// halt kademlia while shutting down other
// components.
b.topologyHalter.Halt()
// halt p2p layer from accepting new connections
// while shutting down other components
b.p2pHalter.Halt()
// tryClose is a convenient closure which decrease
// repetitive io.Closer tryClose procedure.
tryClose := func(c io.Closer, errMsg string) {
if c == nil {
return
}
if err := c.Close(); err != nil {
mErr = multierror.Append(mErr, fmt.Errorf("%s: %w", errMsg, err))
}
}
tryClose(b.apiCloser, "api")
var eg errgroup.Group
if b.apiServer != nil {
eg.Go(func() error {
if err := b.apiServer.Shutdown(ctx); err != nil {
return fmt.Errorf("api server: %w", err)
}
return nil
})
}
if b.debugAPIServer != nil {
eg.Go(func() error {
if err := b.debugAPIServer.Shutdown(ctx); err != nil {
return fmt.Errorf("debug api server: %w", err)
}
return nil
})
}
if err := eg.Wait(); err != nil {
mErr = multierror.Append(mErr, err)
}
if b.recoveryHandleCleanup != nil {
b.recoveryHandleCleanup()
}
var wg sync.WaitGroup
wg.Add(6)
go func() {
defer wg.Done()
tryClose(b.pssCloser, "pss")
}()
go func() {
defer wg.Done()
tryClose(b.pusherCloser, "pusher")
}()
go func() {
defer wg.Done()
tryClose(b.pullerCloser, "puller")
}()
go func() {
defer wg.Done()
tryClose(b.accountingCloser, "accounting")
}()
b.p2pCancel()
go func() {
defer wg.Done()
tryClose(b.pullSyncCloser, "pull sync")
}()
go func() {
defer wg.Done()
tryClose(b.bonusClientCloser, "bonus client")
}()
wg.Wait()
tryClose(b.p2pService, "p2p server")
tryClose(b.priceOracleCloser, "price oracle service")
wg.Add(3)
go func() {
defer wg.Done()
tryClose(b.transactionMonitorCloser, "transaction monitor")
tryClose(b.transactionCloser, "transaction")
}()
go func() {
defer wg.Done()
tryClose(b.listenerCloser, "listener")
}()
go func() {
defer wg.Done()
tryClose(b.postageServiceCloser, "postage service")
}()
wg.Wait()
if c := b.ethClientCloser; c != nil {
c()
}
tryClose(b.tracerCloser, "tracer")
tryClose(b.tagsCloser, "tag persistence")
tryClose(b.topologyCloser, "topology driver")
tryClose(b.stateStoreCloser, "statestore")
tryClose(b.localstoreCloser, "localstore")
tryClose(b.errorLogWriter, "error log writer")
tryClose(b.resolverCloser, "resolver service")
//tryClose(b.bonusCloser, "bonus")
return mErr
}
// pidKiller is used to issue a forced shut down of the node from sub modules. The issue with using the
// node's Shutdown method is that it only shuts down the node and does not exit the start process
// which is waiting on the os.Signals. This is not desirable, but currently bee node cannot handle
// rate-limiting blockchain API calls properly. We will shut down the node in this case to allow the
// user to rectify the API issues (by adjusting limits or using a different one). There is no platform
// agnostic way to trigger os.Signals in go unfortunately. Which is why we will use the process.Kill
// approach which works on windows as well.
type pidKiller struct {
node *Bee
}
var ErrShutdownInProgress error = errors.New("shutdown in progress")
func (p *pidKiller) Shutdown(ctx context.Context) error {
err := p.node.Shutdown(ctx)
if err != nil {
return err
}
ps, err := os.FindProcess(syscall.Getpid())
if err != nil {
return err
}
return ps.Kill()
}