-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (85 loc) · 1.85 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
96
97
98
99
100
101
102
103
104
105
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime"
"strconv"
"github.com/BottleHub/Smart-Chain/internal/blockchain"
"github.com/BottleHub/Smart-Chain/internal/proof"
)
type CLI struct {
blockchain *blockchain.BlockChain
}
func (cli *CLI) printUsage() {
fmt.Println("Usage")
fmt.Println(" add -block BLOCK_DATA - Adds a block to the chain")
fmt.Println(" print - Prints the blocks in the chain")
}
func (cli *CLI) validateArgs() {
if len(os.Args) < 2 {
cli.printUsage()
runtime.Goexit()
}
}
func (cli *CLI) addBlock(data string) {
cli.blockchain.AddBlock(data)
fmt.Println("Added Block")
}
func (cli *CLI) printChain() {
iter := cli.blockchain.Iterator()
for {
block := iter.Next()
fmt.Printf("Previous Hash: %x\n", block.PrevHash)
fmt.Printf("Block Data: %s\n", block.Data)
fmt.Printf("Hash: %x\n", block.Hash)
pow := proof.NewProof(block)
fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.Validate()))
fmt.Println()
if len(block.PrevHash) == 0 {
break
}
}
}
func (cli *CLI) 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:])
if err != nil {
log.Fatal(err)
}
case "print":
err := printChainCMD.Parse(os.Args[2:])
if err != nil {
log.Fatal(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() {
//router := gin.Default()
chain := blockchain.Init()
defer chain.DB.Close()
cli := CLI{chain}
defer cli.run()
//router.GET("/")
//router.POST("/")
//router.POST("/create")
}