Пример #1
0
    def test_loop(self):
        loop = asyncio.get_event_loop()
        responder_shaked = asyncio.Event()
        server_shaked = asyncio.Event()
        responder_key = ECPrivkey.generate_random_key()
        initiator_key = ECPrivkey.generate_random_key()
        async def cb(reader, writer):
            t = LNResponderTransport(responder_key.get_secret_bytes(), reader, writer)
            self.assertEqual(await t.handshake(), initiator_key.get_public_key_bytes())
            t.send_bytes(b'hello from server')
            self.assertEqual(await t.read_messages().__anext__(), b'hello from client')
            responder_shaked.set()
        server_future = asyncio.ensure_future(asyncio.start_server(cb, '127.0.0.1', 42898))
        loop.run_until_complete(server_future)
        server = server_future.result()  # type: asyncio.Server
        async def connect():
            peer_addr = LNPeerAddr('127.0.0.1', 42898, responder_key.get_public_key_bytes())
            t = LNTransport(initiator_key.get_secret_bytes(), peer_addr)
            await t.handshake()
            t.send_bytes(b'hello from client')
            self.assertEqual(await t.read_messages().__anext__(), b'hello from server')
            server_shaked.set()

        try:
            connect_future = asyncio.ensure_future(connect())
            loop.run_until_complete(responder_shaked.wait())
            loop.run_until_complete(server_shaked.wait())
        finally:
            server.close()
            loop.run_until_complete(server.wait_closed())
 def __init__(self, parent, title_label: str, pin_label: str,
              qr_data: dict):
     super().__init__()
     self.parent = parent
     self.pubkey = ECPrivkey(
         short_mnemonic.entropy_to_privkey(
             qr_data['entropy'])).get_public_key_hex()
     qr = QRCodeWidget(self.prepare_qr_data_for_display(qr_data))
     self.edit = QLineEdit()
     self.edit.setMaxLength(4)
     self.edit.setFixedWidth(50)
     self.edit.setFont(QFont("Monospace"))
     self.edit.textChanged.connect(self._on_change)
     self.addWidget(title_label, alignment=Qt.AlignCenter)
     self.addWidget(qr, alignment=Qt.AlignCenter)
     self.addWidget(pin_label, alignment=Qt.AlignCenter)
     self.addWidget(self.edit, alignment=Qt.AlignCenter)
Пример #3
0
def keypair():
    priv = ECPrivkey.generate_random_key().get_secret_bytes()
    k1 = Keypair(pubkey=privkey_to_pubkey(priv), privkey=priv)
    return k1
Пример #4
0
from bitcoin.core.key import use_libsecp256k1_for_signing
from bitcoin.core import x, b2x
from bitcoin.wallet import CBitcoinSecret
from electrum.ecc import ECPrivkey
from electrum.bitcoin import EncodeBase58Check

use_libsecp256k1_for_signing(True)

sechex = '535b755a4c265772c4f6c7e0316bfd21e24c9e47441989e14e8133c7cb2f41a3'
hashhex = '9039c54c1c34aa12b69b4dda962f501bb6c9cdb6745014ef326f5d4d0472aa99'

seckey = CBitcoinSecret.from_secret_bytes(x(sechex))
sig = seckey.sign(x(hashhex))
b_wif = str(seckey)
b_pub = b2x(seckey.pub)
b_sig = b2x(sig)

seckey = ECPrivkey(x(sechex))
sig = seckey.sign_transaction(x(hashhex))
e_wif = EncodeBase58Check(b'\x80' + seckey.get_secret_bytes() + b'\x01')
e_pub = seckey.get_public_key_hex(compressed=True)
e_sig = b2x(sig)

assert b_wif == e_wif
assert b_pub == e_pub
print("wif:", b_wif)
print("pub:", b_pub)
print("sighash:", hashhex)
print("bitcoinlib sig:", b_sig)
print("electrum sig:  ", e_sig)
Пример #5
0
    def test_loop(self):
        loop = asyncio.get_event_loop()
        responder_shaked = asyncio.Event()
        server_shaked = asyncio.Event()
        responder_key = ECPrivkey.generate_random_key()
        initiator_key = ECPrivkey.generate_random_key()
        messages_sent_by_client = [
            b'hello from client',
            b'long data from client ' + bytes(range(256)) * 100 +
            b'... client done',
            b'client is running out of things to say',
        ]
        messages_sent_by_server = [
            b'hello from server',
            b'hello2 from server',
            b'long data from server ' + bytes(range(256)) * 100 +
            b'... server done',
        ]

        async def read_messages(transport, expected_messages):
            ctr = 0
            async for msg in transport.read_messages():
                self.assertEqual(expected_messages[ctr], msg)
                ctr += 1
                if ctr == len(expected_messages):
                    return

        async def write_messages(transport, expected_messages):
            for msg in expected_messages:
                transport.send_bytes(msg)
                await asyncio.sleep(0.01)

        async def cb(reader, writer):
            t = LNResponderTransport(responder_key.get_secret_bytes(), reader,
                                     writer)
            self.assertEqual(await t.handshake(),
                             initiator_key.get_public_key_bytes())
            async with OldTaskGroup() as group:
                await group.spawn(read_messages(t, messages_sent_by_client))
                await group.spawn(write_messages(t, messages_sent_by_server))
            responder_shaked.set()

        async def connect():
            peer_addr = LNPeerAddr('127.0.0.1', 42898,
                                   responder_key.get_public_key_bytes())
            t = LNTransport(initiator_key.get_secret_bytes(),
                            peer_addr,
                            proxy=None)
            await t.handshake()
            async with OldTaskGroup() as group:
                await group.spawn(read_messages(t, messages_sent_by_server))
                await group.spawn(write_messages(t, messages_sent_by_client))
            server_shaked.set()

        async def f():
            server = await asyncio.start_server(cb, '127.0.0.1', 42898)
            try:
                async with OldTaskGroup() as group:
                    await group.spawn(connect())
                    await group.spawn(responder_shaked.wait())
                    await group.spawn(server_shaked.wait())
            finally:
                server.close()
                await server.wait_closed()

        loop.run_until_complete(f())
Пример #6
0
def seed_to_keypair(seed: List[str]) -> Tuple[bytes, str]:
    privkey = seed_to_privkey(seed)
    pubkey = ECPrivkey(privkey).get_public_key_hex()
    keypair = (privkey, pubkey)
    del privkey, pubkey
    return keypair
Пример #7
0
# Basic constants to build the TXNIN
wif = 'cQNjiPwYKMBr2oB3bWzf3rgBsu198xb8Nxxe51k6D3zVTA98L25N'
txid = x('6d500966f9e494b38a04545f0cea35fc7b3944e341a64b804fed71cdee11d434')
vout = 1
sats = 9999
script_type = 'p2sh'
binzero  = 2**32
sequence = binzero - 3
address = 'tb1qv9hg20f0g08d460l67ph6p4ukwt7m0ttqzj7mk'
sats_less_fees = sats - 200
locktime = 1602565200

# Build the Transaction Input
_, privkey, compressed = deserialize_privkey(wif)
pubkey = ECPrivkey(privkey).get_public_key_hex(compressed=compressed)
prevout = TxOutpoint(txid=txid, out_idx=vout)
txin = PartialTxInput(prevout=prevout)
txin.nsequence = sequence
txin.script_type = script_type
expiry = b2x(lx(b2x(locktime)))
redeem_script = compile([
    expiry, 'OP_CHECKLOCKTIMEVERIFY', 'OP_DROP', pubkey, 'OP_CHECKSIG'])
txin.redeem_script = x(redeem_script)

# Build the Transaction Output
txout = PartialTxOutput.from_address_and_value(address, sats_less_fees)

# Build and sign the transaction
tx = P2SHPartialTransaction.from_io([txin], [txout], locktime=locktime)
tx.version = 1
Пример #8
0
# Set testnet
set_testnet()

# Set mainnet
# set_mainnet()

# Number of addresses to generate:
n = 20

# Type of address
type = 'p2wpkh'

# type = 'p2wpkh-p2sh'
# type = 'p2pkh'


# https://www.secg.org/sec2-v2.pdf section 2.4.1
def get_priv():
    n = 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141'
    n = int(n.replace(' ', ''), 16)
    priv = randint(1, n - 1)
    return bytes.fromhex(f"{priv:064x}")


for i in range(0, n):
    priv = get_priv()
    wif = serialize_privkey(priv, True, '').replace(':', '')
    pubk = ECPrivkey(priv).get_public_key_bytes()
    addr = pubkey_to_address('p2wpkh', pubk.hex())
    print(f"WIF: {wif} Address: {addr}")