Skip to content

GetRandomKeys

Generates a random key pair for testing and development.

Function Signature

func GetRandomKeys() (ks *MemKeystore, pubKey, privKey *felt.Felt)

Parameters

None

Returns

  • ks - MemKeystore containing the generated private key
  • pubKey - Generated public key
  • privKey - Generated private key

Usage Example

package main
 
import (
	"fmt"
 
	"github.com/NethermindEth/starknet.go/account"
)
 
func main() {
	// Get random keys (keystore, public key, private key)
	ks, pubKey, privKey := account.GetRandomKeys()
 
	fmt.Println("Random keys generated:")
	fmt.Printf("Public Key:  %s\n", pubKey)
	fmt.Printf("Private Key: %s\n", privKey)
 
	// Show that keystore contains the key
	fmt.Println("\nVerifying keystore contains the key:")
	storedKey, err := ks.Get(pubKey.String())
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	} else {
		fmt.Printf("Retrieved key from keystore: %s\n", storedKey)
		// The keystore stores the private key associated with the public key
		fmt.Printf("Keys stored successfully: %v\n", storedKey != nil)
	}
 
	// Generate another set of random keys
	fmt.Println("\nGenerating another set of random keys:")
	ks2, pubKey2, privKey2 := account.GetRandomKeys()
	fmt.Printf("Public Key 2:  %s\n", pubKey2)
	fmt.Printf("Private Key 2: %s\n", privKey2)
 
	// Verify keys are different
	fmt.Printf("\nKeys are different: %v\n", pubKey.String() != pubKey2.String())
 
	// Show both keystores are independent
	_, err1 := ks.Get(pubKey2.String())
	_, err2 := ks2.Get(pubKey.String())
	fmt.Printf("Keystore 1 has key 2: %v\n", err1 == nil)
	fmt.Printf("Keystore 2 has key 1: %v\n", err2 == nil)
}

Expected Output

Random keys generated:
Public Key:  0x68ab6bede5d0d19e91a7e08103ef5b473be1b60496c8ade7c1feef767fe4b6
Private Key: 0x4018388719f3a4e75b53c192fe559a7890a2a9f1f887b084552ecef866c72f8
 
Verifying keystore contains the key:
Retrieved key from keystore: 1811926048687811693773218878414096663361903231379212933171229578164471362296
Keys stored successfully: true
 
Generating another set of random keys:
Public Key 2:  0x27940ce5d0deacca17157ea90ef8d6520237894adc27119500185ecde43bacb
Private Key 2: 0x7fdbd39e2648fb036c534e8b090aba26883bfc4b7bb6a93dee4731144b624b5
 
Keys are different: true
Keystore 1 has key 2: false
Keystore 2 has key 1: false

Description

GetRandomKeys generates a cryptographically random key pair using the Starknet curve. The private key is automatically stored in a MemKeystore indexed by the public key.

This function is intended for:

  • Testing and development
  • Examples and tutorials
  • Temporary accounts

For production use, implement a secure Keystore that persists keys safely.

Error Handling

If key generation fails, the function prints an error message and exits. This is acceptable for testing code but should be handled differently in production.

Related Functions