gui.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package ethui
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/ethereum/eth-go"
  6. "github.com/ethereum/eth-go/ethchain"
  7. "github.com/ethereum/eth-go/ethdb"
  8. "github.com/ethereum/eth-go/ethlog"
  9. "github.com/ethereum/eth-go/ethpub"
  10. "github.com/ethereum/eth-go/ethutil"
  11. "github.com/ethereum/go-ethereum/utils"
  12. "github.com/go-qml/qml"
  13. "math/big"
  14. "strings"
  15. "time"
  16. )
  17. var logger = ethlog.NewLogger("GUI")
  18. type Gui struct {
  19. // The main application window
  20. win *qml.Window
  21. // QML Engine
  22. engine *qml.Engine
  23. component *qml.Common
  24. // The ethereum interface
  25. eth *eth.Ethereum
  26. // The public Ethereum library
  27. uiLib *UiLib
  28. txDb *ethdb.LDBDatabase
  29. pub *ethpub.PEthereum
  30. logLevel ethlog.LogLevel
  31. open bool
  32. Session string
  33. }
  34. // Create GUI, but doesn't start it
  35. func New(ethereum *eth.Ethereum, session string, logLevel int) *Gui {
  36. db, err := ethdb.NewLDBDatabase("tx_database")
  37. if err != nil {
  38. panic(err)
  39. }
  40. pub := ethpub.NewPEthereum(ethereum)
  41. return &Gui{eth: ethereum, txDb: db, pub: pub, logLevel: ethlog.LogLevel(logLevel), Session: session, open: false}
  42. }
  43. func (gui *Gui) Start(assetPath string) {
  44. const version = "0.5.0 RC15"
  45. defer gui.txDb.Close()
  46. // Register ethereum functions
  47. qml.RegisterTypes("Ethereum", 1, 0, []qml.TypeSpec{{
  48. Init: func(p *ethpub.PBlock, obj qml.Object) { p.Number = 0; p.Hash = "" },
  49. }, {
  50. Init: func(p *ethpub.PTx, obj qml.Object) { p.Value = ""; p.Hash = ""; p.Address = "" },
  51. }, {
  52. Init: func(p *ethpub.KeyVal, obj qml.Object) { p.Key = ""; p.Value = "" },
  53. }})
  54. ethutil.Config.SetClientString("Ethereal")
  55. // Create a new QML engine
  56. gui.engine = qml.NewEngine()
  57. context := gui.engine.Context()
  58. // Expose the eth library and the ui library to QML
  59. context.SetVar("eth", gui)
  60. context.SetVar("pub", gui.pub)
  61. gui.uiLib = NewUiLib(gui.engine, gui.eth, assetPath)
  62. context.SetVar("ui", gui.uiLib)
  63. // Load the main QML interface
  64. data, _ := ethutil.Config.Db.Get([]byte("KeyRing"))
  65. var win *qml.Window
  66. var err error
  67. var addlog = false
  68. if len(data) == 0 {
  69. win, err = gui.showKeyImport(context)
  70. } else {
  71. win, err = gui.showWallet(context)
  72. addlog = true
  73. }
  74. if err != nil {
  75. logger.Errorln("asset not found: you can set an alternative asset path on the command line using option 'asset_path'", err)
  76. panic(err)
  77. }
  78. logger.Infoln("Starting GUI")
  79. gui.open = true
  80. win.Show()
  81. // only add the gui logger after window is shown otherwise slider wont be shown
  82. if addlog {
  83. ethlog.AddLogSystem(gui)
  84. }
  85. win.Wait()
  86. // need to silence gui logger after window closed otherwise logsystem hangs
  87. gui.SetLogLevel(ethlog.Silence)
  88. gui.open = false
  89. }
  90. func (gui *Gui) Stop() {
  91. if gui.open {
  92. gui.SetLogLevel(ethlog.Silence)
  93. gui.open = false
  94. gui.win.Hide()
  95. }
  96. logger.Infoln("Stopped")
  97. }
  98. func (gui *Gui) ToggleMining() {
  99. var txt string
  100. if gui.eth.Mining {
  101. utils.StopMining(gui.eth)
  102. txt = "Start mining"
  103. } else {
  104. utils.StartMining(gui.eth)
  105. txt = "Stop mining"
  106. }
  107. gui.win.Root().Set("miningButtonText", txt)
  108. }
  109. func (gui *Gui) showWallet(context *qml.Context) (*qml.Window, error) {
  110. component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/wallet.qml"))
  111. if err != nil {
  112. return nil, err
  113. }
  114. win := gui.createWindow(component)
  115. gui.setInitialBlockChain()
  116. gui.loadAddressBook()
  117. gui.readPreviousTransactions()
  118. gui.setPeerInfo()
  119. go gui.update()
  120. return win, nil
  121. }
  122. func (gui *Gui) showKeyImport(context *qml.Context) (*qml.Window, error) {
  123. context.SetVar("lib", gui)
  124. component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/first_run.qml"))
  125. if err != nil {
  126. return nil, err
  127. }
  128. return gui.createWindow(component), nil
  129. }
  130. func (gui *Gui) createWindow(comp qml.Object) *qml.Window {
  131. win := comp.CreateWindow(nil)
  132. gui.win = win
  133. gui.uiLib.win = win
  134. return gui.win
  135. }
  136. func (gui *Gui) ImportAndSetPrivKey(secret string) bool {
  137. err := gui.eth.KeyManager().InitFromString(gui.Session, 0, secret)
  138. if err != nil {
  139. logger.Errorln("unable to import: ", err)
  140. return false
  141. }
  142. logger.Errorln("successfully imported: ", err)
  143. return true
  144. }
  145. func (gui *Gui) CreateAndSetPrivKey() (string, string, string, string) {
  146. err := gui.eth.KeyManager().Init(gui.Session, 0, true)
  147. if err != nil {
  148. logger.Errorln("unable to create key: ", err)
  149. return "", "", "", ""
  150. }
  151. return gui.eth.KeyManager().KeyPair().AsStrings()
  152. }
  153. func (gui *Gui) setInitialBlockChain() {
  154. sBlk := gui.eth.BlockChain().LastBlockHash
  155. blk := gui.eth.BlockChain().GetBlock(sBlk)
  156. for ; blk != nil; blk = gui.eth.BlockChain().GetBlock(sBlk) {
  157. sBlk = blk.PrevHash
  158. addr := gui.address()
  159. // Loop through all transactions to see if we missed any while being offline
  160. for _, tx := range blk.Transactions() {
  161. if bytes.Compare(tx.Sender(), addr) == 0 || bytes.Compare(tx.Recipient, addr) == 0 {
  162. if ok, _ := gui.txDb.Get(tx.Hash()); ok == nil {
  163. gui.txDb.Put(tx.Hash(), tx.RlpEncode())
  164. }
  165. }
  166. }
  167. gui.processBlock(blk, true)
  168. }
  169. }
  170. type address struct {
  171. Name, Address string
  172. }
  173. var namereg = ethutil.Hex2Bytes("bb5f186604d057c1c5240ca2ae0f6430138ac010")
  174. func (gui *Gui) loadAddressBook() {
  175. gui.win.Root().Call("clearAddress")
  176. stateObject := gui.eth.StateManager().CurrentState().GetStateObject(namereg)
  177. if stateObject != nil {
  178. stateObject.State().EachStorage(func(name string, value *ethutil.Value) {
  179. gui.win.Root().Call("addAddress", struct{ Name, Address string }{name, ethutil.Bytes2Hex(value.Bytes())})
  180. })
  181. }
  182. }
  183. func (gui *Gui) readPreviousTransactions() {
  184. it := gui.txDb.Db().NewIterator(nil, nil)
  185. addr := gui.address()
  186. for it.Next() {
  187. tx := ethchain.NewTransactionFromBytes(it.Value())
  188. var inout string
  189. if bytes.Compare(tx.Sender(), addr) == 0 {
  190. inout = "send"
  191. } else {
  192. inout = "recv"
  193. }
  194. gui.win.Root().Call("addTx", ethpub.NewPTx(tx), inout)
  195. }
  196. it.Release()
  197. }
  198. func (gui *Gui) processBlock(block *ethchain.Block, initial bool) {
  199. gui.win.Root().Call("addBlock", ethpub.NewPBlock(block), initial)
  200. }
  201. func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) {
  202. var str string
  203. if unconfirmedFunds != nil {
  204. pos := "+"
  205. if unconfirmedFunds.Cmp(big.NewInt(0)) < 0 {
  206. pos = "-"
  207. }
  208. val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds)))
  209. str = fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(amount), pos, val)
  210. } else {
  211. str = fmt.Sprintf("%v", ethutil.CurrencyToString(amount))
  212. }
  213. gui.win.Root().Call("setWalletValue", str)
  214. }
  215. // Simple go routine function that updates the list of peers in the GUI
  216. func (gui *Gui) update() {
  217. reactor := gui.eth.Reactor()
  218. blockChan := make(chan ethutil.React, 1)
  219. txChan := make(chan ethutil.React, 1)
  220. objectChan := make(chan ethutil.React, 1)
  221. peerChan := make(chan ethutil.React, 1)
  222. reactor.Subscribe("newBlock", blockChan)
  223. reactor.Subscribe("newTx:pre", txChan)
  224. reactor.Subscribe("newTx:post", txChan)
  225. reactor.Subscribe("object:"+string(namereg), objectChan)
  226. reactor.Subscribe("peerList", peerChan)
  227. ticker := time.NewTicker(5 * time.Second)
  228. state := gui.eth.StateManager().TransState()
  229. unconfirmedFunds := new(big.Int)
  230. gui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(state.GetAccount(gui.address()).Amount)))
  231. for {
  232. select {
  233. case b := <-blockChan:
  234. block := b.Resource.(*ethchain.Block)
  235. gui.processBlock(block, false)
  236. if bytes.Compare(block.Coinbase, gui.address()) == 0 {
  237. gui.setWalletValue(gui.eth.StateManager().CurrentState().GetAccount(gui.address()).Amount, nil)
  238. }
  239. case txMsg := <-txChan:
  240. tx := txMsg.Resource.(*ethchain.Transaction)
  241. if txMsg.Event == "newTx:pre" {
  242. object := state.GetAccount(gui.address())
  243. if bytes.Compare(tx.Sender(), gui.address()) == 0 {
  244. gui.win.Root().Call("addTx", ethpub.NewPTx(tx), "send")
  245. gui.txDb.Put(tx.Hash(), tx.RlpEncode())
  246. unconfirmedFunds.Sub(unconfirmedFunds, tx.Value)
  247. } else if bytes.Compare(tx.Recipient, gui.address()) == 0 {
  248. gui.win.Root().Call("addTx", ethpub.NewPTx(tx), "recv")
  249. gui.txDb.Put(tx.Hash(), tx.RlpEncode())
  250. unconfirmedFunds.Add(unconfirmedFunds, tx.Value)
  251. }
  252. gui.setWalletValue(object.Amount, unconfirmedFunds)
  253. } else {
  254. object := state.GetAccount(gui.address())
  255. if bytes.Compare(tx.Sender(), gui.address()) == 0 {
  256. object.SubAmount(tx.Value)
  257. } else if bytes.Compare(tx.Recipient, gui.address()) == 0 {
  258. object.AddAmount(tx.Value)
  259. }
  260. gui.setWalletValue(object.Amount, nil)
  261. state.UpdateStateObject(object)
  262. }
  263. case <-objectChan:
  264. gui.loadAddressBook()
  265. case <-peerChan:
  266. gui.setPeerInfo()
  267. case <-ticker.C:
  268. gui.setPeerInfo()
  269. }
  270. }
  271. }
  272. func (gui *Gui) setPeerInfo() {
  273. gui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", gui.eth.PeerCount(), gui.eth.MaxPeers))
  274. gui.win.Root().Call("resetPeers")
  275. for _, peer := range gui.pub.GetPeers() {
  276. gui.win.Root().Call("addPeer", peer)
  277. }
  278. }
  279. func (gui *Gui) privateKey() string {
  280. return ethutil.Bytes2Hex(gui.eth.KeyManager().PrivateKey())
  281. }
  282. func (gui *Gui) address() []byte {
  283. return gui.eth.KeyManager().Address()
  284. }
  285. func (gui *Gui) RegisterName(name string) {
  286. name = fmt.Sprintf("\"%s\"\n1", name)
  287. gui.pub.Transact(gui.privateKey(), "namereg", "1000", "1000000", "150", name)
  288. }
  289. func (gui *Gui) Transact(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
  290. return gui.pub.Transact(gui.privateKey(), recipient, value, gas, gasPrice, data)
  291. }
  292. func (gui *Gui) Create(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
  293. return gui.pub.Transact(gui.privateKey(), recipient, value, gas, gasPrice, data)
  294. }
  295. func (gui *Gui) ChangeClientId(id string) {
  296. ethutil.Config.SetIdentifier(id)
  297. }
  298. func (gui *Gui) ClientId() string {
  299. return ethutil.Config.Identifier
  300. }
  301. // functions that allow Gui to implement interface ethlog.LogSystem
  302. func (gui *Gui) SetLogLevel(level ethlog.LogLevel) {
  303. gui.logLevel = level
  304. }
  305. func (gui *Gui) GetLogLevel() ethlog.LogLevel {
  306. return gui.logLevel
  307. }
  308. // this extra function needed to give int typecast value to gui widget
  309. // that sets initial loglevel to default
  310. func (gui *Gui) GetLogLevelInt() int {
  311. return int(gui.logLevel)
  312. }
  313. func (gui *Gui) Println(v ...interface{}) {
  314. gui.printLog(fmt.Sprintln(v...))
  315. }
  316. func (gui *Gui) Printf(format string, v ...interface{}) {
  317. gui.printLog(fmt.Sprintf(format, v...))
  318. }
  319. // Print function that logs directly to the GUI
  320. func (gui *Gui) printLog(s string) {
  321. str := strings.TrimRight(s, "\n")
  322. lines := strings.Split(str, "\n")
  323. for _, line := range lines {
  324. gui.win.Root().Call("addLog", line)
  325. }
  326. }