package rental import ( "context" "sync" "testing" "time" "git.smesh.lol/orly/pkg/nostr/crypto/keys" "git.smesh.lol/orly/pkg/nostr/encoders/hex" "git.smesh.lol/orly/pkg/nostr/interfaces/signer" "git.smesh.lol/orly/pkg/nostr/interfaces/signer/p8k" ) type memStore struct { mu sync.Mutex m map[string][]byte } func (s *memStore) GetMarker(k string) ([]byte, error) { s.mu.Lock() defer s.mu.Unlock() return s.m[k], nil } func (s *memStore) SetMarker(k string, v []byte) error { s.mu.Lock() defer s.mu.Unlock() if s.m == nil { s.m = make(map[string][]byte) } s.m[k] = v return nil } func buyerSigner(t *testing.T) signer.I { t.Helper() sk, err := keys.GenerateSecretKey() if err != nil { t.Fatal(err) } s, err := p8k.New() if err != nil { t.Fatal(err) } if err = s.InitSec(sk); err != nil { t.Fatal(err) } return s } func fakeAsset() string { var b [32]byte for i := range b { b[i] = byte(i + 3) } id, _ := hexAsset(b[:]) return id } func hexAsset(b []byte) (string, error) { return hex.Enc(b), nil } func TestWindowExpires(t *testing.T) { buyer := buyerSigner(t) asset := fakeAsset() m := New(&memStore{}, time.Minute) ctx := context.Background() creq, err := m.Challenge(asset, 50, "https://mint.example.com") if err != nil { t.Fatal(err) } if creq[:5] != "creqA" { t.Fatalf("challenge is not NUT-18: %q", creq) } if m.Valid(ctx, buyer.Pub(), asset) { t.Fatal("access before payment") } w, err := m.Open(ctx, buyer.Pub(), asset, time.Hour, 50) if err != nil { t.Fatal(err) } // The requested window is capped at the host bucket. if w.Expires > time.Now().Add(time.Minute).Unix()+1 { t.Fatalf("window %d exceeds the bucket", w.Expires) } if !m.Valid(ctx, buyer.Pub(), asset) { t.Fatal("paid window is not valid") } // Expire it by moving the clock forward. m.now = func() time.Time { return time.Now().Add(2 * time.Minute) } if m.Valid(ctx, buyer.Pub(), asset) { t.Fatal("expired window is still valid") } if m.Remaining(ctx, buyer.Pub(), asset) != 0 { t.Fatal("expired window reports remaining time") } } func TestChallengeRejectsBadInput(t *testing.T) { m := New(&memStore{}, time.Minute) if _, err := m.Challenge("short", 50, ""); err == nil { t.Fatal("invalid asset id accepted") } if _, err := m.Challenge(fakeAsset(), 0, ""); err == nil { t.Fatal("zero price accepted") } }