def build_tx(inputs, priv, addr, script, fee=0, send=False): """ Build a transaction to post/cancel a book sale Args: inputs (list): list of UTXOs to use. Obtained with bitcoin.unspent() priv (str): private key for wallet addr (str): address to post sale to script (str): script with encoded message of sale/cancelation fee (int): satoshis to pay to miners to write to the blockchain There is no reason to do this. send (bool): if True, send to mempool Returns: signed_tx (str): signed transaction to send to mempool also, sends transaction to mempool """ outputs = [{ 'value': 546, 'address': settings.MARKET_ADDRESS }, { 'value': 0, 'script': script }] fee = fee tx = bitcoin.mksend(inputs, outputs, addr, fee) signed_tx = bitcoin.sign(tx, 0, priv) if send: bitcoin.pushtx(signed_tx) return signed_tx
def pushPayment(self): #compliantScript = bitcoin.mk_multisig_script([bitcoin.privtopub(self.privS), self.pubKeyClient], 2,2) # inversion!!!! compliantScript = bitcoin.mk_multisig_script([self.pubKeyClient, bitcoin.privtopub(self.privS)], 2,2) sigServer = bitcoin.multisign(self.lastpayment, 0, compliantScript, self.privS) signedPtx = bitcoin.apply_multisignatures(self.lastpayment, 0, compliantScript, [self.lastsig, sigServer]) print 'Broadcast the very last payment. Just got richer. Tx hash:', bitcoin.txhash(signedPtx) bitcoin.pushtx(signedPtx)
def send(fromprivkey, toaddr, value): transaction_fee = 20000 print "Sending:", fromprivkey, toaddr, value tx = bitcoin.mksend(bitcoin.history(bitcoin.privtoaddr(fromprivkey)), [toaddr + ":" + str(value)], bitcoin.privtoaddr(fromprivkey), transaction_fee) signed_tx = bitcoin.sign(tx, 0, fromprivkey) bitcoin.pushtx(signed_tx)
def send_whole_wallet(fromprivkey, toaddr): transaction_fee = 20000 # .0002 BTC fromaddress = bitcoin.privtoaddr(fromprivkey) balance = sum(transaction['value'] for transaction in bitcoin.unspent(fromaddress)) assert balance >= transaction_fee tx = bitcoin.mktx(bitcoin.history(fromaddress), [{'value': balance - transaction_fee, 'address': toaddr}]) signed_tx = bitcoin.sign(tx, 0, fromprivkey) bitcoin.pushtx(signed_tx)
def send(fromprivkey, toaddr, value): transaction_fee = 20000 # .0002 BTC fromaddress = bitcoin.privtoaddr(fromprivkey) tx = bitcoin.mksend(bitcoin.history(fromaddress), [{ 'value': value, 'address': toaddr }], fromaddress, transaction_fee) signed_tx = bitcoin.sign(tx, 0, fromprivkey) bitcoin.pushtx(signed_tx)
def send_whole_wallet(fromprivkey, toaddr): transaction_fee = 20000 # .0002 BTC fromaddress = bitcoin.privtoaddr(fromprivkey) balance = sum(transaction['value'] for transaction in bitcoin.unspent(fromaddress)) assert balance >= transaction_fee tx = bitcoin.mktx(bitcoin.history(fromaddress), [{ 'value': balance - transaction_fee, 'address': toaddr }]) signed_tx = bitcoin.sign(tx, 0, fromprivkey) bitcoin.pushtx(signed_tx)
def pushPayment(self): #compliantScript = bitcoin.mk_multisig_script([bitcoin.privtopub(self.privS), self.pubKeyClient], 2,2) # inversion!!!! compliantScript = bitcoin.mk_multisig_script( [self.pubKeyClient, bitcoin.privtopub(self.privS)], 2, 2) sigServer = bitcoin.multisign(self.lastpayment, 0, compliantScript, self.privS) signedPtx = bitcoin.apply_multisignatures(self.lastpayment, 0, compliantScript, [self.lastsig, sigServer]) print 'Broadcast the very last payment. Just got richer. Tx hash:', bitcoin.txhash( signedPtx) bitcoin.pushtx(signedPtx)
def sign_n_send(filename, priv, addr, fee): if not os.path.isfile(filename): print "ERR: file not found" print "exiting, no operation" exit(-1) balance = get_balance(addr) if balance < fee: print "ERR: not enough funds, refill wallet", addr exit(-1) f = open(filename, "r") content = f.read() hashed = btc.sha256(content) print "hash\n" print hashed print "" sig_tx = op_return_tx('sha256:' + hashed[:32], priv) print "transaction hex is\n" print sig_tx #raise(Exception('not finished')) tid = btc.pushtx(sig_tx, 'testnet', source='blockr') return tid
def run(self): print 'Initialisation of MPC...' # exchange public keys pubKeyServer = bitcoin.privtopub(self.privS) print 'pubKeyServer: ', pubKeyServer self.pubKeyClient = txUtils.exchangePubKey(pubKeyServer, self.c) print 30 * '#', 'Handshake', 30 * '#' print 'Public Key received from client is: ', self.pubKeyClient # receive the signed Dtx and signedDtx = self.c.jrecv() print 'SignedDtx:', signedDtx #print pprint(bitcoin.deserialize(signedDtx)) scriptDtx = self.c.jrecv() print 'ScriptDtx: ', scriptDtx own = bitcoin.mk_multisig_script( [self.pubKeyClient, bitcoin.privtopub(self.privS)], 2, 2) # inversion!!!! if own != scriptDtx: print 'Anomalous ScriptDtx. Own is:', own # broadcast D bitcoin.pushtx(signedDtx) print 35 * '#', ' MPC initialised ', 35 * '#' self.balance += 1000000 # authorize use of the internet: hpUtils.allowFwd(self.ipClient) # set up Cashier (observed) self.cashier = cashier(self.c) self.cashier.addObserver(self) # obviously not the right way self.cashier.start() # start control spin self.controlSpin() # broadcast payment print 'Manager broadcasts payment' self.pushPayment() # terminate cashier print "Manager waiting for cashier's termination" self.cashier.join() #self.c.close() print 'Manager terminating'
def run(self): print 'Initialisation of MPC...' # exchange public keys pubKeyServer = bitcoin.privtopub(self.privS) print 'pubKeyServer: ', pubKeyServer self.pubKeyClient = txUtils.exchangePubKey(pubKeyServer, self.c) print 30*'#', 'Handshake', 30*'#' print 'Public Key received from client is: ', self.pubKeyClient # receive the signed Dtx and signedDtx = self.c.jrecv() print 'SignedDtx:' , signedDtx #print pprint(bitcoin.deserialize(signedDtx)) scriptDtx = self.c.jrecv() print 'ScriptDtx: ', scriptDtx own = bitcoin.mk_multisig_script([self.pubKeyClient, bitcoin.privtopub(self.privS)], 2,2) # inversion!!!! if own != scriptDtx: print 'Anomalous ScriptDtx. Own is:', own # broadcast D bitcoin.pushtx(signedDtx) print 35*'#',' MPC initialised ', 35*'#' self.balance += 1000000 # authorize use of the internet: hpUtils.allowFwd(self.ipClient) # set up Cashier (observed) self.cashier = cashier(self.c) self.cashier.addObserver(self) # obviously not the right way self.cashier.start() # start control spin self.controlSpin() # broadcast payment print 'Manager broadcasts payment' self.pushPayment() # terminate cashier print "Manager waiting for cashier's termination" self.cashier.join() #self.c.close() print 'Manager terminating'
def send_message(recipient_addr, scripts, fee=0, send=False): """ Send encoded message Args: recipient_addr (str): address of user to send message too scripts (list): list of strings, each element is a single encoded message. Multiple encodings are needed if the message is longer than 40 char. fee (int): Satoshis to pay in miner fees. Not actually required. send (bool): If True, send transactions to mempool. Returns: signed_txs (list): list of strings where each element is a signed transaction encoding a message Also sends transaction to the mempool. Notes: This is currently sending the message to blockchain.info, but this is trivially changed if needed. """ priv, pub, addr = books.read_wallet() signed_txs = [] for script in scripts: outputs = [{'value': 546, 'address': recipient_addr}] inputs = bitcoin.unspent(addr) for _input in inputs: if _input > 1092: input_tx = _input break outputs.append({'value': 0, 'script': script}) fee = fee tx = bitcoin.mksend(input_tx, outputs, addr, fee) signed_tx = bitcoin.sign(tx, 0, priv) if send: bitcoin.pushtx(signed_tx) signed_txs.append(signed_tx) if send: _write_message(recipient_addr, signed_txs) return signed_txs
def sendCustomTransaction(self, privkeys, inputs, outputs, fee=0): success = False totalInputValue = 0 UTXOs = [] for tx_input in inputs: if 'spend' not in tx_input: totalInputValue += tx_input['value'] UTXOs.append(tx_input) totalOutputValue = 0 for tx_output in outputs: totalOutputValue += tx_output['value'] diff = totalInputValue - totalOutputValue if fee != diff: pprint("Warning: Fee incorrect! aborting transaction") else: allKeysPresent = True allInputsConfirmed = True for tx_input in UTXOs: if tx_input['address'] not in privkeys: print 'not found:', tx_input['address'] allKeysPresent = False if tx_input['block_height'] == None: allInputsConfirmed = False if allKeysPresent == True and allInputsConfirmed == True: tx = bitcoin.mktx(UTXOs, outputs) for i in range(0, len(UTXOs)): tx = bitcoin.sign(tx, i, str(privkeys[UTXOs[i]['address']])) try: bitcoin.pushtx(tx) success = True except: e = sys.exc_info() print e success = False return success
def test(): x = new_wallet_mnemonic("definition+seen+production+cause") #send(x, "1B5kMyVu8DtXDvs5dqScrN98kA5RE6Ws3Q", 1) to = new_wallet_mnemonic("loading+money+onto+channel") #to="1B5kMyVu8DtXDvs5dqScrN98kA5RE6Ws3Q" #peer_pub="04b4810b2ddd78dd8f5cf1abdf547aa527bcfd45167aab0cad9e5e8062aa63e7ebc1fce2af55fe190f05533de581974e6b14fc481cd61a39a46eb7f0027f518ea8" receive = 10 send = 100000 secret_hash = "db1bab70f6a3e320f0d13bf46216ca9dade18e381e48000baed5775fe07b3970" #hash of "brainwallet" a = atomic(to["pub"], x, to["address"], send, receive, secret_hash) #print("a: " +str(a)) refund = a["refund"] channel = a["channel"] refund = atomic_sign_1(refund, 0, to["priv"], a["script"]) for i in range(len(b.deserialize(channel)["ins"])): channel = sign(channel, i, x["priv"]) refund = atomic_sign_2(refund, 0, x["priv"], a["script"]) print("channel: " + str(channel)) print(b.pushtx(channel)) print(b.pushtx(refund))
def test(): x=new_wallet_mnemonic("definition+seen+production+cause") #send(x, "1B5kMyVu8DtXDvs5dqScrN98kA5RE6Ws3Q", 1) to = new_wallet_mnemonic("loading+money+onto+channel") #to="1B5kMyVu8DtXDvs5dqScrN98kA5RE6Ws3Q" #peer_pub="04b4810b2ddd78dd8f5cf1abdf547aa527bcfd45167aab0cad9e5e8062aa63e7ebc1fce2af55fe190f05533de581974e6b14fc481cd61a39a46eb7f0027f518ea8" receive=10 send=100000 secret_hash="db1bab70f6a3e320f0d13bf46216ca9dade18e381e48000baed5775fe07b3970"#hash of "brainwallet" a=atomic(to["pub"], x, to["address"], send, receive, secret_hash) #print("a: " +str(a)) refund=a["refund"] channel=a["channel"] refund=atomic_sign_1(refund, 0, to["priv"], a["script"]) for i in range(len(b.deserialize(channel)["ins"])): channel = sign(channel, i, x["priv"]) refund=atomic_sign_2(refund, 0, x["priv"], a["script"]) print("channel: " +str(channel)) print(b.pushtx(channel)) print(b.pushtx(refund))
def sendCustomTransaction(self, privkeys, inputs, outputs, fee=0): success = False totalInputValue = 0 UTXOs = [] for tx_input in inputs: if 'spend' not in tx_input: totalInputValue += tx_input['value'] UTXOs.append(tx_input) totalOutputValue = 0 for tx_output in outputs: totalOutputValue += tx_output['value'] diff = totalInputValue - totalOutputValue if fee != diff: self.response.write( "<br>Warning: Fee incorrect! aborting transaction") logging.error("Warning: Fee incorrect! aborting transaction") else: allKeysPresent = True allInputsConfirmed = True for tx_input in UTXOs: if tx_input['address'] not in privkeys: allKeysPresent = False if tx_input['block_height'] == None: allInputsConfirmed = False if allKeysPresent == True and allInputsConfirmed == True: tx = bitcoin.mktx(UTXOs, outputs) for i in range(0, len(UTXOs)): tx = bitcoin.sign(tx, i, str(privkeys[UTXOs[i]['address']])) bitcoin.pushtx(tx) success = True return success
def sendCustomTransaction(self, privkeys, inputs, outputs, fee=0): success = False totalInputValue = 0 UTXOs = [] for tx_input in inputs: if 'spend' not in tx_input: totalInputValue += tx_input['value'] UTXOs.append(tx_input) totalOutputValue = 0 for tx_output in outputs: totalOutputValue += tx_output['value'] diff = totalInputValue - totalOutputValue if fee != diff: self.response.write("<br>Warning: Fee incorrect! aborting transaction") logging.error("Warning: Fee incorrect! aborting transaction") else: allKeysPresent = True allInputsConfirmed = True for tx_input in UTXOs: if tx_input['address'] not in privkeys: allKeysPresent = False if tx_input['block_height'] == None: allInputsConfirmed = False if allKeysPresent == True and allInputsConfirmed == True: tx = bitcoin.mktx(UTXOs, outputs) for i in range(0, len(UTXOs)): tx = bitcoin.sign(tx, i, str(privkeys[UTXOs[i]['address']])) bitcoin.pushtx(tx) success = True return success
return { 'status': 'fail', 'data': { 'message': 'There are no addresses to where the donation can be successfully forwarded. The value of the donation may be too low, try sending a little more.', 'code': 500 } } raw_tx = bitcoin.transaction.mktx(address_unspent, outs) tx = bitcoin.transaction.signall(raw_tx, address_info.private_key) tx_hash = bitcoin.transaction.txhash(tx) try: try: push_result = bitcoin.pushtx(tx) except: push_result = bitcoin.blockr_pushtx(tx) tx_total = sum(out.get('value') for out in outs) # This address has been successfully spent from, update tx info and don't check it again. address_info.spent = True address_info.spending_tx = tx_hash address_info.donation_amount = tx_total # Keep a total of all bitcoins tipped total_donated = DataStore.query.filter_by( key='total_donated').first() if total_donated: total_donated.value = int(int(total_donated.value) + tx_total) else:
def send(wallet, dst, amount): return b.pushtx(mk_spend(wallet, dst, amount)) def txid(tx): return b.txhash(tx)
def send(fromprivkey, toaddr, value): transaction_fee = 20000 print "Sending:", fromprivkey, toaddr, value tx = bitcoin.mksend(bitcoin.history(bitcoin.privtoaddr(fromprivkey)), [toaddr+":"+str(value)], bitcoin.privtoaddr(fromprivkey), transaction_fee) signed_tx = bitcoin.sign(tx, 0, fromprivkey) bitcoin.pushtx(signed_tx)
def send(wallet, dst, amount): return b.pushtx(mk_spend(wallet, dst, amount))
def commitTo(self, testnet, commit_address, private_key): """ Commit to some address on the blockchain """ # Check if we have the keys for the BM address public_key = highlevelcrypto.privToPub( private_key.encode('hex')).decode('hex') fromAddress = self.getAddress(testnet, public_key) result = self.getUnspentTransactions(testnet, [fromAddress]) if not 'unspent' in result or len(result['unspent']) == 0: log_debug("commitTo: No unspent TXs (%s)" % (fromAddress)) return False unspent_txs = result['unspent'] # filter for those with an amount >= minimum amount unspent_txs = filter( lambda tx: float(tx['amount']) > BitcoinThread. BTC_UNSPENT_MIN_AVAILABLE, unspent_txs) if len(unspent_txs) == 0: log_debug("commitTo: No unspent TXs >= %d (%s, %s)" % (BitcoinThread.BTC_UNSPENT_MIN_AVAILABLE, fromAddress, result['unspent'])) return False # Find random unspent with an amount >= 0.00010 mBTC random.shuffle(unspent_txs) while len(unspent_txs) > 0: tx = unspent_txs.pop(0) log_debug("Trying unspent tx: %s" % tx) amount = float(tx['amount']) amount_satoshis = int(amount * 100000000) change_satoshis = amount_satoshis - BitcoinThread.SATOSHI_COMMITMENT_AMOUNT - BitcoinThread.SATOSHI_TRANSACTION_FEE # Code in bitcoin.mktx separates the input string into tx=input[:64] and n=input[65:] input_tx = "%s %d" % (tx['tx'], tx['n']) commit_payable = { "address": commit_address, "value": BitcoinThread.SATOSHI_COMMITMENT_AMOUNT } change_payable = {"address": fromAddress, "value": change_satoshis} tx = bitcoin.mktx([input_tx], [commit_payable, change_payable]) signed_tx = bitcoin.sign(tx, 0, private_key) log_debug("Pushing tx: %s" % bitcoin.deserialize(tx)) if testnet: try: result = json.loads( bitcoin.blockr_pushtx(signed_tx, 'testnet')) except Exception, e: # If we get {"status":"fail","data":"Could not push your transaction!","code":500,"message":"Did you sign your transaction?"} # in an exception here, it probably means that the referenced inputs in our transaction have been spent in the meantime. try: e_obj = json.loads(e.message) if e_obj["data"] == "Could not push your transaction!": from debug import logger log_warn( "Couldn't push transaction. Sometimes this is because the referenced inputs have been spent in the meantime, %s" % e_obj) # Continue to try the next unspent tx continue else: log_warn(e) except: log_warn(e) return 'status' in result and result['status'] == "success" else: # if not testnet # I had problems pushing non-testnet transactions to blockr.io, # so we're using blockchain.info for this, and that works fine. try: result = bitcoin.pushtx(signed_tx) if result.lower() == "transaction submitted": log_debug("Committed to %s" % commit_address) return True else: log_warn("Transaction push fail: %s" % (result, )) except Exception, e: log_warn("Transaction push exception: %s" % (e, )) continue
def commitTo(self, testnet, commit_address, private_key): """ Commit to some address on the blockchain """ # Check if we have the keys for the BM address public_key = highlevelcrypto.privToPub( private_key.encode('hex') ).decode('hex') fromAddress = self.getAddress( testnet, public_key ) result = self.getUnspentTransactions( testnet, [fromAddress] ) if not 'unspent' in result or len( result['unspent'] ) == 0: log_debug( "commitTo: No unspent TXs (%s)" % ( fromAddress ) ) return False unspent_txs = result['unspent'] # filter for those with an amount >= minimum amount unspent_txs = filter( lambda tx: float( tx['amount'] ) > BitcoinThread.BTC_UNSPENT_MIN_AVAILABLE, unspent_txs ) if len( unspent_txs ) == 0: log_debug( "commitTo: No unspent TXs >= %d (%s, %s)" % ( BitcoinThread.BTC_UNSPENT_MIN_AVAILABLE, fromAddress, result['unspent'] ) ) return False # Find random unspent with an amount >= 0.00010 mBTC random.shuffle( unspent_txs ) while len( unspent_txs ) > 0: tx = unspent_txs.pop( 0 ) log_debug( "Trying unspent tx: %s" % tx ) amount = float( tx['amount'] ) amount_satoshis = int( amount * 100000000 ) change_satoshis = amount_satoshis - BitcoinThread.SATOSHI_COMMITMENT_AMOUNT - BitcoinThread.SATOSHI_TRANSACTION_FEE # Code in bitcoin.mktx separates the input string into tx=input[:64] and n=input[65:] input_tx = "%s %d" % ( tx['tx'], tx['n'] ) commit_payable = { "address": commit_address, "value": BitcoinThread.SATOSHI_COMMITMENT_AMOUNT } change_payable = { "address": fromAddress, "value": change_satoshis } tx = bitcoin.mktx( [input_tx], [ commit_payable, change_payable ] ) signed_tx = bitcoin.sign(tx, 0, private_key ) log_debug( "Pushing tx: %s" % bitcoin.deserialize( tx ) ) if testnet: try: result = json.loads( bitcoin.blockr_pushtx(signed_tx, 'testnet') ) except Exception, e: # If we get {"status":"fail","data":"Could not push your transaction!","code":500,"message":"Did you sign your transaction?"} # in an exception here, it probably means that the referenced inputs in our transaction have been spent in the meantime. try: e_obj = json.loads( e.message ) if e_obj["data"] == "Could not push your transaction!": from debug import logger log_warn( "Couldn't push transaction. Sometimes this is because the referenced inputs have been spent in the meantime, %s" % e_obj ) # Continue to try the next unspent tx continue else: log_warn( e ) except: log_warn( e ) return 'status' in result and result['status'] == "success" else: # if not testnet # I had problems pushing non-testnet transactions to blockr.io, # so we're using blockchain.info for this, and that works fine. try: result = bitcoin.pushtx( signed_tx ) if result.lower() == "transaction submitted": log_debug( "Committed to %s" % commit_address ) return True else: log_warn( "Transaction push fail: %s" % ( result, ) ) except Exception, e: log_warn( "Transaction push exception: %s" % ( e, ) ) continue
out['value'] += int(math.floor(new_ratio * discarded_value)) if not outs: app.logger.error('Could not find addresses suitable to spend to from {}. Outputs may be too small.'.format(address)) return {'status': 'fail', 'data': { 'message': 'There are no addresses to where the donation can be successfully forwarded. The value of the donation may be too low, try sending a little more.', 'code': 500 }} raw_tx = bitcoin.transaction.mktx(address_unspent, outs) tx = bitcoin.transaction.signall(raw_tx, address_info.private_key) tx_hash = bitcoin.transaction.txhash(tx) try: push_result = bitcoin.pushtx(tx) tx_total = sum(out.get('value') for out in outs) # This address has been successfully spent from and doesn't need to be checked again. address_info.spent = True # Keep a total of all bitcoins tipped total_donated = DataStore.query.filter_by(key='total_donated').first() if total_donated: total_donated.value = int(int(total_donated.value) + tx_total) else: total_donated = DataStore('total_donated', tx_total) db.session.add(total_donated) db.session.commit() app.logger.info('Transaction successfully sent {} satoshi from {} in tx {}.'.format(tx_total, address, tx_hash))
def send(fromprivkey, toaddr, value): transaction_fee = 20000 # .0002 BTC fromaddress = bitcoin.privtoaddr(fromprivkey) tx = bitcoin.mksend(bitcoin.history(fromaddress), [{'value': value, 'address': toaddr}], fromaddress, transaction_fee) signed_tx = bitcoin.sign(tx, 0, fromprivkey) bitcoin.pushtx(signed_tx)
def send(self, from_account, to_addr, amount, fee=0): ''' This method sends the transaction from create_tx to the mainnet''' tx = self.create_tx(from_account, to_addr, amount, fee) res = pushtx(binascii.unhexlify(tx)) return res