123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493(*****************************************************************************)(* Open Source License *)(* Copyright (c) 2020-2021 Nomadic Labs, <contact@nomadic-labs.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)type'at={hash:'a->bytes;(** Cryptographically secure hash function. We must have
[Bytes.length (hash x) >= index_bits * hashes]. *)hashes:int;(** The value returned by [hash] is split and converted in
[hashes] indices, each [index_bits] wide. *)index_bits:int;(** [index_bits] is the width in bits of the indices into
the [filter]. *)countdown_bits:int;(** [countdown_bits] is the width in bits of the counter cells
stored in the [filter]. *)filter:bytes;(** [filter] stores [2^index_bits] counter cells,
each [countdown_bits] wide. *)count:intarray;(** [count] stores approximate statistics on the number of counter cells
with a given value. [count.(i)] is the approximate number of cells
equal to [2^countdown_bits - 1 - i].
Note that this field is not required for Bloom filter operation. *)}letsf=Printf.sprintfletcheck_peek_poke_argsfnamebytesofsbits=ifbits<=0theninvalid_arg(sf"Bloomer.%s: non positive bits value"fname);ifofs<0theninvalid_arg(sf"Bloomer.%s: negative offset"fname);ifbits>Sys.int_size-7theninvalid_arg(sf"Bloomer.%s: indexes out of bounds"fname);ifbits+ofs>Bytes.lengthbytes*8theninvalid_arg(sf"Bloomer.%s: indexes out of bounds"fname)(* Read [bits] bits of [bytes] at offset [ofs] as an OCaml int in big endian order.
The function proceeds by iteratively blitting the bytes overlapping the sought
bit interval into [v]. The superfluous bits at the beginning and at the end
are then removed from [v], yielding the returned value.
*)letpeek_unsafebytesofsbits=letfirst=ofs/8inletlast=first+(((ofsmod8)+bits+7)/8)inletv=ref0infori=last-1downtofirstdov:=(!vlsl8)lorChar.code(Bytes.getbytesi)done;v:=!vlsr(ofsmod8);v:=!vland((1lslbits)-1);!vletpeekbytesofsbits=check_peek_poke_args"peek"bytesofsbits;peek_unsafebytesofsbits(* blits [bits] bits of [bytes] at offset [ofs] from an OCaml int in big endian order *)letpoke_unsafebytesofsbitsv=letfirst=ofs/8inletlast=first+(((ofsmod8)+bits+7)/8)inletcur=ref0infori=last-1downtofirstdocur:=(!curlsl8)lorChar.code(Bytes.getbytesi)done;letmask=lnot(((1lslbits)-1)lsl(ofsmod8))inletv=!curlandmasklor(vlsl(ofsmod8))infori=firsttolast-1doBytes.setbytesi(Char.chr((vlsr((i-first)*8))land0xFF))doneletpokebytesofsbitsv=ifvlsrbits<>0theninvalid_arg"Bloomer.poke: value too large";check_peek_poke_args"poke"bytesofsbits;poke_unsafebytesofsbitsvlet%test_unit"random_read_writes"=letbytes_length=45inletbit_length=bytes_length*8in(* max_data_bit_width = 29 to to stay within Random.int bounds.
int_size - 7 to stay within [check_peek_poke_args] domain. *)letmax_data_bit_width=min29(Sys.int_size-7)inletbytes=Bytes.make45'\000'inletpoke_et_peekofslenv=pokebytesofslenv;assert(peekbytesofslen=v)infor_=0to100_000doletofs=Random.int(bit_length-max_data_bit_width)inletlen=Random.intmax_data_bit_width+1inletv=Random.int(1lsllen)inpoke_et_peekofslenvdone;poke_et_peek350100x3FF;poke_et_peek35550x1F;poke_et_peek350100;poke_et_peek35550;trypoke_et_peek35560;assertfalsewith_->()let%test_unit"peek and poke work with bits = [1 .. Sys.int_size - 7]"=letfail_or_successf=tryf();truewith_->falseinletbytes=Bytes.make45'\000'in(* we ignore len = 0, the implementation would accepts it but check_peek_poke_args is more strict. *)forlen=1toSys.int_sizedoletints=List.init400(fun_->Int64.(to_int(Random.int64(sub(shift_leftonelen)one))))inletunsafe_result=fail_or_success(fun()->(* we want to test the property regardless of the offset, we test all possible offset (mod 8) *)forofs=8to16doList.iter(funv->poke_unsafebytesofslenv;assert(peek_unsafebytesofslen=v))intsdone)inletcheck_result=fail_or_success(fun()->(* we want to test the property regardless of the offset, we test all possible offset (mod 8) *)forofs=8to16doList.iter(funv->ifvlsrlen<>0theninvalid_arg"Bloomer.poke: value too large";check_peek_poke_args"unti-test"bytesofslen)intsdone)inassert(unsafe_result=check_result)donelet%test_unit"sequential_read_writes"=letbytes=Bytes.make45'\000'inletbits=Bytes.lengthbytes*8in(* max_data_bit_width = 29 to stay within Random.int bounds.
int_size - 7 to stay within [check_peek_poke_args] domain. *)letmax_data_bit_width=min29(Sys.int_size-7)infor_=0to10_000doletrecinitofsacc=ifofs>=bitsthenList.revaccelseletlen=min(Random.intmax_data_bit_width+1)(bits-ofs)inletv=Random.int(1lsllen)inpokebytesofslenv;assert(peekbytesofslen=v);init(ofs+len)((ofs,len,v)::acc)inList.iter(fun(ofs,len,v)->assert(peekbytesofslen=v))(init0[])donelet%test_unit"read_over_write"=(* Check that non-overlapping writes really do not overlap. *)letbytes=Bytes.make45'\000'inletbits=Bytes.lengthbytes*8inletrandom_disjoint_writes()=letwidth=1lslRandom.int3inletindices=bits/widthinleti1=Random.intindicesinleti2=(i1+1+Random.int(indices-1))modindicesinleti1=i1*widthinleti2=i2*widthinassert(i1<>i2);letv1=Random.int(1lslwidth)inletv2=Random.int(1lslwidth)inpokebytesi1widthv1;pokebytesi2widthv2;assert(peekbytesi1width=v1)infor_=0to10_000dorandom_disjoint_writes()doneletcreate~hash~hashes~index_bits~countdown_bits=(* We constrain [index_bits] and [countdown_bits] to a maximum of 24. This is
because [peek] and [poke] operate on ints with size [1 .. int_size - 7]
and we want to stay compatible with 32bit arch (e.g. JavaScript).
31 (int_size on 32bit) - 7 = 24
*)ifindex_bits<=0||index_bits>24theninvalid_arg"Bloomer.create: invalid value for index_bits";ifcountdown_bits<=0||countdown_bits>24theninvalid_arg"Bloomer.create: invalid value for countdown_bits";letfilter=Bytes.make((((1lslindex_bits)*countdown_bits)+7)/8)'\000'inletcount=Array.make((1lslcountdown_bits)-1)0in{hash;hashes;index_bits;countdown_bits;filter;count}letmem{hash;hashes;index_bits;countdown_bits;filter;_}x=leth=hashxintryfori=0tohashes-1doletj=peekh(index_bits*i)index_bitsinifpeekfilter(j*countdown_bits)countdown_bits=0thenraiseExitdone;truewithExit->falseletadd{hash;hashes;index_bits;countdown_bits;filter;count}x=count.(0)<-count.(0)+1;leth=hashxinfori=0tohashes-1doletj=peekh(index_bits*i)index_bitsinpokefilter(j*countdown_bits)countdown_bits((1lslcountdown_bits)-1)doneletrem{hash;hashes;index_bits;countdown_bits;filter;_}x=leth=hashxinfori=0tohashes-1doletj=peekh(index_bits*i)index_bitsinpokefilter(j*countdown_bits)countdown_bits0doneletcountdown{hash=_;hashes=_;index_bits;countdown_bits;filter;count}=fori=Array.lengthcount-1downto1docount.(i)<-count.(i-1)done;count.(0)<-0;forj=0to(1lslindex_bits)-1doletcur=peekfilter(j*countdown_bits)countdown_bitsinifcur>0thenpokefilter(j*countdown_bits)countdown_bits(cur-1)doneletclear{hash=_;hashes=_;index_bits=_;countdown_bits=_;filter;count}=Array.fillcount0(Array.lengthcount)0;Bytes.fillfilter0(Bytes.lengthfilter)'\000'letfill_percentage{hash=_;hashes=_;index_bits;countdown_bits;filter;_}=lettotal=float(1lslindex_bits)inletnonzero=ref0inforj=0to(1lslindex_bits)-1doletcur=peekfilter(j*countdown_bits)countdown_bitsinifcur>0thenincrnonzerodone;float!nonzero/.totalletlife_expectancy_histogram{hash=_;hashes=_;index_bits;countdown_bits;filter;_}=lethist_table=Array.make(1lslcountdown_bits)0inforj=0to(1lslindex_bits)-1doletcur=peekfilter(j*countdown_bits)countdown_bitsinhist_table.(cur)<-hist_table.(cur)+1done;hist_tableletapprox_count{count;_}=Array.fold_left(+)0countlet%test_unit"consistent_add_mem_countdown"=for_=0to100doletindex_bits=Random.int16+1inlethashes=Random.int7+1inletcountdown_bits=Random.int5+1inlethashv=Bytes.init(((hashes*index_bits)+7)/8)(funi->Char.chr(Hashtbl.hash(v,i)mod256))inletbloomer=create~hash~index_bits~hashes~countdown_bitsinletrecinitnacc=ifn=0thenaccelseletx=Random.int(1lsl29)inaddbloomerx;assert(membloomerx);init(n-1)(x::acc)inletall=init1000[]infor_=0to(1lslcountdown_bits)-2doList.iter(funx->assert(membloomerx))all;countdownbloomerdone;List.iter(funx->assert(not(membloomerx)))alldonelet%test_unit"consistent_add_countdown_count"=letmoduleSet=Hashtbl.Make(structincludeIntlethash=Hashtbl.hashend)infor_=0to100doletindex_bits=16inlethashes=Random.int7+1inletcountdown_bits=Random.int5+1inletset=Set.create100inlethashv=Bytes.init(((hashes*index_bits)+7)/8)(funi->Char.chr(Hashtbl.hash(v,i)mod256))inletbloomer=create~hash~index_bits~hashes~countdown_bitsinletnext_ref=ref0inletnext()=incrnext_ref;!next_refinletactual_set()=List.filter(membloomer)(List.of_seq@@Set.to_seq_keysset)inletrecinit_stepnacc=ifn=0thenaccelseletx=next()inaddbloomerx;assert(membloomerx);Set.addsetx();init_step(n-1)(1+acc)inletrecinitnstopcounts=ifn=stopthencountselseletapprox_counted=approx_countbloomerinletaccurate_count=List.length@@actual_set()inletcount=Random.int10inletadded=init_stepcount0inassert(added=count);countdownbloomer;init(n+1)stop((approx_counted,accurate_count)::counts)inletall=init0((1lslcountdown_bits)+30)[]inList.iter(fun(approx,accurate)->assert(approx=accurate))all;clearbloomer;assert(approx_countbloomer=0)donelet%test_unit"false_positive_rate"=(* We acknowledge the results published in "On the false-positive
rate of Bloom filters" (Information Processing Letters, volume
108, issue 4, 2008, pages 210-213) stating that the model formula
below is wrong.
However, we still use the original approximation made by Bloom to
check the behaviour of this implementation, as it is close enough
for security yet much simpler to compute. *)letruns=[|(18,4);(18,6);(18,8);(18,10);(20,2);(20,4);(20,6);(20,8);(20,9);(20,10);(20,11);(20,12);(20,13);(20,14);(21,2);(21,3);(21,4);(21,5);(22,2);(22,3);(22,4);(22,5);(22,6);(22,8);|]inletsteps=995inletinit_samples=5_000inletsamples_per_step=1_000inletdata=Array.map(fun(index_bits,hashes)->letcountdown_bits=1inlethashv=Bytes.init(((hashes*index_bits)+7)/8)(funi->Char.chr(Hashtbl.hash(v,i)mod256))inletbloomer=create~hash~index_bits~hashes~countdown_bitsinlet(add,cur)=letcur=ref0in((funn->for_=1tondoaddbloomer!cur;incrcurdone),fun()->!cur)inaddinit_samples;(float(Bytes.lengthbloomer.filter)/.1024.,index_bits,hashes,Array.initsteps@@funi->addsamples_per_step;letn=init_samples+((i+1)*samples_per_step)inletexpected_fp_proba=lete=2.718281828459045in(1.-.(e**(-.floathashes*.floatn/.float(1lslindex_bits))))**floathashesinletactual_proba=letfalses=ref0inforj=1to500doifmembloomer(cur()+j)thenincrfalsesdone;float!falses/.500.in(ifabs_float(expected_fp_proba-.actual_proba)>=0.1thenletmessage=Format.asprintf"wrong false positive rate for n=%d, m=%d,k=%d, expected %g, \
got %g"n(1lslindex_bits)hashesexpected_fp_probaactual_probainfailwithmessage);(expected_fp_proba,actual_proba)))runsinmatchSys.getenv_opt"BLOOMER_TEST_GNUPLOT_PATH"with|Somepath->forrun=0toArray.lengthruns-1dolet(kb,index_bits,hashes,values)=data.(run)in(letfp=open_out(Format.asprintf"%s/run_%02d.plot"pathrun)inPrintf.fprintffp"set title 'false positive rate (bits=%d (%g KiB), hashes=%d)'\n%!"(1lslindex_bits)kbhashes;Printf.fprintffp"set xlabel 'insertions'\n";Printf.fprintffp"set ylabel 'rate'\n";Printf.fprintffp"set yrange [0:1]\n";Printf.fprintffp"set terminal 'png' size 800,600\n";Printf.fprintffp"set output 'run_%02d.png'\n"run;Printf.fprintffp"plot 'run_%02d.dat' using 1:2 title 'expected', 'run_%02d.dat' \
using 1:3 title 'obtained'\n\
%!"runrun;close_outfp);letfp=open_out(Format.asprintf"%s/run_%02d.dat"pathrun)inforstep=0tosteps-1doPrintf.fprintffp"%d %f %f\n"(init_samples+(step*samples_per_step))(fstvalues.(step))(sndvalues.(step))done;flushfp;close_outfpdone|None->Format.eprintf"Set the BLOOMER_TEST_GNUPLOT_PATH to a directory to get some human \
readable test results."