arnaucube
arnaucube/slowlorisdbPublic Self-hosted repository
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
46// Bytes outputs a byte array containing the data of the Block
47func (blk Block) Bytes() []byte {
48	b, _ := json.Marshal(blk)
49	return b
50}
51
52func (blk *Block) GetNonce() uint64 {
53	return blk.Nonce
54}
55
56func (blk *Block) IncrementNonce() {
57	blk.Nonce++
58}
59func (block *Block) CalculatePoW(difficulty int) error {
60	hash := HashBytes(block.Bytes())
61	for !CheckPoW(hash, difficulty) {
62		block.IncrementNonce()
63		hash = HashBytes(block.Bytes())
64	}
65	block.Hash = hash
66	return nil
67}
68
69func BlockFromBytes(b []byte) (*Block, error) {
70	var block *Block
71	err := json.Unmarshal(b, &block)
72	return block, err
73}