Пример #1
0
 def test_example_6(self):
     tx_ins = []
     prev_tx = bytes.fromhex(
         '0d6fe5213c0b3291f208cba8bfb59b7476dffacc4e5cb66f6eb20a080843a299')
     prev_index = 13
     tx_ins.append(TxIn(prev_tx, prev_index, Script([]), 0xffffffff))
     tx_outs = []
     change_amount = int(0.33 * 100000000)
     change_h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2')
     change_script = p2pkh_script(change_h160)
     tx_outs.append(TxOut(amount=change_amount,
                          script_pubkey=change_script))
     target_amount = int(0.1 * 100000000)
     target_h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf')
     target_script = p2pkh_script(target_h160)
     tx_outs.append(TxOut(amount=target_amount,
                          script_pubkey=target_script))
     transaction = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     z = transaction.sig_hash(0)
     private_key = PrivateKey(secret=8675309)
     der = private_key.sign(z).der()
     sig = der + SIGHASH_ALL.to_bytes(1, 'big')
     sec = private_key.point.sec()
     transaction.tx_ins[0].script_sig = Script([sig, sec])
     want = '010000000199a24308080ab26e6fb65c4eccfadf76749bb5bfa8cb08f291320b3c21e56f0d0d0000006b4830450221008ed46aa2cf12d6d81065bfabe903670165b538f65ee9a3385e6327d80c66d3b502203124f804410527497329ec4715e18558082d489b218677bd029e7fa306a72236012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff02408af701000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac80969800000000001976a914507b27411ccf7f16f10297de6cef3f291623eddf88ac00000000'
     self.assertEqual(transaction.serialize().hex(), want)
Пример #2
0
 def test_exercise_4(self):
     prev_tx = bytes.fromhex(
         '75a1c4bc671f55f626dda1074c7725991e6f68b8fcefcfca7b64405ca3b45f1c')
     prev_index = 1
     target_address = 'miKegze5FQNCnGw6PKyqUbYUeBa4x2hFeM'
     target_amount = 0.01
     change_address = 'mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2'
     change_amount = 0.009
     secret = 8675309
     priv = PrivateKey(secret=secret)
     tx_ins = []
     tx_ins.append(TxIn(prev_tx, prev_index, Script([]), 0xffffffff))
     tx_outs = []
     h160 = decode_base58(target_address)
     script_pubkey = p2pkh_script(h160)
     target_satoshis = int(target_amount * 100000000)
     tx_outs.append(TxOut(target_satoshis, script_pubkey))
     h160 = decode_base58(change_address)
     script_pubkey = p2pkh_script(h160)
     change_satoshis = int(change_amount * 100000000)
     tx_outs.append(TxOut(change_satoshis, script_pubkey))
     tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     self.assertTrue(tx_obj.sign_input(0, priv))
     self.assertTrue(tx_obj.verify())
     want = '01000000011c5fb4a35c40647bcacfeffcb8686f1e9925774c07a1dd26f6551f67bcc4a175010000006b483045022100a08ebb92422b3599a2d2fcdaa11f8f807a66ccf33e7f4a9ff0a3c51f1b1ec5dd02205ed21dfede5925362b8d9833e908646c54be7ac6664e31650159e8f69b6ca539012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff0240420f00000000001976a9141ec51b3654c1f1d0f4929d11a1f702937eaf50c888ac9fbb0d00000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac00000000'
     self.assertEqual(tx_obj.serialize().hex(), want)
 def test_exercise_4(self):
     last_block_hex = '000000000d65610b5af03d73ed67704713c9b734d87cf4b970d39a0416dd80f9'
     last_block = bytes.fromhex(last_block_hex)
     secret = little_endian_to_int(
         hash256(b'Jimmy Song Programming Blockchain'))
     private_key = PrivateKey(secret=secret)
     addr = private_key.point.address(testnet=True)
     h160 = decode_base58(addr)
     target_address = 'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv'
     self.assertEqual(addr, target_address)
     filter_size = 30
     filter_num_functions = 5
     filter_tweak = 90210  # FILL THIS IN
     target_h160 = decode_base58(target_address)
     target_script = p2pkh_script(target_h160)
     fee = 5000  # fee in satoshis
     node = SimpleNode('tbtc.programmingblockchain.com',
                       testnet=True,
                       logging=False)
     bf = BloomFilter(filter_size, filter_num_functions, filter_tweak)
     bf.add(h160)
     node.handshake()
     node.send(b'filterload', bf.filterload())
     getheaders_message = GetHeadersMessage(start_block=last_block)
     node.send(getheaders_message.command, getheaders_message.serialize())
     headers_envelope = node.wait_for_commands([HeadersMessage.command])
     stream = headers_envelope.stream()
     headers = HeadersMessage.parse(stream)
     get_data_message = GetDataMessage()
     for block in headers.blocks:
         self.assertTrue(block.check_pow())
         if last_block is not None:
             self.assertEqual(block.prev_block, last_block)
         last_block = block.hash()
         get_data_message.add_data(FILTERED_BLOCK_DATA_TYPE, last_block)
     node.send(get_data_message.command, get_data_message.serialize())
     prev_tx = None
     while prev_tx is None:
         envelope = node.wait_for_commands([b'merkleblock', b'tx'])
         stream = envelope.stream()
         if envelope.command == b'merkleblock':
             mb = MerkleBlock.parse(stream)
             self.assertTrue(mb.is_valid())
         else:
             prev = Tx.parse(stream, testnet=True)
             for i, tx_out in enumerate(prev.tx_outs):
                 if tx_out.script_pubkey.address(testnet=True) == addr:
                     prev_tx = prev.hash()
                     prev_index = i
                     prev_amount = tx_out.amount
                     break
     tx_in = TxIn(prev_tx, prev_index)
     output_amount = prev_amount - fee
     tx_out = TxOut(output_amount, target_script)
     tx_obj = Tx(1, [tx_in], [tx_out], 0, testnet=True)
     tx_obj.sign_input(0, private_key)
     self.assertEqual(
         tx_obj.serialize().hex(),
         '010000000194e631abb9e1079ec72a1616a3aa0111c614e65b96a6a4420e2cc6af9e6cc96e000000006a47304402203cc8c56abe1c0dd043afa9eb125dafbebdde2dd4cd7abf0fb1aae0667a22006e02203c95b74d0f0735bbf1b261d36e077515b6939fc088b9d7c1b7030a5e494596330121021cdd761c7eb1c90c0af0a5963e94bf0203176b4662778d32bd6d7ab5d8628b32ffffffff01f8829800000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788ac00000000'
     )
Пример #4
0
 def test_example_1(self):
     tx_ins = []
     prev_tx = bytes.fromhex(
         '8be2f69037de71e3bc856a6627ed3e222a7a2d0ce81daeeb54a3aea8db274149')
     prev_index = 4
     tx_ins.append(TxIn(prev_tx, prev_index))
     tx_outs = []
     h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2')
     tx_outs.append(
         TxOut(
             amount=int(0.38 * 100000000),
             script_pubkey=p2pkh_script(h160),
         ))
     h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf')
     tx_outs.append(
         TxOut(
             amount=int(0.1 * 100000000),
             script_pubkey=p2pkh_script(h160),
         ))
     tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     z = tx_obj.sig_hash(0)
     pk = PrivateKey(secret=8675309)
     der = pk.sign(z).der()
     sig = der + SIGHASH_ALL.to_bytes(1, 'big')
     sec = pk.point.sec()
     tx_obj.tx_ins[0].script_sig = Script([sig, sec])
     want = '0100000001494127dba8aea354ebae1de80c2d7a2a223eed27666a85bce371de3790f6e28b040000006b483045022100fa3032607b50e8cb05bedc9d43f986f19dedc22e61320b9765061c5cd9c66946022072d514ef637988515bfa59a660596206de68f0ed4090d0a398e70f4d81370dfb012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff0280d54302000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac80969800000000001976a914507b27411ccf7f16f10297de6cef3f291623eddf88ac00000000'
     self.assertEqual(tx_obj.serialize().hex(), want)
def new_commitment_tx(node, current_channel, cost, secret_hash):

    remote_peer = current_channel.peer

    # Create input using the output from the funding tx
    tx_in = TxIn(bytes.fromhex(current_channel.funding_tx.id()), 0)

    # Create 3 outputs. 1 to nodeA and 1 to nodeB and 1 to an HTLC script
    script_1 = p2pkh_script(decode_base58(node.address))
    tx_out_1 = TxOut(amount=current_channel.local_amt - cost,
                     script_pubkey=script_1)

    script_2 = p2pkh_script(decode_base58(remote_peer.btc_addr.decode()))
    tx_out_2 = TxOut(amount=current_channel.remote_amt, script_pubkey=script_2)

    #script_3 HTLC
    script_3 = Script([
        99, 168, secret_hash, 136, 118, 169,
        hash160(remote_peer.public_key.sec()), 103,
        encode_varint(1000), 177, 117, 118, 169,
        hash160(node.public_key.sec()), 104, 136, 172
    ])
    tx_out_3 = TxOut(amount=cost, script_pubkey=script_3)

    # Construct the commitment tx object
    commitment_tx = Tx(1, [tx_in], [tx_out_1, tx_out_2, tx_out_3], 0, True)

    #sign it
    commitment_tx.tx_ins[0].script_sig = get_script_sig(
        commitment_tx, node.private_key)

    return commitment_tx
Пример #6
0
    def test_sign_input(self):
        private_key = PrivateKey(secret=8675309)
        tx_ins = []
        prev_tx = bytes.fromhex(
            '0025bc3c0fa8b7eb55b9437fdbd016870d18e0df0ace7bc9864efc38414147c8')
        tx_ins.append(
            TxIn(
                prev_tx=prev_tx,
                prev_index=0,
                script_sig=b'',
                sequence=0xffffffff,
            ))
        tx_outs = []
        h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2')
        tx_outs.append(
            TxOut(amount=int(0.99 * 100000000),
                  script_pubkey=p2pkh_script(h160)))
        h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf')
        tx_outs.append(
            TxOut(amount=int(0.1 * 100000000),
                  script_pubkey=p2pkh_script(h160)))

        tx = Tx(
            version=1,
            tx_ins=tx_ins,
            tx_outs=tx_outs,
            locktime=0,
            testnet=True,
        )
        self.assertTrue(tx.sign_input(0, private_key, SIGHASH_ALL))
Пример #7
0
 def test_exercise_6(self):
     last_block_hex = '000000000d65610b5af03d73ed67704713c9b734d87cf4b970d39a0416dd80f9'
     secret = little_endian_to_int(
         hash256(b'Jimmy Song Programming Blockchain'))
     private_key = PrivateKey(secret=secret)
     addr = private_key.point.address(testnet=True)
     h160 = decode_base58(addr)
     target_address = 'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv'
     self.assertEqual(addr, target_address)
     target_h160 = decode_base58(target_address)
     target_script = p2pkh_script(target_h160)
     fee = 5000
     node = SimpleNode('tbtc.programmingblockchain.com', testnet=True)
     bf = BloomFilter(30, 5, 90210)
     bf.add(h160)
     node.handshake()
     node.send(bf.filterload())
     start_block = bytes.fromhex(last_block_hex)
     getheaders = GetHeadersMessage(start_block=start_block)
     node.send(getheaders)
     headers = node.wait_for(HeadersMessage)
     last_block = None
     getdata = GetDataMessage()
     for b in headers.blocks:
         if not b.check_pow():
             raise RuntimeError('proof of work is invalid')
         if last_block is not None and b.prev_block != last_block:
             raise RuntimeError('chain broken')
         getdata.add_data(FILTERED_BLOCK_DATA_TYPE, b.hash())
         last_block = b.hash()
     node.send(getdata)
     prev_tx, prev_index, prev_tx_obj = None, None, None
     while prev_tx is None:
         message = node.wait_for(MerkleBlock, Tx)
         if message.command == b'merkleblock':
             if not message.is_valid():
                 raise RuntimeError('invalid merkle proof')
         else:
             message.testnet = True
             for i, tx_out in enumerate(message.tx_outs):
                 if tx_out.script_pubkey.address(testnet=True) == addr:
                     prev_tx = message.hash()
                     prev_index = i
                     prev_amount = tx_out.amount
                     self.assertEqual(
                         message.id(),
                         '6ec96c9eafc62c0e42a4a6965be614c61101aaa316162ac79e07e1b9ab31e694'
                     )
                     self.assertEqual(i, 0)
                     break
     tx_in = TxIn(prev_tx, prev_index)
     output_amount = prev_amount - fee
     tx_out = TxOut(output_amount, target_script)
     tx_obj = Tx(1, [tx_in], [tx_out], 0, testnet=True)
     tx_obj.sign_input(0, private_key)
     self.assertEqual(
         tx_obj.serialize().hex(),
         '010000000194e631abb9e1079ec72a1616a3aa0111c614e65b96a6a4420e2cc6af9e6cc96e000000006a47304402203cc8c56abe1c0dd043afa9eb125dafbebdde2dd4cd7abf0fb1aae0667a22006e02203c95b74d0f0735bbf1b261d36e077515b6939fc088b9d7c1b7030a5e494596330121021cdd761c7eb1c90c0af0a5963e94bf0203176b4662778d32bd6d7ab5d8628b32ffffffff01f8829800000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788ac00000000'
     )
 def test_base58(self):
     addr = '1BenRpVUFK65JFWcQSuHnJKzc4M8ZP8Eqa'
     h160 = unhexlify('0074d691da1574e6b3c192ecfb52cc8984ee7b6c56')
     self.assertEqual(decode_base58(addr), h160)
     self.assertRaises(ValueError, decode_base58, addr+'1')
     got = encode_base58_checksum(h160)
     self.assertEqual(got, addr)
     wif = '5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf'
     want = unhexlify('800000000000000000000000000000000000000000000000000000000000000001')
     self.assertEqual(decode_base58(wif, num_bytes=38, strip_leading_zeros=True), want)
Пример #9
0
 def test_address(self):
     address_1 = '1BenRpVUFK65JFWcQSuHnJKzc4M8ZP8Eqa'
     h160 = decode_base58(address_1)
     p2pkh_script_pubkey = p2pkh_script(h160)
     self.assertEqual(p2pkh_script_pubkey.address(), address_1)
     address_2 = 'mrAjisaT4LXL5MzE81sfcDYKU3wqWSvf9q'
     self.assertEqual(p2pkh_script_pubkey.address(testnet=True), address_2)
     address_3 = '3CLoMMyuoDQTPRD3XYZtCvgvkadrAdvdXh'
     h160 = decode_base58(address_3)
     p2sh_script_pubkey = p2sh_script(h160)
     self.assertEqual(p2sh_script_pubkey.address(), address_3)
     address_4 = '2N3u1R6uwQfuobCqbCgBkpsgBxvr1tZpe7B'
     self.assertEqual(p2sh_script_pubkey.address(testnet=True), address_4)
Пример #10
0
def get_output_info(num_outputs, amount_available):
    tx_outs = []
    amount = amount_available

    for i in range(num_outputs):
        target_address = input("Enter address of recipient: ")
        target_h160 = decode_base58(target_address)
        valid_amount = False
        target_amount = int(float(input("How much would you like to pay them (in tBTC)?  ")) * sat_in_bit)

        while(valid_amount  == False):

            if(target_amount > amount):
                print("Insufficient Funds")
                target_amount = int(float(input("How much would you like to pay them (in tBTC)?  ")) * sat_in_bit)
            else:
                print("Sufficient Funds")
                valid_amount = True

        amount = amount - target_amount
        print(str(amount/sat_in_bit)+" tBTC remaining")

        if(target_address[0]=='2'):
            print("This recipient is a P2SH")
            target_script = p2sh_script(target_h160)
            tx_outs.append(TxOut(amount = target_amount, script_pubkey = target_script))
        else:
            print("This recipient is a P2PKH")
            target_script = p2pkh_script(target_h160)
            tx_outs.append(TxOut(amount = target_amount, script_pubkey = target_script))


    if(amount > 0):
        print("There is a remainder of "+str(amount/sat_in_bit)+" tBTC. Please fill in recipient details:")

        target_address = input("Enter address of recipient: ")
        target_h160 = decode_base58(target_address)
        target_amount = amount

        if(target_address[0]=='2'):
            print("This recipient is a P2SH")
            target_script = p2sh_script(target_h160)
            tx_outs.append(TxOut(amount = target_amount, script_pubkey = target_script))
        else:
            print("This recipient is a P2PKH")
            target_script = p2pkh_script(target_h160)
            tx_outs.append(TxOut(amount = target_amount, script_pubkey = target_script))

    return tx_outs
Пример #11
0
def address_to_script_pubkey(s):
    if s[:1] in ('1', 'm', 'n'):
        # p2pkh
        h160 = decode_base58(s)
        return p2pkh_script(h160)
    elif s[:1] in ('2', '3'):
        # p2sh
        h160 = decode_base58(s)
        return p2sh_script(h160)
    elif s[:3] in ('bc1', 'tb1'):
        # p2wpkh
        raw_script = decode_bech32(s)
        return Script.parse(BytesIO(encode_varstr(raw_script)))
    else:
        raise RuntimeError('unknown type of address: {}'.format(s))
Пример #12
0
 def test_exercise_5(self):
     prev_tx_1 = bytes.fromhex(
         '11d05ce707c1120248370d1cbf5561d22c4f83aeba0436792c82e0bd57fe2a2f')
     prev_index_1 = 1
     prev_tx_2 = bytes.fromhex(
         '51f61f77bd061b9a0da60d4bedaaf1b1fad0c11e65fdc744797ee22d20b03d15')
     prev_index_2 = 1
     target_address = 'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv'
     target_amount = 0.0429
     secret = 8675309
     priv = PrivateKey(secret=secret)
     tx_ins = []
     tx_ins.append(TxIn(prev_tx_1, prev_index_1, Script([]), 0xffffffff))
     tx_ins.append(TxIn(prev_tx_2, prev_index_2, Script([]), 0xffffffff))
     tx_outs = []
     h160 = decode_base58(target_address)
     script_pubkey = p2pkh_script(h160)
     target_satoshis = int(target_amount * 100000000)
     tx_outs.append(TxOut(target_satoshis, script_pubkey))
     tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     self.assertTrue(tx_obj.sign_input(0, priv))
     self.assertTrue(tx_obj.sign_input(1, priv))
     self.assertTrue(tx_obj.verify())
     want = '01000000022f2afe57bde0822c793604baae834f2cd26155bf1c0d37480212c107e75cd011010000006a47304402204cc5fe11b2b025f8fc9f6073b5e3942883bbba266b71751068badeb8f11f0364022070178363f5dea4149581a4b9b9dbad91ec1fd990e3fa14f9de3ccb421fa5b269012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff153db0202de27e7944c7fd651ec1d0fab1f1aaed4b0da60d9a1b06bd771ff651010000006b483045022100b7a938d4679aa7271f0d32d83b61a85eb0180cf1261d44feaad23dfd9799dafb02205ff2f366ddd9555f7146861a8298b7636be8b292090a224c5dc84268480d8be1012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff01d0754100000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788ac00000000'
     self.assertEqual(tx_obj.serialize().hex(), want)
Пример #13
0
    def from_address(cls, address):
        testnet = address.testnet
        addr = address.addr
        try:  # Bech32
            witver, decoded = bech32_address_decode(addr, testnet=testnet)
            if witver != 0:
                raise NotImplementedError(
                    "SegWit versions > 0 not yet supported.")
            if len(decoded) == 20:
                return p2wpkh_script(bytes(decoded))
            # bech32_decode raises error on all other lens
            else:  # len = 32
                return p2wsh_script(bytes(decoded))
        except (Bech32Error, NotImplementedError):
            pass
        try:  # Base58
            parsed = decode_base58(addr)
            if testnet:
                pkh = LEGACY_TEST_PREFIX[:2]
                sh = LEGACY_TEST_PREFIX[2]
            else:
                pkh = LEGACY_MAIN_PREFIX[:1]
                sh = LEGACY_MAIN_PREFIX[1]
            if addr[0] in pkh:
                return p2pkh_script(parsed)
            elif addr[0] == sh:
                return p2sh_script(parsed)
            else:
                raise ScriptError("Invalid mainnet legacy address prefix.")

        except Exception as e:
            raise ScriptError(f"Failed to parse address. Error: {e}")
Пример #14
0
 def test_exercise_2(self):
     block_hash = bytes.fromhex(
         '0000000053787814ed9dd8c029d0a0a9af4ab8ec0591dc31bdc4ab31fae88ce9')
     passphrase = b'Jimmy Song Programming Blockchain'  # FILL THIS IN
     secret = little_endian_to_int(hash256(passphrase))
     private_key = PrivateKey(secret=secret)
     addr = private_key.point.address(testnet=True)
     filter_size = 30
     filter_num_functions = 5
     filter_tweak = 90210  # FILL THIS IN
     h160 = decode_base58(addr)
     bf = BloomFilter(filter_size, filter_num_functions, filter_tweak)
     bf.add(h160)
     node = SimpleNode('tbtc.programmingblockchain.com',
                       testnet=True,
                       logging=False)
     node.handshake()
     node.send(bf.filterload())
     getdata = GetDataMessage()
     getdata.add_data(FILTERED_BLOCK_DATA_TYPE, block_hash)
     node.send(getdata)
     mb = node.wait_for(MerkleBlock)
     tx = node.wait_for(Tx)
     self.assertEqual(
         tx.serialize().hex(),
         '0100000002a663815ab2b2ba5f53e442f9a2ea6cc11bbcd98fb1585e48a134bd870dbfbd6a000000006a47304402202151107dc2367cf5a9e2429cde0641c252374501214ce52069fbca1320180aa602201a43b5d4f91e48514c00c01521dc04f02c57f15305adc4eaad01c418f6e7a1180121031dbe3aff7b9ad64e2612b8b15e9f5e4a3130663a526df91abfb7b1bd16de5d6effffffff618b00a343488bd62751cf21f368ce3be76e3a0323fdc594a0d24f27a1155cd2000000006a473044022024c4dd043ab8637c019528b549e0b10333b2dfa83e7ca66776e401ad3fc31b6702207d4d1d73ac8940c59c57c0b7daf084953324154811c10d06d0563947a88f99b20121031dbe3aff7b9ad64e2612b8b15e9f5e4a3130663a526df91abfb7b1bd16de5d6effffffff0280969800000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788aca0ce6594000000001976a9146e13971913b9aa89659a9f53d327baa8826f2d7588ac00000000'
     )
Пример #15
0
 def test_address(self):
     address_1 = '3CLoMMyuoDQTPRD3XYZtCvgvkadrAdvdXh'
     h160 = decode_base58(address_1)
     p2sh_script_pubkey = P2SHScriptPubKey(h160)
     self.assertEqual(p2sh_script_pubkey.address(), address_1)
     address_2 = '2N3u1R6uwQfuobCqbCgBkpsgBxvr1tZpe7B'
     self.assertEqual(p2sh_script_pubkey.address(testnet=True), address_2)
Пример #16
0
 def test_address(self):
     address_1 = '1BenRpVUFK65JFWcQSuHnJKzc4M8ZP8Eqa'
     h160 = decode_base58(address_1)
     p2pkh_script_pubkey = P2PKHScriptPubKey(h160)
     self.assertEqual(p2pkh_script_pubkey.address(), address_1)
     address_2 = 'mrAjisaT4LXL5MzE81sfcDYKU3wqWSvf9q'
     self.assertEqual(p2pkh_script_pubkey.address(testnet=True), address_2)
Пример #17
0
 def test_example_5(self):
     tx_ins = []
     prev_tx = bytes.fromhex('0d6fe5213c0b3291f208cba8bfb59b7476dffacc4e5cb66f6eb20a080843a299')
     prev_index = 13
     tx_ins.append(TxIn(prev_tx, prev_index, Script([]), 0xffffffff))
     tx_outs = []
     change_amount = int(0.33 * 100000000)
     change_h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2')
     change_script = p2pkh_script(change_h160)
     tx_outs.append(TxOut(change_amount, change_script))
     target_amount = int(0.1 * 100000000)
     target_h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf')
     target_script = p2pkh_script(target_h160)
     tx_outs.append(TxOut(target_amount, target_script))
     transaction = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     want = '010000000199a24308080ab26e6fb65c4eccfadf76749bb5bfa8cb08f291320b3c21e56f0d0d00000000ffffffff02408af701000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac80969800000000001976a914507b27411ccf7f16f10297de6cef3f291623eddf88ac00000000'
     self.assertEqual(transaction.serialize().hex(), want)
Пример #18
0
 def test_sign_input(self):
     private_key = PrivateKey(secret=8675309)
     tx_ins = []
     prev_tx = bytes.fromhex(
         '0025bc3c0fa8b7eb55b9437fdbd016870d18e0df0ace7bc9864efc38414147c8')
     tx_ins.append(TxIn(prev_tx, 0))
     tx_outs = []
     h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2')
     tx_outs.append(
         TxOut(amount=int(0.99 * 100000000),
               script_pubkey=P2PKHScriptPubKey(h160)))
     h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf')
     tx_outs.append(
         TxOut(amount=int(0.1 * 100000000),
               script_pubkey=P2PKHScriptPubKey(h160)))
     tx = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     self.assertTrue(tx.sign_input(0, private_key))
Пример #19
0
 def find_utxos(self, address):
     '''Returns transaction outputs that matches the address'''
     h160 = decode_base58(address)
     # utxos are a list of tuples: (hash, index, amount)
     utxos = []
     for index, tx_out in enumerate(self.tx_outs):
         if tx_out.script_pubkey.hash160() == h160:
             utxos.append((self.hash(), index, tx_out.amount))
     return utxos
Пример #20
0
def buildoutputs(pubkeysarr, amountsarr):
    tx_outs = []
    for i in range(len(pubkeysarr)):
        if amountsarr[i] != 0:
            tx_outs.append(
                TxOut(
                    amount=int(amountsarr[i]),
                    script_pubkey=p2pkh_script(decode_base58(pubkeysarr[i])),
                ))
    return tx_outs
Пример #21
0
    def send(self, adddress, amount, fee=500):
        # collect inputs
        unspent = self.unspent()
        tx_ins = []
        input_sum = 0
        for utxo in unspent:
            if input_sum >= amount + fee:
                break
            input_sum += utxo.amount
            tx_in = TxIn(utxo.tx_id, utxo.index)
            tx_ins.append(tx_in)

        # make sure we have enough
        assert input_sum > amount + fee, 'not enough satoshis'

        # send output
        send_h160 = decode_base58(address)
        send_script = p2pkh_script(send_h160)
        send_output = TxOut(amount=amount, script_pubkey=send_script)

        # change output
        change_amount = input_sum - amount - fee
        change_h160 = decode_base58(self.address())
        change_script = p2pkh_script(change_h160)
        change_output = TxOut(amount=amount, script_pubkey=change_script)

        # construct
        tx = Tx(1, tx_ins, [send_output, change_output], 0, True)

        # sign
        for i in range(len(tx_ins)):
            utxo = unspent[i]
            assert tx.sign_input(i, self.private_key, utxo.script_pubkey)
            print(f'signed {i}')
        print(tx)

        # broadcast
        import bit
        tx_hex = tx.serialize().hex()
        print(tx_hex)
        # raises a ConnectionError if it fails
        print(bit.network.NetworkAPI.broadcast_tx_testnet(tx_hex))
 def is_type_base58_address(hex_string):
     if type(hex_string) == str:
         if (hex_string[0] == "1"
                 or hex_string[0] == "3") and len(hex_string) == 34:
             try:
                 decoded_address = decode_base58(hex_string)
                 return check_format_hex_to_hash(
                     decoded_address.hex(), 20)
             except (ValueError, AssertionError):
                 return False
     return False
Пример #23
0
 def test_exercise_3_1(self):
     prev_tx = bytes.fromhex(
         'eb581753a4dbd6befeaaaa28a6f4576698ba13a07c03da693a65bce11cf9887a')
     prev_index = 1
     target_address = 'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv'
     target_amount = 0.04
     change_address = 'mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2'
     fee = 50000
     secret = 8675309
     private_key = PrivateKey(secret=secret)
     tx_ins = []
     tx_ins.append(TxIn(prev_tx, prev_index))
     tx_outs = []
     h160 = decode_base58(target_address)
     script_pubkey = p2pkh_script(h160)
     target_satoshis = int(target_amount * 100000000)
     tx_outs.append(TxOut(target_satoshis, script_pubkey))
     h160 = decode_base58(change_address)
     script_pubkey = p2pkh_script(h160)
     prev_amount = tx_ins[0].value(testnet=True)
     change_satoshis = prev_amount - target_satoshis - fee
     tx_outs.append(TxOut(change_satoshis, script_pubkey))
     tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     tx_obj.sign_input(0, private_key)
     if private_key.point.address(testnet=True) != change_address:
         raise RuntimeError(
             'Private Key does not correspond to Change Address, check priv_key and change_address'
         )
     if tx_ins[0].script_pubkey(
             testnet=True).instructions[2] != decode_base58(change_address):
         raise RuntimeError(
             'Output is not something you can spend with this private key. Check that the prev_tx and prev_index are correct'
         )
     if tx_obj.fee() > 0.05 * 100000000 or tx_obj.fee() <= 0:
         raise RuntimeError(
             'Check that the change amount is reasonable. Fee is {}'.format(
                 tx_obj.fee()))
     self.assertEqual(
         tx_obj.serialize().hex(),
         '01000000017a88f91ce1bc653a69da037ca013ba986657f4a628aaaafebed6dba4531758eb010000006a47304402204ce6e3877ed2e18d2165276cbdba241507ce72b44d8df640eb6cb4d415eaaea002207dffd162da35593d86188ce87a1cbc9d3a5b26391870f19bf1764ca05b315ad9012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff0200093d00000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788ac7077e401000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac00000000'
     )
Пример #24
0
 def test_get_filtered_txs(self):
     from bloomfilter import BloomFilter
     bf = BloomFilter(30, 5, 90210)
     h160 = decode_base58('mseRGXB89UTFVkWJhTRTzzZ9Ujj4ZPbGK5')
     bf.add(h160)
     node = SimpleNode('tbtc.programmingblockchain.com', testnet=True)
     node.handshake()
     node.send(bf.filterload())
     block_hash = bytes.fromhex('00000000000377db7fde98411876c53e318a395af7304de298fd47b7c549d125')
     txs = node.get_filtered_txs([block_hash])
     self.assertEqual(txs[0].id(), '0c024b9d3aa2ae8faae96603b8d40c88df2fc6bf50b3f446295206f70f3cf6ad')
     self.assertEqual(txs[1].id(), '0886537e27969a12478e0d33707bf6b9fe4fdaec8d5d471b5304453b04135e7e')
     self.assertEqual(txs[2].id(), '23d4effc88b80fb7dbcc2e6a0b0af9821c6fe3bb4c8dc3b61bcab7c45f0f6888')
Пример #25
0
 def parse(cls, wif):
     secret_bytes = decode_base58(wif, num_bytes=40, strip_leading_zeros=True)
     # remove the first and last if we have 34, only the first if we have 33
     testnet = secret_bytes[0] == 0xef
     if len(secret_bytes) == 34:
         secret_bytes = secret_bytes[1:-1]
         compressed = True
     elif len(secret_bytes) == 33:
         secret_bytes = secret_bytes[1:]
         compressed = False
     else:
         raise RuntimeError('not valid WIF')
     secret = int.from_bytes(secret_bytes, 'big')
     return cls(secret, compressed=compressed, testnet=testnet)
Пример #26
0
 def test_sign_p2wpkh(self):
     private_key = PrivateKey(secret=8675309)
     prev_tx = bytes.fromhex(
         '6bfa079532dd9fad6cfbf218edc294fdfa7dd0cb3956375bc864577fb36fad97')
     prev_index = 0
     fee = 500
     tx_in = TxIn(prev_tx, prev_index)
     amount = tx_in.value(testnet=True) - fee
     h160 = decode_base58('mqYz6JpuKukHzPg94y4XNDdPCEJrNkLQcv')
     tx_out = TxOut(amount=amount, script_pubkey=P2PKHScriptPubKey(h160))
     t = Tx(1, [tx_in], [tx_out], 0, testnet=True, segwit=True)
     self.assertTrue(t.sign_input(0, private_key))
     want = '0100000000010197ad6fb37f5764c85b375639cbd07dfafd94c2ed18f2fb6cad9fdd329507fa6b0000000000ffffffff014c400f00000000001976a9146e13971913b9aa89659a9f53d327baa8826f2d7588ac02483045022100feab5b8feefd5e774bdfdc1dc23525b40f1ffaa25a376f8453158614f00fa6cb02204456493d0bc606ebeb3fa008e056bbc96a67cb0c11abcc871bfc2bec60206bf0012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b6700000000'
     self.assertEqual(t.serialize().hex(), want)
def check_htlc_and_get_secret_hash(node, commitment_tx, channel):
    tx_in = commitment_tx.tx_ins[0]
    tx_out_1 = commitment_tx.tx_outs[1]
    tx_out_2 = commitment_tx.tx_outs[2]

    if (
            tx_in.prev_tx.hex() == channel.funding_tx.id()
    ):  #checks that it is spending from the correct 2-of-2 multisig tx (the funding tx)
        if (tx_out_1.script_pubkey.cmds[2] == decode_base58(node.address)
                and tx_out_1.amount == channel.local_amt):
            if (tx_out_2.script_pubkey.cmds[6] == hash160(
                    node.public_key.sec())):
                return tx_out_2.script_pubkey.cmds[2]
    return None
Пример #28
0
 def test_exercise_3_2(self):
     prev_tx_1 = bytes.fromhex(
         '89cbfe2eddaddf1eb11f5c4adf6adaa9bca4adc01b2a3d03f8dd36125c068af4')
     prev_index_1 = 0
     prev_tx_2 = bytes.fromhex(
         '19069e1304d95f70e03311d9d58ee821e0978e83ecfc47a30af7cd10fca55cf4')
     prev_index_2 = 0
     target_address = 'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv'
     fee = 50000
     secret = 61740721216174072121
     private_key = PrivateKey(secret=secret)
     tx_ins = []
     tx_ins.append(TxIn(prev_tx_1, prev_index_1))
     tx_ins.append(TxIn(prev_tx_2, prev_index_2))
     tx_outs = []
     h160 = decode_base58(target_address)
     script_pubkey = p2pkh_script(h160)
     target_satoshis = tx_ins[0].value(True) + tx_ins[1].value(True) - fee
     tx_outs.append(TxOut(target_satoshis, script_pubkey))
     tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True)
     tx_obj.sign_input(0, private_key)
     tx_obj.sign_input(1, private_key)
     if tx_ins[0].script_pubkey(
             testnet=True).instructions[2] != decode_base58(
                 private_key.point.address(testnet=True)):
         raise RuntimeError(
             'Output is not something you can spend with this private key. Check that the prev_tx and prev_index are correct'
         )
     if tx_obj.fee() > 0.05 * 100000000 or tx_obj.fee() <= 0:
         raise RuntimeError(
             'Check that the change amount is reasonable. Fee is {}'.format(
                 tx_obj.fee()))
     self.assertEqual(
         tx_obj.serialize().hex(),
         '0100000002f48a065c1236ddf8033d2a1bc0ada4bca9da6adf4a5c1fb11edfaddd2efecb89000000006a47304402204b9ee431a2f5deaefb5282a34d7dcfdb47d55b1e3ce00cac4c6b6e6f0f0e8d58022062710e84786d2c6c89ddda5a149b45088b15230c6b825f0f21490f99bd74c81d012103f96f3a1efd31e1a8d7078118ee56bff7355d58907ce0f865f5f0b3dbe34e55befffffffff45ca5fc10cdf70aa347fcec838e97e021e88ed5d91133e0705fd904139e0619000000006a473044022073d7217b2d582e55978284c2628015a14e3490e835c76488eb29b63de15d17920220384e4b5282c911273efd4d98170e7092e10a729d142db17f4725c15364fa4ecc012103f96f3a1efd31e1a8d7078118ee56bff7355d58907ce0f865f5f0b3dbe34e55beffffffff01021f320a000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788ac00000000'
     )
Пример #29
0
 def get_address_data(cls, addr):
     b58 = decode_base58(addr)
     prefix = b58[0]
     h160 = b58[1:]
     testnet = prefix in cls.testnet_prefixes
     if prefix in cls.p2pkh_prefixes:
         script_pubkey = Script.parse(p2pkh_script(h160))
     elif prefix in cls.p2sh_prefixes:
         script_pubkey = Script.parse(p2sh_script(h160))
     else:
         raise RuntimeError('unknown type of address {}'.format(addr))
     return {
         'testnet': testnet,
         'h160': h160,
         'script_pubkey': script_pubkey,
     }
Пример #30
0
 def test_sign_p2sh_p2wpkh(self):
     private_key = PrivateKey(secret=8675309)
     redeem_script = private_key.point.p2sh_p2wpkh_redeem_script()
     prev_tx = bytes.fromhex(
         '2e19b463bd5c8a3e0f10ae827f5a670f6794fca96394ecf8488321291d1c2ee9')
     prev_index = 1
     fee = 500
     tx_in = TxIn(prev_tx, prev_index)
     amount = tx_in.value(testnet=True) - fee
     h160 = decode_base58('mqYz6JpuKukHzPg94y4XNDdPCEJrNkLQcv')
     tx_out = TxOut(amount=amount, script_pubkey=P2PKHScriptPubKey(h160))
     t = Tx(1, [tx_in], [tx_out], 0, testnet=True, segwit=True)
     self.assertTrue(
         t.sign_input(0, private_key, redeem_script=redeem_script))
     want = '01000000000101e92e1c1d29218348f8ec9463a9fc94670f675a7f82ae100f3e8a5cbd63b4192e0100000017160014d52ad7ca9b3d096a38e752c2018e6fbc40cdf26fffffffff014c400f00000000001976a9146e13971913b9aa89659a9f53d327baa8826f2d7588ac0247304402205e3ae5ac9a0e0a16ae04b0678c5732973ce31051ba9f42193e69843e600d84f2022060a91cbd48899b1bf5d1ffb7532f69ab74bc1701a253a415196b38feb599163b012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b6700000000'
     self.assertEqual(t.serialize().hex(), want)