trie: use hasher instead of allocate keccack256 every time

This commit is contained in:
rjl493456442 2019-05-07 18:25:03 +08:00
parent e10e8f23c4
commit 04dccfb25a

View file

@ -21,7 +21,6 @@ import (
"fmt" "fmt"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
@ -81,7 +80,7 @@ func (t *Trie) Prove(key []byte, fromLevel uint, proofDb ethdb.Writer) error {
} else { } else {
enc, _ := rlp.EncodeToBytes(n) enc, _ := rlp.EncodeToBytes(n)
if !ok { if !ok {
hash = crypto.Keccak256(enc) hash = hasher.makeHashNode(enc)
} }
proofDb.Put(hash, enc) proofDb.Put(hash, enc)
} }
@ -105,6 +104,9 @@ func (t *SecureTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Writer) err
// key in a trie with the given root hash. VerifyProof returns an error if the // key in a trie with the given root hash. VerifyProof returns an error if the
// proof contains invalid trie nodes or the wrong value. // proof contains invalid trie nodes or the wrong value.
func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.Reader) (value []byte, nodes int, err error) { func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.Reader) (value []byte, nodes int, err error) {
hasher := newHasher(nil)
defer returnHasherToPool(hasher)
key = keybytesToHex(key) key = keybytesToHex(key)
wantHash := rootHash wantHash := rootHash
for i := 0; ; i++ { for i := 0; ; i++ {
@ -112,8 +114,8 @@ func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.Reader) (value
if buf == nil { if buf == nil {
return nil, i, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash) return nil, i, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash)
} }
if bytes.Compare(crypto.Keccak256(buf), wantHash[:]) != 0 { if !bytes.Equal(hasher.makeHashNode(buf), wantHash.Bytes()) {
return nil, i, fmt.Errorf("proof node %d (hash %64x) invalid", i, wantHash) return nil, i, fmt.Errorf("proof node %d (hash %064x) invalid", i, wantHash)
} }
n, err := decodeNode(wantHash[:], buf) n, err := decodeNode(wantHash[:], buf)
if err != nil { if err != nil {