forked from ava-labs/coreth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatting.go
62 lines (53 loc) · 2.06 KB
/
formatting.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package evm
import (
"fmt"
"github.com/haowang0402/avalanchego/ids"
"github.com/haowang0402/avalanchego/utils/constants"
"github.com/haowang0402/avalanchego/utils/crypto"
"github.com/haowang0402/avalanchego/utils/formatting"
"github.com/ethereum/go-ethereum/common"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
)
// ParseLocalAddress takes in an address for this chain and produces the ID
func (vm *VM) ParseLocalAddress(addrStr string) (ids.ShortID, error) {
chainID, addr, err := vm.ParseAddress(addrStr)
if err != nil {
return ids.ShortID{}, err
}
if chainID != vm.ctx.ChainID {
return ids.ShortID{}, fmt.Errorf("expected chainID to be %q but was %q",
vm.ctx.ChainID, chainID)
}
return addr, nil
}
// FormatLocalAddress takes in a raw address and produces the formatted address
func (vm *VM) FormatLocalAddress(addr ids.ShortID) (string, error) {
return vm.FormatAddress(vm.ctx.ChainID, addr)
}
// FormatAddress takes in a chainID and a raw address and produces the formatted
// address
func (vm *VM) FormatAddress(chainID ids.ID, addr ids.ShortID) (string, error) {
chainIDAlias, err := vm.ctx.BCLookup.PrimaryAlias(chainID)
if err != nil {
return "", err
}
hrp := constants.GetHRP(vm.ctx.NetworkID)
return formatting.FormatAddress(chainIDAlias, hrp, addr.Bytes())
}
// ParseEthAddress parses [addrStr] and returns an Ethereum address
func ParseEthAddress(addrStr string) (common.Address, error) {
if !common.IsHexAddress(addrStr) {
return common.Address{}, errInvalidAddr
}
return common.HexToAddress(addrStr), nil
}
// GetEthAddress returns the ethereum address derived from [privKey]
func GetEthAddress(privKey *crypto.PrivateKeySECP256K1R) common.Address {
return PublicKeyToEthAddress(privKey.PublicKey().(*crypto.PublicKeySECP256K1R))
}
// PublicKeyToEthAddress returns the ethereum address derived from [pubKey]
func PublicKeyToEthAddress(pubKey *crypto.PublicKeySECP256K1R) common.Address {
return ethcrypto.PubkeyToAddress(*(pubKey.ToECDSA()))
}