github.com/mandrigin/go-ethereum@v1.7.4-0.20180116162341-02aeb3d76652/whisper/whisperv6/envelope.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum 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 go-ethereum 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 go-ethereum 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 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/common/math" 31 "github.com/ethereum/go-ethereum/crypto" 32 "github.com/ethereum/go-ethereum/crypto/ecies" 33 "github.com/ethereum/go-ethereum/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 var target, bestBit int 81 if options.PoW == 0 { 82 // adjust for the duration of Seal() execution only if execution time is predefined unconditionally 83 e.Expiry += options.WorkTime 84 } else { 85 target = e.powToFirstBit(options.PoW) 86 if target < 1 { 87 target = 1 88 } 89 } 90 91 buf := make([]byte, 64) 92 h := crypto.Keccak256(e.rlpWithoutNonce()) 93 copy(buf[:32], h) 94 95 finish := time.Now().Add(time.Duration(options.WorkTime) * time.Second).UnixNano() 96 for nonce := uint64(0); time.Now().UnixNano() < finish; { 97 for i := 0; i < 1024; i++ { 98 binary.BigEndian.PutUint64(buf[56:], nonce) 99 d := new(big.Int).SetBytes(crypto.Keccak256(buf)) 100 firstBit := math.FirstBitSet(d) 101 if firstBit > bestBit { 102 e.Nonce, bestBit = nonce, firstBit 103 if target > 0 && bestBit >= target { 104 return nil 105 } 106 } 107 nonce++ 108 } 109 } 110 111 if target > 0 && bestBit < target { 112 return fmt.Errorf("failed to reach the PoW target, specified pow time (%d seconds) was insufficient", options.WorkTime) 113 } 114 115 return nil 116 } 117 118 func (e *Envelope) PoW() float64 { 119 if e.pow == 0 { 120 e.calculatePoW(0) 121 } 122 return e.pow 123 } 124 125 func (e *Envelope) calculatePoW(diff uint32) { 126 buf := make([]byte, 64) 127 h := crypto.Keccak256(e.rlpWithoutNonce()) 128 copy(buf[:32], h) 129 binary.BigEndian.PutUint64(buf[56:], e.Nonce) 130 d := new(big.Int).SetBytes(crypto.Keccak256(buf)) 131 firstBit := math.FirstBitSet(d) 132 x := gmath.Pow(2, float64(firstBit)) 133 x /= float64(e.size()) 134 x /= float64(e.TTL + diff) 135 e.pow = x 136 } 137 138 func (e *Envelope) powToFirstBit(pow float64) int { 139 x := pow 140 x *= float64(e.size()) 141 x *= float64(e.TTL) 142 bits := gmath.Log2(x) 143 bits = gmath.Ceil(bits) 144 return int(bits) 145 } 146 147 // Hash returns the SHA3 hash of the envelope, calculating it if not yet done. 148 func (e *Envelope) Hash() common.Hash { 149 if (e.hash == common.Hash{}) { 150 encoded, _ := rlp.EncodeToBytes(e) 151 e.hash = crypto.Keccak256Hash(encoded) 152 } 153 return e.hash 154 } 155 156 // DecodeRLP decodes an Envelope from an RLP data stream. 157 func (e *Envelope) DecodeRLP(s *rlp.Stream) error { 158 raw, err := s.Raw() 159 if err != nil { 160 return err 161 } 162 // The decoding of Envelope uses the struct fields but also needs 163 // to compute the hash of the whole RLP-encoded envelope. This 164 // type has the same structure as Envelope but is not an 165 // rlp.Decoder (does not implement DecodeRLP function). 166 // Only public members will be encoded. 167 type rlpenv Envelope 168 if err := rlp.DecodeBytes(raw, (*rlpenv)(e)); err != nil { 169 return err 170 } 171 e.hash = crypto.Keccak256Hash(raw) 172 return nil 173 } 174 175 // OpenAsymmetric tries to decrypt an envelope, potentially encrypted with a particular key. 176 func (e *Envelope) OpenAsymmetric(key *ecdsa.PrivateKey) (*ReceivedMessage, error) { 177 message := &ReceivedMessage{Raw: e.Data} 178 err := message.decryptAsymmetric(key) 179 switch err { 180 case nil: 181 return message, nil 182 case ecies.ErrInvalidPublicKey: // addressed to somebody else 183 return nil, err 184 default: 185 return nil, fmt.Errorf("unable to open envelope, decrypt failed: %v", err) 186 } 187 } 188 189 // OpenSymmetric tries to decrypt an envelope, potentially encrypted with a particular key. 190 func (e *Envelope) OpenSymmetric(key []byte) (msg *ReceivedMessage, err error) { 191 msg = &ReceivedMessage{Raw: e.Data} 192 err = msg.decryptSymmetric(key) 193 if err != nil { 194 msg = nil 195 } 196 return msg, err 197 } 198 199 // Open tries to decrypt an envelope, and populates the message fields in case of success. 200 func (e *Envelope) Open(watcher *Filter) (msg *ReceivedMessage) { 201 // The API interface forbids filters doing both symmetric and 202 // asymmetric encryption. 203 if watcher.expectsAsymmetricEncryption() && watcher.expectsSymmetricEncryption() { 204 return nil 205 } 206 207 if watcher.expectsAsymmetricEncryption() { 208 msg, _ = e.OpenAsymmetric(watcher.KeyAsym) 209 if msg != nil { 210 msg.Dst = &watcher.KeyAsym.PublicKey 211 } 212 } else if watcher.expectsSymmetricEncryption() { 213 msg, _ = e.OpenSymmetric(watcher.KeySym) 214 if msg != nil { 215 msg.SymKeyHash = crypto.Keccak256Hash(watcher.KeySym) 216 } 217 } 218 219 if msg != nil { 220 ok := msg.Validate() 221 if !ok { 222 return nil 223 } 224 msg.Topic = e.Topic 225 msg.PoW = e.PoW() 226 msg.TTL = e.TTL 227 msg.Sent = e.Expiry - e.TTL 228 msg.EnvelopeHash = e.Hash() 229 } 230 return msg 231 } 232 233 // Bloom maps 4-bytes Topic into 64-byte bloom filter with 3 bits set (at most). 234 func (e *Envelope) Bloom() []byte { 235 if e.bloom == nil { 236 e.bloom = TopicToBloom(e.Topic) 237 } 238 return e.bloom 239 } 240 241 // TopicToBloom converts the topic (4 bytes) to the bloom filter (64 bytes) 242 func TopicToBloom(topic TopicType) []byte { 243 b := make([]byte, bloomFilterSize) 244 var index [3]int 245 for j := 0; j < 3; j++ { 246 index[j] = int(topic[j]) 247 if (topic[3] & (1 << uint(j))) != 0 { 248 index[j] += 256 249 } 250 } 251 252 for j := 0; j < 3; j++ { 253 byteIndex := index[j] / 8 254 bitIndex := index[j] % 8 255 b[byteIndex] = (1 << uint(bitIndex)) 256 } 257 return b 258 }