crypto/crypto, cmd/geth: added ChecksumAddress

This commit is contained in:
8go 2016-03-10 22:08:36 +01:00 committed by 8go
parent 597105d4dd
commit eb250e9684
2 changed files with 13 additions and 19 deletions

View file

@ -350,13 +350,12 @@ func zeroBytes(bytes []byte) {
}
}
// for input read: https://github.com/ethereum/EIPs/issues/55
// modelled after the JavaScript function toChecksumAddress()
// Convert address into checksummed address
// ChecksumAddress converts an address into a checksummed address.
// It returns a 42-letter string starting with "0x".
// The checksum algorithm is discussed in https://github.com/ethereum/EIPs/issues/55
func ChecksumAddress(a common.Address) string {
address := strings.Replace(strings.ToLower(hex.EncodeToString(a.Bytes())), "0x", "", 1)
addressHash := hex.EncodeToString(Sha3([]byte(common.Bytes2Hex(a.Bytes()))))
address := hex.EncodeToString(a[:]) // hex.EncodeToString is always lower case without 0x prefix
addressHash := hex.EncodeToString(Sha3([]byte(common.Bytes2Hex(a[:]))))
checksumAddress := "0x"
for i := 0; i < len(address); i++ {
// If ith character is 8 to f then make it uppercase
@ -370,8 +369,9 @@ func ChecksumAddress(a common.Address) string {
return checksumAddress
}
// Convert address in Hex format, with or without prefixed 0x into checksummed address
// ChecksumAddressHex converts an address into a checksummed address.
// The input s may or may not be prefixed with "0x".
// The returned string is 42 long and always includes the prefix "0x".
func ChecksumAddressHex(s string) string {
return ChecksumAddress(common.HexToAddress(strings.Replace(strings.ToLower(s), "0x", "", 1)))
return ChecksumAddress(common.HexToAddress(s))
}

View file

@ -26,7 +26,6 @@ import (
"os"
"testing"
"time"
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto/secp256k1"
@ -249,13 +248,10 @@ func TestPythonIntegration(t *testing.T) {
fmt.Printf("msg: %x, privkey: %x sig: %x\n", msg1, k1, sig1)
}
// TestChecksumAddress performs 4 groups of tests: a) all caps,
// b) all lower, c) mixed lower and upper case, and
// d) examples taken from myetherwallet.com
func TestChecksumAddress(t *testing.T) {
// 4 groups of tests:
// All caps
// All lower
// Normal = mixed
// Taken from myetherwallet.com
testcases := []string{
"0x52908400098527886E0F7030069857D2E4169EE7",
"0x8617E340B3D01FA5F11F306F4090FD50E238070D",
@ -289,8 +285,7 @@ func TestChecksumAddress(t *testing.T) {
failed, passed := 0, 0
for i := 0; i < len(testcases); i++ {
ba, _ := hex.DecodeString(strings.Replace(testcases[i], "0x", "", 1))
ca := ChecksumAddress(common.BytesToAddress(ba))
ca := ChecksumAddress(common.HexToAddress(testcases[i]))
if testcases[i] == ca {
passed++
} else {
@ -386,4 +381,3 @@ func TestChecksumAddressHex(t *testing.T) {
}
fmt.Printf("Passed %d tests and failed %d tests out of %d.\n", passed, failed, passed+failed)
}