From 415d9579e141c5d2c438fc5e3411639b7c109f57 Mon Sep 17 00:00:00 2001 From: Zaki Manian Date: Tue, 16 Jul 2019 19:55:09 -0700 Subject: [PATCH] Add the compare validator powers proposal as discussed with Zarko in the ADR --- lite/errors/errors.go | 22 ++++++++++++++++++++++ lite/verifying/provider.go | 26 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/lite/errors/errors.go b/lite/errors/errors.go index 9242f46c9..ce479342c 100644 --- a/lite/errors/errors.go +++ b/lite/errors/errors.go @@ -130,3 +130,25 @@ func IsErrCommitExpired(err error) bool { } return false } + +type errValidatorChange struct { + change float64 +} + +func (e errValidatorChange) Error() string { + return fmt.Sprintf("%f is more than 1/3rd validator change", e.change) +} + +func ErrValidatorChange(change float64) error { + return cmn.ErrorWrap(errValidatorChange{ + change: change, + }, "") +} + +func IsErrValidatorChange(err error) bool { + if err_, ok := err.(cmn.Error); ok { + _, ok := err_.Data().(errValidatorChange) + return ok + } + return false +} diff --git a/lite/verifying/provider.go b/lite/verifying/provider.go index b45922ab8..e53e3ab91 100644 --- a/lite/verifying/provider.go +++ b/lite/verifying/provider.go @@ -7,6 +7,7 @@ import ( "bytes" "errors" "fmt" + "math" "sync" "time" @@ -369,10 +370,35 @@ func (vp *Provider) verifyAndSave(trustedFC, newFC lite.FullCommit) error { return err } } + change := CompareVotingPowers(trustedFC, newFC) + + if change > float64(1/3) { + return lerr.ErrValidatorChange(change) + } return vp.trusted.SaveFullCommit(newFC) } +func CompareVotingPowers(trustedFC, newFC lite.FullCommit) float64 { + + var diffAccumulator float64 + + for _, val := range newFC.Validators.Validators { + + newPowerRatio := float64(val.VotingPower) / float64(newFC.Validators.TotalVotingPower()) + + _, tval := trustedFC.NextValidators.GetByAddress(val.Address) + + oldPowerRatio := float64(tval.VotingPower) / float64(trustedFC.NextValidators.TotalVotingPower()) + + diffAccumulator += math.Abs(newPowerRatio - oldPowerRatio) + + } + + return diffAccumulator + +} + func (vp *Provider) fetchAndVerifyToHeightLinear(h int64) (lite.FullCommit, error) { // Fetch latest full commit from source.