2021-04-30 19:55:12 +00:00
|
|
|
package consensus
|
|
|
|
|
|
|
|
import (
|
2021-07-19 20:19:06 +00:00
|
|
|
"encoding/hex"
|
2021-06-11 11:40:32 +00:00
|
|
|
|
2021-07-21 21:56:58 +00:00
|
|
|
drand2 "github.com/Secured-Finance/dione/beacon/drand"
|
|
|
|
|
2021-07-19 20:19:06 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2021-06-11 11:40:32 +00:00
|
|
|
|
|
|
|
"github.com/Secured-Finance/dione/blockchain"
|
2021-04-30 19:55:12 +00:00
|
|
|
types2 "github.com/Secured-Finance/dione/consensus/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ConsensusValidator struct {
|
2021-07-19 20:19:06 +00:00
|
|
|
validationFuncMap map[types2.ConsensusMessageType]func(msg types2.ConsensusMessage) bool
|
|
|
|
miner *blockchain.Miner
|
2021-07-21 21:56:58 +00:00
|
|
|
beacon *drand2.DrandBeacon
|
2021-06-11 11:40:32 +00:00
|
|
|
blockchain *blockchain.BlockChain
|
2021-04-30 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2021-07-21 21:56:58 +00:00
|
|
|
func NewConsensusValidator(miner *blockchain.Miner, bc *blockchain.BlockChain, db *drand2.DrandBeacon) *ConsensusValidator {
|
2021-04-30 19:55:12 +00:00
|
|
|
cv := &ConsensusValidator{
|
2021-06-11 11:40:32 +00:00
|
|
|
miner: miner,
|
|
|
|
blockchain: bc,
|
2021-07-21 21:56:58 +00:00
|
|
|
beacon: db,
|
2021-04-30 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
2021-07-19 20:19:06 +00:00
|
|
|
cv.validationFuncMap = map[types2.ConsensusMessageType]func(msg types2.ConsensusMessage) bool{
|
|
|
|
types2.ConsensusMessageTypePrePrepare: func(msg types2.ConsensusMessage) bool {
|
|
|
|
if err := cv.blockchain.ValidateBlock(msg.Block); err != nil {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"blockHash": hex.EncodeToString(msg.Block.Header.Hash),
|
|
|
|
"err": err.Error(),
|
|
|
|
}).Error("failed to validate block from PrePrepare message")
|
2021-06-11 11:40:32 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
},
|
2021-07-19 20:19:06 +00:00
|
|
|
types2.ConsensusMessageTypePrepare: checkSignatureForBlockhash,
|
|
|
|
types2.ConsensusMessageTypeCommit: checkSignatureForBlockhash,
|
2021-04-30 19:55:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return cv
|
|
|
|
}
|
|
|
|
|
2021-07-19 20:19:06 +00:00
|
|
|
func (cv *ConsensusValidator) Valid(msg types2.ConsensusMessage) bool {
|
|
|
|
return cv.validationFuncMap[msg.Type](msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkSignatureForBlockhash(msg types2.ConsensusMessage) bool {
|
|
|
|
pubKey, err := msg.From.ExtractPublicKey()
|
|
|
|
if err != nil {
|
|
|
|
// TODO logging
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ok, err := pubKey.Verify(msg.Blockhash, msg.Signature)
|
|
|
|
if err != nil {
|
|
|
|
// TODO logging
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return ok
|
2021-04-30 19:55:12 +00:00
|
|
|
}
|