pubhash.go raw

   1  package types
   2  
   3  import (
   4  	"io"
   5  
   6  	"next.orly.dev/pkg/lol/chk"
   7  	"next.orly.dev/pkg/lol/errorf"
   8  	"next.orly.dev/pkg/nostr/crypto/ec/schnorr"
   9  	"github.com/minio/sha256-simd"
  10  	"next.orly.dev/pkg/nostr/encoders/hex"
  11  )
  12  
  13  const PubHashLen = 8
  14  
  15  type PubHash struct{ val [PubHashLen]byte }
  16  
  17  func (ph *PubHash) FromPubkey(pk []byte) (err error) {
  18  	if len(pk) == 0 {
  19  		panic("nil pubkey")
  20  	}
  21  	if len(pk) != schnorr.PubKeyBytesLen {
  22  		err = errorf.E(
  23  			"invalid Pubkey length, got %d require %d %0x",
  24  			len(pk), schnorr.PubKeyBytesLen, pk,
  25  		)
  26  		return
  27  	}
  28  	pkh := sha256.Sum256(pk)
  29  	copy(ph.val[:], pkh[:PubHashLen])
  30  	return
  31  }
  32  
  33  func (ph *PubHash) FromPubkeyHex(pk string) (err error) {
  34  	if len(pk) != schnorr.PubKeyBytesLen*2 {
  35  		err = errorf.E(
  36  			"invalid Pubkey length, got %d require %d",
  37  			len(pk), schnorr.PubKeyBytesLen*2,
  38  		)
  39  		return
  40  	}
  41  	var pkb []byte
  42  	if pkb, err = hex.Dec(pk); chk.E(err) {
  43  		return
  44  	}
  45  	h := sha256.Sum256(pkb)
  46  	copy(ph.val[:], h[:PubHashLen])
  47  	return
  48  }
  49  
  50  func (ph *PubHash) Bytes() (b []byte) { return ph.val[:] }
  51  
  52  func (ph *PubHash) MarshalWrite(w io.Writer) (err error) {
  53  	_, err = w.Write(ph.val[:])
  54  	return
  55  }
  56  
  57  func (ph *PubHash) UnmarshalRead(r io.Reader) (err error) {
  58  	copy(ph.val[:], ph.val[:PubHashLen])
  59  	_, err = r.Read(ph.val[:])
  60  	return
  61  }
  62