Skip to content

Commit

Permalink
fix: store raw authority and parse to authority only to verify signature
Browse files Browse the repository at this point in the history
  • Loading branch information
EclesioMeloJunior committed Dec 5, 2023
1 parent bb4c105 commit 34f296d
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 79 deletions.
61 changes: 23 additions & 38 deletions dot/state/epoch.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,12 @@ func NewEpochStateFromGenesis(db database.Database, blockState *BlockState,
nextConfigData: make(nextEpochMap[types.NextConfigDataV1]),
}

auths, err := types.BABEAuthorityRawToAuthority(genesisConfig.GenesisAuthorities)
if err != nil {
return nil, err
epochDataRaw := &types.EpochDataRaw{
Authorities: genesisConfig.GenesisAuthorities,
Randomness: genesisConfig.Randomness,
}

err = s.SetEpochData(0, &types.EpochData{
Authorities: auths,
Randomness: genesisConfig.Randomness,
})
err = s.setEpochDataRaw(0, epochDataRaw)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -235,10 +232,8 @@ func (s *EpochState) GetEpochForBlock(header *types.Header) (uint64, error) {
return 0, errNoPreRuntimeDigest
}

// SetEpochData sets the epoch data for a given epoch
func (s *EpochState) SetEpochData(epoch uint64, info *types.EpochData) error {
raw := info.ToEpochDataRaw()

// setEpochDataRaw sets the epoch data raw for a given epoch
func (s *EpochState) setEpochDataRaw(epoch uint64, raw *types.EpochDataRaw) error {
enc, err := scale.Marshal(*raw)
if err != nil {
return err
Expand All @@ -247,17 +242,17 @@ func (s *EpochState) SetEpochData(epoch uint64, info *types.EpochData) error {
return s.db.Put(epochDataKey(epoch), enc)
}

// GetEpochData returns the epoch data for a given epoch persisted in database
// GetEpochDataRaw returns the epoch data raw for a given epoch persisted in database
// otherwise will try to get the data from the in-memory map using the header
// if the header params is nil then it will search only in database
func (s *EpochState) GetEpochData(epoch uint64, header *types.Header) (*types.EpochData, error) {
epochData, err := s.getEpochDataFromDatabase(epoch)
func (s *EpochState) GetEpochDataRaw(epoch uint64, header *types.Header) (*types.EpochDataRaw, error) {
epochDataRaw, err := s.getEpochDataRawFromDatabase(epoch)
if err != nil && !errors.Is(err, database.ErrNotFound) {
return nil, fmt.Errorf("failed to retrieve epoch data from database: %w", err)
}

if epochData != nil {
return epochData, nil
if epochDataRaw != nil {
return epochDataRaw, nil
}

if header == nil {
Expand All @@ -272,38 +267,33 @@ func (s *EpochState) GetEpochData(epoch uint64, header *types.Header) (*types.Ep
return nil, fmt.Errorf("failed to get epoch data from memory: %w", err)
}

epochData, err = inMemoryEpochData.ToEpochData()
if err != nil {
return nil, fmt.Errorf("cannot transform into epoch data: %w", err)
}

return epochData, nil
return inMemoryEpochData.ToEpochDataRaw(), nil
}

// getEpochDataFromDatabase returns the epoch data for a given epoch persisted in database
func (s *EpochState) getEpochDataFromDatabase(epoch uint64) (*types.EpochData, error) {
// getEpochDataRawFromDatabase returns the epoch data for a given epoch persisted in database
func (s *EpochState) getEpochDataRawFromDatabase(epoch uint64) (*types.EpochDataRaw, error) {
enc, err := s.db.Get(epochDataKey(epoch))
if err != nil {
return nil, err
}

raw := &types.EpochDataRaw{}
raw := new(types.EpochDataRaw)
err = scale.Unmarshal(enc, raw)
if err != nil {
return nil, err
return nil, fmt.Errorf("unmarshaling into epoch data raw: %w", err)
}

return raw.ToEpochData()
return raw, nil
}

// GetLatestEpochData returns the EpochData for the current epoch
func (s *EpochState) GetLatestEpochData() (*types.EpochData, error) {
// GetLatestEpochDataRaw returns the EpochData for the current epoch
func (s *EpochState) GetLatestEpochDataRaw() (*types.EpochDataRaw, error) {
curr, err := s.GetCurrentEpoch()
if err != nil {
return nil, err
}

return s.GetEpochData(curr, nil)
return s.GetEpochDataRaw(curr, nil)
}

// SetConfigData sets the BABE config data for a given epoch
Expand Down Expand Up @@ -586,7 +576,7 @@ func (s *EpochState) FinalizeBABENextEpochData(finalizedHeader *types.Header) er
nextEpoch = finalizedBlockEpoch + 1
}

epochInDatabase, err := s.getEpochDataFromDatabase(nextEpoch)
epochRawInDatabase, err := s.getEpochDataRawFromDatabase(nextEpoch)

// if an error occurs and the error is database.ErrNotFound we ignore
// since this error is what we will handle in the next lines
Expand All @@ -595,7 +585,7 @@ func (s *EpochState) FinalizeBABENextEpochData(finalizedHeader *types.Header) er
}

// epoch data already defined we don't need to lookup in the map
if epochInDatabase != nil {
if epochRawInDatabase != nil {
return nil
}

Expand All @@ -604,12 +594,7 @@ func (s *EpochState) FinalizeBABENextEpochData(finalizedHeader *types.Header) er
return fmt.Errorf("cannot find next epoch data: %w", err)
}

ed, err := finalizedNextEpochData.ToEpochData()
if err != nil {
return fmt.Errorf("cannot transform epoch data: %w", err)
}

err = s.SetEpochData(nextEpoch, ed)
err = s.setEpochDataRaw(nextEpoch, finalizedNextEpochData.ToEpochDataRaw())
if err != nil {
return fmt.Errorf("cannot set epoch data: %w", err)
}
Expand Down
13 changes: 4 additions & 9 deletions dot/types/consensus_digest.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,16 +102,11 @@ func (d NextEpochData) String() string { //skipcq: GO-W1029
}

// ToEpochData returns the NextEpochData as EpochData
func (d *NextEpochData) ToEpochData() (*EpochData, error) { //skipcq: GO-W1029
auths, err := BABEAuthorityRawToAuthority(d.Authorities)
if err != nil {
return nil, err
}

return &EpochData{
Authorities: auths,
func (d *NextEpochData) ToEpochDataRaw() *EpochDataRaw {
return &EpochDataRaw{
Authorities: d.Authorities,
Randomness: d.Randomness,
}, nil
}
}

// BABEOnDisabled represents a GRANDPA authority being disabled
Expand Down
12 changes: 4 additions & 8 deletions lib/babe/babe.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,28 +258,24 @@ func (b *Service) Stop() error {
}

// Authorities returns the current BABE authorities
func (b *Service) Authorities() []types.Authority {
auths := make([]types.Authority, len(b.epochHandler.epochData.authorities))
for i, auth := range b.epochHandler.epochData.authorities {
auths[i] = *auth.DeepCopy()
}
return auths
func (b *Service) AuthoritiesRaw() []types.AuthorityRaw {
return b.epochHandler.epochData.authorities
}

// IsStopped returns true if the service is stopped (ie not producing blocks)
func (b *Service) IsStopped() bool {
return b.ctx.Err() != nil
}

func (b *Service) getAuthorityIndex(Authorities []types.Authority) (uint32, error) {
func (b *Service) getAuthorityIndex(Authorities []types.AuthorityRaw) (uint32, error) {
if !b.authority {
return 0, ErrNotAuthority
}

pub := b.keypair.Public()

for i, auth := range Authorities {
if bytes.Equal(pub.Encode(), auth.Key.Encode()) {
if bytes.Equal(pub.Encode(), auth.Key[:]) {
return uint32(i), nil
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/babe/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func checkPrimaryThreshold(randomness Randomness,

func claimSecondarySlotVRF(randomness Randomness,
slot, epoch uint64,
authorities []types.Authority,
authorities []types.AuthorityRaw,
keypair *sr25519.Keypair,
authorityIndex uint32,
) (*VrfOutputAndProof, error) {
Expand Down Expand Up @@ -123,7 +123,7 @@ func claimSecondarySlotVRF(randomness Randomness,
}, nil
}

func claimSecondarySlotPlain(randomness Randomness, slot uint64, authorities []types.Authority, authorityIndex uint32,
func claimSecondarySlotPlain(randomness Randomness, slot uint64, authorities []types.AuthorityRaw, authorityIndex uint32,
) error {
secondarySlotAuthor, err := getSecondarySlotAuthor(slot, len(authorities), randomness)
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions lib/babe/epoch.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (b *Service) getEpochData(epoch uint64, bestBlock *types.Header) (*epochDat
return epochData, nil
}

currEpochData, err := b.epochState.GetEpochData(epoch, bestBlock)
currEpochData, err := b.epochState.GetEpochDataRaw(epoch, bestBlock)
if err != nil {
return nil, fmt.Errorf("cannot get epoch data for epoch %d: %w", epoch, err)
}
Expand Down Expand Up @@ -127,13 +127,13 @@ func (b *Service) getEpochData(epoch uint64, bestBlock *types.Header) (*epochDat
func (b *Service) getLatestEpochData() (resEpochData *epochData, error error) {
resEpochData = &epochData{}

epochData, err := b.epochState.GetLatestEpochData()
epochDataRaw, err := b.epochState.GetLatestEpochDataRaw()
if err != nil {
return nil, fmt.Errorf("cannot get latest epoch data: %w", err)
}

resEpochData.randomness = epochData.Randomness
resEpochData.authorities = epochData.Authorities
resEpochData.randomness = epochDataRaw.Randomness
resEpochData.authorities = epochDataRaw.Authorities

configData, err := b.epochState.GetLatestConfigData()
if err != nil {
Expand Down
5 changes: 2 additions & 3 deletions lib/babe/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,15 @@ type EpochState interface {
GetSlotDuration() (time.Duration, error)
SetCurrentEpoch(epoch uint64) error
GetCurrentEpoch() (uint64, error)
SetEpochData(epoch uint64, info *types.EpochData) error

GetEpochData(epoch uint64, header *types.Header) (*types.EpochData, error)
GetEpochDataRaw(epoch uint64, header *types.Header) (*types.EpochDataRaw, error)
GetConfigData(epoch uint64, header *types.Header) (*types.ConfigData, error)

GetLatestConfigData() (*types.ConfigData, error)
GetStartSlotForEpoch(epoch uint64) (uint64, error)
GetEpochForBlock(header *types.Header) (uint64, error)
SetFirstSlot(slot uint64) error
GetLatestEpochData() (*types.EpochData, error)
GetLatestEpochDataRaw() (*types.EpochDataRaw, error)
SkipVerify(*types.Header) (bool, error)
}

Expand Down
2 changes: 1 addition & 1 deletion lib/babe/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (d Authorities) String() string {
type epochData struct {
randomness Randomness
authorityIndex uint32
authorities []types.Authority
authorities []types.AuthorityRaw
threshold *scale.Uint128
allowedSlots types.AllowedSlots
}
Expand Down
30 changes: 16 additions & 14 deletions lib/babe/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ var errEmptyKeyOwnershipProof = errors.New("key ownership proof is nil")
// verifierInfo contains the information needed to verify blocks
// it remains the same for an epoch
type verifierInfo struct {
authorities []types.Authority
authorities []types.AuthorityRaw
randomness Randomness
threshold *scale.Uint128
secondarySlots bool
Expand Down Expand Up @@ -195,7 +195,7 @@ func (v *VerificationManager) VerifyBlock(header *types.Header) error {
}

func (v *VerificationManager) getVerifierInfo(epoch uint64, header *types.Header) (*verifierInfo, error) {
epochData, err := v.epochState.GetEpochData(epoch, header)
epochData, err := v.epochState.GetEpochDataRaw(epoch, header)
if err != nil {
return nil, fmt.Errorf("failed to get epoch data for epoch %d: %w", epoch, err)
}
Expand Down Expand Up @@ -223,7 +223,7 @@ type verifier struct {
blockState BlockState
slotState SlotState
epoch uint64
authorities []types.Authority
authorities []types.AuthorityRaw
randomness Randomness
threshold *scale.Uint128
secondarySlots bool
Expand Down Expand Up @@ -294,7 +294,11 @@ func (b *verifier) verifyAuthorshipRight(header *types.Header) error {
authIdx = d.AuthorityIndex
}

authorPub := b.authorities[authIdx].Key
authority := new(types.Authority)
err = authority.FromRawSr25519(&b.authorities[authIdx])
if err != nil {
return fmt.Errorf("from raw sr25519: %w", err)
}

// remove seal before verifying signature
h := types.NewDigest()
Expand Down Expand Up @@ -331,7 +335,7 @@ func (b *verifier) verifyAuthorshipRight(header *types.Header) error {
return err
}

ok, err = authorPub.Verify(hash[:], seal.Data)
ok, err = authority.Key.Verify(hash[:], seal.Data)
if err != nil {
return err
}
Expand Down Expand Up @@ -396,7 +400,7 @@ func (b *verifier) verifyBlockEquivocation(header *types.Header) (bool, error) {
}

slotNow := getCurrentSlot(b.slotDuration)
signer := types.AuthorityID(b.authorities[authorityIndex].ToRaw().Key)
signer := b.authorities[authorityIndex].Key
equivocationProof, err := b.slotState.CheckEquivocation(slotNow, slotNumber,
header, signer)
if err != nil {
Expand Down Expand Up @@ -449,9 +453,8 @@ func (b *verifier) verifyPreRuntimeDigest(digest *types.PreRuntimeDigest) (scale
ok = false
break
}
pub := b.authorities[d.AuthorityIndex].Key

pk, err := sr25519.NewPublicKey(pub.Encode())
authority := b.authorities[d.AuthorityIndex]
pk, err := sr25519.NewPublicKey(authority.Key[:])
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -487,9 +490,8 @@ func (b *verifier) verifyPreRuntimeDigest(digest *types.PreRuntimeDigest) (scale
func (b *verifier) verifyPrimarySlotWinner(authorityIndex uint32,
slot uint64, vrfOutput [sr25519.VRFOutputLength]byte,
vrfProof [sr25519.VRFProofLength]byte) (bool, error) {
pub := b.authorities[authorityIndex].Key

pk, err := sr25519.NewPublicKey(pub.Encode())
authority := b.authorities[authorityIndex]
pk, err := sr25519.NewPublicKey(authority.Key[:])
if err != nil {
return false, err
}
Expand All @@ -511,10 +513,10 @@ func (b *verifier) verifyPrimarySlotWinner(authorityIndex uint32,

// validate VRF proof
logger.Tracef("verifyPrimarySlotWinner authority index %d, "+
"public key %s, randomness 0x%x, slot %d, epoch %d, "+
"public key 0x%x, randomness 0x%x, slot %d, epoch %d, "+
"output 0x%x and proof 0x%x",
authorityIndex,
pub.Hex(), b.randomness, slot, b.epoch,
authority.Key[:], b.randomness, slot, b.epoch,
vrfOutput, vrfProof[:])

t := makeTranscript(b.randomness, slot, b.epoch)
Expand Down

0 comments on commit 34f296d

Please sign in to comment.