This repository has been archived by the owner on Jun 16, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
122 lines (94 loc) · 2.18 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"bufio"
"encoding/binary"
"fmt"
"net"
"os"
"strconv"
"strings"
blockchain "github.com/pmh-only/blockchain/src"
)
func main() {
DATA_DIRECTORY := os.Getenv("DATA_DIRECTORY")
if len(DATA_DIRECTORY) < 1 {
DATA_DIRECTORY = "./data"
}
args := os.Args[1:]
if len(args) < 1 {
println("Invalid Subcommnd\n")
return
}
subcmd := args[0]
chain := blockchain.Load(DATA_DIRECTORY)
fmt.Printf("Chain Valid: %v\n", chain.IsValid())
fmt.Printf("Chain Length: %d blocks\n", len(chain.Blocks))
fmt.Println()
if subcmd == "list" {
for _, block := range chain.Blocks {
fmt.Printf("%d. (%d) %s\n", block.Head.Index, block.Body.Flag, block.Body.Message)
}
return
}
if subcmd == "list-detail" {
for _, block := range chain.Blocks {
fmt.Printf("\nIndex: %d\nCreatedAt: %d\nPrevHash: %x\nNonce: %d\nDifficulty: %d\nBody: (%d) %s\nCurrHash: %x\n",
block.Head.Index,
block.Head.CreatedAt,
block.Head.PrevHash,
block.Head.Nonce,
block.Head.Difficulty,
block.Body.Flag,
block.Body.Message,
block.Tail.CurrHash,
)
}
return
}
if subcmd == "add" {
if len(args) < 2 {
println("Uncompleted Subcommand")
return
}
data := strings.Join(args[1:], " ")
chain.AddStringBlock(data)
chain.Save(DATA_DIRECTORY)
lastCreated := chain.GetLatestBlock()
fmt.Printf("Block Created:\n%x", lastCreated.SerializationWithTail())
return
}
if subcmd == "drop" {
chain.Drop(DATA_DIRECTORY)
println("Dropped")
}
if subcmd == "serve" {
if len(args) < 2 {
println("Uncompleted Subcommand")
return
}
port, _ := strconv.Atoi(args[1])
peer := chain.CreatePeer(port)
chain.AddPeerBlock(peer)
chain.Save(DATA_DIRECTORY)
peer.Open()
}
if subcmd == "client-test" {
if len(args) < 3 {
println("Uncompleted Subcommand")
return
}
packet := make([]byte, 2048)
indexraw, _ := strconv.Atoi(args[2])
index := make([]byte, 2)
binary.BigEndian.PutUint16(index, uint16(indexraw))
conn, _ := net.Dial("udp", args[1])
conn.Write(index)
_, err := bufio.NewReader(conn).Read(packet)
if err == nil {
fmt.Printf("%s\n", packet)
} else {
fmt.Printf("Some error %v\n", err)
}
conn.Close()
}
}