Beispiel #1
0
# This Python file uses the following encoding: utf-8
#c++ python

# if__name__ == "__main__":
#     pass

from web3 import Web3
import web3
w3 = Web3(Web3.HTTPProvider("http://192.168.3.213:8545"))

def getblock():
    print(w3.eth.blockNumber)

def offlineSign(privkey, toaddress, amount, gas, price, nonce):
    print(privkey)
    pk = int(privkey,16)
    print(privkey)
    sendfrom = web3.eth.Account.privateKeyToAccount(pk)
    print(sendfrom)

    chktoaddress =web3.Web3.toChecksumAddress(toaddress)
    stx = sendfrom.signTransaction(dict(nonce = nonce,
    gasPrice = web3.Web3.toWei(price, 'ether'),
    gas =  web3.Web3.toWei(gas, 'ether'),
    to = chktoaddress,
    value = web3.Web3.toWei(amount, 'ether'),
    data = b'',
    )
    )
    print(stx)
    data = w3.eth.sendRawTransaction(stx.rawTransaction)
Beispiel #2
0
def connect():
    w3 = Web3(IPCProvider(get_default_ipc_path()))
    if w3.isConnected():
        return w3

    return False
Beispiel #3
0
from contracts import deploy
from crypto.dh_tuple import dh_create, dh_verify
from crypto.altbn128 import *
from observer import Observer, pedersen_c, H
from web3 import Web3, HTTPProvider
import unittest

provider = HTTPProvider('http://127.0.0.1:8545',
                        request_kwargs={'timeout': 10})
web3 = Web3(provider)
web3.eth.defaultAccount = web3.eth.accounts[0]


class TestObservableCommitments(unittest.TestCase):
    def test_update_commitment(self):
        a = randsn()
        p = randsn()
        A = multiply(G1, a)
        P = multiply(G1, p)
        contract = deploy(web3, 'TestPointUpdate', *(pasint(A), pasint(P)))
        u, e, _, P_ = dh_create(G1, P, a)
        b = contract.functions.verifyDHTuple(u, e, pasint(P_)).call()
        self.assertTrue(b)

    # target_a _> target_a
    # target_b _> target_b
    # target_c _> target_c
    # z -> u
    # u -> u
    # a -> x
    def test_commitment(self):
import web3
from web3 import Web3, HTTPProvider
import json
import sys
import urllib
from eth_account import Account

#connecting

with open("network.json") as file:
    rpc_url = json.loads(file.read())['rpcUrl']
web3 = Web3(HTTPProvider(rpc_url))


def get_adress(private_key):
    adress = Account.privateKeyToAccount("0x" + private_key)
    return adress


def balance_all(balance):
    currency = ["wei", "kwei", "mwei", "gwei", "szabo", "finney", "poa"]
    ind = 0
    while (balance > 10):
        balance /= 1000
        ind += 1
    if balance < 1:
        balance *= 1000
        ind -= 1
    balance = str(round(balance, 6))
    if balance[-1] == '0':
        balance = balance[:-2]
Beispiel #5
0
# -*- coding: utf-8 -*-
import json
import time
from web3 import Web3, HTTPProvider, TestRPCProvider
from solc import compile_source
from web3.contract import ConciseContract
import sys

host = sys.argv[1]
passwd = sys.argv[2]
contract_address = sys.argv[3]
behavior = sys.argv[4]

# web3.py instance
w3 = Web3(HTTPProvider('http://' + host + ':3000'))
abi = '[{"name": "endTime", "payable": false, "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "type": "function", "constant": true, "stateMutability": "view"}, {"name": "checkList", "payable": false, "inputs": [{"name": "_password", "type": "bytes32"}], "outputs": [{"name": "_List", "type": "address[10]"}], "type": "function", "constant": true, "stateMutability": "view"}, {"name": "standard", "payable": false, "inputs": [], "outputs": [{"name": "", "type": "string"}], "type": "function", "constant": true, "stateMutability": "view"}, {"name": "sendAnswer", "payable": false, "inputs": [{"name": "_answer", "type": "string"}], "outputs": [], "type": "function", "constant": false, "stateMutability": "nonpayable"}, {"name": "checkAnswer", "payable": false, "inputs": [{"name": "_password", "type": "bytes32"}], "outputs": [{"name": "_answer", "type": "string"}], "type": "function", "constant": true, "stateMutability": "view"}, {"name": "creationTime", "payable": false, "inputs": [], "outputs": [{"name": "", "type": "uint256"}], "type": "function", "constant": true, "stateMutability": "view"}, {"type": "constructor", "payable": false, "inputs": [{"name": "_answer", "type": "string"}, {"name": "_password", "type": "bytes32"}, {"name": "_duration", "type": "uint256"}], "stateMutability": "nonpayable"}]'
abi = json.loads(abi)

# Contract instance in concise mode

contract_instance = w3.eth.contract(abi,
                                    contract_address,
                                    ContractFactoryClass=ConciseContract)

if behavior == 'checkAnswer':
    outputA = contract_instance.checkAnswer(passwd)
    print("尚未公佈")
elif behavior == 'checkList':
    print(json.dumps(contract_instance.checkList(passwd)))
Beispiel #6
0
app.conf.beat_schedule = {
    "maintain_eth_balances": {
        "task": celery_utils.eth_endpoint('topup_wallets'),
        "schedule": 600.0
    },
}
app.conf.beat_schedule = {
    'third-party-transaction-sync': {
        'task':
        celery_utils.eth_endpoint('synchronize_third_party_transactions'),
        'schedule': 30,  # Every 30 seconds
    }
}

w3 = Web3(HTTPProvider(config.ETH_HTTP_PROVIDER))

w3_websocket = Web3(WebsocketProvider(config.ETH_WEBSOCKET_PROVIDER))

red = redis.Redis.from_url(config.REDIS_URL)

first_block_hash = w3.eth.getBlock(0).hash.hex()

persistence_module = SQLPersistenceInterface(red=red,
                                             session=session,
                                             first_block_hash=first_block_hash)

processor = EthTransactionProcessor(ethereum_chain_id=config.ETH_CHAIN_ID,
                                    gas_price_wei=w3.toWei(
                                        config.ETH_GAS_PRICE, 'gwei'),
                                    gas_limit=config.ETH_GAS_LIMIT,
Beispiel #7
0
	-> calculation of newL is done in the python code and not in the smart contract

"""

import json
import pandas as pd
import tools as tl
import numpy as np
import matplotlib.pyplot as plt
import pickle
from web3.middleware import geth_poa_middleware

#from web3.auto import web3 # IPC automatic connection
from web3 import Web3
node_url = "http://localhost:8000"
web3 = Web3(Web3.HTTPProvider(node_url, request_kwargs={'timeout': 5000}))

# PoA compatibility
web3.middleware_onion.inject(geth_poa_middleware, layer=0)

# set pre-funded account as sender
web3.eth.defaultAccount = web3.eth.accounts[0]
web3.geth.personal.unlockAccount(web3.eth.defaultAccount, "0000",
                                 0)  # unlock account permanently

# mining of all sealers nodes necessary
web3.geth.miner.start()

# gas counter initialization
gasSpend = 0
etherSpend = web3.eth.getBalance(web3.eth.defaultAccount)
Beispiel #8
0
def con2ETH(full_node_url):
    t_w = Web3(HTTPProvider(full_node_url))
    return t_w
Beispiel #9
0
#!/usr/bin/python3

from web3 import Web3, HTTPProvider, middleware
import sys
import json
import time
import yaml
from web3.gas_strategies.time_based import medium_gas_price_strategy, fast_gas_price_strategy, slow_gas_price_strategy

try:
    w3 = Web3(
        HTTPProvider(
            "https://kovan.infura.io/v3/12658a3bd98b410483b8cd44328533d0",
            request_kwargs={'timeout': 60}))
except Exception as e:
    print('\033[91m\033[1m' + 'Error : Could not connect to Provider' +
          '\033[0m\033[0m')
    print(e)
    exit()

w3.middleware_onion.add(middleware.time_based_cache_middleware)
w3.middleware_onion.add(middleware.latest_block_based_cache_middleware)
w3.middleware_onion.add(middleware.simple_cache_middleware)

try:
    uniswap_router2_address = Web3.toChecksumAddress(
        "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
    #Uniswap exchange contract abi
    with open("./abi/uniswap_router2_abi.json") as f:
        uniswap_router2_abi = json.load(f)
Beispiel #10
0
def getContract(item, network, address=None, prefix=""):
    abi = json.loads(open('bin/' + prefix +  item + '_sol_' + item + '.abi').read())
    bin = open('bin/' + prefix + item + '_sol_' +  item + '.bin').read()
    json_data=open('src/solc/contracts/' + item + '.json').read()
    data = json.loads(json_data)
    
    if address is None:
        address=data['networks'][network]['address']
    conf_c = web3.eth.contract(abi=abi, bytecode=bin)
    conf=conf_c(web3.toChecksumAddress(address))
    return conf

network='4'
port='8666'
#web3 = Web3(IPCProvider("~/.ethereum/rinkeby/geth.ipc"))
web3 = Web3(HTTPProvider('http://35.165.47.77:' + port ))
#web3 = Web3(HTTPProvider('https://rinkeby.infura.io/8BNRVVlo2wy7YaOLcKCR'))
address=web3.toChecksumAddress(web3.eth.coinbase)
address2=web3.toChecksumAddress(web3.eth.accounts[0])

print (address, address2)
gc=getContract('SmartKey',network)
io=getContract('PublicOffering',network)
amount=1000000000000000000 #1 ETH

print ('getBalance (eth) for address1',web3.eth.getBalance(address))
print ('getBalance (eth) for address2',web3.eth.getBalance(address2))
print (io.transact({ 'from': address2, 'value': amount}).loadSmartKey(address2))
print ('convertToToken', gc.call({ 'from': address2}).convertToToken(amount))
print ('getBalance', gc.call({ 'from': address2}).getBalance(address2))
print ('getSmartKey', gc.call({ 'from': address2 }).getSmartKey(address2))
Beispiel #11
0
    function setGreeting(string _greeting) public {
        greeting = _greeting;
    }

    function greet() constant returns (string) {
        GreetEvent()
        return greeting;
    }
}
'''

compiled_sol = compile_source(contract_source_code)  # Compiled source code
contract_interface = compiled_sol['<stdin>:Greeter']

# web3.py instance
w3 = Web3(TestRPCProvider())

# Instantiate and deploy contract
contract = w3.eth.contract(contract_interface['abi'], bytecode=contract_interface['bin'])

# Get transaction hash from deployed contract
tx_hash = contract.deploy(transaction={'from': w3.eth.accounts[0], 'gas': 410000})

# Get tx receipt to get contract address
tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
contract_address = tx_receipt['contractAddress']
print("contract_address=" + contract_address)
# Contract instance in concise mode
contract_instance = w3.eth.contract(contract_interface['abi'], contract_address, ContractFactoryClass=ConciseContract)

# Getters + Setters for web3.eth.contract object
Beispiel #12
0
    def __init__(self, args: list):
        # Define basic arguments
        parser = argparse.ArgumentParser(prog='plunger')
        parser.add_argument(
            "address",
            help="Ethereum address to check for pending transactions",
            type=str)
        parser.add_argument("--rpc-host",
                            help="JSON-RPC host (default: `localhost')",
                            default="localhost",
                            type=str)
        parser.add_argument("--rpc-port",
                            help="JSON-RPC port (default: `8545')",
                            default=8545,
                            type=int)
        parser.add_argument(
            "--gas-price",
            help="Gas price (in Wei) for overriding transactions",
            default=0,
            type=int)
        parser.add_argument(
            "--source",
            help=
            f"Comma-separated list of sources to use for pending transaction discovery"
            f" (available: {self.SOURCE_PARITY_TXQUEUE}, {self.SOURCE_JSONRPC_GETBLOCK})",
            type=lambda x: x.split(','),
            required=True)
        parser.add_argument("-j",
                            '--json',
                            help="Generate result as JSON",
                            dest='json',
                            action='store_true')

        # Define mutually exclusive action arguments
        action = parser.add_mutually_exclusive_group(required=True)
        action.add_argument('--list',
                            help="List pending transactions",
                            dest='list',
                            action='store_true')
        action.add_argument('--wait',
                            help="Wait for the pending transactions to clear",
                            dest='wait',
                            action='store_true')
        action.add_argument(
            '--override-with-zero-txs',
            help="Override the pending transactions with zero-value txs",
            dest='override',
            action='store_true')

        # Define arguments for smart gas client
        parser.add_argument("-s",
                            '--smart-gas',
                            help="Use smart gas strategy to plunge",
                            dest='smart_gas',
                            action='store_true')
        parser.add_argument("--ethgasstation-api-key",
                            type=str,
                            default=None,
                            help="ethgasstation API key")
        parser.add_argument("--etherscan-api-key",
                            type=str,
                            default=None,
                            help="etherscan API key")
        parser.add_argument("--poanetwork-url",
                            type=str,
                            default=None,
                            help="Alternative POANetwork URL")

        parser.add_argument(
            "--eth-key",
            type=str,
            help=
            "Ethereum private key to use (e.g. 'key_file=aaa.json,pass_file=aaa.pass') for unlocking account"
        )

        # Parse the arguments, validate source
        self.arguments = parser.parse_args(args)

        # Initialize pending transactions list
        self.transactions = []

        # Initialize web3.py
        if self.arguments.rpc_host.startswith("http"):
            endpoint_uri = f"{self.arguments.rpc_host}:{self.arguments.rpc_port}"
        else:
            endpoint_uri = f"http://{self.arguments.rpc_host}:{self.arguments.rpc_port}"
        self.web3 = Web3(HTTPProvider(endpoint_uri=endpoint_uri))
        self.web3.eth.defaultAccount = self.arguments.address
        if self.arguments.eth_key:
            register_key(self.web3, self.arguments.eth_key)

        if self.arguments.smart_gas:
            self.gas_client = Aggregator(
                refresh_interval=60,
                expiry=600,
                ethgasstation_api_key=self.arguments.ethgasstation_api_key,
                poa_network_alt_url=self.arguments.poanetwork_url,
                etherscan_api_key=self.arguments.etherscan_api_key,
                gasnow_app_name="makerdao/plunger")

        self.validate_sources(self.web3)
def get_contract():
    w3 = Web3(Web3.HTTPProvider(config.config.get_web3_provider()))
    with open(config.config.CONTRACT_ABI_FILENAME) as json_file:
        abi = json.load(json_file)
    return w3.eth.contract(address=config.config.CONTRACT_ADDRESS, abi=abi)
Beispiel #14
0
from flask import Flask, render_template, url_for
from web3.auto import w3
from web3 import Web3, HTTPProvider
import json

ADDRESS = '0xde961a60602afc50dfdcc533dd164061bb1fd6e7'  # Address where the contract is deployed.

app = Flask(__name__)
web3 = Web3(HTTPProvider('http://localhost:8545'))
eipAddress = web3.toChecksumAddress(ADDRESS)
abi = {
    "constant":
    False,
    "inputs": [{
        "name": "_fName",
        "type": "string"
    }, {
        "name": "_age",
        "type": "uint256"
    }],
    "name":
    "setInfo",
    "outputs": [],
    "payable":
    False,
    "stateMutability":
    "nonpayable",
    "type":
    "function"
}, {
    "constant": True,
Beispiel #15
0
def run_app(
    address,
    keystore_path,
    gas_price,
    eth_rpc_endpoint,
    registry_contract_address,
    secret_registry_contract_address,
    discovery_contract_address,
    listen_address,
    mapped_socket,
    max_unresponsive_time,
    api_address,
    rpc,
    sync_check,
    console,
    password_file,
    web_ui,
    datadir,
    transport,
    matrix_server,
    network_id,
    network_type,
    extra_config=None,
    **kwargs,
):
    # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument

    from raiden.app import App

    if not assert_sqlite_version():
        log.error('SQLite3 should be at least version {}'.format(
            '.'.join(SQLITE_MIN_REQUIRED_VERSION), ))
        sys.exit(1)

    if transport == 'udp' and not mapped_socket:
        raise RuntimeError('Missing socket')

    address_hex = to_normalized_address(address) if address else None
    address_hex, privatekey_bin = prompt_account(address_hex, keystore_path,
                                                 password_file)
    address = to_canonical_address(address_hex)

    (listen_host, listen_port) = split_endpoint(listen_address)
    (api_host, api_port) = split_endpoint(api_address)

    if datadir is None:
        datadir = os.path.join(os.path.expanduser('~'), '.raiden')

    config = deepcopy(App.DEFAULT_CONFIG)
    if extra_config:
        merge_dict(config, extra_config)

    config['transport']['udp']['host'] = listen_host
    config['transport']['udp']['port'] = listen_port
    config['console'] = console
    config['rpc'] = rpc
    config['web_ui'] = rpc and web_ui
    config['api_host'] = api_host
    config['api_port'] = api_port
    if mapped_socket:
        config['socket'] = mapped_socket.socket
        config['transport']['udp']['external_ip'] = mapped_socket.external_ip
        config['transport']['udp'][
            'external_port'] = mapped_socket.external_port
    config['transport_type'] = transport
    config['transport']['matrix']['server'] = matrix_server
    config['transport']['udp'][
        'nat_keepalive_retries'] = DEFAULT_NAT_KEEPALIVE_RETRIES
    timeout = max_unresponsive_time / DEFAULT_NAT_KEEPALIVE_RETRIES
    config['transport']['udp']['nat_keepalive_timeout'] = timeout

    privatekey_hex = hexlify(privatekey_bin)
    config['privatekey_hex'] = privatekey_hex

    parsed_eth_rpc_endpoint = urlparse(eth_rpc_endpoint)
    if not parsed_eth_rpc_endpoint.scheme:
        eth_rpc_endpoint = f'http://{eth_rpc_endpoint}'

    web3 = Web3(HTTPProvider(eth_rpc_endpoint))

    try:
        node_version = web3.version.node  # pylint: disable=no-member
    except ConnectTimeout:
        raise EthNodeCommunicationError(
            "Couldn't connect to the ethereum node")

    supported, _ = is_supported_client(node_version)
    if not supported:
        click.secho(
            'You need a Byzantium enabled ethereum node. Parity >= 1.7.6 or Geth >= 1.7.2',
            fg='red',
        )
        sys.exit(1)

    rpc_client = JSONRPCClient(
        web3,
        privatekey_bin,
        gas_price_strategy=gas_price,
    )

    blockchain_service = BlockChainService(privatekey_bin, rpc_client)

    net_id = blockchain_service.network_id
    if net_id != network_id:
        if network_id in ID_TO_NETWORKNAME and net_id in ID_TO_NETWORKNAME:
            click.secho(
                f"The chosen ethereum network '{ID_TO_NETWORKNAME[network_id]}' "
                f"differs from the ethereum client '{ID_TO_NETWORKNAME[net_id]}'. "
                "Please update your settings.",
                fg='red',
            )
        else:
            click.secho(
                f"The chosen ethereum network id '{network_id}' differs from the "
                f"ethereum client '{net_id}'. "
                "Please update your settings.",
                fg='red',
            )
        sys.exit(1)

    config['chain_id'] = network_id

    if network_type == 'main':
        config['network_type'] = NetworkType.MAIN
        # Forcing private rooms to true for the mainnet
        config['transport']['matrix']['private_rooms'] = True
    else:
        config['network_type'] = NetworkType.TEST

    network_type = config['network_type']
    chain_config = {}
    contract_addresses_known = False
    contract_addresses = dict()
    if net_id in ID_TO_NETWORK_CONFIG:
        network_config = ID_TO_NETWORK_CONFIG[net_id]
        not_allowed = (NetworkType.TEST not in network_config
                       and network_type == NetworkType.TEST)
        if not_allowed:
            click.secho(
                'The chosen network {} has no test configuration but a test network type '
                'was given. This is not allowed.'.format(
                    ID_TO_NETWORKNAME[network_id], ),
                fg='red',
            )
            sys.exit(1)

        if network_type in network_config:
            chain_config = network_config[network_type]
            contract_addresses = chain_config['contract_addresses']
            contract_addresses_known = True

    if sync_check:
        check_synced(blockchain_service)

    contract_addresses_given = (registry_contract_address is not None and
                                secret_registry_contract_address is not None
                                and discovery_contract_address is not None)

    if not contract_addresses_given and not contract_addresses_known:
        click.secho(
            f"There are no known contract addresses for network id '{net_id}'. "
            "Please provide them in the command line or in the configuration file.",
            fg='red',
        )
        sys.exit(1)

    try:
        token_network_registry = blockchain_service.token_network_registry(
            registry_contract_address
            or contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], )
    except ContractVersionMismatch:
        handle_contract_version_mismatch('token network registry',
                                         registry_contract_address)
    except AddressWithoutCode:
        handle_contract_no_code('token network registry',
                                registry_contract_address)
    except AddressWrongContract:
        handle_contract_wrong_address('token network registry',
                                      registry_contract_address)

    try:
        secret_registry = blockchain_service.secret_registry(
            secret_registry_contract_address
            or contract_addresses[CONTRACT_SECRET_REGISTRY], )
    except ContractVersionMismatch:
        handle_contract_version_mismatch('secret registry',
                                         secret_registry_contract_address)
    except AddressWithoutCode:
        handle_contract_no_code('secret registry',
                                secret_registry_contract_address)
    except AddressWrongContract:
        handle_contract_wrong_address('secret registry',
                                      secret_registry_contract_address)

    database_path = os.path.join(
        datadir,
        f'node_{pex(address)}',
        f'netid_{net_id}',
        f'network_{pex(token_network_registry.address)}',
        f'v{RAIDEN_DB_VERSION}_log.db',
    )
    config['database_path'] = database_path

    print(
        '\nYou are connected to the \'{}\' network and the DB path is: {}'.
        format(
            ID_TO_NETWORKNAME.get(net_id) or net_id,
            database_path,
        ), )

    discovery = None
    if transport == 'udp':
        check_discovery_registration_gas(blockchain_service, address)
        try:
            dicovery_proxy = blockchain_service.discovery(
                discovery_contract_address
                or contract_addresses[CONTRACT_ENDPOINT_REGISTRY], )
            discovery = ContractDiscovery(
                blockchain_service.node_address,
                dicovery_proxy,
            )
        except ContractVersionMismatch:
            handle_contract_version_mismatch('discovery',
                                             discovery_contract_address)
        except AddressWithoutCode:
            handle_contract_no_code('discovery', discovery_contract_address)
        except AddressWrongContract:
            handle_contract_wrong_address('discovery',
                                          discovery_contract_address)

        throttle_policy = TokenBucket(
            config['transport']['udp']['throttle_capacity'],
            config['transport']['udp']['throttle_fill_rate'],
        )

        transport = UDPTransport(
            discovery,
            mapped_socket.socket,
            throttle_policy,
            config['transport']['udp'],
        )
    elif transport == 'matrix':
        try:
            transport = MatrixTransport(config['transport']['matrix'])
        except RaidenError as ex:
            click.secho(f'FATAL: {ex}', fg='red')
            sys.exit(1)
    else:
        raise RuntimeError(f'Unknown transport type "{transport}" given')

    raiden_event_handler = RaidenEventHandler()

    try:
        start_block = chain_config.get(START_QUERY_BLOCK_KEY, 0)
        raiden_app = App(
            config=config,
            chain=blockchain_service,
            query_start_block=start_block,
            default_registry=token_network_registry,
            default_secret_registry=secret_registry,
            transport=transport,
            raiden_event_handler=raiden_event_handler,
            discovery=discovery,
        )
    except RaidenError as e:
        click.secho(f'FATAL: {e}', fg='red')
        sys.exit(1)

    try:
        raiden_app.start()
    except RuntimeError as e:
        click.secho(f'FATAL: {e}', fg='red')
        sys.exit(1)
    except filelock.Timeout:
        name_or_id = ID_TO_NETWORKNAME.get(network_id, network_id)
        click.secho(
            f'FATAL: Another Raiden instance already running for account {address_hex} on '
            f'network id {name_or_id}',
            fg='red',
        )
        sys.exit(1)

    return raiden_app
Beispiel #16
0
 def setup_method(self):
     self.web3 = Web3(EthereumTesterProvider())
     self.web3.eth.defaultAccount = self.web3.eth.accounts[0]
     self.dsvalue = DSValue.deploy(self.web3)
import argparse
import logging

from ethereum.utils import checksum_encode, privtoaddr
from web3 import HTTPProvider, Web3
from web3.middleware import geth_poa_middleware
import settings
from utils import load_contract_interface, read_addresses_from_file

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

w3 = Web3(HTTPProvider(settings.NODE_URL))
w3.middleware_stack.inject(geth_poa_middleware, layer=0)

OLY_ABI = load_contract_interface('contracts/OlympiaToken.json')
STANDARD_TOKEN_ABI = load_contract_interface('contracts/StandardToken.json')
ETH_SPLITTER_ABI = load_contract_interface('contracts/EtherSplitter.json')
TOKEN_SPLITTER_ABI = load_contract_interface('contracts/TokenSplitter.json')

OLY_CONTRACT = w3.eth.contract(settings.OLY_ADDRESS, abi=OLY_ABI['abi'])
RDN_CONTRACT = w3.eth.contract(settings.RDN_ADDRESS,
                               abi=STANDARD_TOKEN_ABI['abi'])
ETH_SPLITTER_CONTRACT = w3.eth.contract(settings.ETH_SPLITTER_ADDRESS,
                                        abi=ETH_SPLITTER_ABI['abi'])
TOKEN_SPLITTER_CONTRACT = w3.eth.contract(settings.TOKEN_SPLITTER_ADDRESS,
                                          abi=TOKEN_SPLITTER_ABI['abi'])

OLY_PER_ADDRESS = w3.toWei(1, 'ether')
ETHER_PER_ADDRESS = w3.toWei(0.0001, 'ether')
RDN_PER_ADDRESS = w3.toWei(1, 'ether')
Beispiel #18
0
def web3(eth_tester_provider):
    _web3 = Web3(eth_tester_provider)
    return _web3
Beispiel #19
0
import json
import time
import ethereum
import web3
from flask import Flask, request
from flask_restful import Resource, Api, abort

from web3 import Web3, HTTPProvider
w3 = Web3(HTTPProvider("http://127.0.0.1:7545"))

w3.eth.enable_unaudited_features()

app = Flask(__name__)
api = Api(app)

Abi = """[ { "constant": false, "inputs": [ { "name": "_procedureId", "type": "uint256" }, { "name": "_priceInTokens", "type": "uint256" } ], "name": "changeProcedurePrice", "outputs": [ { "name": "_procedurePriceChanged", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "_provider", "type": "address" } ], "name": "whiteListAnyProvider", "outputs": [ { "name": "_whiteListed", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "viewAllProviders", "outputs": [ { "name": "", "type": "address[]" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "_provider", "type": "address" }, { "name": "_blocknumber", "type": "uint256" }, { "name": "_procedureId", "type": "uint256" } ], "name": "checkProcedurePriceByBlock", "outputs": [ { "name": "_procedurePriceAtBlokcnumber", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "uint256" } ], "name": "providers", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_provider", "type": "address" }, { "name": "_procedureId", "type": "uint256" } ], "name": "approveProcedureListing", "outputs": [ { "name": "_procedureApproved", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "_provider", "type": "address" } ], "name": "applyForWhiteListing", "outputs": [ { "name": "_applied", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "contractOwner", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_procedureId", "type": "uint256" }, { "name": "_priceInTokens", "type": "uint256" } ], "name": "listProcedure", "outputs": [ { "name": "_procedureListed", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "_provider", "type": "address" } ], "name": "viewProcedures", "outputs": [ { "name": "", "type": "uint256[]" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "_provider", "type": "address" } ], "name": "checkIfProviderExists", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "_provider", "type": "address" }, { "name": "_procedureId", "type": "uint256" } ], "name": "checkCurrentProcedurePrice", "outputs": [ { "name": "_procedurePrice", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_provider", "type": "address" } ], "name": "appliedForWhitelisting", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_provider", "type": "address" } ], "name": "whiteListed", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_provider", "type": "address" }, { "indexed": true, "name": "_procedureId", "type": "uint256" } ], "name": "procedureListedSuccess", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_provider", "type": "address" }, { "indexed": true, "name": "_procedureId", "type": "uint256" } ], "name": "procedureApproved", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_provider", "type": "address" }, { "indexed": true, "name": "_procedureId", "type": "uint256" }, { "indexed": true, "name": "_priceChangedTo", "type": "uint256" } ], "name": "procedurePriceChanged", "type": "event" } ]"""

#Enter your deployed contract address here
contract_address = Web3.toChecksumAddress(
    "0x46a4e325f2aa8af41b9b7f2b2ebf744408610a4a")
contract = w3.eth.contract(address=contract_address, abi=Abi)


class applyForWhiteListing(Resource):
    def post(self):
        address = request.json["address"]
        wallet_address = request.json["wallet_address"]
        wallet_private_key = request.json["Private_key"]
        nonce = w3.eth.getTransactionCount(wallet_address)

        txn_dict = contract.functions.applyForWhiteListing(
Beispiel #20
0
import requests
from web3 import Web3, HTTPProvider
from app import mongo
import uuid
import time
from bs4 import BeautifulSoup
from urllib.request import urlopen

web3 = Web3(
    HTTPProvider(
        endpoint_uri="https://rinkeby.infura.io/KbuOINU0Q1pTnO7j30hw"))

RUB_QIWI = 'RUB (QIWI)'
ETH = 'ETH'

TR_GAS_LIMIT = 21000
# set once gas price. In future make it updateable
gas_price = web3.eth.gasPrice


def _send_ethereum_transaction(
    private_key,
    to_address,
    amount_wei,
    only_estimate=False,
):
    '''
    low level method sending eth
    :param private_key:
    :param to_address:
    :param amount_wei:
from flask_cors import CORS
from web3 import Web3
from npre import bbs98
import base64

parser = reqparse.RequestParser()
pre = bbs98.PRE()

app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy   dog'
app.config['CORS_HEADERS'] = 'Content-Type'

cors = CORS(app, resources={r"*": {"origins": "*"}})

# w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545"))
w3 = Web3(Web3.HTTPProvider("http://ganachecli:8545"))
w3.eth.defaultAccount = w3.eth.accounts[1]

sw3 = Web3(Web3.HTTPProvider("http://ganachecli:8545"))
w3.eth.defaultAccount = w3.eth.accounts[1]

with open("data.json", 'r') as f:
    datastore = json.load(f)
    abi = datastore["abi"]
    contract_address = datastore["contract_address"]

with open("sdata.json", 'r') as sf:
    sdatastore = json.load(sf)
    sabi = sdatastore["abi"]
    scontract_address = sdatastore["contract_address"]
Beispiel #22
0
from web3 import Web3
w3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io/v3/address"))

try:
    signed_txn = w3.eth.account.signTransaction(
        dict(nonce=w3.eth.getTransactionCount('address'),
             gasPrice=w3.eth.gasPrice,
             gas=100000,
             to='to',
             value=Web3.toWei(0.1, 'ether')), b'binary')

    w3.eth.sendRawTransaction(signed_txn.rawTransaction)
except ValueError:
    print('a')
Beispiel #23
0
                suppress_callback_exceptions=True)

CONTENT_STYLE = {
    "margin-left": "2rem",
    "margin-right": "2rem",
    "padding": "2rem 1rem",
}
auth = dash_auth.BasicAuth(app, VALID_USERNAME_PASSWORD_PAIRS)

RB_LOGO = "https://raw.githubusercontent.com/MKallun/Rice-in-a-Block/master/108155783_584586912419739_2665953725697700139_n%20(2).png"

# Blockchain stuff here
#========================================================

ganache_url = "HTTP://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))

web3.eth.defaultAccount = web3.eth.accounts[0]

abi = json.loads(
    '[{"inputs":[{"internalType":"string","name":"_UserName","type":"string"}],"name":"Login","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_UserName","type":"string"},{"internalType":"string","name":"_Password","type":"string"}],"name":"Register","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_User","type":"string"},{"internalType":"string","name":"_Manufacturer","type":"string"},{"internalType":"string","name":"_Brand","type":"string"},{"internalType":"string","name":"_Area","type":"string"},{"internalType":"string","name":"_Status","type":"string"},{"internalType":"string","name":"_StatusRecieved","type":"string"},{"internalType":"uint256","name":"_StatusWeight","type":"uint256"},{"internalType":"uint256","name":"_Date","type":"uint256"},{"internalType":"uint256","name":"_Year","type":"uint256"},{"internalType":"uint256","name":"_Month","type":"uint256"},{"internalType":"uint256","name":"_Day","type":"uint256"},{"internalType":"uint256","name":"_Weight","type":"uint256"},{"internalType":"uint256","name":"_Price","type":"uint256"}],"name":"enterRiceInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getArea","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getBrand","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getDate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getDay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getManu","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getMonth","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getStatus","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getStatusRecieved","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getStatusWeight","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTransID","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getUser","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getWeight","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_StoreId","type":"uint256"}],"name":"getYear","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"newcount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"transactionCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]'
)

# needs to be changed to match address in remix solidity
address = web3.toChecksumAddress("0xF5Aeb9F211522A8eeAD06A1c105DeceCbB8339a2")

contract = web3.eth.contract(address=address, abi=abi)

# Webpage stuff
#========================================================
# Navbar
Beispiel #24
0
from web3 import Web3, IPCProvider

w3 = Web3(IPCProvider())

for i in range(0, 256):
    if (w3.solidityKeccak(['uint8'], [i]).hex(
    ) == "0xdb81b4d58595fbbbb592d3661a34cdca14d7ab379441400cbfa1b78bc447c365"):
        print("hash cracked: ", i)
Beispiel #25
0
from web3 import Web3
from eth_account import Account
import json

w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))

CONTRACT_ADDR = '0x51121d4632647Bb828F7B10D5AD3633b75316F29'

CONTRACT_ABI = json.loads("""[ 
  {
    "constant": true,
    "inputs": [
      {
        "name": "_username",
        "type": "string"
      },
      {
        "name": "_password",
        "type": "string"
      }
    ],
    "name": "checkUserData",
    "outputs": [
      {
        "name": "",
        "type": "bool"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function",
Beispiel #26
0

def alert():
    print(
        'Anomaly detected! If nothing extraordinary as a blackout happened, the chances that you were hacked are very high.'
    )


print(
    'Attention: someone could be able to change the source code of this tool.')
print(
    'Please, upload a new version of this tool each time you need to check the integrity of your system. Thank you.\n'
)

w3 = Web3(
    Web3.HTTPProvider(
        'https://ropsten.infura.io/v3/8f283916dfab4e8e8fc2adf4c4a94127')
)  # testnet
configurationFile = 'gianoConfiguration.json'

with open(configurationFile) as jsonFile:
    data = json.load(jsonFile)
files = {}
logs = glob.glob("%s/*.json" % (data['logsPath']))
counter = 1
previousLogHash = None
for number in range(len(logs), 0, -1):
    log = 'logs/%s.json' % (number)
    print("Checking (%s/%s)" % (counter, len(logs)))
    if previousLogHash and previousLogHash != sha256(log):
        alert()
        break
Beispiel #27
0
import json
import web3
import requests
import time

from web3 import Web3, IPCProvider, TestRPCProvider
from solc import compile_source
from web3.contract import ConciseContract

# Loading the Hydro Smart Contract ABI
# Note this is the testnet ABI which is slightly different than the mainnet version
with open('abi.json') as abi_json:
    HydroABI = json.load(abi_json)

# This will need to point to your geth node
w3 = Web3(IPCProvider('{your geth node}'))

# This is the testnet address on Rinkeby. Replace with mainnet address when you are finished testing
contract_address = '{mainnet or testnet address here}'
hydroConctract = w3.eth.contract(HydroABI,
                                 contract_address,
                                 ContractFactoryClass=ConciseContract)

w3.personal.unlockAccount(w3.eth.accounts[0], '{your account password}')

# Uncomment this to get more hydro tokens in the testnet
# print(hydroConctract.getMoreTokens(transact={'from':w3.eth.accounts[0]}))

headers = {"Content-type": "application/json"}

# Use your Hydro API username and key here
import os, sys, json
_PATH = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.append(_PATH)

from web3 import Web3
from util import extract_key_from_keyfile

# w3 = Web3(Web3.IPCProvider("./blockchain/geth.ipc"))
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))

account_list = []
password = ['coinbase', 'n1', 'n2']
for i in password :
    privKey = extract_key_from_keyfile(_PATH + '/keyFile/'+i+'.json', i.encode())

    with open(_PATH + '/keyFile/'+i+'.json', 'r') as f:
        key_file = json.load(f)

    print(i + ": ")
    print("accout : ", '0x' +key_file['address'])
    print("privKey : ", privKey.hex())
    print()
Beispiel #29
0
                    type=int,
                    help='The maximum number of workers.')
parser.add_argument('--ipc-path',
                    required=True,
                    type=str,
                    help='The full path to the ipc socket file.')
parser.add_argument('--ipc-timeout',
                    default=300,
                    type=int,
                    help='The timeout in seconds for ipc calls.')
parser.add_argument('-t',
                    '--tokens',
                    default=None,
                    type=str,
                    nargs='+',
                    help='The list of token addresses to filter by.')

args = parser.parse_args()

job = ExportErc20TransfersJob(
    start_block=args.start_block,
    end_block=args.end_block,
    batch_size=args.batch_size,
    web3=ThreadLocalProxy(
        lambda: Web3(IPCProvider(args.ipc_path, timeout=args.ipc_timeout))),
    item_exporter=export_erc20_transfers_job_item_exporter(args.output),
    max_workers=args.max_workers,
    tokens=args.tokens)

job.run()
Beispiel #30
0
class TestRnsPy(unittest.TestCase):
    """
    Test methods of interface to the RSK Name Service.
    """

    def test_resolve_domain_public_resolver(self):
        result = rnspy.addr(lumino_domain)
        self.assertEqual(result, "0x3278deEd4eE3DE26Bb53fFb82f4Be82a6bB66D19")

    def test_resolve_domain_multichain_resolver(self):
        result = rnspy.addr(test_domain)
        self.assertEqual(result, "0x3278deEd4eE3DE26Bb53fFb82f4Be82a6bB66D19")

    def test_resolve_domain_multichain_resolver_chain_id(self):
        result = rnspy.chain_addr(test_domain, RSK_CHAIN_ID)
        self.assertEqual(result, '')


if __name__ == '__main__':
    rpc_endpoint = "http://localhost:4444"
    web3 = Web3(Web3.HTTPProvider(rpc_endpoint))
    rnspy = RnsPy(web3, REGTEST_ENV)
    rnspy.set_public_resolver(REGTEST_PUBLIC_RESOLVER_ADDRESS)
    rnspy.set_rns(REGTEST_RNS_ADDRESS)
    rnspy.set_multichain_resolver(REGTEST_MULTICHAIN_RESOLVER_ADDRESS)

    lumino_domain = "lumino.rsk"
    test_domain = "testdomain.rsk"
    unittest.main()