gcs.go raw

   1  // Package gcs implements the exact Golomb-coded membership set that gates paid
   2  // musiquay assets.
   3  //
   4  // The set is exact: a non-member is never matched, because membership is a
   5  // binary search over the stored hashes, not a probabilistic probe. A filter
   6  // collision would require a SHA-256 collision. There is deliberately no Bloom
   7  // or Cuckoo variant in the gate path.
   8  //
   9  // Blob layout (all integers big-endian, bits within a byte MSB first):
  10  //
  11  //	magic "MQG1" | version | mode | hash width | n (8) | address len (2) | address
  12  //	| Rice parameter p | Golomb-coded sorted deltas
  13  //
  14  // A delta blob adds only elements:
  15  //
  16  //	magic "MQD1" | version | base x (32) | hash width | n_delta (8) | p
  17  //	| Golomb-coded sorted deltas of added elements
  18  package gcs
  19  
  20  import (
  21  	"bytes"
  22  	"crypto/sha256"
  23  	"encoding/binary"
  24  	"fmt"
  25  	"math/big"
  26  	"sort"
  27  )
  28  
  29  // Magic and format constants.
  30  const (
  31  	// Magic is the full-set magic.
  32  	Magic = "MQG1"
  33  	// DeltaMagic is the delta-set magic.
  34  	DeltaMagic = "MQD1"
  35  	// Version is the only supported format version.
  36  	Version = 1
  37  	// ModeExact is the only mode usable for gating. ModeGCSMod is reserved for
  38  	// the probabilistic variant and is rejected.
  39  	ModeExact = 0
  40  	// Domain is the element hash domain separator.
  41  	Domain = "musiquay.filter.v1"
  42  
  43  	// MaxHashWidth is the largest element width the format allows.
  44  	MaxHashWidth = 32
  45  	// MaxElements bounds a parse, so a hostile blob cannot exhaust memory.
  46  	MaxElements = 10_000_000
  47  	// maxQuotient bounds the unary part of one code, so a corrupt blob cannot
  48  	// make the decoder read gigabytes of zeros.
  49  	maxQuotient = 1 << 24
  50  )
  51  
  52  // Element hashes a pubkey into the set's domain.
  53  func Element(pubkey []byte, hashWidth int) []byte {
  54  	h := sha256.New()
  55  	h.Write([]byte(Domain))
  56  	h.Write([]byte("|"))
  57  	h.Write(pubkey)
  58  	sum := h.Sum(nil)
  59  	if hashWidth <= 0 || hashWidth > len(sum) {
  60  		hashWidth = 32
  61  	}
  62  	return sum[:hashWidth]
  63  }
  64  
  65  // Set is an exact sorted membership set for one asset address.
  66  type Set struct {
  67  	// Asset is the address the set is bound to.
  68  	Asset string
  69  	// HashWidth is the element width in bytes.
  70  	HashWidth int
  71  	// N is the element count.
  72  	N uint64
  73  	// P is the Rice parameter stored in the blob.
  74  	P uint8
  75  	// values are the sorted, truncated element hashes.
  76  	values [][]byte
  77  }
  78  
  79  // Build constructs a set from pubkeys. Duplicate pubkeys collapse, so a
  80  // republished set with a repeated element is byte-identical.
  81  func Build(asset string, pubkeys [][]byte, hashWidth int) (*Set, error) {
  82  	if asset == "" {
  83  		return nil, fmt.Errorf("gcs: empty asset address")
  84  	}
  85  	if hashWidth <= 0 || hashWidth > MaxHashWidth {
  86  		return nil, fmt.Errorf("gcs: hash width %d out of range", hashWidth)
  87  	}
  88  	if len(pubkeys) > MaxElements {
  89  		return nil, fmt.Errorf("gcs: too many elements")
  90  	}
  91  	seen := make(map[string]struct{}, len(pubkeys))
  92  	values := make([][]byte, 0, len(pubkeys))
  93  	for _, pk := range pubkeys {
  94  		e := Element(pk, hashWidth)
  95  		k := string(e)
  96  		if _, ok := seen[k]; ok {
  97  			continue
  98  		}
  99  		seen[k] = struct{}{}
 100  		values = append(values, e)
 101  	}
 102  	sort.Slice(values, func(i, j int) bool { return bytes.Compare(values[i], values[j]) < 0 })
 103  	s := &Set{Asset: asset, HashWidth: hashWidth, N: uint64(len(values)), values: values}
 104  	s.P = riceParameter(hashWidth, s.N)
 105  	return s, nil
 106  }
 107  
 108  // contains reports membership by exact search.
 109  func (s *Set) Contains(pubkey []byte) bool {
 110  	if s == nil {
 111  		return false
 112  	}
 113  	e := Element(pubkey, s.HashWidth)
 114  	i := sort.Search(len(s.values), func(i int) bool {
 115  		return bytes.Compare(s.values[i], e) >= 0
 116  	})
 117  	return i < len(s.values) && bytes.Equal(s.values[i], e)
 118  }
 119  
 120  // Len returns the element count.
 121  func (s *Set) Len() int {
 122  	if s == nil {
 123  		return 0
 124  	}
 125  	return len(s.values)
 126  }
 127  
 128  // Rebuild returns a new set with additions and, optionally, removals. GCS has
 129  // no in-place mutation, so a rebuild re-encodes from scratch.
 130  //
 131  // Ownership sets must never remove: the caller enforces that by passing an
 132  // empty remove list. Subscriptions remove at rebuild by passing the lapsed keys.
 133  func (s *Set) Rebuild(asset string, add, remove [][]byte) (*Set, error) {
 134  	if s == nil {
 135  		return Build(asset, add, 32)
 136  	}
 137  	if asset == "" {
 138  		asset = s.Asset
 139  	}
 140  	drop := make(map[string]struct{}, len(remove))
 141  	for _, pk := range remove {
 142  		drop[string(Element(pk, s.HashWidth))] = struct{}{}
 143  	}
 144  	seen := make(map[string]struct{}, len(s.values)+len(add))
 145  	keys := make([][]byte, 0, len(s.values)+len(add))
 146  	for _, v := range s.values {
 147  		k := string(v)
 148  		if _, gone := drop[k]; gone {
 149  			continue
 150  		}
 151  		if _, ok := seen[k]; ok {
 152  			continue
 153  		}
 154  		seen[k] = struct{}{}
 155  		keys = append(keys, v)
 156  	}
 157  	for _, pk := range add {
 158  		e := Element(pk, s.HashWidth)
 159  		k := string(e)
 160  		if _, gone := drop[k]; gone {
 161  			continue
 162  		}
 163  		if _, ok := seen[k]; ok {
 164  			continue
 165  		}
 166  		seen[k] = struct{}{}
 167  		keys = append(keys, e)
 168  	}
 169  	sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i], keys[j]) < 0 })
 170  	out := &Set{Asset: asset, HashWidth: s.HashWidth, N: uint64(len(keys)), values: keys}
 171  	out.P = riceParameter(out.HashWidth, out.N)
 172  	return out, nil
 173  }
 174  
 175  // riceParameter derives p = max(1, ceil(log2(2^(8*hash)/n))).
 176  func riceParameter(hashWidth int, n uint64) uint8 {
 177  	if n == 0 {
 178  		return 1
 179  	}
 180  	// floor(log2(n))
 181  	floor := 0
 182  	for v := n; v > 1; v >>= 1 {
 183  		floor++
 184  	}
 185  	p := 8*hashWidth - floor
 186  	if p < 1 {
 187  		p = 1
 188  	}
 189  	// The parameter is stored in one byte. For a single element the formula
 190  	// reaches 8*hash, which is 256 for a 32-byte hash; 255 is the largest
 191  	// representable value and costs at most one extra unary bit.
 192  	if p > 255 {
 193  		p = 255
 194  	}
 195  	return uint8(p)
 196  }
 197  
 198  // Marshal encodes the set.
 199  func (s *Set) Marshal() ([]byte, error) {
 200  	if s == nil {
 201  		return nil, fmt.Errorf("gcs: nil set")
 202  	}
 203  	if s.HashWidth > MaxHashWidth {
 204  		return nil, fmt.Errorf("gcs: hash width %d out of range", s.HashWidth)
 205  	}
 206  	buf := make([]byte, 0, 4+1+1+1+8+2+len(s.Asset)+1+len(s.values)*int(s.P+2)/8)
 207  	buf = append(buf, Magic...)
 208  	buf = append(buf, Version)
 209  	buf = append(buf, ModeExact)
 210  	buf = append(buf, byte(s.HashWidth))
 211  	var n [8]byte
 212  	binary.BigEndian.PutUint64(n[:], s.N)
 213  	buf = append(buf, n[:]...)
 214  	var al [2]byte
 215  	binary.BigEndian.PutUint16(al[:], uint16(len(s.Asset)))
 216  	buf = append(buf, al[:]...)
 217  	buf = append(buf, s.Asset...)
 218  	p := riceParameter(s.HashWidth, s.N)
 219  	buf = append(buf, p)
 220  	w := newBitWriter()
 221  	prev := new(big.Int)
 222  	for _, v := range s.values {
 223  		cur := new(big.Int).SetBytes(v)
 224  		delta := new(big.Int).Sub(cur, prev)
 225  		writeRice(w, delta, int(p))
 226  		prev = cur
 227  	}
 228  	return append(buf, w.flush()...), nil
 229  }
 230  
 231  // Parse decodes and validates a full set blob.
 232  func Parse(b []byte) (*Set, error) {
 233  	if len(b) < 4+1+1+1+8 {
 234  		return nil, fmt.Errorf("gcs: blob too short")
 235  	}
 236  	if string(b[:4]) != Magic {
 237  		return nil, fmt.Errorf("gcs: bad magic")
 238  	}
 239  	if b[4] != Version {
 240  		return nil, fmt.Errorf("gcs: unsupported version %d", b[4])
 241  	}
 242  	if b[5] != ModeExact {
 243  		return nil, fmt.Errorf("gcs: unsupported mode %d (mode %d is not usable for gating)", b[5], b[5])
 244  	}
 245  	hashWidth := int(b[6])
 246  	if hashWidth <= 0 || hashWidth > MaxHashWidth {
 247  		return nil, fmt.Errorf("gcs: hash width %d out of range", hashWidth)
 248  	}
 249  	n := binary.BigEndian.Uint64(b[7:15])
 250  	if n > MaxElements {
 251  		return nil, fmt.Errorf("gcs: %d elements exceeds the limit", n)
 252  	}
 253  	off := 15
 254  	if len(b) < off+2 {
 255  		return nil, fmt.Errorf("gcs: truncated address length")
 256  	}
 257  	alen := int(binary.BigEndian.Uint16(b[off : off+2]))
 258  	off += 2
 259  	if alen == 0 || len(b) < off+alen+1 {
 260  		return nil, fmt.Errorf("gcs: truncated address")
 261  	}
 262  	asset := string(b[off : off+alen])
 263  	off += alen
 264  	p := b[off]
 265  	off++
 266  	if want := riceParameter(hashWidth, n); p != want {
 267  		return nil, fmt.Errorf("gcs: stored Rice parameter %d does not match derived %d", p, want)
 268  	}
 269  
 270  	r := newBitReader(b[off:])
 271  	values := make([][]byte, 0, n)
 272  	cur := new(big.Int)
 273  	limit := new(big.Int).Lsh(big.NewInt(1), uint(8*hashWidth))
 274  	for i := uint64(0); i < n; i++ {
 275  		d, err := readRice(r, int(p))
 276  		if err != nil {
 277  			return nil, fmt.Errorf("gcs: element %d: %w", i, err)
 278  		}
 279  		cur = new(big.Int).Add(cur, d)
 280  		if cur.Cmp(limit) >= 0 {
 281  			return nil, fmt.Errorf("gcs: element %d exceeds the hash width", i)
 282  		}
 283  		v, err := leftPad(cur.Bytes(), hashWidth)
 284  		if err != nil {
 285  			return nil, err
 286  		}
 287  		if len(values) > 0 && bytes.Compare(values[len(values)-1], v) >= 0 {
 288  			return nil, fmt.Errorf("gcs: values are not strictly ascending at element %d", i)
 289  		}
 290  		values = append(values, v)
 291  	}
 292  	return &Set{Asset: asset, HashWidth: hashWidth, N: n, P: p, values: values}, nil
 293  }
 294  
 295  // BuildDelta encodes the elements to add on top of a base set. baseX is the
 296  // parent set blob's SHA-256.
 297  func BuildDelta(baseX []byte, base *Set, added [][]byte) ([]byte, error) {
 298  	if len(baseX) != 32 {
 299  		return nil, fmt.Errorf("gcs: base x must be 32 bytes")
 300  	}
 301  	if base == nil {
 302  		return nil, fmt.Errorf("gcs: delta needs a base")
 303  	}
 304  	have := make(map[string]struct{}, len(base.values))
 305  	for _, v := range base.values {
 306  		have[string(v)] = struct{}{}
 307  	}
 308  	seen := make(map[string]struct{}, len(added))
 309  	values := make([][]byte, 0, len(added))
 310  	for _, pk := range added {
 311  		e := Element(pk, base.HashWidth)
 312  		k := string(e)
 313  		if _, ok := have[k]; ok {
 314  			continue
 315  		}
 316  		if _, ok := seen[k]; ok {
 317  			continue
 318  		}
 319  		seen[k] = struct{}{}
 320  		values = append(values, e)
 321  	}
 322  	sort.Slice(values, func(i, j int) bool { return bytes.Compare(values[i], values[j]) < 0 })
 323  
 324  	buf := make([]byte, 0, 4+1+32+1+8+1+len(values)*(int(riceParameter(base.HashWidth, uint64(len(values))))+2)/8)
 325  	buf = append(buf, DeltaMagic...)
 326  	buf = append(buf, Version)
 327  	buf = append(buf, baseX...)
 328  	buf = append(buf, byte(base.HashWidth))
 329  	var n [8]byte
 330  	binary.BigEndian.PutUint64(n[:], uint64(len(values)))
 331  	buf = append(buf, n[:]...)
 332  	p := riceParameter(base.HashWidth, uint64(len(values)))
 333  	buf = append(buf, p)
 334  	w := newBitWriter()
 335  	prev := new(big.Int)
 336  	for _, v := range values {
 337  		cur := new(big.Int).SetBytes(v)
 338  		writeRice(w, new(big.Int).Sub(cur, prev), int(p))
 339  		prev = cur
 340  	}
 341  	return append(buf, w.flush()...), nil
 342  }
 343  
 344  // ApplyDelta decodes a delta blob and returns the added element hashes. The
 345  // caller checks the base x and merges with Set.Rebuild.
 346  func ApplyDelta(base *Set, delta []byte) (added [][]byte, err error) {
 347  	if len(delta) < 4+1+32+1+8+1 {
 348  		return nil, fmt.Errorf("gcs: delta too short")
 349  	}
 350  	if string(delta[:4]) != DeltaMagic {
 351  		return nil, fmt.Errorf("gcs: bad delta magic")
 352  	}
 353  	if delta[4] != Version {
 354  		return nil, fmt.Errorf("gcs: unsupported delta version %d", delta[4])
 355  	}
 356  	baseX := delta[5:37]
 357  	_ = baseX
 358  	hashWidth := int(delta[37])
 359  	if base != nil && hashWidth != base.HashWidth {
 360  		return nil, fmt.Errorf("gcs: delta hash width %d does not match the base %d", hashWidth, base.HashWidth)
 361  	}
 362  	if hashWidth <= 0 || hashWidth > MaxHashWidth {
 363  		return nil, fmt.Errorf("gcs: delta hash width out of range")
 364  	}
 365  	n := binary.BigEndian.Uint64(delta[38:46])
 366  	if n > MaxElements {
 367  		return nil, fmt.Errorf("gcs: delta element count exceeds the limit")
 368  	}
 369  	p := delta[46]
 370  	if want := riceParameter(hashWidth, n); p != want {
 371  		return nil, fmt.Errorf("gcs: delta Rice parameter does not match the element count")
 372  	}
 373  	r := newBitReader(delta[47:])
 374  	cur := new(big.Int)
 375  	limit := new(big.Int).Lsh(big.NewInt(1), uint(8*hashWidth))
 376  	added = make([][]byte, 0, n)
 377  	for i := uint64(0); i < n; i++ {
 378  		d, err := readRice(r, int(p))
 379  		if err != nil {
 380  			return nil, err
 381  		}
 382  		cur = new(big.Int).Add(cur, d)
 383  		if cur.Cmp(limit) >= 0 {
 384  			return nil, fmt.Errorf("gcs: delta element exceeds the hash width")
 385  		}
 386  		v, err := leftPad(cur.Bytes(), hashWidth)
 387  		if err != nil {
 388  			return nil, err
 389  		}
 390  		added = append(added, v)
 391  	}
 392  	return added, nil
 393  }
 394  
 395  // DeltaBaseX returns the parent hash a delta names.
 396  func DeltaBaseX(delta []byte) ([]byte, error) {
 397  	if len(delta) < 37 || string(delta[:4]) != DeltaMagic {
 398  		return nil, fmt.Errorf("gcs: not a delta blob")
 399  	}
 400  	out := make([]byte, 32)
 401  	copy(out, delta[5:37])
 402  	return out, nil
 403  }
 404  
 405  func leftPad(b []byte, width int) ([]byte, error) {
 406  	if len(b) > width {
 407  		return nil, fmt.Errorf("gcs: value is wider than the hash width")
 408  	}
 409  	out := make([]byte, width)
 410  	copy(out[width-len(b):], b)
 411  	return out, nil
 412  }
 413  
 414  // --- Rice coding ---------------------------------------------------------
 415  
 416  func writeRice(w *bitWriter, delta *big.Int, p int) {
 417  	q := new(big.Int).Rsh(delta, uint(p))
 418  	// Unary: q zero bits then a one. The expected q is small because p is
 419  	// derived from n and the hash width, but a set with a huge first value can
 420  	// still produce a large q; the writer has no reason to bound it.
 421  	qi := q.Uint64()
 422  	for i := uint64(0); i < qi; i++ {
 423  		w.bit(false)
 424  	}
 425  	w.bit(true)
 426  	rem := new(big.Int).And(delta, new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), uint(p)), big.NewInt(1)))
 427  	for i := p - 1; i >= 0; i-- {
 428  		w.bit(rem.Bit(i) == 1)
 429  	}
 430  }
 431  
 432  func readRice(r *bitReader, p int) (*big.Int, error) {
 433  	var q uint64
 434  	for {
 435  		b, err := r.bit()
 436  		if err != nil {
 437  			return nil, err
 438  		}
 439  		if b {
 440  			break
 441  		}
 442  		q++
 443  		if q > maxQuotient {
 444  			return nil, fmt.Errorf("gcs: unary quotient exceeds the limit")
 445  		}
 446  	}
 447  	rem := new(big.Int)
 448  	for i := 0; i < p; i++ {
 449  		b, err := r.bit()
 450  		if err != nil {
 451  			return nil, err
 452  		}
 453  		rem.Lsh(rem, 1)
 454  		if b {
 455  			rem.SetBit(rem, 0, 1)
 456  		}
 457  	}
 458  	out := new(big.Int).Lsh(new(big.Int).SetUint64(q), uint(p))
 459  	return out.Add(out, rem), nil
 460  }
 461  
 462  type bitWriter struct {
 463  	buf []byte
 464  	cur byte
 465  	n   uint
 466  }
 467  
 468  func newBitWriter() *bitWriter { return &bitWriter{} }
 469  
 470  func (w *bitWriter) bit(set bool) {
 471  	if set {
 472  		w.cur |= 1 << (7 - w.n)
 473  	}
 474  	w.n++
 475  	if w.n == 8 {
 476  		w.buf = append(w.buf, w.cur)
 477  		w.cur = 0
 478  		w.n = 0
 479  	}
 480  }
 481  
 482  func (w *bitWriter) flush() []byte {
 483  	if w.n > 0 {
 484  		w.buf = append(w.buf, w.cur)
 485  		w.cur = 0
 486  		w.n = 0
 487  	}
 488  	return w.buf
 489  }
 490  
 491  type bitReader struct {
 492  	buf []byte
 493  	pos int
 494  }
 495  
 496  func newBitReader(b []byte) *bitReader { return &bitReader{buf: b} }
 497  
 498  func (r *bitReader) bit() (bool, error) {
 499  	if r.pos >= len(r.buf)*8 {
 500  		return false, fmt.Errorf("gcs: unexpected end of bit stream")
 501  	}
 502  	byteIdx := r.pos / 8
 503  	bitIdx := uint(r.pos % 8)
 504  	r.pos++
 505  	return r.buf[byteIdx]&(1<<(7-bitIdx)) != 0, nil
 506  }
 507  
 508  // MergeHashes returns a new set containing the base values plus the supplied
 509  // element hashes. It is the delta-apply path: ApplyDelta decodes hashes, and
 510  // MergeHashes folds them in without re-hashing.
 511  func MergeHashes(base *Set, added [][]byte) (*Set, error) {
 512  	if base == nil {
 513  		return nil, fmt.Errorf("gcs: merge needs a base")
 514  	}
 515  	seen := make(map[string]struct{}, len(base.values)+len(added))
 516  	values := make([][]byte, 0, len(base.values)+len(added))
 517  	for _, v := range base.values {
 518  		k := string(v)
 519  		if _, ok := seen[k]; ok {
 520  			continue
 521  		}
 522  		seen[k] = struct{}{}
 523  		values = append(values, v)
 524  	}
 525  	for _, v := range added {
 526  		if len(v) != base.HashWidth {
 527  			return nil, fmt.Errorf("gcs: merged element has the wrong width")
 528  		}
 529  		k := string(v)
 530  		if _, ok := seen[k]; ok {
 531  			continue
 532  		}
 533  		seen[k] = struct{}{}
 534  		values = append(values, v)
 535  	}
 536  	sort.Slice(values, func(i, j int) bool { return bytes.Compare(values[i], values[j]) < 0 })
 537  	out := &Set{Asset: base.Asset, HashWidth: base.HashWidth, N: uint64(len(values)), values: values}
 538  	out.P = riceParameter(out.HashWidth, out.N)
 539  	return out, nil
 540  }
 541