play.go raw
1 // Package play implements certified play reports.
2 //
3 // A paid play is certified with a BDHKE blind signature from the serving host's
4 // play key, accompanied by a NUT-12 DLEQ proof. The host never learns which
5 // listener received a signature, and the listener can prove the signature was
6 // issued for a specific host, asset, blob, and time window.
7 //
8 // The statement deliberately covers only facts the host itself observed. It is
9 // an oracle: a host that signs a blind point without a bound statement can be
10 // made to certify a fiction. Money is accounted by receipts and aggregates, so
11 // price and tier are not part of the statement.
12 package play
13
14 import (
15 "fmt"
16 "strconv"
17 "strings"
18 "sync"
19 "time"
20
21 "github.com/decred/dcrd/dcrec/secp256k1/v4"
22 "github.com/elnosh/gonuts/crypto"
23
24 "git.smesh.lol/orly/pkg/nostr/encoders/hex"
25 "git.smesh.lol/orly/pkg/nostr/interfaces/signer"
26 )
27
28 // Domain is the statement domain separator.
29 const Domain = "musiquay.play:v1"
30
31 // Statement builds the signed statement bytes:
32 //
33 // musiquay.play:v1|<asset-address>|<blob-sha256>|<start>|<end>
34 func Statement(assetAddress, blobHex string, start, end int64) []byte {
35 return []byte(fmt.Sprintf("%s|%s|%s|%d|%d", Domain, assetAddress, strings.ToLower(blobHex), start, end))
36 }
37
38 // ParsedStatement is a decoded statement.
39 type ParsedStatement struct {
40 AssetAddress string
41 Blob string
42 Start int64
43 End int64
44 }
45
46 // ParseStatement validates the domain and shape.
47 func ParseStatement(raw []byte) (*ParsedStatement, error) {
48 parts := strings.Split(string(raw), "|")
49 if len(parts) != 5 {
50 return nil, fmt.Errorf("play: statement must have five fields")
51 }
52 if parts[0] != Domain {
53 return nil, fmt.Errorf("play: wrong domain %q", parts[0])
54 }
55 if len(parts[2]) != 64 {
56 return nil, fmt.Errorf("play: blob hash must be 64 hex characters")
57 }
58 start, err := strconv.ParseInt(parts[3], 10, 64)
59 if err != nil {
60 return nil, fmt.Errorf("play: invalid start")
61 }
62 end, err := strconv.ParseInt(parts[4], 10, 64)
63 if err != nil {
64 return nil, fmt.Errorf("play: invalid end")
65 }
66 if end < start {
67 return nil, fmt.Errorf("play: end precedes start")
68 }
69 return &ParsedStatement{AssetAddress: parts[1], Blob: parts[2], Start: start, End: end}, nil
70 }
71
72 // DLEQ is the NUT-12 proof that the blind signature used the host's key.
73 type DLEQ struct {
74 E string `json:"e"`
75 S string `json:"s"`
76 }
77
78 // Certification is the host's response to a blind-sign request.
79 type Certification struct {
80 // C_ is the blind signature, compressed hex.
81 C_ string `json:"C_"`
82 // DLEQ proves C_ = k*B_ without revealing k.
83 DLEQ DLEQ `json:"dleq"`
84 }
85
86 // Sign produces C_ and a DLEQ proof for one blinded point.
87 //
88 // The blinded point must be a valid compressed secp256k1 key. The signature is
89 // over the point, not the statement: the statement binding is enforced by the
90 // caller's entitlement check and by the host's record of what it served.
91 func Sign(sign signer.I, blindedHex string) (*Certification, error) {
92 b, err := hex.Dec(blindedHex)
93 if err != nil || len(b) == 0 {
94 return nil, fmt.Errorf("play: invalid blinded point")
95 }
96 B_, err := secp256k1.ParsePubKey(b)
97 if err != nil {
98 return nil, fmt.Errorf("play: blinded point is not a public key: %w", err)
99 }
100 sec := sign.Sec()
101 if len(sec) != 32 {
102 return nil, fmt.Errorf("play: signer has no secret key")
103 }
104 k := secp256k1.PrivKeyFromBytes(sec)
105 C_ := crypto.SignBlindedMessage(B_, k)
106 e, s := crypto.GenerateDLEQ(k, B_, C_)
107 eb := e.Key.Bytes()
108 sb := s.Key.Bytes()
109 return &Certification{
110 C_: hex.Enc(C_.SerializeCompressed()),
111 DLEQ: DLEQ{
112 E: hex.Enc(eb[:]),
113 S: hex.Enc(sb[:]),
114 },
115 }, nil
116 }
117
118 // Verify checks a DLEQ proof for a host, a blinded point, and a blind
119 // signature. It is the independent verifier a play-report consumer runs.
120 func Verify(hostPubHex, blindedHex, cHex, eHex, sHex string) bool {
121 host, err := hex.Dec(hostPubHex)
122 if err != nil || len(host) != 32 {
123 return false
124 }
125 // The host key is x-only on Nostr; the DLEQ A is a 33-byte point.
126 A, err := secp256k1.ParsePubKey(append([]byte{0x02}, host...))
127 if err != nil {
128 return false
129 }
130 return verifyPoints(A, blindedHex, cHex, eHex, sHex)
131 }
132
133 func verifyPoints(A *secp256k1.PublicKey, blindedHex, cHex, eHex, sHex string) bool {
134 bb, err := hex.Dec(blindedHex)
135 if err != nil {
136 return false
137 }
138 B_, err := secp256k1.ParsePubKey(bb)
139 if err != nil {
140 return false
141 }
142 cb, err := hex.Dec(cHex)
143 if err != nil {
144 return false
145 }
146 C_, err := secp256k1.ParsePubKey(cb)
147 if err != nil {
148 return false
149 }
150 eb, err := hex.Dec(eHex)
151 if err != nil || len(eb) == 0 {
152 return false
153 }
154 sb, err := hex.Dec(sHex)
155 if err != nil || len(sb) == 0 {
156 return false
157 }
158 e := secp256k1.PrivKeyFromBytes(eb)
159 s := secp256k1.PrivKeyFromBytes(sb)
160 return crypto.VerifyDLEQ(e, s, A, B_, C_)
161 }
162
163 // IssuanceLimiter allows at most one signature per (identity, asset, window)
164 // within a window. It is in-memory and honour-system across restarts, which is
165 // the right trade: the limit is a sybil speed bump, not accounting.
166 type IssuanceLimiter struct {
167 mu sync.Mutex
168 seen map[string]time.Time
169 ttl time.Duration
170 }
171
172 // NewIssuanceLimiter creates a limiter whose entries live for ttl.
173 func NewIssuanceLimiter(ttl time.Duration) *IssuanceLimiter {
174 if ttl <= 0 {
175 ttl = 15 * time.Minute
176 }
177 return &IssuanceLimiter{seen: make(map[string]time.Time), ttl: ttl}
178 }
179
180 // Allow records an issuance and reports whether it is the first.
181 func (l *IssuanceLimiter) Allow(identityHex, asset string, start, end int64) bool {
182 key := fmt.Sprintf("%s|%s|%d|%d", identityHex, asset, start, end)
183 now := time.Now()
184 l.mu.Lock()
185 defer l.mu.Unlock()
186 for k, at := range l.seen {
187 if now.Sub(at) > l.ttl {
188 delete(l.seen, k)
189 }
190 }
191 if _, ok := l.seen[key]; ok {
192 return false
193 }
194 l.seen[key] = now
195 return true
196 }
197