Hyperledger Fabric 智能合约实战–go语言开发–简单(1)


一、区块链是什么?

区块链是用分布式数据库识别、传播和记载信息的智能化对等网络,也称为价值互联网。
即分布式账本。

二、用Hyperledger Fabric开发区块链智能合约实践

1.什么是区块链智能合约

智能合约(英语: Smart contract)是一种旨在以信息化方式传播、验证或执行合同的计算机协议。智能合约允许在没有第三方的情况下进行可信交易,这些交易可追踪且不可逆转。
智能合约的目的是提供优于传统合约的安全方法,并减少与合约相关的其他交易成本。

2.主要调用的两个包

import(
    "github.com/hyperledger/fabric-chaincode-go/shim"
    pb"github.com/hyperledger/fabric-protos-go/peer"
)

3.主要的两个方法

代码如下(示例):

func (t *A) Init (stub shim.ChaincodeStubInterface) pb.Response {
}
func (t *A) Invoke (stub shim.ChaincodeStubInterface) pb.Response{
}

4.主要的两个关键字

PutState和GetState

PutState用来存放数据
GetState用来获取数据

5.编写智能合约代码

用 Fabric 编写智能合约代码 A.go,go语言实现。
代码如下(示例):

package main

import(
   "fmt"
   "github.com/hyperledger/fabric-chaincode-go/shim"
   pb"github.com/hyperledger/fabric-protos-go/peer"
)

type A struct {

}

func (t *A) Init (stub shim.ChaincodeStubInterface) pb.Response {

   args := stub.GetStringArgs()
   err :=  stub.PutState(args[0],[]byte(args[1]))
   if err != nil {
       shim.Error(err.Error())
   }
   
   return shim.Success(nil)
}

func (t *A) Invoke (stub shim.ChaincodeStubInterface) pb.Response {

   fn, args := stub.GetFunctionAndParameters ()
   
   if fn == "set" {
     return t.set(stub, args)
  } else if fn == "get" {
     return t.get(stub,args)
  }
  
  return shim.Error("Invoke fn error")
}

func (t *A) set (stub shim.ChaincodeStubInterface, args []string) pb.Response{
   
   if len(args) != 2 {
       return fmt.Errorf("Incorrect arguments. Expecting a key and value")
  }
   
   err := stub.PutState(args[0],[]byte(args[1]))
   if err != nil {
       return shim.Error(err.Error())
   }
   
   return shim.Success(nil)
}

func (t *A) get (stub shim.ChaincodeStubInterface, args []string) pb.Response{
   
   if len(args) != 1 {
      return fmt.Errorf("Incorrect arguments. Expecting a key")
  }

   value,err := stub.GetState(args[0])
   if err != nil {
       return shim.Error(err.Error)
  }

  return shim.Success(value)
}

func main() {
  err := shim.Start(new(A))
  if err != nil {
      fmt.Printf("start error: %s",err)
  }
}

函数入参口中(stub shim.ChaincodeStubInterface, args [ ]string)这两个入参:
shim.ChaincodeStubInterface 是链码的根接口
args []string 是传入的参数


总结

以上就是今天要讲的内容,本文仅仅简单介绍了关于区块链的一些概念和Fabric的主要代码的实现。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>