This repository has been archived by the owner on Aug 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 110
/
swarm.go
594 lines (522 loc) · 17.2 KB
/
swarm.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
// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package swarm
import (
"bytes"
"crypto/ecdsa"
"errors"
"fmt"
"io"
"net"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"unicode"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rpc"
"github.com/ethersphere/swarm/api"
httpapi "github.com/ethersphere/swarm/api/http"
"github.com/ethersphere/swarm/bzzeth"
"github.com/ethersphere/swarm/chunk"
"github.com/ethersphere/swarm/contracts/ens"
"github.com/ethersphere/swarm/fuse"
"github.com/ethersphere/swarm/log"
"github.com/ethersphere/swarm/network"
"github.com/ethersphere/swarm/network/retrieval"
"github.com/ethersphere/swarm/network/stream"
"github.com/ethersphere/swarm/p2p/protocols"
"github.com/ethersphere/swarm/pss"
pssmessage "github.com/ethersphere/swarm/pss/message"
"github.com/ethersphere/swarm/pushsync"
"github.com/ethersphere/swarm/state"
"github.com/ethersphere/swarm/storage"
"github.com/ethersphere/swarm/storage/feed"
"github.com/ethersphere/swarm/storage/localstore"
"github.com/ethersphere/swarm/storage/mock"
"github.com/ethersphere/swarm/storage/pin"
"github.com/ethersphere/swarm/swap"
"github.com/ethersphere/swarm/tracing"
rnsconfig "github.com/rnsdomains/rns-go-lib/config"
rnsresolver "github.com/rnsdomains/rns-go-lib/resolver"
)
var (
updateGaugesPeriod = 5 * time.Second
startCounter = metrics.NewRegisteredCounter("stack/start", nil)
stopCounter = metrics.NewRegisteredCounter("stack/stop", nil)
uptimeGauge = metrics.NewRegisteredGauge("stack/uptime", nil)
)
// Swarm abstracts the complete Swarm stack
type Swarm struct {
config *api.Config // swarm configuration
api *api.API // high level api layer (fs/manifest)
dns api.Resolver // DNS registrar
rns api.Resolver // RNS registrar
fileStore *storage.FileStore // distributed preimage archive, the local API to the storage with document level storage/retrieval support
streamer *stream.Registry
retrieval *retrieval.Retrieval
bzz *network.Bzz // the logistic manager
bzzEth *bzzeth.BzzEth
privateKey *ecdsa.PrivateKey
netStore *storage.NetStore
sfs *fuse.SwarmFS // need this to cleanup all the active mounts on node exit
ps *pss.Pss
pushSync *pushsync.Pusher
storer *pushsync.Storer
swap *swap.Swap
stateStore *state.DBStore
tags *chunk.Tags
accountingMetrics *protocols.AccountingMetrics
cleanupFuncs []func() error
pinAPI *pin.API // API object implements all pinning related commands
inspector *api.Inspector
tracerClose io.Closer
}
// NewSwarm creates a new swarm service instance
// implements node.Service
// If mockStore is not nil, it will be used as the storage for chunk data.
// MockStore should be used only for testing.
func NewSwarm(config *api.Config, mockStore *mock.NodeStore) (self *Swarm, err error) {
if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroAddr) {
return nil, fmt.Errorf("empty public key")
}
if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroAddr) {
return nil, fmt.Errorf("empty bzz key")
}
self = &Swarm{
config: config,
privateKey: config.ShiftPrivateKey(),
cleanupFuncs: []func() error{},
}
log.Debug("Setting up Swarm service components")
bzzconfig := &network.BzzConfig{
NetworkID: config.NetworkID,
Address: network.NewBzzAddr(common.FromHex(config.BzzKey), []byte(config.Enode.URLv4())),
HiveParams: config.HiveParams,
LightNode: config.LightNodeEnabled,
BootnodeMode: config.BootnodeMode,
SyncEnabled: config.SyncEnabled,
}
// Swap initialization
if config.SwapEnabled {
// for now, Swap can only be enabled in a whitelisted network
if self.config.NetworkID != swap.AllowedNetworkID {
return nil, fmt.Errorf("swap can only be enabled under BZZ Network ID %d, found Network ID %d instead", swap.AllowedNetworkID, self.config.NetworkID)
}
swapParams := &swap.Params{
BaseAddrs: bzzconfig.Address,
LogPath: self.config.SwapLogPath,
LogLevel: self.config.SwapLogLevel,
DisconnectThreshold: int64(self.config.SwapDisconnectThreshold),
PaymentThreshold: int64(self.config.SwapPaymentThreshold),
}
// create the accounting objects
self.swap, err = swap.New(
self.config.Path,
self.privateKey,
self.config.SwapBackendURL,
swapParams,
self.config.Contract,
self.config.SwapSkipDeposit,
self.config.SwapDepositAmount,
self.config.SwapChequebookFactory,
)
if err != nil {
return nil, err
}
// start anonymous metrics collection
self.accountingMetrics = protocols.SetupAccountingMetrics(10*time.Second, filepath.Join(config.Path, "metrics.db"))
}
config.HiveParams.Discovery = true
if config.DisableAutoConnect {
config.HiveParams.DisableAutoConnect = true
}
self.stateStore, err = state.NewDBStore(filepath.Join(config.Path, "state-store.db"))
if err != nil {
return
}
// set up high level api
var resolver *api.MultiResolver
if len(config.EnsAPIs) > 0 {
opts := []api.MultiResolverOption{}
for _, c := range config.EnsAPIs {
tld, endpoint, addr := parseResolverAPIAddress(c)
r, err := newEnsClient(endpoint, addr, config, self.privateKey)
if err != nil {
return nil, err
}
opts = append(opts, api.MultiResolverOptionWithResolver(r, tld))
}
resolver = api.NewMultiResolver(opts...)
self.dns = resolver
}
if config.RnsAPI != "" {
var contractAddress string
_, endpoint, addr := parseResolverAPIAddress(config.RnsAPI)
if !bytes.Equal(addr.Bytes(), common.Address{}.Bytes()) {
contractAddress = addr.String()
}
rnsconfig.SetConfiguration(endpoint, contractAddress)
self.rns = api.ResolverFunc(rnsresolver.ResolveDomainContent)
}
// check that we are not in the old database schema
// if so - fail and exit
isLegacy := localstore.IsLegacyDatabase(config.ChunkDbPath)
if isLegacy {
return nil, errors.New("Legacy database format detected! Please read the migration announcement at: https://github.com/ethersphere/swarm/blob/master/docs/Migration-v0.3-to-v0.4.md")
}
var feedsHandler *feed.Handler
fhParams := &feed.HandlerParams{}
feedsHandler = feed.NewHandler(fhParams)
self.tags = chunk.NewTags()
err = self.stateStore.Get("tags", self.tags)
if err != nil {
if err == state.ErrNotFound {
self.tags = chunk.NewTags()
} else {
return nil, err
}
} else {
log.Info("loaded saved tags successfully from state store")
}
to := network.NewKademlia(
common.FromHex(config.BzzKey),
network.NewKadParams(),
)
localStore, err := localstore.New(config.ChunkDbPath, config.BaseKey, &localstore.Options{
MockStore: mockStore,
Capacity: config.DbCapacity,
Tags: self.tags,
PutToGCCheck: to.IsWithinDepth,
})
if err != nil {
return nil, err
}
lstore := chunk.NewValidatorStore(
localStore,
storage.NewContentAddressValidator(storage.MakeHashFunc(storage.DefaultHash)),
feedsHandler,
)
self.netStore = storage.NewNetStore(lstore, bzzconfig.Address)
self.retrieval = retrieval.New(to, self.netStore, bzzconfig.Address, self.swap)
self.netStore.RemoteGet = self.retrieval.RequestFromPeers
feedsHandler.SetStore(self.netStore)
syncing := true
if !config.SyncEnabled || config.LightNodeEnabled || config.BootnodeMode {
syncing = false
}
syncProvider := stream.NewSyncProvider(self.netStore, to, bzzconfig.Address, syncing, false)
self.streamer = stream.New(self.stateStore, bzzconfig.Address, syncProvider)
// Swarm Hash Merklised Chunking for Arbitrary-length Document/File storage
lnetStore := storage.NewLNetStore(self.netStore)
self.fileStore = storage.NewFileStore(lnetStore, localStore, self.config.FileStoreParams, self.tags)
log.Debug("Setup local storage")
self.bzz = network.NewBzz(bzzconfig, to, self.stateStore, stream.Spec, self.retrieval.Spec(), self.streamer.Run, self.retrieval.Run)
self.bzzEth = bzzeth.New(self.netStore, to)
// Pss = postal service over swarm (devp2p over bzz)
self.ps, err = pss.New(to, config.Pss)
if err != nil {
return nil, err
}
if pss.IsActiveHandshake {
pss.SetHandshakeController(self.ps, pss.NewHandshakeParams())
}
if config.PushSyncEnabled {
// expire time for push-sync messages should be lower than regular chat-like messages to avoid network flooding
pubsub := pss.NewPubSub(self.ps, 20*time.Second)
self.pushSync = pushsync.NewPusher(localStore, pubsub, self.tags)
self.storer = pushsync.NewStorer(self.netStore, pubsub)
}
self.api = api.NewAPI(self.fileStore, self.dns, self.rns, feedsHandler, self.privateKey, self.tags)
if config.EnablePinning {
// Instantiate the pinAPI object with the already opened localstore
self.pinAPI = pin.NewAPI(localStore, self.stateStore, self.config.FileStoreParams, self.tags, self.api)
}
self.sfs = fuse.NewSwarmFS(self.api)
log.Debug("Initialized FUSE filesystem")
self.inspector = api.NewInspector(self.api, self.bzz.Hive, self.netStore, self.streamer, localStore)
return self, nil
}
// parseResolverAPIAddress parses string according to format
// [tld:][contract-addr@]url and returns ClientConfig structure
// with endpoint, contract address and TLD.
func parseResolverAPIAddress(s string) (tld, endpoint string, addr common.Address) {
isAllLetterString := func(s string) bool {
for _, r := range s {
if !unicode.IsLetter(r) {
return false
}
}
return true
}
endpoint = s
if i := strings.Index(endpoint, ":"); i > 0 {
if isAllLetterString(endpoint[:i]) && len(endpoint) > i+2 && endpoint[i+1:i+3] != "//" {
tld = endpoint[:i]
endpoint = endpoint[i+1:]
}
}
if i := strings.Index(endpoint, "@"); i > 0 {
addr = common.HexToAddress(endpoint[:i])
endpoint = endpoint[i+1:]
}
return
}
// ensClient provides functionality for api.ResolveValidator
type ensClient struct {
*ens.ENS
*ethclient.Client
}
// newEnsClient creates a new ENS client for that is a consumer of
// a ENS API on a specific endpoint. It is used as a helper function
// for creating multiple resolvers in NewSwarm function.
func newEnsClient(endpoint string, addr common.Address, config *api.Config, privkey *ecdsa.PrivateKey) (*ensClient, error) {
log.Info("connecting to ENS API", "url", endpoint)
client, err := rpc.Dial(endpoint)
if err != nil {
return nil, fmt.Errorf("error connecting to ENS API %s: %s", endpoint, err)
}
ethClient := ethclient.NewClient(client)
ensRoot := config.EnsRoot
if addr != (common.Address{}) {
ensRoot = addr
} else {
ensRoot = ens.Address
}
transactOpts := bind.NewKeyedTransactor(privkey)
dns, err := ens.NewENS(transactOpts, ensRoot, ethClient)
if err != nil {
return nil, err
}
log.Debug(fmt.Sprintf("-> Swarm Domain Name Registrar %v @ address %v", endpoint, ensRoot.Hex()))
return &ensClient{
ENS: dns,
Client: ethClient,
}, err
}
/*
Start is called when the stack is started
* starts the network kademlia hive peer management
* (starts netStore level 0 api)
* starts DPA level 1 api (chunking -> store/retrieve requests)
* (starts level 2 api)
* starts http proxy server
* registers url scheme handlers for bzz, etc
* TODO: start subservices like sword, swear, swarmdns
*/
// implements the node.Service interface
func (s *Swarm) Start(srv *p2p.Server) error {
startTime := time.Now()
s.tracerClose = tracing.Closer
// update uaddr to correct enode
newaddr := s.bzz.UpdateLocalAddr([]byte(srv.Self().URLv4()))
log.Info("Updated bzz local addr", "oaddr", fmt.Sprintf("%x", newaddr.OAddr), "uaddr", fmt.Sprintf("%s", newaddr.UAddr))
log.Info("Starting bzz service")
err := s.bzz.Start(srv)
if err != nil {
log.Error("bzz failed", "err", err)
return err
}
log.Info("Swarm network started", "bzzaddr", fmt.Sprintf("%x", s.bzz.Hive.BaseAddr()))
err = s.bzzEth.Start(srv)
if err != nil {
return err
}
if s.ps != nil {
s.ps.Start(srv)
}
// start swarm http proxy server
if s.config.Port != "" {
addr := net.JoinHostPort(s.config.ListenAddr, s.config.Port)
server := httpapi.NewServer(s.api, s.pinAPI, s.config.Cors)
if s.config.Cors != "" {
log.Info("Swarm HTTP proxy CORS headers", "allowedOrigins", s.config.Cors)
}
go func() {
// We need to use net.Listen because the addr could be on port '0',
// which means that the OS will allocate a port for us
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Error("Could not open a port for Swarm HTTP proxy", "err", err.Error())
return
}
s.config.Port = strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)
log.Info("Starting Swarm HTTP proxy", "port", s.config.Port)
err = http.Serve(listener, server)
if err != nil {
log.Error("Could not start Swarm HTTP proxy", "err", err.Error())
}
}()
}
doneC := make(chan struct{})
s.cleanupFuncs = append(s.cleanupFuncs, func() error {
close(doneC)
return nil
})
go func(time.Time) {
for {
select {
case <-time.After(updateGaugesPeriod):
uptimeGauge.Update(time.Since(startTime).Nanoseconds())
case <-doneC:
return
}
}
}(startTime)
startCounter.Inc(1)
if err := s.streamer.Start(srv); err != nil {
return err
}
return s.retrieval.Start(srv)
}
// Stop stops all component services.
// Implements the node.Service interface.
func (s *Swarm) Stop() error {
if s.tracerClose != nil {
err := s.tracerClose.Close()
tracing.FinishSpans()
if err != nil {
return err
}
}
if s.pushSync != nil {
s.pushSync.Close()
}
if s.ps != nil {
s.ps.Stop()
}
if s.swap != nil {
s.swap.Stop()
}
if s.accountingMetrics != nil {
s.accountingMetrics.Close()
}
if err := s.streamer.Stop(); err != nil {
log.Error("streamer stop", "err", err)
}
if err := s.retrieval.Stop(); err != nil {
log.Error("retrieval stop", "err", err)
}
if s.tags != nil {
err := s.stateStore.Put("tags", s.tags)
if err != nil {
log.Error("had an error persisting tags", "err", err)
}
}
if s.storer != nil {
s.storer.Close()
}
if s.netStore != nil {
s.netStore.Close()
}
s.sfs.Stop()
stopCounter.Inc(1)
err := s.bzzEth.Stop()
if err != nil {
log.Error("error during bzz-eth shutdown", "err", err)
}
err = s.bzz.Stop()
if s.stateStore != nil {
s.stateStore.Close()
}
for _, cleanF := range s.cleanupFuncs {
err = cleanF()
if err != nil {
log.Error("encountered an error while running cleanup function", "err", err)
break
}
}
return err
}
// Protocols implements the node.Service interface
func (s *Swarm) Protocols() (protos []p2p.Protocol) {
if s.config.BootnodeMode {
protos = append(protos, s.bzz.Protocols()...)
} else {
protos = append(protos, s.bzz.Protocols()...)
protos = append(protos, s.bzzEth.Protocols()...)
if s.ps != nil {
protos = append(protos, s.ps.Protocols()...)
}
if s.swap != nil {
protos = append(protos, s.swap.Protocols()...)
}
}
return
}
// APIs returns the RPC API descriptors the Swarm implementation offers
// implements node.Service
func (s *Swarm) APIs() []rpc.API {
apis := []rpc.API{
// public APIs
{
Namespace: "bzz",
Version: "4.0",
Service: &Info{s.config},
Public: true,
},
// admin APIs
{
Namespace: "bzz",
Version: "4.0",
Service: s.inspector,
Public: false,
},
{
Namespace: "swarmfs",
Version: fuse.SwarmFSVersion,
Service: s.sfs,
Public: false,
},
{
Namespace: "accounting",
Version: protocols.AccountingVersion,
Service: protocols.NewAccountingApi(s.accountingMetrics),
Public: false,
},
}
apis = append(apis, s.bzz.APIs()...)
// this is a workaround disabling syncing altogether from a node but
// must be changed when multiple stream implementations are at hand
if s.config.SyncEnabled {
apis = append(apis, s.streamer.APIs()...)
}
apis = append(apis, s.bzzEth.APIs()...)
if s.ps != nil {
apis = append(apis, s.ps.APIs()...)
}
if s.config.SwapEnabled {
apis = append(apis, s.swap.APIs()...)
}
return apis
}
// RegisterPssProtocol adds a devp2p protocol to the swarm node's Pss instance
func (s *Swarm) RegisterPssProtocol(topic *pssmessage.Topic, spec *protocols.Spec, targetprotocol *p2p.Protocol, options *pss.ProtocolParams) (*pss.Protocol, error) {
return pss.RegisterProtocol(s.ps, topic, spec, targetprotocol, options)
}
// Info represents the current Swarm node's configuration
type Info struct {
*api.Config
}
// Info returns the current Swarm configuration
func (i *Info) Info() *Info {
return i
}