|
4 | 4 | package block
|
5 | 5 |
|
6 | 6 | import (
|
| 7 | + "bytes" |
7 | 8 | "crypto/sha256"
|
8 | 9 | "encoding/base64"
|
9 | 10 | "fmt"
|
@@ -310,7 +311,7 @@ type Block struct {
|
310 | 311 | // Block Hash will automatically be computed and set.
|
311 | 312 | func New(header Header, txs Txs, plan Plan, prevState State) Block {
|
312 | 313 | return Block{
|
313 |
| - hash: ComputeHash(header, txs, plan, prevState), |
| 314 | + hash: NewBlockHash(header, txs, plan, prevState), |
314 | 315 | header: header,
|
315 | 316 | txs: txs,
|
316 | 317 | plan: plan,
|
@@ -438,9 +439,23 @@ var (
|
438 | 439 | InvalidHeight = Height(-1)
|
439 | 440 | )
|
440 | 441 |
|
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 |
442 | 443 | // state before execution (i.e. state after execution of its parent). This
|
443 | 444 | // 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()) |
446 | 461 | }
|
0 commit comments