From d23f38b4f3eea39f02b967ad77106ac8bf580517 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 12 Mar 2016 13:01:08 -0500 Subject: [PATCH] txs.Hash() to avoid extra allocs --- types/block.go | 8 ++------ types/tx.go | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/types/block.go b/types/block.go index 739a61b1f..9ce45bce0 100644 --- a/types/block.go +++ b/types/block.go @@ -329,7 +329,7 @@ type Data struct { // Txs that will be applied by state @ block.Height+1. // NOTE: not all txs here are valid. We're just agreeing on the order first. // This means that block.AppHash does not include these txs. - Txs []Tx `json:"txs"` + Txs Txs `json:"txs"` // Volatile hash []byte @@ -342,11 +342,7 @@ func (data *Data) Hash() []byte { return data.hash } if data.hash == nil { - txs := make([]interface{}, len(data.Txs)) - for i, tx := range data.Txs { - txs[i] = tx - } - data.hash = merkle.SimpleHashFromBinaries(txs) // NOTE: leaves are TxIDs. + data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs } return data.hash } diff --git a/types/tx.go b/types/tx.go index a3cb9fc04..63a7afad4 100644 --- a/types/tx.go +++ b/types/tx.go @@ -1,3 +1,24 @@ package types +import ( + "github.com/tendermint/go-merkle" +) + type Tx []byte + +type Txs []Tx + +func (txs Txs) Hash() []byte { + // Recursive impl. + // Copied from go-merkle to avoid allocations + switch len(txs) { + case 0: + return nil + case 1: + return txs[0] + default: + left := Txs(txs[:(len(txs)+1)/2]).Hash() + right := Txs(txs[(len(txs)+1)/2:]).Hash() + return merkle.SimpleHashFromTwoHashes(left, right) + } +}