Hyperledger's Smart Contract demo analysis

Source: Internet
Author: User
Tags printf stub

This article address: original link

Share your experience on Hyperledger smart contracts.

Source Address: Chaincode_example2


In the previous setfabriconubuntu, there was no need for virtualbox and vagrant to deploy the fabric directly, and its usefulness now manifests itself ~

The operation of the smart contract Chaincode does not require multiple nodes to be started locally and can be tested directly. Then we can test the existing CHAINCODE_EXAMPLE02 project directly on Alibaba Cloud.


Refer to this article, follow the steps to start the CA, start the authentication node, and deploy Chaincode on that single node, then you can test the smart contract.

There are two ways to test Chaincode, one is the CLI and the other is rest.


/* Copyright IBM Corp All rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
You are not a use of this file except in compliance with the License.  Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by applicable law or Agreed to writing, software distributed under the License are distributed on a "as is" BASIS, without warranties OR CO
Nditions of any KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License. */Package main//warning-this Chaincode ' s ID was hard-coded in Chaincode_example04 to illustrate one-to-one-to-//calling Chaincode from a chaincode.
If This example is modified, chaincode_example04.go have//to be modified as well with the new ID of CHAINCODE_EXAMPLE02.

Chaincode_example05 Show ' s how Chaincode ID can is passed in as a parameter instead of//hard-coding. Import ("Errors" "FMT" "StrConv" "Github.com/hypErledger/fabric/core/chaincode/shim ")//Simplechaincode Example Simple Chaincode implementation type Simplechaincode s truct {} func (T *simplechaincode) Init (stub *shim. Chaincodestub, function string, args []string] ([]byte, error) {var A, B string//Entities var aval, Bval Int//AS Set Holdings var err error if Len (args)! = 4 {return nil, errors. New ("Incorrect number of arguments. Expecting 4 ")}//Initialize the Chaincode A = args[0] aval, err = StrConv. Atoi (args[1]) if err! = Nil {return nil, errors. New ("Expecting integer value for asset holding")} B = args[2] Bval, err = StrConv. Atoi (args[3]) if err! = Nil {return nil, errors. New ("Expecting integer value for asset holding")} FMT. Printf ("Aval =%d, Bval =%d\n", Aval, Bval)//Write the state to the Ledger err = stub. Putstate (A, []byte (StrConv). Itoa (Aval))) If err! = Nil {return nil, err} err = stub. Putstate (B, []byte (StrConv). Itoa (Bval))) If err! = Nil {return nil, err} return Nil, nil}//Transaction makes payment of X units from A to B func (t *simplechaincode) Invoke (stub *shim. Chaincodestub, function string, args []string] ([]byte, error) {if function = = "Delete" {//Deletes an entity from it           S state return T.delete (stub, args)} var A, B string//Entities var aval, Bval Int//Asset holdings var X int Transaction value var err error if Len (args)! = 3 {return nil, errors. New ("Incorrect number of arguments. Expecting 3 ")} A = Args[0] B = args[1]//Get the state from the ledger//Todo:will is nice to having A Getallstat E Call to ledger avalbytes, err: = Stub. GetState (A) if err! = Nil {return nil, errors. New ("Failed to Get State")} if Avalbytes = = Nil {return nil, errors. New ("Entity Not Found")} Aval, _ = StrConv. Atoi (String (avalbytes)) bvalbytes, Err: = Stub. GetState (B) if err! = Nil {return nil, errors. New ("Failed to Get State")} if Bvalbytes = = Nil {return nil, errors. New ("Entity notFound ")} Bval, _ = StrConv. Atoi (String (bvalbytes))//Perform The execution X, err = StrConv. Atoi (args[2]) Aval = aval-x Bval = Bval + X FMT. Printf ("Aval =%d, Bval =%d\n", Aval, Bval)//Write the state back to the Ledger err = stub. Putstate (A, []byte (StrConv). Itoa (Aval))) If err! = Nil {return nil, err} err = stub. Putstate (B, []byte (StrConv). Itoa (Bval))) If err! = Nil {return nil, err} return nil, nil}//Deletes an entity from the state func (T *simplecha Incode) Delete (stub *shim. Chaincodestub, args []string] ([]byte, error) {if Len (args)! = 1 {return nil, errors. New ("Incorrect number of arguments. Expecting 1 ")} A: = Args[0]//Delete The key from the state in ledger err: = Stub. Delstate (A) if err! = Nil {return nil, errors. New ("Failed to delete state")} return nil, nil}//query callback representing the query of a chaincode func (t *sim Plechaincode) Query (stub *shim.
	Chaincodestub, function string, args []string] ([]byte, error) {if function! = "Query" {return nil, errors. New ("Invalid query function name. Expecting \ "Query\" ")} var A string//entities var err error if Len (args)! = 1 {return nil, errors. New ("Incorrect number of arguments. Expecting name of the person to query ')} A = Args[0]//Get the state from the ledger avalbytes, err: = Stub. GetState (A) if err! = Nil {jsonresp: = "{\" error\ ": \" Failed to get the state for "+ A +" \ "}" return nil, errors. New (JSONRESP)} if avalbytes = = Nil {jsonresp: = "{\" error\ ": \" nil amount for "+ A +" \ "}" return nil, errors. New (JSONRESP)} JSONRESP: = "{\" name\ ": \" "+ A +" \ ", \" amount\ ": \" "+ string (avalbytes) +" \ "}" FMT. Printf ("Query response:%s\n", Jsonresp) return avalbytes, nil} func main () {err: = shim. Start (New (Simplechaincode)) if err! = Nil {fmt. Printf ("Error starting simple Chaincode:%s", err)}}


Chaincode_example02 mainly performs three core functions, Init, invoke, and query.

The init function initializes two accounts A, a, a, a, a, and a certain number of assets on a A, B account during the initial process.

The Invoke function transfers money on a and b.

The query function queries the account balances on the A and B functions.

The code in general is not very complex, writing similar projects can be done according to gourd painting scoop.


The CLI interacts as follows:

Core_security_enabled=true core_security_privacy=true Peer Chaincode deploy-u jim-n mycc-c ' {"Function": "Init", "Args" : ["A", "+", "B", "200"]} '

Rest can use postman and interact as follows,

POST Host:port/chaincode
POST host:port/chaincode

{
  "JSONRPC": "2.0",
  "method": "Deploy",
  "params": {
    "type": 1,
    " Chaincodeid ": {
        " name ":" MYCC "
    },
    " Ctormsg ": {
        " function ":" Init ","
        args ": [" a "," + "," B "," 200 "]
    },
    " Securecontext ":" Jim "
  },
  " id ": 1
}


The CLI and Rest pro-test is feasible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.