github.com/aquanetwork/aquachain@v1.7.8/opt/whisper/whisperv6/envelope.go (about) 1 // Copyright 2016 The aquachain Authors 2 // This file is part of the aquachain library. 3 // 4 // The aquachain library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The aquachain library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the aquachain library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Contains the Whisper protocol Envelope element. 18 19 package whisperv6 20 21 import ( 22 "crypto/ecdsa" 23 "encoding/binary" 24 "fmt" 25 gmath "math" 26 "math/big" 27 "time" 28 29 "gitlab.com/aquachain/aquachain/common" 30 "gitlab.com/aquachain/aquachain/common/math" 31 "gitlab.com/aquachain/aquachain/crypto" 32 "gitlab.com/aquachain/aquachain/crypto/ecies" 33 "gitlab.com/aquachain/aquachain/rlp" 34 ) 35 36 // Envelope represents a clear-text data packet to transmit through the Whisper 37 // network. Its contents may or may not be encrypted and signed. 38 type Envelope struct { 39 Expiry uint32 40 TTL uint32 41 Topic TopicType 42 Data []byte 43 Nonce uint64 44 45 pow float64 // Message-specific PoW as described in the Whisper specification. 46 47 // the following variables should not be accessed directly, use the corresponding function instead: Hash(), Bloom() 48 hash common.Hash // Cached hash of the envelope to avoid rehashing every time. 49 bloom []byte 50 } 51 52 // size returns the size of envelope as it is sent (i.e. public fields only) 53 func (e *Envelope) size() int { 54 return EnvelopeHeaderLength + len(e.Data) 55 } 56 57 // rlpWithoutNonce returns the RLP encoded envelope contents, except the nonce. 58 func (e *Envelope) rlpWithoutNonce() []byte { 59 res, _ := rlp.EncodeToBytes([]interface{}{e.Expiry, e.TTL, e.Topic, e.Data}) 60 return res 61 } 62 63 // NewEnvelope wraps a Whisper message with expiration and destination data 64 // included into an envelope for network forwarding. 65 func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage) *Envelope { 66 env := Envelope{ 67 Expiry: uint32(time.Now().Add(time.Second * time.Duration(ttl)).Unix()), 68 TTL: ttl, 69 Topic: topic, 70 Data: msg.Raw, 71 Nonce: 0, 72 } 73 74 return &env 75 } 76 77 // Seal closes the envelope by spending the requested amount of time as a proof 78 // of work on hashing the data. 79 func (e *Envelope) Seal(options *MessageParams) error { 80 if options.PoW == 0 { 81 // PoW is not required 82 return nil 83 } 84 85 var target, bestBit int 86 if options.PoW < 0 { 87 // target is not set - the function should run for a period 88 // of time specified in WorkTime param. Since we can predict 89 // the execution time, we can also adjust Expiry. 90 e.Expiry += options.WorkTime 91 } else { 92 target = e.powToFirstBit(options.PoW) 93 } 94 95 buf := make([]byte, 64) 96 h := crypto.Keccak256(e.rlpWithoutNonce()) 97 copy(buf[:32], h) 98 99 finish := time.Now().Add(time.Duration(options.WorkTime) * time.Second).UnixNano() 100 for nonce := uint64(0); time.Now().UnixNano() < finish; { 101 for i := 0; i < 1024; i++ { 102 binary.BigEndian.PutUint64(buf[56:], nonce) 103 d := new(big.Int).SetBytes(crypto.Keccak256(buf)) 104 firstBit := math.FirstBitSet(d) 105 if firstBit > bestBit { 106 e.Nonce, bestBit = nonce, firstBit 107 if target > 0 && bestBit >= target { 108 return nil 109 } 110 } 111 nonce++ 112 } 113 } 114 115 if target > 0 && bestBit < target { 116 return fmt.Errorf("failed to reach the PoW target, specified pow time (%d seconds) was insufficient", options.WorkTime) 117 } 118 119 return nil 120 } 121 122 // PoW computes (if necessary) and returns the proof of work target 123 // of the envelope. 124 func (e *Envelope) PoW() float64 { 125 if e.pow == 0 { 126 e.calculatePoW(0) 127 } 128 return e.pow 129 } 130 131 func (e *Envelope) calculatePoW(diff uint32) { 132 buf := make([]byte, 64) 133 h := crypto.Keccak256(e.rlpWithoutNonce()) 134 copy(buf[:32], h) 135 binary.BigEndian.PutUint64(buf[56:], e.Nonce) 136 d := new(big.Int).SetBytes(crypto.Keccak256(buf)) 137 firstBit := math.FirstBitSet(d) 138 x := gmath.Pow(2, float64(firstBit)) 139 x /= float64(e.size()) 140 x /= float64(e.TTL + diff) 141 e.pow = x 142 } 143 144 func (e *Envelope) powToFirstBit(pow float64) int { 145 x := pow 146 x *= float64(e.size()) 147 x *= float64(e.TTL) 148 bits := gmath.Log2(x) 149 bits = gmath.Ceil(bits) 150 res := int(bits) 151 if res < 1 { 152 res = 1 153 } 154 return res 155 } 156 157 // Hash returns the SHA3 hash of the envelope, calculating it if not yet done. 158 func (e *Envelope) Hash() common.Hash { 159 if (e.hash == common.Hash{}) { 160 encoded, _ := rlp.EncodeToBytes(e) 161 e.hash = crypto.Keccak256Hash(encoded) 162 } 163 return e.hash 164 } 165 166 // DecodeRLP decodes an Envelope from an RLP data stream. 167 func (e *Envelope) DecodeRLP(s *rlp.Stream) error { 168 raw, err := s.Raw() 169 if err != nil { 170 return err 171 } 172 // The decoding of Envelope uses the struct fields but also needs 173 // to compute the hash of the whole RLP-encoded envelope. This 174 // type has the same structure as Envelope but is not an 175 // rlp.Decoder (does not implement DecodeRLP function). 176 // Only public members will be encoded. 177 type rlpenv Envelope 178 if err := rlp.DecodeBytes(raw, (*rlpenv)(e)); err != nil { 179 return err 180 } 181 e.hash = crypto.Keccak256Hash(raw) 182 return nil 183 } 184 185 // OpenAsymmetric tries to decrypt an envelope, potentially encrypted with a particular key. 186 func (e *Envelope) OpenAsymmetric(key *ecdsa.PrivateKey) (*ReceivedMessage, error) { 187 message := &ReceivedMessage{Raw: e.Data} 188 err := message.decryptAsymmetric(key) 189 switch err { 190 case nil: 191 return message, nil 192 case ecies.ErrInvalidPublicKey: // addressed to somebody else 193 return nil, err 194 default: 195 return nil, fmt.Errorf("unable to open envelope, decrypt failed: %v", err) 196 } 197 } 198 199 // OpenSymmetric tries to decrypt an envelope, potentially encrypted with a particular key. 200 func (e *Envelope) OpenSymmetric(key []byte) (msg *ReceivedMessage, err error) { 201 msg = &ReceivedMessage{Raw: e.Data} 202 err = msg.decryptSymmetric(key) 203 if err != nil { 204 msg = nil 205 } 206 return msg, err 207 } 208 209 // Open tries to decrypt an envelope, and populates the message fields in case of success. 210 func (e *Envelope) Open(watcher *Filter) (msg *ReceivedMessage) { 211 // The API interface forbids filters doing both symmetric and asymmetric encryption. 212 if watcher.expectsAsymmetricEncryption() && watcher.expectsSymmetricEncryption() { 213 return nil 214 } 215 216 if watcher.expectsAsymmetricEncryption() { 217 msg, _ = e.OpenAsymmetric(watcher.KeyAsym) 218 if msg != nil { 219 msg.Dst = &watcher.KeyAsym.PublicKey 220 } 221 } else if watcher.expectsSymmetricEncryption() { 222 msg, _ = e.OpenSymmetric(watcher.KeySym) 223 if msg != nil { 224 msg.SymKeyHash = crypto.Keccak256Hash(watcher.KeySym) 225 } 226 } 227 228 if msg != nil { 229 ok := msg.ValidateAndParse() 230 if !ok { 231 return nil 232 } 233 msg.Topic = e.Topic 234 msg.PoW = e.PoW() 235 msg.TTL = e.TTL 236 msg.Sent = e.Expiry - e.TTL 237 msg.EnvelopeHash = e.Hash() 238 } 239 return msg 240 } 241 242 // Bloom maps 4-bytes Topic into 64-byte bloom filter with 3 bits set (at most). 243 func (e *Envelope) Bloom() []byte { 244 if e.bloom == nil { 245 e.bloom = TopicToBloom(e.Topic) 246 } 247 return e.bloom 248 } 249 250 // TopicToBloom converts the topic (4 bytes) to the bloom filter (64 bytes) 251 func TopicToBloom(topic TopicType) []byte { 252 b := make([]byte, bloomFilterSize) 253 var index [3]int 254 for j := 0; j < 3; j++ { 255 index[j] = int(topic[j]) 256 if (topic[3] & (1 << uint(j))) != 0 { 257 index[j] += 256 258 } 259 } 260 261 for j := 0; j < 3; j++ { 262 byteIndex := index[j] / 8 263 bitIndex := index[j] % 8 264 b[byteIndex] = (1 << uint(bitIndex)) 265 } 266 return b 267 }