api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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 a message on the Whisper network.
  199. func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (bool, error) {
  200. var (
  201. symKeyGiven = len(req.SymKeyID) > 0
  202. pubKeyGiven = len(req.PublicKey) > 0
  203. err error
  204. )
  205. // user must specify either a symmetric or an asymmetric key
  206. if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
  207. return false, ErrSymAsym
  208. }
  209. params := &MessageParams{
  210. TTL: req.TTL,
  211. Payload: req.Payload,
  212. Padding: req.Padding,
  213. WorkTime: req.PowTime,
  214. PoW: req.PowTarget,
  215. Topic: req.Topic,
  216. }
  217. // Set key that is used to sign the message
  218. if len(req.Sig) > 0 {
  219. if params.Src, err = api.w.GetPrivateKey(req.Sig); err != nil {
  220. return false, err
  221. }
  222. }
  223. // Set symmetric key that is used to encrypt the message
  224. if symKeyGiven {
  225. if params.Topic == (TopicType{}) { // topics are mandatory with symmetric encryption
  226. return false, ErrNoTopics
  227. }
  228. if params.KeySym, err = api.w.GetSymKey(req.SymKeyID); err != nil {
  229. return false, err
  230. }
  231. if !validateDataIntegrity(params.KeySym, aesKeyLength) {
  232. return false, ErrInvalidSymmetricKey
  233. }
  234. }
  235. // Set asymmetric key that is used to encrypt the message
  236. if pubKeyGiven {
  237. params.Dst = crypto.ToECDSAPub(req.PublicKey)
  238. if !ValidatePublicKey(params.Dst) {
  239. return false, ErrInvalidPublicKey
  240. }
  241. }
  242. // encrypt and sent message
  243. whisperMsg, err := NewSentMessage(params)
  244. if err != nil {
  245. return false, err
  246. }
  247. env, err := whisperMsg.Wrap(params)
  248. if err != nil {
  249. return false, err
  250. }
  251. // send to specific node (skip PoW check)
  252. if len(req.TargetPeer) > 0 {
  253. n, err := discover.ParseNode(req.TargetPeer)
  254. if err != nil {
  255. return false, fmt.Errorf("failed to parse target peer: %s", err)
  256. }
  257. return true, api.w.SendP2PMessage(n.ID[:], env)
  258. }
  259. // ensure that the message PoW meets the node's minimum accepted PoW
  260. if req.PowTarget < api.w.MinPow() {
  261. return false, ErrTooLowPoW
  262. }
  263. return true, api.w.Send(env)
  264. }
  265. //go:generate gencodec -type Criteria -field-override criteriaOverride -out gen_criteria_json.go
  266. // Criteria holds various filter options for inbound messages.
  267. type Criteria struct {
  268. SymKeyID string `json:"symKeyID"`
  269. PrivateKeyID string `json:"privateKeyID"`
  270. Sig []byte `json:"sig"`
  271. MinPow float64 `json:"minPow"`
  272. Topics []TopicType `json:"topics"`
  273. AllowP2P bool `json:"allowP2P"`
  274. }
  275. type criteriaOverride struct {
  276. Sig hexutil.Bytes
  277. }
  278. // Messages set up a subscription that fires events when messages arrive that match
  279. // the given set of criteria.
  280. func (api *PublicWhisperAPI) Messages(ctx context.Context, crit Criteria) (*rpc.Subscription, error) {
  281. var (
  282. symKeyGiven = len(crit.SymKeyID) > 0
  283. pubKeyGiven = len(crit.PrivateKeyID) > 0
  284. err error
  285. )
  286. // ensure that the RPC connection supports subscriptions
  287. notifier, supported := rpc.NotifierFromContext(ctx)
  288. if !supported {
  289. return nil, rpc.ErrNotificationsUnsupported
  290. }
  291. // user must specify either a symmetric or an asymmetric key
  292. if (symKeyGiven && pubKeyGiven) || (!symKeyGiven && !pubKeyGiven) {
  293. return nil, ErrSymAsym
  294. }
  295. filter := Filter{
  296. PoW: crit.MinPow,
  297. Messages: make(map[common.Hash]*ReceivedMessage),
  298. AllowP2P: crit.AllowP2P,
  299. }
  300. if len(crit.Sig) > 0 {
  301. filter.Src = crypto.ToECDSAPub(crit.Sig)
  302. if !ValidatePublicKey(filter.Src) {
  303. return nil, ErrInvalidSigningPubKey
  304. }
  305. }
  306. for i, bt := range crit.Topics {
  307. if len(bt) == 0 || len(bt) > 4 {
  308. return nil, fmt.Errorf("subscribe: topic %d has wrong size: %d", i, len(bt))
  309. }
  310. filter.Topics = append(filter.Topics, bt[:])
  311. }
  312. // listen for message that are encrypted with the given symmetric key
  313. if symKeyGiven {
  314. if len(filter.Topics) == 0 {
  315. return nil, ErrNoTopics
  316. }
  317. key, err := api.w.GetSymKey(crit.SymKeyID)
  318. if err != nil {
  319. return nil, err
  320. }
  321. if !validateDataIntegrity(key, aesKeyLength) {
  322. return nil, ErrInvalidSymmetricKey
  323. }
  324. filter.KeySym = key
  325. filter.SymKeyHash = crypto.Keccak256Hash(filter.KeySym)
  326. }
  327. // listen for messages that are encrypted with the given public key
  328. if pubKeyGiven {
  329. filter.KeyAsym, err = api.w.GetPrivateKey(crit.PrivateKeyID)
  330. if err != nil || filter.KeyAsym == nil {
  331. return nil, ErrInvalidPublicKey
  332. }
  333. }
  334. id, err := api.w.Subscribe(&filter)
  335. if err != nil {
  336. return nil, err
  337. }
  338. // create subscription and start waiting for message events
  339. rpcSub := notifier.CreateSubscription()
  340. go func() {
  341. // for now poll internally, refactor whisper internal for channel support
  342. ticker := time.NewTicker(250 * time.Millisecond)
  343. defer ticker.Stop()
  344. for {
  345. select {
  346. case <-ticker.C:
  347. if filter := api.w.GetFilter(id); filter != nil {
  348. for _, rpcMessage := range toMessage(filter.Retrieve()) {
  349. if err := notifier.Notify(rpcSub.ID, rpcMessage); err != nil {
  350. log.Error("Failed to send notification", "err", err)
  351. }
  352. }
  353. }
  354. case <-rpcSub.Err():
  355. api.w.Unsubscribe(id)
  356. return
  357. case <-notifier.Closed():
  358. api.w.Unsubscribe(id)
  359. return
  360. }
  361. }
  362. }()
  363. return rpcSub, nil
  364. }
  365. //go:generate gencodec -type Message -field-override messageOverride -out gen_message_json.go
  366. // Message is the RPC representation of a whisper message.
  367. type Message struct {
  368. Sig []byte `json:"sig,omitempty"`
  369. TTL uint32 `json:"ttl"`
  370. Timestamp uint32 `json:"timestamp"`
  371. Topic TopicType `json:"topic"`
  372. Payload []byte `json:"payload"`
  373. Padding []byte `json:"padding"`
  374. PoW float64 `json:"pow"`
  375. Hash []byte `json:"hash"`
  376. Dst []byte `json:"recipientPublicKey,omitempty"`
  377. }
  378. type messageOverride struct {
  379. Sig hexutil.Bytes
  380. Payload hexutil.Bytes
  381. Padding hexutil.Bytes
  382. Hash hexutil.Bytes
  383. Dst hexutil.Bytes
  384. }
  385. // ToWhisperMessage converts an internal message into an API version.
  386. func ToWhisperMessage(message *ReceivedMessage) *Message {
  387. msg := Message{
  388. Payload: message.Payload,
  389. Padding: message.Padding,
  390. Timestamp: message.Sent,
  391. TTL: message.TTL,
  392. PoW: message.PoW,
  393. Hash: message.EnvelopeHash.Bytes(),
  394. Topic: message.Topic,
  395. }
  396. if message.Dst != nil {
  397. b := crypto.FromECDSAPub(message.Dst)
  398. if b != nil {
  399. msg.Dst = b
  400. }
  401. }
  402. if isMessageSigned(message.Raw[0]) {
  403. b := crypto.FromECDSAPub(message.SigToPubKey())
  404. if b != nil {
  405. msg.Sig = b
  406. }
  407. }
  408. return &msg
  409. }
  410. // toMessage converts a set of messages to its RPC representation.
  411. func toMessage(messages []*ReceivedMessage) []*Message {
  412. msgs := make([]*Message, len(messages))
  413. for i, msg := range messages {
  414. msgs[i] = ToWhisperMessage(msg)
  415. }
  416. return msgs
  417. }
  418. // GetFilterMessages returns the messages that match the filter criteria and
  419. // are received between the last poll and now.
  420. func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) {
  421. api.mu.Lock()
  422. f := api.w.GetFilter(id)
  423. if f == nil {
  424. api.mu.Unlock()
  425. return nil, fmt.Errorf("filter not found")
  426. }
  427. api.lastUsed[id] = time.Now()
  428. api.mu.Unlock()
  429. receivedMessages := f.Retrieve()
  430. messages := make([]*Message, 0, len(receivedMessages))
  431. for _, msg := range receivedMessages {
  432. messages = append(messages, ToWhisperMessage(msg))
  433. }
  434. return messages, nil
  435. }
  436. // DeleteMessageFilter deletes a filter.
  437. func (api *PublicWhisperAPI) DeleteMessageFilter(id string) (bool, error) {
  438. api.mu.Lock()
  439. defer api.mu.Unlock()
  440. delete(api.lastUsed, id)
  441. return true, api.w.Unsubscribe(id)
  442. }
  443. // NewMessageFilter creates a new filter that can be used to poll for
  444. // (new) messages that satisfy the given criteria.
  445. func (api *PublicWhisperAPI) NewMessageFilter(req Criteria) (string, error) {
  446. var (
  447. src *ecdsa.PublicKey
  448. keySym []byte
  449. keyAsym *ecdsa.PrivateKey
  450. topics [][]byte
  451. symKeyGiven = len(req.SymKeyID) > 0
  452. asymKeyGiven = len(req.PrivateKeyID) > 0
  453. err error
  454. )
  455. // user must specify either a symmetric or an asymmetric key
  456. if (symKeyGiven && asymKeyGiven) || (!symKeyGiven && !asymKeyGiven) {
  457. return "", ErrSymAsym
  458. }
  459. if len(req.Sig) > 0 {
  460. src = crypto.ToECDSAPub(req.Sig)
  461. if !ValidatePublicKey(src) {
  462. return "", ErrInvalidSigningPubKey
  463. }
  464. }
  465. if symKeyGiven {
  466. if keySym, err = api.w.GetSymKey(req.SymKeyID); err != nil {
  467. return "", err
  468. }
  469. if !validateDataIntegrity(keySym, aesKeyLength) {
  470. return "", ErrInvalidSymmetricKey
  471. }
  472. }
  473. if asymKeyGiven {
  474. if keyAsym, err = api.w.GetPrivateKey(req.PrivateKeyID); err != nil {
  475. return "", err
  476. }
  477. }
  478. if len(req.Topics) > 0 {
  479. topics = make([][]byte, len(req.Topics))
  480. for i, topic := range req.Topics {
  481. topics[i] = make([]byte, TopicLength)
  482. copy(topics[i], topic[:])
  483. }
  484. }
  485. f := &Filter{
  486. Src: src,
  487. KeySym: keySym,
  488. KeyAsym: keyAsym,
  489. PoW: req.MinPow,
  490. AllowP2P: req.AllowP2P,
  491. Topics: topics,
  492. Messages: make(map[common.Hash]*ReceivedMessage),
  493. }
  494. id, err := api.w.Subscribe(f)
  495. if err != nil {
  496. return "", err
  497. }
  498. api.mu.Lock()
  499. api.lastUsed[id] = time.Now()
  500. api.mu.Unlock()
  501. return id, nil
  502. }