-
Notifications
You must be signed in to change notification settings - Fork 210
/
blockoracle.go
266 lines (236 loc) · 8.78 KB
/
blockoracle.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
package blocks
import (
"errors"
"fmt"
"sort"
"strings"
"sync"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/common/util"
"github.com/spacemeshos/go-spacemesh/log"
)
type activationDB interface {
GetNodeAtxIDForEpoch(nodeID types.NodeID, targetEpoch types.EpochID) (types.ATXID, error)
GetAtxHeader(types.ATXID) (*types.ActivationTxHeader, error)
GetEpochWeight(types.EpochID) (uint64, []types.ATXID, error)
}
type vrfSigner interface {
Sign(msg []byte) []byte
}
// DefaultProofsEpoch is set such that it will never equal the current epoch
const DefaultProofsEpoch = ^types.EpochID(0)
// Oracle is the oracle that provides block eligibility proofs for the miner.
type Oracle struct {
committeeSize uint32
layersPerEpoch uint32
atxDB activationDB
beaconProvider BeaconGetter
vrfSigner vrfSigner
nodeID types.NodeID
proofsEpoch types.EpochID
epochAtxs []types.ATXID
eligibilityProofs map[types.LayerID][]types.BlockEligibilityProof
atxID types.ATXID
isSynced func() bool
eligibilityMutex sync.RWMutex
log log.Log
}
// NewMinerBlockOracle returns a new Oracle.
func NewMinerBlockOracle(committeeSize uint32, layersPerEpoch uint32, atxDB activationDB, beaconProvider BeaconGetter, vrfSigner vrfSigner, nodeID types.NodeID, isSynced func() bool, log log.Log) *Oracle {
return &Oracle{
committeeSize: committeeSize,
layersPerEpoch: layersPerEpoch,
atxDB: atxDB,
beaconProvider: beaconProvider,
vrfSigner: vrfSigner,
nodeID: nodeID,
proofsEpoch: DefaultProofsEpoch,
isSynced: isSynced,
log: log,
}
}
// BlockEligible returns the ATXID and list of block eligibility proofs for the given layer. It caches proofs for a
// single epoch and only refreshes the cache if eligibility is queried for a different epoch.
func (bo *Oracle) BlockEligible(layerID types.LayerID) (types.ATXID, []types.BlockEligibilityProof, []types.ATXID, error) {
if !bo.isSynced() {
return types.ATXID{}, nil, nil, fmt.Errorf("cannot calc eligibility, not synced yet")
}
epochNumber := layerID.GetEpoch()
var cachedEpochDescription log.Field
if bo.proofsEpoch == DefaultProofsEpoch {
cachedEpochDescription = log.Int("cached_epoch_id", -1)
} else {
cachedEpochDescription = log.FieldNamed("cached_epoch_id", bo.proofsEpoch.Field())
}
bo.log.With().Info("asked for block eligibility", layerID, epochNumber, cachedEpochDescription)
if epochNumber.IsGenesis() {
bo.log.With().Error("asked for block eligibility in genesis epoch, cannot create blocks here",
layerID, epochNumber, cachedEpochDescription)
return *types.EmptyATXID, nil, nil, nil
}
var proofs []types.BlockEligibilityProof
bo.eligibilityMutex.RLock()
if bo.proofsEpoch != epochNumber {
bo.eligibilityMutex.RUnlock()
newProofs, err := bo.calcEligibilityProofs(epochNumber)
proofs = newProofs[layerID]
if err != nil {
bo.log.With().Error("failed to calculate eligibility proofs", layerID, epochNumber, log.Err(err))
return *types.EmptyATXID, nil, nil, err
}
} else {
proofs = bo.eligibilityProofs[layerID]
bo.eligibilityMutex.RUnlock()
}
bo.log.With().Info("got eligibility for blocks",
bo.nodeID, layerID, layerID.GetEpoch(),
log.Int("num_blocks", len(proofs)))
return bo.atxID, proofs, bo.epochAtxs, nil
}
func (bo *Oracle) calcEligibilityProofs(epochNumber types.EpochID) (map[types.LayerID][]types.BlockEligibilityProof, error) {
epochBeacon, err := bo.beaconProvider.GetBeacon(epochNumber)
if err != nil {
bo.log.With().Error("Failed to get beacon",
log.Uint64("epoch_id", uint64(epochNumber)),
log.Err(err))
return nil, err
}
beaconDbgStr := types.BytesToHash(epochBeacon).ShortString()
bo.log.With().Info("got beacon",
log.Uint64("epoch_id", uint64(epochNumber)),
log.String("epoch_beacon", beaconDbgStr))
var weight uint64
// get the previous epoch's total weight
totalWeight, activeSet, err := bo.atxDB.GetEpochWeight(epochNumber)
if err != nil {
return nil, fmt.Errorf("failed to get epoch %v weight: %w", epochNumber, err)
}
atx, err := bo.getValidAtxForEpoch(epochNumber)
if err != nil {
if !epochNumber.IsGenesis() {
return nil, fmt.Errorf("failed to get latest atx for node in epoch %d: %w", epochNumber, err)
}
} else {
weight = atx.GetWeight()
bo.atxID = atx.ID()
}
bo.log.With().Info("calculating eligibility",
epochNumber,
log.Uint64("total_weight", totalWeight))
bo.log.With().Debug("calculating eligibility",
epochNumber,
log.String("epoch_beacon", beaconDbgStr))
numberOfEligibleBlocks, err := getNumberOfEligibleBlocks(weight, totalWeight, bo.committeeSize, bo.layersPerEpoch)
if err != nil {
bo.log.With().Error("failed to get number of eligible blocks", log.Err(err))
return nil, err
}
eligibilityProofs := map[types.LayerID][]types.BlockEligibilityProof{}
for counter := uint32(0); counter < numberOfEligibleBlocks; counter++ {
message, err := serializeVRFMessage(epochBeacon, epochNumber, counter)
if err != nil {
return nil, err
}
vrfSig := bo.vrfSigner.Sign(message)
bo.log.Debug("signed vrf message, beacon %v, epoch %v, counter: %v, vrfSig: %v",
types.BytesToHash(epochBeacon).ShortString(), epochNumber, counter, types.BytesToHash(vrfSig).ShortString())
eligibleLayer := calcEligibleLayer(epochNumber, bo.layersPerEpoch, vrfSig)
eligibilityProofs[eligibleLayer] = append(eligibilityProofs[eligibleLayer], types.BlockEligibilityProof{
J: counter,
Sig: vrfSig,
TortoiseBeacon: epochBeacon,
})
}
bo.eligibilityMutex.Lock()
bo.epochAtxs = activeSet
bo.proofsEpoch = epochNumber
bo.eligibilityProofs = eligibilityProofs
bo.eligibilityMutex.Unlock()
// Sort the layer map so we can print the layer data in order
keys := make([]types.LayerID, len(eligibilityProofs))
i := 0
for k := range eligibilityProofs {
keys[i] = k
i++
}
sort.Slice(keys, func(i, j int) bool {
return keys[i].Before(keys[j])
})
// Pretty-print the number of blocks per eligible layer
var strs []string
for k := range keys {
strs = append(strs, fmt.Sprintf("Layer %s: %d", keys[k].String(), len(eligibilityProofs[keys[k]])))
}
bo.log.With().Info("block eligibility calculated",
epochNumber,
log.Uint32("total_num_blocks", numberOfEligibleBlocks),
log.Int("num_layers_eligible", len(eligibilityProofs)),
log.String("layers_and_num_blocks", strings.Join(strs, ", ")))
return eligibilityProofs, nil
}
func (bo *Oracle) getValidAtxForEpoch(validForEpoch types.EpochID) (*types.ActivationTxHeader, error) {
atxID, err := bo.getATXIDForEpoch(validForEpoch - 1)
if err != nil {
return nil, fmt.Errorf("failed to get atx id for target epoch %v: %w", validForEpoch, err)
}
atx, err := bo.atxDB.GetAtxHeader(atxID)
if err != nil {
bo.log.With().Error("getting atx failed", log.Err(err))
return nil, err
}
return atx, nil
}
func calcEligibleLayer(epochNumber types.EpochID, layersPerEpoch uint32, vrfSig []byte) types.LayerID {
vrfInteger := util.BytesToUint64(vrfSig)
eligibleLayerOffset := vrfInteger % uint64(layersPerEpoch)
return epochNumber.FirstLayer().Add(uint32(eligibleLayerOffset))
}
func getNumberOfEligibleBlocks(weight, totalWeight uint64, committeeSize uint32, layersPerEpoch uint32) (uint32, error) {
if totalWeight == 0 {
return 0, errors.New("zero total weight not allowed")
}
numberOfEligibleBlocks := weight * uint64(committeeSize) * uint64(layersPerEpoch) / totalWeight // TODO: ensure no overflow
if numberOfEligibleBlocks == 0 {
numberOfEligibleBlocks = 1
}
return uint32(numberOfEligibleBlocks), nil
}
func (bo *Oracle) getATXIDForEpoch(targetEpoch types.EpochID) (types.ATXID, error) {
latestATXID, err := bo.atxDB.GetNodeAtxIDForEpoch(bo.nodeID, targetEpoch)
if err != nil {
bo.log.With().Warning("did not find atx ids for node",
log.FieldNamed("atx_node_id", bo.nodeID),
log.Err(err))
return types.ATXID{}, err
}
bo.log.With().Info("latest atx id found", latestATXID)
return latestATXID, err
}
type vrfMessage struct {
EpochBeacon []byte
EpochNumber types.EpochID
Counter uint32
}
func serializeVRFMessage(epochBeacon []byte, epochNumber types.EpochID, counter uint32) ([]byte, error) {
m := vrfMessage{
EpochBeacon: epochBeacon,
EpochNumber: epochNumber,
Counter: counter,
}
serialized, err := types.InterfaceToBytes(&m)
if err != nil {
return nil, fmt.Errorf("failed to serialize vrf message: %v", err)
}
return serialized, nil
}
// GetEligibleLayers returns a list of layers in which the miner is eligible for at least one block. The list is
// returned in arbitrary order.
func (bo *Oracle) GetEligibleLayers() []types.LayerID {
bo.eligibilityMutex.RLock()
layers := make([]types.LayerID, 0, len(bo.eligibilityProofs))
for layer := range bo.eligibilityProofs {
layers = append(layers, layer)
}
bo.eligibilityMutex.RUnlock()
return layers
}