signature.go raw

   1  package validation
   2  
   3  import (
   4  	"fmt"
   5  
   6  	"next.orly.dev/pkg/nostr/encoders/event"
   7  	"next.orly.dev/pkg/nostr/encoders/hex"
   8  	"next.orly.dev/pkg/lol/log"
   9  	"next.orly.dev/pkg/utils"
  10  )
  11  
  12  // ValidateEventID checks that the event ID matches the computed hash.
  13  func ValidateEventID(ev *event.E) Result {
  14  	calculatedID := ev.GetIDBytes()
  15  	if !utils.FastEqual(calculatedID, ev.ID) {
  16  		canonical := ev.ToCanonical(nil)
  17  		log.E.F("ValidateEventID FAIL: event ID %0x computed %0x, canonical: %s",
  18  			ev.ID, calculatedID, string(canonical))
  19  		return Invalid(fmt.Sprintf(
  20  			"event id is computed incorrectly, event has ID %0x, but when computed it is %0x",
  21  			ev.ID, calculatedID,
  22  		))
  23  	}
  24  	return OK()
  25  }
  26  
  27  // ValidateSignature verifies the event signature.
  28  func ValidateSignature(ev *event.E) Result {
  29  	ok, err := ev.Verify()
  30  	if err != nil {
  31  		log.E.F("ValidateSignature ERROR: kind=%d pubkey=%s id=%0x err=%v",
  32  			ev.Kind, hex.Enc(ev.Pubkey), ev.ID, err)
  33  		return Error(fmt.Sprintf("failed to verify signature: %s", err.Error()))
  34  	}
  35  	if !ok {
  36  		canonical := ev.ToCanonical(nil)
  37  		log.E.F("ValidateSignature FAIL: kind=%d pubkey=%s id=%0x sig=%0x canonical=%s",
  38  			ev.Kind, hex.Enc(ev.Pubkey), ev.ID, ev.Sig, string(canonical))
  39  		return Invalid("signature is invalid")
  40  	}
  41  	return OK()
  42  }
  43