def push_raw_tx(tx_signed_raw): pushtx(tx_hex=tx_signed_raw, coin_symbol='btc-testnet', api_key='0b63236dab064c8fb9e1f53e97895b7e') tx_hash = public_txhash(tx_signed_raw) print(tx_hash) return tx_hash
def sendfunding(self): global a t = strftime("%Y-%m-%d %H:%M") self.time = unicode(t) self.lineEdit_2.setText(_translate("send2bit", self.time, None)) a = '1' send('1') flag = 'btc-testnet' mytoken = 'bcd4149ae42a400c9838081564d6ec23' print pushtx(self.sigid[0], flag, mytoken) self.showHint()
def do_broadcast(self, line): param = line.split(" ") if len(param) > 1 or param[0] == '-help': print("usage: broadcast [-testnet (optional)]") return if not hasattr(self, 'broadcast'): print("usege: call send before broadcast") return if (param[0] == "-testnet"): API_KEY = "3e10e111bbcc4c6e8fb7fc9baafb564e" check = blockcypher.pushtx(tx_hex = self.broadcast, coin_symbol='btc-testnet', api_key = API_KEY) if 'tx' in check: print("Broadcast succesfull tx_hex: %" % check['tx']['hash'], "yellow") elif 'error' in check: print(colored(check['error'], 'red')) else: print(check) else: url = "http://127.0.0.1:5000/transaction" data = {'data': self.broadcast} r = requests.post(url, data) if r.status_code == 200: print(colored("Broadcast succesfull", "yellow")) else: print(colored("Broadcast fail", "red"))
def push_raw_tx(tx_serialized_hex): API_KEY = 'e1d429fefa834a18abb6f16ebd4f557d' coin = 'btc-testnet' # returns a JSON object: """ Pushed Tx: {'tx': {'block_height': -1, 'block_index': -1, 'hash': '0aa127db5e775571f1919bccddc9ef4e52aa3785585a5a26d42fb7282e6ac992', 'addresses': ['mwV7paRv7VdcecM1UPc2jLEWYJb9Uk8pzB', 'muArwFiHwKb682YwStc9VdevUeosghzxTq', 'n1fpHjQXCEumdBVKhhJA77aEmsdjNLErNr', 'mkKJzpQbCQacNtKn6n8MR43nF3CX2v8ttP'], 'total': 950000, 'fees': 50000, 'size': 260, 'preference': 'high', 'relayed_by': '216.18.205.180', 'received': '2020-08-22T17:58:52.741500514Z', 'ver': 1, 'double_spend': False, 'vin_sz': 1, 'vout_sz': 3, 'confirmations': 0, 'inputs': [{'prev_hash': '1379573a272bc1d5b2c6ddf82f0a653d1acb3539f6ee231e2f1c2ed1243812b3', 'output_index': 0, 'script': '483045022100fd66ba3d86cd5283479946b47267c47fb1bf47a2eda6de4fd55e1ee4c00b6b46022017492d5215026337d484d2fa8e9c92112394a48fbef1274da76eb32869fe729c0121035f43cc7aef82e9b603cafdc35b3e0b274138c23323eb05f3b7f7c818534120c4', 'output_value': 1000000, 'sequence': 4294967295, 'addresses': ['mwV7paRv7VdcecM1UPc2jLEWYJb9Uk8pzB'], 'script_type': 'pay-to-pubkey-hash', 'age': 1773191}], 'outputs': [{'value': 100000, 'script': '76a91495c4f7f5aa0390f476865a2a416ac0be1125c8ba88ac', 'addresses': ['muArwFiHwKb682YwStc9VdevUeosghzxTq'], 'script_type': 'pay-to-pubkey-hash'}, {'value': 200001, 'script': '76a914dd0f939e30b2ba468d8ce8fac07c512d3dffe3d788ac', 'addresses': ['n1fpHjQXCEumdBVKhhJA77aEmsdjNLErNr'], 'script_type': 'pay-to-pubkey-hash'}, {'value': 649999, 'script': '76a91434a4eb52a487bc2cdc3839355322b3e7d1c028ab88ac', 'addresses': ['mkKJzpQbCQacNtKn6n8MR43nF3CX2v8ttP'], 'script_type': 'pay-to-pubkey-hash'}]}} """ return pushtx(tx_hex=tx_serialized_hex, coin_symbol=coin, api_key=API_KEY)
def open_tx(committer, secret, commit_tx_hash): # 创建输入脚本 p2pkh_solver = P2pkhSolver(committer.privk) hasklock_solver = HashlockSolver(secret.encode(), p2pkh_solver) if_solver = IfElseSolver( Branch.IF, # branch selection hasklock_solver) # 创建输出脚本 script = P2pkhScript(committer.pubk) # 获取commit交易 to_spend_raw = get_raw_tx(commit_tx_hash, coin_symbol) to_spend = TransactionFactory.unhexlify(to_spend_raw) # 获取罚金数额 penalty = int(float(to_spend.to_json()['vout'][0]['value']) * (10**8)) # 估算挖矿费用 print('estimating mining fee...') mining_fee_per_kb = get_mining_fee_per_kb(coin_symbol, committer.api_key, condidence='high') estimated_tx_size = cal_tx_size_in_byte(inputs_num=1, outputs_num=1) mining_fee = int(mining_fee_per_kb * (estimated_tx_size / 1000)) * 2 # 创建交易 unsigned = MutableTransaction(version=2, ins=[ TxIn(txid=to_spend.txid, txout=0, script_sig=ScriptSig.empty(), sequence=Sequence.max()) ], outs=[ TxOut(value=penalty - mining_fee, n=0, script_pubkey=script), ], locktime=Locktime(0)) # 修改交易 signed = unsigned.spend([to_spend.outs[0]], [if_solver]) # 广播交易 print('open_tx_hex: ', signed.hexlify()) msg = pushtx(coin_symbol=coin_symbol, api_key=committer.api_key, tx_hex=signed.hexlify()) format_output(msg) return msg['tx']['hash']
def do_broadcast(self, args): """ broadcast - send POST request with serialized transaction data to web API of Pitcoin full node, which provide route /transaction/new. broadcast Testnet - send POST request with serialized transaction data to Testnet""" if self.transaction != 1: args = args.split() if len(args) > 0 and args[0] == "-t": check = blockcypher.pushtx(tx_hex=self.transaction, coin_symbol='btc-testnet', api_key=API_KEY) else: broadcast_command(self.transaction) self.transaction = 1 else: print('Use command send before broadcast command!\n')
def send_subsidized(hex_privkey, unsigned_tx_hex): reply = {} # sign all unsigned inputs signed_tx = sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex) resp = pushtx(tx_hex=signed_tx) if 'tx' in resp: reply['tx_hash'] = resp['tx']['hash'] else: reply['error'] = "ERROR: broadcasting tx" log.debug(pprint(resp)) return reply
def send_payment(hex_privkey, to_address, btc_amount): to_satoshis = btc_to_satoshis(btc_amount) fee_satoshis = btc_to_satoshis(TX_FEE) signed_tx = make_send_to_address_tx(to_address, to_satoshis, hex_privkey, blockchain_client=blockcypher_client, fee=fee_satoshis) resp = pushtx(tx_hex=signed_tx) if 'tx' in resp: return resp['tx']['hash'] else: log.debug("ERROR: broadcasting tx") return resp
def send_payment(hex_privkey, to_address, btc_amount): payment_address = get_address_from_privkey(hex_privkey) if dontuseAddress(payment_address): log.debug("Payment address %s not ready" % payment_address) return None to_satoshis = btc_to_satoshis(btc_amount) fee_satoshis = btc_to_satoshis(TX_FEE) signed_tx = make_send_to_address_tx(to_address, to_satoshis, hex_privkey, blockchain_client=blockcypher_client, fee=fee_satoshis) resp = pushtx(tx_hex=signed_tx, api_key=BLOCKCYPHER_TOKEN) if 'tx' in resp: return resp['tx']['hash'] else: log.debug("ERROR: broadcasting tx") return resp
rows = cur.fetchall() for row in rows: transaction_info = row[1] transaction_info_hex = transaction_info.decode('hex') sha_tx = hashlib.sha256(transaction_info_hex).digest() sha_f = hashlib.sha256(sha_tx).digest() sha_f = sha_f[::-1].encode('hex_codec') #print sha_f #if form.getvalue(transaction_info): try: #try to get raw trans #request_url = request_fetch_if_exist_prefix + sha_f #now we veryfy if that is already in network #r = requests.get(request_url) result = blockcypher.pushtx(transaction_info, coin_symbol='btc-testnet', api_key=blockCypherApiToken) #print r cur.execute( "UPDATE Transaction_Info SET verified = ? WHERE transaction_text = ?", ( 'TRUE', transaction_info, )) print "<p>A transação %s foi submetida com sucesso.</p>" % ( sha_f) ################################################### ########Add code for change transactions status#### ################################################### except:
to_spend = TransactionFactory.unhexlify(to_spend_raw) unsigned = MutableTransaction(version=2, ins=[ TxIn(txid=to_spend.txid, txout=0, script_sig=ScriptSig.empty(), sequence=Sequence.max()) ], outs=[ TxOut(value=penalty, n=0, script_pubkey=lock_time_script), TxOut(value=balance - penalty - mining_fee, n=1, script_pubkey=change_script) ], locktime=Locktime(0)) # 输入脚本 solver = P2pkhSolver(privk) # 修改交易 signed = unsigned.spend([to_spend.outs[0]], [solver]) print('commit_tx_hex: ', signed.hexlify()) # 发送交易 from blockcypher import pushtx tx = pushtx(coin_symbol=coin_symbol, api_key=api_key, tx_hex=signed.hexlify()) format_output(tx)
def commit_tx(committer, receiver, secret, type, lock_time, penalty): if type not in ['Timed', 'Height']: raise ValueError("type should be 'Timed' or 'Height'") secret_hash = hashlib.sha256(hashlib.sha256( secret.encode()).digest()).digest() secret_hash = StackData.from_bytes(secret_hash) print("秘密经hash256加密结果:", secret_hash) # 创建输出脚本 if type is 'Height': # Relative - HeightBased sequence = lock_time lock_time_script = IfElseScript( # if branch Hashlock256Script(secret_hash, P2pkhScript(committer.pubk)), # else branch RelativeTimelockScript( # timelocked script HeightBasedSequence(sequence), # expiration P2pkhScript(receiver.pubk))) else: # Relative - TimedBased time_delta = datetime.timedelta(minutes=lock_time) time_now = datetime.datetime.now() print("current time: ", time_now.strftime("%y-%m-%d %H:%M:%S")) print("pay deposit time: ", (time_now + time_delta).strftime("%y-%m-%d %H:%M:%S")) lock_time_script = IfElseScript( # if branch Hashlock256Script(secret_hash, P2pkhScript(committer.pubk)), # else branch RelativeTimelockScript( # timelocked script TimeBasedSequence.from_timedelta(time_delta), # expiration P2pkhScript(receiver.pubk))) # 找零脚本 change_script = P2pkhScript(committer.pubk) # 清理资产 print("sweeping fund...") to_spend_hash, balance = sweep_fund(privkey=str(committer.privk), address=str(committer.address), coin_symbol=coin_symbol, api_key=committer.api_key) # 估算挖矿费用 print('estimating mining fee...') mining_fee_per_kb = get_mining_fee_per_kb(coin_symbol, committer.api_key, condidence='high') estimated_tx_size = cal_tx_size_in_byte(inputs_num=1, outputs_num=2) mining_fee = int(mining_fee_per_kb * (estimated_tx_size / 1000)) * 2 # 设置罚金 assert penalty + mining_fee <= balance, 'committer账户余额不足' # 创建交易 to_spend_raw = get_raw_tx(to_spend_hash, coin_symbol) to_spend = TransactionFactory.unhexlify(to_spend_raw) unsigned = MutableTransaction(version=2, ins=[ TxIn(txid=to_spend.txid, txout=0, script_sig=ScriptSig.empty(), sequence=Sequence.max()) ], outs=[ TxOut(value=penalty, n=0, script_pubkey=lock_time_script), TxOut(value=balance - penalty - mining_fee, n=1, script_pubkey=change_script) ], locktime=Locktime(0)) # 输入脚本 solver = P2pkhSolver(committer.privk) # 修改交易 signed = unsigned.spend([to_spend.outs[0]], [solver]) print('commit_tx_hex: ', signed.hexlify()) # 发送交易 tx = pushtx(coin_symbol=coin_symbol, api_key=committer.api_key, tx_hex=signed.hexlify()) format_output(tx) return tx['tx']['hash']
tx_value_list = [tx_value] d_addr_list = [d_addr] for utxo in utxos: prev_tx_list.append(utxo["tx_hash"]) prev_tx_output_list.append(utxo["tx_output_n"]) if exchange: tx_value_list.append(tx_exchange) d_addr_list.append(exchange_addr) # Creates the transaction new_tx = build_raw_tx(prev_tx_list, prev_tx_output_list, tx_value_list, s_addr, d_addr_list) t = pushtx(tx_hex=new_tx.strip(), coin_symbol="btc-testnet", api_key="c042531962c741879044c11c11b042a2") if "error" in t: print(t) else: print(f'Transaction ID:\n{t["tx"]["hash"]}') elif "try_utxo" in args: addr_details = get_address_details( "mqa4rqExcA7GY8ZqGhpXted6UQNJnpGA2B", coin_symbol="btc-testnet", unspent_only=True) utxos = addr_details["txrefs"] print(utxos)
#print "My testnetAddress is: ", testnetAddress #pubkey1 = bitcoin.privkey_to_pubkey('139cb0d1038dccc8b5e7e224216670b76647c9f8df8a8ec29069cbb3d59aed2b') #pubkey2 = bitcoin.privkey_to_pubkey('36b4fbdf43365191d3aea9361467b234f58a7244ae8d05f696e634726a162d01') #pubkey = bitcoin.privkey_to_pubkey('15e9a5e2097c9a40eb4bd0aea4e334dd2f799c7e1f6173cb59505d470816fe9e') #print "pubkey 1: ", pubkey1 #print "pubkey 2: ", pubkey2 #print "intial pubkey: ", pubkey #num = bitcoin.is_privkey('15e9a5e2097c9a40eb4bd0aea4e334dd2f799c7e1f6173cb59505d470816fe9e') pub = bitcoin.privkey_to_pubkey( '15e9a5e2097c9a40eb4bd0aea4e334dd2f799c7e1f6173cb59505d470816fe9e') compPub = bitcoin.compress(pub) add = bitcoin.pubkey_to_address(compPub, 111) print compPub print add #if num: # print "OK" #else: # print "damn" #print add transaction_info = '01000000018fd99010bf216c4aeece38bebcc94a740b853d64a4ee5d7d8217bf61b77abb1a010000006b483045022100f2353403f2f6aeb981b0870f35c0441e58a15786dd4c76307b8129d786031fcc022039c1861433a28d71026ba5860078cd8aa61951faee73af916fcb7d3301ac6ffc0121035ec6f5e117a67b3164f388105bf23b3d2af9fb39f939e24df53cf303b27e1bf7ffffffff01e01fec22000000001976a91464e6df2dbc78c34a8fffe908c223bd05683c479688ac00000000' txinfo_hex = transaction_info.decode("hex") transaction_i = hashlib.sha256(txinfo_hex).digest() transaction_id = hashlib.sha256(transaction_i).digest() transaction_id = transaction_id[::-1].encode('hex_codec') print transaction_id #Starting api = '2422c50d3321416d97d2184cb76a2fed' tx = '0100000001aa4e7c55ad414ef9d1d3724043190436fb551930d455d8fa0b84f51375e46182000000006b483045022100c51a09fb137084f7f2149c14ccac7209fdb3e772a3a7e49b5247ac14b9eaa71802203321b6998d812aaa91b3578187918d6f65e72624fd2c4be45bc417f5d453b522012102a10be900dfd57ac00eeb0259b7f4c61566b111599fd762ae4befb7a16ed8d78fffffffff0240420f00000000001976a91464e6df2dbc78c34a8fffe908c223bd05683c479688ac6416fb06000000001976a91447a022a80d1cbf4f7ebf84870caf4b3596728bd788ac00000000' print blockcypher.pushtx(tx, coin_symbol='btc-testnet', api_key=api)
def sendBTC (fromAddress, toAddress, satValue, satFee, fromWIF ): """Send testnet Bitcoin from `fromAddress` to `toAddress`. Args: fromAddress (str): Address of sender. toAddress (str): Address of recipient. satValue (int): Transaction amount in Satoshi. Pass -1 to send entire balance. satFee (int): Transaction fee in Satoshi. fromWIF (str): WIF string of sender. Returns: Success: { 'status': 'success', 'result': decoded transaction } Failure: { 'status': 'failure', 'error': error message } """ response = { 'status': 'failure', } try: # validation if len(fromAddress) != 34: response['error'] = "fromAddress should be 34 letters." return response if len(toAddress) != 34: response['error'] = "toAddress should be 34 letters." return response if len(fromWIF) != 52: response['error'] = "fromWIF should be 52 letters." return response key = PrivateKeyTestnet(wif=fromWIF) if key.address != fromAddress: response['error'] = "fromAddress cannot be derived from fromWIF." return response key.get_balance(currency='satoshi') satBalance = key.balance print ('\nBalance (satoshi): ') print (satBalance) if satValue == -1: # sending all amount if satBalance < satFee: response['error'] = "insufficient balance. less than tx fee." return response else: if satBalance < satFee + satValue: response['error'] = "insufficient balance." return response # create transaction print ('\nTransactions: ') print (key.get_transactions()) print ('\nUTXOs: ') print (key.get_unspents()) if satValue == -1: # sending all amount rawtx = key.create_transaction(outputs=[], leftover=toAddress, fee=satFee, absolute_fee=True) else: output1 = (toAddress, satValue, 'satoshi') output2 = (fromAddress, satBalance - satValue - satFee, 'satoshi') rawtx = key.create_transaction(outputs=[output1, output2], fee=satFee, absolute_fee=True) # push transaction decodedTx = blockcypher.pushtx(tx_hex=rawtx, coin_symbol='btc-testnet', api_key=APIKEY) response['status'] = 'success' response['result'] = decodedTx return response except TypeError as err: response['error'] = str(err) return response except Exception as err: response['error'] = str(err) return response response['error'] = 'unexpected error occured.' return response
from blockcypher import pushtx Hex = '01000000023573cd82132ab9338539a497385abba69bdf0f2dc2e08f0faf11945053fde8a0010000006b483045022100c05c91d8ccd703de44bb641707877113584d1915f921e466437d33ed84732a7302200500316109799c1224cb2f52f638cab62aabc2d7dd7e76f5fd5151ba59c58c0b012103b68793892f1dcb7ea2d78f14e993c1f4075b6e483125f691c55fe858fba2e75dffffffff13ff24d8ccf019c417e8639190bc8e43e29621718f346b69e1cd19aa3b40dd3e000000008b483045022100ee5388a8bc4348c65490d1ca8d83307d05ec2855b127156e3bd260601f65fbe102203312b1d2deb0ac0c7bba8b364cccea9d80d935cbefe143df01ee272c38b24fa001410450d3fd4360b76b6d5c33129620d657b9b0f2703c5ac1edf947840675d17dee5eeb9fc3f77a10a01304bfdcd1812edda92675ff3f2a7d25e7d383032f68267e06ffffffff0100497f0f0000000017a9142349a1de6d8f73ae399ecef22c1c21e6127797268700000000' flag = 'btc-testnet' mytoken = 'bcd4149ae42a400c9838081564d6ec23' print pushtx(Hex, flag, mytoken)