Fabric 1.0原始碼分析(17)gossip(流言演算法) #deliverclient(deliver客戶端)
# Fabric 1.0原始碼筆記 之 gossip(流言演算法) #deliverclient(deliver客戶端)
## 1、deliverclient概述
deliverclient程式碼分佈在gossip/service、core/deliverservice目錄下,目錄結構如下:
* gossip/service目錄:
* gossip_service.go,DeliveryServiceFactory介面定義及實現。
* core/deliverservice目錄:
* deliveryclient.go,DeliverService介面定義及實現。
* client.go,broadcastClient結構體,實現AtomicBroadcast_BroadcastClient介面。
* requester.go,blocksRequester結構體及方法。
* blocksprovider目錄,BlocksProvider介面定義及實現。
## 2、DeliveryServiceFactory介面定義及實現
```go
type DeliveryServiceFactory interface {
Service(g GossipService, endpoints []string, msc api.MessageCryptoService) (deliverclient.DeliverService, error)
}
type deliveryFactoryImpl struct {
}
// Returns an instance of delivery client
func (*deliveryFactoryImpl) Service(g GossipService, endpoints []string, mcs api.MessageCryptoService) (deliverclient.DeliverService, error) {
return deliverclient.NewDeliverService(&deliverclient.Config{
CryptoSvc: mcs,
Gossip: g,
Endpoints: endpoints,
ConnFactory: deliverclient.DefaultConnectionFactory,
ABCFactory: deliverclient.DefaultABCFactory,
})
}
//程式碼在gossip/service/gossip_service.go
```
## 3、DeliverService介面定義及實現
### 3.1、DeliverService介面定義
用於與orderer溝通獲取新區塊,併傳送給committer。
```go
type DeliverService interface {
//從orderer接收通道的新塊,接收完畢呼叫終結器
StartDeliverForChannel(chainID string, ledgerInfo blocksprovider.LedgerInfo, finalizer func()) error
//停止從orderer接收通道的新快
StopDeliverForChannel(chainID string) error
//終止所有通道Deliver
Stop()
}
//程式碼在core/deliverservice/deliveryclient.go
```
### 3.2、Config結構體定義
```go
type Config struct {
//建立grpc.ClientConn
ConnFactory func(channelID string) func(endpoint string) (*grpc.ClientConn, error)
//建立AtomicBroadcastClient
ABCFactory func(*grpc.ClientConn) orderer.AtomicBroadcastClient
//執行加密操作
CryptoSvc api.MessageCryptoService
//GossipServiceAdapter
Gossip blocksprovider.GossipServiceAdapter
//排序服務的地址和埠
Endpoints []string
}
//程式碼在core/deliverservice/deliveryclient.go
```
### 3.3、DeliverService介面實現
DeliverService介面實現,即deliverServiceImpl結構體及方法。
```go
type deliverServiceImpl struct {
conf *Config //配置
blockProviders map[string]blocksprovider.BlocksProvider
lock sync.RWMutex
stopping bool //是否停止
}
//構造deliverServiceImpl
func NewDeliverService(conf *Config) (DeliverService, error)
//校驗Config
func (d *deliverServiceImpl) validateConfiguration() error
//從orderer接收通道的新塊,接收完畢呼叫終結器
func (d *deliverServiceImpl) StartDeliverForChannel(chainID string, ledgerInfo blocksprovider.LedgerInfo, finalizer func()) error
//停止從orderer接收通道的新快
func (d *deliverServiceImpl) StopDeliverForChannel(chainID string) error
//所有通道調取client.Stop()
func (d *deliverServiceImpl) Stop()
//構造blocksRequester,並返回blocksRequester.client
func (d *deliverServiceImpl) newClient(chainID string, ledgerInfoProvider blocksprovider.LedgerInfo) *broadcastClient
func DefaultConnectionFactory(channelID string) func(endpoint string) (*grpc.ClientConn, error)
func DefaultABCFactory(conn *grpc.ClientConn) orderer.AtomicBroadcastClient
//程式碼在core/deliverservice/deliveryclient.go
```
#### 3.3.1、func (d *deliverServiceImpl) StartDeliverForChannel(chainID string, ledgerInfo blocksprovider.LedgerInfo, finalizer func()) error
```go
func (d *deliverServiceImpl) StartDeliverForChannel(chainID string, ledgerInfo blocksprovider.LedgerInfo, finalizer func()) error {
d.lock.Lock()
defer d.lock.Unlock()
if d.stopping {
return errors.New(errMsg)
}
if _, exist := d.blockProviders[chainID]; exist {
errMsg := fmt.Sprintf("Delivery service - block provider already exists for %s found, can't start delivery", chainID)
return errors.New(errMsg)
} else {
client := d.newClient(chainID, ledgerInfo)
d.blockProviders[chainID] = blocksprovider.NewBlocksProvider(chainID, client, d.conf.Gossip, d.conf.CryptoSvc)
go func() {
d.blockProviders[chainID].DeliverBlocks()
finalizer()
}()
}
return nil
}
//程式碼在core/deliverservice/deliveryclient.go
```
#### 3.3.2、func (d *deliverServiceImpl) StopDeliverForChannel(chainID string) error
```go
func (d *deliverServiceImpl) StopDeliverForChannel(chainID string) error {
d.lock.Lock()
defer d.lock.Unlock()
if d.stopping {
return errors.New(errMsg)
}
if client, exist := d.blockProviders[chainID]; exist {
client.Stop()
delete(d.blockProviders, chainID)
logger.Debug("This peer will stop pass blocks from orderer service to other peers")
} else {
errMsg := fmt.Sprintf("Delivery service - no block provider for %s found, can't stop delivery", chainID)
return errors.New(errMsg)
}
return nil
}
//程式碼在core/deliverservice/deliveryclient.go
```
####3.3.3、func (d *deliverServiceImpl) newClient(chainID string, ledgerInfoProvider blocksprovider.LedgerInfo) *broadcastClient
```go
func (d *deliverServiceImpl) newClient(chainID string, ledgerInfoProvider blocksprovider.LedgerInfo) *broadcastClient {
requester := &blocksRequester{
chainID: chainID,
}
broadcastSetup := func(bd blocksprovider.BlocksDeliverer) error {
return requester.RequestBlocks(ledgerInfoProvider)
}
backoffPolicy := func(attemptNum int, elapsedTime time.Duration) (time.Duration, bool) {
if elapsedTime.Nanoseconds() > reConnectTotalTimeThreshold.Nanoseconds() {
return 0, false
}
sleepIncrement := float64(time.Millisecond * 500)
attempt := float64(attemptNum)
return time.Duration(math.Min(math.Pow(2, attempt)*sleepIncrement, reConnectBackoffThreshold)), true
}
connProd := comm.NewConnectionProducer(d.conf.ConnFactory(chainID), d.conf.Endpoints)
bClient := NewBroadcastClient(connProd, d.conf.ABCFactory, broadcastSetup, backoffPolicy)
requester.client = bClient
return bClient
}
//程式碼在core/deliverservice/deliveryclient.go
```
## 4、blocksRequester結構體及方法
```go
type blocksRequester struct {
chainID string
client blocksprovider.BlocksDeliverer
}
func (b *blocksRequester) RequestBlocks(ledgerInfoProvider blocksprovider.LedgerInfo) error
func (b *blocksRequester) seekOldest() error
func (b *blocksRequester) seekLatestFromCommitter(height uint64) error
//程式碼在core/deliverservice/requester.go
```
### 4.1、func (b *blocksRequester) RequestBlocks(ledgerInfoProvider blocksprovider.LedgerInfo) error
```go
func (b *blocksRequester) RequestBlocks(ledgerInfoProvider blocksprovider.LedgerInfo) error {
height, err := ledgerInfoProvider.LedgerHeight()
if height > 0 {
err := b.seekLatestFromCommitter(height)
} else {
err := b.seekOldest()
}
return nil
}
//程式碼在core/deliverservice/requester.go
```
## 5、BlocksProvider介面定義及實現
### 5.1、BlocksProvider介面定義
```go
type BlocksProvider interface {
DeliverBlocks()
Stop()
}
//程式碼在core/deliverservice/blocksprovider/blocksprovider.go
```
### 5.2、BlocksProvider介面實現
BlocksProvider介面實現,即blocksProviderImpl結構體及方法。
```go
type blocksProviderImpl struct {
chainID string
client streamClient
gossip GossipServiceAdapter
mcs api.MessageCryptoService
done int32
wrongStatusThreshold int
}
//構造blocksProviderImpl
func NewBlocksProvider(chainID string, client streamClient, gossip GossipServiceAdapter, mcs api.MessageCryptoService) BlocksProvider
//從orderer獲取塊,並在peer分發
func (b *blocksProviderImpl) DeliverBlocks()
func (b *blocksProviderImpl) Stop()
func (b *blocksProviderImpl) isDone() bool
func createGossipMsg(chainID string, payload *gossip_proto.Payload) *gossip_proto.GossipMessage
func createPayload(seqNum uint64, marshaledBlock []byte) *gossip_proto.Payload
//程式碼在core/deliverservice/blocksprovider/blocksprovider.go
```
#### 5.2.1、func (b *blocksProviderImpl) DeliverBlocks()
```go
func (b *blocksProviderImpl) DeliverBlocks() {
errorStatusCounter := 0
statusCounter := 0
defer b.client.Close()
for !b.isDone() {
msg, err := b.client.Recv()
switch t := msg.Type.(type) {
case *orderer.DeliverResponse_Status: //狀態
//狀態相關
case *orderer.DeliverResponse_Block: //如果是塊,接收並分發給其他節點
errorStatusCounter = 0
statusCounter = 0
seqNum := t.Block.Header.Number
marshaledBlock, err := proto.Marshal(t.Block)
b.mcs.VerifyBlock(gossipcommon.ChainID(b.chainID), seqNum, marshaledBlock)
numberOfPeers := len(b.gossip.PeersOfChannel(gossipcommon.ChainID(b.chainID)))
payload := createPayload(seqNum, marshaledBlock)
gossipMsg := createGossipMsg(b.chainID, payload)
b.gossip.AddPayload(b.chainID, payload)
b.gossip.Gossip(gossipMsg) //分發給其他節點
default:
logger.Warningf("[%s] Received unknown: ", b.chainID, t)
return
}
}
}
//程式碼在core/deliverservice/blocksprovider/blocksprovider.go
```
網址:http://www.qukuailianxueyuan.io/
欲領取造幣技術與全套虛擬機器資料
區塊鏈技術交流QQ群:756146052 備註:CSDN
尹成學院微信:備註:CSDN
網址:http://www.qukuailianxueyuan.io/
欲領取造幣技術與全套虛擬機器資料
區塊鏈技術交流QQ群:756146052 備註:CSDN
尹成學院微信:備註:CSDN
相關文章
- Fabric 1.0原始碼分析(37) Peer #DeliverClient(Deliver客戶端)原始碼client客戶端
- Fabric 1.0原始碼分析(15)gossip(流言演算法)原始碼Go演算法
- Fabric 1.0原始碼分析(16)gossip(流言演算法) #GossipServer(Gossip服務端)原始碼Go演算法Server服務端
- 區塊鏈教程Fabric1.0原始碼分析流言演算法Gossip服務端二-兄弟連區塊鏈原始碼演算法Go服務端
- Fabric 1.0原始碼分析(36) Peer #EndorserClient(Endorser客戶端)原始碼client客戶端
- 區塊鏈教程Fabric1.0原始碼分析流言演算法Gossip服務端一兄弟連區塊鏈教程區塊鏈原始碼演算法Go服務端
- Fabric 1.0原始碼分析(38) Peer #BroadcastClient(Broadcast客戶端)原始碼ASTclient客戶端
- Fabric 1.0原始碼分析(25) Orderer原始碼
- Fabric 1.0原始碼分析(31) Peer原始碼
- Fabric 1.0原始碼分析(35)Peer #EndorserServer(Endorser服務端)原始碼Server服務端
- Fabric 1.0原始碼分析(40) Proposal(提案)原始碼
- Fabric1.4原始碼解析:客戶端建立通道過程原始碼客戶端
- Fabric 1.0原始碼分析(3)Chaincode(鏈碼)原始碼AI
- Fabric 1.0原始碼分析(18) Ledger(賬本)原始碼
- Fabric 1.0原始碼分析(43) Tx(Transaction 交易)原始碼
- Fabric 1.0原始碼分析(30) Orderer #BroadcastServer(Broadcast服務端)原始碼ASTServer服務端
- Tars-Java客戶端原始碼分析Java客戶端原始碼
- Fabric 1.0原始碼分析(47)Fabric 1.0.4 go程式碼量統計原始碼Go
- Fabric 1.0原始碼分析(42)scc(系統鏈碼)原始碼
- Fabric 1.0原始碼分析(13)events(事件服務)原始碼事件
- Fabric 1.0原始碼分析(26)Orderer #ledger(Orderer Ledger)原始碼
- Fabric 1.0原始碼分析(39) policy(背書策略)原始碼
- MapReduce——客戶端提交任務原始碼分析客戶端原始碼
- Fabric 1.0原始碼分析(23)LevelDB(KV資料庫)原始碼資料庫
- Fabric 1.0原始碼分析(44)Tx #RWSet(讀寫集)原始碼
- Fabric 1.0原始碼分析(14) flogging(Fabric日誌系統)原始碼
- Netty原始碼分析(三):客戶端啟動Netty原始碼客戶端
- Fabric 1.0原始碼分析(10)consenter(共識外掛)原始碼
- Fabric 1.0原始碼分析(29) Orderer #multichain(多鏈支援包)原始碼AI
- Fabric 1.0原始碼分析(41)putils(protos/utils工具包)原始碼
- Fabric 1.0原始碼分析(45)gRPC(Fabric中註冊的gRPC Service)原始碼RPC
- Fabric 1.0原始碼分析(46)ECDSA(橢圓曲線數字簽名演算法)原始碼演算法
- Fabric 1.0原始碼分析(5)Chaincode(鏈碼)體系總結原始碼AI
- Fabric 1.0原始碼分析(2) blockfile(區塊檔案儲存)原始碼BloC
- Fabric 1.0原始碼分析(19) Ledger #statedb(狀態資料庫)原始碼資料庫
- Fabric 1.0原始碼分析(21)Ledger #historydb(歷史資料庫)原始碼資料庫
- Fabric 1.0原始碼分析(22)Ledger #blkstorage(block檔案儲存)原始碼BloC
- Fabric 1.0原始碼分析(32) Peer #peer node start命令實現原始碼