Example #1
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)
def add_channel(local_node, remote_peer, input_tx_id, input_tx_index):

    tx_in = TxIn(bytes.fromhex(input_tx_id), input_tx_index)
    local_amount = tx_in.value()
    remote_amount = 0

    # Construct the output: amount, scriptPubKey = 2-of-2 Bare Multisig  = Script([op_1, pubkey1, pubkey2, op_2, op_checkmultisig])
    scriptPubKey = Script([
        0x52,
        local_node.public_key.sec(),
        remote_peer.public_key.sec(), 0x52, 0xae
    ])
    tx_out = TxOut(amount=local_amount, script_pubkey=scriptPubKey)

    # Construct the transaction object
    funding_tx = Tx(1, [tx_in], [tx_out], 0, True)

    # Sign the input
    funding_tx.sign_input(0, local_node.private_key)

    #send channel request
    new_channel = Channel(remote_peer, local_amount, remote_amount, funding_tx)
    remote_peer.send(str.encode(new_channel.toJSON()))

    return new_channel
Example #3
0
    def transfer(self, amount, address):
        uTxs = []
        total = 0

        for (tx, i) in self.unspentOutputs():
            total += tx.outputs[i].amount
            uTxs.append((tx, i))

            if total >= amount:
                break
        else:
            raise ValueError(
                "Wallet dose not have enough spendable outputs for transfer.")

        txIns = []
        for (tx, i) in uTxs:
            txIn = TxIn(tx.toHash(), i)
            txIn.setScriptSig(
                generateSignature(txIn.toBytes(), self.privateKey),
                self.publicKey)
            txIns.append(txIn)

        txOuts = [TxOut(amount, address)]

        change = total - amount
        if change > 0:
            txOuts.append(TxOut(change, self.address))

        self.receiveTx(Tx(txIns, txOuts))
Example #4
0
def sig_hash(self, input_index, redeem_script=None):
    s = int_to_little_endian(self.version, 4)
    s += encode_varint(len(self.tx_ins))
    for i, tx_in in enumerate(self.tx_ins):
        if i == input_index:
            if redeem_script:
                script_sig = redeem_script
            else:
                script_sig = tx_in.script_pubkey(self.testnet)
            s += TxIn(
                prev_tx=tx_in.prev_tx,
                prev_index=tx_in.prev_index,
                script_sig=script_sig,
                sequence=tx_in.sequence,
            ).serialize()
        else:
            s += TxIn(
                prev_tx=tx_in.prev_tx,
                prev_index=tx_in.prev_index,
                sequence=tx_in.sequence,
            ).serialize()
    s += encode_varint(len(self.tx_outs))
    for tx_out in self.tx_outs:
        s += tx_out.serialize()
    s += int_to_little_endian(self.locktime, 4)
    s += int_to_little_endian(SIGHASH_ALL, 4)
    h256 = hash256(s)
    return int.from_bytes(h256, 'big')
Example #5
0
 def test_exercise_6(self):
     prev_tx = bytes.fromhex('d1c789a9c60383bf715f3f6ad9d14b91fe55f3deb369fe5d9280cb1a01793f81') 
     prev_index = 0
     tx_in = TxIn(prev_tx, 0)
     t = tx_in.fetch_tx()
     prev_output = t.tx_outs[prev_index]
     self.assertEqual(prev_output.amount, 42505594)
     want = [0x76, 0xa9, bytes.fromhex('a802fc56c704ce87c42d7c92eb75e7896bdc41ae'), 0x88, 0xac]
     self.assertEqual(prev_output.script_pubkey.instructions, want)
Example #6
0
 def test_input_pubkey(self):
     tx_hash = 'd1c789a9c60383bf715f3f6ad9d14b91fe55f3deb369fe5d9280cb1a01793f81'
     index = 0
     tx_in = TxIn(
         prev_tx=unhexlify(tx_hash),
         prev_index=index,
         script_sig=b'',
         sequence=0,
     )
     want = unhexlify('76a914a802fc56c704ce87c42d7c92eb75e7896bdc41ae88ac')
     self.assertEqual(tx_in.script_pubkey().serialize(), want)
Example #7
0
 def test_input_value(self):
     tx_hash = 'd1c789a9c60383bf715f3f6ad9d14b91fe55f3deb369fe5d9280cb1a01793f81'
     index = 0
     want = 42505594
     tx_in = TxIn(
         prev_tx=unhexlify(tx_hash),
         prev_index=index,
         script_sig=b'',
         sequence=0,
     )
     self.assertEqual(tx_in.value(), want)
Example #8
0
 def sig_hash(self, input_index, redeem_script=None):
     alt_tx_ins = []
     for tx_in in self.tx_ins:
         alt_tx_ins.append(
             TxIn(
                 prev_tx=tx_in.prev_tx,
                 prev_index=tx_in.prev_index,
                 script_sig=Script([]),
                 sequence=tx_in.sequence,
             ))
     signing_input = alt_tx_ins[input_index]
     if redeem_script:
         print(redeem_script)
         signing_input.script_sig = redeem_script
     else:
         signing_input.script_sig = signing_input.script_pubkey(
             self.testnet)
     for i in alt_tx_ins:
         print(i.script_sig)
     alt_tx = self.__class__(version=self.version,
                             tx_ins=alt_tx_ins,
                             tx_outs=self.tx_outs,
                             locktime=self.locktime)
     result = alt_tx.serialize() + int_to_little_endian(SIGHASH_ALL, 4)
     h256 = hash256(result)
     return int.from_bytes(h256, 'big')
Example #9
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
Example #11
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'
     )
Example #13
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)
Example #14
0
    def test_sign_input(self):
        private_key = PrivateKey(secret=8675309)
        tx_ins = []
        prev_tx = unhexlify(
            '0025bc3c0fa8b7eb55b9437fdbd016870d18e0df0ace7bc9864efc38414147c8')
        tx_ins.append(
            TxIn(
                prev_tx=prev_tx,
                prev_index=0,
                script_sig=b'',
                sequence=0xffffffff,
            ))
        tx_ins[0]._value = 110000000
        tx_ins[0]._script_pubkey = Script.parse(
            private_key.point.p2pkh_script())
        tx_outs = []
        h160 = Tx.get_address_data(
            'mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2')['h160']
        tx_outs.append(
            TxOut(amount=int(0.99 * 100000000),
                  script_pubkey=p2pkh_script(h160)))
        h160 = Tx.get_address_data(
            'mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf')['h160']
        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))
Example #15
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'
     )
Example #16
0
def buildinputs(transidsarr, transindexarr):
    tx_ins = []
    for i in range(len(transidsarr)):
        tx_ins.append(
            TxIn(
                prev_tx=unhexlify(transidsarr[i]),
                prev_index=transindexarr[i],
                script_sig=b'',
                sequence=0xffffffff,
            ))
    return tx_ins
def parse(cls, s, testnet=False):
    version = little_endian_to_int(s.read(4))
    num_inputs = read_varint(s)
    inputs = []
    for _ in range(num_inputs):
        inputs.append(TxIn.parse(s))
    num_outputs = read_varint(s)
    outputs = []
    for _ in range(num_outputs):
        outputs.append(TxOut.parse(s))
    locktime = little_endian_to_int(s.read(4))
    return cls(version, inputs, outputs, locktime, testnet=testnet)
def check_htlc(node, commitment_tx, secret):

    tx_in = TxIn(bytes.fromhex(commitment_tx.id()), 2)
    tx_out = TxOut(amount=commitment_tx.tx_outs[2].amount,
                   script_pubkey=commitment_tx.tx_outs[0].script_pubkey)
    spendingTx = Tx(1, [tx_in], [tx_out], 0, True)

    z = spendingTx.sig_hash(0)
    signature = node.private_key.sign(z).der() + SIGHASH_ALL.to_bytes(1, 'big')
    combined = Script(
        [signature, node.public_key.sec(),
         str.encode(secret), b'1']) + commitment_tx.tx_outs[2].script_pubkey

    return combined.evaluate(z, None)
Example #19
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'
     )
Example #20
0
 def test_sign(self, gp):
     gp.return_value = 'password'
     mnemonic = 'method wire potato cotton fame can repair mother elder festival hurry trophy'
     enc = EncryptedPrivateKey.from_mnemonic(mnemonic, testnet=True)
     path = "m/84'/1'/0'/0/0"
     hd_priv = enc.get_private_key().traverse(path)
     tx_id = bytes.fromhex('07affe8b0ef5f009eef5399c20586b3181103564e8ffe444631dcae20389738c')
     tx_index = 0
     amount = 12753130
     tx_in = TxIn(tx_id, tx_index)
     tx_out = TxOut(amount - 5000, hd_priv.p2wpkh_script())
     tx_obj = Tx(1, [tx_in], [tx_out], 0, testnet=True, segwit=True)
     self.assertTrue(tx_obj.sign_p2wpkh(0, hd_priv.private_key))
     want = '010000000001018c738903e2ca1d6344e4ffe864351081316b58209c39f5ee09f0f50e8bfeaf070000000000ffffffff016285c200000000001600145b3a0784c7674df3645541a39f1d0061fafd121302483045022100ed55340424848ac402279a703440c3e64234cda15693b155e23daddea8e3ea75022018af9c2df35393e168980b835d1c08318e5417647522fb3c71c936fa20a416ae012102221f70f0e3f9cb3e164a45e7994e6e83816c76dc122d0987e4559536b888530b00000000'
     self.assertEqual(want, tx_obj.serialize().hex())
Example #21
0
def parse_tx(cls, s):
    '''Takes a byte stream and parses the transaction at the start
    return a Tx object
    '''
    version = little_endian_to_int(s.read(4))
    num_inputs = read_varint(s)
    inputs = []
    for _ in range(num_inputs):
        inputs.append(TxIn.parse(s))
    num_outputs = read_varint(s)
    outputs = []
    for _ in range(num_outputs):
        outputs.append(TxOut.parse(s))
    locktime = little_endian_to_int(s.read(4))
    return cls(version, inputs, outputs, locktime)
Example #22
0
def get_input_info(num_inputs):
    tx_ins = []
    amount_available = 0

    for i in range(num_inputs):
        temp_id = input("Enter prev_tx_id for input "+str(i+1)+": ")
        temp_index =  int(input("Enter prev_tx_index for input "+str(i+1)+": "))

        if(is_unspent(temp_id, temp_index)):
            print("Tx had already been spent. Not good.")
        else:
            print("Tx is Unspent. All good.")
            tx_ins.append(TxIn(bytes.fromhex(temp_id), temp_index))
            amount_available += tx_ins[i].value(testnet=True)

    return tx_ins, amount_available
Example #23
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)
Example #24
0
def sig_hash(self, input_index):
    alt_tx_ins = []
    for tx_in in self.tx_ins:
        alt_tx_ins.append(TxIn(
            prev_tx=tx_in.prev_tx,
            prev_index=tx_in.prev_index,
            sequence=tx_in.sequence,
        ))
    signing_input = alt_tx_ins[input_index]
    script_pubkey = signing_input.script_pubkey(self.testnet)
    signing_input.script_sig = script_pubkey
    alt_tx = self.__class__(
        version=self.version,
        tx_ins=alt_tx_ins,
        tx_outs=self.tx_outs,
        locktime=self.locktime)
    result = alt_tx.serialize() + int_to_little_endian(SIGHASH_ALL, 4)
    h256 = hash256(result)
    return int.from_bytes(h256, 'big')
Example #25
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))
Example #26
0
	def __init__(self, inputs, outputs, version=1, input_sequence=0xffffffff, locktime=0, segwit=False):
		"""
		- inputs: list of tuples (prev-tx, vout) or TxIns
		- outputs: list of tuples (amount, script_pubkey) or TxOuts
		"""
		self.role = "Creator"
		self.inputs = []
		self.outputs = []
		if type(inputs[0]) != TxIn:
			for i in inputs:
				self.inputs.append(TxIn(prev_tx=i[0], prev_index=i[1], script_sig=None, sequence=input_sequence))
		if type(outputs[0]) != TxOut:
			for o in outputs:
				#print(type(o[0]), type(0[1]))
				self.outputs.append(TxOut(amount=o[0], script_pubkey=o[1]))
		self.tx_obj = Tx(version=version, tx_ins=self.inputs, tx_outs=self.outputs, locktime=locktime, segwit=segwit)
		serialized_tx = self.tx_obj.serialize()
		ser_psbt = MAGIC + HEAD_SEPARATOR + PSBT.serialize_pair(key=GLOBAL_UNSIGNED_TX, value=serialized_tx)
		ser_psbt += DATA_SEPARATOR + (DATA_SEPARATOR*len(self.inputs)) + (DATA_SEPARATOR*len(self.outputs))
		self.psbt = PSBT.parse(BytesIO(ser_psbt))
Example #27
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'
     )
Example #28
0
    def simple_send(self, address, amount, satoshi_per_byte=1):
        if amount > self.balance():
            raise RuntimeError(
                'Balance is less than how much you want to send')
        input_total = 0
        tx_ins = []
        paths = []
        # gather inputs using our utxos
        for utxo in self.utxo_lookup.values():
            input_total += utxo.txo.amount
            tx_ins.append(TxIn(utxo.txo.tx_id, utxo.txo.tx_index))
            paths.append(utxo.txo.path)
            if input_total > amount:
                break

        # target output
        tx_outs = [TxOut(amount, address_to_script_pubkey(address))]
        tx_outs_size = len(tx_outs[0].serialize())

        # calculate how much fees should be at this point
        # our utxos are always bech32, so each input is 32+4+1+4 = 41 bytes
        # our change outputs are bech32, so each output is 8+23 = 31 bytes
        # the witness will be 33 + 72 bytes per input but count 1/4
        tx_size = 4 + 1 + len(tx_ins) * 41 + 1 + tx_outs_size + 31 + len(
            tx_ins) * (2 + 33 + 72)
        fee = tx_size * satoshi_per_byte
        if input_total < fee + amount:
            raise RuntimeError('Balance does not cover fees')

        # change output
        change_amount = input_total - amount - fee
        # don't bother if we're creating dust
        if change_amount > 200:
            tx_outs.append(TxOut(change_amount, self.change_script_pubkey()))

        # create transaction and sign
        tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=self.testnet, segwit=True)
        # signing the transaction
        self.encrypted_private.sign(tx_obj, paths)
        LOGGER.info('sending the transaction')
        return self.node.send_tx(tx_obj)
Example #29
0
    def test_b2x_sign(self):
        # Generated from ./bitcoin2x-qt -regtest
        wif = 'cVC6z7gnezHZut5yyuCX3x79tfcbauCWiFcBY92Vg4crfu4Maa5B'
        prev_tx = 'b6d073333c1a8e4360b1e2c7fa2ed6b67b74272ad7fabf52a4e4732df5f47dbd'
        prev_index = 0
        prev_value = 5000000000
        destination = 'mrVqpGm7F5MVCwsP4s3fQEN2GAaykJoTu4'
        amount = 4996000000

        priv_key = PrivateKey.parse(wif)
        prev_script_pubkey = B2XTx.get_address_data(
            priv_key.point.address())['script_pubkey'].serialize()
        tx_in = TxIn(unhexlify(prev_tx), prev_index, b'', 0xffffffff, b'\x00',
                     prev_value, prev_script_pubkey)
        script = B2XTx.get_address_data(
            destination)['script_pubkey'].serialize()
        tx_out = TxOut(amount, script)
        tx = B2XTx(2, [tx_in], [tx_out], 0, testnet=True)
        tx.sign(priv_key)
        want = "0200000001bd7df4f52d73e4a452bffad72a27747bb6d62efac7e2b160438e1a3c3373d0b6000000006a47304402201df7c8c97443bd46da751e0051a4395ba3613be3604be97d3c801c21e3d23c79022012ad30b7ffd42ad7bb96f9157519f7e3c35409ed54f783a3c854a596343a6c713121030f96812693c4a50162134cfa307afb63580171963d6c4198e8e5cfeee2c92b60ffffffff0100e9c829010000001976a91478738f2c5a75397eb2f851597261f766a67d9b6388ac00000000"
        self.assertTrue(tx.verify())
        self.assertEqual(tx.serialize().hex(), want)
Example #30
0
def spend(keypool, send_amount, fee=500):
    # collect inputs
    unspent = keypool.unspent()
    tx_ins = []
    input_sum = 0
    for private_key, utxo in unspent:
        if input_sum >= send_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 > send_amount + fee

    # outputs
    send_output = construct_tx_out(keypool.next_address(), send_amount)
    change_amount = input_sum - send_amount - fee
    change_output = construct_tx_out(keypool.next_address(), change_amount)

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

    # sign
    # FIXME
    for i in range(len(tx_ins)):
        private_key, utxo = unspent[i]
        assert tx.sign_input(i, 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))