def main(): # always remember to setup the network setup('testnet') priv1 = PrivateKey("cN1XE3ESGgdvr4fWsB7L3BcqXncUauF8Fo8zzv4Sm6WrkiGrsxrG") priv2 = PrivateKey("cR8AkcbL2pgBswrHp28AftEznHPPLA86HiTog8MpNCibxwrsUcZ4") p2sh_redeem_script = Script( ['OP_1', priv1.get_public_key().to_hex(), priv2.get_public_key().to_hex(),'OP_2', 'OP_CHECKMULTISIG']) fromAddress = P2wshAddress.from_script(p2sh_redeem_script) toAddress = P2wpkhAddress.from_address("tb1qtstf97nhk2gycz7vl37esddjpxwt3ut30qp5pn") # set values txid = '2042195c40a92353f2ffe30cd0df8d177698560e81807e8bf9174a9c0e98e6c2' vout = 0 amount = 0.01 # create transaction input from tx id of UTXO txin = TxInput(txid, vout) txOut1 = TxOutput(0.0001, toAddress.to_script_pub_key()) txOut2 = TxOutput(0.0098, fromAddress.to_script_pub_key()) tx = Transaction([txin], [txOut1, txOut2], has_segwit=True) sig1 = priv1.sign_segwit_input(tx, 0, p2sh_redeem_script, amount) tx.witnesses.append(Script(['OP_0', sig1, p2sh_redeem_script.to_hex()])) # print raw signed transaction ready to be broadcasted print("\nRaw signed transaction:\n" + tx.serialize()) print("\nTxId:", tx.get_txid())
def main(): # always remember to setup the network setup('testnet') priv0 = PrivateKey("cN1XE3ESGgdvr4fWsB7L3BcqXncUauF8Fo8zzv4Sm6WrkiGrsxrG") pub = priv0.get_public_key() fromAddress = pub.get_segwit_address() priv1 = PrivateKey("cN1XE3ESGgdvr4fWsB7L3BcqXncUauF8Fo8zzv4Sm6WrkiGrsxrG") # P2SH Script: OP_M <Public key 1> <Public key 2> ... OP_N OP_CHECKMULTISIG p2sh_redeem_script = Script( ['OP_1', priv1.get_public_key().to_hex(), 'OP_1', 'OP_CHECKMULTISIG']) toAddress = P2wshAddress.from_script(p2sh_redeem_script) # set values txid = 'd222d91e2da368ac38e84aa615c557e4caeacce02aa5dbca10d840fd460fc938' vout = 0 amount = Decimal('0.01764912') # create transaction input from tx id of UTXO txin = TxInput(txid, vout) redeem_script1 = Script([ 'OP_DUP', 'OP_HASH160', priv0.get_public_key().to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG' ]) # create transaction output txOut1 = TxOutput(Decimal('0.0001'), toAddress.to_script_pub_key()) txOut2 = TxOutput(Decimal('0.01744912'), fromAddress.to_script_pub_key()) # create transaction tx = Transaction([txin], [txOut1, txOut2], has_segwit=True) print("\nRaw transaction:\n" + tx.serialize()) sig1 = priv0.sign_segwit_input(tx, 0, redeem_script1, amount) tx.witnesses.append(Script([sig1, pub.to_hex()])) # print raw signed transaction ready to be broadcasted print("\nRaw signed transaction:\n" + tx.serialize()) print("\nTxId:", tx.get_txid())
def main(): # always remember to setup the network setup('testnet') # the key that corresponds to the P2WPKH address priv = PrivateKey("cVdte9ei2xsVjmZSPtyucG43YZgNkmKTqhwiUA8M4Fc3LdPJxPmZ") pub = priv.get_public_key() fromAddress = pub.get_segwit_address() print(fromAddress.to_string()) # amount is needed to sign the segwit input fromAddressAmount = to_satoshis(0.01) # UTXO of fromAddress txid = '13d2d30eca974e8fa5da11b9608fa36905a22215e8df895e767fc903889367ff' vout = 0 toAddress = P2pkhAddress('mrrKUpJnAjvQntPgz2Z4kkyr1gbtHmQv28') # create transaction input from tx id of UTXO txin = TxInput(txid, vout) # the script code required for signing for p2wpkh is the same as p2pkh script_code = Script([ 'OP_DUP', 'OP_HASH160', pub.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG' ]) # create transaction output txOut = TxOutput(to_satoshis(0.009), toAddress.to_script_pub_key()) # create transaction without change output - if at least a single input is # segwit we need to set has_segwit=True tx = Transaction([txin], [txOut], has_segwit=True) print("\nRaw transaction:\n" + tx.serialize()) sig = priv.sign_segwit_input(tx, 0, script_code, fromAddressAmount) tx.witnesses.append(Script([sig, pub.to_hex()])) # print raw signed transaction ready to be broadcasted print("\nRaw signed transaction:\n" + tx.serialize()) print("\nTxId:", tx.get_txid())
def main(): # always remember to setup the network setup('testnet') # the key that corresponds to the P2WPKH address priv = PrivateKey('cNho8fw3bPfLKT4jPzpANTsxTsP8aTdVBD6cXksBEXt4KhBN7uVk') pub = priv.get_public_key() # the p2sh script and the corresponding address redeem_script = pub.get_segwit_address().to_script_pub_key() p2sh_addr = P2shAddress.from_script(redeem_script) # the UTXO of the P2SH-P2WPKH that we are trying to spend inp = TxInput('95c5cac558a8b47436a3306ba300c8d7af4cd1d1523d35da3874153c66d99b09', 0) # exact amount of UTXO we try to spent amount = 0.0014 # the address to send funds to to_addr = P2pkhAddress('mvBGdiYC8jLumpJ142ghePYuY8kecQgeqS') # the output sending 0.001 -- 0.0004 goes to miners as fee -- no change out = TxOutput(to_satoshis(0.001), to_addr.to_script_pub_key()) # create a tx with at least one segwit input tx = Transaction([inp], [out], has_segwit=True) # script code is the script that is evaluated for a witness program type; each # witness program type has a specific template for the script code # script code that corresponds to P2WPKH (it is the classic P2PKH) script_code = pub.get_address().to_script_pub_key() # calculate signature using the appropriate script code # remember to include the original amount of the UTXO sig = priv.sign_segwit_input(tx, 0, script_code, to_satoshis(amount)) # script_sig is the redeem script passed as a single element inp.script_sig = Script([redeem_script.to_hex()]) # finally, the unlocking script is added as a witness tx.witnesses.append(Script([sig, pub.to_hex()])) # print raw signed transaction ready to be broadcasted print("\nRaw signed transaction:\n" + tx.serialize())
def tip_or_withdrawFunc(update, ctx): # Initialise bitcoin.py setup('mainnet') query = update.callback_query chID = query.message.chat.id msgID = query.message.message_id query.answer() data = str(query.data).split(",") sender = str(query.from_user.id) if sender == data[3]: if data[4] == "t": target = data[1] if data[0] == "Y": ctx.bot.delete_message(chat_id=chID, message_id=msgID) sender_wif = PrivateKey(db.getWIF(sender)) fee = convertToSatoshis(Decimal(config.coin['minFee'])) target_address = P2wpkhAddress(getAddress(target)) sender_address = P2wpkhAddress(getAddress(sender)) sender_balance = 0 amount = convertToSatoshis(Decimal(data[2])) + fee unspent = requests.get( f"{config.apiUrl}/unspent/{sender_address.to_string()}" ).json()["result"] txin = [] for i in range(0, len(unspent)): sender_balance += unspent[i]['value'] txin.append( TxInput(unspent[i]['txid'], unspent[i]['index'])) if sender_balance >= amount: txout = [] txout.append( TxOutput((amount - fee), target_address.to_script_pub_key())) txchange = sender_balance - amount if txchange > 0: txout.append( TxOutput(txchange, sender_address.to_script_pub_key())) script_code = Script([ 'OP_DUP', 'OP_HASH160', sender_wif.get_public_key().to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG' ]) tx = Transaction(txin, txout, has_segwit=True) tx.witnesses = [] for i in range(0, len(unspent)): value = unspent[i]['value'] sig = sender_wif.sign_segwit_input( tx, i, script_code, value) tx.witnesses.append( Script([sig, sender_wif.get_public_key().to_hex()])) post_data = {'raw': tx.serialize()} txid = requests.post(f"{config.apiUrl}/broadcast", data=post_data).json()['result'] ctx.bot.send_message( chat_id=chID, text= f"Success, sent @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}." ) ctx.bot.send_message( chat_id=chID, text= f"[View Transaction](https://sugar\\.wtf/esplora/tx/{str(txid)})", parse_mode="MarkdownV2") else: ctx.bot.send_message( chat_id=chID, text="You do not have enough funds to tip that amount") elif data[0] == "N": ctx.bot.delete_message(chat_id=chID, message_id=msgID) ctx.bot.send_message( chat_id=chID, text= f"You declined sending @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}" ) elif data[4] == "w": if data[0] == "Y": ctx.bot.delete_message(chat_id=chID, message_id=msgID) sender_wif = PrivateKey(db.getWIF(sender)) fee = convertToSatoshis(Decimal(config.coin['minFee'])) sender_address = P2wpkhAddress(getAddress(sender)) sender_balance = 0 amount = convertToSatoshis(Decimal(data[2])) + fee target_address = P2wpkhAddress("sugar1q" + data[1]) unspent = requests.get( f"{config.apiUrl}/unspent/{sender_address.to_string()}" ).json()['result'] txin = [] for i in range(0, len(unspent)): sender_balance += unspent[i]['value'] txin.append( TxInput(unspent[i]['txid'], unspent[i]['index'])) if sender_balance >= amount: txout = [] txout.append( TxOutput((amount - fee), target_address.to_script_pub_key())) txchange = sender_balance - amount if txchange > 0: txout.append( TxOutput(txchange, sender_address.to_script_pub_key())) script_code = Script([ 'OP_DUP', 'OP_HASH160', sender_wif.get_public_key().to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG' ]) tx = Transaction(txin, txout, has_segwit=True) tx.witnesses = [] for i in range(0, len(unspent)): value = unspent[i]['value'] sig = sender_wif.sign_segwit_input( tx, i, script_code, value) tx.witnesses.append( Script([sig, sender_wif.get_public_key().to_hex()])) post_data = {'raw': tx.serialize()} txid = requests.post(f"{config.apiUrl}/broadcast", data=post_data).json()['result'] ctx.bot.send_message( chat_id=chID, text= f"Success, withdrew {data[2]} {config.coin['ticker']} to address {target_address.to_string()} " ) ctx.bot.send_message( chat_id=chID, text= f"[View Transaction](https://sugar\\.wtf/esplora/tx/{str(txid)})", parse_mode="MarkdownV2") else: ctx.bot.send_message( chat_id=chID, text= "You do not have enough funds to withdraw the specified amount." ) elif data[0] == "N": ctx.bot.delete_message(chat_id=chID, message_id=msgID) ctx.bot.send_message( chat_id=chID, text= f"You declined withdrawing {data[2]} {config.coin['ticker']} to address {'sugar1q' + data[1]}" )