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