cmd.go 5.3 KB
Newer Older
obscuren's avatar
obscuren committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
	This file is part of go-ethereum

	go-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	go-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with go-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @authors
 * 	Jeffrey Wilcke <i@jev.io>
 * 	Viktor Tron <viktor@ethdev.com>
 */
22 23 24
package utils

import (
25
	"bufio"
zelig's avatar
zelig committed
26
	"fmt"
27
	"io"
28 29
	"os"
	"os/signal"
obscuren's avatar
obscuren committed
30
	"regexp"
31
	"strings"
32

33
	"github.com/ethereum/go-ethereum/common"
34
	"github.com/ethereum/go-ethereum/core"
obscuren's avatar
obscuren committed
35
	"github.com/ethereum/go-ethereum/core/types"
zelig's avatar
zelig committed
36
	"github.com/ethereum/go-ethereum/eth"
obscuren's avatar
obscuren committed
37
	"github.com/ethereum/go-ethereum/logger"
obscuren's avatar
obscuren committed
38
	"github.com/ethereum/go-ethereum/logger/glog"
obscuren's avatar
obscuren committed
39
	"github.com/ethereum/go-ethereum/rlp"
40
	"github.com/peterh/liner"
41 42
)

zelig's avatar
zelig committed
43
var interruptCallbacks = []func(os.Signal){}
44

zelig's avatar
zelig committed
45
// Register interrupt handlers callbacks
46
func RegisterInterrupt(cb func(os.Signal)) {
zelig's avatar
zelig committed
47
	interruptCallbacks = append(interruptCallbacks, cb)
zelig's avatar
zelig committed
48 49 50 51
}

// go routine that call interrupt handlers in order of registering
func HandleInterrupt() {
zelig's avatar
zelig committed
52 53 54 55
	c := make(chan os.Signal, 1)
	go func() {
		signal.Notify(c, os.Interrupt)
		for sig := range c {
obscuren's avatar
obscuren committed
56
			glog.V(logger.Error).Infof("Shutting down (%v) ... \n", sig)
zelig's avatar
zelig committed
57 58 59
			RunInterruptCallbacks(sig)
		}
	}()
60 61
}

zelig's avatar
zelig committed
62
func RunInterruptCallbacks(sig os.Signal) {
zelig's avatar
zelig committed
63 64 65
	for _, cb := range interruptCallbacks {
		cb(sig)
	}
zelig's avatar
zelig committed
66 67
}

zelig's avatar
zelig committed
68
func openLogFile(Datadir string, filename string) *os.File {
obscuren's avatar
obscuren committed
69
	path := common.AbsolutePath(Datadir, filename)
zelig's avatar
zelig committed
70 71 72 73 74 75 76
	file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
	}
	return file
}

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
func PromptConfirm(prompt string) (bool, error) {
	var (
		input string
		err   error
	)
	prompt = prompt + " [y/N] "

	if liner.TerminalSupported() {
		lr := liner.NewLiner()
		defer lr.Close()
		input, err = lr.Prompt(prompt)
	} else {
		fmt.Print(prompt)
		input, err = bufio.NewReader(os.Stdin).ReadString('\n')
		fmt.Println()
	}

	if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
		return true, nil
	} else {
		return false, nil
	}

	return false, err
}

func PromptPassword(prompt string, warnTerm bool) (string, error) {
	if liner.TerminalSupported() {
		lr := liner.NewLiner()
		defer lr.Close()
		return lr.PasswordPrompt(prompt)
	}
	if warnTerm {
		fmt.Println("!! Unsupported terminal, password will be echoed.")
	}
	fmt.Print(prompt)
	input, err := bufio.NewReader(os.Stdin).ReadString('\n')
	fmt.Println()
	return input, err
}

obscuren's avatar
obscuren committed
118
func initDataDir(Datadir string) {
zelig's avatar
zelig committed
119 120 121
	_, err := os.Stat(Datadir)
	if err != nil {
		if os.IsNotExist(err) {
122
			fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
zelig's avatar
zelig committed
123 124 125 126 127
			os.Mkdir(Datadir, 0777)
		}
	}
}

128 129 130
// Fatalf formats a message to standard output and exits the program.
func Fatalf(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, "Fatal: "+format+"\n", args...)
131
	fmt.Fprintf(os.Stdout, "Fatal: "+format+"\n", args...)
132 133 134 135
	logger.Flush()
	os.Exit(1)
}

136
func StartEthereum(ethereum *eth.Ethereum) {
137
	glog.V(logger.Info).Infoln("Starting", ethereum.Name())
138
	if err := ethereum.Start(); err != nil {
139
		Fatalf("Error starting Ethereum: %v", err)
obscuren's avatar
obscuren committed
140
	}
zelig's avatar
zelig committed
141 142
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
obscuren's avatar
obscuren committed
143
		logger.Flush()
zelig's avatar
zelig committed
144
	})
145
}
obscuren's avatar
obscuren committed
146

147
func StartEthereumForTest(ethereum *eth.Ethereum) {
obscuren's avatar
obscuren committed
148
	glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
149 150 151 152 153 154 155
	ethereum.StartForTest()
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
		logger.Flush()
	})
}

obscuren's avatar
obscuren committed
156
func FormatTransactionData(data string) []byte {
obscuren's avatar
obscuren committed
157
	d := common.StringToByteFunc(data, func(s string) (ret []byte) {
obscuren's avatar
obscuren committed
158 159
		slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
		for _, dataItem := range slice {
obscuren's avatar
obscuren committed
160
			d := common.FormatData(dataItem)
obscuren's avatar
obscuren committed
161 162 163 164 165 166 167 168
			ret = append(ret, d...)
		}
		return
	})

	return d
}

169 170
func ImportChain(chainmgr *core.ChainManager, fn string) error {
	fmt.Printf("importing blockchain '%s'\n", fn)
obscuren's avatar
obscuren committed
171 172 173 174 175 176
	fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
	if err != nil {
		return err
	}
	defer fh.Close()

177
	chainmgr.Reset()
178
	stream := rlp.NewStream(fh, 0)
179 180 181 182 183
	var i, n int

	batchSize := 2500
	blocks := make(types.Blocks, batchSize)

184 185
	for ; ; i++ {
		var b types.Block
186
		if err := stream.Decode(&b); err == io.EOF {
187 188 189 190
			break
		} else if err != nil {
			return fmt.Errorf("at block %d: %v", i, err)
		}
191 192 193 194 195

		blocks[n] = &b
		n++

		if n == batchSize {
196
			if _, err := chainmgr.InsertChain(blocks); err != nil {
197 198 199 200 201 202 203 204
				return fmt.Errorf("invalid block %v", err)
			}
			n = 0
			blocks = make(types.Blocks, batchSize)
		}
	}

	if n > 0 {
205
		if _, err := chainmgr.InsertChain(blocks[:n]); err != nil {
206
			return fmt.Errorf("invalid block %v", err)
207
		}
obscuren's avatar
obscuren committed
208
	}
209

210
	fmt.Printf("imported %d blocks\n", i)
obscuren's avatar
obscuren committed
211 212
	return nil
}
213 214 215

func ExportChain(chainmgr *core.ChainManager, fn string) error {
	fmt.Printf("exporting blockchain '%s'\n", fn)
216
	fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
217 218 219 220 221
	if err != nil {
		return err
	}
	defer fh.Close()
	if err := chainmgr.Export(fh); err != nil {
222 223 224 225 226
		return err
	}
	fmt.Printf("exported blockchain\n")
	return nil
}