all: Rename crypto.Sha3{,Hash}() to crypto.Keccak256{,Hash}()

As we aren't really using the standarized SHA-3
This commit is contained in:
Ricardo Catalinas Jiménez 2016-02-21 18:40:27 +00:00
parent c20d6e5e4e
commit 436fc8d76a
48 changed files with 92 additions and 92 deletions

View File

@ -244,7 +244,7 @@ func TestMethodSignature(t *testing.T) {
t.Error("signature mismatch", exp, "!=", m.Sig()) t.Error("signature mismatch", exp, "!=", m.Sig())
} }
idexp := crypto.Sha3([]byte(exp))[:4] idexp := crypto.Keccak256([]byte(exp))[:4]
if !bytes.Equal(m.Id(), idexp) { if !bytes.Equal(m.Id(), idexp) {
t.Errorf("expected ids to match %x != %x", m.Id(), idexp) t.Errorf("expected ids to match %x != %x", m.Id(), idexp)
} }
@ -264,7 +264,7 @@ func TestPack(t *testing.T) {
t.FailNow() t.FailNow()
} }
sig := crypto.Sha3([]byte("foo(uint32)"))[:4] sig := crypto.Keccak256([]byte("foo(uint32)"))[:4]
sig = append(sig, make([]byte, 32)...) sig = append(sig, make([]byte, 32)...)
sig[35] = 10 sig[35] = 10
@ -286,7 +286,7 @@ func TestMultiPack(t *testing.T) {
t.FailNow() t.FailNow()
} }
sig := crypto.Sha3([]byte("bar(uint32,uint16)"))[:4] sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
sig = append(sig, make([]byte, 64)...) sig = append(sig, make([]byte, 64)...)
sig[35] = 10 sig[35] = 10
sig[67] = 11 sig[67] = 11
@ -309,7 +309,7 @@ func TestPackSlice(t *testing.T) {
t.FailNow() t.FailNow()
} }
sig := crypto.Sha3([]byte("slice(uint32[2])"))[:4] sig := crypto.Keccak256([]byte("slice(uint32[2])"))[:4]
sig = append(sig, make([]byte, 64)...) sig = append(sig, make([]byte, 64)...)
sig[35] = 1 sig[35] = 1
sig[67] = 2 sig[67] = 2
@ -332,7 +332,7 @@ func TestPackSliceBig(t *testing.T) {
t.FailNow() t.FailNow()
} }
sig := crypto.Sha3([]byte("slice256(uint256[2])"))[:4] sig := crypto.Keccak256([]byte("slice256(uint256[2])"))[:4]
sig = append(sig, make([]byte, 64)...) sig = append(sig, make([]byte, 64)...)
sig[35] = 1 sig[35] = 1
sig[67] = 2 sig[67] = 2

View File

@ -40,5 +40,5 @@ func (e Event) Id() common.Hash {
types[i] = input.Type.String() types[i] = input.Type.String()
i++ i++
} }
return common.BytesToHash(crypto.Sha3([]byte(fmt.Sprintf("%v(%v)", e.Name, strings.Join(types, ","))))) return common.BytesToHash(crypto.Keccak256([]byte(fmt.Sprintf("%v(%v)", e.Name, strings.Join(types, ",")))))
} }

View File

@ -19,8 +19,8 @@ func TestEventId(t *testing.T) {
{ "type" : "event", "name" : "check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] } { "type" : "event", "name" : "check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] }
]`, ]`,
expectations: map[string]common.Hash{ expectations: map[string]common.Hash{
"balance": crypto.Sha3Hash([]byte("balance(uint256)")), "balance": crypto.Keccak256Hash([]byte("balance(uint256)")),
"check": crypto.Sha3Hash([]byte("check(address,uint256)")), "check": crypto.Keccak256Hash([]byte("check(address,uint256)")),
}, },
}, },
} }

View File

@ -72,5 +72,5 @@ func (m Method) String() string {
} }
func (m Method) Id() []byte { func (m Method) Id() []byte {
return crypto.Sha3([]byte(m.Sig()))[:4] return crypto.Keccak256([]byte(m.Sig()))[:4]
} }

View File

@ -396,7 +396,7 @@ multiply7 = Multiply7.at(contractaddress);
if sol != nil && solcVersion != sol.Version() { if sol != nil && solcVersion != sol.Version() {
modContractInfo := versionRE.ReplaceAll(contractInfo, []byte(`"compilerVersion":"`+sol.Version()+`"`)) modContractInfo := versionRE.ReplaceAll(contractInfo, []byte(`"compilerVersion":"`+sol.Version()+`"`))
fmt.Printf("modified contractinfo:\n%s\n", modContractInfo) fmt.Printf("modified contractinfo:\n%s\n", modContractInfo)
contentHash = `"` + common.ToHex(crypto.Sha3([]byte(modContractInfo))) + `"` contentHash = `"` + common.ToHex(crypto.Keccak256([]byte(modContractInfo))) + `"`
} }
if checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`) != nil { if checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`) != nil {
return return

View File

@ -220,7 +220,7 @@ func SaveInfo(info *ContractInfo, filename string) (contenthash common.Hash, err
if err != nil { if err != nil {
return return
} }
contenthash = common.BytesToHash(crypto.Sha3(infojson)) contenthash = common.BytesToHash(crypto.Keccak256(infojson))
err = ioutil.WriteFile(filename, infojson, 0600) err = ioutil.WriteFile(filename, infojson, 0600)
return return
} }

View File

@ -74,7 +74,7 @@ func (self *HTTPClient) GetAuthContent(uri string, hash common.Hash) ([]byte, er
} }
// check hash to authenticate content // check hash to authenticate content
chash := crypto.Sha3Hash(content) chash := crypto.Keccak256Hash(content)
if chash != hash { if chash != hash {
return nil, fmt.Errorf("content hash mismatch %x != %x (exp)", hash[:], chash[:]) return nil, fmt.Errorf("content hash mismatch %x != %x (exp)", hash[:], chash[:])
} }

View File

@ -36,7 +36,7 @@ func TestGetAuthContent(t *testing.T) {
client := New(dir) client := New(dir)
text := "test" text := "test"
hash := crypto.Sha3Hash([]byte(text)) hash := crypto.Keccak256Hash([]byte(text))
if err := ioutil.WriteFile(path.Join(dir, "test.content"), []byte(text), os.ModePerm); err != nil { if err := ioutil.WriteFile(path.Join(dir, "test.content"), []byte(text), os.ModePerm); err != nil {
t.Fatal("could not write test file", err) t.Fatal("could not write test file", err)
} }

View File

@ -115,7 +115,7 @@ func FetchDocsForContract(contractAddress string, xeth *xeth.XEth, client *httpc
err = fmt.Errorf("contract (%v) not found", contractAddress) err = fmt.Errorf("contract (%v) not found", contractAddress)
return return
} }
codehash := common.BytesToHash(crypto.Sha3(codeb)) codehash := common.BytesToHash(crypto.Keccak256(codeb))
// set up nameresolver with natspecreg + urlhint contract addresses // set up nameresolver with natspecreg + urlhint contract addresses
reg := registrar.New(xeth) reg := registrar.New(xeth)
@ -197,7 +197,7 @@ type userDoc struct {
func (self *NatSpec) makeAbi2method(abiKey [8]byte) (meth *method) { func (self *NatSpec) makeAbi2method(abiKey [8]byte) (meth *method) {
for signature, m := range self.userDoc.Methods { for signature, m := range self.userDoc.Methods {
name := strings.Split(signature, "(")[0] name := strings.Split(signature, "(")[0]
hash := []byte(common.Bytes2Hex(crypto.Sha3([]byte(signature)))) hash := []byte(common.Bytes2Hex(crypto.Keccak256([]byte(signature))))
var key [8]byte var key [8]byte
copy(key[:], hash[:8]) copy(key[:], hash[:8])
if bytes.Equal(key[:], abiKey[:]) { if bytes.Equal(key[:], abiKey[:]) {

View File

@ -238,11 +238,11 @@ func TestNatspecE2E(t *testing.T) {
// create a contractInfo file (mock cloud-deployed contract metadocs) // create a contractInfo file (mock cloud-deployed contract metadocs)
// incidentally this is the info for the HashReg contract itself // incidentally this is the info for the HashReg contract itself
ioutil.WriteFile("/tmp/"+testFileName, []byte(testContractInfo), os.ModePerm) ioutil.WriteFile("/tmp/"+testFileName, []byte(testContractInfo), os.ModePerm)
dochash := crypto.Sha3Hash([]byte(testContractInfo)) dochash := crypto.Keccak256Hash([]byte(testContractInfo))
// take the codehash for the contract we wanna test // take the codehash for the contract we wanna test
codeb := tf.xeth.CodeAtBytes(registrar.HashRegAddr) codeb := tf.xeth.CodeAtBytes(registrar.HashRegAddr)
codehash := crypto.Sha3Hash(codeb) codehash := crypto.Keccak256Hash(codeb)
reg := registrar.New(tf.xeth) reg := registrar.New(tf.xeth)
_, err := reg.SetHashToHash(addr, codehash, dochash) _, err := reg.SetHashToHash(addr, codehash, dochash)

View File

@ -86,7 +86,7 @@ func (api *PrivateRegistarAPI) Register(sender common.Address, addr common.Addre
} }
codeb := state.GetCode(addr) codeb := state.GetCode(addr)
codeHash := common.BytesToHash(crypto.Sha3(codeb)) codeHash := common.BytesToHash(crypto.Keccak256(codeb))
contentHash := common.HexToHash(contentHashHex) contentHash := common.HexToHash(contentHashHex)
_, err = registrar.New(api.be).SetHashToHash(sender, codeHash, contentHash) _, err = registrar.New(api.be).SetHashToHash(sender, codeHash, contentHash)

View File

@ -68,7 +68,7 @@ const (
) )
func abiSignature(s string) string { func abiSignature(s string) string {
return common.ToHex(crypto.Sha3([]byte(s))[:4]) return common.ToHex(crypto.Keccak256([]byte(s))[:4])
} }
var ( var (
@ -401,7 +401,7 @@ func storageMapping(addr, key []byte) []byte {
data := make([]byte, 64) data := make([]byte, 64)
copy(data[0:32], key[0:32]) copy(data[0:32], key[0:32])
copy(data[32:64], addr[0:32]) copy(data[32:64], addr[0:32])
sha := crypto.Sha3(data) sha := crypto.Keccak256(data)
return sha return sha
} }

View File

@ -31,7 +31,7 @@ type testBackend struct {
var ( var (
text = "test" text = "test"
codehash = common.StringToHash("1234") codehash = common.StringToHash("1234")
hash = common.BytesToHash(crypto.Sha3([]byte(text))) hash = common.BytesToHash(crypto.Keccak256([]byte(text)))
url = "bzz://bzzhash/my/path/contr.act" url = "bzz://bzzhash/my/path/contr.act"
) )

View File

@ -31,8 +31,8 @@ const (
tokenToken = 0xff tokenToken = 0xff
) )
var empty = crypto.Sha3([]byte("")) var empty = crypto.Keccak256([]byte(""))
var emptyList = crypto.Sha3([]byte{0x80}) var emptyList = crypto.Keccak256([]byte{0x80})
func Decompress(dat []byte) ([]byte, error) { func Decompress(dat []byte) ([]byte, error) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)

View File

@ -67,8 +67,8 @@ func (s *CompressionRleSuite) TestDecompressSimple(c *checker.C) {
// } // }
// var exp []byte // var exp []byte
// exp = append(exp, crypto.Sha3([]byte(""))...) // exp = append(exp, crypto.Keccak256([]byte(""))...)
// exp = append(exp, crypto.Sha3([]byte{0x80})...) // exp = append(exp, crypto.Keccak256([]byte{0x80})...)
// exp = append(exp, make([]byte, 10)...) // exp = append(exp, make([]byte, 10)...)
// if bytes.Compare(res, res) != 0 { // if bytes.Compare(res, res) != 0 {
@ -82,12 +82,12 @@ func (s *CompressionRleSuite) TestDecompressSimple(c *checker.C) {
// t.Error("5 * zero", res) // t.Error("5 * zero", res)
// } // }
// res = Compress(crypto.Sha3([]byte(""))) // res = Compress(crypto.Keccak256([]byte("")))
// if bytes.Compare(res, []byte{token, emptyShaToken}) != 0 { // if bytes.Compare(res, []byte{token, emptyShaToken}) != 0 {
// t.Error("empty sha", res) // t.Error("empty sha", res)
// } // }
// res = Compress(crypto.Sha3([]byte{0x80})) // res = Compress(crypto.Keccak256([]byte{0x80}))
// if bytes.Compare(res, []byte{token, emptyListShaToken}) != 0 { // if bytes.Compare(res, []byte{token, emptyListShaToken}) != 0 {
// t.Error("empty list sha", res) // t.Error("empty list sha", res)
// } // }
@ -100,8 +100,8 @@ func (s *CompressionRleSuite) TestDecompressSimple(c *checker.C) {
// func TestCompressMulti(t *testing.T) { // func TestCompressMulti(t *testing.T) {
// in := []byte{0, 0, 0, 0, 0} // in := []byte{0, 0, 0, 0, 0}
// in = append(in, crypto.Sha3([]byte(""))...) // in = append(in, crypto.Keccak256([]byte(""))...)
// in = append(in, crypto.Sha3([]byte{0x80})...) // in = append(in, crypto.Keccak256([]byte{0x80})...)
// in = append(in, token) // in = append(in, token)
// res := Compress(in) // res := Compress(in)
@ -116,8 +116,8 @@ func (s *CompressionRleSuite) TestDecompressSimple(c *checker.C) {
// for i := 0; i < 20; i++ { // for i := 0; i < 20; i++ {
// in = append(in, []byte{0, 0, 0, 0, 0}...) // in = append(in, []byte{0, 0, 0, 0, 0}...)
// in = append(in, crypto.Sha3([]byte(""))...) // in = append(in, crypto.Keccak256([]byte(""))...)
// in = append(in, crypto.Sha3([]byte{0x80})...) // in = append(in, crypto.Keccak256([]byte{0x80})...)
// in = append(in, []byte{123, 2, 19, 89, 245, 254, 255, token, 98, 233}...) // in = append(in, []byte{123, 2, 19, 89, 245, 254, 255, token, 98, 233}...)
// in = append(in, token) // in = append(in, token)
// } // }

View File

@ -30,7 +30,7 @@ import (
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
) )
var emptyCodeHash = crypto.Sha3(nil) var emptyCodeHash = crypto.Keccak256(nil)
type Code []byte type Code []byte
@ -225,7 +225,7 @@ func (self *StateObject) Code() []byte {
func (self *StateObject) SetCode(code []byte) { func (self *StateObject) SetCode(code []byte) {
self.code = code self.code = code
self.codeHash = crypto.Sha3(code) self.codeHash = crypto.Keccak256(code)
self.dirty = true self.dirty = true
} }

View File

@ -101,7 +101,7 @@ func LogsBloom(logs vm.Logs) *big.Int {
} }
func bloom9(b []byte) *big.Int { func bloom9(b []byte) *big.Int {
b = crypto.Sha3(b[:]) b = crypto.Keccak256(b[:])
r := new(big.Int) r := new(big.Int)

View File

@ -73,7 +73,7 @@ func TestBloom9(t *testing.T) {
func TestAddress(t *testing.T) { func TestAddress(t *testing.T) {
block := &Block{} block := &Block{}
block.Coinbase = common.Hex2Bytes("22341ae42d6dd7384bc8584e50419ea3ac75b83f") block.Coinbase = common.Hex2Bytes("22341ae42d6dd7384bc8584e50419ea3ac75b83f")
fmt.Printf("%x\n", crypto.Sha3(block.Coinbase)) fmt.Printf("%x\n", crypto.Keccak256(block.Coinbase))
bin := CreateBloom(block) bin := CreateBloom(block)
fmt.Printf("bin = %x\n", common.LeftPadBytes(bin, 64)) fmt.Printf("bin = %x\n", common.LeftPadBytes(bin, 64))

View File

@ -202,7 +202,7 @@ func doFrom(tx *Transaction, homestead bool) (common.Address, error) {
return common.Address{}, err return common.Address{}, err
} }
var addr common.Address var addr common.Address
copy(addr[:], crypto.Sha3(pubkey[1:])[12:]) copy(addr[:], crypto.Keccak256(pubkey[1:])[12:])
tx.from.Store(addr) tx.from.Store(addr)
return addr, nil return addr, nil
} }

View File

@ -111,7 +111,7 @@ func ecrecoverFunc(in []byte) []byte {
} }
// the first byte of pubkey is bitcoin heritage // the first byte of pubkey is bitcoin heritage
return common.LeftPadBytes(crypto.Sha3(pubKey[1:])[12:], 32) return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32)
} }
func memCpy(in []byte) []byte { func memCpy(in []byte) []byte {

View File

@ -316,7 +316,7 @@ func opMulmod(instr instruction, pc *uint64, env Environment, contract *Contract
func opSha3(instr instruction, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *stack) { func opSha3(instr instruction, pc *uint64, env Environment, contract *Contract, memory *Memory, stack *stack) {
offset, size := stack.pop(), stack.pop() offset, size := stack.pop(), stack.pop()
hash := crypto.Sha3(memory.Get(offset.Int64(), size.Int64())) hash := crypto.Keccak256(memory.Get(offset.Int64(), size.Int64()))
stack.push(common.BytesToBig(hash)) stack.push(common.BytesToBig(hash))
} }

View File

@ -96,7 +96,7 @@ type Program struct {
// NewProgram returns a new JIT program // NewProgram returns a new JIT program
func NewProgram(code []byte) *Program { func NewProgram(code []byte) *Program {
program := &Program{ program := &Program{
Id: crypto.Sha3Hash(code), Id: crypto.Keccak256Hash(code),
mapping: make(map[uint64]uint64), mapping: make(map[uint64]uint64),
destinations: make(map[uint64]struct{}), destinations: make(map[uint64]struct{}),
code: code, code: code,

View File

@ -189,7 +189,7 @@ func (self *Env) Db() Database { return nil }
func (self *Env) GasLimit() *big.Int { return self.gasLimit } func (self *Env) GasLimit() *big.Int { return self.gasLimit }
func (self *Env) VmType() Type { return StdVmTy } func (self *Env) VmType() Type { return StdVmTy }
func (self *Env) GetHash(n uint64) common.Hash { func (self *Env) GetHash(n uint64) common.Hash {
return common.BytesToHash(crypto.Sha3([]byte(big.NewInt(int64(n)).String()))) return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String())))
} }
func (self *Env) AddLog(log *Log) { func (self *Env) AddLog(log *Log) {
} }

View File

@ -67,7 +67,7 @@ func setDefaults(cfg *Config) {
} }
if cfg.GetHashFn == nil { if cfg.GetHashFn == nil {
cfg.GetHashFn = func(n uint64) common.Hash { cfg.GetHashFn = func(n uint64) common.Hash {
return common.BytesToHash(crypto.Sha3([]byte(new(big.Int).SetUint64(n).String()))) return common.BytesToHash(crypto.Keccak256([]byte(new(big.Int).SetUint64(n).String())))
} }
} }
} }

View File

@ -58,7 +58,7 @@ func (self *Vm) Run(contract *Contract, input []byte) (ret []byte, err error) {
} }
var ( var (
codehash = crypto.Sha3Hash(contract.Code) // codehash is used when doing jump dest caching codehash = crypto.Keccak256Hash(contract.Code) // codehash is used when doing jump dest caching
program *Program program *Program
) )
if EnableJit { if EnableJit {

View File

@ -200,7 +200,7 @@ func (self *JitVm) Run(me, caller ContextRef, code []byte, value, gas, price *bi
self.data.timestamp = self.env.Time() self.data.timestamp = self.env.Time()
self.data.code = getDataPtr(code) self.data.code = getDataPtr(code)
self.data.codeSize = uint64(len(code)) self.data.codeSize = uint64(len(code))
self.data.codeHash = hash2llvm(crypto.Sha3(code)) // TODO: Get already computed hash? self.data.codeHash = hash2llvm(crypto.Keccak256(code)) // TODO: Get already computed hash?
jit := C.evmjit_create() jit := C.evmjit_create()
retCode := C.evmjit_run(jit, unsafe.Pointer(&self.data), unsafe.Pointer(self)) retCode := C.evmjit_run(jit, unsafe.Pointer(&self.data), unsafe.Pointer(self))
@ -242,7 +242,7 @@ func (self *JitVm) Env() Environment {
//export env_sha3 //export env_sha3
func env_sha3(dataPtr *byte, length uint64, resultPtr unsafe.Pointer) { func env_sha3(dataPtr *byte, length uint64, resultPtr unsafe.Pointer) {
data := llvm2bytesRef(dataPtr, length) data := llvm2bytesRef(dataPtr, length)
hash := crypto.Sha3(data) hash := crypto.Keccak256(data)
result := (*i256)(resultPtr) result := (*i256)(resultPtr)
*result = hash2llvm(hash) *result = hash2llvm(hash)
} }

View File

@ -43,7 +43,7 @@ import (
"golang.org/x/crypto/ripemd160" "golang.org/x/crypto/ripemd160"
) )
func Sha3(data ...[]byte) []byte { func Keccak256(data ...[]byte) []byte {
d := sha3.NewKeccak256() d := sha3.NewKeccak256()
for _, b := range data { for _, b := range data {
d.Write(b) d.Write(b)
@ -51,7 +51,7 @@ func Sha3(data ...[]byte) []byte {
return d.Sum(nil) return d.Sum(nil)
} }
func Sha3Hash(data ...[]byte) (h common.Hash) { func Keccak256Hash(data ...[]byte) (h common.Hash) {
d := sha3.NewKeccak256() d := sha3.NewKeccak256()
for _, b := range data { for _, b := range data {
d.Write(b) d.Write(b)
@ -63,7 +63,7 @@ func Sha3Hash(data ...[]byte) (h common.Hash) {
// Creates an ethereum address given the bytes and the nonce // Creates an ethereum address given the bytes and the nonce
func CreateAddress(b common.Address, nonce uint64) common.Address { func CreateAddress(b common.Address, nonce uint64) common.Address {
data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
return common.BytesToAddress(Sha3(data)[12:]) return common.BytesToAddress(Keccak256(data)[12:])
//return Sha3(common.NewValue([]interface{}{b, nonce}).Encode())[12:] //return Sha3(common.NewValue([]interface{}{b, nonce}).Encode())[12:]
} }
@ -265,7 +265,7 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error
if err != nil { if err != nil {
return nil, err return nil, err
} }
ethPriv := Sha3(plainText) ethPriv := Keccak256(plainText)
ecKey := ToECDSA(ethPriv) ecKey := ToECDSA(ethPriv)
key = &Key{ key = &Key{
Id: nil, Id: nil,
@ -330,7 +330,7 @@ func PKCS7Unpad(in []byte) []byte {
func PubkeyToAddress(p ecdsa.PublicKey) common.Address { func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
pubBytes := FromECDSAPub(&p) pubBytes := FromECDSAPub(&p)
return common.BytesToAddress(Sha3(pubBytes[1:])[12:]) return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
} }
func zeroBytes(bytes []byte) { func zeroBytes(bytes []byte) {

View File

@ -40,13 +40,13 @@ var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232
func TestSha3(t *testing.T) { func TestSha3(t *testing.T) {
msg := []byte("abc") msg := []byte("abc")
exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45") exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
checkhash(t, "Sha3-256", func(in []byte) []byte { return Sha3(in) }, msg, exp) checkhash(t, "Sha3-256", func(in []byte) []byte { return Keccak256(in) }, msg, exp)
} }
func TestSha3Hash(t *testing.T) { func TestSha3Hash(t *testing.T) {
msg := []byte("abc") msg := []byte("abc")
exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45") exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Sha3Hash(in); return h[:] }, msg, exp) checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
} }
func TestSha256(t *testing.T) { func TestSha256(t *testing.T) {
@ -66,7 +66,7 @@ func BenchmarkSha3(b *testing.B) {
amount := 1000000 amount := 1000000
start := time.Now() start := time.Now()
for i := 0; i < amount; i++ { for i := 0; i < amount; i++ {
Sha3(a) Keccak256(a)
} }
fmt.Println(amount, ":", time.Since(start)) fmt.Println(amount, ":", time.Since(start))
@ -84,7 +84,7 @@ func TestSign(t *testing.T) {
key, _ := HexToECDSA(testPrivHex) key, _ := HexToECDSA(testPrivHex)
addr := common.HexToAddress(testAddrHex) addr := common.HexToAddress(testAddrHex)
msg := Sha3([]byte("foo")) msg := Keccak256([]byte("foo"))
sig, err := Sign(msg, key) sig, err := Sign(msg, key)
if err != nil { if err != nil {
t.Errorf("Sign error: %s", err) t.Errorf("Sign error: %s", err)
@ -238,7 +238,7 @@ func TestPythonIntegration(t *testing.T) {
k0, _ := HexToECDSA(kh) k0, _ := HexToECDSA(kh)
k1 := FromECDSA(k0) k1 := FromECDSA(k0)
msg0 := Sha3([]byte("foo")) msg0 := Keccak256([]byte("foo"))
sig0, _ := secp256k1.Sign(msg0, k1) sig0, _ := secp256k1.Sign(msg0, k1)
msg1 := common.FromHex("00000000000000000000000000000000") msg1 := common.FromHex("00000000000000000000000000000000")

View File

@ -110,7 +110,7 @@ func (ks keyStorePassphrase) StoreKey(key *Key, auth string) (err error) {
return err return err
} }
mac := Sha3(derivedKey[16:32], cipherText) mac := Keccak256(derivedKey[16:32], cipherText)
scryptParamsJSON := make(map[string]interface{}, 5) scryptParamsJSON := make(map[string]interface{}, 5)
scryptParamsJSON["n"] = ks.scryptN scryptParamsJSON["n"] = ks.scryptN
@ -210,7 +210,7 @@ func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byt
return nil, nil, err return nil, nil, err
} }
calculatedMAC := Sha3(derivedKey[16:32], cipherText) calculatedMAC := Keccak256(derivedKey[16:32], cipherText)
if !bytes.Equal(calculatedMAC, mac) { if !bytes.Equal(calculatedMAC, mac) {
return nil, nil, errors.New("Decryption failed: MAC mismatch") return nil, nil, errors.New("Decryption failed: MAC mismatch")
} }
@ -244,12 +244,12 @@ func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byt
return nil, nil, err return nil, nil, err
} }
calculatedMAC := Sha3(derivedKey[16:32], cipherText) calculatedMAC := Keccak256(derivedKey[16:32], cipherText)
if !bytes.Equal(calculatedMAC, mac) { if !bytes.Equal(calculatedMAC, mac) {
return nil, nil, errors.New("Decryption failed: MAC mismatch") return nil, nil, errors.New("Decryption failed: MAC mismatch")
} }
plainText, err := aesCBCDecrypt(Sha3(derivedKey[:16])[:16], cipherText, iv) plainText, err := aesCBCDecrypt(Keccak256(derivedKey[:16])[:16], cipherText, iv)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }

View File

@ -977,7 +977,7 @@ func (q *queue) DeliverNodeData(id string, data [][]byte, callback func(error, i
process := []trie.SyncResult{} process := []trie.SyncResult{}
for _, blob := range data { for _, blob := range data {
// Skip any state trie entires that were not requested // Skip any state trie entires that were not requested
hash := common.BytesToHash(crypto.Sha3(blob)) hash := common.BytesToHash(crypto.Keccak256(blob))
if _, ok := request.Hashes[hash]; !ok { if _, ok := request.Hashes[hash]; !ok {
errs = append(errs, fmt.Errorf("non-requested state data %x", hash)) errs = append(errs, fmt.Errorf("non-requested state data %x", hash))
continue continue

View File

@ -481,7 +481,7 @@ func testGetNodeData(t *testing.T, protocol int) {
} }
// Verify that all hashes correspond to the requested data, and reconstruct a state tree // Verify that all hashes correspond to the requested data, and reconstruct a state tree
for i, want := range hashes { for i, want := range hashes {
if hash := crypto.Sha3Hash(data[i]); hash != want { if hash := crypto.Keccak256Hash(data[i]); hash != want {
fmt.Errorf("data hash mismatch: have %x, want %x", hash, want) fmt.Errorf("data hash mismatch: have %x, want %x", hash, want)
} }
} }

View File

@ -53,7 +53,7 @@ func (req *TrieRequest) StoreResult(db ethdb.Database) {
// storeProof stores the new trie nodes obtained from a merkle proof in the database // storeProof stores the new trie nodes obtained from a merkle proof in the database
func storeProof(db ethdb.Database, proof []rlp.RawValue) { func storeProof(db ethdb.Database, proof []rlp.RawValue) {
for _, buf := range proof { for _, buf := range proof {
hash := crypto.Sha3(buf) hash := crypto.Keccak256(buf)
val, _ := db.Get(hash) val, _ := db.Get(hash)
if val == nil { if val == nil {
db.Put(hash, buf) db.Put(hash, buf)
@ -78,7 +78,7 @@ func (req *NodeDataRequest) StoreResult(db ethdb.Database) {
db.Put(req.hash[:], req.GetData()) db.Put(req.hash[:], req.GetData())
} }
var sha3_nil = crypto.Sha3Hash(nil) var sha3_nil = crypto.Keccak256Hash(nil)
// retrieveNodeData tries to retrieve node data with the given hash from the network // retrieveNodeData tries to retrieve node data with the given hash from the network
func retrieveNodeData(ctx context.Context, odr OdrBackend, hash common.Hash) ([]byte, error) { func retrieveNodeData(ctx context.Context, odr OdrBackend, hash common.Hash) ([]byte, error) {

View File

@ -29,7 +29,7 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
) )
var emptyCodeHash = crypto.Sha3(nil) var emptyCodeHash = crypto.Keccak256(nil)
// Code represents a contract code in binary form // Code represents a contract code in binary form
type Code []byte type Code []byte
@ -220,7 +220,7 @@ func (self *StateObject) Code() []byte {
// SetCode sets the contract code // SetCode sets the contract code
func (self *StateObject) SetCode(code []byte) { func (self *StateObject) SetCode(code []byte) {
self.code = code self.code = code
self.codeHash = crypto.Sha3(code) self.codeHash = crypto.Keccak256(code)
self.dirty = true self.dirty = true
} }

View File

@ -269,5 +269,5 @@ func (s *PublicWeb3API) ClientVersion() string {
// Sha3 applies the ethereum sha3 implementation on the input. // Sha3 applies the ethereum sha3 implementation on the input.
// It assumes the input is hex encoded. // It assumes the input is hex encoded.
func (s *PublicWeb3API) Sha3(input string) string { func (s *PublicWeb3API) Sha3(input string) string {
return common.ToHex(crypto.Sha3(common.FromHex(input))) return common.ToHex(crypto.Keccak256(common.FromHex(input)))
} }

View File

@ -188,7 +188,7 @@ func (db *nodeDB) node(id NodeID) *Node {
glog.V(logger.Warn).Infof("failed to decode node RLP: %v", err) glog.V(logger.Warn).Infof("failed to decode node RLP: %v", err)
return nil return nil
} }
node.sha = crypto.Sha3Hash(node.ID[:]) node.sha = crypto.Keccak256Hash(node.ID[:])
return node return node
} }

View File

@ -67,7 +67,7 @@ func NewNode(id NodeID, ip net.IP, udpPort, tcpPort uint16) *Node {
UDP: udpPort, UDP: udpPort,
TCP: tcpPort, TCP: tcpPort,
ID: id, ID: id,
sha: crypto.Sha3Hash(id[:]), sha: crypto.Keccak256Hash(id[:]),
} }
} }

View File

@ -195,7 +195,7 @@ func (tab *Table) SetFallbackNodes(nodes []*Node) error {
cpy := *n cpy := *n
// Recompute cpy.sha because the node might not have been // Recompute cpy.sha because the node might not have been
// created by NewNode or ParseNode. // created by NewNode or ParseNode.
cpy.sha = crypto.Sha3Hash(n.ID[:]) cpy.sha = crypto.Keccak256Hash(n.ID[:])
tab.nursery = append(tab.nursery, &cpy) tab.nursery = append(tab.nursery, &cpy)
} }
tab.mutex.Unlock() tab.mutex.Unlock()
@ -208,7 +208,7 @@ func (tab *Table) SetFallbackNodes(nodes []*Node) error {
func (tab *Table) Resolve(targetID NodeID) *Node { func (tab *Table) Resolve(targetID NodeID) *Node {
// If the node is present in the local table, no // If the node is present in the local table, no
// network interaction is required. // network interaction is required.
hash := crypto.Sha3Hash(targetID[:]) hash := crypto.Keccak256Hash(targetID[:])
tab.mutex.Lock() tab.mutex.Lock()
cl := tab.closest(hash, 1) cl := tab.closest(hash, 1)
tab.mutex.Unlock() tab.mutex.Unlock()
@ -236,7 +236,7 @@ func (tab *Table) Lookup(targetID NodeID) []*Node {
func (tab *Table) lookup(targetID NodeID, refreshIfEmpty bool) []*Node { func (tab *Table) lookup(targetID NodeID, refreshIfEmpty bool) []*Node {
var ( var (
target = crypto.Sha3Hash(targetID[:]) target = crypto.Keccak256Hash(targetID[:])
asked = make(map[NodeID]bool) asked = make(map[NodeID]bool)
seen = make(map[NodeID]bool) seen = make(map[NodeID]bool)
reply = make(chan []*Node, alpha) reply = make(chan []*Node, alpha)

View File

@ -530,12 +530,12 @@ func (*preminedTestnet) ping(toid NodeID, toaddr *net.UDPAddr) error { return ni
// various distances to the given target. // various distances to the given target.
func (n *preminedTestnet) mine(target NodeID) { func (n *preminedTestnet) mine(target NodeID) {
n.target = target n.target = target
n.targetSha = crypto.Sha3Hash(n.target[:]) n.targetSha = crypto.Keccak256Hash(n.target[:])
found := 0 found := 0
for found < bucketSize*10 { for found < bucketSize*10 {
k := newkey() k := newkey()
id := PubkeyID(&k.PublicKey) id := PubkeyID(&k.PublicKey)
sha := crypto.Sha3Hash(id[:]) sha := crypto.Keccak256Hash(id[:])
ld := logdist(n.targetSha, sha) ld := logdist(n.targetSha, sha)
if len(n.dists[ld]) < bucketSize { if len(n.dists[ld]) < bucketSize {
n.dists[ld] = append(n.dists[ld], id) n.dists[ld] = append(n.dists[ld], id)

View File

@ -448,7 +448,7 @@ func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) ([]byte,
return nil, err return nil, err
} }
packet := b.Bytes() packet := b.Bytes()
sig, err := crypto.Sign(crypto.Sha3(packet[headSize:]), priv) sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
if err != nil { if err != nil {
glog.V(logger.Error).Infoln("could not sign packet:", err) glog.V(logger.Error).Infoln("could not sign packet:", err)
return nil, err return nil, err
@ -457,7 +457,7 @@ func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) ([]byte,
// add the hash to the front. Note: this doesn't protect the // add the hash to the front. Note: this doesn't protect the
// packet in any way. Our public key will be part of this hash in // packet in any way. Our public key will be part of this hash in
// The future. // The future.
copy(packet, crypto.Sha3(packet[macSize:])) copy(packet, crypto.Keccak256(packet[macSize:]))
return packet, nil return packet, nil
} }
@ -509,11 +509,11 @@ func decodePacket(buf []byte) (packet, NodeID, []byte, error) {
return nil, NodeID{}, nil, errPacketTooSmall return nil, NodeID{}, nil, errPacketTooSmall
} }
hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:] hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
shouldhash := crypto.Sha3(buf[macSize:]) shouldhash := crypto.Keccak256(buf[macSize:])
if !bytes.Equal(hash, shouldhash) { if !bytes.Equal(hash, shouldhash) {
return nil, NodeID{}, nil, errBadHash return nil, NodeID{}, nil, errBadHash
} }
fromID, err := recoverNodeID(crypto.Sha3(buf[headSize:]), sig) fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig)
if err != nil { if err != nil {
return nil, NodeID{}, hash, err return nil, NodeID{}, hash, err
} }
@ -575,7 +575,7 @@ func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte
// (which is a much bigger packet than findnode) to the victim. // (which is a much bigger packet than findnode) to the victim.
return errUnknownNode return errUnknownNode
} }
target := crypto.Sha3Hash(req.Target[:]) target := crypto.Keccak256Hash(req.Target[:])
t.mutex.Lock() t.mutex.Lock()
closest := t.closest(target, bucketSize).entries closest := t.closest(target, bucketSize).entries
t.mutex.Unlock() t.mutex.Unlock()

View File

@ -286,7 +286,7 @@ func TestUDP_findnode(t *testing.T) {
// put a few nodes into the table. their exact // put a few nodes into the table. their exact
// distribution shouldn't matter much, altough we need to // distribution shouldn't matter much, altough we need to
// take care not to overflow any bucket. // take care not to overflow any bucket.
targetHash := crypto.Sha3Hash(testTarget[:]) targetHash := crypto.Keccak256Hash(testTarget[:])
nodes := &nodesByDistance{target: targetHash} nodes := &nodesByDistance{target: targetHash}
for i := 0; i < bucketSize; i++ { for i := 0; i < bucketSize; i++ {
nodes.push(nodeAtDistance(test.table.self.sha, i+2), bucketSize) nodes.push(nodeAtDistance(test.table.self.sha, i+2), bucketSize)

View File

@ -232,12 +232,12 @@ func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
} }
// derive base secrets from ephemeral key agreement // derive base secrets from ephemeral key agreement
sharedSecret := crypto.Sha3(ecdheSecret, crypto.Sha3(h.respNonce, h.initNonce)) sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
aesSecret := crypto.Sha3(ecdheSecret, sharedSecret) aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
s := secrets{ s := secrets{
RemoteID: h.remoteID, RemoteID: h.remoteID,
AES: aesSecret, AES: aesSecret,
MAC: crypto.Sha3(ecdheSecret, aesSecret), MAC: crypto.Keccak256(ecdheSecret, aesSecret),
} }
// setup sha3 instances for the MACs // setup sha3 instances for the MACs
@ -426,7 +426,7 @@ func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) { func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) {
buf := make([]byte, authMsgLen) buf := make([]byte, authMsgLen)
n := copy(buf, msg.Signature[:]) n := copy(buf, msg.Signature[:])
n += copy(buf[n:], crypto.Sha3(exportPubkey(&h.randomPrivKey.PublicKey))) n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey)))
n += copy(buf[n:], msg.InitiatorPubkey[:]) n += copy(buf[n:], msg.InitiatorPubkey[:])
n += copy(buf[n:], msg.Nonce[:]) n += copy(buf[n:], msg.Nonce[:])
buf[n] = 0 // token-flag buf[n] = 0 // token-flag

View File

@ -267,8 +267,8 @@ func TestRLPXFrameFake(t *testing.T) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
hash := fakeHash([]byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}) hash := fakeHash([]byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})
rw := newRLPXFrameRW(buf, secrets{ rw := newRLPXFrameRW(buf, secrets{
AES: crypto.Sha3(), AES: crypto.Keccak256(),
MAC: crypto.Sha3(), MAC: crypto.Keccak256(),
IngressMAC: hash, IngressMAC: hash,
EgressMAC: hash, EgressMAC: hash,
}) })

View File

@ -183,7 +183,7 @@ func (self *Env) Db() vm.Database { return self.state }
func (self *Env) GasLimit() *big.Int { return self.gasLimit } func (self *Env) GasLimit() *big.Int { return self.gasLimit }
func (self *Env) VmType() vm.Type { return vm.StdVmTy } func (self *Env) VmType() vm.Type { return vm.StdVmTy }
func (self *Env) GetHash(n uint64) common.Hash { func (self *Env) GetHash(n uint64) common.Hash {
return common.BytesToHash(crypto.Sha3([]byte(big.NewInt(int64(n)).String()))) return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String())))
} }
func (self *Env) AddLog(log *vm.Log) { func (self *Env) AddLog(log *vm.Log) {
self.state.AddLog(log) self.state.AddLog(log)

View File

@ -63,7 +63,7 @@ func TestSecureGetKey(t *testing.T) {
key := []byte("foo") key := []byte("foo")
value := []byte("bar") value := []byte("bar")
seckey := crypto.Sha3(key) seckey := crypto.Keccak256(key)
if !bytes.Equal(trie.Get(key), value) { if !bytes.Equal(trie.Get(key), value) {
t.Errorf("Get did not return bar") t.Errorf("Get did not return bar")

View File

@ -40,7 +40,7 @@ var (
emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
// This is the known hash of an empty state trie entry. // This is the known hash of an empty state trie entry.
emptyState = crypto.Sha3Hash(nil) emptyState = crypto.Keccak256Hash(nil)
) )
// ClearGlobalCache clears the global trie cache // ClearGlobalCache clears the global trie cache

View File

@ -66,7 +66,7 @@ func (self *Envelope) Seal(pow time.Duration) {
for i := 0; i < 1024; i++ { for i := 0; i < 1024; i++ {
binary.BigEndian.PutUint32(d[60:], nonce) binary.BigEndian.PutUint32(d[60:], nonce)
firstBit := common.FirstBitSet(common.BigD(crypto.Sha3(d))) firstBit := common.FirstBitSet(common.BigD(crypto.Keccak256(d)))
if firstBit > bestBit { if firstBit > bestBit {
self.Nonce, bestBit = nonce, firstBit self.Nonce, bestBit = nonce, firstBit
} }
@ -123,7 +123,7 @@ func (self *Envelope) Open(key *ecdsa.PrivateKey) (msg *Message, err error) {
func (self *Envelope) Hash() common.Hash { func (self *Envelope) Hash() common.Hash {
if (self.hash == common.Hash{}) { if (self.hash == common.Hash{}) {
enc, _ := rlp.EncodeToBytes(self) enc, _ := rlp.EncodeToBytes(self)
self.hash = crypto.Sha3Hash(enc) self.hash = crypto.Keccak256Hash(enc)
} }
return self.hash return self.hash
} }
@ -142,6 +142,6 @@ func (self *Envelope) DecodeRLP(s *rlp.Stream) error {
if err := rlp.DecodeBytes(raw, (*rlpenv)(self)); err != nil { if err := rlp.DecodeBytes(raw, (*rlpenv)(self)); err != nil {
return err return err
} }
self.hash = crypto.Sha3Hash(raw) self.hash = crypto.Keccak256Hash(raw)
return nil return nil
} }

View File

@ -146,7 +146,7 @@ func (self *Message) decrypt(key *ecdsa.PrivateKey) error {
// hash calculates the SHA3 checksum of the message flags and payload. // hash calculates the SHA3 checksum of the message flags and payload.
func (self *Message) hash() []byte { func (self *Message) hash() []byte {
return crypto.Sha3(append([]byte{self.Flags}, self.Payload...)) return crypto.Keccak256(append([]byte{self.Flags}, self.Payload...))
} }
// bytes flattens the message contents (flags, signature and payload) into a // bytes flattens the message contents (flags, signature and payload) into a

View File

@ -31,7 +31,7 @@ type Topic [4]byte
// Note, empty topics are considered the wildcard, and cannot be used in messages. // Note, empty topics are considered the wildcard, and cannot be used in messages.
func NewTopic(data []byte) Topic { func NewTopic(data []byte) Topic {
prefix := [4]byte{} prefix := [4]byte{}
copy(prefix[:], crypto.Sha3(data)[:4]) copy(prefix[:], crypto.Keccak256(data)[:4])
return Topic(prefix) return Topic(prefix)
} }