コード例 #1
0
def test_token_transfer(client, base_ddo_url, events_object):
    web3 = events_object._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    send_create_update_tx("create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    initial_ddo = get_ddo(client, base_ddo_url, did)
    assert initial_ddo["id"] == did
    assert initial_ddo["nft"]["owner"] == test_account1.address

    nft_contract = web3.eth.contract(
        abi=ERC721Template.abi,
        address=web3.toChecksumAddress(initial_ddo["nftAddress"]),
    )

    web3.eth.default_account = test_account1.address
    txn_hash = nft_contract.functions.safeTransferFrom(test_account1.address,
                                                       test_account2.address,
                                                       1).transact()
    _ = web3.eth.wait_for_transaction_receipt(txn_hash)

    events_object.process_current_blocks()
    updated_ddo = get_ddo(client, base_ddo_url, did)
    assert updated_ddo["id"] == did
    assert updated_ddo["nft"]["owner"] == test_account2.address
コード例 #2
0
def test_token_uri_update(client, base_ddo_url, events_object):
    web3 = events_object._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    send_create_update_tx("create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    initial_ddo = get_ddo(client, base_ddo_url, did)
    assert initial_ddo["id"] == did
    assert initial_ddo["nft"]["tokenURI"] == "http://oceanprotocol.com/nft"

    nft_contract = web3.eth.contract(
        abi=ERC721Template.abi,
        address=web3.toChecksumAddress(initial_ddo["nftAddress"]),
    )

    web3.eth.default_account = test_account1.address
    txn_hash = nft_contract.functions.setTokenURI(
        1, "http://something-else.com").transact()
    _ = web3.eth.wait_for_transaction_receipt(txn_hash)

    events_object.process_current_blocks()
    updated_ddo = get_ddo(client, base_ddo_url, did)
    assert updated_ddo["id"] == did
    assert updated_ddo["nft"]["tokenURI"] == "http://something-else.com"
コード例 #3
0
def test_dispenser_created(events_object, client, base_ddo_url):
    web3 = events_object._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    _, dt_contract, erc20_address = send_create_update_tx(
        "create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    token_contract = web3.eth.contract(
        abi=ERC20Template.abi, address=web3.toChecksumAddress(erc20_address))

    address_file = get_address_file()
    with open(address_file) as f:
        address_json = json.load(f)

    dispenser_address = address_json["development"]["Dispenser"]

    tx = token_contract.functions.createDispenser(
        web3.toChecksumAddress(dispenser_address),
        web3.toWei("1", "ether"),
        web3.toWei("1", "ether"),
        True,
        "0x0000000000000000000000000000000000000000",
    ).transact({"from": test_account1.address})

    _ = web3.eth.wait_for_transaction_receipt(tx)
    events_object.process_current_blocks()

    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["stats"]["price"] == {"value": 0.0}
コード例 #4
0
def test_publish_unallowed_address(client, base_ddo_url, events_object):
    _ddo = new_ddo(test_account3, get_web3(), "dt.0")
    did = _ddo.id
    send_create_update_tx("create", _ddo, bytes([2]), test_account3)
    events_object.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo[
        "error"] == f"Asset DID {did} not found in Elasticsearch."
コード例 #5
0
def test_publish(client, base_ddo_url, events_object):
    _ddo = new_ddo(test_account1, get_web3(), "dt.0")
    did = _ddo.id
    send_create_update_tx("create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["id"] == did
    assert published_ddo["chainId"] == get_web3().eth.chain_id
コード例 #6
0
def test_publish_unallowed_address(client, base_ddo_url, events_object):
    _ddo = new_ddo(test_account3, get_web3(), f'dt.0')
    did = _ddo.id
    ddo_string = json.dumps(dict(_ddo))
    data = Web3.toBytes(text=ddo_string)
    send_create_update_tx('create', did, bytes([0]), data, test_account3)
    events_object.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo == None
コード例 #7
0
def run_test(client, base_ddo_url, events_instance, flags=None, encryption_key=None):
    web3 = get_web3()
    block = web3.eth.blockNumber
    _ddo = new_ddo(test_account1, web3, f'dt.{block}')
    did = _ddo.id
    ddo_string = json.dumps(dict(_ddo))
    data = Web3.toBytes(text=ddo_string)
    _flags = flags or 0
    if flags is not None:
        data = lzma.compress(data)
        # mark bit 1
        _flags = _flags | 1

    if encryption_key is not None:
        # ecies encrypt - bit 2
        _flags = _flags | 2
        key = eth_keys.KeyAPI.PrivateKey(encryption_key)
        data = ecies.encrypt(key.public_key.to_hex(), data)

    send_create_update_tx('create', did, bytes([_flags]), data, test_account1)
    get_event(EVENT_METADATA_CREATED, block, did)
    events_instance.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo['id'] == did

    _ddo['service'][0]['attributes']['main']['name'] = 'Updated ddo by event'
    ddo_string = json.dumps(dict(_ddo))
    data = Web3.toBytes(text=ddo_string)
    if flags is not None:
        data = lzma.compress(data)

    if encryption_key is not None:
        key = eth_keys.KeyAPI.PrivateKey(encryption_key)
        data = ecies.encrypt(key.public_key.to_hex(), data)

    send_create_update_tx('update', did, bytes([_flags]), data, test_account1)
    get_event(EVENT_METADATA_UPDATED, block, did)
    events_instance.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo['id'] == did
    assert published_ddo['service'][0]['attributes']['main']['name'] == 'Updated ddo by event'
コード例 #8
0
def run_test(client, base_ddo_url, events_instance, flags):
    web3 = events_instance._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    _, _, erc20_address = send_create_update_tx("create", _ddo, bytes([flags]),
                                                test_account1)
    events_instance.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["id"] == did
    for service in published_ddo["services"]:
        assert service["datatokenAddress"] == erc20_address
        assert service["name"] in [
            "dataAssetAccess", "dataAssetComputingService"
        ]

    _ddo["metadata"]["name"] = "Updated ddo by event"
    send_create_update_tx("update", _ddo, bytes([flags]), test_account1)
    events_instance.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["id"] == did
    assert published_ddo["metadata"]["name"] == "Updated ddo by event"
コード例 #9
0
def test_purgatory_with_accounts(client, base_ddo_url, events_object, monkeypatch):
    monkeypatch.setenv(
        "ASSET_PURGATORY_URL",
        "https://raw.githubusercontent.com/oceanprotocol/list-purgatory/main/list-assets.json",
    )
    monkeypatch.setenv(
        "ACCOUNT_PURGATORY_URL",
        "https://raw.githubusercontent.com/oceanprotocol/list-purgatory/main/list-accounts.json",
    )
    did = publish_ddo(client, base_ddo_url, events_object)

    purgatory = PurgatoryForTesting(events_object._es_instance)
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["purgatory"]["state"] is False

    acc_id = events_object._es_instance.read(did)["event"]["from"]
    purgatory.current_test_account_list = {(acc_id, "test_reason")}
    purgatory.update_lists()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["purgatory"]["state"] is True

    # remove account from purgatory, but before 1h passed (won't have an effect)
    purgatory.current_test_account_list = set()
    purgatory.update_lists()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["purgatory"]["state"] is True

    # simulate the passage of time (1 hour until next purgatory update)
    in_one_hour = datetime.now() + timedelta(hours=1)
    freezer = freeze_time(in_one_hour)
    freezer.start()

    # this time, removing the account from purgatory will take effect
    purgatory.update_lists()
    freezer.stop()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["purgatory"]["state"] is False
コード例 #10
0
def test_process_fallback(monkeypatch, client, base_ddo_url, events_object):
    config_file = app.config["AQUARIUS_CONFIG_FILE"]
    web3 = setup_web3(config_file)
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id
    send_create_update_tx("create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["id"] == did

    events_object._es_instance.delete(did)

    _ddo["metadata"]["name"] = "Updated ddo by event"
    send_create_update_tx("update", _ddo, bytes(2), test_account1)

    # falls back on the MetadataCreatedProcessor
    # since no es instance means read will throw an Exception
    with patch("aquarius.events.processors.MetadataCreatedProcessor.process"
               ) as mock:
        events_object.process_current_blocks()
        mock.assert_called()
コード例 #11
0
def test_exchange_created(events_object, client, base_ddo_url):
    web3 = events_object._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    _, dt_contract, erc20_address = send_create_update_tx(
        "create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    token_contract = web3.eth.contract(
        abi=ERC20Template.abi, address=web3.toChecksumAddress(erc20_address))

    amount = web3.toWei("100000", "ether")
    rate = web3.toWei("1", "ether")

    address_file = get_address_file()
    with open(address_file) as f:
        address_json = json.load(f)

    fre_address = address_json["development"]["FixedPrice"]

    token_contract.functions.mint(
        web3.toChecksumAddress(test_account3.address),
        amount).transact({"from": test_account1.address})

    ocean_address = web3.toChecksumAddress(
        address_json["development"]["Ocean"])
    tx = token_contract.functions.createFixedRate(
        web3.toChecksumAddress(fre_address),
        [
            ocean_address,
            web3.toChecksumAddress(test_account1.address),
            "0x0000000000000000000000000000000000000000",
            "0x0000000000000000000000000000000000000000",
        ],
        [
            18,
            18,
            rate,
            0,
            0,
        ],
    ).transact({"from": test_account1.address})
    receipt = web3.eth.wait_for_transaction_receipt(tx)
    events_object.process_current_blocks()

    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["stats"]["price"] == {
        "tokenAddress": ocean_address,
        "tokenSymbol": "Ocean",
        "value": 1.0,
    }

    fre = get_fre(web3)
    rate = 2 * rate
    exchange_id = (fre.events.ExchangeCreated().processReceipt(receipt)
                   [0].args.exchangeId)
    tx = fre.functions.setRate(exchange_id,
                               rate).transact({"from": test_account1.address})
    receipt = web3.eth.wait_for_transaction_receipt(tx)
    events_object.process_current_blocks()

    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["stats"]["price"] == {
        "tokenAddress": ocean_address,
        "tokenSymbol": "Ocean",
        "value": 2.0,
    }
コード例 #12
0
def test_trigger_caching(client, base_ddo_url, events_object):
    web3 = events_object._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    txn_receipt, _, erc20_address = send_create_update_tx(
        "create", _ddo, bytes([2]), test_account1)
    tx_id = txn_receipt["transactionHash"].hex()

    with patch("aquarius.app.es_instance.ElasticsearchInstance.get") as mock:
        mock.side_effect = Exception("Boom!")
        response = run_request_get_data(client.post,
                                        "api/aquarius/assets/triggerCaching",
                                        {"transactionId": tx_id})
        assert response[
            "error"] == "Encountered error when triggering caching: Boom!."

    response = run_request_get_data(client.post,
                                    "api/aquarius/assets/triggerCaching",
                                    {"transactionId": tx_id})
    assert response["id"] == did

    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["id"] == did
    for service in published_ddo["services"]:
        assert service["datatokenAddress"] == erc20_address
        assert service["name"] in [
            "dataAssetAccess", "dataAssetComputingService"
        ]

    _ddo["metadata"]["name"] = "Updated ddo by event"
    txn_receipt, dt_contract, _ = send_create_update_tx(
        "update", _ddo, bytes([2]), test_account1)
    tx_id = txn_receipt["transactionHash"].hex()

    response = run_request_get_data(client.post,
                                    "api/aquarius/assets/triggerCaching",
                                    {"transactionId": tx_id})
    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["id"] == did
    assert published_ddo["metadata"]["name"] == "Updated ddo by event"

    assert response["metadata"]["name"] == "Updated ddo by event"

    # index out of range
    response = run_request_get_data(
        client.post,
        "api/aquarius/assets/triggerCaching",
        {
            "transactionId": tx_id,
            "logIndex": 2
        },
    )
    assert response["error"] == "Log index 2 not found"

    # can not find event created, nor event updated
    txn_hash = dt_contract.functions.setTokenURI(
        1, "http://something-else.com").transact()
    txn_receipt = web3.eth.wait_for_transaction_receipt(txn_hash)
    tx_id = txn_receipt["transactionHash"].hex()
    response = run_request_get_data(client.post,
                                    "api/aquarius/assets/triggerCaching",
                                    {"transactionId": tx_id})
    assert response[
        "error"] == "No metadata created/updated event found in tx."
コード例 #13
0
def test_metadata_state_update(client, base_ddo_url, events_object):
    web3 = events_object._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    send_create_update_tx("create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    initial_ddo = get_ddo(client, base_ddo_url, did)
    assert initial_ddo["id"] == did

    # MetadataState updated to other than active should soft delete the ddo from elasticsearch
    send_set_metadata_state_tx(ddo=_ddo,
                               account=test_account1,
                               state=MetadataStates.DEPRECATED)
    events_object.process_current_blocks()
    time.sleep(30)
    published_ddo = get_ddo(client, base_ddo_url, did)
    # Check if asset is soft deleted
    assert "id" not in published_ddo
    assert list(
        published_ddo.keys()) == AquariusCustomDDOFields.get_all_values()
    assert (published_ddo[AquariusCustomDDOFields.EVENT]["tx"] == initial_ddo[
        AquariusCustomDDOFields.EVENT]["tx"])
    assert (published_ddo[AquariusCustomDDOFields.NFT]["state"] ==
            MetadataStates.DEPRECATED)

    # MetadataState updated to active should delegate to MetadataCreated processor
    # and recreate asset
    send_set_metadata_state_tx(ddo=_ddo,
                               account=test_account1,
                               state=MetadataStates.ACTIVE)
    events_object.process_current_blocks()
    time.sleep(30)
    published_ddo = get_ddo(client, base_ddo_url, did)
    # Asset has been recreated
    assert published_ddo["id"] == did
    # The event after recreation is kept as it uses the same original creation event
    assert published_ddo["event"]["tx"] == initial_ddo["event"]["tx"]
    # The NFT state is active
    assert published_ddo[
        AquariusCustomDDOFields.NFT]["state"] == MetadataStates.ACTIVE

    # MetadataState updated to order disabled should leave the contents intact
    # but change the state
    send_set_metadata_state_tx(ddo=_ddo,
                               account=test_account1,
                               state=MetadataStates.ORDERING_DISABLED)
    events_object.process_current_blocks()
    time.sleep(30)
    published_ddo = get_ddo(client, base_ddo_url, did)
    # Asset id and event are untouched
    assert published_ddo["id"] == did
    assert published_ddo["event"]["tx"] == initial_ddo["event"]["tx"]
    # The NFT state is disabled
    assert (published_ddo[AquariusCustomDDOFields.NFT]["state"] ==
            MetadataStates.ORDERING_DISABLED)

    # MetadataState updated to active should delegate to MetadataCreated processor
    # and reactivate the existing asset
    send_set_metadata_state_tx(ddo=_ddo,
                               account=test_account1,
                               state=MetadataStates.ACTIVE)
    events_object.process_current_blocks()
    time.sleep(30)
    published_ddo = get_ddo(client, base_ddo_url, did)
    # Existing asset has been reactivated
    assert published_ddo["id"] == did
    # The event after reactivated is kept as it uses the same original creation event
    assert published_ddo["event"]["tx"] == initial_ddo["event"]["tx"]
    # The NFT state is active
    assert published_ddo[
        AquariusCustomDDOFields.NFT]["state"] == MetadataStates.ACTIVE
コード例 #14
0
def test_order_started(events_object, client, base_ddo_url):
    web3 = events_object._web3  # get_web3()
    block = web3.eth.block_number
    _ddo = new_ddo(test_account1, web3, f"dt.{block}")
    did = _ddo.id

    _, dt_contract, erc20_address = send_create_update_tx(
        "create", _ddo, bytes([2]), test_account1)
    events_object.process_current_blocks()
    token_contract = web3.eth.contract(
        abi=ERC20Template.abi, address=web3.toChecksumAddress(erc20_address))

    token_contract.functions.mint(
        web3.toChecksumAddress(test_account3.address),
        web3.toWei(10, "ether")).transact({"from": test_account1.address})
    # mock provider fees
    provider_wallet = get_aquarius_wallet()
    provider_fee_amount = 0
    provider_data = json.dumps({"timeout": 0}, separators=(",", ":"))
    provider_fee_address = provider_wallet.address
    provider_fee_token = "0x0000000000000000000000000000000000000000"
    message_hash = Web3.solidityKeccak(
        ["bytes", "address", "address", "uint256", "uint256"],
        [
            Web3.toHex(Web3.toBytes(text=provider_data)),
            provider_fee_address,
            provider_fee_token,
            provider_fee_amount,
            0,
        ],
    )
    pk = keys.PrivateKey(provider_wallet.key)
    prefix = "\x19Ethereum Signed Message:\n32"
    signable_hash = Web3.solidityKeccak(
        ["bytes", "bytes"],
        [Web3.toBytes(text=prefix),
         Web3.toBytes(message_hash)])
    signed = keys.ecdsa_sign(message_hash=signable_hash, private_key=pk)

    provider_fee = {
        "providerFeeAddress": web3.toChecksumAddress(provider_fee_address),
        "providerFeeToken": web3.toChecksumAddress(provider_fee_token),
        "providerFeeAmount": provider_fee_amount,
        "providerData": Web3.toHex(Web3.toBytes(text=provider_data)),
        # make it compatible with last openzepellin https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1622
        "v": (signed.v + 27) if signed.v <= 1 else signed.v,
        "r": Web3.toHex(Web3.toBytes(signed.r).rjust(32, b"\0")),
        "s": Web3.toHex(Web3.toBytes(signed.s).rjust(32, b"\0")),
        "validUntil": 0,
    }
    txn = token_contract.functions.startOrder(
        web3.toChecksumAddress(test_account3.address),
        1,
        (
            web3.toChecksumAddress(provider_fee["providerFeeAddress"]),
            web3.toChecksumAddress(provider_fee["providerFeeToken"]),
            provider_fee["providerFeeAmount"],
            provider_fee["v"],
            provider_fee["r"],
            provider_fee["s"],
            provider_fee["validUntil"],
            provider_fee["providerData"],
        ),
        (
            "0x0000000000000000000000000000000000000000",
            "0x0000000000000000000000000000000000000000",
            0,
        ),
    ).transact({"from": test_account3.address})
    web3.eth.wait_for_transaction_receipt(txn)
    events_object.process_current_blocks()

    published_ddo = get_ddo(client, base_ddo_url, did)
    assert published_ddo["stats"]["orders"] == 1