gui.go 15 KB

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