Ejemplo n.º 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)
Ejemplo n.º 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 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
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
 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'
     )
Ejemplo n.º 6
0
def build_transaction(transidsarr, transindexarr, pubeysarr, amountsarr,
                      privatekey):
    tx_ins = buildinputs(transidsarr, transindexarr)
    tx_outs = buildoutputs(pubkeysarr, amountsarr)
    tx_obj = Tx(version=1,
                tx_ins=tx_ins,
                tx_outs=tx_outs,
                locktime=0,
                testnet=True)
    hash_type = SIGHASH_ALL
    z = tx_obj.sig_hash(0, hash_type)
    pk = PrivateKey(secret=privatekey)
    sighash = SIGHASH_ALL
    z = tx_obj.sig_hash(0, sighash)
    #print(z)
    sig = pk.sign(z)
    #print("r: " + str(sig.r))
    #print("s: " + str(sig.s))
    der = pk.sign(z).der()
    sig = der + bytes([sighash])
    sec = pk.point.sec()
    tx_obj.tx_ins[0].script_sig = Script([sig, sec])
    #print("serialized:")
    #print(hexlify(Script([sig,sec]).serialize()))
    #print("----------")
    return hexlify(tx_obj.serialize())
Ejemplo n.º 7
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)
Ejemplo n.º 8
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))
Ejemplo n.º 9
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))
Ejemplo n.º 10
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)
Ejemplo n.º 11
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'
     )
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
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())
Ejemplo n.º 14
0
    def create_unfunded_transaction(cls,
                                    outputs,
                                    testnet=False,
                                    version=1,
                                    locktime=0):
        """
		-inputs is a list of tuples(bytes prev_txid, int vout)
		-outputs is a list of tuples (int amount, Script script_pubkey)
		returns Tx object
		"""
        tx_outs = [cls.create_tx_out(o[0], o[1]) for o in outputs]
        return Tx(version, [],
                  tx_outs,
                  locktime=locktime,
                  testnet=testnet,
                  segwit=False)
Ejemplo n.º 15
0
 def wlogin(self,user,passwd):
     url = self.urlEntry.get()
     self.tx = Tx(url,user,passwd,0)
     status = self.tx.status
     # print(user,passwd,status)
     self.info.config(state=NORMAL)
     if status == 0:
         self.tx.get_family_id()
         userinfo = '当前登录用户ID:%s\n当前登录用户名:%s\n当前登录用户家族ID:%s\n当前登录用户家族名称:%s\n'%(str(self.tx.userId),self.tx.username,str(self.tx.family_id),self.tx.family_name)
         self.info.insert(END,userinfo)
         self.info.config(state=DISABLED)
     else:
         userinfo = '当前登录用户ID:%s\n'%(user)
         self.info.insert(END,userinfo)
         self.info.config(state=DISABLED)
     return status
Ejemplo n.º 16
0
    def get_mempool_tx(self, prev_time, curr_time):
        new_tx = []
        for t in range(int(prev_time), int(curr_time)):
            try:
                for tx in all_txs[t]:
                    if tx['serial'] in self.txs_set:
                        input("found a duplicate")
                        break
                    self.txs_set.add(tx['serial'])
                    new_tx.append(Tx(timestamp=tx['timestamp'], size=tx['size'], fee=tx['fee'], serial=tx['serial']))
                    if  tx['timestamp'] >= self.end_time:
                        self.experiment_end_flag = True

            except:
                pass
        return new_tx
Ejemplo n.º 17
0
def build_transaction2(transidsarr,
                       transindexarr,
                       pubkeysarr,
                       amountsarr,
                       tnet=True):
    tx_ins = buildinputs(transidsarr, transindexarr)
    print("ins")
    print(tx_ins)
    tx_outs = buildoutputs(pubkeysarr, amountsarr)
    print("pubkeys")
    print(pubkeysarr)
    print("outs")
    print(tx_outs)
    tx_obj = Tx(version=1,
                tx_ins=tx_ins,
                tx_outs=tx_outs,
                locktime=0,
                testnet=tnet)
    #hash_type = SIGHASH_ALL
    #z = tx_obj.sig_hash(0, hash_type)
    #pk = PrivateKey(secret=privatekey)
    for i in range(len(tx_ins)):
        sighash = SIGHASH_ALL
        z = tx_obj.sig_hash(i, sighash)
        #print("getting sign:")
        r, s = ardubridge.sign(z)
        s = int(s)
        others = N - s
        if others < s:
            s = others
        #print("r: " + str(r))
        #print("s: " + str(s))
        sig = Signature(int(r), s)
        der = sig.der()
        sig = der + bytes([sighash])
        #sec = pk.point.sec()
        #print("public point:")
        #print(int(pk.point.x.hex(), 16))
        #print(int(pk.point.y.hex(), 16))
        x, y = ardubridge.getpubkey()
        if (x == -1 and y == -1):
            return '-1'
        #pub = S256Point(53237820045986896539096637357322002537362350769420441605069248472301971758546, 49407176618187043960559197373734381057571970898731550795341045595301080938882)
        pub = S256Point(int(x), int(y))
        sec2 = pub.sec()
        tx_obj.tx_ins[i].script_sig = Script([sig, sec2])
    return hexlify(tx_obj.serialize())
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
    def __parse_mempool(mempool):
        """
        Parses the json or dict file to list of Txs

        :param mempool:
        :return:
        """
        txs = list()

        if isinstance(mempool, str):
            with open(mempool) as fp:
                mempool = json.load(fp)

        for tx_id, tx_desc in mempool.items():
            tx_desc = list(tx_desc.values())[0]
            txs.append(Tx(tx_id, tx_desc))

        return txs
Ejemplo n.º 20
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))
Ejemplo n.º 21
0
    def transfer(self, approved):
        print(
            "Inside callback\nfrom_player is {} to_player is {} and amount is {} approved {}"
            .format(self.from_player, self.to_player, self.amount, approved))

        if approved and self.players[
                self.from_player].balance - self.amount >= 0:

            self.players[self.from_player].balance -= self.amount
            self.players[self.to_player].balance += self.amount
            success = True
        else:
            success = False

        tx = Tx(self.from_player, self.to_player, self.amount, success)
        self.txs[tx.txId] = tx

        msgs_from = [{
            'topic':
            'game/{}/balance/{}'.format(self.gameId, self.from_player),
            'payload':
            str(self.players[self.from_player].balance)
        }, {
            'topic':
            'game/{}/txs/{}'.format(self.gameId, self.from_player),
            'payload':
            tx.toString()
        }]
        publish_multiple(msgs_from)

        msgs_to = [{
            'topic':
            'game/{}/balance/{}'.format(self.gameId, self.to_player),
            'payload':
            str(self.players[self.to_player].balance)
        }, {
            'topic':
            'game/{}/txs/{}'.format(self.gameId, self.to_player),
            'payload':
            tx.toString()
        }]
        publish_multiple(msgs_to)
Ejemplo n.º 22
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))
Ejemplo n.º 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'
     )
Ejemplo n.º 24
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)
Ejemplo n.º 25
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))
Ejemplo n.º 26
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'
     )
Ejemplo n.º 27
0
assert all(p == pk.point for p,pk in key_pairs)
pubkeys = [p for p, _ in key_pairs]

OP_n = lambda n: 0x51 + n - 1

n_required = 2
elements = [OP_n(n_required)] + [pk.sec(compressed=False) for pk in pubkeys] + [OP_n(len(pubkeys))] + [174]
redeemScript = script.Script(elements)

address=helper.h160_to_p2sh_address(helper.hash160(redeemScript.serialize()), testnet=False)
redeemScript=hexlify(redeemScript.serialize())
assert address=="3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC"
assert redeemScript=="52410491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f864104865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec687441048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d4621353ae".encode('ascii')
print(hexlify(helper.hash160(unhexlify(redeemScript))))

prev_tx = 'd6f72aab8ff86ff6289842a0424319bf2ddba85dc7c52757912297f948286389'
prev_index = 0
tx_in = TxIn(unhexlify(prev_tx), prev_index, b'')

h160 = helper.decode_base58_checksum(address)[1:]
tx_out = TxOut(int(0.01*100e6), script_pubkey=helper.p2sh_script(h160))
t = Tx(version=1, tx_ins=[tx_in], tx_outs=[tx_out], locktime=0, testnet=False)
raw_transaction = hexlify(t.serialize())
assert raw_transaction == "010000000189632848f99722915727c5c75da8db2dbf194342a0429828f66ff88fab2af7d60000000000ffffffff0140420f000000000017a914f815b036d9bbbce5e9f2a00abd1bf3dc91e955108700000000".encode('ascii')
print(t)

#tx.sign_input(input_index=0, private_key='', hash_type=helper.SIGHASH_ALL)



Ejemplo n.º 28
0
 def send(self, from_player, to_player, amount):
     tx = Tx(from_player, to_player, amount)
     txs[tx.txId] = tx
     players[from_player].balance -= amount
     players[to_player].balance += amount
Ejemplo n.º 29
0
change_amount = int(0.00003 * 100000000)

# output address that will receive the sat we have not spend

change_h160 = decode_base58('mvEg6eZ3sUApodedYQrkpEPMMALsr1K1k1')
change_script = p2pkh_script(change_h160)
change_output = TxOut(amount=change_amount, script_pubkey=change_script)

# output address that will receive our sat

target_amount = int(0.00006 * 100000000)
target_h160 = decode_base58('mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv')

target_script = p2pkh_script(target_h160)
target_output = TxOut(amount=target_amount, script_pubkey=target_script)
tx_obj = Tx(1, [tx_in], [change_output, target_output], 0, True)
#print(tx_obj).hex()

# now we sign the transaction

z = tx_obj.sig_hash(0)
private_key = PrivateKey(little_endian_to_int(
    hash256(b'dat_test_private_key')))
der = private_key.sign(z).der()
sig = der + SIGHASH_ALL.to_bytes(1, 'big')
sec = private_key.point.sec()
script_sig = Script([sig, sec])
tx_obj.tx_ins[0].script_sig = script_sig
print(tx_obj.serialize().hex())

# end
Ejemplo n.º 30
0
    'b685879f3939fa9531899b729394ed85edab8b6850b72a9e378ea31af96a304a')
index_tx_previa = 1

tx_inputs = []
tx_inputs.append(TxIn(tx_previa, index_tx_previa))

#OUPUTS
tx_outputs = []
destinatario = 'mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB'
monto = .00008
change_adress = ADDRESS
cambio = .00001
#SEND OUTPUT
h160 = decode_base58(destinatario)
script_pubkey = p2pkh_script(h160)
monto_satoshis = int(monto * 100_000_000)
tx_outputs.append(TxOut(monto_satoshis, script_pubkey))

#CHANGE OUPUT
h160 = decode_base58(change_adress)
script_pubkey = p2pkh_script(h160)
cambio_satoshis = int(cambio * 100_000_000)
tx_outputs.append(TxOut(cambio_satoshis, script_pubkey))

#TX BUILD
TX_BUILD = Tx(1, tx_inputs, tx_outputs, 0, testnet=True)

#SIGN
print(TX_BUILD.sign_input(0, PrivKey))
print(TX_BUILD.serialize().hex())