0

BTCD源码阅读笔记-netsync

 2 years ago
source link: https://imnisen.github.io/btcd-code-netsync.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1 netsync模块

下面摘选自包的doc文件

Package netsync implements a concurrency safe block syncing protocol. The SyncManager communicates with connected peers to perform an initial block download, keep the chain and unconfirmed transaction pool in sync, and announce new blocks connected to the chain. Currently the sync manager selects a single sync peer that it downloads all blocks from until it is up to date with the longest chain the sync peer is aware of.

netsync包用来同步peer间消息。核心是定义了一个SyncManager,用来管理不同的peer节点的同步状态。

SyncManager的Start方法,以goroutine的方式启动了blockHandler,来处理block和inv相关的消息。


blockHandler核心是通过for/select来监听不同事件:
1. SyncManager有消息传来(<-sm.msgChan)
   根据不同的消息类型作不同的处理:
   1. 消息类型是newPeerMsg,表示发现新的peer,用handleNewPeerMsg处理;该消息由NewPeer方法发送
   2. 消息类型是txMsg, 表示接收到tx消息,用handleTxMsg处理;该消息由QueueTx发送
   3. 消息类型是blockMsg,表示接收到peer发送的block消息,用handleBlockMsg处理;该消息有QueueBlock发送
   4. 消息类型是invMsg, 表示接收到inv消息,用handleInvMsg处理,该消息由QueueInv发送
   5. 消息类型是headerMsg, 表示接收到headers消息,用handleHeadersMsg处理,该消息由QueueHeaders发送
   6. 消息类型是donePeerMsg, 表示有peer断开连接,用handleDonePeerMsg处理,由DonePeer触发
   7. 消息类型是getSyncPeerMsg,表示获取目前的同步节点, 由SyncManager.SyncPeerID方法调用,处理该消息时直接取出同步节点的id即可
   8. 消息类型是processBlockMsg,表示处理新的区块, 由SyncManager.ProcessBlock方法调用,处理该消息时直接调用chain.ProcessBlock处理
   9. 消息类型是isCurrentMsg, 表示查询是否和连接的peer同步, 由SyncManager.IsCurrent方法调用,处理该消息时直接调用SyncManager.current处理
   10.消息类型是pauseMsg, 表示暂停SyncManager, 由SyncManager.Pause方法调用,处理该消息时直接等待SyncManager的unpause channel

2. 本身30s的ticker
3. SyncManager退出(<-sm.quit)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK