def payment_notify(social_id, payrec): user = User.query.filter_by(social_id=social_id).first() value = bitcoin.history(payrec.addr)[0]['value'] exchange = Bitstamp().get_current_price() usd_value = ((value) * float(exchange) / 100000000) usd_two_places = float(format(usd_value, '.2f')) token_call = { 'grant_type': 'refresh_token', 'client_id': STREAMLABS_CLIENT_ID, 'client_secret': STREAMLABS_CLIENT_SECRET, 'refresh_token': user.streamlabs_rtoken, 'redirect_uri': COINSTREAM_REDIRECT_URI } headers = [] tip_response = requests.post(api_token, data=token_call, headers=headers).json() user.streamlabs_rtoken = tip_response['refresh_token'] user.streamlabs_atoken = tip_response['access_token'] db.session.commit() tip_call = { 'name': payrec.user_display, 'identifier': payrec.user_identifier, 'message': payrec.user_message, 'amount': usd_two_places, 'currency': 'USD', 'access_token': tip_response['access_token'] } tip_check = requests.post(api_tips, data=tip_call, headers=headers).json() return tip_check
def get_history(): history = bitcoin.history(addr) total = 0 for tx in history: total += tx['value'] callback(total)
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 main(args): ''' OnionTip uses a simple Type 1 deterministic wallet where a key is generated from a seed appended with an increasing integer ''' logging.basicConfig(level=args.loglevel or logging.INFO, format='%(message)s') total_spent = 0 total_unspent = 0 logging.info(__doc__) logging.info( 'Starting to check {} addreses beginning from address offset {}\n'. format(args.limit, args.offset)) for key_increment in range(args.offset, (args.offset + args.limit)): address = bitcoin.electrum_address(args.public_seed, key_increment) try: history = bitcoin.history(address) except: logging.info( 'Network error when retreiving the transaction history for address {} (n={})' .format(address, key_increment)) break if not history: logging.debug( 'No transactions were found for address {} (n={})'.format( address, key_increment)) else: spent = sum( output.get('value', 0) for output in history if 'spend' in output) unspent = sum( output.get('value', 0) for output in history if not 'spend' in output) total_spent += spent total_unspent += unspent if unspent: logging.info( 'The address {} has unforwarded donations totaling {} satoshi! (n={})' .format(address, unspent, key_increment)) else: logging.info( 'All donations to {} totaling {} satoshi have been forwarded! (n={})' .format(address, spent, key_increment)) logging.info( '\nComplete! {} addresses were checked. {} satoshi were successfully forwarded and {} satoshi were unforwarded.' .format(args.limit, total_spent, total_unspent))
def check_and_send(address): ''' Check generated addresses and forwarded any unspent outputs Check_and_send does the heavy lifting for creating the bitcoin transactions for users on the web interface and for requests from the automated cronjob on the CLI ''' try: address_history = bitcoin.history(address) except Exception, err: app.logger.error('Error retrieving address history for {} from blockchain.info: {}'.format(address, str(err))) return {'status': 'error', 'message': '<strong>Blockchain.info Error:</strong> {}'.format(str(err)) }
def verify_payment(): btc_addr = request.form['btc_addr'] social_id = request.form['social_id'] payrec_check = PayReq.query.filter_by(addr=btc_addr).first() print "Checking for payment" payment_check_return = { 'payment_verified' : "FALSE" } if bitcoin.history(btc_addr) and payrec_check: payment_check_return['payment_verified'] = "TRUE" print "Payment Found!" payment_notify(social_id, payrec_check) db.session.delete(payrec_check) db.session.commit() return jsonify(payment_check_return)
def main(args): ''' OnionTip uses a simple Type 1 deterministic wallet where a key is generated from a seed appended with an increasing integer ''' logging.basicConfig(level=args.loglevel or logging.INFO, format='%(message)s') total_spent = 0 total_unspent = 0 logging.info(__doc__) logging.info('Starting to check {} addreses beginning from address offset {}\n'.format( args.limit,args.offset) ) for key_increment in range(args.offset, (args.offset + args.limit)): address = bitcoin.electrum_address(args.public_seed, key_increment) try: history = bitcoin.history(address) except: logging.info('Network error when retreiving the transaction history for address {} (n={})'.format( address, key_increment )) break if not history: logging.debug('No transactions were found for address {} (n={})'.format(address, key_increment)) else: spent = sum(output.get('value', 0) for output in history if 'spend' in output) unspent = sum(output.get('value', 0) for output in history if not 'spend' in output) total_spent += spent total_unspent += unspent if unspent: logging.info('The address {} has unforwarded donations totaling {} satoshi! (n={})'.format( address, unspent, key_increment) ) else: logging.info('All donations to {} totaling {} satoshi have been forwarded! (n={})'.format( address, spent, key_increment) ) logging.info('\nComplete! {} addresses were checked. {} satoshi were successfully forwarded and {} satoshi were unforwarded.'.format( args.limit, total_spent, total_unspent ))
def get_postings(): """ Retrive all books for sale in the mempool Returns: current_postings (list): list of current postings each element is tuple of (poster, isbn, price, quality) """ postings = [] canceled_postings = [] current_postings = [] txs = bitcoin.history(settings.MARKET_ADDRESS) for tx in txs: poster, isbn, price = None, None, None fetched = bitcoin.fetchtx(tx['output'].split(':')[0]) tx_outputs = bitcoin.deserialize(fetched)['outs'] tx_inputs = bitcoin.deserialize( bitcoin.fetchtx( bitcoin.deserialize(fetched)['ins'][0]['outpoint'] ['hash']))['outs'] for input in tx_inputs: if input['script'].startswith('76a914'): try: text = input['script'].lstrip('76a914').rstrip('88ac') poster = bitcoin.hex_to_b58check(text) except: pass for output in tx_outputs: if output['script'].startswith('6a'): text = str(binascii.unhexlify(output['script'][2:])) components = text.split('-') if len(components) == 3: isbn, price, quality = components isbn = isbn[-10:] if poster and isbn and price and quality: if price == '0': canceled_postings.append((poster, isbn)) else: postings.append((poster, isbn, price, quality)) for posting in postings: if (posting[0], posting[1]) not in canceled_postings: current_postings.append(posting) return list(set(current_postings))
def check_and_send(address): ''' Check generated address and forwarded any unspent outputs Check_and_send does the heavy lifting for creating the bitcoin transactions for users on the web interface and for requests from the automated cronjob on the CLI ''' try: address_history = bitcoin.history(address) except Exception, err: app.logger.error( 'Error retrieving address history for {} from blockchain.info: {}'. format(address, str(err))) return { 'status': 'error', 'message': '<strong>Blockchain.info Error:</strong> {}'.format(str(err)) }
def init_addresses(self, account_num): ''' find first address under account that has no transaction history iterate through 20 addresses from last one with tx history (BIP 44) this constant is set to 3 in this instance to save time returns free address under this account number ''' print("Initializing addresses for account : %i ..." % account_num) addr_count = 0 last_free = 0 internal = {} external = {} flag = True while True: external[addr_count] = self.get_address(account_num, 0, addr_count) internal[addr_count] = self.get_address(account_num, 1, addr_count) tx_history = history(external[addr_count]) if len(tx_history) == 0 and flag: last_free = addr_count flag = False if len(tx_history) != 0: flag = True if (addr_count - last_free) == ADDRESS_CAP and not flag: if last_free != 0: self.hierarchy[account_num] = { k: external[k] for k in range(0, last_free) } self.change_hierarchy[account_num] = { k: internal[k] for k in range(0, last_free) } return last_free addr_count += 1
def get_unused_address(social_id, deriv): ''' Need to be careful about when to move up the latest_derivation listing. Figure only incrementing the database entry when blockchain activity is found is the least likely to create large gaps of empty addresses in someone's BTC Wallet. ''' userdata = User.query.filter_by(social_id=social_id).first() # Pull BTC Address from given user data key = Key.from_text(userdata.xpub).subkey(0). \ subkey(deriv) address = key.address(use_uncompressed=False) # Check for existing payment request, delete if older than 5m. payment_request = PayReq.query.filter_by(addr=address).first() if payment_request: req_timestamp = payment_request.timestamp now_timestamp = datetime.utcnow() delta_timestamp = now_timestamp - req_timestamp if delta_timestamp > timedelta(seconds=60 * 5): db.session.delete(payment_request) db.session.commit() payment_request = None if not bitcoin.history(address): if not payment_request: return address else: print "Address has payment request..." print "Address Derivation: ", deriv return get_unused_address(social_id, deriv + 1) else: print "Address has blockchain history, searching new address..." print "Address Derivation: ", userdata.latest_derivation userdata.latest_derivation = userdata.latest_derivation + 1 db.session.commit() return get_unused_address(social_id, deriv + 1)
def get_messages(): """ Gets inbox messages from the mempool Returns: messages (dict): dict of messages {sender: {message_num: {submessage_num: message}}} """ messages = defaultdict(dict) priv, pub, addr = books.read_wallet() txs = bitcoin.history(addr) for tx in txs: sender, message_num, submessage_num, message = None, None, None, None fetched = bitcoin.fetchtx(tx['output'].split(':')[0]) tx_outputs = bitcoin.deserialize(fetched)['outs'] tx_inputs = bitcoin.deserialize( bitcoin.fetchtx( bitcoin.deserialize(fetched)['ins'][0]['outpoint'] ['hash']))['outs'] for output in tx_outputs: if output['script'].startswith('6a'): text = str(binascii.unhexlify(output['script'].lstrip('6a'))) message_num = text[1] submessage_num = text[2] message = text[3:] for input in tx_inputs: try: if input['script'].startswith('76a914'): text = input['script'].lstrip('76a914').rstrip('88ac') sender = bitcoin.hex_to_b58check(text) except: pass if sender and message: if sender != addr: if sender not in messages: messages[sender] = defaultdict(dict) messages[sender][message_num].update({submessage_num: message}) return messages
def mk_spend(wallet, dst, amount): h = b.history(wallet["address"]) h = filter(lambda x: 'spend' not in x, h) return mk_spend_txids(wallet, dst, amount, h)
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)
from bitcoin import history btcaddr = 'put btc addr here' print(history(btcaddr))
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)
import bitcoin as bt #any bitcoin Address btc_address = '329e5RtfraHHNPKGDMXNxtuS4QjZTXqBDg' #btc_address = input("Enter a BitCoin Address: ") #prints the history of the bitcoin address history = bt.history(btc_address) for i in history: for j in i: print(j, ":", i[j])