mailserver.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright 2017 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. // Package mailserver provides a naive, example mailserver implementation
  17. package mailserver
  18. import (
  19. "encoding/binary"
  20. "fmt"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/log"
  24. "github.com/ethereum/go-ethereum/rlp"
  25. whisper "github.com/ethereum/go-ethereum/whisper/whisperv6"
  26. "github.com/syndtr/goleveldb/leveldb"
  27. "github.com/syndtr/goleveldb/leveldb/errors"
  28. "github.com/syndtr/goleveldb/leveldb/opt"
  29. "github.com/syndtr/goleveldb/leveldb/util"
  30. )
  31. // WMailServer represents the state data of the mailserver.
  32. type WMailServer struct {
  33. db *leveldb.DB
  34. w *whisper.Whisper
  35. pow float64
  36. key []byte
  37. }
  38. type DBKey struct {
  39. timestamp uint32
  40. hash common.Hash
  41. raw []byte
  42. }
  43. // NewDbKey is a helper function that creates a levelDB
  44. // key from a hash and an integer.
  45. func NewDbKey(t uint32, h common.Hash) *DBKey {
  46. const sz = common.HashLength + 4
  47. var k DBKey
  48. k.timestamp = t
  49. k.hash = h
  50. k.raw = make([]byte, sz)
  51. binary.BigEndian.PutUint32(k.raw, k.timestamp)
  52. copy(k.raw[4:], k.hash[:])
  53. return &k
  54. }
  55. // Init initializes the mail server.
  56. func (s *WMailServer) Init(shh *whisper.Whisper, path string, password string, pow float64) error {
  57. var err error
  58. if len(path) == 0 {
  59. return fmt.Errorf("DB file is not specified")
  60. }
  61. if len(password) == 0 {
  62. return fmt.Errorf("password is not specified")
  63. }
  64. s.db, err = leveldb.OpenFile(path, &opt.Options{OpenFilesCacheCapacity: 32})
  65. if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted {
  66. s.db, err = leveldb.RecoverFile(path, nil)
  67. }
  68. if err != nil {
  69. return fmt.Errorf("open DB file: %s", err)
  70. }
  71. s.w = shh
  72. s.pow = pow
  73. MailServerKeyID, err := s.w.AddSymKeyFromPassword(password)
  74. if err != nil {
  75. return fmt.Errorf("create symmetric key: %s", err)
  76. }
  77. s.key, err = s.w.GetSymKey(MailServerKeyID)
  78. if err != nil {
  79. return fmt.Errorf("save symmetric key: %s", err)
  80. }
  81. return nil
  82. }
  83. // Close cleans up before shutdown.
  84. func (s *WMailServer) Close() {
  85. if s.db != nil {
  86. s.db.Close()
  87. }
  88. }
  89. // Archive stores the
  90. func (s *WMailServer) Archive(env *whisper.Envelope) {
  91. key := NewDbKey(env.Expiry-env.TTL, env.Hash())
  92. rawEnvelope, err := rlp.EncodeToBytes(env)
  93. if err != nil {
  94. log.Error(fmt.Sprintf("rlp.EncodeToBytes failed: %s", err))
  95. } else {
  96. err = s.db.Put(key.raw, rawEnvelope, nil)
  97. if err != nil {
  98. log.Error(fmt.Sprintf("Writing to DB failed: %s", err))
  99. }
  100. }
  101. }
  102. // DeliverMail responds with saved messages upon request by the
  103. // messages' owner.
  104. func (s *WMailServer) DeliverMail(peer *whisper.Peer, request *whisper.Envelope) {
  105. if peer == nil {
  106. log.Error("Whisper peer is nil")
  107. return
  108. }
  109. ok, lower, upper, bloom := s.validateRequest(peer.ID(), request)
  110. if ok {
  111. s.processRequest(peer, lower, upper, bloom)
  112. }
  113. }
  114. func (s *WMailServer) processRequest(peer *whisper.Peer, lower, upper uint32, bloom []byte) []*whisper.Envelope {
  115. ret := make([]*whisper.Envelope, 0)
  116. var err error
  117. var zero common.Hash
  118. kl := NewDbKey(lower, zero)
  119. ku := NewDbKey(upper+1, zero) // LevelDB is exclusive, while the Whisper API is inclusive
  120. i := s.db.NewIterator(&util.Range{Start: kl.raw, Limit: ku.raw}, nil)
  121. defer i.Release()
  122. for i.Next() {
  123. var envelope whisper.Envelope
  124. err = rlp.DecodeBytes(i.Value(), &envelope)
  125. if err != nil {
  126. log.Error(fmt.Sprintf("RLP decoding failed: %s", err))
  127. }
  128. if whisper.BloomFilterMatch(bloom, envelope.Bloom()) {
  129. if peer == nil {
  130. // used for test purposes
  131. ret = append(ret, &envelope)
  132. } else {
  133. err = s.w.SendP2PDirect(peer, &envelope)
  134. if err != nil {
  135. log.Error(fmt.Sprintf("Failed to send direct message to peer: %s", err))
  136. return nil
  137. }
  138. }
  139. }
  140. }
  141. err = i.Error()
  142. if err != nil {
  143. log.Error(fmt.Sprintf("Level DB iterator error: %s", err))
  144. }
  145. return ret
  146. }
  147. func (s *WMailServer) validateRequest(peerID []byte, request *whisper.Envelope) (bool, uint32, uint32, []byte) {
  148. if s.pow > 0.0 && request.PoW() < s.pow {
  149. return false, 0, 0, nil
  150. }
  151. f := whisper.Filter{KeySym: s.key}
  152. decrypted := request.Open(&f)
  153. if decrypted == nil {
  154. log.Warn("Failed to decrypt p2p request")
  155. return false, 0, 0, nil
  156. }
  157. src := crypto.FromECDSAPub(decrypted.Src)
  158. if len(src)-len(peerID) == 1 {
  159. src = src[1:]
  160. }
  161. // if you want to check the signature, you can do it here. e.g.:
  162. // if !bytes.Equal(peerID, src) {
  163. if src == nil {
  164. log.Warn("Wrong signature of p2p request")
  165. return false, 0, 0, nil
  166. }
  167. var bloom []byte
  168. payloadSize := len(decrypted.Payload)
  169. if payloadSize < 8 {
  170. log.Warn("Undersized p2p request")
  171. return false, 0, 0, nil
  172. } else if payloadSize == 8 {
  173. bloom = whisper.MakeFullNodeBloom()
  174. } else if payloadSize < 8+whisper.BloomFilterSize {
  175. log.Warn("Undersized bloom filter in p2p request")
  176. return false, 0, 0, nil
  177. } else {
  178. bloom = decrypted.Payload[8 : 8+whisper.BloomFilterSize]
  179. }
  180. lower := binary.BigEndian.Uint32(decrypted.Payload[:4])
  181. upper := binary.BigEndian.Uint32(decrypted.Payload[4:8])
  182. return true, lower, upper, bloom
  183. }