HyperLeger Fabric SDK开发

1、sdk/main.go 文件

package main

import (
    "fmt"
    "github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
    "github.com/hyperledger/fabric-sdk-go/pkg/common/logging"
    "github.com/hyperledger/fabric-sdk-go/pkg/core/config"
    "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
    "os"
)

var (
    cc          = "copyright"
    user        = "Admin" //此处Admin,但实际中应使用User1
    secret      = ""
    channelName = "mychannel"
    lvl         = logging.INFO
    orgName     = "Org1MSP"
)

func main() {
    c := config.FromFile("./config.yaml")
    sdk, err := fabsdk.New(c)
    if err != nil {
        fmt.Printf("Failed to create new SDK: %s\n", err)
        os.Exit(1)
    }
    defer sdk.Close()
    clientChannelContext := sdk.ChannelContext(channelName, fabsdk.WithUser(user), fabsdk.WithOrg(orgName))
    if err != nil {
        fmt.Printf("Failed to create channel [%s] client: %#v", channelName, err)
        os.Exit(1)
    }

    client, err := channel.New(clientChannelContext)
    if err != nil {
        fmt.Printf("Failed to create channel [%s]:", channelName, err)
    }
    //queryCC(client, []byte("李四"))
    //json := `{"name":"zhangsi","age":18,"address":"北京市丰台区"}`
    name := "张三"
    //invokeCC(client, name, json)
    //deleteCC(client, []byte(name))
    queryCC(client, []byte(name))
}

func invokeCC(client *channel.Client, name string, value string) {
    args := [][]byte{[]byte(name), []byte(value)}
    _, err := client.Execute(channel.Request{
        ChaincodeID: cc,
        Fcn:         "set",
        Args:        args,
    })

    if err != nil {
        fmt.Printf("Failed to invoke: %+v\n", err)
    }
}

func deleteCC(client *channel.Client, name []byte) {
    var args = [][]byte{name}
    _, err := client.Execute(channel.Request{
        ChaincodeID: cc,
        Fcn:         "del",
        Args:        args,
    })

    if err != nil {
        fmt.Println("Failed to query: ", err)
    }

}

func queryCC(client *channel.Client, name []byte) string {
    var args = [][]byte{name}
    response, err := client.Query(channel.Request{
        ChaincodeID: cc,
        Fcn:         "get",
        Args:        args,
    })

    if err != nil {
        fmt.Println("Failed to query: ", err)
    }

    //ret := string(response.Payload)
    fmt.Println("Chaincode status: ", response.ChaincodeStatus)
    fmt.Println("Payload: ", response)
    return ""
}

 

2、config.yaml 文件

#指定版本GO SDK
version: 1.0.0

#客户端定义
client:

  # Which organization does this application instance belong to? The value must be the name of an org
  # defined under "organizations"
  organization: Org1MSP

  logging:
    level: info

  # Root of the MSP directories with keys and certs.
  cryptoconfig:
    # path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}
    path: ./organizations
  # Some SDKs support pluggable KV stores, the properties under "credentialStore"
  # are implementation specific
  credentialStore:
    # [Optional]. Used by user store. Not needed if all credentials are embedded in configuration
    # and enrollments are performed elswhere.
    path: "./tmp/state-store"

    # [Optional]. Specific to the CryptoSuite implementation used by GO SDK. Software-based implementations
    # requiring a key store. PKCS#11 based implementations does not.
    #cryptoStore:
      # Specific to the underlying KeyValueStore that backs the crypto key store.
      #path: ./organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/

  # [Optional] BCCSP config for the client. Used by GO SDK.
  BCCSP:
    security:
      enabled: true
      default:
        provider: "SW"
      hashAlgorithm: "SHA2"
      softVerify: true
      level: 256

  tlsCerts:
    # [Optional]. Use system certificate pool when connecting to peers, orderers (for negotiating TLS) Default: false
    systemCertPool: true

    # [Optional]. Client key and cert for TLS handshake with peers and orderers
    client:
      key:
        # path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/tls.example.com/users/User1@tls.example.com/tls/client.key
        path: /Users/lishengqiang/website/go/fabric-go-api/organizations/peerOrganizations/org1.example.com/users/User1@org1.example.com/tls/client.key
      cert:
        # path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/tls.example.com/users/User1@tls.example.com/tls/client.crt
        path: /Users/lishengqiang/website/go/fabric-go-api/organizations/peerOrganizations/org1.example.com/users/User1@org1.example.com/tls/client.crt

#
# [Optional]. But most apps would have this section so that channel objects can be constructed
# based on the content below. If an app is creating channels, then it likely will not need this
# section.
#
channels:
  # Default channel is used if channel configuration is missing or if defined channel configuration is missing info
  # If channel doesn't define peers then peers from default channel will be used
  # If channel doesn't define orderes then orderes from default channel will be used
  # If channel doesn't define policies then policies from default channel will be used.
  # Also, if channel defines policies and some policy info is missing than that missing info will be filled from default channel.
  _default:

    # Optional. list of peers from participating orgs
    peers:
      peer0.org1.example.com:
        # [Optional]. will this peer be sent transaction proposals for endorsement? The peer must
        # have the chaincode installed. The app can also use this property to decide which peers
        # to send the chaincode install request. Default: true
        endorsingPeer: true

        # [Optional]. will this peer be sent query proposals? The peer must have the chaincode
        # installed. The app can also use this property to decide which peers to send the
        # chaincode install request. Default: true
        chaincodeQuery: true

        # [Optional]. will this peer be sent query proposals that do not require chaincodes, like
        # queryBlock(), queryTransaction(), etc. Default: true
        ledgerQuery: true

        # [Optional]. will this peer be the target of the SDK's listener registration? All peers can
        # produce events but the app typically only needs to connect to one to listen to events.
        # Default: true
        eventSource: true

    # [Optional]. The application can use these options to perform channel operations like retrieving channel
    # config etc.
    policies:
      #[Optional] options for retrieving channel configuration blocks
      queryChannelConfig:
        #[Optional] min number of success responses (from targets/peers)
        minResponses: 1
        #[Optional] channel config will be retrieved for these number of random targets
        maxTargets: 1
        #[Optional] retry options for query config block
        retryOpts:
          #[Optional] number of retry attempts
          attempts: 5
          #[Optional] the back off interval for the first retry attempt
          initialBackoff: 500ms
          #[Optional] the maximum back off interval for any retry attempt
          maxBackoff: 5s
          #[Optional] he factor by which the initial back off period is exponentially incremented
          backoffFactor: 2.0
      #[Optional] options for retrieving discovery info
      discovery:
        #[Optional] discovery info will be retrieved for these number of random targets
        maxTargets: 2
        #[Optional] retry options for retrieving discovery info
        retryOpts:
          #[Optional] number of retry attempts
          attempts: 4
          #[Optional] the back off interval for the first retry attempt
          initialBackoff: 500ms
          #[Optional] the maximum back off interval for any retry attempt
          maxBackoff: 5s
          #[Optional] he factor by which the initial back off period is exponentially incremented
          backoffFactor: 2.0

      #[Optional] options for the event service
      eventService:
        resolverStrategy: PreferOrg
        balancer: Random
        blockHeightLagThreshold: 5
        reconnectBlockHeightLagThreshold: 8
        peerMonitorPeriod: 6s

  mychannel:

    peers:
      peer0.org1.example.com:

        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true

organizations:
  # Org1:
  Org1MSP:
    mspid: Org1MSP
    cryptoPath:  /Users/lishengqiang/website/go/fabric-go-api/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp

    peers:
      - peer0.org1.example.com

orderers: #这部分内容没有起作用,原因未知
  orderer.example.com:
    # [Optional] Default: Infer from hostname
    url: orderer.example.com:7050

    # these are standard properties defined by the gRPC library
    # they will be passed in as-is to gRPC client constructor
    grpcOptions:
      ssl-target-name-override: orderer.example.com
      # These parameters should be set in coordination with the keepalive policy on the server,
      # as incompatible settings can result in closing of connection.
      # When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
      keep-alive-time: 0s
      keep-alive-timeout: 20s
      keep-alive-permit: false
      fail-fast: false
      # allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
      allow-insecure: false

    tlsCACerts:
      # Certificate location absolute path
      # path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem
      path: /Users/lishengqiang/website/go/fabric-go-api/organizations/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem

#
# List of peers to send various requests to, including endorsement, query
# and event listener registration.
#
peers:
  peer0.org1.example.com:
    # this URL is used to send endorsement and query requests
    # [Optional] Default: Infer from hostname
    url: peer0.org1.example.com:7051

    grpcOptions:
      ssl-target-name-override: peer0.org1.example.com
      # These parameters should be set in coordination with the keepalive policy on the server,
      # as incompatible settings can result in closing of connection.
      # When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
      keep-alive-time: 0s
      keep-alive-timeout: 20s
      keep-alive-permit: false
      fail-fast: false
      # allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
      allow-insecure: false

    tlsCACerts:
      # Certificate location absolute path
      # path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem
      path: /Users/lishengqiang/website/go/fabric-go-api/organizations/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem

  peer0.org2.example.com:
    url: peer0.org2.example.com:9051
    grpcOptions:
      ssl-target-name-override: peer0.org2.example.com
      # These parameters should be set in coordination with the keepalive policy on the server,
      # as incompatible settings can result in closing of connection.
      # When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
      keep-alive-time: 0s
      keep-alive-timeout: 20s
      keep-alive-permit: false
      fail-fast: false
      # allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
      allow-insecure: false

    tlsCACerts:
      # path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem
      path: /Users/lishengqiang/website/go/fabric-go-api/organizations/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem

  #
  # Fabric-CA is a special kind of Certificate Authority provided by Hyperledger Fabric which allows
  # certificate management to be done via REST APIs. Application may choose to use a standard
  # Certificate Authority instead of Fabric-CA, in which case this section would not be specified.
  #
  # certificateAuthorities:
  #   ca.org1.example.com:
  #     # [Optional] Default: Infer from hostname
  #     url: https://ca.org1.example.com:7054
  #     tlsCACerts:
  #       # Comma-Separated list of paths
  #       path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem
  #       # Client key and cert for SSL handshake with Fabric CA
  #       client:
  #         key:
  #           path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/tls.example.com/users/User1@tls.example.com/tls/client.key
  #         cert:
  #           path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/tls.example.com/users/User1@tls.example.com/tls/client.crt

  #     # Fabric-CA supports dynamic user enrollment via REST APIs. A "root" user, a.k.a registrar, is
  #     # needed to enroll and invoke new users.
  #     registrar:
  #       enrollId: admin
  #       enrollSecret: adminpw
  #     # [Optional] The optional name of the CA.
  #     caName: ca.org1.example.com
  #   ca.org2.example.com:
  #     url: https://ca.org2.example.com:8054
  #     tlsCACerts:
  #       # Comma-Separated list of paths
  #       path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem
  #       # Client key and cert for SSL handshake with Fabric CA
  #       client:
  #         key:
  #           path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/tls.example.com/users/User1@tls.example.com/tls/client.key
  #         cert:
  #           path: ${FABRIC_SDK_GO_PROJECT_PATH}/${CRYPTOCONFIG_FIXTURES_PATH}/peerOrganizations/tls.example.com/users/User1@tls.example.com/tls/client.crt

  #      # Fabric-CA supports dynamic user enrollment via REST APIs. A "root" user, a.k.a registrar, is
  #      # needed to enroll and invoke new users.
  #     registrar:
  #       enrollId: admin
  #       enrollSecret: adminpw
  #     # [Optional] The optional name of the CA.
  #     caName: ca.org2.example.com

  # EntityMatchers enable substitution of network hostnames with static configurations
  # so that properties can be mapped. Regex can be used for this purpose
  # UrlSubstitutionExp can be empty which means the same network hostname will be used
  # UrlSubstitutionExp can be given same as mapped peer url, so that mapped peer url can be used
  # UrlSubstitutionExp can have golang regex matchers like ${1}.local.example.${2}:${3} for pattern
  # like peer0.org1.example.com:1234 which converts peer0.org1.example.com to peer0.org1.local.example.com:1234
  # sslTargetOverrideUrlSubstitutionExp follow in the same lines as
  # SubstitutionExp for the fields gprcOptions.ssl-target-name-override respectively
# In any case mappedHost's config will be used, so mapped host cannot be empty, if entityMatchers are used
#entityMatchers:
entityMatchers:
  peer:
    - pattern: (\w+).org1.example.com:(\d+)
      urlSubstitutionExp: ${1}.org1.example.com:${2}
      sslTargetOverrideUrlSubstitutionExp: ${1}.org1.example.com
      mappedHost: peer0.org1.example.com

    - pattern: (\w+).org2.example.com:(\d+)
      urlSubstitutionExp: ${1}.org2.example.com:${2}
      sslTargetOverrideUrlSubstitutionExp: ${1}.org2.example.com
      mappedHost: peer0.org2.example.com

  orderer:
    - pattern: (\w+) #理论上该写(\w+).example.(\w+),但总是访问127.0.0.1:7050,暂时未找到原因,先模糊匹配
      urlSubstitutionExp: orderer.example.com:7050
      sslTargetOverrideUrlSubstitutionExp: orderer.example.com
      mappedHost: orderer.example.com
#
#    - pattern: (\w+).example2.(\w+)
#      urlSubstitutionExp: localhost:7050
#      sslTargetOverrideUrlSubstitutionExp: localhost
#      mappedHost: orderer.example.com
#
#    - pattern: (\w+).example3.(\w+)
#      urlSubstitutionExp:
#      sslTargetOverrideUrlSubstitutionExp:
#      mappedHost: orderer.example.com
#
#    - pattern: (\w+).example4.(\w+):(\d+)
#      urlSubstitutionExp: ${1}.example.${2}:${3}
#      sslTargetOverrideUrlSubstitutionExp: ${1}.example.${2}
#      mappedHost: orderer.example.com
#
#  certificateAuthority:
#    - pattern: (\w+).org1.example.(\w+)
#      urlSubstitutionExp:
#      mappedHost: ca.org1.example.com
#
#    - pattern: (\w+).org2.example.(\w+)
#      urlSubstitutionExp:
#      mappedHost: ca.org2.example.com

 

结合上篇链码文章使用

posted @ 2021-03-01 15:18  北漂生活  阅读(220)  评论(0编辑  收藏  举报