api.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/hexutil"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/p2p/discover"
  25. )
  26. var whisperOfflineErr = errors.New("whisper is offline")
  27. // PublicWhisperAPI provides the whisper RPC service.
  28. type PublicWhisperAPI struct {
  29. whisper *Whisper
  30. }
  31. // NewPublicWhisperAPI create a new RPC whisper service.
  32. func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI {
  33. return &PublicWhisperAPI{whisper: w}
  34. }
  35. // Start starts the Whisper worker threads.
  36. func (api *PublicWhisperAPI) Start() error {
  37. if api.whisper == nil {
  38. return whisperOfflineErr
  39. }
  40. return api.whisper.Start(nil)
  41. }
  42. // Stop stops the Whisper worker threads.
  43. func (api *PublicWhisperAPI) Stop() error {
  44. if api.whisper == nil {
  45. return whisperOfflineErr
  46. }
  47. return api.whisper.Stop()
  48. }
  49. // Version returns the Whisper version this node offers.
  50. func (api *PublicWhisperAPI) Version() (hexutil.Uint, error) {
  51. if api.whisper == nil {
  52. return 0, whisperOfflineErr
  53. }
  54. return hexutil.Uint(api.whisper.Version()), nil
  55. }
  56. // Info returns the Whisper statistics for diagnostics.
  57. func (api *PublicWhisperAPI) Info() (string, error) {
  58. if api.whisper == nil {
  59. return "", whisperOfflineErr
  60. }
  61. return api.whisper.Stats(), nil
  62. }
  63. // SetMaxMessageLength sets the maximal message length allowed by this node
  64. func (api *PublicWhisperAPI) SetMaxMessageLength(val int) error {
  65. if api.whisper == nil {
  66. return whisperOfflineErr
  67. }
  68. return api.whisper.SetMaxMessageLength(val)
  69. }
  70. // SetMinimumPoW sets the minimal PoW required by this node
  71. func (api *PublicWhisperAPI) SetMinimumPoW(val float64) error {
  72. if api.whisper == nil {
  73. return whisperOfflineErr
  74. }
  75. return api.whisper.SetMinimumPoW(val)
  76. }
  77. // AllowP2PMessagesFromPeer marks specific peer trusted, which will allow it
  78. // to send historic (expired) messages.
  79. func (api *PublicWhisperAPI) AllowP2PMessagesFromPeer(enode string) error {
  80. if api.whisper == nil {
  81. return whisperOfflineErr
  82. }
  83. n, err := discover.ParseNode(enode)
  84. if err != nil {
  85. return errors.New("failed to parse enode of trusted peer: " + err.Error())
  86. }
  87. return api.whisper.AllowP2PMessagesFromPeer(n.ID[:])
  88. }
  89. // HasKeyPair checks if the whisper node is configured with the private key
  90. // of the specified public pair.
  91. func (api *PublicWhisperAPI) HasKeyPair(id string) (bool, error) {
  92. if api.whisper == nil {
  93. return false, whisperOfflineErr
  94. }
  95. return api.whisper.HasKeyPair(id), nil
  96. }
  97. // DeleteKeyPair deletes the specifies key if it exists.
  98. func (api *PublicWhisperAPI) DeleteKeyPair(id string) (bool, error) {
  99. if api.whisper == nil {
  100. return false, whisperOfflineErr
  101. }
  102. return api.whisper.DeleteKeyPair(id), nil
  103. }
  104. // NewKeyPair generates a new cryptographic identity for the client, and injects
  105. // it into the known identities for message decryption.
  106. func (api *PublicWhisperAPI) NewKeyPair() (string, error) {
  107. if api.whisper == nil {
  108. return "", whisperOfflineErr
  109. }
  110. return api.whisper.NewKeyPair()
  111. }
  112. // GetPublicKey returns the public key for identity id
  113. func (api *PublicWhisperAPI) GetPublicKey(id string) (hexutil.Bytes, error) {
  114. if api.whisper == nil {
  115. return nil, whisperOfflineErr
  116. }
  117. key, err := api.whisper.GetPrivateKey(id)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return crypto.FromECDSAPub(&key.PublicKey), nil
  122. }
  123. // GetPrivateKey returns the private key for identity id
  124. func (api *PublicWhisperAPI) GetPrivateKey(id string) (string, error) {
  125. if api.whisper == nil {
  126. return "", whisperOfflineErr
  127. }
  128. key, err := api.whisper.GetPrivateKey(id)
  129. if err != nil {
  130. return "", err
  131. }
  132. return common.ToHex(crypto.FromECDSA(key)), nil
  133. }
  134. // GenerateSymmetricKey generates a random symmetric key and stores it under id,
  135. // which is then returned. Will be used in the future for session key exchange.
  136. func (api *PublicWhisperAPI) GenerateSymmetricKey() (string, error) {
  137. if api.whisper == nil {
  138. return "", whisperOfflineErr
  139. }
  140. return api.whisper.GenerateSymKey()
  141. }
  142. // AddSymmetricKeyDirect stores the key, and returns its id.
  143. func (api *PublicWhisperAPI) AddSymmetricKeyDirect(key hexutil.Bytes) (string, error) {
  144. if api.whisper == nil {
  145. return "", whisperOfflineErr
  146. }
  147. return api.whisper.AddSymKeyDirect(key)
  148. }
  149. // AddSymmetricKeyFromPassword generates the key from password, stores it, and returns its id.
  150. func (api *PublicWhisperAPI) AddSymmetricKeyFromPassword(password string) (string, error) {
  151. if api.whisper == nil {
  152. return "", whisperOfflineErr
  153. }
  154. return api.whisper.AddSymKeyFromPassword(password)
  155. }
  156. // HasSymmetricKey returns true if there is a key associated with the given id.
  157. // Otherwise returns false.
  158. func (api *PublicWhisperAPI) HasSymmetricKey(id string) (bool, error) {
  159. if api.whisper == nil {
  160. return false, whisperOfflineErr
  161. }
  162. res := api.whisper.HasSymKey(id)
  163. return res, nil
  164. }
  165. // GetSymmetricKey returns the symmetric key associated with the given id.
  166. func (api *PublicWhisperAPI) GetSymmetricKey(name string) (hexutil.Bytes, error) {
  167. if api.whisper == nil {
  168. return nil, whisperOfflineErr
  169. }
  170. b, err := api.whisper.GetSymKey(name)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return b, nil
  175. }
  176. // DeleteSymmetricKey deletes the key associated with the name string if it exists.
  177. func (api *PublicWhisperAPI) DeleteSymmetricKey(name string) (bool, error) {
  178. if api.whisper == nil {
  179. return false, whisperOfflineErr
  180. }
  181. res := api.whisper.DeleteSymKey(name)
  182. return res, nil
  183. }
  184. // Subscribe creates and registers a new filter to watch for inbound whisper messages.
  185. // Returns the ID of the newly created filter.
  186. func (api *PublicWhisperAPI) Subscribe(args WhisperFilterArgs) (string, error) {
  187. if api.whisper == nil {
  188. return "", whisperOfflineErr
  189. }
  190. filter := Filter{
  191. PoW: args.MinPoW,
  192. Messages: make(map[common.Hash]*ReceivedMessage),
  193. AllowP2P: args.AllowP2P,
  194. }
  195. var err error
  196. for i, bt := range args.Topics {
  197. if len(bt) == 0 || len(bt) > 4 {
  198. return "", errors.New(fmt.Sprintf("subscribe: topic %d has wrong size: %d", i, len(bt)))
  199. }
  200. filter.Topics = append(filter.Topics, bt)
  201. }
  202. if err = ValidateKeyID(args.Key); err != nil {
  203. return "", errors.New("subscribe: " + err.Error())
  204. }
  205. if len(args.Sig) > 0 {
  206. sb := common.FromHex(args.Sig)
  207. if sb == nil {
  208. return "", errors.New("subscribe: sig parameter is invalid")
  209. }
  210. filter.Src = crypto.ToECDSAPub(sb)
  211. if !ValidatePublicKey(filter.Src) {
  212. return "", errors.New("subscribe: invalid 'sig' field")
  213. }
  214. }
  215. if args.Symmetric {
  216. if len(args.Topics) == 0 {
  217. return "", errors.New("subscribe: at least one topic must be specified with symmetric encryption")
  218. }
  219. symKey, err := api.whisper.GetSymKey(args.Key)
  220. if err != nil {
  221. return "", errors.New("subscribe: invalid key ID")
  222. }
  223. if !validateSymmetricKey(symKey) {
  224. return "", errors.New("subscribe: retrieved key is invalid")
  225. }
  226. filter.KeySym = symKey
  227. filter.SymKeyHash = crypto.Keccak256Hash(filter.KeySym)
  228. } else {
  229. filter.KeyAsym, err = api.whisper.GetPrivateKey(args.Key)
  230. if err != nil {
  231. return "", errors.New("subscribe: invalid key ID")
  232. }
  233. if filter.KeyAsym == nil {
  234. return "", errors.New("subscribe: non-existent identity provided")
  235. }
  236. }
  237. return api.whisper.Subscribe(&filter)
  238. }
  239. // Unsubscribe disables and removes an existing filter.
  240. func (api *PublicWhisperAPI) Unsubscribe(id string) {
  241. api.whisper.Unsubscribe(id)
  242. }
  243. // GetSubscriptionMessages retrieves all the new messages matched by the corresponding
  244. // subscription filter since the last retrieval.
  245. func (api *PublicWhisperAPI) GetNewSubscriptionMessages(id string) []*WhisperMessage {
  246. f := api.whisper.GetFilter(id)
  247. if f != nil {
  248. newMail := f.Retrieve()
  249. return toWhisperMessages(newMail)
  250. }
  251. return toWhisperMessages(nil)
  252. }
  253. // GetMessages retrieves all the floating messages that match a specific subscription filter.
  254. // It is likely to be called once per session, right after Subscribe call.
  255. func (api *PublicWhisperAPI) GetFloatingMessages(id string) []*WhisperMessage {
  256. all := api.whisper.Messages(id)
  257. return toWhisperMessages(all)
  258. }
  259. // toWhisperMessages converts a Whisper message to a RPC whisper message.
  260. func toWhisperMessages(messages []*ReceivedMessage) []*WhisperMessage {
  261. msgs := make([]*WhisperMessage, len(messages))
  262. for i, msg := range messages {
  263. msgs[i] = NewWhisperMessage(msg)
  264. }
  265. return msgs
  266. }
  267. // Post creates a whisper message and injects it into the network for distribution.
  268. func (api *PublicWhisperAPI) Post(args PostArgs) error {
  269. if api.whisper == nil {
  270. return whisperOfflineErr
  271. }
  272. var err error
  273. params := MessageParams{
  274. TTL: args.TTL,
  275. WorkTime: args.PowTime,
  276. PoW: args.PowTarget,
  277. Payload: args.Payload,
  278. Padding: args.Padding,
  279. }
  280. if len(args.Key) == 0 {
  281. return errors.New("post: key is missing")
  282. }
  283. if len(args.Sig) > 0 {
  284. params.Src, err = api.whisper.GetPrivateKey(args.Sig)
  285. if err != nil {
  286. return err
  287. }
  288. if params.Src == nil {
  289. return errors.New("post: empty identity")
  290. }
  291. }
  292. if len(args.Topic) == TopicLength {
  293. params.Topic = BytesToTopic(args.Topic)
  294. } else if len(args.Topic) != 0 {
  295. return errors.New(fmt.Sprintf("post: wrong topic size %d", len(args.Topic)))
  296. }
  297. if args.Type == "sym" {
  298. if err = ValidateKeyID(args.Key); err != nil {
  299. return err
  300. }
  301. params.KeySym, err = api.whisper.GetSymKey(args.Key)
  302. if err != nil {
  303. return err
  304. }
  305. if !validateSymmetricKey(params.KeySym) {
  306. return errors.New("post: key for symmetric encryption is invalid")
  307. }
  308. if len(params.Topic) == 0 {
  309. return errors.New("post: topic is missing for symmetric encryption")
  310. }
  311. } else if args.Type == "asym" {
  312. kb := common.FromHex(args.Key)
  313. if kb == nil {
  314. return errors.New("post: public key for asymmetric encryption is invalid")
  315. }
  316. params.Dst = crypto.ToECDSAPub(kb)
  317. if !ValidatePublicKey(params.Dst) {
  318. return errors.New("post: public key for asymmetric encryption is invalid")
  319. }
  320. } else {
  321. return errors.New("post: wrong type (sym/asym)")
  322. }
  323. // encrypt and send
  324. message, err := NewSentMessage(&params)
  325. if err != nil {
  326. return err
  327. }
  328. envelope, err := message.Wrap(&params)
  329. if err != nil {
  330. return err
  331. }
  332. if envelope.size() > api.whisper.maxMsgLength {
  333. return errors.New("post: message is too big")
  334. }
  335. if len(args.TargetPeer) != 0 {
  336. n, err := discover.ParseNode(args.TargetPeer)
  337. if err != nil {
  338. return errors.New("post: failed to parse enode of target peer: " + err.Error())
  339. }
  340. return api.whisper.SendP2PMessage(n.ID[:], envelope)
  341. } else if args.PowTarget < api.whisper.minPoW {
  342. return errors.New("post: target PoW is less than minimum PoW, the message can not be sent")
  343. }
  344. return api.whisper.Send(envelope)
  345. }
  346. type PostArgs struct {
  347. Type string `json:"type"` // "sym"/"asym" (symmetric or asymmetric)
  348. TTL uint32 `json:"ttl"` // time-to-live in seconds
  349. Sig string `json:"sig"` // id of the signing key
  350. Key string `json:"key"` // key id (in case of sym) or public key (in case of asym)
  351. Topic hexutil.Bytes `json:"topic"` // topic (4 bytes)
  352. Padding hexutil.Bytes `json:"padding"` // optional padding bytes
  353. Payload hexutil.Bytes `json:"payload"` // payload to be encrypted
  354. PowTime uint32 `json:"powTime"` // maximal time in seconds to be spent on PoW
  355. PowTarget float64 `json:"powTarget"` // minimal PoW required for this message
  356. TargetPeer string `json:"targetPeer"` // peer id (for p2p message only)
  357. }
  358. type WhisperFilterArgs struct {
  359. Symmetric bool // encryption type
  360. Key string // id of the key to be used for decryption
  361. Sig string // public key of the sender to be verified
  362. MinPoW float64 // minimal PoW requirement
  363. Topics [][]byte // list of topics (up to 4 bytes each) to match
  364. AllowP2P bool // indicates wheather direct p2p messages are allowed for this filter
  365. }
  366. // UnmarshalJSON implements the json.Unmarshaler interface, invoked to convert a
  367. // JSON message blob into a WhisperFilterArgs structure.
  368. func (args *WhisperFilterArgs) UnmarshalJSON(b []byte) (err error) {
  369. // Unmarshal the JSON message and sanity check
  370. var obj struct {
  371. Type string `json:"type"`
  372. Key string `json:"key"`
  373. Sig string `json:"sig"`
  374. MinPoW float64 `json:"minPoW"`
  375. Topics []interface{} `json:"topics"`
  376. AllowP2P bool `json:"allowP2P"`
  377. }
  378. if err := json.Unmarshal(b, &obj); err != nil {
  379. return err
  380. }
  381. switch obj.Type {
  382. case "sym":
  383. args.Symmetric = true
  384. case "asym":
  385. args.Symmetric = false
  386. default:
  387. return errors.New("wrong type (sym/asym)")
  388. }
  389. args.Key = obj.Key
  390. args.Sig = obj.Sig
  391. args.MinPoW = obj.MinPoW
  392. args.AllowP2P = obj.AllowP2P
  393. // Construct the topic array
  394. if obj.Topics != nil {
  395. topics := make([]string, len(obj.Topics))
  396. for i, field := range obj.Topics {
  397. switch value := field.(type) {
  398. case string:
  399. topics[i] = value
  400. case nil:
  401. return fmt.Errorf("topic[%d] is empty", i)
  402. default:
  403. return fmt.Errorf("topic[%d] is not a string", i)
  404. }
  405. }
  406. topicsDecoded := make([][]byte, len(topics))
  407. for j, s := range topics {
  408. x := common.FromHex(s)
  409. if x == nil || len(x) > TopicLength {
  410. return fmt.Errorf("topic[%d] is invalid", j)
  411. }
  412. topicsDecoded[j] = x
  413. }
  414. args.Topics = topicsDecoded
  415. }
  416. return nil
  417. }
  418. // WhisperMessage is the RPC representation of a whisper message.
  419. type WhisperMessage struct {
  420. Topic string `json:"topic"`
  421. Payload string `json:"payload"`
  422. Padding string `json:"padding"`
  423. Src string `json:"sig"`
  424. Dst string `json:"recipientPublicKey"`
  425. Timestamp uint32 `json:"timestamp"`
  426. TTL uint32 `json:"ttl"`
  427. PoW float64 `json:"pow"`
  428. Hash string `json:"hash"`
  429. }
  430. // NewWhisperMessage converts an internal message into an API version.
  431. func NewWhisperMessage(message *ReceivedMessage) *WhisperMessage {
  432. msg := WhisperMessage{
  433. Payload: common.ToHex(message.Payload),
  434. Padding: common.ToHex(message.Padding),
  435. Timestamp: message.Sent,
  436. TTL: message.TTL,
  437. PoW: message.PoW,
  438. Hash: common.ToHex(message.EnvelopeHash.Bytes()),
  439. }
  440. if len(message.Topic) == TopicLength {
  441. msg.Topic = common.ToHex(message.Topic[:])
  442. }
  443. if message.Dst != nil {
  444. b := crypto.FromECDSAPub(message.Dst)
  445. if b != nil {
  446. msg.Dst = common.ToHex(b)
  447. }
  448. }
  449. if isMessageSigned(message.Raw[0]) {
  450. b := crypto.FromECDSAPub(message.SigToPubKey())
  451. if b != nil {
  452. msg.Src = common.ToHex(b)
  453. }
  454. }
  455. return &msg
  456. }