Ejemplo n.º 1
0
Archivo: isc.py Proyecto: KenHopkin/UIP
    def __init__(
        self,
        isc_owners=None,
        transaction_intents=None,
        required_funds=None,
        ves_signature=None,
        host_addr=None,
        contract_addr=None,
        wlt=None
    ):
        self.handler = ISC(bind_cli=Client(host_addr))
        super().__init__()
        self.debugger = partial(isc_log.debug, extra={'iscaddr': self.address})
        self.infoer = partial(isc_log.info, extra={'iscaddr': self.address})
        if contract_addr is None:

            self.address = TenInsuranceSmartContract.make_contract(
                isc_owners,
                transaction_intents,
                required_funds,
                ves_signature,
                host_addr,
                wlt
            )
            self.debugger('NewISCBuilt owners: {owners}'.format(owners=isc_owners))
        else:
            self.address = contract_addr
        self.owners = isc_owners
        console_logger.info('isc {} built'.format(self.address))
Ejemplo n.º 2
0
    def send_attestation(self,
                         session_index: int,
                         atte: Attestation,
                         tx_index: int,
                         state: StateType,
                         host_name: str = None) -> ContractFunctionClient:
        if host_name is None:
            host_name = self.default_domain
        host_info = self.info[host_name]
        # nsb = EthLightNetStatusBlockChain(
        #     host_info['address'],
        #     host_info['host'],
        #     self.session_event[session_index]['nsb']
        # )

        console_logger.info(
            'dapp ({0}) adding atte[\n'
            '     isc: {1}\n'
            '    transaction-action index: ({2}, {3})\n'
            '    atte: ({4}, {5})\n'
            ']'.format(self.name, self.session_event[session_index]['isc'],
                       tx_index, state.value,
                       HexBytes(atte.pre_hash).hex(),
                       atte.signatures[-1][0].to_hex()))
        self.unlockself(host_name)
        sys_act = SystemAction(host_info['host'])
        sys_act.add_action(
            host_info['password'],
            Action(bytes.fromhex("123456"), tx_index, state.value,
                   action_using_flag[host_info['chain_type']].value,
                   HexBytes(atte.pre_hash), atte.signatures[-1][0].bytes()))
Ejemplo n.º 3
0
    def ackinit(self, ves, isc, content, sig, host_name=None, testing=False):

        if host_name is None:
            host_name = self.default_domain
        host_info = self.info[host_name]
        host_name = host_info['domain']

        # if not SignatureVerifier.verify_by_raw_message(sig, rlp.encode(content), ves.address):
        #     # user refuse TODO
        #     try:
        #         ves.session_setup_update(int(content[0]), self.name, None)
        #     except Exception as e:
        #         raise e
        # user looking through content
        # print(sig, host_name)
        if host_name == "Tendermint://chain1":
            signature = self.sign(bytes.fromhex(sig[2:]), host_name)
        else:
            signature = self.sign(sig, host_name)

        console_logger.info(
            'dapp ({0}) is trying call user_ack, name: {1} host: {2}'.format(
                self.name, host_name, host_info))
        if not testing:
            if host_name == "Tendermint://chain1":
                self.unlockself(host_name)
                sys_act = SystemAction(host_info['host'])
                sys_act.add_action(
                    host_info['password'],
                    Action(bytes.fromhex("123456"), None, None,
                           action_using_flag[host_info['chain_type']].value,
                           bytes.fromhex(sig[2:]), signature))
            else:
                self.unlockself(host_name)
                sys_act = SystemAction(host_info['host'])
                sys_act.add_action(
                    host_info['password'],
                    Action(bytes.fromhex("123456"), None, None,
                           action_using_flag[host_info['chain_type']].value,
                           bytes.fromhex(sig[2:]),
                           bytes.fromhex(signature[2:])))

        # what if update no successful? TODO

        ret = ves.session_setup_update(int(content[0]),
                                       host_name + '.' + self.name, signature)
        if isinstance(ret, Exception):
            raise ret
        else:
            console_logger.info(
                'dapp ({0}) user_ack accepted by ves: {1}'.format(
                    self.name, ves.address))
            self.session_event[int(content[0])] = {
                'host_info': host_info,
                # TODO: temporary eth-nsb-address
                'isc': isc.address,
                'nsb': "PLACEHODER"
            }
Ejemplo n.º 4
0
Archivo: isc.py Proyecto: KenHopkin/UIP
    def make_contract(owners, signature, rlped_txs, tx_count, ves, bytescode=None, bin_dir=isc_bin_dir):
        try:
            rlped_txs = HexBytes(rlped_txs)
            encoded_data = AbiEncoder.encodes(
                [
                    owners,
                    [0, 0, 0],
                    HexBytes(ETHSIGN_HEADER + bytes(str(len(rlped_txs)).encode(ENC)) + bytes(rlped_txs)).hex(),
                    signature,
                    keccak(ETHSIGN_HEADER + b'\x36\x35' + HexBytes(signature)),
                    tx_count
                ],
                ['address[]', 'uint256[]', 'bytes', 'bytes', 'bytes32', 'uint256']
            )
            if bytescode is None:
                bytescode = FileLoad.getbytecode(bin_dir)

            ves.unlockself()
            tx_json = JsonRPC.eth_send_transaction({
                'from': ves.address,
                'data': bytescode.decode(ENC) + encoded_data,
                'gas': hex(8000000)
            })
            # print(tx_json)
            response = JsonRPC.send(tx_json, rpc_host=ves.chain_host)
            rp_json = JsonRPC.eth_get_transaction_receipt(response['result'])
        except Exception as e:
            isc_log.debug('ISCBulidError: {}'.format(str(e)))
            raise e
        while True:
            try:

                response = JsonRPC.send(rp_json, rpc_host=ves.chain_host)
                if response['result'] is None:
                    console_logger.info("Contract is deploying, please stand by")
                    time.sleep(2)
                    continue
                console_logger.info("got Transaction_result {}".format(response['result']))

                block_number = response['result']['blockNumber']
                contract_addr = response['result']['contractAddress']

                cd_json = JsonRPC.eth_get_code(contract_addr, block_number)
                response = JsonRPC.send(cd_json, rpc_host=ves.chain_host)
                if response['result'] == '0x':
                    raise IndexError("Contract deployment failed")

                return contract_addr
            except Exception as e:
                isc_log.debug('ISCBulidError: {exec}'.format(exec=str(e)), extra={"addr": ""})
                raise e
Ejemplo n.º 5
0
Archivo: isc.py Proyecto: KenHopkin/UIP
    def __init__(
        self,
        owners,
        abi_dir=isc_abi_dir,
        bin_dir=isc_bin_dir,
        rlped_txs=None,
        signature=None,
        ves=None,
        tx_head=None,
        tx_count=None,
        contract_addr=None,
        isc_bytecode_dir=None,
        **kwargs
    ):
        super().__init__()
        self.debugger = partial(isc_log.debug, extra={'iscaddr': self.address})
        self.infoer = partial(isc_log.info, extra={'iscaddr': self.address})
        if contract_addr is None:
            if rlped_txs is None or signature is None or owners is None or ves is None or tx_count is None:
                pass
            else:
                self.address = EthInsuranceSmartContract.make_contract(
                    owners=owners,
                    signature=signature,
                    rlped_txs=rlped_txs,
                    tx_count=tx_count,
                    ves=ves,
                    bin_dir=bin_dir
                )
                self.debugger('NewISCBuilt owners: {owners}'.format(owners=owners))
        else:
            self.address = contract_addr
        self.owners = owners
        self.handle = EthContract(
            ves.chain_host, Web3.toChecksumAddress(self.address), abi_dir, isc_bytecode_dir
        )
        console_logger.info('isc {} built'.format(self.address))

        self.web3 = self.handle.web3
        self.tx = tx_head.copy()

        console_logger.info('isc({0}) init: functions:{1}'.format(self.address, self.handle.funcs()))
Ejemplo n.º 6
0
Archivo: isc.py Proyecto: KenHopkin/UIP
 def insurance_claim(self, atte: Attestation, tid, state, nsb_addr=None, result=None, tcg=None, tx=None):
     if tx is None:
         tx = self.tx
     console_logger.info('isc({0}) claiming:\n Attestation: {1},\n tid:{2},\n state: {3}'.format(
         self.address, atte.__dict__, tid, state
     ))
     print(atte, "is not verified")
     if state == StateType.opened:
         if tcg is None:
             raise Missing("the opening time of Transaction must be given")
         return self.handle.funct('ChangeStateOpened', tx, tid, tcg)
     elif state == StateType.closed:
         if tcg is None:
             raise Missing("the close time of Transaction must be given")
         return self.handle.funct('ChangeStateClosed', tx, tid, tcg)
     elif state == StateType.open:
         if result is None:
             raise Missing("the result of Transaction must be given")
         return (
             self.handle.funct('ChangeState', tx, tid, state),
             self.handle.funct('ChangeResult', tx, nsb_addr, tid, result)
         )
     else:
         return self.handle.funct('ChangeState', tx, tid, state)
Ejemplo n.º 7
0
# python modules

# uip modules
from uiputils.ethtools import FileLoad, JsonRPC
from ves import VerifiableExecutionSystem
from dapp import DApp
from uiputils.transaction import StateType
import time


# config
from uiputils.config import HTTP_HEADER, alice, bob, tom

from uiputils.loggers import console_logger

from py_nsbcli.modules.admin import set_admin_singleton_mode
set_admin_singleton_mode(False)

if __name__ == '__main__':
    # 029a
    tot_time = time.perf_counter()
    # prepare
    ves = VerifiableExecutionSystem()
    dapp_x = DApp(info_x)
    dapp_y = DApp(info_y)
    ves.appenduserlink([dapp_x, dapp_y])

    console_logger.info('{0} built, info:{1}'.format(dapp_x, dapp_x.info))
    console_logger.info('{0} built, info:{1}'.format(dapp_y, dapp_y.info))
    console_logger.info('{0} built, info:{1}'.format(ves, ves.__dict__))
Ejemplo n.º 8
0
    unlock = JsonRPC.personal_unlock_account(user['name'], user['passphrase'],
                                             20)
    response = JsonRPC.send(unlock, HTTP_HEADER, user['domain'])
    if not response['result']:
        raise ValueError("unlock failed. wrong password?")


if __name__ == '__main__':

    # prepare
    ves = VerifiableExecutionSystem()
    dapp_x = DApp(info_x)
    dapp_y = DApp(info_y)
    ves.appenduserlink([dapp_x, dapp_y])

    console_logger.info('{0} built, info:{1}'.format(dapp_x, dapp_x.info))
    console_logger.info('{0} built, info:{1}'.format(dapp_y, dapp_y.info))
    console_logger.info('{0} built, info:{1}'.format(ves, ves.__dict__))

    # load Sample.json
    op_intents_json = FileLoad.getopintents("./opintents2.json")

    for intent in op_intents_json['Op-intents']:
        intent['contract_domain'] = "Ethereum://" + intent['contract_domain']

    session_content, isc, session_signature, tx_intents = ves.session_setup_prepare(
        op_intents_json)

    dapp_x.ackinit(ves,
                   isc,
                   session_content,
Ejemplo n.º 9
0
            break
            # if response['result'] is None:
            #     print("Exec...", resp)
            #     time.sleep(5)


if __name__ == '__main__':
    # 029a
    tot_time = time.perf_counter()
    # prepare
    ves = VerifiableExecutionSystem()
    dapp_x = DApp(info_x)
    dapp_y = DApp(info_y)
    ves.appenduserlink([dapp_x, dapp_y])

    console_logger.info('{0} built, info:{1}'.format(dapp_x, dapp_x.info))
    console_logger.info('{0} built, info:{1}'.format(dapp_y, dapp_y.info))
    console_logger.info('{0} built, info:{1}'.format(ves, ves.__dict__))

    # load Sample.json
    op_intents_json = FileLoad.getopintents("./opintents5.json")

    # for intent in op_intents_json['Op-intents']:
    #     intent['contract_domain'] = "Ethereum://" + intent['contract_domain']

    session_content, isc, session_signature, tx_intents = ves.session_setup_prepare(
        op_intents_json)

    dapp_x.ackinit(ves,
                   isc,
                   session_content,
Ejemplo n.º 10
0
def e2e_execution():
    # prepare
    ves = VerifiableExecutionSystem()
    dapp_x = DApp(info_x)
    dapp_y = DApp(info_y)
    dapp_z = DApp(info_z)
    ves.appenduserlink([dapp_x, dapp_y, dapp_z])

    console_logger.info('{0} built, info:{1}'.format(dapp_x, dapp_x.info))
    console_logger.info('{0} built, info:{1}'.format(dapp_y, dapp_y.info))
    console_logger.info('{0} built, info:{1}'.format(dapp_z, dapp_z.info))
    console_logger.info('{0} built, info:{1}'.format(ves, ves.__dict__))

    # load Sample.json
    op_intents_json = FileLoad.getopintents("./test/opintents4.json")

    # for intent in op_intents_json['Op-intents']:
    #     intent['contract_domain'] = "Ethereum://" + intent['contract_domain']

    latency_profile = LatencyProfile()
    tot_time = time.perf_counter()
    session_content, isc, session_signature, tx_intents = ves.session_setup_prepare(
        op_intents_json)
    dapp_x.ackinit(ves,
                   isc,
                   session_content,
                   session_signature,
                   ves.nsb.host,
                   testing=False)
    dapp_y.ackinit(ves,
                   isc,
                   session_content,
                   session_signature,
                   ves.nsb.host,
                   testing=False)
    dapp_z.ackinit(ves,
                   isc,
                   session_content,
                   session_signature,
                   ves.nsb.host,
                   testing=False)
    latency_profile.isc_init = time.perf_counter() - tot_time

    # print("raw: ", ves.address)
    # print(isc.is_owner(ves.address))
    # print(isc.is_raw_sender(ves.address))
    # print(isc.is_owner(dapp_x.info[ves.nsb.host]['address']))
    # print(isc.is_owner(dapp_y.info[ves.nsb.host]['address']))
    # print(isc.tx_info_length())
    # print(isc.get_isc_state())
    # print(ves.nsb.is_active_isc(isc.address))

    user_table = [
        (dapp_x, ves),
        (dapp_y, ves),
        (dapp_x, ves),
        (ves, dapp_z),
        (dapp_z, ves),
    ]
    session_id = int(session_content[0])

    tag_time = None
    tag_time_end = None
    atte_computation = []
    action_staking = []
    proof_retriveal = []
    print("prepare end..", time.perf_counter() - tot_time)
    for idx, [u, v] in enumerate(user_table):
        # assert tx_intent is on ISC

        # Part_A # inited ##############################################################################################

        print("compute on_chain_tx")
        tag_time = time.perf_counter()
        # compute on_chain_tx
        tx = tx_intents.intents[idx].jsonize()
        console_logger.info(
            'on chain transaction computed index: {0}, content: {1}'.format(
                idx, tx))
        tag_time_end = time.perf_counter() - tag_time
        print("compute on_chain_tx", tag_time_end)

        print("attestation inited")
        # compute attestation
        tag_time = time.perf_counter()
        atte = u.init_attestation(tx, StateType.inited, session_id, idx,
                                  ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        print("Atte computation", tag_time_end)
        atte_computation.append(tag_time_end)

        # send inited attestaion
        tag_time = time.perf_counter()
        ret = u.send_attestation(session_id, atte, idx, StateType.inited,
                                 ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        action_staking.append(tag_time_end)
        print("Action staking", tag_time_end)

        # receive attestaion
        tag_time = time.perf_counter()
        atte_rec = v.receive(atte.encode(), int(session_content[0]), idx,
                             StateType.inited.value, ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        proof_retriveal.append(tag_time_end)
        print("attestation inited", tag_time_end)
        # laz_func = u.send_attestation(session_id, atte, idx, StateType.inited, ves.nsb.host)
        # u.unlockself(ves.nsb.host)
        # laz_func.transact()
        # console_logger.info('nsb received action, response: {}'.format(laz_func.loop_and_wait()))
        console_logger.info('nsb received action, response: {}'.format(ret))

        # Part_Z # open ################################################################################################

        print("attestation open")
        # compute attestation
        tag_time = time.perf_counter()
        rlped_data = v.sign_attestation(atte_rec)
        tag_time_end = time.perf_counter() - tag_time
        print("Atte computation", tag_time_end)
        atte_computation.append(tag_time_end)

        # send open-request attestion
        tag_time = time.perf_counter()
        ret = v.send_attestation(session_id, atte_rec, idx, StateType.open,
                                 ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        print("Action staking", tag_time_end)
        action_staking.append(tag_time_end)

        # no necessary to ack, just verify it
        tag_time = time.perf_counter()
        u.receive(rlped_data, int(session_content[0]), idx,
                  StateType.open.value, ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        proof_retriveal.append(tag_time_end)
        print("attestation open", tag_time_end)
        # laz_func = v.send_attestation(session_id, atte_rec, idx, StateType.open, ves.nsb.host)
        # v.unlockself(ves.nsb.host)
        # laz_func.transact()
        # console_logger.info('nsb received action, response: {}'.format(laz_func.loop_and_wait()))
        console_logger.info('nsb received action, response: {}'.format(ret))

        # Part_A # opened ##############################################################################################

        # open transaction
        print("transact")
        tag_time = time.perf_counter()
        # u.unlockself(tx_intents.intents[idx].chain_host)
        # temporary_transact(tx, tx_intents.intents[idx].chain_host, u)
        tag_time_end = time.perf_counter() - tag_time
        print("transact", tag_time_end)

        print("attestation opened")
        # compute opened attestaion
        tag_time = time.perf_counter()
        atte = u.init_attestation(tx, StateType.opened,
                                  int(session_content[0]), 0, ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        atte_computation.append(tag_time_end)

        # send opened attestion
        tag_time = time.perf_counter()
        ret = u.send_attestation(session_id, atte, idx, StateType.opened,
                                 ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        action_staking.append(tag_time_end)

        # no necessary to ack, just verify it
        tag_time = time.perf_counter()
        v.receive(atte.encode(), int(session_content[0]), idx,
                  StateType.opened.value, ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        proof_retriveal.append(tag_time_end)
        print("attestation opened", tag_time_end)

        # laz_func = u.send_attestation(session_id, atte, idx, StateType.opened, ves.nsb.host)
        # laz_func.transact()
        # console_logger.info('nsb received action, response: {}'.format(laz_func.loop_and_wait()))
        console_logger.info('nsb received action, response: {}'.format(ret))

        # Part_Z # closed ##############################################################################################

        # atte = v.init_attestation(tx, StateType.closed, int(session_content[0]), 0, ves.nsb.host)
        # laz_func = v.send_attestation(session_id, atte, idx, StateType.closed, ves.nsb.host)
        # laz_func.transact()
        # console_logger.info('nsb received action, response: {}'.format(laz_func.loop_and_wait()))

        # compute closed attestaion
        print("attestation closed")
        tag_time = time.perf_counter()
        atte = v.init_attestation(tx, StateType.closed,
                                  int(session_content[0]), 0, ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        atte_computation.append(tag_time_end)

        # send closed attestion
        tag_time = time.perf_counter()
        ret = v.send_attestation(session_id, atte, idx, StateType.closed,
                                 ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        action_staking.append(tag_time_end)

        # receive closed attestion
        tag_time = time.perf_counter()
        u.receive(atte.encode(), int(session_content[0]), idx,
                  StateType.closed.value, ves.nsb.host)
        tag_time_end = time.perf_counter() - tag_time
        proof_retriveal.append(tag_time_end)
        print("attestation closed", tag_time_end)
        console_logger.info('nsb received action, response: {}'.format(ret))

        # end ##########################################################################################################

        print("----------end transaction----------")
    # #
    # # # settle
    # #
    # # # close
    latency_profile.atte_computation = sum(atte_computation) / len(
        atte_computation)
    latency_profile.action_staking = sum(action_staking) / len(action_staking)
    latency_profile.proof_retrieval = sum(proof_retriveal) / len(
        proof_retriveal)
    print("tot_time", time.perf_counter() - tot_time)
    return latency_profile
Ejemplo n.º 11
0
Archivo: isc.py Proyecto: KenHopkin/UIP
 def get_transaction_info(self, tid):
     ret = self.handle.func('getTransactionInfo', tid)
     console_logger.info('geted transaction information(index: {0}) {1}'.format(tid, ret))
     ret[4] = JsonRlpize.unserialize(ret[4])
     return ret
Ejemplo n.º 12
0
Archivo: isc.py Proyecto: KenHopkin/UIP
 def return_funds(self, tx=None):
     if tx is None:
         tx = self.tx
     console_logger.info('isc({}) returing funds'.format(self.address))
     return self.handle.funct('returnFunds', tx)
Ejemplo n.º 13
0
Archivo: isc.py Proyecto: KenHopkin/UIP
 def update_funds(self, owner, tx):
     if owner not in self.owners:
         raise Missing('this address is not owner')
     console_logger.info('isc({}) updating funds'.format(self.address))
     print(owner, "updated fund:", tx)
Ejemplo n.º 14
0
Archivo: isc.py Proyecto: KenHopkin/UIP
 def settle_contract(self, tx=None):
     if tx is None:
         tx = self.tx
     console_logger.info('isc({}) settling'.format(self.address))
     return self.handle.funct('settleContract', tx)
Ejemplo n.º 15
0
Archivo: isc.py Proyecto: KenHopkin/UIP
 def stop_isc(self, tx=None):
     if tx is None:
         tx = self.tx
     console_logger.info('isc({}) closed'.format(self.address))
     return self.handle.funct('StopISC', tx)