4 log "github.com/sirupsen/logrus"
5 "gopkg.in/karalabe/cookiejar.v2/collections/prque"
7 "github.com/bytom/protocol/bc"
16 // blockFetcher is responsible for accumulating block announcements from various peers
17 // and scheduling them for retrieval.
18 type blockFetcher struct {
22 newBlockCh chan *blockMsg
24 msgSet map[bc.Hash]*blockMsg
27 //NewBlockFetcher creates a block fetcher to retrieve blocks of the new mined.
28 func newBlockFetcher(chain Chain, peers *peerSet) *blockFetcher {
32 newBlockCh: make(chan *blockMsg, newBlockChSize),
34 msgSet: make(map[bc.Hash]*blockMsg),
40 func (f *blockFetcher) blockProcessor() {
42 height := f.chain.BestBlockHeight()
43 for !f.queue.Empty() {
44 msg := f.queue.PopItem().(*blockMsg)
45 if msg.block.Height > height+1 {
46 f.queue.Push(msg, -float32(msg.block.Height))
51 delete(f.msgSet, msg.block.Hash())
57 func (f *blockFetcher) add(msg *blockMsg) {
58 bestHeight := f.chain.BestBlockHeight()
59 if len(f.msgSet) > maxMsgSetSize || bestHeight > msg.block.Height || msg.block.Height-bestHeight > maxBlockDistance {
63 blockHash := msg.block.Hash()
64 if _, ok := f.msgSet[blockHash]; !ok {
65 f.msgSet[blockHash] = msg
66 f.queue.Push(msg, -float32(msg.block.Height))
67 log.WithFields(log.Fields{
69 "block height": msg.block.Height,
70 "block hash": blockHash.String(),
71 }).Debug("blockFetcher receive mine block")
75 func (f *blockFetcher) insert(msg *blockMsg) {
76 isOrphan, err := f.chain.ProcessBlock(msg.block)
78 peer := f.peers.getPeer(msg.peerID)
83 f.peers.addBanScore(msg.peerID, 20, 0, err.Error())
91 if err := f.peers.broadcastMinedBlock(msg.block); err != nil {
92 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("blockFetcher fail on broadcast new block")
97 func (f *blockFetcher) processNewBlock(msg *blockMsg) {