-
Notifications
You must be signed in to change notification settings - Fork 651
/
unique_vertex.go
505 lines (424 loc) · 12.8 KB
/
unique_vertex.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package state
import (
"errors"
"fmt"
"strings"
"time"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/choices"
"github.com/ava-labs/avalanchego/snow/consensus/avalanche"
"github.com/ava-labs/avalanchego/snow/consensus/snowstorm"
"github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex"
"github.com/ava-labs/avalanchego/utils/formatting"
"github.com/ava-labs/avalanchego/utils/hashing"
)
var (
_ cache.Evictable = &uniqueVertex{}
_ avalanche.Vertex = &uniqueVertex{}
)
// uniqueVertex acts as a cache for vertices in the database.
//
// If a vertex is loaded, it will have one canonical uniqueVertex. The vertex
// will eventually be evicted from memory, when the uniqueVertex is evicted from
// the cache. If the uniqueVertex has a function called again after this
// eviction, the vertex will be re-loaded from the database.
type uniqueVertex struct {
serializer *Serializer
id ids.ID
v *vertexState
// default to "time.Now", used for testing
time func() time.Time
}
// newUniqueVertex returns a uniqueVertex instance from [b] by checking the cache
// and then parsing the vertex bytes on a cache miss.
func newUniqueVertex(s *Serializer, b []byte) (*uniqueVertex, error) {
vtx := &uniqueVertex{
id: hashing.ComputeHash256Array(b),
serializer: s,
}
vtx.shallowRefresh()
// If the vtx exists, then the vertex is already known
if vtx.v.vtx != nil {
return vtx, nil
}
// If it wasn't in the cache parse the vertex and set it
innerVertex, err := s.parseVertex(b)
if err != nil {
return nil, err
}
if err := innerVertex.Verify(); err != nil {
return nil, err
}
unparsedTxs := innerVertex.Txs()
txs := make([]snowstorm.Tx, len(unparsedTxs))
for i, txBytes := range unparsedTxs {
tx, err := vtx.serializer.VM.ParseTx(txBytes)
if err != nil {
return nil, err
}
txs[i] = tx
}
vtx.v.vtx = innerVertex
vtx.v.txs = txs
// If the vertex has already been fetched,
// skip persisting the vertex.
if vtx.v.status.Fetched() {
return vtx, nil
}
// The vertex is newly parsed, so set the status
// and persist it.
vtx.v.status = choices.Processing
return vtx, vtx.persist()
}
func (vtx *uniqueVertex) refresh() {
vtx.shallowRefresh()
if vtx.v.vtx == nil && vtx.v.status.Fetched() {
vtx.v.vtx = vtx.serializer.state.Vertex(vtx.ID())
}
}
// shallowRefresh checks the cache for the uniqueVertex and gets the
// most up-to-date status for [vtx]
// ensures that the status is up-to-date for this vertex
// inner vertex may be nil after calling shallowRefresh
func (vtx *uniqueVertex) shallowRefresh() {
if vtx.v == nil {
vtx.v = &vertexState{}
}
if vtx.v.latest {
return
}
latest := vtx.serializer.state.UniqueVertex(vtx)
prevVtx := vtx.v.vtx
if latest == vtx {
vtx.v.status = vtx.serializer.state.Status(vtx.ID())
vtx.v.latest = true
} else {
// If someone is in the cache, they must be up-to-date
*vtx = *latest
}
if vtx.v.vtx == nil {
vtx.v.vtx = prevVtx
}
}
func (vtx *uniqueVertex) Evict() {
if vtx.v != nil {
vtx.v.latest = false
// make sure the parents can be garbage collected
vtx.v.parents = nil
}
}
func (vtx *uniqueVertex) setVertex(innerVtx vertex.StatelessVertex) error {
vtx.shallowRefresh()
vtx.v.vtx = innerVtx
if vtx.v.status.Fetched() {
return nil
}
if _, err := vtx.Txs(); err != nil {
return err
}
vtx.v.status = choices.Processing
return vtx.persist()
}
func (vtx *uniqueVertex) persist() error {
if err := vtx.serializer.state.SetVertex(vtx.v.vtx); err != nil {
return err
}
if err := vtx.serializer.state.SetStatus(vtx.ID(), vtx.v.status); err != nil {
return err
}
return vtx.serializer.versionDB.Commit()
}
func (vtx *uniqueVertex) setStatus(status choices.Status) error {
vtx.shallowRefresh()
if vtx.v.status == status {
return nil
}
vtx.v.status = status
return vtx.serializer.state.SetStatus(vtx.ID(), status)
}
func (vtx *uniqueVertex) ID() ids.ID { return vtx.id }
func (vtx *uniqueVertex) Key() interface{} { return vtx.id }
func (vtx *uniqueVertex) Accept() error {
if err := vtx.setStatus(choices.Accepted); err != nil {
return err
}
vtx.serializer.edge.Add(vtx.id)
parents, err := vtx.Parents()
if err != nil {
return err
}
for _, parent := range parents {
vtx.serializer.edge.Remove(parent.ID())
}
if err := vtx.serializer.state.SetEdge(vtx.serializer.Edge()); err != nil {
return fmt.Errorf("failed to set edge while accepting vertex %s due to %w", vtx.id, err)
}
// Should never traverse into parents of a decided vertex. Allows for the
// parents to be garbage collected
vtx.v.parents = nil
return vtx.serializer.versionDB.Commit()
}
func (vtx *uniqueVertex) Reject() error {
if err := vtx.setStatus(choices.Rejected); err != nil {
return err
}
// Should never traverse into parents of a decided vertex. Allows for the
// parents to be garbage collected
vtx.v.parents = nil
return vtx.serializer.versionDB.Commit()
}
// TODO: run performance test to see if shallow refreshing
// (which will mean that refresh must be called in Bytes and Verify)
// improves performance
func (vtx *uniqueVertex) Status() choices.Status { vtx.refresh(); return vtx.v.status }
func (vtx *uniqueVertex) Parents() ([]avalanche.Vertex, error) {
vtx.refresh()
if vtx.v.vtx == nil {
return nil, fmt.Errorf("failed to get parents for vertex with status: %s", vtx.v.status)
}
parentIDs := vtx.v.vtx.ParentIDs()
if len(vtx.v.parents) != len(parentIDs) {
vtx.v.parents = make([]avalanche.Vertex, len(parentIDs))
for i, parentID := range parentIDs {
vtx.v.parents[i] = &uniqueVertex{
serializer: vtx.serializer,
id: parentID,
}
}
}
return vtx.v.parents, nil
}
var (
errStopVertexNotAllowedTimestamp = errors.New("stop vertex not allowed timestamp")
errStopVertexAlreadyAccepted = errors.New("stop vertex already accepted")
errUnexpectedEdges = errors.New("unexpected edge, expected accepted frontier")
errUnexpectedDependencyStopVtx = errors.New("unexpected dependencies found in stop vertex transitive path")
)
// "uniqueVertex" itself implements "Verify" regardless of whether the underlying vertex
// is stop vertex or not. Called before issuing the vertex to the consensus.
// No vertex should ever be able to refer to a stop vertex in its transitive closure.
func (vtx *uniqueVertex) Verify() error {
// first verify the underlying stateless vertex
if err := vtx.v.vtx.Verify(); err != nil {
return err
}
whitelistVtx := vtx.v.vtx.StopVertex()
if whitelistVtx {
now := time.Now()
if vtx.time != nil {
now = vtx.time()
}
allowed := vtx.serializer.XChainMigrationTime
if now.Before(allowed) {
return errStopVertexNotAllowedTimestamp
}
}
// MUST error if stop vertex has already been accepted (can't be accepted twice)
// regardless of whether the underlying vertex is stop vertex or not
stopVtxAccepted, err := vtx.serializer.StopVertexAccepted()
if err != nil {
return err
}
if stopVtxAccepted {
return errStopVertexAlreadyAccepted
}
if !whitelistVtx {
// below are stop vertex specific verifications
// no need to continue
return nil
}
// (accepted) (accepted)
// vtx_1 vtx_2
// [tx_a, tx_b] [tx_c, tx_d]
// ⬆ ⬉ ⬈ ⬆
// vtx_3 vtx_4
// [tx_e, tx_f] [tx_g, tx_h]
// ⬆
// stop_vertex_5
//
// [tx_a, tx_b] transitively referenced by "stop_vertex_5"
// has the dependent transactions [tx_e, tx_f]
// that are not transitively referenced by "stop_vertex_5"
// in case "tx_g" depends on "tx_e" that is not in vtx4.
// Thus "stop_vertex_5" is invalid!
//
// To make sure such transitive paths of the stop vertex reach all accepted frontier:
// 1. check the edge of the transitive paths refers to the accepted frontier
// 2. check dependencies of all txs must be subset of transitive paths
queue := []avalanche.Vertex{vtx}
visitedVtx := ids.NewSet(0)
acceptedFrontier := ids.NewSet(0)
transitivePaths := ids.NewSet(0)
dependencies := ids.NewSet(0)
for len(queue) > 0 { // perform BFS
cur := queue[0]
queue = queue[1:]
curID := cur.ID()
if cur.Status() == choices.Accepted {
// 1. check the edge of the transitive paths refers to the accepted frontier
acceptedFrontier.Add(curID)
// have reached the accepted frontier on the transitive closure
// no need to continue the search on this path
continue
}
if visitedVtx.Contains(curID) {
continue
}
visitedVtx.Add(curID)
transitivePaths.Add(curID)
txs, err := cur.Txs()
if err != nil {
return err
}
for _, tx := range txs {
transitivePaths.Add(tx.ID())
deps, err := tx.Dependencies()
if err != nil {
return err
}
for _, dep := range deps {
// only add non-accepted dependencies
if dep.Status() != choices.Accepted {
dependencies.Add(dep.ID())
}
}
}
parents, err := cur.Parents()
if err != nil {
return err
}
queue = append(queue, parents...)
}
acceptedEdges := ids.NewSet(0)
acceptedEdges.Add(vtx.serializer.Edge()...)
// stop vertex should be able to reach all IDs
// that are returned by the "Edge"
if !acceptedFrontier.Equals(acceptedEdges) {
return errUnexpectedEdges
}
// 2. check dependencies of all txs must be subset of transitive paths
prev := transitivePaths.Len()
transitivePaths.Union(dependencies)
if prev != transitivePaths.Len() {
return errUnexpectedDependencyStopVtx
}
return nil
}
func (vtx *uniqueVertex) HasWhitelist() bool {
return vtx.v.vtx.StopVertex()
}
// "uniqueVertex" itself implements "Whitelist" traversal iff its underlying
// "vertex.StatelessVertex" is marked as a stop vertex.
func (vtx *uniqueVertex) Whitelist() (ids.Set, error) {
if !vtx.v.vtx.StopVertex() {
return nil, nil
}
// perform BFS on transitive paths until reaching the accepted frontier
// represents all processing transaction IDs transitively referenced by the
// vertex
queue := []avalanche.Vertex{vtx}
whitlist := ids.NewSet(0)
visitedVtx := ids.NewSet(0)
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
if cur.Status() == choices.Accepted {
// have reached the accepted frontier on the transitive closure
// no need to continue the search on this path
continue
}
curID := cur.ID()
if visitedVtx.Contains(curID) {
continue
}
visitedVtx.Add(curID)
txs, err := cur.Txs()
if err != nil {
return nil, err
}
for _, tx := range txs {
whitlist.Add(tx.ID())
}
whitlist.Add(curID)
parents, err := cur.Parents()
if err != nil {
return nil, err
}
queue = append(queue, parents...)
}
return whitlist, nil
}
func (vtx *uniqueVertex) Height() (uint64, error) {
vtx.refresh()
if vtx.v.vtx == nil {
return 0, fmt.Errorf("failed to get height for vertex with status: %s", vtx.v.status)
}
return vtx.v.vtx.Height(), nil
}
func (vtx *uniqueVertex) Epoch() (uint32, error) {
vtx.refresh()
if vtx.v.vtx == nil {
return 0, fmt.Errorf("failed to get epoch for vertex with status: %s", vtx.v.status)
}
return vtx.v.vtx.Epoch(), nil
}
func (vtx *uniqueVertex) Txs() ([]snowstorm.Tx, error) {
vtx.refresh()
if vtx.v.vtx == nil {
return nil, fmt.Errorf("failed to get txs for vertex with status: %s", vtx.v.status)
}
txs := vtx.v.vtx.Txs()
if len(txs) != len(vtx.v.txs) {
vtx.v.txs = make([]snowstorm.Tx, len(txs))
for i, txBytes := range txs {
tx, err := vtx.serializer.VM.ParseTx(txBytes)
if err != nil {
return nil, err
}
vtx.v.txs[i] = tx
}
}
return vtx.v.txs, nil
}
func (vtx *uniqueVertex) Bytes() []byte { return vtx.v.vtx.Bytes() }
func (vtx *uniqueVertex) String() string {
sb := strings.Builder{}
parents, err := vtx.Parents()
if err != nil {
sb.WriteString(fmt.Sprintf("Vertex(ID = %s, Error=error while retrieving vertex parents: %s)", vtx.ID(), err))
return sb.String()
}
txs, err := vtx.Txs()
if err != nil {
sb.WriteString(fmt.Sprintf("Vertex(ID = %s, Error=error while retrieving vertex txs: %s)", vtx.ID(), err))
return sb.String()
}
sb.WriteString(fmt.Sprintf(
"Vertex(ID = %s, Status = %s, Number of Dependencies = %d, Number of Transactions = %d)",
vtx.ID(),
vtx.Status(),
len(parents),
len(txs),
))
parentFormat := fmt.Sprintf("\n Parent[%s]: ID = %%s, Status = %%s",
formatting.IntFormat(len(parents)-1))
for i, parent := range parents {
sb.WriteString(fmt.Sprintf(parentFormat, i, parent.ID(), parent.Status()))
}
txFormat := fmt.Sprintf("\n Transaction[%s]: ID = %%s, Status = %%s",
formatting.IntFormat(len(txs)-1))
for i, tx := range txs {
sb.WriteString(fmt.Sprintf(txFormat, i, tx.ID(), tx.Status()))
}
return sb.String()
}
type vertexState struct {
latest bool
vtx vertex.StatelessVertex
status choices.Status
parents []avalanche.Vertex
txs []snowstorm.Tx
}