// Package gcs implements the exact Golomb-coded membership set that gates paid // musiquay assets. // // The set is exact: a non-member is never matched, because membership is a // binary search over the stored hashes, not a probabilistic probe. A filter // collision would require a SHA-256 collision. There is deliberately no Bloom // or Cuckoo variant in the gate path. // // Blob layout (all integers big-endian, bits within a byte MSB first): // // magic "MQG1" | version | mode | hash width | n (8) | address len (2) | address // | Rice parameter p | Golomb-coded sorted deltas // // A delta blob adds only elements: // // magic "MQD1" | version | base x (32) | hash width | n_delta (8) | p // | Golomb-coded sorted deltas of added elements package gcs import ( "bytes" "crypto/sha256" "encoding/binary" "fmt" "math/big" "sort" ) // Magic and format constants. const ( // Magic is the full-set magic. Magic = "MQG1" // DeltaMagic is the delta-set magic. DeltaMagic = "MQD1" // Version is the only supported format version. Version = 1 // ModeExact is the only mode usable for gating. ModeGCSMod is reserved for // the probabilistic variant and is rejected. ModeExact = 0 // Domain is the element hash domain separator. Domain = "musiquay.filter.v1" // MaxHashWidth is the largest element width the format allows. MaxHashWidth = 32 // MaxElements bounds a parse, so a hostile blob cannot exhaust memory. MaxElements = 10_000_000 // maxQuotient bounds the unary part of one code, so a corrupt blob cannot // make the decoder read gigabytes of zeros. maxQuotient = 1 << 24 ) // Element hashes a pubkey into the set's domain. func Element(pubkey []byte, hashWidth int) []byte { h := sha256.New() h.Write([]byte(Domain)) h.Write([]byte("|")) h.Write(pubkey) sum := h.Sum(nil) if hashWidth <= 0 || hashWidth > len(sum) { hashWidth = 32 } return sum[:hashWidth] } // Set is an exact sorted membership set for one asset address. type Set struct { // Asset is the address the set is bound to. Asset string // HashWidth is the element width in bytes. HashWidth int // N is the element count. N uint64 // P is the Rice parameter stored in the blob. P uint8 // values are the sorted, truncated element hashes. values [][]byte } // Build constructs a set from pubkeys. Duplicate pubkeys collapse, so a // republished set with a repeated element is byte-identical. func Build(asset string, pubkeys [][]byte, hashWidth int) (*Set, error) { if asset == "" { return nil, fmt.Errorf("gcs: empty asset address") } if hashWidth <= 0 || hashWidth > MaxHashWidth { return nil, fmt.Errorf("gcs: hash width %d out of range", hashWidth) } if len(pubkeys) > MaxElements { return nil, fmt.Errorf("gcs: too many elements") } seen := make(map[string]struct{}, len(pubkeys)) values := make([][]byte, 0, len(pubkeys)) for _, pk := range pubkeys { e := Element(pk, hashWidth) k := string(e) if _, ok := seen[k]; ok { continue } seen[k] = struct{}{} values = append(values, e) } sort.Slice(values, func(i, j int) bool { return bytes.Compare(values[i], values[j]) < 0 }) s := &Set{Asset: asset, HashWidth: hashWidth, N: uint64(len(values)), values: values} s.P = riceParameter(hashWidth, s.N) return s, nil } // contains reports membership by exact search. func (s *Set) Contains(pubkey []byte) bool { if s == nil { return false } e := Element(pubkey, s.HashWidth) i := sort.Search(len(s.values), func(i int) bool { return bytes.Compare(s.values[i], e) >= 0 }) return i < len(s.values) && bytes.Equal(s.values[i], e) } // Len returns the element count. func (s *Set) Len() int { if s == nil { return 0 } return len(s.values) } // Rebuild returns a new set with additions and, optionally, removals. GCS has // no in-place mutation, so a rebuild re-encodes from scratch. // // Ownership sets must never remove: the caller enforces that by passing an // empty remove list. Subscriptions remove at rebuild by passing the lapsed keys. func (s *Set) Rebuild(asset string, add, remove [][]byte) (*Set, error) { if s == nil { return Build(asset, add, 32) } if asset == "" { asset = s.Asset } drop := make(map[string]struct{}, len(remove)) for _, pk := range remove { drop[string(Element(pk, s.HashWidth))] = struct{}{} } seen := make(map[string]struct{}, len(s.values)+len(add)) keys := make([][]byte, 0, len(s.values)+len(add)) for _, v := range s.values { k := string(v) if _, gone := drop[k]; gone { continue } if _, ok := seen[k]; ok { continue } seen[k] = struct{}{} keys = append(keys, v) } for _, pk := range add { e := Element(pk, s.HashWidth) k := string(e) if _, gone := drop[k]; gone { continue } if _, ok := seen[k]; ok { continue } seen[k] = struct{}{} keys = append(keys, e) } sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i], keys[j]) < 0 }) out := &Set{Asset: asset, HashWidth: s.HashWidth, N: uint64(len(keys)), values: keys} out.P = riceParameter(out.HashWidth, out.N) return out, nil } // riceParameter derives p = max(1, ceil(log2(2^(8*hash)/n))). func riceParameter(hashWidth int, n uint64) uint8 { if n == 0 { return 1 } // floor(log2(n)) floor := 0 for v := n; v > 1; v >>= 1 { floor++ } p := 8*hashWidth - floor if p < 1 { p = 1 } // The parameter is stored in one byte. For a single element the formula // reaches 8*hash, which is 256 for a 32-byte hash; 255 is the largest // representable value and costs at most one extra unary bit. if p > 255 { p = 255 } return uint8(p) } // Marshal encodes the set. func (s *Set) Marshal() ([]byte, error) { if s == nil { return nil, fmt.Errorf("gcs: nil set") } if s.HashWidth > MaxHashWidth { return nil, fmt.Errorf("gcs: hash width %d out of range", s.HashWidth) } buf := make([]byte, 0, 4+1+1+1+8+2+len(s.Asset)+1+len(s.values)*int(s.P+2)/8) buf = append(buf, Magic...) buf = append(buf, Version) buf = append(buf, ModeExact) buf = append(buf, byte(s.HashWidth)) var n [8]byte binary.BigEndian.PutUint64(n[:], s.N) buf = append(buf, n[:]...) var al [2]byte binary.BigEndian.PutUint16(al[:], uint16(len(s.Asset))) buf = append(buf, al[:]...) buf = append(buf, s.Asset...) p := riceParameter(s.HashWidth, s.N) buf = append(buf, p) w := newBitWriter() prev := new(big.Int) for _, v := range s.values { cur := new(big.Int).SetBytes(v) delta := new(big.Int).Sub(cur, prev) writeRice(w, delta, int(p)) prev = cur } return append(buf, w.flush()...), nil } // Parse decodes and validates a full set blob. func Parse(b []byte) (*Set, error) { if len(b) < 4+1+1+1+8 { return nil, fmt.Errorf("gcs: blob too short") } if string(b[:4]) != Magic { return nil, fmt.Errorf("gcs: bad magic") } if b[4] != Version { return nil, fmt.Errorf("gcs: unsupported version %d", b[4]) } if b[5] != ModeExact { return nil, fmt.Errorf("gcs: unsupported mode %d (mode %d is not usable for gating)", b[5], b[5]) } hashWidth := int(b[6]) if hashWidth <= 0 || hashWidth > MaxHashWidth { return nil, fmt.Errorf("gcs: hash width %d out of range", hashWidth) } n := binary.BigEndian.Uint64(b[7:15]) if n > MaxElements { return nil, fmt.Errorf("gcs: %d elements exceeds the limit", n) } off := 15 if len(b) < off+2 { return nil, fmt.Errorf("gcs: truncated address length") } alen := int(binary.BigEndian.Uint16(b[off : off+2])) off += 2 if alen == 0 || len(b) < off+alen+1 { return nil, fmt.Errorf("gcs: truncated address") } asset := string(b[off : off+alen]) off += alen p := b[off] off++ if want := riceParameter(hashWidth, n); p != want { return nil, fmt.Errorf("gcs: stored Rice parameter %d does not match derived %d", p, want) } r := newBitReader(b[off:]) values := make([][]byte, 0, n) cur := new(big.Int) limit := new(big.Int).Lsh(big.NewInt(1), uint(8*hashWidth)) for i := uint64(0); i < n; i++ { d, err := readRice(r, int(p)) if err != nil { return nil, fmt.Errorf("gcs: element %d: %w", i, err) } cur = new(big.Int).Add(cur, d) if cur.Cmp(limit) >= 0 { return nil, fmt.Errorf("gcs: element %d exceeds the hash width", i) } v, err := leftPad(cur.Bytes(), hashWidth) if err != nil { return nil, err } if len(values) > 0 && bytes.Compare(values[len(values)-1], v) >= 0 { return nil, fmt.Errorf("gcs: values are not strictly ascending at element %d", i) } values = append(values, v) } return &Set{Asset: asset, HashWidth: hashWidth, N: n, P: p, values: values}, nil } // BuildDelta encodes the elements to add on top of a base set. baseX is the // parent set blob's SHA-256. func BuildDelta(baseX []byte, base *Set, added [][]byte) ([]byte, error) { if len(baseX) != 32 { return nil, fmt.Errorf("gcs: base x must be 32 bytes") } if base == nil { return nil, fmt.Errorf("gcs: delta needs a base") } have := make(map[string]struct{}, len(base.values)) for _, v := range base.values { have[string(v)] = struct{}{} } seen := make(map[string]struct{}, len(added)) values := make([][]byte, 0, len(added)) for _, pk := range added { e := Element(pk, base.HashWidth) k := string(e) if _, ok := have[k]; ok { continue } if _, ok := seen[k]; ok { continue } seen[k] = struct{}{} values = append(values, e) } sort.Slice(values, func(i, j int) bool { return bytes.Compare(values[i], values[j]) < 0 }) buf := make([]byte, 0, 4+1+32+1+8+1+len(values)*(int(riceParameter(base.HashWidth, uint64(len(values))))+2)/8) buf = append(buf, DeltaMagic...) buf = append(buf, Version) buf = append(buf, baseX...) buf = append(buf, byte(base.HashWidth)) var n [8]byte binary.BigEndian.PutUint64(n[:], uint64(len(values))) buf = append(buf, n[:]...) p := riceParameter(base.HashWidth, uint64(len(values))) buf = append(buf, p) w := newBitWriter() prev := new(big.Int) for _, v := range values { cur := new(big.Int).SetBytes(v) writeRice(w, new(big.Int).Sub(cur, prev), int(p)) prev = cur } return append(buf, w.flush()...), nil } // ApplyDelta decodes a delta blob and returns the added element hashes. The // caller checks the base x and merges with Set.Rebuild. func ApplyDelta(base *Set, delta []byte) (added [][]byte, err error) { if len(delta) < 4+1+32+1+8+1 { return nil, fmt.Errorf("gcs: delta too short") } if string(delta[:4]) != DeltaMagic { return nil, fmt.Errorf("gcs: bad delta magic") } if delta[4] != Version { return nil, fmt.Errorf("gcs: unsupported delta version %d", delta[4]) } baseX := delta[5:37] _ = baseX hashWidth := int(delta[37]) if base != nil && hashWidth != base.HashWidth { return nil, fmt.Errorf("gcs: delta hash width %d does not match the base %d", hashWidth, base.HashWidth) } if hashWidth <= 0 || hashWidth > MaxHashWidth { return nil, fmt.Errorf("gcs: delta hash width out of range") } n := binary.BigEndian.Uint64(delta[38:46]) if n > MaxElements { return nil, fmt.Errorf("gcs: delta element count exceeds the limit") } p := delta[46] if want := riceParameter(hashWidth, n); p != want { return nil, fmt.Errorf("gcs: delta Rice parameter does not match the element count") } r := newBitReader(delta[47:]) cur := new(big.Int) limit := new(big.Int).Lsh(big.NewInt(1), uint(8*hashWidth)) added = make([][]byte, 0, n) for i := uint64(0); i < n; i++ { d, err := readRice(r, int(p)) if err != nil { return nil, err } cur = new(big.Int).Add(cur, d) if cur.Cmp(limit) >= 0 { return nil, fmt.Errorf("gcs: delta element exceeds the hash width") } v, err := leftPad(cur.Bytes(), hashWidth) if err != nil { return nil, err } added = append(added, v) } return added, nil } // DeltaBaseX returns the parent hash a delta names. func DeltaBaseX(delta []byte) ([]byte, error) { if len(delta) < 37 || string(delta[:4]) != DeltaMagic { return nil, fmt.Errorf("gcs: not a delta blob") } out := make([]byte, 32) copy(out, delta[5:37]) return out, nil } func leftPad(b []byte, width int) ([]byte, error) { if len(b) > width { return nil, fmt.Errorf("gcs: value is wider than the hash width") } out := make([]byte, width) copy(out[width-len(b):], b) return out, nil } // --- Rice coding --------------------------------------------------------- func writeRice(w *bitWriter, delta *big.Int, p int) { q := new(big.Int).Rsh(delta, uint(p)) // Unary: q zero bits then a one. The expected q is small because p is // derived from n and the hash width, but a set with a huge first value can // still produce a large q; the writer has no reason to bound it. qi := q.Uint64() for i := uint64(0); i < qi; i++ { w.bit(false) } w.bit(true) rem := new(big.Int).And(delta, new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), uint(p)), big.NewInt(1))) for i := p - 1; i >= 0; i-- { w.bit(rem.Bit(i) == 1) } } func readRice(r *bitReader, p int) (*big.Int, error) { var q uint64 for { b, err := r.bit() if err != nil { return nil, err } if b { break } q++ if q > maxQuotient { return nil, fmt.Errorf("gcs: unary quotient exceeds the limit") } } rem := new(big.Int) for i := 0; i < p; i++ { b, err := r.bit() if err != nil { return nil, err } rem.Lsh(rem, 1) if b { rem.SetBit(rem, 0, 1) } } out := new(big.Int).Lsh(new(big.Int).SetUint64(q), uint(p)) return out.Add(out, rem), nil } type bitWriter struct { buf []byte cur byte n uint } func newBitWriter() *bitWriter { return &bitWriter{} } func (w *bitWriter) bit(set bool) { if set { w.cur |= 1 << (7 - w.n) } w.n++ if w.n == 8 { w.buf = append(w.buf, w.cur) w.cur = 0 w.n = 0 } } func (w *bitWriter) flush() []byte { if w.n > 0 { w.buf = append(w.buf, w.cur) w.cur = 0 w.n = 0 } return w.buf } type bitReader struct { buf []byte pos int } func newBitReader(b []byte) *bitReader { return &bitReader{buf: b} } func (r *bitReader) bit() (bool, error) { if r.pos >= len(r.buf)*8 { return false, fmt.Errorf("gcs: unexpected end of bit stream") } byteIdx := r.pos / 8 bitIdx := uint(r.pos % 8) r.pos++ return r.buf[byteIdx]&(1<<(7-bitIdx)) != 0, nil } // MergeHashes returns a new set containing the base values plus the supplied // element hashes. It is the delta-apply path: ApplyDelta decodes hashes, and // MergeHashes folds them in without re-hashing. func MergeHashes(base *Set, added [][]byte) (*Set, error) { if base == nil { return nil, fmt.Errorf("gcs: merge needs a base") } seen := make(map[string]struct{}, len(base.values)+len(added)) values := make([][]byte, 0, len(base.values)+len(added)) for _, v := range base.values { k := string(v) if _, ok := seen[k]; ok { continue } seen[k] = struct{}{} values = append(values, v) } for _, v := range added { if len(v) != base.HashWidth { return nil, fmt.Errorf("gcs: merged element has the wrong width") } k := string(v) if _, ok := seen[k]; ok { continue } seen[k] = struct{}{} values = append(values, v) } sort.Slice(values, func(i, j int) bool { return bytes.Compare(values[i], values[j]) < 0 }) out := &Set{Asset: base.Asset, HashWidth: base.HashWidth, N: uint64(len(values)), values: values} out.P = riceParameter(out.HashWidth, out.N) return out, nil }