Commit 45152dea authored by Jeffrey Wilcke's avatar Jeffrey Wilcke

Merge pull request #1181 from obscuren/txpool_fixes

cmd: transaction pool fixes and improvements 
parents 10fc7337 912cf7ba
...@@ -78,6 +78,12 @@ func (js *jsre) adminBindings() { ...@@ -78,6 +78,12 @@ func (js *jsre) adminBindings() {
miner.Set("stopAutoDAG", js.stopAutoDAG) miner.Set("stopAutoDAG", js.stopAutoDAG)
miner.Set("makeDAG", js.makeDAG) miner.Set("makeDAG", js.makeDAG)
admin.Set("txPool", struct{}{})
t, _ = admin.Get("txPool")
txPool := t.Object()
txPool.Set("pending", js.allPendingTransactions)
txPool.Set("queued", js.allQueuedTransactions)
admin.Set("debug", struct{}{}) admin.Set("debug", struct{}{})
t, _ = admin.Get("debug") t, _ = admin.Get("debug")
debug := t.Object() debug := t.Object()
...@@ -89,6 +95,7 @@ func (js *jsre) adminBindings() { ...@@ -89,6 +95,7 @@ func (js *jsre) adminBindings() {
debug.Set("setHead", js.setHead) debug.Set("setHead", js.setHead)
debug.Set("processBlock", js.debugBlock) debug.Set("processBlock", js.debugBlock)
debug.Set("seedhash", js.seedHash) debug.Set("seedhash", js.seedHash)
debug.Set("insertBlock", js.insertBlockRlp)
// undocumented temporary // undocumented temporary
debug.Set("waitForBlocks", js.waitForBlocks) debug.Set("waitForBlocks", js.waitForBlocks)
} }
...@@ -140,6 +147,32 @@ func (js *jsre) seedHash(call otto.FunctionCall) otto.Value { ...@@ -140,6 +147,32 @@ func (js *jsre) seedHash(call otto.FunctionCall) otto.Value {
return otto.UndefinedValue() return otto.UndefinedValue()
} }
func (js *jsre) allPendingTransactions(call otto.FunctionCall) otto.Value {
txs := js.ethereum.TxPool().GetTransactions()
ltxs := make([]*tx, len(txs))
for i, tx := range txs {
// no need to check err
ltxs[i] = newTx(tx)
}
v, _ := call.Otto.ToValue(ltxs)
return v
}
func (js *jsre) allQueuedTransactions(call otto.FunctionCall) otto.Value {
txs := js.ethereum.TxPool().GetQueuedTransactions()
ltxs := make([]*tx, len(txs))
for i, tx := range txs {
// no need to check err
ltxs[i] = newTx(tx)
}
v, _ := call.Otto.ToValue(ltxs)
return v
}
func (js *jsre) pendingTransactions(call otto.FunctionCall) otto.Value { func (js *jsre) pendingTransactions(call otto.FunctionCall) otto.Value {
txs := js.ethereum.TxPool().GetTransactions() txs := js.ethereum.TxPool().GetTransactions()
...@@ -237,16 +270,47 @@ func (js *jsre) debugBlock(call otto.FunctionCall) otto.Value { ...@@ -237,16 +270,47 @@ func (js *jsre) debugBlock(call otto.FunctionCall) otto.Value {
return otto.UndefinedValue() return otto.UndefinedValue()
} }
tstart := time.Now()
old := vm.Debug old := vm.Debug
vm.Debug = true vm.Debug = true
_, err = js.ethereum.BlockProcessor().RetryProcess(block) _, err = js.ethereum.BlockProcessor().RetryProcess(block)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
r, _ := call.Otto.ToValue(map[string]interface{}{"success": false, "time": time.Since(tstart).Seconds()})
return r
} }
vm.Debug = old vm.Debug = old
fmt.Println("ok") r, _ := call.Otto.ToValue(map[string]interface{}{"success": true, "time": time.Since(tstart).Seconds()})
return r
}
func (js *jsre) insertBlockRlp(call otto.FunctionCall) otto.Value {
tstart := time.Now()
var block types.Block
if call.Argument(0).IsString() {
blockRlp, _ := call.Argument(0).ToString()
err := rlp.DecodeBytes(common.Hex2Bytes(blockRlp), &block)
if err != nil {
fmt.Println(err)
return otto.UndefinedValue() return otto.UndefinedValue()
}
}
old := vm.Debug
vm.Debug = true
_, err := js.ethereum.BlockProcessor().RetryProcess(&block)
if err != nil {
fmt.Println(err)
r, _ := call.Otto.ToValue(map[string]interface{}{"success": false, "time": time.Since(tstart).Seconds()})
return r
}
vm.Debug = old
r, _ := call.Otto.ToValue(map[string]interface{}{"success": true, "time": time.Since(tstart).Seconds()})
return r
} }
func (js *jsre) setHead(call otto.FunctionCall) otto.Value { func (js *jsre) setHead(call otto.FunctionCall) otto.Value {
......
...@@ -68,7 +68,7 @@ func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) { ...@@ -68,7 +68,7 @@ func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
} }
// set up mock genesis with balance on the testAddress // set up mock genesis with balance on the testAddress
core.GenesisData = []byte(testGenesis) core.GenesisAccounts = []byte(testGenesis)
ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore")) ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore"))
am := accounts.NewManager(ks) am := accounts.NewManager(ks)
...@@ -250,7 +250,7 @@ func TestSignature(t *testing.T) { ...@@ -250,7 +250,7 @@ func TestSignature(t *testing.T) {
} }
func TestContract(t *testing.T) { func TestContract(t *testing.T) {
t.Skip()
tmp, repl, ethereum := testJEthRE(t) tmp, repl, ethereum := testJEthRE(t)
if err := ethereum.Start(); err != nil { if err := ethereum.Start(); err != nil {
t.Errorf("error starting ethereum: %v", err) t.Errorf("error starting ethereum: %v", err)
......
...@@ -345,8 +345,7 @@ func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, ex ...@@ -345,8 +345,7 @@ func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, ex
eventMux := new(event.TypeMux) eventMux := new(event.TypeMux)
pow := ethash.New() pow := ethash.New()
chain = core.NewChainManager(blockDB, stateDB, pow, eventMux) chain = core.NewChainManager(blockDB, stateDB, pow, eventMux)
txpool := core.NewTxPool(eventMux, chain.State, chain.GasLimit) proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
proc := core.NewBlockProcessor(stateDB, extraDB, pow, txpool, chain, eventMux)
chain.SetProcessor(proc) chain.SetProcessor(proc)
return chain, blockDB, stateDB, extraDB return chain, blockDB, stateDB, extraDB
} }
......
...@@ -36,16 +36,16 @@ func Big(num string) *big.Int { ...@@ -36,16 +36,16 @@ func Big(num string) *big.Int {
return n return n
} }
// BigD // Bytes2Big
// //
// Shortcut for new(big.Int).SetBytes(...) func BytesToBig(data []byte) *big.Int {
func Bytes2Big(data []byte) *big.Int {
n := new(big.Int) n := new(big.Int)
n.SetBytes(data) n.SetBytes(data)
return n return n
} }
func BigD(data []byte) *big.Int { return Bytes2Big(data) } func Bytes2Big(data []byte) *big.Int { return BytesToBig(data) }
func BigD(data []byte) *big.Int { return BytesToBig(data) }
func String2Big(num string) *big.Int { func String2Big(num string) *big.Int {
n := new(big.Int) n := new(big.Int)
......
...@@ -119,7 +119,7 @@ func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) { ...@@ -119,7 +119,7 @@ func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) {
testAddress := strings.TrimPrefix(testAccount.Address.Hex(), "0x") testAddress := strings.TrimPrefix(testAccount.Address.Hex(), "0x")
// set up mock genesis with balance on the testAddress // set up mock genesis with balance on the testAddress
core.GenesisData = []byte(`{ core.GenesisAccounts = []byte(`{
"` + testAddress + `": {"balance": "` + testBalance + `"} "` + testAddress + `": {"balance": "` + testBalance + `"}
}`) }`)
...@@ -181,7 +181,7 @@ func (self *testFrontend) applyTxs() { ...@@ -181,7 +181,7 @@ func (self *testFrontend) applyTxs() {
// end to end test // end to end test
func TestNatspecE2E(t *testing.T) { func TestNatspecE2E(t *testing.T) {
// t.Skip() t.Skip()
tf := testInit(t) tf := testInit(t)
defer tf.ethereum.Stop() defer tf.ethereum.Stop()
......
...@@ -38,14 +38,12 @@ type BlockProcessor struct { ...@@ -38,14 +38,12 @@ type BlockProcessor struct {
// Proof of work used for validating // Proof of work used for validating
Pow pow.PoW Pow pow.PoW
txpool *TxPool
events event.Subscription events event.Subscription
eventMux *event.TypeMux eventMux *event.TypeMux
} }
func NewBlockProcessor(db, extra common.Database, pow pow.PoW, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor { func NewBlockProcessor(db, extra common.Database, pow pow.PoW, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
sm := &BlockProcessor{ sm := &BlockProcessor{
db: db, db: db,
extraDb: extra, extraDb: extra,
...@@ -53,7 +51,6 @@ func NewBlockProcessor(db, extra common.Database, pow pow.PoW, txpool *TxPool, c ...@@ -53,7 +51,6 @@ func NewBlockProcessor(db, extra common.Database, pow pow.PoW, txpool *TxPool, c
Pow: pow, Pow: pow,
bc: chainManager, bc: chainManager,
eventMux: eventMux, eventMux: eventMux,
txpool: txpool,
} }
return sm return sm
...@@ -178,7 +175,6 @@ func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, err erro ...@@ -178,7 +175,6 @@ func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, err erro
return nil, ParentError(header.ParentHash) return nil, ParentError(header.ParentHash)
} }
parent := sm.bc.GetBlock(header.ParentHash) parent := sm.bc.GetBlock(header.ParentHash)
return sm.processWithParent(block, parent) return sm.processWithParent(block, parent)
} }
...@@ -254,14 +250,9 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs st ...@@ -254,14 +250,9 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs st
return nil, err return nil, err
} }
// Calculate the td for this block
//td = CalculateTD(block, parent)
// Sync the current block's state to the database // Sync the current block's state to the database
state.Sync() state.Sync()
// Remove transactions from the pool
sm.txpool.RemoveTransactions(block.Transactions())
// This puts transactions in a extra db for rpc // This puts transactions in a extra db for rpc
for i, tx := range block.Transactions() { for i, tx := range block.Transactions() {
putTx(sm.extraDb, tx, block, uint64(i)) putTx(sm.extraDb, tx, block, uint64(i))
......
...@@ -17,7 +17,7 @@ func proc() (*BlockProcessor, *ChainManager) { ...@@ -17,7 +17,7 @@ func proc() (*BlockProcessor, *ChainManager) {
var mux event.TypeMux var mux event.TypeMux
chainMan := NewChainManager(db, db, thePow(), &mux) chainMan := NewChainManager(db, db, thePow(), &mux)
return NewBlockProcessor(db, db, ezp.New(), nil, chainMan, &mux), chainMan return NewBlockProcessor(db, db, ezp.New(), chainMan, &mux), chainMan
} }
func TestNumber(t *testing.T) { func TestNumber(t *testing.T) {
......
...@@ -124,8 +124,7 @@ func newChainManager(block *types.Block, eventMux *event.TypeMux, db common.Data ...@@ -124,8 +124,7 @@ func newChainManager(block *types.Block, eventMux *event.TypeMux, db common.Data
// block processor with fake pow // block processor with fake pow
func newBlockProcessor(db common.Database, cman *ChainManager, eventMux *event.TypeMux) *BlockProcessor { func newBlockProcessor(db common.Database, cman *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
chainMan := newChainManager(nil, eventMux, db) chainMan := newChainManager(nil, eventMux, db)
txpool := NewTxPool(eventMux, chainMan.State, chainMan.GasLimit) bman := NewBlockProcessor(db, db, FakePow{}, chainMan, eventMux)
bman := NewBlockProcessor(db, db, FakePow{}, txpool, chainMan, eventMux)
return bman return bman
} }
......
...@@ -214,19 +214,6 @@ func (self *ChainManager) TransState() *state.StateDB { ...@@ -214,19 +214,6 @@ func (self *ChainManager) TransState() *state.StateDB {
return self.transState return self.transState
} }
func (self *ChainManager) TxState() *state.ManagedState {
self.tsmu.RLock()
defer self.tsmu.RUnlock()
return self.txState
}
func (self *ChainManager) setTxState(statedb *state.StateDB) {
self.tsmu.Lock()
defer self.tsmu.Unlock()
self.txState = state.ManageState(statedb)
}
func (self *ChainManager) setTransState(statedb *state.StateDB) { func (self *ChainManager) setTransState(statedb *state.StateDB) {
self.transState = statedb self.transState = statedb
} }
...@@ -560,6 +547,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) { ...@@ -560,6 +547,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
defer close(nonceQuit) defer close(nonceQuit)
for i, block := range chain { for i, block := range chain {
bstart := time.Now()
// Wait for block i's nonce to be verified before processing // Wait for block i's nonce to be verified before processing
// its state transition. // its state transition.
for nonceChecked[i] { for nonceChecked[i] {
...@@ -642,11 +630,11 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) { ...@@ -642,11 +630,11 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
queueEvent.canonicalCount++ queueEvent.canonicalCount++
if glog.V(logger.Debug) { if glog.V(logger.Debug) {
glog.Infof("[%v] inserted block #%d (%d TXs %d UNCs) (%x...)\n", time.Now().UnixNano(), block.Number(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4]) glog.Infof("[%v] inserted block #%d (%d TXs %d UNCs) (%x...). Took %v\n", time.Now().UnixNano(), block.Number(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4], time.Since(bstart))
} }
} else { } else {
if glog.V(logger.Detail) { if glog.V(logger.Detail) {
glog.Infof("inserted forked block #%d (TD=%v) (%d TXs %d UNCs) (%x...)\n", block.Number(), block.Difficulty(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4]) glog.Infof("inserted forked block #%d (TD=%v) (%d TXs %d UNCs) (%x...). Took %v\n", block.Number(), block.Difficulty(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4], time.Since(bstart))
} }
queue[i] = ChainSideEvent{block, logs} queue[i] = ChainSideEvent{block, logs}
...@@ -750,7 +738,7 @@ out: ...@@ -750,7 +738,7 @@ out:
case ev := <-events.Chan(): case ev := <-events.Chan():
switch ev := ev.(type) { switch ev := ev.(type) {
case queueEvent: case queueEvent:
for i, event := range ev.queue { for _, event := range ev.queue {
switch event := event.(type) { switch event := event.(type) {
case ChainEvent: case ChainEvent:
// We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
...@@ -759,12 +747,6 @@ out: ...@@ -759,12 +747,6 @@ out:
self.currentGasLimit = CalcGasLimit(event.Block) self.currentGasLimit = CalcGasLimit(event.Block)
self.eventMux.Post(ChainHeadEvent{event.Block}) self.eventMux.Post(ChainHeadEvent{event.Block})
} }
case ChainSplitEvent:
// On chain splits we need to reset the transaction state. We can't be sure whether the actual
// state of the accounts are still valid.
if i == ev.splitCount {
self.setTxState(state.New(event.Block.Root(), self.stateDb))
}
} }
self.eventMux.Post(event) self.eventMux.Post(event)
......
...@@ -267,8 +267,7 @@ func TestChainInsertions(t *testing.T) { ...@@ -267,8 +267,7 @@ func TestChainInsertions(t *testing.T) {
var eventMux event.TypeMux var eventMux event.TypeMux
chainMan := NewChainManager(db, db, thePow(), &eventMux) chainMan := NewChainManager(db, db, thePow(), &eventMux)
txPool := NewTxPool(&eventMux, chainMan.State, func() *big.Int { return big.NewInt(100000000) }) blockMan := NewBlockProcessor(db, db, nil, chainMan, &eventMux)
blockMan := NewBlockProcessor(db, db, nil, txPool, chainMan, &eventMux)
chainMan.SetProcessor(blockMan) chainMan.SetProcessor(blockMan)
const max = 2 const max = 2
...@@ -313,8 +312,7 @@ func TestChainMultipleInsertions(t *testing.T) { ...@@ -313,8 +312,7 @@ func TestChainMultipleInsertions(t *testing.T) {
} }
var eventMux event.TypeMux var eventMux event.TypeMux
chainMan := NewChainManager(db, db, thePow(), &eventMux) chainMan := NewChainManager(db, db, thePow(), &eventMux)
txPool := NewTxPool(&eventMux, chainMan.State, func() *big.Int { return big.NewInt(100000000) }) blockMan := NewBlockProcessor(db, db, nil, chainMan, &eventMux)
blockMan := NewBlockProcessor(db, db, nil, txPool, chainMan, &eventMux)
chainMan.SetProcessor(blockMan) chainMan.SetProcessor(blockMan)
done := make(chan bool, max) done := make(chan bool, max)
for i, chain := range chains { for i, chain := range chains {
......
...@@ -36,7 +36,7 @@ func GenesisBlock(db common.Database) *types.Block { ...@@ -36,7 +36,7 @@ func GenesisBlock(db common.Database) *types.Block {
Balance string Balance string
Code string Code string
} }
err := json.Unmarshal(GenesisData, &accounts) err := json.Unmarshal(GenesisAccounts, &accounts)
if err != nil { if err != nil {
fmt.Println("enable to decode genesis json data:", err) fmt.Println("enable to decode genesis json data:", err)
os.Exit(1) os.Exit(1)
...@@ -57,7 +57,7 @@ func GenesisBlock(db common.Database) *types.Block { ...@@ -57,7 +57,7 @@ func GenesisBlock(db common.Database) *types.Block {
return genesis return genesis
} }
var GenesisData = []byte(`{ var GenesisAccounts = []byte(`{
"0000000000000000000000000000000000000001": {"balance": "1"}, "0000000000000000000000000000000000000001": {"balance": "1"},
"0000000000000000000000000000000000000002": {"balance": "1"}, "0000000000000000000000000000000000000002": {"balance": "1"},
"0000000000000000000000000000000000000003": {"balance": "1"}, "0000000000000000000000000000000000000003": {"balance": "1"},
......
This diff is collapsed.
...@@ -37,21 +37,21 @@ func TestInvalidTransactions(t *testing.T) { ...@@ -37,21 +37,21 @@ func TestInvalidTransactions(t *testing.T) {
} }
from, _ := tx.From() from, _ := tx.From()
pool.currentState().AddBalance(from, big.NewInt(1)) pool.state.AddBalance(from, big.NewInt(1))
err = pool.Add(tx) err = pool.Add(tx)
if err != ErrInsufficientFunds { if err != ErrInsufficientFunds {
t.Error("expected", ErrInsufficientFunds) t.Error("expected", ErrInsufficientFunds)
} }
balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(tx.Gas(), tx.GasPrice())) balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(tx.Gas(), tx.GasPrice()))
pool.currentState().AddBalance(from, balance) pool.state.AddBalance(from, balance)
err = pool.Add(tx) err = pool.Add(tx)
if err != ErrIntrinsicGas { if err != ErrIntrinsicGas {
t.Error("expected", ErrIntrinsicGas, "got", err) t.Error("expected", ErrIntrinsicGas, "got", err)
} }
pool.currentState().SetNonce(from, 1) pool.state.SetNonce(from, 1)
pool.currentState().AddBalance(from, big.NewInt(0xffffffffffffff)) pool.state.AddBalance(from, big.NewInt(0xffffffffffffff))
tx.GasLimit = big.NewInt(100000) tx.GasLimit = big.NewInt(100000)
tx.Price = big.NewInt(1) tx.Price = big.NewInt(1)
tx.SignECDSA(key) tx.SignECDSA(key)
...@@ -67,26 +67,26 @@ func TestTransactionQueue(t *testing.T) { ...@@ -67,26 +67,26 @@ func TestTransactionQueue(t *testing.T) {
tx := transaction() tx := transaction()
tx.SignECDSA(key) tx.SignECDSA(key)
from, _ := tx.From() from, _ := tx.From()
pool.currentState().AddBalance(from, big.NewInt(1)) pool.state.AddBalance(from, big.NewInt(1))
pool.queueTx(tx) pool.queueTx(tx.Hash(), tx)
pool.checkQueue() pool.checkQueue()
if len(pool.txs) != 1 { if len(pool.pending) != 1 {
t.Error("expected valid txs to be 1 is", len(pool.txs)) t.Error("expected valid txs to be 1 is", len(pool.pending))
} }
tx = transaction() tx = transaction()
tx.SetNonce(1)
tx.SignECDSA(key) tx.SignECDSA(key)
from, _ = tx.From() from, _ = tx.From()
pool.currentState().SetNonce(from, 10) pool.state.SetNonce(from, 2)
tx.SetNonce(1) pool.queueTx(tx.Hash(), tx)
pool.queueTx(tx)
pool.checkQueue() pool.checkQueue()
if _, ok := pool.txs[tx.Hash()]; ok { if _, ok := pool.pending[tx.Hash()]; ok {
t.Error("expected transaction to be in tx pool") t.Error("expected transaction to be in tx pool")
} }
if len(pool.queue[from]) != 0 { if len(pool.queue[from]) > 0 {
t.Error("expected transaction queue to be empty. is", len(pool.queue[from])) t.Error("expected transaction queue to be empty. is", len(pool.queue[from]))
} }
...@@ -97,18 +97,18 @@ func TestTransactionQueue(t *testing.T) { ...@@ -97,18 +97,18 @@ func TestTransactionQueue(t *testing.T) {
tx1.SignECDSA(key) tx1.SignECDSA(key)
tx2.SignECDSA(key) tx2.SignECDSA(key)
tx3.SignECDSA(key) tx3.SignECDSA(key)
pool.queueTx(tx1) pool.queueTx(tx1.Hash(), tx1)
pool.queueTx(tx2) pool.queueTx(tx2.Hash(), tx2)
pool.queueTx(tx3) pool.queueTx(tx3.Hash(), tx3)
from, _ = tx1.From() from, _ = tx1.From()
pool.checkQueue() pool.checkQueue()
if len(pool.txs) != 1 { if len(pool.pending) != 1 {
t.Error("expected tx pool to be 1 =") t.Error("expected tx pool to be 1 =")
} }
if len(pool.queue[from]) != 2 {
if len(pool.queue[from]) != 3 { t.Error("expected len(queue) == 2, got", len(pool.queue[from]))
t.Error("expected transaction queue to be empty. is", len(pool.queue[from]))
} }
} }
...@@ -117,15 +117,15 @@ func TestRemoveTx(t *testing.T) { ...@@ -117,15 +117,15 @@ func TestRemoveTx(t *testing.T) {
tx := transaction() tx := transaction()
tx.SignECDSA(key) tx.SignECDSA(key)
from, _ := tx.From() from, _ := tx.From()
pool.currentState().AddBalance(from, big.NewInt(1)) pool.state.AddBalance(from, big.NewInt(1))
pool.queueTx(tx) pool.queueTx(tx.Hash(), tx)
pool.addTx(tx) pool.addTx(tx.Hash(), from, tx)
if len(pool.queue) != 1 { if len(pool.queue) != 1 {
t.Error("expected queue to be 1, got", len(pool.queue)) t.Error("expected queue to be 1, got", len(pool.queue))
} }
if len(pool.txs) != 1 { if len(pool.pending) != 1 {
t.Error("expected txs to be 1, got", len(pool.txs)) t.Error("expected txs to be 1, got", len(pool.pending))
} }
pool.removeTx(tx.Hash()) pool.removeTx(tx.Hash())
...@@ -134,8 +134,8 @@ func TestRemoveTx(t *testing.T) { ...@@ -134,8 +134,8 @@ func TestRemoveTx(t *testing.T) {
t.Error("expected queue to be 0, got", len(pool.queue)) t.Error("expected queue to be 0, got", len(pool.queue))
} }
if len(pool.txs) > 0 { if len(pool.pending) > 0 {
t.Error("expected txs to be 0, got", len(pool.txs)) t.Error("expected txs to be 0, got", len(pool.pending))
} }
} }
...@@ -146,9 +146,58 @@ func TestNegativeValue(t *testing.T) { ...@@ -146,9 +146,58 @@ func TestNegativeValue(t *testing.T) {
tx.Value().Set(big.NewInt(-1)) tx.Value().Set(big.NewInt(-1))
tx.SignECDSA(key) tx.SignECDSA(key)
from, _ := tx.From() from, _ := tx.From()
pool.currentState().AddBalance(from, big.NewInt(1)) pool.state.AddBalance(from, big.NewInt(1))
err := pool.Add(tx) err := pool.Add(tx)
if err != ErrNegativeValue { if err != ErrNegativeValue {
t.Error("expected", ErrNegativeValue, "got", err) t.Error("expected", ErrNegativeValue, "got", err)
} }
} }
func TestTransactionChainFork(t *testing.T) {
pool, key := setupTxPool()
addr := crypto.PubkeyToAddress(key.PublicKey)
pool.currentState().AddBalance(addr, big.NewInt(100000000000000))
tx := transaction()
tx.GasLimit = big.NewInt(100000)
tx.SignECDSA(key)
err := pool.add(tx)
if err != nil {
t.Error("didn't expect error", err)
}
pool.RemoveTransactions([]*types.Transaction{tx})
// reset the pool's internal state
pool.resetState()
err = pool.add(tx)
if err != nil {
t.Error("didn't expect error", err)
}
}
func TestTransactionDoubleNonce(t *testing.T) {
pool, key := setupTxPool()
addr := crypto.PubkeyToAddress(key.PublicKey)
pool.currentState().AddBalance(addr, big.NewInt(100000000000000))
tx := transaction()
tx.GasLimit = big.NewInt(100000)
tx.SignECDSA(key)
err := pool.add(tx)
if err != nil {
t.Error("didn't expect error", err)
}
tx2 := transaction()
tx2.GasLimit = big.NewInt(1000000)
tx2.SignECDSA(key)
err = pool.add(tx2)
if err != nil {
t.Error("didn't expect error", err)
}
if len(pool.pending) != 2 {
t.Error("expected 2 pending txs. Got", len(pool.pending))
}
}
package types package types
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"encoding/json"
"fmt" "fmt"
"io" "io"
"math/big" "math/big"
...@@ -80,6 +82,28 @@ func (self *Header) RlpData() interface{} { ...@@ -80,6 +82,28 @@ func (self *Header) RlpData() interface{} {
return self.rlpData(true) return self.rlpData(true)
} }
func (h *Header) UnmarshalJSON(data []byte) error {
var ext struct {
ParentHash string
Coinbase string
Difficulty string
GasLimit string
Time uint64
Extra string
}
dec := json.NewDecoder(bytes.NewReader(data))
if err := dec.Decode(&ext); err != nil {
return err
}
h.ParentHash = common.HexToHash(ext.ParentHash)
h.Coinbase = common.HexToAddress(ext.Coinbase)
h.Difficulty = common.String2Big(ext.Difficulty)
h.Time = ext.Time
h.Extra = []byte(ext.Extra)
return nil
}
func rlpHash(x interface{}) (h common.Hash) { func rlpHash(x interface{}) (h common.Hash) {
hw := sha3.NewKeccak256() hw := sha3.NewKeccak256()
rlp.Encode(hw, x) rlp.Encode(hw, x)
......
...@@ -64,7 +64,7 @@ func decodeTx(data []byte) (*Transaction, error) { ...@@ -64,7 +64,7 @@ func decodeTx(data []byte) (*Transaction, error) {
return &tx, rlp.Decode(bytes.NewReader(data), &tx) return &tx, rlp.Decode(bytes.NewReader(data), &tx)
} }
func defaultTestKey() (*ecdsa.PrivateKey, []byte) { func defaultTestKey() (*ecdsa.PrivateKey, common.Address) {
key := crypto.ToECDSA(common.Hex2Bytes("45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8")) key := crypto.ToECDSA(common.Hex2Bytes("45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"))
addr := crypto.PubkeyToAddress(key.PublicKey) addr := crypto.PubkeyToAddress(key.PublicKey)
return key, addr return key, addr
...@@ -85,7 +85,7 @@ func TestRecipientEmpty(t *testing.T) { ...@@ -85,7 +85,7 @@ func TestRecipientEmpty(t *testing.T) {
t.FailNow() t.FailNow()
} }
if !bytes.Equal(addr, from.Bytes()) { if addr != from {
t.Error("derived address doesn't match") t.Error("derived address doesn't match")
} }
} }
...@@ -105,7 +105,7 @@ func TestRecipientNormal(t *testing.T) { ...@@ -105,7 +105,7 @@ func TestRecipientNormal(t *testing.T) {
t.FailNow() t.FailNow()
} }
if !bytes.Equal(addr, from.Bytes()) { if addr != from {
t.Error("derived address doesn't match") t.Error("derived address doesn't match")
} }
} }
...@@ -2,13 +2,10 @@ package vm ...@@ -2,13 +2,10 @@ package vm
import ( import (
"errors" "errors"
"fmt"
"io"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/rlp"
) )
type Environment interface { type Environment interface {
...@@ -52,40 +49,3 @@ func Transfer(from, to Account, amount *big.Int) error { ...@@ -52,40 +49,3 @@ func Transfer(from, to Account, amount *big.Int) error {
return nil return nil
} }
type Log struct {
address common.Address
topics []common.Hash
data []byte
log uint64
}
func (self *Log) Address() common.Address {
return self.address
}
func (self *Log) Topics() []common.Hash {
return self.topics
}
func (self *Log) Data() []byte {
return self.data
}
func (self *Log) Number() uint64 {
return self.log
}
func (self *Log) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, []interface{}{self.address, self.topics, self.data})
}
/*
func (self *Log) RlpData() interface{} {
return []interface{}{self.address, common.ByteSliceToInterface(self.topics), self.data}
}
*/
func (self *Log) String() string {
return fmt.Sprintf("{%x %x %x}", self.address, self.data, self.topics)
}
package vm
import (
"testing"
checker "gopkg.in/check.v1"
)
func Test(t *testing.T) { checker.TestingT(t) }
package vm
// Tests have been removed in favour of general tests. If anything implementation specific needs testing, put it here
...@@ -201,7 +201,7 @@ func ImportBlockTestKey(privKeyBytes []byte) error { ...@@ -201,7 +201,7 @@ func ImportBlockTestKey(privKeyBytes []byte) error {
ecKey := ToECDSA(privKeyBytes) ecKey := ToECDSA(privKeyBytes)
key := &Key{ key := &Key{
Id: uuid.NewRandom(), Id: uuid.NewRandom(),
Address: common.BytesToAddress(PubkeyToAddress(ecKey.PublicKey)), Address: PubkeyToAddress(ecKey.PublicKey),
PrivateKey: ecKey, PrivateKey: ecKey,
} }
err := ks.StoreKey(key, "") err := ks.StoreKey(key, "")
...@@ -247,7 +247,7 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error ...@@ -247,7 +247,7 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error
ecKey := ToECDSA(ethPriv) ecKey := ToECDSA(ethPriv)
key = &Key{ key = &Key{
Id: nil, Id: nil,
Address: common.BytesToAddress(PubkeyToAddress(ecKey.PublicKey)), Address: PubkeyToAddress(ecKey.PublicKey),
PrivateKey: ecKey, PrivateKey: ecKey,
} }
derivedAddr := hex.EncodeToString(key.Address.Bytes()) // needed because .Hex() gives leading "0x" derivedAddr := hex.EncodeToString(key.Address.Bytes()) // needed because .Hex() gives leading "0x"
...@@ -305,7 +305,7 @@ func PKCS7Unpad(in []byte) []byte { ...@@ -305,7 +305,7 @@ func PKCS7Unpad(in []byte) []byte {
return in[:len(in)-int(padding)] return in[:len(in)-int(padding)]
} }
func PubkeyToAddress(p ecdsa.PublicKey) []byte { func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
pubBytes := FromECDSAPub(&p) pubBytes := FromECDSAPub(&p)
return Sha3(pubBytes[1:])[12:] return common.BytesToAddress(Sha3(pubBytes[1:])[12:])
} }
...@@ -124,7 +124,7 @@ func NewKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key { ...@@ -124,7 +124,7 @@ func NewKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
id := uuid.NewRandom() id := uuid.NewRandom()
key := &Key{ key := &Key{
Id: id, Id: id,
Address: common.BytesToAddress(PubkeyToAddress(privateKeyECDSA.PublicKey)), Address: PubkeyToAddress(privateKeyECDSA.PublicKey),
PrivateKey: privateKeyECDSA, PrivateKey: privateKeyECDSA,
} }
return key return key
......
...@@ -198,7 +198,6 @@ type Ethereum struct { ...@@ -198,7 +198,6 @@ type Ethereum struct {
net *p2p.Server net *p2p.Server
eventMux *event.TypeMux eventMux *event.TypeMux
txSub event.Subscription
miner *miner.Miner miner *miner.Miner
// logger logger.LogSystem // logger logger.LogSystem
...@@ -288,7 +287,7 @@ func New(config *Config) (*Ethereum, error) { ...@@ -288,7 +287,7 @@ func New(config *Config) (*Ethereum, error) {
eth.chainManager = core.NewChainManager(blockDb, stateDb, eth.pow, eth.EventMux()) eth.chainManager = core.NewChainManager(blockDb, stateDb, eth.pow, eth.EventMux())
eth.downloader = downloader.New(eth.EventMux(), eth.chainManager.HasBlock, eth.chainManager.GetBlock) eth.downloader = downloader.New(eth.EventMux(), eth.chainManager.HasBlock, eth.chainManager.GetBlock)
eth.txPool = core.NewTxPool(eth.EventMux(), eth.chainManager.State, eth.chainManager.GasLimit) eth.txPool = core.NewTxPool(eth.EventMux(), eth.chainManager.State, eth.chainManager.GasLimit)
eth.blockProcessor = core.NewBlockProcessor(stateDb, extraDb, eth.pow, eth.txPool, eth.chainManager, eth.EventMux()) eth.blockProcessor = core.NewBlockProcessor(stateDb, extraDb, eth.pow, eth.chainManager, eth.EventMux())
eth.chainManager.SetProcessor(eth.blockProcessor) eth.chainManager.SetProcessor(eth.blockProcessor)
eth.miner = miner.New(eth, eth.EventMux(), eth.pow) eth.miner = miner.New(eth, eth.EventMux(), eth.pow)
eth.miner.SetGasPrice(config.GasPrice) eth.miner.SetGasPrice(config.GasPrice)
...@@ -470,10 +469,6 @@ func (s *Ethereum) Start() error { ...@@ -470,10 +469,6 @@ func (s *Ethereum) Start() error {
s.whisper.Start() s.whisper.Start()
} }
// broadcast transactions
s.txSub = s.eventMux.Subscribe(core.TxPreEvent{})
go s.txBroadcastLoop()
glog.V(logger.Info).Infoln("Server started") glog.V(logger.Info).Infoln("Server started")
return nil return nil
} }
...@@ -531,8 +526,6 @@ func (self *Ethereum) AddPeer(nodeURL string) error { ...@@ -531,8 +526,6 @@ func (self *Ethereum) AddPeer(nodeURL string) error {
} }
func (s *Ethereum) Stop() { func (s *Ethereum) Stop() {
s.txSub.Unsubscribe() // quits txBroadcastLoop
s.net.Stop() s.net.Stop()
s.protocolManager.Stop() s.protocolManager.Stop()
s.chainManager.Stop() s.chainManager.Stop()
...@@ -552,28 +545,6 @@ func (s *Ethereum) WaitForShutdown() { ...@@ -552,28 +545,6 @@ func (s *Ethereum) WaitForShutdown() {
<-s.shutdownChan <-s.shutdownChan
} }
func (self *Ethereum) txBroadcastLoop() {
// automatically stops if unsubscribe
for obj := range self.txSub.Chan() {
event := obj.(core.TxPreEvent)
self.syncAccounts(event.Tx)
}
}
// keep accounts synced up
func (self *Ethereum) syncAccounts(tx *types.Transaction) {
from, err := tx.From()
if err != nil {
return
}
if self.accountManager.HasAccount(from) {
if self.chainManager.TxState().GetNonce(from) < tx.Nonce() {
self.chainManager.TxState().SetNonce(from, tx.Nonce())
}
}
}
// StartAutoDAG() spawns a go routine that checks the DAG every autoDAGcheckInterval // StartAutoDAG() spawns a go routine that checks the DAG every autoDAGcheckInterval
// by default that is 10 times per epoch // by default that is 10 times per epoch
// in epoch n, if we past autoDAGepochHeight within-epoch blocks, // in epoch n, if we past autoDAGepochHeight within-epoch blocks,
......
...@@ -494,10 +494,6 @@ func (self *worker) commitTransactions(transactions types.Transactions) { ...@@ -494,10 +494,6 @@ func (self *worker) commitTransactions(transactions types.Transactions) {
err := self.commitTransaction(tx) err := self.commitTransaction(tx)
switch { switch {
case core.IsNonceErr(err) || core.IsInvalidTxErr(err): case core.IsNonceErr(err) || core.IsInvalidTxErr(err):
// Remove invalid transactions
from, _ := tx.From()
self.chain.TxState().RemoveNonce(from, tx.Nonce())
current.remove.Add(tx.Hash()) current.remove.Add(tx.Hash())
if glog.V(logger.Detail) { if glog.V(logger.Detail) {
......
...@@ -936,24 +936,23 @@ func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceS ...@@ -936,24 +936,23 @@ func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceS
tx = types.NewTransactionMessage(to, value, gas, price, data) tx = types.NewTransactionMessage(to, value, gas, price, data)
} }
state := self.backend.ChainManager().TxState() state := self.backend.TxPool().State()
var nonce uint64 var nonce uint64
if len(nonceStr) != 0 { if len(nonceStr) != 0 {
nonce = common.Big(nonceStr).Uint64() nonce = common.Big(nonceStr).Uint64()
} else { } else {
nonce = state.NewNonce(from) nonce = state.GetNonce(from)
} }
tx.SetNonce(nonce) tx.SetNonce(nonce)
if err := self.sign(tx, from, false); err != nil { if err := self.sign(tx, from, false); err != nil {
state.RemoveNonce(from, tx.Nonce())
return "", err return "", err
} }
if err := self.backend.TxPool().Add(tx); err != nil { if err := self.backend.TxPool().Add(tx); err != nil {
state.RemoveNonce(from, tx.Nonce())
return "", err return "", err
} }
state.SetNonce(from, nonce+1)
if contractCreation { if contractCreation {
addr := core.AddressFromMessage(tx) addr := core.AddressFromMessage(tx)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment