event_test.go raw

   1  package nostr
   2  
   3  import (
   4  	"testing"
   5  )
   6  
   7  func TestEventCanonicalAndID(t *testing.T) {
   8  	// Create an event and sign it, then verify the round-trip.
   9  	e := &Event{
  10  		CreatedAt: 1700000000,
  11  		Kind:      1,
  12  		Tags:      [][]string{},
  13  		Content:   "hello nostr",
  14  	}
  15  
  16  	// Use a test private key (NOT for production).
  17  	testPriv := "0000000000000000000000000000000000000000000000000000000000000001"
  18  	if err := e.Sign(testPriv); err != nil {
  19  		t.Fatalf("sign: %v", err)
  20  	}
  21  
  22  	// ID should be set.
  23  	if e.ID == "" {
  24  		t.Fatal("expected non-empty ID after signing")
  25  	}
  26  
  27  	// Pubkey should be set.
  28  	if e.Pubkey == "" {
  29  		t.Fatal("expected non-empty pubkey after signing")
  30  	}
  31  	if len(e.Pubkey) != 64 {
  32  		t.Fatalf("expected 64-char hex pubkey, got %d chars", len(e.Pubkey))
  33  	}
  34  
  35  	// Sig should be set.
  36  	if e.Sig == "" {
  37  		t.Fatal("expected non-empty sig after signing")
  38  	}
  39  	if len(e.Sig) != 128 {
  40  		t.Fatalf("expected 128-char hex sig, got %d chars", len(e.Sig))
  41  	}
  42  
  43  	// ID should match recomputation.
  44  	if !e.ValidID() {
  45  		t.Error("ValidID returned false")
  46  	}
  47  
  48  	// Signature should be valid.
  49  	if !e.ValidSig() {
  50  		t.Error("ValidSig returned false")
  51  	}
  52  
  53  	// Full validation.
  54  	if !e.Valid() {
  55  		t.Error("Valid returned false")
  56  	}
  57  }
  58  
  59  func TestEventInvalidID(t *testing.T) {
  60  	e := &Event{
  61  		ID:        "0000000000000000000000000000000000000000000000000000000000000000",
  62  		Pubkey:    "0000000000000000000000000000000000000000000000000000000000000001",
  63  		CreatedAt: 1700000000,
  64  		Kind:      1,
  65  		Tags:      [][]string{},
  66  		Content:   "hello",
  67  		Sig:       "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000",
  68  	}
  69  
  70  	if e.ValidID() {
  71  		t.Error("expected ValidID to return false for wrong ID")
  72  	}
  73  }
  74  
  75  func TestEventTampered(t *testing.T) {
  76  	e := &Event{
  77  		CreatedAt: 1700000000,
  78  		Kind:      1,
  79  		Tags:      [][]string{},
  80  		Content:   "original",
  81  	}
  82  
  83  	testPriv := "0000000000000000000000000000000000000000000000000000000000000001"
  84  	if err := e.Sign(testPriv); err != nil {
  85  		t.Fatalf("sign: %v", err)
  86  	}
  87  
  88  	if !e.Valid() {
  89  		t.Fatal("expected valid before tampering")
  90  	}
  91  
  92  	// Tamper with content.
  93  	e.Content = "tampered"
  94  
  95  	// ID should no longer match.
  96  	if e.ValidID() {
  97  		t.Error("expected ValidID to return false after tampering")
  98  	}
  99  }
 100