-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbloomfilter.py
51 lines (43 loc) · 1.74 KB
/
bloomfilter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from helpers import (
bit_field_to_bytes,
encode_varint,
int_to_little_endian,
murmur3,
)
from network import GenericMessage
BIP37_CONSTANT = 0xfba4c795
class BloomFilter:
def __init__(self, size, function_count, tweak):
self.size = size
self.bit_field = [0] * (size * 8)
self.function_count = function_count
self.tweak = tweak
def add(self, item):
'''Add an item to the filter'''
# iterate self.function_count number of times
for i in range(self.function_count):
# BIP0037 spec seed is i*BIP37_CONSTANT + self.tweak
seed = i * BIP37_CONSTANT + self.tweak
# get the murmur3 hash given that seed
h = murmur3(item, seed=seed)
# set the bit at the hash mod the bitfield size (self.size*8)
bit = h % (self.size * 8)
# set the bit field at bit to be 1
self.bit_field[bit] = 1
def filter_bytes(self):
return bit_field_to_bytes(self.bit_field)
def filterload(self, flag=1):
'''Return the filterload message'''
# start the payload with the size of the filter in bytes
payload = encode_varint(self.size)
# next add the bit field using self.filter_bytes()
payload += self.filter_bytes()
# function count is 4 bytes little endian
payload += int_to_little_endian(self.function_count, 4)
# tweak is 4 bytes little endian
payload += int_to_little_endian(self.tweak, 4)
# flag is 1 byte little endian
payload += int_to_little_endian(flag, 1)
# return a GenericMessage whose command is b'filterload'
# and payload is what we've calculated
return GenericMessage(b'filterload', payload)