gui.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. "bytes"
  22. "encoding/json"
  23. "fmt"
  24. "io/ioutil"
  25. "math/big"
  26. "os"
  27. "path"
  28. "runtime"
  29. "strconv"
  30. "time"
  31. "github.com/ethereum/go-ethereum/core"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/eth"
  34. "github.com/ethereum/go-ethereum/ethdb"
  35. "github.com/ethereum/go-ethereum/ethutil"
  36. "github.com/ethereum/go-ethereum/logger"
  37. "github.com/ethereum/go-ethereum/miner"
  38. "github.com/ethereum/go-ethereum/p2p"
  39. "github.com/ethereum/go-ethereum/ui/qt/qwhisper"
  40. "github.com/ethereum/go-ethereum/xeth"
  41. "gopkg.in/qml.v1"
  42. )
  43. var guilogger = logger.NewLogger("GUI")
  44. type ServEv byte
  45. const (
  46. setup ServEv = iota
  47. update
  48. )
  49. type Gui struct {
  50. // The main application window
  51. win *qml.Window
  52. // QML Engine
  53. engine *qml.Engine
  54. component *qml.Common
  55. // The ethereum interface
  56. eth *eth.Ethereum
  57. serviceEvents chan ServEv
  58. // The public Ethereum library
  59. uiLib *UiLib
  60. whisper *qwhisper.Whisper
  61. txDb *ethdb.LDBDatabase
  62. logLevel logger.LogLevel
  63. open bool
  64. xeth *xeth.JSXEth
  65. Session string
  66. clientIdentity *p2p.SimpleClientIdentity
  67. config *ethutil.ConfigManager
  68. plugins map[string]plugin
  69. miner *miner.Miner
  70. }
  71. // Create GUI, but doesn't start it
  72. func NewWindow(ethereum *eth.Ethereum, config *ethutil.ConfigManager, clientIdentity *p2p.SimpleClientIdentity, session string, logLevel int) *Gui {
  73. db, err := ethdb.NewLDBDatabase("tx_database")
  74. if err != nil {
  75. panic(err)
  76. }
  77. xeth := xeth.NewJSXEth(ethereum)
  78. gui := &Gui{eth: ethereum,
  79. txDb: db,
  80. xeth: xeth,
  81. logLevel: logger.LogLevel(logLevel),
  82. Session: session,
  83. open: false,
  84. clientIdentity: clientIdentity,
  85. config: config,
  86. plugins: make(map[string]plugin),
  87. serviceEvents: make(chan ServEv, 1),
  88. }
  89. data, _ := ethutil.ReadAllFile(path.Join(ethutil.Config.ExecPath, "plugins.json"))
  90. json.Unmarshal([]byte(data), &gui.plugins)
  91. return gui
  92. }
  93. func (gui *Gui) Start(assetPath string) {
  94. defer gui.txDb.Close()
  95. guilogger.Infoln("Starting GUI")
  96. go gui.service()
  97. // Register ethereum functions
  98. qml.RegisterTypes("Ethereum", 1, 0, []qml.TypeSpec{{
  99. Init: func(p *xeth.JSBlock, obj qml.Object) { p.Number = 0; p.Hash = "" },
  100. }, {
  101. Init: func(p *xeth.JSTransaction, obj qml.Object) { p.Value = ""; p.Hash = ""; p.Address = "" },
  102. }, {
  103. Init: func(p *xeth.KeyVal, obj qml.Object) { p.Key = ""; p.Value = "" },
  104. }})
  105. // Create a new QML engine
  106. gui.engine = qml.NewEngine()
  107. context := gui.engine.Context()
  108. gui.uiLib = NewUiLib(gui.engine, gui.eth, assetPath)
  109. gui.whisper = qwhisper.New(gui.eth.Whisper())
  110. // Expose the eth library and the ui library to QML
  111. context.SetVar("gui", gui)
  112. context.SetVar("eth", gui.uiLib)
  113. context.SetVar("shh", gui.whisper)
  114. win, err := gui.showWallet(context)
  115. if err != nil {
  116. guilogger.Errorln("asset not found: you can set an alternative asset path on the command line using option 'asset_path'", err)
  117. panic(err)
  118. }
  119. gui.open = true
  120. win.Show()
  121. // only add the gui guilogger after window is shown otherwise slider wont be shown
  122. logger.AddLogSystem(gui)
  123. win.Wait()
  124. // need to silence gui guilogger after window closed otherwise logsystem hangs (but do not save loglevel)
  125. gui.logLevel = logger.Silence
  126. gui.open = false
  127. }
  128. func (gui *Gui) Stop() {
  129. if gui.open {
  130. gui.logLevel = logger.Silence
  131. gui.open = false
  132. gui.win.Hide()
  133. }
  134. gui.uiLib.jsEngine.Stop()
  135. guilogger.Infoln("Stopped")
  136. }
  137. func (gui *Gui) showWallet(context *qml.Context) (*qml.Window, error) {
  138. component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/main.qml"))
  139. if err != nil {
  140. return nil, err
  141. }
  142. gui.createWindow(component)
  143. return gui.win, nil
  144. }
  145. func (gui *Gui) ImportKey(filePath string) {
  146. }
  147. func (gui *Gui) showKeyImport(context *qml.Context) (*qml.Window, error) {
  148. context.SetVar("lib", gui)
  149. component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/first_run.qml"))
  150. if err != nil {
  151. return nil, err
  152. }
  153. return gui.createWindow(component), nil
  154. }
  155. func (gui *Gui) createWindow(comp qml.Object) *qml.Window {
  156. gui.win = comp.CreateWindow(nil)
  157. gui.uiLib.win = gui.win
  158. return gui.win
  159. }
  160. func (gui *Gui) ImportAndSetPrivKey(secret string) bool {
  161. err := gui.eth.KeyManager().InitFromString(gui.Session, 0, secret)
  162. if err != nil {
  163. guilogger.Errorln("unable to import: ", err)
  164. return false
  165. }
  166. guilogger.Errorln("successfully imported: ", err)
  167. return true
  168. }
  169. func (gui *Gui) CreateAndSetPrivKey() (string, string, string, string) {
  170. err := gui.eth.KeyManager().Init(gui.Session, 0, true)
  171. if err != nil {
  172. guilogger.Errorln("unable to create key: ", err)
  173. return "", "", "", ""
  174. }
  175. return gui.eth.KeyManager().KeyPair().AsStrings()
  176. }
  177. func (gui *Gui) setInitialChain(ancientBlocks bool) {
  178. sBlk := gui.eth.ChainManager().LastBlockHash()
  179. blk := gui.eth.ChainManager().GetBlock(sBlk)
  180. for ; blk != nil; blk = gui.eth.ChainManager().GetBlock(sBlk) {
  181. sBlk = blk.ParentHash()
  182. gui.processBlock(blk, true)
  183. }
  184. }
  185. func (gui *Gui) loadAddressBook() {
  186. /*
  187. view := gui.getObjectByName("infoView")
  188. nameReg := gui.xeth.World().Config().Get("NameReg")
  189. if nameReg != nil {
  190. it := nameReg.Trie().Iterator()
  191. for it.Next() {
  192. if it.Key[0] != 0 {
  193. view.Call("addAddress", struct{ Name, Address string }{string(it.Key), ethutil.Bytes2Hex(it.Value)})
  194. }
  195. }
  196. }
  197. */
  198. }
  199. func (self *Gui) loadMergedMiningOptions() {
  200. /*
  201. view := self.getObjectByName("mergedMiningModel")
  202. mergeMining := self.xeth.World().Config().Get("MergeMining")
  203. if mergeMining != nil {
  204. i := 0
  205. it := mergeMining.Trie().Iterator()
  206. for it.Next() {
  207. view.Call("addMergedMiningOption", struct {
  208. Checked bool
  209. Name, Address string
  210. Id, ItemId int
  211. }{false, string(it.Key), ethutil.Bytes2Hex(it.Value), 0, i})
  212. i++
  213. }
  214. }
  215. */
  216. }
  217. func (gui *Gui) insertTransaction(window string, tx *types.Transaction) {
  218. addr := gui.address()
  219. var inout string
  220. if bytes.Compare(tx.From(), addr) == 0 {
  221. inout = "send"
  222. } else {
  223. inout = "recv"
  224. }
  225. var (
  226. ptx = xeth.NewJSTx(tx)
  227. send = ethutil.Bytes2Hex(tx.From())
  228. rec = ethutil.Bytes2Hex(tx.To())
  229. )
  230. ptx.Sender = send
  231. ptx.Address = rec
  232. if window == "post" {
  233. //gui.getObjectByName("transactionView").Call("addTx", ptx, inout)
  234. } else {
  235. gui.getObjectByName("pendingTxView").Call("addTx", ptx, inout)
  236. }
  237. }
  238. func (gui *Gui) readPreviousTransactions() {
  239. it := gui.txDb.NewIterator()
  240. for it.Next() {
  241. tx := types.NewTransactionFromBytes(it.Value())
  242. gui.insertTransaction("post", tx)
  243. }
  244. it.Release()
  245. }
  246. func (gui *Gui) processBlock(block *types.Block, initial bool) {
  247. name := ethutil.Bytes2Hex(block.Coinbase())
  248. b := xeth.NewJSBlock(block)
  249. b.Name = name
  250. gui.getObjectByName("chainView").Call("addBlock", b, initial)
  251. }
  252. func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) {
  253. var str string
  254. if unconfirmedFunds != nil {
  255. pos := "+"
  256. if unconfirmedFunds.Cmp(big.NewInt(0)) < 0 {
  257. pos = "-"
  258. }
  259. val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds)))
  260. str = fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(amount), pos, val)
  261. } else {
  262. str = fmt.Sprintf("%v", ethutil.CurrencyToString(amount))
  263. }
  264. gui.win.Root().Call("setWalletValue", str)
  265. }
  266. func (self *Gui) getObjectByName(objectName string) qml.Object {
  267. return self.win.Root().ObjectByName(objectName)
  268. }
  269. func loadJavascriptAssets(gui *Gui) (jsfiles string) {
  270. for _, fn := range []string{"ext/q.js", "ext/eth.js/main.js", "ext/eth.js/qt.js", "ext/setup.js"} {
  271. f, err := os.Open(gui.uiLib.AssetPath(fn))
  272. if err != nil {
  273. fmt.Println(err)
  274. continue
  275. }
  276. content, err := ioutil.ReadAll(f)
  277. if err != nil {
  278. fmt.Println(err)
  279. continue
  280. }
  281. jsfiles += string(content)
  282. }
  283. return
  284. }
  285. func (gui *Gui) SendCommand(cmd ServEv) {
  286. gui.serviceEvents <- cmd
  287. }
  288. func (gui *Gui) service() {
  289. for ev := range gui.serviceEvents {
  290. switch ev {
  291. case setup:
  292. go gui.setup()
  293. case update:
  294. go gui.update()
  295. }
  296. }
  297. }
  298. func (gui *Gui) setup() {
  299. for gui.win == nil {
  300. time.Sleep(time.Millisecond * 200)
  301. }
  302. for _, plugin := range gui.plugins {
  303. guilogger.Infoln("Loading plugin ", plugin.Name)
  304. gui.win.Root().Call("addPlugin", plugin.Path, "")
  305. }
  306. go func() {
  307. go gui.setInitialChain(false)
  308. gui.loadAddressBook()
  309. gui.loadMergedMiningOptions()
  310. gui.setPeerInfo()
  311. }()
  312. // Inject javascript files each time navigation is requested.
  313. // Unfortunately webview.experimental.userScripts injects _after_
  314. // the page has loaded which kind of renders it useless...
  315. //jsfiles := loadJavascriptAssets(gui)
  316. gui.getObjectByName("webView").On("navigationRequested", func() {
  317. //gui.getObjectByName("webView").Call("injectJs", jsfiles)
  318. })
  319. gui.whisper.SetView(gui.getObjectByName("whisperView"))
  320. gui.SendCommand(update)
  321. }
  322. // Simple go routine function that updates the list of peers in the GUI
  323. func (gui *Gui) update() {
  324. peerUpdateTicker := time.NewTicker(5 * time.Second)
  325. generalUpdateTicker := time.NewTicker(500 * time.Millisecond)
  326. statsUpdateTicker := time.NewTicker(5 * time.Second)
  327. state := gui.eth.ChainManager().TransState()
  328. gui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(state.GetAccount(gui.address()).Balance())))
  329. lastBlockLabel := gui.getObjectByName("lastBlockLabel")
  330. miningLabel := gui.getObjectByName("miningLabel")
  331. events := gui.eth.EventMux().Subscribe(
  332. //eth.PeerListEvent{},
  333. core.NewBlockEvent{},
  334. core.TxPreEvent{},
  335. core.TxPostEvent{},
  336. )
  337. defer events.Unsubscribe()
  338. for {
  339. select {
  340. case ev, isopen := <-events.Chan():
  341. if !isopen {
  342. return
  343. }
  344. switch ev := ev.(type) {
  345. case core.NewBlockEvent:
  346. gui.processBlock(ev.Block, false)
  347. if bytes.Compare(ev.Block.Coinbase(), gui.address()) == 0 {
  348. gui.setWalletValue(gui.eth.ChainManager().State().GetBalance(gui.address()), nil)
  349. }
  350. case core.TxPreEvent:
  351. tx := ev.Tx
  352. tstate := gui.eth.ChainManager().TransState()
  353. cstate := gui.eth.ChainManager().State()
  354. taccount := tstate.GetAccount(gui.address())
  355. caccount := cstate.GetAccount(gui.address())
  356. unconfirmedFunds := new(big.Int).Sub(taccount.Balance(), caccount.Balance())
  357. gui.setWalletValue(taccount.Balance(), unconfirmedFunds)
  358. gui.insertTransaction("pre", tx)
  359. case core.TxPostEvent:
  360. tx := ev.Tx
  361. object := state.GetAccount(gui.address())
  362. if bytes.Compare(tx.From(), gui.address()) == 0 {
  363. object.SubAmount(tx.Value())
  364. gui.txDb.Put(tx.Hash(), tx.RlpEncode())
  365. } else if bytes.Compare(tx.To(), gui.address()) == 0 {
  366. object.AddAmount(tx.Value())
  367. gui.txDb.Put(tx.Hash(), tx.RlpEncode())
  368. }
  369. gui.setWalletValue(object.Balance(), nil)
  370. state.UpdateStateObject(object)
  371. }
  372. case <-peerUpdateTicker.C:
  373. gui.setPeerInfo()
  374. case <-generalUpdateTicker.C:
  375. statusText := "#" + gui.eth.ChainManager().CurrentBlock().Number().String()
  376. lastBlockLabel.Set("text", statusText)
  377. miningLabel.Set("text", "Mining @ "+strconv.FormatInt(gui.uiLib.miner.GetPow().GetHashrate(), 10)+"Khash")
  378. /*
  379. blockLength := gui.eth.BlockPool().BlocksProcessed
  380. chainLength := gui.eth.BlockPool().ChainLength
  381. var (
  382. pct float64 = 1.0 / float64(chainLength) * float64(blockLength)
  383. dlWidget = gui.win.Root().ObjectByName("downloadIndicator")
  384. dlLabel = gui.win.Root().ObjectByName("downloadLabel")
  385. )
  386. dlWidget.Set("value", pct)
  387. dlLabel.Set("text", fmt.Sprintf("%d / %d", blockLength, chainLength))
  388. */
  389. case <-statsUpdateTicker.C:
  390. gui.setStatsPane()
  391. }
  392. }
  393. }
  394. func (gui *Gui) setStatsPane() {
  395. var memStats runtime.MemStats
  396. runtime.ReadMemStats(&memStats)
  397. statsPane := gui.getObjectByName("statsPane")
  398. statsPane.Set("text", fmt.Sprintf(`###### Mist %s (%s) #######
  399. eth %d (p2p = %d)
  400. CPU: # %d
  401. Goroutines: # %d
  402. CGoCalls: # %d
  403. Alloc: %d
  404. Heap Alloc: %d
  405. CGNext: %x
  406. NumGC: %d
  407. `, Version, runtime.Version(),
  408. eth.ProtocolVersion, 2,
  409. runtime.NumCPU, runtime.NumGoroutine(), runtime.NumCgoCall(),
  410. memStats.Alloc, memStats.HeapAlloc,
  411. memStats.NextGC, memStats.NumGC,
  412. ))
  413. }
  414. func (gui *Gui) setPeerInfo() {
  415. gui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", gui.eth.PeerCount(), gui.eth.MaxPeers))
  416. gui.win.Root().Call("resetPeers")
  417. //for _, peer := range gui.xeth.Peers() {
  418. //gui.win.Root().Call("addPeer", peer)
  419. //}
  420. }
  421. func (gui *Gui) privateKey() string {
  422. return ethutil.Bytes2Hex(gui.eth.KeyManager().PrivateKey())
  423. }
  424. func (gui *Gui) address() []byte {
  425. return gui.eth.KeyManager().Address()
  426. }
  427. /*
  428. func LoadExtension(path string) (uintptr, error) {
  429. lib, err := ffi.NewLibrary(path)
  430. if err != nil {
  431. return 0, err
  432. }
  433. so, err := lib.Fct("sharedObject", ffi.Pointer, nil)
  434. if err != nil {
  435. return 0, err
  436. }
  437. ptr := so()
  438. err = lib.Close()
  439. if err != nil {
  440. return 0, err
  441. }
  442. return ptr.Interface().(uintptr), nil
  443. }
  444. */
  445. /*
  446. vec, errr := LoadExtension("/Users/jeffrey/Desktop/build-libqmltest-Desktop_Qt_5_2_1_clang_64bit-Debug/liblibqmltest_debug.dylib")
  447. fmt.Printf("Fetched vec with addr: %#x\n", vec)
  448. if errr != nil {
  449. fmt.Println(errr)
  450. } else {
  451. context.SetVar("vec", (unsafe.Pointer)(vec))
  452. }
  453. */