Пример #1
0
    def create_contract_tx_hash(self):
        compiled_sol = compile_source_file('%s/contract/OwnerToken.sol' % BASE_DIR)
        contract_interface = compiled_sol['<stdin>:OwnerToken']

        # web3.py instance
        w3 = Web3(HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH'))

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

        with open('%s/contract/owner_contract_abi.json' % BASE_DIR, 'w') as outfile:
            json.dump(contract_interface['abi'], outfile)

        data = contract._encode_constructor_data(args=(self.name, self.symbol))
        transaction = {'data': data,
                       'gas': w3.toHex(1000000),
                       'gasPrice': w3.toWei('1000', 'gwei'),
                       'chainId': 4,
                       'to': '',
                       'from': self.ADDRESS,
                       'nonce': w3.eth.getTransactionCount(self.ADDRESS, "pending")
                       }
        acct = Account.privateKeyToAccount(self.PRIVATE_KEY)
        signed = acct.signTransaction(transaction)
        tx = w3.eth.sendRawTransaction(signed.rawTransaction)
        tx_hash = w3.toHex(tx)
        return tx_hash
def priv_key_to_account(coin, priv_key):
    if coin == ETH:
        # do something
        return Account.privateKeyToAccount(priv_key)
    elif coin == BTCTEST:
        # do something else
        return PrivateKeyTestnet(priv_key)
Пример #3
0
    def deploy_contract(self):
        compiled_sol = compile_source_file('TokenERC20.sol')
        contract_interface = compiled_sol['<stdin>:TokenERC20']

        # web3.py instance
        w3 = Web3(
            HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH'))

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

        with open('contract_abi.json', 'w') as outfile:
            json.dump(contract_interface['abi'], outfile)

        data = contract._encode_constructor_data(args=(self.total_supply,
                                                       self.name, self.symbol))
        transaction = {
            'data': data,
            'gas': 3000001,
            'gasPrice': 8000001,
            'chainId': 4,
            'to': '',
            'from': self.ADDRESS,
            'nonce': w3.eth.getTransactionCount(self.ADDRESS)
        }
        acct = Account.privateKeyToAccount(self.PRIVATE_KEY)
        signed = acct.signTransaction(transaction)
        tx = w3.eth.sendRawTransaction(signed.rawTransaction)
        tx_hash = w3.toHex(tx)
        return tx_hash
Пример #4
0
def priv_key_to_account(coin, privkey):
    if coin == ETH:
        return Account.privateKeyToAccount(privkey)
    elif coin == BTCTEST:
        account = PrivateKeyTestnet(privkey)
        print(account.address)
        return PrivateKeyTestnet(privkey)
Пример #5
0
def transfer(contract_address, to, amount):
    with open(os.path.join('./contract_abi.json'), 'r') as abi_definition:
        abi = json.load(abi_definition)

    w3 = Web3(HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH'))

    contract = w3.eth.contract(address=contract_address, abi=abi)

    unicorn_txn = contract.functions.transfer(
        to, amount * 1000000000000000000).buildTransaction({
            'value':
            0,
            'gas':
            w3.toHex(1000001),
            'gasPrice':
            w3.toWei('10000', 'gwei'),
            'nonce':
            w3.eth.getTransactionCount(
                '0x6f212bF41DF64De9782dbfb26112BD3B0e39514B'),
            'from':
            '0x6f212bF41DF64De9782dbfb26112BD3B0e39514B'
        })

    private_key = r"955ca0f797c309aadd06d6bd9272ed71e57210ea145edff4b238c3db0b63f219"
    acct = Account.privateKeyToAccount(private_key)
    signed = acct.signTransaction(unicorn_txn)
    tx = w3.eth.sendRawTransaction(signed.rawTransaction)
    tx_hash = w3.toHex(tx)
    return tx_hash
def create_and_recharge(num):
    w3 = create_web3_instance("http://52.205.30.16:8545")
    acc = Account.privateKeyToAccount("f87fdefd98ef1347f4ee213d80e3495e4beaba5991a18bfee0fa80f0fba05b1a")
    nonce = w3.eth.getTransactionCount(acc.address)
    addrs = []
    for i in range(num):
        addr = create_acc()
        print(addr)
        transaction = {
            'to': addr,
            'value': value,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        transaction['gas'] = gas
        transaction['gasPrice'] = gas_price
        signed = acc.signTransaction(transaction)
        w3.eth.sendRawTransaction(signed.rawTransaction)
        addrs.append(addr)
        nonce += 1

    time.sleep(100)
    for t in addrs:
        print(t, w3.eth.getBalance(t))
Пример #7
0
def submit_sign_and_wait_for_transaction(w3: Web3, txn: Dict, private_key: str, timeout: int):
    signed = w3.eth.account.signTransaction(txn, private_key)
    tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash, timeout=timeout)

    # after the transaction is confirmed, save it
    account_address = Account.privateKeyToAccount(private_key).address
    wallet = Wallet.objects.get(address=account_address)
    to = txn['to']
    if isinstance(to, bytes):
        to = to.decode('utf-8')

    Transaction.objects.create(
        block_number=tx_receipt['blockNumber'],
        chain_id=txn['chainId'],
        contract_address=tx_receipt['contractAddress'],
        cumulative_gas_used=tx_receipt['cumulativeGasUsed'],
        data=txn['data'],
        gas_limit=txn['gas'],
        gas_price=txn['gasPrice'],
        gas_used=tx_receipt['gasUsed'],
        hash=tx_hash.hex(),
        nonce=txn['nonce'],
        status=tx_receipt.get('status', -1),
        to=to,
        value=txn['value'],
        wallet=wallet,
    )

    return tx_receipt
Пример #8
0
    def __init__(self,
                 private_key,
                 wss_url=None,
                 contract_address=None,
                 **kwargs):
        self.logger = logging.getLogger('gnosis.extension.contract')
        self.web3 = Web3(
            Web3.WebsocketProvider(endpoint_uri=wss_url,
                                   websocket_timeout=1800))

        self.private_key = private_key
        self.account = Account.privateKeyToAccount(self.private_key)
        self.contract_address = self.web3.toChecksumAddress(contract_address)
        self.gnosis_gas_station_url = kwargs.get(
            'gnosis_gas_station_url',
            'https://safe-relay.gnosis.io/api/v1/gas-station/')

        abi_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                'gnosis/exchange_abi.json')

        with open(abi_file) as json_file:
            abi = json.load(json_file)
            self.contract = self.web3.eth.contract(
                address=self.contract_address, abi=abi)

        if not self.web3.isConnected():
            raise ConnectionError("Failed to connect to the Ethereum network.")

        self.max_gas_price = kwargs.get('max_gas_price', -1)
        self.gas_price_level = kwargs.get('gas_price_level', 'standard')
def run_limit_case(tx_manager: TransactionManager):
    miner_w3 = create_web3_instance("http://127.0.0.1:1111")
    normal_w3 = create_web3_instance("http://127.0.0.1:2222")
    miner_addr = "0x040e18b1bbb5dead8120fec5885fdf56498bcd6a"
    # mainacc = get_rand_account()
    mainacc = Account.privateKeyToAccount(
        "15bac02dbaff32a8da673c490753a070b054b9d62adbc52cc474f2b49370613b")
    targetacc = get_rand_account()
    subaccs = []
    acc3 = get_rand_account()
    acc_addrs = []
    acc_addrs.append(miner_addr)
    acc_addrs.append(str(mainacc.address))
    acc_addrs.append(str(targetacc.address))
    acc_addrs.append(str(acc3.address))

    for i in range(1000):
        acc = get_rand_account()
        subaccs.append(acc)
        acc_addrs.append(str(acc.address))

    # rechargestartmoney
    # res = rechange_by_address(tx_manager, mainacc.address, 700000000000, miner_w3)
    # print("privatekey", str(binascii.b2a_hex(mainacc.privateKey), 'utf-8'))

    # return
    # if not res:
    #     log_print("Rechange Failed")
    #     log_print_is_case_pass(False, case_name)
    #     return

    show_address_balance("start_send_txs", miner_w3, acc_addrs)
    mainacc_balance = miner_w3.eth.getBalance(mainacc.address)

    log_print("--------------Start create Txs-----------------")
    start_mutiple_send_txs(normal_w3, mainacc, subaccs, targetacc, 100000,
                           10000000000000, mainacc_balance)
    # send_normal_txs(acc1, acc2, 100000, 10000000000000000, acc1_start)
    log_print("--------------End create Txs-----------------")

    # res = rechange_by_address(tx_manager, acc3.address, 10000000000, miner_w3)
    # if not res:
    #     log_print("Rechange Failed")
    #     log_print_is_case_pass(False, case_name)
    #     return
    global thread_tps
    if thread_tps:
        log_print("**********join tps*************")
        thread_tps.join()
    else:
        log_print("***********not join tps*******************")

    log_print("================show address result===================")

    for i in range(40):
        log_print("Show result at index ", i)
        show_address_balance("end_send_txs", miner_w3, acc_addrs)
        # get_address_balance(acc1.address, acc2.address, acc3.address, miner_addr)
        time.sleep(1)
Пример #10
0
def priv_key_to_account(coin, priv_key):
    # print(coin)
    # print(priv_key)
    if coin == ETH:
        return Account.privateKeyToAccount(priv_key)
    elif coin == BTC:
        key = wif_to_key("")
        return key.PrivateKeyTestnet(priv_key)
def priv_key_to_account(coin, priv_key):
    #    print(coin)
    #    print(priv_key)
    if coin == ETH:
        account = Account.privateKeyToAccount(priv_key)
        return account
    if coin == BTCTEST:
        account = PrivateKeyTestnet(priv_key)
        return account
Пример #12
0
def decryptPrivateKey(_file, _pwd):
    with open(_file) as keyfile:
        encrypted_key = keyfile.read()
    keyfile.close()

    ac_obj = Account()

    decrypted_key = ac_obj.decrypt(encrypted_key, _pwd)
    return ac_obj.privateKeyToAccount(decrypted_key)
Пример #13
0
def transfer_between_accounts(w3: Web3,
                              source_private_key: str,
                              destination_private_key: str,
                              amount_in_wei: int) -> None:
    source_account = Account.privateKeyToAccount(source_private_key)
    destination_account = Account.privateKeyToAccount(destination_private_key)
    signed_txn = w3.eth.account.signTransaction(dict(
        nonce=w3.eth.getTransactionCount(source_account.address),
        gasPrice=int(w3.eth.gasPrice * 1.1),
        # increase by 10% just to be sure this will be included
        gas=3 * 21000,  # 3x normal transaction cost just to be safe
        to=destination_account.address,
        value=amount_in_wei
    ),
        source_private_key)

    tx_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    w3.eth.waitForTransactionReceipt(tx_hash, timeout=120)
Пример #14
0
 def checkWallet(self, publicKey, privateKey):
     try:
         publicKey = Web3.toChecksumAddress(publicKey)
         account = Account.privateKeyToAccount(privateKey)
         if account.address == publicKey:
             return True
         else:
             return False
     except Exception as e:
         print(e)
         return False
Пример #15
0
    def __init__(self, key: str, contract_address: str, node_address: str):
        self._account = Account.privateKeyToAccount(key)
        self._contract_address = contract_address
        self._node_address = node_address

        self.w3 = Web3(HTTPProvider(self._node_address))
        self.contract = self.w3.eth.contract(address=self._contract_address,
                                             abi=EIP20_ABI)

        self._balanceOf = self.contract.functions.balanceOf
        self._totalSupply = self.contract.functions.totalSupply
        self._transfer = self.contract.functions.transfer
Пример #16
0
def main():
    i = 1
    priv = '2defac83d19dfe04610864da99cec58fdcf11af07178cfacbf30c02d6ac57e46'
    account = Account.privateKeyToAccount(priv)
    print(account.address)
    try:
        balance = w3.eth.getBalance(account.address)
        if balance != 0:
            logging.info("有钱地址-" + account.address + ",私钥-" + priv)
            print(balance)
    except BaseException as e:
        print(str(e))
Пример #17
0
def _build_transaction_dict(w3, private_key, gas=None, gas_price=None):
    acc = Account.privateKeyToAccount(private_key)
    nonce = get_nonce_for_wallet(private_key)
    latest_block = w3.eth.getBlock('latest')
    if not gas:
        gas = 7000000  # tech debt until we figure out how to always pick a good gas limit

    if not gas_price:
        gas_price = int(
            w3.eth.gasPrice * 1.1)  # add an additional 10% just to be safe

    return {'nonce': nonce, 'gas': gas, 'gasPrice': gas_price}
Пример #18
0
 def eth_sign(self, params):
     sign_str = self.get_sign_str(params, None)
     message = Web3.toHex(Web3.sha3(text=sign_str))
     private_key = Account.decrypt(self.key_store, self.key_pwd)
     acct = Account.privateKeyToAccount(private_key)
     hash = acct.signHash(message)
     border = 'big'
     v = hash['v'].to_bytes(1, border)
     r = hash['r'].to_bytes(32, border)
     s = hash['s'].to_bytes(32, border)
     z = v + r + s
     sign = z.hex()
     params['presign'] = sign
Пример #19
0
def random_find():
    logging.info("启动扫描,扫描地址-->>" + main_url)
    while True:
        private_key = build_64_private_key()
        try:
            account = Account.privateKeyToAccount(private_key)
            balance = w3.eth.getBalance(account.address)
            if balance != 0:
                logging.info("有钱地址-" + account.address + ",私钥-" + private_key)
                print(private_key)
                print(balance)
        except BaseException as e:
            logging.error("异常信息" + str(e))
            continue
def generate_account():
    """Create a digital wallet and Ethereum account from a mnemonic seed phrase."""
    # Fetch mnemonic from environment variable.
    mnemonic = os.getenv("MNEMONIC")

    # Create Wallet Object
    wallet = Wallet(mnemonic)

    # Derive Ethereum Private Key
    private, public = wallet.derive_account("eth")

    # Convert private key into an Ethereum account
    account = Account.privateKeyToAccount(private)

    return account
Пример #21
0
def priv_key_to_account(coin, privkey):

    if coin == ETH:

        account = Account.privateKeyToAccount(privkey)

        return account

    elif coin == BTCTEST:

        account = PrivateKeyTestnet(privkey)

        return account

    else:
        print("Error with function")
Пример #22
0
 def run(self):
     main_url = self.main_url
     logging.info("启动扫描,扫描地址-->>" + main_url)
     logging.info(self.print_thread_group_name())
     w3 = Web3(HTTPProvider(main_url))
     while True:
         private_key = EthUtil.build_64_private_key()
         try:
             account = Account.privateKeyToAccount(private_key)
             balance = w3.eth.getBalance(account.address)
             # logging.info(self.print_thread_group_name() + "," + private_key)
             if balance != 0:
                 logging.info(self.print_thread_group_name() + ",有钱地址-" +
                              account.address + ",私钥-" + private_key)
         except BaseException as e:
             logging.error("异常信息" + str(e))
             continue
Пример #23
0
def get_nonce(*, web3: Web3, nonce: int, auto_nonce: bool, private_key: bytes):
    """get the nonce to be used as specified via command line options

     we do some option checking in this function. It would be better to do this
     before doing any real work, but we would need another function then.
    """
    if auto_nonce and not private_key:
        raise click.UsageError("--auto-nonce requires --keystore argument")
    if nonce is not None and auto_nonce:
        raise click.UsageError(
            "--nonce and --auto-nonce cannot be used at the same time"
        )

    if auto_nonce:
        return web3.eth.getTransactionCount(
            Account.privateKeyToAccount(private_key).address, block_identifier="pending"
        )
    else:
        return nonce
Пример #24
0
    def create(self, request, *args, **kwargs):
        to = request.data.get('address')
        c = Category.objects.get(pk=int(request.data.get('category')))
        cp = CategoryProfile.objects.get(profile=request.user.profile,
                                         category=c)
        amount = cp.balance

        with open('%s/contract/owner_contract_abi.json' % settings.BASE_DIR,
                  'r') as abi_definition:
            abi = json.load(abi_definition)

        w3 = Web3(
            HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH'))

        contract_checksum = w3.toChecksumAddress(c.contract_address)
        contract = w3.eth.contract(address=contract_checksum, abi=abi)

        unicorn_txn = contract.functions.add_amount(to, 1).buildTransaction({
            'value':
            0,
            'gas':
            w3.toHex(1000000),
            'chainId':
            4,
            'gasPrice':
            w3.toWei('500', 'gwei'),
            'nonce':
            w3.eth.getTransactionCount(
                '0x6f212bF41DF64De9782dbfb26112BD3B0e39514B'),
            'from':
            os.environ['ADDRESS']
        })

        private_key = os.environ['PRIVATE_KEY']
        acct = Account.privateKeyToAccount(private_key)
        signed = acct.signTransaction(unicorn_txn)
        tx = w3.eth.sendRawTransaction(signed.rawTransaction)
        tx_hash = w3.toHex(tx)

        cp.balance = 0
        cp.save()
        return Response({"tx_hash": tx_hash}, status=status.HTTP_200_OK)
Пример #25
0
    def deploy(self):
        contract = self.w3.eth.contract(abi=self.abi, bytecode=self.bin)

        acct = Account.privateKeyToAccount(self.priv)
        contract_data = contract.constructor().buildTransaction(
            {'from': acct.address,
             'gasPrice': self.w3.eth.gasPrice,
             'gas': 10}
        )
        contract_data["nonce"] = self.w3.eth.getTransactionCount(
            acct.address)

        try:
            signed = self.w3.eth.account.signTransaction(
                contract_data, self.priv)
            tx_hash = self.w3.eth.sendRawTransaction(signed.rawTransaction)
        except ValueError as verr:
            log.debug(f'sendRawTransaction error: {verr}')
        else:
            return tx_hash.hex()
Пример #26
0
def do_test():
    acc1 = Account.privateKeyToAccount(
        "15bac02dbaff32a8da673c490753a070b054b9d62adbc52cc474f2b49370613b")

    normal_w3 = create_web3_instance("http://127.0.0.1:2222")
    miner_w3 = create_web3_instance("http://127.0.0.1:1111")
    balance_end = miner_w3.eth.getBalance(acc1.address)
    w3 = miner_w3
    print(balance_end)

    print(miner_w3.eth.getTransactionCount(acc1.address))
    # return
    nonce = w3.eth.getTransactionCount(acc1.address)

    accs = []
    for i in range(100):
        print("nonec", nonce)
        acc2 = get_rand_account()
        accs.append(acc2)
        transaction = {
            'to': acc2.address,
            'value': 1000000000,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(miner_w3, transaction)
        gas_price = w3.eth.gasPrice
        log_debug_print("use gas ", gas, "gasPrice", gas_price)
        transaction['gas'] = int(gas)
        transaction['gasPrice'] = int(gas_price)
        signed = acc1.signTransaction(transaction)
        res = w3.eth.sendRawTransaction(signed.rawTransaction)
        print(acc2.address,
              "0x" + str(binascii.b2a_hex(res), encoding='utf-8'))
        # time.sleep(15)
        print("---", w3.eth.getBalance(acc2.address))
        print("--------------------")
        nonce += 1
    time.sleep(40)
    for acc in accs:
        print("===>", acc.address, w3.eth.getBalance(acc.address))
Пример #27
0
    def __init__(self, config, max_gas_price=-1, gas_price_level='standard'):
        # Required parameters: config = {'secret': ''}
        # additional config['network'] = mainnet or rinkeby
        # max_gas_price (wei) will prevent actions if gas price is too high
        # gas_price_level is a parameter from gnosis gas station API (see).

        self.logger = logging.getLogger('gnosis.extension')

        self.network = config.get('network', 'mainnet').lower()
        if self.network not in self._NETWORK_CONFIGS.keys():
            raise KeyError(
                f"Invalid network name. Network must be one of {list(self._NETWORK_CONFIGS.keys())}"
            )
        self._network_config = self._NETWORK_CONFIGS[self.network]

        self.secret = config.get('secret')
        self.account = Account.privateKeyToAccount(config.get('secret'))
        self.account_address = self.account.address
        self.web3 = Web3(
            Web3.WebsocketProvider(
                endpoint_uri=self._network_config['wss_url'],
                websocket_timeout=1800))

        self.logger.debug(f"Owner account: {self.account_address}")

        self.ALLOWED_TOKENS = self._network_config['allowed_tokens']

        self.dfusion_contract = DfusionContract(
            max_gas_price=max_gas_price,
            gas_price_level=gas_price_level,
            private_key=config.get('secret'),
            wss_url=self._network_config['wss_url'],
            contract_address=self._network_config['contract_address'],
            gnosis_gas_station_url=self.
            _network_config['gnosis_gas_station_url'],
        )

        self.the_graph = TheGraph(self._network_config['thegraph_url'])
        self._load_tokens_info()

        self.logger.info(f"Current batch: {self.current_batch_id()}")
Пример #28
0
    def test_transfer_between_accounts(self):
        source_account_key = constants.WALLET.privateKey
        destination_account_key = settings.ethereum_private_key()
        amount = 100
        w3 = MagicMock()
        destination_address = Account.privateKeyToAccount(
            destination_account_key)

        deploy.transfer_between_accounts(w3, source_account_key,
                                         destination_account_key, amount)

        w3.eth.account.signTransaction.assert_called_once_with(
            dict(nonce=ANY,
                 gasPrice=ANY,
                 gas=ANY,
                 to=destination_address.address,
                 value=amount), source_account_key)
        w3.eth.sendRawTransaction.assert_called_once_with(
            w3.eth.account.signTransaction.return_value.rawTransaction)
        w3.eth.waitForTransactionReceipt.assert_called_once_with(
            w3.eth.sendRawTransaction.return_value, timeout=120)
from web3 import Web3, Account
from web3.utils.encoding import to_hex
import json

w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
accounts = w3.eth.accounts

# load wallet account
wfn = './keystore/{0}.json'.format(
    '0x6FAA97edd198F59DFb6f0063Bc34777eAa0BF02c')
with open(wfn, 'r') as f:
    wallet = json.load(f)
priv_key = Account.decrypt(wallet, '123')
account = Account.privateKeyToAccount(priv_key)

# funds wallet account
tx_hash = w3.eth.sendTransaction({
    'from': accounts[0],
    'to': account.address,
    'value': Web3.toWei(1, 'ether')
})
w3.eth.waitForTransactionReceipt(tx_hash)

balance = w3.eth.getBalance(account.address)
print('wallet balance before raw tx => {0}'.format(balance))

# prepare tx payload
nonce = w3.eth.getTransactionCount(account.address)
payload = {
    'to': accounts[9],
    'value': 1000,
Пример #30
0
def priv_key_to_account(coin, priv_key):
    if coin == ETH:
        return Account.privateKeyToAccount(priv_key)
    if coin == BTCTEST:
        return PrivateKeyTestnet(priv_key)