pubkey.go raw

   1  package nostr
   2  
   3  import (
   4  	"next.orly.dev/pkg/nostr/encoders/bech32encoding"
   5  	"next.orly.dev/pkg/nostr/encoders/hex"
   6  )
   7  
   8  // PubkeyToNpub converts a hex public key to bech32 npub format
   9  func PubkeyToNpub(hexPubkey string) string {
  10  	npub, err := bech32encoding.HexToNpub([]byte(hexPubkey))
  11  	if err != nil {
  12  		// If encoding fails, return truncated hex
  13  		if len(hexPubkey) > 16 {
  14  			return hexPubkey[:16] + "..."
  15  		}
  16  		return hexPubkey
  17  	}
  18  	return string(npub)
  19  }
  20  
  21  // NpubToPubkey converts a bech32 npub to hex public key
  22  func NpubToPubkey(npub string) (string, error) {
  23  	pkBytes, err := bech32encoding.NpubToBytes([]byte(npub))
  24  	if err != nil {
  25  		return "", err
  26  	}
  27  	return hex.Enc(pkBytes), nil
  28  }
  29  
  30  // TruncateNpub returns a shortened npub for display
  31  func TruncateNpub(npub string) string {
  32  	if len(npub) <= 20 {
  33  		return npub
  34  	}
  35  	return npub[:12] + "..." + npub[len(npub)-8:]
  36  }
  37  
  38  // GenerateUsername creates a username from a pubkey
  39  // Prefers NIP-05 identifier if available, otherwise uses npub prefix
  40  func GenerateUsername(hexPubkey string) string {
  41  	npub := PubkeyToNpub(hexPubkey)
  42  	// Use first 12 chars of npub (npub1 + 7 chars)
  43  	if len(npub) > 12 {
  44  		return npub[:12]
  45  	}
  46  	return npub
  47  }
  48  
  49  // GeneratePlaceholderEmail creates a placeholder email for Gitea
  50  func GeneratePlaceholderEmail(hexPubkey string) string {
  51  	username := GenerateUsername(hexPubkey)
  52  	return username + "@nostr.local"
  53  }
  54