From f526503defa0feb23afcd588af6645789481ad71 Mon Sep 17 00:00:00 2001 From: paladz <453256728@qq.com> Date: Tue, 26 Sep 2017 15:38:43 +0800 Subject: [PATCH] code need to be little better elegant --- blockchain/reactor.go | 16 +++++--------- consensus/general.go | 2 +- mining/cpuminer/cpuminer.go | 14 ++++--------- mining/mining.go | 51 +++++++++++++++++++-------------------------- mining/mining_test.go | 2 +- node/node.go | 18 ++-------------- protocol/block.go | 23 +++++++++++++------- protocol/protocol.go | 1 + 8 files changed, 51 insertions(+), 76 deletions(-) diff --git a/blockchain/reactor.go b/blockchain/reactor.go index 87131525..cd4fb668 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -411,19 +411,13 @@ FOR_LOOP: if block == nil { break SYNC_LOOP } - bcR.pool.PopRequest() - snap, err := bcR.chain.ApplyValidBlock(block) - if err != nil { - fmt.Printf("Failed to apply valid block: %v \n", err) - break SYNC_LOOP - } - err = bcR.chain.CommitAppliedBlock(nil, block, snap) - if err != nil { - fmt.Printf("Failed to commit block: %v \n", err) - break SYNC_LOOP + + if err := bcR.chain.AddBlock(nil, block); err == nil { + bcR.Logger.Info("finish to sync commit block", "blockHeigh", block.BlockHeader.Height) + } else { + bcR.Logger.Info("fail to sync commit block", "blockHeigh", block.BlockHeader.Height, "error", err) } - bcR.Logger.Info("finish to sync commit block", block.BlockHeader.Height) } continue FOR_LOOP case <-bcR.Quit: diff --git a/consensus/general.go b/consensus/general.go index 2ae80eb4..5362e607 100644 --- a/consensus/general.go +++ b/consensus/general.go @@ -36,5 +36,5 @@ func BlockSubsidy(height uint64) uint64 { } func InitBlock() []byte { - return []byte("03010000000000000000000000000000000000000000000000000000000000000000008a9edde9ea2b40dc4e0aaee625a0b0d72c9e6fef0a70cb016ba55d86e85ebec9da87651aa15109492159980684155da19e87de0d1b37b35c1a1123770ec1dcc710aabe77607cce00fbdfb3e6cc99b32601070107008a9edde9ea2b000001012cffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8080ccdee2a69fb314010151000000") + return []byte("0301000000000000000000000000000000000000000000000000000000000000000000ece090e7eb2b4078a79ed5c640a026361c4af77a37342e503cc68493229996e11dd9be38b18f5b492159980684155da19e87de0d1b37b35c1a1123770ec1dcc710aabe77607cce00b1c5a181808080802e0107010700ece090e7eb2b000001012cffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8080ccdee2a69fb314010151000000") } diff --git a/mining/cpuminer/cpuminer.go b/mining/cpuminer/cpuminer.go index bebaf3e2..11c80d61 100644 --- a/mining/cpuminer/cpuminer.go +++ b/mining/cpuminer/cpuminer.go @@ -94,17 +94,11 @@ out: } if m.solveBlock(block, ticker, quit) { - snap, err := m.chain.ApplyValidBlock(block) - if err != nil { - fmt.Printf("Failed to apply valid block: %v \n", err) - continue - } - err = m.chain.CommitAppliedBlock(nil, block, snap) - if err != nil { - fmt.Printf("Failed to commit block: %v \n", err) - continue + if err := m.chain.AddBlock(nil, block); err == nil { + fmt.Printf("finish commit block heigh %d \n", block.BlockHeader.Height) + } else { + fmt.Printf("fail commit block heigh %d, err: %v \n", block.BlockHeader.Height, err) } - fmt.Printf("finish commit block heigh %d \n", block.BlockHeader.Height) } } diff --git a/mining/mining.go b/mining/mining.go index ab509fbe..9a290e50 100644 --- a/mining/mining.go +++ b/mining/mining.go @@ -53,21 +53,13 @@ func createCoinbaseTx(amount uint64, blockHeight uint64, addr []byte) (*legacy.T func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, addr []byte) (*legacy.Block, error) { // Extend the most recently known best block. var err error - newSnap := state.Empty() - var blockData *bc.Block - nextBlockHeight := uint64(1) - preBlockHash := bc.Hash{} - - block, snap := c.State() - if block != nil { - nextBlockHeight = block.BlockHeader.Height + 1 - preBlockHash = block.Hash() - newSnap = state.Copy(snap) - blockData = legacy.MapBlock(block) - } + preBlock, snap := c.State() + newSnap := state.Copy(snap) + nextBlockHeight := preBlock.BlockHeader.Height + 1 + preBcBlock := legacy.MapBlock(preBlock) txDescs := txPool.GetTransactions() - blockTxns := make([]*legacy.Tx, 0, len(txDescs)) + txEntries := make([]*bc.Tx, 0, len(txDescs)) blockWeight := uint64(0) txFee := uint64(0) @@ -75,46 +67,47 @@ func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, addr []byte) ( BlockHeader: legacy.BlockHeader{ Version: 1, Height: nextBlockHeight, - PreviousBlockHash: preBlockHash, + PreviousBlockHash: preBlock.Hash(), TimestampMS: bc.Millis(time.Now()), BlockCommitment: legacy.BlockCommitment{}, Bits: consensus.CalcNextRequiredDifficulty(nil, nil), }, + Transactions: make([]*legacy.Tx, 0, len(txDescs)), } newSnap.PruneNonces(b.BlockHeader.TimestampMS) - var txEntries []*bc.Tx + appendTx := func(tx *legacy.Tx, weight, fee uint64) { + b.Transactions = append(b.Transactions, tx) + txEntries = append(txEntries, tx.Tx) + blockWeight += weight + txFee += fee + } + for _, txDesc := range txDescs { tx := txDesc.Tx.Tx - blockPlusTxWeight := blockWeight + txDesc.Weight - if blockPlusTxWeight > consensus.MaxBlockSzie { + if blockWeight+txDesc.Weight > consensus.MaxBlockSzie-consensus.MaxTxSize { break } - if err := newSnap.ApplyTx(tx); err != nil { txPool.RemoveTransaction(&tx.ID) continue } - - if _, err := validation.ValidateTx(tx, blockData); err != nil { + if _, err := validation.ValidateTx(tx, preBcBlock); err != nil { txPool.RemoveTransaction(&tx.ID) continue } - blockTxns = append(blockTxns, txDesc.Tx) - txEntries = append(txEntries, tx) - blockWeight = blockPlusTxWeight - txFee += txDesc.Fee + appendTx(txDesc.Tx, txDesc.Weight, txDesc.Fee) } cbTx, _ := createCoinbaseTx(txFee, nextBlockHeight, addr) - newSnap.ApplyTx(cbTx.Tx) - blockTxns = append([]*legacy.Tx{cbTx}, blockTxns...) - - b.Transactions = blockTxns + if err := newSnap.ApplyTx(cbTx.Tx); err != nil { + return nil, errors.Wrap(err, "fail on append coinbase transaction to snap") + } + appendTx(cbTx, 0, 0) - b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.MerkleRoot(txEntries) b.BlockHeader.BlockCommitment.AssetsMerkleRoot = newSnap.Tree.RootHash() + b.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.MerkleRoot(txEntries) if err != nil { return nil, errors.Wrap(err, "calculating tx merkle root") } diff --git a/mining/mining_test.go b/mining/mining_test.go index 1a2ad3f9..bdab99c0 100644 --- a/mining/mining_test.go +++ b/mining/mining_test.go @@ -38,7 +38,7 @@ func TestNewInitBlock(t *testing.T) { TransactionsMerkleRoot: merkleRoot, AssetsMerkleRoot: snap.Tree.RootHash(), }, - Bits: uint64(21617278211387387), + Bits: uint64(3314649325747331761), Nonce: 0, }, Transactions: []*legacy.Tx{coinbaseTx}, diff --git a/node/node.go b/node/node.go index 3bb4be52..51ff4fbb 100644 --- a/node/node.go +++ b/node/node.go @@ -190,24 +190,10 @@ func NewNode(config *cfg.Config, logger log.Logger) *Node { txPool := protocol.NewTxPool() chain, err := protocol.NewChain(context.Background(), genesisBlock.Hash(), store, txPool, nil) - genesisSnap, err := chain.ApplyValidBlock(genesisBlock) - if err != nil { - cmn.Exit(cmn.Fmt("Failed to apply valid block: %v", err)) - } - if err := chain.CommitAppliedBlock(nil, genesisBlock, genesisSnap); err != nil { - cmn.Exit(cmn.Fmt("Failed to commit applied block: %v", err)) + if err := chain.AddBlock(nil, genesisBlock); err != nil { + cmn.Exit(cmn.Fmt("Failed to add genesisBlock to Chain: %v", err)) } - /* if err != nil { - cmn.Exit(cmn.Fmt("protocol new chain failed: %v", err)) - } - err = chain.CommitAppliedBlock(context.Background(), block, state.Empty()) - if err != nil { - cmn.Exit(cmn.Fmt("commit block failed: %v", err)) - } - chain.MaxIssuanceWindow = bc.MillisDuration(c.MaxIssuanceWindowMs) - */ - accounts_db := dbm.NewDB("account", config.DBBackend, config.DBDir()) accounts := account.NewManager(accounts_db, chain) assets_db := dbm.NewDB("asset", config.DBBackend, config.DBDir()) diff --git a/protocol/block.go b/protocol/block.go index 172c8e60..20941f7e 100644 --- a/protocol/block.go +++ b/protocol/block.go @@ -54,14 +54,7 @@ func (c *Chain) ValidateBlock(block, prev *legacy.Block) error { // ApplyValidBlock creates an updated snapshot without validating the // block. func (c *Chain) ApplyValidBlock(block *legacy.Block) (*state.Snapshot, error) { - //TODO replace with a pre-defined init blo - var newSnapshot *state.Snapshot - if c.state.snapshot == nil { - newSnapshot = state.Empty() - } else { - newSnapshot = state.Copy(c.state.snapshot) - } - + newSnapshot := state.Copy(c.state.snapshot) err := newSnapshot.ApplyBlock(legacy.MapBlock(block)) if err != nil { return nil, err @@ -113,6 +106,20 @@ func (c *Chain) CommitAppliedBlock(ctx context.Context, block *legacy.Block, sna return nil } +func (c *Chain) AddBlock(ctx context.Context, block *legacy.Block) error { + currentBlock, _ := c.State() + if err := c.ValidateBlock(block, currentBlock); err != nil { + return err + } + + newSnap, err := c.ApplyValidBlock(block) + if err != nil { + return err + } + + return c.CommitAppliedBlock(ctx, block, newSnap) +} + func (c *Chain) queueSnapshot(ctx context.Context, height uint64, timestamp time.Time, s *state.Snapshot) { // Non-blockingly queue the snapshot for storage. ps := pendingSnapshot{height: height, snapshot: s} diff --git a/protocol/protocol.go b/protocol/protocol.go index 1b126aa7..e27594d4 100644 --- a/protocol/protocol.go +++ b/protocol/protocol.go @@ -76,6 +76,7 @@ func NewChain(ctx context.Context, initialBlockHash bc.Hash, store Store, txPool c.state.cond.L = new(sync.Mutex) c.state.height = store.Height() + c.state.snapshot = state.Empty() // Note that c.height.n may still be zero here. if heights != nil { -- 2.11.0