api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright 2015 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 whisperv2
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/hexutil"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. )
  26. // PublicWhisperAPI provides the whisper RPC service.
  27. type PublicWhisperAPI struct {
  28. w *Whisper
  29. messagesMu sync.RWMutex
  30. messages map[hexutil.Uint]*whisperFilter
  31. }
  32. type whisperOfflineError struct{}
  33. func (e *whisperOfflineError) Error() string {
  34. return "whisper is offline"
  35. }
  36. // whisperOffLineErr is returned when the node doesn't offer the shh service.
  37. var whisperOffLineErr = new(whisperOfflineError)
  38. // NewPublicWhisperAPI create a new RPC whisper service.
  39. func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI {
  40. return &PublicWhisperAPI{w: w, messages: make(map[hexutil.Uint]*whisperFilter)}
  41. }
  42. // Version returns the Whisper version this node offers.
  43. func (s *PublicWhisperAPI) Version() (hexutil.Uint, error) {
  44. if s.w == nil {
  45. return 0, whisperOffLineErr
  46. }
  47. return hexutil.Uint(s.w.Version()), nil
  48. }
  49. // HasIdentity checks if the the whisper node is configured with the private key
  50. // of the specified public pair.
  51. func (s *PublicWhisperAPI) HasIdentity(identity string) (bool, error) {
  52. if s.w == nil {
  53. return false, whisperOffLineErr
  54. }
  55. return s.w.HasIdentity(crypto.ToECDSAPub(common.FromHex(identity))), nil
  56. }
  57. // NewIdentity generates a new cryptographic identity for the client, and injects
  58. // it into the known identities for message decryption.
  59. func (s *PublicWhisperAPI) NewIdentity() (string, error) {
  60. if s.w == nil {
  61. return "", whisperOffLineErr
  62. }
  63. identity := s.w.NewIdentity()
  64. return common.ToHex(crypto.FromECDSAPub(&identity.PublicKey)), nil
  65. }
  66. type NewFilterArgs struct {
  67. To string
  68. From string
  69. Topics [][][]byte
  70. }
  71. // NewWhisperFilter creates and registers a new message filter to watch for inbound whisper messages.
  72. func (s *PublicWhisperAPI) NewFilter(args NewFilterArgs) (hexutil.Uint, error) {
  73. if s.w == nil {
  74. return 0, whisperOffLineErr
  75. }
  76. var id hexutil.Uint
  77. filter := Filter{
  78. To: crypto.ToECDSAPub(common.FromHex(args.To)),
  79. From: crypto.ToECDSAPub(common.FromHex(args.From)),
  80. Topics: NewFilterTopics(args.Topics...),
  81. Fn: func(message *Message) {
  82. wmsg := NewWhisperMessage(message)
  83. s.messagesMu.RLock() // Only read lock to the filter pool
  84. defer s.messagesMu.RUnlock()
  85. if s.messages[id] != nil {
  86. s.messages[id].insert(wmsg)
  87. }
  88. },
  89. }
  90. id = hexutil.Uint(s.w.Watch(filter))
  91. s.messagesMu.Lock()
  92. s.messages[id] = newWhisperFilter(id, s.w)
  93. s.messagesMu.Unlock()
  94. return id, nil
  95. }
  96. // GetFilterChanges retrieves all the new messages matched by a filter since the last retrieval.
  97. func (s *PublicWhisperAPI) GetFilterChanges(filterId hexutil.Uint) []WhisperMessage {
  98. s.messagesMu.RLock()
  99. defer s.messagesMu.RUnlock()
  100. if s.messages[filterId] != nil {
  101. if changes := s.messages[filterId].retrieve(); changes != nil {
  102. return changes
  103. }
  104. }
  105. return returnWhisperMessages(nil)
  106. }
  107. // UninstallFilter disables and removes an existing filter.
  108. func (s *PublicWhisperAPI) UninstallFilter(filterId hexutil.Uint) bool {
  109. s.messagesMu.Lock()
  110. defer s.messagesMu.Unlock()
  111. if _, ok := s.messages[filterId]; ok {
  112. delete(s.messages, filterId)
  113. return true
  114. }
  115. return false
  116. }
  117. // GetMessages retrieves all the known messages that match a specific filter.
  118. func (s *PublicWhisperAPI) GetMessages(filterId hexutil.Uint) []WhisperMessage {
  119. // Retrieve all the cached messages matching a specific, existing filter
  120. s.messagesMu.RLock()
  121. defer s.messagesMu.RUnlock()
  122. var messages []*Message
  123. if s.messages[filterId] != nil {
  124. messages = s.messages[filterId].messages()
  125. }
  126. return returnWhisperMessages(messages)
  127. }
  128. // returnWhisperMessages converts aNhisper message to a RPC whisper message.
  129. func returnWhisperMessages(messages []*Message) []WhisperMessage {
  130. msgs := make([]WhisperMessage, len(messages))
  131. for i, msg := range messages {
  132. msgs[i] = NewWhisperMessage(msg)
  133. }
  134. return msgs
  135. }
  136. type PostArgs struct {
  137. From string `json:"from"`
  138. To string `json:"to"`
  139. Topics [][]byte `json:"topics"`
  140. Payload string `json:"payload"`
  141. Priority int64 `json:"priority"`
  142. TTL int64 `json:"ttl"`
  143. }
  144. // Post injects a message into the whisper network for distribution.
  145. func (s *PublicWhisperAPI) Post(args PostArgs) (bool, error) {
  146. if s.w == nil {
  147. return false, whisperOffLineErr
  148. }
  149. // construct whisper message with transmission options
  150. message := NewMessage(common.FromHex(args.Payload))
  151. options := Options{
  152. To: crypto.ToECDSAPub(common.FromHex(args.To)),
  153. TTL: time.Duration(args.TTL) * time.Second,
  154. Topics: NewTopics(args.Topics...),
  155. }
  156. // set sender identity
  157. if len(args.From) > 0 {
  158. if key := s.w.GetIdentity(crypto.ToECDSAPub(common.FromHex(args.From))); key != nil {
  159. options.From = key
  160. } else {
  161. return false, fmt.Errorf("unknown identity to send from: %s", args.From)
  162. }
  163. }
  164. // Wrap and send the message
  165. pow := time.Duration(args.Priority) * time.Millisecond
  166. envelope, err := message.Wrap(pow, options)
  167. if err != nil {
  168. return false, err
  169. }
  170. return true, s.w.Send(envelope)
  171. }
  172. // WhisperMessage is the RPC representation of a whisper message.
  173. type WhisperMessage struct {
  174. ref *Message
  175. Payload string `json:"payload"`
  176. To string `json:"to"`
  177. From string `json:"from"`
  178. Sent int64 `json:"sent"`
  179. TTL int64 `json:"ttl"`
  180. Hash string `json:"hash"`
  181. }
  182. func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
  183. var obj struct {
  184. From string `json:"from"`
  185. To string `json:"to"`
  186. Topics []string `json:"topics"`
  187. Payload string `json:"payload"`
  188. Priority hexutil.Uint64 `json:"priority"`
  189. TTL hexutil.Uint64 `json:"ttl"`
  190. }
  191. if err := json.Unmarshal(data, &obj); err != nil {
  192. return err
  193. }
  194. args.From = obj.From
  195. args.To = obj.To
  196. args.Payload = obj.Payload
  197. args.Priority = int64(obj.Priority) // TODO(gluk256): handle overflow
  198. args.TTL = int64(obj.TTL) // ... here too ...
  199. // decode topic strings
  200. args.Topics = make([][]byte, len(obj.Topics))
  201. for i, topic := range obj.Topics {
  202. args.Topics[i] = common.FromHex(topic)
  203. }
  204. return nil
  205. }
  206. // UnmarshalJSON implements the json.Unmarshaler interface, invoked to convert a
  207. // JSON message blob into a WhisperFilterArgs structure.
  208. func (args *NewFilterArgs) UnmarshalJSON(b []byte) (err error) {
  209. // Unmarshal the JSON message and sanity check
  210. var obj struct {
  211. To interface{} `json:"to"`
  212. From interface{} `json:"from"`
  213. Topics interface{} `json:"topics"`
  214. }
  215. if err := json.Unmarshal(b, &obj); err != nil {
  216. return err
  217. }
  218. // Retrieve the simple data contents of the filter arguments
  219. if obj.To == nil {
  220. args.To = ""
  221. } else {
  222. argstr, ok := obj.To.(string)
  223. if !ok {
  224. return fmt.Errorf("to is not a string")
  225. }
  226. args.To = argstr
  227. }
  228. if obj.From == nil {
  229. args.From = ""
  230. } else {
  231. argstr, ok := obj.From.(string)
  232. if !ok {
  233. return fmt.Errorf("from is not a string")
  234. }
  235. args.From = argstr
  236. }
  237. // Construct the nested topic array
  238. if obj.Topics != nil {
  239. // Make sure we have an actual topic array
  240. list, ok := obj.Topics.([]interface{})
  241. if !ok {
  242. return fmt.Errorf("topics is not an array")
  243. }
  244. // Iterate over each topic and handle nil, string or array
  245. topics := make([][]string, len(list))
  246. for idx, field := range list {
  247. switch value := field.(type) {
  248. case nil:
  249. topics[idx] = []string{}
  250. case string:
  251. topics[idx] = []string{value}
  252. case []interface{}:
  253. topics[idx] = make([]string, len(value))
  254. for i, nested := range value {
  255. switch value := nested.(type) {
  256. case nil:
  257. topics[idx][i] = ""
  258. case string:
  259. topics[idx][i] = value
  260. default:
  261. return fmt.Errorf("topic[%d][%d] is not a string", idx, i)
  262. }
  263. }
  264. default:
  265. return fmt.Errorf("topic[%d] not a string or array", idx)
  266. }
  267. }
  268. topicsDecoded := make([][][]byte, len(topics))
  269. for i, condition := range topics {
  270. topicsDecoded[i] = make([][]byte, len(condition))
  271. for j, topic := range condition {
  272. topicsDecoded[i][j] = common.FromHex(topic)
  273. }
  274. }
  275. args.Topics = topicsDecoded
  276. }
  277. return nil
  278. }
  279. // whisperFilter is the message cache matching a specific filter, accumulating
  280. // inbound messages until the are requested by the client.
  281. type whisperFilter struct {
  282. id hexutil.Uint // Filter identifier for old message retrieval
  283. ref *Whisper // Whisper reference for old message retrieval
  284. cache []WhisperMessage // Cache of messages not yet polled
  285. skip map[common.Hash]struct{} // List of retrieved messages to avoid duplication
  286. update time.Time // Time of the last message query
  287. lock sync.RWMutex // Lock protecting the filter internals
  288. }
  289. // messages retrieves all the cached messages from the entire pool matching the
  290. // filter, resetting the filter's change buffer.
  291. func (w *whisperFilter) messages() []*Message {
  292. w.lock.Lock()
  293. defer w.lock.Unlock()
  294. w.cache = nil
  295. w.update = time.Now()
  296. w.skip = make(map[common.Hash]struct{})
  297. messages := w.ref.Messages(int(w.id))
  298. for _, message := range messages {
  299. w.skip[message.Hash] = struct{}{}
  300. }
  301. return messages
  302. }
  303. // insert injects a new batch of messages into the filter cache.
  304. func (w *whisperFilter) insert(messages ...WhisperMessage) {
  305. w.lock.Lock()
  306. defer w.lock.Unlock()
  307. for _, message := range messages {
  308. if _, ok := w.skip[message.ref.Hash]; !ok {
  309. w.cache = append(w.cache, messages...)
  310. }
  311. }
  312. }
  313. // retrieve fetches all the cached messages from the filter.
  314. func (w *whisperFilter) retrieve() (messages []WhisperMessage) {
  315. w.lock.Lock()
  316. defer w.lock.Unlock()
  317. messages, w.cache = w.cache, nil
  318. w.update = time.Now()
  319. return
  320. }
  321. // activity returns the last time instance when client requests were executed on
  322. // the filter.
  323. func (w *whisperFilter) activity() time.Time {
  324. w.lock.RLock()
  325. defer w.lock.RUnlock()
  326. return w.update
  327. }
  328. // newWhisperFilter creates a new serialized, poll based whisper topic filter.
  329. func newWhisperFilter(id hexutil.Uint, ref *Whisper) *whisperFilter {
  330. return &whisperFilter{
  331. id: id,
  332. ref: ref,
  333. update: time.Now(),
  334. skip: make(map[common.Hash]struct{}),
  335. }
  336. }
  337. // NewWhisperMessage converts an internal message into an API version.
  338. func NewWhisperMessage(message *Message) WhisperMessage {
  339. return WhisperMessage{
  340. ref: message,
  341. Payload: common.ToHex(message.Payload),
  342. From: common.ToHex(crypto.FromECDSAPub(message.Recover())),
  343. To: common.ToHex(crypto.FromECDSAPub(message.To)),
  344. Sent: message.Sent.Unix(),
  345. TTL: int64(message.TTL / time.Second),
  346. Hash: common.ToHex(message.Hash.Bytes()),
  347. }
  348. }