Smart fabric contract

package main
//首先需要准备好必备的Go 编程样板,与所有的智能合约一样,它实现了Chaincode 接
//口,特别是实现了In it 和Invoke 方法。因此,需要给智能合约添加impo口语句,以获得必要
//的依赖项。这里将导入chaincode shim 包和peer protobuf 包。接下来,继续添加一个名为
//SimpleAsset 的struct 作为Chaincode shim 方法的接收方。
import (
    "fmt"

    "github.com/hyperledger/fabric/core/chaincode/shim"
    "github.com/hyperledger/fabric/protos/peer"

)

// SimpleAsset实现一个简单的智能合约来管理资产。
type SimpleAsset struct {

}


// Init在智能合约实例化过程中被调用初始化任何数据。

//智能合约升级也调用这个函数。在编写将妥升级的现有版本的智能合约时,请确保
//适当地修改Init 函数。特别是,如果没有“迁移”或者没有什么东西可以作为升级的一部分进
//行初始化,那么就提供一个空的“ Init”方法。
//func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response{
//}


//接下来,将使用ChaincodeStublnterface.GetStringArgs 方法检索Init所需要的参数,并核
//实其参数数量的有效性。在这个例子中,需要传入的是一个键值对,即两个参数。

//Init在智能合约实例化过程中被调用来初始化任何数据。
//注意,智能合约升级也调用这个方法来重置或迁移数据,
//所以要小心避免在无意中破坏了账本数据的情况!
func (t *SimpleAsset) Init(stub shim.ChaincodeStubinterface) peer.Response {
    //从交易请求中获取请求参数数组。
    args := stub.GetStringArgs()
    if len(args) != 2 {
        return shim.Error("Incorrect arguments. Expecting a key and a value")
    }

    //接下来,既然己经确定了调用是否具备有效性,那么在调用时传入参数有效的情况下,将把初始状态存储在账本中。
    //为了达到上述目的,这里将调用ChaincodeStubinterface.PutState 作为参数传递的键和值。
    //假设一切顺利,返回一个Peer响应对象。表示初始化的操作是成功的。具体示例代码如下:

    //在这里通过调用stub.PutState()方法来存入资产信息。

    //将资产的value和相关联key存入账本。
    err := stub.PutState(args[0], []byte(args[1]))
    if err != nil {
        return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0]))
    }
    return shim.Success(nil)
}


//与上面的Init 方法一样,这里需要从ChaincodeStublnterface 接口中提取参数.Invoke 方法
//的参数是将要调用的智能合约应用程序方法的名称。在这个例子中,所编写的应用程序只有两
//个功能: set 和get ,它允许设定一个资产的值,或者检索它的当前状态。
//首先调用ChaincodeStublnterface.GetFunctionAndParameters 方法,提取方法名和该智能合
//约应用程序功能的参数。具体示例如下:


//在智能合约上的每笔交易都会调用Invoke 。
//每一个事务都是由Init 方法创建的资产的“ get ”或“ set ”。
//“ set "方法可以通过指定新的键, 值对来创建新资产。
func (t *SimpleAsset) Invoke(stub shim.ChaincodeStublnterface) peer.Response {
    //从交易请求中获取方法名和请求参数数组。
    fn, args := stub.GetFunctionAndParameters()

    //接下来,将继续验证方法名是否为set 或get ,并调用那些智能合约应用程序的方法,通过
    //shim.Success 或shim.Error 方法返回适当的响应,这些方法将响应序列化成gRPC protobuf 消
    //息。具体示例代码如下:

    var result string
    var err error
    if fn == "set"{
        result, err = set(stub, args)
    } else { // assume 'get ’ even if fn is nil
        result, err = get(stub, args)
    }
    if err != nil {
        return shim.Error(err.Error())
    }
    //返回成功结果。
    return shim.Success([]byte(result))
}

//将资产(包括key 和lvalue )存储在账本上。
//如果key存在, 它会用新key覆盖value 。
func set(stub shim.ChaincodeStubinterface, args []string) (string, error) {
    if len(args) != 2 {
        return "", fmt.Errorf("Incorrect arguments . Expecting a key and a value")
    }
    err := stub.PutState(args[0], []byte(args[1]))
    if err != nil {
        return "", fmt.Errorf("Failed to set asset: %s", args[0])
    }
    return args[1], nil
}

//获取指定资产key的value
func get(stub shim.ChaincodeStubinterface, args []string) (string, error) {
    if  len(args) != 1 {
        return "", fmt.Errorf("Incorrect arguments. Expecting a key")
    }
    value, err := stub.GetState(args[0])
    if err != nil {
        return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err)
    }
    if value == nil {
        return "", fmt.Errorf("Asset not found : %s ", args[0])
    }
    return string(value), nil
}

//需要添加一个main 方法,它将调用shim.Start 方法。这是整个智能合约应用程序的入口方法。
//main方法在实例化过程中启动容器中的智能合约。
func main() {
    if err := shim.Start(new(SimpleAsset)); err != nil {
        fmt.Printf("Error sta 「ting SimpleAsset chaincode: %s", err)
    }
}

Contract to build intelligent environment

Written before this step is start compiling intelligence contracts code.
Specific execute the following command:

go get -u github.com/hyperledger/fabric/core/chaincode/shim
go build

Installation Hyperledger Fabric Samples

Determining a position to place any Hyperledger Fabric Samples warehouse and enter the directory terminal window on the server. The following command will perform the following steps:

  • Step 1: If necessary, clones hyperledger / fabric- samples warehouse.
  • Step 2: handover appropriate version label.
  • Step 3: Installation Hyperledger Fabric assigned to a particular version of fabric-samples repository root platform
    binaries and configuration files (particularly refer to section 3.1).
  • Step 4: Download Docker Hyperledger Fabric image for designating version (Specific Section 2.4, 2.).
    If you are ready to complete the above work, and entered through the terminal will be installed Fabric Samples and binaries
    directory member, continue with the following command:
    curl -ssl https://goo.gl/6wtTN5 | -s bash 1.1. 0

Note: If you encounter an error in the above curl command, you might curl version is too low, it can not at the
support processing or redirection from the environment. Access to curl the official website, the address for the HTTPS: //curl.haxx.se/download.html , find the latest version of the server environment in line with the curl to download and install. Further, it is possible to replace the above address is not a link shortening
https://github.com/hyperledger/fabric/blob/master/scripts/boot.sh .

The above command to download and execute a bash script that will download and extract all the specific needs of the network settings Fabric
platform binaries and place on top of them to create a clone warehouse. It retrieves six platform-specific binary files: Cryptogen, configtxgen, configtx lator, peer, orderer and fabric-ca client.
Bn and place them in a subdirectory of the current working directory.
You may be added to the PATH environment variable so that it can not fully define each binary path
in the case of access to these variables. For example, run the following command:
Export the PATH = <path to downloads LOCATION> / bin: $ the PATH
Finally, the script in the Hub will Docker Docker Docker image downloaded from the Hub to the local and label it as "latest".

Testing Smart Contract

Next, the terminal proceeds to the next directory chaincode-docker-devmode cloned into the fabric-samples the local repository. This process we need to open three terminal

Terminal 1 Start Network

Execute the following command:

docker-compose -f docker-compose-simple.yaml up

The above content SingleSampleMSPSoloorderer configuration file to start the network, and to "dev mode" startup peer. It also launched two additional containers - one for chaincode environment, a CLI for the chaincode interaction. Create and join the command channel is embedded CLI container, so we can immediately jump to the chain code calls.

Terminal 2 build and launch the chain code

First $ GOPATH / src / fcc copied to chaincode directory.

docker exec -it chaincode bash 

Chaincode into the container, you will see the following results:
root @ d2629980e76b: / opt / GOPATH / src / chaincode #
Now let's compile chaincode:

cd fcc 
go build

Now to run smart contract

CORE_PEER_ADDRESS=peer:7052 CORE_CHAINCODE_ID_NAME=mycc:0 ./fcc 

The above command does not establish a connection with any channel, so let's go to the third terminal to see how to use chaincode

Terminal 3 using a chain code

Hyperledger Fabric 1.1 official documents suggesting Although we in -peer-chaincodedev mode, but still need to install our own chain code, so that the system life cycle chain code can normally be checked, however, may remove this requirement in the future.

docker exec -it cli bash

Into the container cli

peer chaincode install -p chaincodedev/chaincode/fcc -n mycc -v 0 

peer chaincode instantiate -n mycc -v 0 -C myc -c '{"Args":["a","10"]}' 

The next issue to invoke a change value "a" to "20", the following command:

peer chaincode invoke -n mycc -c  '{”Args":["set ", "a", "20"]}' -C myc

Finally, the query a. You should see the value 20, execute the following command:

peer chaincode query -n mycc -c '{"Args": ["query", "a"]}'-C myc

By default, only install and instantiate the sacc. However, you can restart and different this network to easily test the smart contract by adding them to the smart contract subdirectory. At this point, they will visit in the smart container contract.

Reproduced in: https: //www.jianshu.com/p/715963cde34e

Guess you like

Origin blog.csdn.net/weixin_34023863/article/details/91115590