api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. package rpc
  2. import (
  3. "encoding/json"
  4. "math/big"
  5. // "sync"
  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. *reply = br
  204. case "eth_getTransactionByHash":
  205. args := new(HashArgs)
  206. if err := json.Unmarshal(req.Params, &args); err != nil {
  207. return err
  208. }
  209. tx, bhash, bnum, txi := api.xeth().EthTransactionByHash(args.Hash)
  210. if tx != nil {
  211. v := NewTransactionRes(tx)
  212. v.BlockHash = newHexData(bhash)
  213. v.BlockNumber = newHexNum(bnum)
  214. v.TxIndex = newHexNum(txi)
  215. *reply = v
  216. }
  217. case "eth_getTransactionByBlockHashAndIndex":
  218. args := new(HashIndexArgs)
  219. if err := json.Unmarshal(req.Params, &args); err != nil {
  220. return err
  221. }
  222. block := api.xeth().EthBlockByHash(args.Hash)
  223. br := NewBlockRes(block, true)
  224. if br == nil {
  225. *reply = nil
  226. break
  227. }
  228. if args.Index >= int64(len(br.Transactions)) || args.Index < 0 {
  229. // return NewValidationError("Index", "does not exist")
  230. *reply = nil
  231. } else {
  232. *reply = br.Transactions[args.Index]
  233. }
  234. case "eth_getTransactionByBlockNumberAndIndex":
  235. args := new(BlockNumIndexArgs)
  236. if err := json.Unmarshal(req.Params, &args); err != nil {
  237. return err
  238. }
  239. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  240. v := NewBlockRes(block, true)
  241. if v == nil {
  242. *reply = nil
  243. break
  244. }
  245. if args.Index >= int64(len(v.Transactions)) || args.Index < 0 {
  246. // return NewValidationError("Index", "does not exist")
  247. *reply = nil
  248. } else {
  249. *reply = v.Transactions[args.Index]
  250. }
  251. case "eth_getUncleByBlockHashAndIndex":
  252. args := new(HashIndexArgs)
  253. if err := json.Unmarshal(req.Params, &args); err != nil {
  254. return err
  255. }
  256. br := NewBlockRes(api.xeth().EthBlockByHash(args.Hash), false)
  257. if br == nil {
  258. *reply = nil
  259. return nil
  260. }
  261. if args.Index >= int64(len(br.Uncles)) || args.Index < 0 {
  262. // return NewValidationError("Index", "does not exist")
  263. *reply = nil
  264. } else {
  265. *reply = br.Uncles[args.Index]
  266. }
  267. case "eth_getUncleByBlockNumberAndIndex":
  268. args := new(BlockNumIndexArgs)
  269. if err := json.Unmarshal(req.Params, &args); err != nil {
  270. return err
  271. }
  272. block := api.xeth().EthBlockByNumber(args.BlockNumber)
  273. v := NewBlockRes(block, true)
  274. if v == nil {
  275. *reply = nil
  276. return nil
  277. }
  278. if args.Index >= int64(len(v.Uncles)) || args.Index < 0 {
  279. // return NewValidationError("Index", "does not exist")
  280. *reply = nil
  281. } else {
  282. *reply = v.Uncles[args.Index]
  283. }
  284. case "eth_getCompilers":
  285. var lang string
  286. if solc, _ := api.xeth().Solc(); solc != nil {
  287. lang = "Solidity"
  288. }
  289. c := []string{lang}
  290. *reply = c
  291. case "eth_compileLLL", "eth_compileSerpent":
  292. return NewNotImplementedError(req.Method)
  293. case "eth_compileSolidity":
  294. solc, _ := api.xeth().Solc()
  295. if solc == nil {
  296. return NewNotImplementedError(req.Method)
  297. }
  298. args := new(SourceArgs)
  299. if err := json.Unmarshal(req.Params, &args); err != nil {
  300. return err
  301. }
  302. contract, err := solc.Compile(args.Source)
  303. if err != nil {
  304. return err
  305. }
  306. contract.Code = newHexData(contract.Code).String()
  307. *reply = contract
  308. case "eth_newFilter":
  309. args := new(BlockFilterArgs)
  310. if err := json.Unmarshal(req.Params, &args); err != nil {
  311. return err
  312. }
  313. id := api.xeth().NewLogFilter(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics)
  314. *reply = newHexNum(big.NewInt(int64(id)).Bytes())
  315. case "eth_newBlockFilter":
  316. *reply = newHexNum(api.xeth().NewBlockFilter())
  317. case "eth_newPendingTransactionFilter":
  318. *reply = newHexNum(api.xeth().NewTransactionFilter())
  319. case "eth_uninstallFilter":
  320. args := new(FilterIdArgs)
  321. if err := json.Unmarshal(req.Params, &args); err != nil {
  322. return err
  323. }
  324. *reply = api.xeth().UninstallFilter(args.Id)
  325. case "eth_getFilterChanges":
  326. args := new(FilterIdArgs)
  327. if err := json.Unmarshal(req.Params, &args); err != nil {
  328. return err
  329. }
  330. switch api.xeth().GetFilterType(args.Id) {
  331. case xeth.BlockFilterTy:
  332. *reply = NewHashesRes(api.xeth().BlockFilterChanged(args.Id))
  333. case xeth.TransactionFilterTy:
  334. *reply = NewHashesRes(api.xeth().TransactionFilterChanged(args.Id))
  335. case xeth.LogFilterTy:
  336. *reply = NewLogsRes(api.xeth().LogFilterChanged(args.Id))
  337. default:
  338. *reply = []string{} // reply empty string slice
  339. }
  340. case "eth_getFilterLogs":
  341. args := new(FilterIdArgs)
  342. if err := json.Unmarshal(req.Params, &args); err != nil {
  343. return err
  344. }
  345. *reply = NewLogsRes(api.xeth().Logs(args.Id))
  346. case "eth_getLogs":
  347. args := new(BlockFilterArgs)
  348. if err := json.Unmarshal(req.Params, &args); err != nil {
  349. return err
  350. }
  351. *reply = NewLogsRes(api.xeth().AllLogs(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics))
  352. case "eth_getWork":
  353. api.xeth().SetMining(true, 0)
  354. *reply = api.xeth().RemoteMining().GetWork()
  355. case "eth_submitWork":
  356. args := new(SubmitWorkArgs)
  357. if err := json.Unmarshal(req.Params, &args); err != nil {
  358. return err
  359. }
  360. *reply = api.xeth().RemoteMining().SubmitWork(args.Nonce, common.HexToHash(args.Digest), common.HexToHash(args.Header))
  361. case "db_putString":
  362. args := new(DbArgs)
  363. if err := json.Unmarshal(req.Params, &args); err != nil {
  364. return err
  365. }
  366. if err := args.requirements(); err != nil {
  367. return err
  368. }
  369. api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
  370. *reply = true
  371. case "db_getString":
  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. res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
  380. *reply = string(res)
  381. case "db_putHex":
  382. args := new(DbHexArgs)
  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. api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
  390. *reply = true
  391. case "db_getHex":
  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. res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
  400. *reply = newHexData(res)
  401. case "shh_version":
  402. // Short circuit if whisper is not running
  403. if api.xeth().Whisper() == nil {
  404. return NewNotAvailableError(req.Method, "whisper offline")
  405. }
  406. // Retrieves the currently running whisper protocol version
  407. *reply = api.xeth().WhisperVersion()
  408. case "shh_post":
  409. // Short circuit if whisper is not running
  410. if api.xeth().Whisper() == nil {
  411. return NewNotAvailableError(req.Method, "whisper offline")
  412. }
  413. // Injects a new message into the whisper network
  414. args := new(WhisperMessageArgs)
  415. if err := json.Unmarshal(req.Params, &args); err != nil {
  416. return err
  417. }
  418. err := api.xeth().Whisper().Post(args.Payload, args.To, args.From, args.Topics, args.Priority, args.Ttl)
  419. if err != nil {
  420. return err
  421. }
  422. *reply = true
  423. case "shh_newIdentity":
  424. // Short circuit if whisper is not running
  425. if api.xeth().Whisper() == nil {
  426. return NewNotAvailableError(req.Method, "whisper offline")
  427. }
  428. // Creates a new whisper identity to use for sending/receiving messages
  429. *reply = api.xeth().Whisper().NewIdentity()
  430. case "shh_hasIdentity":
  431. // Short circuit if whisper is not running
  432. if api.xeth().Whisper() == nil {
  433. return NewNotAvailableError(req.Method, "whisper offline")
  434. }
  435. // Checks if an identity if owned or not
  436. args := new(WhisperIdentityArgs)
  437. if err := json.Unmarshal(req.Params, &args); err != nil {
  438. return err
  439. }
  440. *reply = api.xeth().Whisper().HasIdentity(args.Identity)
  441. case "shh_newFilter":
  442. // Short circuit if whisper is not running
  443. if api.xeth().Whisper() == nil {
  444. return NewNotAvailableError(req.Method, "whisper offline")
  445. }
  446. // Create a new filter to watch and match messages with
  447. args := new(WhisperFilterArgs)
  448. if err := json.Unmarshal(req.Params, &args); err != nil {
  449. return err
  450. }
  451. id := api.xeth().NewWhisperFilter(args.To, args.From, args.Topics)
  452. *reply = newHexNum(big.NewInt(int64(id)).Bytes())
  453. case "shh_uninstallFilter":
  454. // Short circuit if whisper is not running
  455. if api.xeth().Whisper() == nil {
  456. return NewNotAvailableError(req.Method, "whisper offline")
  457. }
  458. // Remove an existing filter watching messages
  459. args := new(FilterIdArgs)
  460. if err := json.Unmarshal(req.Params, &args); err != nil {
  461. return err
  462. }
  463. *reply = api.xeth().UninstallWhisperFilter(args.Id)
  464. case "shh_getFilterChanges":
  465. // Short circuit if whisper is not running
  466. if api.xeth().Whisper() == nil {
  467. return NewNotAvailableError(req.Method, "whisper offline")
  468. }
  469. // Retrieve all the new messages arrived since the last request
  470. args := new(FilterIdArgs)
  471. if err := json.Unmarshal(req.Params, &args); err != nil {
  472. return err
  473. }
  474. *reply = api.xeth().WhisperMessagesChanged(args.Id)
  475. case "shh_getMessages":
  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 cached messages matching a specific, existing filter
  481. args := new(FilterIdArgs)
  482. if err := json.Unmarshal(req.Params, &args); err != nil {
  483. return err
  484. }
  485. *reply = api.xeth().WhisperMessages(args.Id)
  486. case "eth_hashrate":
  487. *reply = newHexNum(api.xeth().HashRate())
  488. // case "eth_register":
  489. // // Placeholder for actual type
  490. // args := new(HashIndexArgs)
  491. // if err := json.Unmarshal(req.Params, &args); err != nil {
  492. // return err
  493. // }
  494. // *reply = api.xeth().Register(args.Hash)
  495. // case "eth_unregister":
  496. // args := new(HashIndexArgs)
  497. // if err := json.Unmarshal(req.Params, &args); err != nil {
  498. // return err
  499. // }
  500. // *reply = api.xeth().Unregister(args.Hash)
  501. // case "eth_watchTx":
  502. // args := new(HashIndexArgs)
  503. // if err := json.Unmarshal(req.Params, &args); err != nil {
  504. // return err
  505. // }
  506. // *reply = api.xeth().PullWatchTx(args.Hash)
  507. default:
  508. return NewNotImplementedError(req.Method)
  509. }
  510. glog.V(logger.Detail).Infof("Reply: %T %s\n", reply, reply)
  511. return nil
  512. }
  513. func (api *EthereumApi) doCall(params json.RawMessage) (string, string, error) {
  514. args := new(CallArgs)
  515. if err := json.Unmarshal(params, &args); err != nil {
  516. return "", "", err
  517. }
  518. return api.xethAtStateNum(args.BlockNumber).Call(args.From, args.To, args.Value.String(), args.Gas.String(), args.GasPrice.String(), args.Data)
  519. }