github.com/status-im/status-go@v1.1.0/waku/common/topic.go (about) 1 // Copyright 2019 The Waku Library Authors. 2 // 3 // The Waku library is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Lesser General Public License as published by 5 // the Free Software Foundation, either version 3 of the License, or 6 // (at your option) any later version. 7 // 8 // The Waku library is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty off 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Lesser General Public License for more details. 12 // 13 // You should have received a copy of the GNU Lesser General Public License 14 // along with the Waku library. If not, see <http://www.gnu.org/licenses/>. 15 // 16 // This software uses the go-ethereum library, which is licensed 17 // under the GNU Lesser General Public Library, version 3 or any later. 18 19 package common 20 21 import ( 22 "github.com/ethereum/go-ethereum/common/hexutil" 23 ) 24 25 // TopicType represents a cryptographically secure, probabilistic partial 26 // classifications of a message, determined as the first (leftmost) 4 bytes of the 27 // SHA3 hash of some arbitrary data given by the original author of the message. 28 type TopicType [TopicLength]byte 29 30 // BytesToTopic converts from the byte array representation of a topic 31 // into the TopicType type. 32 func BytesToTopic(b []byte) (t TopicType) { 33 sz := TopicLength 34 if x := len(b); x < TopicLength { 35 sz = x 36 } 37 for i := 0; i < sz; i++ { 38 t[i] = b[i] 39 } 40 return t 41 } 42 43 // String converts a topic byte array to a string representation. 44 func (t *TopicType) String() string { 45 return hexutil.Encode(t[:]) 46 } 47 48 // MarshalText returns the hex representation of t. 49 func (t TopicType) MarshalText() ([]byte, error) { 50 return hexutil.Bytes(t[:]).MarshalText() 51 } 52 53 // UnmarshalText parses a hex representation to a topic. 54 func (t *TopicType) UnmarshalText(input []byte) error { 55 return hexutil.UnmarshalFixedText("Topic", input, t[:]) 56 } 57 58 // ToBloom converts the topic (4 bytes) to the bloom filter (64 bytes) 59 func (t TopicType) ToBloom() []byte { 60 b := make([]byte, BloomFilterSize) 61 var index [3]int 62 for j := 0; j < 3; j++ { 63 index[j] = int(t[j]) 64 if (t[3] & (1 << uint(j))) != 0 { 65 index[j] += 256 66 } 67 } 68 69 for j := 0; j < 3; j++ { 70 byteIndex := index[j] / 8 71 bitIndex := index[j] % 8 72 b[byteIndex] = 1 << uint(bitIndex) 73 } 74 return b 75 }