-
Notifications
You must be signed in to change notification settings - Fork 211
/
oracle.go
196 lines (174 loc) · 6.01 KB
/
oracle.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
package miner
import (
"bytes"
"errors"
"fmt"
"sort"
"sync"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/datastore"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/proposals"
"github.com/spacemeshos/go-spacemesh/signing"
"github.com/spacemeshos/go-spacemesh/sql"
"github.com/spacemeshos/go-spacemesh/sql/atxs"
)
var (
errMinerHasNoATXInPreviousEpoch = errors.New("miner has no ATX in previous epoch")
errZeroEpochWeight = errors.New("zero total weight for epoch")
errEmptyActiveSet = errors.New("empty active set for epoch")
)
type EpochEligibility struct {
Epoch types.EpochID
Atx types.ATXID
ActiveSet types.ATXIDList
Proofs map[types.LayerID][]types.VotingEligibility
Slots uint32
}
// Oracle provides proposal eligibility proofs for the miner.
type Oracle struct {
avgLayerSize uint32
layersPerEpoch uint32
cdb *datastore.CachedDB
vrfSigner *signing.VRFSigner
nodeID types.NodeID
log log.Log
mu sync.Mutex
cache *EpochEligibility
}
func newMinerOracle(layerSize, layersPerEpoch uint32, cdb *datastore.CachedDB, vrfSigner *signing.VRFSigner, nodeID types.NodeID, log log.Log) *Oracle {
return &Oracle{
avgLayerSize: layerSize,
layersPerEpoch: layersPerEpoch,
cdb: cdb,
vrfSigner: vrfSigner,
nodeID: nodeID,
log: log,
cache: &EpochEligibility{},
}
}
// GetProposalEligibility returns the miner's ATXID and the active set for the layer's epoch, along with the list of eligibility
// proofs for that layer.
func (o *Oracle) GetProposalEligibility(lid types.LayerID, beacon types.Beacon, nonce types.VRFPostIndex) (*EpochEligibility, error) {
o.mu.Lock()
defer o.mu.Unlock()
epoch := lid.GetEpoch()
if lid <= types.GetEffectiveGenesis() {
o.log.With().Panic("eligibility should not be queried during genesis", lid, epoch)
}
o.log.With().Debug("asked for proposal eligibility",
log.Stringer("requested epoch", epoch),
log.Stringer("cached epoch", o.cache.Epoch),
)
var layerProofs []types.VotingEligibility
if o.cache.Epoch == epoch { // use the cached value
layerProofs = o.cache.Proofs[lid]
o.log.With().Debug("got cached eligibility",
log.Stringer("requested epoch", epoch),
log.Stringer("cached epoch", o.cache.Epoch),
log.Int("num proposals", len(layerProofs)),
)
return o.cache, nil
}
// calculate the proof
atx, err := o.getOwnEpochATX(epoch)
if err != nil {
if errors.Is(err, sql.ErrNotFound) {
return nil, errMinerHasNoATXInPreviousEpoch
}
return nil, fmt.Errorf("failed to get valid atx for node for target epoch %d: %w", epoch, err)
}
ee, err := o.calcEligibilityProofs(atx, epoch, beacon, nonce)
if err != nil {
return nil, err
}
o.cache = ee
return ee, nil
}
func (o *Oracle) getOwnEpochATX(targetEpoch types.EpochID) (*types.ActivationTxHeader, error) {
publishEpoch := targetEpoch - 1
atxID, err := atxs.GetIDByEpochAndNodeID(o.cdb, publishEpoch, o.nodeID)
if err != nil {
return nil, fmt.Errorf("get ATX ID: %w", err)
}
atx, err := o.cdb.GetAtxHeader(atxID)
if err != nil {
return nil, fmt.Errorf("get ATX header: %w", err)
}
return atx, nil
}
// calcEligibilityProofs calculates the eligibility proofs of proposals for the miner in the given epoch
// and returns the proofs along with the epoch's active set.
func (o *Oracle) calcEligibilityProofs(atx *types.ActivationTxHeader, epoch types.EpochID, beacon types.Beacon, nonce types.VRFPostIndex) (*EpochEligibility, error) {
weight := atx.GetWeight()
// get the previous epoch's total weight
totalWeight, activeSet, err := o.cdb.GetEpochWeight(epoch)
if err != nil {
return nil, fmt.Errorf("failed to get epoch %v weight: %w", epoch, err)
}
if totalWeight == 0 {
return nil, errZeroEpochWeight
}
if len(activeSet) == 0 {
return nil, errEmptyActiveSet
}
o.log.With().Debug("calculating eligibility",
epoch,
beacon,
log.Uint64("weight", weight),
log.Uint64("total weight", totalWeight),
)
numEligibleSlots, err := proposals.GetNumEligibleSlots(weight, totalWeight, o.avgLayerSize, o.layersPerEpoch)
if err != nil {
return nil, fmt.Errorf("oracle get num slots: %w", err)
}
eligibilityProofs := map[types.LayerID][]types.VotingEligibility{}
for counter := uint32(0); counter < numEligibleSlots; counter++ {
message, err := proposals.SerializeVRFMessage(beacon, epoch, nonce, counter)
if err != nil {
o.log.With().Fatal("failed to serialize VRF msg", log.Err(err))
}
vrfSig := o.vrfSigner.Sign(message)
eligibleLayer := proposals.CalcEligibleLayer(epoch, o.layersPerEpoch, vrfSig)
eligibilityProofs[eligibleLayer] = append(eligibilityProofs[eligibleLayer], types.VotingEligibility{
J: counter,
Sig: vrfSig,
})
o.log.Debug(fmt.Sprintf("signed vrf message, counter: %v, vrfSig: %s, layer: %v", counter, vrfSig, eligibleLayer))
}
o.log.With().Info("proposal eligibility for an epoch",
epoch,
beacon,
log.Uint64("weight", weight),
log.Uint64("total weight", totalWeight),
log.Uint32("total num slots", numEligibleSlots),
log.Int("num layers eligible", len(eligibilityProofs)),
log.Array("layers to num proposals", log.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error {
// Sort the layer map to log the layer data in order
keys := make([]types.LayerID, 0, len(eligibilityProofs))
for k := range eligibilityProofs {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i].Before(keys[j])
})
for _, lyr := range keys {
encoder.AppendObject(log.ObjectMarshallerFunc(func(encoder log.ObjectEncoder) error {
encoder.AddUint32("layer", lyr.Uint32())
encoder.AddInt("slots", len(eligibilityProofs[lyr]))
return nil
}))
}
return nil
})))
sort.Slice(activeSet, func(i, j int) bool {
return bytes.Compare(activeSet[i].Bytes(), activeSet[j].Bytes()) < 0
})
return &EpochEligibility{
Epoch: epoch,
Atx: atx.ID,
ActiveSet: activeSet,
Proofs: eligibilityProofs,
Slots: numEligibleSlots,
}, nil
}