网关SDK是根据超级账本的基础SDK开发出来的一个高级SDK,为我们开发部署省去很多的麻烦。
网关SDK是应用程序与区块链网络交互的一个工具,提供了一些简单的API向账本提交交易或者查询。
这里我们使用超级账本中的fabric-sample作为操作环境。
进入到fabric-sample中的asset-transfer-basic目录下,这里有为我们提供的模板(不仅仅只是Golang的),我们照着模板修改写出我们自己的程序即可。
go mod init
在main.go文件中导入以下包
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/gateway"
)
wallet, err := gateway.NewFileSystemWallet("wallet")
if err != nil {
log.Fatalf("Failed to create wallet: %v", err)
}
if !wallet.Exists("appUser") {
err = populateWallet(wallet) // 方法写在最下面
if err != nil {
log.Fatalf("Failed to populate wallet contents: %v", err)
}
}
ccpPath := filepath.Join(
"..",
"..",
"test-network",
"organizations",
"peerOrganizations",
"org1.example.com",
"connection-org1.yaml",
)
gw, err := gateway.Connect(
gateway.WithConfig(config.FromFile(filepath.Clean(ccpPath))),
gateway.WithIdentity(wallet, "appUser"),
)
if err != nil {
log.Fatalf("Failed to connect to gateway: %v", err)
}
defer gw.Close()
network, err := gw.GetNetwork("mychannel")
if err != nil {
log.Fatalf("Failed to get network: %v", err)
}
contract := network.GetContract("basic")
result, err := contract.SubmitTransaction("InitLedger")
if err != nil {
log.Fatalf("Failed to Submit transaction: %v", err)
}
result, err = contract.EvaluateTransaction("ReadAsset", "asset13")
// 返回结果[]byte,进行类型强制转换
log.Println(string(result))
func populateWallet(wallet *gateway.Wallet) error {
log.Println("============ Populating wallet ============")
credPath := filepath.Join(
"..",
"..",
"test-network",
"organizations",
"peerOrganizations",
"org1.example.com",
"users",
"[email protected]",
"msp",
)
certPath := filepath.Join(credPath, "signcerts", "cert.pem")
// 证书文件
cert, err := ioutil.ReadFile(filepath.Clean(certPath))
if err != nil {
return err
}
keyDir := filepath.Join(credPath, "keystore")
// 私钥文件
files, err := ioutil.ReadDir(keyDir)
if err != nil {
return err
}
if len(files) != 1 {
return fmt.Errorf("keystore folder should have contain one file")
}
keyPath := filepath.Join(keyDir, files[0].Name())
key, err := ioutil.ReadFile(filepath.Clean(keyPath))
if err != nil {
return err
}
identity := gateway.NewX509Identity("Org1MSP", string(cert), string(key))
return wallet.Put("appUser", identity)
}