gui.go 14 KB

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