internal/ethapi: make NewAccount return EIP-55 format (#26973)

This commit is contained in:
Daniel Liu 2024-12-18 19:02:48 +08:00
parent 12111d30ea
commit 59b14ed2cb
3 changed files with 45 additions and 3 deletions

View file

@ -19,6 +19,7 @@ package common
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"math/rand"
@ -405,3 +406,16 @@ func ExtractAddressFromBytes(bytePenalties []byte) []Address {
}
return penalties
}
// AddressEIP55 is an alias of Address with a customized json marshaller
type AddressEIP55 Address
// String returns the hex representation of the address in the manner of EIP55.
func (addr AddressEIP55) String() string {
return Address(addr).Hex()
}
// MarshalJSON marshals the address in the manner of EIP55.
func (addr AddressEIP55) MarshalJSON() ([]byte, error) {
return json.Marshal(addr.String())
}

View file

@ -371,6 +371,30 @@ func TestStringToBinaryAddress(t *testing.T) {
}
}
func TestAddressEIP55(t *testing.T) {
addr := HexToAddress("0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed")
addrEIP55 := AddressEIP55(addr)
if addr.Hex() != addrEIP55.String() {
t.Fatal("AddressEIP55 should match original address hex")
}
blob, err := addrEIP55.MarshalJSON()
if err != nil {
t.Fatal("Failed to marshal AddressEIP55", err)
}
if strings.Trim(string(blob), "\"") != addr.Hex() {
t.Fatal("Address with checksum is expected")
}
var dec Address
if err := json.Unmarshal(blob, &dec); err != nil {
t.Fatal("Failed to unmarshal AddressEIP55", err)
}
if addr != dec {
t.Fatal("Unexpected address after unmarshal")
}
}
func BenchmarkPrettyDuration(b *testing.B) {
var x = PrettyDuration(time.Duration(int64(1203123912312)))
b.Logf("Pre %s", time.Duration(x).String())

View file

@ -383,12 +383,16 @@ func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (a
}
// NewAccount will create a new account and returns the address for the new account.
func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
func (s *PrivateAccountAPI) NewAccount(password string) (common.AddressEIP55, error) {
acc, err := fetchKeystore(s.am).NewAccount(password)
if err == nil {
return acc.Address, nil
addrEIP55 := common.AddressEIP55(acc.Address)
log.Info("Your new key was generated", "address", addrEIP55.String())
log.Warn("Please backup your key file!", "path", acc.URL.Path)
log.Warn("Please remember your password!")
return addrEIP55, nil
}
return common.Address{}, err
return common.AddressEIP55{}, err
}
// fetchKeystore retrives the encrypted keystore from the account manager.