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