OSDN Git Service

code need to be little better elegant
authorpaladz <453256728@qq.com>
Tue, 26 Sep 2017 07:38:43 +0000 (15:38 +0800)
committerpaladz <453256728@qq.com>
Tue, 26 Sep 2017 07:38:43 +0000 (15:38 +0800)
blockchain/reactor.go
consensus/general.go
mining/cpuminer/cpuminer.go
mining/mining.go
mining/mining_test.go
node/node.go
protocol/block.go
protocol/protocol.go

index 8713152..cd4fb66 100644 (file)
@@ -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:
index 2ae80eb..5362e60 100644 (file)
@@ -36,5 +36,5 @@ func BlockSubsidy(height uint64) uint64 {
 }
 
 func InitBlock() []byte {
-       return []byte("03010000000000000000000000000000000000000000000000000000000000000000008a9edde9ea2b40dc4e0aaee625a0b0d72c9e6fef0a70cb016ba55d86e85ebec9da87651aa15109492159980684155da19e87de0d1b37b35c1a1123770ec1dcc710aabe77607cce00fbdfb3e6cc99b32601070107008a9edde9ea2b000001012cffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8080ccdee2a69fb314010151000000")
+       return []byte("0301000000000000000000000000000000000000000000000000000000000000000000ece090e7eb2b4078a79ed5c640a026361c4af77a37342e503cc68493229996e11dd9be38b18f5b492159980684155da19e87de0d1b37b35c1a1123770ec1dcc710aabe77607cce00b1c5a181808080802e0107010700ece090e7eb2b000001012cffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8080ccdee2a69fb314010151000000")
 }
index bebaf3e..11c80d6 100644 (file)
@@ -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)
                }
        }
 
index ab509fb..9a290e5 100644 (file)
@@ -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")
        }
index 1a2ad3f..bdab99c 100644 (file)
@@ -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},
index 3bb4be5..51ff4fb 100644 (file)
@@ -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())
index 172c8e6..20941f7 100644 (file)
@@ -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}
index 1b126aa..e27594d 100644 (file)
@@ -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 {