文章目录
一、智能合约是什么
智能合约是Fabric区块链网络的心脏,在可执行代码中定义不同组织之间的规则。智能合约打包成chaincode,部署chaincode后即可通过chaincode生成交易记录到账本上。
二、智能合约与账本的交互
开发者需要开发的模块包括Application和SmartContract,Application可以通过ledger的API直接访问区块链,也可以通过智能合约访问区块链和世界状态,智能合约和账本都可以发出event,如下图所示:
智能合约访问World state的接口:
- get:直接访问world state就可以获得返回结果,不会去访问区块链
- put:写入world state,同时在区块链中增加一条写入交易
- delete:在world state删除一条记录,不会删除区块链中的记录,只会增加一条删除的交易
三、chaincode样例
chaincode支持Java、Node.js、Go等语言,下面给出Go的样例:
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}
// Init is called during chaincode instantiation to initialize any data.
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
// Initialize the chaincode
A = args[0]
Aval, err = strconv.