ui_lib.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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/chain"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/ethutil"
  28. "github.com/ethereum/go-ethereum/javascript"
  29. "github.com/ethereum/go-ethereum/miner"
  30. "github.com/ethereum/go-ethereum/state"
  31. "github.com/ethereum/go-ethereum/ui/qt"
  32. "github.com/ethereum/go-ethereum/xeth"
  33. "gopkg.in/qml.v1"
  34. )
  35. type memAddr struct {
  36. Num string
  37. Value string
  38. }
  39. // UI Library that has some basic functionality exposed
  40. type UiLib struct {
  41. *xeth.JSXEth
  42. engine *qml.Engine
  43. eth *eth.Ethereum
  44. connected bool
  45. assetPath string
  46. // The main application window
  47. win *qml.Window
  48. Db *Debugger
  49. DbWindow *DebuggerWindow
  50. jsEngine *javascript.JSRE
  51. filterCallbacks map[int][]int
  52. miner *miner.Miner
  53. }
  54. func NewUiLib(engine *qml.Engine, eth *eth.Ethereum, assetPath string) *UiLib {
  55. 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)}
  56. lib.miner = miner.New(eth.KeyManager().Address(), eth)
  57. return lib
  58. }
  59. func (self *UiLib) Notef(args []interface{}) {
  60. guilogger.Infoln(args...)
  61. }
  62. func (self *UiLib) LookupDomain(domain string) string {
  63. world := self.World()
  64. if len(domain) > 32 {
  65. domain = string(crypto.Sha3([]byte(domain)))
  66. }
  67. data := world.Config().Get("DnsReg").StorageString(domain).Bytes()
  68. // Left padded = A record, Right padded = CNAME
  69. if len(data) > 0 && data[0] == 0 {
  70. data = bytes.TrimLeft(data, "\x00")
  71. var ipSlice []string
  72. for _, d := range data {
  73. ipSlice = append(ipSlice, strconv.Itoa(int(d)))
  74. }
  75. return strings.Join(ipSlice, ".")
  76. } else {
  77. data = bytes.TrimRight(data, "\x00")
  78. return string(data)
  79. }
  80. }
  81. func (self *UiLib) LookupName(addr string) string {
  82. var (
  83. nameReg = self.World().Config().Get("NameReg")
  84. lookup = nameReg.Storage(ethutil.Hex2Bytes(addr))
  85. )
  86. if lookup.Len() != 0 {
  87. return strings.Trim(lookup.Str(), "\x00")
  88. }
  89. return addr
  90. }
  91. func (self *UiLib) LookupAddress(name string) string {
  92. var (
  93. nameReg = self.World().Config().Get("NameReg")
  94. lookup = nameReg.Storage(ethutil.RightPadBytes([]byte(name), 32))
  95. )
  96. if lookup.Len() != 0 {
  97. return ethutil.Bytes2Hex(lookup.Bytes())
  98. }
  99. return ""
  100. }
  101. func (self *UiLib) PastPeers() *ethutil.List {
  102. return ethutil.NewList(eth.PastPeers())
  103. }
  104. func (self *UiLib) ImportTx(rlpTx string) {
  105. tx := chain.NewTransactionFromBytes(ethutil.Hex2Bytes(rlpTx))
  106. self.eth.TxPool().QueueTransaction(tx)
  107. }
  108. func (self *UiLib) EvalJavascriptFile(path string) {
  109. self.jsEngine.LoadExtFile(path[7:])
  110. }
  111. func (self *UiLib) EvalJavascriptString(str string) string {
  112. value, err := self.jsEngine.Run(str)
  113. if err != nil {
  114. return err.Error()
  115. }
  116. return fmt.Sprintf("%v", value)
  117. }
  118. func (ui *UiLib) OpenQml(path string) {
  119. container := NewQmlApplication(path[7:], ui)
  120. app := NewExtApplication(container, ui)
  121. go app.run()
  122. }
  123. func (ui *UiLib) OpenHtml(path string) {
  124. container := NewHtmlApplication(path, ui)
  125. app := NewExtApplication(container, ui)
  126. go app.run()
  127. }
  128. func (ui *UiLib) OpenBrowser() {
  129. ui.OpenHtml("file://" + ui.AssetPath("ext/home.html"))
  130. }
  131. func (ui *UiLib) Muted(content string) {
  132. component, err := ui.engine.LoadFile(ui.AssetPath("qml/muted.qml"))
  133. if err != nil {
  134. guilogger.Debugln(err)
  135. return
  136. }
  137. win := component.CreateWindow(nil)
  138. go func() {
  139. path := "file://" + ui.AssetPath("muted/index.html")
  140. win.Set("url", path)
  141. win.Show()
  142. win.Wait()
  143. }()
  144. }
  145. func (ui *UiLib) Connect(button qml.Object) {
  146. if !ui.connected {
  147. ui.eth.Start(true)
  148. ui.connected = true
  149. button.Set("enabled", false)
  150. }
  151. }
  152. func (ui *UiLib) ConnectToPeer(addr string) {
  153. ui.eth.ConnectToPeer(addr)
  154. }
  155. func (ui *UiLib) AssetPath(p string) string {
  156. return path.Join(ui.assetPath, p)
  157. }
  158. func (self *UiLib) StartDbWithContractAndData(contractHash, data string) {
  159. dbWindow := NewDebuggerWindow(self)
  160. object := self.eth.BlockManager().CurrentState().GetStateObject(ethutil.Hex2Bytes(contractHash))
  161. if len(object.Code) > 0 {
  162. dbWindow.SetCode("0x" + ethutil.Bytes2Hex(object.Code))
  163. }
  164. dbWindow.SetData("0x" + data)
  165. dbWindow.Show()
  166. }
  167. func (self *UiLib) StartDbWithCode(code string) {
  168. dbWindow := NewDebuggerWindow(self)
  169. dbWindow.SetCode("0x" + code)
  170. dbWindow.Show()
  171. }
  172. func (self *UiLib) StartDebugger() {
  173. dbWindow := NewDebuggerWindow(self)
  174. dbWindow.Show()
  175. }
  176. func (self *UiLib) NewFilter(object map[string]interface{}) (id int) {
  177. filter := qt.NewFilterFromMap(object, self.eth)
  178. filter.MessageCallback = func(messages state.Messages) {
  179. self.win.Root().Call("invokeFilterCallback", xeth.ToJSMessages(messages), id)
  180. }
  181. id = self.eth.InstallFilter(filter)
  182. return id
  183. }
  184. func (self *UiLib) NewFilterString(typ string) (id int) {
  185. filter := chain.NewFilter(self.eth)
  186. filter.BlockCallback = func(block *chain.Block) {
  187. self.win.Root().Call("invokeFilterCallback", "{}", id)
  188. }
  189. id = self.eth.InstallFilter(filter)
  190. return id
  191. }
  192. func (self *UiLib) Messages(id int) *ethutil.List {
  193. filter := self.eth.GetFilter(id)
  194. if filter != nil {
  195. messages := xeth.ToJSMessages(filter.Find())
  196. return messages
  197. }
  198. return ethutil.EmptyList()
  199. }
  200. func (self *UiLib) UninstallFilter(id int) {
  201. self.eth.UninstallFilter(id)
  202. }
  203. func mapToTxParams(object map[string]interface{}) map[string]string {
  204. // Default values
  205. if object["from"] == nil {
  206. object["from"] = ""
  207. }
  208. if object["to"] == nil {
  209. object["to"] = ""
  210. }
  211. if object["value"] == nil {
  212. object["value"] = ""
  213. }
  214. if object["gas"] == nil {
  215. object["gas"] = ""
  216. }
  217. if object["gasPrice"] == nil {
  218. object["gasPrice"] = ""
  219. }
  220. var dataStr string
  221. var data []string
  222. if list, ok := object["data"].(*qml.List); ok {
  223. list.Convert(&data)
  224. } else if str, ok := object["data"].(string); ok {
  225. data = []string{str}
  226. }
  227. for _, str := range data {
  228. if ethutil.IsHex(str) {
  229. str = str[2:]
  230. if len(str) != 64 {
  231. str = ethutil.LeftPadString(str, 64)
  232. }
  233. } else {
  234. str = ethutil.Bytes2Hex(ethutil.LeftPadBytes(ethutil.Big(str).Bytes(), 32))
  235. }
  236. dataStr += str
  237. }
  238. object["data"] = dataStr
  239. conv := make(map[string]string)
  240. for key, value := range object {
  241. if v, ok := value.(string); ok {
  242. conv[key] = v
  243. }
  244. }
  245. return conv
  246. }
  247. func (self *UiLib) Transact(params map[string]interface{}) (*xeth.JSReceipt, error) {
  248. object := mapToTxParams(params)
  249. return self.JSXEth.Transact(
  250. object["from"],
  251. object["to"],
  252. object["value"],
  253. object["gas"],
  254. object["gasPrice"],
  255. object["data"],
  256. )
  257. }
  258. func (self *UiLib) Compile(code string) (string, error) {
  259. bcode, err := ethutil.Compile(code, false)
  260. if err != nil {
  261. return err.Error(), err
  262. }
  263. return ethutil.Bytes2Hex(bcode), err
  264. }
  265. func (self *UiLib) Call(params map[string]interface{}) (string, error) {
  266. object := mapToTxParams(params)
  267. return self.JSXEth.Execute(
  268. object["to"],
  269. object["value"],
  270. object["gas"],
  271. object["gasPrice"],
  272. object["data"],
  273. )
  274. }
  275. func (self *UiLib) AddLocalTransaction(to, data, gas, gasPrice, value string) int {
  276. return self.miner.AddLocalTx(&miner.LocalTx{
  277. To: ethutil.Hex2Bytes(to),
  278. Data: ethutil.Hex2Bytes(data),
  279. Gas: gas,
  280. GasPrice: gasPrice,
  281. Value: value,
  282. }) - 1
  283. }
  284. func (self *UiLib) RemoveLocalTransaction(id int) {
  285. self.miner.RemoveLocalTx(id)
  286. }
  287. func (self *UiLib) SetGasPrice(price string) {
  288. self.miner.MinAcceptedGasPrice = ethutil.Big(price)
  289. }
  290. func (self *UiLib) ToggleMining() bool {
  291. if !self.miner.Mining() {
  292. self.miner.Start()
  293. return true
  294. } else {
  295. self.miner.Stop()
  296. return false
  297. }
  298. }