Exemplo n.º 1
0
def test_computational_refund():
    job = Job()
    provider = accounts[0]
    requester = accounts[1]
    register_provider(100)
    register_requester(requester)
    job.code_hashes = [
        b"9b3e9babb65d9c1aceea8d606fc55403",
        b"9a4c0c1c9aadb203daf9367bd4df930b"
    ]
    job.cores = [1]
    job.run_time = [5]
    job.data_transfer_ins = [1, 1]
    job.data_transfer_out = 1
    job.storage_ids = [StorageID.EUDAT.value, StorageID.EUDAT.value]
    job.cache_types = [CacheType.PUBLIC.value, CacheType.PUBLIC.value]
    job.storage_hours = [0, 0]
    job.data_prices_set_block_numbers = [0, 0]
    job_price, _cost = job.cost(provider, requester)
    provider_price_block_number = ebb.getProviderSetBlockNumbers(
        accounts[0])[-1]
    args = [
        provider,
        provider_price_block_number,
        job.storage_ids,
        job.cache_types,
        job.data_prices_set_block_numbers,
        job.cores,
        job.run_time,
        job.data_transfer_out,
    ]
    tx = ebb.submitJob(
        job.code_hashes[0],
        job.data_transfer_ins,
        args,
        job.storage_hours,
        job.code_hashes,
        {
            "from": requester,
            "value": web3.toWei(job_price, "wei")
        },
    )
    index = 0
    job_id = 0
    start_time = 1579524978
    tx = ebb.setJobStatusRunning(job.code_hashes[0], index, job_id, start_time,
                                 {"from": accounts[0]})
    rpc.sleep(60)
    mine(5)
    args = [index, job_id, 1579524998, 2, 0, job.cores, [5], True]
    run_time = 1
    tx = ebb.processPayment(job.code_hashes[0], args, run_time, zero_bytes32,
                            {"from": accounts[0]})
    received_sum = tx.events["LogProcessPayment"]["receivedWei"]
    refunded_sum = tx.events["LogProcessPayment"]["refundedWei"]
    log(f"{received_sum} {refunded_sum}")
    assert received_sum + refunded_sum == 505
    assert received_sum == 104 and refunded_sum == 401
    withdraw(accounts[0], received_sum)
    withdraw(requester, refunded_sum)
Exemplo n.º 2
0
def submit_receipt(index,
                   cores,
                   start_time,
                   completion_time,
                   elapsed_time,
                   is_print=True):
    text = f"{start_time},{completion_time}"
    log(f"==> {br(text)} cores={cores}")
    job = Job()
    job.code_hashes = [b"8b3e98abb65d0c1aceea8d606fc55403"]
    job.key = job.code_hashes[0]
    job.index = index
    job._id = 0
    job.cores = cores
    job.run_time = [1]
    job.data_transfer_ins = [1]
    job.data_transfer_out = 1
    job.storage_ids = [StorageID.EUDAT.value]
    job.cache_types = [CacheType.PUBLIC.value]
    job.storage_hours = [0]
    job.data_prices_set_block_numbers = [0]
    job_price, _cost = job.cost(provider, requester)
    provider_price_block_number = ebb.getProviderSetBlockNumbers(provider)[-1]
    args = [
        provider,
        provider_price_block_number,
        job.storage_ids,
        job.cache_types,
        job.data_prices_set_block_numbers,
        job.cores,
        job.run_time,
        job.data_transfer_out,
    ]
    tx = ebb.submitJob(
        job.key,
        job.data_transfer_ins,
        args,
        job.storage_hours,
        job.code_hashes,
        {
            "from": requester,
            "value": web3.toWei(job_price, "wei")
        },
    )

    tx = ebb.setJobStatusRunning(job.key, job.index, job._id, start_time,
                                 {"from": provider})
    rpc.sleep(60)

    mine(5)
    data_transfer_in = 0
    data_transfer_out = 0

    args = [
        job.index, job._id, completion_time, data_transfer_in,
        data_transfer_out, job.cores, [1], True
    ]
    tx = ebb.processPayment(job.key, args, elapsed_time, "",
                            {"from": provider})
    if is_print:
        log(f"==> process_payment received_gas_used={tx.__dict__['gas_used']}")
    # received_sum = tx.events["LogProcessPayment"]["receivedWei"]
    # refunded_sum = tx.events["LogProcessPayment"]["refundedWei"]
    # withdraw(provider, received_sum)
    # withdraw(requester, refunded_sum)
    check_list(is_print)
    if is_print:
        console_ruler(character="-=")

    return tx
Exemplo n.º 3
0
def test_workflow():
    job = Job()
    provider = accounts[0]
    requester = accounts[1]
    register_provider()
    register_requester(requester)
    job_key = "QmQv4AAL8DZNxZeK3jfJGJi63v1msLMZGan7vSsCDXzZud"
    code_hash = ipfs_to_bytes32(job_key)
    with brownie.reverts():
        ebb.updataDataPrice(code_hash, 20, 100, {"from": provider})

    ebb.registerData(code_hash, 20, cfg.BLOCK_DURATION_1_HOUR,
                     {"from": provider})
    ebb.removeRegisteredData(
        code_hash,
        {"from": provider})  # should submitJob fail if it is not removed

    code_hash1 = "0x68b8d8218e730fc2957bcb12119cb204"
    # "web3.toBytes(hexstr=ipfs_to_bytes32("QmWmyoMoctfbAaiEs2G46gpeUmhqFRDW6KWo64y5r581Ve"))
    ebb.registerData(code_hash1, 20, cfg.BLOCK_DURATION_1_HOUR,
                     {"from": provider})
    mine(6)

    with brownie.reverts():
        ebb.registerData(code_hash1, 20, 1000, {"from": provider})

    ebb.updataDataPrice(code_hash1, 250, cfg.BLOCK_DURATION_1_HOUR + 1,
                        {"from": provider})

    data_block_numbers = ebb.getRegisteredDataBlockNumbers(
        provider, code_hash1)
    log(f"get_registered_data_block_numbers={data_block_numbers[1]}", "bold")
    get_block_number()
    data_prices = ebb.getRegisteredDataPrice(provider, code_hash1, 0)
    log(f"register_data_price={data_prices}", "bold")
    assert data_prices[0] == 20

    res = ebb.getRegisteredDataPrice(provider, code_hash1,
                                     data_block_numbers[1])
    log(f"register_data_price={res}", "bold")
    assert res[0] == 250
    mine(cfg.BLOCK_DURATION_1_HOUR - 9)

    res = ebb.getRegisteredDataPrice(provider, code_hash1, 0)
    log(f"register_data_price={res}", "bold")
    assert res[0] == 20
    mine(1)

    res = ebb.getRegisteredDataPrice(provider, code_hash1, 0)
    log(f"register_data_price={res}", "bold")
    assert res[0] == 250

    job.code_hashes = [code_hash,
                       code_hash1]  # Hashed of the data file in array
    job.storage_hours = [0, 0]
    job.data_transfer_ins = [100, 0]
    job.data_transfer_out = 100

    # job.data_prices_set_block_numbers = [0, 253]  # TODO: check this ex 253 exists or not
    job.data_prices_set_block_numbers = [
        0, data_block_numbers[1]
    ]  # TODO: check this ex 253 exists or not
    check_price_keys(job.data_prices_set_block_numbers, provider, code_hash1)
    job.cores = [2, 4, 2]
    job.run_time = [10, 15, 20]
    job.storage_ids = [StorageID.IPFS.value, StorageID.NONE.value]
    job.cache_types = [CacheType.PUBLIC.value, CacheType.PUBLIC.value]
    args = [
        provider,
        ebb.getProviderSetBlockNumbers(accounts[0])[-1],
        job.storage_ids,
        job.cache_types,
        job.data_prices_set_block_numbers,
        job.cores,
        job.run_time,
        job.data_transfer_out,
    ]

    job_price, _cost = job.cost(provider, requester)
    tx = ebb.submitJob(  # first submit
        job_key,
        job.data_transfer_ins,
        args,
        job.storage_hours,
        job.code_hashes,
        {
            "from": requester,
            "value": web3.toWei(job_price, "wei")
        },
    )
    for idx in range(0, 3):
        log(ebb.getJobInfo(provider, job_key, 0, idx))

    console_ruler(character="-=")
    assert (
        tx.events["LogRegisteredDataRequestToUse"][0]["registeredDataHash"] ==
        "0x0000000000000000000000000000000068b8d8218e730fc2957bcb12119cb204"
    ), "registered data should be used"

    with brownie.reverts():
        log(ebb.getJobInfo(provider, job_key, 1, 2))
        log(ebb.getJobInfo(provider, job_key, 0, 3))

    # setJobStatus for the workflow:
    index = 0
    job_id = 0
    start_time = 10
    tx = ebb.setJobStatusRunning(job_key, index, job_id, start_time,
                                 {"from": accounts[0]})
    index = 0
    job_id = 1
    start_time = 20
    tx = ebb.setJobStatusRunning(job_key, index, job_id, start_time,
                                 {"from": accounts[0]})
    # process_payment for the workflow
    index = 0
    job_id = 0
    execution_time = 10
    data_transfer = [100, 0]
    end_time = 20
    result_ipfs_hash = ipfs_to_bytes32(
        "QmWmyoMoctfbAaiEs2G46gpeUmhqFRDW6KWo64y5r581Ve")

    received_sums = []
    refunded_sums = []
    received_sum = 0
    refunded_sum = 0
    args = [
        index, job_id, end_time, data_transfer[0], data_transfer[1], job.cores,
        job.run_time, False
    ]
    tx = ebb.processPayment(job_key, args, execution_time, result_ipfs_hash,
                            {"from": accounts[0]})
    # log(tx.events['LogProcessPayment'])
    received_sums.append(tx.events["LogProcessPayment"]["receivedWei"])
    refunded_sums.append(tx.events["LogProcessPayment"]["refundedWei"])
    received_sum += tx.events["LogProcessPayment"]["receivedWei"]
    refunded_sum += tx.events["LogProcessPayment"]["refundedWei"]
    log(f"received_sum={received_sum} | refunded_sum={refunded_sum} | job_price={job_price}"
        )
    # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    index = 0
    job_id = 1
    execution_time = 15
    data_transfer = [0, 0]
    end_time = 39
    result_ipfs_hash = ipfs_to_bytes32(
        "QmWmyoMoctfbAaiEs2G46gpeUmhqFRDW6KWo64y5r581Ve")

    args = [
        index, job_id, end_time, data_transfer[0], data_transfer[1], job.cores,
        job.run_time, False
    ]
    tx = ebb.processPayment(job_key, args, execution_time, result_ipfs_hash,
                            {"from": accounts[0]})
    received_sums.append(tx.events["LogProcessPayment"]["receivedWei"])
    refunded_sums.append(tx.events["LogProcessPayment"]["refundedWei"])
    received_sum += tx.events["LogProcessPayment"]["receivedWei"]
    refunded_sum += tx.events["LogProcessPayment"]["refundedWei"]
    log(f"received_sum={received_sum} | refunded_sum={refunded_sum} | job_price={job_price}"
        )
    # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    index = 0
    job_id = 2
    execution_time = 20
    data_transfer = [0, 100]
    end_time = 39
    result_ipfs_hash = ipfs_to_bytes32(
        "QmWmyoMoctfbAaiEs2G46gpeUmhqFRDW6KWo64y5r581Ve")
    with brownie.reverts(
    ):  # processPayment should revert, setRunning is not called for the job=2
        args = [
            index,
            job_id,
            end_time,
            data_transfer[0],
            data_transfer[1],
            job.cores,
            job.run_time,
            False,
        ]
        tx = ebb.processPayment(job_key, args, execution_time,
                                result_ipfs_hash, {"from": accounts[0]})

    index = 0
    job_id = 2
    start_time = 20
    tx = ebb.setJobStatusRunning(job_key, index, job_id, start_time,
                                 {"from": accounts[0]})

    args = [
        index, job_id, end_time, data_transfer[0], data_transfer[1], job.cores,
        job.run_time, True
    ]
    tx = ebb.processPayment(job_key, args, execution_time, result_ipfs_hash,
                            {"from": accounts[0]})
    # log(tx.events['LogProcessPayment'])
    received_sums.append(tx.events["LogProcessPayment"]["receivedWei"])
    refunded_sums.append(tx.events["LogProcessPayment"]["refundedWei"])
    received_sum += tx.events["LogProcessPayment"]["receivedWei"]
    refunded_sum += tx.events["LogProcessPayment"]["refundedWei"]
    log(f"received_sum={received_sum} | refunded_sum={refunded_sum} | job_price={job_price}"
        )
    log(received_sums)
    log(refunded_sums)
    assert job_price - _cost["storage"] == received_sum + refunded_sum
    withdraw(accounts[0], received_sum)
    withdraw(requester, refunded_sum)
Exemplo n.º 4
0
def test_data_info():
    job = Job()
    provider = accounts[0]
    requester = accounts[1]
    register_provider(100)
    register_requester(requester)
    job_key = b"9b3e9babb65d9c1aceea8d606fc55403"
    job.code_hashes = [job_key, b"9a4c0c1c9aadb203daf9367bd4df930b"]
    job.cores = [1]
    job.run_time = [5]
    job.data_transfer_ins = [0, 1]
    job.data_transfer_out = 1
    job.storage_ids = [StorageID.IPFS.value, StorageID.IPFS.value]
    job.cache_types = [CacheType.PUBLIC.value, CacheType.PUBLIC.value]
    job.storage_hours = [0, 1]
    job.data_prices_set_block_numbers = [0, 0]
    job_price, _cost = job.cost(provider, requester)
    provider_price_block_number = ebb.getProviderSetBlockNumbers(
        accounts[0])[-1]
    args = [
        provider,
        provider_price_block_number,
        job.storage_ids,
        job.cache_types,
        job.data_prices_set_block_numbers,
        job.cores,
        job.run_time,
        job.data_transfer_out,
    ]
    ebb.submitJob(
        job_key,
        job.data_transfer_ins,
        args,
        job.storage_hours,
        job.code_hashes,
        {
            "from": requester,
            "value": web3.toWei(job_price, "wei")
        },
    )
    provider_price_info = ebb.getProviderInfo(provider, 0)
    price_cache = provider_price_info[1][4]
    storage_payment = []
    for idx, code_hash in enumerate(job.code_hashes):
        deposit, *_ = ebb.getStorageInfo(provider, requester, code_hash)
        storage_payment.append(deposit)
        assert storage_payment[idx] == job.storage_hours[idx] * price_cache

    job.is_verified = [False, True]
    ebb.dataReceived(  # called by the provider
        job_key,
        0,
        job.code_hashes,
        job.cache_types,
        job.is_verified,
        {
            "from": provider,
            "gas": 4500000
        },
    )
    for idx, code_hash in enumerate(job.code_hashes):
        *_, output = ebb.getStorageInfo(provider, cfg.ZERO_ADDRESS, code_hash)
        assert output[3] == job.is_verified[idx]
        # requester is data_owner

    for idx, code_hash in enumerate(job.code_hashes):
        with brownie.reverts():
            tx = ebb.depositStorage(requester, code_hash, {
                "from": provider,
                "gas": 4500000
            })

    mine(cfg.BLOCK_DURATION_1_HOUR)
    for idx, code_hash in enumerate(job.code_hashes):
        *_, output = ebb.getStorageInfo(provider, cfg.ZERO_ADDRESS, code_hash)
        if output[3]:
            tx = ebb.depositStorage(requester, code_hash, {
                "from": provider,
                "gas": 4500000
            })
            print(tx.events["LogDepositStorage"])
Exemplo n.º 5
0
def test_submit_job():
    job = Job()
    provider = accounts[0]
    requester = accounts[1]
    register_provider()
    register_requester(requester)
    fname = f"{cwd}/files/test.txt"
    # fname = f"{cwd}/files/test_.txt"
    log(f"==> registered_provider_addresses={ebb.getProviders()}")
    provider_price_info = ebb.getProviderInfo(accounts[0], 0)
    # block_read_from = provider_price_info[0]
    _provider_price_info = provider_price_info[1]
    # availableCoreNum = _provider_price_info[0]
    # commitmentBlockDuration = _provider_price_info[1]
    price_core_min = _provider_price_info[2]
    # price_data_transfer = _provider_price_info[3]
    # price_storage = _provider_price_info[4]
    # price_cache = _provider_price_info[5]
    log(f"provider_available_core={available_core}")
    log(f"provider_price_core_min={price_core_min}")
    log(provider_price_info)
    job_price_sum = 0
    job_id = 0
    index = 0
    with open(fname) as f:
        for line in f:
            arguments = line.rstrip("\n").split(" ")
            storage_hour = 1
            core_min = int(arguments[1]) - int(arguments[0])
            core = int(arguments[2])
            job.cores = [core]
            job.run_time = [core_min]
            # time.sleep(1)
            # rpc.mine(int(arguments[0]))

            job_key = "QmQv4AAL8DZNxZeK3jfJGJi63v1msLMZGan7vSsCDXzZud"
            data_key = "QmQv4AAL8DZNxZeK3jfJGJi63v1msLMZGan7vSsCDXzZud"
            code_hash = ipfs_to_bytes32(data_key)
            # log("Client Balance before: " + str(web3.eth.balanceOf(account)))
            # log("Contract Balance before: " + str(web3.eth.balanceOf(accounts[0])))
            job.code_hashes = [code_hash]
            job.storage_hours = [storage_hour]
            job.data_transfer_ins = [100]
            job.data_transfer_out = 100
            job.data_prices_set_block_numbers = [0]
            job.storage_ids = [StorageID.IPFS.value]
            job.cache_types = [CacheType.PUBLIC.value]
            args = [
                provider,
                ebb.getProviderSetBlockNumbers(accounts[0])[-1],
                job.storage_ids,
                job.cache_types,
                job.data_prices_set_block_numbers,
                job.cores,
                job.run_time,
                job.data_transfer_out,
            ]

            # log(code_hashes[0])
            job_price, _cost = job.cost(provider, requester)
            job_price_sum += job_price
            data_transfer_ins = [100]
            job_key = job.storage_hours[0]
            tx = ebb.submitJob(
                job_key,
                data_transfer_ins,
                args,
                job.storage_hours,
                job.code_hashes,
                {
                    "from": requester,
                    "value": web3.toWei(job_price, "wei")
                },
            )
            # log('submitJob => GasUsed:' + str(tx.__dict__['gas_used']) + '| blockNumber=' + str(tx.block_number))
            log(f"job_index={tx.events['LogJob']['index']}", "bold")
            # log("Contract Balance after: " + str(web3.eth.balanceOf(accouts[0])))
            # log("Client Balance after: " + str(web3.eth.balanceOf(accounts[8])))
            # sys.stdout.write('jobInfo: ')
            # sys.stdout.flush()
            log(ebb.getJobInfo(provider, job_key, index, job_id))
            index += 1

    log(f"total_paid={job_price_sum}")
    # log(block_read_from)
    # rpc.mine(100)
    # log(web3.eth.blockNumber)
    job_id = 0
    with open(fname) as f:
        for index, line in enumerate(f):
            arguments = line.rstrip("\n").split(" ")
            tx = ebb.setJobStatusRunning(job_key, index, job_id,
                                         int(arguments[0]),
                                         {"from": accounts[0]})
            if index == 0:
                with brownie.reverts():
                    tx = ebb.setJobStatusRunning(job_key, index, job_id,
                                                 int(arguments[0]) + 1,
                                                 {"from": accounts[0]})

    console_ruler()
    result_ipfs_hash = ipfs_to_bytes32(
        "QmWmyoMoctfbAaiEs2G46gpeUmhqFRDW6KWo64y5r581Ve")
    with open(fname) as f:
        for index, line in enumerate(f):
            arguments = line.rstrip("\n").split(" ")
            if index == 0:
                data_transfer_in_sum = 90
                job.data_transfer_out = 100
            else:
                data_transfer_in_sum = 0
                job.data_transfer_out = 100

            core_min = int(arguments[1]) - int(arguments[0])
            core = int(arguments[2])
            job.cores = [core]
            job.run_time = [core_min]
            log(f"contract_balance={ebb.getContractBalance()}", "bold")
            job_id = 0
            execution_time = int(arguments[1]) - int(arguments[0])
            end_time = int(arguments[1])
            args = [
                index,
                job_id,
                end_time,
                data_transfer_in_sum,
                job.data_transfer_out,
                job.cores,
                job.run_time,
                True,
            ]
            tx = ebb.processPayment(job_key, args, execution_time,
                                    result_ipfs_hash, {"from": accounts[0]})
            # code_hashes
            received = tx.events["LogProcessPayment"]["receivedWei"]
            refunded = tx.events["LogProcessPayment"]["refundedWei"]
            withdraw(accounts[0], received)
            withdraw(requester, refunded)
            log(f"received={received} | refunded={refunded}", "bold")

    log(f"contract_balance={ebb.getContractBalance()}", "bold")
    for idx in range(0, ebb.getProviderReceiptSize(provider)):
        # prints finalize version of the linked list
        log(ebb.getProviderReceiptNode(provider, idx))

    console_ruler()
    log(f"==> storage_duration for job={job_key}")
    *_, job_storage_info = ebb.getStorageInfo(provider, cfg.ZERO_ADDRESS,
                                              code_hash)
    ds = DataStorage(job_storage_info)
    log(f"receivedBlockNumber={ds.received_block} |"
        f"storage_duration(block numbers)={ds.storage_duration} | "
        f"is_private={ds.is_private} |"
        f"is_verified_Used={ds.is_verified_used}")
    received_storage_deposit, *_ = ebb.getStorageInfo(provider, requester,
                                                      code_hash)
    log(f"received_storage_deposit={received_storage_deposit}")
    console_ruler("DONE")
Exemplo n.º 6
0
def test_simple_submit():
    job = Job()
    provider = accounts[0]
    requester = accounts[1]
    price_core_min = 100
    register_provider(price_core_min)
    register_requester(requester)
    job.code_hashes = [
        b"9b3e9babb65d9c1aceea8d606fc55403",
        b"9a4c0c1c9aadb203daf9367bd4df930b"
    ]
    job.key = job.code_hashes[0]
    job.cores = [2]
    job.run_time = [1]
    job.data_transfer_ins = [1, 1]
    job.data_transfer_out = 1
    job.storage_ids = [StorageID.EUDAT.value, StorageID.EUDAT.value]
    job.cache_types = [CacheType.PUBLIC.value, CacheType.PUBLIC.value]
    job.storage_hours = [0, 0]
    job.data_prices_set_block_numbers = [0, 0]

    job_price, _cost = job.cost(provider, requester)
    provider_price_block_number = ebb.getProviderSetBlockNumbers(
        accounts[0])[-1]

    args = [
        provider,
        provider_price_block_number,
        job.storage_ids,
        job.cache_types,
        job.data_prices_set_block_numbers,
        job.cores,
        job.run_time,
        job.data_transfer_out,
    ]

    tx = ebb.submitJob(
        job.key,
        job.data_transfer_ins,
        args,
        job.storage_hours,
        job.code_hashes,
        {
            "from": requester,
            "value": web3.toWei(job_price, "wei")
        },
    )
    log(f"submitJob_gas_used={tx.__dict__['gas_used']}")
    index = 0
    job_id = 0
    start_time = 1579524978
    tx = ebb.setJobStatusRunning(job.key, index, job_id, start_time,
                                 {"from": provider})
    rpc.sleep(60)
    mine(5)

    completion_time = 1579524998
    data_transfer_in = 0
    data_transfer_out = 0.01
    args = [
        index, job_id, completion_time, data_transfer_in, data_transfer_out,
        job.cores, [1], True
    ]
    elapsed_time = 1
    out_hash = b"[46\x17\x98r\xc2\xfc\xe7\xfc\xb8\xdd\n\xd6\xe8\xc5\xca$fZ\xebVs\xec\xff\x06[\x1e\xd4f\xce\x99"
    tx = ebb.processPayment(job.key, args, elapsed_time, out_hash,
                            {"from": accounts[0]})
    # tx = ebb.processPayment(job.code_hashes[0], args, elapsed_time, zero_bytes32, {"from": accounts[0]})
    received_sum = tx.events["LogProcessPayment"]["receivedWei"]
    refunded_sum = tx.events["LogProcessPayment"]["refundedWei"]
    # log(str(received_sum) + " " + str(refunded_sum))
    assert received_sum == job.cores[0] * price_core_min and refunded_sum == 5
    withdraw(accounts[0], received_sum)
    withdraw(requester, refunded_sum)