github.com/amazechain/amc@v0.1.3/common/types/bloom.go (about) 1 // Copyright 2022 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The AmazeChain library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package types 18 19 import ( 20 "encoding/binary" 21 "fmt" 22 bloomfilter "github.com/holiman/bloomfilter/v2" 23 ) 24 25 // Collide rate 26 const probCollide = 0.0000001 27 28 type hasher []byte 29 30 func (f hasher) Write(p []byte) (n int, err error) { panic("not implemented") } 31 func (f hasher) Sum(b []byte) []byte { panic("not implemented") } 32 func (f hasher) Reset() { panic("not implemented") } 33 func (f hasher) BlockSize() int { panic("not implemented") } 34 func (f hasher) Size() int { return 8 } 35 func (f hasher) Sum64() uint64 { return binary.BigEndian.Uint64(f) } 36 37 type Bloom struct { 38 bloom *bloomfilter.Filter 39 } 40 41 func NewBloom(size uint64) (*Bloom, error) { 42 bloom, err := bloomfilter.NewOptimal(size, probCollide) 43 if err != nil { 44 return nil, err 45 } 46 return &Bloom{bloom: bloom}, nil 47 } 48 49 func (b *Bloom) UnMarshalBloom(data []byte) error { 50 err := b.bloom.UnmarshalBinary(data) 51 return err 52 } 53 54 func (b *Bloom) Add(key []byte) error { 55 if len(key) != HashLength { 56 return fmt.Errorf("key length is not 32 ") 57 } 58 b.bloom.Add(hasher(key)) 59 return nil 60 } 61 62 // Contain 63 // - true maybe in the set 64 // - false must not in the set 65 func (b *Bloom) Contain(key []byte) bool { 66 return b.bloom.Contains(hasher(key)) 67 } 68 69 func (b *Bloom) Marshal() ([]byte, error) { 70 return b.bloom.MarshalBinary() 71 }