cmd.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright 2014 The go-ethereum Authors
  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. // Package utils contains internal helper functions for go-ethereum commands.
  17. package utils
  18. import (
  19. "bufio"
  20. "fmt"
  21. "io"
  22. "os"
  23. "os/signal"
  24. "regexp"
  25. "strings"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/eth"
  30. "github.com/ethereum/go-ethereum/logger"
  31. "github.com/ethereum/go-ethereum/logger/glog"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/peterh/liner"
  34. )
  35. const (
  36. importBatchSize = 2500
  37. legalese = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse a tincidunt magna. Phasellus a eros volutpat, sagittis ipsum sit amet, eleifend quam. Aenean venenatis ultricies feugiat. Nulla finibus arcu blandit tincidunt rutrum. Aliquam maximus convallis elementum. Etiam ornare molestie tortor, quis scelerisque est laoreet et. Sed lobortis pellentesque metus, et bibendum libero efficitur quis. Sed posuere sapien erat, vitae tempus neque maximus tincidunt. Nam fermentum lectus in scelerisque convallis. In laoreet volutpat enim, eget laoreet nulla vehicula iaculis. Pellentesque vel mattis lorem. Fusce consectetur orci at bibendum fermentum. Vestibulum venenatis vitae ipsum vel rhoncus. Nulla facilisi. Donec imperdiet, eros a eleifend dignissim, mauris lacus pharetra arcu, et aliquam lacus enim a magna. Phasellus congue consectetur tellus a vehicula.
  38. Praesent laoreet quis leo et lacinia. Cras a laoreet orci. Quisque magna nisl, dignissim eget aliquet ut, bibendum mattis justo. Fusce at tortor ligula. Nulla sollicitudin mollis euismod. Nulla enim sem, interdum ac auctor non, faucibus id risus. Duis nisi mauris, maximus vel ex ut, ullamcorper vehicula arcu. Sed nec lobortis nibh. Sed malesuada semper nulla sit amet tristique. Fusce at leo orci. Quisque nec porttitor ante. Nunc scelerisque dolor lectus, iaculis auctor mi mattis id. Donec tempor non tellus id ultricies. Praesent at felis non augue auctor efficitur.
  39. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque cursus ullamcorper dapibus. Suspendisse fringilla erat eget nunc dapibus pellentesque eget eget ante. Morbi sollicitudin nec ex eget finibus. Nam volutpat nunc at elit varius, id fringilla lectus sollicitudin. Curabitur ac varius ex. Nam commodo nibh a neque aliquam fringilla. Morbi suscipit magna sit amet enim tincidunt sollicitudin. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
  40. Ut pretium iaculis pellentesque. Nam eros tortor, malesuada a varius nec, aliquet placerat magna. Integer rutrum porttitor cursus. Praesent in pharetra turpis, eget fringilla neque. Aliquam venenatis tellus lectus, nec imperdiet nibh accumsan vel. Maecenas semper dapibus velit, ac pretium tortor. Maecenas dapibus, nunc sit amet egestas porttitor, arcu ipsum maximus lorem, non varius lorem turpis eget tortor. Cras at purus aliquam, blandit nunc placerat, imperdiet tellus. Phasellus dignissim venenatis dictum. Aliquam eu nisi nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse sit amet ultrices metus, at pulvinar eros. Suspendisse sollicitudin posuere metus sed pulvinar. Cras et velit vel sem gravida faucibus quis quis mi. Vivamus eleifend ante sit amet ultricies tincidunt.
  41. Mauris et elementum nulla. Fusce at scelerisque purus. Proin molestie sapien id velit viverra, a pharetra quam tempor. Fusce orci risus, semper et interdum at, imperdiet eget lectus. Praesent feugiat ante ut egestas tempor. Morbi convallis, quam sed mattis consequat, libero diam interdum sem, quis tempor enim nibh a ligula. Quisque est felis, pharetra nec pharetra vel, euismod et tellus. Nulla et dui nulla. Aliquam consectetur nunc ligula, sed molestie odio elementum vitae. Mauris neque nisi, venenatis et est ut, vehicula accumsan lectus.
  42. Do you accept this agreement?`
  43. )
  44. var interruptCallbacks = []func(os.Signal){}
  45. func openLogFile(Datadir string, filename string) *os.File {
  46. path := common.AbsolutePath(Datadir, filename)
  47. file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  48. if err != nil {
  49. panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
  50. }
  51. return file
  52. }
  53. func PromptConfirm(prompt string) (bool, error) {
  54. var (
  55. input string
  56. err error
  57. )
  58. prompt = prompt + " [y/N] "
  59. if liner.TerminalSupported() {
  60. lr := liner.NewLiner()
  61. defer lr.Close()
  62. input, err = lr.Prompt(prompt)
  63. } else {
  64. fmt.Print(prompt)
  65. input, err = bufio.NewReader(os.Stdin).ReadString('\n')
  66. fmt.Println()
  67. }
  68. if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
  69. return true, nil
  70. } else {
  71. return false, nil
  72. }
  73. return false, err
  74. }
  75. func PromptPassword(prompt string, warnTerm bool) (string, error) {
  76. if liner.TerminalSupported() {
  77. lr := liner.NewLiner()
  78. defer lr.Close()
  79. return lr.PasswordPrompt(prompt)
  80. }
  81. if warnTerm {
  82. fmt.Println("!! Unsupported terminal, password will be echoed.")
  83. }
  84. fmt.Print(prompt)
  85. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  86. fmt.Println()
  87. return input, err
  88. }
  89. func CheckLegalese(datadir string) {
  90. // check "first run"
  91. if !common.FileExist(datadir) {
  92. r, _ := PromptConfirm(legalese)
  93. if !r {
  94. Fatalf("Must accept to continue. Shutting down...\n")
  95. }
  96. }
  97. }
  98. // Fatalf formats a message to standard error and exits the program.
  99. // The message is also printed to standard output if standard error
  100. // is redirected to a different file.
  101. func Fatalf(format string, args ...interface{}) {
  102. w := io.MultiWriter(os.Stdout, os.Stderr)
  103. outf, _ := os.Stdout.Stat()
  104. errf, _ := os.Stderr.Stat()
  105. if outf != nil && errf != nil && os.SameFile(outf, errf) {
  106. w = os.Stderr
  107. }
  108. fmt.Fprintf(w, "Fatal: "+format+"\n", args...)
  109. logger.Flush()
  110. os.Exit(1)
  111. }
  112. func StartEthereum(ethereum *eth.Ethereum) {
  113. glog.V(logger.Info).Infoln("Starting", ethereum.Name())
  114. if err := ethereum.Start(); err != nil {
  115. Fatalf("Error starting Ethereum: %v", err)
  116. }
  117. go func() {
  118. sigc := make(chan os.Signal, 1)
  119. signal.Notify(sigc, os.Interrupt)
  120. defer signal.Stop(sigc)
  121. <-sigc
  122. glog.V(logger.Info).Infoln("Got interrupt, shutting down...")
  123. go ethereum.Stop()
  124. logger.Flush()
  125. for i := 10; i > 0; i-- {
  126. <-sigc
  127. if i > 1 {
  128. glog.V(logger.Info).Infoln("Already shutting down, please be patient.")
  129. glog.V(logger.Info).Infoln("Interrupt", i-1, "more times to induce panic.")
  130. }
  131. }
  132. glog.V(logger.Error).Infof("Force quitting: this might not end so well.")
  133. panic("boom")
  134. }()
  135. }
  136. func FormatTransactionData(data string) []byte {
  137. d := common.StringToByteFunc(data, func(s string) (ret []byte) {
  138. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  139. for _, dataItem := range slice {
  140. d := common.FormatData(dataItem)
  141. ret = append(ret, d...)
  142. }
  143. return
  144. })
  145. return d
  146. }
  147. func ImportChain(chain *core.ChainManager, fn string) error {
  148. // Watch for Ctrl-C while the import is running.
  149. // If a signal is received, the import will stop at the next batch.
  150. interrupt := make(chan os.Signal, 1)
  151. stop := make(chan struct{})
  152. signal.Notify(interrupt, os.Interrupt)
  153. defer signal.Stop(interrupt)
  154. defer close(interrupt)
  155. go func() {
  156. if _, ok := <-interrupt; ok {
  157. glog.Info("caught interrupt during import, will stop at next batch")
  158. }
  159. close(stop)
  160. }()
  161. checkInterrupt := func() bool {
  162. select {
  163. case <-stop:
  164. return true
  165. default:
  166. return false
  167. }
  168. }
  169. glog.Infoln("Importing blockchain", fn)
  170. fh, err := os.Open(fn)
  171. if err != nil {
  172. return err
  173. }
  174. defer fh.Close()
  175. stream := rlp.NewStream(fh, 0)
  176. // Run actual the import.
  177. blocks := make(types.Blocks, importBatchSize)
  178. n := 0
  179. for batch := 0; ; batch++ {
  180. // Load a batch of RLP blocks.
  181. if checkInterrupt() {
  182. return fmt.Errorf("interrupted")
  183. }
  184. i := 0
  185. for ; i < importBatchSize; i++ {
  186. var b types.Block
  187. if err := stream.Decode(&b); err == io.EOF {
  188. break
  189. } else if err != nil {
  190. return fmt.Errorf("at block %d: %v", n, err)
  191. }
  192. blocks[i] = &b
  193. n++
  194. }
  195. if i == 0 {
  196. break
  197. }
  198. // Import the batch.
  199. if checkInterrupt() {
  200. return fmt.Errorf("interrupted")
  201. }
  202. if hasAllBlocks(chain, blocks[:i]) {
  203. glog.Infof("skipping batch %d, all blocks present [%x / %x]",
  204. batch, blocks[0].Hash().Bytes()[:4], blocks[i-1].Hash().Bytes()[:4])
  205. continue
  206. }
  207. if _, err := chain.InsertChain(blocks[:i]); err != nil {
  208. return fmt.Errorf("invalid block %d: %v", n, err)
  209. }
  210. }
  211. return nil
  212. }
  213. func hasAllBlocks(chain *core.ChainManager, bs []*types.Block) bool {
  214. for _, b := range bs {
  215. if !chain.HasBlock(b.Hash()) {
  216. return false
  217. }
  218. }
  219. return true
  220. }
  221. func ExportChain(chainmgr *core.ChainManager, fn string) error {
  222. glog.Infoln("Exporting blockchain to", fn)
  223. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  224. if err != nil {
  225. return err
  226. }
  227. defer fh.Close()
  228. if err := chainmgr.Export(fh); err != nil {
  229. return err
  230. }
  231. glog.Infoln("Exported blockchain to", fn)
  232. return nil
  233. }
  234. func ExportAppendChain(chainmgr *core.ChainManager, fn string, first uint64, last uint64) error {
  235. glog.Infoln("Exporting blockchain to", fn)
  236. // TODO verify mode perms
  237. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
  238. if err != nil {
  239. return err
  240. }
  241. defer fh.Close()
  242. if err := chainmgr.ExportN(fh, first, last); err != nil {
  243. return err
  244. }
  245. glog.Infoln("Exported blockchain to", fn)
  246. return nil
  247. }