2017-08-28 09:03:43 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-08-29 00:09:47 -05:00
|
|
|
"flag"
|
2017-08-28 09:03:43 -05:00
|
|
|
"fmt"
|
2017-08-29 00:09:47 -05:00
|
|
|
"log"
|
2017-08-28 09:03:43 -05:00
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
// CLI responsible for processing command line arguments
|
|
|
|
type CLI struct {
|
|
|
|
bc *Blockchain
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cli *CLI) printUsage() {
|
|
|
|
fmt.Println("Usage:")
|
2017-08-29 00:09:47 -05:00
|
|
|
fmt.Println(" addblock -data BLOCK_DATA - add a block to the blockchain")
|
|
|
|
fmt.Println(" printchain - print all the blocks of the blockchain")
|
2017-08-28 09:03:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cli *CLI) validateArgs() {
|
|
|
|
if len(os.Args) < 2 {
|
|
|
|
cli.printUsage()
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-29 00:09:47 -05:00
|
|
|
func (cli *CLI) addBlock(data string) {
|
|
|
|
cli.bc.AddBlock(data)
|
2017-08-28 09:03:43 -05:00
|
|
|
fmt.Println("Success!")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cli *CLI) printChain() {
|
|
|
|
bci := cli.bc.Iterator()
|
|
|
|
|
|
|
|
for {
|
|
|
|
block := bci.Next()
|
|
|
|
|
|
|
|
fmt.Printf("Prev. hash: %x\n", block.PrevBlockHash)
|
|
|
|
fmt.Printf("Data: %s\n", block.Data)
|
|
|
|
fmt.Printf("Hash: %x\n", block.Hash)
|
|
|
|
pow := NewProofOfWork(block)
|
|
|
|
fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.Validate()))
|
|
|
|
fmt.Println()
|
|
|
|
|
|
|
|
if len(block.PrevBlockHash) == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-29 00:09:47 -05:00
|
|
|
// Run parses command line arguments and processes commands
|
|
|
|
func (cli *CLI) Run() {
|
2017-08-28 09:03:43 -05:00
|
|
|
cli.validateArgs()
|
|
|
|
|
2017-08-29 00:09:47 -05:00
|
|
|
addBlockCmd := flag.NewFlagSet("addblock", flag.ExitOnError)
|
|
|
|
printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError)
|
|
|
|
|
|
|
|
addBlockData := addBlockCmd.String("data", "", "Block data")
|
|
|
|
|
2017-08-28 09:03:43 -05:00
|
|
|
switch os.Args[1] {
|
2017-08-29 00:09:47 -05:00
|
|
|
case "addblock":
|
|
|
|
err := addBlockCmd.Parse(os.Args[2:])
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
|
|
|
case "printchain":
|
|
|
|
err := printChainCmd.Parse(os.Args[2:])
|
|
|
|
if err != nil {
|
|
|
|
log.Panic(err)
|
|
|
|
}
|
2017-08-28 09:03:43 -05:00
|
|
|
default:
|
|
|
|
cli.printUsage()
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2017-08-29 00:09:47 -05:00
|
|
|
|
|
|
|
if addBlockCmd.Parsed() {
|
|
|
|
if *addBlockData == "" {
|
|
|
|
addBlockCmd.Usage()
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
cli.addBlock(*addBlockData)
|
|
|
|
}
|
|
|
|
|
|
|
|
if printChainCmd.Parsed() {
|
|
|
|
cli.printChain()
|
|
|
|
}
|
2017-08-28 09:03:43 -05:00
|
|
|
}
|