api.go 17 KB

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