api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. "context"
  19. "crypto/ecdsa"
  20. "errors"
  21. "fmt"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/common/hexutil"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/p2p/discover"
  29. "github.com/ethereum/go-ethereum/rpc"
  30. )
  31. const (
  32. filterTimeout = 300 // filters are considered timeout out after filterTimeout seconds
  33. )
  34. var (
  35. ErrSymAsym = errors.New("specify either a symmetric or an asymmetric key")
  36. ErrInvalidSymmetricKey = errors.New("invalid symmetric key")
  37. ErrInvalidPublicKey = errors.New("invalid public key")
  38. ErrInvalidSigningPubKey = errors.New("invalid signing public key")
  39. ErrTooLowPoW = errors.New("message rejected, PoW too low")
  40. ErrNoTopics = errors.New("missing topic(s)")
  41. )
  42. // PublicWhisperAPI provides the whisper RPC service that can be
  43. // use publicly without security implications.
  44. type PublicWhisperAPI struct {
  45. w *Whisper
  46. mu sync.Mutex
  47. lastUsed map[string]time.Time // keeps track when a filter was polled for the last time.
  48. }
  49. // NewPublicWhisperAPI create a new RPC whisper service.
  50. func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI {
  51. api := &PublicWhisperAPI{
  52. w: w,
  53. lastUsed: make(map[string]time.Time),
  54. }
  55. go api.run()
  56. return api
  57. }
  58. // run the api event loop.
  59. // this loop deletes filter that have not been used within filterTimeout
  60. func (api *PublicWhisperAPI) run() {
  61. timeout := time.NewTicker(2 * time.Minute)
  62. for {
  63. <-timeout.C
  64. api.mu.Lock()
  65. for id, lastUsed := range api.lastUsed {
  66. if time.Since(lastUsed).Seconds() >= filterTimeout {
  67. delete(api.lastUsed, id)
  68. if err := api.w.Unsubscribe(id); err != nil {
  69. log.Error("could not unsubscribe whisper filter", "error", err)
  70. }
  71. log.Debug("delete whisper filter (timeout)", "id", id)
  72. }
  73. }
  74. api.mu.Unlock()
  75. }
  76. }
  77. // Version returns the Whisper sub-protocol version.
  78. func (api *PublicWhisperAPI) Version(ctx context.Context) string {
  79. return ProtocolVersionStr
  80. }
  81. // Info contains diagnostic information.
  82. type Info struct {
  83. Memory int `json:"memory"` // Memory size of the floating messages in bytes.
  84. Messages int `json:"messages"` // Number of floating messages.
  85. MinPow float64 `json:"minPow"` // Minimal accepted PoW
  86. MaxMessageSize uint32 `json:"maxMessageSize"` // Maximum accepted message size
  87. }
  88. // Info returns diagnostic information about the whisper node.
  89. func (api *PublicWhisperAPI) Info(ctx context.Context) Info {
  90. stats := api.w.Stats()
  91. return Info{
  92. Memory: stats.memoryUsed,
  93. Messages: len(api.w.messageQueue) + len(api.w.p2pMsgQueue),
  94. MinPow: api.w.MinPow(),
  95. MaxMessageSize: api.w.MaxMessageSize(),
  96. }
  97. }
  98. // SetMaxMessageSize sets the maximum message size that is accepted.
  99. // Upper limit is defined by MaxMessageSize.
  100. func (api *PublicWhisperAPI) SetMaxMessageSize(ctx context.Context, size uint32) (bool, error) {
  101. return true, api.w.SetMaxMessageSize(size)
  102. }
  103. // SetMinPow sets the minimum PoW, and notifies the peers.
  104. func (api *PublicWhisperAPI) SetMinPoW(ctx context.Context, pow float64) (bool, error) {
  105. return true, api.w.SetMinimumPoW(pow)
  106. }
  107. // SetBloomFilter sets the new value of bloom filter, and notifies the peers.
  108. func (api *PublicWhisperAPI) SetBloomFilter(ctx context.Context, bloom hexutil.Bytes) (bool, error) {
  109. return true, api.w.SetBloomFilter(bloom)
  110. }
  111. // MarkTrustedPeer marks a peer trusted, which will allow it to send historic (expired) messages.
  112. // Note: This function is not adding new nodes, the node needs to exists as a peer.
  113. func (api *PublicWhisperAPI) MarkTrustedPeer(ctx context.Context, enode string) (bool, error) {
  114. n, err := discover.ParseNode(enode)
  115. if err != nil {
  116. return false, err
  117. }
  118. return true, api.w.AllowP2PMessagesFromPeer(n.ID[:])
  119. }
  120. // NewKeyPair generates a new public and private key pair for message decryption and encryption.
  121. // It returns an ID that can be used to refer to the keypair.
  122. func (api *PublicWhisperAPI) NewKeyPair(ctx context.Context) (string, error) {
  123. return api.w.NewKeyPair()
  124. }
  125. // AddPrivateKey imports the given private key.
  126. func (api *PublicWhisperAPI) AddPrivateKey(ctx context.Context, privateKey hexutil.Bytes) (string, error) {
  127. key, err := crypto.ToECDSA(privateKey)
  128. if err != nil {
  129. return "", err
  130. }
  131. return api.w.AddKeyPair(key)
  132. }
  133. // DeleteKeyPair removes the key with the given key if it exists.
  134. func (api *PublicWhisperAPI) DeleteKeyPair(ctx context.Context, key string) (bool, error) {
  135. if ok := api.w.DeleteKeyPair(key); ok {
  136. return true, nil
  137. }
  138. return false, fmt.Errorf("key pair %s not found", key)
  139. }
  140. // HasKeyPair returns an indication if the node has a key pair that is associated with the given id.
  141. func (api *PublicWhisperAPI) HasKeyPair(ctx context.Context, id string) bool {
  142. return api.w.HasKeyPair(id)
  143. }
  144. // GetPublicKey returns the public key associated with the given key. The key is the hex
  145. // encoded representation of a key in the form specified in section 4.3.6 of ANSI X9.62.
  146. func (api *PublicWhisperAPI) GetPublicKey(ctx context.Context, id string) (hexutil.Bytes, error) {
  147. key, err := api.w.GetPrivateKey(id)
  148. if err != nil {
  149. return hexutil.Bytes{}, err
  150. }
  151. return crypto.FromECDSAPub(&key.PublicKey), nil
  152. }
  153. // GetPublicKey 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. // NewSymKey generate a random symmetric key.
  163. // It returns an ID that can be used to refer to the key.
  164. // Can be used encrypting and decrypting messages where the key is known to both parties.
  165. func (api *PublicWhisperAPI) NewSymKey(ctx context.Context) (string, error) {
  166. return api.w.GenerateSymKey()
  167. }
  168. // AddSymKey import a symmetric key.
  169. // It returns an ID that can be used to refer to the key.
  170. // Can be used encrypting and decrypting messages where the key is known to both parties.
  171. func (api *PublicWhisperAPI) AddSymKey(ctx context.Context, key hexutil.Bytes) (string, error) {
  172. return api.w.AddSymKeyDirect([]byte(key))
  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. // HasSymKey returns an indication if the node has a symmetric key associated with the given key.
  179. func (api *PublicWhisperAPI) HasSymKey(ctx context.Context, id string) bool {
  180. return api.w.HasSymKey(id)
  181. }
  182. // GetSymKey returns the symmetric key associated with the given id.
  183. func (api *PublicWhisperAPI) GetSymKey(ctx context.Context, id string) (hexutil.Bytes, error) {
  184. return api.w.GetSymKey(id)
  185. }
  186. // DeleteSymKey deletes the symmetric key that is associated with the given id.
  187. func (api *PublicWhisperAPI) DeleteSymKey(ctx context.Context, id string) bool {
  188. return api.w.DeleteSymKey(id)
  189. }
  190. //go:generate gencodec -type NewMessage -field-override newMessageOverride -out gen_newmessage_json.go
  191. // NewMessage represents a new whisper message that is posted through the RPC.
  192. type NewMessage struct {
  193. SymKeyID string `json:"symKeyID"`
  194. PublicKey []byte `json:"pubKey"`
  195. Sig string `json:"sig"`
  196. TTL uint32 `json:"ttl"`
  197. Topic TopicType `json:"topic"`
  198. Payload []byte `json:"payload"`
  199. Padding []byte `json:"padding"`
  200. PowTime uint32 `json:"powTime"`
  201. PowTarget float64 `json:"powTarget"`
  202. TargetPeer string `json:"targetPeer"`
  203. }
  204. type newMessageOverride struct {
  205. PublicKey hexutil.Bytes
  206. Payload hexutil.Bytes
  207. Padding hexutil.Bytes
  208. }
  209. // Post a message on the Whisper network.
  210. func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (bool, error) {
  211. var (
  212. symKeyGiven = len(req.SymKeyID) > 0
  213. pubKeyGiven = len(req.PublicKey) > 0
  214. err error
  215. )
  216. // user must specify either a symmetric or an asymmetric key
  217. if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
  218. return false, ErrSymAsym
  219. }
  220. params := &MessageParams{
  221. TTL: req.TTL,
  222. Payload: req.Payload,
  223. Padding: req.Padding,
  224. WorkTime: req.PowTime,
  225. PoW: req.PowTarget,
  226. Topic: req.Topic,
  227. }
  228. // Set key that is used to sign the message
  229. if len(req.Sig) > 0 {
  230. if params.Src, err = api.w.GetPrivateKey(req.Sig); err != nil {
  231. return false, err
  232. }
  233. }
  234. // Set symmetric key that is used to encrypt the message
  235. if symKeyGiven {
  236. if params.Topic == (TopicType{}) { // topics are mandatory with symmetric encryption
  237. return false, ErrNoTopics
  238. }
  239. if params.KeySym, err = api.w.GetSymKey(req.SymKeyID); err != nil {
  240. return false, err
  241. }
  242. if !validateSymmetricKey(params.KeySym) {
  243. return false, ErrInvalidSymmetricKey
  244. }
  245. }
  246. // Set asymmetric key that is used to encrypt the message
  247. if pubKeyGiven {
  248. params.Dst = crypto.ToECDSAPub(req.PublicKey)
  249. if !ValidatePublicKey(params.Dst) {
  250. return false, ErrInvalidPublicKey
  251. }
  252. }
  253. // encrypt and sent message
  254. whisperMsg, err := NewSentMessage(params)
  255. if err != nil {
  256. return false, err
  257. }
  258. env, err := whisperMsg.Wrap(params)
  259. if err != nil {
  260. return false, err
  261. }
  262. // send to specific node (skip PoW check)
  263. if len(req.TargetPeer) > 0 {
  264. n, err := discover.ParseNode(req.TargetPeer)
  265. if err != nil {
  266. return false, fmt.Errorf("failed to parse target peer: %s", err)
  267. }
  268. return true, api.w.SendP2PMessage(n.ID[:], env)
  269. }
  270. // ensure that the message PoW meets the node's minimum accepted PoW
  271. if req.PowTarget < api.w.MinPow() {
  272. return false, ErrTooLowPoW
  273. }
  274. return true, api.w.Send(env)
  275. }
  276. //go:generate gencodec -type Criteria -field-override criteriaOverride -out gen_criteria_json.go
  277. // Criteria holds various filter options for inbound messages.
  278. type Criteria struct {
  279. SymKeyID string `json:"symKeyID"`
  280. PrivateKeyID string `json:"privateKeyID"`
  281. Sig []byte `json:"sig"`
  282. MinPow float64 `json:"minPow"`
  283. Topics []TopicType `json:"topics"`
  284. AllowP2P bool `json:"allowP2P"`
  285. }
  286. type criteriaOverride struct {
  287. Sig hexutil.Bytes
  288. }
  289. // Messages set up a subscription that fires events when messages arrive that match
  290. // the given set of criteria.
  291. func (api *PublicWhisperAPI) Messages(ctx context.Context, crit Criteria) (*rpc.Subscription, error) {
  292. var (
  293. symKeyGiven = len(crit.SymKeyID) > 0
  294. pubKeyGiven = len(crit.PrivateKeyID) > 0
  295. err error
  296. )
  297. // ensure that the RPC connection supports subscriptions
  298. notifier, supported := rpc.NotifierFromContext(ctx)
  299. if !supported {
  300. return nil, rpc.ErrNotificationsUnsupported
  301. }
  302. // user must specify either a symmetric or an asymmetric key
  303. if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
  304. return nil, ErrSymAsym
  305. }
  306. filter := Filter{
  307. PoW: crit.MinPow,
  308. Messages: make(map[common.Hash]*ReceivedMessage),
  309. AllowP2P: crit.AllowP2P,
  310. }
  311. if len(crit.Sig) > 0 {
  312. filter.Src = crypto.ToECDSAPub(crit.Sig)
  313. if !ValidatePublicKey(filter.Src) {
  314. return nil, ErrInvalidSigningPubKey
  315. }
  316. }
  317. for i, bt := range crit.Topics {
  318. if len(bt) == 0 || len(bt) > 4 {
  319. return nil, fmt.Errorf("subscribe: topic %d has wrong size: %d", i, len(bt))
  320. }
  321. filter.Topics = append(filter.Topics, bt[:])
  322. }
  323. // listen for message that are encrypted with the given symmetric key
  324. if symKeyGiven {
  325. if len(filter.Topics) == 0 {
  326. return nil, ErrNoTopics
  327. }
  328. key, err := api.w.GetSymKey(crit.SymKeyID)
  329. if err != nil {
  330. return nil, err
  331. }
  332. if !validateSymmetricKey(key) {
  333. return nil, ErrInvalidSymmetricKey
  334. }
  335. filter.KeySym = key
  336. filter.SymKeyHash = crypto.Keccak256Hash(filter.KeySym)
  337. }
  338. // listen for messages that are encrypted with the given public key
  339. if pubKeyGiven {
  340. filter.KeyAsym, err = api.w.GetPrivateKey(crit.PrivateKeyID)
  341. if err != nil || filter.KeyAsym == nil {
  342. return nil, ErrInvalidPublicKey
  343. }
  344. }
  345. id, err := api.w.Subscribe(&filter)
  346. if err != nil {
  347. return nil, err
  348. }
  349. // create subscription and start waiting for message events
  350. rpcSub := notifier.CreateSubscription()
  351. go func() {
  352. // for now poll internally, refactor whisper internal for channel support
  353. ticker := time.NewTicker(250 * time.Millisecond)
  354. defer ticker.Stop()
  355. for {
  356. select {
  357. case <-ticker.C:
  358. if filter := api.w.GetFilter(id); filter != nil {
  359. for _, rpcMessage := range toMessage(filter.Retrieve()) {
  360. if err := notifier.Notify(rpcSub.ID, rpcMessage); err != nil {
  361. log.Error("Failed to send notification", "err", err)
  362. }
  363. }
  364. }
  365. case <-rpcSub.Err():
  366. api.w.Unsubscribe(id)
  367. return
  368. case <-notifier.Closed():
  369. api.w.Unsubscribe(id)
  370. return
  371. }
  372. }
  373. }()
  374. return rpcSub, nil
  375. }
  376. //go:generate gencodec -type Message -field-override messageOverride -out gen_message_json.go
  377. // Message is the RPC representation of a whisper message.
  378. type Message struct {
  379. Sig []byte `json:"sig,omitempty"`
  380. TTL uint32 `json:"ttl"`
  381. Timestamp uint32 `json:"timestamp"`
  382. Topic TopicType `json:"topic"`
  383. Payload []byte `json:"payload"`
  384. Padding []byte `json:"padding"`
  385. PoW float64 `json:"pow"`
  386. Hash []byte `json:"hash"`
  387. Dst []byte `json:"recipientPublicKey,omitempty"`
  388. }
  389. type messageOverride struct {
  390. Sig hexutil.Bytes
  391. Payload hexutil.Bytes
  392. Padding hexutil.Bytes
  393. Hash hexutil.Bytes
  394. Dst hexutil.Bytes
  395. }
  396. // ToWhisperMessage converts an internal message into an API version.
  397. func ToWhisperMessage(message *ReceivedMessage) *Message {
  398. msg := Message{
  399. Payload: message.Payload,
  400. Padding: message.Padding,
  401. Timestamp: message.Sent,
  402. TTL: message.TTL,
  403. PoW: message.PoW,
  404. Hash: message.EnvelopeHash.Bytes(),
  405. Topic: message.Topic,
  406. }
  407. if message.Dst != nil {
  408. b := crypto.FromECDSAPub(message.Dst)
  409. if b != nil {
  410. msg.Dst = b
  411. }
  412. }
  413. if isMessageSigned(message.Raw[0]) {
  414. b := crypto.FromECDSAPub(message.SigToPubKey())
  415. if b != nil {
  416. msg.Sig = b
  417. }
  418. }
  419. return &msg
  420. }
  421. // toMessage converts a set of messages to its RPC representation.
  422. func toMessage(messages []*ReceivedMessage) []*Message {
  423. msgs := make([]*Message, len(messages))
  424. for i, msg := range messages {
  425. msgs[i] = ToWhisperMessage(msg)
  426. }
  427. return msgs
  428. }
  429. // GetFilterMessages returns the messages that match the filter criteria and
  430. // are received between the last poll and now.
  431. func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) {
  432. api.mu.Lock()
  433. f := api.w.GetFilter(id)
  434. if f == nil {
  435. api.mu.Unlock()
  436. return nil, fmt.Errorf("filter not found")
  437. }
  438. api.lastUsed[id] = time.Now()
  439. api.mu.Unlock()
  440. receivedMessages := f.Retrieve()
  441. messages := make([]*Message, 0, len(receivedMessages))
  442. for _, msg := range receivedMessages {
  443. messages = append(messages, ToWhisperMessage(msg))
  444. }
  445. return messages, nil
  446. }
  447. // DeleteMessageFilter deletes a filter.
  448. func (api *PublicWhisperAPI) DeleteMessageFilter(id string) (bool, error) {
  449. api.mu.Lock()
  450. defer api.mu.Unlock()
  451. delete(api.lastUsed, id)
  452. return true, api.w.Unsubscribe(id)
  453. }
  454. // NewMessageFilter creates a new filter that can be used to poll for
  455. // (new) messages that satisfy the given criteria.
  456. func (api *PublicWhisperAPI) NewMessageFilter(req Criteria) (string, error) {
  457. var (
  458. src *ecdsa.PublicKey
  459. keySym []byte
  460. keyAsym *ecdsa.PrivateKey
  461. topics [][]byte
  462. symKeyGiven = len(req.SymKeyID) > 0
  463. asymKeyGiven = len(req.PrivateKeyID) > 0
  464. err error
  465. )
  466. // user must specify either a symmetric or an asymmetric key
  467. if (symKeyGiven && asymKeyGiven) || (!symKeyGiven && !asymKeyGiven) {
  468. return "", ErrSymAsym
  469. }
  470. if len(req.Sig) > 0 {
  471. src = crypto.ToECDSAPub(req.Sig)
  472. if !ValidatePublicKey(src) {
  473. return "", ErrInvalidSigningPubKey
  474. }
  475. }
  476. if symKeyGiven {
  477. if keySym, err = api.w.GetSymKey(req.SymKeyID); err != nil {
  478. return "", err
  479. }
  480. if !validateSymmetricKey(keySym) {
  481. return "", ErrInvalidSymmetricKey
  482. }
  483. }
  484. if asymKeyGiven {
  485. if keyAsym, err = api.w.GetPrivateKey(req.PrivateKeyID); err != nil {
  486. return "", err
  487. }
  488. }
  489. if len(req.Topics) > 0 {
  490. topics = make([][]byte, 1)
  491. for _, topic := range req.Topics {
  492. topics = append(topics, topic[:])
  493. }
  494. }
  495. f := &Filter{
  496. Src: src,
  497. KeySym: keySym,
  498. KeyAsym: keyAsym,
  499. PoW: req.MinPow,
  500. AllowP2P: req.AllowP2P,
  501. Topics: topics,
  502. Messages: make(map[common.Hash]*ReceivedMessage),
  503. }
  504. id, err := api.w.Subscribe(f)
  505. if err != nil {
  506. return "", err
  507. }
  508. api.mu.Lock()
  509. api.lastUsed[id] = time.Now()
  510. api.mu.Unlock()
  511. return id, nil
  512. }