Exemplo n.º 1
0
def validate_channels():
    # Check ledger connection for each channel
    for channel_name, channel in settings.LEDGER_CHANNELS.items():
        with get_hfc(channel_name) as (loop, client, user):
            # if channel_name starts with 'solo-' channel name is include channel['restricted']
            # get_hfc will throw if the solo channel has more than 1 member
            pass
Exemplo n.º 2
0
def get_transaction(channel_name: str, tx_id: str) -> Dict:
    with get_hfc(channel_name) as (loop, client, user):
        transaction = loop.run_until_complete(
            client.query_transaction(user,
                                     channel_name, [settings.LEDGER_PEER_NAME],
                                     tx_id=tx_id,
                                     decode=True))
        return transaction
Exemplo n.º 3
0
def get_block(channel_name: str, block_number: int) -> Dict:
    with get_hfc(channel_name) as (loop, client, user):
        block = loop.run_until_complete(
            client.query_block(user,
                               channel_name, [settings.LEDGER_PEER_NAME],
                               str(block_number),
                               decode=True))
        return block
Exemplo n.º 4
0
def get_ledger_height(channel_name: str) -> int:
    """Return the highest block number in the ledger (aka ledger height)"""
    with get_hfc(channel_name) as (loop, client, user):
        info = loop.run_until_complete(
            client.query_info(user,
                              channel_name, [settings.LEDGER_PEER_NAME],
                              decode=True))
        return info.height
Exemplo n.º 5
0
    def listen_to_channel(self, channel_name):
        # We try to connect a client first, if it fails the backend will not start.
        # It prevents potential issues when we launch the channel event hub in a subprocess.
        while True:
            try:
                with get_hfc(channel_name) as (loop, client, user):
                    logger.info(f'Events: Connected to channel {channel_name}.')
            except Exception as e:
                logger.exception(e)
                time.sleep(5)
                logger.error(f'Events: Retry connecting to channel {channel_name}.')
            else:
                break

        p1 = multiprocessing.Process(target=wait, args=[channel_name])
        p1.start()
Exemplo n.º 6
0
def _call_ledger(channel_name, call_type, fcn, args=None, kwargs=None):

    with get_hfc(channel_name) as (loop, client, user):
        if not args:
            args = []
        else:
            args = [json.dumps(args, cls=UUIDEncoder)]

        chaincode_calls = {
            'invoke': client.chaincode_invoke,
            'query': client.chaincode_query,
        }

        all_peers = client._peers.keys()

        peers = {
            'invoke':
            get_invoke_endorsing_peers(current_peer=settings.LEDGER_PEER_NAME,
                                       all_peers=all_peers),
            'query':
            get_query_endorsing_peers(current_peer=settings.LEDGER_PEER_NAME,
                                      all_peers=all_peers),
        }

        params = {
            'requestor': user,
            'channel_name': channel_name,
            'peers': peers[call_type],
            'args': args,
            'cc_name':
            settings.LEDGER_CHANNELS[channel_name]['chaincode']['name'],
            'fcn': fcn
        }

        if kwargs is not None and isinstance(kwargs, dict):
            params.update(kwargs)

        try:
            response = loop.run_until_complete(
                chaincode_calls[call_type](**params))
        except TimeoutError as e:
            raise LedgerTimeout(str(e))
        except Exception as e:
            # TODO add a method to parse properly the base Exception raised by the fabric-sdk-py
            if hasattr(e, 'details') and 'access denied' in e.details():
                raise LedgerForbidden(f'Access denied for {(fcn, args)}')

            if hasattr(
                    e, 'details'
            ) and 'failed to connect to all addresses' in e.details():
                logger.error(
                    f'failed to reach all peers {all_peers}, current_peer is {settings.LEDGER_PEER_NAME}'
                )
                raise LedgerUnavailable(
                    f'Failed to connect to all addresses for {(fcn, args)}')

            for arg in e.args:
                if 'MVCC_READ_CONFLICT' in arg:
                    logger.error(f'MVCC read conflict for {(fcn, args)}')
                    raise LedgerMVCCError(arg) from e

                if 'PHANTOM_READ_CONFLICT' in arg:
                    logger.error(f'PHANTOM read conflict for {(fcn, args)}')
                    raise LedgerPhantomReadConflictError(arg) from e

                if 'ENDORSEMENT_POLICY_FAILURE' in arg:
                    logger.error(
                        f'ENDORSEMENT_POLICY_FAILURE for {(fcn, args)}')
                    raise LedgerEndorsementPolicyFailure(arg) from e

            try:  # get first failed response from list of protobuf ProposalResponse
                response = [r for r in e.args[0]
                            if r.response.status != 200][0].response.message
            except Exception:
                raise LedgerError(str(e))

        # Deserialize the stringified json
        try:
            response = json.loads(response)
        except json.decoder.JSONDecodeError:
            raise LedgerInvalidResponse(response)

        # Raise errors if status is not ok
        raise_for_status(response)

        return response