api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. package rpc
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math/big"
  6. "sync"
  7. "github.com/ethereum/go-ethereum/common"
  8. "github.com/ethereum/go-ethereum/crypto"
  9. "github.com/ethereum/go-ethereum/logger"
  10. "github.com/ethereum/go-ethereum/logger/glog"
  11. "github.com/ethereum/go-ethereum/xeth"
  12. )
  13. type EthereumApi struct {
  14. eth *xeth.XEth
  15. xethMu sync.RWMutex
  16. }
  17. func NewEthereumApi(xeth *xeth.XEth) *EthereumApi {
  18. api := &EthereumApi{
  19. eth: xeth,
  20. }
  21. return api
  22. }
  23. func (api *EthereumApi) xeth() *xeth.XEth {
  24. api.xethMu.RLock()
  25. defer api.xethMu.RUnlock()
  26. return api.eth
  27. }
  28. func (api *EthereumApi) xethAtStateNum(num int64) *xeth.XEth {
  29. return api.xeth().AtStateNum(num)
  30. }
  31. func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error {
  32. // Spec at https://github.com/ethereum/wiki/wiki/JSON-RPC
  33. glog.V(logger.Debug).Infof("%s %s", req.Method, req.Params)
  34. switch req.Method {
  35. case "web3_sha3":
  36. args := new(Sha3Args)
  37. if err := json.Unmarshal(req.Params, &args); err != nil {
  38. return err
  39. }
  40. *reply = common.ToHex(crypto.Sha3(common.FromHex(args.Data)))
  41. case "web3_clientVersion":
  42. *reply = api.xeth().ClientVersion()
  43. case "net_version":
  44. *reply = api.xeth().NetworkVersion()
  45. case "net_listening":
  46. *reply = api.xeth().IsListening()
  47. case "net_peerCount":
  48. *reply = newHexNum(api.xeth().PeerCount())
  49. case "eth_protocolVersion":
  50. *reply = api.xeth().EthVersion()
  51. case "eth_coinbase":
  52. *reply = newHexData(api.xeth().Coinbase())
  53. case "eth_mining":
  54. *reply = api.xeth().IsMining()
  55. case "eth_gasPrice":
  56. v := xeth.DefaultGasPrice()
  57. *reply = newHexNum(v.Bytes())
  58. case "eth_accounts":
  59. *reply = api.xeth().Accounts()
  60. case "eth_blockNumber":
  61. v := api.xeth().CurrentBlock().Number()
  62. *reply = newHexNum(v.Bytes())
  63. case "eth_getBalance":
  64. args := new(GetBalanceArgs)
  65. if err := json.Unmarshal(req.Params, &args); err != nil {
  66. return err
  67. }
  68. *reply = api.xethAtStateNum(args.BlockNumber).BalanceAt(args.Address)
  69. //v := api.xethAtStateNum(args.BlockNumber).State().SafeGet(args.Address).Balance()
  70. //*reply = common.ToHex(v.Bytes())
  71. case "eth_getStorage", "eth_storageAt":
  72. args := new(GetStorageArgs)
  73. if err := json.Unmarshal(req.Params, &args); err != nil {
  74. return err
  75. }
  76. *reply = api.xethAtStateNum(args.BlockNumber).State().SafeGet(args.Address).Storage()
  77. case "eth_getStorageAt":
  78. args := new(GetStorageAtArgs)
  79. if err := json.Unmarshal(req.Params, &args); err != nil {
  80. return err
  81. }
  82. *reply = api.xethAtStateNum(args.BlockNumber).StorageAt(args.Address, args.Key)
  83. case "eth_getTransactionCount":
  84. args := new(GetTxCountArgs)
  85. if err := json.Unmarshal(req.Params, &args); err != nil {
  86. return err
  87. }
  88. count := api.xethAtStateNum(args.BlockNumber).TxCountAt(args.Address)
  89. *reply = newHexNum(big.NewInt(int64(count)).Bytes())
  90. case "eth_getBlockTransactionCountByHash":
  91. args := new(HashArgs)
  92. if err := json.Unmarshal(req.Params, &args); err != nil {
  93. return err
  94. }
  95. block := NewBlockRes(api.xeth().EthBlockByHash(args.Hash), false)
  96. if block == nil {
  97. *reply = nil
  98. } else {
  99. *reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
  100. }
  101. case "eth_getBlockTransactionCountByNumber":
  102. args := new(BlockNumArg)
  103. if err := json.Unmarshal(req.Params, &args); err != nil {
  104. return err
  105. }
  106. block := NewBlockRes(api.xeth().EthBlockByNumber(args.BlockNumber), false)
  107. if block == nil {
  108. *reply = nil
  109. break
  110. }
  111. *reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
  112. case "eth_getUncleCountByBlockHash":
  113. args := new(HashArgs)
  114. if err := json.Unmarshal(req.Params, &args); err != nil {
  115. return err
  116. }
  117. block := api.xeth().EthBlockByHash(args.Hash)
  118. br := NewBlockRes(block, false)
  119. if br == nil {
  120. *reply = nil
  121. break
  122. }
  123. *reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
  124. case "eth_getUncleCountByBlockNumber":
  125. args := new(BlockNumArg)
  126. if err := json.Unmarshal(req.Params, &args); err != nil {
  127. return err
  128. }
  129. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  130. br := NewBlockRes(block, false)
  131. if br == nil {
  132. *reply = nil
  133. break
  134. }
  135. *reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
  136. case "eth_getData", "eth_getCode":
  137. args := new(GetDataArgs)
  138. if err := json.Unmarshal(req.Params, &args); err != nil {
  139. return err
  140. }
  141. v := api.xethAtStateNum(args.BlockNumber).CodeAtBytes(args.Address)
  142. *reply = newHexData(v)
  143. case "eth_sendTransaction", "eth_transact":
  144. args := new(NewTxArgs)
  145. if err := json.Unmarshal(req.Params, &args); err != nil {
  146. return err
  147. }
  148. // call ConfirmTransaction first
  149. tx, _ := json.Marshal(req)
  150. if !api.xeth().ConfirmTransaction(string(tx)) {
  151. return fmt.Errorf("Transaction not confirmed")
  152. }
  153. // nonce may be nil ("guess" mode)
  154. var nonce string
  155. if args.Nonce != nil {
  156. nonce = args.Nonce.String()
  157. }
  158. v, err := api.xeth().Transact(args.From, args.To, nonce, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
  159. if err != nil {
  160. return err
  161. }
  162. *reply = v
  163. case "eth_call":
  164. args := new(CallArgs)
  165. if err := json.Unmarshal(req.Params, &args); err != nil {
  166. return err
  167. }
  168. v, err := api.xethAtStateNum(args.BlockNumber).Call(args.From, args.To, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
  169. if err != nil {
  170. return err
  171. }
  172. // TODO unwrap the parent method's ToHex call
  173. if v == "0x0" {
  174. *reply = newHexData([]byte{})
  175. } else {
  176. *reply = newHexData(common.FromHex(v))
  177. }
  178. case "eth_flush":
  179. return NewNotImplementedError(req.Method)
  180. case "eth_getBlockByHash":
  181. args := new(GetBlockByHashArgs)
  182. if err := json.Unmarshal(req.Params, &args); err != nil {
  183. return err
  184. }
  185. block := api.xeth().EthBlockByHash(args.BlockHash)
  186. br := NewBlockRes(block, args.IncludeTxs)
  187. *reply = br
  188. case "eth_getBlockByNumber":
  189. args := new(GetBlockByNumberArgs)
  190. if err := json.Unmarshal(req.Params, &args); err != nil {
  191. return err
  192. }
  193. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  194. br := NewBlockRes(block, args.IncludeTxs)
  195. *reply = br
  196. case "eth_getTransactionByHash":
  197. args := new(HashArgs)
  198. if err := json.Unmarshal(req.Params, &args); err != nil {
  199. return err
  200. }
  201. tx, bhash, bnum, txi := api.xeth().EthTransactionByHash(args.Hash)
  202. if tx != nil {
  203. v := NewTransactionRes(tx)
  204. v.BlockHash = newHexData(bhash)
  205. v.BlockNumber = newHexNum(bnum)
  206. v.TxIndex = newHexNum(txi)
  207. *reply = v
  208. }
  209. case "eth_getTransactionByBlockHashAndIndex":
  210. args := new(HashIndexArgs)
  211. if err := json.Unmarshal(req.Params, &args); err != nil {
  212. return err
  213. }
  214. block := api.xeth().EthBlockByHash(args.Hash)
  215. br := NewBlockRes(block, true)
  216. if br == nil {
  217. *reply = nil
  218. break
  219. }
  220. if args.Index >= int64(len(br.Transactions)) || args.Index < 0 {
  221. // return NewValidationError("Index", "does not exist")
  222. *reply = nil
  223. } else {
  224. *reply = br.Transactions[args.Index]
  225. }
  226. case "eth_getTransactionByBlockNumberAndIndex":
  227. args := new(BlockNumIndexArgs)
  228. if err := json.Unmarshal(req.Params, &args); err != nil {
  229. return err
  230. }
  231. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  232. v := NewBlockRes(block, true)
  233. if v == nil {
  234. *reply = nil
  235. break
  236. }
  237. if args.Index >= int64(len(v.Transactions)) || args.Index < 0 {
  238. // return NewValidationError("Index", "does not exist")
  239. *reply = nil
  240. } else {
  241. *reply = v.Transactions[args.Index]
  242. }
  243. case "eth_getUncleByBlockHashAndIndex":
  244. args := new(HashIndexArgs)
  245. if err := json.Unmarshal(req.Params, &args); err != nil {
  246. return err
  247. }
  248. br := NewBlockRes(api.xeth().EthBlockByHash(args.Hash), false)
  249. if br == nil {
  250. *reply = nil
  251. return nil
  252. }
  253. if args.Index >= int64(len(br.Uncles)) || args.Index < 0 {
  254. // return NewValidationError("Index", "does not exist")
  255. *reply = nil
  256. } else {
  257. *reply = br.Uncles[args.Index]
  258. }
  259. case "eth_getUncleByBlockNumberAndIndex":
  260. args := new(BlockNumIndexArgs)
  261. if err := json.Unmarshal(req.Params, &args); err != nil {
  262. return err
  263. }
  264. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  265. v := NewBlockRes(block, true)
  266. if v == nil {
  267. *reply = nil
  268. return nil
  269. }
  270. if args.Index >= int64(len(v.Uncles)) || args.Index < 0 {
  271. // return NewValidationError("Index", "does not exist")
  272. *reply = nil
  273. } else {
  274. *reply = v.Uncles[args.Index]
  275. }
  276. case "eth_getCompilers":
  277. c := []string{""}
  278. *reply = c
  279. case "eth_compileSolidity", "eth_compileLLL", "eth_compileSerpent":
  280. return NewNotImplementedError(req.Method)
  281. case "eth_newFilter":
  282. args := new(BlockFilterArgs)
  283. if err := json.Unmarshal(req.Params, &args); err != nil {
  284. return err
  285. }
  286. id := api.xeth().RegisterFilter(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics)
  287. *reply = newHexNum(big.NewInt(int64(id)).Bytes())
  288. case "eth_newBlockFilter":
  289. args := new(FilterStringArgs)
  290. if err := json.Unmarshal(req.Params, &args); err != nil {
  291. return err
  292. }
  293. *reply = newHexNum(api.xeth().NewFilterString(args.Word))
  294. case "eth_uninstallFilter":
  295. args := new(FilterIdArgs)
  296. if err := json.Unmarshal(req.Params, &args); err != nil {
  297. return err
  298. }
  299. *reply = api.xeth().UninstallFilter(args.Id)
  300. case "eth_getFilterChanges":
  301. args := new(FilterIdArgs)
  302. if err := json.Unmarshal(req.Params, &args); err != nil {
  303. return err
  304. }
  305. *reply = NewLogsRes(api.xeth().FilterChanged(args.Id))
  306. case "eth_getFilterLogs":
  307. args := new(FilterIdArgs)
  308. if err := json.Unmarshal(req.Params, &args); err != nil {
  309. return err
  310. }
  311. *reply = NewLogsRes(api.xeth().Logs(args.Id))
  312. case "eth_getLogs":
  313. args := new(BlockFilterArgs)
  314. if err := json.Unmarshal(req.Params, &args); err != nil {
  315. return err
  316. }
  317. *reply = NewLogsRes(api.xeth().AllLogs(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics))
  318. case "eth_getWork":
  319. api.xeth().SetMining(true)
  320. *reply = api.xeth().RemoteMining().GetWork()
  321. case "eth_submitWork":
  322. args := new(SubmitWorkArgs)
  323. if err := json.Unmarshal(req.Params, &args); err != nil {
  324. return err
  325. }
  326. *reply = api.xeth().RemoteMining().SubmitWork(args.Nonce, common.HexToHash(args.Digest), common.HexToHash(args.Header))
  327. case "db_putString":
  328. args := new(DbArgs)
  329. if err := json.Unmarshal(req.Params, &args); err != nil {
  330. return err
  331. }
  332. if err := args.requirements(); err != nil {
  333. return err
  334. }
  335. api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
  336. *reply = true
  337. case "db_getString":
  338. args := new(DbArgs)
  339. if err := json.Unmarshal(req.Params, &args); err != nil {
  340. return err
  341. }
  342. if err := args.requirements(); err != nil {
  343. return err
  344. }
  345. res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
  346. *reply = string(res)
  347. case "db_putHex":
  348. args := new(DbHexArgs)
  349. if err := json.Unmarshal(req.Params, &args); err != nil {
  350. return err
  351. }
  352. if err := args.requirements(); err != nil {
  353. return err
  354. }
  355. api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
  356. *reply = true
  357. case "db_getHex":
  358. args := new(DbHexArgs)
  359. if err := json.Unmarshal(req.Params, &args); err != nil {
  360. return err
  361. }
  362. if err := args.requirements(); err != nil {
  363. return err
  364. }
  365. res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
  366. *reply = newHexData(res)
  367. case "shh_version":
  368. // Retrieves the currently running whisper protocol version
  369. *reply = api.xeth().WhisperVersion()
  370. case "shh_post":
  371. // Injects a new message into the whisper network
  372. args := new(WhisperMessageArgs)
  373. if err := json.Unmarshal(req.Params, &args); err != nil {
  374. return err
  375. }
  376. err := api.xeth().Whisper().Post(args.Payload, args.To, args.From, args.Topics, args.Priority, args.Ttl)
  377. if err != nil {
  378. return err
  379. }
  380. *reply = true
  381. case "shh_newIdentity":
  382. // Creates a new whisper identity to use for sending/receiving messages
  383. *reply = api.xeth().Whisper().NewIdentity()
  384. case "shh_hasIdentity":
  385. // Checks if an identity if owned or not
  386. args := new(WhisperIdentityArgs)
  387. if err := json.Unmarshal(req.Params, &args); err != nil {
  388. return err
  389. }
  390. *reply = api.xeth().Whisper().HasIdentity(args.Identity)
  391. case "shh_newFilter":
  392. // Create a new filter to watch and match messages with
  393. args := new(WhisperFilterArgs)
  394. if err := json.Unmarshal(req.Params, &args); err != nil {
  395. return err
  396. }
  397. id := api.xeth().NewWhisperFilter(args.To, args.From, args.Topics)
  398. *reply = newHexNum(big.NewInt(int64(id)).Bytes())
  399. case "shh_uninstallFilter":
  400. // Remove an existing filter watching messages
  401. args := new(FilterIdArgs)
  402. if err := json.Unmarshal(req.Params, &args); err != nil {
  403. return err
  404. }
  405. *reply = api.xeth().UninstallWhisperFilter(args.Id)
  406. case "shh_getFilterChanges":
  407. // Retrieve all the new messages arrived since the last request
  408. args := new(FilterIdArgs)
  409. if err := json.Unmarshal(req.Params, &args); err != nil {
  410. return err
  411. }
  412. *reply = api.xeth().WhisperMessagesChanged(args.Id)
  413. case "shh_getMessages":
  414. // Retrieve all the cached messages matching a specific, existing filter
  415. args := new(FilterIdArgs)
  416. if err := json.Unmarshal(req.Params, &args); err != nil {
  417. return err
  418. }
  419. *reply = api.xeth().WhisperMessages(args.Id)
  420. case "eth_hashrate":
  421. *reply = newHexNum(api.xeth().HashRate())
  422. // case "eth_register":
  423. // // Placeholder for actual type
  424. // args := new(HashIndexArgs)
  425. // if err := json.Unmarshal(req.Params, &args); err != nil {
  426. // return err
  427. // }
  428. // *reply = api.xeth().Register(args.Hash)
  429. // case "eth_unregister":
  430. // args := new(HashIndexArgs)
  431. // if err := json.Unmarshal(req.Params, &args); err != nil {
  432. // return err
  433. // }
  434. // *reply = api.xeth().Unregister(args.Hash)
  435. // case "eth_watchTx":
  436. // args := new(HashIndexArgs)
  437. // if err := json.Unmarshal(req.Params, &args); err != nil {
  438. // return err
  439. // }
  440. // *reply = api.xeth().PullWatchTx(args.Hash)
  441. default:
  442. return NewNotImplementedError(req.Method)
  443. }
  444. glog.V(logger.Detail).Infof("Reply: %T %s\n", reply, reply)
  445. return nil
  446. }