api.go 16 KB

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