From 36cfffcb64a3b4acf37e1aef02c5c98baca9130e Mon Sep 17 00:00:00 2001 From: Wei Yang Date: Thu, 19 Oct 2017 15:42:05 +0800 Subject: [PATCH] cli: add getBlock command --- cli.go | 17 +++++++++++++++++ cli_printchain.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/cli.go b/cli.go index c23a9d3..e01794d 100644 --- a/cli.go +++ b/cli.go @@ -27,6 +27,7 @@ func (cli *CLI) printUsage() { fmt.Println(" getAddress -pubKey PUBKEY - convert pubKey to address") fmt.Println(" getPubKeyHash -address Address - get pubKeyHash of an address") fmt.Println(" validateAddress -addr Address - validate an address") + fmt.Println(" getBlock -hash BlockHash - get a block with BlockHash") } func (cli *CLI) validateArgs() { @@ -58,6 +59,7 @@ func (cli *CLI) Run() { getAddressCmd := flag.NewFlagSet("getAddress", flag.ExitOnError) getPubKeyHashCmd := flag.NewFlagSet("getPubKeyHash", flag.ExitOnError) validateAddrCmd := flag.NewFlagSet("validateAddress", flag.ExitOnError) + getBlockCmd := flag.NewFlagSet("getBlock", flag.ExitOnError) getBalanceAddress := getBalanceCmd.String("address", "", "The address to get balance for") createBlockchainAddress := createBlockchainCmd.String("address", "", "The address to send genesis block reward to") @@ -69,6 +71,7 @@ func (cli *CLI) Run() { pubKey := getAddressCmd.String("pubKey", "", "the key where address generated") pubKeyAddress := getPubKeyHashCmd.String("address", "", "the pub address") address := validateAddrCmd.String("addr", "", "the public address") + blockHash := getBlockCmd.String("hash", "", "the block hash") switch os.Args[1] { case "getbalance": @@ -131,6 +134,11 @@ func (cli *CLI) Run() { if err != nil { log.Panic(err) } + case "getBlock": + err := getBlockCmd.Parse(os.Args[2:]) + if err != nil { + log.Panic(err) + } default: cli.printUsage() os.Exit(1) @@ -217,4 +225,13 @@ func (cli *CLI) Run() { cli.validateAddr(*address) } + if getBlockCmd.Parsed() { + if *blockHash == "" { + getBlockCmd.Usage() + os.Exit(1) + } + + cli.printBlock(*blockHash, nodeID) + } + } diff --git a/cli_printchain.go b/cli_printchain.go index 6c344de..49c4deb 100644 --- a/cli_printchain.go +++ b/cli_printchain.go @@ -31,3 +31,32 @@ func (cli *CLI) printChain(nodeID string) { } } } + +func (cli *CLI) printBlock(blockHash, nodeID string) { + bc := NewBlockchain(nodeID) + defer bc.db.Close() + + bci := bc.Iterator() + + for { + block := bci.Next() + + hash := fmt.Sprintf("%x", block.Hash) + if hash == blockHash { + fmt.Printf("============ Block %x ============\n", block.Hash) + fmt.Printf("Height: %d\n", block.Height) + fmt.Printf("Prev. block: %x\n", block.PrevBlockHash) + fmt.Printf("Created at : %s\n", time.Unix(block.Timestamp, 0)) + pow := NewProofOfWork(block) + fmt.Printf("PoW: %s\n\n", strconv.FormatBool(pow.Validate())) + for _, tx := range block.Transactions { + fmt.Println(tx) + } + fmt.Printf("\n\n") + } + + if len(block.PrevBlockHash) == 0 { + break + } + } +}