def get_network_id():
        """
        Return the ethereum network id calling the `web3.version.network` method.

        :return: Network id, int
        """
        return int(Web3Provider.get_web3().version.network)
    def _load(contract_name):
        """Retrieve the contract instance for `contract_name` that represent the smart
        contract in the keeper network.

        :param contract_name: str name of the solidity keeper contract without the network name.
        :return: web3.eth.Contract instance
        """
        assert ContractHandler.artifacts_path is not None, 'artifacts_path should be already set.'
        contract_definition = ContractHandler.get_contract_dict_by_name(
            contract_name, ContractHandler.artifacts_path)
        abi = contract_definition['abi']
        # 用truffle存在一些问题,因此采用了暴力方案
        # address = Web3.toChecksumAddress(contract_definition['address'])
        if contract_name == 'CDTRegistry':
            address = ContractHandler.cdt_registry_address
        else:
            address = ContractHandler.task_market_address
        contract = Web3Provider.get_web3().eth.contract(address=address,
                                                        abi=abi)
        # version = contract_definition['version']
        version = 0
        ContractHandler._contracts[contract_name] = (contract,
                                                     ConciseContract(contract),
                                                     version)
        return ContractHandler._contracts[contract_name]
    def get_tx_receipt(tx_hash):
        """
        Get the receipt of a tx.

        :param tx_hash: hash of the transaction
        :return: Tx receipt
        """
        try:
            Web3Provider.get_web3().eth.waitForTransactionReceipt(tx_hash,
                                                                  timeout=20)
        except Timeout:
            logger.info('Waiting for transaction receipt timed out.')
            return
        except ValueError as e:
            logger.error(f'Waiting for transaction receipt failed: {e}')
            return

        return Web3Provider.get_web3().eth.getTransactionReceipt(tx_hash)
    def get_ether_balance(address):
        """
        Get balance of an ethereum address.

        :param address: address, bytes32
        :return: balance, int
        """
        return Web3Provider.get_web3().eth.getBalance(
            address, block_identifier='latest')
    def unlock_account(account):
        """
        Unlock the account.

        :param account: Account
        :return:
        """
        return Web3Provider.get_web3().personal.unlockAccount(
            account.address, account.password)
    def sign_hash(msg_hash, account):
        """
        This method use `personal_sign`for signing a message. This will always prepend the
        `\x19Ethereum Signed Message:\n32` prefix before signing.

        :param msg_hash:
        :param account: Account
        :return: signature
        """
        wallet = Wallet(Web3Provider.get_web3(), account.key, account.password,
                        account.address)
        s = wallet.sign(msg_hash)
        return s.signature.hex()
    def ec_recover(message, signed_message):
        """
        This method does not prepend the message with the prefix `\x19Ethereum Signed Message:\n32`.
        The caller should add the prefix to the msg/hash before calling this if the signature was
        produced for an ethereum-prefixed message.

        :param message:
        :param signed_message:
        :return:
        """
        w3 = Web3Provider.get_web3()
        v, r, s = split_signature(w3, w3.toBytes(hexstr=signed_message))
        signature_object = SignatureFix(vrs=(v, big_endian_to_int(r),
                                             big_endian_to_int(s)))
        return w3.eth.account.recoverHash(
            message, signature=signature_object.to_hex_v_hacked())
Esempio n. 8
0
def process_tx_receipt(tx_hash, event_instance, event_name, agreement_id=None):
    """
    Wait until the tx receipt is processed.

    :param tx_hash: hash of the transaction
    :param event_instance: instance of ContractEvent
    :param event_name: name of the event to subscribe, str
    :param agreement_id: hex str
    :return:
    """
    if not isinstance(tx_hash, bytes):
        raise TypeError(f'first argument should be bytes type, '
                        f'got type {type(tx_hash)} and value {tx_hash}')
    if not isinstance(event_instance, ContractEvent):
        raise TypeError(f'second argument should be a ContractEvent, '
                        f'got {event_instance} of type {type(event_instance)}')
    web3 = Web3Provider.get_web3()
    try:
        web3.eth.waitForTransactionReceipt(tx_hash, timeout=20)
    except Timeout:
        logger.info(f'Waiting for {event_name} transaction receipt timed out. '
                    f'Cannot verify receipt and event.')
        return False

    receipt = web3.eth.getTransactionReceipt(tx_hash)
    event_logs = event_instance.processReceipt(receipt) if receipt else None
    if event_logs:
        logger.info(
            f'Success: got {event_name} event after fulfilling condition.')
        logger.debug(
            f'Success: got {event_name} event after fulfilling condition. {receipt}, '
            f'::: {event_logs}')
    else:
        logger.debug(
            f'Something is not right, cannot find the {event_name} event after calling the'
            f' fulfillment condition. This is the transaction receipt {receipt}'
        )

    if receipt and receipt.status == 0:
        logger.warning(
            f'Transaction failed: tx_hash {tx_hash.hex()}, tx event {event_name}, receipt '
            f'{receipt}, id {agreement_id}')
        return False

    return True
    def __init__(self, contract_names=None):
        self.network_name = Keeper.get_network_name(Keeper.get_network_id())
        self.accounts = Web3Provider.get_web3().eth.accounts
        self._contract_name_to_instance = {}
        if contract_names:
            for name in contract_names:
                try:
                    contract = GenericContract(name)
                    self._contract_name_to_instance[name] = contract
                    setattr(self, name, contract)
                except (KeyError, Exception):
                    pass

        self.cdt_registry = CDTRegistry.get_instance()
        self.task_market = TaskMarket.get_instance()
        contracts = [self.cdt_registry, self.task_market]

        self._contract_name_to_instance.update(
            {contract.name: contract
             for contract in contracts if contract})
Esempio n. 10
0
        print('Importing environment from .env...')
    for line in open('.env'):
        var = line.strip().split('=')
        if len(var) == 2:
            key, value = var[0].strip(), var[1].strip()
            os.environ[key] = value


if __name__ == "__main__":
    # 合约地址、abi路径设置
    import_env()
    artifacts_path = os.getenv('ARTIFACTS_PATH')
    cdt_registry_address = os.getenv('CDT_REGISTRY_ADDRESS')
    task_market_address = os.getenv('TASK_MARKET_ADDRESS')

    Web3Provider.init_web3('http://localhost:8545')
    ContractHandler.set_artifacts_path(os.path.expanduser(artifacts_path))
    ContractHandler.set_contract_address(cdt_registry_address,
                                         task_market_address)
    keeper = Keeper.get_instance()

    # 通过环境变量获取三个以太坊账户, ganache-cli的第一个账户为合约部署的系统账户
    account1 = get_account(0)
    account2 = get_account(1)
    account3 = get_account(2)
    system_account = account1

    # 下面以两家企业的联合建模为例,第三方科技公司提供模型并发起任务
    # data_provider1在企业1的私域,将数据秘密共享后传给企业1、2的联邦域computa_provider1、2
    ipfs_client = IPFSProvider()
    system_provider = SystemProvider(keeper, system_account)