栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

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

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录
  • 一、区块链是什么?
  • 二、用Hyperledger Fabric开发区块链智能合约实践
    • 1.什么是区块链智能合约
    • 2.主要调用的两个包
    • 3.主要的两个方法
    • 4.主要的两个关键字
        • PutState和GetState
    • 5.编写智能合约代码
  • 总结


一、区块链是什么?

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

二、用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的主要代码的实现。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/944210.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号