github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/network/node/service.go (about) 1 package node 2 3 import ( 4 "crypto/ecdsa" 5 "reflect" 6 7 "github.com/neatlab/neatio/chain/core/rawdb" 8 9 "github.com/neatlab/neatio/chain/accounts" 10 "github.com/neatlab/neatio/neatdb" 11 "github.com/neatlab/neatio/network/p2p" 12 "github.com/neatlab/neatio/network/rpc" 13 "github.com/neatlab/neatio/utilities/event" 14 ) 15 16 type ServiceContext struct { 17 config *Config 18 services map[reflect.Type]Service 19 EventMux *event.TypeMux 20 AccountManager *accounts.Manager 21 } 22 23 func (ctx *ServiceContext) OpenDatabase(name string, cache int, handles int, namespace string) (neatdb.Database, error) { 24 if ctx.config.DataDir == "" { 25 return rawdb.NewMemoryDatabase(), nil 26 } 27 db, err := rawdb.NewLevelDBDatabase(ctx.config.ResolvePath(name), cache, handles, namespace) 28 if err != nil { 29 return nil, err 30 } 31 return db, nil 32 } 33 34 func (ctx *ServiceContext) ResolvePath(path string) string { 35 return ctx.config.ResolvePath(path) 36 } 37 38 func (ctx *ServiceContext) Service(service interface{}) error { 39 element := reflect.ValueOf(service).Elem() 40 if running, ok := ctx.services[element.Type()]; ok { 41 element.Set(reflect.ValueOf(running)) 42 return nil 43 } 44 return ErrServiceUnknown 45 } 46 47 func (ctx *ServiceContext) NodeKey() *ecdsa.PrivateKey { 48 return ctx.config.NodeKey() 49 } 50 51 func (ctx *ServiceContext) ChainId() string { 52 return ctx.config.ChainId 53 } 54 55 type ServiceConstructor func(ctx *ServiceContext) (Service, error) 56 57 type Service interface { 58 Protocols() []p2p.Protocol 59 60 APIs() []rpc.API 61 62 Start(server *p2p.Server) error 63 64 Stop() error 65 }