Ejemplo n.º 1
0
    def get_contract_dict_by_name(contract_name, artifacts_path):
        """
        Retrieve the Contract instance for a given contract name.

        :param contract_name: str
        :param artifacts_path: str the path to keeper contracts artifacts (`abi` .json files)
        :return: the smart contract's definition from the json abi file, dict
        """

        network_name = Keeper.get_network_name(Keeper.get_network_id()).lower()

        # file_name = '{}.{}.json'.format(contract_name, network_name)
        # path = os.path.join(keeper.artifacts_path, file_name)
        path = ContractHandler._get_contract_file_path(artifacts_path,
                                                       contract_name,
                                                       network_name,
                                                       artifacts_path)
        if not (path and os.path.exists(path)):
            path = ContractHandler._get_contract_file_path(
                artifacts_path, contract_name, network_name.lower(),
                artifacts_path)

        if not (path and os.path.exists(path)):
            path = ContractHandler._get_contract_file_path(
                artifacts_path, contract_name, Keeper.DEFAULT_NETWORK_NAME,
                artifacts_path)

        if not (path and os.path.exists(path)):
            raise FileNotFoundError(f'Keeper contract {contract_name} file '
                                    f'not found in {artifacts_path} '
                                    f'using network name {network_name}')

        with open(path) as f:
            contract_dict = json.loads(f.read())
            return contract_dict
Ejemplo n.º 2
0
def test_ec_recover():
    test_values = [
        ('0xe2DD09d719Da89e5a3D0F2549c7E24566e947260',
         'c80996119e884cb38599bcd96a22ad3eea3a4734bcfb47959a5d41ecdcbdfe67',
         '0xa50427a9d5beccdea3eeabecfc1014096b35cd05965e772e8ea32477d2f217'
         'c30d0ec5dbf6b14de1d6eeff45011d17490fe5126576b20d2cbada828cb068c9f801'
         ),
        ('0x00Bd138aBD70e2F00903268F3Db08f2D25677C9e',
         'd77c3a84cafe4cb8bc28bf41a99c63fd530c10da33a54acf94e8d1369d09fbb2',
         '0x9076b561e554cf657af333d9680ba118d556c5b697622636bce4b02f4d5632'
         '5a0ea6a474ca85291252c8c1b8637174ee32072bef357bb0c21b0db4c25b379e781b'
         ),
        ('0xe2DD09d719Da89e5a3D0F2549c7E24566e947260',
         '8d5c1065a9c74da59fbb9e41d1f196e40517e92d81b14c3a8143d6887f3f4438',
         '0x662f6cffd96ada4b6ce5497d444c92126bd053ab131915332edf0dbba716ba'
         '82662275670c95eb2a4d65245cac70313c25e34f594d7c0fbca5232c3d5701a57e00'
         )
    ]

    for expected_address, document_id, signed_document_id in test_values:
        rec_address = Keeper.get_instance().ec_recover(document_id,
                                                       signed_document_id)
        if expected_address.lower() == rec_address.lower():
            msg_hsh = prepare_prefixed_hash(document_id)
            rec_address = Keeper.get_instance().ec_recover(
                msg_hsh, signed_document_id)
            assert expected_address.lower() == rec_address.lower()
Ejemplo n.º 3
0
    def verify_contracts():
        """
        Verify that the contracts are deployed correctly in the network.

        :raise Exception: raise exception if the contracts are not deployed correctly.
        """
        artifacts_path = Keeper.get_instance().artifacts_path
        logger.info(
            f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}')

        if os.environ.get('KEEPER_NETWORK_NAME'):
            logger.warning(
                f'The `KEEPER_NETWORK_NAME` env var is set to '
                f'{os.environ.get("KEEPER_NETWORK_NAME")}. '
                f'This enables the user to override the method of how the network name '
                f'is inferred from network id.')

        # try to find contract with this network name
        contract_name = Diagnostics.TEST_CONTRACT_NAME
        network_id = Keeper.get_network_id()
        network_name = Keeper.get_network_name(network_id)
        logger.info(f'Using keeper contracts from network {network_name}, '
                    f'network id is {network_id}')
        logger.info(
            f'Looking for keeper contracts ending with ".{network_name}.json", '
            f'e.g. "{contract_name}.{network_name}.json".')
        existing_contract_names = os.listdir(artifacts_path)
        try:
            ContractHandler.get(contract_name)
        except Exception as e:
            logger.error(e)
            logger.error(
                f'Cannot find the keeper contracts. \n'
                f'Current network id is {network_id} and network name is {network_name}.'
                f'Expected to find contracts ending with ".{network_name}.json",'
                f' e.g. "{contract_name}.{network_name}.json"')
            raise ContractsNotFound(
                f'Keeper contracts for keeper network {network_name} were not found '
                f'in {artifacts_path}. \n'
                f'Found the following contracts: \n\t{existing_contract_names}'
            )

        keeper = Keeper.get_instance()
        contracts = [
            keeper.token, keeper.did_registry, keeper.agreement_manager,
            keeper.template_manager, keeper.condition_manager,
            keeper.access_condition, keeper.sign_condition,
            keeper.lock_payment_condition, keeper.access_template,
            keeper.escrow_payment_condition, keeper.hash_lock_condition
        ]
        addresses = '\n'.join([f'\t{c.name}: {c.address}' for c in contracts])
        logging.info('Finished loading keeper contracts:\n' '%s', addresses)
Ejemplo n.º 4
0
def test_load_external_contract(external_contract):
    address, abi, name = external_contract
    keeper = Keeper.get_instance(external_contracts=[external_contract])

    contract = keeper.get_contract(name)
    assert contract is not None
    assert contract.address == address
    assert contract.CONTRACT_NAME == name
Ejemplo n.º 5
0
def test_nft_approval():
    did_registry = DIDRegistry.get_instance()
    w3 = Web3
    keeper = Keeper(ContractHandler.artifacts_path)

    assert did_registry.is_nft_approved_for_all(w3.toChecksumAddress('068ed00cf0441e4829d9784fcbe7b9e26d4bd8d0'),
                                                keeper.transfer_nft_condition.address) is True

    assert did_registry.is_nft_approved_for_all(w3.toChecksumAddress('068ed00cf0441e4829d9784fcbe7b9e26d4bd8d0'),
                                                keeper.did_sales_template.address) is False
Ejemplo n.º 6
0
def test_sign_and_recover(web3_instance):
    w3 = web3_instance
    account = get_publisher_account()
    msg = 'testing-signature-and-recovery-of-signer-address'
    msg_hash = w3.keccak(text=msg)
    signature = Keeper.sign_hash(msg_hash, account)
    address = w3.toChecksumAddress(Keeper.ec_recover(msg_hash, signature))
    assert address == account.address

    # Signature created on msg with the ethereum prefix. `web3.eth.account.recoverHash` does NOT
    # add any prefixes to the message, so we have to add the prefix before the call.
    address = w3.eth.account.recoverHash(msg_hash, signature=signature)
    assert address == account.address

    # Now do the opposite, sign with eth.account.sign_hash() (using prefixed msg hash),
    # then recover address with Keeper.ec_recover() on the msg hash with no prefix.
    with open(get_resource_path('data', 'publisher_key_file.json')) as kf:
        key = kf.read()
    prvkey = w3.eth.account.decrypt(key, account.password)
    account_sig_prefixed = add_0x_prefix(
        w3.eth.account.signHash(msg_hash, prvkey)['signature'].hex())
    assert Keeper.ec_recover(
        msg_hash, account_sig_prefixed).lower() == account.address.lower()

    # Test specific case where message is signed by some Wallet web3 such as Metamask or
    # burner wallet. Such signature uses the `web3.personal` `sign` method which adds
    # `Ethereum Signed Message` prefix in a generic way, see `add_ethereum_prefix_and_hash_msg` for details.
    sig = '0xa9e78d2c088c0b17a8c35b69e0dfa774692ccabed570e40502795bd41f561cf7677ed02bf4ee7967a55979d585bbf203b4a490e1d747e5a4d60a50859d816ac51b'
    publisher_address = '0x903322C7E45A60d7c8C3EA236c5beA9Af86310c7'
    doc_id = '028faa498d154388a89dc0dea908a4e27700920217a44abe8f1cdd64953125b8'
    prefixed_hash = add_ethereum_prefix_and_hash_msg(doc_id)
    recovered_address = w3.eth.account.recoverHash(prefixed_hash,
                                                   signature=sig)
    assert recovered_address == publisher_address
    recovered_address = Keeper.ec_recover(prefixed_hash, sig)
    assert recovered_address == publisher_address

    recovered_address = Keeper.personal_ec_recover(doc_id, sig)
    assert recovered_address == publisher_address
Ejemplo n.º 7
0
def test_create_ddo(metadata):
    pub_acc = get_publisher_account()
    ddo = DDO()
    ddo.add_service(ServiceTypes.METADATA,
                    'http://mymetadata.com',
                    values=dict({"attributes": metadata}),
                    index='0')
    checksums = dict()
    for service in ddo.services:
        checksums[str(service.index)] = checksum(service.main)
    ddo.add_proof(checksums, pub_acc)
    did = ddo.assign_did(DID.encoded_did(ddo.proof['checksum']))
    ddo.proof['signatureValue'] = Keeper.sign_hash(did_to_id_bytes(did),
                                                   pub_acc)
    ddo.add_public_key(did, pub_acc.address)
    ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA)
Ejemplo n.º 8
0
def test_get_network_name():
    name = Keeper.get_network_name(Keeper.get_network_id())
    assert name in Keeper._network_name_map.values()
    os.environ['KEEPER_NETWORK_NAME'] = 'yellow'
    assert 'KEEPER_NETWORK_NAME' in os.environ
    name = Keeper.get_network_name(Keeper.get_network_id())
    assert name == 'yellow'
    del os.environ['KEEPER_NETWORK_NAME']

    assert Keeper.get_network_name(1) == Keeper._network_name_map.get(1)
    assert Keeper.get_network_name(2) == Keeper._network_name_map.get(2)
    assert Keeper.get_network_name(3) == Keeper._network_name_map.get(3)
    assert Keeper.get_network_name(4) == Keeper._network_name_map.get(4)
    assert Keeper.get_network_name(42) == Keeper._network_name_map.get(42)
    assert Keeper.get_network_name(77) == Keeper._network_name_map.get(77)
    assert Keeper.get_network_name(99) == Keeper._network_name_map.get(99)
    assert Keeper.get_network_name(137) == Keeper._network_name_map.get(137)
    assert Keeper.get_network_name(8996) == Keeper._network_name_map.get(8996)
    assert Keeper.get_network_name(8997) == Keeper._network_name_map.get(8997)
    assert Keeper.get_network_name(42220) == Keeper._network_name_map.get(
        42220)
    assert Keeper.get_network_name(44787) == Keeper._network_name_map.get(
        44787)
    assert Keeper.get_network_name(62320) == Keeper._network_name_map.get(
        62320)
    assert Keeper.get_network_name(80001) == Keeper._network_name_map.get(
        80001)
    assert Keeper.get_network_name(1313161554) == Keeper._network_name_map.get(
        1313161554)
    assert Keeper.get_network_name(1313161555) == Keeper._network_name_map.get(
        1313161555)
    assert Keeper.get_network_name(1313161556) == Keeper._network_name_map.get(
        1313161556)
    assert Keeper.get_network_name(0) == 'development'
Ejemplo n.º 9
0
def test_get_network_id():
    network_id = Keeper.get_network_id()
    assert isinstance(network_id, int)
    assert network_id in Keeper._network_name_map
Ejemplo n.º 10
0
def test_artifacts_path():
    artifacts_path = '/some/other/path'
    keeper = Keeper.get_instance(artifacts_path)
    assert keeper.artifacts_path == artifacts_path
Ejemplo n.º 11
0
def test_keeper_instance():
    keeper = Keeper(ContractHandler.artifacts_path)
    assert keeper
    assert isinstance(keeper.get_instance(), Keeper)
Ejemplo n.º 12
0
def keeper():
    return Keeper.get_instance()
Ejemplo n.º 13
0
def init_ocn_tokens(ocn, account, amount=100):
    ocn.accounts.request_tokens(account, amount)
    Keeper.get_instance().token.token_approve(
        Keeper.get_instance().dispenser.address, amount, account)
Ejemplo n.º 14
0
def get_network_name():
    return Keeper.get_instance().get_network_name(
        Keeper.get_instance().get_network_id())
Ejemplo n.º 15
0
def setup_keeper():
    Web3Provider._web3 = Web3(CustomHTTPProvider(get_keeper_url()))
    ContractHandler.artifacts_path = os.path.expanduser(
        '~/.nevermined/nevermined-contracts/artifacts')
    Keeper.get_instance(artifacts_path=ContractHandler.artifacts_path)
Ejemplo n.º 16
0
def keeper_instance():
    # Init web3 before fetching keeper instance.
    web3()
    external_contracts = get_config().external_contracts
    return Keeper.get_instance(external_contracts=external_contracts)