api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 shhapi
  17. import (
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. mathrand "math/rand"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/hexutil"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "github.com/ethereum/go-ethereum/rpc"
  28. "github.com/ethereum/go-ethereum/whisper/whisperv5"
  29. )
  30. var whisperOffLineErr = errors.New("whisper is offline")
  31. // PublicWhisperAPI provides the whisper RPC service.
  32. type PublicWhisperAPI struct {
  33. whisper *whisperv5.Whisper
  34. }
  35. // NewPublicWhisperAPI create a new RPC whisper service.
  36. func NewPublicWhisperAPI() *PublicWhisperAPI {
  37. w := whisperv5.NewWhisper(nil)
  38. return &PublicWhisperAPI{whisper: w}
  39. }
  40. // APIs returns the RPC descriptors the Whisper implementation offers
  41. func APIs() []rpc.API {
  42. return []rpc.API{
  43. {
  44. Namespace: whisperv5.ProtocolName,
  45. Version: whisperv5.ProtocolVersionStr,
  46. Service: NewPublicWhisperAPI(),
  47. Public: true,
  48. },
  49. }
  50. }
  51. // Start starts the Whisper worker threads.
  52. func (api *PublicWhisperAPI) Start() error {
  53. if api.whisper == nil {
  54. return whisperOffLineErr
  55. }
  56. return api.whisper.Start(nil)
  57. }
  58. // Stop stops the Whisper worker threads.
  59. func (api *PublicWhisperAPI) Stop() error {
  60. if api.whisper == nil {
  61. return whisperOffLineErr
  62. }
  63. return api.whisper.Stop()
  64. }
  65. // Version returns the Whisper version this node offers.
  66. func (api *PublicWhisperAPI) Version() (hexutil.Uint, error) {
  67. if api.whisper == nil {
  68. return 0, whisperOffLineErr
  69. }
  70. return hexutil.Uint(api.whisper.Version()), nil
  71. }
  72. // MarkPeerTrusted marks specific peer trusted, which will allow it
  73. // to send historic (expired) messages.
  74. func (api *PublicWhisperAPI) MarkPeerTrusted(peerID hexutil.Bytes) error {
  75. if api.whisper == nil {
  76. return whisperOffLineErr
  77. }
  78. return api.whisper.MarkPeerTrusted(peerID)
  79. }
  80. // RequestHistoricMessages requests the peer to deliver the old (expired) messages.
  81. // data contains parameters (time frame, payment details, etc.), required
  82. // by the remote email-like server. Whisper is not aware about the data format,
  83. // it will just forward the raw data to the server.
  84. func (api *PublicWhisperAPI) RequestHistoricMessages(peerID hexutil.Bytes, data hexutil.Bytes) error {
  85. if api.whisper == nil {
  86. return whisperOffLineErr
  87. }
  88. return api.whisper.RequestHistoricMessages(peerID, data)
  89. }
  90. // HasIdentity checks if the whisper node is configured with the private key
  91. // of the specified public pair.
  92. func (api *PublicWhisperAPI) HasIdentity(identity string) (bool, error) {
  93. if api.whisper == nil {
  94. return false, whisperOffLineErr
  95. }
  96. return api.whisper.HasIdentity(identity), nil
  97. }
  98. // DeleteIdentity deletes the specifies key if it exists.
  99. func (api *PublicWhisperAPI) DeleteIdentity(identity string) error {
  100. if api.whisper == nil {
  101. return whisperOffLineErr
  102. }
  103. api.whisper.DeleteIdentity(identity)
  104. return nil
  105. }
  106. // NewIdentity generates a new cryptographic identity for the client, and injects
  107. // it into the known identities for message decryption.
  108. func (api *PublicWhisperAPI) NewIdentity() (string, error) {
  109. if api.whisper == nil {
  110. return "", whisperOffLineErr
  111. }
  112. identity := api.whisper.NewIdentity()
  113. return common.ToHex(crypto.FromECDSAPub(&identity.PublicKey)), nil
  114. }
  115. // GenerateSymKey generates a random symmetric key and stores it under
  116. // the 'name' id. Will be used in the future for session key exchange.
  117. func (api *PublicWhisperAPI) GenerateSymKey(name string) error {
  118. if api.whisper == nil {
  119. return whisperOffLineErr
  120. }
  121. return api.whisper.GenerateSymKey(name)
  122. }
  123. // AddSymKey stores the key under the 'name' id.
  124. func (api *PublicWhisperAPI) AddSymKey(name string, key []byte) error {
  125. if api.whisper == nil {
  126. return whisperOffLineErr
  127. }
  128. return api.whisper.AddSymKey(name, key)
  129. }
  130. // HasSymKey returns true if there is a key associated with the name string.
  131. // Otherwise returns false.
  132. func (api *PublicWhisperAPI) HasSymKey(name string) (bool, error) {
  133. if api.whisper == nil {
  134. return false, whisperOffLineErr
  135. }
  136. res := api.whisper.HasSymKey(name)
  137. return res, nil
  138. }
  139. // DeleteSymKey deletes the key associated with the name string if it exists.
  140. func (api *PublicWhisperAPI) DeleteSymKey(name string) error {
  141. if api.whisper == nil {
  142. return whisperOffLineErr
  143. }
  144. api.whisper.DeleteSymKey(name)
  145. return nil
  146. }
  147. // NewWhisperFilter creates and registers a new message filter to watch for inbound whisper messages.
  148. // Returns the ID of the newly created Filter.
  149. func (api *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (uint32, error) {
  150. if api.whisper == nil {
  151. return 0, whisperOffLineErr
  152. }
  153. filter := whisperv5.Filter{
  154. Src: crypto.ToECDSAPub(common.FromHex(args.From)),
  155. KeySym: api.whisper.GetSymKey(args.KeyName),
  156. PoW: args.PoW,
  157. Messages: make(map[common.Hash]*whisperv5.ReceivedMessage),
  158. AcceptP2P: args.AcceptP2P,
  159. }
  160. if len(filter.KeySym) > 0 {
  161. filter.SymKeyHash = crypto.Keccak256Hash(filter.KeySym)
  162. }
  163. for _, t := range args.Topics {
  164. filter.Topics = append(filter.Topics, t)
  165. }
  166. if len(args.Topics) == 0 {
  167. info := "NewFilter: at least one topic must be specified"
  168. glog.V(logger.Error).Infof(info)
  169. return 0, errors.New(info)
  170. }
  171. if len(args.KeyName) != 0 && len(filter.KeySym) == 0 {
  172. info := "NewFilter: key was not found by name: " + args.KeyName
  173. glog.V(logger.Error).Infof(info)
  174. return 0, errors.New(info)
  175. }
  176. if len(args.To) == 0 && len(filter.KeySym) == 0 {
  177. info := "NewFilter: filter must contain either symmetric or asymmetric key"
  178. glog.V(logger.Error).Infof(info)
  179. return 0, errors.New(info)
  180. }
  181. if len(args.To) != 0 && len(filter.KeySym) != 0 {
  182. info := "NewFilter: filter must not contain both symmetric and asymmetric key"
  183. glog.V(logger.Error).Infof(info)
  184. return 0, errors.New(info)
  185. }
  186. if len(args.To) > 0 {
  187. dst := crypto.ToECDSAPub(common.FromHex(args.To))
  188. if !whisperv5.ValidatePublicKey(dst) {
  189. info := "NewFilter: Invalid 'To' address"
  190. glog.V(logger.Error).Infof(info)
  191. return 0, errors.New(info)
  192. }
  193. filter.KeyAsym = api.whisper.GetIdentity(string(args.To))
  194. if filter.KeyAsym == nil {
  195. info := "NewFilter: non-existent identity provided"
  196. glog.V(logger.Error).Infof(info)
  197. return 0, errors.New(info)
  198. }
  199. }
  200. if len(args.From) > 0 {
  201. if !whisperv5.ValidatePublicKey(filter.Src) {
  202. info := "NewFilter: Invalid 'From' address"
  203. glog.V(logger.Error).Infof(info)
  204. return 0, errors.New(info)
  205. }
  206. }
  207. id := api.whisper.Watch(&filter)
  208. return id, nil
  209. }
  210. // UninstallFilter disables and removes an existing filter.
  211. func (api *PublicWhisperAPI) UninstallFilter(filterId uint32) {
  212. api.whisper.Unwatch(filterId)
  213. }
  214. // GetFilterChanges retrieves all the new messages matched by a filter since the last retrieval.
  215. func (api *PublicWhisperAPI) GetFilterChanges(filterId uint32) []WhisperMessage {
  216. f := api.whisper.GetFilter(filterId)
  217. if f != nil {
  218. newMail := f.Retrieve()
  219. return toWhisperMessages(newMail)
  220. }
  221. return toWhisperMessages(nil)
  222. }
  223. // GetMessages retrieves all the known messages that match a specific filter.
  224. func (api *PublicWhisperAPI) GetMessages(filterId uint32) []WhisperMessage {
  225. all := api.whisper.Messages(filterId)
  226. return toWhisperMessages(all)
  227. }
  228. // toWhisperMessages converts a Whisper message to a RPC whisper message.
  229. func toWhisperMessages(messages []*whisperv5.ReceivedMessage) []WhisperMessage {
  230. msgs := make([]WhisperMessage, len(messages))
  231. for i, msg := range messages {
  232. msgs[i] = NewWhisperMessage(msg)
  233. }
  234. return msgs
  235. }
  236. // Post creates a whisper message and injects it into the network for distribution.
  237. func (api *PublicWhisperAPI) Post(args PostArgs) error {
  238. if api.whisper == nil {
  239. return whisperOffLineErr
  240. }
  241. params := whisperv5.MessageParams{
  242. TTL: args.TTL,
  243. Dst: crypto.ToECDSAPub(common.FromHex(args.To)),
  244. KeySym: api.whisper.GetSymKey(args.KeyName),
  245. Topic: args.Topic,
  246. Payload: args.Payload,
  247. Padding: args.Padding,
  248. WorkTime: args.WorkTime,
  249. PoW: args.PoW,
  250. }
  251. if len(args.From) > 0 {
  252. pub := crypto.ToECDSAPub(common.FromHex(args.From))
  253. if !whisperv5.ValidatePublicKey(pub) {
  254. info := "Post: Invalid 'From' address"
  255. glog.V(logger.Error).Infof(info)
  256. return errors.New(info)
  257. }
  258. params.Src = api.whisper.GetIdentity(string(args.From))
  259. if params.Src == nil {
  260. info := "Post: non-existent identity provided"
  261. glog.V(logger.Error).Infof(info)
  262. return errors.New(info)
  263. }
  264. }
  265. filter := api.whisper.GetFilter(args.FilterID)
  266. if filter == nil && args.FilterID > 0 {
  267. info := fmt.Sprintf("Post: wrong filter id %d", args.FilterID)
  268. glog.V(logger.Error).Infof(info)
  269. return errors.New(info)
  270. }
  271. if filter != nil {
  272. // get the missing fields from the filter
  273. if params.KeySym == nil && filter.KeySym != nil {
  274. params.KeySym = filter.KeySym
  275. }
  276. if params.Src == nil && filter.Src != nil {
  277. params.Src = filter.KeyAsym
  278. }
  279. if (params.Topic == whisperv5.TopicType{}) {
  280. sz := len(filter.Topics)
  281. if sz < 1 {
  282. info := fmt.Sprintf("Post: no topics in filter # %d", args.FilterID)
  283. glog.V(logger.Error).Infof(info)
  284. return errors.New(info)
  285. } else if sz == 1 {
  286. params.Topic = filter.Topics[0]
  287. } else {
  288. // choose randomly
  289. rnd := mathrand.Intn(sz)
  290. params.Topic = filter.Topics[rnd]
  291. }
  292. }
  293. }
  294. // validate
  295. if len(args.KeyName) != 0 && len(params.KeySym) == 0 {
  296. info := "Post: key was not found by name: " + args.KeyName
  297. glog.V(logger.Error).Infof(info)
  298. return errors.New(info)
  299. }
  300. if len(args.To) == 0 && len(params.KeySym) == 0 {
  301. info := "Post: message must be encrypted either symmetrically or asymmetrically"
  302. glog.V(logger.Error).Infof(info)
  303. return errors.New(info)
  304. }
  305. if len(args.To) != 0 && len(params.KeySym) != 0 {
  306. info := "Post: ambigous encryption method requested"
  307. glog.V(logger.Error).Infof(info)
  308. return errors.New(info)
  309. }
  310. if len(args.To) > 0 {
  311. if !whisperv5.ValidatePublicKey(params.Dst) {
  312. info := "Post: Invalid 'To' address"
  313. glog.V(logger.Error).Infof(info)
  314. return errors.New(info)
  315. }
  316. }
  317. // encrypt and send
  318. message := whisperv5.NewSentMessage(&params)
  319. envelope, err := message.Wrap(&params)
  320. if err != nil {
  321. glog.V(logger.Error).Infof(err.Error())
  322. return err
  323. }
  324. if len(envelope.Data) > whisperv5.MaxMessageLength {
  325. info := "Post: message is too big"
  326. glog.V(logger.Error).Infof(info)
  327. return errors.New(info)
  328. }
  329. if (envelope.Topic == whisperv5.TopicType{} && envelope.IsSymmetric()) {
  330. info := "Post: topic is missing for symmetric encryption"
  331. glog.V(logger.Error).Infof(info)
  332. return errors.New(info)
  333. }
  334. if args.PeerID != nil {
  335. return api.whisper.SendP2PMessage(args.PeerID, envelope)
  336. }
  337. return api.whisper.Send(envelope)
  338. }
  339. type PostArgs struct {
  340. TTL uint32 `json:"ttl"`
  341. From string `json:"from"`
  342. To string `json:"to"`
  343. KeyName string `json:"keyname"`
  344. Topic whisperv5.TopicType `json:"topic"`
  345. Padding hexutil.Bytes `json:"padding"`
  346. Payload hexutil.Bytes `json:"payload"`
  347. WorkTime uint32 `json:"worktime"`
  348. PoW float64 `json:"pow"`
  349. FilterID uint32 `json:"filterID"`
  350. PeerID hexutil.Bytes `json:"peerID"`
  351. }
  352. type WhisperFilterArgs struct {
  353. To string
  354. From string
  355. KeyName string
  356. PoW float64
  357. Topics []whisperv5.TopicType
  358. AcceptP2P bool
  359. }
  360. // UnmarshalJSON implements the json.Unmarshaler interface, invoked to convert a
  361. // JSON message blob into a WhisperFilterArgs structure.
  362. func (args *WhisperFilterArgs) UnmarshalJSON(b []byte) (err error) {
  363. // Unmarshal the JSON message and sanity check
  364. var obj struct {
  365. To string `json:"to"`
  366. From string `json:"from"`
  367. KeyName string `json:"keyname"`
  368. PoW float64 `json:"pow"`
  369. Topics []interface{} `json:"topics"`
  370. AcceptP2P bool `json:"acceptP2P"`
  371. }
  372. if err := json.Unmarshal(b, &obj); err != nil {
  373. return err
  374. }
  375. args.To = obj.To
  376. args.From = obj.From
  377. args.KeyName = obj.KeyName
  378. args.PoW = obj.PoW
  379. args.AcceptP2P = obj.AcceptP2P
  380. // Construct the topic array
  381. if obj.Topics != nil {
  382. topics := make([]string, len(obj.Topics))
  383. for i, field := range obj.Topics {
  384. switch value := field.(type) {
  385. case string:
  386. topics[i] = value
  387. case nil:
  388. return fmt.Errorf("topic[%d] is empty", i)
  389. default:
  390. return fmt.Errorf("topic[%d] is not a string", i)
  391. }
  392. }
  393. topicsDecoded := make([]whisperv5.TopicType, len(topics))
  394. for j, s := range topics {
  395. x := common.FromHex(s)
  396. if x == nil || len(x) != whisperv5.TopicLength {
  397. return fmt.Errorf("topic[%d] is invalid", j)
  398. }
  399. topicsDecoded[j] = whisperv5.BytesToTopic(x)
  400. }
  401. args.Topics = topicsDecoded
  402. }
  403. return nil
  404. }
  405. // WhisperMessage is the RPC representation of a whisper message.
  406. type WhisperMessage struct {
  407. Payload string `json:"payload"`
  408. Padding string `json:"padding"`
  409. From string `json:"from"`
  410. To string `json:"to"`
  411. Sent uint32 `json:"sent"`
  412. TTL uint32 `json:"ttl"`
  413. PoW float64 `json:"pow"`
  414. Hash string `json:"hash"`
  415. }
  416. // NewWhisperMessage converts an internal message into an API version.
  417. func NewWhisperMessage(message *whisperv5.ReceivedMessage) WhisperMessage {
  418. return WhisperMessage{
  419. Payload: common.ToHex(message.Payload),
  420. Padding: common.ToHex(message.Padding),
  421. From: common.ToHex(crypto.FromECDSAPub(message.SigToPubKey())),
  422. To: common.ToHex(crypto.FromECDSAPub(message.Dst)),
  423. Sent: message.Sent,
  424. TTL: message.TTL,
  425. PoW: message.PoW,
  426. Hash: common.ToHex(message.EnvelopeHash.Bytes()),
  427. }
  428. }