xeth.go 17.2 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
func (self *XEth) AtStateNum(num int64) *XEth {
T
Taylor Gerring 已提交
139
	block := self.getBlockByHeight(num)
T
Taylor Gerring 已提交
140 141 142

	var st *state.StateDB
	if block != nil {
T
Taylor Gerring 已提交
143
		st = state.New(block.Root(), self.backend.StateDb())
T
Taylor Gerring 已提交
144
	} else {
T
Taylor Gerring 已提交
145
		st = self.backend.ChainManager().State()
T
Taylor Gerring 已提交
146
	}
T
Taylor Gerring 已提交
147 148

	return self.withState(st)
T
Taylor Gerring 已提交
149 150
}

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

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

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

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

T
Taylor Gerring 已提交
164 165 166
func (self *XEth) getBlockByHeight(height int64) *types.Block {
	var num uint64

167 168
	if height < 0 {
		num = self.CurrentBlock().NumberU64() + uint64(-1*height)
T
Taylor Gerring 已提交
169 170 171 172 173 174 175
	} else {
		num = uint64(height)
	}

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

O
obscuren 已提交
176
func (self *XEth) BlockByHash(strHash string) *Block {
O
obscuren 已提交
177
	hash := common.HexToHash(strHash)
T
Taylor Gerring 已提交
178
	block := self.backend.ChainManager().GetBlock(hash)
O
obscuren 已提交
179

O
obscuren 已提交
180
	return NewBlock(block)
O
obscuren 已提交
181 182
}

T
Taylor Gerring 已提交
183 184
func (self *XEth) EthBlockByHash(strHash string) *types.Block {
	hash := common.HexToHash(strHash)
T
Taylor Gerring 已提交
185
	block := self.backend.ChainManager().GetBlock(hash)
T
Taylor Gerring 已提交
186 187 188 189

	return block
}

190
func (self *XEth) EthTransactionByHash(hash string) (tx *types.Transaction, blhash common.Hash, blnum *big.Int, txi uint64) {
T
Taylor Gerring 已提交
191
	data, _ := self.backend.ExtraDb().Get(common.FromHex(hash))
O
obscuren 已提交
192
	if len(data) != 0 {
193
		tx = types.NewTransactionFromBytes(data)
O
obscuren 已提交
194
	}
195

T
Taylor Gerring 已提交
196 197 198 199 200
	// meta
	var txExtra struct {
		BlockHash  common.Hash
		BlockIndex int64
		Index      uint64
201
	}
T
Taylor Gerring 已提交
202 203 204 205 206 207 208 209

	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
		blnum = big.NewInt(txExtra.BlockIndex)
		txi = txExtra.Index
210 211 212
	}

	return
O
obscuren 已提交
213 214
}

T
Taylor Gerring 已提交
215
func (self *XEth) BlockByNumber(num int64) *Block {
T
Taylor Gerring 已提交
216
	return NewBlock(self.getBlockByHeight(num))
O
obscuren 已提交
217 218
}

T
Taylor Gerring 已提交
219
func (self *XEth) EthBlockByNumber(num int64) *types.Block {
T
Taylor Gerring 已提交
220
	return self.getBlockByHeight(num)
T
Taylor Gerring 已提交
221 222
}

T
Taylor Gerring 已提交
223 224 225 226
func (self *XEth) CurrentBlock() *types.Block {
	return self.backend.ChainManager().CurrentBlock()
}

O
obscuren 已提交
227
func (self *XEth) Block(v interface{}) *Block {
O
obscuren 已提交
228
	if n, ok := v.(int32); ok {
T
Taylor Gerring 已提交
229
		return self.BlockByNumber(int64(n))
O
obscuren 已提交
230 231 232
	} else if str, ok := v.(string); ok {
		return self.BlockByHash(str)
	} else if f, ok := v.(float64); ok { // Don't ask ...
T
Taylor Gerring 已提交
233
		return self.BlockByNumber(int64(f))
O
obscuren 已提交
234 235 236 237 238
	}

	return nil
}

O
obscuren 已提交
239
func (self *XEth) Accounts() []string {
240
	// TODO: check err?
T
Taylor Gerring 已提交
241
	accounts, _ := self.backend.AccountManager().Accounts()
242 243
	accountAddresses := make([]string, len(accounts))
	for i, ac := range accounts {
244
		accountAddresses[i] = common.ToHex(ac.Address)
245 246
	}
	return accountAddresses
O
obscuren 已提交
247 248
}

249 250 251 252 253 254 255 256 257 258
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 已提交
259
func (self *XEth) PeerCount() int {
T
Taylor Gerring 已提交
260
	return self.backend.PeerCount()
O
obscuren 已提交
261 262
}

O
obscuren 已提交
263
func (self *XEth) IsMining() bool {
T
Taylor Gerring 已提交
264
	return self.backend.IsMining()
O
obscuren 已提交
265 266
}

267
func (self *XEth) EthVersion() string {
268
	return fmt.Sprintf("%d", self.backend.EthVersion())
269 270
}

T
Taylor Gerring 已提交
271
func (self *XEth) NetworkVersion() string {
272
	return fmt.Sprintf("%d", self.backend.NetVersion())
273 274 275
}

func (self *XEth) WhisperVersion() string {
276
	return fmt.Sprintf("%d", self.backend.ShhVersion())
T
Taylor Gerring 已提交
277 278 279
}

func (self *XEth) ClientVersion() string {
280
	return self.backend.ClientVersion()
T
Taylor Gerring 已提交
281 282
}

T
Taylor Gerring 已提交
283
func (self *XEth) SetMining(shouldmine bool) bool {
T
Taylor Gerring 已提交
284
	ismining := self.backend.IsMining()
T
Taylor Gerring 已提交
285
	if shouldmine && !ismining {
T
Taylor Gerring 已提交
286
		err := self.backend.StartMining()
287
		return err == nil
T
Taylor Gerring 已提交
288 289
	}
	if ismining && !shouldmine {
T
Taylor Gerring 已提交
290
		self.backend.StopMining()
T
Taylor Gerring 已提交
291
	}
T
Taylor Gerring 已提交
292
	return self.backend.IsMining()
T
Taylor Gerring 已提交
293 294
}

O
obscuren 已提交
295
func (self *XEth) IsListening() bool {
T
Taylor Gerring 已提交
296
	return self.backend.IsListening()
O
obscuren 已提交
297 298
}

O
obscuren 已提交
299
func (self *XEth) Coinbase() string {
Z
zelig 已提交
300 301
	eb, _ := self.backend.Etherbase()
	return eb.Hex()
O
obscuren 已提交
302 303
}

O
obscuren 已提交
304
func (self *XEth) NumberToHuman(balance string) string {
O
obscuren 已提交
305
	b := common.Big(balance)
O
obscuren 已提交
306

O
obscuren 已提交
307
	return common.CurrencyToString(b)
O
obscuren 已提交
308 309
}

O
obscuren 已提交
310
func (self *XEth) StorageAt(addr, storageAddr string) string {
311
	return common.ToHex(self.State().state.GetState(common.HexToAddress(addr), common.HexToHash(storageAddr)))
O
obscuren 已提交
312 313
}

O
obscuren 已提交
314
func (self *XEth) BalanceAt(addr string) string {
O
obscuren 已提交
315
	return common.ToHex(self.State().state.GetBalance(common.HexToAddress(addr)).Bytes())
O
obscuren 已提交
316 317
}

O
obscuren 已提交
318
func (self *XEth) TxCountAt(address string) int {
319
	return int(self.State().state.GetNonce(common.HexToAddress(address)))
O
obscuren 已提交
320 321
}

O
obscuren 已提交
322
func (self *XEth) CodeAt(address string) string {
323
	return common.ToHex(self.State().state.GetCode(common.HexToAddress(address)))
O
obscuren 已提交
324 325
}

O
obscuren 已提交
326
func (self *XEth) IsContract(address string) bool {
327
	return len(self.State().SafeGet(address).Code()) > 0
O
obscuren 已提交
328 329
}

O
obscuren 已提交
330
func (self *XEth) SecretToAddress(key string) string {
O
obscuren 已提交
331
	pair, err := crypto.NewKeyPairFromSec(common.FromHex(key))
O
obscuren 已提交
332 333 334 335
	if err != nil {
		return ""
	}

336
	return common.ToHex(pair.Address())
O
obscuren 已提交
337 338
}

T
Taylor Gerring 已提交
339
func (self *XEth) RegisterFilter(earliest, latest int64, skip, max int, address []string, topics [][]string) int {
T
Taylor Gerring 已提交
340
	var id int
T
Taylor Gerring 已提交
341
	filter := core.NewFilter(self.backend)
T
Taylor Gerring 已提交
342 343 344 345 346 347
	filter.SetEarliestBlock(earliest)
	filter.SetLatestBlock(latest)
	filter.SetSkip(skip)
	filter.SetMax(max)
	filter.SetAddress(cAddress(address))
	filter.SetTopics(cTopics(topics))
T
Taylor Gerring 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
	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 已提交
372
	filter := core.NewFilter(self.backend)
T
Taylor Gerring 已提交
373 374 375

	switch word {
	case "pending":
376 377 378 379 380 381
		filter.PendingCallback = func(tx *types.Transaction) {
			self.logMut.Lock()
			defer self.logMut.Unlock()

			self.logs[id].add(&state.StateLog{})
		}
T
Taylor Gerring 已提交
382
	case "latest":
383 384 385 386 387 388 389 390 391
		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)
			}
			self.logs[id].add(&state.StateLog{})
		}
T
Taylor Gerring 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
	}

	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 已提交
423
func (self *XEth) AllLogs(earliest, latest int64, skip, max int, address []string, topics [][]string) state.Logs {
T
Taylor Gerring 已提交
424
	filter := core.NewFilter(self.backend)
T
Taylor Gerring 已提交
425 426 427 428 429 430
	filter.SetEarliestBlock(earliest)
	filter.SetLatestBlock(latest)
	filter.SetSkip(skip)
	filter.SetMax(max)
	filter.SetAddress(cAddress(address))
	filter.SetTopics(cTopics(topics))
T
Taylor Gerring 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

	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 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
// 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 已提交
500 501 502 503 504
type KeyVal struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

O
obscuren 已提交
505
func (self *XEth) EachStorage(addr string) string {
O
obscuren 已提交
506 507 508 509
	var values []KeyVal
	object := self.State().SafeGet(addr)
	it := object.Trie().Iterator()
	for it.Next() {
O
obscuren 已提交
510
		values = append(values, KeyVal{common.ToHex(object.Trie().GetKey(it.Key)), common.ToHex(it.Value)})
O
obscuren 已提交
511 512 513 514 515 516 517 518 519 520
	}

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

	return string(valuesJson)
}

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

524
	return "0x" + common.ToHex(padded)
O
obscuren 已提交
525 526
}

O
obscuren 已提交
527
func (self *XEth) FromAscii(str string) string {
O
obscuren 已提交
528
	if common.IsHex(str) {
O
obscuren 已提交
529 530 531
		str = str[2:]
	}

O
obscuren 已提交
532
	return string(bytes.Trim(common.FromHex(str), "\x00"))
O
obscuren 已提交
533 534
}

O
obscuren 已提交
535
func (self *XEth) FromNumber(str string) string {
O
obscuren 已提交
536
	if common.IsHex(str) {
O
obscuren 已提交
537 538 539
		str = str[2:]
	}

O
obscuren 已提交
540
	return common.BigD(common.FromHex(str)).String()
O
obscuren 已提交
541 542
}

O
obscuren 已提交
543
func (self *XEth) PushTx(encodedTx string) (string, error) {
O
obscuren 已提交
544
	tx := types.NewTransactionFromBytes(common.FromHex(encodedTx))
T
Taylor Gerring 已提交
545
	err := self.backend.TxPool().Add(tx)
O
obscuren 已提交
546 547 548 549 550 551
	if err != nil {
		return "", err
	}

	if tx.To() == nil {
		addr := core.AddressFromMessage(tx)
O
obscuren 已提交
552
		return addr.Hex(), nil
O
obscuren 已提交
553
	}
O
obscuren 已提交
554
	return tx.Hash().Hex(), nil
O
obscuren 已提交
555
}
556

557
func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, error) {
T
Taylor Gerring 已提交
558
	statedb := self.State().State() //self.eth.ChainManager().TransState()
559
	msg := callmsg{
O
obscuren 已提交
560 561
		from:     statedb.GetOrNewStateObject(common.HexToAddress(fromStr)),
		to:       common.HexToAddress(toStr),
O
obscuren 已提交
562 563 564 565
		gas:      common.Big(gasStr),
		gasPrice: common.Big(gasPriceStr),
		value:    common.Big(valueStr),
		data:     common.FromHex(dataStr),
566
	}
B
Bas van Kervel 已提交
567

568
	if msg.gas.Cmp(big.NewInt(0)) == 0 {
B
Bas van Kervel 已提交
569
		msg.gas = self.DefaultGas()
570 571 572
	}

	if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
B
Bas van Kervel 已提交
573
		msg.gasPrice = self.DefaultGasPrice()
574 575
	}

576
	block := self.CurrentBlock()
T
Taylor Gerring 已提交
577
	vmenv := core.NewEnv(statedb, self.backend.ChainManager(), msg, block)
578

579
	res, err := vmenv.Call(msg.from, msg.to, msg.data, msg.gas, msg.gasPrice, msg.value)
580
	return common.ToHex(res), err
581 582
}

583
func (self *XEth) Transact(fromStr, toStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) {
584
	var (
O
obscuren 已提交
585 586
		from             = common.HexToAddress(fromStr)
		to               = common.HexToAddress(toStr)
O
obscuren 已提交
587
		value            = common.NewValue(valueStr)
T
Taylor Gerring 已提交
588 589
		gas              = common.Big(gasStr)
		price            = common.Big(gasPriceStr)
590 591 592 593
		data             []byte
		contractCreation bool
	)

T
Taylor Gerring 已提交
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
	// 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 已提交
616 617 618
	// 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 {
B
Bas van Kervel 已提交
619
		gas = self.DefaultGas()
T
Taylor Gerring 已提交
620 621 622
	}

	if price.Cmp(big.NewInt(0)) == 0 {
B
Bas van Kervel 已提交
623
		price = self.DefaultGasPrice()
T
Taylor Gerring 已提交
624 625
	}

O
obscuren 已提交
626
	data = common.FromHex(codeStr)
O
obscuren 已提交
627
	if len(toStr) == 0 {
628 629 630 631 632
		contractCreation = true
	}

	var tx *types.Transaction
	if contractCreation {
T
Taylor Gerring 已提交
633
		tx = types.NewContractCreationTx(value.BigInt(), gas, price, data)
634
	} else {
T
Taylor Gerring 已提交
635
		tx = types.NewTransactionMessage(to, value.BigInt(), gas, price, data)
636 637
	}

T
Taylor Gerring 已提交
638
	state := self.backend.ChainManager().TxState()
O
obscuren 已提交
639
	nonce := state.NewNonce(from)
640 641
	tx.SetNonce(nonce)

642
	if err := self.sign(tx, from, false); err != nil {
643 644
		return "", err
	}
T
Taylor Gerring 已提交
645
	if err := self.backend.TxPool().Add(tx); err != nil {
646 647
		return "", err
	}
648 649 650 651

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

O
obscuren 已提交
653
		return core.AddressFromMessage(tx).Hex(), nil
654
	}
O
obscuren 已提交
655
	return tx.Hash().Hex(), nil
656
}
657

O
obscuren 已提交
658
func (self *XEth) sign(tx *types.Transaction, from common.Address, didUnlock bool) error {
T
Taylor Gerring 已提交
659
	sig, err := self.backend.AccountManager().Sign(accounts.Account{Address: from.Bytes()}, tx.Hash().Bytes())
660 661 662 663
	if err == accounts.ErrLocked {
		if didUnlock {
			return fmt.Errorf("sender account still locked after successful unlock")
		}
O
obscuren 已提交
664
		if !self.frontend.UnlockAccount(from.Bytes()) {
665 666 667
			return fmt.Errorf("could not unlock sender account")
		}
		// retry signing, the account should now be unlocked.
668
		return self.sign(tx, from, true)
669 670 671 672 673 674 675
	} else if err != nil {
		return err
	}
	tx.SetSignatureValues(sig)
	return nil
}

676 677 678
// callmsg is the message type used for call transations.
type callmsg struct {
	from          *state.StateObject
O
obscuren 已提交
679
	to            common.Address
680 681 682 683 684 685
	gas, gasPrice *big.Int
	value         *big.Int
	data          []byte
}

// accessor boilerplate to implement core.Message
O
obscuren 已提交
686 687 688 689 690 691 692
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 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725

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
}

func (l *logFilter) add(logs ...state.Log) {
	l.logs = append(l.logs, logs...)
}

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