// Address contains information about the created address.
type Address struct {
Address string // in hexadecimal format
AddressBase58 string // encoded in Base58 format
PrivateKey string // Private key in hexadecimal format
PublicKey string // Public key in hexadecimal format
Mnemonic string
}
// CreateAddress creates a new address, returns the full Address structure
func (c *Client) CreateAddress() (*Address, error) {
accountPath := "m/44'/195'/0'/0/0"
passphrase := ""
m, err := mnemonic.GenerateMnemonic24()
if err != nil {
return nil, fmt.Errorf("failed to generate mnemonic 24 words")
}
seed := bip39.NewSeed(m, passphrase)
masterKey, err := bip32.NewMasterKey(seed)
if err != nil {
return nil, fmt.Errorf("failed to create master bip32Key: %w", err)
}
// Split the path and parse each component
segments := strings.Split(accountPath, "/")
var bip32Key = masterKey
for _, segment := range segments[1:] { // skipping the 'm' part
var hardened bool
if strings.HasSuffix(segment, "'") {
hardened = true
segment = segment[:len(segment)-1]
}
index, err := strconv.Atoi(segment)
if err != nil {
return nil, fmt.Errorf("invalid path segment '%s': %w", segment, err)
}
if hardened {
bip32Key, err = bip32Key.NewChildKey(uint32(index) + bip32.FirstHardenedChild)
} else {
bip32Key, err = bip32Key.NewChildKey(uint32(index))
}
if err != nil {
return nil, fmt.Errorf("failed to derive bip32Key at %s: %w", segment, err)
}
}
privateKey, err := crypto.HexToECDSA(hex.EncodeToString(bip32Key.Key))
if err != nil {
return nil, fmt.Errorf("failed to derive private key: %w", err)
}
privateKeyHex := hex.EncodeToString(bip32Key.Key)
publicKeyHex := tools.ConvertPublicKeyToHex(privateKey.Public().(*ecdsa.PublicKey))
address := tools.GetAddressFromPublicKey(privateKey.Public().(*ecdsa.PublicKey))
addressBase58, err := tools.HexToBase58(address)
if err != nil {
return nil, fmt.Errorf("failed to derive address base58: %w", err)
}
return &Address{
Address: address,
AddressBase58: addressBase58,
PrivateKey: privateKeyHex,
PublicKey: publicKeyHex,
Mnemonic: m,
}, nil
}