以太坊源碼情景分析之區塊(block)資料同步
來源:互聯網
上載者:User
區塊資料同步分為被動同步和主動同步 被動同步是指本地節點收到其他節點的一些訊息,然後請求區塊資訊。比如NewBlockHashesMsg
主動同步是指節點主動向其他節點請求區塊資料,比如geth剛啟動時的syning,以及運行時定時和相鄰節點同步 被動同步 被動同步由fetcher完成,被動模式又分為兩種 收到完整的block廣播訊息(NewBlockMsg) 收到blockhash廣播訊息(NewBlockHashesMsg)
NewBlockHashesMsg被動模式 由於NewBlockHashesMsg被動同步模式下和主動同步模式下都會請求其他節點並接收header和body,因此需要有相關邏輯區分是被動同步模式下請求的資料還是主動模式下請求的資料,這個區分是通過filterHeaders和filterBodies實現的。NewBlockHashesMsg這種模式下邏輯很複雜,我們一起來先看下這種模式下的流程源碼 收到外部節點 NewBlockHashesMsg訊息,然後發送一個 announce 給fetcher
func (pm *ProtocolManager) handleMsg { case msg.Code == NewBlockHashesMsg: var announces newBlockHashesData if err := msg. Decode ( & announces); err != nil { return errResp (ErrDecode, "%v: %v" , msg, err) } // Mark the hashes as present at the remote node for _ , block := range announces { p. MarkBlock (block.Hash) } // Schedule all the unknown hashes for retrieval unknown := make (newBlockHashesData, 0 , len (announces)) for _ , block := range announces { if ! pm.blockchain. HasBlock (block.Hash, block.Number) { unknown = append (unknown, block) } } for _ , block := range unknown { pm.fetcher. Notify (p.id, block.Hash, block.Number, time. Now (), p.RequestOneHeader, p.RequestBodies) } }
func (f * Fetcher) Notify (peer string , hash common.Hash, number uint64 , time time.Time, headerFetcher headerRequesterFn, bodyFetcher bodyRequesterFn) error { block := & announce{ hash: hash, number: number, time: time, origin: peer, fetchHeader: headerFetcher, fetchBodies: bodyFetcher, } select { //發送通知 case f.notify <- block: return nil case <- f.quit: return errTerminated } }
fetcher收到announce會將其放置到announced[]數組 func (f * Fetcher) loop () { case notification := <- f.notify: // All is well, schedule the announce if block's not yet downloading if _ , ok := f.fetching[notification.hash]; ok { break } if _ , ok := f.completing [notification.hash]; ok { break } f.announces[notification.origin] = count f.announced[notification.hash] = append (f.announced[notification.hash], notification) if f.announceChangeHook != nil && len (f.announced[notification.hash]) == 1 { f. announceChangeHook (notification.hash, true ) } if len (f.announced) == 1 { f.rescheduleFetch(fetchTimer) } }
fetchTimer工作情境 f.announced的len=1,上面會調用f.rescheduleFetch,然後就會進入fetchTimer.C分支 f.announced的len > 1,則它自身會不停的調用自己,知道將所有announce處理完畢 fetchTimer會將announce放置到f.fetching並調用fetchHeader請求其他節點擷取header資料
func (f * Fetcher) loop () { case <- fetchTimer.C: // At least one block's timer ran out, check for needing retrieval request := make ( map [ string ][]common.Hash)
for hash , announces