slowlorisdb/core/block.go
core/block.goRaw
1package core
2
3import (
4 "encoding/json"
5 "time"
6)
7
8type Input struct {
9}
10type Output struct {
11}
12
13// Tx holds the data structure of a transaction
14type Tx struct {
15 From Address
16 To Address
17 InputCount uint64
18 Inputs []Input
19 Outputs []Output
20}
21
22func NewTx(from, to Address, in []Input, out []Output) *Tx {
23 tx := &Tx{
24 From: from,
25 To: to,
26 InputCount: uint64(len(in)),
27 Inputs: in,
28 Outputs: out,
29 }
30 return tx
31}
32
33// Block holds the data structure for the block
34type Block struct {
35 Height uint64
36 PrevHash Hash
37 NextHash Hash
38 Txs []Tx
39 Miner Address
40 Timestamp time.Time
41 Nonce uint64
42 Hash Hash
43 Signature []byte
44}
45
46func (block Block) Copy() *Block {
47 return &Block{
48 Height: block.Height,
49 PrevHash: block.PrevHash,
50 NextHash: block.NextHash,
51 Txs: block.Txs,
52 Miner: block.Miner,
53 Timestamp: block.Timestamp,
54 Nonce: block.Nonce,
55 Hash: block.Hash,
56 Signature: block.Signature,
57 }
58}
59
60// Bytes outputs a byte array containing the data of the Block
61func (blk Block) Bytes() []byte {
62 b, _ := json.Marshal(blk)
63 return b
64}
65
66func (blk *Block) GetNonce() uint64 {
67 return blk.Nonce
68}
69
70func (blk *Block) IncrementNonce() {
71 blk.Nonce++
72}
73func (block *Block) CalculatePoW(difficulty uint64) error {
74 blockCopy := block.Copy()
75 blockCopy.Hash = Hash{}
76
77 hash := HashBytes(blockCopy.Bytes())
78 for !CheckPoW(hash, difficulty) {
79 blockCopy.IncrementNonce()
80 hash = HashBytes(blockCopy.Bytes())
81 }
82 block.Hash = hash
83 return nil
84}
85
86func CheckBlockPoW(block *Block, difficulty uint64) bool {
87 blockCopy := block.Copy()
88 blockCopy.Hash = Hash{}
89 return CheckPoW(HashBytes(blockCopy.Bytes()), difficulty)
90}
91
92func BlockFromBytes(b []byte) (*Block, error) {
93 var block *Block
94 err := json.Unmarshal(b, &block)
95 return block, err
96}