github.com/needkane/go-ethereum@v1.7.4-0.20180131070256-c212876ea2b7/whisper/whisperv6/api.go (about)

     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  
    17  package whisperv6
    18  
    19  import (
    20  	"context"
    21  	"crypto/ecdsa"
    22  	"errors"
    23  	"fmt"
    24  	"sync"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/hexutil"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"github.com/ethereum/go-ethereum/p2p/discover"
    32  	"github.com/ethereum/go-ethereum/rpc"
    33  )
    34  
    35  const (
    36  	filterTimeout = 300 // filters are considered timeout out after filterTimeout seconds
    37  )
    38  
    39  // List of errors
    40  var (
    41  	ErrSymAsym              = errors.New("specify either a symmetric or an asymmetric key")
    42  	ErrInvalidSymmetricKey  = errors.New("invalid symmetric key")
    43  	ErrInvalidPublicKey     = errors.New("invalid public key")
    44  	ErrInvalidSigningPubKey = errors.New("invalid signing public key")
    45  	ErrTooLowPoW            = errors.New("message rejected, PoW too low")
    46  	ErrNoTopics             = errors.New("missing topic(s)")
    47  )
    48  
    49  // PublicWhisperAPI provides the whisper RPC service that can be
    50  // use publicly without security implications.
    51  type PublicWhisperAPI struct {
    52  	w *Whisper
    53  
    54  	mu       sync.Mutex
    55  	lastUsed map[string]time.Time // keeps track when a filter was polled for the last time.
    56  }
    57  
    58  // NewPublicWhisperAPI create a new RPC whisper service.
    59  func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI {
    60  	api := &PublicWhisperAPI{
    61  		w:        w,
    62  		lastUsed: make(map[string]time.Time),
    63  	}
    64  
    65  	go api.run()
    66  	return api
    67  }
    68  
    69  // run the api event loop.
    70  // this loop deletes filter that have not been used within filterTimeout
    71  func (api *PublicWhisperAPI) run() {
    72  	timeout := time.NewTicker(2 * time.Minute)
    73  	for {
    74  		<-timeout.C
    75  
    76  		api.mu.Lock()
    77  		for id, lastUsed := range api.lastUsed {
    78  			if time.Since(lastUsed).Seconds() >= filterTimeout {
    79  				delete(api.lastUsed, id)
    80  				if err := api.w.Unsubscribe(id); err != nil {
    81  					log.Error("could not unsubscribe whisper filter", "error", err)
    82  				}
    83  				log.Debug("delete whisper filter (timeout)", "id", id)
    84  			}
    85  		}
    86  		api.mu.Unlock()
    87  	}
    88  }
    89  
    90  // Version returns the Whisper sub-protocol version.
    91  func (api *PublicWhisperAPI) Version(ctx context.Context) string {
    92  	return ProtocolVersionStr
    93  }
    94  
    95  // Info contains diagnostic information.
    96  type Info struct {
    97  	Memory         int     `json:"memory"`         // Memory size of the floating messages in bytes.
    98  	Messages       int     `json:"messages"`       // Number of floating messages.
    99  	MinPow         float64 `json:"minPow"`         // Minimal accepted PoW
   100  	MaxMessageSize uint32  `json:"maxMessageSize"` // Maximum accepted message size
   101  }
   102  
   103  // Info returns diagnostic information about the whisper node.
   104  func (api *PublicWhisperAPI) Info(ctx context.Context) Info {
   105  	stats := api.w.Stats()
   106  	return Info{
   107  		Memory:         stats.memoryUsed,
   108  		Messages:       len(api.w.messageQueue) + len(api.w.p2pMsgQueue),
   109  		MinPow:         api.w.MinPow(),
   110  		MaxMessageSize: api.w.MaxMessageSize(),
   111  	}
   112  }
   113  
   114  // SetMaxMessageSize sets the maximum message size that is accepted.
   115  // Upper limit is defined by MaxMessageSize.
   116  func (api *PublicWhisperAPI) SetMaxMessageSize(ctx context.Context, size uint32) (bool, error) {
   117  	return true, api.w.SetMaxMessageSize(size)
   118  }
   119  
   120  // SetMinPoW sets the minimum PoW, and notifies the peers.
   121  func (api *PublicWhisperAPI) SetMinPoW(ctx context.Context, pow float64) (bool, error) {
   122  	return true, api.w.SetMinimumPoW(pow)
   123  }
   124  
   125  // SetBloomFilter sets the new value of bloom filter, and notifies the peers.
   126  func (api *PublicWhisperAPI) SetBloomFilter(ctx context.Context, bloom hexutil.Bytes) (bool, error) {
   127  	return true, api.w.SetBloomFilter(bloom)
   128  }
   129  
   130  // MarkTrustedPeer marks a peer trusted, which will allow it to send historic (expired) messages.
   131  // Note: This function is not adding new nodes, the node needs to exists as a peer.
   132  func (api *PublicWhisperAPI) MarkTrustedPeer(ctx context.Context, enode string) (bool, error) {
   133  	n, err := discover.ParseNode(enode)
   134  	if err != nil {
   135  		return false, err
   136  	}
   137  	return true, api.w.AllowP2PMessagesFromPeer(n.ID[:])
   138  }
   139  
   140  // NewKeyPair generates a new public and private key pair for message decryption and encryption.
   141  // It returns an ID that can be used to refer to the keypair.
   142  func (api *PublicWhisperAPI) NewKeyPair(ctx context.Context) (string, error) {
   143  	return api.w.NewKeyPair()
   144  }
   145  
   146  // AddPrivateKey imports the given private key.
   147  func (api *PublicWhisperAPI) AddPrivateKey(ctx context.Context, privateKey hexutil.Bytes) (string, error) {
   148  	key, err := crypto.ToECDSA(privateKey)
   149  	if err != nil {
   150  		return "", err
   151  	}
   152  	return api.w.AddKeyPair(key)
   153  }
   154  
   155  // DeleteKeyPair removes the key with the given key if it exists.
   156  func (api *PublicWhisperAPI) DeleteKeyPair(ctx context.Context, key string) (bool, error) {
   157  	if ok := api.w.DeleteKeyPair(key); ok {
   158  		return true, nil
   159  	}
   160  	return false, fmt.Errorf("key pair %s not found", key)
   161  }
   162  
   163  // HasKeyPair returns an indication if the node has a key pair that is associated with the given id.
   164  func (api *PublicWhisperAPI) HasKeyPair(ctx context.Context, id string) bool {
   165  	return api.w.HasKeyPair(id)
   166  }
   167  
   168  // GetPublicKey returns the public key associated with the given key. The key is the hex
   169  // encoded representation of a key in the form specified in section 4.3.6 of ANSI X9.62.
   170  func (api *PublicWhisperAPI) GetPublicKey(ctx context.Context, id string) (hexutil.Bytes, error) {
   171  	key, err := api.w.GetPrivateKey(id)
   172  	if err != nil {
   173  		return hexutil.Bytes{}, err
   174  	}
   175  	return crypto.FromECDSAPub(&key.PublicKey), nil
   176  }
   177  
   178  // GetPrivateKey returns the private key associated with the given key. The key is the hex
   179  // encoded representation of a key in the form specified in section 4.3.6 of ANSI X9.62.
   180  func (api *PublicWhisperAPI) GetPrivateKey(ctx context.Context, id string) (hexutil.Bytes, error) {
   181  	key, err := api.w.GetPrivateKey(id)
   182  	if err != nil {
   183  		return hexutil.Bytes{}, err
   184  	}
   185  	return crypto.FromECDSA(key), nil
   186  }
   187  
   188  // NewSymKey generate a random symmetric key.
   189  // It returns an ID that can be used to refer to the key.
   190  // Can be used encrypting and decrypting messages where the key is known to both parties.
   191  func (api *PublicWhisperAPI) NewSymKey(ctx context.Context) (string, error) {
   192  	return api.w.GenerateSymKey()
   193  }
   194  
   195  // AddSymKey import a symmetric key.
   196  // It returns an ID that can be used to refer to the key.
   197  // Can be used encrypting and decrypting messages where the key is known to both parties.
   198  func (api *PublicWhisperAPI) AddSymKey(ctx context.Context, key hexutil.Bytes) (string, error) {
   199  	return api.w.AddSymKeyDirect([]byte(key))
   200  }
   201  
   202  // GenerateSymKeyFromPassword derive a key from the given password, stores it, and returns its ID.
   203  func (api *PublicWhisperAPI) GenerateSymKeyFromPassword(ctx context.Context, passwd string) (string, error) {
   204  	return api.w.AddSymKeyFromPassword(passwd)
   205  }
   206  
   207  // HasSymKey returns an indication if the node has a symmetric key associated with the given key.
   208  func (api *PublicWhisperAPI) HasSymKey(ctx context.Context, id string) bool {
   209  	return api.w.HasSymKey(id)
   210  }
   211  
   212  // GetSymKey returns the symmetric key associated with the given id.
   213  func (api *PublicWhisperAPI) GetSymKey(ctx context.Context, id string) (hexutil.Bytes, error) {
   214  	return api.w.GetSymKey(id)
   215  }
   216  
   217  // DeleteSymKey deletes the symmetric key that is associated with the given id.
   218  func (api *PublicWhisperAPI) DeleteSymKey(ctx context.Context, id string) bool {
   219  	return api.w.DeleteSymKey(id)
   220  }
   221  
   222  //go:generate gencodec -type NewMessage -field-override newMessageOverride -out gen_newmessage_json.go
   223  
   224  // NewMessage represents a new whisper message that is posted through the RPC.
   225  type NewMessage struct {
   226  	SymKeyID   string    `json:"symKeyID"`
   227  	PublicKey  []byte    `json:"pubKey"`
   228  	Sig        string    `json:"sig"`
   229  	TTL        uint32    `json:"ttl"`
   230  	Topic      TopicType `json:"topic"`
   231  	Payload    []byte    `json:"payload"`
   232  	Padding    []byte    `json:"padding"`
   233  	PowTime    uint32    `json:"powTime"`
   234  	PowTarget  float64   `json:"powTarget"`
   235  	TargetPeer string    `json:"targetPeer"`
   236  }
   237  
   238  type newMessageOverride struct {
   239  	PublicKey hexutil.Bytes
   240  	Payload   hexutil.Bytes
   241  	Padding   hexutil.Bytes
   242  }
   243  
   244  // Post a message on the Whisper network.
   245  func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (bool, error) {
   246  	var (
   247  		symKeyGiven = len(req.SymKeyID) > 0
   248  		pubKeyGiven = len(req.PublicKey) > 0
   249  		err         error
   250  	)
   251  
   252  	// user must specify either a symmetric or an asymmetric key
   253  	if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
   254  		return false, ErrSymAsym
   255  	}
   256  
   257  	params := &MessageParams{
   258  		TTL:      req.TTL,
   259  		Payload:  req.Payload,
   260  		Padding:  req.Padding,
   261  		WorkTime: req.PowTime,
   262  		PoW:      req.PowTarget,
   263  		Topic:    req.Topic,
   264  	}
   265  
   266  	// Set key that is used to sign the message
   267  	if len(req.Sig) > 0 {
   268  		if params.Src, err = api.w.GetPrivateKey(req.Sig); err != nil {
   269  			return false, err
   270  		}
   271  	}
   272  
   273  	// Set symmetric key that is used to encrypt the message
   274  	if symKeyGiven {
   275  		if params.Topic == (TopicType{}) { // topics are mandatory with symmetric encryption
   276  			return false, ErrNoTopics
   277  		}
   278  		if params.KeySym, err = api.w.GetSymKey(req.SymKeyID); err != nil {
   279  			return false, err
   280  		}
   281  		if !validateDataIntegrity(params.KeySym, aesKeyLength) {
   282  			return false, ErrInvalidSymmetricKey
   283  		}
   284  	}
   285  
   286  	// Set asymmetric key that is used to encrypt the message
   287  	if pubKeyGiven {
   288  		params.Dst = crypto.ToECDSAPub(req.PublicKey)
   289  		if !ValidatePublicKey(params.Dst) {
   290  			return false, ErrInvalidPublicKey
   291  		}
   292  	}
   293  
   294  	// encrypt and sent message
   295  	whisperMsg, err := newSentMessage(params)
   296  	if err != nil {
   297  		return false, err
   298  	}
   299  
   300  	env, err := whisperMsg.Wrap(params)
   301  	if err != nil {
   302  		return false, err
   303  	}
   304  
   305  	// send to specific node (skip PoW check)
   306  	if len(req.TargetPeer) > 0 {
   307  		n, err := discover.ParseNode(req.TargetPeer)
   308  		if err != nil {
   309  			return false, fmt.Errorf("failed to parse target peer: %s", err)
   310  		}
   311  		return true, api.w.SendP2PMessage(n.ID[:], env)
   312  	}
   313  
   314  	// ensure that the message PoW meets the node's minimum accepted PoW
   315  	if req.PowTarget < api.w.MinPow() {
   316  		return false, ErrTooLowPoW
   317  	}
   318  
   319  	return true, api.w.Send(env)
   320  }
   321  
   322  //go:generate gencodec -type Criteria -field-override criteriaOverride -out gen_criteria_json.go
   323  
   324  // Criteria holds various filter options for inbound messages.
   325  type Criteria struct {
   326  	SymKeyID     string      `json:"symKeyID"`
   327  	PrivateKeyID string      `json:"privateKeyID"`
   328  	Sig          []byte      `json:"sig"`
   329  	MinPow       float64     `json:"minPow"`
   330  	Topics       []TopicType `json:"topics"`
   331  	AllowP2P     bool        `json:"allowP2P"`
   332  }
   333  
   334  type criteriaOverride struct {
   335  	Sig hexutil.Bytes
   336  }
   337  
   338  // Messages set up a subscription that fires events when messages arrive that match
   339  // the given set of criteria.
   340  func (api *PublicWhisperAPI) Messages(ctx context.Context, crit Criteria) (*rpc.Subscription, error) {
   341  	var (
   342  		symKeyGiven = len(crit.SymKeyID) > 0
   343  		pubKeyGiven = len(crit.PrivateKeyID) > 0
   344  		err         error
   345  	)
   346  
   347  	// ensure that the RPC connection supports subscriptions
   348  	notifier, supported := rpc.NotifierFromContext(ctx)
   349  	if !supported {
   350  		return nil, rpc.ErrNotificationsUnsupported
   351  	}
   352  
   353  	// user must specify either a symmetric or an asymmetric key
   354  	if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
   355  		return nil, ErrSymAsym
   356  	}
   357  
   358  	filter := Filter{
   359  		PoW:      crit.MinPow,
   360  		Messages: make(map[common.Hash]*ReceivedMessage),
   361  		AllowP2P: crit.AllowP2P,
   362  	}
   363  
   364  	if len(crit.Sig) > 0 {
   365  		filter.Src = crypto.ToECDSAPub(crit.Sig)
   366  		if !ValidatePublicKey(filter.Src) {
   367  			return nil, ErrInvalidSigningPubKey
   368  		}
   369  	}
   370  
   371  	for i, bt := range crit.Topics {
   372  		if len(bt) == 0 || len(bt) > 4 {
   373  			return nil, fmt.Errorf("subscribe: topic %d has wrong size: %d", i, len(bt))
   374  		}
   375  		filter.Topics = append(filter.Topics, bt[:])
   376  	}
   377  
   378  	// listen for message that are encrypted with the given symmetric key
   379  	if symKeyGiven {
   380  		if len(filter.Topics) == 0 {
   381  			return nil, ErrNoTopics
   382  		}
   383  		key, err := api.w.GetSymKey(crit.SymKeyID)
   384  		if err != nil {
   385  			return nil, err
   386  		}
   387  		if !validateDataIntegrity(key, aesKeyLength) {
   388  			return nil, ErrInvalidSymmetricKey
   389  		}
   390  		filter.KeySym = key
   391  		filter.SymKeyHash = crypto.Keccak256Hash(filter.KeySym)
   392  	}
   393  
   394  	// listen for messages that are encrypted with the given public key
   395  	if pubKeyGiven {
   396  		filter.KeyAsym, err = api.w.GetPrivateKey(crit.PrivateKeyID)
   397  		if err != nil || filter.KeyAsym == nil {
   398  			return nil, ErrInvalidPublicKey
   399  		}
   400  	}
   401  
   402  	id, err := api.w.Subscribe(&filter)
   403  	if err != nil {
   404  		return nil, err
   405  	}
   406  
   407  	// create subscription and start waiting for message events
   408  	rpcSub := notifier.CreateSubscription()
   409  	go func() {
   410  		// for now poll internally, refactor whisper internal for channel support
   411  		ticker := time.NewTicker(250 * time.Millisecond)
   412  		defer ticker.Stop()
   413  
   414  		for {
   415  			select {
   416  			case <-ticker.C:
   417  				if filter := api.w.GetFilter(id); filter != nil {
   418  					for _, rpcMessage := range toMessage(filter.Retrieve()) {
   419  						if err := notifier.Notify(rpcSub.ID, rpcMessage); err != nil {
   420  							log.Error("Failed to send notification", "err", err)
   421  						}
   422  					}
   423  				}
   424  			case <-rpcSub.Err():
   425  				api.w.Unsubscribe(id)
   426  				return
   427  			case <-notifier.Closed():
   428  				api.w.Unsubscribe(id)
   429  				return
   430  			}
   431  		}
   432  	}()
   433  
   434  	return rpcSub, nil
   435  }
   436  
   437  //go:generate gencodec -type Message -field-override messageOverride -out gen_message_json.go
   438  
   439  // Message is the RPC representation of a whisper message.
   440  type Message struct {
   441  	Sig       []byte    `json:"sig,omitempty"`
   442  	TTL       uint32    `json:"ttl"`
   443  	Timestamp uint32    `json:"timestamp"`
   444  	Topic     TopicType `json:"topic"`
   445  	Payload   []byte    `json:"payload"`
   446  	Padding   []byte    `json:"padding"`
   447  	PoW       float64   `json:"pow"`
   448  	Hash      []byte    `json:"hash"`
   449  	Dst       []byte    `json:"recipientPublicKey,omitempty"`
   450  }
   451  
   452  type messageOverride struct {
   453  	Sig     hexutil.Bytes
   454  	Payload hexutil.Bytes
   455  	Padding hexutil.Bytes
   456  	Hash    hexutil.Bytes
   457  	Dst     hexutil.Bytes
   458  }
   459  
   460  // ToWhisperMessage converts an internal message into an API version.
   461  func ToWhisperMessage(message *ReceivedMessage) *Message {
   462  	msg := Message{
   463  		Payload:   message.Payload,
   464  		Padding:   message.Padding,
   465  		Timestamp: message.Sent,
   466  		TTL:       message.TTL,
   467  		PoW:       message.PoW,
   468  		Hash:      message.EnvelopeHash.Bytes(),
   469  		Topic:     message.Topic,
   470  	}
   471  
   472  	if message.Dst != nil {
   473  		b := crypto.FromECDSAPub(message.Dst)
   474  		if b != nil {
   475  			msg.Dst = b
   476  		}
   477  	}
   478  
   479  	if isMessageSigned(message.Raw[0]) {
   480  		b := crypto.FromECDSAPub(message.SigToPubKey())
   481  		if b != nil {
   482  			msg.Sig = b
   483  		}
   484  	}
   485  
   486  	return &msg
   487  }
   488  
   489  // toMessage converts a set of messages to its RPC representation.
   490  func toMessage(messages []*ReceivedMessage) []*Message {
   491  	msgs := make([]*Message, len(messages))
   492  	for i, msg := range messages {
   493  		msgs[i] = ToWhisperMessage(msg)
   494  	}
   495  	return msgs
   496  }
   497  
   498  // GetFilterMessages returns the messages that match the filter criteria and
   499  // are received between the last poll and now.
   500  func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) {
   501  	api.mu.Lock()
   502  	f := api.w.GetFilter(id)
   503  	if f == nil {
   504  		api.mu.Unlock()
   505  		return nil, fmt.Errorf("filter not found")
   506  	}
   507  	api.lastUsed[id] = time.Now()
   508  	api.mu.Unlock()
   509  
   510  	receivedMessages := f.Retrieve()
   511  	messages := make([]*Message, 0, len(receivedMessages))
   512  	for _, msg := range receivedMessages {
   513  		messages = append(messages, ToWhisperMessage(msg))
   514  	}
   515  
   516  	return messages, nil
   517  }
   518  
   519  // DeleteMessageFilter deletes a filter.
   520  func (api *PublicWhisperAPI) DeleteMessageFilter(id string) (bool, error) {
   521  	api.mu.Lock()
   522  	defer api.mu.Unlock()
   523  
   524  	delete(api.lastUsed, id)
   525  	return true, api.w.Unsubscribe(id)
   526  }
   527  
   528  // NewMessageFilter creates a new filter that can be used to poll for
   529  // (new) messages that satisfy the given criteria.
   530  func (api *PublicWhisperAPI) NewMessageFilter(req Criteria) (string, error) {
   531  	var (
   532  		src     *ecdsa.PublicKey
   533  		keySym  []byte
   534  		keyAsym *ecdsa.PrivateKey
   535  		topics  [][]byte
   536  
   537  		symKeyGiven  = len(req.SymKeyID) > 0
   538  		asymKeyGiven = len(req.PrivateKeyID) > 0
   539  
   540  		err error
   541  	)
   542  
   543  	// user must specify either a symmetric or an asymmetric key
   544  	if (symKeyGiven && asymKeyGiven) || (!symKeyGiven && !asymKeyGiven) {
   545  		return "", ErrSymAsym
   546  	}
   547  
   548  	if len(req.Sig) > 0 {
   549  		src = crypto.ToECDSAPub(req.Sig)
   550  		if !ValidatePublicKey(src) {
   551  			return "", ErrInvalidSigningPubKey
   552  		}
   553  	}
   554  
   555  	if symKeyGiven {
   556  		if keySym, err = api.w.GetSymKey(req.SymKeyID); err != nil {
   557  			return "", err
   558  		}
   559  		if !validateDataIntegrity(keySym, aesKeyLength) {
   560  			return "", ErrInvalidSymmetricKey
   561  		}
   562  	}
   563  
   564  	if asymKeyGiven {
   565  		if keyAsym, err = api.w.GetPrivateKey(req.PrivateKeyID); err != nil {
   566  			return "", err
   567  		}
   568  	}
   569  
   570  	if len(req.Topics) > 0 {
   571  		topics = make([][]byte, 0, len(req.Topics))
   572  		for _, topic := range req.Topics {
   573  			topics = append(topics, topic[:])
   574  		}
   575  	}
   576  
   577  	f := &Filter{
   578  		Src:      src,
   579  		KeySym:   keySym,
   580  		KeyAsym:  keyAsym,
   581  		PoW:      req.MinPow,
   582  		AllowP2P: req.AllowP2P,
   583  		Topics:   topics,
   584  		Messages: make(map[common.Hash]*ReceivedMessage),
   585  	}
   586  
   587  	id, err := api.w.Subscribe(f)
   588  	if err != nil {
   589  		return "", err
   590  	}
   591  
   592  	api.mu.Lock()
   593  	api.lastUsed[id] = time.Now()
   594  	api.mu.Unlock()
   595  
   596  	return id, nil
   597  }