arnaucube
arnaucube/slowlorisdbPublic Self-hosted repository
slowlorisdb/core/blockchain.go
core/blockchain.goRaw
 1package core
 2
 3import (
 4	"errors"
 5	"time"
 6
 7	"github.com/arnaucube/slowlorisdb/db"
 8)
 9
10type Blockchain struct {
11	Id         []byte // Id allows to have multiple blockchains
12	Difficulty uint64
13	Genesis    Hash
14	LastBlock  *Block
15	db         *db.Db
16}
17
18func NewBlockchain(database *db.Db, dif uint64) *Blockchain {
19	blockchain := &Blockchain{
20		Id:         []byte{},
21		Difficulty: dif,
22		Genesis:    HashBytes([]byte("genesis")),
23		LastBlock:  &Block{},
24		db:         database,
25	}
26	return blockchain
27}
28
29func (bc *Blockchain) NewBlock(txs []Tx) *Block {
30	block := &Block{
31		Height:    bc.GetHeight() + 1,
32		PrevHash:  bc.LastBlock.Hash,
33		Txs:       txs,
34		Miner:     Address{}, // TODO put the node address
35		Timestamp: time.Now(),
36		Nonce:     0,
37		Hash:      Hash{},
38		Signature: []byte{},
39	}
40	return block
41}
42
43func (bc *Blockchain) GetHeight() uint64 {
44	return bc.LastBlock.Height
45}
46
47func (bc *Blockchain) GetLastBlock() *Block {
48	return bc.LastBlock
49}
50
51func (bc *Blockchain) AddBlock(block *Block) error {
52	bc.LastBlock = block
53	err := bc.db.Put(block.Hash[:], block.Bytes())
54	return err
55}
56
57func (bc *Blockchain) GetBlock(hash Hash) (*Block, error) {
58	v, err := bc.db.Get(hash[:])
59	if err != nil {
60		return nil, err
61	}
62	block, err := BlockFromBytes(v)
63	if err != nil {
64		return nil, err
65	}
66	return block, nil
67}
68
69func (bc *Blockchain) GetPrevBlock(hash Hash) (*Block, error) {
70	currentBlock, err := bc.GetBlock(hash)
71	if err != nil {
72		return nil, err
73	}
74	if currentBlock.PrevHash.IsZero() {
75		return nil, errors.New("This was the oldest block")
76	}
77	prevBlock, err := bc.GetBlock(currentBlock.PrevHash)
78	if err != nil {
79		return nil, err
80	}
81
82	return prevBlock, nil
83}