forked from spacemeshos/go-spacemesh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
52 lines (45 loc) · 1.68 KB
/
util.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
package proposals
import (
"errors"
"fmt"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/common/util"
)
// ErrZeroTotalWeight is returned when zero total epoch weight is used when calculating eligible slots.
var ErrZeroTotalWeight = errors.New("zero total weight not allowed")
// CalcEligibleLayer calculates the eligible layer from the VRF signature.
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))
}
// GetNumEligibleSlots calculates the number of eligible slots for a smesher in an epoch.
func GetNumEligibleSlots(weight, totalWeight uint64, committeeSize uint32, layersPerEpoch uint32) (uint32, error) {
if totalWeight == 0 {
return 0, ErrZeroTotalWeight
}
numberOfEligibleBlocks := weight * uint64(committeeSize) * uint64(layersPerEpoch) / totalWeight // TODO: ensure no overflow
if numberOfEligibleBlocks == 0 {
numberOfEligibleBlocks = 1
}
return uint32(numberOfEligibleBlocks), nil
}
type vrfMessage struct {
Beacon types.Beacon
Epoch types.EpochID
Counter uint32
}
// SerializeVRFMessage serializes a message for generating/verifying a VRF signature.
func SerializeVRFMessage(beacon types.Beacon, epoch types.EpochID, counter uint32) ([]byte, error) {
m := vrfMessage{
Beacon: beacon,
Epoch: epoch,
Counter: counter,
}
serialized, err := codec.Encode(&m)
if err != nil {
return nil, fmt.Errorf("serialize vrf message: %w", err)
}
return serialized, nil
}