cli: add getBlock command

This commit is contained in:
Wei Yang 2017-10-19 15:42:05 +08:00
parent 5f4f2f518d
commit 36cfffcb64
2 changed files with 46 additions and 0 deletions

17
cli.go
View File

@ -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)
}
}

View File

@ -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
}
}
}