gui.go 14 KB

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