文章內容基於 Fabric v2.0.1 整理
Fabric 中所有與鏈相關的操作都通過 Chaincode
來實現,所有 Chaincode
的執行都是向 EndorserServer
提交 SignedProposal
來觸發。
1. System Chaincode
Fabric 對於一些特殊功能(如 Chaincode
本身的管理,Channel
相關操作等)提供內置的 System Chaincode 來實現。有如下 System Chaincode :
cscc
:the configuration handler for the peer,對Channel
的管理qscc
:the ledger query functions,一些通用的查詢功能:chaincode lifecycle and policies around it,1.x 版lscc
Chaincode
管理_lifecycle
:2.0 新增用於替代lscc
,實現更完善的Chaincode
lifecycle 管理(根據命令等的組織方式,個人臆測今後可能還會用於其他內容的lifecycle
管理)
另外還有兩個 System Chaincode 通過插件的方式提供:
escc
:endorsement system chaincode,部署Chaincode
時指定,對Chaincode
執行結果進行背書vscc
:Validate system chaincode,validates the given envelope corresponding to a transaction with an endorsement policy as given in its serialized form.
2. Process Proposal
Proposal 處理流程主要分爲三部分:
- Pre Process : 校驗 Proposal 有效性,簽名是否匹配等,對於非
System Chaincode
此階段進行ACL
檢查 - Simulate :此階段會以當前
World State
爲基礎,使用提供的輸入執行Chaincode
,並生成對World State
操作的讀寫集(RWSet
) - Endorse :當前
Peer
對此次Proposal
正確的執行結果進行簽名背書,有些System Chaincode
不進行背書如_lifecycle InstallChaincode
大體流程如下:
3. Simulate Proposal
Simulate Proposal 過程負責 Chaincode
的模擬執行,所謂模擬執行指的是以當前的 World State 爲基礎來,傳遞輸入參數執行 Chaincode
相關邏輯,Chaincode
對 World State 的插入、刪除更新操作以及刪除更新操作引用哪些值(基於當前狀態值修改)由模擬器收集並記錄,最終的結果即爲讀寫集(RWSet
)。需要注意的是私有數據的讀寫集不直接返回到 Response
中,而是返回私有數據對應的 Hash
值,私有數據讀寫集本身通過 Gossip
網絡進行分發。
Chaincode
調用過程中可能需要 build
And / Or launch
Chaincode ,自 2.0 起 Chaincode
(1.x 的 instantiate
過的,2.0 approve
& commit
的)會預加載並啓動,所以大部分情況下 Chaincode
都是出於 Ready 狀態,這裏只關注 Chaincode 執行部分。
Peer 與 Chaincode 之間的交互由一對 Handler
進行處理,Application Chaincode 通過 gRPC
連接、System Chaincode 通過 兩個 golang channel
模擬連接。2.0 之前只能由 Chaincode 主動連接 Peer,2.0 新增了 Chaincode as Service 由 Peer 主動連接 Chaincode,交互過程沒有太多區別。兩個成對的 Handler 代碼見:Peer 側 Handler 、Chaincode 側 Handler 。