Skip to content

Commit eeb322a

Browse files
committed
node: ensure datadir can be co-inhabited by different instances
This change ensures that nodes started with different Name but same DataDir values don't use the same nodekey and IPC socket.
1 parent 52ede09 commit eeb322a

14 files changed

Lines changed: 422 additions & 186 deletions

File tree

‎cmd/geth/chaincmd.go‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ func importChain(ctx *cli.Context) error {
7979
if ctx.GlobalBool(utils.TestNetFlag.Name) {
8080
state.StartingNonce = 1048576 // (2**20)
8181
}
82-
chain, chainDb := utils.MakeChain(ctx)
82+
stack := makeFullNode(ctx)
83+
chain, chainDb := utils.MakeChain(ctx, stack)
8384
start := time.Now()
8485
err := utils.ImportChain(chain, ctx.Args().First())
8586
chainDb.Close()
@@ -94,7 +95,8 @@ func exportChain(ctx *cli.Context) error {
9495
if len(ctx.Args()) < 1 {
9596
utils.Fatalf("This command requires an argument.")
9697
}
97-
chain, _ := utils.MakeChain(ctx)
98+
stack := makeFullNode(ctx)
99+
chain, _ := utils.MakeChain(ctx, stack)
98100
start := time.Now()
99101

100102
var err error
@@ -122,28 +124,34 @@ func exportChain(ctx *cli.Context) error {
122124
}
123125

124126
func removeDB(ctx *cli.Context) error {
125-
confirm, err := console.Stdin.PromptConfirm("Remove local database?")
126-
if err != nil {
127-
utils.Fatalf("%v", err)
127+
stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
128+
dbdir := stack.ResolvePath("chaindata")
129+
if !common.FileExist(dbdir) {
130+
fmt.Println(dbdir, "does not exist")
131+
return nil
128132
}
129133

130-
if confirm {
131-
fmt.Println("Removing chaindata...")
134+
fmt.Println(dbdir)
135+
confirm, err := console.Stdin.PromptConfirm("Remove this database?")
136+
switch {
137+
case err != nil:
138+
utils.Fatalf("%v", err)
139+
case !confirm:
140+
fmt.Println("Operation aborted")
141+
default:
142+
fmt.Println("Removing...")
132143
start := time.Now()
133-
134-
os.RemoveAll(filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), "chaindata"))
135-
144+
os.RemoveAll(dbdir)
136145
fmt.Printf("Removed in %v\n", time.Since(start))
137-
} else {
138-
fmt.Println("Operation aborted")
139146
}
140147
return nil
141148
}
142149

143150
func upgradeDB(ctx *cli.Context) error {
144151
glog.Infoln("Upgrading blockchain database")
145152

146-
chain, chainDb := utils.MakeChain(ctx)
153+
stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
154+
chain, chainDb := utils.MakeChain(ctx, stack)
147155
bcVersion := core.GetBlockChainVersion(chainDb)
148156
if bcVersion == 0 {
149157
bcVersion = core.BlockChainVersion
@@ -156,10 +164,12 @@ func upgradeDB(ctx *cli.Context) error {
156164
utils.Fatalf("Unable to export chain for reimport %s", err)
157165
}
158166
chainDb.Close()
159-
os.RemoveAll(filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), "chaindata"))
167+
if dir := dbDirectory(chainDb); dir != "" {
168+
os.RemoveAll(dir)
169+
}
160170

161171
// Import the chain file.
162-
chain, chainDb = utils.MakeChain(ctx)
172+
chain, chainDb = utils.MakeChain(ctx, stack)
163173
core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
164174
err := utils.ImportChain(chain, exportFile)
165175
chainDb.Close()
@@ -172,8 +182,17 @@ func upgradeDB(ctx *cli.Context) error {
172182
return nil
173183
}
174184

185+
func dbDirectory(db ethdb.Database) string {
186+
ldb, ok := db.(*ethdb.LDBDatabase)
187+
if !ok {
188+
return ""
189+
}
190+
return ldb.Path()
191+
}
192+
175193
func dump(ctx *cli.Context) error {
176-
chain, chainDb := utils.MakeChain(ctx)
194+
stack := makeFullNode(ctx)
195+
chain, chainDb := utils.MakeChain(ctx, stack)
177196
for _, arg := range ctx.Args() {
178197
var block *types.Block
179198
if hashish(arg) {

‎cmd/geth/consolecmd.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func remoteConsole(ctx *cli.Context) error {
107107
utils.Fatalf("Unable to attach to remote geth: %v", err)
108108
}
109109
config := console.Config{
110-
DataDir: utils.MustMakeDataDir(ctx),
110+
DataDir: utils.MakeDataDir(ctx),
111111
DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
112112
Client: client,
113113
Preload: utils.MakeConsolePreloads(ctx),
@@ -135,7 +135,7 @@ func remoteConsole(ctx *cli.Context) error {
135135
// for "geth attach" and "geth monitor" with no argument.
136136
func dialRPC(endpoint string) (*rpc.Client, error) {
137137
if endpoint == "" {
138-
endpoint = node.DefaultIPCEndpoint()
138+
endpoint = node.DefaultIPCEndpoint(clientIdentifier)
139139
} else if strings.HasPrefix(endpoint, "rpc:") || strings.HasPrefix(endpoint, "ipc:") {
140140
// Backwards compatibility with geth < 1.5 which required
141141
// these prefixes.

‎cmd/geth/dao_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,9 @@ func testDAOForkBlockNewChain(t *testing.T, testnet bool, genesis string, votes
195195
geth.cmd.Wait()
196196
}
197197
// Retrieve the DAO config flag from the database
198-
path := filepath.Join(datadir, "chaindata")
198+
path := filepath.Join(datadir, "geth", "chaindata")
199199
if testnet && genesis == "" {
200-
path = filepath.Join(datadir, "testnet", "chaindata")
200+
path = filepath.Join(datadir, "testnet", "geth", "chaindata")
201201
}
202202
db, err := ethdb.NewLDBDatabase(path, 0, 0)
203203
if err != nil {

‎cmd/geth/main.go‎

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ import (
3636
"github.com/ethereum/go-ethereum/core"
3737
"github.com/ethereum/go-ethereum/core/state"
3838
"github.com/ethereum/go-ethereum/eth"
39-
"github.com/ethereum/go-ethereum/ethdb"
4039
"github.com/ethereum/go-ethereum/internal/debug"
4140
"github.com/ethereum/go-ethereum/logger"
4241
"github.com/ethereum/go-ethereum/logger/glog"
@@ -46,7 +45,7 @@ import (
4645
)
4746

4847
const (
49-
clientIdentifier = "Geth" // Client identifier to advertise over the network
48+
clientIdentifier = "geth" // Client identifier to advertise over the network
5049
)
5150

5251
var (
@@ -245,17 +244,15 @@ func initGenesis(ctx *cli.Context) error {
245244
state.StartingNonce = 1048576 // (2**20)
246245
}
247246

248-
chainDb, err := ethdb.NewLDBDatabase(filepath.Join(utils.MustMakeDataDir(ctx), "chaindata"), 0, 0)
249-
if err != nil {
250-
utils.Fatalf("could not open database: %v", err)
251-
}
247+
stack := makeFullNode(ctx)
248+
chaindb := utils.MakeChainDatabase(ctx, stack)
252249

253250
genesisFile, err := os.Open(genesisPath)
254251
if err != nil {
255252
utils.Fatalf("failed to read genesis file: %v", err)
256253
}
257254

258-
block, err := core.WriteGenesisBlock(chainDb, genesisFile)
255+
block, err := core.WriteGenesisBlock(chaindb, genesisFile)
259256
if err != nil {
260257
utils.Fatalf("failed to write genesis block: %v", err)
261258
}
@@ -296,9 +293,6 @@ func makeFullNode(ctx *cli.Context) *node.Node {
296293
// it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
297294
// miner.
298295
func startNode(ctx *cli.Context, stack *node.Node) {
299-
// Report geth version
300-
glog.V(logger.Info).Infof("instance: Geth/%s/%s/%s\n", utils.Version, runtime.Version(), runtime.GOOS)
301-
302296
// Start up the node itself
303297
utils.StartNode(stack)
304298

@@ -379,7 +373,7 @@ func gpubench(ctx *cli.Context) error {
379373
}
380374

381375
func version(c *cli.Context) error {
382-
fmt.Println(clientIdentifier)
376+
fmt.Println(strings.Title(clientIdentifier))
383377
fmt.Println("Version:", utils.Version)
384378
if gitCommit != "" {
385379
fmt.Println("Git Commit:", gitCommit)

‎cmd/geth/monitorcmd.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ import (
3535
var (
3636
monitorCommandAttachFlag = cli.StringFlag{
3737
Name: "attach",
38-
Value: node.DefaultIPCEndpoint(),
38+
Value: node.DefaultIPCEndpoint(clientIdentifier),
3939
Usage: "API endpoint to attach to",
4040
}
4141
monitorCommandRowsFlag = cli.IntFlag{

‎cmd/gethrpctest/main.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ func MakeSystemNode(privkey string, test *tests.BlockTest) (*node.Node, error) {
8888
// Create a networkless protocol stack
8989
stack, err := node.New(&node.Config{
9090
UseLightweightKDF: true,
91-
IPCPath: node.DefaultIPCEndpoint(),
91+
IPCPath: node.DefaultIPCEndpoint(""),
9292
HTTPHost: common.DefaultHTTPHost,
9393
HTTPPort: common.DefaultHTTPPort,
9494
HTTPModules: []string{"admin", "db", "eth", "debug", "miner", "net", "shh", "txpool", "personal", "web3"},

‎cmd/utils/flags.go‎

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -396,13 +396,14 @@ var (
396396
}
397397
)
398398

399-
// MustMakeDataDir retrieves the currently requested data directory, terminating
399+
// MakeDataDir retrieves the currently requested data directory, terminating
400400
// if none (or the empty string) is specified. If the node is starting a testnet,
401401
// the a subdirectory of the specified datadir will be used.
402-
func MustMakeDataDir(ctx *cli.Context) string {
402+
func MakeDataDir(ctx *cli.Context) string {
403403
if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
404+
// TODO: choose a different location outside of the regular datadir.
404405
if ctx.GlobalBool(TestNetFlag.Name) {
405-
return filepath.Join(path, "/testnet")
406+
return filepath.Join(path, "testnet")
406407
}
407408
return path
408409
}
@@ -447,16 +448,16 @@ func MakeNodeKey(ctx *cli.Context) *ecdsa.PrivateKey {
447448
return key
448449
}
449450

450-
// MakeNodeName creates a node name from a base set and the command line flags.
451-
func MakeNodeName(client, version string, ctx *cli.Context) string {
452-
name := common.MakeName(client, version)
451+
// makeNodeUserIdent creates the user identifier from CLI flags.
452+
func makeNodeUserIdent(ctx *cli.Context) string {
453+
var comps []string
453454
if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
454-
name += "/" + identity
455+
comps = append(comps, identity)
455456
}
456457
if ctx.GlobalBool(VMEnableJitFlag.Name) {
457-
name += "/JIT"
458+
comps = append(comps, "JIT")
458459
}
459-
return name
460+
return strings.Join(comps, "/")
460461
}
461462

462463
// MakeBootstrapNodes creates a list of bootstrap nodes from the command line
@@ -612,11 +613,13 @@ func MakeNode(ctx *cli.Context, name, gitCommit string) *node.Node {
612613
}
613614

614615
config := &node.Config{
615-
DataDir: MustMakeDataDir(ctx),
616+
DataDir: MakeDataDir(ctx),
616617
KeyStoreDir: ctx.GlobalString(KeyStoreDirFlag.Name),
617618
UseLightweightKDF: ctx.GlobalBool(LightKDFFlag.Name),
618619
PrivateKey: MakeNodeKey(ctx),
619-
Name: MakeNodeName(name, vsn, ctx),
620+
Name: name,
621+
Version: vsn,
622+
UserIdent: makeNodeUserIdent(ctx),
620623
NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name),
621624
BootstrapNodes: MakeBootstrapNodes(ctx),
622625
ListenAddr: MakeListenAddress(ctx),
@@ -674,7 +677,7 @@ func RegisterEthService(ctx *cli.Context, stack *node.Node, extra []byte) {
674677

675678
ethConf := &eth.Config{
676679
Etherbase: MakeEtherbase(stack.AccountManager(), ctx),
677-
ChainConfig: MustMakeChainConfig(ctx),
680+
ChainConfig: MakeChainConfig(ctx, stack),
678681
FastSync: ctx.GlobalBool(FastSyncFlag.Name),
679682
DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
680683
DatabaseHandles: MakeDatabaseHandles(),
@@ -748,16 +751,16 @@ func SetupNetwork(ctx *cli.Context) {
748751
params.TargetGasLimit = common.String2Big(ctx.GlobalString(TargetGasLimitFlag.Name))
749752
}
750753

751-
// MustMakeChainConfig reads the chain configuration from the database in ctx.Datadir.
752-
func MustMakeChainConfig(ctx *cli.Context) *core.ChainConfig {
753-
db := MakeChainDatabase(ctx)
754+
// MakeChainConfig reads the chain configuration from the database in ctx.Datadir.
755+
func MakeChainConfig(ctx *cli.Context, stack *node.Node) *core.ChainConfig {
756+
db := MakeChainDatabase(ctx, stack)
754757
defer db.Close()
755758

756-
return MustMakeChainConfigFromDb(ctx, db)
759+
return MakeChainConfigFromDb(ctx, db)
757760
}
758761

759-
// MustMakeChainConfigFromDb reads the chain configuration from the given database.
760-
func MustMakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *core.ChainConfig {
762+
// MakeChainConfigFromDb reads the chain configuration from the given database.
763+
func MakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *core.ChainConfig {
761764
// If the chain is already initialized, use any existing chain configs
762765
config := new(core.ChainConfig)
763766

@@ -800,32 +803,31 @@ func MustMakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *core.ChainC
800803
}
801804

802805
// MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
803-
func MakeChainDatabase(ctx *cli.Context) ethdb.Database {
806+
func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
804807
var (
805-
datadir = MustMakeDataDir(ctx)
806808
cache = ctx.GlobalInt(CacheFlag.Name)
807809
handles = MakeDatabaseHandles()
808810
)
809811

810-
chainDb, err := ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache, handles)
812+
chainDb, err := stack.OpenDatabase("chaindata", cache, handles)
811813
if err != nil {
812814
Fatalf("Could not open database: %v", err)
813815
}
814816
return chainDb
815817
}
816818

817819
// MakeChain creates a chain manager from set command line flags.
818-
func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database) {
820+
func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
819821
var err error
820-
chainDb = MakeChainDatabase(ctx)
822+
chainDb = MakeChainDatabase(ctx, stack)
821823

822824
if ctx.GlobalBool(OlympicFlag.Name) {
823825
_, err := core.WriteTestNetGenesisBlock(chainDb)
824826
if err != nil {
825827
glog.Fatalln(err)
826828
}
827829
}
828-
chainConfig := MustMakeChainConfigFromDb(ctx, chainDb)
830+
chainConfig := MakeChainConfigFromDb(ctx, chainDb)
829831

830832
pow := pow.PoW(core.FakePow{})
831833
if !ctx.GlobalBool(FakePoWFlag.Name) {

‎node/api.go‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -85,16 +85,16 @@ func (api *PrivateAdminAPI) StartRPC(host *string, port *rpc.HexNumber, cors *st
8585

8686
if host == nil {
8787
h := common.DefaultHTTPHost
88-
if api.node.httpHost != "" {
89-
h = api.node.httpHost
88+
if api.node.config.HTTPHost != "" {
89+
h = api.node.config.HTTPHost
9090
}
9191
host = &h
9292
}
9393
if port == nil {
94-
port = rpc.NewHexNumber(api.node.httpPort)
94+
port = rpc.NewHexNumber(api.node.config.HTTPPort)
9595
}
9696
if cors == nil {
97-
cors = &api.node.httpCors
97+
cors = &api.node.config.HTTPCors
9898
}
9999

100100
modules := api.node.httpWhitelist
@@ -134,19 +134,19 @@ func (api *PrivateAdminAPI) StartWS(host *string, port *rpc.HexNumber, allowedOr
134134

135135
if host == nil {
136136
h := common.DefaultWSHost
137-
if api.node.wsHost != "" {
138-
h = api.node.wsHost
137+
if api.node.config.WSHost != "" {
138+
h = api.node.config.WSHost
139139
}
140140
host = &h
141141
}
142142
if port == nil {
143-
port = rpc.NewHexNumber(api.node.wsPort)
143+
port = rpc.NewHexNumber(api.node.config.WSPort)
144144
}
145145
if allowedOrigins == nil {
146-
allowedOrigins = &api.node.wsOrigins
146+
allowedOrigins = &api.node.config.WSOrigins
147147
}
148148

149-
modules := api.node.wsWhitelist
149+
modules := api.node.config.WSModules
150150
if apis != nil {
151151
modules = nil
152152
for _, m := range strings.Split(*apis, ",") {

0 commit comments

Comments
 (0)