ui_lib.go 8.96 KB
Newer Older
obscuren's avatar
obscuren committed
1 2
/*
	This file is part of go-ethereum
Felix Lange's avatar
Felix Lange committed
3

obscuren's avatar
obscuren committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
	go-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	go-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with go-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @authors
 * 	Jeffrey Wilcke <i@jev.io>
 */
obscuren's avatar
obscuren committed
21
package main
obscuren's avatar
obscuren committed
22 23

import (
obscuren's avatar
obscuren committed
24
	"bytes"
25
	"fmt"
obscuren's avatar
obscuren committed
26
	"path"
obscuren's avatar
obscuren committed
27 28
	"strconv"
	"strings"
obscuren's avatar
obscuren committed
29

obscuren's avatar
obscuren committed
30 31
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
obscuren's avatar
obscuren committed
32
	"github.com/ethereum/go-ethereum/crypto"
33
	"github.com/ethereum/go-ethereum/eth"
34
	"github.com/ethereum/go-ethereum/ethutil"
35
	"github.com/ethereum/go-ethereum/event/filter"
36
	"github.com/ethereum/go-ethereum/javascript"
37
	"github.com/ethereum/go-ethereum/miner"
obscuren's avatar
obscuren committed
38
	"github.com/ethereum/go-ethereum/state"
39
	"github.com/ethereum/go-ethereum/ui/qt"
40
	"github.com/ethereum/go-ethereum/xeth"
41
	"gopkg.in/qml.v1"
obscuren's avatar
obscuren committed
42 43
)

obscuren's avatar
obscuren committed
44 45 46 47 48
type memAddr struct {
	Num   string
	Value string
}

obscuren's avatar
obscuren committed
49 50
// UI Library that has some basic functionality exposed
type UiLib struct {
51
	*xeth.JSXEth
obscuren's avatar
obscuren committed
52 53 54
	engine    *qml.Engine
	eth       *eth.Ethereum
	connected bool
55
	assetPath string
obscuren's avatar
obscuren committed
56
	// The main application window
57 58 59
	win      *qml.Window
	Db       *Debugger
	DbWindow *DebuggerWindow
60 61

	jsEngine *javascript.JSRE
62 63

	filterCallbacks map[int][]int
64
	filterManager   *filter.FilterManager
65 66

	miner *miner.Miner
67 68 69
}

func NewUiLib(engine *qml.Engine, eth *eth.Ethereum, assetPath string) *UiLib {
70 71
	lib := &UiLib{JSXEth: xeth.NewJSXEth(eth), engine: engine, eth: eth, assetPath: assetPath, jsEngine: javascript.NewJSRE(eth), filterCallbacks: make(map[int][]int)} //, filters: make(map[int]*xeth.JSFilter)}
	lib.miner = miner.New(eth.KeyManager().Address(), eth)
72
	lib.filterManager = filter.NewFilterManager(eth.EventMux())
73 74

	return lib
75 76
}

obscuren's avatar
obscuren committed
77
func (self *UiLib) Notef(args []interface{}) {
obscuren's avatar
obscuren committed
78
	guilogger.Infoln(args...)
obscuren's avatar
obscuren committed
79 80
}

obscuren's avatar
obscuren committed
81 82 83 84
func (self *UiLib) LookupDomain(domain string) string {
	world := self.World()

	if len(domain) > 32 {
obscuren's avatar
obscuren committed
85
		domain = string(crypto.Sha3([]byte(domain)))
obscuren's avatar
obscuren committed
86 87 88 89
	}
	data := world.Config().Get("DnsReg").StorageString(domain).Bytes()

	// Left padded = A record, Right padded = CNAME
obscuren's avatar
obscuren committed
90
	if len(data) > 0 && data[0] == 0 {
obscuren's avatar
obscuren committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104
		data = bytes.TrimLeft(data, "\x00")
		var ipSlice []string
		for _, d := range data {
			ipSlice = append(ipSlice, strconv.Itoa(int(d)))
		}

		return strings.Join(ipSlice, ".")
	} else {
		data = bytes.TrimRight(data, "\x00")

		return string(data)
	}
}

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
func (self *UiLib) LookupName(addr string) string {
	var (
		nameReg = self.World().Config().Get("NameReg")
		lookup  = nameReg.Storage(ethutil.Hex2Bytes(addr))
	)

	if lookup.Len() != 0 {
		return strings.Trim(lookup.Str(), "\x00")
	}

	return addr
}

func (self *UiLib) LookupAddress(name string) string {
	var (
		nameReg = self.World().Config().Get("NameReg")
		lookup  = nameReg.Storage(ethutil.RightPadBytes([]byte(name), 32))
	)

	if lookup.Len() != 0 {
		return ethutil.Bytes2Hex(lookup.Bytes())
	}

	return ""
}

131
func (self *UiLib) PastPeers() *ethutil.List {
132 133
	return ethutil.NewList([]string{})
	//return ethutil.NewList(eth.PastPeers())
134 135
}

136
func (self *UiLib) ImportTx(rlpTx string) {
137
	tx := types.NewTransactionFromBytes(ethutil.Hex2Bytes(rlpTx))
138 139 140 141
	err := self.eth.TxPool().Add(tx)
	if err != nil {
		guilogger.Infoln("import tx failed ", err)
	}
142 143 144 145
}

func (self *UiLib) EvalJavascriptFile(path string) {
	self.jsEngine.LoadExtFile(path[7:])
obscuren's avatar
obscuren committed
146 147
}

148 149 150 151 152 153 154 155 156
func (self *UiLib) EvalJavascriptString(str string) string {
	value, err := self.jsEngine.Run(str)
	if err != nil {
		return err.Error()
	}

	return fmt.Sprintf("%v", value)
}

157 158 159
func (ui *UiLib) OpenQml(path string) {
	container := NewQmlApplication(path[7:], ui)
	app := NewExtApplication(container, ui)
obscuren's avatar
obscuren committed
160

161
	go app.run()
obscuren's avatar
obscuren committed
162 163
}

164
func (ui *UiLib) OpenHtml(path string) {
165 166
	container := NewHtmlApplication(path, ui)
	app := NewExtApplication(container, ui)
167

168 169
	go app.run()
}
170

obscuren's avatar
obscuren committed
171 172 173 174
func (ui *UiLib) OpenBrowser() {
	ui.OpenHtml("file://" + ui.AssetPath("ext/home.html"))
}

obscuren's avatar
obscuren committed
175 176 177
func (ui *UiLib) Muted(content string) {
	component, err := ui.engine.LoadFile(ui.AssetPath("qml/muted.qml"))
	if err != nil {
obscuren's avatar
obscuren committed
178
		guilogger.Debugln(err)
obscuren's avatar
obscuren committed
179 180 181 182 183 184 185 186 187 188 189 190 191

		return
	}
	win := component.CreateWindow(nil)
	go func() {
		path := "file://" + ui.AssetPath("muted/index.html")
		win.Set("url", path)

		win.Show()
		win.Wait()
	}()
}

192
func (ui *UiLib) Connect(button qml.Object) {
obscuren's avatar
obscuren committed
193
	if !ui.connected {
obscuren's avatar
obscuren committed
194
		ui.eth.Start(true)
195 196
		ui.connected = true
		button.Set("enabled", false)
obscuren's avatar
obscuren committed
197 198 199 200
	}
}

func (ui *UiLib) ConnectToPeer(addr string) {
obscuren's avatar
obscuren committed
201 202 203
	if err := ui.eth.SuggestPeer(addr); err != nil {
		guilogger.Infoln(err)
	}
obscuren's avatar
obscuren committed
204
}
205 206

func (ui *UiLib) AssetPath(p string) string {
207
	return path.Join(ui.assetPath, p)
208
}
209

210 211
func (self *UiLib) StartDbWithContractAndData(contractHash, data string) {
	dbWindow := NewDebuggerWindow(self)
obscuren's avatar
obscuren committed
212
	object := self.eth.ChainManager().State().GetStateObject(ethutil.Hex2Bytes(contractHash))
213 214
	if len(object.Code) > 0 {
		dbWindow.SetCode("0x" + ethutil.Bytes2Hex(object.Code))
215
	}
216
	dbWindow.SetData("0x" + data)
217 218 219 220 221 222 223 224 225

	dbWindow.Show()
}

func (self *UiLib) StartDbWithCode(code string) {
	dbWindow := NewDebuggerWindow(self)
	dbWindow.SetCode("0x" + code)
	dbWindow.Show()
}
226

obscuren's avatar
obscuren committed
227 228 229 230 231
func (self *UiLib) StartDebugger() {
	dbWindow := NewDebuggerWindow(self)

	dbWindow.Show()
}
232

obscuren's avatar
obscuren committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
func (self *UiLib) Transact(params map[string]interface{}) (string, error) {
	object := mapToTxParams(params)

	return self.JSXEth.Transact(
		object["from"],
		object["to"],
		object["value"],
		object["gas"],
		object["gasPrice"],
		object["data"],
	)
}

func (self *UiLib) Compile(code string) (string, error) {
	bcode, err := ethutil.Compile(code, false)
	if err != nil {
		return err.Error(), err
	}

	return ethutil.Bytes2Hex(bcode), err
}

func (self *UiLib) Call(params map[string]interface{}) (string, error) {
	object := mapToTxParams(params)

	return self.JSXEth.Execute(
		object["to"],
		object["value"],
		object["gas"],
		object["gasPrice"],
		object["data"],
	)
}

func (self *UiLib) AddLocalTransaction(to, data, gas, gasPrice, value string) int {
	return self.miner.AddLocalTx(&miner.LocalTx{
		To:       ethutil.Hex2Bytes(to),
		Data:     ethutil.Hex2Bytes(data),
		Gas:      gas,
		GasPrice: gasPrice,
		Value:    value,
	}) - 1
}

func (self *UiLib) RemoveLocalTransaction(id int) {
	self.miner.RemoveLocalTx(id)
}

func (self *UiLib) SetGasPrice(price string) {
	self.miner.MinAcceptedGasPrice = ethutil.Big(price)
}

285 286 287 288
func (self *UiLib) SetExtra(extra string) {
	self.miner.Extra = extra
}

obscuren's avatar
obscuren committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
func (self *UiLib) ToggleMining() bool {
	if !self.miner.Mining() {
		self.miner.Start()

		return true
	} else {
		self.miner.Stop()

		return false
	}
}

func (self *UiLib) ToHex(data string) string {
	return "0x" + ethutil.Bytes2Hex([]byte(data))
}

func (self *UiLib) ToAscii(data string) string {
	start := 0
	if len(data) > 1 && data[0:2] == "0x" {
		start = 2
	}
	return string(ethutil.Hex2Bytes(data[start:]))
}

/// Ethereum filter methods
314
func (self *UiLib) NewFilter(object map[string]interface{}) (id int) {
315
	filter := qt.NewFilterFromMap(object, self.eth)
obscuren's avatar
obscuren committed
316
	filter.MessageCallback = func(messages state.Messages) {
317
		self.win.Root().Call("invokeFilterCallback", xeth.ToJSMessages(messages), id)
318
	}
319
	id = self.filterManager.InstallFilter(filter)
obscuren's avatar
obscuren committed
320
	return id
321 322
}

323
func (self *UiLib) NewFilterString(typ string) (id int) {
obscuren's avatar
obscuren committed
324
	filter := core.NewFilter(self.eth)
325
	filter.BlockCallback = func(block *types.Block) {
326 327 328 329 330
		if self.win != nil && self.win.Root() != nil {
			self.win.Root().Call("invokeFilterCallback", "{}", id)
		} else {
			fmt.Println("QML is lagging")
		}
331
	}
332
	id = self.filterManager.InstallFilter(filter)
obscuren's avatar
obscuren committed
333
	return id
334 335
}

obscuren's avatar
obscuren committed
336
func (self *UiLib) Messages(id int) *ethutil.List {
337
	filter := self.filterManager.GetFilter(id)
338
	if filter != nil {
339
		messages := xeth.ToJSMessages(filter.Find())
obscuren's avatar
obscuren committed
340

obscuren's avatar
obscuren committed
341
		return messages
342
	}
obscuren's avatar
obscuren committed
343 344

	return ethutil.EmptyList()
345 346
}

obscuren's avatar
obscuren committed
347
func (self *UiLib) UninstallFilter(id int) {
348
	self.filterManager.UninstallFilter(id)
349
}
350

obscuren's avatar
obscuren committed
351
func mapToTxParams(object map[string]interface{}) map[string]string {
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
	// Default values
	if object["from"] == nil {
		object["from"] = ""
	}
	if object["to"] == nil {
		object["to"] = ""
	}
	if object["value"] == nil {
		object["value"] = ""
	}
	if object["gas"] == nil {
		object["gas"] = ""
	}
	if object["gasPrice"] == nil {
		object["gasPrice"] = ""
	}

	var dataStr string
	var data []string
	if list, ok := object["data"].(*qml.List); ok {
		list.Convert(&data)
obscuren's avatar
obscuren committed
373 374
	} else if str, ok := object["data"].(string); ok {
		data = []string{str}
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
	}

	for _, str := range data {
		if ethutil.IsHex(str) {
			str = str[2:]

			if len(str) != 64 {
				str = ethutil.LeftPadString(str, 64)
			}
		} else {
			str = ethutil.Bytes2Hex(ethutil.LeftPadBytes(ethutil.Big(str).Bytes(), 32))
		}

		dataStr += str
	}
obscuren's avatar
obscuren committed
390 391 392 393 394 395 396 397 398 399 400
	object["data"] = dataStr

	conv := make(map[string]string)
	for key, value := range object {
		if v, ok := value.(string); ok {
			conv[key] = v
		}
	}

	return conv
}