/
blockchain.go
64 lines (52 loc) · 1.28 KB
/
blockchain.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
// implement a simple p2p blockchain which use dpos algorithm.
// this file just for a simple block generate and validate.
// This file is created by magic at 2018-9-2
package dpos
import (
"crypto/sha256"
"encoding/hex"
"time"
)
var BlockChain []Block
type Block struct {
Index int
Timestamp string
BPM int
Hash string
PrevHash string
validator string
}
// 计算string的hash值
func CaculateHash(s string) string {
h := sha256.New()
h.Write([]byte(s))
hashed := h.Sum(nil)
return hex.EncodeToString(hashed)
}
func CaculateBlockHash(block Block) string {
record := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash
return CaculateHash(record)
}
func GenerateBlock(oldBlock Block, BPM int, address string) (Block, error) {
var newBlock Block
t := time.Now()
newBlock.Index = oldBlock.Index + 1
newBlock.BPM = BPM
newBlock.Timestamp = t.String()
newBlock.PrevHash = oldBlock.Hash
newBlock.Hash = CaculateBlockHash(newBlock)
newBlock.validator = address
return newBlock, nil
}
func IsBlockValid(newBlock, oldBlock Block) bool {
if oldBlock.Index+1 != newBlock.Index {
return false
}
if oldBlock.Hash != newBlock.PrevHash {
return false
}
if CaculateBlockHash(newBlock) != newBlock.Hash {
return false
}
return true
}