/
block.go
151 lines (125 loc) · 3.27 KB
/
block.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package services
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sync"
"github.com/v4lproik/simple-blockchain-quickstart/common/utils"
Logger "github.com/v4lproik/simple-blockchain-quickstart/log"
"github.com/v4lproik/simple-blockchain-quickstart/common/models"
)
type BlockService interface {
GetNextBlocksFromHash(models.Hash) ([]models.Block, error)
Mine(context.Context, models.PendingBlock) (*models.Block, error)
ThisNodeMiningAddress() models.Account
}
type FileBlockService struct {
mu sync.Mutex
db *os.File
miningComplexity uint32
thisNodeMiningAddress models.Account
}
func NewFileBlockService(
transactionFilePath string,
miningComplexity uint32,
miningAddress models.Account,
) (*FileBlockService, error) {
db, err := os.OpenFile(transactionFilePath, os.O_APPEND|os.O_RDWR, 0o600)
if err != nil {
return nil, fmt.Errorf("NewFileBlockService: cannot open txs database: %w", err)
}
return &FileBlockService{
mu: sync.Mutex{},
db: db,
miningComplexity: miningComplexity,
thisNodeMiningAddress: miningAddress,
}, nil
}
func (a *FileBlockService) GetNextBlocksFromHash(from models.Hash) ([]models.Block, error) {
a.mu.Lock()
blocks := make([]models.Block, 0)
hasFoundHash := false
// for each block found in database
scanner := bufio.NewScanner(a.db)
for scanner.Scan() {
if err := scanner.Err(); err != nil {
return blocks, fmt.Errorf("GetNextBlocksFromHash: error while scanning: %w", err)
}
blockFsJson := scanner.Bytes()
var blockDB models.BlockDB
err := json.Unmarshal(blockFsJson, &blockDB)
if err != nil {
return blocks, err
}
if hasFoundHash {
blocks = append(blocks, blockDB.Block)
continue
}
if from == blockDB.Hash {
hasFoundHash = true
}
}
_, err := a.db.Seek(0, io.SeekStart)
if err != nil {
return blocks, fmt.Errorf("GetNextBlocksFromHash: couldn't reset pointer on dbfile: %w", err)
}
a.mu.Unlock()
return blocks, nil
}
// Mine mines a pending block meaning that it'll try to find a valid nonce
// so it can create a block in the blockchain
func (a *FileBlockService) Mine(ctx context.Context, pb models.PendingBlock) (*models.Block, error) {
var block *models.Block
if len(pb.Txs) == 0 {
return nil, errors.New("Mine: cannot mine block with empty transaction")
}
count := uint32(0)
for {
select {
case <-ctx.Done():
return block, fmt.Errorf("Mine: mining task has been shutdown")
default:
}
nonce := utils.GenerateNonce()
block = &models.Block{
Header: models.BlockHeader{
Parent: pb.Parent,
Height: pb.Height,
Nonce: nonce,
Time: pb.Time,
},
Txs: pb.Txs,
}
blockHash, err := block.Hash()
if err != nil {
// notest
return block, fmt.Errorf("Mine: failed to get block hash: %w", err)
}
var i uint32
isValid := true
for i = 0; i < a.miningComplexity; i++ {
if fmt.Sprintf("%x", blockHash[i]) != "0" {
isValid = false
break
}
}
printAttempts(count)
count++
if isValid {
Logger.Infof("Mine: attempt %d found a nonce=%d, block hash=%s", count, nonce, blockHash.Hex())
return block, nil
}
}
}
func (a *FileBlockService) ThisNodeMiningAddress() models.Account {
return a.thisNodeMiningAddress
}
func printAttempts(i uint32) {
if i%1000000 == 0 {
Logger.Debugf("attempt: %d", i+1)
}
}