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