sdk python中hyperledger结构的服务发现

pxq42qpu  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(313)

实际上,我正在使用python sdk在hyperledger结构中进行服务发现。我面临的问题是,发现功能不使用随机对等点发送事务,它只返回与hyperledger网络上活动对等点相关的信息。我在java sdk之前使用过它,它提供了一个函数来发送一个事务,选择随机对等点,并且在配置文件中只有一个对等点,如下所示:

Peer discoveryPeer = this.client.newPeer(this.properties.getPeer0Name(), this.properties.getPeer0Address(),
                peerProperties);

        // TODO: Loop on configured peers
        this.channel.addPeer(discoveryPeer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.SERVICE_DISCOVERY,
                PeerRole.LEDGER_QUERY, PeerRole.EVENT_SOURCE, PeerRole.CHAINCODE_QUERY)));

        this.channel.initialize();
        this.initialized = true;

这是:

private Pair<HashMap<String ,String>, CompletableFuture<TransactionEvent>> sendTransaction(
            String chainCodeName, String functionName, String[] arguments) throws Exception {
        TransactionProposalRequest tpr = this.client.newTransactionProposalRequest();
        ChaincodeID cid = ChaincodeID.newBuilder().setName(chainCodeName).build();
        tpr.setChaincodeID(cid);
        tpr.setFcn(functionName);
        tpr.setArgs(arguments);
        DiscoveryOptions discoveryOptions = createDiscoveryOptions()
                .setEndorsementSelector(ServiceDiscovery.EndorsementSelector.ENDORSEMENT_SELECTION_RANDOM)
                .setForceDiscovery(true);
        Collection<ProposalResponse> responses;
        try {
            responses = this.channel.sendTransactionProposalToEndorsers(tpr, discoveryOptions);
        } catch (Exception e1) {
            log.error("Sending trx proposal failed");
            throw (e1);

        }

在application-dev.yml文件中,我也只使用了yc-one-peer。当我尝试对pythin sdk进行同样的操作时,我有一个如下的配置文件:

{
  "name":"sample-network",
  "description":"Sample network contains 4 peers (2 orgs), 1 orderer and 2 cas for Python SDK testing",
  "version":"0.1",
  "client":{
    "organization":"Org1",
    "credentialStore":{
      "path":"/tmp/hfc-kvs",
      "cryptoStore":{
        "path":"/tmp/hfc-cvs"
      },
      "wallet":"wallet-name"
    }
  },
  "organizations":{
    "Orderer": {
      "mspid": "OrdererMSP",
      "orderers": [
        "orderer1"
      ],
      "certificateAuthorities": [
        "ca"
      ],
      "users": {
        "Admin": {
          "cert": "cert_path",
          "private_key": "key_path"
        }
      }
    },
    "org1":{
      "mspid":"org1msp",
      "peers":[
        "peer1"
      ],
      "users": {
        "Admin": {
          "cert": "user_cert_path",
          "private_key": "user_key_path"
      }
    }
  }
},
  "orderers":{
    "orderer1":{
      "url":"orderer1:7052",
      "grpcOptions":{
        "grpc.ssl_target_name_override":"orderer1",
        "grpc-max-send-message-length":15
      },
      "tlsCACerts":{
        "path":"ca_cert_path"
      }
    }
  },
  "peers":{
    "peer1":{
      "url":"peer1:7065",
      "eventUrl":"peer1:7066",
      "grpcOptions":{
        "grpc.ssl_target_name_override":"peer1",
        "grpc.http2.keepalive_time":1000
      },
      "tlsCACerts":{
        "path":"ca_cert_path"
      }
    }
  },
  "certificateAuthorities":{

  }
}

我在sdk文件中做了两个函数:一个用于发现对等点,另一个用于发送事务。。。使用我在network.json文件中所做的如下操作:
sdk.py:

import asyncio
from BerryStorageProxy.tools.HyperledgerFabric.hfc.fabric import Client 
from BerryStorageProxy.tools.HyperledgerFabric.hfc.fabric.peer import Peer
import os 
import sys
sys.path.append(os.path.abspath('.'))

from digitalberry.util.helpers import decorate_all_functions, log_on_call
from digitalberry.util.json import parse_config
import logging
import json
from BerryStorageProxy.settings import CONF_FILE_HLF

consoleHandler = logging.StreamHandler()
_logger = logging.getLogger(__name__)

_logger.setLevel(logging.DEBUG)
_logger.addHandler(consoleHandler)

@decorate_all_functions(log_on_call)
class SDK_HLF:

        def __init__(self):

                try:
                        with open(CONF_FILE_HLF) as config_file:
                                conf = json.load(config_file)
                except FileNotFoundError:
                        msg='Couldn\'t load configuration file: {}'.format(CONF_FILE_HLF)
                        _logger.error(msg)
                        raise FileNotFoundError(msg)
                except json.decoder.JSONDecodeError:
                        msg='Invalid JSON file: {}'.format(CONF_FILE_HLF)
                        _logger.error(msg)
                        raise ValueError(msg)

                _logger.debug("JSON configuration loaded successfully")

                self.loop = asyncio.new_event_loop()
                asyncio.set_event_loop(self.loop)

                self.config_schema={
                "type" : "object",
                "properties" : {
                        "network_profile" : {"type" : "string"},
                        "channel" : {"type" : "string"},
                        "peer_org_name" : {"type" : "string"},
                        "username" : {"type" : "string"},
                },
                "required" : ["network_profile","channel","peer_org_name","username",]
                }

                try:
                        parse_config(self.config_schema,conf)
                except Exception:
                        message="Error validating the JSON conf:\n{}".format(conf)
                        _logger.error(message)
                        raise Exception(message)

                _logger.debug("JSON configuration valid")

                self.cli = Client(net_profile=conf['network_profile'])

                self.requestor = self.cli.get_user(conf['peer_org_name'], conf['username'])
                self.cli.new_channel(conf['channel'])

        def chaincode_invoke(self, args):

                response = self.loop.run_until_complete(self.cli.chaincode_invoke(
                        requestor=self.requestor,
                        channel_name=args['channel'],
                        peers=args['peer'],
                        args=args['cc_args'],
                        cc_name=args['cc_name'],
                        fcn=args['cc_func'],
                        transient_map=None, 
                        ))
                _logger.debug("Chaincode invoke response")
                _logger.debug(response)
                return response

        def chaincode_query(self,args):

                response = self.loop.run_until_complete(self.cli.chaincode_query(
                        requestor=self.requestor,
                        channel_name=args['channel'],
                        peers=args['peer'],
                        args=args['cc_args'],
                        cc_name=args['cc_name'],
                        fcn=args['cc_func']
                        ))

                _logger.debug("Chaincode query response")
                _logger.debug(response)
                return response

        def channel_discovery(self): 

                response = self.loop.run_until_complete(self.cli.query_peers(requestor=self.requestor,
                        peer='peer1',
                        channel='channel1',
                        local=False,
                        decode=True))
                _logger.debug("Chaincode query response")
                _logger.debug(response)
                return response

这是我用来获取频道名称和其他有用信息的额外配置文件:

{
   "network_profile":"network.json_path",
   "channel":"channel1",
   "peer_org_name":"org1",
   "username":"Admin",
   "peer_msp_id":"orgmsp"
}

当我执行所有这些操作并尝试发送事务时,它显示一个错误,表示找不到请求的对等方。您能否帮助我使用发现系统发送请求,而不必像java案例那样将所有对等方放在我的network.json文件中?非常感谢。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题