-
Notifications
You must be signed in to change notification settings - Fork 1
/
dpos.go
101 lines (83 loc) · 1.68 KB
/
dpos.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
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"math/rand"
"strconv"
"time"
)
type Block struct {
Index int
PreHash string
HashCode string
BMP int
validator string
TimeStamp string
}
var Blockchain []Block
func GenerateNextBlock(oldBlock Block, BMP int, adds string) Block {
var newBlock Block
newBlock.Index = oldBlock.Index + 1
newBlock.PreHash = oldBlock.HashCode
newBlock.BMP = BMP
newBlock.TimeStamp = time.Now().String()
newBlock.validator = adds
newBlock.HashCode = GenerateHashValue(newBlock)
return newBlock
}
func GenerateHashValue(block Block) string {
var hashCode = block.PreHash + block.validator + block.TimeStamp +
strconv.Itoa(block.Index) + strconv.Itoa(block.BMP)
var sha = sha256.New()
sha.Write([]byte(hashCode))
hashed := sha.Sum(nil)
return hex.EncodeToString(hashed)
}
var delegate = []string{"aaa", "bbb", "ccc", "dddd"}
func RandDelegate() {
rand.Seed(time.Now().Unix())
var r = rand.Intn(3)
t := delegate[r]
delegate[r] = delegate[3]
delegate[3] = t
}
func main() {
fmt.Println(delegate)
var firstBlock Block
Blockchain = append(Blockchain, firstBlock)
var n = 0
ch1 := make(chan bool)
ch2 := make(chan bool)
go func() {
flag:
<-ch1
count := 0
for {
count++
time.Sleep(time.Second * 3)
var nextBlock = GenerateNextBlock(firstBlock, 1, delegate[n])
n++
n = n % len(delegate)
firstBlock = nextBlock
Blockchain = append(Blockchain, nextBlock)
fmt.Println(Blockchain)
fmt.Println(count)
if count == 10 {
count = 0
ch2 <- true
goto flag
}
}
}()
go func() {
for {
RandDelegate()
fmt.Println("", delegate)
ch1 <- true
<-ch2
}
}()
for {
}
}