github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/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/enode"
    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, url string) (bool, error) {
   100  	n, err := enode.ParseV4(url)
   101  	if err != nil {
   102  		return false, err
   103  	}
   104  	return true, api.w.AllowP2PMessagesFromPeer(n.ID().Bytes())
   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  		if params.Dst, err = crypto.UnmarshalPubkey(req.PublicKey); err != nil {
   256  			return false, ErrInvalidPublicKey
   257  		}
   258  	}
   259  
   260  	// encrypt and sent message
   261  	whisperMsg, err := NewSentMessage(params)
   262  	if err != nil {
   263  		return false, err
   264  	}
   265  
   266  	env, err := whisperMsg.Wrap(params)
   267  	if err != nil {
   268  		return false, err
   269  	}
   270  
   271  	// send to specific node (skip PoW check)
   272  	if len(req.TargetPeer) > 0 {
   273  		n, err := enode.ParseV4(req.TargetPeer)
   274  		if err != nil {
   275  			return false, fmt.Errorf("failed to parse target peer: %s", err)
   276  		}
   277  		return true, api.w.SendP2PMessage(n.ID().Bytes(), env)
   278  	}
   279  
   280  	// ensure that the message PoW meets the node's minimum accepted PoW
   281  	if req.PowTarget < api.w.MinPow() {
   282  		return false, ErrTooLowPoW
   283  	}
   284  
   285  	return true, api.w.Send(env)
   286  }
   287  
   288  //go:generate gencodec -type Criteria -field-override criteriaOverride -out gen_criteria_json.go
   289  
   290  // Criteria holds various filter options for inbound messages.
   291  type Criteria struct {
   292  	SymKeyID     string      `json:"symKeyID"`
   293  	PrivateKeyID string      `json:"privateKeyID"`
   294  	Sig          []byte      `json:"sig"`
   295  	MinPow       float64     `json:"minPow"`
   296  	Topics       []TopicType `json:"topics"`
   297  	AllowP2P     bool        `json:"allowP2P"`
   298  }
   299  
   300  type criteriaOverride struct {
   301  	Sig hexutil.Bytes
   302  }
   303  
   304  // Messages set up a subscription that fires events when messages arrive that match
   305  // the given set of criteria.
   306  func (api *PublicWhisperAPI) Messages(ctx context.Context, crit Criteria) (*rpc.Subscription, error) {
   307  	var (
   308  		symKeyGiven = len(crit.SymKeyID) > 0
   309  		pubKeyGiven = len(crit.PrivateKeyID) > 0
   310  		err         error
   311  	)
   312  
   313  	// ensure that the RPC connection supports subscriptions
   314  	notifier, supported := rpc.NotifierFromContext(ctx)
   315  	if !supported {
   316  		return nil, rpc.ErrNotificationsUnsupported
   317  	}
   318  
   319  	// user must specify either a symmetric or an asymmetric key
   320  	if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
   321  		return nil, ErrSymAsym
   322  	}
   323  
   324  	filter := Filter{
   325  		PoW:      crit.MinPow,
   326  		Messages: make(map[common.Hash]*ReceivedMessage),
   327  		AllowP2P: crit.AllowP2P,
   328  	}
   329  
   330  	if len(crit.Sig) > 0 {
   331  		if filter.Src, err = crypto.UnmarshalPubkey(crit.Sig); err != nil {
   332  			return nil, ErrInvalidSigningPubKey
   333  		}
   334  	}
   335  
   336  	for i, bt := range crit.Topics {
   337  		if len(bt) == 0 || len(bt) > 4 {
   338  			return nil, fmt.Errorf("subscribe: topic %d has wrong size: %d", i, len(bt))
   339  		}
   340  		filter.Topics = append(filter.Topics, bt[:])
   341  	}
   342  
   343  	// listen for message that are encrypted with the given symmetric key
   344  	if symKeyGiven {
   345  		if len(filter.Topics) == 0 {
   346  			return nil, ErrNoTopics
   347  		}
   348  		key, err := api.w.GetSymKey(crit.SymKeyID)
   349  		if err != nil {
   350  			return nil, err
   351  		}
   352  		if !validateSymmetricKey(key) {
   353  			return nil, ErrInvalidSymmetricKey
   354  		}
   355  		filter.KeySym = key
   356  		filter.SymKeyHash = crypto.Keccak256Hash(filter.KeySym)
   357  	}
   358  
   359  	// listen for messages that are encrypted with the given public key
   360  	if pubKeyGiven {
   361  		filter.KeyAsym, err = api.w.GetPrivateKey(crit.PrivateKeyID)
   362  		if err != nil || filter.KeyAsym == nil {
   363  			return nil, ErrInvalidPublicKey
   364  		}
   365  	}
   366  
   367  	id, err := api.w.Subscribe(&filter)
   368  	if err != nil {
   369  		return nil, err
   370  	}
   371  
   372  	// create subscription and start waiting for message events
   373  	rpcSub := notifier.CreateSubscription()
   374  	go func() {
   375  		// for now poll internally, refactor whisper internal for channel support
   376  		ticker := time.NewTicker(250 * time.Millisecond)
   377  		defer ticker.Stop()
   378  
   379  		for {
   380  			select {
   381  			case <-ticker.C:
   382  				if filter := api.w.GetFilter(id); filter != nil {
   383  					for _, rpcMessage := range toMessage(filter.Retrieve()) {
   384  						if err := notifier.Notify(rpcSub.ID, rpcMessage); err != nil {
   385  							log.Error("Failed to send notification", "err", err)
   386  						}
   387  					}
   388  				}
   389  			case <-rpcSub.Err():
   390  				api.w.Unsubscribe(id)
   391  				return
   392  			case <-notifier.Closed():
   393  				api.w.Unsubscribe(id)
   394  				return
   395  			}
   396  		}
   397  	}()
   398  
   399  	return rpcSub, nil
   400  }
   401  
   402  //go:generate gencodec -type Message -field-override messageOverride -out gen_message_json.go
   403  
   404  // Message is the RPC representation of a whisper message.
   405  type Message struct {
   406  	Sig       []byte    `json:"sig,omitempty"`
   407  	TTL       uint32    `json:"ttl"`
   408  	Timestamp uint32    `json:"timestamp"`
   409  	Topic     TopicType `json:"topic"`
   410  	Payload   []byte    `json:"payload"`
   411  	Padding   []byte    `json:"padding"`
   412  	PoW       float64   `json:"pow"`
   413  	Hash      []byte    `json:"hash"`
   414  	Dst       []byte    `json:"recipientPublicKey,omitempty"`
   415  }
   416  
   417  type messageOverride struct {
   418  	Sig     hexutil.Bytes
   419  	Payload hexutil.Bytes
   420  	Padding hexutil.Bytes
   421  	Hash    hexutil.Bytes
   422  	Dst     hexutil.Bytes
   423  }
   424  
   425  // ToWhisperMessage converts an internal message into an API version.
   426  func ToWhisperMessage(message *ReceivedMessage) *Message {
   427  	msg := Message{
   428  		Payload:   message.Payload,
   429  		Padding:   message.Padding,
   430  		Timestamp: message.Sent,
   431  		TTL:       message.TTL,
   432  		PoW:       message.PoW,
   433  		Hash:      message.EnvelopeHash.Bytes(),
   434  		Topic:     message.Topic,
   435  	}
   436  
   437  	if message.Dst != nil {
   438  		b := crypto.FromECDSAPub(message.Dst)
   439  		if b != nil {
   440  			msg.Dst = b
   441  		}
   442  	}
   443  
   444  	if isMessageSigned(message.Raw[0]) {
   445  		b := crypto.FromECDSAPub(message.SigToPubKey())
   446  		if b != nil {
   447  			msg.Sig = b
   448  		}
   449  	}
   450  
   451  	return &msg
   452  }
   453  
   454  // toMessage converts a set of messages to its RPC representation.
   455  func toMessage(messages []*ReceivedMessage) []*Message {
   456  	msgs := make([]*Message, len(messages))
   457  	for i, msg := range messages {
   458  		msgs[i] = ToWhisperMessage(msg)
   459  	}
   460  	return msgs
   461  }
   462  
   463  // GetFilterMessages returns the messages that match the filter criteria and
   464  // are received between the last poll and now.
   465  func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) {
   466  	api.mu.Lock()
   467  	f := api.w.GetFilter(id)
   468  	if f == nil {
   469  		api.mu.Unlock()
   470  		return nil, fmt.Errorf("filter not found")
   471  	}
   472  	api.lastUsed[id] = time.Now()
   473  	api.mu.Unlock()
   474  
   475  	receivedMessages := f.Retrieve()
   476  	messages := make([]*Message, 0, len(receivedMessages))
   477  	for _, msg := range receivedMessages {
   478  		messages = append(messages, ToWhisperMessage(msg))
   479  	}
   480  
   481  	return messages, nil
   482  }
   483  
   484  // DeleteMessageFilter deletes a filter.
   485  func (api *PublicWhisperAPI) DeleteMessageFilter(id string) (bool, error) {
   486  	api.mu.Lock()
   487  	defer api.mu.Unlock()
   488  
   489  	delete(api.lastUsed, id)
   490  	return true, api.w.Unsubscribe(id)
   491  }
   492  
   493  // NewMessageFilter creates a new filter that can be used to poll for
   494  // (new) messages that satisfy the given criteria.
   495  func (api *PublicWhisperAPI) NewMessageFilter(req Criteria) (string, error) {
   496  	var (
   497  		src     *ecdsa.PublicKey
   498  		keySym  []byte
   499  		keyAsym *ecdsa.PrivateKey
   500  		topics  [][]byte
   501  
   502  		symKeyGiven  = len(req.SymKeyID) > 0
   503  		asymKeyGiven = len(req.PrivateKeyID) > 0
   504  
   505  		err error
   506  	)
   507  
   508  	// user must specify either a symmetric or an asymmetric key
   509  	if (symKeyGiven && asymKeyGiven) || (!symKeyGiven && !asymKeyGiven) {
   510  		return "", ErrSymAsym
   511  	}
   512  
   513  	if len(req.Sig) > 0 {
   514  		if src, err = crypto.UnmarshalPubkey(req.Sig); err != nil {
   515  			return "", ErrInvalidSigningPubKey
   516  		}
   517  	}
   518  
   519  	if symKeyGiven {
   520  		if keySym, err = api.w.GetSymKey(req.SymKeyID); err != nil {
   521  			return "", err
   522  		}
   523  		if !validateSymmetricKey(keySym) {
   524  			return "", ErrInvalidSymmetricKey
   525  		}
   526  	}
   527  
   528  	if asymKeyGiven {
   529  		if keyAsym, err = api.w.GetPrivateKey(req.PrivateKeyID); err != nil {
   530  			return "", err
   531  		}
   532  	}
   533  
   534  	if len(req.Topics) > 0 {
   535  		topics = make([][]byte, 0, len(req.Topics))
   536  		for _, topic := range req.Topics {
   537  			topics = append(topics, topic[:])
   538  		}
   539  	}
   540  
   541  	f := &Filter{
   542  		Src:      src,
   543  		KeySym:   keySym,
   544  		KeyAsym:  keyAsym,
   545  		PoW:      req.MinPow,
   546  		AllowP2P: req.AllowP2P,
   547  		Topics:   topics,
   548  		Messages: make(map[common.Hash]*ReceivedMessage),
   549  	}
   550  
   551  	id, err := api.w.Subscribe(f)
   552  	if err != nil {
   553  		return "", err
   554  	}
   555  
   556  	api.mu.Lock()
   557  	api.lastUsed[id] = time.Now()
   558  	api.mu.Unlock()
   559  
   560  	return id, nil
   561  }