Skip to content

Commit

Permalink
feat: add Optimize the code: Add test case (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
MagicalBridge authored Oct 15, 2024
1 parent 040344b commit ea66925
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
2 changes: 0 additions & 2 deletions wallet/ethereum/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package ethereum
import (
"crypto/ecdsa"
"encoding/hex"

"github.com/ethereum/go-ethereum/common"

"github.com/ethereum/go-ethereum/crypto"
)

Expand Down
58 changes: 58 additions & 0 deletions wallet/ethereum/address_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package ethereum

import (
"crypto/elliptic"
"encoding/hex"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"testing"
)

Expand All @@ -12,3 +16,57 @@ func TestCreateAddressByKeyPairs(t *testing.T) {
}
fmt.Println(address.PrivateKey, address.PublicKey, address.Address)
}

func TestCreateAddressFromPrivateKey(t *testing.T) {
privKey, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("Failed to generate private key: %v", err)
}

priKeyHex, address, err := CreateAddressFromPrivateKey(privKey)
if err != nil {
t.Fatalf("Error creating address from private key: %v", err)
}

expectedPriKeyHex := hex.EncodeToString(privKey.D.Bytes())
if priKeyHex != expectedPriKeyHex {
t.Errorf("Expected private key hex: %s, got: %s", expectedPriKeyHex, priKeyHex)
}

expectedAddress := crypto.PubkeyToAddress(privKey.PublicKey).String()
if address != expectedAddress {
t.Errorf("Expected address: %s, got: %s", expectedAddress, address)
}
}

func TestPublicKeyToAddress(t *testing.T) {
// Generate a new ECDSA private key
privKey, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("Failed to generate private key: %v", err)
}

// Encode the public key in uncompressed format
pubKeyBytes := elliptic.Marshal(crypto.S256(), privKey.PublicKey.X, privKey.PublicKey.Y)
pubKeyHex := hex.EncodeToString(pubKeyBytes)

// Calculate the expected address using common.BytesToAddress
hash := crypto.Keccak256(pubKeyBytes[1:])
expectedAddress := common.BytesToAddress(hash[12:]).String()

t.Logf("Public Key: %s", pubKeyHex)
t.Logf("Expected Address: %s", expectedAddress)

// Call the function PublicKeyToAddress
gotAddress, err := PublicKeyToAddress(pubKeyHex)
if err != nil {
t.Fatalf("Error creating address from public key: %v", err)
}

t.Logf("Got Address: %s", gotAddress)

// Compare the expected address with the address generated by the function
if gotAddress != expectedAddress {
t.Errorf("Expected address: %s, got: %s", expectedAddress, gotAddress)
}
}

0 comments on commit ea66925

Please sign in to comment.