Exemple #1
0
def create_new_offer(bc_interface, bc_contract, energy, price, seller):
    unlock_account(bc_interface.chain, bc_interface.users[seller].address)
    bc_energy = int(energy * BC_NUM_FACTOR)
    tx_hash = bc_contract.functions.offer(bc_energy, int(
        price * BC_NUM_FACTOR)).transact(
            {"from": bc_interface.users[seller].address})
    tx_hash_hex = hex(int.from_bytes(tx_hash, byteorder='big'))
    log.debug(f"tx_hash of New Offer {tx_hash_hex}")

    tx_receipt = bc_interface.chain.eth.waitForTransactionReceipt(tx_hash)
    status = tx_receipt["status"]
    log.debug(f"tx_receipt Status: {status}")
    assert status > 0
    wait_for_node_synchronization(bc_interface)

    def get_offer_id():
        return bc_contract.events.NewOffer().processReceipt(
            tx_receipt)[0]['args']["offerId"]

    wait_until_timeout_blocking(lambda: get_offer_id() is not 0, timeout=20)

    offer_id = get_offer_id()

    log.debug(f"offer_id: {offer_id}")
    assert offer_id is not 0
    return offer_id
 def _wait_and_consume_command_response(self, command_type):
     logging.info(f"Command {command_type} waiting for response...")
     wait_until_timeout_blocking(
         lambda: command_type in self._blocking_command_responses,
         timeout=120)
     command_output = self._blocking_command_responses.pop(command_type)
     logging.info(f"Command {command_type} got response {command_output}")
     return command_output
Exemple #3
0
    def _wait_and_consume_command_response(self, command_type, transaction_id):
        def check_if_command_response_received():
            return any(
                command == command_type and "transaction_id" in data
                and data["transaction_id"] == transaction_id
                for command, data in self._blocking_command_responses.items())

        logging.info(f"Command {command_type} waiting for response...")
        wait_until_timeout_blocking(check_if_command_response_received,
                                    timeout=120)
        command_output = self._blocking_command_responses.pop(command_type)
        logging.info(f"Command {command_type} got response {command_output}")
        return command_output
    def wait_for_command_response(self, command_name, transaction_id):
        def check_if_command_response_received():
            return any(
                "command" in c and c["command"] == command_name and
                "transaction_id" in c and c["transaction_id"] == transaction_id
                for c in self.command_response_buffer)

        logging.info(f"Command {command_name} waiting for response...")
        wait_until_timeout_blocking(check_if_command_response_received,
                                    timeout=120)
        response = next(
            c for c in self.command_response_buffer
            if "command" in c and c["command"] == command_name and
            "transaction_id" in c and c["transaction_id"] == transaction_id)
        self.command_response_buffer.remove(response)
        return response
Exemple #5
0
def wait_for_node_synchronization(bc_interface):
    if ConstSettings.BlockchainSettings.START_LOCAL_CHAIN:
        return

    node_status = bc_interface.chain.eth.syncing
    current_time = time.time()
    time_out = ConstSettings.BlockchainSettings.TIMEOUT
    while not node_status and (time.time() < (current_time + time_out)):
        node_status = bc_interface.chain.eth.syncing
        if time.time() >= (current_time + time_out):
            raise BlockchainTimeoutException(
                f"Syncing to blockchain failed after "
                f"timeout: {time_out} secs")
    highest_block = node_status["highestBlock"]
    wait_until_timeout_blocking(
        lambda: bc_interface.chain.eth.blockNumber >= highest_block)
    time.sleep(0.1)
Exemple #6
0
def trade_offer(bc_interface, bc_contract, offer_id, energy, buyer):
    unlock_account(bc_interface.chain, bc_interface.users[buyer].address)
    trade_energy = int(energy * BC_NUM_FACTOR)
    tx_hash = bc_contract.functions.trade(offer_id, trade_energy). \
        transact({"from": bc_interface.users[buyer].address})
    tx_hash_hex = hex(int.from_bytes(tx_hash, byteorder='big'))
    log.debug(f"tx_hash of Trade {tx_hash_hex}")
    tx_receipt = bc_interface.chain.eth.waitForTransactionReceipt(tx_hash)
    status = tx_receipt["status"]
    log.debug(f"tx_receipt Status: {status}")
    assert status > 0

    wait_for_node_synchronization(bc_interface)
    new_trade_retval = bc_contract.events.NewTrade().processReceipt(tx_receipt)
    if len(new_trade_retval) == 0:
        wait_until_timeout_blocking(lambda: len(bc_contract.events.NewTrade(
        ).processReceipt(tx_receipt)) is not 0,
                                    timeout=20)
        new_trade_retval = bc_contract.events.NewTrade().processReceipt(
            tx_receipt)
        log.debug(f"new_trade_retval after retry: {new_trade_retval}")

    offer_changed_retval = bc_contract.events \
        .OfferChanged() \
        .processReceipt(tx_receipt)

    if len(offer_changed_retval) > 0 and \
            not offer_changed_retval[0]['args']['success']:
        raise InvalidBlockchainOffer(
            f"Invalid blockchain offer changed. Transaction return "
            f"value {offer_changed_retval}")

    if not new_trade_retval[0]['args']['success']:
        raise InvalidBlockchainTrade(
            f"Invalid blockchain trade. Transaction return "
            f"value {new_trade_retval}")

    trade_id = new_trade_retval[0]['args']['tradeId']
    new_offer_id = offer_changed_retval[0]['args']['newOfferId'] \
        if len(offer_changed_retval) > 0 \
        else None
    return trade_id, new_offer_id
Exemple #7
0
    def register(self, is_blocking=False):
        logging.info(
            f"Trying to register to {self.area_id} as client {self.client_id}")
        if self.is_active:
            raise RedisAPIException(
                f'API is already registered to the market.')

        data = {"name": self.client_id, "transaction_id": str(uuid.uuid4())}
        self.redis_db.publish(f'{self.area_id}/register_participant',
                              json.dumps(data))
        self._blocking_command_responses["register"] = data

        if is_blocking:
            try:
                wait_until_timeout_blocking(lambda: self.is_active,
                                            timeout=120)
            except AssertionError:
                raise RedisAPIException(
                    f'API registration process timed out. Server will continue processing your '
                    f'request on the background and will notify you as soon as the registration '
                    f'has been completed.')
Exemple #8
0
    def __init__(self, default_user_balance=10 ** 8):
        if ConstSettings.BlockchainSettings.START_LOCAL_CHAIN:
            self._ganache_process = Popen(['ganache-cli', '-a', '50', '-e', '10000000000'],
                                          close_fds=False, stdout=DEVNULL, stderr=DEVNULL)
            self.chain = Web3(HTTPProvider(ConstSettings.BlockchainSettings.URL))
            log.debug("Launching Ganache Blockchain")

        else:
            self.chain = Web3(HTTPProvider(ConstSettings.BlockchainSettings.URL))
            log.debug("Connected to Remote Blockchain")

            wait_until_timeout_blocking(lambda: self.chain.net.peerCount > 0, timeout=20)
            log.debug(f"Number of Peers: {self.chain.net.peerCount}")

        self.contracts = {}  # type: Dict[str, Contract]
        self.users = BCUsers(self.chain, self.contracts, default_user_balance)
        self.listeners = defaultdict(list)  # type: Dict[str, List[callable]]
        self.init_contract("ClearingToken.sol", "ClearingToken", [10 ** 10,
                                                                  "ClearingToken", 0,
                                                                  "CT"],
                           id_='ClearingToken')
Exemple #9
0
    def init_contract(self, contract_filename: str, contract_name: str,
                      args: list, listeners: Optional[List] = None, id_: str = None):

        log.trace("Initializing contract '%s'", contract_name)
        compiled_sol = compile_source(get_cached_joined_contract_source(contract_filename))
        contract_interface = compiled_sol['<stdin>:' + contract_name]

        contract = self.chain.eth.contract(abi=contract_interface['abi'],
                                           bytecode=contract_interface['bin'])
        unlock_account(self.chain, self.chain.eth.accounts[0])
        tx_hash = contract.constructor(*args).transact({'from': self.chain.eth.accounts[0]})
        wait_until_timeout_blocking(lambda: self.chain.eth.waitForTransactionReceipt(tx_hash).
                                    contractAddress is not None, timeout=20)
        contract_address = self.chain.eth.waitForTransactionReceipt(tx_hash).contractAddress
        contract = self.chain.eth.contract(address=contract_address,
                                           abi=contract_interface['abi'],
                                           ContractFactoryClass=Contract)
        log.debug(f"{contract_name} SmartContract deployed with Address: {contract_address}")
        self.contracts[contract.address] = contract
        if id_:
            self.contracts[id_] = contract
        if listeners:
            self.listeners[contract.address].extend(listeners)
        return contract