api.go 16 KB

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