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