arnaucube
arnaucube/blockchainIDsystemPublic Self-hosted repository
blockchainIDsystem/peer/blockchain.go
peer/blockchain.goRaw
 1package main
 2
 3import (
 4	"errors"
 5	"time"
 6)
 7
 8type Block struct {
 9	Hash         string    `json:"hash"`
10	Height       int64     `json:"height"`
11	Date         time.Time `json:"date"`
12	PreviousHash string    `json:"previoushash"`
13	NextHash     string    `json:"nexthash"`
14	Data         []Address `json:"data"`
15	Emitter      string    `json:"emitter"` //the ID of the peer that has emmited the block
16}
17
18type Blockchain struct {
19	GenesisBlock string    `json:"genesisblock"`
20	LastUpdate   time.Time `json:"lastupdate"`
21	Blocks       []Block   `json:"blocks"`
22}
23
24var blockchain Blockchain
25
26func (bc *Blockchain) getBlockByHash(hash string) (Block, error) {
27	for _, block := range bc.Blocks {
28		if block.Hash == hash {
29			return block, nil
30		}
31	}
32	var b Block
33	return b, errors.New("Block Hash not found")
34}
35
36func (bc *Blockchain) createBlock(address Address) Block {
37	var b Block
38	b.Height = int64(len(bc.Blocks))
39	if len(bc.Blocks) == 0 {
40		b.Height = 0
41	} else {
42		b.PreviousHash = bc.Blocks[len(bc.Blocks)-1].Hash
43	}
44	b.Date = time.Now()
45	b.Data = append(b.Data, address)
46	b.Emitter = runningPeer.ID
47
48	b.Hash = hashBlock(b)
49	return b
50}
51
52func (bc *Blockchain) blockExists(block Block) bool {
53	for _, b := range bc.Blocks {
54		if b.Hash == block.Hash {
55			return true
56		}
57	}
58	return false
59}
60func (bc *Blockchain) addBlock(block Block) error {
61	if len(bc.Blocks) > 0 {
62		bc.Blocks[len(bc.Blocks)-1].NextHash = block.Hash
63	} else {
64		bc.GenesisBlock = block.Hash
65	}
66	bc.Blocks = append(bc.Blocks, block)
67
68	return nil
69}