Fabric 1.0原始碼分析(17)gossip(流言演算法) #deliverclient(deliver客戶端)

尹成發表於2018-05-20
# 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

相關文章