envelope.go 7.8 KB

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