Exemplo n.º 1
0
    def cc_invoke(self, args, cc_name, fcn, cc_version, queryonly=False):
        loop = asyncio.get_event_loop()
        crypto = ecies()

        endorses = self._get_endorsers(queryonly)

        tran_prop_req = create_tx_prop_req(
            prop_type=CC_INVOKE,
            cc_type=CC_TYPE_GOLANG, cc_name=cc_name, fcn=fcn,
            cc_version=cc_version, args=args)

        tx_context = create_tx_context(self.user, crypto, tran_prop_req)

        responses, proposal, header = self.channel.send_tx_proposal(
            tx_context, endorses.values())

        res = loop.run_until_complete(asyncio.gather(*responses))

        if queryonly:
            return res

        tran_req = build_tx_req((res, proposal, header))

        tx_context_tx = create_tx_context(self.user,
                                          crypto,
                                          TXProposalRequest())

        responses = loop.run_until_complete(base.get_stream_result(
            send_transaction(self.client.orderers, tran_req, tx_context_tx)))

        logger.info('Tx response: {0}'.format(responses))

        return responses
Exemplo n.º 2
0
    def test_instantiate_chaincode(self):

        channel = self.client.new_channel(self.channel_name)
        org1 = 'org1.example.com'
        peer_config = test_network['org1.example.com']['peers']['peer0']
        tls_cacerts = peer_config['tls_cacerts']
        opts = (('grpc.ssl_target_name_override',
                 peer_config['server_hostname']), )
        endpoint = peer_config['grpc_request_endpoint']

        peer = create_peer(endpoint=endpoint,
                           tls_cacerts=tls_cacerts,
                           opts=opts)

        org1_admin = get_peer_org_user(org1, 'Admin', self.client.state_store)
        crypto = ecies()

        # for chain code install
        tran_prop_req_in = create_tx_prop_req(prop_type=CC_INSTALL,
                                              cc_path=CC_PATH,
                                              cc_type=CC_TYPE_GOLANG,
                                              cc_name=CC_NAME,
                                              cc_version=CC_VERSION)

        # install chain code
        tx_context_in = create_tx_context(org1_admin, crypto, tran_prop_req_in)

        # for chain code deploy
        args = ['a', '100', 'b', '40']
        tran_prop_req_dep = create_tx_prop_req(prop_type=CC_INSTANTIATE,
                                               cc_type=CC_TYPE_GOLANG,
                                               cc_name=CC_NAME,
                                               cc_version=CC_VERSION,
                                               args=args,
                                               fcn='init')

        # deploy the chain code
        tx_context_dep = create_tx_context(org1_admin, crypto,
                                           tran_prop_req_dep)

        # create a channel
        request = build_channel_request(self.client, self.channel_tx,
                                        self.channel_name)

        self.client._create_channel(request)

        # join channel
        join_req = build_join_channel_req(org1, channel, self.client)
        channel.join_channel(join_req)

        self.client.send_install_proposal(tx_context_in, [peer])

        # send the transaction to the channel
        res = channel.send_instantiate_proposal(tx_context_dep, [peer])
        tran_req = build_tx_req(res)

        tx_context = create_tx_context(org1_admin, crypto, TXProposalRequest())
        response = send_transaction(channel.orderers, tran_req, tx_context)

        self.assertEqual(response[0].status, 200)
Exemplo n.º 3
0
    def chaincode_instantiate(self, requestor, channel_name, peer_names, args,
                              cc_name, cc_version, timeout=10):
        """
            Instantiate installed chaincode to particular peer in
            particular channel

        :param requestor: User role who issue the request
        :param channel_name: the name of the channel to send tx proposal
        :param peer_names: Names of the peers to install
        :param args (list): arguments (keys and values) for initialization
        :param cc_name: chaincode name
        :param cc_version: chaincode version
        :param timeout: Timeout to wait
        :return: True or False
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        tran_prop_req_dep = create_tx_prop_req(
            prop_type=CC_INSTANTIATE,
            cc_type=CC_TYPE_GOLANG,
            cc_name=cc_name,
            cc_version=cc_version,
            fcn='init',
            args=args
        )

        tx_context_dep = create_tx_context(
            requestor,
            ecies(),
            tran_prop_req_dep
        )

        res = self.send_instantiate_proposal(
            tx_context_dep, peers, channel_name)

        sleep(5)

        tx_context = create_tx_context(requestor,
                                       ecies(),
                                       TXProposalRequest())
        tran_req = utils.build_tx_req(res)
        response = utils.send_transaction(self.orderers, tran_req, tx_context)

        sleep(5)

        self.txid_for_test = tx_context_dep.tx_id  # used only for query test

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res, _ = queue.get(timeout=timeout)
        _logger.debug(res)
        return res.status == 200
Exemplo n.º 4
0
    def test_instantiate_chaincode(self):

        peer_config = test_network['org1.example.com']['peers']['peer0']
        tls_cacerts = peer_config['tls_cacerts']
        endpoint = peer_config['grpc_request_endpoint']

        opts = (('grpc.ssl_target_name_override',
                 peer_config['server_hostname']), )

        peer = create_peer(endpoint=endpoint,
                           tls_cacerts=tls_cacerts,
                           opts=opts)

        tran_prop_req_in = create_tx_prop_req(prop_type=CC_INSTALL,
                                              cc_path=CC_PATH,
                                              cc_type=CC_TYPE_GOLANG,
                                              cc_name=CC_NAME,
                                              cc_version=CC_VERSION)
        args = ['a', '100', 'b', '40']
        tran_prop_req_dep = create_tx_prop_req(prop_type=CC_INSTANTIATE,
                                               cc_type=CC_TYPE_GOLANG,
                                               cc_name=CC_NAME,
                                               cc_version=CC_VERSION,
                                               fcn='init',
                                               args=args)

        org1 = 'org1.example.com'
        crypto = ecies()
        org1_admin = get_peer_org_user(org1, 'Admin', self.client.state_store)
        tx_context_in = create_tx_context(org1_admin, crypto, tran_prop_req_in)

        request = build_channel_request(self.client, self.channel_tx,
                                        self.channel_name)

        res = self.client._create_channel(request)
        q = Queue(1)
        res.subscribe(on_next=lambda x: q.put(x), on_error=lambda x: q.put(x))
        status, _ = q.get(timeout=5)
        if status.status == 200:
            logger.info("create channel successfully")

        time.sleep(5)
        channel = self.client.new_channel(self.channel_name)
        join_req = build_join_channel_req(org1, channel, self.client)
        channel.join_channel(join_req)

        res = self.client.send_install_proposal(tx_context_in, [peer])
        res.subscribe(on_next=lambda x: q.put(x), on_error=lambda x: q.put(x))
        status, _ = q.get(timeout=5)[0][0]
        if status.response.status == 200:
            logger.info("chaincode installed successfully")

        time.sleep(5)
        tx_context_dep = create_tx_context(org1_admin, crypto,
                                           tran_prop_req_dep)
        res = channel.send_instantiate_proposal(tx_context_dep, [peer])
        assert (res)
Exemplo n.º 5
0
    def chaincode_invoke(self, requestor, channel_name, peer_names, args,
                         cc_name, cc_version, cc_type=CC_TYPE_JAVA, timeout=10):
        """
        Invoke chaincode for ledger update

        :param requestor: User role who issue the request
        :param channel_name: the name of the channel to send tx proposal
        :param peer_names: Names of the peers to install
        :param args (list): arguments (keys and values) for initialization
        :param cc_name: chaincode name
        :param cc_version: chaincode version
        :param cc_type: chaincode language
        :param timeout: Timeout to wait
        :return: True or False
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        tran_prop_req = create_tx_prop_req(
            prop_type=CC_INVOKE,
            cc_type=cc_type,
            cc_name=cc_name,
            cc_version=cc_version,
            fcn='invoke',
            args=args
        )

        tx_context = create_tx_context(
            requestor,
            ecies(),
            tran_prop_req
        )

        res = self.get_channel(
            channel_name).send_tx_proposal(tx_context, peers)

        tran_req = utils.build_tx_req(res)
        tx_context_tx = create_tx_context(
            requestor,
            ecies(),
            tran_req
        )

        utils.send_transaction(self.orderers, tran_req, tx_context_tx)

        queue = Queue(1)
        res.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res = queue.get(timeout=timeout)
        _logger.debug(res)
        return res[0][0][0].response
Exemplo n.º 6
0
    def cc_invoke(self, args, cc_name, fcn, cc_version, queryonly=False):
        """
        Invoke a chaincode method.

        Parameters:
        args       JSON RPC serialized data used as the
                   sole parameter to invoke the chaincode
        cc_name    chaincode name
        fcn        chaincode function name to be invoked
        cc_version chaincode version to be used
        queryonly  If the invocation does not result in ledger change,
                   queryonly should be set to True.
                   If the invocation does result in ledger change, it should
                   be set to False.
        """
        if queryonly:
            return self.cc_query(args, cc_name, fcn)

        loop = asyncio.get_event_loop()
        crypto = ecies()

        endorses = self._get_endorsers(queryonly)

        tran_prop_req = create_tx_prop_req(prop_type=CC_INVOKE,
                                           cc_type=CC_TYPE_GOLANG,
                                           cc_name=cc_name,
                                           fcn=fcn,
                                           cc_version=cc_version,
                                           args=args)

        tx_context = create_tx_context(self.user, crypto, tran_prop_req)

        responses, proposal, header = self.channel.send_tx_proposal(
            tx_context, endorses.values())

        res = loop.run_until_complete(asyncio.gather(*responses))

        tran_req = build_tx_req((res, proposal, header))

        tx_context_tx = create_tx_context(self.user, crypto,
                                          TXProposalRequest())

        responses = loop.run_until_complete(
            base.get_stream_result(
                send_transaction(self.client.orderers, tran_req,
                                 tx_context_tx)))

        logger.info('Tx response: {}'.format(responses))
        return responses
    def test_install_chaincode_success(self):
        self.client.state_store = file_key_value_store(self.kv_store_path)

        with open(self.peer0Org1_tls_certs) as f:
            pem = f.read()

        opts = (
            ('grpc.ssl_target_name_override', self.peer0Org1_tls_hostname),)
        peer0_org1 = create_peer(endpoint=self.peer0Org1_req_endpoint,
                                 pem=pem, opts=opts)
        org1_admin = get_peer_org_admin(self.client, 'org1.example.com')

        crypto = ecies()
        tran_prop_req = create_tx_prop_req(CC_INSTALL, CC_PATH, CC_TYPE_GOLANG,
                                           CC_NAME, CC_VERSION)
        tx_context = create_tx_context(org1_admin, crypto, tran_prop_req)

        queue = Queue(1)

        sleep(5)
        response = self.client.send_install_proposal(tx_context, [peer0_org1])

        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res = queue.get(timeout=5)
        proposal_response, _ = res[0][0]
        self.assertEqual(proposal_response.response.status, 200)
Exemplo n.º 8
0
    def query_info(self, requestor, channel_name, peer_names, decode=True):
        """
        Queries information of a channel

        :param requestor: User role who issue the request
        :param channel_name: Name of channel to query
        :param peer_names: Names of the peers to install
        :param deocode: Decode the response payload
        :return: A `BlockchainInfo` or `ProposalResponse`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        responses = channel.query_info(tx_context, peers)

        try:
            if responses[0][0].response and decode:
                chain_info = ledger_pb2.BlockchainInfo()
                chain_info.ParseFromString(responses[0][0].response.payload)
                _logger.debug('response status {}'.format(
                    responses[0][0].response.status))
                return chain_info
            return responses[0][0]

        except Exception:
            _logger.error("Failed to query info: {}", sys.exc_info()[0])
            raise
Exemplo n.º 9
0
    def chaincode_install(self, requestor, peer_names, cc_path, cc_name,
                          cc_version, timeout=5):
        """
        Install chaincode to given peers by requestor role

        :param requestor: User role who issue the request
        :param peer_names: Names of the peers to install
        :param cc_path: chaincode path
        :param cc_name: chaincode name
        :param cc_version: chaincode version
        :param timeout: Timeout to wait
        :return: True or False
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        tran_prop_req = create_tx_prop_req(CC_INSTALL, cc_path, CC_TYPE_GOLANG,
                                           cc_name, cc_version)
        tx_context = create_tx_context(requestor, ecies(), tran_prop_req)

        # sleep(5)
        response = self.send_install_proposal(tx_context, peers)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res = queue.get(timeout=timeout)
        proposal_response, _ = res[0][0]
        return proposal_response.response.status == 200
Exemplo n.º 10
0
    def test_install_chaincode_success(self):
        """
        Test a chaincode installation success.
        :return:
        """

        opts = (('grpc.ssl_target_name_override',
                 self.peer0_org1_tls_hostname), )
        peer0_org1 = create_peer(endpoint=self.peer0_org1_endpoint,
                                 tls_cacerts=self.peer0_org1_tls_certs,
                                 opts=opts)
        org1_admin = get_peer_org_user('org1.example.com', "Admin",
                                       self.client.state_store)

        crypto = ecies()
        tran_prop_req = create_tx_prop_req(CC_INSTALL, CC_PATH, CC_TYPE_GOLANG,
                                           CC_NAME, CC_VERSION)
        tx_context = create_tx_context(org1_admin, crypto, tran_prop_req)

        queue = Queue(1)

        sleep(5)
        response = self.client.send_install_proposal(tx_context, [peer0_org1])

        response.subscribe(on_next=lambda x: queue.put(x),
                           on_error=lambda x: queue.put(x))

        res = queue.get(timeout=5)
        proposal_response, _ = res[0][0]
        self.assertEqual(proposal_response.response.status, 200)
Exemplo n.º 11
0
    def test_query_installed_chaincodes_sucess(self):

        self.invoke_chaincode()

        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())
        response = self.channel.query_info(tx_context, [self.org1_peer])
        self.assertEqual(response[0][0].response.status, 200)
Exemplo n.º 12
0
    def test_query_chain_info(self):
        loop = asyncio.get_event_loop()

        loop.run_until_complete(self.invoke_chaincode())

        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())
        responses, proposal, header = self.channel.query_info(
            tx_context, [self.peer])
        res = loop.run_until_complete(asyncio.gather(*responses))

        self.assertEqual(res[0].response.status, 200)
Exemplo n.º 13
0
    def test_query_transaction_id_success(self):
        tx_id = self.invoke_chaincode()
        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())

        response = self.channel.query_transaction(tx_context, [self.org1_peer],
                                                  tx_id)
        q = Queue(1)
        response.subscribe(on_next=lambda x: q.put(x),
                           on_error=lambda x: q.put(x))
        res = q.get(timeout=5)
        self.assertEqual(res[0][0][0].response.status, 200)
Exemplo n.º 14
0
    def __cc_install(self):
        """Installs chaincode"""

        tran_prop_req_in = create_tx_prop_req(
            prop_type=CC_INSTALL,
            cc_path=CC_PATH,
            cc_type=CC_TYPE_GOLANG,
            cc_name=CC_NAME,
            cc_version=CC_VERSION)
        tx_ctx = create_tx_context(self.ixp_admin, self.crypto,
                                   tran_prop_req_in)
        self.client.send_install_proposal(tx_ctx, self.peers)
Exemplo n.º 15
0
    def query_channels(self, requestor, peer_names, request_channel='mychannel', timeout=10):
        """
        Queries channel name joined by a peer

        :param requestor: User role who issue the request
        :param peer_names: Names of the peers to install
        :param request_channel: Name of the channel that the query sent to
        :return: A `ChannelQueryResponse`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        request = create_tx_prop_req(
            prop_type=CC_QUERY,
            fcn='GetChannels',
            cc_name='cscc',
            cc_type=CC_TYPE_GOLANG,
            args=[]
        )

        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())
        tx_context.tx_prop_req = request

        response = Channel(request_channel, self).send_tx_proposal(
            tx_context, peers)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        try:
            res = queue.get(timeout=timeout)
            _logger.debug(res)
            response = res[0][0][0]
            if response.response:
                query_trans = query_pb2.ChannelQueryResponse()
                query_trans.ParseFromString(res[0][0][0].response.payload)
                for ch in query_trans.channels:
                    _logger.debug('channel id {}'.format(
                        ch.channel_id))
                return query_trans
            return response

        except Exception:
            _logger.error(
                "Failed to query channel: {}", sys.exc_info()[0])
            raise
Exemplo n.º 16
0
    def query_installed_chaincodes(self, requestor, peer_names, channel_name='mychannel', timeout=10):
        """
        Queries installed chaincode, returns all chaincodes installed on a peer

        :param requestor: User role who issue the request
        :param peer_names: Names of the peers to query
        :param channel_name: Name of the channel to send query to
        :return: A `ChaincodeQueryResponse`
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        request = create_tx_prop_req(
            prop_type=CC_QUERY,
            fcn='getinstalledchaincodes',
            cc_name='lscc',
            cc_type=CC_TYPE_GOLANG,
            args=[]
        )

        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())
        tx_context.tx_prop_req = request

        response = Channel(channel_name, self).send_tx_proposal(
            tx_context, peers)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        try:
            res = queue.get(timeout=timeout)
            _logger.debug(res)
            response = res[0][0][0]
            if response.response:
                query_trans = query_pb2.ChaincodeQueryResponse()
                query_trans.ParseFromString(res[0][0][0].response.payload)
                for cc in query_trans.chaincodes:
                    _logger.debug('cc name {}, version {}, path {}'.format(
                                  cc.name, cc.version, cc.path))
                return query_trans
            return response

        except Exception:
            _logger.error(
                "Failed to query installed chaincodes: {}", sys.exc_info()[0])
            raise
Exemplo n.º 17
0
    def test_query_block_success(self):

        block_hash = self.invoke_chaincode()
        sleep(5)
        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())
        response = self.channel.query_block_by_hash(tx_context,
                                                    [self.org1_peer],
                                                    block_hash)
        q = Queue(1)
        response.subscribe(on_next=lambda x: q.put(x),
                           on_error=lambda x: q.put(x))
        res = q.get(timeout=5)
        self.assertEqual(res[0][0][0].response.status, 200)
Exemplo n.º 18
0
    def test_query_transaction_id_success(self, timeout=30):
        loop = asyncio.get_event_loop()

        tx_id = loop.run_until_complete(self.invoke_chaincode())

        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())

        responses, proposal, header = self.channel.query_transaction(
            tx_context, [self.peer], tx_id)

        res = loop.run_until_complete(asyncio.gather(*responses))
        logger.debug('Responses of query transaction:\n {}'.format(res))

        self.assertEqual(res[0].response.status, 200)
Exemplo n.º 19
0
    def test_query_instantiated_chaincodes_sucess(self):

        self.invoke_chaincode()
        sleep(5)

        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())
        response = self.channel.query_instantiated_chaincodes(
            tx_context, [self.org1_peer])

        q = Queue(1)
        response.subscribe(on_next=lambda x: q.put(x),
                           on_error=lambda x: q.put(x))
        res = q.get(timeout=10)
        logger.debug(res)
        self.assertEqual(res[0][0][0].response.status, 200)
Exemplo n.º 20
0
    def test_query_transaction_id_success(self, timeout=30):
        tx_id = self.invoke_chaincode()

        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())

        starttime = int(time.time())
        while int(time.time()) - starttime < timeout:
            responses = self.channel.query_transaction(tx_context,
                                                       [self.org1_peer], tx_id)
            if responses[0][0].response.status == 200:
                break

        logger.debug('Responses of query transaction:\n {}'.format(responses))

        self.assertEqual(responses[0][0].response.status, 200)
Exemplo n.º 21
0
    def query_block_by_txid(self,
                            requestor,
                            channel_name,
                            peer_names,
                            tx_id,
                            timeout=5):
        """
        Queries block by tx id

        :param requestor: User role who issue the request
        :param channel_name: Name of channel to query
        :param peer_names: Names of the peers to install
        :param tx_id: Transaction ID
        :return: A `BlockDecoder`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        response = channel.query_block_by_txid(tx_context, peers, tx_id)

        queue = Queue(1)
        response.subscribe(on_next=lambda x: queue.put(x),
                           on_error=lambda x: queue.put(x))

        try:
            res = queue.get(timeout=timeout)
            _logger.debug(res)
            response = res[0][0][0]
            if response.response:
                _logger.debug('response status {}'.format(
                    response.response.status))
                block = BlockDecoder().decode(response.response.payload)
                _logger.debug('looking at block {}'.format(
                    block['header']['number']))
                return block
            return response

        except Exception:
            _logger.error("Failed to query block: {}", sys.exc_info()[0])
            raise
Exemplo n.º 22
0
    def chaincode_query(self,
                        requestor,
                        channel_name,
                        peer_names,
                        args,
                        cc_name,
                        cc_version,
                        cc_type=CC_TYPE_GOLANG,
                        fcn='query'):
        """
        Query chaincode

        :param requestor: User role who issue the request
        :param channel_name: the name of the channel to send tx proposal
        :param peer_names: Names of the peers to install
        :param args (list): arguments (keys and values) for initialization
        :param cc_name: chaincode name
        :param cc_version: chaincode version
        :param cc_type: chaincode type language
        :param fcn: chaincode function
        :return: True or False
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        tran_prop_req = create_tx_prop_req(prop_type=CC_QUERY,
                                           cc_name=cc_name,
                                           cc_version=cc_version,
                                           cc_type=cc_type,
                                           fcn=fcn,
                                           args=args)

        tx_context = create_tx_context(requestor, ecies(), tran_prop_req)

        res = self.get_channel(channel_name).send_tx_proposal(
            tx_context, peers)

        tran_req = utils.build_tx_req(res)
        res = tran_req.responses[0].response
        if res.status == 200:
            return res.payload.decode('utf-8')

        return res.message
Exemplo n.º 23
0
    def query_instantiated_chaincodes(self,
                                      requestor,
                                      channel_name,
                                      peer_names,
                                      timeout=5):
        """
        Queries instantiated chaincode

        :param requestor: User role who issue the request
        :param channel_name: name of channel to query
        :param peer_names: Names of the peers to query
        :return: A `ChaincodeQueryResponse`
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        response = channel.query_instantiated_chaincodes(tx_context, peers)

        queue = Queue(1)
        response.subscribe(on_next=lambda x: queue.put(x),
                           on_error=lambda x: queue.put(x))

        try:
            res = queue.get(timeout=timeout)
            _logger.debug(res)
            response = res[0][0][0]
            if response.response:
                query_trans = query_pb2.ChaincodeQueryResponse()
                query_trans.ParseFromString(res[0][0][0].response.payload)
                for cc in query_trans.chaincodes:
                    _logger.debug('cc name {}, version {}, path {}'.format(
                        cc.name, cc.version, cc.path))
                return query_trans
            return response

        except Exception:
            _logger.error("Failed to query instantiated chaincodes: {}",
                          sys.exc_info()[0])
            raise
Exemplo n.º 24
0
    def get_channel_config(self,
                           requestor,
                           channel_name,
                           peer_names,
                           decode=True):
        """
        Get configuration block for the channel

        :param requestor: User role who issue the request
        :param channel_name: name of channel to query
        :param peer_names: Names of the peers to query
        :param deocode: Decode the response payload
        :return: A `ChaincodeQueryResponse` or `ProposalResponse`
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        responses = channel.get_channel_config(tx_context, peers)

        try:
            if responses[0][0].response and decode:
                _logger.debug('response status {}'.format(
                    responses[0][0].response.status))
                block = common_pb2.Block()
                block.ParseFromString(responses[0][0].response.payload)
                envelope = common_pb2.Envelope()
                envelope.ParseFromString(block.data.data[0])
                payload = common_pb2.Payload()
                payload.ParseFromString(envelope.payload)
                config_envelope = configtx_pb2.ConfigEnvelope()
                config_envelope.ParseFromString(payload.data)
                return config_envelope

            return responses[0][0]

        except Exception:
            _logger.error("Failed to get channel config block: {}",
                          sys.exc_info()[0])
            raise
Exemplo n.º 25
0
    def test_query_block_success(self):
        loop = asyncio.get_event_loop()

        loop.run_until_complete(self.invoke_chaincode())

        orgs = ["org1.example.com"]
        for org in orgs:
            org_admin = self.client.get_user(org, "Admin")

            channel = self.client.get_channel(self.channel_name)
            tx_context = create_tx_context(org_admin, org_admin.cryptoSuite,
                                           TXProposalRequest())
            responses, p, h = channel.query_block(tx_context, [self.peer], '1')
            res = loop.run_until_complete(asyncio.gather(*responses))

            self.assertTrue(all([x.response.status == 200 for x in res]))

            blocks = [BlockDecoder().decode(v.response.payload) for v in res]
            self.assertEqual(blocks[0]['header']['number'], 1)
Exemplo n.º 26
0
    def query_info(self, requestor, channel_name,
                   peer_names, timeout=10):
        """
        Queries information of a channel

        :param requestor: User role who issue the request
        :param channel_name: Name of channel to query
        :param peer_names: Names of the peers to install
        :return: A `BlockchainInfo`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        response = channel.query_info(tx_context, peers)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        try:
            res = queue.get(timeout=timeout)
            _logger.debug(res)
            response = res[0][0][0]
            if response.response:
                chain_info = ledger_pb2.BlockchainInfo()
                chain_info.ParseFromString(response.response.payload)
                _logger.debug('response status {}'.format(
                    response.response.status))
                return chain_info
            return response

        except Exception:
            _logger.error(
                "Failed to query info: {}", sys.exc_info()[0])
            raise
Exemplo n.º 27
0
    def query_transaction(self, requestor, channel_name,
                          peer_names, tx_id, timeout=5):
        """
        Queries block by number

        :param requestor: User role who issue the request
        :param channel_name: name of channel to query
        :param peer_names: Names of the peers to install
        :param tx_id: The id of the transaction
        :return: A `BlockDecoder`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        response = channel.query_transaction(tx_context, peers, tx_id)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        try:
            res = queue.get(timeout=timeout)
            response = res[0][0][0]
            if response.response:
                logging.debug('response status {}'.format(
                    response.response.status))
                process_trans = BlockDecoder().decode_transaction(
                    response.response.payload)
                return process_trans
            return response

        except Exception:
            logging.error(
                "Failed to query block: {}", sys.exc_info()[0])
            raise
Exemplo n.º 28
0
    async def query(self,
                    requestor,
                    channel_name,
                    peers,
                    args,
                    cc_type=CC_TYPE_GOLANG,
                    fcn='query',
                    transient_map=None):
        """
        Query chaincode

        :param requestor: User role who issue the request
        :param channel_name: the name of the channel to send tx proposal
        :param peers: List of  peer name and/or Peer to install
        :param args (list): arguments (keys and values) for initialization
        :param cc_type: chaincode type language
        :param fcn: chaincode function
        :param transient_map: transient map
        :return: requested value
        """
        target_peers = self._client.get_target_peers(peers)

        tran_prop_req = create_tx_prop_req(prop_type=CC_QUERY,
                                           cc_name=self._name,
                                           cc_type=cc_type,
                                           fcn=fcn,
                                           args=args,
                                           transient_map=transient_map)

        tx_context = create_tx_context(requestor, requestor.cryptoSuite,
                                       tran_prop_req)

        responses, proposal, header = self._client.get_channel(
            channel_name).send_tx_proposal(tx_context, target_peers)
        res = await asyncio.gather(*responses)
        tran_req = utils.build_tx_req((res, proposal, header))

        if not all(
            [x.response.status == SUCCESS_STATUS for x in tran_req.responses]):
            raise Exception(res)

        return res[0].response.payload.decode('utf-8')
Exemplo n.º 29
0
    def query_block(self,
                    requestor,
                    channel_name,
                    peer_names,
                    block_number,
                    decode=True):
        """
        Queries block by number

        :param requestor: User role who issue the request
        :param channel_name: name of channel to query
        :param peer_names: Names of the peers to install
        :param block_number: Number of a block
        :param deocode: Decode the response payload
        :return: A `BlockDecoder` or `ProposalResponse`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        responses = channel.query_block(tx_context, peers, block_number)

        try:
            if responses[0][0].response and decode:
                _logger.debug('response status {}'.format(
                    responses[0][0].response.status))
                block = BlockDecoder().decode(responses[0][0].response.payload)
                _logger.debug('looking at block {}'.format(
                    block['header']['number']))
                return block
            return responses[0][0]

        except Exception:
            _logger.error("Failed to query block: {}", sys.exc_info()[0])
            raise
Exemplo n.º 30
0
    def query_transaction(self,
                          requestor,
                          channel_name,
                          peer_names,
                          tx_id,
                          decode=True):
        """
        Queries block by number

        :param requestor: User role who issue the request
        :param channel_name: name of channel to query
        :param peer_names: Names of the peers to install
        :param tx_id: The id of the transaction
        :param deocode: Decode the response payload
        :return:  A `BlockDecoder` or `ProposalResponse`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        responses = channel.query_transaction(tx_context, peers, tx_id)

        try:
            if responses[0][0].response and decode:
                _logger.debug('response status {}'.format(
                    responses[0][0].response.status))
                process_trans = BlockDecoder().decode_transaction(
                    responses[0][0].response.payload)
                return process_trans

            return responses[0][0]

        except Exception:
            _logger.error("Failed to query block: {}", sys.exc_info()[0])
            raise