package play import ( "encoding/hex" "strings" "testing" "time" "github.com/decred/dcrd/dcrec/secp256k1/v4" "github.com/elnosh/gonuts/crypto" "git.smesh.lol/orly/pkg/nostr/crypto/keys" "git.smesh.lol/orly/pkg/nostr/interfaces/signer" "git.smesh.lol/orly/pkg/nostr/interfaces/signer/p8k" ) func hostSigner(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 TestBlindSignatureVerifies(t *testing.T) { host := hostSigner(t) statement := Statement("32210:aa:track", strings.Repeat("11", 32), 100, 200) if _, err := ParseStatement(statement); err != nil { t.Fatal(err) } r, err := secp256k1.GeneratePrivateKey() if err != nil { t.Fatal(err) } secret := "0000000000000000000000000000000000000000000000000000000000000001" B_, _, err := crypto.BlindMessage(secret, r) if err != nil { t.Fatal(err) } cert, err := Sign(host, hex.EncodeToString(B_.SerializeCompressed())) if err != nil { t.Fatal(err) } if !Verify(hex.EncodeToString(host.Pub()), hex.EncodeToString(B_.SerializeCompressed()), cert.C_, cert.DLEQ.E, cert.DLEQ.S) { t.Fatal("DLEQ proof did not verify") } // The blind signature unblinds to a valid signature of the statement by the // host key. Cb, _ := hex.DecodeString(cert.C_) C_, err := secp256k1.ParsePubKey(Cb) if err != nil { t.Fatal(err) } pub, err := secp256k1.ParsePubKey(append([]byte{0x02}, host.Pub()...)) if err != nil { t.Fatal(err) } C := crypto.UnblindSignature(C_, r, pub) if !crypto.Verify(secret, secp256k1.PrivKeyFromBytes(host.Sec()), C) { t.Fatal("unblinded signature does not verify against the host key") } // A different host key must not verify the same proof. other := hostSigner(t) if Verify(hex.EncodeToString(other.Pub()), hex.EncodeToString(B_.SerializeCompressed()), cert.C_, cert.DLEQ.E, cert.DLEQ.S) { t.Fatal("a proof verified under the wrong host key") } } func TestStatementShape(t *testing.T) { s := Statement("32210:aa:track", "ABCDEF", 1, 2) if string(s) != "musiquay.play:v1|32210:aa:track|abcdef|1|2" { t.Fatalf("unexpected statement %q", s) } for _, bad := range []string{ "", "musiquay.play:v1|a|b|1|2", "other:v1|a|" + "00" + "|2|1", } { if _, err := ParseStatement([]byte(bad)); err == nil { t.Fatalf("accepted %q", bad) } } } func TestIssuanceLimiter(t *testing.T) { l := NewIssuanceLimiter(time.Minute) if !l.Allow("aa", "asset", 1, 2) { t.Fatal("first issuance refused") } if l.Allow("aa", "asset", 1, 2) { t.Fatal("second issuance allowed for the same window") } if !l.Allow("bb", "asset", 1, 2) { t.Fatal("a different identity was refused") } }