      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
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303

    use parking_lot::Mutex;
    use bit_vec::BitVec;
    use murmur3::murmur3_32;
    use chain::{IndexedTransaction, OutPoint};
    use message::types;
    use ser::serialize;
    use script::Script;

    /// Constant optimized to create large differences in the seed for different values of `hash_functions_num`.
    const SEED_OFFSET: u32 = 0xFBA4C795;

    /// Connection bloom filter
    #[derive(Debug)]
    pub struct BloomFilter {
    	/// Bloom data. Filter can be updated when transaction is matched => we have to use some kind of lock here.
    	/// Mutex is an only choice, because:
    	/// 1) we do not know if transaction matches the filter in advance
    	/// 2) RwLock is non-upgradeable in Rust
    	bloom: Option<Mutex<BloomFilterData>>,
    	/// Filter update type.
    	filter_flags: types::FilterFlags,
    }

    /// Bloom filter data implemented as described in:
    /// https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki
    #[derive(Debug, Default)]
    struct BloomFilterData {
    	/// Filter storage
    	filter: BitVec,
    	/// Number of hash functions to use in bloom filter
    	hash_functions_num: u32,
    	/// Value to add to Murmur3 hash seed when calculating hash
    	tweak: u32,
    }

    impl Default for BloomFilter {
    	fn default() -> Self {
    		BloomFilter {
    			bloom: None,
    			filter_flags: types::FilterFlags::None,
    		}
    	}
    }

    impl BloomFilter {
    	/// Create with given parameters
    	#[cfg(test)]
    	pub fn with_filter_load(message: types::FilterLoad) -> Self {
    		BloomFilter {
    			filter_flags: message.flags,
    			bloom: Some(Mutex::new(BloomFilterData::with_filter_load(message))),
    		}
    	}

    	/// Returns true if bloom filter is set
    	pub fn is_set(&self) -> bool {
    		self.bloom.is_some()
    	}

    	/// Sets bloom filter to given value
    	pub fn set_bloom_filter(&mut self, message: types::FilterLoad) {
    		self.bloom = Some(Mutex::new(BloomFilterData::with_filter_load(message)));
    	}

    	/// Adds given data to current filter, so that new transactions can be accepted
    	pub fn update_bloom_filter(&mut self, message: types::FilterAdd) {
    		if let Some(ref mut bloom) = self.bloom {
    			bloom.lock().insert(&message.data);
    		}
    	}

    	/// Removes bloom filter, so that all transactions are now accepted by this filter
    	pub fn remove_bloom_filter(&mut self) {
    		self.bloom = None;
    	}

    	/// Filters transaction using bloom filter data
    	pub fn filter_transaction(&self, tx: &IndexedTransaction) -> bool {
    		// check with bloom filter, if set
    		match self.bloom {
    			// if no filter is set for the connection => match everything
    			None => true,
    			// filter using bloom filter, then update
    			Some(ref bloom) => {
    				let mut bloom = bloom.lock();
    				let mut is_match = false;

    				// match if filter contains any arbitrary script data element in any scriptPubKey in tx
    				for (output_index, output) in tx.raw.outputs.iter().enumerate() {
    					let script = Script::new(output.script_pubkey.clone());
    					let is_update_needed = self.filter_flags == types::FilterFlags::All
    						|| (self.filter_flags == types::FilterFlags::PubKeyOnly && (script.is_pay_to_public_key() || script.is_multisig_script()));
    					for instruction in script.iter().filter_map(|i| i.ok()) {
    						if let Some(instruction_data) = instruction.data {
    							if bloom.contains(instruction_data) {
    								is_match = true;

    								if is_update_needed {
    									bloom.insert(&serialize(&OutPoint {
    										hash: tx.hash.clone(),
    										index: output_index as u32,
    									}));
    								}
    							}
    						}
    					}
    				}

    				// filter is updated only above => we can early-return from now
    				if is_match {
    					return is_match;
    				}

    				// match if filter contains transaction itself
    				if bloom.contains(&*tx.hash) {
    					return true;
    				}

    				// match if filter contains an outpoint this transaction spends
    				for input in &tx.raw.inputs {
    					// check if match previous output
    					let previous_output = serialize(&input.previous_output);
    					is_match = bloom.contains(&*previous_output);
    					if is_match {
    						return true;
    					}

    					// check if match any arbitrary script data element in any scriptSig in tx
    					let script = Script::new(input.script_sig.clone());
    					for instruction in script.iter().filter_map(|i| i.ok()) {
    						if let Some(instruction_data) = instruction.data {
    							is_match = bloom.contains(&*instruction_data);
    							if is_match {
    								return true;
    							}
    						}
    					}
    				}

    				// no matches
    				false
    			},
    		}
    	}
    }

    impl BloomFilterData {
    	/// Create with given parameters
    	pub fn with_filter_load(message: types::FilterLoad) -> Self {
    		BloomFilterData {
    			filter: BitVec::from_bytes(&message.filter),
    			hash_functions_num: message.hash_functions,
    			tweak: message.tweak,
    		}
    	}

    	/// True if filter contains given bytes
    	pub fn contains(&self, data: &[u8]) -> bool {
    		for hash_function_idx in 0..self.hash_functions_num {
    			let murmur_seed = hash_function_idx.overflowing_mul(SEED_OFFSET).0.overflowing_add(self.tweak).0;
    			let murmur_hash = murmur3_32(&mut data.as_ref(), murmur_seed) as usize % self.filter.len();
    			let index = (murmur_hash & !7usize) | ((murmur_hash & 7) ^ 7);
    			if !self.filter.get(index).expect("murmur_hash is result of mod operation by filter len; qed") {
    				return false;
    			}
    		}
    		true
    	}

    	/// Add bytes to the filter
    	pub fn insert(&mut self, data: &[u8]) {
    		for hash_function_idx in 0..self.hash_functions_num {
    			let murmur_seed = hash_function_idx.overflowing_mul(SEED_OFFSET).0.overflowing_add(self.tweak).0;
    			let murmur_hash = murmur3_32(&mut data.as_ref(), murmur_seed) as usize % self.filter.len();
    			let index = (murmur_hash & !7usize) | ((murmur_hash & 7) ^ 7);
    			self.filter.set(index, true);
    		}
    	}
    }

    #[cfg(test)]
    mod tests {
    	extern crate test_data;

    	use std::iter::repeat;
    	use chain::IndexedTransaction;
    	use message::types;
    	use primitives::bytes::Bytes;
    	use primitives::hash::H256;
    	use ser::serialize;
    	use super::{BloomFilter, BloomFilterData};

    	fn default_filterload() -> types::FilterLoad {
    		types::FilterLoad {
    			filter: Bytes::from(repeat(0u8).take(1024).collect::<Vec<_>>()),
    			hash_functions: 10,
    			tweak: 5,
    			flags: types::FilterFlags::None,
    		}
    	}

    	fn make_filteradd(data: &[u8]) -> types::FilterAdd {
    		types::FilterAdd {
    			data: data.into(),
    		}
    	}

    	#[test]
    	fn bloom_insert_data() {
    		let mut bloom = BloomFilterData::with_filter_load(default_filterload());

    		assert!(!bloom.contains(&*H256::default()));

    		bloom.insert(&*H256::default());
    		assert!(bloom.contains(&*H256::default()));
    	}

    	#[test]
    	fn bloom_filter_matches_transaction_by_hash() {
    		let tx1: IndexedTransaction = test_data::TransactionBuilder::with_output(10).into();
    		let tx2: IndexedTransaction = test_data::TransactionBuilder::with_output(20).into();

    		let mut filter = BloomFilter::with_filter_load(default_filterload());

    		assert!(!filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));

    		filter.update_bloom_filter(make_filteradd(&*tx1.hash));

    		assert!(filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));
    	}

    	#[test]
    	fn bloom_filter_matches_transaction_by_output_script_data_element() {
    		// https://webbtc.com/tx/eb3b82c0884e3efa6d8b0be55b4915eb20be124c9766245bcc7f34fdac32bccb
    		// output script: OP_DUP OP_HASH160 380cb3c594de4e7e9b8e18db182987bebb5a4f70 OP_EQUALVERIFY OP_CHECKSIG
    		let tx1: IndexedTransaction = " ".into();
    		let tx1_out_data: Bytes = "380cb3c594de4e7e9b8e18db182987bebb5a4f70".into();
    		let tx2 = IndexedTransaction::default();

    		let mut filter = BloomFilter::with_filter_load(default_filterload());

    		assert!(!filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));

    		filter.update_bloom_filter(make_filteradd(&tx1_out_data));

    		assert!(filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));
    	}

    	#[test]
    	fn bloom_filter_matches_transaction_by_previous_output_point() {
    		// https://webbtc.com/tx/eb3b82c0884e3efa6d8b0be55b4915eb20be124c9766245bcc7f34fdac32bccb
    		let tx1: IndexedTransaction = " ".into();
    		let tx1_previous_output: Bytes = serialize(&tx1.raw.inputs[0].previous_output);
    		let tx2 = IndexedTransaction::default();

    		let mut filter = BloomFilter::with_filter_load(default_filterload());

    		assert!(!filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));

    		filter.update_bloom_filter(make_filteradd(&tx1_previous_output));

    		assert!(filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));
    	}

    	#[test]
    	fn connection_filter_matches_transaction_by_input_script_data_element() {
    		// https://webbtc.com/tx/eb3b82c0884e3efa6d8b0be55b4915eb20be124c9766245bcc7f34fdac32bccb
    		// input script: PUSH DATA 304502205b282fbc9b064f3bc823a23edcc0048cbb174754e7aa742e3c9f483ebe02911c022100e4b0b3a117d36cab5a67404dddbf43db7bea3c1530e0fe128ebc15621bd69a3b01
    		let tx1: IndexedTransaction = " ".into();
    		let tx1_input_data: Bytes = "304502205b282fbc9b064f3bc823a23edcc0048cbb174754e7aa742e3c9f483ebe02911c022100e4b0b3a117d36cab5a67404dddbf43db7bea3c1530e0fe128ebc15621bd69a3b01".into();
    		let tx2 = IndexedTransaction::default();

    		let mut filter = BloomFilter::with_filter_load(default_filterload());

    		assert!(!filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));

    		filter.update_bloom_filter(make_filteradd(&tx1_input_data));

    		assert!(filter.filter_transaction(&tx1));
    		assert!(!filter.filter_transaction(&tx2));
    	}

    	#[test]
    	fn bloom_filter_data_works_on_address() {
    		use message::{types, deserialize_payload};

    		// real world message
    		let payload: Bytes = " ".parse().unwrap();
    		let message: types::FilterLoad = deserialize_payload(&payload, 70001).unwrap();
    		// containing this address
    		let address: Bytes = "BA99435B59DEBDBB5E207C0B33FF55752DBC5EFF".parse().unwrap();

    		let bloom = BloomFilterData::with_filter_load(message);
    		assert!(bloom.contains(address.as_slice()));
    	}
    }

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)