github.com/Gessiux/neatchain@v1.3.1/utilities/utils/cmd.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of go-neatchain.
     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-neatchain. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package utils contains internal helper functions for go-ethereum commands.
    18  package utils
    19  
    20  import (
    21  	"compress/gzip"
    22  	"fmt"
    23  	"io"
    24  	"os"
    25  	"os/signal"
    26  	"runtime"
    27  	"strings"
    28  	"syscall"
    29  
    30  	"github.com/Gessiux/neatchain/chain/consensus"
    31  	neatptc "github.com/Gessiux/neatchain/neatptc"
    32  	"gopkg.in/urfave/cli.v1"
    33  
    34  	"github.com/Gessiux/neatchain/chain/core"
    35  	"github.com/Gessiux/neatchain/chain/core/rawdb"
    36  	"github.com/Gessiux/neatchain/chain/core/types"
    37  	"github.com/Gessiux/neatchain/chain/log"
    38  	"github.com/Gessiux/neatchain/neatdb"
    39  	"github.com/Gessiux/neatchain/network/node"
    40  	"github.com/Gessiux/neatchain/utilities/common"
    41  	"github.com/Gessiux/neatchain/utilities/crypto"
    42  	"github.com/Gessiux/neatchain/utilities/rlp"
    43  )
    44  
    45  const (
    46  	importBatchSize = 2500
    47  )
    48  
    49  // Fatalf formats a message to standard error and exits the program.
    50  // The message is also printed to standard output if standard error
    51  // is redirected to a different file.
    52  func Fatalf(format string, args ...interface{}) {
    53  	w := io.MultiWriter(os.Stdout, os.Stderr)
    54  	if runtime.GOOS == "windows" {
    55  		// The SameFile check below doesn't work on Windows.
    56  		// stdout is unlikely to get redirected though, so just print there.
    57  		w = os.Stdout
    58  	} else {
    59  		outf, _ := os.Stdout.Stat()
    60  		errf, _ := os.Stderr.Stat()
    61  		if outf != nil && errf != nil && os.SameFile(outf, errf) {
    62  			w = os.Stderr
    63  		}
    64  	}
    65  	fmt.Fprintf(w, "Fatal: "+format+"\n", args...)
    66  	os.Exit(1)
    67  }
    68  
    69  func StartNode(ctx *cli.Context, stack *node.Node) error {
    70  	if err := stack.Start1(); err != nil {
    71  		Fatalf("Error starting protocol stack: %v", err)
    72  	}
    73  	//go func() {
    74  	//	sigc := make(chan os.Signal, 1)
    75  	//	signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
    76  	//	defer signal.Stop(sigc)
    77  	//	<-sigc
    78  	//	log.Info("Got interrupt, shutting down...")
    79  	//	go stack.Stop()
    80  	//	for i := 10; i > 0; i-- {
    81  	//		<-sigc
    82  	//		if i > 1 {
    83  	//			log.Warn("Already shutting down, interrupt more to panic.", "times", i-1)
    84  	//		}
    85  	//	}
    86  	//	debug.Exit() // ensure trace and CPU profile data is flushed.
    87  	//	debug.LoudPanic("boom")
    88  	//}()
    89  
    90  	mining := false
    91  	var neatchain *neatptc.NeatChain
    92  	if err := stack.Service(&neatchain); err == nil {
    93  		if neatcon, ok := neatchain.Engine().(consensus.NeatCon); ok {
    94  			mining = neatcon.ShouldStart()
    95  			if mining {
    96  				stack.GetLogger().Info("NeatCon Consensus Engine will be start shortly")
    97  			}
    98  		}
    99  	}
   100  
   101  	// Start auxiliary services if enabled
   102  	if mining || ctx.GlobalBool(DeveloperFlag.Name) {
   103  		stack.GetLogger().Info("Mine will be start shortly")
   104  		// Mining only makes sense if a full neatchain node is running
   105  		var neatchain *neatptc.NeatChain
   106  		if err := stack.Service(&neatchain); err != nil {
   107  			Fatalf("NEAT Chain service not running: %v", err)
   108  		}
   109  
   110  		// Use a reduced number of threads if requested
   111  		if threads := ctx.GlobalInt(MinerThreadsFlag.Name); threads > 0 {
   112  			type threaded interface {
   113  				SetThreads(threads int)
   114  			}
   115  			if th, ok := neatchain.Engine().(threaded); ok {
   116  				th.SetThreads(threads)
   117  			}
   118  		}
   119  		// Set the gas price to the limits from the CLI and start mining
   120  		neatchain.TxPool().SetGasPrice(GlobalBig(ctx, MinerGasPriceFlag.Name))
   121  		if err := neatchain.StartMining(true); err != nil {
   122  			Fatalf("Failed to start mining: %v", err)
   123  		}
   124  	}
   125  
   126  	return nil
   127  }
   128  
   129  func ImportChain(chain *core.BlockChain, fn string) error {
   130  	// Watch for Ctrl-C while the import is running.
   131  	// If a signal is received, the import will stop at the next batch.
   132  	interrupt := make(chan os.Signal, 1)
   133  	stop := make(chan struct{})
   134  	signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
   135  	defer signal.Stop(interrupt)
   136  	defer close(interrupt)
   137  	go func() {
   138  		if _, ok := <-interrupt; ok {
   139  			log.Info("Interrupted during import, stopping at next batch")
   140  		}
   141  		close(stop)
   142  	}()
   143  	checkInterrupt := func() bool {
   144  		select {
   145  		case <-stop:
   146  			return true
   147  		default:
   148  			return false
   149  		}
   150  	}
   151  
   152  	log.Info("Importing blockchain", "file", fn)
   153  	fh, err := os.Open(fn)
   154  	if err != nil {
   155  		return err
   156  	}
   157  	defer fh.Close()
   158  
   159  	var reader io.Reader = fh
   160  	if strings.HasSuffix(fn, ".gz") {
   161  		if reader, err = gzip.NewReader(reader); err != nil {
   162  			return err
   163  		}
   164  	}
   165  	stream := rlp.NewStream(reader, 0)
   166  
   167  	// Run actual the import.
   168  	blocks := make(types.Blocks, importBatchSize)
   169  	n := 0
   170  	for batch := 0; ; batch++ {
   171  		// Load a batch of RLP blocks.
   172  		if checkInterrupt() {
   173  			return fmt.Errorf("interrupted")
   174  		}
   175  		i := 0
   176  		for ; i < importBatchSize; i++ {
   177  			var b types.Block
   178  			if err := stream.Decode(&b); err == io.EOF {
   179  				break
   180  			} else if err != nil {
   181  				return fmt.Errorf("at block %d: %v", n, err)
   182  			}
   183  			// don't import first block
   184  			if b.NumberU64() == 0 {
   185  				i--
   186  				continue
   187  			}
   188  			blocks[i] = &b
   189  			n++
   190  		}
   191  		if i == 0 {
   192  			break
   193  		}
   194  		// Import the batch.
   195  		if checkInterrupt() {
   196  			return fmt.Errorf("interrupted")
   197  		}
   198  		missing := missingBlocks(chain, blocks[:i])
   199  		if len(missing) == 0 {
   200  			log.Info("Skipping batch as all blocks present", "batch", batch, "first", blocks[0].Hash(), "last", blocks[i-1].Hash())
   201  			continue
   202  		}
   203  		if _, err := chain.InsertChain(missing); err != nil {
   204  			return fmt.Errorf("invalid block %d: %v", n, err)
   205  		}
   206  	}
   207  	return nil
   208  }
   209  
   210  func missingBlocks(chain *core.BlockChain, blocks []*types.Block) []*types.Block {
   211  	head := chain.CurrentBlock()
   212  	for i, block := range blocks {
   213  		// If we're behind the chain head, only check block, state is available at head
   214  		if head.NumberU64() > block.NumberU64() {
   215  			if !chain.HasBlock(block.Hash(), block.NumberU64()) {
   216  				return blocks[i:]
   217  			}
   218  			continue
   219  		}
   220  		// If we're above the chain head, state availability is a must
   221  		if !chain.HasBlockAndState(block.Hash(), block.NumberU64()) {
   222  			return blocks[i:]
   223  		}
   224  	}
   225  	return nil
   226  }
   227  
   228  func ExportChain(blockchain *core.BlockChain, fn string) error {
   229  	log.Info("Exporting blockchain", "file", fn)
   230  	fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
   231  	if err != nil {
   232  		return err
   233  	}
   234  	defer fh.Close()
   235  
   236  	var writer io.Writer = fh
   237  	if strings.HasSuffix(fn, ".gz") {
   238  		writer = gzip.NewWriter(writer)
   239  		defer writer.(*gzip.Writer).Close()
   240  	}
   241  
   242  	if err := blockchain.Export(writer); err != nil {
   243  		return err
   244  	}
   245  	log.Info("Exported blockchain", "file", fn)
   246  
   247  	return nil
   248  }
   249  
   250  func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, last uint64) error {
   251  	log.Info("Exporting blockchain", "file", fn)
   252  	// TODO verify mode perms
   253  	fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
   254  	if err != nil {
   255  		return err
   256  	}
   257  	defer fh.Close()
   258  
   259  	var writer io.Writer = fh
   260  	if strings.HasSuffix(fn, ".gz") {
   261  		writer = gzip.NewWriter(writer)
   262  		defer writer.(*gzip.Writer).Close()
   263  	}
   264  
   265  	if err := blockchain.ExportN(writer, first, last); err != nil {
   266  		return err
   267  	}
   268  	log.Info("Exported blockchain to", "file", fn)
   269  	return nil
   270  }
   271  
   272  // ImportPreimages imports a batch of exported hash preimages into the database.
   273  func ImportPreimages(db neatdb.Database, fn string) error {
   274  	log.Info("Importing preimages", "file", fn)
   275  
   276  	// Open the file handle and potentially unwrap the gzip stream
   277  	fh, err := os.Open(fn)
   278  	if err != nil {
   279  		return err
   280  	}
   281  	defer fh.Close()
   282  
   283  	var reader io.Reader = fh
   284  	if strings.HasSuffix(fn, ".gz") {
   285  		if reader, err = gzip.NewReader(reader); err != nil {
   286  			return err
   287  		}
   288  	}
   289  	stream := rlp.NewStream(reader, 0)
   290  
   291  	// Import the preimages in batches to prevent disk trashing
   292  	preimages := make(map[common.Hash][]byte)
   293  
   294  	for {
   295  		// Read the next entry and ensure it's not junk
   296  		var blob []byte
   297  
   298  		if err := stream.Decode(&blob); err != nil {
   299  			if err == io.EOF {
   300  				break
   301  			}
   302  			return err
   303  		}
   304  		// Accumulate the preimages and flush when enough ws gathered
   305  		preimages[crypto.Keccak256Hash(blob)] = common.CopyBytes(blob)
   306  		if len(preimages) > 1024 {
   307  			rawdb.WritePreimages(db, preimages)
   308  			preimages = make(map[common.Hash][]byte)
   309  		}
   310  	}
   311  	// Flush the last batch preimage data
   312  	if len(preimages) > 0 {
   313  		rawdb.WritePreimages(db, preimages)
   314  	}
   315  	return nil
   316  }
   317  
   318  // ExportPreimages exports all known hash preimages into the specified file,
   319  // truncating any data already present in the file.
   320  func ExportPreimages(db neatdb.Database, fn string) error {
   321  	log.Info("Exporting preimages", "file", fn)
   322  
   323  	// Open the file handle and potentially wrap with a gzip stream
   324  	fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
   325  	if err != nil {
   326  		return err
   327  	}
   328  	defer fh.Close()
   329  
   330  	var writer io.Writer = fh
   331  	if strings.HasSuffix(fn, ".gz") {
   332  		writer = gzip.NewWriter(writer)
   333  		defer writer.(*gzip.Writer).Close()
   334  	}
   335  	// Iterate over the preimages and export them
   336  	it := db.NewIteratorWithPrefix([]byte("secure-key-"))
   337  	defer it.Release()
   338  
   339  	for it.Next() {
   340  		if err := rlp.Encode(writer, it.Value()); err != nil {
   341  			return err
   342  		}
   343  	}
   344  	log.Info("Exported preimages", "file", fn)
   345  	return nil
   346  }