Ejemplo n.º 1
0
    def handle(self, message: Message, sender: str) -> None:
        """
        Implement the reaction to a message.

        :param message: the message
        :param sender: the sender
        :return: None
        """
        tac_msg = cast(TACMessage, message)
        tac_msg_type = TACMessage.Type(tac_msg.get("type"))
        game = cast(Game, self.context.game)
        logger.debug("[{}]: Handling controller response. type={}".format(
            self.context.agent_name, tac_msg_type))
        try:
            if sender != game.expected_controller_pbk:
                raise ValueError(
                    "The sender of the message is not the controller agent we registered with."
                )

            if tac_msg_type == TACMessage.Type.TAC_ERROR:
                self._on_tac_error(tac_msg, sender)
            elif game.phase.value == Phase.PRE_GAME.value:
                raise ValueError(
                    "We do not expect a controller agent message in the pre game phase."
                )
            elif game.phase.value == Phase.GAME_REGISTRATION.value:
                if tac_msg_type == TACMessage.Type.GAME_DATA:
                    self._on_start(tac_msg, sender)
                elif tac_msg_type == TACMessage.Type.CANCELLED:
                    self._on_cancelled()
            elif game.phase.value == Phase.GAME.value:
                if tac_msg_type == TACMessage.Type.TRANSACTION_CONFIRMATION:
                    self._on_transaction_confirmed(tac_msg, sender)
                elif tac_msg_type == TACMessage.Type.CANCELLED:
                    self._on_cancelled()
                # elif tac_msg_type == TACMessage.Type.STATE_UPDATE:
                #     self._on_state_update(tac_msg, sender)
            elif game.phase.value == Phase.POST_GAME.value:
                raise ValueError(
                    "We do not expect a controller agent message in the post game phase."
                )
        except ValueError as e:
            logger.warning(str(e))
Ejemplo n.º 2
0
    def handle_envelope(self, envelope: Envelope) -> None:
        """
        Implement the reaction to an envelope.

        :param envelope: the envelope
        :return: None
        """
        tac_msg = TACSerializer().decode(envelope.message)
        tac_msg_type = TACMessage.Type(tac_msg.get("type"))
        tac_msg = cast(TACMessage, tac_msg)
        game = cast(Game, self.context.game)
        logger.debug("[{}]: Handling controller response. type={}".format(self.context.agent_name, tac_msg_type))
        try:
            if envelope.sender != game.expected_controller_pbk:
                raise ValueError("The sender of the message is not the controller agent we registered with.")

            if tac_msg_type == TACMessage.Type.TAC_ERROR:
                self._on_tac_error(tac_msg, envelope.sender)
            elif game.game_phase == GamePhase.PRE_GAME:
                raise ValueError("We do not expect a controller agent message in the pre game phase.")
            elif game.game_phase == GamePhase.GAME_SETUP:
                if tac_msg_type == TACMessage.Type.GAME_DATA:
                    self._on_start(tac_msg, envelope.sender)
                elif tac_msg_type == TACMessage.Type.CANCELLED:
                    self._on_cancelled()
            elif game.game_phase == GamePhase.GAME:
                if tac_msg_type == TACMessage.Type.TRANSACTION_CONFIRMATION:
                    self._on_transaction_confirmed(tac_msg, envelope.sender)
                elif tac_msg_type == TACMessage.Type.CANCELLED:
                    self._on_cancelled()
                elif tac_msg_type == TACMessage.Type.STATE_UPDATE:
                    self._on_state_update(tac_msg, envelope.sender)
            elif game.game_phase == GamePhase.POST_GAME:
                raise ValueError("We do not expect a controller agent message in the post game phase.")
        except ValueError as e:
            logger.warning(str(e))
Ejemplo n.º 3
0
    def encode(self, msg: Message) -> bytes:
        """
        Decode the message.

        :param msg: the message object
        :return: the bytes
        """
        tac_type = TACMessage.Type(msg.get("type"))
        tac_container = tac_pb2.TACMessage()

        if tac_type == TACMessage.Type.REGISTER:
            agent_name = msg.get("agent_name")
            tac_msg = tac_pb2.TACAgent.Register()  # type: ignore
            tac_msg.agent_name = agent_name
            tac_container.register.CopyFrom(tac_msg)
        elif tac_type == TACMessage.Type.UNREGISTER:
            tac_msg = tac_pb2.TACAgent.Unregister()  # type: ignore
            tac_container.unregister.CopyFrom(tac_msg)
        elif tac_type == TACMessage.Type.TRANSACTION:
            tac_msg = tac_pb2.TACAgent.Transaction()  # type: ignore
            tac_msg.transaction_id = msg.get("transaction_id")
            tac_msg.counterparty = msg.get("counterparty")
            tac_msg.amount_by_currency.extend(
                _from_dict_to_pairs(msg.get("amount_by_currency")))
            tac_msg.sender_tx_fee = msg.get("sender_tx_fee")
            tac_msg.counterparty_tx_fee = msg.get("counterparty_tx_fee")
            tac_msg.quantities_by_good_pbk.extend(
                _from_dict_to_pairs(msg.get("quantities_by_good_pbk")))
            tac_container.transaction.CopyFrom(tac_msg)
        elif tac_type == TACMessage.Type.GET_STATE_UPDATE:
            tac_msg = tac_pb2.TACAgent.GetStateUpdate()  # type: ignore
            tac_container.get_state_update.CopyFrom(tac_msg)
        elif tac_type == TACMessage.Type.CANCELLED:
            tac_msg = tac_pb2.TACController.Cancelled()  # type: ignore
            tac_container.cancelled.CopyFrom(tac_msg)
        elif tac_type == TACMessage.Type.GAME_DATA:
            tac_msg = tac_pb2.TACController.GameData()  # type: ignore
            tac_msg.amount_by_currency.extend(
                _from_dict_to_pairs(msg.get("amount_by_currency")))
            tac_msg.exchange_params_by_currency.extend(
                _from_dict_to_pairs(msg.get("exchange_params_by_currency")))
            tac_msg.quantities_by_good_pbk.extend(
                _from_dict_to_pairs(msg.get("quantities_by_good_pbk")))
            tac_msg.utility_params_by_good_pbk.extend(
                _from_dict_to_pairs(msg.get("utility_params_by_good_pbk")))
            tac_msg.tx_fee = msg.get("tx_fee")
            tac_msg.agent_pbk_to_name.extend(
                _from_dict_to_pairs(msg.get("agent_pbk_to_name")))
            tac_msg.good_pbk_to_name.extend(
                _from_dict_to_pairs(msg.get("good_pbk_to_name")))
            tac_msg.version_id = msg.get("version_id")
            tac_container.game_data.CopyFrom(tac_msg)
        elif tac_type == TACMessage.Type.TRANSACTION_CONFIRMATION:
            tac_msg = tac_pb2.TACController.TransactionConfirmation(
            )  # type: ignore
            tac_msg.transaction_id = msg.get("transaction_id")
            tac_msg.amount_by_currency.extend(
                _from_dict_to_pairs(msg.get("amount_by_currency")))
            tac_msg.quantities_by_good_pbk.extend(
                _from_dict_to_pairs(msg.get("quantities_by_good_pbk")))
            tac_container.transaction_confirmation.CopyFrom(tac_msg)
        # elif tac_type == TACMessage.Type.STATE_UPDATE:
        #     tac_msg = tac_pb2.TACController.StateUpdate()  # type: ignore
        #     game_data_json = msg.get("game_data")
        #     game_data = tac_pb2.TACController.GameData()  # type: ignore
        #     game_data.amount_by_currency.extend(_from_dict_to_pairs(cast(Dict[str, str], game_data_json["amount_by_currency"])))  # type: ignore
        #     game_data.exchange_params_by_currency.extend(_from_dict_to_pairs(cast(Dict[str, str], game_data_json["exchange_params_by_currency"])))  # type: ignore
        #     game_data.quantities_by_good_pbk.extend(_from_dict_to_pairs(cast(Dict[str, str], game_data_json["quantities_by_good_pbk"])))  # type: ignore
        #     game_data.utility_params_by_good_pbk.extend(_from_dict_to_pairs(cast(Dict[str, str], game_data_json["utility_params_by_good_pbk"])))  # type: ignore
        #     game_data.tx_fee = game_data_json["tx_fee"]  # type: ignore
        #     game_data.agent_pbk_to_name.extend(_from_dict_to_pairs(cast(Dict[str, str], game_data_json["agent_pbk_to_name"])))  # type: ignore
        #     game_data.good_pbk_to_name.extend(_from_dict_to_pairs(cast(Dict[str, str], game_data_json["good_pbk_to_name"])))  # type: ignore

        #     tac_msg.initial_state.CopyFrom(game_data)

        #     transactions = []
        #     msg_transactions = cast(List[Any], msg.get("transactions"))
        #     for t in msg_transactions:
        #         tx = tac_pb2.TACAgent.Transaction()  # type: ignore
        #         tx.transaction_id = t.get("transaction_id")
        #         tx.counterparty = t.get("counterparty")
        #         tx.amount_by_currency.extend(_from_dict_to_pairs(t.get("amount_by_currency")))
        #         tx.sender_tx_fee = t.get("sender_tx_fee")
        #         tx.counterparty_tx_fee = t.get("counterparty_tx_fee")
        #         tx.quantities_by_good_pbk.extend(_from_dict_to_pairs(t.get("quantities_by_good_pbk")))
        #         transactions.append(tx)
        #     tac_msg.txs.extend(transactions)
        #     tac_container.state_update.CopyFrom(tac_msg)
        elif tac_type == TACMessage.Type.TAC_ERROR:
            tac_msg = tac_pb2.TACController.Error()  # type: ignore
            tac_msg.error_code = TACMessage.ErrorCode(
                msg.get("error_code")).value
            if msg.is_set("error_msg"):
                tac_msg.error_msg = msg.get("error_msg")
            if msg.is_set("details"):
                tac_msg.details.update(msg.get("details"))

            tac_container.error.CopyFrom(tac_msg)
        else:
            raise ValueError("Type not recognized: {}.".format(tac_type))

        tac_message_bytes = tac_container.SerializeToString()
        return tac_message_bytes
Ejemplo n.º 4
0
    def decode(self, obj: bytes) -> Message:
        """
        Decode the message.

        :param obj: the bytes object
        :return: the message
        """
        tac_container = tac_pb2.TACMessage()
        tac_container.ParseFromString(obj)

        new_body = {}  # type: Dict[str, Any]
        tac_type = tac_container.WhichOneof("content")

        if tac_type == "register":
            new_body["type"] = TACMessage.Type.REGISTER
            new_body["agent_name"] = tac_container.register.agent_name
        elif tac_type == "unregister":
            new_body["type"] = TACMessage.Type.UNREGISTER
        elif tac_type == "transaction":
            new_body["type"] = TACMessage.Type.TRANSACTION
            new_body[
                "transaction_id"] = tac_container.transaction.transaction_id
            new_body["counterparty"] = tac_container.transaction.counterparty
            new_body["amount_by_currency"] = _from_pairs_to_dict(
                tac_container.transaction.amount_by_currency)
            new_body["sender_tx_fee"] = tac_container.transaction.sender_tx_fee
            new_body[
                "counterparty_tx_fee"] = tac_container.transaction.counterparty_tx_fee
            new_body["quantities_by_good_pbk"] = _from_pairs_to_dict(
                tac_container.transaction.quantities_by_good_pbk)
        elif tac_type == "get_state_update":
            new_body["type"] = TACMessage.Type.GET_STATE_UPDATE
        elif tac_type == "cancelled":
            new_body["type"] = TACMessage.Type.CANCELLED
        elif tac_type == "game_data":
            new_body["type"] = TACMessage.Type.GAME_DATA
            new_body["amount_by_currency"] = _from_pairs_to_dict(
                tac_container.game_data.amount_by_currency)
            new_body["exchange_params_by_currency"] = _from_pairs_to_dict(
                tac_container.game_data.exchange_params_by_currency)
            new_body["quantities_by_good_pbk"] = _from_pairs_to_dict(
                tac_container.game_data.quantities_by_good_pbk)
            new_body["utility_params_by_good_pbk"] = _from_pairs_to_dict(
                tac_container.game_data.utility_params_by_good_pbk)
            new_body["tx_fee"] = tac_container.game_data.tx_fee
            new_body["agent_pbk_to_name"] = _from_pairs_to_dict(
                tac_container.game_data.agent_pbk_to_name)
            new_body["good_pbk_to_name"] = _from_pairs_to_dict(
                tac_container.game_data.good_pbk_to_name)
            new_body["version_id"] = tac_container.game_data.version_id
        elif tac_type == "transaction_confirmation":
            new_body["type"] = TACMessage.Type.TRANSACTION_CONFIRMATION
            new_body[
                "transaction_id"] = tac_container.transaction_confirmation.transaction_id
            new_body["amount_by_currency"] = _from_pairs_to_dict(
                tac_container.transaction_confirmation.amount_by_currency)
            new_body["quantities_by_good_pbk"] = _from_pairs_to_dict(
                tac_container.transaction_confirmation.quantities_by_good_pbk)
        # elif tac_type == "state_update":
        #     new_body["type"] = TACMessage.Type.STATE_UPDATE
        #     game_data = dict(
        #         amount_by_currency=_from_pairs_to_dict(tac_container.state_update.game_data.amount_by_currency),
        #         exchange_params_by_currency=_from_pairs_to_dict(tac_container.state_update.game_data.exchange_params_by_currency),
        #         quantities_by_good_pbk=_from_pairs_to_dict(tac_container.state_update.game_data.quantities_by_good_pbk),
        #         utility_params_by_good_pbk=_from_pairs_to_dict(tac_container.state_update.game_data.utility_params_by_good_pbk),
        #         tx_fee=tac_container.state_update.game_data.tx_fee,
        #         agent_pbk_to_name=_from_pairs_to_dict(tac_container.state_update.game_data.agent_pbk_to_name),
        #         good_pbk_to_name=_from_pairs_to_dict(tac_container.state_update.game_data.good_pbk_to_name),
        #         version_id=tac_container.state_update.game_data.version_id
        #     )
        #     new_body["game_data"] = game_data
        #     transactions = []
        #     for transaction in tac_container.state_update.transactions:
        #         tx_json = dict(
        #             transaction_id=transaction.transaction_id,
        #             counterparty=transaction.counterparty,
        #             amount_by_currency=_from_pairs_to_dict(transaction.amount_by_currency),
        #             sender_tx_fee=transaction.sender_tx_fee,
        #             counterparty_tx_fee=transaction.counterparty_tx_fee,
        #             quantities_by_good_pbk=_from_pairs_to_dict(transaction.quantities_by_good_pbk),
        #         )
        #         transactions.append(tx_json)
        #     new_body["transactions"] = transactions
        elif tac_type == "error":
            new_body["type"] = TACMessage.Type.TAC_ERROR
            new_body["error_code"] = TACMessage.ErrorCode(
                tac_container.error.error_code)
            if tac_container.error.error_msg:
                new_body["error_msg"] = tac_container.error.error_msg
            if tac_container.error.details:
                new_body["details"] = dict(tac_container.error.details)
        else:
            raise ValueError("Type not recognized.")

        tac_type = TACMessage.Type(new_body["type"])
        new_body["type"] = tac_type
        tac_message = TACMessage(tac_type=tac_type, body=new_body)
        return tac_message
Ejemplo n.º 5
0
    def decode(self, obj: bytes) -> Message:
        """
        Decode the message.

        :param obj: the bytes object
        :return: the message
        """
        tac_container = tac_pb2.TACMessage()
        tac_container.ParseFromString(obj)

        new_body = {}  # type: Dict[str, Any]
        tac_type = tac_container.WhichOneof("content")

        if tac_type == "register":
            new_body["type"] = TACMessage.Type.REGISTER
            new_body["agent_name"] = tac_container.register.agent_name
        elif tac_type == "unregister":
            new_body["type"] = TACMessage.Type.UNREGISTER
        elif tac_type == "transaction":
            new_body["type"] = TACMessage.Type.TRANSACTION
            new_body[
                "transaction_id"] = tac_container.transaction.transaction_id
            new_body[
                "is_sender_buyer"] = tac_container.transaction.is_sender_buyer
            new_body["counterparty"] = tac_container.transaction.counterparty
            new_body["amount"] = tac_container.transaction.amount
            new_body["quantities_by_good_pbk"] = _from_pairs_to_dict(
                tac_container.transaction.quantities)
        elif tac_type == "get_state_update":
            new_body["type"] = TACMessage.Type.GET_STATE_UPDATE
        elif tac_type == "cancelled":
            new_body["type"] = TACMessage.Type.CANCELLED
        elif tac_type == "game_data":
            new_body["type"] = TACMessage.Type.GAME_DATA
            new_body["money"] = tac_container.game_data.money
            new_body["endowment"] = list(tac_container.game_data.endowment)
            new_body["utility_params"] = list(
                tac_container.game_data.utility_params)
            new_body["nb_agents"] = tac_container.game_data.nb_agents
            new_body["nb_goods"] = tac_container.game_data.nb_goods
            new_body["tx_fee"] = tac_container.game_data.tx_fee
            new_body["agent_pbk_to_name"] = _from_pairs_to_dict(
                tac_container.game_data.agent_pbk_to_name)
            new_body["good_pbk_to_name"] = _from_pairs_to_dict(
                tac_container.game_data.good_pbk_to_name)
        elif tac_type == "transaction_confirmation":
            new_body["type"] = TACMessage.Type.TRANSACTION_CONFIRMATION
            new_body[
                "transaction_id"] = tac_container.transaction_confirmation.transaction_id
        elif tac_type == "state_update":
            new_body["type"] = TACMessage.Type.STATE_UPDATE
            game_data = dict(
                money=tac_container.state_update.initial_state.money,
                endowment=tac_container.state_update.initial_state.endowment,
                utility_params=tac_container.state_update.initial_state.
                utility_params,
                nb_agents=tac_container.state_update.initial_state.nb_agents,
                nb_goods=tac_container.state_update.initial_state.nb_goods,
                tx_fee=tac_container.state_update.initial_state.tx_fee,
                agent_pbk_to_name=_from_pairs_to_dict(
                    tac_container.state_update.initial_state.agent_pbk_to_name
                ),
                good_pbk_to_name=_from_pairs_to_dict(
                    tac_container.state_update.initial_state.good_pbk_to_name),
            )
            new_body["initial_state"] = game_data
            transactions = []
            for t in tac_container.state_update.txs:
                tx_json = dict(
                    transaction_id=t.transaction_id,
                    is_sender_buyer=t.is_sender_buyer,
                    counterparty=t.counterparty,
                    amount=t.amount,
                    quantities_by_good_pbk=_from_pairs_to_dict(t.quantities),
                )
                transactions.append(tx_json)
            new_body["transactions"] = transactions
        elif tac_type == "error":
            new_body["type"] = TACMessage.Type.TAC_ERROR
            new_body["error_code"] = TACMessage.ErrorCode(
                tac_container.error.error_code)
            if tac_container.error.error_msg:
                new_body["error_msg"] = tac_container.error.error_msg
            if tac_container.error.details:
                new_body["details"] = dict(tac_container.error.details)
        else:
            raise ValueError("Type not recognized.")

        tac_type = TACMessage.Type(new_body["type"])
        new_body["type"] = tac_type
        tac_message = TACMessage(tac_type=tac_type, body=new_body)
        return tac_message