-
Notifications
You must be signed in to change notification settings - Fork 3
/
heaviest.go
339 lines (274 loc) · 10.3 KB
/
heaviest.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package mselection
import (
"container/list"
"context"
"fmt"
"sync"
"time"
"github.com/bits-and-blooms/bitset"
"github.com/pkg/errors"
inx "github.com/iotaledger/inx/go"
iotago "github.com/iotaledger/iota.go/v3"
)
var (
// ErrNoTipsAvailable is returned when no tips are available in the node.
ErrNoTipsAvailable = errors.New("no tips available")
)
// HeaviestSelector implements the heaviest branch selection strategy.
type HeaviestSelector struct {
sync.Mutex
// the minimum threshold of unreferenced blocks in the heaviest branch for milestone tipselection
// if the value falls below that threshold, no more heaviest branch tips are picked
minHeaviestBranchUnreferencedBlocksThreshold int
// the maximum amount of checkpoint blocks with heaviest branch tips that are picked
// if the heaviest branch is not below "UnreferencedBlocksThreshold" before
maxHeaviestBranchTipsPerCheckpoint int
// the amount of checkpoint blocks with random tips that are picked if a checkpoint is issued and at least
// one heaviest branch tip was found, otherwise no random tips will be picked
randomTipsPerCheckpoint int
// the maximum duration to select the heaviest branch tips
heaviestBranchSelectionTimeout time.Duration
// map of all tracked blocks
trackedBlocks map[iotago.BlockID]*trackedBlock
// list of available tips
tips *list.List
// whether new blocks should be accepted (used to protect against memory overflows in case the issuing of milestones is halted)
acceptNewBlocks bool
}
type trackedBlock struct {
blockID iotago.BlockID // block ID of the corresponding block
tip *list.Element // pointer to the element in the tip list
refs *bitset.BitSet // BitSet of all the referenced blocks
}
type TrackedBlocksList struct {
blocks map[iotago.BlockID]*trackedBlock
}
// Len returns the length of the inner blocks slice.
func (il *TrackedBlocksList) Len() int {
return len(il.blocks)
}
// randomTip selects a random tip item from the trackedBlocksList.
func (il *TrackedBlocksList) randomTip() (*trackedBlock, error) {
if len(il.blocks) == 0 {
return nil, ErrNoTipsAvailable
}
randomBlockIndex := randomInsecure(0, len(il.blocks)-1)
for _, tip := range il.blocks {
randomBlockIndex--
// if randomBlockIndex is below zero, we return the given tip
if randomBlockIndex < 0 {
return tip, nil
}
}
return nil, ErrNoTipsAvailable
}
// referenceTip removes the tip and set all bits of all referenced
// blocks of the tip in all existing tips to zero.
// this way we can track which parts of the cone would already be referenced by this tip, and
// correctly calculate the weight of the remaining tips.
func (il *TrackedBlocksList) referenceTip(tip *trackedBlock) {
il.removeTip(tip)
// set all bits of all referenced blocks in all existing tips to zero
for _, otherTip := range il.blocks {
otherTip.refs.InPlaceDifference(tip.refs)
}
}
// removeTip removes the tip from the map.
func (il *TrackedBlocksList) removeTip(tip *trackedBlock) {
delete(il.blocks, tip.blockID)
}
// New creates a new HeaviestSelector instance.
func New(minHeaviestBranchUnreferencedBlocksThreshold int, maxHeaviestBranchTipsPerCheckpoint int, randomTipsPerCheckpoint int, heaviestBranchSelectionTimeout time.Duration) *HeaviestSelector {
s := &HeaviestSelector{
minHeaviestBranchUnreferencedBlocksThreshold: minHeaviestBranchUnreferencedBlocksThreshold,
maxHeaviestBranchTipsPerCheckpoint: maxHeaviestBranchTipsPerCheckpoint,
randomTipsPerCheckpoint: randomTipsPerCheckpoint,
heaviestBranchSelectionTimeout: heaviestBranchSelectionTimeout,
acceptNewBlocks: true,
}
s.Reset()
return s
}
func (s *HeaviestSelector) Stop() {
s.Lock()
defer s.Unlock()
s.acceptNewBlocks = false
}
func (s *HeaviestSelector) Continue() {
s.Lock()
defer s.Unlock()
s.acceptNewBlocks = true
}
// Reset resets the tracked blocks map and tips list of s.
func (s *HeaviestSelector) Reset() {
s.Lock()
defer s.Unlock()
// create an empty map
s.trackedBlocks = make(map[iotago.BlockID]*trackedBlock)
// create an empty list
s.tips = list.New()
}
// selectTip selects a tip to be used for the next checkpoint.
// it returns a tip, confirming the most blocks in the future cone,
// and the amount of referenced blocks of this tip, that were not referenced by previously chosen tips.
func (s *HeaviestSelector) selectTip(tipsList *TrackedBlocksList) (*trackedBlock, uint, error) {
if tipsList.Len() == 0 {
return nil, 0, ErrNoTipsAvailable
}
var best = struct {
tips []*trackedBlock
count uint
}{
tips: []*trackedBlock{},
count: 0,
}
// loop through all tips and find the one with the most referenced blocks
for _, tip := range tipsList.blocks {
c := tip.refs.Count()
if c > best.count {
// tip with heavier branch found
best.tips = []*trackedBlock{
tip,
}
best.count = c
} else if c == best.count {
// add the tip to the slice of currently best tips
best.tips = append(best.tips, tip)
}
}
if len(best.tips) == 0 {
return nil, 0, ErrNoTipsAvailable
}
// select a random tip from the provided slice of tips.
selected := best.tips[randomInsecure(0, len(best.tips)-1)]
return selected, best.count, nil
}
// SelectTips tries to collect tips that confirm the most recent blocks since the last reset of the selector.
// best tips are determined by counting the referenced blocks (heaviest branches) and by "removing" the
// blocks of the referenced cone of the already chosen tips in the bitsets of the available tips.
// only tips are considered that were present at the beginning of the SelectTips call,
// to prevent attackers from creating heavier branches while we are searching the best tips.
// "maxHeaviestBranchTipsPerCheckpoint" is the amount of tips that are collected if
// the current best tip is not below "UnreferencedBlocksThreshold" before.
// a minimum amount of selected tips can be enforced, even if none of the heaviest branches matches the
// "minHeaviestBranchUnreferencedBlocksThreshold" criteria.
// if at least one heaviest branch tip was found, "randomTipsPerCheckpoint" random tips are added
// to add some additional randomness to prevent parasite chain attacks.
// the selection is canceled after a fixed deadline. in this case, it returns the current collected tips.
func (s *HeaviestSelector) SelectTips(minRequiredTips int) (iotago.BlockIDs, error) {
// create a working list with the current tips to release the lock to allow faster iteration
// and to get a frozen view of the tangle, so an attacker can't
// create heavier branches while we are searching the best tips
// caution: the tips are not copied, do not mutate!
tipsList := s.TipsToList()
// tips could be empty after a reset
if tipsList.Len() == 0 {
return nil, ErrNoTipsAvailable
}
var tips iotago.BlockIDs
// run the tip selection for at most 0.1s to keep the view on the tangle recent; this should be plenty
ctx, cancel := context.WithTimeout(context.Background(), s.heaviestBranchSelectionTimeout)
defer cancel()
deadlineExceeded := false
for i := 0; i < s.maxHeaviestBranchTipsPerCheckpoint; i++ {
// when the context has been canceled, stop collecting heaviest branch tips
select {
case <-ctx.Done():
deadlineExceeded = true
default:
}
tip, count, err := s.selectTip(tipsList)
if err != nil {
break
}
if (len(tips) > minRequiredTips) && ((count < uint(s.minHeaviestBranchUnreferencedBlocksThreshold)) || deadlineExceeded) {
// minimum amount of tips reached and the heaviest tips do not confirm enough blocks or the deadline was exceeded
// => no need to collect more
break
}
tipsList.referenceTip(tip)
tips = append(tips, tip.blockID)
}
if len(tips) == 0 {
return nil, ErrNoTipsAvailable
}
// also pick random tips if at least one heaviest branch tip was found
for i := 0; i < s.randomTipsPerCheckpoint; i++ {
item, err := tipsList.randomTip()
if err != nil {
break
}
tipsList.referenceTip(item)
tips = append(tips, item.blockID)
}
// reset the whole HeaviestSelector if valid tips were found
s.Reset()
//nolint:nilerr // false positive
return tips, nil
}
// OnNewSolidBlock adds a new block to be processed by s.
// The block must be solid and OnNewSolidBlock must be called in the order of solidification.
// The block must also not be below max depth.
func (s *HeaviestSelector) OnNewSolidBlock(blockMeta *inx.BlockMetadata) (trackedBlocksCount int) {
s.Lock()
defer s.Unlock()
if !s.acceptNewBlocks {
return s.TrackedBlocksCount()
}
blockID := blockMeta.UnwrapBlockID()
parents := blockMeta.UnwrapParents()
// filter duplicate blocks
if _, contains := s.trackedBlocks[blockID]; contains {
return 0
}
parentItems := []*trackedBlock{}
for _, parent := range parents {
parentItem := s.trackedBlocks[parent]
if parentItem == nil {
continue
}
parentItems = append(parentItems, parentItem)
}
// compute the referenced blocks
// all the known children in the HeaviestSelector are represented by a unique bit in a bitset.
// if a new child is added, we expand the bitset by 1 bit and store the Union of the bitsets
// of the parents for this child, to know which parts of the cone are referenced by this child.
idx := uint(len(s.trackedBlocks))
it := &trackedBlock{blockID: blockID, refs: bitset.New(idx + 1).Set(idx)}
for _, parentItem := range parentItems {
it.refs.InPlaceUnion(parentItem.refs)
}
s.trackedBlocks[it.blockID] = it
// update tips
for _, parentItem := range parentItems {
s.removeTip(parentItem)
}
it.tip = s.tips.PushBack(it)
return s.TrackedBlocksCount()
}
// removeTip removes the tip item from s.
func (s *HeaviestSelector) removeTip(it *trackedBlock) {
if it == nil || it.tip == nil {
return
}
s.tips.Remove(it.tip)
it.tip = nil
}
// TipsToList returns a new list containing the current tips.
func (s *HeaviestSelector) TipsToList() *TrackedBlocksList {
s.Lock()
defer s.Unlock()
result := make(map[iotago.BlockID]*trackedBlock)
for e := s.tips.Front(); e != nil; e = e.Next() {
tip, ok := e.Value.(*trackedBlock)
if !ok {
panic(fmt.Sprintf("invalid type: expected *trackedBlock, got %T", e.Value))
}
result[tip.blockID] = tip
}
return &TrackedBlocksList{blocks: result}
}
// TrackedBlocksCount returns the amount of known blocks.
func (s *HeaviestSelector) TrackedBlocksCount() (trackedBlocksCount int) {
return len(s.trackedBlocks)
}