-
Notifications
You must be signed in to change notification settings - Fork 165
/
blockchain.go
51 lines (41 loc) · 1.12 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
package blockchain
import (
"crypto/sha256"
"encoding/hex"
)
// Block keeps block headers
type Block struct {
Data string
PrevBlockHash string
Hash string
}
// Blockchain keeps a sequence of Blocks
type Blockchain struct {
Blocks []*Block
}
// setHash calculates and sets block hash
func (b *Block) setHash() {
hash := sha256.Sum256([]byte(b.PrevBlockHash + b.Data))
b.Hash = hex.EncodeToString(hash[:])
}
// NewBlock creates and returns Block
func NewBlock(data string, prevBlockHash string) *Block {
block := &Block{data, prevBlockHash, ""}
block.setHash()
return block
}
// NewGenesisBlock creates and returns genesis Block
func NewGenesisBlock() *Block {
return NewBlock("Genesis Block", "")
}
// AddBlock saves provided data as a block in the blockchain
func (bc *Blockchain) AddBlock(data string) *Block {
prevBlock := bc.Blocks[len(bc.Blocks)-1]
newBlock := NewBlock(data, prevBlock.Hash)
bc.Blocks = append(bc.Blocks, newBlock)
return newBlock
}
// NewBlockchain creates a new Blockchain with genesis Block
func NewBlockchain() *Blockchain {
return &Blockchain{[]*Block{NewGenesisBlock()}}
}