gui.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. view.Call("clearAddress")
  223. nameReg := gui.pipe.World().Config().Get("NameReg")
  224. if nameReg != nil {
  225. nameReg.EachStorage(func(name string, value *ethutil.Value) {
  226. if name[0] != 0 {
  227. value.Decode()
  228. view.Call("addAddress", struct{ Name, Address string }{name, ethutil.Bytes2Hex(value.Bytes())})
  229. }
  230. })
  231. }
  232. }
  233. func (gui *Gui) insertTransaction(window string, tx *chain.Transaction) {
  234. pipe := xeth.New(gui.eth)
  235. nameReg := pipe.World().Config().Get("NameReg")
  236. addr := gui.address()
  237. var inout string
  238. if bytes.Compare(tx.Sender(), addr) == 0 {
  239. inout = "send"
  240. } else {
  241. inout = "recv"
  242. }
  243. var (
  244. ptx = xeth.NewJSTx(tx, pipe.World().State())
  245. send = nameReg.Storage(tx.Sender())
  246. rec = nameReg.Storage(tx.Recipient)
  247. s, r string
  248. )
  249. if tx.CreatesContract() {
  250. rec = nameReg.Storage(tx.CreationAddress(pipe.World().State()))
  251. }
  252. if send.Len() != 0 {
  253. s = strings.Trim(send.Str(), "\x00")
  254. } else {
  255. s = ethutil.Bytes2Hex(tx.Sender())
  256. }
  257. if rec.Len() != 0 {
  258. r = strings.Trim(rec.Str(), "\x00")
  259. } else {
  260. if tx.CreatesContract() {
  261. r = ethutil.Bytes2Hex(tx.CreationAddress(pipe.World().State()))
  262. } else {
  263. r = ethutil.Bytes2Hex(tx.Recipient)
  264. }
  265. }
  266. ptx.Sender = s
  267. ptx.Address = r
  268. if window == "post" {
  269. //gui.getObjectByName("transactionView").Call("addTx", ptx, inout)
  270. } else {
  271. gui.getObjectByName("pendingTxView").Call("addTx", ptx, inout)
  272. }
  273. }
  274. func (gui *Gui) readPreviousTransactions() {
  275. it := gui.txDb.NewIterator()
  276. for it.Next() {
  277. tx := chain.NewTransactionFromBytes(it.Value())
  278. gui.insertTransaction("post", tx)
  279. }
  280. it.Release()
  281. }
  282. func (gui *Gui) processBlock(block *chain.Block, initial bool) {
  283. name := strings.Trim(gui.pipe.World().Config().Get("NameReg").Storage(block.Coinbase).Str(), "\x00")
  284. b := xeth.NewJSBlock(block)
  285. b.Name = name
  286. gui.getObjectByName("chainView").Call("addBlock", b, initial)
  287. }
  288. func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) {
  289. var str string
  290. if unconfirmedFunds != nil {
  291. pos := "+"
  292. if unconfirmedFunds.Cmp(big.NewInt(0)) < 0 {
  293. pos = "-"
  294. }
  295. val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds)))
  296. str = fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(amount), pos, val)
  297. } else {
  298. str = fmt.Sprintf("%v", ethutil.CurrencyToString(amount))
  299. }
  300. gui.win.Root().Call("setWalletValue", str)
  301. }
  302. func (self *Gui) getObjectByName(objectName string) qml.Object {
  303. return self.win.Root().ObjectByName(objectName)
  304. }
  305. // Simple go routine function that updates the list of peers in the GUI
  306. func (gui *Gui) update() {
  307. // We have to wait for qml to be done loading all the windows.
  308. for !gui.qmlDone {
  309. time.Sleep(500 * time.Millisecond)
  310. }
  311. go func() {
  312. go gui.setInitialChainManager()
  313. gui.loadAddressBook()
  314. gui.setPeerInfo()
  315. gui.readPreviousTransactions()
  316. }()
  317. for _, plugin := range gui.plugins {
  318. guilogger.Infoln("Loading plugin ", plugin.Name)
  319. gui.win.Root().Call("addPlugin", plugin.Path, "")
  320. }
  321. peerUpdateTicker := time.NewTicker(5 * time.Second)
  322. generalUpdateTicker := time.NewTicker(500 * time.Millisecond)
  323. statsUpdateTicker := time.NewTicker(5 * time.Second)
  324. state := gui.eth.BlockManager().TransState()
  325. unconfirmedFunds := new(big.Int)
  326. gui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(state.GetAccount(gui.address()).Balance())))
  327. lastBlockLabel := gui.getObjectByName("lastBlockLabel")
  328. miningLabel := gui.getObjectByName("miningLabel")
  329. events := gui.eth.EventMux().Subscribe(
  330. eth.ChainSyncEvent{},
  331. eth.PeerListEvent{},
  332. chain.NewBlockEvent{},
  333. chain.TxPreEvent{},
  334. chain.TxPostEvent{},
  335. miner.Event{},
  336. )
  337. // nameReg := gui.pipe.World().Config().Get("NameReg")
  338. // mux.Subscribe("object:"+string(nameReg.Address()), objectChan)
  339. go func() {
  340. defer events.Unsubscribe()
  341. for {
  342. select {
  343. case ev, isopen := <-events.Chan():
  344. if !isopen {
  345. return
  346. }
  347. switch ev := ev.(type) {
  348. case chain.NewBlockEvent:
  349. gui.processBlock(ev.Block, false)
  350. if bytes.Compare(ev.Block.Coinbase, gui.address()) == 0 {
  351. gui.setWalletValue(gui.eth.BlockManager().CurrentState().GetAccount(gui.address()).Balance(), nil)
  352. }
  353. case chain.TxPreEvent:
  354. tx := ev.Tx
  355. object := state.GetAccount(gui.address())
  356. if bytes.Compare(tx.Sender(), gui.address()) == 0 {
  357. unconfirmedFunds.Sub(unconfirmedFunds, tx.Value)
  358. } else if bytes.Compare(tx.Recipient, gui.address()) == 0 {
  359. unconfirmedFunds.Add(unconfirmedFunds, tx.Value)
  360. }
  361. gui.setWalletValue(object.Balance(), unconfirmedFunds)
  362. gui.insertTransaction("pre", tx)
  363. case chain.TxPostEvent:
  364. tx := ev.Tx
  365. object := state.GetAccount(gui.address())
  366. if bytes.Compare(tx.Sender(), gui.address()) == 0 {
  367. object.SubAmount(tx.Value)
  368. //gui.getObjectByName("transactionView").Call("addTx", xeth.NewJSTx(tx), "send")
  369. gui.txDb.Put(tx.Hash(), tx.RlpEncode())
  370. } else if bytes.Compare(tx.Recipient, gui.address()) == 0 {
  371. object.AddAmount(tx.Value)
  372. //gui.getObjectByName("transactionView").Call("addTx", xeth.NewJSTx(tx), "recv")
  373. gui.txDb.Put(tx.Hash(), tx.RlpEncode())
  374. }
  375. gui.setWalletValue(object.Balance(), nil)
  376. state.UpdateStateObject(object)
  377. // case object:
  378. // gui.loadAddressBook()
  379. case eth.PeerListEvent:
  380. gui.setPeerInfo()
  381. case miner.Event:
  382. if ev.Type == miner.Started {
  383. gui.miner = ev.Miner
  384. } else {
  385. gui.miner = nil
  386. }
  387. }
  388. case <-peerUpdateTicker.C:
  389. gui.setPeerInfo()
  390. case <-generalUpdateTicker.C:
  391. statusText := "#" + gui.eth.ChainManager().CurrentBlock.Number.String()
  392. lastBlockLabel.Set("text", statusText)
  393. if gui.miner != nil {
  394. pow := gui.miner.GetPow()
  395. miningLabel.Set("text", "Mining @ "+strconv.FormatInt(pow.GetHashrate(), 10)+"Khash")
  396. }
  397. blockLength := gui.eth.BlockPool().BlocksProcessed
  398. chainLength := gui.eth.BlockPool().ChainLength
  399. var (
  400. pct float64 = 1.0 / float64(chainLength) * float64(blockLength)
  401. dlWidget = gui.win.Root().ObjectByName("downloadIndicator")
  402. dlLabel = gui.win.Root().ObjectByName("downloadLabel")
  403. )
  404. dlWidget.Set("value", pct)
  405. dlLabel.Set("text", fmt.Sprintf("%d / %d", blockLength, chainLength))
  406. case <-statsUpdateTicker.C:
  407. gui.setStatsPane()
  408. }
  409. }
  410. }()
  411. }
  412. func (gui *Gui) setStatsPane() {
  413. var memStats runtime.MemStats
  414. runtime.ReadMemStats(&memStats)
  415. statsPane := gui.getObjectByName("statsPane")
  416. statsPane.Set("text", fmt.Sprintf(`###### Mist 0.6.8 (%s) #######
  417. eth %d (p2p = %d)
  418. CPU: # %d
  419. Goroutines: # %d
  420. CGoCalls: # %d
  421. Alloc: %d
  422. Heap Alloc: %d
  423. CGNext: %x
  424. NumGC: %d
  425. `, runtime.Version(),
  426. eth.ProtocolVersion, eth.P2PVersion,
  427. runtime.NumCPU, runtime.NumGoroutine(), runtime.NumCgoCall(),
  428. memStats.Alloc, memStats.HeapAlloc,
  429. memStats.NextGC, memStats.NumGC,
  430. ))
  431. }
  432. func (gui *Gui) setPeerInfo() {
  433. gui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", gui.eth.PeerCount(), gui.eth.MaxPeers))
  434. gui.win.Root().Call("resetPeers")
  435. for _, peer := range gui.pipe.Peers() {
  436. gui.win.Root().Call("addPeer", peer)
  437. }
  438. }
  439. func (gui *Gui) privateKey() string {
  440. return ethutil.Bytes2Hex(gui.eth.KeyManager().PrivateKey())
  441. }
  442. func (gui *Gui) address() []byte {
  443. return gui.eth.KeyManager().Address()
  444. }