Beispiel #1
0
def test_lock(account, password, privkey):
    assert not account.locked
    assert account.address == privtoaddr(privkey)
    assert account.privkey == privkey
    assert account.pubkey is not None
    account.unlock(password + 'fdsa')
    account.lock()
    assert account.locked
    assert account.address == privtoaddr(privkey)
    assert account.privkey is None
    assert account.pubkey is None
    with pytest.raises(ValueError):
        account.unlock(password + 'fdsa')
    account.unlock(password)
Beispiel #2
0
    def send_transaction(self, sender, to, value=0, data='', startgas=0,
                         gasprice=10 * denoms.szabo, nonce=None):
        """ Helper to send signed messages.

        This method will use the `privkey` provided in the constructor to
        locally sign the transaction. This requires an extended server
        implementation that accepts the variables v, r, and s.
        """

        if not self.privkey and not sender:
            raise ValueError('Either privkey or sender needs to be supplied.')

        if self.privkey and not sender:
            sender = privtoaddr(self.privkey)

            if nonce is None:
                nonce = self.nonce(sender)
        elif self.privkey:
            if sender != privtoaddr(self.privkey):
                raise ValueError('sender for a different privkey.')

            if nonce is None:
                nonce = self.nonce(sender)
        else:
            if nonce is None:
                nonce = 0

        if not startgas:
            startgas = self.gaslimit() - 1

        tx = Transaction(nonce, gasprice, startgas, to=to, value=value, data=data)

        if self.privkey:
            # add the fields v, r and s
            tx.sign(self.privkey)

        tx_dict = tx.to_dict()
        # Transaction.to_dict() encodes 'data', so we need to decode it here.
        tx_dict['data'] = data_decoder(tx_dict['data'])

        # rename the fields to match the eth_sendTransaction signature
        tx_dict.pop('hash')
        tx_dict['sender'] = sender
        tx_dict['gasPrice'] = tx_dict.pop('gasprice')
        tx_dict['gas'] = tx_dict.pop('startgas')

        res = self.eth_sendTransaction(**tx_dict)
        assert len(res) in (20, 32)
        return encode_hex(res)
Beispiel #3
0
def test_unlock(keystore, password, privkey, uuid):
    account = Account(keystore)
    assert account.locked
    account.unlock(password)
    assert not account.locked
    assert account.privkey == privkey
    assert account.address == privtoaddr(privkey)
Beispiel #4
0
    def sender(self):
        if self.privkey:
            return privtoaddr(self.privkey)

        if self._sender is None:
            self._sender = self.coinbase

        return self._sender
Beispiel #5
0
def test_address(keystore, password, privkey):
    keystore_wo_address = keystore.copy()
    keystore_wo_address.pop('address')
    account = Account(keystore_wo_address)
    assert account.address is None
    account.unlock(password)
    account.lock()
    assert account.address == privtoaddr(privkey)
 def address(self):
     """The account's address or `None` if the address is not stored in the key file and cannot
     be reconstructed (because the account is locked)
     """
     if self._address:
         pass
     elif 'address' in self.keystore:
         self._address = unhexlify(self.keystore['address'])
     elif not self.locked:
         self._address = keys.privtoaddr(self.privkey)
     else:
         return None
     return self._address
Beispiel #7
0
 def address(self):
     """The account's address or `None` if the address is not stored in the key file and cannot
     be reconstructed (because the account is locked)
     """
     if self._address:
         pass
     elif 'address' in self.keystore:
         self._address = unhexlify(self.keystore['address'])
     elif not self.locked:
         self._address = keys.privtoaddr(self.privkey)
     else:
         return None
     return self._address
    def address(self):
        """

        :return:
        """
        if self._address:
            pass
        elif 'address' in self.keystore:
            self._address = decode_hex(self.keystore['address'])
        elif not self.locked:
            self._address = keys.privtoaddr(self.privkey)
        else:
            return None
        return checksum_encode(encode_hex(self._address))
Beispiel #9
0
    def test_allowances(self):

        # a
        # aa             ab
        # aaa  aab       aba
        # aaaa aaba aabb abaa

        genesis_hash = decode_hex("fca5e1a248b8fee34db137da5e38b41f95d11feb5a8fa192a150d8d5d8de1c59")

        null_hash = decode_hex("0000000000000000000000000000000000000000000000000000000000000000")
        # print encode_hex(null_hash)

        k0_addr = encode_hex(keys.privtoaddr(t.k0))
        k1_addr = encode_hex(keys.privtoaddr(t.k1))
        k2_addr = encode_hex(keys.privtoaddr(t.k2))

        contract_addr = encode_hex(keys.privtoaddr(t.k9))

        self.assertEqual(k1_addr, '7d577a597b2742b498cb5cf0c26cdcd726d39e6e')

        self.assertEqual(self.rc.balanceOf(keys.privtoaddr(t.k0), genesis_hash), 2100000000000000)

        self.rc.transfer(k1_addr, 1000000, genesis_hash, sender=t.k0, startgas=200000)

        # self.s.block.timestamp = self.s.block.timestamp + 100
        # self.s = t.state()

        window_index = 4 # index of genesis hash in struct

        self.assertEqual(self.rc.balanceOf(keys.privtoaddr(t.k0), genesis_hash), 2100000000000000-1000000)
        self.assertEqual(self.rc.balanceOf(k1_addr, genesis_hash), 1000000)

        with self.assertRaises(TransactionFailed):
            self.rc.transferFrom(k0_addr, k1_addr, 400000, genesis_hash, sender=t.k2, startgas=200000)

        self.rc.approve(k2_addr, 500000, genesis_hash, sender=t.k0, startgas=200000)

        with self.assertRaises(TransactionFailed):
            self.rc.transferFrom(k0_addr, k1_addr, 600000, genesis_hash, sender=t.k2, startgas=200000)


        self.mine()
        start_bal = self.rc.balanceOf(k0_addr, genesis_hash)

        self.rc.transferFrom(k0_addr, k1_addr, 400000, genesis_hash, sender=t.k2, startgas=200000)
        #self.assertEqual(self.rc.balanceOf(k1_addr, genesis_hash), 1000000-500000)

        self.mine()

        self.assertEqual(self.rc.balanceOf(k1_addr, genesis_hash), 400000+1000000)
        self.assertEqual(self.rc.balanceOf(k0_addr, genesis_hash), start_bal - 400000)

        with self.assertRaises(TransactionFailed):
            self.rc.transferFrom(k0_addr, 400000, genesis_hash, sender=t.k2, startgas=200000)
Beispiel #10
0
    def new_contract_proxy(self, contract_interface, address):
        """ Return a proxy for interacting with a smart contract.

        Args:
            contract_interface: The contract interface as defined by the json.
            address: The contract's address.
        """
        sender = self.sender or privtoaddr(self.privkey)

        return ContractProxy(
            sender,
            contract_interface,
            address,
            self.eth_call,
            self.send_transaction,
            self.eth_estimateGas,
        )
Beispiel #11
0
    def test_register_and_fetch(self):

        # a
        # aa             ab
        # aaa  aab       aba
        # aaaa aaba aabb abaa
        #self.c.mine()
        #self.s = self.c.head_state

        genesis_hash = decode_hex("fca5e1a248b8fee34db137da5e38b41f95d11feb5a8fa192a150d8d5d8de1c59")

        null_hash = decode_hex("0000000000000000000000000000000000000000000000000000000000000000")
        # print encode_hex(null_hash)

        k0_addr = encode_hex(keys.privtoaddr(t.k0))
        k1_addr = encode_hex(keys.privtoaddr(t.k1))
        k2_addr = encode_hex(keys.privtoaddr(t.k2))

        contract_addr = encode_hex(keys.privtoaddr(t.k9))

        self.assertEqual(k1_addr, '7d577a597b2742b498cb5cf0c26cdcd726d39e6e')

        self.assertEqual(self.rc.balanceOf(keys.privtoaddr(t.k0), genesis_hash), 2100000000000000)


        self.rc.transfer(k1_addr, 1000000, genesis_hash, sender=t.k0)

        # self.s.timestamp = self.s.timestamp + 100
        # self.s = t.state()

        # print self.s.gas_used - u
        u = self.s.gas_used
        # print self.s.get_balance(k0_addr)

        window_index = 4 # index of genesis hash in struct

        self.assertEqual(self.rc.balanceOf(keys.privtoaddr(t.k0), genesis_hash), 2100000000000000-1000000)
        self.assertEqual(self.rc.balanceOf(k1_addr, genesis_hash), 1000000)

        genesis_branch = self.rc.branches(genesis_hash);
        self.assertEqual(null_hash, genesis_branch[0])
        self.assertEqual(0, genesis_branch[window_index], "Genesis hash window is 0")

        madeup_block_hash = decode_hex(sha3_256('pants').hexdigest())

        dummy_merkle_root_aa = decode_hex(sha3_256('aa').hexdigest())
        dummy_merkle_root_ab = decode_hex(sha3_256('ab').hexdigest())

        dummy_merkle_root_aab = decode_hex(sha3_256('aab').hexdigest())
        dummy_merkle_root_aba = decode_hex(sha3_256('aba').hexdigest())
        dummy_merkle_root_abb = decode_hex(sha3_256('abb').hexdigest())

        dummy_merkle_root_aaaa = decode_hex(sha3_256('aaaa').hexdigest())
        dummy_merkle_root_aaba = decode_hex(sha3_256('aaba').hexdigest())
        dummy_merkle_root_abaa = decode_hex(sha3_256('abaa').hexdigest())

        failed = False
        try:
            branch_aa_hash = self.rc.createBranch(genesis_hash, dummy_merkle_root_aa, contract_addr, startgas=200000)
        except TransactionFailed:
            failed = True
        self.assertTrue(failed, "You can't build on a block in the window in which it was created")

        self.mine(secs=86400)

        branch_aa_hash = self.rc.createBranch(genesis_hash, dummy_merkle_root_aa, contract_addr)

        self.assertEqual(1, len(self.rc.getWindowBranches(1)))
        self.assertEqual([branch_aa_hash], self.rc.getWindowBranches(1))

        aa_branch = self.rc.branches(branch_aa_hash);
        self.assertEqual(1, aa_branch[window_index], "First branch window is 1")

        self.mine(secs=86400*4)

        branch_ab_hash = self.rc.createBranch(genesis_hash, dummy_merkle_root_ab, contract_addr)

        ab_branch = self.rc.branches(branch_ab_hash);
        self.assertEqual(5, ab_branch[window_index])
        self.assertEqual(5, ab_branch[window_index], "window of branch created a few days later is 5, despite having skipped several days")

        self.mine(secs=86400)

        # print encode_hex(self.rc.branches(branch_ab_hash)[0])

        branch_aab_hash = self.rc.createBranch(branch_aa_hash, dummy_merkle_root_aab, contract_addr)
        branch_aba_hash = self.rc.createBranch(branch_ab_hash, dummy_merkle_root_aba, contract_addr)
        self.assertEqual(2, len(self.rc.getWindowBranches(6)))
        self.assertEqual([branch_aab_hash, branch_aba_hash], self.rc.getWindowBranches(6))

        self.mine(secs=86400)

        null_test_merkle_root = decode_hex(sha3_256('nulltest').hexdigest())

        failed = False
        try:
            self.rc.createBranch(null_hash, null_test_merkle_root, contract_addr, startgas=200000)
            self.c.mine()
        except TransactionFailed:
            failed = True 
        self.assertTrue(failed, "You cannot create a branch with a null parent hash")

        self.assertEqual(self.rc.balanceOf(k1_addr, branch_aa_hash), 1000000)

        self.assertTrue(self.rc.isAmountSpendable(k1_addr, 1000000, branch_aa_hash))
        self.assertTrue(self.rc.isAmountSpendable(k1_addr, 1, branch_ab_hash))
        self.assertFalse(self.rc.isAmountSpendable(k1_addr, 1000001, branch_ab_hash))

        failed = False
        try:
            self.rc.createBranch(branch_ab_hash, dummy_merkle_root_aba, contract_addr, startgas=200000)
            self.c.mine()
        except TransactionFailed:
            failed = True
        self.assertTrue(failed, "You can only create a branch with a given hash once")

        #print "Gas used to send coins after %d blocks: %d" % (2, self.s.gas_used - u)
        self.rc.transfer(k2_addr, 500000, branch_aa_hash, sender=t.k1)
        #print "Gas used to send coins after %d blocks: %d" % (2, self.s.block.gas_used - u)

        self.assertEqual(self.rc.balanceOf(k2_addr, branch_aa_hash), 500000)
        self.assertEqual(self.rc.balanceOf(k2_addr, branch_ab_hash), 0)

        branch_hash = branch_aba_hash
        for i in range(0,10):
            dummy_merkle_root = decode_hex(sha3_256('dummy' + str(i)).hexdigest())
            branch_hash = self.rc.createBranch(branch_hash, dummy_merkle_root, contract_addr)
            self.mine(secs=86400)
            # print encode_hex(branch_hash)

        u = self.c.block.gas_used
        self.rc.transfer(k2_addr, 500000, branch_hash, sender=t.k1)

        gas_used = self.c.block.gas_used - u
        #print "Gas used to send coins after %d blocks: %d" % (i+1, gas_used)
        # self.assertTrue(u < 130000, "100 branches read in less than 130000 gas")

        failed = False
        try:
            self.rc.transfer(k2_addr, 1, branch_aba_hash, sender=t.k1)
        except:
            failed = True


        k0_bal = self.rc.balanceOf(k0_addr, branch_ab_hash)
        #print k0_bal
        self.rc.transfer(k2_addr, 5, branch_aba_hash, sender=t.k0)
        branch_abaa_hash = self.rc.createBranch(branch_aba_hash, dummy_merkle_root_abaa, contract_addr)
        self.mine(secs=86400)
        k0_bal_spent = self.rc.balanceOf(k0_addr, branch_abaa_hash)

        #print k0_bal_spent
        self.assertEqual(k0_bal_spent, k0_bal - 5)

        self.assertFalse(self.rc.transfer(k2_addr, 5, branch_ab_hash, sender=t.k0), "Attempting to send coins on an earlier branch returns false")
        self.assertEqual(k0_bal_spent, k0_bal - 5, "Attempt to send coins on an earlier branch left balance unchanged")
        return
Beispiel #12
0
    def generateTX(self):
        try:
            address = self.textbox_receiver.text()
            if not len(address) == 42:
                raise Exception(
                    'Address must have length 42 (beginning with "0x")')

            unitconv = {'wei (atto)':1, 'babbage (femto)':10**3, 'lovelace (pico)':10**6,\
                'shannon (nano)':10**9, 'szabo (micro)':10**12, 'finney (milli)':10**15,\
                'ether':10**18}
            unit = self.combobox_unit.currentText()

            amount = int(
                float(self.textbox_amount.text().replace(',', '.')) *
                unitconv[unit])
            if amount < 0:
                raise Exception('Amount must be greated than 0')

            nonce = int(self.textbox_nonce.text())
            if nonce < 0:
                raise Exception('Nonce must be greated than 0')

            gas_price = int(self.textbox_gasprice.text())
            if gas_price < 0:
                raise Exception('Gas price must be greated than 0')

            gas = int(self.textbox_gas.text())
            if gas < 0:
                raise Exception('Gas amount must be greated than 0')

            #data = self.textbox_data.text().encode('utf-8')
            data = self.textbox_data.text()

            # try to get data from base16 input
            try:
                ldata = ceil(len(data[2:]) /
                             2) if data[:2] == '0x' else ceil(len(data) / 2)
                data = int(data, 16).to_bytes(ldata, 'big')
            except ValueError as e:
                data = data.encode('utf-8')

            # from which field do we get the networkid?
            if (self.radiobutton_networkid_textbox.isChecked()):
                # textbox
                networkid = int(self.textbox_networkid.text())
            else:
                # drop down menu
                networkid = int(self.combobox_networkid.currentText()[:2])

            if networkid < 0:
                raise Exception('Network ID must be greated than 0')

            # how to retrieve the private key?
            if (self.radiobutton_key.isChecked()):
                # directly
                priv_key = self.textbox_privatekey.text()

            else:
                # keystore
                keystorefile = self.textbox_keystore.text()
                keystorepw = self.textbox_keystore_pw.text()

                with open(keystorefile, 'r') as kf:
                    jdata = jload(kf)

                priv_key = keys.decode_keystore_json(jdata, keystorepw)
                priv_key = self.safeBytesToHex(priv_key, 64)

            if not len(priv_key) in [64, 66]:
                raise Exception(
                    'Invalid private key length: got {}, expected 64 or 66'.
                    format(len(priv_key)))

            #address_sender = hex(int.from_bytes(keys.privtoaddr(priv_key), 'big'))
            address_sender = self.safeBytesToHex(keys.privtoaddr(priv_key), 40)
            self.label_address_sender.setText(address_sender)

            priv_key = int(priv_key, 16)

            # generate the tx data
            tx = Transaction(nonce, gas_price, gas, address, amount, data)
            tx_signed = tx.sign(priv_key)
            tx_data = hex(int.from_bytes(rlpencode(tx_signed), 'big'))
            self.textbrowser_result.setPlainText(str(tx_data))
        except Exception as e:
            print(dir(e))
            self.textbrowser_result.setPlainText('ERROR: \n' + str(e))
Beispiel #13
0
def test_account_creation(account, password, privkey, uuid):
    assert not account.locked
    assert account.privkey == privkey
    assert account.address == privtoaddr(privkey)
    assert account.uuid == uuid