message.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // Copyright 2014 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 Message element. For formal details please see
  17. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#messages.
  18. package whisperv2
  19. import (
  20. "crypto/ecdsa"
  21. crand "crypto/rand"
  22. "math/rand"
  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/logger"
  28. "github.com/ethereum/go-ethereum/logger/glog"
  29. )
  30. // Message represents an end-user data packet to transmit through the Whisper
  31. // protocol. These are wrapped into Envelopes that need not be understood by
  32. // intermediate nodes, just forwarded.
  33. type Message struct {
  34. Flags byte // First bit is signature presence, rest reserved and should be random
  35. Signature []byte
  36. Payload []byte
  37. Sent time.Time // Time when the message was posted into the network
  38. TTL time.Duration // Maximum time to live allowed for the message
  39. To *ecdsa.PublicKey // Message recipient (identity used to decode the message)
  40. Hash common.Hash // Message envelope hash to act as a unique id
  41. }
  42. // Options specifies the exact way a message should be wrapped into an Envelope.
  43. type Options struct {
  44. From *ecdsa.PrivateKey
  45. To *ecdsa.PublicKey
  46. TTL time.Duration
  47. Topics []Topic
  48. }
  49. // NewMessage creates and initializes a non-signed, non-encrypted Whisper message.
  50. func NewMessage(payload []byte) *Message {
  51. // Construct an initial flag set: no signature, rest random
  52. flags := byte(rand.Intn(256))
  53. flags &= ^signatureFlag
  54. // Assemble and return the message
  55. return &Message{
  56. Flags: flags,
  57. Payload: payload,
  58. Sent: time.Now(),
  59. }
  60. }
  61. // Wrap bundles the message into an Envelope to transmit over the network.
  62. //
  63. // pow (Proof Of Work) controls how much time to spend on hashing the message,
  64. // inherently controlling its priority through the network (smaller hash, bigger
  65. // priority).
  66. //
  67. // The user can control the amount of identity, privacy and encryption through
  68. // the options parameter as follows:
  69. // - options.From == nil && options.To == nil: anonymous broadcast
  70. // - options.From != nil && options.To == nil: signed broadcast (known sender)
  71. // - options.From == nil && options.To != nil: encrypted anonymous message
  72. // - options.From != nil && options.To != nil: encrypted signed message
  73. func (self *Message) Wrap(pow time.Duration, options Options) (*Envelope, error) {
  74. // Use the default TTL if non was specified
  75. if options.TTL == 0 {
  76. options.TTL = DefaultTTL
  77. }
  78. self.TTL = options.TTL
  79. // Sign and encrypt the message if requested
  80. if options.From != nil {
  81. if err := self.sign(options.From); err != nil {
  82. return nil, err
  83. }
  84. }
  85. if options.To != nil {
  86. if err := self.encrypt(options.To); err != nil {
  87. return nil, err
  88. }
  89. }
  90. // Wrap the processed message, seal it and return
  91. envelope := NewEnvelope(options.TTL, options.Topics, self)
  92. envelope.Seal(pow)
  93. return envelope, nil
  94. }
  95. // sign calculates and sets the cryptographic signature for the message , also
  96. // setting the sign flag.
  97. func (self *Message) sign(key *ecdsa.PrivateKey) (err error) {
  98. self.Flags |= signatureFlag
  99. self.Signature, err = crypto.Sign(self.hash(), key)
  100. return
  101. }
  102. // Recover retrieves the public key of the message signer.
  103. func (self *Message) Recover() *ecdsa.PublicKey {
  104. defer func() { recover() }() // in case of invalid signature
  105. // Short circuit if no signature is present
  106. if self.Signature == nil {
  107. return nil
  108. }
  109. // Otherwise try and recover the signature
  110. pub, err := crypto.SigToPub(self.hash(), self.Signature)
  111. if err != nil {
  112. glog.V(logger.Error).Infof("Could not get public key from signature: %v", err)
  113. return nil
  114. }
  115. return pub
  116. }
  117. // encrypt encrypts a message payload with a public key.
  118. func (self *Message) encrypt(key *ecdsa.PublicKey) (err error) {
  119. self.Payload, err = ecies.Encrypt(crand.Reader, ecies.ImportECDSAPublic(key), self.Payload, nil, nil)
  120. return
  121. }
  122. // decrypt decrypts an encrypted payload with a private key.
  123. func (self *Message) decrypt(key *ecdsa.PrivateKey) error {
  124. cleartext, err := ecies.ImportECDSA(key).Decrypt(crand.Reader, self.Payload, nil, nil)
  125. if err == nil {
  126. self.Payload = cleartext
  127. }
  128. return err
  129. }
  130. // hash calculates the SHA3 checksum of the message flags and payload.
  131. func (self *Message) hash() []byte {
  132. return crypto.Keccak256(append([]byte{self.Flags}, self.Payload...))
  133. }
  134. // bytes flattens the message contents (flags, signature and payload) into a
  135. // single binary blob.
  136. func (self *Message) bytes() []byte {
  137. return append([]byte{self.Flags}, append(self.Signature, self.Payload...)...)
  138. }