api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. contract, err := solc.Compile(args.Source)
  314. if err != nil {
  315. return err
  316. }
  317. contract.Code = newHexData(contract.Code).String()
  318. *reply = contract
  319. case "eth_newFilter":
  320. args := new(BlockFilterArgs)
  321. if err := json.Unmarshal(req.Params, &args); err != nil {
  322. return err
  323. }
  324. id := api.xeth().NewLogFilter(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics)
  325. *reply = newHexNum(big.NewInt(int64(id)).Bytes())
  326. case "eth_newBlockFilter":
  327. *reply = newHexNum(api.xeth().NewBlockFilter())
  328. case "eth_newPendingTransactionFilter":
  329. *reply = newHexNum(api.xeth().NewTransactionFilter())
  330. case "eth_uninstallFilter":
  331. args := new(FilterIdArgs)
  332. if err := json.Unmarshal(req.Params, &args); err != nil {
  333. return err
  334. }
  335. *reply = api.xeth().UninstallFilter(args.Id)
  336. case "eth_getFilterChanges":
  337. args := new(FilterIdArgs)
  338. if err := json.Unmarshal(req.Params, &args); err != nil {
  339. return err
  340. }
  341. switch api.xeth().GetFilterType(args.Id) {
  342. case xeth.BlockFilterTy:
  343. *reply = NewHashesRes(api.xeth().BlockFilterChanged(args.Id))
  344. case xeth.TransactionFilterTy:
  345. *reply = NewHashesRes(api.xeth().TransactionFilterChanged(args.Id))
  346. case xeth.LogFilterTy:
  347. *reply = NewLogsRes(api.xeth().LogFilterChanged(args.Id))
  348. default:
  349. *reply = []string{} // reply empty string slice
  350. }
  351. case "eth_getFilterLogs":
  352. args := new(FilterIdArgs)
  353. if err := json.Unmarshal(req.Params, &args); err != nil {
  354. return err
  355. }
  356. *reply = NewLogsRes(api.xeth().Logs(args.Id))
  357. case "eth_getLogs":
  358. args := new(BlockFilterArgs)
  359. if err := json.Unmarshal(req.Params, &args); err != nil {
  360. return err
  361. }
  362. *reply = NewLogsRes(api.xeth().AllLogs(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics))
  363. case "eth_getWork":
  364. api.xeth().SetMining(true, 0)
  365. *reply = api.xeth().RemoteMining().GetWork()
  366. case "eth_submitWork":
  367. args := new(SubmitWorkArgs)
  368. if err := json.Unmarshal(req.Params, &args); err != nil {
  369. return err
  370. }
  371. *reply = api.xeth().RemoteMining().SubmitWork(args.Nonce, common.HexToHash(args.Digest), common.HexToHash(args.Header))
  372. case "db_putString":
  373. args := new(DbArgs)
  374. if err := json.Unmarshal(req.Params, &args); err != nil {
  375. return err
  376. }
  377. if err := args.requirements(); err != nil {
  378. return err
  379. }
  380. api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
  381. *reply = true
  382. case "db_getString":
  383. args := new(DbArgs)
  384. if err := json.Unmarshal(req.Params, &args); err != nil {
  385. return err
  386. }
  387. if err := args.requirements(); err != nil {
  388. return err
  389. }
  390. res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
  391. *reply = string(res)
  392. case "db_putHex":
  393. args := new(DbHexArgs)
  394. if err := json.Unmarshal(req.Params, &args); err != nil {
  395. return err
  396. }
  397. if err := args.requirements(); err != nil {
  398. return err
  399. }
  400. api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
  401. *reply = true
  402. case "db_getHex":
  403. args := new(DbHexArgs)
  404. if err := json.Unmarshal(req.Params, &args); err != nil {
  405. return err
  406. }
  407. if err := args.requirements(); err != nil {
  408. return err
  409. }
  410. res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
  411. *reply = newHexData(res)
  412. case "shh_version":
  413. // Short circuit if whisper is not running
  414. if api.xeth().Whisper() == nil {
  415. return NewNotAvailableError(req.Method, "whisper offline")
  416. }
  417. // Retrieves the currently running whisper protocol version
  418. *reply = api.xeth().WhisperVersion()
  419. case "shh_post":
  420. // Short circuit if whisper is not running
  421. if api.xeth().Whisper() == nil {
  422. return NewNotAvailableError(req.Method, "whisper offline")
  423. }
  424. // Injects a new message into the whisper network
  425. args := new(WhisperMessageArgs)
  426. if err := json.Unmarshal(req.Params, &args); err != nil {
  427. return err
  428. }
  429. err := api.xeth().Whisper().Post(args.Payload, args.To, args.From, args.Topics, args.Priority, args.Ttl)
  430. if err != nil {
  431. return err
  432. }
  433. *reply = true
  434. case "shh_newIdentity":
  435. // Short circuit if whisper is not running
  436. if api.xeth().Whisper() == nil {
  437. return NewNotAvailableError(req.Method, "whisper offline")
  438. }
  439. // Creates a new whisper identity to use for sending/receiving messages
  440. *reply = api.xeth().Whisper().NewIdentity()
  441. case "shh_hasIdentity":
  442. // Short circuit if whisper is not running
  443. if api.xeth().Whisper() == nil {
  444. return NewNotAvailableError(req.Method, "whisper offline")
  445. }
  446. // Checks if an identity if owned or not
  447. args := new(WhisperIdentityArgs)
  448. if err := json.Unmarshal(req.Params, &args); err != nil {
  449. return err
  450. }
  451. *reply = api.xeth().Whisper().HasIdentity(args.Identity)
  452. case "shh_newFilter":
  453. // Short circuit if whisper is not running
  454. if api.xeth().Whisper() == nil {
  455. return NewNotAvailableError(req.Method, "whisper offline")
  456. }
  457. // Create a new filter to watch and match messages with
  458. args := new(WhisperFilterArgs)
  459. if err := json.Unmarshal(req.Params, &args); err != nil {
  460. return err
  461. }
  462. id := api.xeth().NewWhisperFilter(args.To, args.From, args.Topics)
  463. *reply = newHexNum(big.NewInt(int64(id)).Bytes())
  464. case "shh_uninstallFilter":
  465. // Short circuit if whisper is not running
  466. if api.xeth().Whisper() == nil {
  467. return NewNotAvailableError(req.Method, "whisper offline")
  468. }
  469. // Remove an existing filter watching messages
  470. args := new(FilterIdArgs)
  471. if err := json.Unmarshal(req.Params, &args); err != nil {
  472. return err
  473. }
  474. *reply = api.xeth().UninstallWhisperFilter(args.Id)
  475. case "shh_getFilterChanges":
  476. // Short circuit if whisper is not running
  477. if api.xeth().Whisper() == nil {
  478. return NewNotAvailableError(req.Method, "whisper offline")
  479. }
  480. // Retrieve all the new messages arrived since the last request
  481. args := new(FilterIdArgs)
  482. if err := json.Unmarshal(req.Params, &args); err != nil {
  483. return err
  484. }
  485. *reply = api.xeth().WhisperMessagesChanged(args.Id)
  486. case "shh_getMessages":
  487. // Short circuit if whisper is not running
  488. if api.xeth().Whisper() == nil {
  489. return NewNotAvailableError(req.Method, "whisper offline")
  490. }
  491. // Retrieve all the cached messages matching a specific, existing filter
  492. args := new(FilterIdArgs)
  493. if err := json.Unmarshal(req.Params, &args); err != nil {
  494. return err
  495. }
  496. *reply = api.xeth().WhisperMessages(args.Id)
  497. case "eth_hashrate":
  498. *reply = newHexNum(api.xeth().HashRate())
  499. // case "eth_register":
  500. // // Placeholder for actual type
  501. // args := new(HashIndexArgs)
  502. // if err := json.Unmarshal(req.Params, &args); err != nil {
  503. // return err
  504. // }
  505. // *reply = api.xeth().Register(args.Hash)
  506. // case "eth_unregister":
  507. // args := new(HashIndexArgs)
  508. // if err := json.Unmarshal(req.Params, &args); err != nil {
  509. // return err
  510. // }
  511. // *reply = api.xeth().Unregister(args.Hash)
  512. // case "eth_watchTx":
  513. // args := new(HashIndexArgs)
  514. // if err := json.Unmarshal(req.Params, &args); err != nil {
  515. // return err
  516. // }
  517. // *reply = api.xeth().PullWatchTx(args.Hash)
  518. default:
  519. return NewNotImplementedError(req.Method)
  520. }
  521. // glog.V(logger.Detail).Infof("Reply: %v\n", reply)
  522. return nil
  523. }
  524. func (api *EthereumApi) doCall(params json.RawMessage) (string, string, error) {
  525. args := new(CallArgs)
  526. if err := json.Unmarshal(params, &args); err != nil {
  527. return "", "", err
  528. }
  529. return api.xethAtStateNum(args.BlockNumber).Call(args.From, args.To, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
  530. }