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