whisper.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 whisperv6
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "crypto/sha256"
  21. "fmt"
  22. "math"
  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/rlp"
  31. "github.com/ethereum/go-ethereum/rpc"
  32. "github.com/syndtr/goleveldb/leveldb/errors"
  33. "golang.org/x/crypto/pbkdf2"
  34. "golang.org/x/sync/syncmap"
  35. set "gopkg.in/fatih/set.v0"
  36. )
  37. // Statistics holds several message-related counter for analytics
  38. // purposes.
  39. type Statistics struct {
  40. messagesCleared int
  41. memoryCleared int
  42. memoryUsed int
  43. cycles int
  44. totalMessagesCleared int
  45. }
  46. const (
  47. maxMsgSizeIdx = iota // Maximal message length allowed by the whisper node
  48. overflowIdx // Indicator of message queue overflow
  49. minPowIdx // Minimal PoW required by the whisper node
  50. minPowToleranceIdx // Minimal PoW tolerated by the whisper node for a limited time
  51. bloomFilterIdx // Bloom filter for topics of interest for this node
  52. bloomFilterToleranceIdx // Bloom filter tolerated by the whisper node for a limited time
  53. )
  54. // Whisper represents a dark communication interface through the Ethereum
  55. // network, using its very own P2P communication layer.
  56. type Whisper struct {
  57. protocol p2p.Protocol // Protocol description and parameters
  58. filters *Filters // Message filters installed with Subscribe function
  59. privateKeys map[string]*ecdsa.PrivateKey // Private key storage
  60. symKeys map[string][]byte // Symmetric key storage
  61. keyMu sync.RWMutex // Mutex associated with key storages
  62. poolMu sync.RWMutex // Mutex to sync the message and expiration pools
  63. envelopes map[common.Hash]*Envelope // Pool of envelopes currently tracked by this node
  64. expirations map[uint32]*set.SetNonTS // Message expiration pool
  65. peerMu sync.RWMutex // Mutex to sync the active peer set
  66. peers map[*Peer]struct{} // Set of currently active peers
  67. messageQueue chan *Envelope // Message queue for normal whisper messages
  68. p2pMsgQueue chan *Envelope // Message queue for peer-to-peer messages (not to be forwarded any further)
  69. quit chan struct{} // Channel used for graceful exit
  70. settings syncmap.Map // holds configuration settings that can be dynamically changed
  71. syncAllowance int // maximum time in seconds allowed to process the whisper-related messages
  72. lightClient bool // indicates is this node is pure light client (does not forward any messages)
  73. statsMu sync.Mutex // guard stats
  74. stats Statistics // Statistics of whisper node
  75. mailServer MailServer // MailServer interface
  76. }
  77. // New creates a Whisper client ready to communicate through the Ethereum P2P network.
  78. func New(cfg *Config) *Whisper {
  79. if cfg == nil {
  80. cfg = &DefaultConfig
  81. }
  82. whisper := &Whisper{
  83. privateKeys: make(map[string]*ecdsa.PrivateKey),
  84. symKeys: make(map[string][]byte),
  85. envelopes: make(map[common.Hash]*Envelope),
  86. expirations: make(map[uint32]*set.SetNonTS),
  87. peers: make(map[*Peer]struct{}),
  88. messageQueue: make(chan *Envelope, messageQueueLimit),
  89. p2pMsgQueue: make(chan *Envelope, messageQueueLimit),
  90. quit: make(chan struct{}),
  91. syncAllowance: DefaultSyncAllowance,
  92. }
  93. whisper.filters = NewFilters(whisper)
  94. whisper.settings.Store(minPowIdx, cfg.MinimumAcceptedPOW)
  95. whisper.settings.Store(maxMsgSizeIdx, cfg.MaxMessageSize)
  96. whisper.settings.Store(overflowIdx, false)
  97. // p2p whisper sub protocol handler
  98. whisper.protocol = p2p.Protocol{
  99. Name: ProtocolName,
  100. Version: uint(ProtocolVersion),
  101. Length: NumberOfMessageCodes,
  102. Run: whisper.HandlePeer,
  103. NodeInfo: func() interface{} {
  104. return map[string]interface{}{
  105. "version": ProtocolVersionStr,
  106. "maxMessageSize": whisper.MaxMessageSize(),
  107. "minimumPoW": whisper.MinPow(),
  108. }
  109. },
  110. }
  111. return whisper
  112. }
  113. // MinPow returns the PoW value required by this node.
  114. func (whisper *Whisper) MinPow() float64 {
  115. val, exist := whisper.settings.Load(minPowIdx)
  116. if !exist || val == nil {
  117. return DefaultMinimumPoW
  118. }
  119. v, ok := val.(float64)
  120. if !ok {
  121. log.Error("Error loading minPowIdx, using default")
  122. return DefaultMinimumPoW
  123. }
  124. return v
  125. }
  126. // MinPowTolerance returns the value of minimum PoW which is tolerated for a limited
  127. // time after PoW was changed. If sufficient time have elapsed or no change of PoW
  128. // have ever occurred, the return value will be the same as return value of MinPow().
  129. func (whisper *Whisper) MinPowTolerance() float64 {
  130. val, exist := whisper.settings.Load(minPowToleranceIdx)
  131. if !exist || val == nil {
  132. return DefaultMinimumPoW
  133. }
  134. return val.(float64)
  135. }
  136. // BloomFilter returns the aggregated bloom filter for all the topics of interest.
  137. // The nodes are required to send only messages that match the advertised bloom filter.
  138. // If a message does not match the bloom, it will tantamount to spam, and the peer will
  139. // be disconnected.
  140. func (whisper *Whisper) BloomFilter() []byte {
  141. val, exist := whisper.settings.Load(bloomFilterIdx)
  142. if !exist || val == nil {
  143. return nil
  144. }
  145. return val.([]byte)
  146. }
  147. // BloomFilterTolerance returns the bloom filter which is tolerated for a limited
  148. // time after new bloom was advertised to the peers. If sufficient time have elapsed
  149. // or no change of bloom filter have ever occurred, the return value will be the same
  150. // as return value of BloomFilter().
  151. func (whisper *Whisper) BloomFilterTolerance() []byte {
  152. val, exist := whisper.settings.Load(bloomFilterToleranceIdx)
  153. if !exist || val == nil {
  154. return nil
  155. }
  156. return val.([]byte)
  157. }
  158. // MaxMessageSize returns the maximum accepted message size.
  159. func (whisper *Whisper) MaxMessageSize() uint32 {
  160. val, _ := whisper.settings.Load(maxMsgSizeIdx)
  161. return val.(uint32)
  162. }
  163. // Overflow returns an indication if the message queue is full.
  164. func (whisper *Whisper) Overflow() bool {
  165. val, _ := whisper.settings.Load(overflowIdx)
  166. return val.(bool)
  167. }
  168. // APIs returns the RPC descriptors the Whisper implementation offers
  169. func (whisper *Whisper) APIs() []rpc.API {
  170. return []rpc.API{
  171. {
  172. Namespace: ProtocolName,
  173. Version: ProtocolVersionStr,
  174. Service: NewPublicWhisperAPI(whisper),
  175. Public: true,
  176. },
  177. }
  178. }
  179. // RegisterServer registers MailServer interface.
  180. // MailServer will process all the incoming messages with p2pRequestCode.
  181. func (whisper *Whisper) RegisterServer(server MailServer) {
  182. whisper.mailServer = server
  183. }
  184. // Protocols returns the whisper sub-protocols ran by this particular client.
  185. func (whisper *Whisper) Protocols() []p2p.Protocol {
  186. return []p2p.Protocol{whisper.protocol}
  187. }
  188. // Version returns the whisper sub-protocols version number.
  189. func (whisper *Whisper) Version() uint {
  190. return whisper.protocol.Version
  191. }
  192. // SetMaxMessageSize sets the maximal message size allowed by this node
  193. func (whisper *Whisper) SetMaxMessageSize(size uint32) error {
  194. if size > MaxMessageSize {
  195. return fmt.Errorf("message size too large [%d>%d]", size, MaxMessageSize)
  196. }
  197. whisper.settings.Store(maxMsgSizeIdx, size)
  198. return nil
  199. }
  200. // SetBloomFilter sets the new bloom filter
  201. func (whisper *Whisper) SetBloomFilter(bloom []byte) error {
  202. if len(bloom) != BloomFilterSize {
  203. return fmt.Errorf("invalid bloom filter size: %d", len(bloom))
  204. }
  205. b := make([]byte, BloomFilterSize)
  206. copy(b, bloom)
  207. whisper.settings.Store(bloomFilterIdx, b)
  208. whisper.notifyPeersAboutBloomFilterChange(b)
  209. go func() {
  210. // allow some time before all the peers have processed the notification
  211. time.Sleep(time.Duration(whisper.syncAllowance) * time.Second)
  212. whisper.settings.Store(bloomFilterToleranceIdx, b)
  213. }()
  214. return nil
  215. }
  216. // SetMinimumPoW sets the minimal PoW required by this node
  217. func (whisper *Whisper) SetMinimumPoW(val float64) error {
  218. if val < 0.0 {
  219. return fmt.Errorf("invalid PoW: %f", val)
  220. }
  221. whisper.settings.Store(minPowIdx, val)
  222. whisper.notifyPeersAboutPowRequirementChange(val)
  223. go func() {
  224. // allow some time before all the peers have processed the notification
  225. time.Sleep(time.Duration(whisper.syncAllowance) * time.Second)
  226. whisper.settings.Store(minPowToleranceIdx, val)
  227. }()
  228. return nil
  229. }
  230. // SetMinimumPowTest sets the minimal PoW in test environment
  231. func (whisper *Whisper) SetMinimumPowTest(val float64) {
  232. whisper.settings.Store(minPowIdx, val)
  233. whisper.notifyPeersAboutPowRequirementChange(val)
  234. whisper.settings.Store(minPowToleranceIdx, val)
  235. }
  236. func (whisper *Whisper) notifyPeersAboutPowRequirementChange(pow float64) {
  237. arr := whisper.getPeers()
  238. for _, p := range arr {
  239. err := p.notifyAboutPowRequirementChange(pow)
  240. if err != nil {
  241. // allow one retry
  242. err = p.notifyAboutPowRequirementChange(pow)
  243. }
  244. if err != nil {
  245. log.Warn("failed to notify peer about new pow requirement", "peer", p.ID(), "error", err)
  246. }
  247. }
  248. }
  249. func (whisper *Whisper) notifyPeersAboutBloomFilterChange(bloom []byte) {
  250. arr := whisper.getPeers()
  251. for _, p := range arr {
  252. err := p.notifyAboutBloomFilterChange(bloom)
  253. if err != nil {
  254. // allow one retry
  255. err = p.notifyAboutBloomFilterChange(bloom)
  256. }
  257. if err != nil {
  258. log.Warn("failed to notify peer about new bloom filter", "peer", p.ID(), "error", err)
  259. }
  260. }
  261. }
  262. func (whisper *Whisper) getPeers() []*Peer {
  263. arr := make([]*Peer, len(whisper.peers))
  264. i := 0
  265. whisper.peerMu.Lock()
  266. for p := range whisper.peers {
  267. arr[i] = p
  268. i++
  269. }
  270. whisper.peerMu.Unlock()
  271. return arr
  272. }
  273. // getPeer retrieves peer by ID
  274. func (whisper *Whisper) getPeer(peerID []byte) (*Peer, error) {
  275. whisper.peerMu.Lock()
  276. defer whisper.peerMu.Unlock()
  277. for p := range whisper.peers {
  278. id := p.peer.ID()
  279. if bytes.Equal(peerID, id[:]) {
  280. return p, nil
  281. }
  282. }
  283. return nil, fmt.Errorf("Could not find peer with ID: %x", peerID)
  284. }
  285. // AllowP2PMessagesFromPeer marks specific peer trusted,
  286. // which will allow it to send historic (expired) messages.
  287. func (whisper *Whisper) AllowP2PMessagesFromPeer(peerID []byte) error {
  288. p, err := whisper.getPeer(peerID)
  289. if err != nil {
  290. return err
  291. }
  292. p.trusted = true
  293. return nil
  294. }
  295. // RequestHistoricMessages sends a message with p2pRequestCode to a specific peer,
  296. // which is known to implement MailServer interface, and is supposed to process this
  297. // request and respond with a number of peer-to-peer messages (possibly expired),
  298. // which are not supposed to be forwarded any further.
  299. // The whisper protocol is agnostic of the format and contents of envelope.
  300. func (whisper *Whisper) RequestHistoricMessages(peerID []byte, envelope *Envelope) error {
  301. p, err := whisper.getPeer(peerID)
  302. if err != nil {
  303. return err
  304. }
  305. p.trusted = true
  306. return p2p.Send(p.ws, p2pRequestCode, envelope)
  307. }
  308. // SendP2PMessage sends a peer-to-peer message to a specific peer.
  309. func (whisper *Whisper) SendP2PMessage(peerID []byte, envelope *Envelope) error {
  310. p, err := whisper.getPeer(peerID)
  311. if err != nil {
  312. return err
  313. }
  314. return whisper.SendP2PDirect(p, envelope)
  315. }
  316. // SendP2PDirect sends a peer-to-peer message to a specific peer.
  317. func (whisper *Whisper) SendP2PDirect(peer *Peer, envelope *Envelope) error {
  318. return p2p.Send(peer.ws, p2pMessageCode, envelope)
  319. }
  320. // NewKeyPair generates a new cryptographic identity for the client, and injects
  321. // it into the known identities for message decryption. Returns ID of the new key pair.
  322. func (whisper *Whisper) NewKeyPair() (string, error) {
  323. key, err := crypto.GenerateKey()
  324. if err != nil || !validatePrivateKey(key) {
  325. key, err = crypto.GenerateKey() // retry once
  326. }
  327. if err != nil {
  328. return "", err
  329. }
  330. if !validatePrivateKey(key) {
  331. return "", fmt.Errorf("failed to generate valid key")
  332. }
  333. id, err := GenerateRandomID()
  334. if err != nil {
  335. return "", fmt.Errorf("failed to generate ID: %s", err)
  336. }
  337. whisper.keyMu.Lock()
  338. defer whisper.keyMu.Unlock()
  339. if whisper.privateKeys[id] != nil {
  340. return "", fmt.Errorf("failed to generate unique ID")
  341. }
  342. whisper.privateKeys[id] = key
  343. return id, nil
  344. }
  345. // DeleteKeyPair deletes the specified key if it exists.
  346. func (whisper *Whisper) DeleteKeyPair(key string) bool {
  347. whisper.keyMu.Lock()
  348. defer whisper.keyMu.Unlock()
  349. if whisper.privateKeys[key] != nil {
  350. delete(whisper.privateKeys, key)
  351. return true
  352. }
  353. return false
  354. }
  355. // AddKeyPair imports a asymmetric private key and returns it identifier.
  356. func (whisper *Whisper) AddKeyPair(key *ecdsa.PrivateKey) (string, error) {
  357. id, err := GenerateRandomID()
  358. if err != nil {
  359. return "", fmt.Errorf("failed to generate ID: %s", err)
  360. }
  361. whisper.keyMu.Lock()
  362. whisper.privateKeys[id] = key
  363. whisper.keyMu.Unlock()
  364. return id, nil
  365. }
  366. // HasKeyPair checks if the the whisper node is configured with the private key
  367. // of the specified public pair.
  368. func (whisper *Whisper) HasKeyPair(id string) bool {
  369. whisper.keyMu.RLock()
  370. defer whisper.keyMu.RUnlock()
  371. return whisper.privateKeys[id] != nil
  372. }
  373. // GetPrivateKey retrieves the private key of the specified identity.
  374. func (whisper *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) {
  375. whisper.keyMu.RLock()
  376. defer whisper.keyMu.RUnlock()
  377. key := whisper.privateKeys[id]
  378. if key == nil {
  379. return nil, fmt.Errorf("invalid id")
  380. }
  381. return key, nil
  382. }
  383. // GenerateSymKey generates a random symmetric key and stores it under id,
  384. // which is then returned. Will be used in the future for session key exchange.
  385. func (whisper *Whisper) GenerateSymKey() (string, error) {
  386. key, err := generateSecureRandomData(aesKeyLength)
  387. if err != nil {
  388. return "", err
  389. } else if !validateDataIntegrity(key, aesKeyLength) {
  390. return "", fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data")
  391. }
  392. id, err := GenerateRandomID()
  393. if err != nil {
  394. return "", fmt.Errorf("failed to generate ID: %s", err)
  395. }
  396. whisper.keyMu.Lock()
  397. defer whisper.keyMu.Unlock()
  398. if whisper.symKeys[id] != nil {
  399. return "", fmt.Errorf("failed to generate unique ID")
  400. }
  401. whisper.symKeys[id] = key
  402. return id, nil
  403. }
  404. // AddSymKeyDirect stores the key, and returns its id.
  405. func (whisper *Whisper) AddSymKeyDirect(key []byte) (string, error) {
  406. if len(key) != aesKeyLength {
  407. return "", fmt.Errorf("wrong key size: %d", len(key))
  408. }
  409. id, err := GenerateRandomID()
  410. if err != nil {
  411. return "", fmt.Errorf("failed to generate ID: %s", err)
  412. }
  413. whisper.keyMu.Lock()
  414. defer whisper.keyMu.Unlock()
  415. if whisper.symKeys[id] != nil {
  416. return "", fmt.Errorf("failed to generate unique ID")
  417. }
  418. whisper.symKeys[id] = key
  419. return id, nil
  420. }
  421. // AddSymKeyFromPassword generates the key from password, stores it, and returns its id.
  422. func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error) {
  423. id, err := GenerateRandomID()
  424. if err != nil {
  425. return "", fmt.Errorf("failed to generate ID: %s", err)
  426. }
  427. if whisper.HasSymKey(id) {
  428. return "", fmt.Errorf("failed to generate unique ID")
  429. }
  430. // kdf should run no less than 0.1 seconds on an average computer,
  431. // because it's an once in a session experience
  432. derived := pbkdf2.Key([]byte(password), nil, 65356, aesKeyLength, sha256.New)
  433. if err != nil {
  434. return "", err
  435. }
  436. whisper.keyMu.Lock()
  437. defer whisper.keyMu.Unlock()
  438. // double check is necessary, because deriveKeyMaterial() is very slow
  439. if whisper.symKeys[id] != nil {
  440. return "", fmt.Errorf("critical error: failed to generate unique ID")
  441. }
  442. whisper.symKeys[id] = derived
  443. return id, nil
  444. }
  445. // HasSymKey returns true if there is a key associated with the given id.
  446. // Otherwise returns false.
  447. func (whisper *Whisper) HasSymKey(id string) bool {
  448. whisper.keyMu.RLock()
  449. defer whisper.keyMu.RUnlock()
  450. return whisper.symKeys[id] != nil
  451. }
  452. // DeleteSymKey deletes the key associated with the name string if it exists.
  453. func (whisper *Whisper) DeleteSymKey(id string) bool {
  454. whisper.keyMu.Lock()
  455. defer whisper.keyMu.Unlock()
  456. if whisper.symKeys[id] != nil {
  457. delete(whisper.symKeys, id)
  458. return true
  459. }
  460. return false
  461. }
  462. // GetSymKey returns the symmetric key associated with the given id.
  463. func (whisper *Whisper) GetSymKey(id string) ([]byte, error) {
  464. whisper.keyMu.RLock()
  465. defer whisper.keyMu.RUnlock()
  466. if whisper.symKeys[id] != nil {
  467. return whisper.symKeys[id], nil
  468. }
  469. return nil, fmt.Errorf("non-existent key ID")
  470. }
  471. // Subscribe installs a new message handler used for filtering, decrypting
  472. // and subsequent storing of incoming messages.
  473. func (whisper *Whisper) Subscribe(f *Filter) (string, error) {
  474. s, err := whisper.filters.Install(f)
  475. if err == nil {
  476. whisper.updateBloomFilter(f)
  477. }
  478. return s, err
  479. }
  480. // updateBloomFilter recalculates the new value of bloom filter,
  481. // and informs the peers if necessary.
  482. func (whisper *Whisper) updateBloomFilter(f *Filter) {
  483. aggregate := make([]byte, BloomFilterSize)
  484. for _, t := range f.Topics {
  485. top := BytesToTopic(t)
  486. b := TopicToBloom(top)
  487. aggregate = addBloom(aggregate, b)
  488. }
  489. if !BloomFilterMatch(whisper.BloomFilter(), aggregate) {
  490. // existing bloom filter must be updated
  491. aggregate = addBloom(whisper.BloomFilter(), aggregate)
  492. whisper.SetBloomFilter(aggregate)
  493. }
  494. }
  495. // GetFilter returns the filter by id.
  496. func (whisper *Whisper) GetFilter(id string) *Filter {
  497. return whisper.filters.Get(id)
  498. }
  499. // Unsubscribe removes an installed message handler.
  500. func (whisper *Whisper) Unsubscribe(id string) error {
  501. ok := whisper.filters.Uninstall(id)
  502. if !ok {
  503. return fmt.Errorf("Unsubscribe: Invalid ID")
  504. }
  505. return nil
  506. }
  507. // Send injects a message into the whisper send queue, to be distributed in the
  508. // network in the coming cycles.
  509. func (whisper *Whisper) Send(envelope *Envelope) error {
  510. ok, err := whisper.add(envelope, false)
  511. if err == nil && !ok {
  512. return fmt.Errorf("failed to add envelope")
  513. }
  514. return err
  515. }
  516. // Start implements node.Service, starting the background data propagation thread
  517. // of the Whisper protocol.
  518. func (whisper *Whisper) Start(*p2p.Server) error {
  519. log.Info("started whisper v." + ProtocolVersionStr)
  520. go whisper.update()
  521. numCPU := runtime.NumCPU()
  522. for i := 0; i < numCPU; i++ {
  523. go whisper.processQueue()
  524. }
  525. return nil
  526. }
  527. // Stop implements node.Service, stopping the background data propagation thread
  528. // of the Whisper protocol.
  529. func (whisper *Whisper) Stop() error {
  530. close(whisper.quit)
  531. log.Info("whisper stopped")
  532. return nil
  533. }
  534. // HandlePeer is called by the underlying P2P layer when the whisper sub-protocol
  535. // connection is negotiated.
  536. func (whisper *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
  537. // Create the new peer and start tracking it
  538. whisperPeer := newPeer(whisper, peer, rw)
  539. whisper.peerMu.Lock()
  540. whisper.peers[whisperPeer] = struct{}{}
  541. whisper.peerMu.Unlock()
  542. defer func() {
  543. whisper.peerMu.Lock()
  544. delete(whisper.peers, whisperPeer)
  545. whisper.peerMu.Unlock()
  546. }()
  547. // Run the peer handshake and state updates
  548. if err := whisperPeer.handshake(); err != nil {
  549. return err
  550. }
  551. whisperPeer.start()
  552. defer whisperPeer.stop()
  553. return whisper.runMessageLoop(whisperPeer, rw)
  554. }
  555. // runMessageLoop reads and processes inbound messages directly to merge into client-global state.
  556. func (whisper *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
  557. for {
  558. // fetch the next packet
  559. packet, err := rw.ReadMsg()
  560. if err != nil {
  561. log.Info("message loop", "peer", p.peer.ID(), "err", err)
  562. return err
  563. }
  564. if packet.Size > whisper.MaxMessageSize() {
  565. log.Warn("oversized message received", "peer", p.peer.ID())
  566. return errors.New("oversized message received")
  567. }
  568. switch packet.Code {
  569. case statusCode:
  570. // this should not happen, but no need to panic; just ignore this message.
  571. log.Warn("unxepected status message received", "peer", p.peer.ID())
  572. case messagesCode:
  573. // decode the contained envelopes
  574. var envelopes []*Envelope
  575. if err := packet.Decode(&envelopes); err != nil {
  576. log.Warn("failed to decode envelopes, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  577. return errors.New("invalid envelopes")
  578. }
  579. trouble := false
  580. for _, env := range envelopes {
  581. cached, err := whisper.add(env, whisper.lightClient)
  582. if err != nil {
  583. trouble = true
  584. log.Error("bad envelope received, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  585. }
  586. if cached {
  587. p.mark(env)
  588. }
  589. }
  590. if trouble {
  591. return errors.New("invalid envelope")
  592. }
  593. case powRequirementCode:
  594. s := rlp.NewStream(packet.Payload, uint64(packet.Size))
  595. i, err := s.Uint()
  596. if err != nil {
  597. log.Warn("failed to decode powRequirementCode message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  598. return errors.New("invalid powRequirementCode message")
  599. }
  600. f := math.Float64frombits(i)
  601. if math.IsInf(f, 0) || math.IsNaN(f) || f < 0.0 {
  602. log.Warn("invalid value in powRequirementCode message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  603. return errors.New("invalid value in powRequirementCode message")
  604. }
  605. p.powRequirement = f
  606. case bloomFilterExCode:
  607. var bloom []byte
  608. err := packet.Decode(&bloom)
  609. if err == nil && len(bloom) != BloomFilterSize {
  610. err = fmt.Errorf("wrong bloom filter size %d", len(bloom))
  611. }
  612. if err != nil {
  613. log.Warn("failed to decode bloom filter exchange message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  614. return errors.New("invalid bloom filter exchange message")
  615. }
  616. p.setBloomFilter(bloom)
  617. case p2pMessageCode:
  618. // peer-to-peer message, sent directly to peer bypassing PoW checks, etc.
  619. // this message is not supposed to be forwarded to other peers, and
  620. // therefore might not satisfy the PoW, expiry and other requirements.
  621. // these messages are only accepted from the trusted peer.
  622. if p.trusted {
  623. var envelope Envelope
  624. if err := packet.Decode(&envelope); err != nil {
  625. log.Warn("failed to decode direct message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  626. return errors.New("invalid direct message")
  627. }
  628. whisper.postEvent(&envelope, true)
  629. }
  630. case p2pRequestCode:
  631. // Must be processed if mail server is implemented. Otherwise ignore.
  632. if whisper.mailServer != nil {
  633. var request Envelope
  634. if err := packet.Decode(&request); err != nil {
  635. log.Warn("failed to decode p2p request message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
  636. return errors.New("invalid p2p request")
  637. }
  638. whisper.mailServer.DeliverMail(p, &request)
  639. }
  640. default:
  641. // New message types might be implemented in the future versions of Whisper.
  642. // For forward compatibility, just ignore.
  643. }
  644. packet.Discard()
  645. }
  646. }
  647. // add inserts a new envelope into the message pool to be distributed within the
  648. // whisper network. It also inserts the envelope into the expiration pool at the
  649. // appropriate time-stamp. In case of error, connection should be dropped.
  650. // param isP2P indicates whether the message is peer-to-peer (should not be forwarded).
  651. func (whisper *Whisper) add(envelope *Envelope, isP2P bool) (bool, error) {
  652. now := uint32(time.Now().Unix())
  653. sent := envelope.Expiry - envelope.TTL
  654. if sent > now {
  655. if sent-DefaultSyncAllowance > now {
  656. return false, fmt.Errorf("envelope created in the future [%x]", envelope.Hash())
  657. }
  658. // recalculate PoW, adjusted for the time difference, plus one second for latency
  659. envelope.calculatePoW(sent - now + 1)
  660. }
  661. if envelope.Expiry < now {
  662. if envelope.Expiry+DefaultSyncAllowance*2 < now {
  663. return false, fmt.Errorf("very old message")
  664. }
  665. log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
  666. return false, nil // drop envelope without error
  667. }
  668. if uint32(envelope.size()) > whisper.MaxMessageSize() {
  669. return false, fmt.Errorf("huge messages are not allowed [%x]", envelope.Hash())
  670. }
  671. if envelope.PoW() < whisper.MinPow() {
  672. // maybe the value was recently changed, and the peers did not adjust yet.
  673. // in this case the previous value is retrieved by MinPowTolerance()
  674. // for a short period of peer synchronization.
  675. if envelope.PoW() < whisper.MinPowTolerance() {
  676. return false, fmt.Errorf("envelope with low PoW received: PoW=%f, hash=[%v]", envelope.PoW(), envelope.Hash().Hex())
  677. }
  678. }
  679. if !BloomFilterMatch(whisper.BloomFilter(), envelope.Bloom()) {
  680. // maybe the value was recently changed, and the peers did not adjust yet.
  681. // in this case the previous value is retrieved by BloomFilterTolerance()
  682. // for a short period of peer synchronization.
  683. if !BloomFilterMatch(whisper.BloomFilterTolerance(), envelope.Bloom()) {
  684. return false, fmt.Errorf("envelope does not match bloom filter, hash=[%v], bloom: \n%x \n%x \n%x",
  685. envelope.Hash().Hex(), whisper.BloomFilter(), envelope.Bloom(), envelope.Topic)
  686. }
  687. }
  688. hash := envelope.Hash()
  689. whisper.poolMu.Lock()
  690. _, alreadyCached := whisper.envelopes[hash]
  691. if !alreadyCached {
  692. whisper.envelopes[hash] = envelope
  693. if whisper.expirations[envelope.Expiry] == nil {
  694. whisper.expirations[envelope.Expiry] = set.NewNonTS()
  695. }
  696. if !whisper.expirations[envelope.Expiry].Has(hash) {
  697. whisper.expirations[envelope.Expiry].Add(hash)
  698. }
  699. }
  700. whisper.poolMu.Unlock()
  701. if alreadyCached {
  702. log.Trace("whisper envelope already cached", "hash", envelope.Hash().Hex())
  703. } else {
  704. log.Trace("cached whisper envelope", "hash", envelope.Hash().Hex())
  705. whisper.statsMu.Lock()
  706. whisper.stats.memoryUsed += envelope.size()
  707. whisper.statsMu.Unlock()
  708. whisper.postEvent(envelope, isP2P) // notify the local node about the new message
  709. if whisper.mailServer != nil {
  710. whisper.mailServer.Archive(envelope)
  711. }
  712. }
  713. return true, nil
  714. }
  715. // postEvent queues the message for further processing.
  716. func (whisper *Whisper) postEvent(envelope *Envelope, isP2P bool) {
  717. if isP2P {
  718. whisper.p2pMsgQueue <- envelope
  719. } else {
  720. whisper.checkOverflow()
  721. whisper.messageQueue <- envelope
  722. }
  723. }
  724. // checkOverflow checks if message queue overflow occurs and reports it if necessary.
  725. func (whisper *Whisper) checkOverflow() {
  726. queueSize := len(whisper.messageQueue)
  727. if queueSize == messageQueueLimit {
  728. if !whisper.Overflow() {
  729. whisper.settings.Store(overflowIdx, true)
  730. log.Warn("message queue overflow")
  731. }
  732. } else if queueSize <= messageQueueLimit/2 {
  733. if whisper.Overflow() {
  734. whisper.settings.Store(overflowIdx, false)
  735. log.Warn("message queue overflow fixed (back to normal)")
  736. }
  737. }
  738. }
  739. // processQueue delivers the messages to the watchers during the lifetime of the whisper node.
  740. func (whisper *Whisper) processQueue() {
  741. var e *Envelope
  742. for {
  743. select {
  744. case <-whisper.quit:
  745. return
  746. case e = <-whisper.messageQueue:
  747. whisper.filters.NotifyWatchers(e, false)
  748. case e = <-whisper.p2pMsgQueue:
  749. whisper.filters.NotifyWatchers(e, true)
  750. }
  751. }
  752. }
  753. // update loops until the lifetime of the whisper node, updating its internal
  754. // state by expiring stale messages from the pool.
  755. func (whisper *Whisper) update() {
  756. // Start a ticker to check for expirations
  757. expire := time.NewTicker(expirationCycle)
  758. // Repeat updates until termination is requested
  759. for {
  760. select {
  761. case <-expire.C:
  762. whisper.expire()
  763. case <-whisper.quit:
  764. return
  765. }
  766. }
  767. }
  768. // expire iterates over all the expiration timestamps, removing all stale
  769. // messages from the pools.
  770. func (whisper *Whisper) expire() {
  771. whisper.poolMu.Lock()
  772. defer whisper.poolMu.Unlock()
  773. whisper.statsMu.Lock()
  774. defer whisper.statsMu.Unlock()
  775. whisper.stats.reset()
  776. now := uint32(time.Now().Unix())
  777. for expiry, hashSet := range whisper.expirations {
  778. if expiry < now {
  779. // Dump all expired messages and remove timestamp
  780. hashSet.Each(func(v interface{}) bool {
  781. sz := whisper.envelopes[v.(common.Hash)].size()
  782. delete(whisper.envelopes, v.(common.Hash))
  783. whisper.stats.messagesCleared++
  784. whisper.stats.memoryCleared += sz
  785. whisper.stats.memoryUsed -= sz
  786. return true
  787. })
  788. whisper.expirations[expiry].Clear()
  789. delete(whisper.expirations, expiry)
  790. }
  791. }
  792. }
  793. // Stats returns the whisper node statistics.
  794. func (whisper *Whisper) Stats() Statistics {
  795. whisper.statsMu.Lock()
  796. defer whisper.statsMu.Unlock()
  797. return whisper.stats
  798. }
  799. // Envelopes retrieves all the messages currently pooled by the node.
  800. func (whisper *Whisper) Envelopes() []*Envelope {
  801. whisper.poolMu.RLock()
  802. defer whisper.poolMu.RUnlock()
  803. all := make([]*Envelope, 0, len(whisper.envelopes))
  804. for _, envelope := range whisper.envelopes {
  805. all = append(all, envelope)
  806. }
  807. return all
  808. }
  809. // isEnvelopeCached checks if envelope with specific hash has already been received and cached.
  810. func (whisper *Whisper) isEnvelopeCached(hash common.Hash) bool {
  811. whisper.poolMu.Lock()
  812. defer whisper.poolMu.Unlock()
  813. _, exist := whisper.envelopes[hash]
  814. return exist
  815. }
  816. // reset resets the node's statistics after each expiry cycle.
  817. func (s *Statistics) reset() {
  818. s.cycles++
  819. s.totalMessagesCleared += s.messagesCleared
  820. s.memoryCleared = 0
  821. s.messagesCleared = 0
  822. }
  823. // ValidatePublicKey checks the format of the given public key.
  824. func ValidatePublicKey(k *ecdsa.PublicKey) bool {
  825. return k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0
  826. }
  827. // validatePrivateKey checks the format of the given private key.
  828. func validatePrivateKey(k *ecdsa.PrivateKey) bool {
  829. if k == nil || k.D == nil || k.D.Sign() == 0 {
  830. return false
  831. }
  832. return ValidatePublicKey(&k.PublicKey)
  833. }
  834. // validateDataIntegrity returns false if the data have the wrong or contains all zeros,
  835. // which is the simplest and the most common bug.
  836. func validateDataIntegrity(k []byte, expectedSize int) bool {
  837. if len(k) != expectedSize {
  838. return false
  839. }
  840. if expectedSize > 3 && containsOnlyZeros(k) {
  841. return false
  842. }
  843. return true
  844. }
  845. // containsOnlyZeros checks if the data contain only zeros.
  846. func containsOnlyZeros(data []byte) bool {
  847. for _, b := range data {
  848. if b != 0 {
  849. return false
  850. }
  851. }
  852. return true
  853. }
  854. // bytesToUintLittleEndian converts the slice to 64-bit unsigned integer.
  855. func bytesToUintLittleEndian(b []byte) (res uint64) {
  856. mul := uint64(1)
  857. for i := 0; i < len(b); i++ {
  858. res += uint64(b[i]) * mul
  859. mul *= 256
  860. }
  861. return res
  862. }
  863. // BytesToUintBigEndian converts the slice to 64-bit unsigned integer.
  864. func BytesToUintBigEndian(b []byte) (res uint64) {
  865. for i := 0; i < len(b); i++ {
  866. res *= 256
  867. res += uint64(b[i])
  868. }
  869. return res
  870. }
  871. // GenerateRandomID generates a random string, which is then returned to be used as a key id
  872. func GenerateRandomID() (id string, err error) {
  873. buf, err := generateSecureRandomData(keyIDSize)
  874. if err != nil {
  875. return "", err
  876. }
  877. if !validateDataIntegrity(buf, keyIDSize) {
  878. return "", fmt.Errorf("error in generateRandomID: crypto/rand failed to generate random data")
  879. }
  880. id = common.Bytes2Hex(buf)
  881. return id, err
  882. }
  883. func isFullNode(bloom []byte) bool {
  884. if bloom == nil {
  885. return true
  886. }
  887. for _, b := range bloom {
  888. if b != 255 {
  889. return false
  890. }
  891. }
  892. return true
  893. }
  894. func BloomFilterMatch(filter, sample []byte) bool {
  895. if filter == nil {
  896. return true
  897. }
  898. for i := 0; i < BloomFilterSize; i++ {
  899. f := filter[i]
  900. s := sample[i]
  901. if (f | s) != f {
  902. return false
  903. }
  904. }
  905. return true
  906. }
  907. func addBloom(a, b []byte) []byte {
  908. c := make([]byte, BloomFilterSize)
  909. for i := 0; i < BloomFilterSize; i++ {
  910. c[i] = a[i] | b[i]
  911. }
  912. return c
  913. }