2022-10-08 14:15:44 +00:00
|
|
|
/*
|
|
|
|
Copyright 2022 Erigon-Lightclient contributors
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2022-09-30 21:53:54 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2023-03-31 05:07:43 +00:00
|
|
|
"crypto/sha256"
|
2022-09-30 21:53:54 +00:00
|
|
|
"hash"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2023-02-07 16:44:37 +00:00
|
|
|
type HashFunc func(data []byte, extras ...[]byte) [32]byte
|
|
|
|
|
2022-09-30 21:53:54 +00:00
|
|
|
var hasherPool = sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
return sha256.New()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2023-02-07 16:44:37 +00:00
|
|
|
// General purpose Keccak256
|
2022-12-09 18:19:01 +00:00
|
|
|
func Keccak256(data []byte, extras ...[]byte) [32]byte {
|
2022-09-30 21:53:54 +00:00
|
|
|
h, ok := hasherPool.Get().(hash.Hash)
|
|
|
|
if !ok {
|
|
|
|
h = sha256.New()
|
|
|
|
}
|
|
|
|
defer hasherPool.Put(h)
|
|
|
|
h.Reset()
|
|
|
|
|
|
|
|
var b [32]byte
|
|
|
|
|
|
|
|
h.Write(data)
|
2022-12-09 18:19:01 +00:00
|
|
|
for _, extra := range extras {
|
|
|
|
h.Write(extra)
|
|
|
|
}
|
2022-09-30 21:53:54 +00:00
|
|
|
h.Sum(b[:0])
|
|
|
|
return b
|
|
|
|
}
|
2023-02-07 16:44:37 +00:00
|
|
|
|
|
|
|
// Optimized Keccak256, avoid pool.put/pool.get, meant for intensive operations.
|
|
|
|
func OptimizedKeccak256() HashFunc {
|
|
|
|
h := sha256.New()
|
|
|
|
return func(data []byte, extras ...[]byte) [32]byte {
|
|
|
|
h.Reset()
|
|
|
|
var b [32]byte
|
|
|
|
h.Write(data)
|
|
|
|
for _, extra := range extras {
|
|
|
|
h.Write(extra)
|
|
|
|
}
|
|
|
|
h.Sum(b[:0])
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
}
|
2023-05-04 13:18:42 +00:00
|
|
|
|
|
|
|
// Optimized Keccak256, avoid pool.put/pool.get, meant for intensive operations.
|
|
|
|
// this version is not thread safe
|
|
|
|
func OptimizedKeccak256NotThreadSafe() HashFunc {
|
|
|
|
h := sha256.New()
|
|
|
|
var b [32]byte
|
|
|
|
return func(data []byte, extras ...[]byte) [32]byte {
|
|
|
|
h.Reset()
|
|
|
|
h.Write(data)
|
|
|
|
for _, extra := range extras {
|
|
|
|
h.Write(extra)
|
|
|
|
}
|
|
|
|
h.Sum(b[:0])
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
}
|