Skip to content

Commit 3655766

Browse files
committed
Merge pull request #1216 from karalabe/fix-eth-dataraces
Fix various data races in eth and core
2 parents 60b780c + ebf2aab commit 3655766

File tree

5 files changed

+85
-38
lines changed

5 files changed

+85
-38
lines changed

core/chain_manager.go

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,7 @@ func CalcTD(block, parent *types.Block) *big.Int {
5656
if parent == nil {
5757
return block.Difficulty()
5858
}
59-
60-
td := new(big.Int).Add(parent.Td, block.Header().Difficulty)
61-
62-
return td
59+
return new(big.Int).Add(parent.Td, block.Header().Difficulty)
6360
}
6461

6562
func CalcGasLimit(parent *types.Block) *big.Int {
@@ -178,7 +175,7 @@ func (self *ChainManager) Td() *big.Int {
178175
self.mu.RLock()
179176
defer self.mu.RUnlock()
180177

181-
return self.td
178+
return new(big.Int).Set(self.td)
182179
}
183180

184181
func (self *ChainManager) GasLimit() *big.Int {
@@ -204,7 +201,7 @@ func (self *ChainManager) Status() (td *big.Int, currentBlock common.Hash, genes
204201
self.mu.RLock()
205202
defer self.mu.RUnlock()
206203

207-
return self.td, self.currentBlock.Hash(), self.genesisBlock.Hash()
204+
return new(big.Int).Set(self.td), self.currentBlock.Hash(), self.genesisBlock.Hash()
208205
}
209206

210207
func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
@@ -382,8 +379,8 @@ func (self *ChainManager) ExportN(w io.Writer, first uint64, last uint64) error
382379
func (bc *ChainManager) insert(block *types.Block) {
383380
key := append(blockNumPre, block.Number().Bytes()...)
384381
bc.blockDb.Put(key, block.Hash().Bytes())
385-
386382
bc.blockDb.Put([]byte("LastBlock"), block.Hash().Bytes())
383+
387384
bc.currentBlock = block
388385
bc.lastBlockHash = block.Hash()
389386
}
@@ -488,8 +485,7 @@ func (self *ChainManager) GetAncestors(block *types.Block, length int) (blocks [
488485
}
489486

490487
func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
491-
//bc.blockDb.Put([]byte("LTD"), td.Bytes())
492-
bc.td = td
488+
bc.td = new(big.Int).Set(td)
493489
}
494490

495491
func (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {
@@ -544,6 +540,9 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
544540
self.wg.Add(1)
545541
defer self.wg.Done()
546542

543+
self.mu.Lock()
544+
defer self.mu.Unlock()
545+
547546
self.chainmu.Lock()
548547
defer self.chainmu.Unlock()
549548

eth/handler.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ func (pm *ProtocolManager) handle(p *peer) error {
157157
}
158158
defer pm.removePeer(p.id)
159159

160-
if err := pm.downloader.RegisterPeer(p.id, p.recentHash, p.requestHashes, p.requestBlocks); err != nil {
160+
if err := pm.downloader.RegisterPeer(p.id, p.Head(), p.requestHashes, p.requestBlocks); err != nil {
161161
return err
162162
}
163163
// propagate existing transactions. new transactions appearing
@@ -303,7 +303,7 @@ func (self *ProtocolManager) handleMsg(p *peer) error {
303303
// Mark the hashes as present at the remote node
304304
for _, hash := range hashes {
305305
p.blockHashes.Add(hash)
306-
p.recentHash = hash
306+
p.SetHead(hash)
307307
}
308308
// Schedule all the unknown hashes for retrieval
309309
unknown := make([]common.Hash, 0, len(hashes))
@@ -354,9 +354,9 @@ func (pm *ProtocolManager) importBlock(p *peer, block *types.Block, td *big.Int)
354354

355355
// Mark the block as present at the remote node (don't duplicate already held data)
356356
p.blockHashes.Add(hash)
357-
p.recentHash = hash
357+
p.SetHead(hash)
358358
if td != nil {
359-
p.td = td
359+
p.SetTd(td)
360360
}
361361
// Log the block's arrival
362362
_, chainHead, _ := pm.chainman.Status()
@@ -369,7 +369,7 @@ func (pm *ProtocolManager) importBlock(p *peer, block *types.Block, td *big.Int)
369369
})
370370
// If the block's already known or its difficulty is lower than ours, drop
371371
if pm.chainman.HasBlock(hash) {
372-
p.td = pm.chainman.GetBlock(hash).Td // update the peer's TD to the real value
372+
p.SetTd(pm.chainman.GetBlock(hash).Td) // update the peer's TD to the real value
373373
return nil
374374
}
375375
if td != nil && pm.chainman.Td().Cmp(td) > 0 && new(big.Int).Add(block.Number(), big.NewInt(7)).Cmp(pm.chainman.CurrentBlock().Number()) < 0 {

eth/peer.go

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,11 @@ type peer struct {
4040

4141
protv, netid int
4242

43-
recentHash common.Hash
44-
id string
45-
td *big.Int
43+
id string
44+
45+
head common.Hash
46+
td *big.Int
47+
lock sync.RWMutex
4648

4749
genesis, ourHash common.Hash
4850
ourTd *big.Int
@@ -51,14 +53,14 @@ type peer struct {
5153
blockHashes *set.Set
5254
}
5355

54-
func newPeer(protv, netid int, genesis, recentHash common.Hash, td *big.Int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
56+
func newPeer(protv, netid int, genesis, head common.Hash, td *big.Int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
5557
id := p.ID()
5658

5759
return &peer{
5860
Peer: p,
5961
rw: rw,
6062
genesis: genesis,
61-
ourHash: recentHash,
63+
ourHash: head,
6264
ourTd: td,
6365
protv: protv,
6466
netid: netid,
@@ -68,6 +70,39 @@ func newPeer(protv, netid int, genesis, recentHash common.Hash, td *big.Int, p *
6870
}
6971
}
7072

73+
// Head retrieves a copy of the current head (most recent) hash of the peer.
74+
func (p *peer) Head() (hash common.Hash) {
75+
p.lock.RLock()
76+
defer p.lock.RUnlock()
77+
78+
copy(hash[:], p.head[:])
79+
return hash
80+
}
81+
82+
// SetHead updates the head (most recent) hash of the peer.
83+
func (p *peer) SetHead(hash common.Hash) {
84+
p.lock.Lock()
85+
defer p.lock.Unlock()
86+
87+
copy(p.head[:], hash[:])
88+
}
89+
90+
// Td retrieves the current total difficulty of a peer.
91+
func (p *peer) Td() *big.Int {
92+
p.lock.RLock()
93+
defer p.lock.RUnlock()
94+
95+
return new(big.Int).Set(p.td)
96+
}
97+
98+
// SetTd updates the current total difficulty of a peer.
99+
func (p *peer) SetTd(td *big.Int) {
100+
p.lock.Lock()
101+
defer p.lock.Unlock()
102+
103+
p.td.Set(td)
104+
}
105+
71106
// sendTransactions sends transactions to the peer and includes the hashes
72107
// in it's tx hash set for future reference. The tx hash will allow the
73108
// manager to check whether the peer has already received this particular
@@ -160,7 +195,7 @@ func (p *peer) handleStatus() error {
160195
// Set the total difficulty of the peer
161196
p.td = status.TD
162197
// set the best hash of the peer
163-
p.recentHash = status.CurrentBlock
198+
p.head = status.CurrentBlock
164199

165200
return <-errc
166201
}
@@ -256,11 +291,14 @@ func (ps *peerSet) BestPeer() *peer {
256291
ps.lock.RLock()
257292
defer ps.lock.RUnlock()
258293

259-
var best *peer
294+
var (
295+
bestPeer *peer
296+
bestTd *big.Int
297+
)
260298
for _, p := range ps.peers {
261-
if best == nil || p.td.Cmp(best.td) > 0 {
262-
best = p
299+
if td := p.Td(); bestPeer == nil || td.Cmp(bestTd) > 0 {
300+
bestPeer, bestTd = p, td
263301
}
264302
}
265-
return best
303+
return bestPeer
266304
}

eth/sync.go

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -109,17 +109,25 @@ func (pm *ProtocolManager) fetcher() {
109109
// If any explicit fetches were replied to, import them
110110
if count := len(explicit); count > 0 {
111111
glog.V(logger.Debug).Infof("Importing %d explicitly fetched blocks", count)
112+
113+
// Create a closure with the retrieved blocks and origin peers
114+
peers := make([]*peer, 0, count)
115+
blocks := make([]*types.Block, 0, count)
116+
for _, block := range explicit {
117+
hash := block.Hash()
118+
if announce := pending[hash]; announce != nil {
119+
peers = append(peers, announce.peer)
120+
blocks = append(blocks, block)
121+
122+
delete(pending, hash)
123+
}
124+
}
125+
// Run the importer on a new thread
112126
go func() {
113-
for _, block := range explicit {
114-
hash := block.Hash()
115-
116-
// Make sure there's still something pending to import
117-
if announce := pending[hash]; announce != nil {
118-
delete(pending, hash)
119-
if err := pm.importBlock(announce.peer, block, nil); err != nil {
120-
glog.V(logger.Detail).Infof("Failed to import explicitly fetched block: %v", err)
121-
return
122-
}
127+
for i := 0; i < len(blocks); i++ {
128+
if err := pm.importBlock(peers[i], blocks[i], nil); err != nil {
129+
glog.V(logger.Detail).Infof("Failed to import explicitly fetched block: %v", err)
130+
return
123131
}
124132
}
125133
}()
@@ -208,20 +216,21 @@ func (pm *ProtocolManager) synchronise(peer *peer) {
208216
return
209217
}
210218
// Make sure the peer's TD is higher than our own. If not drop.
211-
if peer.td.Cmp(pm.chainman.Td()) <= 0 {
219+
if peer.Td().Cmp(pm.chainman.Td()) <= 0 {
212220
return
213221
}
214222
// FIXME if we have the hash in our chain and the TD of the peer is
215223
// much higher than ours, something is wrong with us or the peer.
216224
// Check if the hash is on our own chain
217-
if pm.chainman.HasBlock(peer.recentHash) {
225+
head := peer.Head()
226+
if pm.chainman.HasBlock(head) {
218227
glog.V(logger.Debug).Infoln("Synchronisation canceled: head already known")
219228
return
220229
}
221230
// Get the hashes from the peer (synchronously)
222-
glog.V(logger.Detail).Infof("Attempting synchronisation: %v, 0x%x", peer.id, peer.recentHash)
231+
glog.V(logger.Detail).Infof("Attempting synchronisation: %v, 0x%x", peer.id, head)
223232

224-
err := pm.downloader.Synchronise(peer.id, peer.recentHash)
233+
err := pm.downloader.Synchronise(peer.id, head)
225234
switch err {
226235
case nil:
227236
glog.V(logger.Detail).Infof("Synchronisation completed")

p2p/rlpx.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err
102102
werr := make(chan error, 1)
103103
go func() { werr <- Send(t.rw, handshakeMsg, our) }()
104104
if their, err = readProtocolHandshake(t.rw, our); err != nil {
105+
<-werr // make sure the write terminates too
105106
return nil, err
106107
}
107108
if err := <-werr; err != nil {

0 commit comments

Comments
 (0)