debug.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package api
  17. import (
  18. "fmt"
  19. "strings"
  20. "time"
  21. "github.com/ethereum/ethash"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/core/state"
  24. "github.com/ethereum/go-ethereum/core/vm"
  25. "github.com/ethereum/go-ethereum/eth"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "github.com/ethereum/go-ethereum/rpc/codec"
  28. "github.com/ethereum/go-ethereum/rpc/shared"
  29. "github.com/ethereum/go-ethereum/xeth"
  30. "github.com/rcrowley/go-metrics"
  31. )
  32. const (
  33. DebugApiVersion = "1.0"
  34. )
  35. var (
  36. // mapping between methods and handlers
  37. DebugMapping = map[string]debughandler{
  38. "debug_dumpBlock": (*debugApi).DumpBlock,
  39. "debug_getBlockRlp": (*debugApi).GetBlockRlp,
  40. "debug_printBlock": (*debugApi).PrintBlock,
  41. "debug_processBlock": (*debugApi).ProcessBlock,
  42. "debug_seedHash": (*debugApi).SeedHash,
  43. "debug_setHead": (*debugApi).SetHead,
  44. "debug_metrics": (*debugApi).Metrics,
  45. }
  46. )
  47. // debug callback handler
  48. type debughandler func(*debugApi, *shared.Request) (interface{}, error)
  49. // admin api provider
  50. type debugApi struct {
  51. xeth *xeth.XEth
  52. ethereum *eth.Ethereum
  53. methods map[string]debughandler
  54. codec codec.ApiCoder
  55. }
  56. // create a new debug api instance
  57. func NewDebugApi(xeth *xeth.XEth, ethereum *eth.Ethereum, coder codec.Codec) *debugApi {
  58. return &debugApi{
  59. xeth: xeth,
  60. ethereum: ethereum,
  61. methods: DebugMapping,
  62. codec: coder.New(nil),
  63. }
  64. }
  65. // collection with supported methods
  66. func (self *debugApi) Methods() []string {
  67. methods := make([]string, len(self.methods))
  68. i := 0
  69. for k := range self.methods {
  70. methods[i] = k
  71. i++
  72. }
  73. return methods
  74. }
  75. // Execute given request
  76. func (self *debugApi) Execute(req *shared.Request) (interface{}, error) {
  77. if callback, ok := self.methods[req.Method]; ok {
  78. return callback(self, req)
  79. }
  80. return nil, &shared.NotImplementedError{req.Method}
  81. }
  82. func (self *debugApi) Name() string {
  83. return shared.DebugApiName
  84. }
  85. func (self *debugApi) ApiVersion() string {
  86. return DebugApiVersion
  87. }
  88. func (self *debugApi) PrintBlock(req *shared.Request) (interface{}, error) {
  89. args := new(BlockNumArg)
  90. if err := self.codec.Decode(req.Params, &args); err != nil {
  91. return nil, shared.NewDecodeParamError(err.Error())
  92. }
  93. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  94. return fmt.Sprintf("%s", block), nil
  95. }
  96. func (self *debugApi) DumpBlock(req *shared.Request) (interface{}, error) {
  97. args := new(BlockNumArg)
  98. if err := self.codec.Decode(req.Params, &args); err != nil {
  99. return nil, shared.NewDecodeParamError(err.Error())
  100. }
  101. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  102. if block == nil {
  103. return nil, fmt.Errorf("block #%d not found", args.BlockNumber)
  104. }
  105. stateDb, err := state.New(block.Root(), self.ethereum.ChainDb())
  106. if err != nil {
  107. return nil, err
  108. }
  109. return stateDb.RawDump(), nil
  110. }
  111. func (self *debugApi) GetBlockRlp(req *shared.Request) (interface{}, error) {
  112. args := new(BlockNumArg)
  113. if err := self.codec.Decode(req.Params, &args); err != nil {
  114. return nil, shared.NewDecodeParamError(err.Error())
  115. }
  116. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  117. if block == nil {
  118. return nil, fmt.Errorf("block #%d not found", args.BlockNumber)
  119. }
  120. encoded, err := rlp.EncodeToBytes(block)
  121. return fmt.Sprintf("%x", encoded), err
  122. }
  123. func (self *debugApi) SetHead(req *shared.Request) (interface{}, error) {
  124. args := new(BlockNumArg)
  125. if err := self.codec.Decode(req.Params, &args); err != nil {
  126. return nil, shared.NewDecodeParamError(err.Error())
  127. }
  128. self.ethereum.BlockChain().SetHead(uint64(args.BlockNumber))
  129. return nil, nil
  130. }
  131. func (self *debugApi) ProcessBlock(req *shared.Request) (interface{}, error) {
  132. args := new(BlockNumArg)
  133. if err := self.codec.Decode(req.Params, &args); err != nil {
  134. return nil, shared.NewDecodeParamError(err.Error())
  135. }
  136. block := self.xeth.EthBlockByNumber(args.BlockNumber)
  137. if block == nil {
  138. return nil, fmt.Errorf("block #%d not found", args.BlockNumber)
  139. }
  140. old := vm.Debug
  141. defer func() { vm.Debug = old }()
  142. vm.Debug = true
  143. var (
  144. blockchain = self.ethereum.BlockChain()
  145. validator = blockchain.Validator()
  146. processor = blockchain.Processor()
  147. )
  148. err := core.ValidateHeader(blockchain.AuxValidator(), block.Header(), blockchain.GetHeader(block.ParentHash()), true, false)
  149. if err != nil {
  150. return false, err
  151. }
  152. statedb, err := state.New(blockchain.GetBlock(block.ParentHash()).Root(), self.ethereum.ChainDb())
  153. if err != nil {
  154. return false, err
  155. }
  156. receipts, _, usedGas, err := processor.Process(block, statedb)
  157. if err != nil {
  158. return false, err
  159. }
  160. err = validator.ValidateState(block, blockchain.GetBlock(block.ParentHash()), statedb, receipts, usedGas)
  161. if err != nil {
  162. return false, err
  163. }
  164. return true, nil
  165. }
  166. func (self *debugApi) SeedHash(req *shared.Request) (interface{}, error) {
  167. args := new(BlockNumArg)
  168. if err := self.codec.Decode(req.Params, &args); err != nil {
  169. return nil, shared.NewDecodeParamError(err.Error())
  170. }
  171. if hash, err := ethash.GetSeedHash(uint64(args.BlockNumber)); err == nil {
  172. return fmt.Sprintf("0x%x", hash), nil
  173. } else {
  174. return nil, err
  175. }
  176. }
  177. func (self *debugApi) Metrics(req *shared.Request) (interface{}, error) {
  178. args := new(MetricsArgs)
  179. if err := self.codec.Decode(req.Params, &args); err != nil {
  180. return nil, shared.NewDecodeParamError(err.Error())
  181. }
  182. // Create a rate formatter
  183. units := []string{"", "K", "M", "G", "T", "E", "P"}
  184. round := func(value float64, prec int) string {
  185. unit := 0
  186. for value >= 1000 {
  187. unit, value, prec = unit+1, value/1000, 2
  188. }
  189. return fmt.Sprintf(fmt.Sprintf("%%.%df%s", prec, units[unit]), value)
  190. }
  191. format := func(total float64, rate float64) string {
  192. return fmt.Sprintf("%s (%s/s)", round(total, 0), round(rate, 2))
  193. }
  194. // Iterate over all the metrics, and just dump for now
  195. counters := make(map[string]interface{})
  196. metrics.DefaultRegistry.Each(func(name string, metric interface{}) {
  197. // Create or retrieve the counter hierarchy for this metric
  198. root, parts := counters, strings.Split(name, "/")
  199. for _, part := range parts[:len(parts)-1] {
  200. if _, ok := root[part]; !ok {
  201. root[part] = make(map[string]interface{})
  202. }
  203. root = root[part].(map[string]interface{})
  204. }
  205. name = parts[len(parts)-1]
  206. // Fill the counter with the metric details, formatting if requested
  207. if args.Raw {
  208. switch metric := metric.(type) {
  209. case metrics.Meter:
  210. root[name] = map[string]interface{}{
  211. "AvgRate01Min": metric.Rate1(),
  212. "AvgRate05Min": metric.Rate5(),
  213. "AvgRate15Min": metric.Rate15(),
  214. "MeanRate": metric.RateMean(),
  215. "Overall": float64(metric.Count()),
  216. }
  217. case metrics.Timer:
  218. root[name] = map[string]interface{}{
  219. "AvgRate01Min": metric.Rate1(),
  220. "AvgRate05Min": metric.Rate5(),
  221. "AvgRate15Min": metric.Rate15(),
  222. "MeanRate": metric.RateMean(),
  223. "Overall": float64(metric.Count()),
  224. "Percentiles": map[string]interface{}{
  225. "5": metric.Percentile(0.05),
  226. "20": metric.Percentile(0.2),
  227. "50": metric.Percentile(0.5),
  228. "80": metric.Percentile(0.8),
  229. "95": metric.Percentile(0.95),
  230. },
  231. }
  232. default:
  233. root[name] = "Unknown metric type"
  234. }
  235. } else {
  236. switch metric := metric.(type) {
  237. case metrics.Meter:
  238. root[name] = map[string]interface{}{
  239. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  240. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  241. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  242. "Overall": format(float64(metric.Count()), metric.RateMean()),
  243. }
  244. case metrics.Timer:
  245. root[name] = map[string]interface{}{
  246. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  247. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  248. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  249. "Overall": format(float64(metric.Count()), metric.RateMean()),
  250. "Maximum": time.Duration(metric.Max()).String(),
  251. "Minimum": time.Duration(metric.Min()).String(),
  252. "Percentiles": map[string]interface{}{
  253. "5": time.Duration(metric.Percentile(0.05)).String(),
  254. "20": time.Duration(metric.Percentile(0.2)).String(),
  255. "50": time.Duration(metric.Percentile(0.5)).String(),
  256. "80": time.Duration(metric.Percentile(0.8)).String(),
  257. "95": time.Duration(metric.Percentile(0.95)).String(),
  258. },
  259. }
  260. default:
  261. root[name] = "Unknown metric type"
  262. }
  263. }
  264. })
  265. return counters, nil
  266. }