gui.go 13 KB

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