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