envelope.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // Contains the Whisper protocol Envelope element. For formal details please see
  17. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#envelopes.
  18. package whisper
  19. import (
  20. "crypto/ecdsa"
  21. "encoding/binary"
  22. "fmt"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/crypto/ecies"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. // Envelope represents a clear-text data packet to transmit through the Whisper
  30. // network. Its contents may or may not be encrypted and signed.
  31. type Envelope struct {
  32. Expiry uint32 // Whisper protocol specifies int32, really should be int64
  33. TTL uint32 // ^^^^^^
  34. Topics []Topic
  35. Data []byte
  36. Nonce uint32
  37. hash common.Hash // Cached hash of the envelope to avoid rehashing every time
  38. }
  39. // NewEnvelope wraps a Whisper message with expiration and destination data
  40. // included into an envelope for network forwarding.
  41. func NewEnvelope(ttl time.Duration, topics []Topic, msg *Message) *Envelope {
  42. return &Envelope{
  43. Expiry: uint32(time.Now().Add(ttl).Unix()),
  44. TTL: uint32(ttl.Seconds()),
  45. Topics: topics,
  46. Data: msg.bytes(),
  47. Nonce: 0,
  48. }
  49. }
  50. // Seal closes the envelope by spending the requested amount of time as a proof
  51. // of work on hashing the data.
  52. func (self *Envelope) Seal(pow time.Duration) {
  53. d := make([]byte, 64)
  54. copy(d[:32], self.rlpWithoutNonce())
  55. finish, bestBit := time.Now().Add(pow).UnixNano(), 0
  56. for nonce := uint32(0); time.Now().UnixNano() < finish; {
  57. for i := 0; i < 1024; i++ {
  58. binary.BigEndian.PutUint32(d[60:], nonce)
  59. firstBit := common.FirstBitSet(common.BigD(crypto.Sha3(d)))
  60. if firstBit > bestBit {
  61. self.Nonce, bestBit = nonce, firstBit
  62. }
  63. nonce++
  64. }
  65. }
  66. }
  67. // rlpWithoutNonce returns the RLP encoded envelope contents, except the nonce.
  68. func (self *Envelope) rlpWithoutNonce() []byte {
  69. enc, _ := rlp.EncodeToBytes([]interface{}{self.Expiry, self.TTL, self.Topics, self.Data})
  70. return enc
  71. }
  72. // Open extracts the message contained within a potentially encrypted envelope.
  73. func (self *Envelope) Open(key *ecdsa.PrivateKey) (msg *Message, err error) {
  74. // Split open the payload into a message construct
  75. data := self.Data
  76. message := &Message{
  77. Flags: data[0],
  78. Sent: time.Unix(int64(self.Expiry-self.TTL), 0),
  79. TTL: time.Duration(self.TTL) * time.Second,
  80. Hash: self.Hash(),
  81. }
  82. data = data[1:]
  83. if message.Flags&signatureFlag == signatureFlag {
  84. if len(data) < signatureLength {
  85. return nil, fmt.Errorf("unable to open envelope. First bit set but len(data) < len(signature)")
  86. }
  87. message.Signature, data = data[:signatureLength], data[signatureLength:]
  88. }
  89. message.Payload = data
  90. // Decrypt the message, if requested
  91. if key == nil {
  92. return message, nil
  93. }
  94. err = message.decrypt(key)
  95. switch err {
  96. case nil:
  97. return message, nil
  98. case ecies.ErrInvalidPublicKey: // Payload isn't encrypted
  99. return message, err
  100. default:
  101. return nil, fmt.Errorf("unable to open envelope, decrypt failed: %v", err)
  102. }
  103. }
  104. // Hash returns the SHA3 hash of the envelope, calculating it if not yet done.
  105. func (self *Envelope) Hash() common.Hash {
  106. if (self.hash == common.Hash{}) {
  107. enc, _ := rlp.EncodeToBytes(self)
  108. self.hash = crypto.Sha3Hash(enc)
  109. }
  110. return self.hash
  111. }
  112. // DecodeRLP decodes an Envelope from an RLP data stream.
  113. func (self *Envelope) DecodeRLP(s *rlp.Stream) error {
  114. raw, err := s.Raw()
  115. if err != nil {
  116. return err
  117. }
  118. // The decoding of Envelope uses the struct fields but also needs
  119. // to compute the hash of the whole RLP-encoded envelope. This
  120. // type has the same structure as Envelope but is not an
  121. // rlp.Decoder so we can reuse the Envelope struct definition.
  122. type rlpenv Envelope
  123. if err := rlp.DecodeBytes(raw, (*rlpenv)(self)); err != nil {
  124. return err
  125. }
  126. self.hash = crypto.Sha3Hash(raw)
  127. return nil
  128. }