/
blockchain.go
41 lines (35 loc) · 1.06 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
package blockchain
import (
"encoding/hex"
"log"
"errors"
)
// Blockchain represents the chain of blocks
type Blockchain struct {
Blocks []*Block
}
// AddBlock adds a new block to the blockchain
// Returns an error if it fails to create a new block
func (bc *Blockchain) AddBlock(data string) error {
var prevHash []byte
var err error
// Handling the case when adding the first block after the genesis block
if len(bc.Blocks) > 0 {
prevBlock := bc.Blocks[len(bc.Blocks)-1]
prevHash, err = hex.DecodeString(prevBlock.Hash)
if err != nil {
log.Printf("Failed to decode previous block hash: %v", err)
return err
}
}
newBlock := NewBlock(data, prevHash)
bc.Blocks = append(bc.Blocks, newBlock)
return nil
}
// NewBlockchain creates a new Blockchain with genesis Block
func NewBlockchain() *Blockchain {
blockchain := &Blockchain{}
genesisBlock := NewBlock("Genesis Block", []byte{})
blockchain.Blocks = append(blockchain.Blocks, genesisBlock)
return blockchain
}