Merge pull request #2909 from fjl/account-manager-cleanup

all: clean up tech debt left behind by the API split
This commit is contained in:
Felix Lange 2016-08-17 20:59:59 +02:00 committed by GitHub
commit 475521dd74
22 changed files with 463 additions and 497 deletions

View File

@ -34,8 +34,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rpc"
) )
var ( var (
@ -342,23 +340,3 @@ func zeroKey(k *ecdsa.PrivateKey) {
b[i] = 0 b[i] = 0
} }
} }
// APIs implements node.Service
func (am *Manager) APIs() []rpc.API {
return nil
}
// Protocols implements node.Service
func (am *Manager) Protocols() []p2p.Protocol {
return nil
}
// Start implements node.Service
func (am *Manager) Start(srvr *p2p.Server) error {
return nil
}
// Stop implements node.Service
func (am *Manager) Stop() error {
return nil
}

View File

@ -68,18 +68,7 @@ func main() {
for _, kind := range strings.Split(*excFlag, ",") { for _, kind := range strings.Split(*excFlag, ",") {
exclude[strings.ToLower(kind)] = true exclude[strings.ToLower(kind)] = true
} }
// Build the Solidity source into bindable components contracts, err := compiler.CompileSolidity(*solcFlag, *solFlag)
solc, err := compiler.New(*solcFlag)
if err != nil {
fmt.Printf("Failed to locate Solidity compiler: %v\n", err)
os.Exit(-1)
}
source, err := ioutil.ReadFile(*solFlag)
if err != nil {
fmt.Printf("Failed to read Soldity source code: %v\n", err)
os.Exit(-1)
}
contracts, err := solc.Compile(string(source))
if err != nil { if err != nil {
fmt.Printf("Failed to build Solidity contract: %v\n", err) fmt.Printf("Failed to build Solidity contract: %v\n", err)
os.Exit(-1) os.Exit(-1)

View File

@ -168,8 +168,8 @@ nodes.
) )
func accountList(ctx *cli.Context) error { func accountList(ctx *cli.Context) error {
accman := utils.MakeAccountManager(ctx) stack := utils.MakeNode(ctx, clientIdentifier, verString)
for i, acct := range accman.Accounts() { for i, acct := range stack.AccountManager().Accounts() {
fmt.Printf("Account #%d: {%x} %s\n", i, acct.Address, acct.File) fmt.Printf("Account #%d: {%x} %s\n", i, acct.Address, acct.File)
} }
return nil return nil
@ -261,10 +261,10 @@ func ambiguousAddrRecovery(am *accounts.Manager, err *accounts.AmbiguousAddrErro
// accountCreate creates a new account into the keystore defined by the CLI flags. // accountCreate creates a new account into the keystore defined by the CLI flags.
func accountCreate(ctx *cli.Context) error { func accountCreate(ctx *cli.Context) error {
accman := utils.MakeAccountManager(ctx) stack := utils.MakeNode(ctx, clientIdentifier, verString)
password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx)) password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
account, err := accman.NewAccount(password) account, err := stack.AccountManager().NewAccount(password)
if err != nil { if err != nil {
utils.Fatalf("Failed to create account: %v", err) utils.Fatalf("Failed to create account: %v", err)
} }
@ -278,11 +278,10 @@ func accountUpdate(ctx *cli.Context) error {
if len(ctx.Args()) == 0 { if len(ctx.Args()) == 0 {
utils.Fatalf("No accounts specified to update") utils.Fatalf("No accounts specified to update")
} }
accman := utils.MakeAccountManager(ctx) stack := utils.MakeNode(ctx, clientIdentifier, verString)
account, oldPassword := unlockAccount(ctx, stack.AccountManager(), ctx.Args().First(), 0, nil)
account, oldPassword := unlockAccount(ctx, accman, ctx.Args().First(), 0, nil)
newPassword := getPassPhrase("Please give a new password. Do not forget this password.", true, 0, nil) newPassword := getPassPhrase("Please give a new password. Do not forget this password.", true, 0, nil)
if err := accman.Update(account, oldPassword, newPassword); err != nil { if err := stack.AccountManager().Update(account, oldPassword, newPassword); err != nil {
utils.Fatalf("Could not update the account: %v", err) utils.Fatalf("Could not update the account: %v", err)
} }
return nil return nil
@ -298,10 +297,9 @@ func importWallet(ctx *cli.Context) error {
utils.Fatalf("Could not read wallet file: %v", err) utils.Fatalf("Could not read wallet file: %v", err)
} }
accman := utils.MakeAccountManager(ctx) stack := utils.MakeNode(ctx, clientIdentifier, verString)
passphrase := getPassPhrase("", false, 0, utils.MakePasswordList(ctx)) passphrase := getPassPhrase("", false, 0, utils.MakePasswordList(ctx))
acct, err := stack.AccountManager().ImportPreSaleKey(keyJson, passphrase)
acct, err := accman.ImportPreSaleKey(keyJson, passphrase)
if err != nil { if err != nil {
utils.Fatalf("%v", err) utils.Fatalf("%v", err)
} }
@ -318,9 +316,9 @@ func accountImport(ctx *cli.Context) error {
if err != nil { if err != nil {
utils.Fatalf("Failed to load the private key: %v", err) utils.Fatalf("Failed to load the private key: %v", err)
} }
accman := utils.MakeAccountManager(ctx) stack := utils.MakeNode(ctx, clientIdentifier, verString)
passphrase := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx)) passphrase := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
acct, err := accman.ImportECDSA(key, passphrase) acct, err := stack.AccountManager().ImportECDSA(key, passphrase)
if err != nil { if err != nil {
utils.Fatalf("Could not create the account: %v", err) utils.Fatalf("Could not create the account: %v", err)
} }

View File

@ -65,7 +65,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
// same time. // same time.
func localConsole(ctx *cli.Context) error { func localConsole(ctx *cli.Context) error {
// Create and start the node based on the CLI flags // Create and start the node based on the CLI flags
node := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx) node := makeFullNode(ctx)
startNode(ctx, node) startNode(ctx, node)
defer node.Stop() defer node.Stop()
@ -149,7 +149,7 @@ func dialRPC(endpoint string) (*rpc.Client, error) {
// everything down. // everything down.
func ephemeralConsole(ctx *cli.Context) error { func ephemeralConsole(ctx *cli.Context) error {
// Create and start the node based on the CLI flags // Create and start the node based on the CLI flags
node := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx) node := makeFullNode(ctx)
startNode(ctx, node) startNode(ctx, node)
defer node.Stop() defer node.Stop()

View File

@ -29,7 +29,6 @@ import (
"time" "time"
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/console" "github.com/ethereum/go-ethereum/console"
@ -244,34 +243,13 @@ func main() {
} }
} }
func makeDefaultExtra() []byte {
var clientInfo = struct {
Version uint
Name string
GoVersion string
Os string
}{uint(versionMajor<<16 | versionMinor<<8 | versionPatch), clientIdentifier, runtime.Version(), runtime.GOOS}
extra, err := rlp.EncodeToBytes(clientInfo)
if err != nil {
glog.V(logger.Warn).Infoln("error setting canonical miner information:", err)
}
if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
glog.V(logger.Warn).Infoln("error setting canonical miner information: extra exceeds", params.MaximumExtraDataSize)
glog.V(logger.Debug).Infof("extra: %x\n", extra)
return nil
}
return extra
}
// geth is the main entry point into the system if no special subcommand is ran. // geth is the main entry point into the system if no special subcommand is ran.
// It creates a default node based on the command line arguments and runs it in // It creates a default node based on the command line arguments and runs it in
// blocking mode, waiting for it to be shut down. // blocking mode, waiting for it to be shut down.
func geth(ctx *cli.Context) error { func geth(ctx *cli.Context) error {
node := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx) node := makeFullNode(ctx)
startNode(ctx, node) startNode(ctx, node)
node.Wait() node.Wait()
return nil return nil
} }
@ -301,6 +279,38 @@ func initGenesis(ctx *cli.Context) error {
return nil return nil
} }
func makeFullNode(ctx *cli.Context) *node.Node {
node := utils.MakeNode(ctx, clientIdentifier, verString)
utils.RegisterEthService(ctx, node, relConfig, makeDefaultExtra())
// Whisper must be explicitly enabled, but is auto-enabled in --dev mode.
shhEnabled := ctx.GlobalBool(utils.WhisperEnabledFlag.Name)
shhAutoEnabled := !ctx.GlobalIsSet(utils.WhisperEnabledFlag.Name) && ctx.GlobalIsSet(utils.DevModeFlag.Name)
if shhEnabled || shhAutoEnabled {
utils.RegisterShhService(node)
}
return node
}
func makeDefaultExtra() []byte {
var clientInfo = struct {
Version uint
Name string
GoVersion string
Os string
}{uint(versionMajor<<16 | versionMinor<<8 | versionPatch), clientIdentifier, runtime.Version(), runtime.GOOS}
extra, err := rlp.EncodeToBytes(clientInfo)
if err != nil {
glog.V(logger.Warn).Infoln("error setting canonical miner information:", err)
}
if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
glog.V(logger.Warn).Infoln("error setting canonical miner information: extra exceeds", params.MaximumExtraDataSize)
glog.V(logger.Debug).Infof("extra: %x\n", extra)
return nil
}
return extra
}
// startNode boots up the system node and all registered protocols, after which // startNode boots up the system node and all registered protocols, after which
// it unlocks any requested accounts, and starts the RPC/IPC interfaces and the // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
// miner. // miner.
@ -311,12 +321,8 @@ func startNode(ctx *cli.Context, stack *node.Node) {
utils.StartNode(stack) utils.StartNode(stack)
// Unlock any account specifically requested // Unlock any account specifically requested
var accman *accounts.Manager accman := stack.AccountManager()
if err := stack.Service(&accman); err != nil {
utils.Fatalf("ethereum service not running: %v", err)
}
passwords := utils.MakePasswordList(ctx) passwords := utils.MakePasswordList(ctx)
accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
for i, account := range accounts { for i, account := range accounts {
if trimmed := strings.TrimSpace(account); trimmed != "" { if trimmed := strings.TrimSpace(account); trimmed != "" {

View File

@ -19,12 +19,10 @@ package main
import ( import (
"flag" "flag"
"io/ioutil"
"log" "log"
"os" "os"
"os/signal" "os/signal"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
@ -61,14 +59,8 @@ func main() {
if !found { if !found {
log.Fatalf("Requested test (%s) not found within suite", *testName) log.Fatalf("Requested test (%s) not found within suite", *testName)
} }
// Create the protocol stack to run the test with
keydir, err := ioutil.TempDir("", "")
if err != nil {
log.Fatalf("Failed to create temporary keystore directory: %v", err)
}
defer os.RemoveAll(keydir)
stack, err := MakeSystemNode(keydir, *testKey, test) stack, err := MakeSystemNode(*testKey, test)
if err != nil { if err != nil {
log.Fatalf("Failed to assemble test stack: %v", err) log.Fatalf("Failed to assemble test stack: %v", err)
} }
@ -92,9 +84,10 @@ func main() {
// MakeSystemNode configures a protocol stack for the RPC tests based on a given // MakeSystemNode configures a protocol stack for the RPC tests based on a given
// keystore path and initial pre-state. // keystore path and initial pre-state.
func MakeSystemNode(keydir string, privkey string, test *tests.BlockTest) (*node.Node, error) { func MakeSystemNode(privkey string, test *tests.BlockTest) (*node.Node, error) {
// Create a networkless protocol stack // Create a networkless protocol stack
stack, err := node.New(&node.Config{ stack, err := node.New(&node.Config{
UseLightweightKDF: true,
IPCPath: node.DefaultIPCEndpoint(), IPCPath: node.DefaultIPCEndpoint(),
HTTPHost: common.DefaultHTTPHost, HTTPHost: common.DefaultHTTPHost,
HTTPPort: common.DefaultHTTPPort, HTTPPort: common.DefaultHTTPPort,
@ -108,7 +101,7 @@ func MakeSystemNode(keydir string, privkey string, test *tests.BlockTest) (*node
return nil, err return nil, err
} }
// Create the keystore and inject an unlocked account if requested // Create the keystore and inject an unlocked account if requested
accman := accounts.NewPlaintextManager(keydir) accman := stack.AccountManager()
if len(privkey) > 0 { if len(privkey) > 0 {
key, err := crypto.HexToECDSA(privkey) key, err := crypto.HexToECDSA(privkey)
if err != nil { if err != nil {
@ -131,7 +124,6 @@ func MakeSystemNode(keydir string, privkey string, test *tests.BlockTest) (*node
TestGenesisState: db, TestGenesisState: db,
TestGenesisBlock: test.Genesis, TestGenesisBlock: test.Genesis,
ChainConfig: &core.ChainConfig{HomesteadBlock: params.MainNetHomesteadBlock}, ChainConfig: &core.ChainConfig{HomesteadBlock: params.MainNetHomesteadBlock},
AccountManager: accman,
} }
if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil { if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
return nil, err return nil, err

View File

@ -413,16 +413,6 @@ func MustMakeDataDir(ctx *cli.Context) string {
return "" return ""
} }
// MakeKeyStoreDir resolves the folder to use for storing the account keys from the
// set command line flags, returning the explicitly requested path, or one inside
// the data directory otherwise.
func MakeKeyStoreDir(datadir string, ctx *cli.Context) string {
if path := ctx.GlobalString(KeyStoreDirFlag.Name); path != "" {
return path
}
return filepath.Join(datadir, "keystore")
}
// MakeIPCPath creates an IPC path configuration from the set command line flags, // MakeIPCPath creates an IPC path configuration from the set command line flags,
// returning an empty string if IPC was explicitly disabled, or the set path. // returning an empty string if IPC was explicitly disabled, or the set path.
func MakeIPCPath(ctx *cli.Context) string { func MakeIPCPath(ctx *cli.Context) string {
@ -555,20 +545,6 @@ func MakeDatabaseHandles() int {
return limit / 2 // Leave half for networking and other stuff return limit / 2 // Leave half for networking and other stuff
} }
// MakeAccountManager creates an account manager from set command line flags.
func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
// Create the keystore crypto primitive, light if requested
scryptN := accounts.StandardScryptN
scryptP := accounts.StandardScryptP
if ctx.GlobalBool(LightKDFFlag.Name) {
scryptN = accounts.LightScryptN
scryptP = accounts.LightScryptP
}
datadir := MustMakeDataDir(ctx)
keydir := MakeKeyStoreDir(datadir, ctx)
return accounts.NewManager(keydir, scryptN, scryptP)
}
// MakeAddress converts an account specified directly as a hex encoded string or // MakeAddress converts an account specified directly as a hex encoded string or
// a key index in the key store to an internal account representation. // a key index in the key store to an internal account representation.
func MakeAddress(accman *accounts.Manager, account string) (accounts.Account, error) { func MakeAddress(accman *accounts.Manager, account string) (accounts.Account, error) {
@ -631,22 +607,12 @@ func MakePasswordList(ctx *cli.Context) []string {
return lines return lines
} }
// MakeSystemNode sets up a local node, configures the services to launch and // MakeNode configures a node with no services from command line flags.
// assembles the P2P protocol stack. func MakeNode(ctx *cli.Context, name, version string) *node.Node {
func MakeSystemNode(name, version string, relconf release.Config, extra []byte, ctx *cli.Context) *node.Node { config := &node.Config{
// 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), DataDir: MustMakeDataDir(ctx),
KeyStoreDir: ctx.GlobalString(KeyStoreDirFlag.Name),
UseLightweightKDF: ctx.GlobalBool(LightKDFFlag.Name),
PrivateKey: MakeNodeKey(ctx), PrivateKey: MakeNodeKey(ctx),
Name: MakeNodeName(name, version, ctx), Name: MakeNodeName(name, version, ctx),
NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name), NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name),
@ -665,8 +631,34 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
WSOrigins: ctx.GlobalString(WSAllowedOriginsFlag.Name), WSOrigins: ctx.GlobalString(WSAllowedOriginsFlag.Name),
WSModules: MakeRPCModules(ctx.GlobalString(WSApiFlag.Name)), WSModules: MakeRPCModules(ctx.GlobalString(WSApiFlag.Name)),
} }
// Configure the Ethereum service if ctx.GlobalBool(DevModeFlag.Name) {
accman := MakeAccountManager(ctx) if !ctx.GlobalIsSet(DataDirFlag.Name) {
config.DataDir = filepath.Join(os.TempDir(), "/ethereum_dev_mode")
}
// --dev mode does not need p2p networking.
config.MaxPeers = 0
config.ListenAddr = ":0"
}
stack, err := node.New(config)
if err != nil {
Fatalf("Failed to create the protocol stack: %v", err)
}
return stack
}
// RegisterEthService configures eth.Ethereum from command line flags and adds it to the
// given node.
func RegisterEthService(ctx *cli.Context, stack *node.Node, relconf release.Config, extra []byte) {
// 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)
}
// initialise new random number generator // initialise new random number generator
rand := rand.New(rand.NewSource(time.Now().UnixNano())) rand := rand.New(rand.NewSource(time.Now().UnixNano()))
@ -679,14 +671,13 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
} }
ethConf := &eth.Config{ ethConf := &eth.Config{
Etherbase: MakeEtherbase(stack.AccountManager(), ctx),
ChainConfig: MustMakeChainConfig(ctx), ChainConfig: MustMakeChainConfig(ctx),
FastSync: ctx.GlobalBool(FastSyncFlag.Name), FastSync: ctx.GlobalBool(FastSyncFlag.Name),
BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name), BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
DatabaseCache: ctx.GlobalInt(CacheFlag.Name), DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
DatabaseHandles: MakeDatabaseHandles(), DatabaseHandles: MakeDatabaseHandles(),
NetworkId: ctx.GlobalInt(NetworkIdFlag.Name), NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
AccountManager: accman,
Etherbase: MakeEtherbase(accman, ctx),
MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name), MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
ExtraData: MakeMinerExtra(extra, ctx), ExtraData: MakeMinerExtra(extra, ctx),
NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name), NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
@ -703,8 +694,6 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
SolcPath: ctx.GlobalString(SolcPathFlag.Name), SolcPath: ctx.GlobalString(SolcPathFlag.Name),
AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.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 // Override any default configs in dev mode or the test net
switch { switch {
@ -722,54 +711,30 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
state.StartingNonce = 1048576 // (2**20) state.StartingNonce = 1048576 // (2**20)
case ctx.GlobalBool(DevModeFlag.Name): 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
ethConf.Genesis = core.OlympicGenesisBlock() ethConf.Genesis = core.OlympicGenesisBlock()
if !ctx.GlobalIsSet(GasPriceFlag.Name) { if !ctx.GlobalIsSet(GasPriceFlag.Name) {
ethConf.GasPrice = new(big.Int) ethConf.GasPrice = new(big.Int)
} }
if !ctx.GlobalIsSet(WhisperEnabledFlag.Name) {
shhEnable = true
}
ethConf.PowTest = 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 accman, nil
}); err != nil {
Fatalf("Failed to register the account manager service: %v", err)
}
if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
return eth.New(ctx, ethConf) return eth.New(ctx, ethConf)
}); err != nil { }); err != nil {
Fatalf("Failed to register the Ethereum service: %v", err) 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) { if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
return release.NewReleaseService(ctx, relconf) return release.NewReleaseService(ctx, relconf)
}); err != nil { }); err != nil {
Fatalf("Failed to register the Geth release oracle service: %v", err) Fatalf("Failed to register the Geth release oracle service: %v", err)
} }
return stack }
// RegisterShhService configures whisper and adds it to the given node.
func RegisterShhService(stack *node.Node) {
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)
}
} }
// SetupNetwork configures the system for either the main net or some test network. // SetupNetwork configures the system for either the main net or some test network.

View File

@ -14,6 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package compiler wraps the Solidity compiler executable (solc).
package compiler package compiler
import ( import (
@ -21,42 +22,23 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io"
"io/ioutil" "io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath"
"regexp" "regexp"
"strings" "strings"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
) )
var ( var (
versionRegexp = regexp.MustCompile("[0-9]+\\.[0-9]+\\.[0-9]+") versionRegexp = regexp.MustCompile("[0-9]+\\.[0-9]+\\.[0-9]+")
legacyRegexp = regexp.MustCompile("0\\.(9\\..*|1\\.[01])") solcParams = []string{
paramsLegacy = []string{ "--combined-json", "bin,abi,userdoc,devdoc",
"--binary", // Request to output the contract in binary (hexadecimal).
"file", //
"--json-abi", // Request to output the contract's JSON ABI interface.
"file", //
"--natspec-user", // Request to output the contract's Natspec user documentation.
"file", //
"--natspec-dev", // Request to output the contract's Natspec developer documentation.
"file",
"--add-std",
"1",
}
paramsNew = []string{
"--bin", // Request to output the contract in binary (hexadecimal).
"--abi", // Request to output the contract's JSON ABI interface.
"--userdoc", // Request to output the contract's Natspec user documentation.
"--devdoc", // Request to output the contract's Natspec developer documentation.
"--add-std", // include standard lib contracts "--add-std", // include standard lib contracts
"--optimize", // code optimizer switched on "--optimize", // code optimizer switched on
"-o", // output directory
} }
) )
@ -76,135 +58,112 @@ type ContractInfo struct {
DeveloperDoc interface{} `json:"developerDoc"` DeveloperDoc interface{} `json:"developerDoc"`
} }
// Solidity contains information about the solidity compiler.
type Solidity struct { type Solidity struct {
solcPath string Path, Version, FullVersion string
version string
fullVersion string
legacy bool
} }
func New(solcPath string) (sol *Solidity, err error) { // --combined-output format
// set default solc type solcOutput struct {
if len(solcPath) == 0 { Contracts map[string]struct{ Bin, Abi, Devdoc, Userdoc string }
solcPath = "solc" Version string
}
solcPath, err = exec.LookPath(solcPath)
if err != nil {
return
} }
cmd := exec.Command(solcPath, "--version") // SolidityVersion runs solc and parses its version output.
func SolidityVersion(solc string) (*Solidity, error) {
if solc == "" {
solc = "solc"
}
var out bytes.Buffer var out bytes.Buffer
cmd := exec.Command(solc, "--version")
cmd.Stdout = &out cmd.Stdout = &out
err = cmd.Run() if err := cmd.Run(); err != nil {
if err != nil { return nil, err
return }
s := &Solidity{
Path: cmd.Path,
FullVersion: out.String(),
Version: versionRegexp.FindString(out.String()),
}
return s, nil
} }
fullVersion := out.String() // CompileSolidityString builds and returns all the contracts contained within a source string.
version := versionRegexp.FindString(fullVersion) func CompileSolidityString(solc, source string) (map[string]*Contract, error) {
legacy := legacyRegexp.MatchString(version)
sol = &Solidity{
solcPath: solcPath,
version: version,
fullVersion: fullVersion,
legacy: legacy,
}
glog.V(logger.Info).Infoln(sol.Info())
return
}
func (sol *Solidity) Info() string {
return fmt.Sprintf("%s\npath: %s", sol.fullVersion, sol.solcPath)
}
func (sol *Solidity) Version() string {
return sol.version
}
// Compile builds and returns all the contracts contained within a source string.
func (sol *Solidity) Compile(source string) (map[string]*Contract, error) {
// Short circuit if no source code was specified
if len(source) == 0 { if len(source) == 0 {
return nil, errors.New("solc: empty source string") return nil, errors.New("solc: empty source string")
} }
// Create a safe place to dump compilation output if solc == "" {
wd, err := ioutil.TempDir("", "solc") solc = "solc"
}
// Write source to a temporary file. Compiling stdin used to be supported
// but seems to produce an exception with solc 0.3.5.
infile, err := ioutil.TempFile("", "geth-compile-solidity")
if err != nil { if err != nil {
return nil, fmt.Errorf("solc: failed to create temporary build folder: %v", err) return nil, err
} }
defer os.RemoveAll(wd) defer os.Remove(infile.Name())
if _, err := io.WriteString(infile, source); err != nil {
// Assemble the compiler command, change to the temp folder and capture any errors return nil, err
stderr := new(bytes.Buffer) }
if err := infile.Close(); err != nil {
var params []string return nil, err
if sol.legacy {
params = paramsLegacy
} else {
params = paramsNew
params = append(params, wd)
} }
compilerOptions := strings.Join(params, " ")
cmd := exec.Command(sol.solcPath, params...) return CompileSolidity(solc, infile.Name())
cmd.Stdin = strings.NewReader(source) }
cmd.Stderr = stderr
// CompileSolidity compiles all given Solidity source files.
func CompileSolidity(solc string, sourcefiles ...string) (map[string]*Contract, error) {
if len(sourcefiles) == 0 {
return nil, errors.New("solc: no source ")
}
source, err := slurpFiles(sourcefiles)
if err != nil {
return nil, err
}
if solc == "" {
solc = "solc"
}
var stderr, stdout bytes.Buffer
args := append(solcParams, "--")
cmd := exec.Command(solc, append(args, sourcefiles...)...)
cmd.Stderr = &stderr
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("solc: %v\n%s", err, string(stderr.Bytes())) return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes())
} }
// Sanity check that something was actually built var output solcOutput
matches, _ := filepath.Glob(filepath.Join(wd, "*.bin*")) if err := json.Unmarshal(stdout.Bytes(), &output); err != nil {
if len(matches) < 1 { return nil, err
return nil, fmt.Errorf("solc: no build results found")
} }
// Compilation succeeded, assemble and return the contracts shortVersion := versionRegexp.FindString(output.Version)
// Compilation succeeded, assemble and return the contracts.
contracts := make(map[string]*Contract) contracts := make(map[string]*Contract)
for _, path := range matches { for name, info := range output.Contracts {
_, file := filepath.Split(path) // Parse the individual compilation results.
base := strings.Split(file, ".")[0]
// Parse the individual compilation results (code binary, ABI definitions, user and dev docs)
var binary []byte
binext := ".bin"
if sol.legacy {
binext = ".binary"
}
if binary, err = ioutil.ReadFile(filepath.Join(wd, base+binext)); err != nil {
return nil, fmt.Errorf("solc: error reading compiler output for code: %v", err)
}
var abi interface{} var abi interface{}
if blob, err := ioutil.ReadFile(filepath.Join(wd, base+".abi")); err != nil { if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil {
return nil, fmt.Errorf("solc: error reading abi definition: %v", err) return nil, fmt.Errorf("solc: error reading abi definition (%v)", err)
} else if err = json.Unmarshal(blob, &abi); err != nil {
return nil, fmt.Errorf("solc: error parsing abi definition: %v", err)
} }
var userdoc interface{} var userdoc interface{}
if blob, err := ioutil.ReadFile(filepath.Join(wd, base+".docuser")); err != nil { if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil {
return nil, fmt.Errorf("solc: error reading user doc: %v", err) return nil, fmt.Errorf("solc: error reading user doc: %v", err)
} else if err = json.Unmarshal(blob, &userdoc); err != nil {
return nil, fmt.Errorf("solc: error parsing user doc: %v", err)
} }
var devdoc interface{} var devdoc interface{}
if blob, err := ioutil.ReadFile(filepath.Join(wd, base+".docdev")); err != nil { if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil {
return nil, fmt.Errorf("solc: error reading dev doc: %v", err) return nil, fmt.Errorf("solc: error reading dev doc: %v", err)
} else if err = json.Unmarshal(blob, &devdoc); err != nil {
return nil, fmt.Errorf("solc: error parsing dev doc: %v", err)
} }
// Assemble the final contract contracts[name] = &Contract{
contracts[base] = &Contract{ Code: "0x" + info.Bin,
Code: "0x" + string(binary),
Info: ContractInfo{ Info: ContractInfo{
Source: source, Source: source,
Language: "Solidity", Language: "Solidity",
LanguageVersion: sol.version, LanguageVersion: shortVersion,
CompilerVersion: sol.version, CompilerVersion: shortVersion,
CompilerOptions: compilerOptions, CompilerOptions: strings.Join(solcParams, " "),
AbiDefinition: abi, AbiDefinition: abi,
UserDoc: userdoc, UserDoc: userdoc,
DeveloperDoc: devdoc, DeveloperDoc: devdoc,
@ -214,12 +173,24 @@ func (sol *Solidity) Compile(source string) (map[string]*Contract, error) {
return contracts, nil return contracts, nil
} }
func SaveInfo(info *ContractInfo, filename string) (contenthash common.Hash, err error) { func slurpFiles(files []string) (string, error) {
var concat bytes.Buffer
for _, file := range files {
content, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
concat.Write(content)
}
return concat.String(), nil
}
// SaveInfo serializes info to the given file and returns its Keccak256 hash.
func SaveInfo(info *ContractInfo, filename string) (common.Hash, error) {
infojson, err := json.Marshal(info) infojson, err := json.Marshal(info)
if err != nil { if err != nil {
return return common.Hash{}, err
} }
contenthash = common.BytesToHash(crypto.Keccak256(infojson)) contenthash := common.BytesToHash(crypto.Keccak256(infojson))
err = ioutil.WriteFile(filename, infojson, 0600) return contenthash, ioutil.WriteFile(filename, infojson, 0600)
return
} }

View File

@ -26,10 +26,9 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
) )
const solcVersion = "0.1.1" const (
supportedSolcVersion = "0.3.5"
var ( testSource = `
source = `
contract test { contract test {
/// @notice Will multiply ` + "`a`" + ` by 7. /// @notice Will multiply ` + "`a`" + ` by 7.
function multiply(uint a) returns(uint d) { function multiply(uint a) returns(uint d) {
@ -37,61 +36,57 @@ contract test {
} }
} }
` `
code = "0x6060604052606d8060116000396000f30060606040526000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa1146037576035565b005b6046600480359060200150605c565b6040518082815260200191505060405180910390f35b60006007820290506068565b91905056" testCode = "0x6060604052602a8060106000396000f3606060405260e060020a6000350463c6888fa18114601a575b005b6007600435026060908152602090f3"
info = `{"source":"\ncontract test {\n /// @notice Will multiply ` + "`a`" + ` by 7.\n function multiply(uint a) returns(uint d) {\n return a * 7;\n }\n}\n","language":"Solidity","languageVersion":"0.1.1","compilerVersion":"0.1.1","compilerOptions":"--binary file --json-abi file --natspec-user file --natspec-dev file --add-std 1","abiDefinition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}],"userDoc":{"methods":{"multiply(uint256)":{"notice":"Will multiply ` + "`a`" + ` by 7."}}},"developerDoc":{"methods":{}}}` testInfo = `{"source":"\ncontract test {\n /// @notice Will multiply ` + "`a`" + ` by 7.\n function multiply(uint a) returns(uint d) {\n return a * 7;\n }\n}\n","language":"Solidity","languageVersion":"0.1.1","compilerVersion":"0.1.1","compilerOptions":"--binary file --json-abi file --natspec-user file --natspec-dev file --add-std 1","abiDefinition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}],"userDoc":{"methods":{"multiply(uint256)":{"notice":"Will multiply ` + "`a`" + ` by 7."}}},"developerDoc":{"methods":{}}}`
infohash = common.HexToHash("0x9f3803735e7f16120c5a140ab3f02121fd3533a9655c69b33a10e78752cc49b0")
) )
func TestCompiler(t *testing.T) { func skipUnsupported(t *testing.T) {
sol, err := New("") sol, err := SolidityVersion("")
if err != nil { if err != nil {
t.Skipf("solc not found: %v", err) t.Skip(err)
} else if sol.Version() != solcVersion {
t.Skipf("WARNING: a newer version of solc found (%v, expect %v)", sol.Version(), solcVersion)
}
contracts, err := sol.Compile(source)
if err != nil {
t.Errorf("error compiling source. result %v: %v", contracts, err)
return return
} }
if sol.Version != supportedSolcVersion {
t.Skipf("unsupported version of solc found (%v, expect %v)", sol.Version, supportedSolcVersion)
}
}
func TestCompiler(t *testing.T) {
skipUnsupported(t)
contracts, err := CompileSolidityString("", testSource)
if err != nil {
t.Fatalf("error compiling source. result %v: %v", contracts, err)
}
if len(contracts) != 1 { if len(contracts) != 1 {
t.Errorf("one contract expected, got %d", len(contracts)) t.Errorf("one contract expected, got %d", len(contracts))
} }
c, ok := contracts["test"]
if contracts["test"].Code != code { if !ok {
t.Errorf("wrong code, expected\n%s, got\n%s", code, contracts["test"].Code) t.Fatal("info for contract 'test' not present in result")
}
if c.Code != testCode {
t.Errorf("wrong code: expected\n%s, got\n%s", testCode, c.Code)
}
if c.Info.Source != testSource {
t.Error("wrong source")
}
if c.Info.CompilerVersion != supportedSolcVersion {
t.Errorf("wrong version: expected %q, got %q", supportedSolcVersion, c.Info.CompilerVersion)
} }
} }
func TestCompileError(t *testing.T) { func TestCompileError(t *testing.T) {
sol, err := New("") skipUnsupported(t)
if err != nil || sol.version != solcVersion { contracts, err := CompileSolidityString("", testSource[4:])
t.Skip("solc not found: skip")
} else if sol.Version() != solcVersion {
t.Skip("WARNING: skipping due to a newer version of solc found (%v, expect %v)", sol.Version(), solcVersion)
}
contracts, err := sol.Compile(source[2:])
if err == nil { if err == nil {
t.Errorf("error expected compiling source. got none. result %v", contracts) t.Errorf("error expected compiling source. got none. result %v", contracts)
return
}
}
func TestNoCompiler(t *testing.T) {
_, err := New("/path/to/solc")
if err != nil {
t.Logf("solidity quits with error: %v", err)
} else {
t.Errorf("no solc installed, but got no error")
} }
t.Logf("error: %v", err)
} }
func TestSaveInfo(t *testing.T) { func TestSaveInfo(t *testing.T) {
var cinfo ContractInfo var cinfo ContractInfo
err := json.Unmarshal([]byte(info), &cinfo) err := json.Unmarshal([]byte(testInfo), &cinfo)
if err != nil { if err != nil {
t.Errorf("%v", err) t.Errorf("%v", err)
} }
@ -105,10 +100,11 @@ func TestSaveInfo(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("error reading '%v': %v", filename, err) t.Errorf("error reading '%v': %v", filename, err)
} }
if string(got) != info { if string(got) != testInfo {
t.Errorf("incorrect info.json extracted, expected:\n%s\ngot\n%s", info, string(got)) t.Errorf("incorrect info.json extracted, expected:\n%s\ngot\n%s", testInfo, string(got))
} }
if cinfohash != infohash { wantHash := common.HexToHash("0x9f3803735e7f16120c5a140ab3f02121fd3533a9655c69b33a10e78752cc49b0")
t.Errorf("content hash for info is incorrect. expected %v, got %v", infohash.Hex(), cinfohash.Hex()) if cinfohash != wantHash {
t.Errorf("content hash for info is incorrect. expected %v, got %v", wantHash.Hex(), cinfohash.Hex())
} }
} }

View File

@ -23,12 +23,10 @@ import (
"io/ioutil" "io/ioutil"
"math/big" "math/big"
"os" "os"
"path/filepath"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth"
@ -92,17 +90,15 @@ func newTester(t *testing.T, confOverride func(*eth.Config)) *tester {
if err != nil { if err != nil {
t.Fatalf("failed to create temporary keystore: %v", err) t.Fatalf("failed to create temporary keystore: %v", err)
} }
accman := accounts.NewPlaintextManager(filepath.Join(workspace, "keystore"))
// Create a networkless protocol stack and start an Ethereum service within // Create a networkless protocol stack and start an Ethereum service within
stack, err := node.New(&node.Config{DataDir: workspace, Name: testInstance, NoDiscovery: true}) stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance, NoDiscovery: true})
if err != nil { if err != nil {
t.Fatalf("failed to create node: %v", err) t.Fatalf("failed to create node: %v", err)
} }
ethConf := &eth.Config{ ethConf := &eth.Config{
ChainConfig: &core.ChainConfig{HomesteadBlock: new(big.Int)}, ChainConfig: &core.ChainConfig{HomesteadBlock: new(big.Int)},
Etherbase: common.HexToAddress(testAddress), Etherbase: common.HexToAddress(testAddress),
AccountManager: accman,
PowTest: true, PowTest: true,
} }
if confOverride != nil { if confOverride != nil {

View File

@ -19,12 +19,9 @@ package core
import ( import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
) )
// Validator is an interface which defines the standard for block validation. // Validator is an interface which defines the standard for block validation.
@ -63,16 +60,3 @@ type HeaderValidator interface {
type Processor interface { type Processor interface {
Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, vm.Logs, *big.Int, error) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, vm.Logs, *big.Int, error)
} }
// Backend is an interface defining the basic functionality for an operable node
// with all the functionality to be a functional, valid Ethereum operator.
//
// TODO Remove this
type Backend interface {
AccountManager() *accounts.Manager
BlockChain() *BlockChain
TxPool() *TxPool
ChainDb() ethdb.Database
DappDb() ethdb.Database
EventMux() *event.TypeMux
}

View File

@ -31,7 +31,6 @@ import (
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/common/httpclient" "github.com/ethereum/go-ethereum/common/httpclient"
"github.com/ethereum/go-ethereum/common/registrar/ethreg" "github.com/ethereum/go-ethereum/common/registrar/ethreg"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
@ -83,7 +82,6 @@ type Config struct {
PowShared bool PowShared bool
ExtraData []byte ExtraData []byte
AccountManager *accounts.Manager
Etherbase common.Address Etherbase common.Address
GasPrice *big.Int GasPrice *big.Int
MinerThreads int MinerThreads int
@ -116,7 +114,6 @@ type Ethereum struct {
protocolManager *ProtocolManager protocolManager *ProtocolManager
// DB interfaces // DB interfaces
chainDb ethdb.Database // Block chain database chainDb ethdb.Database // Block chain database
dappDb ethdb.Database // Dapp database
eventMux *event.TypeMux eventMux *event.TypeMux
pow *ethash.Ethash pow *ethash.Ethash
@ -132,7 +129,6 @@ type Ethereum struct {
autodagquit chan bool autodagquit chan bool
etherbase common.Address etherbase common.Address
solcPath string solcPath string
solc *compiler.Solidity
NatSpec bool NatSpec bool
PowTest bool PowTest bool
@ -143,7 +139,7 @@ type Ethereum struct {
// New creates a new Ethereum object (including the // New creates a new Ethereum object (including the
// initialisation of the common Ethereum object) // initialisation of the common Ethereum object)
func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
chainDb, dappDb, err := CreateDBs(ctx, config) chainDb, err := createDB(ctx, config)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -158,9 +154,8 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
eth := &Ethereum{ eth := &Ethereum{
chainDb: chainDb, chainDb: chainDb,
dappDb: dappDb,
eventMux: ctx.EventMux, eventMux: ctx.EventMux,
accountManager: config.AccountManager, accountManager: ctx.AccountManager,
pow: pow, pow: pow,
shutdownChan: make(chan bool), shutdownChan: make(chan bool),
stopDbUpgrade: stopDbUpgrade, stopDbUpgrade: stopDbUpgrade,
@ -244,25 +239,13 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
return eth, nil return eth, nil
} }
// CreateDBs creates the chain and dapp databases for an Ethereum service // createDB creates the chain database.
func CreateDBs(ctx *node.ServiceContext, config *Config) (chainDb, dappDb ethdb.Database, err error) { func createDB(ctx *node.ServiceContext, config *Config) (ethdb.Database, error) {
// Open the chain database and perform any upgrades needed db, err := ctx.OpenDatabase("chaindata", config.DatabaseCache, config.DatabaseHandles)
chainDb, err = ctx.OpenDatabase("chaindata", config.DatabaseCache, config.DatabaseHandles) if db, ok := db.(*ethdb.LDBDatabase); ok {
if err != nil {
return nil, nil, err
}
if db, ok := chainDb.(*ethdb.LDBDatabase); ok {
db.Meter("eth/db/chaindata/") db.Meter("eth/db/chaindata/")
} }
return db, err
dappDb, err = ctx.OpenDatabase("dapp", config.DatabaseCache, config.DatabaseHandles)
if err != nil {
return nil, nil, err
}
if db, ok := dappDb.(*ethdb.LDBDatabase); ok {
db.Meter("eth/db/dapp/")
}
return
} }
// SetupGenesisBlock initializes the genesis block for an Ethereum service // SetupGenesisBlock initializes the genesis block for an Ethereum service
@ -306,7 +289,7 @@ func CreatePoW(config *Config) (*ethash.Ethash, error) {
// APIs returns the collection of RPC services the ethereum package offers. // APIs returns the collection of RPC services the ethereum package offers.
// NOTE, some of these services probably need to be moved to somewhere else. // NOTE, some of these services probably need to be moved to somewhere else.
func (s *Ethereum) APIs() []rpc.API { func (s *Ethereum) APIs() []rpc.API {
return append(ethapi.GetAPIs(s.apiBackend, &s.solcPath, &s.solc), []rpc.API{ return append(ethapi.GetAPIs(s.apiBackend, s.solcPath), []rpc.API{
{ {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
@ -390,7 +373,6 @@ func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux } func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
func (s *Ethereum) Pow() *ethash.Ethash { return s.pow } func (s *Ethereum) Pow() *ethash.Ethash { return s.pow }
func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb } func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
func (s *Ethereum) DappDb() ethdb.Database { return s.dappDb }
func (s *Ethereum) IsListening() bool { return true } // Always listening func (s *Ethereum) IsListening() bool { return true } // Always listening
func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) } func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
func (s *Ethereum) NetVersion() int { return s.netVersionId } func (s *Ethereum) NetVersion() int { return s.netVersionId }
@ -428,7 +410,6 @@ func (s *Ethereum) Stop() error {
s.StopAutoDAG() s.StopAutoDAG()
s.chainDb.Close() s.chainDb.Close()
s.dappDb.Close()
close(s.shutdownChan) close(s.shutdownChan)
return nil return nil

View File

@ -44,7 +44,7 @@ type ContractBackend struct {
// Etheruem object. // Etheruem object.
func NewContractBackend(eth *Ethereum) *ContractBackend { func NewContractBackend(eth *Ethereum) *ContractBackend {
return &ContractBackend{ return &ContractBackend{
eapi: ethapi.NewPublicEthereumAPI(eth.apiBackend, nil, nil), eapi: ethapi.NewPublicEthereumAPI(eth.apiBackend),
bcapi: ethapi.NewPublicBlockChainAPI(eth.apiBackend), bcapi: ethapi.NewPublicBlockChainAPI(eth.apiBackend),
txapi: ethapi.NewPublicTransactionPoolAPI(eth.apiBackend), txapi: ethapi.NewPublicTransactionPoolAPI(eth.apiBackend),
} }

View File

@ -39,14 +39,12 @@ var OpenFileLimit = 64
// cacheRatio specifies how the total allotted cache is distributed between the // cacheRatio specifies how the total allotted cache is distributed between the
// various system databases. // various system databases.
var cacheRatio = map[string]float64{ var cacheRatio = map[string]float64{
"dapp": 0.0,
"chaindata": 1.0, "chaindata": 1.0,
} }
// handleRatio specifies how the total allotted file descriptors is distributed // handleRatio specifies how the total allotted file descriptors is distributed
// between the various system databases. // between the various system databases.
var handleRatio = map[string]float64{ var handleRatio = map[string]float64{
"dapp": 0.0,
"chaindata": 1.0, "chaindata": 1.0,
} }

View File

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"strings" "strings"
@ -29,7 +28,6 @@ import (
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
@ -50,13 +48,11 @@ const defaultGas = uint64(90000)
// It offers only methods that operate on public data that is freely available to anyone. // It offers only methods that operate on public data that is freely available to anyone.
type PublicEthereumAPI struct { type PublicEthereumAPI struct {
b Backend b Backend
solcPath *string
solc **compiler.Solidity
} }
// NewPublicEthereumAPI creates a new Etheruem protocol API. // NewPublicEthereumAPI creates a new Etheruem protocol API.
func NewPublicEthereumAPI(b Backend, solcPath *string, solc **compiler.Solidity) *PublicEthereumAPI { func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
return &PublicEthereumAPI{b, solcPath, solc} return &PublicEthereumAPI{b}
} }
// GasPrice returns a suggestion for a gas price. // GasPrice returns a suggestion for a gas price.
@ -64,39 +60,6 @@ func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*big.Int, error) {
return s.b.SuggestPrice(ctx) return s.b.SuggestPrice(ctx)
} }
func (s *PublicEthereumAPI) getSolc() (*compiler.Solidity, error) {
var err error
solc := *s.solc
if solc == nil {
solc, err = compiler.New(*s.solcPath)
}
return solc, err
}
// GetCompilers returns the collection of available smart contract compilers
func (s *PublicEthereumAPI) GetCompilers() ([]string, error) {
solc, err := s.getSolc()
if err == nil && solc != nil {
return []string{"Solidity"}, nil
}
return []string{}, nil
}
// CompileSolidity compiles the given solidity source
func (s *PublicEthereumAPI) CompileSolidity(source string) (map[string]*compiler.Contract, error) {
solc, err := s.getSolc()
if err != nil {
return nil, err
}
if solc == nil {
return nil, errors.New("solc (solidity compiler) not found")
}
return solc.Compile(source)
}
// ProtocolVersion returns the current Ethereum protocol version this node supports // ProtocolVersion returns the current Ethereum protocol version this node supports
func (s *PublicEthereumAPI) ProtocolVersion() *rpc.HexNumber { func (s *PublicEthereumAPI) ProtocolVersion() *rpc.HexNumber {
return rpc.NewHexNumber(s.b.ProtocolVersion()) return rpc.NewHexNumber(s.b.ProtocolVersion())
@ -1298,31 +1261,6 @@ func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, tx *Tx, gasPrice,
return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash) return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash)
} }
// PrivateAdminAPI is the collection of Etheruem APIs exposed over the private
// admin endpoint.
type PrivateAdminAPI struct {
b Backend
solcPath *string
solc **compiler.Solidity
}
// NewPrivateAdminAPI creates a new API definition for the private admin methods
// of the Ethereum service.
func NewPrivateAdminAPI(b Backend, solcPath *string, solc **compiler.Solidity) *PrivateAdminAPI {
return &PrivateAdminAPI{b, solcPath, solc}
}
// SetSolc sets the Solidity compiler path to be used by the node.
func (api *PrivateAdminAPI) SetSolc(path string) (string, error) {
var err error
*api.solcPath = path
*api.solc, err = compiler.New(path)
if err != nil {
return "", err
}
return (*api.solc).Info(), nil
}
// PublicDebugAPI is the collection of Etheruem APIs exposed over the public // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
// debugging endpoint. // debugging endpoint.
type PublicDebugAPI struct { type PublicDebugAPI struct {

View File

@ -22,7 +22,6 @@ import (
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
@ -69,12 +68,13 @@ type State interface {
GetNonce(ctx context.Context, addr common.Address) (uint64, error) GetNonce(ctx context.Context, addr common.Address) (uint64, error)
} }
func GetAPIs(apiBackend Backend, solcPath *string, solc **compiler.Solidity) []rpc.API { func GetAPIs(apiBackend Backend, solcPath string) []rpc.API {
return []rpc.API{ compiler := makeCompilerAPIs(solcPath)
all := []rpc.API{
{ {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: NewPublicEthereumAPI(apiBackend, solcPath, solc), Service: NewPublicEthereumAPI(apiBackend),
Public: true, Public: true,
}, { }, {
Namespace: "eth", Namespace: "eth",
@ -91,10 +91,6 @@ func GetAPIs(apiBackend Backend, solcPath *string, solc **compiler.Solidity) []r
Version: "1.0", Version: "1.0",
Service: NewPublicTxPoolAPI(apiBackend), Service: NewPublicTxPoolAPI(apiBackend),
Public: true, Public: true,
}, {
Namespace: "admin",
Version: "1.0",
Service: NewPrivateAdminAPI(apiBackend, solcPath, solc),
}, { }, {
Namespace: "debug", Namespace: "debug",
Version: "1.0", Version: "1.0",
@ -116,4 +112,5 @@ func GetAPIs(apiBackend Backend, solcPath *string, solc **compiler.Solidity) []r
Public: false, Public: false,
}, },
} }
return append(compiler, all...)
} }

82
internal/ethapi/solc.go Normal file
View File

@ -0,0 +1,82 @@
// Copyright 2016 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 ethapi
import (
"sync"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/rpc"
)
func makeCompilerAPIs(solcPath string) []rpc.API {
c := &compilerAPI{solc: solcPath}
return []rpc.API{
{
Namespace: "eth",
Version: "1.0",
Service: (*PublicCompilerAPI)(c),
Public: true,
},
{
Namespace: "admin",
Version: "1.0",
Service: (*CompilerAdminAPI)(c),
Public: true,
},
}
}
type compilerAPI struct {
// This lock guards the solc path set through the API.
// It also ensures that only one solc process is used at
// any time.
mu sync.Mutex
solc string
}
type CompilerAdminAPI compilerAPI
// SetSolc sets the Solidity compiler path to be used by the node.
func (api *CompilerAdminAPI) SetSolc(path string) (string, error) {
api.mu.Lock()
defer api.mu.Unlock()
info, err := compiler.SolidityVersion(path)
if err != nil {
return "", err
}
api.solc = path
return info.FullVersion, nil
}
type PublicCompilerAPI compilerAPI
// CompileSolidity compiles the given solidity source.
func (api *PublicCompilerAPI) CompileSolidity(source string) (map[string]*compiler.Contract, error) {
api.mu.Lock()
defer api.mu.Unlock()
return compiler.CompileSolidityString(api.solc, source)
}
func (api *PublicCompilerAPI) GetCompilers() ([]string, error) {
api.mu.Lock()
defer api.mu.Unlock()
if _, err := compiler.SolidityVersion(api.solc); err == nil {
return []string{"Solidity"}, nil
}
return []string{}, nil
}

View File

@ -22,11 +22,13 @@ import (
"math/big" "math/big"
"sync/atomic" "sync/atomic"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/logger/glog"
@ -34,6 +36,15 @@ import (
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
) )
// Backend wraps all methods required for mining.
type Backend interface {
AccountManager() *accounts.Manager
BlockChain() *core.BlockChain
TxPool() *core.TxPool
ChainDb() ethdb.Database
}
// Miner creates blocks and searches for proof-of-work values.
type Miner struct { type Miner struct {
mux *event.TypeMux mux *event.TypeMux
@ -44,15 +55,21 @@ type Miner struct {
threads int threads int
coinbase common.Address coinbase common.Address
mining int32 mining int32
eth core.Backend eth Backend
pow pow.PoW pow pow.PoW
canStart int32 // can start indicates whether we can start the mining operation canStart int32 // can start indicates whether we can start the mining operation
shouldStart int32 // should start indicates whether we should start after sync shouldStart int32 // should start indicates whether we should start after sync
} }
func New(eth core.Backend, config *core.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner { func New(eth Backend, config *core.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner {
miner := &Miner{eth: eth, mux: mux, pow: pow, worker: newWorker(config, common.Address{}, eth), canStart: 1} miner := &Miner{
eth: eth,
mux: mux,
pow: pow,
worker: newWorker(config, common.Address{}, eth, mux),
canStart: 1,
}
go miner.update() go miner.update()
return miner return miner

View File

@ -60,7 +60,7 @@ type uint64RingBuffer struct {
next int //where is the next insertion? assert 0 <= next < len(ints) next int //where is the next insertion? assert 0 <= next < len(ints)
} }
// environment is the workers current environment and holds // Work is the workers current environment and holds
// all of the current state information // all of the current state information
type Work struct { type Work struct {
config *core.ChainConfig config *core.ChainConfig
@ -105,7 +105,7 @@ type worker struct {
recv chan *Result recv chan *Result
pow pow.PoW pow pow.PoW
eth core.Backend eth Backend
chain *core.BlockChain chain *core.BlockChain
proc core.Validator proc core.Validator
chainDb ethdb.Database chainDb ethdb.Database
@ -130,11 +130,11 @@ type worker struct {
fullValidation bool fullValidation bool
} }
func newWorker(config *core.ChainConfig, coinbase common.Address, eth core.Backend) *worker { func newWorker(config *core.ChainConfig, coinbase common.Address, eth Backend, mux *event.TypeMux) *worker {
worker := &worker{ worker := &worker{
config: config, config: config,
eth: eth, eth: eth,
mux: eth.EventMux(), mux: mux,
chainDb: eth.ChainDb(), chainDb: eth.ChainDb(),
recv: make(chan *Result, resultQueueSize), recv: make(chan *Result, resultQueueSize),
gasPrice: new(big.Int), gasPrice: new(big.Int),

View File

@ -27,6 +27,7 @@ import (
"runtime" "runtime"
"strings" "strings"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
@ -37,6 +38,7 @@ import (
var ( var (
datadirPrivateKey = "nodekey" // Path within the datadir to the node's private key datadirPrivateKey = "nodekey" // Path within the datadir to the node's private key
datadirDefaultKeyStore = "keystore" // Path within the datadir to the keystore
datadirStaticNodes = "static-nodes.json" // Path within the datadir to the static node list datadirStaticNodes = "static-nodes.json" // Path within the datadir to the static node list
datadirTrustedNodes = "trusted-nodes.json" // Path within the datadir to the trusted node list datadirTrustedNodes = "trusted-nodes.json" // Path within the datadir to the trusted node list
datadirNodeDatabase = "nodes" // Path within the datadir to store the node infos datadirNodeDatabase = "nodes" // Path within the datadir to store the node infos
@ -53,6 +55,19 @@ type Config struct {
// in memory. // in memory.
DataDir string DataDir string
// KeyStoreDir is the file system folder that contains private keys. The directory can
// be specified as a relative path, in which case it is resolved relative to the
// current directory.
//
// If KeyStoreDir is empty, the default location is the "keystore" subdirectory of
// DataDir. If DataDir is unspecified and KeyStoreDir is empty, an ephemeral directory
// is created by New and destroyed when the node is stopped.
KeyStoreDir string
// UseLightweightKDF lowers the memory and CPU requirements of the key store
// scrypt KDF at the expense of security.
UseLightweightKDF bool
// IPCPath is the requested location to place the IPC endpoint. If the path is // IPCPath is the requested location to place the IPC endpoint. If the path is
// a simple file name, it is placed inside the data directory (or on the root // a simple file name, it is placed inside the data directory (or on the root
// pipe path on Windows), whereas if it's a resolvable path name (absolute or // pipe path on Windows), whereas if it's a resolvable path name (absolute or
@ -278,3 +293,38 @@ func (c *Config) parsePersistentNodes(file string) []*discover.Node {
} }
return nodes return nodes
} }
func makeAccountManager(conf *Config) (am *accounts.Manager, ephemeralKeystore string, err error) {
scryptN := accounts.StandardScryptN
scryptP := accounts.StandardScryptP
if conf.UseLightweightKDF {
scryptN = accounts.LightScryptN
scryptP = accounts.LightScryptP
}
var keydir string
switch {
case filepath.IsAbs(conf.KeyStoreDir):
keydir = conf.KeyStoreDir
case conf.DataDir != "":
if conf.KeyStoreDir == "" {
keydir = filepath.Join(conf.DataDir, datadirDefaultKeyStore)
} else {
keydir, err = filepath.Abs(conf.KeyStoreDir)
}
case conf.KeyStoreDir != "":
keydir, err = filepath.Abs(conf.KeyStoreDir)
default:
// There is no datadir.
keydir, err = ioutil.TempDir("", "go-ethereum-keystore")
ephemeralKeystore = keydir
}
if err != nil {
return nil, "", err
}
if err := os.MkdirAll(keydir, 0700); err != nil {
return nil, "", err
}
return accounts.NewManager(keydir, scryptN, scryptP), ephemeralKeystore, nil
}

View File

@ -26,6 +26,7 @@ import (
"sync" "sync"
"syscall" "syscall"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/internal/debug" "github.com/ethereum/go-ethereum/internal/debug"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
@ -49,6 +50,9 @@ type Node struct {
datadir string // Path to the currently used data directory datadir string // Path to the currently used data directory
eventmux *event.TypeMux // Event multiplexer used between the services of a stack eventmux *event.TypeMux // Event multiplexer used between the services of a stack
accman *accounts.Manager
ephemeralKeystore string // if non-empty, the key directory that will be removed by Stop
serverConfig p2p.Config serverConfig p2p.Config
server *p2p.Server // Currently running P2P networking layer server *p2p.Server // Currently running P2P networking layer
@ -90,6 +94,11 @@ func New(conf *Config) (*Node, error) {
return nil, err return nil, err
} }
} }
am, ephemeralKeystore, err := makeAccountManager(conf)
if err != nil {
return nil, err
}
// Assemble the networking layer and the node itself // Assemble the networking layer and the node itself
nodeDbPath := "" nodeDbPath := ""
if conf.DataDir != "" { if conf.DataDir != "" {
@ -97,6 +106,8 @@ func New(conf *Config) (*Node, error) {
} }
return &Node{ return &Node{
datadir: conf.DataDir, datadir: conf.DataDir,
accman: am,
ephemeralKeystore: ephemeralKeystore,
serverConfig: p2p.Config{ serverConfig: p2p.Config{
PrivateKey: conf.NodeKey(), PrivateKey: conf.NodeKey(),
Name: conf.Name, Name: conf.Name,
@ -159,6 +170,7 @@ func (n *Node) Start() error {
datadir: n.datadir, datadir: n.datadir,
services: make(map[reflect.Type]Service), services: make(map[reflect.Type]Service),
EventMux: n.eventmux, EventMux: n.eventmux,
AccountManager: n.accman,
} }
for kind, s := range services { // copy needed for threaded access for kind, s := range services { // copy needed for threaded access
ctx.services[kind] = s ctx.services[kind] = s
@ -473,9 +485,18 @@ func (n *Node) Stop() error {
n.server = nil n.server = nil
close(n.stop) close(n.stop)
// Remove the keystore if it was created ephemerally.
var keystoreErr error
if n.ephemeralKeystore != "" {
keystoreErr = os.RemoveAll(n.ephemeralKeystore)
}
if len(failure.Services) > 0 { if len(failure.Services) > 0 {
return failure return failure
} }
if keystoreErr != nil {
return keystoreErr
}
return nil return nil
} }
@ -548,6 +569,11 @@ func (n *Node) DataDir() string {
return n.datadir return n.datadir
} }
// AccountManager retrieves the account manager used by the protocol stack.
func (n *Node) AccountManager() *accounts.Manager {
return n.accman
}
// IPCEndpoint retrieves the current IPC endpoint used by the protocol stack. // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
func (n *Node) IPCEndpoint() string { func (n *Node) IPCEndpoint() string {
return n.ipcEndpoint return n.ipcEndpoint

View File

@ -20,6 +20,7 @@ import (
"path/filepath" "path/filepath"
"reflect" "reflect"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
@ -33,6 +34,7 @@ type ServiceContext struct {
datadir string // Data directory for protocol persistence datadir string // Data directory for protocol persistence
services map[reflect.Type]Service // Index of the already constructed services services map[reflect.Type]Service // Index of the already constructed services
EventMux *event.TypeMux // Event multiplexer used for decoupled notifications EventMux *event.TypeMux // Event multiplexer used for decoupled notifications
AccountManager *accounts.Manager // Account manager created by the node.
} }
// OpenDatabase opens an existing database with the given name (or creates one // OpenDatabase opens an existing database with the given name (or creates one