Exemplo n.º 1
0
    def get_contract(self):
        with open(self.sol_path) as f:
            contract_source_code = f.read()
        compiled_sol = compile_source(
            contract_source_code)  # Compiled source code
        contract_interface = compiled_sol['<stdin>:Lottery']
        w3 = Web3(web3.HTTPProvider(config["url"]))
        self.w3 = w3
        # set pre-funded account as sender
        acct = None
        if not self.account_key:
            if config["one_ether"].get("account"):
                w3.eth.defaultAccount = account.address
            else:
                w3.eth.defaultAccount = w3.eth.accounts[0]
                print("use the default accounts[0]")
        else:
            acct = w3.eth.account.privateKeyToAccount(self.account_key)
            w3.eth.defaultAccount = acct.address
        # Instantiate and deploy contract
        compiled = w3.eth.contract(abi=contract_interface['abi'],
                                   bytecode=contract_interface['bin'])

        # deploy contract
        if not self.contract_address:
            if not acct:
                raise Exception(
                    "account key should be set when there is no contract!")
            contract_ = w3.eth.contract(abi=contract_interface['abi'],
                                        bytecode=contract_interface['bin'])
            construct_txn = contract_.constructor().buildTransaction({
                'from':
                acct.address,
                'nonce':
                w3.eth.getTransactionCount(acct.address),
                'gasPrice':
                self.w3.eth.gasPrice
            })

            signed = acct.signTransaction(construct_txn)

            tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
            print("waiting for contract receipted", end="", flush=True)
            count = 0
            tx_receipt = None
            while not tx_receipt and (count < 300):
                time.sleep(1)
                tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
                print(".", end="", flush=True)
            print()
            if not tx_receipt:
                raise Exception("timeout for contract receipted!")
            self.contract_address = tx_receipt.contractAddress

        # Create the contract instance with the newly-deployed address
        self.contract = w3.eth.contract(
            address=self.contract_address,
            abi=contract_interface['abi'],
        )
        print("contract address: {}".format(self.contract_address))
Exemplo n.º 2
0
def connect(port=None, dev_mode=None):
    global w3, _buffered_accounts, send_rpc_mine_block_commands

    if port is None:
        ports = [7545, 8545]
    else:
        ports = port

    if w3 is None or not w3.isConnected():
        # large request timeout required for performance tests
        for p in ports:
            w3 = web3.Web3(
                web3.HTTPProvider(f"http://127.0.0.1:{p}",
                                  request_kwargs={"timeout": 60 * 10}))
            if w3.isConnected():
                if port is None:
                    send_rpc_mine_block_commands = p == 7545
                break
        _buffered_accounts = None

    if dev_mode:
        send_rpc_mine_block_commands = False

    assert w3.isConnected(), "Connecting to local Ethereum node failed!"
    return w3
Exemplo n.º 3
0
def main():
    parser = argparse.ArgumentParser(prog="check-balances")
    parser.add_argument("--endpoint", default=W3_ENDPOINT)
    subparsers = parser.add_subparsers(dest="command")

    show_balance_parser = subparsers.add_parser("balance")
    show_balance_parser.add_argument("token-address")
    show_balance_parser.add_argument("-a", "--account", default="0")

    transfer_parser = subparsers.add_parser("transfer")
    transfer_parser.add_argument("token-address")
    transfer_parser.add_argument("amount", type=int)
    transfer_parser.add_argument("-f", "--from", default="0")
    transfer_parser.add_argument("-t", "--to", default="1")

    allowance_parser = subparsers.add_parser("allowance")
    allowance_parser.add_argument("token-address")
    allowance_parser.add_argument("--spender")
    allowance_parser.add_argument("-a", "--account", default="0")

    args = vars(parser.parse_args())

    w3 = web3.Web3(web3.HTTPProvider(args["endpoint"]))
    manager = W3Manager(w3)

    if args["command"] == "balance":
        manager.show_balance(args["token-address"], args["account"])
    elif args["command"] == "transfer":
        manager.transfer_tokens(args["token-address"], args["from"],
                                args["to"], args["amount"])
    elif args["command"] == "allowance":
        manager.show_allowance(args["token-address"], args["account"],
                               args["spender"])
    else:
        print("no command passed")
Exemplo n.º 4
0
Arquivo: w32.py Projeto: tanzrok/Post
 def __init__(self):
     self.w3 = web3.Web3(web3.HTTPProvider(self.ganache_url))
     self.w3.eth.defaultAccount = self.w3.eth.accounts[0]
     print (self.w3.eth.accounts)
     self.contract = self.w3.eth.contract(
         address=self.address,
         abi=self.abi)
Exemplo n.º 5
0
def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():

            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)

            w3 = web3.Web3(web3.HTTPProvider(node_url))
            address = w3.personal.newAccount(raw_password)

            var = UserExt(userId=user,
                          address=address,
                          stockA=0,
                          stockB=0,
                          stockC=0,
                          stockD=0,
                          stockE=0)
            var.save()

            login(request, user)
            return redirect('index')
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})
Exemplo n.º 6
0
def connect(port=None, dev=None, poa=None):
    global w3, _buffered_accounts, send_rpc_mine_block_commands, _poa

    if port is None:
        ports = [7545, 8545]
    else:
        ports = port

    if w3 is None or not w3.isConnected():
        # large request timeout required for performance tests
        for p in ports:
            w3 = web3.Web3(web3.HTTPProvider(f"http://127.0.0.1:{p}", request_kwargs={"timeout": 60 * 1000}))

            if (_poa in [None, False]) and (poa or _poa):
                # print("using poa mode")
                w3 = web3.auto.gethdev.w3
                # w3.middleware_onion.inject(geth_poa_middleware, layer=0)
                _poa = True

            if w3.isConnected():
                if port is None:
                    send_rpc_mine_block_commands = p == 7545
                break
        _buffered_accounts = None

    if dev:
        send_rpc_mine_block_commands = True

    assert w3.isConnected(), "Connecting to local Ethereum node failed!"
    return w3
Exemplo n.º 7
0
 def web3_provider(self):
     w3 = web3.Web3(web3.HTTPProvider(self.ETH_RPC_PROVIDER))
     try:
         w3.eth.defaultAccount = self.node_key_store.address
     except Exception as e:
         logger.exception(e)
     return w3
Exemplo n.º 8
0
def get_contract():

    base_url = "https://raw.githubusercontent.com/adriamb/bettingon/96e26fa6faa883119c425c526a20cc542636c7a9/contracts"
    contract_addr = "0x7B77eBD4760D80A12586097ec1527ff8367a067f"

    src = "pragma solidity ^0.4.11;\n" + \
     get_and_filter(base_url+'/Directory.sol') + \
     get_and_filter(base_url+'/PriceUpdater.sol') + \
     get_and_filter(base_url+'/Bettingon.sol')

    compiled = solc.compile_source(src)

    w3 = web3.Web3(web3.HTTPProvider('http://localhost:8546'))

    contract_factory = web3.contract.construct_contract_factory(
        web3=w3, abi=compiled['<stdin>:Bettingon']['abi'])

    contract = contract_factory(contract_addr)

    try:
        contract.call().boat()
    except web3.exceptions.BadFunctionCallOutput:
        raise RuntimeError(
            'Cannot continue, seems that blockchain node is not yet sync.')

    return contract
Exemplo n.º 9
0
def get_web3(rpc_endpoint):
    if rpc_endpoint.startswith("ws:"):
        provider = web3.WebsocketProvider(rpc_endpoint)
    else:
        provider = web3.HTTPProvider(rpc_endpoint)

    return web3.Web3(provider)
Exemplo n.º 10
0
def index(request):
    user = UserExt.objects.get(userId=request.user)
    w3 = web3.Web3(web3.HTTPProvider(node_url))
    d = {}
    d["balance"] = w3.eth.getBalance(user.address)
    d["StockA"] = user.stockA
    d["StockB"] = user.stockB
    d["StockC"] = user.stockC
    d["StockD"] = user.stockD
    d["StockE"] = user.stockE
    d["address"] = user.address

    d["OtherUsers"] = UserExt.objects.exclude(userId=request.user)

    d2 = {
        "A": Stocks.objects.get(name="A").price,
        "B": Stocks.objects.get(name="B").price,
        "C": Stocks.objects.get(name="C").price,
        "D": Stocks.objects.get(name="D").price,
        "E": Stocks.objects.get(name="E").price
    }

    return render(request, 'index.html', {
        'userdict': d,
        'stockdict': d2,
    })
Exemplo n.º 11
0
class transaction():  
    with open("abi.txt", 'r') as file:
        abi = json.load(file)
        print('lohdasjfn lgnkjfdsbgjkasdn gjkadgj')
    contract_address = web3.Web3.toChecksumAddress("0xE736577B09beEE37C47D05abe0C64E520815ABF9")
    w3 = web3.Web3(web3.HTTPProvider('http://127.0.0.1:7545'))
    con = w3.eth.contract(address=contract_address, abi=abi)
    w3.eth.defaultAccount = w3.eth.accounts[0]
 
    def auth(self):
        login = '******'
        password = ''
        public_key = self.con.functions.logins(login).call()
        #Check login password
        if 1:
            self.w3.eth.defaultAccount = public_key

        return public_key
    def reg(self, address, login, fio, fiz_address, password):
        self.con.functions.add_user(login, fio, fiz_address).transact({'from': address})
    def set_admin(self):
        string = 'lll (0xc50De47A6E56f894645eddE455b347Cdc956cd2B)'
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.set_admin(address).transact()
    def del_admin(self):
        string = 'lll (0xc50De47A6E56f894645eddE455b347Cdc956cd2B)'
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        print(address)
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.del_admin(address).transact()
Exemplo n.º 12
0
def view_txns_user(request):
    txnList = []
    w3 = web3.Web3(web3.HTTPProvider(node_url))
    cI = w3.eth.contract(abi,
                         contract_address,
                         ContractFactoryClass=ConciseContract)
    user = UserExt.objects.get(userId=request.user)
    tmp = TxnDB.objects.filter(user=user)
    for i in tmp:
        buyer, seller, balance = cI.getTxn(i.txnID)
        t = {
            "id": i.txnID,
            "buyer": buyer,
            "seller": seller,
            "balance": balance,
            "stock": i.stock,
            "quantity": i.quantity
        }
        txnList.append(t)

    head = "MY TRANSACTIONS"
    return render(request, 'transactions.html', {
        'head': head,
        'transactions': txnList,
    })
Exemplo n.º 13
0
 def __init__(self, host='localhost', port='8545'):
     try:
         self.ethereum = web3.Web3(web3.HTTPProvider('{host}:{port}'.format(host=host, port=port)))
         self.ethereum.eth.blockNumber
         self.contract = None
     except InvalidSchema:
         logging.error('Cannot connect to ethereum provider!')
         raise EthereumConnectionError
Exemplo n.º 14
0
    def __init__(self):
        self.geth = web3.Web3(web3.HTTPProvider("HTTP://26.200.208.237:7545"))
        self.geth.eth.defaultAccount = self.geth.eth.accounts[0]
        print(self.geth.eth.accounts)
        self.cont = self.geth.eth.contract(address=self.address, abi=self.abi)

        for i in range(len(self.accounts())):
            self.cont.functions.add_user(self.accounts()[i]).transact()
Exemplo n.º 15
0
def connect():
    global w3
    if w3 is None or not w3.isConnected:
        # large request timeout require for performance tests
        w3 = web3.Web3(
            web3.HTTPProvider('http://127.0.0.1:8545',
                              request_kwargs={'timeout': 60 * 10}))
    assert w3.isConnected
    return w3
Exemplo n.º 16
0
def connect(port=8545):
    global w3
    if w3 is None or not w3.isConnected:
        # large request timeout required for performance tests
        w3 = web3.Web3(
            web3.HTTPProvider(f"http://127.0.0.1:{port}",
                              request_kwargs={"timeout": 60 * 10}))
    assert w3.isConnected
    return w3
Exemplo n.º 17
0
 def __init__(self, name: str, rpc_address: str, chain_id: int, b64_private_key: str):
     self.blockchain = "ethereum"
     self.name = name
     self.rpc_address = rpc_address
     self.chain_id = chain_id
     self.priv_key = eth_keys.keys.PrivateKey(base64.b64decode(b64_private_key))
     self.address = self.priv_key.public_key.to_checksum_address()
     self.w3 = web3.Web3(web3.HTTPProvider(self.rpc_address))
     # Set gas strategy
     self.w3.eth.setGasPriceStrategy(web3.gas_strategies.time_based.medium_gas_price_strategy)
Exemplo n.º 18
0
 def __init__(self, network, address, rpc_endpoint_url, safe_relay_url):
     """Initializes a Safe.
     """
     self.network = network
     self.address = address
     self.w3 = web3.Web3(web3.HTTPProvider(rpc_endpoint_url))
     # https://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority
     self.w3.middleware_stack.inject(geth_poa_middleware, layer=0)
     self.contract = get_safe_contract(w3=self.w3, address=self.address)
     self.safe_relay = Relay(safe_relay_url)
Exemplo n.º 19
0
 def _get_highest_known_block_infura(self):
     """Get the highest known block from Consensys Infura"""
     infura_uri = "https://mainnet.infura.io/%s" % (self.infura_api_key)
     try:
         infura_web3 = web3.Web3(web3.HTTPProvider(infura_uri))
         number = infura_web3.ifa.blockNumber
         return int(number)
     except:
         self.console.error("Could not retrieve from Infura.")
     return False
Exemplo n.º 20
0
 def is_valid_feedbk(self, net_id, usr_addr, msg_txt, sign):
     try:
         provider = web3.HTTPProvider(NETWORKS[net_id]['http_provider'])
         w3 = web3.Web3(provider)
         message = w3.sha3(text=msg_txt)
         message_hash = defunct_hash_message(primitive=message)
         recovered = str(w3.eth.account.recoverHash(message_hash, signature=sign))
         return str(usr_addr).lower() == recovered.lower()
     except Exception as e:
         print(repr(e))
         raise e
     return False
Exemplo n.º 21
0
def get_client() -> web3.Web3:
    client = web3.Web3(web3.HTTPProvider("http://127.0.0.1:7545"))

    if not client.isConnected():
        print("Not connected")
        raise RuntimeError("Not connected")

    client.middleware_onion.inject(web3.middleware.geth_poa_middleware,
                                   layer=0)
    print(f"Connected: {client.clientVersion}")

    return client
Exemplo n.º 22
0
    def __init__(self, u_addr):
        self.w3 = web3.Web3(web3.HTTPProvider('http://192.168.0.2:8545'))
        with open(f'{os.path.dirname(__file__)}/abi.txt', 'r') as f:
            abi = json.load(f)
            

        with open(f'{os.path.dirname(__file__)}/contract_address.txt', 'r') as f:
            contract_address = f.read()
        contract_address = web3.Web3.toChecksumAddress(contract_address)
        self.contract = self.w3.eth.contract(contract_address, abi=abi)
        self.u_addr = web3.Web3.toChecksumAddress(u_addr)
        self.w3.eth.defaultAccount(self.u_addr)
Exemplo n.º 23
0
class transaction():
    with open("C:/Users/wegas/workspace/Autorisation/abi.txt", 'r') as file:
        abi = json.load(file)
        print('lohdasjfn lgnkjfdsbgjkasdn gjkadgj')
    contract_address = web3.Web3.toChecksumAddress(
        "0x77e31a6550d5e0aac92b3c7264554CF781bbD897")
    w3 = web3.Web3(web3.HTTPProvider('http://127.0.0.1:7545'))
    con = w3.eth.contract(address=contract_address, abi=abi)
    w3.eth.defaultAccount = w3.eth.accounts[0]

    def auth(self):
        public_key = self.con.functions.logins(ContractApp.login).call()
        #Check login password
        if 1:
            self.w3.eth.defaultAccount = ContractApp.public_key

        return public_key

    def reg(self, address, login, fio, fiz_address, password):
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.add_user(login, fio,
                                    fiz_address).transact({'from': address})

    def set_admin(self, string):
        address = string
        """
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        """
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.set_admin(address).transact()

    def del_admin(self, string):
        address = string
        """
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        """
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.del_admin(address).transact()

    def set_postman(self, string):
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.set_postman(address).transact()

    def del_postman(self, string):
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.del_postman(address).transact()
Exemplo n.º 24
0
 def _get_provider(self) -> web3.HTTPProvider:
     # Maintain 'eth' and 'etc' values for backwords compatibility
     if self.network == "ETH_MAINNET":
         provider = Networks.Mainnet.value
     elif self.network == "ETH_ROPSTEN":
         provider = Networks.Ropsten.value
     elif self.network == "ETC_MAINNET":
         provider = Networks.Classic.value
     elif self.network == "ETC_MORDEN":
         provider = Networks.Morden.value
     else:
         raise RuntimeError("Invalid network specified.")
     return web3.HTTPProvider(provider)
Exemplo n.º 25
0
    def _init_web3(self, rpc_url, passwd):
        """
        Initialize Web3 and unlock the zeroth account.

        :param rpc_url: HTTP URL where the RPC server can be found
        :param passwd: passphrase for the zeroth account
        :return: Web3 object
        """

        w3 = web3.Web3(web3.HTTPProvider(rpc_url))
        w3.personal.unlockAccount(w3.eth.accounts[0], passwd, 0)
        if self.debug:
            print('Initialized Web3')
        return w3
Exemplo n.º 26
0
    def __init__(self, eth_node, contract_address, contract_abi):
        """

        :param eth_node: address of ethereum node (example: http://localhost:8545)
        :param contract_address: erc20 token contract address
        :param contract_abi: erc20 token contract ABI
        """
        self.eth_node = eth_node
        self.contract_address = contract_address
        self.contract_abi = contract_abi

        self.w3provider = web3.HTTPProvider(eth_node)
        self.w3 = web3.Web3(self.w3provider)
        self.erc20 = self.w3.eth.contract(contract_address, abi=contract_abi)
Exemplo n.º 27
0
 def __init__(self):
     # w3 = web3.Web3(web3.HTTPProvider("https://rinkeby.infura.io/xxxxxxxxx")) # Test network
     w3 = web3.Web3(web3.HTTPProvider(
         "https://api.myetherapi.com/eth"))  # Real network
     self._amc_contract = w3.eth.contract(
         abi=am_abi.amc_abi,
         # address="0xc4aB0302F2BeA6DE476614f7c20DaE8F35D03A08") # Test network
         address="0xc26aA9AD649C5Def6d7f94fc46667F70210fE565"
     )  # Real network
     self._am_ico_contract = w3.eth.contract(
         # abi=am_abi.test_am_ico_abi, # Test network
         abi=am_abi.am_ico_abi,  # Real network
         # address="0x9A0f9bdBAf42e98172F6CDC07caAFa9a7c75762c") # Test network
         address="0x4D8Cf569C2fd7C436F44dEa3763C6BF967358e8D"
     )  # Real network
    def __init__(self, config, metadata, options):
        self._config = config
        eth_rpc_endpoint = self._config.get("eth_rpc_endpoint",
                                            "https://mainnet.infura.io")
        provider = web3.HTTPProvider(eth_rpc_endpoint)
        self.web3 = web3.Web3(provider)
        self.mpe_contract = MPEContract(self.web3)
        self.account = Account(self.web3, self._config, self.mpe_contract)

        self.options = options
        self.metadata = metadata
        self.expiry_threshold = self.metadata["payment_expiration_threshold"]
        self._base_grpc_channel = self._get_grpc_channel()
        self.payment_channel_state_service_client = self._generate_payment_channel_state_service_client(
        )
        self.payment_channels = []
        self.last_read_block = 0
Exemplo n.º 29
0
    def get(self, request, address):
        key = '{}/balance'.format(address)
        cached = cache.get(key)
        if cached:
            return HttpResponse(cached, content_type='image/svg+xml')

        if not web3.Web3.isAddress(address):
            attrs = {'text': 'Invalid Address'}
            return render(request, self.template, attrs, content_type='image/svg+xml')

        provider = web3.Web3(web3.HTTPProvider(settings.PROVIDER_URL))
        balance = web3.Web3.fromWei(provider.eth.getBalance(address), 'ether')
        attrs = {
            'text': '{:.6f} Ether'.format(balance),
        }
        rendered = render_to_string(self.template, attrs)
        cache.set(key, rendered)
        return HttpResponse(rendered, content_type='image/svg+xml')
Exemplo n.º 30
0
class pnh():

    with open("C:/Users/wegas/workspace/WorldSkills/abi.txt", 'r') as file:
        abi = json.load(file)
    contract_address = web3.Web3.toChecksumAddress(
        "0x4E59E181C01Ca724F6014f4f0892Fd5098876Ef8")
    w3 = web3.Web3(web3.HTTPProvider('http://127.0.0.1:7545'))
    con = w3.eth.contract(address=contract_address, abi=abi)
    w3.eth.defaultAccount = w3.eth.accounts[0]

    def auth(self):
        login = '******'
        password = ''
        public_key = self.con.functions.logins(login).call()
        #Check login password
        if 1:
            self.w3.eth.defaultAccount = public_key

        return public_key

    def reg(self):
        address = web3.Web3.toChecksumAddress(
            '0xc50De47A6E56f894645eddE455b347Cdc956cd2B')
        login = '******'
        fio = 'manman'
        fiz_address = '22'
        password = ''
        self.con.functions.add_user(login, fio,
                                    fiz_address).transact({'from': address})

    def set_admin(self):
        string = 'lll (0xc50De47A6E56f894645eddE455b347Cdc956cd2B)'
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.set_admin(address).transact()

    def del_admin(self):
        string = 'lll (0xc50De47A6E56f894645eddE455b347Cdc956cd2B)'
        index = string.find('(')
        address = string[index + 1:len(string) - 1]
        print(address)
        address = web3.Web3.toChecksumAddress(address)
        self.con.functions.del_admin(address).transact()