ui_lib.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // Copyright (c) 2013-2014, Jeffrey Wilcke. All rights reserved.
  2. //
  3. // This library is free software; you can redistribute it and/or
  4. // modify it under the terms of the GNU General Public
  5. // License as published by the Free Software Foundation; either
  6. // version 2.1 of the License, or (at your option) any later version.
  7. //
  8. // This library is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. // General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this library; if not, write to the Free Software
  15. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. // MA 02110-1301 USA
  17. package main
  18. import (
  19. "bytes"
  20. "fmt"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "github.com/ethereum/go-ethereum"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/ethutil"
  29. "github.com/ethereum/go-ethereum/javascript"
  30. "github.com/ethereum/go-ethereum/miner"
  31. "github.com/ethereum/go-ethereum/state"
  32. "github.com/ethereum/go-ethereum/ui/qt"
  33. "github.com/ethereum/go-ethereum/xeth"
  34. "gopkg.in/qml.v1"
  35. )
  36. type memAddr struct {
  37. Num string
  38. Value string
  39. }
  40. // UI Library that has some basic functionality exposed
  41. type UiLib struct {
  42. *xeth.JSXEth
  43. engine *qml.Engine
  44. eth *eth.Ethereum
  45. connected bool
  46. assetPath string
  47. // The main application window
  48. win *qml.Window
  49. Db *Debugger
  50. DbWindow *DebuggerWindow
  51. jsEngine *javascript.JSRE
  52. filterCallbacks map[int][]int
  53. miner *miner.Miner
  54. }
  55. func NewUiLib(engine *qml.Engine, eth *eth.Ethereum, assetPath string) *UiLib {
  56. lib := &UiLib{JSXEth: xeth.NewJSXEth(eth), engine: engine, eth: eth, assetPath: assetPath, jsEngine: javascript.NewJSRE(eth), filterCallbacks: make(map[int][]int)} //, filters: make(map[int]*xeth.JSFilter)}
  57. lib.miner = miner.New(eth.KeyManager().Address(), eth)
  58. return lib
  59. }
  60. func (self *UiLib) Notef(args []interface{}) {
  61. guilogger.Infoln(args...)
  62. }
  63. func (self *UiLib) LookupDomain(domain string) string {
  64. world := self.World()
  65. if len(domain) > 32 {
  66. domain = string(crypto.Sha3([]byte(domain)))
  67. }
  68. data := world.Config().Get("DnsReg").StorageString(domain).Bytes()
  69. // Left padded = A record, Right padded = CNAME
  70. if len(data) > 0 && data[0] == 0 {
  71. data = bytes.TrimLeft(data, "\x00")
  72. var ipSlice []string
  73. for _, d := range data {
  74. ipSlice = append(ipSlice, strconv.Itoa(int(d)))
  75. }
  76. return strings.Join(ipSlice, ".")
  77. } else {
  78. data = bytes.TrimRight(data, "\x00")
  79. return string(data)
  80. }
  81. }
  82. func (self *UiLib) LookupName(addr string) string {
  83. var (
  84. nameReg = self.World().Config().Get("NameReg")
  85. lookup = nameReg.Storage(ethutil.Hex2Bytes(addr))
  86. )
  87. if lookup.Len() != 0 {
  88. return strings.Trim(lookup.Str(), "\x00")
  89. }
  90. return addr
  91. }
  92. func (self *UiLib) LookupAddress(name string) string {
  93. var (
  94. nameReg = self.World().Config().Get("NameReg")
  95. lookup = nameReg.Storage(ethutil.RightPadBytes([]byte(name), 32))
  96. )
  97. if lookup.Len() != 0 {
  98. return ethutil.Bytes2Hex(lookup.Bytes())
  99. }
  100. return ""
  101. }
  102. func (self *UiLib) PastPeers() *ethutil.List {
  103. return ethutil.NewList(eth.PastPeers())
  104. }
  105. func (self *UiLib) ImportTx(rlpTx string) {
  106. tx := types.NewTransactionFromBytes(ethutil.Hex2Bytes(rlpTx))
  107. err := self.eth.TxPool().Add(tx)
  108. if err != nil {
  109. guilogger.Infoln("import tx failed ", err)
  110. }
  111. }
  112. func (self *UiLib) EvalJavascriptFile(path string) {
  113. self.jsEngine.LoadExtFile(path[7:])
  114. }
  115. func (self *UiLib) EvalJavascriptString(str string) string {
  116. value, err := self.jsEngine.Run(str)
  117. if err != nil {
  118. return err.Error()
  119. }
  120. return fmt.Sprintf("%v", value)
  121. }
  122. func (ui *UiLib) OpenQml(path string) {
  123. container := NewQmlApplication(path[7:], ui)
  124. app := NewExtApplication(container, ui)
  125. go app.run()
  126. }
  127. func (ui *UiLib) OpenHtml(path string) {
  128. container := NewHtmlApplication(path, ui)
  129. app := NewExtApplication(container, ui)
  130. go app.run()
  131. }
  132. func (ui *UiLib) OpenBrowser() {
  133. ui.OpenHtml("file://" + ui.AssetPath("ext/home.html"))
  134. }
  135. func (ui *UiLib) Muted(content string) {
  136. component, err := ui.engine.LoadFile(ui.AssetPath("qml/muted.qml"))
  137. if err != nil {
  138. guilogger.Debugln(err)
  139. return
  140. }
  141. win := component.CreateWindow(nil)
  142. go func() {
  143. path := "file://" + ui.AssetPath("muted/index.html")
  144. win.Set("url", path)
  145. win.Show()
  146. win.Wait()
  147. }()
  148. }
  149. func (ui *UiLib) Connect(button qml.Object) {
  150. if !ui.connected {
  151. ui.eth.Start(true)
  152. ui.connected = true
  153. button.Set("enabled", false)
  154. }
  155. }
  156. func (ui *UiLib) ConnectToPeer(addr string) {
  157. ui.eth.ConnectToPeer(addr)
  158. }
  159. func (ui *UiLib) AssetPath(p string) string {
  160. return path.Join(ui.assetPath, p)
  161. }
  162. func (self *UiLib) StartDbWithContractAndData(contractHash, data string) {
  163. dbWindow := NewDebuggerWindow(self)
  164. object := self.eth.BlockManager().CurrentState().GetStateObject(ethutil.Hex2Bytes(contractHash))
  165. if len(object.Code) > 0 {
  166. dbWindow.SetCode("0x" + ethutil.Bytes2Hex(object.Code))
  167. }
  168. dbWindow.SetData("0x" + data)
  169. dbWindow.Show()
  170. }
  171. func (self *UiLib) StartDbWithCode(code string) {
  172. dbWindow := NewDebuggerWindow(self)
  173. dbWindow.SetCode("0x" + code)
  174. dbWindow.Show()
  175. }
  176. func (self *UiLib) StartDebugger() {
  177. dbWindow := NewDebuggerWindow(self)
  178. dbWindow.Show()
  179. }
  180. func (self *UiLib) NewFilter(object map[string]interface{}) (id int) {
  181. filter := qt.NewFilterFromMap(object, self.eth)
  182. filter.MessageCallback = func(messages state.Messages) {
  183. self.win.Root().Call("invokeFilterCallback", xeth.ToJSMessages(messages), id)
  184. }
  185. id = self.eth.InstallFilter(filter)
  186. return id
  187. }
  188. func (self *UiLib) NewFilterString(typ string) (id int) {
  189. filter := core.NewFilter(self.eth)
  190. filter.BlockCallback = func(block *types.Block) {
  191. if self.win != nil && self.win.Root() != nil {
  192. self.win.Root().Call("invokeFilterCallback", "{}", id)
  193. } else {
  194. fmt.Println("QML is lagging")
  195. }
  196. }
  197. id = self.eth.InstallFilter(filter)
  198. return id
  199. }
  200. func (self *UiLib) Messages(id int) *ethutil.List {
  201. filter := self.eth.GetFilter(id)
  202. if filter != nil {
  203. messages := xeth.ToJSMessages(filter.Find())
  204. return messages
  205. }
  206. return ethutil.EmptyList()
  207. }
  208. func (self *UiLib) UninstallFilter(id int) {
  209. self.eth.UninstallFilter(id)
  210. }
  211. func mapToTxParams(object map[string]interface{}) map[string]string {
  212. // Default values
  213. if object["from"] == nil {
  214. object["from"] = ""
  215. }
  216. if object["to"] == nil {
  217. object["to"] = ""
  218. }
  219. if object["value"] == nil {
  220. object["value"] = ""
  221. }
  222. if object["gas"] == nil {
  223. object["gas"] = ""
  224. }
  225. if object["gasPrice"] == nil {
  226. object["gasPrice"] = ""
  227. }
  228. var dataStr string
  229. var data []string
  230. if list, ok := object["data"].(*qml.List); ok {
  231. list.Convert(&data)
  232. } else if str, ok := object["data"].(string); ok {
  233. data = []string{str}
  234. }
  235. for _, str := range data {
  236. if ethutil.IsHex(str) {
  237. str = str[2:]
  238. if len(str) != 64 {
  239. str = ethutil.LeftPadString(str, 64)
  240. }
  241. } else {
  242. str = ethutil.Bytes2Hex(ethutil.LeftPadBytes(ethutil.Big(str).Bytes(), 32))
  243. }
  244. dataStr += str
  245. }
  246. object["data"] = dataStr
  247. conv := make(map[string]string)
  248. for key, value := range object {
  249. if v, ok := value.(string); ok {
  250. conv[key] = v
  251. }
  252. }
  253. return conv
  254. }
  255. func (self *UiLib) Transact(params map[string]interface{}) (string, error) {
  256. object := mapToTxParams(params)
  257. return self.JSXEth.Transact(
  258. object["from"],
  259. object["to"],
  260. object["value"],
  261. object["gas"],
  262. object["gasPrice"],
  263. object["data"],
  264. )
  265. }
  266. func (self *UiLib) Compile(code string) (string, error) {
  267. bcode, err := ethutil.Compile(code, false)
  268. if err != nil {
  269. return err.Error(), err
  270. }
  271. return ethutil.Bytes2Hex(bcode), err
  272. }
  273. func (self *UiLib) Call(params map[string]interface{}) (string, error) {
  274. object := mapToTxParams(params)
  275. return self.JSXEth.Execute(
  276. object["to"],
  277. object["value"],
  278. object["gas"],
  279. object["gasPrice"],
  280. object["data"],
  281. )
  282. }
  283. func (self *UiLib) AddLocalTransaction(to, data, gas, gasPrice, value string) int {
  284. return self.miner.AddLocalTx(&miner.LocalTx{
  285. To: ethutil.Hex2Bytes(to),
  286. Data: ethutil.Hex2Bytes(data),
  287. Gas: gas,
  288. GasPrice: gasPrice,
  289. Value: value,
  290. }) - 1
  291. }
  292. func (self *UiLib) RemoveLocalTransaction(id int) {
  293. self.miner.RemoveLocalTx(id)
  294. }
  295. func (self *UiLib) SetGasPrice(price string) {
  296. self.miner.MinAcceptedGasPrice = ethutil.Big(price)
  297. }
  298. func (self *UiLib) ToggleMining() bool {
  299. if !self.miner.Mining() {
  300. self.miner.Start()
  301. return true
  302. } else {
  303. self.miner.Stop()
  304. return false
  305. }
  306. }