Beispiel #1
0
 def lazy_function():
     sig = ContractFunction.check_sig(function_sign)
     return JsonRPC.send(JsonRPC.eth_send_transaction(
         dict(tx,
              data=sig +
              AbiEncoder.encodes(function_args, function_args_type))),
                         rpc_host=host)['result']
def temporary_transact(tx, host):
    if host == "http://47.251.2.73:26657":
        from py_nsbcli import Client, Admin
        from py_nsbcli.system_token import SystemToken
        from hexbytes import HexBytes
        admin = Admin()
        admin.set_rpc_host(host)
        cli = Client(admin)
        token_cli = SystemToken(cli)

        print(token_cli.transfer(alice, HexBytes(tx['dst']), tx['fund']))
    else:
        tx_json = JsonRPC.eth_send_transaction(tx)
        print(tx)
        resp = JsonRPC.send(tx_json, HTTP_HEADER, host)['result']
        get_tx = JsonRPC.eth_get_transaction_receipt(resp)
        while True:
            response = JsonRPC.send(get_tx, HTTP_HEADER, host)
            if response['result'] is None:
                print("Exec...")
                time.sleep(1)
                continue
            else:
                print(response)
                break
Beispiel #3
0
    def sign(self, msg, host_name=None):
        """
        assuming self.address is on Ethereum
        :param msg: msg to sign (bytes in string)
        :param host_name: that the msg will send to
        :return: signature
        """
        if host_name is None:
            host_name = self.default_domain

        host_info = self.info[host_name]

        if host_info['chain_type'] == 'Tendermint':
            if isinstance(msg, str):
                if msg[0:2] == "0x":
                    msg = msg[2:]
                msg = bytes.fromhex(msg)
            return host_info['password'].sign(msg)
        elif host_info['chain_type'] == 'Ethereum':
            self.unlockself(host_name)
            sign_json = JsonRPC.eth_sign(host_info['address'], msg)
            return JsonRPC.send(sign_json, HTTP_HEADER,
                                host_info['host'])['result']
        else:
            raise TypeError("unsupported chain-type: ",
                            +host_info['chain_type'])
def temporary_transact(tx, host, dapp):

    if host == "http://47.254.66.11:26657":
        from py_nsbcli import Client, Admin
        from hexbytes import HexBytes
        admin = Admin()
        admin.set_rpc_host(host)
        cli = Client(admin)

        if tx['trans_type'] == "invoke":
            from contract.tendermint.option.contract import Option
            opt = Option(cli)
            opt.buy_option(tom, 5, bytes.fromhex(tx['dst'][2:]))
        else:
            from py_nsbcli.system_token import SystemToken
            token_cli = SystemToken(cli)
            print(token_cli.transfer(alice, HexBytes(tx['dst']), tx['fund']))
    else:
        print(dapp.__dict__, host)
        dapp.unlockself(host)
        tx_json = JsonRPC.eth_send_transaction(tx)
        print(tx)
        resp = JsonRPC.send(tx_json, HTTP_HEADER, host)['result']
        get_tx = JsonRPC.eth_get_transaction_receipt(resp)
        while True:
            response = JsonRPC.send(get_tx, HTTP_HEADER, host)
            if response['result'] is None:
                print("Exec...")
                time.sleep(1)
                continue
            else:
                print(response)
                break
Beispiel #5
0
 def lazy_function(transaction=None):
     if transaction is None:
         transaction = {}
     return JsonRPC.send(JsonRPC.eth_send_transaction(
         dict(transaction,
              data=function_sign +
              AbiEncoder.encodes(function_args, function_args_type))),
                         rpc_host=host)['result']
Beispiel #6
0
 def lazy_function(tx_resp: str, wait_time=25, query_period=1):
     tx_resp_json = JsonRPC.eth_get_transaction_receipt(tx_resp)
     expire_time = wait_time + time.time()
     while time.time() < expire_time:
         try:
             resp = JsonRPC.send(tx_resp_json, rpc_host=host)
             if resp['result'] is not None:
                 return resp
             time.sleep(query_period)
         except Exception:
             raise
Beispiel #7
0
 def call(trans):
     """
     call the contract_methods
     :param trans: transaction with contract invocation's information
     :return: results of function
     """
     if trans.chain_type == 'Ethereum':
         call_json = JsonRPC.eth_call(trans.jsonize())
         # print(json.dumps(tx_response, sort_keys=True, indent=4, separators=(', ', ': ')))
         return JsonRPC.send(call_json, HTTP_HEADER,
                             trans.chain_host)['result']
     else:
         raise TypeError("unsupported chain-type: ", +trans.chain_type)
Beispiel #8
0
def temporary_transact(tx, host):

    if host == "http://47.251.2.73:26657":
        from py_nsbcli import Client, Admin
        admin = Admin()
        admin.set_rpc_host(host)
        cli = Client(admin)
        from contract.tendermint.delegate.contract import DelegateContract
        opt = DelegateContract(cli)
        print(opt.vote(tom, bytes.fromhex(tx['dst'][2:])))
    else:
        tx_json = JsonRPC.eth_send_transaction(tx)
        print(tx)
        resp = JsonRPC.send(tx_json, HTTP_HEADER, host)['result']
        get_tx = JsonRPC.eth_get_transaction_receipt(resp)
        while True:
            response = JsonRPC.send(get_tx, HTTP_HEADER, host)
            print("result", response)
            break
Beispiel #9
0
 def parse(args, args_types):
     parsed_args = []
     for arg, arg_type in zip(args, args_types):
         if isinstance(arg, str) and len(arg) > 0 and arg[0] == '@':
             try:
                 contract_addr, begining_pos = arg[1:].split('.')
                 contract_addr, domain = \
                     eth_known_contract[contract_addr]['address'], eth_known_contract[contract_addr]['host']
                 authen_pos = HexBytes(SoliTypes[arg_type].ori_loc(begining_pos)).hex()
                 # print(authen_pos, contract_addr, domain)
                 parsed_args.append(JsonRPC.send(
                     JsonRPC.eth_get_storage_at(contract_addr, authen_pos, "latest"),
                     HTTP_HEADER,
                     domain
                 )['result'])
             except:
                 parsed_args.append("012")
         else:
             parsed_args.append(arg)
     return AbiEncoder.encodes(parsed_args, args_types)
Beispiel #10
0
    def unlockself(self, host_name=None):
        """
        assuming self.address is on Ethereum
        :param host_name:
        :return:
        """
        if host_name is None:
            host_name = self.default_domain

        host_info = self.info[host_name]

        if host_info['chain_type'] == 'Tendermint':
            return
        elif host_info['chain_type'] == 'Ethereum':
            unlock = JsonRPC.personal_unlock_account(host_info['address'],
                                                     host_info['password'], 20)
            response = JsonRPC.send(unlock, HTTP_HEADER, host_info['host'])
            if not response['result']:
                raise ValueError("unlock failed. wrong password?")
        else:
            raise TypeError("unsupported chain-type: ",
                            +host_info['chain_type'])
Beispiel #11
0
    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
Beispiel #12
0
    def send(self, trans, passphrase=None):
        """
        transact the contract_methods
        :param trans: transaction with contract invocation's information
        :param passphrase:
        :return: None
        """
        if passphrase is None:
            passphrase = self.info[trans.chain_host]
        if trans.chain_type == 'Ethereum':
            unlock = JsonRPC.personal_unlock_account(
                self.info[trans.chain_host]['address'], passphrase, 20)
            tx_response = JsonRPC.send(unlock, HTTP_HEADER, trans.chain_host)
            print(
                json.dumps(tx_response,
                           sort_keys=True,
                           indent=4,
                           separators=(', ', ': ')))

            packet_transaction = JsonRPC.eth_send_transaction(trans.jsonize())
            tx_response = JsonRPC.send(packet_transaction, HTTP_HEADER,
                                       trans.chain_host)
            print(
                json.dumps(tx_response,
                           sort_keys=True,
                           indent=4,
                           separators=(', ', ': ')))

            tx_hash = tx_response['result']
            query = JsonRPC.eth_get_transaction_receipt(tx_hash)
            while True:
                tx_response = JsonRPC.send(query, HTTP_HEADER,
                                           trans.chain_host)
                if tx_response['result'] is None:
                    print("transacting")
                    time.sleep(2)
                    continue
                break
            print(
                json.dumps(tx_response,
                           sort_keys=True,
                           indent=4,
                           separators=(', ', ': ')))
        else:
            raise TypeError("unsupported chain-type: ", +trans.chain_type)
Beispiel #13
0
from uiputils.ethtools import JsonRPC

EDB_PATH = "D:/Go Ethereum/data/geth/chaindata"
url = "http://127.0.0.1:8545"
HTTP_HEADER = {'Content-Type': 'application/json'}
nsb_addr = "0x43710274DaADCe0D8bDFE7ae6495140eA83CDA6a"
# ("0x076122c56613fc1e3ae97d715ca7cb6a35a934c6")

nsb_abi_addr = "../nsb/nsb.abi"
nsb_bytecode_addr = "../nsb/nsb.bin"
nsb_db_addr = "../nsb/actiondata"
if __name__ == '__main__':
    print(
        JsonRPC.send(
            JsonRPC.eth_get_storage_at(
                "0x7c7b26fa65e091f7b9f23db77ad5f714f1dae5ea", "0x0", "latest"),
            HTTP_HEADER, 'http://127.0.0.1:8545')['result'])
    # web3h = ServiceStart.startweb3(url)
    # key = 0
    # nsbt = EthNetStatusBlockchain(url, nsb_addr, nsb_abi_addr, EDB_PATH, nsb_bytecode_addr)
    # nsb = nsbt.handle

    # print(JsonRPC.send(url, HTTP_HEADER, JsonRPC.ethGetProof(nsb_addr, ["0x0"], "latest"))
    #       ['result']['storageProof'][0]['value'])
    #
    # print(nsb.funcs())
    # idx:  0
    #     block_address A
    #     storageHash 0x933b2499f931cef309f61259914d250c69446f55dcd9a6e85cebf0aed214ef36
    #     key 0x0275b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db9
    #     value 0x0100000000000000000000000000000000000000000000000000000000000000
Beispiel #14
0
def unlock_user(user):
    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?")
Beispiel #15
0
    print(ves.nsb.is_active_isc(isc.address))

    user_table = [(dapp_x, ves), (dapp_y, ves)]

    unlock_table = [enc_info_x, enc_info_relay_y]

    session_id = int(session_content[0])

    from uiputils.ethtools import AbiEncoder
    import random
    testnumber = random.randint(0, 100)
    tx = JsonRPC.eth_send_transaction({
        'from':
        dapp_x.info['http://127.0.0.1:8545']['address'],
        'to':
        "0x7c7b26fa65e091f7b9f23db77ad5f714f1dae5ea",
        "data":
        "0x67eb4a3c" + AbiEncoder.encodes([testnumber], ['uint']),
        "gas":
        hex(7999999)
    })
    dapp_x.unlockself('http://127.0.0.1:8545')
    console_logger.info('genuineValue set: {0}\n response: {1}'.format(
        testnumber, JsonRPC.send(tx, HTTP_HEADER, 'http://127.0.0.1:8545')))

    for idx, [u, v] in enumerate(user_table):
        # assert tx_intent is on ISC

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

        # compute on_chain_tx
        tx = tx_intents.intents[idx].jsonize()
Beispiel #16
0
def unlock_user(addr):
    unlock = JsonRPC.personal_unlock_account(addr, "123456", 20)
    response = JsonRPC.send(unlock, HTTP_HEADER, "http://127.0.0.1:8545")
    if not response['result']:
        raise ValueError("unlock failed. wrong password?")
Beispiel #17
0
import time

# ethereum modules
from hexbytes import HexBytes

# uip modules
from uiputils.ethtools import JsonRPC, Prover

EDB_PATH = "D:/Go Ethereum/data/geth/chaindata"
url = "http://127.0.0.1:8545"
HTTP_HEADER = {'Content-Type': 'application/json'}
nsb_addr = "0x85854fe3853b7A51576bFd78564Ec1993f8820d1"


if __name__ == '__main__':
    response = JsonRPC.send(JsonRPC.eth_get_proof(nsb_addr, ["0x0"], "latest"), HTTP_HEADER, url)['result']
    storageProof = response['storageProof'][0]

    time.sleep(5)

    try:
        prover = Prover(EDB_PATH)

        # prover.verify(HexBytes(keccak(HexBytes(uint64hexstring(int(storageProof['key'], 16))))).hex(),
        #               storageProof['value'],
        #               response['storageHash'],
        #               storageProof['proof']
        #               )
        prover.close()
    except Exception:
        raise Exception
Beispiel #18
0
def unlockself(address, password, chain_host):
    unlock = JsonRPC.personal_unlock_account(address, password, 20)
    response = JsonRPC.send(unlock, HTTP_HEADER, chain_host)
    if not response['result']:
        raise ValueError("unlock failed. wrong password?")
Beispiel #19
0
# ("0x076122c56613fc1e3ae97d715ca7cb6a35a934c6")

nsb_abi_dir = "../nsb/nsb.abi"
nsb_bytecode_dir = "../nsb/nsb.bin"
nsb_db_dir = "../nsb/actiondata"
tx = {"from": eth_base_addr, "gas": hex(400000)}

if __name__ == '__main__':
    nsbt = EthNetStatusBlockchain(eth_base_addr,
                                  host_addr,
                                  nsb_addr,
                                  nsb_abi_dir,
                                  "",
                                  nsb_bytecode_dir=nsb_bytecode_dir)
    nsb = nsbt.handle
    unlock = JsonRPC.personal_unlock_account(eth_base_addr, "123456", 20)
    tx_response = JsonRPC.send(unlock, HTTP_HEADER, "http://127.0.0.1:8545")

    # 0x64e604787cbf194841e7b68d7cd28786f6c9a0a3ab9f8b0a0e87cb4387ab0107
    # print(HexBytes(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00C').hex())

    #  = nsbt.addAction("123456781234567812345678123456781")
    # print(keccakhash)

    # print(nsbt.getAction("0xbc7e08dc633826033d13aaab04b8e2196cd944351ea0046dae500d4e027939e2"))

    # print(HexBytes(nsbt.getQueueL()).hex(), HexBytes(nsbt.getQueueR()).hex())
    # nsbt.watchProofPool()

    # print(nsb_addr)
    #
Beispiel #20
0
        print(tx)
        atte = u.init_attestation(tx, StateType.inited,
                                  int(session_content[0]), 0)
        # update

        # relay
        atte_rec = v.receive(atte.encode())
        rlped_data = v.sign_attestation(atte_rec)
        # update

        # check
        u.receive(rlped_data)

        # open
        unlock_user(tx['from'])
        tx_json = JsonRPC.eth_send_transaction(tx)
        print(
            JsonRPC.send(tx_json, HTTP_HEADER,
                         tx_intents.intents[idx].chain_host))
        # verify_transaction_state?
        atte = u.init_attestation(tx, StateType.open, int(session_content[0]),
                                  0)

        #
        v.receive(atte.encode())
        atte = v.init_attestation(tx, StateType.opened,
                                  int(session_content[0]), 0)

        # ves check
        ves.receive(atte.encode())
        # close