api.go 17 KB

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