-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (76 loc) · 1.74 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"flag"
"fmt"
"os"
"runtime"
"strconv"
"github.com/zadahmed/zchain/pkg/blockchain"
)
type CommandLine struct {
blockchain *blockchain.BlockChain
}
func (cli *CommandLine) printUsage() {
fmt.Println("Usage:")
fmt.Println(" add -block BLOCK_DATA - add a block to the chain")
fmt.Println(" print - Prints the blocks in the chain")
}
func (cli *CommandLine) validateArgs() {
if len(os.Args) < 2 {
cli.printUsage()
runtime.Goexit()
}
}
func (cli *CommandLine) addBlock(data string) {
cli.blockchain.AddBlock(data)
fmt.Println("Added Block!")
}
func (cli *CommandLine) printChain() {
iter := cli.blockchain.Iterator()
for {
block := iter.Next()
fmt.Printf("Prev. hash: %x\n", block.PrevHash)
fmt.Printf("Data: %s\n", block.Data)
fmt.Printf("Hash: %x\n", block.Hash)
pow := blockchain.NewProof(block)
fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.Validate()))
fmt.Println()
if len(block.PrevHash) == 0 {
break
}
}
}
func (cli *CommandLine) run() {
cli.validateArgs()
addBlockCmd := flag.NewFlagSet("add", flag.ExitOnError)
printChainCmd := flag.NewFlagSet("print", flag.ExitOnError)
addBlockData := addBlockCmd.String("block", "", "Block data")
switch os.Args[1] {
case "add":
err := addBlockCmd.Parse(os.Args[2:])
blockchain.Handle(err)
case "print":
err := printChainCmd.Parse(os.Args[2:])
blockchain.Handle(err)
default:
cli.printUsage()
runtime.Goexit()
}
if addBlockCmd.Parsed() {
if *addBlockData == "" {
addBlockCmd.Usage()
runtime.Goexit()
}
cli.addBlock(*addBlockData)
}
if printChainCmd.Parsed() {
cli.printChain()
}
}
func main() {
defer os.Exit(0)
chain := blockchain.InitBlockChain()
defer chain.Database.Close()
cli := CommandLine{chain}
cli.run()
}