forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
initial_state.go
105 lines (86 loc) · 2.34 KB
/
initial_state.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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package txs
import (
"bytes"
"errors"
"sort"
"github.com/MetalBlockchain/metalgo/codec"
"github.com/MetalBlockchain/metalgo/ids"
"github.com/MetalBlockchain/metalgo/snow"
"github.com/MetalBlockchain/metalgo/utils"
"github.com/MetalBlockchain/metalgo/vms/components/verify"
)
var (
errNilInitialState = errors.New("nil initial state is not valid")
errNilFxOutput = errors.New("nil feature extension output is not valid")
errOutputsNotSorted = errors.New("outputs not sorted")
errUnknownFx = errors.New("unknown feature extension")
_ utils.Sortable[*InitialState] = (*InitialState)(nil)
)
type InitialState struct {
FxIndex uint32 `serialize:"true" json:"fxIndex"`
FxID ids.ID `serialize:"false" json:"fxID"`
Outs []verify.State `serialize:"true" json:"outputs"`
}
func (is *InitialState) InitCtx(ctx *snow.Context) {
for _, out := range is.Outs {
out.InitCtx(ctx)
}
}
func (is *InitialState) Verify(c codec.Manager, numFxs int) error {
switch {
case is == nil:
return errNilInitialState
case is.FxIndex >= uint32(numFxs):
return errUnknownFx
}
for _, out := range is.Outs {
if out == nil {
return errNilFxOutput
}
if err := out.Verify(); err != nil {
return err
}
}
if !isSortedState(is.Outs, c) {
return errOutputsNotSorted
}
return nil
}
func (is *InitialState) Less(other *InitialState) bool {
return is.FxIndex < other.FxIndex
}
func (is *InitialState) Sort(c codec.Manager) {
sortState(is.Outs, c)
}
type innerSortState struct {
vers []verify.State
codec codec.Manager
}
func (vers *innerSortState) Less(i, j int) bool {
iVer := vers.vers[i]
jVer := vers.vers[j]
iBytes, err := vers.codec.Marshal(CodecVersion, &iVer)
if err != nil {
return false
}
jBytes, err := vers.codec.Marshal(CodecVersion, &jVer)
if err != nil {
return false
}
return bytes.Compare(iBytes, jBytes) == -1
}
func (vers *innerSortState) Len() int {
return len(vers.vers)
}
func (vers *innerSortState) Swap(i, j int) {
v := vers.vers
v[j], v[i] = v[i], v[j]
}
func sortState(vers []verify.State, c codec.Manager) {
sort.Sort(&innerSortState{vers: vers, codec: c})
}
func isSortedState(vers []verify.State, c codec.Manager) bool {
return sort.IsSorted(&innerSortState{vers: vers, codec: c})
}