github.com/jonasnick/go-ethereum@v0.7.12-0.20150216215225-22176f05d387/cmd/utils/cmd.go (about)

     1  /*
     2  	This file is part of go-ethereum
     3  
     4  	go-ethereum is free software: you can redistribute it and/or modify
     5  	it under the terms of the GNU General Public License as published by
     6  	the Free Software Foundation, either version 3 of the License, or
     7  	(at your option) any later version.
     8  
     9  	go-ethereum is distributed in the hope that it will be useful,
    10  	but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  	GNU General Public License for more details.
    13  
    14  	You should have received a copy of the GNU General Public License
    15  	along with go-ethereum.  If not, see <http://www.gnu.org/licenses/>.
    16  */
    17  /**
    18   * @authors
    19   * 	Jeffrey Wilcke <i@jev.io>
    20   * 	Viktor Tron <viktor@ethdev.com>
    21   */
    22  package utils
    23  
    24  import (
    25  	"fmt"
    26  	"os"
    27  	"os/signal"
    28  	"path"
    29  	"path/filepath"
    30  	"regexp"
    31  	"runtime"
    32  
    33  	"bitbucket.org/kardianos/osext"
    34  	"github.com/jonasnick/go-ethereum/core/types"
    35  	"github.com/jonasnick/go-ethereum/crypto"
    36  	"github.com/jonasnick/go-ethereum/eth"
    37  	"github.com/jonasnick/go-ethereum/ethutil"
    38  	"github.com/jonasnick/go-ethereum/logger"
    39  	"github.com/jonasnick/go-ethereum/miner"
    40  	"github.com/jonasnick/go-ethereum/rlp"
    41  	rpchttp "github.com/jonasnick/go-ethereum/rpc/http"
    42  	rpcws "github.com/jonasnick/go-ethereum/rpc/ws"
    43  	"github.com/jonasnick/go-ethereum/state"
    44  	"github.com/jonasnick/go-ethereum/xeth"
    45  )
    46  
    47  var clilogger = logger.NewLogger("CLI")
    48  var interruptCallbacks = []func(os.Signal){}
    49  
    50  // Register interrupt handlers callbacks
    51  func RegisterInterrupt(cb func(os.Signal)) {
    52  	interruptCallbacks = append(interruptCallbacks, cb)
    53  }
    54  
    55  // go routine that call interrupt handlers in order of registering
    56  func HandleInterrupt() {
    57  	c := make(chan os.Signal, 1)
    58  	go func() {
    59  		signal.Notify(c, os.Interrupt)
    60  		for sig := range c {
    61  			clilogger.Errorf("Shutting down (%v) ... \n", sig)
    62  			RunInterruptCallbacks(sig)
    63  		}
    64  	}()
    65  }
    66  
    67  func RunInterruptCallbacks(sig os.Signal) {
    68  	for _, cb := range interruptCallbacks {
    69  		cb(sig)
    70  	}
    71  }
    72  
    73  func openLogFile(Datadir string, filename string) *os.File {
    74  	path := ethutil.AbsolutePath(Datadir, filename)
    75  	file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    76  	if err != nil {
    77  		panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
    78  	}
    79  	return file
    80  }
    81  
    82  func confirm(message string) bool {
    83  	fmt.Println(message, "Are you sure? (y/n)")
    84  	var r string
    85  	fmt.Scanln(&r)
    86  	for ; ; fmt.Scanln(&r) {
    87  		if r == "n" || r == "y" {
    88  			break
    89  		} else {
    90  			fmt.Printf("Yes or no? (%s)", r)
    91  		}
    92  	}
    93  	return r == "y"
    94  }
    95  
    96  func initDataDir(Datadir string) {
    97  	_, err := os.Stat(Datadir)
    98  	if err != nil {
    99  		if os.IsNotExist(err) {
   100  			fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
   101  			os.Mkdir(Datadir, 0777)
   102  		}
   103  	}
   104  }
   105  
   106  func InitConfig(vmType int, ConfigFile string, Datadir string, EnvPrefix string) *ethutil.ConfigManager {
   107  	initDataDir(Datadir)
   108  	cfg := ethutil.ReadConfig(ConfigFile, Datadir, EnvPrefix)
   109  	cfg.VmType = vmType
   110  
   111  	return cfg
   112  }
   113  
   114  func exit(err error) {
   115  	status := 0
   116  	if err != nil {
   117  		clilogger.Errorln("Fatal: ", err)
   118  		status = 1
   119  	}
   120  	logger.Flush()
   121  	os.Exit(status)
   122  }
   123  
   124  func StartEthereum(ethereum *eth.Ethereum) {
   125  	clilogger.Infoln("Starting ", ethereum.Name())
   126  	if err := ethereum.Start(); err != nil {
   127  		exit(err)
   128  	}
   129  	RegisterInterrupt(func(sig os.Signal) {
   130  		ethereum.Stop()
   131  		logger.Flush()
   132  	})
   133  }
   134  
   135  func DefaultAssetPath() string {
   136  	var assetPath string
   137  	// If the current working directory is the go-ethereum dir
   138  	// assume a debug build and use the source directory as
   139  	// asset directory.
   140  	pwd, _ := os.Getwd()
   141  	if pwd == path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist") {
   142  		assetPath = path.Join(pwd, "assets")
   143  	} else {
   144  		switch runtime.GOOS {
   145  		case "darwin":
   146  			// Get Binary Directory
   147  			exedir, _ := osext.ExecutableFolder()
   148  			assetPath = filepath.Join(exedir, "../Resources")
   149  		case "linux":
   150  			assetPath = "/usr/share/mist"
   151  		case "windows":
   152  			assetPath = "./assets"
   153  		default:
   154  			assetPath = "."
   155  		}
   156  	}
   157  	return assetPath
   158  }
   159  
   160  func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) {
   161  
   162  	var err error
   163  	switch {
   164  	case GenAddr:
   165  		if NonInteractive || confirm("This action overwrites your old private key.") {
   166  			err = keyManager.Init(KeyRing, 0, true)
   167  		}
   168  		exit(err)
   169  	case len(SecretFile) > 0:
   170  		SecretFile = ethutil.ExpandHomePath(SecretFile)
   171  
   172  		if NonInteractive || confirm("This action overwrites your old private key.") {
   173  			err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
   174  		}
   175  		exit(err)
   176  	case len(ExportDir) > 0:
   177  		err = keyManager.Init(KeyRing, 0, false)
   178  		if err == nil {
   179  			err = keyManager.Export(ExportDir)
   180  		}
   181  		exit(err)
   182  	default:
   183  		// Creates a keypair if none exists
   184  		err = keyManager.Init(KeyRing, 0, false)
   185  		if err != nil {
   186  			exit(err)
   187  		}
   188  	}
   189  	clilogger.Infof("Main address %x\n", keyManager.Address())
   190  }
   191  
   192  func StartRpc(ethereum *eth.Ethereum, RpcPort int) {
   193  	var err error
   194  	ethereum.RpcServer, err = rpchttp.NewRpcHttpServer(xeth.New(ethereum), RpcPort)
   195  	if err != nil {
   196  		clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err)
   197  	} else {
   198  		go ethereum.RpcServer.Start()
   199  	}
   200  }
   201  
   202  func StartWebSockets(eth *eth.Ethereum, wsPort int) {
   203  	clilogger.Infoln("Starting WebSockets")
   204  
   205  	var err error
   206  	eth.WsServer, err = rpcws.NewWebSocketServer(xeth.New(eth), wsPort)
   207  	if err != nil {
   208  		clilogger.Errorf("Could not start RPC interface (port %v): %v", wsPort, err)
   209  	} else {
   210  		go eth.WsServer.Start()
   211  	}
   212  }
   213  
   214  var gminer *miner.Miner
   215  
   216  func GetMiner() *miner.Miner {
   217  	return gminer
   218  }
   219  
   220  func StartMining(ethereum *eth.Ethereum) bool {
   221  	if !ethereum.Mining {
   222  		ethereum.Mining = true
   223  		addr := ethereum.KeyManager().Address()
   224  
   225  		go func() {
   226  			clilogger.Infoln("Start mining")
   227  			if gminer == nil {
   228  				gminer = miner.New(addr, ethereum)
   229  			}
   230  			gminer.Start()
   231  		}()
   232  		RegisterInterrupt(func(os.Signal) {
   233  			StopMining(ethereum)
   234  		})
   235  		return true
   236  	}
   237  	return false
   238  }
   239  
   240  func FormatTransactionData(data string) []byte {
   241  	d := ethutil.StringToByteFunc(data, func(s string) (ret []byte) {
   242  		slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
   243  		for _, dataItem := range slice {
   244  			d := ethutil.FormatData(dataItem)
   245  			ret = append(ret, d...)
   246  		}
   247  		return
   248  	})
   249  
   250  	return d
   251  }
   252  
   253  func StopMining(ethereum *eth.Ethereum) bool {
   254  	if ethereum.Mining && gminer != nil {
   255  		gminer.Stop()
   256  		clilogger.Infoln("Stopped mining")
   257  		ethereum.Mining = false
   258  
   259  		return true
   260  	}
   261  
   262  	return false
   263  }
   264  
   265  // Replay block
   266  func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
   267  	block := ethereum.ChainManager().GetBlock(hash)
   268  	if block == nil {
   269  		return fmt.Errorf("unknown block %x", hash)
   270  	}
   271  
   272  	parent := ethereum.ChainManager().GetBlock(block.ParentHash())
   273  
   274  	statedb := state.New(parent.Root(), ethereum.Db())
   275  	_, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block)
   276  	if err != nil {
   277  		return err
   278  	}
   279  
   280  	return nil
   281  
   282  }
   283  
   284  func ImportChain(ethereum *eth.Ethereum, fn string) error {
   285  	clilogger.Infof("importing chain '%s'\n", fn)
   286  	fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
   287  	if err != nil {
   288  		return err
   289  	}
   290  	defer fh.Close()
   291  
   292  	var chain types.Blocks
   293  	if err := rlp.Decode(fh, &chain); err != nil {
   294  		return err
   295  	}
   296  
   297  	ethereum.ChainManager().Reset()
   298  	if err := ethereum.ChainManager().InsertChain(chain); err != nil {
   299  		return err
   300  	}
   301  	clilogger.Infof("imported %d blocks\n", len(chain))
   302  
   303  	return nil
   304  }