Merge pull request #992 from harmony-ek/use_bech32

Use bech32
pull/994/head
Eugene Kim 6 years ago committed by GitHub
commit f90cb162a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      accounts/keystore/account_cache.go
  2. 3
      api/client/service/server.go
  3. 14
      api/client/service/server_test.go
  4. 6
      api/service/explorer/service.go
  5. 4
      api/service/explorer/structs.go
  6. 2
      api/service/explorer/structs_test.go
  7. 6
      api/service/staking/service.go
  8. 31
      cmd/client/wallet/main.go
  9. 7
      cmd/harmony/main.go
  10. 4
      cmd/keygen/main.go
  11. 3
      consensus/consensus.go
  12. 7
      consensus/consensus_service.go
  13. 3
      consensus/consensus_service_test.go
  14. 8
      core/resharding.go
  15. 5
      core/state/statedb_test.go
  16. 3
      core/types/shard_state.go
  17. 6
      core/vm/contracts_test.go
  18. 5
      drand/drand.go
  19. 4
      drand/drand_test.go
  20. 6
      internal/bech32/bech32.go
  21. 83
      internal/common/address.go
  22. 3
      internal/hmyapi/util.go
  23. 6
      node/contract.go
  24. 3
      node/node_genesis.go
  25. 5
      test/txgen/main.go

@ -30,7 +30,9 @@ import (
mapset "github.com/deckarep/golang-set"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"github.com/harmony-one/harmony/accounts"
common2 "github.com/harmony-one/harmony/internal/common"
)
// Minimum amount of time between cache reloads. This limit applies if the platform does
@ -258,7 +260,7 @@ func (ac *accountCache) scanAccounts() error {
// Parse the address.
key.Address = ""
err = json.NewDecoder(buf).Decode(&key)
addr := common.HexToAddress(key.Address)
addr := common2.ParseAddr(key.Address)
switch {
case err != nil:
log.Debug("Failed to decode keystore key", "path", path, "err", err)

@ -8,6 +8,7 @@ import (
"github.com/ethereum/go-ethereum/common"
proto "github.com/harmony-one/harmony/api/client/service/proto"
"github.com/harmony-one/harmony/core/state"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
@ -50,7 +51,7 @@ func (s *Server) GetStakingContractInfo(ctx context.Context, request *proto.Stak
return nil, err
}
return &proto.StakingContractInfoResponse{
ContractAddress: s.getDeployedStakingContractAddress().Hex(),
ContractAddress: common2.MustAddressToBech32(s.getDeployedStakingContractAddress()),
Balance: state.GetBalance(address).Bytes(),
Nonce: state.GetNonce(address),
}, nil

@ -11,6 +11,7 @@ import (
client "github.com/harmony-one/harmony/api/client/service/proto"
proto "github.com/harmony-one/harmony/api/client/service/proto"
"github.com/harmony-one/harmony/core/state"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params"
@ -113,20 +114,21 @@ func TestGetStakingContractInfo(test *testing.T) {
})
response, err := server.GetStakingContractInfo(nil, &proto.StakingContractInfoRequest{Address: testBankAddress.Bytes()})
if err != nil {
test.Fatal("GetStakingContractInfo failed:", err)
}
if bytes.Compare(response.Balance, testBankFunds.Bytes()) != 0 {
test.Errorf("Wrong balance is returned")
}
if strings.Compare(response.ContractAddress, deployedStakingContractAddress.String()) != 0 {
test.Errorf("Wrong ContractAddress is returned")
if strings.Compare(response.ContractAddress, common2.MustAddressToBech32(deployedStakingContractAddress)) != 0 {
test.Errorf("Wrong ContractAddress is returned (expected %#v, got %#v)",
common2.MustAddressToBech32(deployedStakingContractAddress),
response.ContractAddress)
}
if response.Nonce != 0 {
test.Errorf("Wrong nonce is returned")
}
if err != nil {
test.Errorf("Failed to get free token")
}
}

@ -14,12 +14,14 @@ import (
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc"
"github.com/gorilla/mux"
libp2p_peer "github.com/libp2p/go-libp2p-peer"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/p2p"
libp2p_peer "github.com/libp2p/go-libp2p-peer"
)
// Constants for explorer service.
@ -291,7 +293,7 @@ func (s *Service) GetExplorerAddress(w http.ResponseWriter, r *http.Request) {
// Check the balance from blockchain rather than local DB dump
if s.GetAccountBalance != nil {
address := common.HexToAddress(id)
address := common2.ParseAddr(id)
balance, err := s.GetAccountBalance(address)
if err == nil {
data.Address.Balance = balance

@ -94,8 +94,8 @@ func GetTransaction(tx *types.Transaction, accountBlock *types.Block) *Transacti
return &Transaction{
ID: tx.Hash().Hex(),
Timestamp: strconv.Itoa(int(accountBlock.Time().Int64() * 1000)),
From: msg.From().Hex(),
To: msg.To().Hex(),
From: msg.From().Hex(), // TODO ek – use bech32
To: msg.To().Hex(), // TODO ek – use bech32
Value: msg.Value(),
Bytes: strconv.Itoa(int(tx.Size())),
Data: hex.EncodeToString(tx.Data()),

@ -22,6 +22,6 @@ func TestGetTransaction(t *testing.T) {
tx := GetTransaction(tx1, block)
assert.Equal(t, tx.ID, tx1.Hash().Hex(), "should be equal tx1.Hash()")
assert.Equal(t, tx.To, tx1.To().Hex(), "should be equal tx1.To()")
assert.Equal(t, tx.To, tx1.To().Hex(), "should be equal tx1.To()") // TODO ek – use bech32
assert.Equal(t, tx.Bytes, strconv.Itoa(int(tx1.Size())), "should be equal tx1.Size()")
}

@ -13,6 +13,7 @@ import (
"github.com/ethereum/go-ethereum/rpc"
protobuf "github.com/golang/protobuf/proto"
"github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/accounts"
"github.com/harmony-one/harmony/accounts/abi"
proto "github.com/harmony-one/harmony/api/client/service/proto"
@ -23,6 +24,7 @@ import (
"github.com/harmony-one/harmony/contracts"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/genesis"
hmykey "github.com/harmony-one/harmony/internal/keystore"
@ -157,7 +159,7 @@ func (s *Service) getFakeStakingInfo() *proto.StakingContractInfoResponse {
stakingContractAddress := crypto.CreateAddress(contractAddress, uint64(nonce))
return &proto.StakingContractInfoResponse{
ContractAddress: stakingContractAddress.Hex(),
ContractAddress: common2.MustAddressToBech32(stakingContractAddress),
Balance: balance.Bytes(),
Nonce: nonce,
}
@ -187,7 +189,7 @@ func constructStakingMessage(ts types.Transactions) []byte {
func (s *Service) createRawStakingMessage() []byte {
// TODO(minhdoan): Enable getStakingInfo back after testing.
stakingInfo := s.getFakeStakingInfo()
toAddress := common.HexToAddress(stakingInfo.ContractAddress)
toAddress := common2.ParseAddr(stakingInfo.ContractAddress)
abi, err := abi.JSON(strings.NewReader(contracts.StakeLockContractABI))
if err != nil {

@ -12,15 +12,17 @@ import (
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"github.com/harmony-one/harmony/accounts"
"github.com/harmony-one/harmony/accounts/keystore"
"github.com/harmony-one/harmony/api/client"
clientService "github.com/harmony-one/harmony/api/client/service"
proto_node "github.com/harmony-one/harmony/api/proto/node"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/shardchain"
@ -29,9 +31,6 @@ import (
"github.com/harmony-one/harmony/p2p"
p2p_host "github.com/harmony-one/harmony/p2p/host"
"github.com/harmony-one/harmony/p2p/p2pimpl"
"github.com/harmony-one/harmony/accounts"
"github.com/harmony-one/harmony/accounts/keystore"
)
var (
@ -273,19 +272,19 @@ func processNewCommnad() {
if err != nil {
fmt.Printf("new account error: %v\n", err)
}
fmt.Printf("account: %s\n", account.Address.Hex())
fmt.Printf("account: %s\n", common2.MustAddressToBech32(account.Address))
fmt.Printf("URL: %s\n", account.URL)
}
func _exportAccount(account accounts.Account) {
fmt.Printf("account: %s\n", account.Address.Hex())
fmt.Printf("account: %s\n", common2.MustAddressToBech32(account.Address))
fmt.Printf("URL: %s\n", account.URL)
pass := utils.AskForPassphrase("Original Passphrase: ")
newpass := utils.AskForPassphrase("Export Passphrase: ")
data, err := ks.Export(account, pass, newpass)
if err == nil {
filename := fmt.Sprintf(".hmy/%s.key", account.Address.Hex())
filename := fmt.Sprintf(".hmy/%s.key", common2.MustAddressToBech32(account.Address))
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic("Failed to open keystore")
@ -317,7 +316,7 @@ func processListCommand() {
allAccounts := ks.Accounts()
for _, account := range allAccounts {
fmt.Printf("account: %s\n", account.Address.Hex())
fmt.Printf("account: %s\n", common2.MustAddressToBech32(account.Address))
fmt.Printf("URL: %s\n", account.URL)
}
}
@ -331,7 +330,7 @@ func processExportCommand() {
allAccounts := ks.Accounts()
for _, account := range allAccounts {
if acc == "" || acc == account.Address.Hex() {
if acc == "" || acc == common2.MustAddressToBech32(account.Address) {
_exportAccount(account)
}
}
@ -361,7 +360,7 @@ func processImportCommnad() {
if err != nil {
panic("Failed to import the private key")
}
fmt.Printf("Private key imported for account: %s\n", account.Address.Hex())
fmt.Printf("Private key imported for account: %s\n", common2.MustAddressToBech32(account.Address))
}
func processBalancesCommand() {
@ -374,14 +373,14 @@ func processBalancesCommand() {
allAccounts := ks.Accounts()
for i, account := range allAccounts {
fmt.Printf("Account %d:\n", i)
fmt.Printf(" Address: %s\n", account.Address.Hex())
fmt.Printf(" Address: %s\n", common2.MustAddressToBech32(account.Address))
for shardID, balanceNonce := range FetchBalance(account.Address) {
fmt.Printf(" Balance in Shard %d: %s, nonce: %v \n", shardID, convertBalanceIntoReadableFormat(balanceNonce.balance), balanceNonce.nonce)
}
}
} else {
address := common.HexToAddress(*balanceAddressPtr)
fmt.Printf("Account: %s:\n", address.Hex())
address := common2.ParseAddr(*balanceAddressPtr)
fmt.Printf("Account: %s:\n", common2.MustAddressToBech32(address))
for shardID, balanceNonce := range FetchBalance(address) {
fmt.Printf(" Balance in Shard %d: %s, nonce: %v \n", shardID, convertBalanceIntoReadableFormat(balanceNonce.balance), balanceNonce.nonce)
}
@ -397,7 +396,7 @@ func processGetFreeToken() {
if *freeTokenAddressPtr == "" {
fmt.Println("Error: --address is required")
} else {
address := common.HexToAddress(*freeTokenAddressPtr)
address := common2.ParseAddr(*freeTokenAddressPtr)
GetFreeToken(address)
}
}
@ -430,13 +429,13 @@ func processTransferCommand() {
return
}
receiverAddress := common.HexToAddress(receiver)
receiverAddress := common2.ParseAddr(receiver)
if len(receiverAddress) != 20 {
fmt.Println("The receiver address is not valid.")
return
}
senderAddress := common.HexToAddress(sender)
senderAddress := common2.ParseAddr(sender)
if len(senderAddress) != 20 {
fmt.Println("The sender address is not valid.")
return

@ -18,6 +18,7 @@ import (
"github.com/harmony-one/harmony/consensus"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/drand"
"github.com/harmony-one/harmony/internal/common"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/genesis"
@ -173,7 +174,7 @@ func initSetup() {
foundAccount := false
for _, account := range allAccounts {
if genesisAccount.Address == account.Address.Hex() {
if common.ParseAddr(genesisAccount.Address) == account.Address {
myAccount = account
foundAccount = true
break
@ -187,7 +188,7 @@ func initSetup() {
genesisAccount.ShardID = uint32(accountIndex % core.GenesisShardNum)
fmt.Printf("My Account: %s\n", myAccount.Address.Hex())
fmt.Printf("My Account: %s\n", common.MustAddressToBech32(myAccount.Address))
fmt.Printf("Key URL: %s\n", myAccount.URL)
fmt.Printf("My Genesis Account: %v\n", *genesisAccount)
@ -313,7 +314,7 @@ func setUpConsensusAndNode(nodeConfig *nodeconfig.ConfigType) *node.Node {
currentNode.NodeConfig.SetRole(nodeconfig.NewNode)
currentNode.StakingAccount = myAccount
utils.GetLogInstance().Info("node account set",
"address", currentNode.StakingAccount.Address.Hex())
"address", common.MustAddressToBech32(currentNode.StakingAccount.Address))
if gsif, err := consensus.NewGenesisStakeInfoFinder(); err == nil {
currentConsensus.SetStakeInfoFinder(gsif)

@ -9,6 +9,8 @@ import (
"strconv"
crypto2 "github.com/ethereum/go-ethereum/crypto"
"github.com/harmony-one/harmony/internal/common"
)
var (
@ -38,7 +40,7 @@ func main() {
}
crypto2.FromECDSA(priKey)
fmt.Printf("{Address: \"%s\", Private: \"%s\", Public: \"%s\"},\n", crypto2.PubkeyToAddress(priKey.PublicKey).Hex(), hex.EncodeToString(crypto2.FromECDSA(priKey)), crypto2.PubkeyToAddress(priKey.PublicKey).Hex())
fmt.Printf("{Address: \"%s\", Private: \"%s\", Public: \"%s\"},"+"\n", common.MustAddressToBech32(crypto2.PubkeyToAddress(priKey.PublicKey)), hex.EncodeToString(crypto2.FromECDSA(priKey)), common.MustAddressToBech32(crypto2.PubkeyToAddress(priKey.PublicKey)))
}
} else {
fmt.Println("Unable to parse # as the argument.")

@ -15,6 +15,7 @@ import (
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
bls_cosi "github.com/harmony-one/harmony/crypto/bls"
common2 "github.com/harmony-one/harmony/internal/common"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/genesis"
@ -217,7 +218,7 @@ func New(host p2p.Host, ShardID uint32, leader p2p.Peer, blsPriKey *bls.SecretKe
consensus.commitSigs = map[common.Address]*bls.Sign{}
consensus.CommitteeAddresses = make(map[common.Address]bool)
consensus.validators.Store(utils.GetBlsAddress(leader.ConsensusPubKey).Hex(), leader)
consensus.validators.Store(common2.MustAddressToBech32(utils.GetBlsAddress(leader.ConsensusPubKey)), leader)
// For now use socket address as ID
// TODO: populate Id derived from address

@ -8,6 +8,7 @@ import (
"time"
"github.com/harmony-one/harmony/crypto/hash"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
@ -380,7 +381,7 @@ func (consensus *Consensus) AddPeers(peers []*p2p.Peer) int {
count := 0
for _, peer := range peers {
_, ok := consensus.validators.LoadOrStore(utils.GetBlsAddress(peer.ConsensusPubKey).Hex(), *peer)
_, ok := consensus.validators.LoadOrStore(common2.MustAddressToBech32(utils.GetBlsAddress(peer.ConsensusPubKey)), *peer)
if !ok {
consensus.pubKeyLock.Lock()
if _, ok := consensus.CommitteeAddresses[peer.ConsensusPubKey.GetAddress()]; !ok {
@ -510,7 +511,7 @@ func (consensus *Consensus) verifySenderKey(msg *msg_pb.Message) (*bls.PublicKey
senderAddr := common.BytesToAddress(addrBytes[:])
if !consensus.IsValidatorInCommittee(senderAddr) {
return nil, fmt.Errorf("Validator address %s is not in committee", senderAddr.Hex())
return nil, fmt.Errorf("Validator address %s is not in committee", common2.MustAddressToBech32(senderAddr))
}
return senderKey, nil
}
@ -525,7 +526,7 @@ func (consensus *Consensus) verifyViewChangeSenderKey(msg *msg_pb.Message) (*bls
senderAddr := common.BytesToAddress(addrBytes[:])
if !consensus.IsValidatorInCommittee(senderAddr) {
return nil, common.Address{}, fmt.Errorf("Validator address %s is not in committee", senderAddr.Hex())
return nil, common.Address{}, fmt.Errorf("Validator address %s is not in committee", common2.MustAddressToBech32(senderAddr))
}
return senderKey, senderAddr, nil
}

@ -7,6 +7,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/crypto/bls"
common2 "github.com/harmony-one/harmony/internal/common"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/internal/utils"
@ -28,7 +29,7 @@ func TestGetPeerFromID(t *testing.T) {
t.Fatalf("Cannot craeate consensus: %v", err)
}
leaderAddress := utils.GetAddressFromBlsPubKey(leader.ConsensusPubKey)
l := consensus.GetPeerByAddress(leaderAddress.Hex())
l := consensus.GetPeerByAddress(common2.MustAddressToBech32(leaderAddress))
if l.IP != leader.IP || l.Port != leader.Port {
t.Errorf("leader IP not equal")
}

@ -10,11 +10,11 @@ import (
"github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/genesis"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/core/types"
)
const (
@ -231,7 +231,7 @@ func GetInitShardState() types.ShardState {
pubKey := types.BlsPublicKey{}
pubKey.FromLibBLSPublicKey(priKey.GetPublicKey())
// TODO: directly read address for bls too
curNodeID := types.NodeID{common.HexToAddress(genesis.GenesisAccounts[index].Address), pubKey}
curNodeID := types.NodeID{common2.ParseAddr(genesis.GenesisAccounts[index].Address), pubKey}
com.NodeList = append(com.NodeList, curNodeID)
}
@ -243,7 +243,7 @@ func GetInitShardState() types.ShardState {
pubKey := types.BlsPublicKey{}
pubKey.FromLibBLSPublicKey(priKey.GetPublicKey())
// TODO: directly read address for bls too
curNodeID := types.NodeID{common.HexToAddress(genesis.GenesisFNAccounts[index].Address), pubKey}
curNodeID := types.NodeID{common2.ParseAddr(genesis.GenesisFNAccounts[index].Address), pubKey}
com.NodeList = append(com.NodeList, curNodeID)
}
shardState = append(shardState, com)

@ -33,6 +33,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
)
// Tests that updating a state trie does not leak any database writes prior to
@ -280,7 +281,7 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
action := actions[r.Intn(len(actions))]
var nameargs []string
if !action.noAddr {
nameargs = append(nameargs, addr.Hex())
nameargs = append(nameargs, common2.MustAddressToBech32(addr))
}
for _, i := range action.args {
action.args[i] = rand.Int63n(100)
@ -366,7 +367,7 @@ func (test *snapshotTest) checkEqual(state, checkstate *DB) error {
var err error
checkeq := func(op string, a, b interface{}) bool {
if err == nil && !reflect.DeepEqual(a, b) {
err = fmt.Errorf("got %s(%s) == %v, want %v", op, addr.Hex(), a, b)
err = fmt.Errorf("got %s(%s) == %v, want %v", op, common2.MustAddressToBech32(addr), a, b)
return false
}
return true

@ -9,6 +9,7 @@ import (
"github.com/harmony-one/bls/ffi/go/bls"
"golang.org/x/crypto/sha3"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror"
)
@ -208,5 +209,5 @@ func (n NodeID) Serialize() []byte {
}
func (n NodeID) String() string {
return "ECDSA: " + n.EcdsaAddress.Hex() + ", BLS: " + hex.EncodeToString(n.BlsPublicKey[:])
return "ECDSA: " + common2.MustAddressToBech32(n.EcdsaAddress) + ", BLS: " + hex.EncodeToString(n.BlsPublicKey[:])
}

@ -22,6 +22,8 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common"
common2 "github.com/harmony-one/harmony/internal/common"
)
// precompiledTest defines the input/output pairs for precompiled contract tests.
@ -337,7 +339,7 @@ var bn256PairingTests = []precompiledTest{
}
func testPrecompiled(addr string, test precompiledTest, t *testing.T) {
p := PrecompiledContractsByzantium[common.HexToAddress(addr)]
p := PrecompiledContractsByzantium[common2.ParseAddr(addr)]
in := common.Hex2Bytes(test.input)
contract := NewContract(AccountRef(common.HexToAddress("1337")),
nil, new(big.Int), p.RequiredGas(in))
@ -354,7 +356,7 @@ func benchmarkPrecompiled(addr string, test precompiledTest, bench *testing.B) {
if test.noBenchmark {
return
}
p := PrecompiledContractsByzantium[common.HexToAddress(addr)]
p := PrecompiledContractsByzantium[common2.ParseAddr(addr)]
in := common.Hex2Bytes(test.input)
reqGas := p.RequiredGas(in)
contract := NewContract(AccountRef(common.HexToAddress("1337")),

@ -5,6 +5,7 @@ import (
"sync"
"github.com/harmony-one/harmony/crypto/hash"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/ethereum/go-ethereum/common"
@ -91,7 +92,7 @@ func New(host p2p.Host, ShardID uint32, peers []p2p.Peer, leader p2p.Peer, confi
dRand.leader = leader
dRand.CommitteeAddresses = map[common.Address]bool{}
for _, peer := range peers {
dRand.validators.Store(utils.GetBlsAddress(peer.ConsensusPubKey).Hex(), peer)
dRand.validators.Store(common2.MustAddressToBech32(utils.GetBlsAddress(peer.ConsensusPubKey)), peer)
dRand.CommitteeAddresses[utils.GetBlsAddress(peer.ConsensusPubKey)] = true
}
@ -136,7 +137,7 @@ func (dRand *DRand) AddPeers(peers []*p2p.Peer) int {
count := 0
for _, peer := range peers {
_, ok := dRand.validators.LoadOrStore(utils.GetBlsAddress(peer.ConsensusPubKey).Hex(), *peer)
_, ok := dRand.validators.LoadOrStore(common2.MustAddressToBech32(utils.GetBlsAddress(peer.ConsensusPubKey)), *peer)
if !ok {
dRand.pubKeyLock.Lock()
if _, ok := dRand.CommitteeAddresses[peer.ConsensusPubKey.GetAddress()]; !ok {

@ -6,9 +6,11 @@ import (
"testing"
bls2 "github.com/harmony-one/harmony/crypto/bls"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/bls/ffi/go/bls"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils"
@ -95,7 +97,7 @@ func TestGetValidatorByPeerId(test *testing.T) {
test.Error("dRand should belong to a leader")
}
validatorAddress := utils.GetAddressFromBlsPubKey(validatorPubKey).Hex()
validatorAddress := common2.MustAddressToBech32(utils.GetAddressFromBlsPubKey(validatorPubKey))
if dRand.getValidatorPeerByAddress(validatorAddress) == nil {
test.Error("Unable to get validator by Peerid")

@ -5,7 +5,8 @@ import (
"github.com/pkg/errors"
)
//ConvertAndEncode converts from a base64 encoded byte string to base32 encoded byte string and then to bech32
// ConvertAndEncode converts from a base64 encoded byte string to base32
// encoded byte string and then to bech32.
func ConvertAndEncode(hrp string, data []byte) (string, error) {
converted, err := bech32.ConvertBits(data, 8, 5, true)
if err != nil {
@ -15,7 +16,8 @@ func ConvertAndEncode(hrp string, data []byte) (string, error) {
}
//DecodeAndConvert decodes a bech32 encoded string and converts to base64 encoded bytes
// DecodeAndConvert decodes a bech32 encoded string and converts to base64
// encoded bytes.
func DecodeAndConvert(bech string) (string, []byte, error) {
hrp, data, err := bech32.Decode(bech)
if err != nil {

@ -6,9 +6,11 @@ import (
"fmt"
"math/big"
ethCommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/harmony-one/harmony/internal/bech32"
"github.com/harmony-one/harmony/internal/utils"
"github.com/pkg/errors"
"golang.org/x/crypto/sha3"
)
@ -143,3 +145,84 @@ func (a *UnprefixedAddress) UnmarshalText(input []byte) error {
func (a UnprefixedAddress) MarshalText() ([]byte, error) {
return []byte(hex.EncodeToString(a[:])), nil
}
// TODO ek – the following functions use Ethereum addresses until we have a
// proper abstraction set in place.
// ParseBech32Addr decodes the given bech32 address and populates the given
// human-readable-part string and address with the decoded result.
func ParseBech32Addr(b32 string, hrp *string, addr *ethCommon.Address) error {
h, b, err := bech32.DecodeAndConvert(b32)
if err != nil {
return errors.Wrapf(err, "cannot decode %#v as bech32 address", b32)
}
if len(b) != ethCommon.AddressLength {
return errors.Errorf("decoded bech32 %#v has invalid length %d",
b32, len(b))
}
*hrp = h
addr.SetBytes(b)
return nil
}
// BuildBech32Addr encodes the given human-readable-part string and address
// into a bech32 address.
func BuildBech32Addr(hrp string, addr ethCommon.Address) (string, error) {
return bech32.ConvertAndEncode(hrp, addr.Bytes())
}
// MustBuildBech32Addr encodes the given human-readable-part string and
// address into a bech32 address. It panics on error.
func MustBuildBech32Addr(hrp string, addr ethCommon.Address) string {
b32, err := BuildBech32Addr(hrp, addr)
if err != nil {
panic(err)
}
return b32
}
// Bech32AddressHRP is the human-readable part of the Harmony address used by
// this process.
var Bech32AddressHRP = "one"
// Bech32ToAddress decodes the given bech32 address.
func Bech32ToAddress(b32 string) (addr ethCommon.Address, err error) {
var hrp string
err = ParseBech32Addr(b32, &hrp, &addr)
if err == nil && hrp != Bech32AddressHRP {
err = errors.Errorf("%#v is not a %#v address", b32, Bech32AddressHRP)
}
return
}
// MustBech32ToAddress decodes the given bech32 address. It panics on error.
func MustBech32ToAddress(b32 string) ethCommon.Address {
addr, err := Bech32ToAddress(b32)
if err != nil {
panic(err)
}
return addr
}
// AddressToBech32 encodes the given address into bech32 format.
func AddressToBech32(addr ethCommon.Address) (string, error) {
return BuildBech32Addr(Bech32AddressHRP, addr)
}
// MustAddressToBech32 encodes the given address into bech32 format.
// It panics on error.
func MustAddressToBech32(addr ethCommon.Address) string {
b32, err := BuildBech32Addr(Bech32AddressHRP, addr)
if err != nil {
panic(err)
}
return b32
}
// ParseAddr parses the given address, either as bech32 or as hex.
func ParseAddr(s string) ethCommon.Address {
if addr, err := Bech32ToAddress(s); err == nil {
return addr
}
return ethCommon.HexToAddress(s)
}

@ -7,6 +7,7 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
)
// SubmitTransaction is a helper function that submits tx to txPool and logs a message.
@ -21,7 +22,7 @@ func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (c
return common.Hash{}, err
}
addr := crypto.CreateAddress(from, tx.Nonce())
log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", common2.MustAddressToBech32(addr))
} else {
log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
}

@ -12,10 +12,12 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/contracts"
"github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/genesis"
"github.com/harmony-one/harmony/internal/utils"
)
@ -170,7 +172,7 @@ func (node *Node) CallFaucetContract(address common.Address) common.Hash {
// Temporary code to workaround explorer issue for searching new addresses (https://github.com/harmony-one/harmony/issues/503)
nonce := atomic.AddUint64(&node.ContractDeployerCurrentNonce, 1)
tx, _ := types.SignTx(types.NewTransaction(nonce-1, address, node.Consensus.ShardID, big.NewInt(0), params.TxGasContractCreation*10, nil, nil), types.HomesteadSigner{}, node.ContractDeployerKey)
utils.GetLogInstance().Info("Sending placeholder token to ", "Address", address.Hex())
utils.GetLogInstance().Info("Sending placeholder token to ", "Address", common2.MustAddressToBech32(address))
node.addPendingTransactions(types.Transactions{tx})
// END Temporary code
@ -199,7 +201,7 @@ func (node *Node) callGetFreeTokenWithNonce(address common.Address, nonce uint64
return common.Hash{}
}
tx, _ := types.SignTx(types.NewTransaction(nonce, node.ContractAddresses[0], node.Consensus.ShardID, big.NewInt(0), params.TxGasContractCreation*10, nil, bytesData), types.HomesteadSigner{}, node.ContractDeployerKey)
utils.GetLogInstance().Info("Sending Free Token to ", "Address", address.Hex())
utils.GetLogInstance().Info("Sending Free Token to ", "Address", common2.MustAddressToBech32(address))
node.addPendingTransactions(types.Transactions{tx})
return tx.Hash()

@ -16,6 +16,7 @@ import (
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/rawdb"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/genesis"
"github.com/harmony-one/harmony/internal/utils"
@ -134,7 +135,7 @@ func AddNodeAddressesToGenesisAlloc(genesisAlloc core.GenesisAlloc) {
for _, account := range genesis.GenesisAccounts {
testBankFunds := big.NewInt(InitFreeFundInEther)
testBankFunds = testBankFunds.Mul(testBankFunds, big.NewInt(denominations.One))
address := common.HexToAddress(account.Address)
address := common2.ParseAddr(account.Address)
genesisAlloc[address] = core.GenesisAccount{Balance: testBankFunds}
}
}

@ -6,9 +6,10 @@ import (
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/common"
)
// {Address: "0xd2Cb501B40D3a9a013A38267a4d2A4Cf6bD2CAa8", Private: "3c8642f7188e05acc4467d9e2aa7fd539e82aa90a5497257cf0ecbb98ed3b88f", Public: "0xd2Cb501B40D3a9a013A38267a4d2A4Cf6bD2CAa8"},
@ -52,7 +53,7 @@ func generateTxnHarmony(PrivateKeyFrom string, ToAddress string, shardID uint32,
nonce := uint64(0)
value := big.NewInt(1000000000000000000 * amount)
gasLimit := uint64(21000)
toAddress := common.HexToAddress(ToAddress)
toAddress := common.ParseAddr(ToAddress)
var data []byte
unsignedTx := types.NewTransaction(nonce,

Loading…
Cancel
Save