From a57a1c2392f6f150d2127cc28236ca74f338dd7e Mon Sep 17 00:00:00 2001 From: Jimmy Hu Date: Sun, 12 Aug 2018 00:40:29 +0800 Subject: core: Hash block in Consensus.PrepareBlock. (#46) * Add hash to block * Check block hash in Consensus.sanityCheck * Add hashBlockFn in block generator.go --- core/consensus.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'core/consensus.go') diff --git a/core/consensus.go b/core/consensus.go index bc6a2d7..b1b1973 100644 --- a/core/consensus.go +++ b/core/consensus.go @@ -18,6 +18,7 @@ package core import ( + "fmt" "sync" "time" @@ -36,6 +37,11 @@ func (e *ErrMissingBlockInfo) Error() string { return "missing " + e.MissingField + " in block" } +// Errors for sanity check error. +var ( + ErrIncorrectHash = fmt.Errorf("hash of block is incorrect") +) + // Consensus implements DEXON Consensus algorithm. type Consensus struct { app Application @@ -76,8 +82,23 @@ func NewConsensus( } } +// sanityCheck checks if the block is a valid block +func (con *Consensus) sanityCheck(blockConv types.BlockConverter) (err error) { + b := blockConv.Block() + // Check the hash of block. + hash, err := hashBlock(blockConv) + if err != nil || hash != b.Hash { + return ErrIncorrectHash + } + + return nil +} + // ProcessBlock is the entry point to submit one block to a Consensus instance. func (con *Consensus) ProcessBlock(blockConv types.BlockConverter) (err error) { + if err := con.sanityCheck(blockConv); err != nil { + return err + } b := blockConv.Block() var ( deliveredBlocks []*types.Block @@ -144,6 +165,7 @@ func (con *Consensus) PrepareBlock(blockConv types.BlockConverter, con.rbModule.prepareBlock(b) b.Timestamps[b.ProposerID] = proposeTime + b.Hash, err = hashBlock(b) blockConv.SetBlock(b) return } -- cgit v1.2.3