Exemplo n.º 1
0
func upgradeDb(ctx *cli.Context) {
	fmt.Println("Upgrade blockchain DB")

	cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
	cfg.SkipBcVersionCheck = true

	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v\n", err)
	}

	v, _ := ethereum.BlockDb().Get([]byte("BlockchainVersion"))
	bcVersion := int(common.NewValue(v).Uint())

	if bcVersion == 0 {
		bcVersion = core.BlockChainVersion
	}

	filename := fmt.Sprintf("blockchain_%d_%s.chain", bcVersion, time.Now().Format("2006-01-02_15:04:05"))
	exportFile := path.Join(ctx.GlobalString(utils.DataDirFlag.Name), filename)

	err = utils.ExportChain(ethereum.ChainManager(), exportFile)
	if err != nil {
		utils.Fatalf("Unable to export chain for reimport %s\n", err)
	}

	ethereum.BlockDb().Close()
	ethereum.StateDb().Close()
	ethereum.ExtraDb().Close()

	os.RemoveAll(path.Join(ctx.GlobalString(utils.DataDirFlag.Name), "blockchain"))

	ethereum, err = eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v\n", err)
	}

	ethereum.BlockDb().Put([]byte("BlockchainVersion"), common.NewValue(core.BlockChainVersion).Bytes())

	err = utils.ImportChain(ethereum.ChainManager(), exportFile)
	if err != nil {
		utils.Fatalf("Import error %v (a backup is made in %s, use the import command to import it)\n", err, exportFile)
	}

	// force database flush
	ethereum.BlockDb().Close()
	ethereum.StateDb().Close()
	ethereum.ExtraDb().Close()

	os.Remove(exportFile)

	fmt.Println("Import finished")
}
Exemplo n.º 2
0
func runOneBlockTest(ctx *cli.Context, test *tests.BlockTest) (*eth.Ethereum, error) {
	cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
	db, _ := ethdb.NewMemDatabase()
	cfg.NewDB = func(path string) (ethdb.Database, error) { return db, nil }
	cfg.MaxPeers = 0 // disable network
	cfg.Shh = false  // disable whisper
	cfg.NAT = nil    // disable port mapping
	ethereum, err := eth.New(cfg)
	if err != nil {
		return nil, err
	}

	// import the genesis block
	ethereum.ResetWithGenesisBlock(test.Genesis)
	// import pre accounts
	_, err = test.InsertPreState(db, cfg.AccountManager)
	if err != nil {
		return ethereum, fmt.Errorf("InsertPreState: %v", err)
	}

	cm := ethereum.BlockChain()
	validBlocks, err := test.TryBlocksInsert(cm)
	if err != nil {
		return ethereum, fmt.Errorf("Block Test load error: %v", err)
	}
	newDB, err := cm.State()
	if err != nil {
		return ethereum, fmt.Errorf("Block Test get state error: %v", err)
	}
	if err := test.ValidatePostState(newDB); err != nil {
		return ethereum, fmt.Errorf("post state validation failed: %v", err)
	}
	return ethereum, test.ValidateImportedHeaders(cm, validBlocks)
}
Exemplo n.º 3
0
func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) {
	os.RemoveAll("/tmp/eth-natspec/")
	err = os.MkdirAll("/tmp/eth-natspec/keys/e273f01c99144c438695e10f24926dc1f9fbf62d/", os.ModePerm)
	if err != nil {
		t.Errorf("%v", err)
		return
	}
	err = os.MkdirAll("/tmp/eth-natspec/data", os.ModePerm)
	if err != nil {
		t.Errorf("%v", err)
		return
	}
	ks := crypto.NewKeyStorePlain("/tmp/eth-natspec/keys")
	ioutil.WriteFile("/tmp/eth-natspec/keys/e273f01c99144c438695e10f24926dc1f9fbf62d/e273f01c99144c438695e10f24926dc1f9fbf62d",
		[]byte(`{"Id":"RhRXD+fNRKS4jx+7ZfEsNA==","Address":"4nPwHJkUTEOGleEPJJJtwfn79i0=","PrivateKey":"h4ACVpe74uIvi5Cg/2tX/Yrm2xdr3J7QoMbMtNX2CNc="}`), os.ModePerm)

	port++
	ethereum, err = eth.New(&eth.Config{
		DataDir:        "/tmp/eth-natspec",
		AccountManager: accounts.NewManager(ks),
		Name:           "test",
	})

	if err != nil {
		t.Errorf("%v", err)
		return
	}

	return
}
func runBlockTest(test *BlockTest) error {
	cfg := test.makeEthConfig()
	cfg.GenesisBlock = test.Genesis

	ethereum, err := eth.New(cfg)
	if err != nil {
		return err
	}

	err = ethereum.Start()
	if err != nil {
		return err
	}

	// import pre accounts
	statedb, err := test.InsertPreState(ethereum)
	if err != nil {
		return fmt.Errorf("InsertPreState: %v", err)
	}

	err = test.TryBlocksInsert(ethereum.ChainManager())
	if err != nil {
		return err
	}

	if err = test.ValidatePostState(statedb); err != nil {
		return fmt.Errorf("post state validation failed: %v", err)
	}
	return nil
}
Exemplo n.º 5
0
func runBlockTest(name string, test *BlockTest, t *testing.T) {
	cfg := testEthConfig()
	ethereum, err := eth.New(cfg)
	if err != nil {
		t.Fatalf("%v", err)
	}

	err = ethereum.Start()
	if err != nil {
		t.Fatalf("%v", err)
	}

	// import the genesis block
	ethereum.ResetWithGenesisBlock(test.Genesis)

	// import pre accounts
	statedb, err := test.InsertPreState(ethereum)
	if err != nil {
		t.Fatalf("InsertPreState: %v", err)
	}

	err = test.TryBlocksInsert(ethereum.ChainManager())
	if err != nil {
		t.Fatal(err)
	}

	if err = test.ValidatePostState(statedb); err != nil {
		t.Fatal("post state validation failed: %v", err)
	}
	t.Log("Test passed: ", name)
}
Exemplo n.º 6
0
func NewEthereumApplication(ctx *cli.Context) *EthereumApplication {
	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	stateDB, err := ethereum.BlockChain().State()
	if err != nil {
		utils.Fatalf("%v", err)
	}

	ethApp := &EthereumApplication{
		ethereum: ethereum,
		stateDB:  stateDB,
		client:   client.NewClientURI(fmt.Sprintf("http://%s", ctx.String(TendermintCoreHostFlag.Name))),
	}

	// NOTE: RPC/IPC should only be enabled on local nodes
	if !ctx.GlobalBool(utils.IPCDisabledFlag.Name) {
		if err := ethApp.StartIPC(ctx); err != nil {
			utils.Fatalf("%v", err)
		}
	}

	if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
		if err := ethApp.StartRPC(ctx); err != nil {
			utils.Fatalf("%v", err)
		}
	}
	return ethApp
}
Exemplo n.º 7
0
func runOneBlockTest(ctx *cli.Context, test *tests.BlockTest) (*eth.Ethereum, error) {
	cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
	cfg.NewDB = func(path string) (common.Database, error) { return ethdb.NewMemDatabase() }
	cfg.MaxPeers = 0 // disable network
	cfg.Shh = false  // disable whisper
	cfg.NAT = nil    // disable port mapping

	ethereum, err := eth.New(cfg)
	if err != nil {
		return nil, err
	}
	// if err := ethereum.Start(); err != nil {
	// 	return nil, err
	// }

	// import the genesis block
	ethereum.ResetWithGenesisBlock(test.Genesis)

	// import pre accounts
	statedb, err := test.InsertPreState(ethereum)
	if err != nil {
		return ethereum, fmt.Errorf("InsertPreState: %v", err)
	}

	if err := test.TryBlocksInsert(ethereum.ChainManager()); err != nil {
		return ethereum, fmt.Errorf("Block Test load error: %v", err)
	}

	if err := test.ValidatePostState(statedb); err != nil {
		return ethereum, fmt.Errorf("post state validation failed: %v", err)
	}
	return ethereum, nil
}
Exemplo n.º 8
0
func console(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	client := comms.NewInProcClient(codec.JSON)

	startEth(ctx, ethereum)
	repl := newJSRE(
		ethereum,
		ctx.GlobalString(utils.JSpathFlag.Name),
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
		client,
		true,
		nil,
	)

	if ctx.GlobalString(utils.ExecFlag.Name) != "" {
		repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
	} else {
		repl.welcome()
		repl.interactive()
	}

	ethereum.Stop()
	ethereum.WaitForShutdown()
}
Exemplo n.º 9
0
func importchain(ctx *cli.Context) {
	if len(ctx.Args()) != 1 {
		utils.Fatalf("This command requires an argument.")
	}

	cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
	cfg.SkipBcVersionCheck = true

	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v\n", err)
	}

	chainmgr := ethereum.ChainManager()
	start := time.Now()
	err = utils.ImportChain(chainmgr, ctx.Args().First())
	if err != nil {
		utils.Fatalf("Import error: %v\n", err)
	}

	// force database flush
	ethereum.BlockDb().Close()
	ethereum.StateDb().Close()
	ethereum.ExtraDb().Close()

	fmt.Printf("Import done in %v", time.Since(start))

	return
}
Exemplo n.º 10
0
func execJSFiles(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	client := comms.NewInProcClient(codec.JSON)
	startEth(ctx, ethereum)
	repl := newJSRE(
		ethereum,
		ctx.GlobalString(utils.JSpathFlag.Name),
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
		client,
		false,
		nil,
	)
	for _, file := range ctx.Args() {
		repl.exec(file)
	}

	ethereum.Stop()
	ethereum.WaitForShutdown()
}
Exemplo n.º 11
0
func testREPL(t *testing.T, config func(*eth.Config)) (string, *testjethre, *node.Node) {
	tmp, err := ioutil.TempDir("", "geth-test")
	if err != nil {
		t.Fatal(err)
	}
	// Create a networkless protocol stack
	stack, err := node.New(&node.Config{DataDir: tmp, PrivateKey: testNodeKey, Name: "test", NoDiscovery: true})
	if err != nil {
		t.Fatalf("failed to create node: %v", err)
	}
	// Initialize and register the Ethereum protocol
	accman := accounts.NewPlaintextManager(filepath.Join(tmp, "keystore"))
	db, _ := ethdb.NewMemDatabase()
	core.WriteGenesisBlockForTesting(db, core.GenesisAccount{
		Address: common.HexToAddress(testAddress),
		Balance: common.String2Big(testBalance),
	})
	ethConf := &eth.Config{
		ChainConfig:      &core.ChainConfig{HomesteadBlock: new(big.Int)},
		TestGenesisState: db,
		AccountManager:   accman,
		DocRoot:          "/",
		SolcPath:         testSolcPath,
		PowTest:          true,
	}
	if config != nil {
		config(ethConf)
	}
	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
		return eth.New(ctx, ethConf)
	}); err != nil {
		t.Fatalf("failed to register ethereum protocol: %v", err)
	}
	// Initialize all the keys for testing
	a, err := accman.ImportECDSA(testAccount, "")
	if err != nil {
		t.Fatal(err)
	}
	if err := accman.Unlock(a, ""); err != nil {
		t.Fatal(err)
	}
	// Start the node and assemble the REPL tester
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start test stack: %v", err)
	}
	var ethereum *eth.Ethereum
	stack.Service(&ethereum)

	assetPath := filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
	client, err := stack.Attach()
	if err != nil {
		t.Fatalf("failed to attach to node: %v", err)
	}
	tf := &testjethre{client: ethereum.HTTPClient()}
	repl := newJSRE(stack, assetPath, "", client, false)
	tf.jsre = repl
	return tmp, tf, stack
}
Exemplo n.º 12
0
func run(ctx *cli.Context) {
	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	startEth(ctx, ethereum)
	// this blocks the thread
	ethereum.WaitForShutdown()
}
Exemplo n.º 13
0
func runBlockTest(test *BlockTest) error {
	ks := crypto.NewKeyStorePassphrase(filepath.Join(common.DefaultDataDir(), "keystore"), crypto.StandardScryptN, crypto.StandardScryptP)
	am := accounts.NewManager(ks)
	db, _ := ethdb.NewMemDatabase()
	cfg := &eth.Config{
		DataDir:        common.DefaultDataDir(),
		Verbosity:      5,
		Etherbase:      common.Address{},
		AccountManager: am,
		NewDB:          func(path string) (ethdb.Database, error) { return db, nil },
	}

	cfg.GenesisBlock = test.Genesis

	// import pre accounts & construct test genesis block & state root
	_, err := test.InsertPreState(db, am)
	if err != nil {
		return fmt.Errorf("InsertPreState: %v", err)
	}

	ethereum, err := eth.New(cfg)
	if err != nil {
		return err
	}

	err = ethereum.Start()
	if err != nil {
		return err
	}

	cm := ethereum.BlockChain()
	validBlocks, err := test.TryBlocksInsert(cm)
	if err != nil {
		return err
	}

	lastblockhash := common.HexToHash(test.lastblockhash)
	cmlast := cm.LastBlockHash()
	if lastblockhash != cmlast {
		return fmt.Errorf("lastblockhash validation mismatch: want: %x, have: %x", lastblockhash, cmlast)
	}

	newDB, err := cm.State()
	if err != nil {
		return err
	}
	if err = test.ValidatePostState(newDB); err != nil {
		return fmt.Errorf("post state validation failed: %v", err)
	}

	return test.ValidateImportedHeaders(cm, validBlocks)
}
Exemplo n.º 14
0
func testREPL(t *testing.T, config func(*eth.Config)) (string, *testjethre, *eth.Ethereum) {
	tmp, err := ioutil.TempDir("", "geth-test")
	if err != nil {
		t.Fatal(err)
	}

	db, _ := ethdb.NewMemDatabase()

	core.WriteGenesisBlockForTesting(db, core.GenesisAccount{common.HexToAddress(testAddress), common.String2Big(testBalance)})
	ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore"))
	am := accounts.NewManager(ks)
	conf := &eth.Config{
		NodeKey:        testNodeKey,
		DataDir:        tmp,
		AccountManager: am,
		MaxPeers:       0,
		Name:           "test",
		SolcPath:       testSolcPath,
		PowTest:        true,
		NewDB:          func(path string) (ethdb.Database, error) { return db, nil },
	}
	if config != nil {
		config(conf)
	}
	ethereum, err := eth.New(conf)
	if err != nil {
		t.Fatal("%v", err)
	}

	keyb, err := crypto.HexToECDSA(testKey)
	if err != nil {
		t.Fatal(err)
	}
	key := crypto.NewKeyFromECDSA(keyb)
	err = ks.StoreKey(key, "")
	if err != nil {
		t.Fatal(err)
	}

	err = am.Unlock(key.Address, "")
	if err != nil {
		t.Fatal(err)
	}

	assetPath := filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
	client := comms.NewInProcClient(codec.JSON)
	ds := docserver.New("/")
	tf := &testjethre{ds: ds}
	repl := newJSRE(ethereum, assetPath, "", client, false, tf)
	tf.jsre = repl
	return tmp, tf, ethereum
}
Exemplo n.º 15
0
func run(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	startEth(ctx, ethereum)
	// this blocks the thread
	ethereum.WaitForShutdown()
}
Exemplo n.º 16
0
func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
	tmp, err := ioutil.TempDir("", "geth-test")
	if err != nil {
		t.Fatal(err)
	}

	// set up mock genesis with balance on the testAddress
	core.GenesisAccounts = []byte(testGenesis)

	ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore"))
	am := accounts.NewManager(ks)
	ethereum, err := eth.New(&eth.Config{
		NodeKey:        testNodeKey,
		DataDir:        tmp,
		AccountManager: am,
		MaxPeers:       0,
		Name:           "test",
		SolcPath:       testSolcPath,
	})
	if err != nil {
		t.Fatal("%v", err)
	}

	keyb, err := crypto.HexToECDSA(testKey)
	if err != nil {
		t.Fatal(err)
	}
	key := crypto.NewKeyFromECDSA(keyb)
	err = ks.StoreKey(key, "")
	if err != nil {
		t.Fatal(err)
	}

	err = am.Unlock(key.Address, "")
	if err != nil {
		t.Fatal(err)
	}

	assetPath := filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
	ds, err := docserver.New("/")
	if err != nil {
		t.Errorf("Error creating DocServer: %v", err)
	}
	tf := &testjethre{ds: ds, stateDb: ethereum.ChainManager().State().Copy()}
	client := comms.NewInProcClient(codec.JSON)
	repl := newJSRE(ethereum, assetPath, "", client, false, tf)
	tf.jsre = repl
	return tmp, tf, ethereum
}
Exemplo n.º 17
0
func run(ctx *cli.Context) {
	utils.CheckLegalese(utils.MustDataDir(ctx))

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	cfg.ExtraData = makeExtra(ctx)

	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	startEth(ctx, ethereum)
	// this blocks the thread
	ethereum.WaitForShutdown()
}
Exemplo n.º 18
0
func execJSFiles(ctx *cli.Context) {
	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	startEth(ctx, ethereum)
	repl := newJSRE(ethereum, ctx.String(utils.JSpathFlag.Name), false, ctx.GlobalString(utils.RPCCORSDomainFlag.Name))
	for _, file := range ctx.Args() {
		repl.exec(file)
	}

	ethereum.Stop()
	ethereum.WaitForShutdown()
}
Exemplo n.º 19
0
func run(ctx *cli.Context) {
	importer := NewImporter(ctx)
	utils.HandleInterrupt()

	cfg := utils.MakeEthConfig("EthChainParser", Version, ctx)

	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}
	utils.StartEthereum(ethereum)

	if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
		utils.StartRPC(ethereum, ctx)
	}

	events := ethereum.EventMux().Subscribe(
		core.ChainEvent{},
		core.TxPreEvent{},
	)

	defer events.Unsubscribe()
	for {
		select {
		case ev, isopen := <-events.Chan():
			if !isopen {
				return
			}
			switch ev := ev.(type) {
			case core.ChainEvent:
				importer.importBlock(ev.Block)
			case core.TxPreEvent:
				// Not dealing with incoming txes for now
				//importer.importTx(ev.Tx)
			}
		}
	}

	ethereum.WaitForShutdown()
	logger.Flush()
	fmt.Printf("Shutting down\n")
}
Exemplo n.º 20
0
func testJEthRE(t *testing.T) (*jsre, *eth.Ethereum) {
	tmp, err := ioutil.TempDir("", "geth-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmp)

	ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keys"))
	ethereum, err := eth.New(&eth.Config{
		DataDir:        tmp,
		AccountManager: accounts.NewManager(ks),
		MaxPeers:       0,
		Name:           "test",
	})
	if err != nil {
		t.Fatal("%v", err)
	}
	assetPath := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
	repl := newJSRE(ethereum, assetPath, false, "")
	return repl, ethereum
}
Exemplo n.º 21
0
func exportchain(ctx *cli.Context) {
	if len(ctx.Args()) != 1 {
		utils.Fatalf("This command requires an argument.")
	}

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	cfg.SkipBcVersionCheck = true

	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v\n", err)
	}

	chainmgr := ethereum.ChainManager()
	start := time.Now()
	err = utils.ExportChain(chainmgr, ctx.Args().First())
	if err != nil {
		utils.Fatalf("Export error: %v\n", err)
	}
	fmt.Printf("Export done in %v", time.Since(start))
	return
}
Exemplo n.º 22
0
func runBlockTest(test *BlockTest) error {
	cfg := test.makeEthConfig()
	cfg.GenesisBlock = test.Genesis

	ethereum, err := eth.New(cfg)
	if err != nil {
		return err
	}

	err = ethereum.Start()
	if err != nil {
		return err
	}

	// import pre accounts
	_, err = test.InsertPreState(ethereum)
	if err != nil {
		return fmt.Errorf("InsertPreState: %v", err)
	}

	cm := ethereum.ChainManager()
	validBlocks, err := test.TryBlocksInsert(cm)
	if err != nil {
		return err
	}

	lastblockhash := common.HexToHash(test.lastblockhash)
	cmlast := cm.LastBlockHash()
	if lastblockhash != cmlast {
		return fmt.Errorf("lastblockhash validation mismatch: want: %x, have: %x", lastblockhash, cmlast)
	}

	newDB := cm.State()
	if err = test.ValidatePostState(newDB); err != nil {
		return fmt.Errorf("post state validation failed: %v", err)
	}

	return test.ValidateImportedHeaders(cm, validBlocks)
}
Exemplo n.º 23
0
func console(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	// Wrap the standard output with a colorified stream (windows)
	if isatty.IsTerminal(os.Stdout.Fd()) {
		if pr, pw, err := os.Pipe(); err == nil {
			go io.Copy(colorable.NewColorableStdout(), pr)
			os.Stdout = pw
		}
	}

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	client := comms.NewInProcClient(codec.JSON)

	startEth(ctx, ethereum)
	repl := newJSRE(
		ethereum,
		ctx.GlobalString(utils.JSpathFlag.Name),
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
		client,
		true,
		nil,
	)

	if ctx.GlobalString(utils.ExecFlag.Name) != "" {
		repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
	} else {
		repl.welcome()
		repl.interactive()
	}

	ethereum.Stop()
	ethereum.WaitForShutdown()
}
Exemplo n.º 24
0
func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) {

	os.RemoveAll("/tmp/eth-natspec/")

	err = os.MkdirAll("/tmp/eth-natspec/keystore", os.ModePerm)
	if err != nil {
		panic(err)
	}

	// create a testAddress
	ks := crypto.NewKeyStorePassphrase("/tmp/eth-natspec/keystore")
	am := accounts.NewManager(ks)
	testAccount, err := am.NewAccount("password")
	if err != nil {
		panic(err)
	}

	testAddress := strings.TrimPrefix(testAccount.Address.Hex(), "0x")

	db, _ := ethdb.NewMemDatabase()
	// set up mock genesis with balance on the testAddress
	core.WriteGenesisBlockForTesting(db, core.GenesisAccount{common.HexToAddress(testAddress), common.String2Big(testBalance)})

	// only use minimalistic stack with no networking
	ethereum, err = eth.New(&eth.Config{
		DataDir:        "/tmp/eth-natspec",
		AccountManager: am,
		MaxPeers:       0,
		PowTest:        true,
		Etherbase:      common.HexToAddress(testAddress),
		NewDB:          func(path string) (ethdb.Database, error) { return db, nil },
	})

	if err != nil {
		panic(err)
	}

	return
}
Exemplo n.º 25
0
func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) {

	tmp, err := ioutil.TempDir("", "natspec-test")
	if err != nil {
		t.Fatal(err)
	}
	db, _ := ethdb.NewMemDatabase()
	addr := common.HexToAddress(testAddress)
	core.WriteGenesisBlockForTesting(db, core.GenesisAccount{addr, common.String2Big(testBalance)})
	ks := crypto.NewKeyStorePassphrase(filepath.Join(tmp, "keystore"), crypto.LightScryptN, crypto.LightScryptP)
	am := accounts.NewManager(ks)
	keyb, err := crypto.HexToECDSA(testKey)
	if err != nil {
		t.Fatal(err)
	}
	key := crypto.NewKeyFromECDSA(keyb)
	err = ks.StoreKey(key, "")
	if err != nil {
		t.Fatal(err)
	}

	err = am.Unlock(key.Address, "")
	if err != nil {
		t.Fatal(err)
	}

	// only use minimalistic stack with no networking
	return eth.New(&eth.Config{
		DataDir:                 tmp,
		AccountManager:          am,
		Etherbase:               common.HexToAddress(testAddress),
		MaxPeers:                0,
		PowTest:                 true,
		NewDB:                   func(path string) (ethdb.Database, error) { return db, nil },
		GpoMinGasPrice:          common.Big1,
		GpobaseCorrectionFactor: 1,
		GpoMaxGasPrice:          common.Big1,
	})
}
Exemplo n.º 26
0
func console(ctx *cli.Context) {
	// Wrap the standard output with a colorified stream (windows)
	if isatty.IsTerminal(os.Stdout.Fd()) {
		if pr, pw, err := os.Pipe(); err == nil {
			go io.Copy(colorable.NewColorableStdout(), pr)
			os.Stdout = pw
		}
	}

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	startEth(ctx, ethereum)
	repl := newJSRE(ethereum, ctx.String(utils.JSpathFlag.Name), true, ctx.GlobalString(utils.RPCCORSDomainFlag.Name))
	repl.interactive()

	ethereum.Stop()
	ethereum.WaitForShutdown()
}
Exemplo n.º 27
0
func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) {

	os.RemoveAll("/tmp/eth-natspec/")

	err = os.MkdirAll("/tmp/eth-natspec/keystore", os.ModePerm)
	if err != nil {
		panic(err)
	}

	// create a testAddress
	ks := crypto.NewKeyStorePassphrase("/tmp/eth-natspec/keystore")
	am := accounts.NewManager(ks)
	testAccount, err := am.NewAccount("password")
	if err != nil {
		panic(err)
	}
	testAddress := strings.TrimPrefix(testAccount.Address.Hex(), "0x")

	// set up mock genesis with balance on the testAddress
	core.GenesisAccounts = []byte(`{
	"` + testAddress + `": {"balance": "` + testBalance + `"}
	}`)

	// only use minimalistic stack with no networking
	ethereum, err = eth.New(&eth.Config{
		DataDir:        "/tmp/eth-natspec",
		AccountManager: am,
		MaxPeers:       0,
		PowTest:        true,
		Etherbase:      common.HexToAddress(testAddress),
	})

	if err != nil {
		panic(err)
	}

	return
}
Exemplo n.º 28
0
func run(ctx *cli.Context) {
	tstart := time.Now()

	// TODO: show qml popup instead of exiting if initialization fails.
	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	cfg.Shh = true
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}
	utils.StartRPC(ethereum, ctx)
	go utils.StartEthereum(ethereum)
	fmt.Println("initializing eth stack took", time.Since(tstart))

	// Open the window
	qml.Run(func() error {
		webengine.Initialize()
		gui := NewWindow(ethereum)
		utils.RegisterInterrupt(func(os.Signal) { gui.Stop() })
		// gui blocks the main thread
		gui.Start(ctx.GlobalString(assetPathFlag.Name), ctx.GlobalString(utils.JSpathFlag.Name))
		return nil
	})
}
Exemplo n.º 29
0
// MakeSystemNode sets up a local node, configures the services to launch and
// assembles the P2P protocol stack.
func MakeSystemNode(name, version string, relconf release.Config, extra []byte, ctx *cli.Context) *node.Node {
	// Avoid conflicting network flags
	networks, netFlags := 0, []cli.BoolFlag{DevModeFlag, TestNetFlag, OlympicFlag}
	for _, flag := range netFlags {
		if ctx.GlobalBool(flag.Name) {
			networks++
		}
	}
	if networks > 1 {
		Fatalf("The %v flags are mutually exclusive", netFlags)
	}
	// Configure the node's service container
	stackConf := &node.Config{
		DataDir:         MustMakeDataDir(ctx),
		PrivateKey:      MakeNodeKey(ctx),
		Name:            MakeNodeName(name, version, ctx),
		NoDiscovery:     ctx.GlobalBool(NoDiscoverFlag.Name),
		BootstrapNodes:  MakeBootstrapNodes(ctx),
		ListenAddr:      MakeListenAddress(ctx),
		NAT:             MakeNAT(ctx),
		MaxPeers:        ctx.GlobalInt(MaxPeersFlag.Name),
		MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
		IPCPath:         MakeIPCPath(ctx),
		HTTPHost:        MakeHTTPRpcHost(ctx),
		HTTPPort:        ctx.GlobalInt(RPCPortFlag.Name),
		HTTPCors:        ctx.GlobalString(RPCCORSDomainFlag.Name),
		HTTPModules:     MakeRPCModules(ctx.GlobalString(RPCApiFlag.Name)),
		WSHost:          MakeWSRpcHost(ctx),
		WSPort:          ctx.GlobalInt(WSPortFlag.Name),
		WSOrigins:       ctx.GlobalString(WSAllowedOriginsFlag.Name),
		WSModules:       MakeRPCModules(ctx.GlobalString(WSApiFlag.Name)),
	}
	// Configure the Ethereum service
	accman := MakeAccountManager(ctx)

	// initialise new random number generator
	rand := rand.New(rand.NewSource(time.Now().UnixNano()))
	// get enabled jit flag
	jitEnabled := ctx.GlobalBool(VMEnableJitFlag.Name)
	// if the jit is not enabled enable it for 10 pct of the people
	if !jitEnabled && rand.Float64() < 0.1 {
		jitEnabled = true
		glog.V(logger.Info).Infoln("You're one of the lucky few that will try out the JIT VM (random). If you get a consensus failure please be so kind to report this incident with the block hash that failed. You can switch to the regular VM by setting --jitvm=false")
	}

	ethConf := &eth.Config{
		ChainConfig:             MustMakeChainConfig(ctx),
		Genesis:                 MakeGenesisBlock(ctx),
		FastSync:                ctx.GlobalBool(FastSyncFlag.Name),
		BlockChainVersion:       ctx.GlobalInt(BlockchainVersionFlag.Name),
		DatabaseCache:           ctx.GlobalInt(CacheFlag.Name),
		DatabaseHandles:         MakeDatabaseHandles(),
		NetworkId:               ctx.GlobalInt(NetworkIdFlag.Name),
		AccountManager:          accman,
		Etherbase:               MakeEtherbase(accman, ctx),
		MinerThreads:            ctx.GlobalInt(MinerThreadsFlag.Name),
		ExtraData:               MakeMinerExtra(extra, ctx),
		NatSpec:                 ctx.GlobalBool(NatspecEnabledFlag.Name),
		DocRoot:                 ctx.GlobalString(DocRootFlag.Name),
		EnableJit:               jitEnabled,
		ForceJit:                ctx.GlobalBool(VMForceJitFlag.Name),
		GasPrice:                common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
		GpoMinGasPrice:          common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
		GpoMaxGasPrice:          common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
		GpoFullBlockRatio:       ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
		GpobaseStepDown:         ctx.GlobalInt(GpobaseStepDownFlag.Name),
		GpobaseStepUp:           ctx.GlobalInt(GpobaseStepUpFlag.Name),
		GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
		SolcPath:                ctx.GlobalString(SolcPathFlag.Name),
		AutoDAG:                 ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
	}
	// Configure the Whisper service
	shhEnable := ctx.GlobalBool(WhisperEnabledFlag.Name)

	// Override any default configs in dev mode or the test net
	switch {
	case ctx.GlobalBool(OlympicFlag.Name):
		if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
			ethConf.NetworkId = 1
		}
		if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
			ethConf.Genesis = core.OlympicGenesisBlock()
		}

	case ctx.GlobalBool(TestNetFlag.Name):
		if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
			ethConf.NetworkId = 2
		}
		if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
			ethConf.Genesis = core.TestNetGenesisBlock()
		}
		state.StartingNonce = 1048576 // (2**20)

	case ctx.GlobalBool(DevModeFlag.Name):
		// Override the base network stack configs
		if !ctx.GlobalIsSet(DataDirFlag.Name) {
			stackConf.DataDir = filepath.Join(os.TempDir(), "/ethereum_dev_mode")
		}
		if !ctx.GlobalIsSet(MaxPeersFlag.Name) {
			stackConf.MaxPeers = 0
		}
		if !ctx.GlobalIsSet(ListenPortFlag.Name) {
			stackConf.ListenAddr = ":0"
		}
		// Override the Ethereum protocol configs
		if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
			ethConf.Genesis = core.OlympicGenesisBlock()
		}
		if !ctx.GlobalIsSet(GasPriceFlag.Name) {
			ethConf.GasPrice = new(big.Int)
		}
		if !ctx.GlobalIsSet(WhisperEnabledFlag.Name) {
			shhEnable = true
		}
		ethConf.PowTest = true
	}
	// Assemble and return the protocol stack
	stack, err := node.New(stackConf)
	if err != nil {
		Fatalf("Failed to create the protocol stack: %v", err)
	}
	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
		return eth.New(ctx, ethConf)
	}); err != nil {
		Fatalf("Failed to register the Ethereum service: %v", err)
	}
	if shhEnable {
		if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
			Fatalf("Failed to register the Whisper service: %v", err)
		}
	}
	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
		return release.NewReleaseService(ctx, relconf)
	}); err != nil {
		Fatalf("Failed to register the Geth release oracle service: %v", err)
	}
	return stack
}
Exemplo n.º 30
0
// New creates a Ethereum client, pre-configured to one of the supported networks.
func New(datadir string, network EthereumNetwork) (*Geth, error) {
	// Tag the data dir with the network name
	switch network {
	case MainNet:
		datadir = filepath.Join(datadir, "mainnet")
	case TestNet:
		datadir = filepath.Join(datadir, "testnet")
	default:
		return nil, fmt.Errorf("unsupported network: %v", network)
	}
	// Select the bootstrap nodes based on the network
	bootnodes := utils.FrontierBootNodes
	if network == TestNet {
		bootnodes = utils.TestNetBootNodes
	}
	// Configure the node's service container
	stackConf := &node.Config{
		DataDir:        datadir,
		IPCPath:        "geth.ipc",
		Name:           common.MakeName(NodeName, NodeVersion),
		BootstrapNodes: bootnodes,
		ListenAddr:     fmt.Sprintf(":%d", NodePort),
		MaxPeers:       NodeMaxPeers,
	}
	// Configure the bare-bone Ethereum service
	ethConf := &eth.Config{
		ChainConfig:    &core.ChainConfig{HomesteadBlock: params.MainNetHomesteadBlock},
		FastSync:       true,
		DatabaseCache:  64,
		NetworkId:      int(network),
		AccountManager: accounts.NewManager(filepath.Join(datadir, "keystore"), accounts.StandardScryptN, accounts.StandardScryptP),

		// Blatantly initialize the gas oracle to the defaults from go-ethereum
		GpoMinGasPrice:          new(big.Int).Mul(big.NewInt(50), common.Shannon),
		GpoMaxGasPrice:          new(big.Int).Mul(big.NewInt(500), common.Shannon),
		GpoFullBlockRatio:       80,
		GpobaseStepDown:         10,
		GpobaseStepUp:           100,
		GpobaseCorrectionFactor: 110,
	}
	// Override any default configs in the test network
	if network == TestNet {
		ethConf.NetworkId = 2
		ethConf.Genesis = core.TestNetGenesisBlock()
		state.StartingNonce = 1048576 // (2**20)
		ethConf.ChainConfig.HomesteadBlock = params.TestNetHomesteadBlock
	}
	// Assemble and return the protocol stack
	stack, err := node.New(stackConf)
	if err != nil {
		return nil, fmt.Errorf("protocol stack: %v", err)
	}
	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
		return nil, fmt.Errorf("ethereum service: %v", err)
	}
	return &Geth{stack: stack}, nil
}