Fabric Learning Notes-smart contract __fabric

Source: Internet
Author: User

This article describes what a smart contract is and how to write a simple smart contract demo under fabric. What is a smart contract.

Intelligent contract is a computer protocol which aims to disseminate, verify or execute contracts in an informational way. Smart contracts allow for credible transactions without a third party. These transactions are traceable and irreversible, and fabric provides a credible execution environment for smart contracts. smart contracts under fabric

Chaincode is the code implementation of intelligent contract under fabric, is a piece of code that validates, stores and executes on the block chain, only through Chaincode can interact with fabric network.

Under the fabric is divided into system chaincode and ordinary Chaincode. The system Chaincode runs in the peer node rather than in an isolated container, and there is no lifecycle concept for implementing some system behavior. Ordinary Chaincode is run in a separate container, providing interfaces for manipulating fabric networks, packaging, installing, instantiating, and upgrading four life cycles with corresponding functions to provide calls, and the more flexible operations we usually refer to as Chaincode.

The running process of Chaincode channel is responsible for connecting different peer, synchronously connecting to the peer of Chaincode, which is equivalent to dividing some nodes into a subset and synchronizing Chaincode execution results. Endorser is responsible for the execution of Chaincode. Orderer is responsible for the chaincode of the implementation of the results of consensus, currently supporting the solo/kafka/sbft three ways of consensus. Committer is responsible for the chaincode after the consensus of the results written to ledger. Write Chaincode

Chaincode must implement two interfaces.

Type Chaincode Interface {	
    //  initialization ⼯, ⼀ in case only ⽤⼀ times, the upgrade will also call the function
    Init (stub chaincodestubinterface) PB. Response
    //  query or update World State, can be adjusted repeatedly ⽤
    Invoke (stub	chaincodestubinterface)	PB. Response
}

Below is the structure required for a minimum smart contract.

Package	main	
import	(	
    "FMT"	
    "Github.com/hyperledger/fabric/core/chaincode/shim"	
)

type simpleasset struct {}

func (t *simpleasset) Init (stub shim.) Chaincodestubinterface) Peer. Response {}
func (t *simpleasset) Invoke (stub shim. Chaincodestubinterface) Peer. Response {}

func main () {
    If err: = shim. Start (New (Simpleasset)); Err!= Nil {
        FMT. Printf ("Error starting Simpleasset Chaincode:%s", err)
    }
}

The specific business logic is written inside the Invoke function.

First, let's refine the init function

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 ")
  }
  //instantiation when initializing the status
  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)
}

And then write the business logic in Invoke.

Func (t *simpleasset) Invoke (stub shim. Chaincodestubinterface) Peer. Response {
    fn, args: = Stub. Getfunctionandparameters ()
    var result string
    var err error
    If fn = ' Set ' {result
        , err = set (stub, args) c5/>} else {result
        , err = get (stub, args)
    }
    If err!= nil {return
        shim. Error (Err. Error ())
    } return
    shim. Success ([]byte (Result)
}

Invoke decides to invoke the query or set the state according to different parameters.

Writing set and get functions

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
}

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
}

GitHub has the complete code, the code is very simple is based on the command query or set the state of the world.

The effect of the implementation of the following figure:

In this way, a simple intelligent contract is realized on the fabric.

https://zhuanlan.zhihu.com/p/33750599

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.