|
| 1 | +//! Based on Parity Common Eth Bloom implementation |
| 2 | +//! Link: <https://github.com/paritytech/parity-common/blob/master/ethbloom/src/lib.rs> |
| 3 | +//! |
| 4 | +//! Reimplemented here since there is a large mismatch in types and dependencies. |
| 5 | +#![allow(clippy::expl_impl_clone_on_copy)] |
| 6 | + |
| 7 | +use aurora_engine_sdk::keccak; |
| 8 | +use aurora_engine_types::borsh::{self, BorshDeserialize, BorshSerialize}; |
| 9 | +use aurora_engine_types::parameters::engine::ResultLog; |
| 10 | +use fixed_hash::construct_fixed_hash; |
| 11 | +use impl_serde::impl_fixed_hash_serde; |
| 12 | + |
| 13 | +const BLOOM_SIZE: usize = 256; |
| 14 | +const BLOOM_BITS: u32 = 3; |
| 15 | + |
| 16 | +construct_fixed_hash! { |
| 17 | + /// Bloom hash type with 256 bytes (2048 bits) size. |
| 18 | + #[derive(BorshSerialize, BorshDeserialize)] |
| 19 | + pub struct Bloom(BLOOM_SIZE); |
| 20 | +} |
| 21 | + |
| 22 | +impl_fixed_hash_serde!(Bloom, BLOOM_SIZE); |
| 23 | + |
| 24 | +/// Returns log2. |
| 25 | +const fn log2(x: usize) -> u32 { |
| 26 | + if x <= 1 { |
| 27 | + return 0; |
| 28 | + } |
| 29 | + |
| 30 | + let n = x.leading_zeros(); |
| 31 | + usize::BITS - n |
| 32 | +} |
| 33 | + |
| 34 | +impl Bloom { |
| 35 | + /// Add a new element to the bloom filter |
| 36 | + #[allow(clippy::as_conversions)] |
| 37 | + pub fn accrue(&mut self, input: &[u8]) { |
| 38 | + let m = self.0.len(); |
| 39 | + let bloom_bits = m * 8; |
| 40 | + let mask = bloom_bits - 1; |
| 41 | + let bloom_bytes = (log2(bloom_bits) + 7) / 8; |
| 42 | + let hash = keccak(input); |
| 43 | + let mut ptr = 0; |
| 44 | + |
| 45 | + for _ in 0..BLOOM_BITS { |
| 46 | + let mut index = 0; |
| 47 | + for _ in 0..bloom_bytes { |
| 48 | + index = (index << 8) | hash[ptr] as usize; |
| 49 | + ptr += 1; |
| 50 | + } |
| 51 | + index &= mask; |
| 52 | + self.0[m - 1 - index / 8] |= 1 << (index % 8); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + /// Merge two bloom filters |
| 57 | + pub fn accrue_bloom(&mut self, bloom: &Self) { |
| 58 | + for i in 0..BLOOM_SIZE { |
| 59 | + self.0[i] |= bloom.0[i]; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +#[must_use] |
| 65 | +pub fn get_logs_bloom(logs: &[ResultLog]) -> Bloom { |
| 66 | + let mut logs_bloom = Bloom::default(); |
| 67 | + |
| 68 | + for log in logs { |
| 69 | + logs_bloom.accrue_bloom(&get_log_bloom(log)); |
| 70 | + } |
| 71 | + |
| 72 | + logs_bloom |
| 73 | +} |
| 74 | + |
| 75 | +#[must_use] |
| 76 | +pub fn get_log_bloom(log: &ResultLog) -> Bloom { |
| 77 | + let mut log_bloom = Bloom::default(); |
| 78 | + |
| 79 | + log_bloom.accrue(log.address.as_bytes()); |
| 80 | + for topic in &log.topics { |
| 81 | + log_bloom.accrue(&topic[..]); |
| 82 | + } |
| 83 | + |
| 84 | + log_bloom |
| 85 | +} |
0 commit comments