api.go 16 KB

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