-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (72 loc) · 1.46 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
package main
import (
"time"
"net"
"fmt"
"io"
"bufio"
"encoding/json"
"github.com/astaxie/beego"
"EZChain/blockchain"
"EZChain/g"
"EZChain/utils"
_ "EZChain/routers"
)
func handleConn(conn net.Conn) {
//defer conn.Close()
io.WriteString(conn, "Input Message:")
scanner := bufio.NewScanner(conn)
go func() {
for scanner.Scan() {
newBlock := blockchain.BC.GenerateBlock(blockchain.BC.Blockchain[len(blockchain.BC.Blockchain)-1], scanner.Text())
utils.PrintBlock(newBlock)
io.WriteString(conn, "\nInput Message:")
}
}()
// 模拟接收广播
go func() {
for {
// 每 30 秒接收一次
time.Sleep(time.Second * 30)
g.Mutex.Lock()
output, err := json.Marshal(blockchain.BC.Blockchain)
if err != nil {
fmt.Println(err)
}
g.Mutex.Unlock()
io.WriteString(conn, string(output) + "\n\n")
}
}()
}
func main() {
oldBlock := blockchain.Block{
Index: -1,
PrevHash: "",
Timestamp: 0,
Nonce: 0,
Hash: "",
Difficulty: g.Difficulty,
Info: "old",
MerkleRootHash: " ",
}
genesisBlock := blockchain.BC.GenerateBlock(oldBlock, "First Block")
utils.PrintBlock(genesisBlock)
// 维护链
go blockchain.BC.TimingFixBlockchain(5)
// 监听 7190 端口
go func() {
listener, err := net.Listen("tcp", ":7190")
if err != nil {
fmt.Println(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
}
go handleConn(conn)
}
}()
beego.Run()
}