go智能合约具体实现代码
以下是一个简单的go智能合约实现代码,实现了一个简单的存储和读取功能:
package main
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
type SimpleChaincode struct {
}
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("Init Chaincode...")
return nil, nil
}
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("Invoke Chaincode...")
if function == "write" {
return t.write(stub, args)
} else if function == "read" {
return t.read(stub, args)
}
return nil, nil
}
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("Query Chaincode...")
if function == "read" {
return t.read(stub, args)
}
return nil, nil
}
func (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var key, value string
var err error
fmt.Println("Running write()")
if len(args) != 2 {
return nil, fmt.Errorf("Incorrect number of arguments. Expecting 2. name of the key and value to set")
}
key = args[0]
value = args[1]
err = stub.PutState(key, []byte(value))
if err != nil {
return nil, err
}
return nil, nil
}
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var key string
var err error
fmt.Println("Running read()")
if len(args) != 1 {
return nil, fmt.Errorf("Incorrect number of arguments. Expecting 1. name of the key to query")
}
key = args[0]
value, err := stub.GetState(key)
if err != nil {
jsonResp := "{\"Error\":\"Failed to get state for " + key + "\"}"
return nil, fmt.Errorf(jsonResp)
}
if value == nil {
jsonResp := "{\"Error\":\"Nil value for " + key + "\"}"
return nil, fmt.Errorf(jsonResp)
}
jsonResp := "{\"Name\":\"" + key + "\",\"Value\":\"" + string(value) + "\"}"
fmt.Printf("Query Response:%s\n", jsonResp)
return value, nil
}
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
这个合约定义了一个名为SimpleChaincode的结构体,并实现了Init、Invoke和Query三个方法。Init方法在合约初始化时调用,Invoke方法实现了合约的写和读操作,Query方法实现了查询操作。具体实现中,write方法将传入的key-value对存储到区块链上,read方法从区块链上检索并返回指定的key-value对。最后,main函数调用了shim.Start方法启动了该合约
原文地址: https://www.cveoy.top/t/topic/fHlV 著作权归作者所有。请勿转载和采集!