Add simulated transactions generation in node_handler

pull/91/head^2
Rongjian Lan 6 years ago
parent e143e6fea8
commit b7db989f00
  1. 8
      consensus/bft.go
  2. 2
      consensus/consensus_engine.go
  3. 3
      core/block_validator.go
  4. 2
      core/chain_makers.go
  5. 2
      core/genesis.go
  6. 2
      core/rawdb/accessors_indexes_test.go
  7. 2
      core/state_processor.go
  8. 2
      core/tx_pool_test.go
  9. 14
      core/types/block.go
  10. 25
      harmony/main.go
  11. 1
      node/node.go
  12. 3
      node/node_handler.go
  13. 23
      node/worker/worker.go
  14. BIN
      transactions.rlp

@ -76,12 +76,12 @@ func (bft *Bft) Prepare(chain ChainReader, header *types.Header) error {
// Finalize implements consensus.Engine, accumulating the block and uncle rewards, // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
// setting the final state and assembling the block. // setting the final state and assembling the block.
func (bft *Bft) Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) { func (bft *Bft) Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, receipts []*types.Receipt) (*types.Block, error) {
// Accumulate any block and uncle rewards and commit the final state root // Accumulate any block and uncle rewards and commit the final state root
// Header seems complete, assemble into a block and return // Header seems complete, assemble into a block and return
accumulateRewards(chain.Config(), state, header, uncles) accumulateRewards(chain.Config(), state, header)
header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
return types.NewBlock(header, txs, uncles, receipts), nil return types.NewBlock(header, txs, receipts), nil
} }
// SealHash returns the hash of a block prior to it being sealed. // SealHash returns the hash of a block prior to it being sealed.
@ -114,6 +114,6 @@ func (bft *Bft) Seal(chain ChainReader, block *types.Block, results chan<- *type
// AccumulateRewards credits the coinbase of the given block with the mining // AccumulateRewards credits the coinbase of the given block with the mining
// reward. The total reward consists of the static block reward and rewards for // reward. The total reward consists of the static block reward and rewards for
// included uncles. The coinbase of each uncle block is also rewarded. // included uncles. The coinbase of each uncle block is also rewarded.
func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) { func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header) {
} }

@ -60,7 +60,7 @@ type Engine interface {
// Note: The block header and state database might be updated to reflect any // Note: The block header and state database might be updated to reflect any
// consensus rules that happen at finalization (e.g. block rewards). // consensus rules that happen at finalization (e.g. block rewards).
Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction,
uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) receipts []*types.Receipt) (*types.Block, error)
// Seal generates a new sealing request for the given input block and pushes // Seal generates a new sealing request for the given input block and pushes
// the result into the given channel. // the result into the given channel.

@ -64,9 +64,6 @@ func (v *BlockValidator) ValidateBody(block *types.Block) error {
//if err := v.engine.VerifyUncles(v.bc, block); err != nil { //if err := v.engine.VerifyUncles(v.bc, block); err != nil {
// return err // return err
//} //}
if hash := types.CalcUncleHash(block.Uncles()); hash != header.UncleHash {
return fmt.Errorf("uncle root hash mismatch: have %x, want %x", hash, header.UncleHash)
}
if hash := types.DeriveSha(block.Transactions()); hash != header.TxHash { if hash := types.DeriveSha(block.Transactions()); hash != header.TxHash {
return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash) return fmt.Errorf("transaction root hash mismatch: have %x, want %x", hash, header.TxHash)
} }

@ -184,7 +184,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
} }
if b.engine != nil { if b.engine != nil {
// Finalize and seal the block // Finalize and seal the block
block, _ := b.engine.Finalize(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts) block, _ := b.engine.Finalize(chainreader, b.header, statedb, b.txs, b.receipts)
// Write state changes to db // Write state changes to db
root, err := statedb.Commit(config.IsEIP158(b.header.Number)) root, err := statedb.Commit(config.IsEIP158(b.header.Number))

@ -254,7 +254,7 @@ func (g *Genesis) ToBlock(db hdb.Database) *types.Block {
statedb.Commit(false) statedb.Commit(false)
statedb.Database().TrieDB().Commit(root, true) statedb.Database().TrieDB().Commit(root, true)
return types.NewBlock(head, nil, nil, nil) return types.NewBlock(head, nil, nil)
} }
// Commit writes the block and state of a genesis specification to the database. // Commit writes the block and state of a genesis specification to the database.

@ -34,7 +34,7 @@ func TestLookupStorage(t *testing.T) {
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33}) tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3} txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil) block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil)
// Check that no transactions entries are in a pristine database // Check that no transactions entries are in a pristine database
for i, tx := range txs { for i, tx := range txs {

@ -75,7 +75,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
allLogs = append(allLogs, receipt.Logs...) allLogs = append(allLogs, receipt.Logs...)
} }
// Finalize the block, applying any consensus engine specific extras (e.g. block rewards) // Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles(), receipts) p.engine.Finalize(p.bc, header, statedb, block.Transactions(), receipts)
return receipts, allLogs, *usedGas, nil return receipts, allLogs, *usedGas, nil
} }

@ -53,7 +53,7 @@ type testBlockChain struct {
func (bc *testBlockChain) CurrentBlock() *types.Block { func (bc *testBlockChain) CurrentBlock() *types.Block {
return types.NewBlock(&types.Header{ return types.NewBlock(&types.Header{
GasLimit: bc.gasLimit, GasLimit: bc.gasLimit,
}, nil, nil, nil) }, nil, nil)
} }
func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block { func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {

@ -176,9 +176,9 @@ type storageblock struct {
// block. // block.
// //
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header // The values of TxHash, UncleHash, ReceiptHash and Bloom in header
// are ignored and set to values derived from the given txs, uncles // are ignored and set to values derived from the given txs,
// and receipts. // and receipts.
func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block { func NewBlock(header *Header, txs []*Transaction, receipts []*Receipt) *Block {
b := &Block{header: CopyHeader(header), td: new(big.Int)} b := &Block{header: CopyHeader(header), td: new(big.Int)}
// TODO: panic if len(txs) != len(receipts) // TODO: panic if len(txs) != len(receipts)
@ -197,16 +197,6 @@ func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*
b.header.Bloom = CreateBloom(receipts) b.header.Bloom = CreateBloom(receipts)
} }
if len(uncles) == 0 {
b.header.UncleHash = EmptyUncleHash
} else {
b.header.UncleHash = CalcUncleHash(uncles)
b.uncles = make([]*Header, len(uncles))
for i := range uncles {
b.uncles[i] = CopyHeader(uncles[i])
}
}
return b return b
} }

@ -9,6 +9,7 @@ import (
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/core/vm" "github.com/harmony-one/harmony/core/vm"
"github.com/harmony-one/harmony/db" "github.com/harmony-one/harmony/db"
"github.com/harmony-one/harmony/node/worker"
"math/big" "math/big"
) )
@ -56,7 +57,7 @@ func main() {
) )
genesis := gspec.MustCommit(database) genesis := gspec.MustCommit(database)
_ = genesis
chain, _ := core.NewBlockChain(database, nil, gspec.Config, consensus.NewFaker(), vm.Config{}, nil) chain, _ := core.NewBlockChain(database, nil, gspec.Config, consensus.NewFaker(), vm.Config{}, nil)
txpool := core.NewTxPool(core.DefaultTxPoolConfig, chainConfig, chain) txpool := core.NewTxPool(core.DefaultTxPoolConfig, chainConfig, chain)
@ -68,7 +69,7 @@ func main() {
} }
backend.txPool.AddLocals(pendingTxs) backend.txPool.AddLocals(pendingTxs)
// Generate a small n-block chain and an uncle block for it //// Generate a small n-block chain and an uncle block for it
n := 3 n := 3
if n > 0 { if n > 0 {
blocks, _ := core.GenerateChain(chainConfig, genesis, consensus.NewFaker(), database, n, func(i int, gen *core.BlockGen) { blocks, _ := core.GenerateChain(chainConfig, genesis, consensus.NewFaker(), database, n, func(i int, gen *core.BlockGen) {
@ -79,4 +80,24 @@ func main() {
fmt.Errorf("failed to insert origin chain: %v", err) fmt.Errorf("failed to insert origin chain: %v", err)
} }
} }
fmt.Println(chain.GetBlockByNumber(1).Root())
fmt.Println(chain.GetBlockByNumber(2).Root())
fmt.Println(chain.GetBlockByNumber(3).Root())
txs := make([]*types.Transaction, 100)
worker := worker.New(params.TestChainConfig, chain, consensus.NewFaker())
fmt.Println(worker.GetCurrentState().GetBalance(testBankAddress))
fmt.Println(worker.Commit().Root())
for i, _ := range txs {
randomUserKey, _ := crypto.GenerateKey()
randomUserAddress := crypto.PubkeyToAddress(randomUserKey.PublicKey)
tx, _ := types.SignTx(types.NewTransaction(worker.GetCurrentState().GetNonce(crypto.PubkeyToAddress(testBankKey.PublicKey)), randomUserAddress, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey)
txs[i] = tx
}
worker.CommitTransactions(txs, crypto.PubkeyToAddress(testBankKey.PublicKey))
fmt.Println(worker.GetCurrentState().GetBalance(testBankAddress))
fmt.Println(worker.Commit().Root())
} }

@ -229,6 +229,7 @@ func New(consensus *bft.Consensus, db *hdb.LDBDatabase) *Node {
node.Chain = chain node.Chain = chain
node.TxPool = core.NewTxPool(core.DefaultTxPoolConfig, params.TestChainConfig, chain) node.TxPool = core.NewTxPool(core.DefaultTxPoolConfig, params.TestChainConfig, chain)
node.BlockChannelAccount = make(chan *types.Block) node.BlockChannelAccount = make(chan *types.Block)
node.worker = worker.New(params.TestChainConfig, chain, bft.NewFaker())
} }
// Logger // Logger

@ -384,10 +384,11 @@ func (node *Node) WaitForConsensusReadyAccount(readySignal chan struct{}) {
for i, _ := range txs { for i, _ := range txs {
randomUserKey, _ := crypto.GenerateKey() randomUserKey, _ := crypto.GenerateKey()
randomUserAddress := crypto.PubkeyToAddress(randomUserKey.PublicKey) randomUserAddress := crypto.PubkeyToAddress(randomUserKey.PublicKey)
tx, _ := types.SignTx(types.NewTransaction(0, randomUserAddress, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, node.testBankKey) tx, _ := types.SignTx(types.NewTransaction(node.worker.GetCurrentState().GetNonce(crypto.PubkeyToAddress(node.testBankKey.PublicKey)), randomUserAddress, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, node.testBankKey)
txs[i] = tx txs[i] = tx
} }
node.worker.CommitTransactions(txs, crypto.PubkeyToAddress(node.testBankKey.PublicKey)) node.worker.CommitTransactions(txs, crypto.PubkeyToAddress(node.testBankKey.PublicKey))
newBlock = node.worker.Commit()
} }
// Send the new block to Consensus so it can be confirmed. // Send the new block to Consensus so it can be confirmed.

@ -3,6 +3,7 @@ package worker
import ( import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/harmony/consensus"
"github.com/harmony-one/harmony/core" "github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/state" "github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types" "github.com/harmony-one/harmony/core/types"
@ -28,6 +29,8 @@ type Worker struct {
chain *core.BlockChain chain *core.BlockChain
current *environment // An environment for current running cycle. current *environment // An environment for current running cycle.
engine consensus.Engine
gasFloor uint64 gasFloor uint64
gasCeil uint64 gasCeil uint64
} }
@ -47,6 +50,10 @@ func (w *Worker) commitTransaction(tx *types.Transaction, coinbase common.Addres
} }
func (w *Worker) CommitTransactions(txs []*types.Transaction, coinbase common.Address) { func (w *Worker) CommitTransactions(txs []*types.Transaction, coinbase common.Address) {
if w.current.gasPool == nil {
w.current.gasPool = new(core.GasPool).AddGas(w.current.header.GasLimit)
}
for _, tx := range txs { for _, tx := range txs {
w.commitTransaction(tx, coinbase) w.commitTransaction(tx, coinbase)
} }
@ -67,10 +74,24 @@ func (w *Worker) makeCurrent(parent *types.Block, header *types.Header) error {
return nil return nil
} }
func New(config *params.ChainConfig, chain *core.BlockChain) *Worker { func (w *Worker) GetCurrentState() *state.StateDB {
return w.current.state
}
func (w *Worker) Commit() *types.Block {
s := w.current.state.Copy()
block, err := w.engine.Finalize(w.chain, w.current.header, s, w.current.txs, w.current.receipts)
if err != nil {
return nil
}
return block
}
func New(config *params.ChainConfig, chain *core.BlockChain, engine consensus.Engine) *Worker {
worker := &Worker{ worker := &Worker{
config: config, config: config,
chain: chain, chain: chain,
engine: engine,
} }
worker.gasFloor = 0 worker.gasFloor = 0
worker.gasCeil = 10000000 worker.gasCeil = 10000000

Binary file not shown.
Loading…
Cancel
Save