开发者首先需要建立一个Fabric网络,在此之上开发chaincode,然后在SDK基础上开发业务应用,与Fabric网络进行业务连接,应用还需要通过Fabric CA签发证书。如下图所示:
编写chaincode所需的接口在core/chaincode/shim/interfaces.go文件中,部分内容如下所示,调用GetState接口根据key查找对应value,调用PutState接口可以根据key值修改value,调用InvokeChaincode接口调用另一个chaincode。
// ChaincodeStubInterface is used by deployable chaincode apps to access and
// modify their ledgers
type ChaincodeStubInterface interface {
// GetArgs returns the arguments intended for the chaincode Init and Invoke
// as an array of byte arrays.
GetArgs() [][]byte
InvokeChaincode(chaincodeName string, args [][]byte, channel string) pb.Response
// GetState returns the value of the specified `key` from the
// ledger. Note that GetState doesn't read data from the writeset, which
// has not been committed to the ledger. In other words, GetState doesn't
// consider data modified by PutState that has not been committed.
// If the key does not exist in the state database, (nil, nil) is returned.
GetState(key string) ([]byte, error)
// PutState puts the specified `key` and `value` into the transaction's
// writeset as a data-write proposal. PutState doesn't effect the ledger
// until the transaction is validated and successfully committed.
// Simple keys must not be an empty string and must not start with null
// character (0x00), in order to avoid range query collisions with
// composite keys, which internally get prefixed with 0x00 as composite
// key namespace.
PutState(key string, value []byte) error
二、开发步骤
2.1 确定应用场景(Scenario)
编写chaincode需要首先确定应用场景,比如某公司需要发行一种票据进行融资,期货平台需要返还相应的利息,核心企业需要发行票据和支持兑现业务,银行、基金等公司会购买票据、转卖票据、兑现,还会有评级机构对票据进行评级,收到一些通知提醒,如下图所示:
确定了业务场景后,需要细化业务数据的生命周期,例如下图所示,信封表示event,书表示state:
以上就是票据业务数据的生命周期,涉及到各种交易、以及对应的状态。
2.3 数据结构(Data Structure)编码前需要确认数据存储的数据结构,根据业务需求设计出对应的value结构,如下图所示:
根据查询需求可以设计出key值的前缀,方便根据key值进行范围查询,比如设计key值为org.papaernet.paperMagnetoCorp00001,可以根据“org.papaernet.paperMagnetoCorp”查询出核心企业拥有的所有票据,如下图所示:
数据结构设计完成后,就可以开始编写智能合约了。如下图所示:
除了编写chaincode,还要基于SDK开发客户端应用,需要确定应用如何通过SDK与智能合约交互,比如提交发行(issue)交易需要调用智能合约中的issue分支,如下图所示:
开发一个Fabric应用还需考虑其他各种问题,包括智能合约命名空间(Chaincode namespace)、背书策略(Endorsement policies)、连接配置文件(Connection Profile)、身份(Idendities)等,贯穿开发中的各个环节。