gui.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. This file is part of go-ethereum
  3. go-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. go-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @authors
  16. * Jeffrey Wilcke <i@jev.io>
  17. */
  18. package main
  19. import "C"
  20. import (
  21. "encoding/json"
  22. "fmt"
  23. "io/ioutil"
  24. "math/big"
  25. "os"
  26. "path"
  27. "runtime"
  28. "sort"
  29. "time"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/eth"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/common"
  35. "github.com/ethereum/go-ethereum/logger"
  36. "github.com/ethereum/go-ethereum/ui/qt/qwhisper"
  37. "github.com/ethereum/go-ethereum/xeth"
  38. "github.com/obscuren/qml"
  39. )
  40. var guilogger = logger.NewLogger("GUI")
  41. type ServEv byte
  42. const (
  43. setup ServEv = iota
  44. update
  45. )
  46. type Gui struct {
  47. // The main application window
  48. win *qml.Window
  49. // QML Engine
  50. engine *qml.Engine
  51. component *qml.Common
  52. // The ethereum interface
  53. eth *eth.Ethereum
  54. serviceEvents chan ServEv
  55. // The public Ethereum library
  56. uiLib *UiLib
  57. whisper *qwhisper.Whisper
  58. txDb *ethdb.LDBDatabase
  59. open bool
  60. xeth *xeth.XEth
  61. Session string
  62. plugins map[string]plugin
  63. }
  64. // Create GUI, but doesn't start it
  65. func NewWindow(ethereum *eth.Ethereum) *Gui {
  66. db, err := ethdb.NewLDBDatabase(path.Join(ethereum.DataDir, "tx_database"))
  67. if err != nil {
  68. panic(err)
  69. }
  70. xeth := xeth.New(ethereum, nil)
  71. gui := &Gui{eth: ethereum,
  72. txDb: db,
  73. xeth: xeth,
  74. open: false,
  75. plugins: make(map[string]plugin),
  76. serviceEvents: make(chan ServEv, 1),
  77. }
  78. data, _ := common.ReadAllFile(path.Join(ethereum.DataDir, "plugins.json"))
  79. json.Unmarshal([]byte(data), &gui.plugins)
  80. return gui
  81. }
  82. func (gui *Gui) Start(assetPath string) {
  83. defer gui.txDb.Close()
  84. guilogger.Infoln("Starting GUI")
  85. go gui.service()
  86. // Register ethereum functions
  87. qml.RegisterTypes("Ethereum", 1, 0, []qml.TypeSpec{{
  88. Init: func(p *xeth.Block, obj qml.Object) { p.Number = 0; p.Hash = "" },
  89. }, {
  90. Init: func(p *xeth.Transaction, obj qml.Object) { p.Value = ""; p.Hash = ""; p.Address = "" },
  91. }, {
  92. Init: func(p *xeth.KeyVal, obj qml.Object) { p.Key = ""; p.Value = "" },
  93. }})
  94. // Create a new QML engine
  95. gui.engine = qml.NewEngine()
  96. context := gui.engine.Context()
  97. gui.uiLib = NewUiLib(gui.engine, gui.eth, assetPath)
  98. gui.whisper = qwhisper.New(gui.eth.Whisper())
  99. // Expose the eth library and the ui library to QML
  100. context.SetVar("gui", gui)
  101. context.SetVar("eth", gui.uiLib)
  102. context.SetVar("shh", gui.whisper)
  103. //clipboard.SetQMLClipboard(context)
  104. win, err := gui.showWallet(context)
  105. if err != nil {
  106. guilogger.Errorln("asset not found: you can set an alternative asset path on the command line using option 'asset_path'", err)
  107. panic(err)
  108. }
  109. gui.open = true
  110. win.Show()
  111. win.Wait()
  112. gui.open = false
  113. }
  114. func (gui *Gui) Stop() {
  115. if gui.open {
  116. gui.open = false
  117. gui.win.Hide()
  118. }
  119. guilogger.Infoln("Stopped")
  120. }
  121. func (gui *Gui) showWallet(context *qml.Context) (*qml.Window, error) {
  122. component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/main.qml"))
  123. if err != nil {
  124. return nil, err
  125. }
  126. gui.createWindow(component)
  127. return gui.win, nil
  128. }
  129. func (gui *Gui) GenerateKey() {
  130. _, err := gui.eth.AccountManager().NewAccount("hurr")
  131. if err != nil {
  132. // TODO: UI feedback?
  133. }
  134. }
  135. func (gui *Gui) showKeyImport(context *qml.Context) (*qml.Window, error) {
  136. context.SetVar("lib", gui)
  137. component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/first_run.qml"))
  138. if err != nil {
  139. return nil, err
  140. }
  141. return gui.createWindow(component), nil
  142. }
  143. func (gui *Gui) createWindow(comp qml.Object) *qml.Window {
  144. gui.win = comp.CreateWindow(nil)
  145. gui.uiLib.win = gui.win
  146. return gui.win
  147. }
  148. func (gui *Gui) setInitialChain(ancientBlocks bool) {
  149. sBlk := gui.eth.ChainManager().LastBlockHash()
  150. blk := gui.eth.ChainManager().GetBlock(sBlk)
  151. for ; blk != nil; blk = gui.eth.ChainManager().GetBlock(sBlk) {
  152. sBlk = blk.ParentHash()
  153. gui.processBlock(blk, true)
  154. }
  155. }
  156. func (gui *Gui) loadAddressBook() {
  157. /*
  158. view := gui.getObjectByName("infoView")
  159. nameReg := gui.xeth.World().Config().Get("NameReg")
  160. if nameReg != nil {
  161. it := nameReg.Trie().Iterator()
  162. for it.Next() {
  163. if it.Key[0] != 0 {
  164. view.Call("addAddress", struct{ Name, Address string }{string(it.Key), common.Bytes2Hex(it.Value)})
  165. }
  166. }
  167. }
  168. */
  169. }
  170. func (self *Gui) loadMergedMiningOptions() {
  171. /*
  172. view := self.getObjectByName("mergedMiningModel")
  173. mergeMining := self.xeth.World().Config().Get("MergeMining")
  174. if mergeMining != nil {
  175. i := 0
  176. it := mergeMining.Trie().Iterator()
  177. for it.Next() {
  178. view.Call("addMergedMiningOption", struct {
  179. Checked bool
  180. Name, Address string
  181. Id, ItemId int
  182. }{false, string(it.Key), common.Bytes2Hex(it.Value), 0, i})
  183. i++
  184. }
  185. }
  186. */
  187. }
  188. func (gui *Gui) insertTransaction(window string, tx *types.Transaction) {
  189. var inout string
  190. if gui.eth.AccountManager().HasAccount(tx.From()) {
  191. inout = "send"
  192. } else {
  193. inout = "recv"
  194. }
  195. var (
  196. ptx = xeth.NewTx(tx)
  197. send = common.Bytes2Hex(tx.From())
  198. rec = common.Bytes2Hex(tx.To())
  199. )
  200. ptx.Sender = send
  201. ptx.Address = rec
  202. if window == "post" {
  203. //gui.getObjectByName("transactionView").Call("addTx", ptx, inout)
  204. } else {
  205. gui.getObjectByName("pendingTxView").Call("addTx", ptx, inout)
  206. }
  207. }
  208. func (gui *Gui) readPreviousTransactions() {
  209. it := gui.txDb.NewIterator()
  210. for it.Next() {
  211. tx := types.NewTransactionFromBytes(it.Value())
  212. gui.insertTransaction("post", tx)
  213. }
  214. it.Release()
  215. }
  216. func (gui *Gui) processBlock(block *types.Block, initial bool) {
  217. name := common.Bytes2Hex(block.Coinbase())
  218. b := xeth.NewBlock(block)
  219. b.Name = name
  220. gui.getObjectByName("chainView").Call("addBlock", b, initial)
  221. }
  222. func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) {
  223. var str string
  224. if unconfirmedFunds != nil {
  225. pos := "+"
  226. if unconfirmedFunds.Cmp(big.NewInt(0)) < 0 {
  227. pos = "-"
  228. }
  229. val := common.CurrencyToString(new(big.Int).Abs(common.BigCopy(unconfirmedFunds)))
  230. str = fmt.Sprintf("%v (%s %v)", common.CurrencyToString(amount), pos, val)
  231. } else {
  232. str = fmt.Sprintf("%v", common.CurrencyToString(amount))
  233. }
  234. gui.win.Root().Call("setWalletValue", str)
  235. }
  236. func (self *Gui) getObjectByName(objectName string) qml.Object {
  237. return self.win.Root().ObjectByName(objectName)
  238. }
  239. func loadJavascriptAssets(gui *Gui) (jsfiles string) {
  240. for _, fn := range []string{"ext/q.js", "ext/eth.js/main.js", "ext/eth.js/qt.js", "ext/setup.js"} {
  241. f, err := os.Open(gui.uiLib.AssetPath(fn))
  242. if err != nil {
  243. fmt.Println(err)
  244. continue
  245. }
  246. content, err := ioutil.ReadAll(f)
  247. if err != nil {
  248. fmt.Println(err)
  249. continue
  250. }
  251. jsfiles += string(content)
  252. }
  253. return
  254. }
  255. func (gui *Gui) SendCommand(cmd ServEv) {
  256. gui.serviceEvents <- cmd
  257. }
  258. func (gui *Gui) service() {
  259. for ev := range gui.serviceEvents {
  260. switch ev {
  261. case setup:
  262. go gui.setup()
  263. case update:
  264. go gui.update()
  265. }
  266. }
  267. }
  268. func (gui *Gui) setup() {
  269. for gui.win == nil {
  270. time.Sleep(time.Millisecond * 200)
  271. }
  272. for _, plugin := range gui.plugins {
  273. guilogger.Infoln("Loading plugin ", plugin.Name)
  274. gui.win.Root().Call("addPlugin", plugin.Path, "")
  275. }
  276. go func() {
  277. go gui.setInitialChain(false)
  278. gui.loadAddressBook()
  279. gui.loadMergedMiningOptions()
  280. gui.setPeerInfo()
  281. }()
  282. gui.whisper.SetView(gui.getObjectByName("whisperView"))
  283. gui.SendCommand(update)
  284. }
  285. // Simple go routine function that updates the list of peers in the GUI
  286. func (gui *Gui) update() {
  287. peerUpdateTicker := time.NewTicker(5 * time.Second)
  288. generalUpdateTicker := time.NewTicker(500 * time.Millisecond)
  289. statsUpdateTicker := time.NewTicker(5 * time.Second)
  290. lastBlockLabel := gui.getObjectByName("lastBlockLabel")
  291. //miningLabel := gui.getObjectByName("miningLabel")
  292. events := gui.eth.EventMux().Subscribe(
  293. core.ChainEvent{},
  294. core.TxPreEvent{},
  295. core.TxPostEvent{},
  296. )
  297. defer events.Unsubscribe()
  298. for {
  299. select {
  300. case ev, isopen := <-events.Chan():
  301. if !isopen {
  302. return
  303. }
  304. switch ev := ev.(type) {
  305. case core.ChainEvent:
  306. gui.processBlock(ev.Block, false)
  307. case core.TxPreEvent:
  308. gui.insertTransaction("pre", ev.Tx)
  309. case core.TxPostEvent:
  310. gui.getObjectByName("pendingTxView").Call("removeTx", xeth.NewTx(ev.Tx))
  311. }
  312. case <-peerUpdateTicker.C:
  313. gui.setPeerInfo()
  314. case <-generalUpdateTicker.C:
  315. statusText := "#" + gui.eth.ChainManager().CurrentBlock().Number().String()
  316. lastBlockLabel.Set("text", statusText)
  317. //miningLabel.Set("text", strconv.FormatInt(gui.uiLib.Miner().HashRate(), 10))
  318. case <-statsUpdateTicker.C:
  319. gui.setStatsPane()
  320. }
  321. }
  322. }
  323. func (gui *Gui) setStatsPane() {
  324. var memStats runtime.MemStats
  325. runtime.ReadMemStats(&memStats)
  326. statsPane := gui.getObjectByName("statsPane")
  327. statsPane.Set("text", fmt.Sprintf(`###### Mist %s (%s) #######
  328. eth %d (p2p = %d)
  329. CPU: # %d
  330. Goroutines: # %d
  331. CGoCalls: # %d
  332. Alloc: %d
  333. Heap Alloc: %d
  334. CGNext: %x
  335. NumGC: %d
  336. `, Version, runtime.Version(),
  337. eth.ProtocolVersion, 2,
  338. runtime.NumCPU, runtime.NumGoroutine(), runtime.NumCgoCall(),
  339. memStats.Alloc, memStats.HeapAlloc,
  340. memStats.NextGC, memStats.NumGC,
  341. ))
  342. }
  343. type qmlpeer struct{ Addr, NodeID, Name, Caps string }
  344. type peersByID []*qmlpeer
  345. func (s peersByID) Len() int { return len(s) }
  346. func (s peersByID) Less(i, j int) bool { return s[i].NodeID < s[j].NodeID }
  347. func (s peersByID) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  348. func (gui *Gui) setPeerInfo() {
  349. peers := gui.eth.Peers()
  350. qpeers := make(peersByID, len(peers))
  351. for i, p := range peers {
  352. qpeers[i] = &qmlpeer{
  353. NodeID: p.ID().String(),
  354. Addr: p.RemoteAddr().String(),
  355. Name: p.Name(),
  356. Caps: fmt.Sprint(p.Caps()),
  357. }
  358. }
  359. // we need to sort the peers because they jump around randomly
  360. // otherwise. order returned by eth.Peers is random because they
  361. // are taken from a map.
  362. sort.Sort(qpeers)
  363. gui.win.Root().Call("setPeerCounters", fmt.Sprintf("%d / %d", len(peers), gui.eth.MaxPeers()))
  364. gui.win.Root().Call("clearPeers")
  365. for _, p := range qpeers {
  366. gui.win.Root().Call("addPeer", p)
  367. }
  368. }
  369. /*
  370. func LoadExtension(path string) (uintptr, error) {
  371. lib, err := ffi.NewLibrary(path)
  372. if err != nil {
  373. return 0, err
  374. }
  375. so, err := lib.Fct("sharedObject", ffi.Pointer, nil)
  376. if err != nil {
  377. return 0, err
  378. }
  379. ptr := so()
  380. err = lib.Close()
  381. if err != nil {
  382. return 0, err
  383. }
  384. return ptr.Interface().(uintptr), nil
  385. }
  386. */
  387. /*
  388. vec, errr := LoadExtension("/Users/jeffrey/Desktop/build-libqmltest-Desktop_Qt_5_2_1_clang_64bit-Debug/liblibqmltest_debug.dylib")
  389. fmt.Printf("Fetched vec with addr: %#x\n", vec)
  390. if errr != nil {
  391. fmt.Println(errr)
  392. } else {
  393. context.SetVar("vec", (unsafe.Pointer)(vec))
  394. }
  395. */