-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.go
53 lines (41 loc) · 926 Bytes
/
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
package main
import "time"
type Blockchain struct {
GenesisBlock Block
Chain []Block
Difficulty int
}
func (b *Blockchain) AddBlock(data BlockData) {
lastBlock := b.Chain[len(b.Chain)-1]
newBlock := Block{
Data: data,
PreviousHash: lastBlock.Hash,
Timestamp: time.Now(),
}
newBlock.Mine(b.Difficulty)
b.Chain = append(b.Chain, newBlock)
}
func (b Blockchain) IsValid() bool {
for i := range b.Chain[1:] {
previousBlock := b.Chain[i]
currentBlock := b.Chain[i+1]
if currentBlock.PreviousHash != previousBlock.Hash {
return false
}
if currentBlock.Hash != currentBlock.CalculateHash() {
return false
}
}
return true
}
func CreateBlockchain(difficulty int) Blockchain {
genesisBlock := Block{
Hash: "0",
Timestamp: time.Now(),
}
return Blockchain{
GenesisBlock: genesisBlock,
Chain: []Block{genesisBlock},
Difficulty: difficulty,
}
}