xeth.go 17.9 KB
Newer Older
1
// eXtended ETHereum
O
obscuren 已提交
2 3
package xeth

O
obscuren 已提交
4 5 6
import (
	"bytes"
	"encoding/json"
7
	"fmt"
8
	"math/big"
T
Taylor Gerring 已提交
9 10
	"sync"
	"time"
O
obscuren 已提交
11

12
	"github.com/ethereum/go-ethereum/accounts"
O
obscuren 已提交
13
	"github.com/ethereum/go-ethereum/common"
O
obscuren 已提交
14
	"github.com/ethereum/go-ethereum/core"
T
Taylor Gerring 已提交
15
	"github.com/ethereum/go-ethereum/core/state"
O
obscuren 已提交
16 17
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
18
	"github.com/ethereum/go-ethereum/eth"
T
Taylor Gerring 已提交
19
	"github.com/ethereum/go-ethereum/event/filter"
O
obscuren 已提交
20
	"github.com/ethereum/go-ethereum/logger"
21
	"github.com/ethereum/go-ethereum/miner"
T
Taylor Gerring 已提交
22
	"github.com/ethereum/go-ethereum/rlp"
O
obscuren 已提交
23
)
O
obscuren 已提交
24

T
Taylor Gerring 已提交
25 26 27
var (
	pipelogger       = logger.NewLogger("XETH")
	filterTickerTime = 5 * time.Minute
T
Taylor Gerring 已提交
28 29
	defaultGasPrice  = big.NewInt(10000000000000) //150000000000
	defaultGas       = big.NewInt(90000)          //500000
T
Taylor Gerring 已提交
30
)
O
obscuren 已提交
31

O
obscuren 已提交
32 33 34
func DefaultGas() *big.Int      { return new(big.Int).Set(defaultGas) }
func DefaultGasPrice() *big.Int { return new(big.Int).Set(defaultGasPrice) }

O
obscuren 已提交
35
type XEth struct {
T
Shuffle  
Taylor Gerring 已提交
36 37 38
	backend  *eth.Ethereum
	frontend Frontend

T
Taylor Gerring 已提交
39 40
	state   *State
	whisper *Whisper
O
obscuren 已提交
41

T
Taylor Gerring 已提交
42 43
	quit          chan struct{}
	filterManager *filter.FilterManager
O
obscuren 已提交
44

T
Taylor Gerring 已提交
45 46 47 48 49
	logMut sync.RWMutex
	logs   map[int]*logFilter

	messagesMut sync.RWMutex
	messages    map[int]*whisperFilter
T
Taylor Gerring 已提交
50 51 52

	// regmut   sync.Mutex
	// register map[string][]*interface{} // TODO improve return type
53

T
Taylor Gerring 已提交
54
	agent *miner.RemoteAgent
O
obscuren 已提交
55
}
O
obscuren 已提交
56

57 58 59
// New creates an XEth that uses the given frontend.
// If a nil Frontend is provided, a default frontend which
// confirms all transactions will be used.
60
func New(eth *eth.Ethereum, frontend Frontend) *XEth {
O
obscuren 已提交
61
	xeth := &XEth{
T
Taylor Gerring 已提交
62
		backend:       eth,
T
Shuffle  
Taylor Gerring 已提交
63
		frontend:      frontend,
T
Taylor Gerring 已提交
64 65 66 67 68 69
		whisper:       NewWhisper(eth.Whisper()),
		quit:          make(chan struct{}),
		filterManager: filter.NewFilterManager(eth.EventMux()),
		logs:          make(map[int]*logFilter),
		messages:      make(map[int]*whisperFilter),
		agent:         miner.NewRemoteAgent(),
O
obscuren 已提交
70
	}
71 72
	eth.Miner().Register(xeth.agent)

O
obscuren 已提交
73
	if frontend == nil {
74
		xeth.frontend = dummyFrontend{}
O
obscuren 已提交
75
	}
T
Taylor Gerring 已提交
76
	xeth.state = NewState(xeth, xeth.backend.ChainManager().TransState())
T
Shuffle  
Taylor Gerring 已提交
77

T
Taylor Gerring 已提交
78 79 80
	go xeth.start()
	go xeth.filterManager.Start()

O
obscuren 已提交
81 82 83
	return xeth
}

T
Taylor Gerring 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
func (self *XEth) start() {
	timer := time.NewTicker(2 * time.Second)
done:
	for {
		select {
		case <-timer.C:
			self.logMut.Lock()
			self.messagesMut.Lock()
			for id, filter := range self.logs {
				if time.Since(filter.timeout) > filterTickerTime {
					self.filterManager.UninstallFilter(id)
					delete(self.logs, id)
				}
			}

			for id, filter := range self.messages {
				if time.Since(filter.timeout) > filterTickerTime {
					self.Whisper().Unwatch(id)
					delete(self.messages, id)
				}
			}
			self.messagesMut.Unlock()
			self.logMut.Unlock()
		case <-self.quit:
			break done
		}
	}
}

func (self *XEth) stop() {
	close(self.quit)
}

T
Taylor Gerring 已提交
117 118 119 120 121 122 123 124 125 126 127
func cAddress(a []string) []common.Address {
	bslice := make([]common.Address, len(a))
	for i, addr := range a {
		bslice[i] = common.HexToAddress(addr)
	}
	return bslice
}

func cTopics(t [][]string) [][]common.Hash {
	topics := make([][]common.Hash, len(t))
	for i, iv := range t {
128
		topics[i] = make([]common.Hash, len(iv))
T
Taylor Gerring 已提交
129 130 131 132 133 134 135
		for j, jv := range iv {
			topics[i][j] = common.HexToHash(jv)
		}
	}
	return topics
}

T
Taylor Gerring 已提交
136
func (self *XEth) RemoteMining() *miner.RemoteAgent { return self.agent }
137

T
Taylor Gerring 已提交
138 139
func (self *XEth) AtStateNum(num int64) *XEth {
	var st *state.StateDB
O
obscuren 已提交
140 141 142 143 144 145 146 147 148
	switch num {
	case -2:
		st = self.backend.Miner().PendingState().Copy()
	default:
		if block := self.getBlockByHeight(num); block != nil {
			st = state.New(block.Root(), self.backend.StateDb())
		} else {
			st = state.New(self.backend.ChainManager().GetBlockByNumber(0).Root(), self.backend.StateDb())
		}
T
Taylor Gerring 已提交
149
	}
T
Taylor Gerring 已提交
150 151

	return self.withState(st)
T
Taylor Gerring 已提交
152 153
}

T
Taylor Gerring 已提交
154
func (self *XEth) withState(statedb *state.StateDB) *XEth {
O
wip  
obscuren 已提交
155
	xeth := &XEth{
T
Taylor Gerring 已提交
156
		backend: self.backend,
O
wip  
obscuren 已提交
157 158 159 160 161
	}

	xeth.state = NewState(xeth, statedb)
	return xeth
}
T
Shuffle  
Taylor Gerring 已提交
162

O
wip  
obscuren 已提交
163 164
func (self *XEth) State() *State { return self.state }

165
func (self *XEth) Whisper() *Whisper { return self.whisper }
O
obscuren 已提交
166

T
Taylor Gerring 已提交
167 168 169
func (self *XEth) getBlockByHeight(height int64) *types.Block {
	var num uint64

O
obscuren 已提交
170 171 172 173 174 175 176 177 178 179
	switch height {
	case -2:
		return self.backend.Miner().PendingBlock()
	case -1:
		return self.CurrentBlock()
	default:
		if height < 0 {
			return nil
		}

T
Taylor Gerring 已提交
180 181 182 183 184 185
		num = uint64(height)
	}

	return self.backend.ChainManager().GetBlockByNumber(num)
}

O
obscuren 已提交
186
func (self *XEth) BlockByHash(strHash string) *Block {
O
obscuren 已提交
187
	hash := common.HexToHash(strHash)
T
Taylor Gerring 已提交
188
	block := self.backend.ChainManager().GetBlock(hash)
O
obscuren 已提交
189

O
obscuren 已提交
190
	return NewBlock(block)
O
obscuren 已提交
191 192
}

T
Taylor Gerring 已提交
193 194
func (self *XEth) EthBlockByHash(strHash string) *types.Block {
	hash := common.HexToHash(strHash)
T
Taylor Gerring 已提交
195
	block := self.backend.ChainManager().GetBlock(hash)
T
Taylor Gerring 已提交
196 197 198 199

	return block
}

200
func (self *XEth) EthTransactionByHash(hash string) (tx *types.Transaction, blhash common.Hash, blnum *big.Int, txi uint64) {
T
Taylor Gerring 已提交
201
	data, _ := self.backend.ExtraDb().Get(common.FromHex(hash))
O
obscuren 已提交
202
	if len(data) != 0 {
203
		tx = types.NewTransactionFromBytes(data)
O
obscuren 已提交
204
	}
205

T
Taylor Gerring 已提交
206 207 208
	// meta
	var txExtra struct {
		BlockHash  common.Hash
T
Taylor Gerring 已提交
209
		BlockIndex uint64
T
Taylor Gerring 已提交
210
		Index      uint64
211
	}
T
Taylor Gerring 已提交
212 213 214 215 216 217

	v, _ := self.backend.ExtraDb().Get(append(common.FromHex(hash), 0x0001))
	r := bytes.NewReader(v)
	err := rlp.Decode(r, &txExtra)
	if err == nil {
		blhash = txExtra.BlockHash
T
Taylor Gerring 已提交
218
		blnum = big.NewInt(int64(txExtra.BlockIndex))
T
Taylor Gerring 已提交
219
		txi = txExtra.Index
T
Taylor Gerring 已提交
220 221
	} else {
		pipelogger.Errorln(err)
222 223 224
	}

	return
O
obscuren 已提交
225 226
}

T
Taylor Gerring 已提交
227
func (self *XEth) BlockByNumber(num int64) *Block {
T
Taylor Gerring 已提交
228
	return NewBlock(self.getBlockByHeight(num))
O
obscuren 已提交
229 230
}

T
Taylor Gerring 已提交
231
func (self *XEth) EthBlockByNumber(num int64) *types.Block {
T
Taylor Gerring 已提交
232
	return self.getBlockByHeight(num)
T
Taylor Gerring 已提交
233 234
}

T
Taylor Gerring 已提交
235 236 237 238
func (self *XEth) CurrentBlock() *types.Block {
	return self.backend.ChainManager().CurrentBlock()
}

O
obscuren 已提交
239
func (self *XEth) Block(v interface{}) *Block {
O
obscuren 已提交
240
	if n, ok := v.(int32); ok {
T
Taylor Gerring 已提交
241
		return self.BlockByNumber(int64(n))
O
obscuren 已提交
242 243 244
	} else if str, ok := v.(string); ok {
		return self.BlockByHash(str)
	} else if f, ok := v.(float64); ok { // Don't ask ...
T
Taylor Gerring 已提交
245
		return self.BlockByNumber(int64(f))
O
obscuren 已提交
246 247 248 249 250
	}

	return nil
}

O
obscuren 已提交
251
func (self *XEth) Accounts() []string {
252
	// TODO: check err?
T
Taylor Gerring 已提交
253
	accounts, _ := self.backend.AccountManager().Accounts()
254 255
	accountAddresses := make([]string, len(accounts))
	for i, ac := range accounts {
256
		accountAddresses[i] = common.ToHex(ac.Address)
257 258
	}
	return accountAddresses
O
obscuren 已提交
259 260
}

261 262 263 264 265 266 267 268 269 270
func (self *XEth) DbPut(key, val []byte) bool {
	self.backend.ExtraDb().Put(key, val)
	return true
}

func (self *XEth) DbGet(key []byte) ([]byte, error) {
	val, err := self.backend.ExtraDb().Get(key)
	return val, err
}

O
obscuren 已提交
271
func (self *XEth) PeerCount() int {
T
Taylor Gerring 已提交
272
	return self.backend.PeerCount()
O
obscuren 已提交
273 274
}

O
obscuren 已提交
275
func (self *XEth) IsMining() bool {
T
Taylor Gerring 已提交
276
	return self.backend.IsMining()
O
obscuren 已提交
277 278
}

279
func (self *XEth) EthVersion() string {
280
	return fmt.Sprintf("%d", self.backend.EthVersion())
281 282
}

T
Taylor Gerring 已提交
283
func (self *XEth) NetworkVersion() string {
284
	return fmt.Sprintf("%d", self.backend.NetVersion())
285 286 287
}

func (self *XEth) WhisperVersion() string {
288
	return fmt.Sprintf("%d", self.backend.ShhVersion())
T
Taylor Gerring 已提交
289 290 291
}

func (self *XEth) ClientVersion() string {
292
	return self.backend.ClientVersion()
T
Taylor Gerring 已提交
293 294
}

T
Taylor Gerring 已提交
295
func (self *XEth) SetMining(shouldmine bool) bool {
T
Taylor Gerring 已提交
296
	ismining := self.backend.IsMining()
T
Taylor Gerring 已提交
297
	if shouldmine && !ismining {
T
Taylor Gerring 已提交
298
		err := self.backend.StartMining()
299
		return err == nil
T
Taylor Gerring 已提交
300 301
	}
	if ismining && !shouldmine {
T
Taylor Gerring 已提交
302
		self.backend.StopMining()
T
Taylor Gerring 已提交
303
	}
T
Taylor Gerring 已提交
304
	return self.backend.IsMining()
T
Taylor Gerring 已提交
305 306
}

O
obscuren 已提交
307
func (self *XEth) IsListening() bool {
T
Taylor Gerring 已提交
308
	return self.backend.IsListening()
O
obscuren 已提交
309 310
}

O
obscuren 已提交
311
func (self *XEth) Coinbase() string {
Z
zelig 已提交
312 313
	eb, _ := self.backend.Etherbase()
	return eb.Hex()
O
obscuren 已提交
314 315
}

O
obscuren 已提交
316
func (self *XEth) NumberToHuman(balance string) string {
O
obscuren 已提交
317
	b := common.Big(balance)
O
obscuren 已提交
318

O
obscuren 已提交
319
	return common.CurrencyToString(b)
O
obscuren 已提交
320 321
}

O
obscuren 已提交
322
func (self *XEth) StorageAt(addr, storageAddr string) string {
323
	return common.ToHex(self.State().state.GetState(common.HexToAddress(addr), common.HexToHash(storageAddr)))
O
obscuren 已提交
324 325
}

O
obscuren 已提交
326
func (self *XEth) BalanceAt(addr string) string {
O
obscuren 已提交
327
	return common.ToHex(self.State().state.GetBalance(common.HexToAddress(addr)).Bytes())
O
obscuren 已提交
328 329
}

O
obscuren 已提交
330
func (self *XEth) TxCountAt(address string) int {
331
	return int(self.State().state.GetNonce(common.HexToAddress(address)))
O
obscuren 已提交
332 333
}

O
obscuren 已提交
334
func (self *XEth) CodeAt(address string) string {
335
	return common.ToHex(self.State().state.GetCode(common.HexToAddress(address)))
O
obscuren 已提交
336 337
}

T
Taylor Gerring 已提交
338 339 340 341
func (self *XEth) CodeAtBytes(address string) []byte {
	return self.State().SafeGet(address).Code()
}

O
obscuren 已提交
342
func (self *XEth) IsContract(address string) bool {
343
	return len(self.State().SafeGet(address).Code()) > 0
O
obscuren 已提交
344 345
}

O
obscuren 已提交
346
func (self *XEth) SecretToAddress(key string) string {
O
obscuren 已提交
347
	pair, err := crypto.NewKeyPairFromSec(common.FromHex(key))
O
obscuren 已提交
348 349 350 351
	if err != nil {
		return ""
	}

352
	return common.ToHex(pair.Address())
O
obscuren 已提交
353 354
}

T
Taylor Gerring 已提交
355
func (self *XEth) RegisterFilter(earliest, latest int64, skip, max int, address []string, topics [][]string) int {
T
Taylor Gerring 已提交
356
	var id int
T
Taylor Gerring 已提交
357
	filter := core.NewFilter(self.backend)
T
Taylor Gerring 已提交
358 359 360 361 362 363
	filter.SetEarliestBlock(earliest)
	filter.SetLatestBlock(latest)
	filter.SetSkip(skip)
	filter.SetMax(max)
	filter.SetAddress(cAddress(address))
	filter.SetTopics(cTopics(topics))
T
Taylor Gerring 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	filter.LogsCallback = func(logs state.Logs) {
		self.logMut.Lock()
		defer self.logMut.Unlock()

		self.logs[id].add(logs...)
	}
	id = self.filterManager.InstallFilter(filter)
	self.logs[id] = &logFilter{timeout: time.Now()}

	return id
}

func (self *XEth) UninstallFilter(id int) bool {
	if _, ok := self.logs[id]; ok {
		delete(self.logs, id)
		self.filterManager.UninstallFilter(id)
		return true
	}

	return false
}

func (self *XEth) NewFilterString(word string) int {
	var id int
T
Taylor Gerring 已提交
388
	filter := core.NewFilter(self.backend)
T
Taylor Gerring 已提交
389 390 391

	switch word {
	case "pending":
392 393 394 395
		filter.PendingCallback = func(tx *types.Transaction) {
			self.logMut.Lock()
			defer self.logMut.Unlock()

O
obscuren 已提交
396
			self.logs[id].add(&state.Log{})
397
		}
T
Taylor Gerring 已提交
398
	case "latest":
399 400 401 402 403 404 405
		filter.BlockCallback = func(block *types.Block, logs state.Logs) {
			self.logMut.Lock()
			defer self.logMut.Unlock()

			for _, log := range logs {
				self.logs[id].add(log)
			}
O
obscuren 已提交
406
			self.logs[id].add(&state.Log{})
407
		}
T
Taylor Gerring 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
	}

	id = self.filterManager.InstallFilter(filter)
	self.logs[id] = &logFilter{timeout: time.Now()}

	return id
}

func (self *XEth) FilterChanged(id int) state.Logs {
	self.logMut.Lock()
	defer self.logMut.Unlock()

	if self.logs[id] != nil {
		return self.logs[id].get()
	}

	return nil
}

func (self *XEth) Logs(id int) state.Logs {
	self.logMut.Lock()
	defer self.logMut.Unlock()

	filter := self.filterManager.GetFilter(id)
	if filter != nil {
		return filter.Find()
	}

	return nil
}

T
Taylor Gerring 已提交
439
func (self *XEth) AllLogs(earliest, latest int64, skip, max int, address []string, topics [][]string) state.Logs {
T
Taylor Gerring 已提交
440
	filter := core.NewFilter(self.backend)
T
Taylor Gerring 已提交
441 442 443 444 445 446
	filter.SetEarliestBlock(earliest)
	filter.SetLatestBlock(latest)
	filter.SetSkip(skip)
	filter.SetMax(max)
	filter.SetAddress(cAddress(address))
	filter.SetTopics(cTopics(topics))
T
Taylor Gerring 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

	return filter.Find()
}

func (p *XEth) NewWhisperFilter(opts *Options) int {
	var id int
	opts.Fn = func(msg WhisperMessage) {
		p.messagesMut.Lock()
		defer p.messagesMut.Unlock()
		p.messages[id].add(msg) // = append(p.messages[id], msg)
	}
	id = p.Whisper().Watch(opts)
	p.messages[id] = &whisperFilter{timeout: time.Now()}
	return id
}

func (p *XEth) UninstallWhisperFilter(id int) bool {
	if _, ok := p.messages[id]; ok {
		delete(p.messages, id)
		return true
	}

	return false
}

func (self *XEth) MessagesChanged(id int) []WhisperMessage {
	self.messagesMut.Lock()
	defer self.messagesMut.Unlock()

	if self.messages[id] != nil {
		return self.messages[id].get()
	}

	return nil
}

T
Taylor Gerring 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
// func (self *XEth) Register(args string) bool {
// 	self.regmut.Lock()
// 	defer self.regmut.Unlock()

// 	if _, ok := self.register[args]; ok {
// 		self.register[args] = nil // register with empty
// 	}
// 	return true
// }

// func (self *XEth) Unregister(args string) bool {
// 	self.regmut.Lock()
// 	defer self.regmut.Unlock()

// 	if _, ok := self.register[args]; ok {
// 		delete(self.register, args)
// 		return true
// 	}

// 	return false
// }

// // TODO improve return type
// func (self *XEth) PullWatchTx(args string) []*interface{} {
// 	self.regmut.Lock()
// 	defer self.regmut.Unlock()

// 	txs := self.register[args]
// 	self.register[args] = nil

// 	return txs
// }

O
obscuren 已提交
516 517 518 519 520
type KeyVal struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

O
obscuren 已提交
521
func (self *XEth) EachStorage(addr string) string {
O
obscuren 已提交
522 523 524 525
	var values []KeyVal
	object := self.State().SafeGet(addr)
	it := object.Trie().Iterator()
	for it.Next() {
O
obscuren 已提交
526
		values = append(values, KeyVal{common.ToHex(object.Trie().GetKey(it.Key)), common.ToHex(it.Value)})
O
obscuren 已提交
527 528 529 530 531 532 533 534 535 536
	}

	valuesJson, err := json.Marshal(values)
	if err != nil {
		return ""
	}

	return string(valuesJson)
}

O
obscuren 已提交
537
func (self *XEth) ToAscii(str string) string {
O
obscuren 已提交
538
	padded := common.RightPadBytes([]byte(str), 32)
O
obscuren 已提交
539

540
	return "0x" + common.ToHex(padded)
O
obscuren 已提交
541 542
}

O
obscuren 已提交
543
func (self *XEth) FromAscii(str string) string {
O
obscuren 已提交
544
	if common.IsHex(str) {
O
obscuren 已提交
545 546 547
		str = str[2:]
	}

O
obscuren 已提交
548
	return string(bytes.Trim(common.FromHex(str), "\x00"))
O
obscuren 已提交
549 550
}

O
obscuren 已提交
551
func (self *XEth) FromNumber(str string) string {
O
obscuren 已提交
552
	if common.IsHex(str) {
O
obscuren 已提交
553 554 555
		str = str[2:]
	}

O
obscuren 已提交
556
	return common.BigD(common.FromHex(str)).String()
O
obscuren 已提交
557 558
}

O
obscuren 已提交
559
func (self *XEth) PushTx(encodedTx string) (string, error) {
O
obscuren 已提交
560
	tx := types.NewTransactionFromBytes(common.FromHex(encodedTx))
T
Taylor Gerring 已提交
561
	err := self.backend.TxPool().Add(tx)
O
obscuren 已提交
562 563 564 565 566 567
	if err != nil {
		return "", err
	}

	if tx.To() == nil {
		addr := core.AddressFromMessage(tx)
O
obscuren 已提交
568
		return addr.Hex(), nil
O
obscuren 已提交
569
	}
O
obscuren 已提交
570
	return tx.Hash().Hex(), nil
O
obscuren 已提交
571
}
572

573
func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, error) {
T
Taylor Gerring 已提交
574
	statedb := self.State().State() //self.eth.ChainManager().TransState()
575 576 577 578 579 580 581 582 583 584 585 586
	var from *state.StateObject
	if len(fromStr) == 0 {
		accounts, err := self.backend.AccountManager().Accounts()
		if err != nil || len(accounts) == 0 {
			from = statedb.GetOrNewStateObject(common.Address{})
		} else {
			from = statedb.GetOrNewStateObject(common.BytesToAddress(accounts[0].Address))
		}
	} else {
		from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr))
	}

587
	msg := callmsg{
588
		from:     from,
O
obscuren 已提交
589
		to:       common.HexToAddress(toStr),
O
obscuren 已提交
590 591 592 593
		gas:      common.Big(gasStr),
		gasPrice: common.Big(gasPriceStr),
		value:    common.Big(valueStr),
		data:     common.FromHex(dataStr),
594
	}
B
Bas van Kervel 已提交
595

596
	if msg.gas.Cmp(big.NewInt(0)) == 0 {
O
obscuren 已提交
597
		msg.gas = DefaultGas()
598 599 600
	}

	if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
O
obscuren 已提交
601
		msg.gasPrice = DefaultGasPrice()
602 603
	}

604
	block := self.CurrentBlock()
T
Taylor Gerring 已提交
605
	vmenv := core.NewEnv(statedb, self.backend.ChainManager(), msg, block)
606

607
	res, err := vmenv.Call(msg.from, msg.to, msg.data, msg.gas, msg.gasPrice, msg.value)
608
	return common.ToHex(res), err
609 610
}

611
func (self *XEth) Transact(fromStr, toStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) {
612
	var (
O
obscuren 已提交
613 614
		from             = common.HexToAddress(fromStr)
		to               = common.HexToAddress(toStr)
O
obscuren 已提交
615
		value            = common.NewValue(valueStr)
T
Taylor Gerring 已提交
616 617
		gas              = common.Big(gasStr)
		price            = common.Big(gasPriceStr)
618 619 620 621
		data             []byte
		contractCreation bool
	)

T
Taylor Gerring 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
	// TODO if no_private_key then
	//if _, exists := p.register[args.From]; exists {
	//	p.register[args.From] = append(p.register[args.From], args)
	//} else {
	/*
		account := accounts.Get(common.FromHex(args.From))
		if account != nil {
			if account.Unlocked() {
				if !unlockAccount(account) {
					return
				}
			}

			result, _ := account.Transact(common.FromHex(args.To), common.FromHex(args.Value), common.FromHex(args.Gas), common.FromHex(args.GasPrice), common.FromHex(args.Data))
			if len(result) > 0 {
				*reply = common.ToHex(result)
			}
		} else if _, exists := p.register[args.From]; exists {
			p.register[ags.From] = append(p.register[args.From], args)
		}
	*/

T
Taylor Gerring 已提交
644 645 646
	// TODO: align default values to have the same type, e.g. not depend on
	// common.Value conversions later on
	if gas.Cmp(big.NewInt(0)) == 0 {
O
obscuren 已提交
647
		gas = DefaultGas()
T
Taylor Gerring 已提交
648 649 650
	}

	if price.Cmp(big.NewInt(0)) == 0 {
O
obscuren 已提交
651
		price = DefaultGasPrice()
T
Taylor Gerring 已提交
652 653
	}

O
obscuren 已提交
654
	data = common.FromHex(codeStr)
O
obscuren 已提交
655
	if len(toStr) == 0 {
656 657 658 659 660
		contractCreation = true
	}

	var tx *types.Transaction
	if contractCreation {
T
Taylor Gerring 已提交
661
		tx = types.NewContractCreationTx(value.BigInt(), gas, price, data)
662
	} else {
T
Taylor Gerring 已提交
663
		tx = types.NewTransactionMessage(to, value.BigInt(), gas, price, data)
664 665
	}

T
Taylor Gerring 已提交
666
	state := self.backend.ChainManager().TxState()
O
obscuren 已提交
667
	nonce := state.NewNonce(from)
668 669
	tx.SetNonce(nonce)

670
	if err := self.sign(tx, from, false); err != nil {
671 672
		return "", err
	}
T
Taylor Gerring 已提交
673
	if err := self.backend.TxPool().Add(tx); err != nil {
674 675
		return "", err
	}
676 677 678 679

	if contractCreation {
		addr := core.AddressFromMessage(tx)
		pipelogger.Infof("Contract addr %x\n", addr)
680

O
obscuren 已提交
681
		return core.AddressFromMessage(tx).Hex(), nil
682
	}
O
obscuren 已提交
683
	return tx.Hash().Hex(), nil
684
}
685

O
obscuren 已提交
686
func (self *XEth) sign(tx *types.Transaction, from common.Address, didUnlock bool) error {
T
Taylor Gerring 已提交
687
	sig, err := self.backend.AccountManager().Sign(accounts.Account{Address: from.Bytes()}, tx.Hash().Bytes())
688 689 690 691
	if err == accounts.ErrLocked {
		if didUnlock {
			return fmt.Errorf("sender account still locked after successful unlock")
		}
O
obscuren 已提交
692
		if !self.frontend.UnlockAccount(from.Bytes()) {
693 694 695
			return fmt.Errorf("could not unlock sender account")
		}
		// retry signing, the account should now be unlocked.
696
		return self.sign(tx, from, true)
697 698 699 700 701 702 703
	} else if err != nil {
		return err
	}
	tx.SetSignatureValues(sig)
	return nil
}

704 705 706
// callmsg is the message type used for call transations.
type callmsg struct {
	from          *state.StateObject
O
obscuren 已提交
707
	to            common.Address
708 709 710 711 712 713
	gas, gasPrice *big.Int
	value         *big.Int
	data          []byte
}

// accessor boilerplate to implement core.Message
O
obscuren 已提交
714 715 716 717 718 719 720
func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
func (m callmsg) Nonce() uint64                 { return m.from.Nonce() }
func (m callmsg) To() *common.Address           { return &m.to }
func (m callmsg) GasPrice() *big.Int            { return m.gasPrice }
func (m callmsg) Gas() *big.Int                 { return m.gas }
func (m callmsg) Value() *big.Int               { return m.value }
func (m callmsg) Data() []byte                  { return m.data }
T
Taylor Gerring 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

type whisperFilter struct {
	messages []WhisperMessage
	timeout  time.Time
	id       int
}

func (w *whisperFilter) add(msgs ...WhisperMessage) {
	w.messages = append(w.messages, msgs...)
}
func (w *whisperFilter) get() []WhisperMessage {
	w.timeout = time.Now()
	tmp := w.messages
	w.messages = nil
	return tmp
}

type logFilter struct {
	logs    state.Logs
	timeout time.Time
	id      int
}

O
obscuren 已提交
744
func (l *logFilter) add(logs ...*state.Log) {
T
Taylor Gerring 已提交
745 746 747 748 749 750 751 752 753
	l.logs = append(l.logs, logs...)
}

func (l *logFilter) get() state.Logs {
	l.timeout = time.Now()
	tmp := l.logs
	l.logs = nil
	return tmp
}