mirror of
https://github.com/nbd-wtf/go-nostr.git
synced 2025-07-08 23:31:41 +02:00
support for naddr on nip19.
This commit is contained in:
@ -2,6 +2,7 @@ package nip19
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
@ -74,6 +75,35 @@ func Decode(bech32string string) (prefix string, value any, err error) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
curr = curr + 2 + len(v)
|
||||
}
|
||||
case "naddr":
|
||||
var result nostr.EntityPointer
|
||||
curr := 0
|
||||
for {
|
||||
t, v := readTLVEntry(data[curr:])
|
||||
if v == nil {
|
||||
// end here
|
||||
if result.Kind == 0 || result.Identifier == "" || result.PublicKey == "" {
|
||||
return prefix, result, fmt.Errorf("incomplete naddr")
|
||||
}
|
||||
|
||||
return prefix, result, nil
|
||||
}
|
||||
|
||||
switch t {
|
||||
case TLVDefault:
|
||||
result.Identifier = string(v)
|
||||
case TLVRelay:
|
||||
result.Relays = append(result.Relays, string(v))
|
||||
case TLVAuthor:
|
||||
result.PublicKey = hex.EncodeToString(v)
|
||||
case TLVKind:
|
||||
result.Kind = int(binary.BigEndian.Uint32(v))
|
||||
default:
|
||||
// ignore
|
||||
}
|
||||
|
||||
curr = curr + 2 + len(v)
|
||||
}
|
||||
}
|
||||
@ -145,11 +175,11 @@ func EncodeProfile(publicKeyHex string, relays []string) (string, error) {
|
||||
|
||||
func EncodeEvent(eventIdHex string, relays []string) (string, error) {
|
||||
buf := &bytes.Buffer{}
|
||||
pubkey, err := hex.DecodeString(eventIdHex)
|
||||
id, err := hex.DecodeString(eventIdHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid id '%s': %w", eventIdHex, err)
|
||||
}
|
||||
writeTLVEntry(buf, TLVDefault, pubkey)
|
||||
writeTLVEntry(buf, TLVDefault, id)
|
||||
|
||||
for _, url := range relays {
|
||||
writeTLVEntry(buf, TLVRelay, []byte(url))
|
||||
@ -162,3 +192,30 @@ func EncodeEvent(eventIdHex string, relays []string) (string, error) {
|
||||
|
||||
return encode("nevent", bits5)
|
||||
}
|
||||
|
||||
func EncodeEntity(publicKey string, kind int, identifier string, relays []string) (string, error) {
|
||||
buf := &bytes.Buffer{}
|
||||
|
||||
writeTLVEntry(buf, TLVDefault, []byte(identifier))
|
||||
|
||||
for _, url := range relays {
|
||||
writeTLVEntry(buf, TLVRelay, []byte(url))
|
||||
}
|
||||
|
||||
pubkey, err := hex.DecodeString(publicKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid pubkey '%s': %w", pubkey, err)
|
||||
}
|
||||
writeTLVEntry(buf, TLVAuthor, pubkey)
|
||||
|
||||
kindBytes := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(kindBytes, uint32(kind))
|
||||
writeTLVEntry(buf, TLVKind, kindBytes)
|
||||
|
||||
bits5, err := convertBits(buf.Bytes(), 8, 5, true)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to convert bits: %w", err)
|
||||
}
|
||||
|
||||
return encode("naddr", bits5)
|
||||
}
|
||||
|
Reference in New Issue
Block a user