Skip to content

Commit 20b34c2

Browse files
author
Loong
committed
block, replica: hash blocks using surge
1 parent f42c792 commit 20b34c2

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

block/block.go

+19-4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package block
55

66
import (
7+
"bytes"
78
"crypto/sha256"
89
"encoding/base64"
910
"fmt"
@@ -310,7 +311,7 @@ type Block struct {
310311
// Block Hash will automatically be computed and set.
311312
func New(header Header, txs Txs, plan Plan, prevState State) Block {
312313
return Block{
313-
hash: ComputeHash(header, txs, plan, prevState),
314+
hash: NewBlockHash(header, txs, plan, prevState),
314315
header: header,
315316
txs: txs,
316317
plan: plan,
@@ -438,9 +439,23 @@ var (
438439
InvalidHeight = Height(-1)
439440
)
440441

441-
// ComputeHash of a block based on its header, transactions, execution plan and
442+
// NewBlockHash of a block based on its header, transactions, execution plan and
442443
// state before execution (i.e. state after execution of its parent). This
443444
// function returns a hash that can be used when creating a block.
444-
func ComputeHash(header Header, txs Txs, plan Plan, prevState State) id.Hash {
445-
return sha256.Sum256([]byte(fmt.Sprintf("BlockHash(Header=%v,Txs=%v,Plan=%v,PreviousState=%v)", header, txs, plan, prevState)))
445+
func NewBlockHash(header Header, txs Txs, plan Plan, prevState State) id.Hash {
446+
buf := new(bytes.Buffer)
447+
buf.Grow(header.SizeHint() + surge.SizeHint([]byte(txs)) + surge.SizeHint([]byte(plan)) + surge.SizeHint([]byte(prevState)))
448+
if _, err := surge.Marshal(buf, header, surge.MaxBytes); err != nil {
449+
return id.Hash{} // Return the empty hash on an error.
450+
}
451+
if _, err := surge.Marshal(buf, []byte(txs), surge.MaxBytes); err != nil {
452+
return id.Hash{} // Return the empty hash on an error.
453+
}
454+
if _, err := surge.Marshal(buf, []byte(plan), surge.MaxBytes); err != nil {
455+
return id.Hash{} // Return the empty hash on an error.
456+
}
457+
if _, err := surge.Marshal(buf, []byte(prevState), surge.MaxBytes); err != nil {
458+
return id.Hash{} // Return the empty hash on an error.
459+
}
460+
return sha256.Sum256(buf.Bytes())
446461
}

replica/rebase.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ func (rebaser *shardRebaser) IsBlockValid(proposedBlock block.Block, checkHistor
153153
}
154154

155155
// Check the expected `block.Hash`
156-
if !proposedBlock.Hash().Equal(block.ComputeHash(proposedBlock.Header(), proposedBlock.Txs(), proposedBlock.Plan(), proposedBlock.PreviousState())) {
156+
if !proposedBlock.Hash().Equal(block.NewBlockHash(proposedBlock.Header(), proposedBlock.Txs(), proposedBlock.Plan(), proposedBlock.PreviousState())) {
157157
return nilReasons, fmt.Errorf("unexpected block hash for proposed block")
158158
}
159159

0 commit comments

Comments
 (0)