gui.go 10.3 KB
Newer Older
obscuren's avatar
obscuren committed
1 2 3
package ethui

import (
obscuren's avatar
obscuren committed
4
	"bytes"
obscuren's avatar
obscuren committed
5 6 7
	"fmt"
	"github.com/ethereum/eth-go"
	"github.com/ethereum/eth-go/ethchain"
obscuren's avatar
obscuren committed
8
	"github.com/ethereum/eth-go/ethdb"
zelig's avatar
zelig committed
9
	"github.com/ethereum/eth-go/ethlog"
obscuren's avatar
obscuren committed
10
	"github.com/ethereum/eth-go/ethpub"
obscuren's avatar
obscuren committed
11
	"github.com/ethereum/eth-go/ethutil"
obscuren's avatar
obscuren committed
12
	"github.com/ethereum/go-ethereum/utils"
13
	"github.com/go-qml/qml"
14
	"math/big"
obscuren's avatar
obscuren committed
15
	"strings"
Maran's avatar
Maran committed
16
	"time"
obscuren's avatar
obscuren committed
17 18
)

19 20
var logger = ethlog.NewLogger("GUI")

obscuren's avatar
obscuren committed
21
type Gui struct {
22 23 24
	// The main application window
	win *qml.Window
	// QML Engine
obscuren's avatar
obscuren committed
25 26
	engine    *qml.Engine
	component *qml.Common
27 28
	// The ethereum interface
	eth *eth.Ethereum
obscuren's avatar
obscuren committed
29

30
	// The public Ethereum library
31
	uiLib *UiLib
obscuren's avatar
obscuren committed
32 33 34

	txDb *ethdb.LDBDatabase

zelig's avatar
zelig committed
35
	pub      *ethpub.PEthereum
36
	logLevel ethlog.LogLevel
zelig's avatar
zelig committed
37
	open     bool
zelig's avatar
zelig committed
38 39

	Session string
obscuren's avatar
obscuren committed
40 41
}

42
// Create GUI, but doesn't start it
zelig's avatar
zelig committed
43 44
func New(ethereum *eth.Ethereum, session string, logLevel int) *Gui {

obscuren's avatar
obscuren committed
45 46 47 48
	db, err := ethdb.NewLDBDatabase("tx_database")
	if err != nil {
		panic(err)
	}
obscuren's avatar
obscuren committed
49

50
	pub := ethpub.NewPEthereum(ethereum)
obscuren's avatar
obscuren committed
51

zelig's avatar
zelig committed
52
	return &Gui{eth: ethereum, txDb: db, pub: pub, logLevel: ethlog.LogLevel(logLevel), Session: session, open: false}
obscuren's avatar
obscuren committed
53 54
}

obscuren's avatar
obscuren committed
55
func (gui *Gui) Start(assetPath string) {
obscuren's avatar
obscuren committed
56
	const version = "0.5.0 RC15"
obscuren's avatar
obscuren committed
57

obscuren's avatar
obscuren committed
58
	defer gui.txDb.Close()
obscuren's avatar
obscuren committed
59

60 61
	// Register ethereum functions
	qml.RegisterTypes("Ethereum", 1, 0, []qml.TypeSpec{{
obscuren's avatar
obscuren committed
62
		Init: func(p *ethpub.PBlock, obj qml.Object) { p.Number = 0; p.Hash = "" },
obscuren's avatar
obscuren committed
63
	}, {
obscuren's avatar
obscuren committed
64
		Init: func(p *ethpub.PTx, obj qml.Object) { p.Value = ""; p.Hash = ""; p.Address = "" },
65 66
	}, {
		Init: func(p *ethpub.KeyVal, obj qml.Object) { p.Key = ""; p.Value = "" },
obscuren's avatar
obscuren committed
67 68
	}})

obscuren's avatar
obscuren committed
69
	ethutil.Config.SetClientString("Ethereal")
70

71
	// Create a new QML engine
obscuren's avatar
obscuren committed
72 73
	gui.engine = qml.NewEngine()
	context := gui.engine.Context()
74 75

	// Expose the eth library and the ui library to QML
obscuren's avatar
obscuren committed
76
	context.SetVar("eth", gui)
obscuren's avatar
obscuren committed
77
	context.SetVar("pub", gui.pub)
78 79
	gui.uiLib = NewUiLib(gui.engine, gui.eth, assetPath)
	context.SetVar("ui", gui.uiLib)
80

81
	// Load the main QML interface
82
	data, _ := ethutil.Config.Db.Get([]byte("KeyRing"))
83 84

	var win *qml.Window
85
	var err error
zelig's avatar
zelig committed
86
	var addlog = false
87 88
	if len(data) == 0 {
		win, err = gui.showKeyImport(context)
89
	} else {
90
		win, err = gui.showWallet(context)
zelig's avatar
zelig committed
91
		addlog = true
92
	}
obscuren's avatar
obscuren committed
93
	if err != nil {
94
		logger.Errorln("asset not found: you can set an alternative asset path on the command line using option 'asset_path'", err)
95

obscuren's avatar
obscuren committed
96 97 98
		panic(err)
	}

99
	logger.Infoln("Starting GUI")
zelig's avatar
zelig committed
100
	gui.open = true
101
	win.Show()
zelig's avatar
zelig committed
102 103 104 105
	// only add the gui logger after window is shown otherwise slider wont be shown
	if addlog {
		ethlog.AddLogSystem(gui)
	}
106
	win.Wait()
zelig's avatar
zelig committed
107 108
	// need to silence gui logger after window closed otherwise logsystem hangs
	gui.SetLogLevel(ethlog.Silence)
zelig's avatar
zelig committed
109 110 111 112 113 114 115 116 117 118
	gui.open = false
}

func (gui *Gui) Stop() {
	if gui.open {
		gui.SetLogLevel(ethlog.Silence)
		gui.open = false
		gui.win.Hide()
	}
	logger.Infoln("Stopped")
119
}
obscuren's avatar
obscuren committed
120

obscuren's avatar
obscuren committed
121 122 123 124 125 126 127 128 129 130 131 132 133
func (gui *Gui) ToggleMining() {
	var txt string
	if gui.eth.Mining {
		utils.StopMining(gui.eth)
		txt = "Start mining"
	} else {
		utils.StartMining(gui.eth)
		txt = "Stop mining"
	}

	gui.win.Root().Set("miningButtonText", txt)
}

134 135 136 137
func (gui *Gui) showWallet(context *qml.Context) (*qml.Window, error) {
	component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/wallet.qml"))
	if err != nil {
		return nil, err
138
	}
obscuren's avatar
obscuren committed
139

140
	win := gui.createWindow(component)
obscuren's avatar
obscuren committed
141

obscuren's avatar
obscuren committed
142 143 144 145 146
	gui.setInitialBlockChain()
	gui.loadAddressBook()
	gui.readPreviousTransactions()
	gui.setPeerInfo()

147 148 149 150 151 152
	go gui.update()

	return win, nil
}

func (gui *Gui) showKeyImport(context *qml.Context) (*qml.Window, error) {
zelig's avatar
zelig committed
153
	context.SetVar("lib", gui)
154 155 156 157 158 159 160 161 162 163 164 165 166 167
	component, err := gui.engine.LoadFile(gui.uiLib.AssetPath("qml/first_run.qml"))
	if err != nil {
		return nil, err
	}
	return gui.createWindow(component), nil
}

func (gui *Gui) createWindow(comp qml.Object) *qml.Window {
	win := comp.CreateWindow(nil)

	gui.win = win
	gui.uiLib.win = win

	return gui.win
obscuren's avatar
obscuren committed
168
}
zelig's avatar
zelig committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

func (gui *Gui) ImportAndSetPrivKey(secret string) bool {
	err := gui.eth.KeyManager().InitFromString(gui.Session, 0, secret)
	if err != nil {
		logger.Errorln("unable to import: ", err)
		return false
	}
	logger.Errorln("successfully imported: ", err)
	return true
}

func (gui *Gui) CreateAndSetPrivKey() (string, string, string, string) {
	err := gui.eth.KeyManager().Init(gui.Session, 0, true)
	if err != nil {
		logger.Errorln("unable to create key: ", err)
		return "", "", "", ""
	}
	return gui.eth.KeyManager().KeyPair().AsStrings()
}

obscuren's avatar
obscuren committed
189
func (gui *Gui) setInitialBlockChain() {
190
	sBlk := gui.eth.BlockChain().LastBlockHash
191
	blk := gui.eth.BlockChain().GetBlock(sBlk)
192 193
	for ; blk != nil; blk = gui.eth.BlockChain().GetBlock(sBlk) {
		sBlk = blk.PrevHash
zelig's avatar
zelig committed
194
		addr := gui.address()
195 196 197

		// Loop through all transactions to see if we missed any while being offline
		for _, tx := range blk.Transactions() {
zelig's avatar
zelig committed
198
			if bytes.Compare(tx.Sender(), addr) == 0 || bytes.Compare(tx.Recipient, addr) == 0 {
199 200 201 202 203 204 205
				if ok, _ := gui.txDb.Get(tx.Hash()); ok == nil {
					gui.txDb.Put(tx.Hash(), tx.RlpEncode())
				}

			}
		}

Maran's avatar
Maran committed
206
		gui.processBlock(blk, true)
207 208 209
	}
}

obscuren's avatar
obscuren committed
210 211 212 213
type address struct {
	Name, Address string
}

zelig's avatar
zelig committed
214
var namereg = ethutil.Hex2Bytes("bb5f186604d057c1c5240ca2ae0f6430138ac010")
obscuren's avatar
obscuren committed
215 216 217

func (gui *Gui) loadAddressBook() {
	gui.win.Root().Call("clearAddress")
218 219 220
	stateObject := gui.eth.StateManager().CurrentState().GetStateObject(namereg)
	if stateObject != nil {
		stateObject.State().EachStorage(func(name string, value *ethutil.Value) {
zelig's avatar
zelig committed
221
			gui.win.Root().Call("addAddress", struct{ Name, Address string }{name, ethutil.Bytes2Hex(value.Bytes())})
222 223
		})
	}
obscuren's avatar
obscuren committed
224 225
}

obscuren's avatar
obscuren committed
226 227
func (gui *Gui) readPreviousTransactions() {
	it := gui.txDb.Db().NewIterator(nil, nil)
zelig's avatar
zelig committed
228
	addr := gui.address()
obscuren's avatar
obscuren committed
229 230 231
	for it.Next() {
		tx := ethchain.NewTransactionFromBytes(it.Value())

obscuren's avatar
obscuren committed
232
		var inout string
zelig's avatar
zelig committed
233
		if bytes.Compare(tx.Sender(), addr) == 0 {
obscuren's avatar
obscuren committed
234 235 236 237 238 239 240
			inout = "send"
		} else {
			inout = "recv"
		}

		gui.win.Root().Call("addTx", ethpub.NewPTx(tx), inout)

obscuren's avatar
obscuren committed
241 242 243 244
	}
	it.Release()
}

Maran's avatar
Maran committed
245 246
func (gui *Gui) processBlock(block *ethchain.Block, initial bool) {
	gui.win.Root().Call("addBlock", ethpub.NewPBlock(block), initial)
obscuren's avatar
obscuren committed
247 248
}

249 250 251 252
func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) {
	var str string
	if unconfirmedFunds != nil {
		pos := "+"
253
		if unconfirmedFunds.Cmp(big.NewInt(0)) < 0 {
254 255 256 257 258 259 260 261 262 263 264
			pos = "-"
		}
		val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds)))
		str = fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(amount), pos, val)
	} else {
		str = fmt.Sprintf("%v", ethutil.CurrencyToString(amount))
	}

	gui.win.Root().Call("setWalletValue", str)
}

obscuren's avatar
obscuren committed
265
// Simple go routine function that updates the list of peers in the GUI
obscuren's avatar
obscuren committed
266
func (gui *Gui) update() {
267 268
	reactor := gui.eth.Reactor()

269 270
	blockChan := make(chan ethutil.React, 1)
	txChan := make(chan ethutil.React, 1)
obscuren's avatar
obscuren committed
271
	objectChan := make(chan ethutil.React, 1)
obscuren's avatar
obscuren committed
272
	peerChan := make(chan ethutil.React, 1)
273

274 275 276
	reactor.Subscribe("newBlock", blockChan)
	reactor.Subscribe("newTx:pre", txChan)
	reactor.Subscribe("newTx:post", txChan)
obscuren's avatar
obscuren committed
277
	reactor.Subscribe("object:"+string(namereg), objectChan)
obscuren's avatar
obscuren committed
278
	reactor.Subscribe("peerList", peerChan)
obscuren's avatar
obscuren committed
279

Maran's avatar
Maran committed
280 281
	ticker := time.NewTicker(5 * time.Second)

obscuren's avatar
obscuren committed
282
	state := gui.eth.StateManager().TransState()
obscuren's avatar
obscuren committed
283

obscuren's avatar
obscuren committed
284
	unconfirmedFunds := new(big.Int)
zelig's avatar
zelig committed
285
	gui.win.Root().Call("setWalletValue", fmt.Sprintf("%v", ethutil.CurrencyToString(state.GetAccount(gui.address()).Amount)))
obscuren's avatar
obscuren committed
286

obscuren's avatar
obscuren committed
287 288
	for {
		select {
289 290
		case b := <-blockChan:
			block := b.Resource.(*ethchain.Block)
Maran's avatar
Maran committed
291
			gui.processBlock(block, false)
zelig's avatar
zelig committed
292 293
			if bytes.Compare(block.Coinbase, gui.address()) == 0 {
				gui.setWalletValue(gui.eth.StateManager().CurrentState().GetAccount(gui.address()).Amount, nil)
294 295
			}

obscuren's avatar
obscuren committed
296
		case txMsg := <-txChan:
297
			tx := txMsg.Resource.(*ethchain.Transaction)
obscuren's avatar
obscuren committed
298

299
			if txMsg.Event == "newTx:pre" {
zelig's avatar
zelig committed
300
				object := state.GetAccount(gui.address())
obscuren's avatar
obscuren committed
301

zelig's avatar
zelig committed
302
				if bytes.Compare(tx.Sender(), gui.address()) == 0 {
obscuren's avatar
obscuren committed
303
					gui.win.Root().Call("addTx", ethpub.NewPTx(tx), "send")
obscuren's avatar
obscuren committed
304 305
					gui.txDb.Put(tx.Hash(), tx.RlpEncode())

306
					unconfirmedFunds.Sub(unconfirmedFunds, tx.Value)
zelig's avatar
zelig committed
307
				} else if bytes.Compare(tx.Recipient, gui.address()) == 0 {
obscuren's avatar
obscuren committed
308
					gui.win.Root().Call("addTx", ethpub.NewPTx(tx), "recv")
obscuren's avatar
obscuren committed
309
					gui.txDb.Put(tx.Hash(), tx.RlpEncode())
310 311 312 313

					unconfirmedFunds.Add(unconfirmedFunds, tx.Value)
				}

314
				gui.setWalletValue(object.Amount, unconfirmedFunds)
obscuren's avatar
obscuren committed
315
			} else {
zelig's avatar
zelig committed
316 317
				object := state.GetAccount(gui.address())
				if bytes.Compare(tx.Sender(), gui.address()) == 0 {
obscuren's avatar
obscuren committed
318
					object.SubAmount(tx.Value)
zelig's avatar
zelig committed
319
				} else if bytes.Compare(tx.Recipient, gui.address()) == 0 {
obscuren's avatar
obscuren committed
320
					object.AddAmount(tx.Value)
obscuren's avatar
obscuren committed
321
				}
322

323
				gui.setWalletValue(object.Amount, nil)
obscuren's avatar
obscuren committed
324

obscuren's avatar
obscuren committed
325
				state.UpdateStateObject(object)
obscuren's avatar
obscuren committed
326
			}
obscuren's avatar
obscuren committed
327 328
		case <-objectChan:
			gui.loadAddressBook()
obscuren's avatar
obscuren committed
329 330
		case <-peerChan:
			gui.setPeerInfo()
Maran's avatar
Maran committed
331 332
		case <-ticker.C:
			gui.setPeerInfo()
obscuren's avatar
obscuren committed
333 334
		}
	}
obscuren's avatar
obscuren committed
335 336
}

obscuren's avatar
obscuren committed
337 338
func (gui *Gui) setPeerInfo() {
	gui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", gui.eth.PeerCount(), gui.eth.MaxPeers))
Maran's avatar
Maran committed
339 340 341 342 343

	gui.win.Root().Call("resetPeers")
	for _, peer := range gui.pub.GetPeers() {
		gui.win.Root().Call("addPeer", peer)
	}
obscuren's avatar
obscuren committed
344 345
}

zelig's avatar
zelig committed
346 347 348 349 350 351 352 353
func (gui *Gui) privateKey() string {
	return ethutil.Bytes2Hex(gui.eth.KeyManager().PrivateKey())
}

func (gui *Gui) address() []byte {
	return gui.eth.KeyManager().Address()
}

354 355
func (gui *Gui) RegisterName(name string) {
	name = fmt.Sprintf("\"%s\"\n1", name)
zelig's avatar
zelig committed
356
	gui.pub.Transact(gui.privateKey(), "namereg", "1000", "1000000", "150", name)
357
}
obscuren's avatar
obscuren committed
358 359

func (gui *Gui) Transact(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
zelig's avatar
zelig committed
360
	return gui.pub.Transact(gui.privateKey(), recipient, value, gas, gasPrice, data)
obscuren's avatar
obscuren committed
361 362 363
}

func (gui *Gui) Create(recipient, value, gas, gasPrice, data string) (*ethpub.PReceipt, error) {
zelig's avatar
zelig committed
364
	return gui.pub.Transact(gui.privateKey(), recipient, value, gas, gasPrice, data)
obscuren's avatar
obscuren committed
365
}
366 367 368 369 370 371 372 373

func (gui *Gui) ChangeClientId(id string) {
	ethutil.Config.SetIdentifier(id)
}

func (gui *Gui) ClientId() string {
	return ethutil.Config.Identifier
}
374

375 376 377 378 379 380 381 382 383
// functions that allow Gui to implement interface ethlog.LogSystem
func (gui *Gui) SetLogLevel(level ethlog.LogLevel) {
	gui.logLevel = level
}

func (gui *Gui) GetLogLevel() ethlog.LogLevel {
	return gui.logLevel
}

zelig's avatar
zelig committed
384 385 386 387 388 389
// this extra function needed to give int typecast value to gui widget
// that sets initial loglevel to default
func (gui *Gui) GetLogLevelInt() int {
	return int(gui.logLevel)
}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
func (gui *Gui) Println(v ...interface{}) {
	gui.printLog(fmt.Sprintln(v...))
}

func (gui *Gui) Printf(format string, v ...interface{}) {
	gui.printLog(fmt.Sprintf(format, v...))
}

// Print function that logs directly to the GUI
func (gui *Gui) printLog(s string) {
	str := strings.TrimRight(s, "\n")
	lines := strings.Split(str, "\n")
	for _, line := range lines {
		gui.win.Root().Call("addLog", line)
	}
405
}