Beispiel #1
0
def ethhack():
    # My ghetto load balancing
    nodes = [
        Web3(KeepAliveRPCProvider(host='geth', port='8545')),
        Web3(KeepAliveRPCProvider(host='parity', port='8545'))
    ]
    node = random.randint(0, 1)
    web3 = nodes[node]
    while True:
        keccak = sha3.keccak_256()
        private = SigningKey.generate(curve=SECP256k1)
        public = private.get_verifying_key().to_string()
        keccak.update(public)
        address = "0x{}".format(keccak.hexdigest()[24:])
        try:
            balance = web3.eth.getBalance(address)
        except:
            try:
                web3 = nodes[int(not node)]
                balance = web3.eth.getBalance(address)
            except:
                balance = 1000000000000000000
        if balance > 0:
            balance = balance / 1000000000000000000
            sql_upload(private.to_string().hex(), address, balance)
Beispiel #2
0
 def __calc_balance(usr):
     web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
     user = User.objects.get(username=usr.kwargs.get("username"))
     print(user.wallet)  #walletidを確認する用に便利なので、少し残しておく
     user.wallet.balance = web3.eth.getBalance(user.wallet.num) / 100000
     user.wallet.save()
     return 0
Beispiel #3
0
def getWindowTotal():
    try:
        # Connect
        web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))

        # EOS ICO contract's address and the ABI
        addr = '0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf'
        abi = json.loads(
            '[{"constant":true,"inputs":[{"name":"","type":"uint256"},{"name":"","type":"address"}],"name":"claimed","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"time","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint128"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"foundersAllocation","outputs":[{"name":"","type":"uint128"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"day","type":"uint256"}],"name":"claim","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"foundersKey","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"},{"name":"","type":"address"}],"name":"userBuys","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"day","type":"uint256"}],"name":"createOnDay","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"freeze","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"keys","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"startTime","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"dailyTotals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"buy","outputs":[],"payable":true,"type":"function"},{"constant":true,"inputs":[],"name":"openTime","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"EOS","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"today","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"eos","type":"address"}],"name":"initialize","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"createFirstDay","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"claimAll","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"timestamp","type":"uint256"}],"name":"dayFor","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"day","type":"uint256"},{"name":"limit","type":"uint256"}],"name":"buyWithLimit","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[],"name":"collect","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"numberOfDays","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"key","type":"string"}],"name":"register","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"createPerDay","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"_numberOfDays","type":"uint256"},{"name":"_totalSupply","type":"uint128"},{"name":"_openTime","type":"uint256"},{"name":"_startTime","type":"uint256"},{"name":"_foundersAllocation","type":"uint128"},{"name":"_foundersKey","type":"string"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"window","type":"uint256"},{"indexed":false,"name":"user","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"LogBuy","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"window","type":"uint256"},{"indexed":false,"name":"user","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"LogClaim","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"user","type":"address"},{"indexed":false,"name":"key","type":"string"}],"name":"LogRegister","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"LogCollect","type":"event"},{"anonymous":false,"inputs":[],"name":"LogFreeze","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"}]'
        )

        # Get the contract
        contract = web3.eth.contract(abi, addr)

        # Get the Window for right now
        window = contract.call().today()

        # Get the total purchases on this window
        totalEOS = getFloat(contract.call().dailyTotals(window))
    except:
        import traceback
        traceback.print_exc()
        window = -1
        totalEOS = -1

    return window, totalEOS
Beispiel #4
0
def send_token_transaction(buyer, lot, token_address, is_issue, *seller):

    seller = seller[0]
    web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
    unlock_validation(seller.wallet.num, seller.username, web3)

    f = open("transactions/abi.json", 'r')
    abi = json.loads(f.read())
    # contractのアドレスはトークンごと abiは共通
    cnt = web3.eth.contract(abi, token_address)
    # print(seller)
    # print(seller.wallet.num)
    cnt.transact(transaction={
        'from': seller.wallet.num
    }).transfer(buyer.wallet.num, lot)
    buyer.wallet.token_balance = buyer.wallet.get_token_lot(token_address)
    if is_issue is True:
        buyer.profile.have_token.add(buyer)
    else:
        print("---------------")
        buyer.profile.have_token.add(seller)
        print(token_address)
    buyer.profile.save()
    print(buyer.have_token.all())
    buyer.wallet.save()
Beispiel #5
0
    def __init__(self,
                 contract_address,
                 account=None,
                 deploy_txn=None,
                 ipfs_host='127.0.0.1',
                 web3_host='localhost',
                 web3_port=8545,
                 ipfs_port=5001):
        """Creates the base blockchain client object (web3), ipfs client object
        (ipfs), and deploys the compiled contract. Thus, it assumes that you're
        working with a local testrpc blockchain."""

        self.deploy_txn = deploy_txn
        self.web3 = Web3(
            KeepAliveRPCProvider(host=web3_host, port=str(web3_port)))
        self.ipfs = ipfsapi.connect(ipfs_host, int(ipfs_port))

        if (account is not None):
            self.account = account
        else:
            print("No account submitted... using default[2]")
            self.account = self.web3.eth.accounts[2]

        self.compile_and_deploy(contract_address)

        print("Connected to OpenMined ModelRepository:" +
              str(self.contract_address))
Beispiel #6
0
    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')

            # Humans are likely to be refreshing this, so keep it up-to-date
            self.send_header('Cache-Control', 'public, max-age=1')

            self.end_headers()

            web3 = Web3(
                KeepAliveRPCProvider(host=self.web3_address[0],
                                     port=self.web3_address[1]))

            # FIXME: Unfortunately getbalance() doesn't return the right thing;
            # need to investigate further, but this seems to work.
            account = web3.eth.accounts[0]
            str_wallet_balance = str(
                web3.eth.getBalance(account) / 1000000000000000000)
            block_number = web3.eth.blockNumber

            welcome_page = """\
<html>
<head>
    <title>OpenTimestamps Calendar Server</title>
</head>
<body>
<p>This is an <a href="http://www.opentimestamps.org">OpenTimestamps</a> Calendar.</p>
<p>Experimental etherum support, use at your own risks</p>
<p>
Best-block height %d</br>
</br>
Wallet balance: %s ETH</br>
</p>

<p>
You can donate to the wallet by sending funds to %s</br>
</p>

</body>
</html>
""" % (block_number, str_wallet_balance, account)

            self.wfile.write(welcome_page.encode())

        elif self.path.startswith('/timestamp/'):
            self.get_timestamp()

        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/plain')

            # a 404 is only going to become not a 404 if the server is upgraded
            self.send_header('Cache-Control', 'public, max-age=3600')

            self.end_headers()
            self.wfile.write(b'Not found')
Beispiel #7
0
 def get_token_lot(self, token_address):
     web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
     web3.personal.unlockAccount(self.num, self.user.username)
     f = open("transactions/abi.json", 'r')
     abi = json.loads(f.read())
     # TODO: トークンごとにアドレスを取得
     cnt = web3.eth.contract(abi, token_address)
     tokenlot = cnt.call().balanceOf(self.num)
     # print(tokenlot)
     return tokenlot
Beispiel #8
0
def get_web3(registry: Registry) -> Web3:
    """Create a new Ethereum RPC client based on INI configuration.

    NOTE: This is only used for test runs. Production mode uses per-network RPC configuration.
    """
    assert isinstance(registry, Registry)
    host = registry.settings.get("ethereum.ethjsonrpc.host")
    port = registry.settings.get("ethereum.ethjsonrpc.port")
    assert host
    assert port
    return Web3(KeepAliveRPCProvider(host, port))
Beispiel #9
0
 def __init__(self, config: EthConfig):
     self.config = config
     print('Connecting to Ethereum node on %s:%d...' %
           (self.config.server, self.config.port))
     self.web3 = Web3(
         KeepAliveRPCProvider(host=self.config.server,
                              port=self.config.port))
     print('Ethereum node connected successfully')
     print('Getting root contract %s...' % self.config.contract)
     self.root_contract = self.web3.eth.contract(
         address=self.config.contract)
     print('Root contract ABI instantiated')
Beispiel #10
0
    def __init__(self, app):
        log.info("Chain service init")
        super(ChainService, self).__init__(app)

        if self.app.config['chain']['provider'] == 'jsonrpc':
            self.web3 = Web3(
                KeepAliveRPCProvider(
                    host=self.app.config['chain']['jsonrpc']['host'],
                    port=self.app.config['chain']['jsonrpc']['port']))
        else:
            raise ValueError("unsupported chain provider %s" %
                             self.app.config['chain']['provider'])
Beispiel #11
0
    def __init__(self, name, parser):
        if name == 'ETH':
            self.ethereum_path = '/'.join([expanduser("~"), '.ethereum'])
        else:
            self.ethereum_path = '/'.join(
                [expanduser("~"), '.ethereum-classic/mainnet'])

        self.HOST = parser.get(name, 'rpcbind')
        self.PORT = parser.get(name, 'rpcport')

        # Don't forget to launch geth of geth-classic
        self.web3 = Web3(KeepAliveRPCProvider(
            host=self.HOST, port=self.PORT))  # connect to RPC
Beispiel #12
0
def get_token_value(touser,fromuser):
    web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
    #web3.personal.unlockAccount(touser.wallet.num, fromuser.username)
    print(fromuser.username)
    #web3.personal.unlockAccount(fromuser.wallet.num, fromuser.username)
    f = open("transactions/abi.json", 'r')
    abi = json.loads(f.read())
    cnt = web3.eth.contract(abi, touser.profile.token_address)
    tokenlot = cnt.call().balanceOf(fromuser.wallet.num)
    #f = open("transactions/abi.json", 'r')
    #abi = json.loads(f.read())

    return tokenlot
Beispiel #13
0
def ethhack():
    web3 = Web3(KeepAliveRPCProvider(host=ethNode, port='8545'))
    while True:
        keccak = sha3.keccak_256()
        private = SigningKey.generate(curve=SECP256k1)
        public = private.get_verifying_key().to_string()
        keccak.update(public)
        address = "0x{}".format(keccak.hexdigest()[24:])
        try:
            balance = web3.eth.getBalance(address)
        except:
            balance = -1
        if balance != 0:
            sql_upload(private.to_string().hex(), address, balance)
Beispiel #14
0
    def __build_provider__():
        config = get_config()

        if config['MODE'] == CONNECTION_MODE_RPC:
            provider = KeepAliveRPCProvider(host=config['HOST'],
                                            port=config['PORT'],
                                            path=config['PREFIX'])
        elif config['MODE'] == CONNECTION_MODE_IPC:
            provider = IPCProvider(ipc_path=config['PATH'],
                                   testnet=config['IS_TESTNET'])
        else:
            raise RuntimeError(_('Invalid mode'))

        return provider
Beispiel #15
0
    def __init__(self, protocol, host, port, gas, gas_price, contract_addr,
                 account, private_key_path):
        # Establish rpc connection
        self.web3 = Web3(KeepAliveRPCProvider(host=host, port=port))
        self.solidity = _solidity.solc_wrapper()
        self._from = None
        self.private_key = None
        self.abi = None
        self.contract_addr = contract_addr

        fn = os.path.join(os.path.dirname(__file__), 'deployed_abis.json')
        with open(fn, 'r') as instructions_file:
            instructions = json.load(instructions_file)
            self.abi = instructions[self.contract_addr]

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

        # Set sending account
        if account:
            self._from = self.add_0x(account)
        elif private_key_path:
            with open(private_key_path, 'r') as private_key_file:
                self.private_key = private_key_file.read().strip()
            self._from = self.add_0x(
                privtoaddr(self.private_key.decode('hex')).encode('hex'))
        else:
            accounts = self.web3.eth.accounts
            if len(accounts) == 0:
                raise ValueError('No account unlocked')
            self._from = self.add_0x(accounts[0])

        # Check if account address in right format
        if not self.is_address(self._from):
            raise ValueError('Account address is wrong')

        self.gas = gas
        self.gas_price = gas_price

        # Total consumed gas
        self.total_gas = 0

        self.log('Instructions are sent from address: {}'.format(self._from))

        balance = self.web3.eth.getBalance(self._from)

        self.log('Address balance: {} Ether / {} Wei'.format(
            balance / 10**18, balance))
 def __init__(self, calendar, exit_event, web3_address, args):
     self.calendar = calendar
     self.exit_event = exit_event
     self.pending_commitments = set()
     self.unconfirmed_txs = []
     self.txs_waiting_for_enough_confirmation = {}
     self.merkle_tree_for_tx = {}
     self.last_timestamp_tx = 0
     self.web3 = Web3(KeepAliveRPCProvider(host=web3_address[0], port=web3_address[1]))
     self.wait_confirmations = args.wait_confirmations
     self.wait_time_between_txs = args.wait_time_between_txs
     self.account = self.web3.eth.accounts[0]
     new_block_filter = self.web3.eth.filter('latest')
     new_block_filter.watch(self.new_block_callback)
     self.thread = threading.Thread(target=self.__loop)
     self.thread.start()
    def __init__(self, protocol, host, port, gas, gas_price, contract_dir,
                 optimize, account, private_key_path):
        # Establish rpc connection
        self.web3 = Web3(KeepAliveRPCProvider(host=host, port=port))
        self.solidity = _solidity.solc_wrapper()
        self._from = None
        self.private_key = None

        # Set sending account
        if account:
            self._from = self.add_0x(account)
        elif private_key_path:
            with open(private_key_path, 'r') as private_key_file:
                self.private_key = private_key_file.read().strip()
            self._from = self.add_0x(
                privtoaddr(self.private_key.decode('hex')).encode('hex'))
        else:
            accounts = self.web3.eth.accounts
            if len(accounts) == 0:
                raise ValueError('No account unlocked')
            self._from = self.add_0x(accounts[0])

        # Check if account address in right format
        if not self.is_address(self._from):
            raise ValueError('Account address is wrong')

        # Set deployment configuration
        self.optimize = optimize
        self.contract_dir = contract_dir
        self.gas = gas
        self.gas_price = gas_price

        # References dict maps labels to addresses
        self.references = {}

        # Abis dict maps addresses to abis
        self.abis = {}

        # Total consumed gas
        self.total_gas = 0

        self.log('Instructions are sent from address: {}'.format(self._from))

        balance = self.web3.eth.getBalance(self._from)

        self.log('Address balance: {} Ether / {} Wei'.format(
            balance / 10**18, balance))
Beispiel #18
0
def ethhack():
    web3 = Web3(KeepAliveRPCProvider(host=ethNode, port='8545', ssl=False))
    while True:
        keccak = sha3.keccak_256()
        private = SigningKey.generate(curve=SECP256k1)
        public = private.get_verifying_key().to_string()
        keccak.update(public)
        address = "0x{}".format(keccak.hexdigest()[24:])
        try:
            balance = web3.eth.getBalance(address)
        except:
            balance = -1
        if balance != 0:
            with open(address + '.txt', 'w') as f:
                f.write("PRIVATE: {0}\nADDRESS: {1}\nBALANCE: {2}\n".format(
                    private.to_string().hex(), address, balance))
            f.close()
Beispiel #19
0
    def __init__(self, enable_encryption=True):
        self.config = Configuration()
        self._logger = Logger("Pollen")
        self.attack_reporting = AttackReporting(self.config)
        self._encryption = None
        if enable_encryption:
            self._encryption = PollenEncryption()
        self._datastore = PollenDatastore(
            encryption=self._encryption
        )
        self.web3 = Web3(
            KeepAliveRPCProvider(host=self.config['BLOCKCHAIN']['HOST_ADDRESS'],
                                 port=self.config['BLOCKCHAIN']['PORT']))

        self.account_address = self.web3.eth.accounts[0]
        self.block_gas_limit = self.web3.eth.getBlock(0)["gasLimit"]

        self.web3.personal.unlockAccount(account=self.account_address,
                                         passphrase=self.config['BLOCKCHAIN']
                                         ['ACCOUNT_PASSPHRASE'],
                                         duration=self.config['BLOCKCHAIN']
                                         ['ACCOUNT_UNLOCK_DURATION'])

        relay_contract_filename = (self.config['BLOCKCHAIN']
                                              ['RELAY_SOURCE_FILENAME'])
        relay_contract_address = (self.config['BLOCKCHAIN']
                                             ['RELAY_CONTRACT_ADDRESS'])
        self.relay_contract = self.web3.eth.contract(
            abi=self._compute_contract_abi(relay_contract_filename),
            address=relay_contract_address
        )

        self.system_contract_filename = (self.config['BLOCKCHAIN']
                                                    ['SYSTEM_SOURCE_FILENAME'])
        system_contract_address = (self.config['BLOCKCHAIN']
                                              ['SYSTEM_CONTRACT_ADDRESS'])
        if system_contract_address is not None:
            self.system_contract = self.web3.eth.contract(
                abi=self._compute_contract_abi(self.system_contract_filename),
                address=system_contract_address
            )
        else:
            self.system_contract = self._create_mitigation_contract()
        if self._encryption is not None:
            self.set_public_key(self._encryption.get_serialized_public_key())
    def __init__(self, contract_address, account=None,
                 ipfs=IPFS('127.0.0.1', 5001),
                 web3_host='localhost', web3_port=9545):
        """Creates the base blockchain client object (web3) then
         connects to the Sonar contract.
        It assumes you're working with a local testrpc blockchain."""

        self.ipfs = ipfs
        self.web3 = Web3(KeepAliveRPCProvider(host=web3_host,
                                              port=str(web3_port)))

        if account is not None:
            self.account = account
        else:
            print("No account submitted... using default[2]")
            self.account = self.web3.eth.accounts[2]

        self.connect_to_contract(contract_address)
Beispiel #21
0
    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            tokenname = "My"
            from_wallet = WalletProfile.objects.get(user=request.user)
            to_user = request.POST.get("username")
            to_user = User.objects.get(username=to_user)
            to_wallet = WalletProfile.objects.get(user=to_user)

            web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
            web3.personal.unlockAccount(from_wallet.num, request.user.username)
            # 暫定的にABIを直接入力(どのトークンでも共通)
            f = open("transactions/abi.json", 'r')
            abi = json.loads(f.read())
            cnt = web3.eth.contract(abi, Token.ground_token_address, tokenname)
            cnt.transact(transaction={
                'from': from_wallet.num
            }).transfer(to_wallet.num, 10)
            # web3.eth.contract()
        return render(request, "home.html")
def mainRPC():
    # Note that you should create only one RPCProvider per
    # process, as it recycles underlying TCP/IP network connections between
    # your process and Ethereum node
    web3 = Web3(KeepAliveRPCProvider(host="localhost", port="8545"))

    # or for an IPC based connection
    # web3 = Web3(IPCProvider())

    print(web3.personal.listAccounts[0])

    # testing functions
    print(web3.personal.listAccounts)
    # print (web3.eth.blockNumber)

    help(cl)
    # for i in dir(cl): print i
    # print (dir(cl))

    newcl = cl.EthTesterClient()
    print(newcl.get_accounts())
Beispiel #23
0
 def form_valid(self, form):
     web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
     if web3.isConnected():
         username = form.cleaned_data.get("username")
         email = form.cleaned_data.get("email")
         password = form.cleaned_data.get("password")
         new_user = User.objects.create(username=username, email=email)
         new_user.set_password(password)
         # host='localhost' port=8545 は geth のデフォルト値
         wallet_num = web3.personal.newAccount(username)
         # geth サーバーにアクセスしてwallet発行
         wallet = WalletProfile.objects.create(user=new_user)
         # Userモデルに格納するwalletオブジェクトを生成
         new_user.wallet.num = wallet_num
         wallet.save()
         # wallet.saveでuser.wallet.numにセーブ
         new_user.save()
         return super(UserRegisterView, self).form_valid(form)
     else:
         raise PermissionDenied
         return 0
Beispiel #24
0
    def connect(self):
        '''
        Connects to the node. Returns True if a connection is created or already exists.

        '''
        if self.isConnected():
            print("Already connected.")
            return True

        try:
            # Connect
            self.web3 = Web3(
                KeepAliveRPCProvider(host=self.host, port=self.port))
        except:
            self.log.error('Error Connecting to %s:%s' % (host, port))
            traceback.print_exc()
            return False

        self.log.info('Connected to %s:%s' % (self.host, self.port))

        return True
Beispiel #25
0
    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            query = request.POST.get("value")
            value = int(query) * 100000
            print(value)
            from_wallet = WalletProfile.objects.get(user=request.user)
            to_user = request.POST.get("username")
            to_user = User.objects.get(username=to_user)
            to_wallet = WalletProfile.objects.get(user=to_user)
            web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))

            transaction = formatters.input_transaction_formatter(
                web3.eth, {
                    'to': to_wallet.num,
                    'from': from_wallet.num,
                    'value': value
                })

            web3.personal.signAndSendTransaction(transaction,
                                                 request.user.username)

            return render(request, "home.html")
Beispiel #26
0
    def post(self, request, *args, **kwargs):
        if request.method == 'POST' and request.user.is_authenticated():
            to_user = User.objects.get(username=request.user.username)
            to_wallet = WalletProfile.objects.get(user=to_user)
            token_dir = '../contract/Token/FixedSupplyToken'
            # Tokenの発行量
            issue_lot = 1000000
            web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
            token_binary = token_dir + '.bin'
            token_abi = token_dir + '.abi'
            binary = open(token_binary)
            abi = open(token_abi)
            abi = json.loads(abi.read())
            cnt = web3.eth.contract()
            cnt.bytecode = '0x' + binary.read()
            cnt.abi = abi

            # TODO トークン発行時のパスフレーズを入力できるようにする
            admin = UserProfile.objects.first()
            unlock_validation(web3.eth.coinbase, admin.user.username, web3)
            #web3.personal.unlockAccount(web3.eth.coinbase, admin.user.username)
            # print(admin.user.password)
            transaction_hash = cnt.deploy(transaction={
                'from': web3.eth.coinbase,
                'gas': 1000000
            })
            sleep(4)
            hash_detail = web3.eth.getTransactionReceipt(transaction_hash)
            #DEBUG print(hash_detail.contractAddress)
            token_address = hash_detail.contractAddress
            token_user = User.objects.get(username=request.user.username)
            token_user.profile.token_address = token_address
            token_user.profile.save()

            from_wallet = WalletProfile.objects.filter(
                num=web3.eth.coinbase).first()
            send_token_transaction(to_user, issue_lot, token_address, True,
                                   from_wallet.user)
            return redirect("home")
Beispiel #27
0
    return ''.join(
        random.choice(string.ascii_uppercase + string.digits)
        for _ in range(n))


def genNewAccount():
    username = rands(6)
    password = rands(8)
    loginInfo = username + " " + password
    return loginInfo


if __name__ == '__main__':
    # web3 = EthJsonRpc('127.0.0.1', 8545)

    web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))
    web3.eth.defaultAccount = web3.eth.accounts[0]

    json_data = open("ethvpn.json").read()
    contractABI = json.loads(json_data)
    ethvpn = web3.eth.contract(abi=contractABI, address=ethvpnAddress)

    while True:
        input_line = raw_input("command: ")
        if input_line == "exit" or input_line == "quit":
            break
        else:
            args = input_line.split()
            # print args
            # list all vpns available
            if args[0] == "list-vpns":
Beispiel #28
0
from web3 import Web3, KeepAliveRPCProvider, IPCProvider
from time import sleep
# Code provided for test purpose by Mchain Team
import socket
import sys
import os

web3 = Web3(KeepAliveRPCProvider(host='127.0.0.1', port='8545'))
ERROR = "ERROR"

# Create a TCP/IP socket
sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address_2 = ('0.0.0.0', 10001)
#print >>sys.stderr, 'starting up on %s port %s' % server_address_2
sk = sock_server.bind(server_address_2)
#Listen for incoming c

#if sock_server:
print("************************************************")
print(" SERVER STARTED")
print("*************************************************")
sock_server.listen(1)

#try:
#****************************Connect to Pi Display*******************
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('192.168.1.6', 10000)
print >> sys.stderr, 'connecting to %s port %s' % server_address
Beispiel #29
0
def start_private_chain(chain, etherbase, debug=False):

    devnull = open(os.devnull, 'w')

    if chain != 'remptychain':

        # Remove previous blockchain
        pr = subprocess.Popen(['rm', '-rf', './blockchains/' + chain])
        pr.wait()

        # Init new blockchain
        if debug:
            pr = subprocess.Popen([
                'geth', '--datadir', './blockchains/' + chain, 'init',
                './blockchains/genesis.json'
            ])
        else:
            pr = subprocess.Popen([
                'geth', '--datadir', './blockchains/' + chain, 'init',
                './blockchains/genesis.json'
            ],
                                  stdout=devnull,
                                  stderr=devnull)
        pr.wait()

        # Copy the accounts
        pr = subprocess.Popen([
            'cp', '-r', './blockchains/remptychain/keystore',
            './blockchains/' + chain + '/'
        ])
        pr.wait()

    if Web3(KeepAliveRPCProvider(host='127.0.0.1',
                                 port=MyGlobals.port_number)).isConnected():
        print('\033[91m[-] Some blockchain is active, killing it... \033[0m',
              end='')
        kill_active_blockchain()
        if not (Web3(
                KeepAliveRPCProvider(
                    host='127.0.0.1',
                    port=MyGlobals.port_number)).isConnected()):
            print('\033[92m Killed \033[0m')
        else:
            print('Cannot kill')

    print('\033[1m[ ] Connecting to PRIVATE blockchain %s  \033[0m' % chain,
          end='')
    if debug:
        pro = subprocess.Popen([
            'geth', '--rpc', '--rpccorsdomain', '"*"',
            '--rpcapi="db,eth,net,web3,personal,web3"', '--rpcport',
            MyGlobals.port_number, '--datadir', 'blockchains/' + chain,
            '--networkid', '123', '--mine', '--minerthreads=1',
            '--etherbase=' + MyGlobals.etherbase_account
        ])
    else:
        pro = subprocess.Popen([
            'geth', '--rpc', '--rpccorsdomain', '"*"',
            '--rpcapi="db,eth,net,web3,personal,web3"', '--rpcport',
            MyGlobals.port_number, '--datadir', 'blockchains/' + chain,
            '--networkid', '123', '--mine', '--minerthreads=1',
            '--etherbase=' + MyGlobals.etherbase_account
        ],
                               stdout=devnull,
                               stderr=devnull)

    global web3
    MyGlobals.web3 = Web3(
        KeepAliveRPCProvider(host='127.0.0.1', port=MyGlobals.port_number))
    while (not MyGlobals.web3.isConnected()):
        print('', end='.')
        if MyGlobals.exec_as_script:
            sys.stdout.flush()
        time.sleep(1)

    if (MyGlobals.web3.isConnected()):
        print('\033[92m ESTABLISHED \033[0m')
    else:
        print('\033[93m[-] Connection failed. Exiting\033[0m')
        exit(2)

    return pro
 def __init__(self):
     self.host = '127.0.0.1'
     self.port = '8545'
     self.web3 = Web3(KeepAliveRPCProvider(host=self.host, port=self.port))