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