whisper.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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. package whisperv5
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. crand "crypto/rand"
  21. "crypto/sha256"
  22. "fmt"
  23. "runtime"
  24. "sync"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/p2p"
  30. "github.com/ethereum/go-ethereum/rpc"
  31. "github.com/syndtr/goleveldb/leveldb/errors"
  32. "golang.org/x/crypto/pbkdf2"
  33. "golang.org/x/sync/syncmap"
  34. set "gopkg.in/fatih/set.v0"
  35. )
  36. type Statistics struct {
  37. messagesCleared int
  38. memoryCleared int
  39. memoryUsed int
  40. cycles int
  41. totalMessagesCleared int
  42. }
  43. const (
  44. minPowIdx = iota // Minimal PoW required by the whisper node
  45. maxMsgSizeIdx = iota // Maximal message length allowed by the whisper node
  46. overflowIdx = iota // Indicator of message queue overflow
  47. )
  48. // Whisper represents a dark communication interface through the Ethereum
  49. // network, using its very own P2P communication layer.
  50. type Whisper struct {
  51. protocol p2p.Protocol // Protocol description and parameters
  52. filters *Filters // Message filters installed with Subscribe function
  53. privateKeys map[string]*ecdsa.PrivateKey // Private key storage
  54. symKeys map[string][]byte // Symmetric key storage
  55. keyMu sync.RWMutex // Mutex associated with key storages
  56. poolMu sync.RWMutex // Mutex to sync the message and expiration pools
  57. envelopes map[common.Hash]*Envelope // Pool of envelopes currently tracked by this node
  58. expirations map[uint32]*set.SetNonTS // Message expiration pool
  59. peerMu sync.RWMutex // Mutex to sync the active peer set
  60. peers map[*Peer]struct{} // Set of currently active peers
  61. messageQueue chan *Envelope // Message queue for normal whisper messages
  62. p2pMsgQueue chan *Envelope // Message queue for peer-to-peer messages (not to be forwarded any further)
  63. quit chan struct{} // Channel used for graceful exit
  64. settings syncmap.Map // holds configuration settings that can be dynamically changed
  65. statsMu sync.Mutex // guard stats
  66. stats Statistics // Statistics of whisper node
  67. mailServer MailServer // MailServer interface
  68. }
  69. // New creates a Whisper client ready to communicate through the Ethereum P2P network.
  70. func New(cfg *Config) *Whisper {
  71. if cfg == nil {
  72. cfg = &DefaultConfig
  73. }
  74. whisper := &Whisper{
  75. privateKeys: make(map[string]*ecdsa.PrivateKey),
  76. symKeys: make(map[string][]byte),
  77. envelopes: make(map[common.Hash]*Envelope),
  78. expirations: make(map[uint32]*set.SetNonTS),
  79. peers: make(map[*Peer]struct{}),
  80. messageQueue: make(chan *Envelope, messageQueueLimit),
  81. p2pMsgQueue: make(chan *Envelope, messageQueueLimit),
  82. quit: make(chan struct{}),
  83. }
  84. whisper.filters = NewFilters(whisper)
  85. whisper.settings.Store(minPowIdx, cfg.MinimumAcceptedPOW)
  86. whisper.settings.Store(maxMsgSizeIdx, cfg.MaxMessageSize)
  87. whisper.settings.Store(overflowIdx, false)
  88. // p2p whisper sub protocol handler
  89. whisper.protocol = p2p.Protocol{
  90. Name: ProtocolName,
  91. Version: uint(ProtocolVersion),
  92. Length: NumberOfMessageCodes,
  93. Run: whisper.HandlePeer,
  94. NodeInfo: func() interface{} {
  95. return map[string]interface{}{
  96. "version": ProtocolVersionStr,
  97. "maxMessageSize": whisper.MaxMessageSize(),
  98. "minimumPoW": whisper.MinPow(),
  99. }
  100. },
  101. }
  102. return whisper
  103. }
  104. func (w *Whisper) MinPow() float64 {
  105. val, _ := w.settings.Load(minPowIdx)
  106. return val.(float64)
  107. }
  108. // MaxMessageSize returns the maximum accepted message size.
  109. func (w *Whisper) MaxMessageSize() uint32 {
  110. val, _ := w.settings.Load(maxMsgSizeIdx)
  111. return val.(uint32)
  112. }
  113. // Overflow returns an indication if the message queue is full.
  114. func (w *Whisper) Overflow() bool {
  115. val, _ := w.settings.Load(overflowIdx)
  116. return val.(bool)
  117. }
  118. // APIs returns the RPC descriptors the Whisper implementation offers
  119. func (w *Whisper) APIs() []rpc.API {
  120. return []rpc.API{
  121. {
  122. Namespace: ProtocolName,
  123. Version: ProtocolVersionStr,
  124. Service: NewPublicWhisperAPI(w),
  125. Public: true,
  126. },
  127. }
  128. }
  129. // RegisterServer registers MailServer interface.
  130. // MailServer will process all the incoming messages with p2pRequestCode.
  131. func (w *Whisper) RegisterServer(server MailServer) {
  132. w.mailServer = server
  133. }
  134. // Protocols returns the whisper sub-protocols ran by this particular client.
  135. func (w *Whisper) Protocols() []p2p.Protocol {
  136. return []p2p.Protocol{w.protocol}
  137. }
  138. // Version returns the whisper sub-protocols version number.
  139. func (w *Whisper) Version() uint {
  140. return w.protocol.Version
  141. }
  142. // SetMaxMessageSize sets the maximal message size allowed by this node
  143. func (w *Whisper) SetMaxMessageSize(size uint32) error {
  144. if size > MaxMessageSize {
  145. return fmt.Errorf("message size too large [%d>%d]", size, MaxMessageSize)
  146. }
  147. w.settings.Store(maxMsgSizeIdx, size)
  148. return nil
  149. }
  150. // SetMinimumPoW sets the minimal PoW required by this node
  151. func (w *Whisper) SetMinimumPoW(val float64) error {
  152. if val <= 0.0 {
  153. return fmt.Errorf("invalid PoW: %f", val)
  154. }
  155. w.settings.Store(minPowIdx, val)
  156. return nil
  157. }
  158. // getPeer retrieves peer by ID
  159. func (w *Whisper) getPeer(peerID []byte) (*Peer, error) {
  160. w.peerMu.Lock()
  161. defer w.peerMu.Unlock()
  162. for p := range w.peers {
  163. id := p.peer.ID()
  164. if bytes.Equal(peerID, id[:]) {
  165. return p, nil
  166. }
  167. }
  168. return nil, fmt.Errorf("Could not find peer with ID: %x", peerID)
  169. }
  170. // AllowP2PMessagesFromPeer marks specific peer trusted,
  171. // which will allow it to send historic (expired) messages.
  172. func (w *Whisper) AllowP2PMessagesFromPeer(peerID []byte) error {
  173. p, err := w.getPeer(peerID)
  174. if err != nil {
  175. return err
  176. }
  177. p.trusted = true
  178. return nil
  179. }
  180. // RequestHistoricMessages sends a message with p2pRequestCode to a specific peer,
  181. // which is known to implement MailServer interface, and is supposed to process this
  182. // request and respond with a number of peer-to-peer messages (possibly expired),
  183. // which are not supposed to be forwarded any further.
  184. // The whisper protocol is agnostic of the format and contents of envelope.
  185. func (w *Whisper) RequestHistoricMessages(peerID []byte, envelope *Envelope) error {
  186. p, err := w.getPeer(peerID)
  187. if err != nil {
  188. return err
  189. }
  190. p.trusted = true
  191. return p2p.Send(p.ws, p2pRequestCode, envelope)
  192. }
  193. // SendP2PMessage sends a peer-to-peer message to a specific peer.
  194. func (w *Whisper) SendP2PMessage(peerID []byte, envelope *Envelope) error {
  195. p, err := w.getPeer(peerID)
  196. if err != nil {
  197. return err
  198. }
  199. return w.SendP2PDirect(p, envelope)
  200. }
  201. // SendP2PDirect sends a peer-to-peer message to a specific peer.
  202. func (w *Whisper) SendP2PDirect(peer *Peer, envelope *Envelope) error {
  203. return p2p.Send(peer.ws, p2pCode, envelope)
  204. }
  205. // NewKeyPair generates a new cryptographic identity for the client, and injects
  206. // it into the known identities for message decryption. Returns ID of the new key pair.
  207. func (w *Whisper) NewKeyPair() (string, error) {
  208. key, err := crypto.GenerateKey()
  209. if err != nil || !validatePrivateKey(key) {
  210. key, err = crypto.GenerateKey() // retry once
  211. }
  212. if err != nil {
  213. return "", err
  214. }
  215. if !validatePrivateKey(key) {
  216. return "", fmt.Errorf("failed to generate valid key")
  217. }
  218. id, err := GenerateRandomID()
  219. if err != nil {
  220. return "", fmt.Errorf("failed to generate ID: %s", err)
  221. }
  222. w.keyMu.Lock()
  223. defer w.keyMu.Unlock()
  224. if w.privateKeys[id] != nil {
  225. return "", fmt.Errorf("failed to generate unique ID")
  226. }
  227. w.privateKeys[id] = key
  228. return id, nil
  229. }
  230. // DeleteKeyPair deletes the specified key if it exists.
  231. func (w *Whisper) DeleteKeyPair(key string) bool {
  232. w.keyMu.Lock()
  233. defer w.keyMu.Unlock()
  234. if w.privateKeys[key] != nil {
  235. delete(w.privateKeys, key)
  236. return true
  237. }
  238. return false
  239. }
  240. // AddKeyPair imports a asymmetric private key and returns it identifier.
  241. func (w *Whisper) AddKeyPair(key *ecdsa.PrivateKey) (string, error) {
  242. id, err := GenerateRandomID()
  243. if err != nil {
  244. return "", fmt.Errorf("failed to generate ID: %s", err)
  245. }
  246. w.keyMu.Lock()
  247. w.privateKeys[id] = key
  248. w.keyMu.Unlock()
  249. return id, nil
  250. }
  251. // HasKeyPair checks if the the whisper node is configured with the private key
  252. // of the specified public pair.
  253. func (w *Whisper) HasKeyPair(id string) bool {
  254. w.keyMu.RLock()
  255. defer w.keyMu.RUnlock()
  256. return w.privateKeys[id] != nil
  257. }
  258. // GetPrivateKey retrieves the private key of the specified identity.
  259. func (w *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) {
  260. w.keyMu.RLock()
  261. defer w.keyMu.RUnlock()
  262. key := w.privateKeys[id]
  263. if key == nil {
  264. return nil, fmt.Errorf("invalid id")
  265. }
  266. return key, nil
  267. }
  268. // GenerateSymKey generates a random symmetric key and stores it under id,
  269. // which is then returned. Will be used in the future for session key exchange.
  270. func (w *Whisper) GenerateSymKey() (string, error) {
  271. key := make([]byte, aesKeyLength)
  272. _, err := crand.Read(key)
  273. if err != nil {
  274. return "", err
  275. } else if !validateSymmetricKey(key) {
  276. return "", fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data")
  277. }
  278. id, err := GenerateRandomID()
  279. if err != nil {
  280. return "", fmt.Errorf("failed to generate ID: %s", err)
  281. }
  282. w.keyMu.Lock()
  283. defer w.keyMu.Unlock()
  284. if w.symKeys[id] != nil {
  285. return "", fmt.Errorf("failed to generate unique ID")
  286. }
  287. w.symKeys[id] = key
  288. return id, nil
  289. }
  290. // AddSymKeyDirect stores the key, and returns its id.
  291. func (w *Whisper) AddSymKeyDirect(key []byte) (string, error) {
  292. if len(key) != aesKeyLength {
  293. return "", fmt.Errorf("wrong key size: %d", len(key))
  294. }
  295. id, err := GenerateRandomID()
  296. if err != nil {
  297. return "", fmt.Errorf("failed to generate ID: %s", err)
  298. }
  299. w.keyMu.Lock()
  300. defer w.keyMu.Unlock()
  301. if w.symKeys[id] != nil {
  302. return "", fmt.Errorf("failed to generate unique ID")
  303. }
  304. w.symKeys[id] = key
  305. return id, nil
  306. }
  307. // AddSymKeyFromPassword generates the key from password, stores it, and returns its id.
  308. func (w *Whisper) AddSymKeyFromPassword(password string) (string, error) {
  309. id, err := GenerateRandomID()
  310. if err != nil {
  311. return "", fmt.Errorf("failed to generate ID: %s", err)
  312. }
  313. if w.HasSymKey(id) {
  314. return "", fmt.Errorf("failed to generate unique ID")
  315. }
  316. derived, err := deriveKeyMaterial([]byte(password), EnvelopeVersion)
  317. if err != nil {
  318. return "", err
  319. }
  320. w.keyMu.Lock()
  321. defer w.keyMu.Unlock()
  322. // double check is necessary, because deriveKeyMaterial() is very slow
  323. if w.symKeys[id] != nil {
  324. return "", fmt.Errorf("critical error: failed to generate unique ID")
  325. }
  326. w.symKeys[id] = derived
  327. return id, nil
  328. }
  329. // HasSymKey returns true if there is a key associated with the given id.
  330. // Otherwise returns false.
  331. func (w *Whisper) HasSymKey(id string) bool {
  332. w.keyMu.RLock()
  333. defer w.keyMu.RUnlock()
  334. return w.symKeys[id] != nil
  335. }
  336. // DeleteSymKey deletes the key associated with the name string if it exists.
  337. func (w *Whisper) DeleteSymKey(id string) bool {
  338. w.keyMu.Lock()
  339. defer w.keyMu.Unlock()
  340. if w.symKeys[id] != nil {
  341. delete(w.symKeys, id)
  342. return true
  343. }
  344. return false
  345. }
  346. // GetSymKey returns the symmetric key associated with the given id.
  347. func (w *Whisper) GetSymKey(id string) ([]byte, error) {
  348. w.keyMu.RLock()
  349. defer w.keyMu.RUnlock()
  350. if w.symKeys[id] != nil {
  351. return w.symKeys[id], nil
  352. }
  353. return nil, fmt.Errorf("non-existent key ID")
  354. }
  355. // Subscribe installs a new message handler used for filtering, decrypting
  356. // and subsequent storing of incoming messages.
  357. func (w *Whisper) Subscribe(f *Filter) (string, error) {
  358. return w.filters.Install(f)
  359. }
  360. // GetFilter returns the filter by id.
  361. func (w *Whisper) GetFilter(id string) *Filter {
  362. return w.filters.Get(id)
  363. }
  364. // Unsubscribe removes an installed message handler.
  365. func (w *Whisper) Unsubscribe(id string) error {
  366. ok := w.filters.Uninstall(id)
  367. if !ok {
  368. return fmt.Errorf("Unsubscribe: Invalid ID")
  369. }
  370. return nil
  371. }
  372. // Send injects a message into the whisper send queue, to be distributed in the
  373. // network in the coming cycles.
  374. func (w *Whisper) Send(envelope *Envelope) error {
  375. ok, err := w.add(envelope)
  376. if err != nil {
  377. return err
  378. }
  379. if !ok {
  380. return fmt.Errorf("failed to add envelope")
  381. }
  382. return err
  383. }
  384. // Start implements node.Service, starting the background data propagation thread
  385. // of the Whisper protocol.
  386. func (w *Whisper) Start(*p2p.Server) error {
  387. log.Info("started whisper v." + ProtocolVersionStr)
  388. go w.update()
  389. numCPU := runtime.NumCPU()
  390. for i := 0; i < numCPU; i++ {
  391. go w.processQueue()
  392. }
  393. return nil
  394. }
  395. // Stop implements node.Service, stopping the background data propagation thread
  396. // of the Whisper protocol.
  397. func (w *Whisper) Stop() error {
  398. close(w.quit)
  399. log.Info("whisper stopped")
  400. return nil
  401. }
  402. // HandlePeer is called by the underlying P2P layer when the whisper sub-protocol
  403. // connection is negotiated.
  404. func (w *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
  405. // Create the new peer and start tracking it
  406. whisperPeer := newPeer(w, peer, rw)
  407. w.peerMu.Lock()
  408. w.peers[whisperPeer] = struct{}{}
  409. w.peerMu.Unlock()
  410. defer func() {
  411. w.peerMu.Lock()
  412. delete(w.peers, whisperPeer)
  413. w.peerMu.Unlock()
  414. }()
  415. // Run the peer handshake and state updates
  416. if err := whisperPeer.handshake(); err != nil {
  417. return err
  418. }
  419. whisperPeer.start()
  420. defer whisperPeer.stop()
  421. return w.runMessageLoop(whisperPeer, rw)
  422. }
  423. // runMessageLoop reads and processes inbound messages directly to merge into client-global state.
  424. func (w *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
  425. for {
  426. // fetch the next packet
  427. packet, err := rw.ReadMsg()
  428. if err != nil {
  429. log.Warn("message loop", "peer", p.peer.ID(), "err", err)
  430. return err
  431. }
  432. if packet.Size > w.MaxMessageSize() {
  433. log.Warn("oversized message received", "peer", p.peer.ID())
  434. return errors.New("oversized message received")
  435. }
  436. switch packet.Code {
  437. case statusCode:
  438. // this should not happen, but no need to panic; just ignore this message.
  439. log.Warn("unxepected status message received", "peer", p.peer.ID())
  440. case messagesCode:
  441. // decode the contained envelopes
  442. var envelope Envelope
  443. if err := packet.Decode(&envelope); err != nil {
  444. log.Warn("failed to decode envelope, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  445. return errors.New("invalid envelope")
  446. }
  447. cached, err := w.add(&envelope)
  448. if err != nil {
  449. log.Warn("bad envelope received, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  450. return errors.New("invalid envelope")
  451. }
  452. if cached {
  453. p.mark(&envelope)
  454. }
  455. case p2pCode:
  456. // peer-to-peer message, sent directly to peer bypassing PoW checks, etc.
  457. // this message is not supposed to be forwarded to other peers, and
  458. // therefore might not satisfy the PoW, expiry and other requirements.
  459. // these messages are only accepted from the trusted peer.
  460. if p.trusted {
  461. var envelope Envelope
  462. if err := packet.Decode(&envelope); err != nil {
  463. log.Warn("failed to decode direct message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  464. return errors.New("invalid direct message")
  465. }
  466. w.postEvent(&envelope, true)
  467. }
  468. case p2pRequestCode:
  469. // Must be processed if mail server is implemented. Otherwise ignore.
  470. if w.mailServer != nil {
  471. var request Envelope
  472. if err := packet.Decode(&request); err != nil {
  473. log.Warn("failed to decode p2p request message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  474. return errors.New("invalid p2p request")
  475. }
  476. w.mailServer.DeliverMail(p, &request)
  477. }
  478. default:
  479. // New message types might be implemented in the future versions of Whisper.
  480. // For forward compatibility, just ignore.
  481. }
  482. packet.Discard()
  483. }
  484. }
  485. // add inserts a new envelope into the message pool to be distributed within the
  486. // whisper network. It also inserts the envelope into the expiration pool at the
  487. // appropriate time-stamp. In case of error, connection should be dropped.
  488. func (w *Whisper) add(envelope *Envelope) (bool, error) {
  489. now := uint32(time.Now().Unix())
  490. sent := envelope.Expiry - envelope.TTL
  491. if sent > now {
  492. if sent-SynchAllowance > now {
  493. return false, fmt.Errorf("envelope created in the future [%x]", envelope.Hash())
  494. }
  495. // recalculate PoW, adjusted for the time difference, plus one second for latency
  496. envelope.calculatePoW(sent - now + 1)
  497. }
  498. if envelope.Expiry < now {
  499. if envelope.Expiry+SynchAllowance*2 < now {
  500. return false, fmt.Errorf("very old message")
  501. }
  502. log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
  503. return false, nil // drop envelope without error
  504. }
  505. if uint32(envelope.size()) > w.MaxMessageSize() {
  506. return false, fmt.Errorf("huge messages are not allowed [%x]", envelope.Hash())
  507. }
  508. if len(envelope.Version) > 4 {
  509. return false, fmt.Errorf("oversized version [%x]", envelope.Hash())
  510. }
  511. aesNonceSize := len(envelope.AESNonce)
  512. if aesNonceSize != 0 && aesNonceSize != AESNonceLength {
  513. // the standard AES GCM nonce size is 12 bytes,
  514. // but constant gcmStandardNonceSize cannot be accessed (not exported)
  515. return false, fmt.Errorf("wrong size of AESNonce: %d bytes [env: %x]", aesNonceSize, envelope.Hash())
  516. }
  517. if envelope.PoW() < w.MinPow() {
  518. log.Debug("envelope with low PoW dropped", "PoW", envelope.PoW(), "hash", envelope.Hash().Hex())
  519. return false, nil // drop envelope without error
  520. }
  521. hash := envelope.Hash()
  522. w.poolMu.Lock()
  523. _, alreadyCached := w.envelopes[hash]
  524. if !alreadyCached {
  525. w.envelopes[hash] = envelope
  526. if w.expirations[envelope.Expiry] == nil {
  527. w.expirations[envelope.Expiry] = set.NewNonTS()
  528. }
  529. if !w.expirations[envelope.Expiry].Has(hash) {
  530. w.expirations[envelope.Expiry].Add(hash)
  531. }
  532. }
  533. w.poolMu.Unlock()
  534. if alreadyCached {
  535. log.Trace("whisper envelope already cached", "hash", envelope.Hash().Hex())
  536. } else {
  537. log.Trace("cached whisper envelope", "hash", envelope.Hash().Hex())
  538. w.statsMu.Lock()
  539. w.stats.memoryUsed += envelope.size()
  540. w.statsMu.Unlock()
  541. w.postEvent(envelope, false) // notify the local node about the new message
  542. if w.mailServer != nil {
  543. w.mailServer.Archive(envelope)
  544. }
  545. }
  546. return true, nil
  547. }
  548. // postEvent queues the message for further processing.
  549. func (w *Whisper) postEvent(envelope *Envelope, isP2P bool) {
  550. // if the version of incoming message is higher than
  551. // currently supported version, we can not decrypt it,
  552. // and therefore just ignore this message
  553. if envelope.Ver() <= EnvelopeVersion {
  554. if isP2P {
  555. w.p2pMsgQueue <- envelope
  556. } else {
  557. w.checkOverflow()
  558. w.messageQueue <- envelope
  559. }
  560. }
  561. }
  562. // checkOverflow checks if message queue overflow occurs and reports it if necessary.
  563. func (w *Whisper) checkOverflow() {
  564. queueSize := len(w.messageQueue)
  565. if queueSize == messageQueueLimit {
  566. if !w.Overflow() {
  567. w.settings.Store(overflowIdx, true)
  568. log.Warn("message queue overflow")
  569. }
  570. } else if queueSize <= messageQueueLimit/2 {
  571. if w.Overflow() {
  572. w.settings.Store(overflowIdx, false)
  573. log.Warn("message queue overflow fixed (back to normal)")
  574. }
  575. }
  576. }
  577. // processQueue delivers the messages to the watchers during the lifetime of the whisper node.
  578. func (w *Whisper) processQueue() {
  579. var e *Envelope
  580. for {
  581. select {
  582. case <-w.quit:
  583. return
  584. case e = <-w.messageQueue:
  585. w.filters.NotifyWatchers(e, false)
  586. case e = <-w.p2pMsgQueue:
  587. w.filters.NotifyWatchers(e, true)
  588. }
  589. }
  590. }
  591. // update loops until the lifetime of the whisper node, updating its internal
  592. // state by expiring stale messages from the pool.
  593. func (w *Whisper) update() {
  594. // Start a ticker to check for expirations
  595. expire := time.NewTicker(expirationCycle)
  596. // Repeat updates until termination is requested
  597. for {
  598. select {
  599. case <-expire.C:
  600. w.expire()
  601. case <-w.quit:
  602. return
  603. }
  604. }
  605. }
  606. // expire iterates over all the expiration timestamps, removing all stale
  607. // messages from the pools.
  608. func (w *Whisper) expire() {
  609. w.poolMu.Lock()
  610. defer w.poolMu.Unlock()
  611. w.statsMu.Lock()
  612. defer w.statsMu.Unlock()
  613. w.stats.reset()
  614. now := uint32(time.Now().Unix())
  615. for expiry, hashSet := range w.expirations {
  616. if expiry < now {
  617. // Dump all expired messages and remove timestamp
  618. hashSet.Each(func(v interface{}) bool {
  619. sz := w.envelopes[v.(common.Hash)].size()
  620. delete(w.envelopes, v.(common.Hash))
  621. w.stats.messagesCleared++
  622. w.stats.memoryCleared += sz
  623. w.stats.memoryUsed -= sz
  624. return true
  625. })
  626. w.expirations[expiry].Clear()
  627. delete(w.expirations, expiry)
  628. }
  629. }
  630. }
  631. // Stats returns the whisper node statistics.
  632. func (w *Whisper) Stats() Statistics {
  633. w.statsMu.Lock()
  634. defer w.statsMu.Unlock()
  635. return w.stats
  636. }
  637. // Envelopes retrieves all the messages currently pooled by the node.
  638. func (w *Whisper) Envelopes() []*Envelope {
  639. w.poolMu.RLock()
  640. defer w.poolMu.RUnlock()
  641. all := make([]*Envelope, 0, len(w.envelopes))
  642. for _, envelope := range w.envelopes {
  643. all = append(all, envelope)
  644. }
  645. return all
  646. }
  647. // Messages iterates through all currently floating envelopes
  648. // and retrieves all the messages, that this filter could decrypt.
  649. func (w *Whisper) Messages(id string) []*ReceivedMessage {
  650. result := make([]*ReceivedMessage, 0)
  651. w.poolMu.RLock()
  652. defer w.poolMu.RUnlock()
  653. if filter := w.filters.Get(id); filter != nil {
  654. for _, env := range w.envelopes {
  655. msg := filter.processEnvelope(env)
  656. if msg != nil {
  657. result = append(result, msg)
  658. }
  659. }
  660. }
  661. return result
  662. }
  663. // isEnvelopeCached checks if envelope with specific hash has already been received and cached.
  664. func (w *Whisper) isEnvelopeCached(hash common.Hash) bool {
  665. w.poolMu.Lock()
  666. defer w.poolMu.Unlock()
  667. _, exist := w.envelopes[hash]
  668. return exist
  669. }
  670. // reset resets the node's statistics after each expiry cycle.
  671. func (s *Statistics) reset() {
  672. s.cycles++
  673. s.totalMessagesCleared += s.messagesCleared
  674. s.memoryCleared = 0
  675. s.messagesCleared = 0
  676. }
  677. // ValidatePublicKey checks the format of the given public key.
  678. func ValidatePublicKey(k *ecdsa.PublicKey) bool {
  679. return k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0
  680. }
  681. // validatePrivateKey checks the format of the given private key.
  682. func validatePrivateKey(k *ecdsa.PrivateKey) bool {
  683. if k == nil || k.D == nil || k.D.Sign() == 0 {
  684. return false
  685. }
  686. return ValidatePublicKey(&k.PublicKey)
  687. }
  688. // validateSymmetricKey returns false if the key contains all zeros
  689. func validateSymmetricKey(k []byte) bool {
  690. return len(k) > 0 && !containsOnlyZeros(k)
  691. }
  692. // containsOnlyZeros checks if the data contain only zeros.
  693. func containsOnlyZeros(data []byte) bool {
  694. for _, b := range data {
  695. if b != 0 {
  696. return false
  697. }
  698. }
  699. return true
  700. }
  701. // bytesToUintLittleEndian converts the slice to 64-bit unsigned integer.
  702. func bytesToUintLittleEndian(b []byte) (res uint64) {
  703. mul := uint64(1)
  704. for i := 0; i < len(b); i++ {
  705. res += uint64(b[i]) * mul
  706. mul *= 256
  707. }
  708. return res
  709. }
  710. // BytesToUintBigEndian converts the slice to 64-bit unsigned integer.
  711. func BytesToUintBigEndian(b []byte) (res uint64) {
  712. for i := 0; i < len(b); i++ {
  713. res *= 256
  714. res += uint64(b[i])
  715. }
  716. return res
  717. }
  718. // deriveKeyMaterial derives symmetric key material from the key or password.
  719. // pbkdf2 is used for security, in case people use password instead of randomly generated keys.
  720. func deriveKeyMaterial(key []byte, version uint64) (derivedKey []byte, err error) {
  721. if version == 0 {
  722. // kdf should run no less than 0.1 seconds on average compute,
  723. // because it's a once in a session experience
  724. derivedKey := pbkdf2.Key(key, nil, 65356, aesKeyLength, sha256.New)
  725. return derivedKey, nil
  726. }
  727. return nil, unknownVersionError(version)
  728. }
  729. // GenerateRandomID generates a random string, which is then returned to be used as a key id
  730. func GenerateRandomID() (id string, err error) {
  731. buf := make([]byte, keyIdSize)
  732. _, err = crand.Read(buf)
  733. if err != nil {
  734. return "", err
  735. }
  736. if !validateSymmetricKey(buf) {
  737. return "", fmt.Errorf("error in generateRandomID: crypto/rand failed to generate random data")
  738. }
  739. id = common.Bytes2Hex(buf)
  740. return id, err
  741. }