Skip to content

Commit

Permalink
feat(BUX-190): add keys generation
Browse files Browse the repository at this point in the history
  • Loading branch information
pawellewandowski98 committed Oct 18, 2023
1 parent c7df2a4 commit 8f8ca5f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
26 changes: 26 additions & 0 deletions examples/keys/keys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"fmt"
"github.com/BuxOrg/go-buxclient/utils"
)

func main() {
// Generate a random set of keys
hdXpriv, hdXpub := utils.GenerateRandomSetOfKeys()

fmt.Println("Your XPriv: ", hdXpriv)
fmt.Println("Your XPub: ", hdXpub)

xpub, err := utils.GetPublicKeyFromHDPrivateKey(hdXpriv.String())
if err != nil {
panic(err)
}

// hdXpub and xpub should be this same
if hdXpub.String() != xpub.String() {
panic("xpub and hdXpub are not the same")
} else {
fmt.Println("Keys generated successfully, xpub and hdXpub are the same")
}
}
38 changes: 38 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/libsv/go-bk/bip39"
"github.com/libsv/go-bk/chaincfg"
"math"
"strconv"

Expand Down Expand Up @@ -83,3 +86,38 @@ func GetChildNumsFromHex(hexHash string) ([]uint32, error) {

return childNums, nil
}

// GenerateRandomSetOfKeys generates a random set of keys - xpriv, xpb and address
func GenerateRandomSetOfKeys() (hdXpriv *bip32.ExtendedKey, hdXpub *bip32.ExtendedKey) {
entropy, err := bip39.GenerateEntropy(160)
if err != nil {
panic(err)
}

_, seed, err := bip39.Mnemonic(entropy, "")

if err != nil {
fmt.Println(err)
panic(err)
}

hdXpriv, err = bip32.NewMaster(seed, &chaincfg.MainNet)

if err != nil {
fmt.Println(err)
panic(err)
}

hdXpub, err = hdXpriv.Neuter()
return
}

// GetPublicKeyFromHDPrivateKey returns the public key from the HD private key
func GetPublicKeyFromHDPrivateKey(hdXpriv string) (hdXpub *bip32.ExtendedKey, err error) {
hdKey, err := bip32.NewKeyFromString(hdXpriv)
hdXpub, err = hdKey.Neuter()
if err != nil {
return nil, err
}
return
}

0 comments on commit 8f8ca5f

Please sign in to comment.