github.com/aquanetwork/aquachain@v1.7.8/opt/whisper/mailserver/mailserver.go (about)

     1  // Copyright 2017 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package mailserver
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/binary"
    22  	"fmt"
    23  
    24  	"github.com/syndtr/goleveldb/leveldb"
    25  	"github.com/syndtr/goleveldb/leveldb/util"
    26  	"gitlab.com/aquachain/aquachain/cmd/utils"
    27  	"gitlab.com/aquachain/aquachain/common"
    28  	"gitlab.com/aquachain/aquachain/common/log"
    29  	"gitlab.com/aquachain/aquachain/crypto"
    30  	whisper "gitlab.com/aquachain/aquachain/opt/whisper/whisperv6"
    31  	"gitlab.com/aquachain/aquachain/rlp"
    32  )
    33  
    34  type WMailServer struct {
    35  	db  *leveldb.DB
    36  	w   *whisper.Whisper
    37  	pow float64
    38  	key []byte
    39  }
    40  
    41  type DBKey struct {
    42  	timestamp uint32
    43  	hash      common.Hash
    44  	raw       []byte
    45  }
    46  
    47  func NewDbKey(t uint32, h common.Hash) *DBKey {
    48  	const sz = common.HashLength + 4
    49  	var k DBKey
    50  	k.timestamp = t
    51  	k.hash = h
    52  	k.raw = make([]byte, sz)
    53  	binary.BigEndian.PutUint32(k.raw, k.timestamp)
    54  	copy(k.raw[4:], k.hash[:])
    55  	return &k
    56  }
    57  
    58  func (s *WMailServer) Init(shh *whisper.Whisper, path string, password string, pow float64) {
    59  	var err error
    60  	if len(path) == 0 {
    61  		utils.Fatalf("DB file is not specified")
    62  	}
    63  
    64  	if len(password) == 0 {
    65  		utils.Fatalf("Password is not specified for MailServer")
    66  	}
    67  
    68  	s.db, err = leveldb.OpenFile(path, nil)
    69  	if err != nil {
    70  		utils.Fatalf("Failed to open DB file: %s", err)
    71  	}
    72  
    73  	s.w = shh
    74  	s.pow = pow
    75  
    76  	MailServerKeyID, err := s.w.AddSymKeyFromPassword(password)
    77  	if err != nil {
    78  		utils.Fatalf("Failed to create symmetric key for MailServer: %s", err)
    79  	}
    80  	s.key, err = s.w.GetSymKey(MailServerKeyID)
    81  	if err != nil {
    82  		utils.Fatalf("Failed to save symmetric key for MailServer")
    83  	}
    84  }
    85  
    86  func (s *WMailServer) Close() {
    87  	if s.db != nil {
    88  		s.db.Close()
    89  	}
    90  }
    91  
    92  func (s *WMailServer) Archive(env *whisper.Envelope) {
    93  	key := NewDbKey(env.Expiry-env.TTL, env.Hash())
    94  	rawEnvelope, err := rlp.EncodeToBytes(env)
    95  	if err != nil {
    96  		log.Error(fmt.Sprintf("rlp.EncodeToBytes failed: %s", err))
    97  	} else {
    98  		err = s.db.Put(key.raw, rawEnvelope, nil)
    99  		if err != nil {
   100  			log.Error(fmt.Sprintf("Writing to DB failed: %s", err))
   101  		}
   102  	}
   103  }
   104  
   105  func (s *WMailServer) DeliverMail(peer *whisper.Peer, request *whisper.Envelope) {
   106  	if peer == nil {
   107  		log.Error("Whisper peer is nil")
   108  		return
   109  	}
   110  
   111  	ok, lower, upper, topic := s.validateRequest(peer.ID(), request)
   112  	if ok {
   113  		s.processRequest(peer, lower, upper, topic)
   114  	}
   115  }
   116  
   117  func (s *WMailServer) processRequest(peer *whisper.Peer, lower, upper uint32, topic whisper.TopicType) []*whisper.Envelope {
   118  	ret := make([]*whisper.Envelope, 0)
   119  	var err error
   120  	var zero common.Hash
   121  	var empty whisper.TopicType
   122  	kl := NewDbKey(lower, zero)
   123  	ku := NewDbKey(upper, zero)
   124  	i := s.db.NewIterator(&util.Range{Start: kl.raw, Limit: ku.raw}, nil)
   125  	defer i.Release()
   126  
   127  	for i.Next() {
   128  		var envelope whisper.Envelope
   129  		err = rlp.DecodeBytes(i.Value(), &envelope)
   130  		if err != nil {
   131  			log.Error(fmt.Sprintf("RLP decoding failed: %s", err))
   132  		}
   133  
   134  		if topic == empty || envelope.Topic == topic {
   135  			if peer == nil {
   136  				// used for test purposes
   137  				ret = append(ret, &envelope)
   138  			} else {
   139  				err = s.w.SendP2PDirect(peer, &envelope)
   140  				if err != nil {
   141  					log.Error(fmt.Sprintf("Failed to send direct message to peer: %s", err))
   142  					return nil
   143  				}
   144  			}
   145  		}
   146  	}
   147  
   148  	err = i.Error()
   149  	if err != nil {
   150  		log.Error(fmt.Sprintf("Level DB iterator error: %s", err))
   151  	}
   152  
   153  	return ret
   154  }
   155  
   156  func (s *WMailServer) validateRequest(peerID []byte, request *whisper.Envelope) (bool, uint32, uint32, whisper.TopicType) {
   157  	var topic whisper.TopicType
   158  	if s.pow > 0.0 && request.PoW() < s.pow {
   159  		return false, 0, 0, topic
   160  	}
   161  
   162  	f := whisper.Filter{KeySym: s.key}
   163  	decrypted := request.Open(&f)
   164  	if decrypted == nil {
   165  		log.Warn(fmt.Sprintf("Failed to decrypt p2p request"))
   166  		return false, 0, 0, topic
   167  	}
   168  
   169  	if len(decrypted.Payload) < 8 {
   170  		log.Warn(fmt.Sprintf("Undersized p2p request"))
   171  		return false, 0, 0, topic
   172  	}
   173  
   174  	src := crypto.FromECDSAPub(decrypted.Src)
   175  	if len(src)-len(peerID) == 1 {
   176  		src = src[1:]
   177  	}
   178  	if !bytes.Equal(peerID, src) {
   179  		log.Warn(fmt.Sprintf("Wrong signature of p2p request"))
   180  		return false, 0, 0, topic
   181  	}
   182  
   183  	lower := binary.BigEndian.Uint32(decrypted.Payload[:4])
   184  	upper := binary.BigEndian.Uint32(decrypted.Payload[4:8])
   185  
   186  	if len(decrypted.Payload) >= 8+whisper.TopicLength {
   187  		topic = whisper.BytesToTopic(decrypted.Payload[8:])
   188  	}
   189  
   190  	return true, lower, upper, topic
   191  }