block_pool.go 8.0 KB
Newer Older
O
obscuren 已提交
1 2 3
package eth

import (
4
	"bytes"
O
tmp  
obscuren 已提交
5
	"container/list"
O
obscuren 已提交
6
	"fmt"
O
obscuren 已提交
7 8 9
	"math"
	"math/big"
	"sync"
O
tmp  
obscuren 已提交
10
	"time"
O
obscuren 已提交
11

12 13 14 15
	"github.com/ethereum/go-ethereum/ethchain"
	"github.com/ethereum/go-ethereum/ethlog"
	"github.com/ethereum/go-ethereum/ethutil"
	"github.com/ethereum/go-ethereum/ethwire"
O
obscuren 已提交
16 17
)

O
obscuren 已提交
18
var poollogger = ethlog.NewLogger("BPOOL")
19

O
obscuren 已提交
20
type block struct {
21
	from      *Peer
O
tmp  
obscuren 已提交
22 23 24 25
	peer      *Peer
	block     *ethchain.Block
	reqAt     time.Time
	requested int
O
obscuren 已提交
26 27 28 29 30 31 32
}

type BlockPool struct {
	mut sync.Mutex

	eth *Ethereum

O
obscuren 已提交
33 34
	hashes [][]byte
	pool   map[string]*block
O
obscuren 已提交
35

O
tmp  
obscuren 已提交
36 37
	td   *big.Int
	quit chan bool
38

O
obscuren 已提交
39 40 41
	fetchingHashes    bool
	downloadStartedAt time.Time

42
	ChainLength, BlocksProcessed int
O
obscuren 已提交
43 44

	peer *Peer
O
obscuren 已提交
45 46 47 48 49 50 51
}

func NewBlockPool(eth *Ethereum) *BlockPool {
	return &BlockPool{
		eth:  eth,
		pool: make(map[string]*block),
		td:   ethutil.Big0,
O
tmp  
obscuren 已提交
52
		quit: make(chan bool),
O
obscuren 已提交
53 54 55
	}
}

O
obscuren 已提交
56
func (self *BlockPool) Len() int {
O
obscuren 已提交
57
	return len(self.hashes)
O
obscuren 已提交
58 59
}

60 61
func (self *BlockPool) Reset() {
	self.pool = make(map[string]*block)
O
obscuren 已提交
62
	self.hashes = nil
63 64
}

O
obscuren 已提交
65
func (self *BlockPool) HasLatestHash() bool {
O
obscuren 已提交
66 67 68
	self.mut.Lock()
	defer self.mut.Unlock()

O
obscuren 已提交
69
	return self.pool[string(self.eth.ChainManager().CurrentBlock.Hash())] != nil
O
obscuren 已提交
70 71 72
}

func (self *BlockPool) HasCommonHash(hash []byte) bool {
O
obscuren 已提交
73
	return self.eth.ChainManager().GetBlock(hash) != nil
O
obscuren 已提交
74 75
}

O
obscuren 已提交
76 77 78 79 80 81 82 83 84 85
func (self *BlockPool) Blocks() (blocks ethchain.Blocks) {
	for _, item := range self.pool {
		if item.block != nil {
			blocks = append(blocks, item.block)
		}
	}

	return
}

86
func (self *BlockPool) FetchHashes(peer *Peer) bool {
O
obscuren 已提交
87 88
	highestTd := self.eth.HighestTDPeer()

O
obscuren 已提交
89
	if (self.peer == nil && peer.td.Cmp(highestTd) >= 0) || (self.peer != nil && peer.td.Cmp(self.peer.td) > 0) || self.peer == peer {
O
obscuren 已提交
90 91
		if self.peer != peer {
			poollogger.Debugf("Found better suitable peer (%v vs %v)\n", self.td, peer.td)
O
obscuren 已提交
92 93 94 95

			if self.peer != nil {
				self.peer.doneFetchingHashes = true
			}
O
obscuren 已提交
96 97 98 99 100 101 102 103 104
		}

		self.peer = peer
		self.td = peer.td

		if !self.HasLatestHash() {
			peer.doneFetchingHashes = false

			const amount = 256
O
obscuren 已提交
105
			peerlogger.Debugf("Fetching hashes (%d) %x...\n", amount, peer.lastReceivedHash[0:4])
O
obscuren 已提交
106 107
			peer.QueueMessage(ethwire.NewMessage(ethwire.MsgGetBlockHashesTy, []interface{}{peer.lastReceivedHash, uint32(amount)}))
		}
108 109

		return true
O
obscuren 已提交
110
	}
111 112

	return false
O
obscuren 已提交
113 114
}

115
func (self *BlockPool) AddHash(hash []byte, peer *Peer) {
O
obscuren 已提交
116 117 118
	self.mut.Lock()
	defer self.mut.Unlock()

O
obscuren 已提交
119
	if self.pool[string(hash)] == nil {
120
		self.pool[string(hash)] = &block{peer, nil, nil, time.Now(), 0}
O
obscuren 已提交
121

O
obscuren 已提交
122
		self.hashes = append([][]byte{hash}, self.hashes...)
O
obscuren 已提交
123 124 125
	}
}

O
obscuren 已提交
126
func (self *BlockPool) Add(b *ethchain.Block, peer *Peer) {
O
obscuren 已提交
127 128 129 130 131 132 133 134
	self.addBlock(b, peer, false)
}

func (self *BlockPool) AddNew(b *ethchain.Block, peer *Peer) {
	self.addBlock(b, peer, true)
}

func (self *BlockPool) addBlock(b *ethchain.Block, peer *Peer, newBlock bool) {
O
obscuren 已提交
135 136 137
	self.mut.Lock()
	defer self.mut.Unlock()

O
obscuren 已提交
138 139
	hash := string(b.Hash())

O
obscuren 已提交
140
	if self.pool[hash] == nil && !self.eth.ChainManager().HasBlock(b.Hash()) {
O
obscuren 已提交
141 142
		poollogger.Infof("Got unrequested block (%x...)\n", hash[0:4])

O
obscuren 已提交
143
		self.hashes = append(self.hashes, b.Hash())
144
		self.pool[hash] = &block{peer, peer, b, time.Now(), 0}
145

O
obscuren 已提交
146 147
		// The following is only performed on an unrequested new block
		if newBlock {
O
obscuren 已提交
148
			fmt.Println("1.", !self.eth.ChainManager().HasBlock(b.PrevHash), ethutil.Bytes2Hex(b.Hash()[0:4]), ethutil.Bytes2Hex(b.PrevHash[0:4]))
O
obscuren 已提交
149 150
			fmt.Println("2.", self.pool[string(b.PrevHash)] == nil)
			fmt.Println("3.", !self.fetchingHashes)
O
obscuren 已提交
151
			if !self.eth.ChainManager().HasBlock(b.PrevHash) && self.pool[string(b.PrevHash)] == nil && !self.fetchingHashes {
O
obscuren 已提交
152 153 154
				poollogger.Infof("Unknown chain, requesting (%x...)\n", b.PrevHash[0:4])
				peer.QueueMessage(ethwire.NewMessage(ethwire.MsgGetBlockHashesTy, []interface{}{b.Hash(), uint32(256)}))
			}
155
		}
O
obscuren 已提交
156 157
	} else if self.pool[hash] != nil {
		self.pool[hash].block = b
O
obscuren 已提交
158
	}
159 160

	self.BlocksProcessed++
O
obscuren 已提交
161 162
}

O
obscuren 已提交
163 164 165
func (self *BlockPool) Remove(hash []byte) {
	self.mut.Lock()
	defer self.mut.Unlock()
O
obscuren 已提交
166

O
obscuren 已提交
167
	self.hashes = ethutil.DeleteFromByteSlice(self.hashes, hash)
O
obscuren 已提交
168
	delete(self.pool, string(hash))
169 170 171
}

func (self *BlockPool) DistributeHashes() {
O
obscuren 已提交
172 173 174
	self.mut.Lock()
	defer self.mut.Unlock()

175 176
	var (
		peerLen = self.eth.peers.Len()
O
obscuren 已提交
177
		amount  = 256 * peerLen
178 179
		dist    = make(map[*Peer][][]byte)
	)
O
obscuren 已提交
180 181

	num := int(math.Min(float64(amount), float64(len(self.pool))))
O
obscuren 已提交
182 183
	for i, j := 0, 0; i < len(self.hashes) && j < num; i++ {
		hash := self.hashes[i]
184 185 186 187 188 189 190
		item := self.pool[string(hash)]

		if item != nil && item.block == nil {
			var peer *Peer
			lastFetchFailed := time.Since(item.reqAt) > 5*time.Second

			// Handle failed requests
O
obscuren 已提交
191
			if lastFetchFailed && item.requested > 5 && item.peer != nil {
192 193 194 195 196
				if item.requested < 100 {
					// Select peer the hash was retrieved off
					peer = item.from
				} else {
					// Remove it
O
obscuren 已提交
197
					self.hashes = ethutil.DeleteFromByteSlice(self.hashes, hash)
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
					delete(self.pool, string(hash))
				}
			} else if lastFetchFailed || item.peer == nil {
				// Find a suitable, available peer
				eachPeer(self.eth.peers, func(p *Peer, v *list.Element) {
					if peer == nil && len(dist[p]) < amount/peerLen {
						peer = p
					}
				})
			}

			if peer != nil {
				item.reqAt = time.Now()
				item.peer = peer
				item.requested++

				dist[peer] = append(dist[peer], hash)
			}
O
obscuren 已提交
216 217 218
		}
	}

219 220 221
	for peer, hashes := range dist {
		peer.FetchBlocks(hashes)
	}
O
obscuren 已提交
222 223 224 225

	if len(dist) > 0 {
		self.downloadStartedAt = time.Now()
	}
O
obscuren 已提交
226
}
O
tmp  
obscuren 已提交
227 228

func (self *BlockPool) Start() {
O
obscuren 已提交
229 230
	go self.downloadThread()
	go self.chainThread()
O
tmp  
obscuren 已提交
231 232 233 234 235 236
}

func (self *BlockPool) Stop() {
	close(self.quit)
}

O
obscuren 已提交
237
func (self *BlockPool) downloadThread() {
O
tmp  
obscuren 已提交
238 239 240 241 242 243 244
	serviceTimer := time.NewTicker(100 * time.Millisecond)
out:
	for {
		select {
		case <-self.quit:
			break out
		case <-serviceTimer.C:
245 246
			// Check if we're catching up. If not distribute the hashes to
			// the peers and download the blockchain
O
obscuren 已提交
247
			self.fetchingHashes = false
O
tmp  
obscuren 已提交
248 249
			eachPeer(self.eth.peers, func(p *Peer, v *list.Element) {
				if p.statusKnown && p.FetchingHashes() {
O
obscuren 已提交
250
					self.fetchingHashes = true
O
tmp  
obscuren 已提交
251 252 253
				}
			})

O
obscuren 已提交
254 255 256
			if len(self.hashes) > 0 {
				self.DistributeHashes()
			}
257

O
obscuren 已提交
258 259
			if self.ChainLength < len(self.hashes) {
				self.ChainLength = len(self.hashes)
O
tmp  
obscuren 已提交
260
			}
O
obscuren 已提交
261 262 263 264 265 266 267

			/*
				if !self.fetchingHashes {
					blocks := self.Blocks()
					ethchain.BlockBy(ethchain.Number).Sort(blocks)

					if len(blocks) > 0 {
O
obscuren 已提交
268
						if !self.eth.ChainManager().HasBlock(b.PrevHash) && self.pool[string(b.PrevHash)] == nil && !self.fetchingHashes {
O
obscuren 已提交
269 270 271 272
						}
					}
				}
			*/
O
obscuren 已提交
273 274 275 276 277
		}
	}
}

func (self *BlockPool) chainThread() {
O
obscuren 已提交
278
	procTimer := time.NewTicker(500 * time.Millisecond)
O
obscuren 已提交
279 280 281 282 283
out:
	for {
		select {
		case <-self.quit:
			break out
O
tmp  
obscuren 已提交
284
		case <-procTimer.C:
285 286 287
			blocks := self.Blocks()
			ethchain.BlockBy(ethchain.Number).Sort(blocks)

O
obscuren 已提交
288 289
			// Find common block
			for i, block := range blocks {
O
obscuren 已提交
290
				if self.eth.ChainManager().HasBlock(block.PrevHash) {
O
obscuren 已提交
291 292 293 294 295
					blocks = blocks[i:]
					break
				}
			}

296
			if len(blocks) > 0 {
O
obscuren 已提交
297
				if self.eth.ChainManager().HasBlock(blocks[0].PrevHash) {
298 299 300 301 302 303 304 305 306 307 308
					for i, block := range blocks[1:] {
						// NOTE: The Ith element in this loop refers to the previous block in
						// outer "blocks"
						if bytes.Compare(block.PrevHash, blocks[i].Hash()) != 0 {
							blocks = blocks[:i]

							break
						}
					}
				} else {
					blocks = nil
309
				}
310 311
			}

O
obscuren 已提交
312 313 314 315
			// TODO figure out whether we were catching up
			// If caught up and just a new block has been propagated:
			// sm.eth.EventMux().Post(NewBlockEvent{block})
			// otherwise process and don't emit anything
O
obscuren 已提交
316 317
			var err error
			for i, block := range blocks {
O
obscuren 已提交
318
				err = self.eth.StateManager().Process(block)
O
obscuren 已提交
319 320 321 322 323 324 325 326 327
				if err != nil {
					poollogger.Infoln(err)
					poollogger.Debugf("Block #%v failed (%x...)\n", block.Number, block.Hash()[0:4])
					poollogger.Debugln(block)

					blocks = blocks[i:]

					break
				}
O
tmp  
obscuren 已提交
328

329
				self.Remove(block.Hash())
O
tmp  
obscuren 已提交
330
			}
O
obscuren 已提交
331 332

			if err != nil {
333
				self.Reset()
O
obscuren 已提交
334 335 336 337 338 339 340 341

				poollogger.Debugf("Punishing peer for supplying bad chain (%v)\n", self.peer.conn.RemoteAddr())
				// This peer gave us bad hashes and made us fetch a bad chain, therefor he shall be punished.
				self.eth.BlacklistPeer(self.peer)
				self.peer.StopWithReason(DiscBadPeer)
				self.td = ethutil.Big0
				self.peer = nil
			}
O
tmp  
obscuren 已提交
342 343 344
		}
	}
}