api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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/core/vm"
  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. }
  16. func NewEthereumApi(xeth *xeth.XEth) *EthereumApi {
  17. api := &EthereumApi{
  18. eth: xeth,
  19. }
  20. return api
  21. }
  22. func (api *EthereumApi) xeth() *xeth.XEth {
  23. return api.eth
  24. }
  25. func (api *EthereumApi) xethAtStateNum(num int64) *xeth.XEth {
  26. return api.xeth().AtStateNum(num)
  27. }
  28. func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error {
  29. // Spec at https://github.com/ethereum/wiki/wiki/JSON-RPC
  30. glog.V(logger.Debug).Infof("%s %s", req.Method, req.Params)
  31. switch req.Method {
  32. case "web3_sha3":
  33. args := new(Sha3Args)
  34. if err := json.Unmarshal(req.Params, &args); err != nil {
  35. return err
  36. }
  37. *reply = common.ToHex(crypto.Sha3(common.FromHex(args.Data)))
  38. case "web3_clientVersion":
  39. *reply = api.xeth().ClientVersion()
  40. case "net_version":
  41. *reply = api.xeth().NetworkVersion()
  42. case "net_listening":
  43. *reply = api.xeth().IsListening()
  44. case "net_peerCount":
  45. *reply = newHexNum(api.xeth().PeerCount())
  46. case "eth_protocolVersion":
  47. *reply = api.xeth().EthVersion()
  48. case "eth_coinbase":
  49. *reply = newHexData(api.xeth().Coinbase())
  50. case "eth_mining":
  51. *reply = api.xeth().IsMining()
  52. case "eth_gasPrice":
  53. v := xeth.DefaultGasPrice()
  54. *reply = newHexNum(v.Bytes())
  55. case "eth_accounts":
  56. *reply = api.xeth().Accounts()
  57. case "eth_blockNumber":
  58. v := api.xeth().CurrentBlock().Number()
  59. *reply = newHexNum(v.Bytes())
  60. case "eth_getBalance":
  61. args := new(GetBalanceArgs)
  62. if err := json.Unmarshal(req.Params, &args); err != nil {
  63. return err
  64. }
  65. *reply = api.xethAtStateNum(args.BlockNumber).BalanceAt(args.Address)
  66. //v := api.xethAtStateNum(args.BlockNumber).State().SafeGet(args.Address).Balance()
  67. //*reply = common.ToHex(v.Bytes())
  68. case "eth_getStorage", "eth_storageAt":
  69. args := new(GetStorageArgs)
  70. if err := json.Unmarshal(req.Params, &args); err != nil {
  71. return err
  72. }
  73. *reply = api.xethAtStateNum(args.BlockNumber).State().SafeGet(args.Address).Storage()
  74. case "eth_getStorageAt":
  75. args := new(GetStorageAtArgs)
  76. if err := json.Unmarshal(req.Params, &args); err != nil {
  77. return err
  78. }
  79. *reply = api.xethAtStateNum(args.BlockNumber).StorageAt(args.Address, args.Key)
  80. case "eth_getTransactionCount":
  81. args := new(GetTxCountArgs)
  82. if err := json.Unmarshal(req.Params, &args); err != nil {
  83. return err
  84. }
  85. count := api.xethAtStateNum(args.BlockNumber).TxCountAt(args.Address)
  86. *reply = newHexNum(big.NewInt(int64(count)).Bytes())
  87. case "eth_getBlockTransactionCountByHash":
  88. args := new(HashArgs)
  89. if err := json.Unmarshal(req.Params, &args); err != nil {
  90. return err
  91. }
  92. block := NewBlockRes(api.xeth().EthBlockByHash(args.Hash), false)
  93. if block == nil {
  94. *reply = nil
  95. } else {
  96. *reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
  97. }
  98. case "eth_getBlockTransactionCountByNumber":
  99. args := new(BlockNumArg)
  100. if err := json.Unmarshal(req.Params, &args); err != nil {
  101. return err
  102. }
  103. block := NewBlockRes(api.xeth().EthBlockByNumber(args.BlockNumber), false)
  104. if block == nil {
  105. *reply = nil
  106. break
  107. }
  108. *reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
  109. case "eth_getUncleCountByBlockHash":
  110. args := new(HashArgs)
  111. if err := json.Unmarshal(req.Params, &args); err != nil {
  112. return err
  113. }
  114. block := api.xeth().EthBlockByHash(args.Hash)
  115. br := NewBlockRes(block, false)
  116. if br == nil {
  117. *reply = nil
  118. break
  119. }
  120. *reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
  121. case "eth_getUncleCountByBlockNumber":
  122. args := new(BlockNumArg)
  123. if err := json.Unmarshal(req.Params, &args); err != nil {
  124. return err
  125. }
  126. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  127. br := NewBlockRes(block, false)
  128. if br == nil {
  129. *reply = nil
  130. break
  131. }
  132. *reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
  133. case "eth_getData", "eth_getCode":
  134. args := new(GetDataArgs)
  135. if err := json.Unmarshal(req.Params, &args); err != nil {
  136. return err
  137. }
  138. v := api.xethAtStateNum(args.BlockNumber).CodeAtBytes(args.Address)
  139. *reply = newHexData(v)
  140. case "eth_sign":
  141. args := new(NewSigArgs)
  142. if err := json.Unmarshal(req.Params, &args); err != nil {
  143. return err
  144. }
  145. v, err := api.xeth().Sign(args.From, args.Data, false)
  146. if err != nil {
  147. return err
  148. }
  149. *reply = v
  150. case "eth_sendTransaction", "eth_transact":
  151. args := new(NewTxArgs)
  152. if err := json.Unmarshal(req.Params, &args); err != nil {
  153. return err
  154. }
  155. // nonce may be nil ("guess" mode)
  156. var nonce string
  157. if args.Nonce != nil {
  158. nonce = args.Nonce.String()
  159. }
  160. v, err := api.xeth().Transact(args.From, args.To, nonce, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
  161. if err != nil {
  162. return err
  163. }
  164. *reply = v
  165. case "eth_estimateGas":
  166. _, gas, err := api.doCall(req.Params)
  167. if err != nil {
  168. return err
  169. }
  170. // TODO unwrap the parent method's ToHex call
  171. if len(gas) == 0 {
  172. *reply = newHexNum(0)
  173. } else {
  174. *reply = newHexNum(gas)
  175. }
  176. case "eth_call":
  177. v, _, err := api.doCall(req.Params)
  178. if err != nil {
  179. return err
  180. }
  181. // TODO unwrap the parent method's ToHex call
  182. if v == "0x0" {
  183. *reply = newHexData([]byte{})
  184. } else {
  185. *reply = newHexData(common.FromHex(v))
  186. }
  187. case "eth_flush":
  188. return NewNotImplementedError(req.Method)
  189. case "eth_getBlockByHash":
  190. args := new(GetBlockByHashArgs)
  191. if err := json.Unmarshal(req.Params, &args); err != nil {
  192. return err
  193. }
  194. block := api.xeth().EthBlockByHash(args.BlockHash)
  195. br := NewBlockRes(block, args.IncludeTxs)
  196. *reply = br
  197. case "eth_getBlockByNumber":
  198. args := new(GetBlockByNumberArgs)
  199. if err := json.Unmarshal(req.Params, &args); err != nil {
  200. return err
  201. }
  202. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  203. br := NewBlockRes(block, args.IncludeTxs)
  204. // If request was for "pending", nil nonsensical fields
  205. if args.BlockNumber == -2 {
  206. br.BlockHash = nil
  207. br.BlockNumber = nil
  208. br.Miner = nil
  209. br.Nonce = nil
  210. br.LogsBloom = nil
  211. }
  212. *reply = br
  213. case "eth_getTransactionByHash":
  214. args := new(HashArgs)
  215. if err := json.Unmarshal(req.Params, &args); err != nil {
  216. return err
  217. }
  218. tx, bhash, bnum, txi := api.xeth().EthTransactionByHash(args.Hash)
  219. if tx != nil {
  220. v := NewTransactionRes(tx)
  221. // if the blockhash is 0, assume this is a pending transaction
  222. if bytes.Compare(bhash.Bytes(), bytes.Repeat([]byte{0}, 32)) != 0 {
  223. v.BlockHash = newHexData(bhash)
  224. v.BlockNumber = newHexNum(bnum)
  225. v.TxIndex = newHexNum(txi)
  226. }
  227. *reply = v
  228. }
  229. case "eth_getTransactionByBlockHashAndIndex":
  230. args := new(HashIndexArgs)
  231. if err := json.Unmarshal(req.Params, &args); err != nil {
  232. return err
  233. }
  234. block := api.xeth().EthBlockByHash(args.Hash)
  235. br := NewBlockRes(block, true)
  236. if br == nil {
  237. *reply = nil
  238. break
  239. }
  240. if args.Index >= int64(len(br.Transactions)) || args.Index < 0 {
  241. // return NewValidationError("Index", "does not exist")
  242. *reply = nil
  243. } else {
  244. *reply = br.Transactions[args.Index]
  245. }
  246. case "eth_getTransactionByBlockNumberAndIndex":
  247. args := new(BlockNumIndexArgs)
  248. if err := json.Unmarshal(req.Params, &args); err != nil {
  249. return err
  250. }
  251. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  252. v := NewBlockRes(block, true)
  253. if v == nil {
  254. *reply = nil
  255. break
  256. }
  257. if args.Index >= int64(len(v.Transactions)) || args.Index < 0 {
  258. // return NewValidationError("Index", "does not exist")
  259. *reply = nil
  260. } else {
  261. *reply = v.Transactions[args.Index]
  262. }
  263. case "eth_getUncleByBlockHashAndIndex":
  264. args := new(HashIndexArgs)
  265. if err := json.Unmarshal(req.Params, &args); err != nil {
  266. return err
  267. }
  268. br := NewBlockRes(api.xeth().EthBlockByHash(args.Hash), false)
  269. if br == nil {
  270. *reply = nil
  271. return nil
  272. }
  273. if args.Index >= int64(len(br.Uncles)) || args.Index < 0 {
  274. // return NewValidationError("Index", "does not exist")
  275. *reply = nil
  276. } else {
  277. *reply = br.Uncles[args.Index]
  278. }
  279. case "eth_getUncleByBlockNumberAndIndex":
  280. args := new(BlockNumIndexArgs)
  281. if err := json.Unmarshal(req.Params, &args); err != nil {
  282. return err
  283. }
  284. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  285. v := NewBlockRes(block, true)
  286. if v == nil {
  287. *reply = nil
  288. return nil
  289. }
  290. if args.Index >= int64(len(v.Uncles)) || args.Index < 0 {
  291. // return NewValidationError("Index", "does not exist")
  292. *reply = nil
  293. } else {
  294. *reply = v.Uncles[args.Index]
  295. }
  296. case "eth_getCompilers":
  297. var lang string
  298. if solc, _ := api.xeth().Solc(); solc != nil {
  299. lang = "Solidity"
  300. }
  301. c := []string{lang}
  302. *reply = c
  303. case "eth_compileLLL", "eth_compileSerpent":
  304. return NewNotImplementedError(req.Method)
  305. case "eth_compileSolidity":
  306. solc, _ := api.xeth().Solc()
  307. if solc == nil {
  308. return NewNotAvailableError(req.Method, "solc (solidity compiler) not found")
  309. }
  310. args := new(SourceArgs)
  311. if err := json.Unmarshal(req.Params, &args); err != nil {
  312. return err
  313. }
  314. contracts, err := solc.Compile(args.Source)
  315. if err != nil {
  316. return err
  317. }
  318. *reply = contracts
  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 "ext_disasm":
  500. args := new(SourceArgs)
  501. if err := json.Unmarshal(req.Params, &args); err != nil {
  502. return err
  503. }
  504. *reply = vm.Disasm(common.FromHex(args.Source))
  505. // case "eth_register":
  506. // // Placeholder for actual type
  507. // args := new(HashIndexArgs)
  508. // if err := json.Unmarshal(req.Params, &args); err != nil {
  509. // return err
  510. // }
  511. // *reply = api.xeth().Register(args.Hash)
  512. // case "eth_unregister":
  513. // args := new(HashIndexArgs)
  514. // if err := json.Unmarshal(req.Params, &args); err != nil {
  515. // return err
  516. // }
  517. // *reply = api.xeth().Unregister(args.Hash)
  518. // case "eth_watchTx":
  519. // args := new(HashIndexArgs)
  520. // if err := json.Unmarshal(req.Params, &args); err != nil {
  521. // return err
  522. // }
  523. // *reply = api.xeth().PullWatchTx(args.Hash)
  524. default:
  525. return NewNotImplementedError(req.Method)
  526. }
  527. // glog.V(logger.Detail).Infof("Reply: %v\n", reply)
  528. return nil
  529. }
  530. func (api *EthereumApi) doCall(params json.RawMessage) (string, string, error) {
  531. args := new(CallArgs)
  532. if err := json.Unmarshal(params, &args); err != nil {
  533. return "", "", err
  534. }
  535. return api.xethAtStateNum(args.BlockNumber).Call(args.From, args.To, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
  536. }