forked from kaspanet/kaspad
/
pruning_violation_proof_of_work_and_difficulty.go
258 lines (214 loc) · 7.37 KB
/
pruning_violation_proof_of_work_and_difficulty.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package blockvalidator
import (
"github.com/Hoosat-Oy/HTND/domain/consensus/model"
"github.com/Hoosat-Oy/HTND/domain/consensus/model/externalapi"
"github.com/Hoosat-Oy/HTND/domain/consensus/ruleerrors"
"github.com/Hoosat-Oy/HTND/domain/consensus/utils/pow"
"github.com/Hoosat-Oy/HTND/domain/consensus/utils/virtual"
"github.com/Hoosat-Oy/HTND/infrastructure/db/database"
"github.com/Hoosat-Oy/HTND/infrastructure/logger"
"github.com/pkg/errors"
)
func (v *blockValidator) ValidatePruningPointViolationAndProofOfWorkAndDifficulty(stagingArea *model.StagingArea,
blockHash *externalapi.DomainHash, isBlockWithTrustedData bool) error {
onEnd := logger.LogAndMeasureExecutionTime(log, "ValidatePruningPointViolationAndProofOfWorkAndDifficulty")
defer onEnd()
header, err := v.blockHeaderStore.BlockHeader(v.databaseContext, stagingArea, blockHash)
if err != nil {
return err
}
err = v.checkParentNotVirtualGenesis(header)
if err != nil {
return err
}
err = v.checkParentHeadersExist(stagingArea, header, isBlockWithTrustedData)
if err != nil {
return err
}
err = v.setParents(stagingArea, blockHash, header, isBlockWithTrustedData)
if err != nil {
return err
}
err = v.checkParentsIncest(stagingArea, blockHash)
if err != nil {
return err
}
if !isBlockWithTrustedData {
err = v.checkPruningPointViolation(stagingArea, blockHash)
if err != nil {
return err
}
}
if !blockHash.Equal(v.genesisHash) {
err = v.checkProofOfWork(header)
if err != nil {
return err
}
}
err = v.validateDifficulty(stagingArea, blockHash, isBlockWithTrustedData)
if err != nil {
return err
}
return nil
}
func (v *blockValidator) setParents(stagingArea *model.StagingArea,
blockHash *externalapi.DomainHash,
header externalapi.BlockHeader,
isBlockWithTrustedData bool) error {
for level := 0; level <= header.BlockLevel(v.maxBlockLevel); level++ {
var parents []*externalapi.DomainHash
for _, parent := range v.parentsManager.ParentsAtLevel(header, level) {
_, err := v.ghostdagDataStores[level].Get(v.databaseContext, stagingArea, parent, false)
isNotFoundError := database.IsNotFoundError(err)
if !isNotFoundError && err != nil {
return err
}
if isNotFoundError {
if level == 0 && !isBlockWithTrustedData {
return errors.Errorf("direct parent %s is missing: only block with prefilled information can have some missing parents", parent)
}
continue
}
parents = append(parents, parent)
}
if len(parents) == 0 {
parents = append(parents, model.VirtualGenesisBlockHash)
}
err := v.dagTopologyManagers[level].SetParents(stagingArea, blockHash, parents)
if err != nil {
return err
}
}
return nil
}
func (v *blockValidator) validateDifficulty(stagingArea *model.StagingArea,
blockHash *externalapi.DomainHash,
isBlockWithTrustedData bool) error {
if !isBlockWithTrustedData {
// We need to calculate GHOSTDAG for the block in order to check its difficulty and blue work
err := v.ghostdagManagers[0].GHOSTDAG(stagingArea, blockHash)
if err != nil {
return err
}
}
header, err := v.blockHeaderStore.BlockHeader(v.databaseContext, stagingArea, blockHash)
if err != nil {
return err
}
blockLevel := header.BlockLevel(v.maxBlockLevel)
for i := 1; i <= blockLevel; i++ {
err = v.ghostdagManagers[i].GHOSTDAG(stagingArea, blockHash)
if err != nil {
return err
}
}
// Ensure the difficulty specified in the block header matches
// the calculated difficulty based on the previous block and
// difficulty retarget rules.
expectedBits, err := v.difficultyManager.StageDAADataAndReturnRequiredDifficulty(stagingArea, blockHash, isBlockWithTrustedData)
if err != nil {
return err
}
if header.Bits() != expectedBits {
return errors.Wrapf(ruleerrors.ErrUnexpectedDifficulty, "block difficulty of %d is not the expected value of %d", header.Bits(), expectedBits)
}
return nil
}
// checkProofOfWork ensures the block header bits which indicate the target
// difficulty is in min/max range and that the block hash is less than the
// target difficulty as claimed.
//
// The flags modify the behavior of this function as follows:
// - BFNoPoWCheck: The check to ensure the block hash is less than the target
// difficulty is not performed.
func (v *blockValidator) checkProofOfWork(header externalapi.BlockHeader) error {
// The target difficulty must be larger than zero.
state := pow.NewState(header.ToMutable())
target := &state.Target
if target.Sign() <= 0 {
return errors.Wrapf(ruleerrors.ErrNegativeTarget, "block target difficulty of %064x is too low",
target)
}
// The target difficulty must be less than the maximum allowed.
if target.Cmp(v.powMax) > 0 {
return errors.Wrapf(ruleerrors.ErrTargetTooHigh, "block target difficulty of %064x is "+
"higher than max of %064x", target, v.powMax)
}
// The block pow must be valid unless the flag to avoid proof of work checks is set.
if !v.skipPoW {
valid := state.CheckProofOfWork()
if !valid {
return errors.Wrap(ruleerrors.ErrInvalidPoW, "block has invalid proof of work")
}
}
return nil
}
func (v *blockValidator) checkParentNotVirtualGenesis(header externalapi.BlockHeader) error {
for _, parent := range header.DirectParents() {
if parent.Equal(model.VirtualGenesisBlockHash) {
return errors.Wrapf(ruleerrors.ErrVirtualGenesisParent, "block header cannot have the virtual genesis as parent")
}
}
return nil
}
func (v *blockValidator) checkParentHeadersExist(stagingArea *model.StagingArea,
header externalapi.BlockHeader,
isBlockWithTrustedData bool) error {
if isBlockWithTrustedData {
return nil
}
missingParentHashes := []*externalapi.DomainHash{}
for _, parent := range header.DirectParents() {
parentHeaderExists, err := v.blockHeaderStore.HasBlockHeader(v.databaseContext, stagingArea, parent)
if err != nil {
return err
}
if !parentHeaderExists {
parentStatus, err := v.blockStatusStore.Get(v.databaseContext, stagingArea, parent)
if err != nil {
if !database.IsNotFoundError(err) {
return err
}
} else if parentStatus == externalapi.StatusInvalid {
return errors.Wrapf(ruleerrors.ErrInvalidAncestorBlock, "parent %s is invalid", parent)
}
missingParentHashes = append(missingParentHashes, parent)
continue
}
}
if len(missingParentHashes) > 0 {
return ruleerrors.NewErrMissingParents(missingParentHashes)
}
return nil
}
func (v *blockValidator) checkPruningPointViolation(stagingArea *model.StagingArea, blockHash *externalapi.DomainHash) error {
// check if the pruning point is on past of at least one parent of the header's parents.
hasPruningPoint, err := v.pruningStore.HasPruningPoint(v.databaseContext, stagingArea)
if err != nil {
return err
}
//If hasPruningPoint has a false value, it means that it's the genesis - so no violation can exist.
if !hasPruningPoint {
return nil
}
pruningPoint, err := v.pruningStore.PruningPoint(v.databaseContext, stagingArea)
if err != nil {
return err
}
parents, err := v.dagTopologyManagers[0].Parents(stagingArea, blockHash)
if err != nil {
return err
}
if virtual.ContainsOnlyVirtualGenesis(parents) {
return nil
}
isAncestorOfAny, err := v.dagTopologyManagers[0].IsAncestorOfAny(stagingArea, pruningPoint, parents)
if err != nil {
return err
}
if !isAncestorOfAny {
return errors.Wrapf(ruleerrors.ErrPruningPointViolation,
"expected pruning point %s to be in block %s past.", pruningPoint, blockHash)
}
return nil
}