def send_data(rpc_connection: authproxy.AuthServiceProxy, hexdata: str, tx_ins: list = ()) -> Transaction: """Creates, funds, signs and sends an OP_RETURN transaction including hexdata Parameters ---------- rpc_connection : bitcoinrpc.authproxy.AuthServiceProxy The RPC connection to the bitcoind client hexdata : str The hex encoded data to be included in the transaction tx_ins : list, optional List of namedtuples 'Transaction', representing UTXOs to fund the transaction Returns ------- Transaction Change UTXO Raises ------ ValueError If hexdata is more than MAX_DATA_LENGTH bytes RuntimeError If the transaction could not be signed """ if len(hexdata) / 2 > MAX_DATA_LENGTH: raise ValueError("hexdata too big") inputs = [{"txid": tx.txid, "vout": tx.vout} for tx in tx_ins] unfinished_tx = rpc_connection.createrawtransaction( inputs, {"data": hexdata}) funded_tx = rpc_connection.fundrawtransaction(unfinished_tx) signed_tx = rpc_connection.signrawtransactionwithwallet(funded_tx["hex"]) if signed_tx["complete"] is False: raise RuntimeError("bitcoind could not sign the transaction.") txid = rpc_connection.sendrawtransaction(signed_tx["hex"]) change_utxo = Transaction(txid, funded_tx["changepos"]) return change_utxo
def main(): bitcoin = AuthServiceProxy("http://{}:{}@127.0.0.1:{}".format( RPCUSER, RPCPASSWORD, RPCPORT)) address = ADDRESS if address is None: address = bitcoin.getaddressesbyaccount("")[0] print("Using wallet address: ", address) parent_txid = "NULL" subprotocols = [None, gen_media, gen_pastebin, gen_randomdata] # Create nodes... for i in range(NUM_NODES_TO_CREATE): node = create_node(address, parent_txid) # Add subprotocols to node for _ in range(5): subprotocol = secrets.choice(subprotocols) if subprotocol is not None: node['subprotocols'].append(subprotocol()) # Create OP_RETURN data data = b'meta' + encode_function(ENCODING)(node) assert (len(data) < 100000) # sanity check for op_return max limit data_hex = data.hex() # bitcoin rpc commands to create and fund tx with metanet data in OP_RETURN rawtx = bitcoin.createrawtransaction([], {'data': data_hex}) result = bitcoin.fundrawtransaction(rawtx, {'changeAddress': address}) rawtx = result['hex'] result = bitcoin.signrawtransaction(rawtx) assert (result['complete']) signedtx = result['hex'] txid = bitcoin.sendrawtransaction(signedtx) # Prepare for next iteration parent_txid = txid print("[Node {}]: https://test.whatsonchain.com/tx/{}".format(i, txid))
cht_read = cht.read() nonce = cht_read.split("\n")[0 + is_testnet][7:] full_contract = cht_read.split("\n")[1 + is_testnet][26:] send_address = cht_read.split("\n")[3 + is_testnet][40:] assert (cht.close() == None) if full_contract[0:8] != "50325348": print("You must use a P2SH address") exit(1) print("Sending %s to %s..." % (args.coinAmt, send_address)) print("(nonce: %s)" % nonce) try: tx_hex = bitcoin.createrawtransaction( [], {send_address: Decimal(args.coinAmt)}) tx_hex = bitcoin.fundrawtransaction(tx_hex)['hex'] tx = bitcoin.signrawtransaction(tx_hex) assert (tx['complete']) tx_hex = tx['hex'] total_length = len(tx_hex) / 2 total_length += 14 * 32 # maximum length of spv proof 1MB blocks total_length += 1000 # len(full_contract) + len(secondScriptPubKey) and rounded up to 1000 if total_length >= 10000: print("Transaction is too large.") exit(1) txid = bitcoin.sendrawtransaction(tx_hex) print("sendrawtransaction - Sent tx with id %s" % txid)
def generate_valid_source_tx( s: protocol.State, con: AuthServiceProxy, max_tx: int ) -> None: # Transmit enough funds to addresses so that we won't need # to use coinbase transactions. # There are at most MAX many transactions in one step. Hence, # we need at most that many different addresses. (We can always # use the change addresses because our transactions have nearly # no costs) num_addr = max_tx // 10 # We want at most 50 advertisements to use the # same address s.source_tx = [] start = con.getblockcount() + 1 con.generate(num_addr + 101) top = con.getblockcount() interval = range(start, top - 100) block_hashes = con.batch_([["getblockhash", h] for h in interval]) blocks = con.batch_([["getblock", ha, 2] for ha in block_hashes]) del block_hashes txs = [block['tx'][0] for block in blocks] del blocks sent_txs = [] i = 0 value = -1 txid = -1 n = -1 for tx in txs: for out in tx['vout']: if out['scriptPubKey']['type'] == 'pubkey': # The pubkey transactions are coinbase transactions because value = out['value'] txid = tx['txid'] n = out['n'] if value == -1 or txid == -1 or n == -1: raise RuntimeError("No coinbase transaction found.") addr = con.getnewaddress() sent_value = float(value) / 2 # create two addresses per transaction raw_tx = con.createrawtransaction([{'txid': txid, 'vout': n}], { addr: sent_value}) # The - is for the fees funded_tx = con.fundrawtransaction(raw_tx) signed_tx = con.signrawtransactionwithwallet(funded_tx["hex"]) if signed_tx["complete"] is False: raise RuntimeError( "bitcoind could not sign the transaction. (During " "Initialization)") txid = con.sendrawtransaction(signed_tx["hex"]) sent_txs.append(txid) i += 1 # Create a block each 100 transactions if i == 100: con.generate(1) i = 0 con.generate(1) txs = con.batch_([['getrawtransaction', txid, 1] for txid in sent_txs]) for tx in txs: for out in tx['vout']: vout = out['n'] s.source_tx.append(opreturn.Transaction(tx['txid'], vout)) c = 0 for utxo in s.source_tx: if not protocol.is_valid_utxo(utxo): c += 1 print("Found %d invalid utxos." % c)
# Get the fee for name_new if fee_type == "feeRate": name_new_fund_options["feeRate"] = fee_rate print("name_new will cost", name_new_fund_options["feeRate"], "NMC / kB") elif fee_type == "conf_target": name_new_fund_options["conf_target"] = conf_target print("name_new will confirm approximately", name_new_fund_options["conf_target"], "after broadcast") # Get the change address for name_new name_new_custom_change_enabled, name_new_change_address = get_change_address() if name_new_custom_change_enabled: name_new_fund_options["changeAddress"] = name_new_change_address # Fund the transaction and add change output. name_new_funded = rpc_connection.fundrawtransaction(name_new_with_name["hex"], name_new_fund_options) # If Coin Control is enabled, make sure that fundrawtransaction didn't add extra inputs. if coin_control_enabled and len( rpc_connection.decoderawtransaction( name_new_funded["hex"])["vin"]) != len( rpc_connection.decoderawtransaction( name_new_with_name["hex"])["vin"]): print("Insufficient funds in Coin Control selection for name_new") quit() wallet_unlock() name_new_signed = rpc_connection.signrawtransaction(name_new_funded["hex"]) print("name_new has been signed")
cht = os.popen("%s %s -g -r %s -d %s" % (contracthashtool_path, testnet_arg, redeem_script, args.p2shSideAddress)) cht_read = cht.read() nonce = cht_read.split("\n")[0 + is_testnet][7:] full_contract = cht_read.split("\n")[1 + is_testnet][26:] send_address = cht_read.split("\n")[3 + is_testnet][40:] assert(cht.close() == None) if full_contract[0:8] != "50325348": print("You must use a P2SH address") exit(1) print("Sending %s to %s..." % (args.coinAmt, send_address)) print("(nonce: %s)" % nonce) try: tx_hex = bitcoin.createrawtransaction([], {send_address: Decimal(args.coinAmt)}) tx_hex = bitcoin.fundrawtransaction(tx_hex)['hex'] tx = bitcoin.signrawtransaction(tx_hex) assert(tx['complete']) tx_hex = tx['hex'] total_length = len(tx_hex)/2 total_length += 14*32 # maximum length of spv proof 1MB blocks total_length += 1000 # len(full_contract) + len(secondScriptPubKey) and rounded up to 1000 if total_length >= 10000: print("Transaction is too large.") exit(1) txid = bitcoin.sendrawtransaction(tx_hex) print("sendrawtransaction - Sent tx with id %s" % txid)
p2sh_tx_test = bitcoin.decoderawtransaction( bitcoin.createrawtransaction( [], {sys.argv[2]: 0.1}))["vout"][0]["scriptPubKey"] if p2sh_tx_test["type"] != "scripthash": print("You must use a P2SH address") exit(1) p2sh_hex = p2sh_tx_test["asm"].split(" ")[1] cht = os.popen( '%s -create outscript=%s:"0x1850325348%s OP_DROP 0x20%s 0x14%s WITHDRAWPROOFVERIFY"' % (sidechain_tx_path, sys.argv[3], p2sh_hex, inverse_bitcoin_genesis_hash, secondScriptPubKeyHash)) res_tx = cht.read().split("\n")[0] assert (cht.close() == None) donation = sidechain.fundrawtransaction(res_tx)["fee"] if donation > 0: if donation < 550: # Probably dust donation = 550 cht = os.popen( '%s -create outscript=%s:"0x1850325348%s OP_DROP 0x20%s 0x14%s WITHDRAWPROOFVERIFY" outscript=%s:"RETURN"' % (sidechain_tx_path, sys.argv[3], p2sh_hex, inverse_bitcoin_genesis_hash, secondScriptPubKeyHash, str(Decimal(donation) / Decimal(100000000)))) res_tx = cht.read().split("\n")[0] assert (cht.close() == None) res_tx = sidechain.fundrawtransaction(res_tx) fee = res_tx["fee"] res_tx = sidechain.signrawtransaction(res_tx["hex"])["hex"]