OSDN Git Service

Merge pull request #24 from Bytom/dev_consensus_engine_and_dpos
[bytom/vapor.git] / protocol / protocol.go
1 package protocol
2
3 import (
4         "sync"
5
6         log "github.com/sirupsen/logrus"
7
8         "github.com/vapor/config"
9         engine "github.com/vapor/consensus/consensus"
10         "github.com/vapor/errors"
11         "github.com/vapor/protocol/bc"
12         "github.com/vapor/protocol/bc/types"
13         "github.com/vapor/protocol/state"
14 )
15
16 const maxProcessBlockChSize = 1024
17
18 // Chain provides functions for working with the Bytom block chain.
19 type Chain struct {
20         index          *state.BlockIndex
21         orphanManage   *OrphanManage
22         txPool         *TxPool
23         store          Store
24         processBlockCh chan *processBlockMsg
25
26         cond       sync.Cond
27         bestNode   *state.BlockNode
28         Authoritys map[string]string
29         position   uint64
30         engine     engine.Engine
31 }
32
33 // NewChain returns a new Chain using store as the underlying storage.
34 func NewChain(store Store, txPool *TxPool) (*Chain, error) {
35         c := &Chain{
36                 orphanManage:   NewOrphanManage(),
37                 txPool:         txPool,
38                 store:          store,
39                 processBlockCh: make(chan *processBlockMsg, maxProcessBlockChSize),
40         }
41         c.cond.L = new(sync.Mutex)
42
43         storeStatus := store.GetStoreStatus()
44         if storeStatus == nil {
45                 if err := c.initChainStatus(); err != nil {
46                         return nil, err
47                 }
48                 storeStatus = store.GetStoreStatus()
49         }
50
51         var err error
52         if c.index, err = store.LoadBlockIndex(storeStatus.Height); err != nil {
53                 return nil, err
54         }
55
56         c.bestNode = c.index.GetNode(storeStatus.Hash)
57         c.index.SetMainChain(c.bestNode)
58         go c.blockProcesser()
59         return c, nil
60 }
61
62 func (c *Chain) SetAuthoritys(authoritys map[string]string) {
63         c.Authoritys = authoritys
64 }
65
66 func (c *Chain) SetPosition(position uint64) {
67         c.position = position
68 }
69
70 func (c *Chain) SetConsensusEngine(engine engine.Engine) {
71         c.engine = engine
72 }
73
74 func (c *Chain) initChainStatus() error {
75         genesisBlock := config.GenesisBlock()
76         txStatus := bc.NewTransactionStatus()
77         for i := range genesisBlock.Transactions {
78                 if err := txStatus.SetStatus(i, false); err != nil {
79                         return err
80                 }
81         }
82
83         if err := c.store.SaveBlock(genesisBlock, txStatus); err != nil {
84                 return err
85         }
86
87         utxoView := state.NewUtxoViewpoint()
88         bcBlock := types.MapBlock(genesisBlock)
89         if err := utxoView.ApplyBlock(bcBlock, txStatus); err != nil {
90                 return err
91         }
92
93         node, err := state.NewBlockNode(&genesisBlock.BlockHeader, nil)
94         if err != nil {
95                 return err
96         }
97         return c.store.SaveChainStatus(node, utxoView)
98 }
99
100 // BestBlockHeight returns the current height of the blockchain.
101 func (c *Chain) BestBlockHeight() uint64 {
102         c.cond.L.Lock()
103         defer c.cond.L.Unlock()
104         return c.bestNode.Height
105 }
106
107 // BestBlockHash return the hash of the chain tail block
108 func (c *Chain) BestBlockHash() *bc.Hash {
109         c.cond.L.Lock()
110         defer c.cond.L.Unlock()
111         return &c.bestNode.Hash
112 }
113
114 // BestBlockHeader returns the chain tail block
115 func (c *Chain) BestBlockHeader() *types.BlockHeader {
116         node := c.index.BestNode()
117         return node.BlockHeader()
118 }
119
120 // InMainChain checks wheather a block is in the main chain
121 func (c *Chain) InMainChain(hash bc.Hash) bool {
122         return c.index.InMainchain(hash)
123 }
124
125 // CalcNextSeed return the seed for the given block
126 func (c *Chain) CalcNextSeed(preBlock *bc.Hash) (*bc.Hash, error) {
127         node := c.index.GetNode(preBlock)
128         if node == nil {
129                 return nil, errors.New("can't find preblock in the blockindex")
130         }
131         return node.CalcNextSeed(), nil
132 }
133
134 // CalcNextBits return the seed for the given block
135 func (c *Chain) CalcNextBits(preBlock *bc.Hash) (uint64, error) {
136         node := c.index.GetNode(preBlock)
137         if node == nil {
138                 return 0, errors.New("can't find preblock in the blockindex")
139         }
140         return node.CalcNextBits(), nil
141 }
142
143 // This function must be called with mu lock in above level
144 func (c *Chain) setState(node *state.BlockNode, view *state.UtxoViewpoint) error {
145         if err := c.store.SaveChainStatus(node, view); err != nil {
146                 return err
147         }
148
149         c.cond.L.Lock()
150         defer c.cond.L.Unlock()
151
152         c.index.SetMainChain(node)
153         c.bestNode = node
154
155         log.WithFields(log.Fields{"height": c.bestNode.Height, "hash": c.bestNode.Hash.String()}).Debug("chain best status has been update")
156         c.cond.Broadcast()
157         return nil
158 }
159
160 // BlockWaiter returns a channel that waits for the block at the given height.
161 func (c *Chain) BlockWaiter(height uint64) <-chan struct{} {
162         ch := make(chan struct{}, 1)
163         go func() {
164                 c.cond.L.Lock()
165                 defer c.cond.L.Unlock()
166                 for c.bestNode.Height < height {
167                         c.cond.Wait()
168                 }
169                 ch <- struct{}{}
170         }()
171
172         return ch
173 }
174
175 // GetTxPool return chain txpool.
176 func (c *Chain) GetTxPool() *TxPool {
177         return c.txPool
178 }