Ejemplo n.º 1
0
 def test_wallet_keys_storage(self):
     w = Wallet(directory=self.directory)
     # Testing password error not in bytes
     with self.assertRaises(ValueError):
         w.unlock('testpass')
     w.unlock(b'testpass')
     w.generate_keys()
     # Using one address to save used/unused addresses in the file
     w.get_unused_address()
     w._write_keys_to_file()
     # wallet 2 will read from saved file
     w2 = Wallet(directory=self.directory)
     w2._manually_initialize()
     for address, key in w.keys.items():
         key2 = w2.keys.pop(address)
         self.assertEqual(key, key2)
Ejemplo n.º 2
0
def execute(args: Namespace, wallet_passwd: str) -> None:
    from hathor.crypto.util import get_private_key_bytes, get_public_key_bytes_compressed
    from hathor.wallet import Wallet
    from hathor.wallet.util import generate_multisig_address, generate_multisig_redeem_script

    if (args.pubkey_count
            and args.pubkey_count > 16) or args.signatures_required > 16:
        print(
            'Error: maximum number of public keys or signatures required is 16'
        )
        return

    if not args.pubkey_count and not args.public_keys:
        print('Error: you must give at least pubkey_count or public_keys')
        return

    if args.dir:
        wallet = Wallet(directory=args.dir)
    else:
        wallet = Wallet()

    wallet.unlock(wallet_passwd.encode())

    if args.public_keys:
        public_keys_hex = args.public_keys.split(',')
        public_bytes = [bytes.fromhex(pkh) for pkh in public_keys_hex]
    else:
        # If not public keys as parameter, we need to create them
        public_bytes = []

        for i in range(args.pubkey_count):
            addr = wallet.get_unused_address()
            key = wallet.keys[addr]
            pk = key.get_private_key(wallet_passwd.encode())
            public_key_bytes = get_public_key_bytes_compressed(pk.public_key())
            public_bytes.append(public_key_bytes)
            print('------------------\n')
            print('Key {}\n'.format(i + 1))
            print('Private key: {}\n'.format(
                get_private_key_bytes(
                    pk,
                    encryption_algorithm=serialization.BestAvailableEncryption(
                        wallet_passwd.encode())).hex()))
            print('Public key: {}\n'.format(public_key_bytes.hex()))
            print('Address: {}\n'.format(addr))

    # Then we create the redeem script
    redeem_script = generate_multisig_redeem_script(args.signatures_required,
                                                    public_bytes)

    print('------------------\n')
    print('Redeem script:', redeem_script.hex())
    print('\n')

    # Then we created the multisig address
    address = generate_multisig_address(redeem_script)

    print('------------------\n')
    print('MultiSig address:', address)
    print('------------------\n\n')
Ejemplo n.º 3
0
    def test_insuficient_funds(self):
        w = Wallet(directory=self.directory)
        w.unlock(PASSWORD)

        # create transaction spending some value
        new_address = w.get_unused_address()
        out = WalletOutputInfo(decode_address(new_address), 100, timelock=None)
        with self.assertRaises(InsufficientFunds):
            w.prepare_transaction_compute_inputs(Transaction, outputs=[out])
class BaseSignatureTest(unittest.TestCase):
    __test__ = False

    def setUp(self):
        super().setUp()

        self.network = 'testnet'
        self.manager = self.create_peer(self.network, unlock_wallet=True)

        self.tmpdir = tempfile.mkdtemp()
        self.wallet = Wallet(directory=self.tmpdir)
        self.wallet.unlock(b'123')

    def tearDown(self):
        super().tearDown()
        shutil.rmtree(self.tmpdir)

    def test_generate_signature(self):
        add_new_blocks(self.manager, 1, advance_clock=1)
        add_blocks_unlock_reward(self.manager)
        tx = add_new_transactions(self.manager, 1, advance_clock=1)[0]

        address = self.wallet.get_unused_address()
        keypair = self.wallet.keys[address]
        private_key_hex = keypair.private_key_bytes.hex()

        private_key = keypair.get_private_key(b'123')
        public_key = private_key.public_key()

        parser = create_parser()

        # Generate signature to validate
        args = parser.parse_args([tx.get_struct().hex(), private_key_hex])
        f = StringIO()
        with capture_logs():
            with redirect_stdout(f):
                execute(args, '123')
        # Transforming prints str in array
        output = f.getvalue().strip().splitlines()

        signature = bytes.fromhex(output[0].split(':')[1].strip())

        # Now we validate that the signature is correct
        data_to_sign = tx.get_sighash_all()
        hashed_data = hashlib.sha256(data_to_sign).digest()
        self.assertIsNone(
            public_key.verify(signature, hashed_data,
                              ec.ECDSA(hashes.SHA256())))
Ejemplo n.º 5
0
 def test_block_increase_balance(self):
     # generate a new block and check if we increase balance
     w = Wallet(directory=self.directory)
     w.unlock(PASSWORD)
     new_address = w.get_unused_address()
     key = w.keys[new_address]
     out = WalletOutputInfo(decode_address(key.address),
                            BLOCK_REWARD,
                            timelock=None)
     tx = w.prepare_transaction(Transaction, inputs=[], outputs=[out])
     tx.update_hash()
     w.on_new_tx(tx)
     utxo = w.unspent_txs[settings.HATHOR_TOKEN_UID].get((tx.hash, 0))
     self.assertIsNotNone(utxo)
     self.assertEqual(w.balance[settings.HATHOR_TOKEN_UID],
                      WalletBalance(0, BLOCK_REWARD))
Ejemplo n.º 6
0
    def test_locked(self):
        # generate a new block and check if we increase balance
        w = Wallet(directory=self.directory)
        with self.assertRaises(OutOfUnusedAddresses):
            w.get_unused_address()

        # now it should work
        w.unlock(PASSWORD)
        w.get_unused_address()

        # lock wallet and fake that there are no more unused keys
        w.unused_keys = set()
        w.lock()
        with self.assertRaises(OutOfUnusedAddresses):
            w.get_unused_address()

        with self.assertRaises(WalletLocked):
            w.generate_keys()
Ejemplo n.º 7
0
    def test_wallet_create_transaction(self):
        genesis_private_key_bytes = get_private_key_bytes(
            self.genesis_private_key,
            encryption_algorithm=serialization.BestAvailableEncryption(
                PASSWORD))
        genesis_address = get_address_b58_from_public_key(
            self.genesis_public_key)
        # create wallet with genesis block key
        key_pair = KeyPair(private_key_bytes=genesis_private_key_bytes,
                           address=genesis_address,
                           used=True)
        keys = {}
        keys[key_pair.address] = key_pair
        w = Wallet(keys=keys, directory=self.directory)
        w.unlock(PASSWORD)
        genesis_blocks = [
            tx for tx in get_genesis_transactions(None) if tx.is_block
        ]
        genesis_block = genesis_blocks[0]
        genesis_value = sum([output.value for output in genesis_block.outputs])

        # wallet will receive genesis block and store in unspent_tx
        w.on_new_tx(genesis_block)
        for index in range(len(genesis_block.outputs)):
            utxo = w.unspent_txs[settings.HATHOR_TOKEN_UID].get(
                (genesis_block.hash, index))
            self.assertIsNotNone(utxo)
        self.assertEqual(w.balance[settings.HATHOR_TOKEN_UID],
                         WalletBalance(0, genesis_value))

        # create transaction spending this value, but sending to same wallet
        new_address = w.get_unused_address()
        out = WalletOutputInfo(decode_address(new_address), 100, timelock=None)
        tx1 = w.prepare_transaction_compute_inputs(Transaction, outputs=[out])
        tx1.storage = self.storage
        tx1.update_hash()
        self.storage.save_transaction(tx1)
        w.on_new_tx(tx1)
        self.assertEqual(len(w.spent_txs), 1)
        self.assertEqual(w.balance[settings.HATHOR_TOKEN_UID],
                         WalletBalance(0, genesis_value))

        # pass inputs and outputs to prepare_transaction, but not the input keys
        # spend output last transaction
        input_info = WalletInputInfo(tx1.hash, 1, None)
        new_address = w.get_unused_address()
        key2 = w.keys[new_address]
        out = WalletOutputInfo(decode_address(key2.address),
                               100,
                               timelock=None)
        tx2 = w.prepare_transaction_incomplete_inputs(Transaction,
                                                      inputs=[input_info],
                                                      outputs=[out],
                                                      tx_storage=self.storage)
        tx2.storage = self.storage
        tx2.update_hash()
        self.storage.save_transaction(tx2)
        w.on_new_tx(tx2)
        self.assertEqual(len(w.spent_txs), 2)
        self.assertEqual(w.balance[settings.HATHOR_TOKEN_UID],
                         WalletBalance(0, genesis_value))

        # test keypair exception
        with self.assertRaises(WalletLocked):
            key_pair.get_private_key(None)