def run(self, starting_block=351816, run_forever=False, sleep_for=30): q = Queue() # 1 confirmation should mean top_block = latest_block.height, offset of 1 needed top_block = get_latest_block().height - CONFIRMATIONS_NEEDED + 1 min_block = starting_block cached_blocks = set() def update_queue(): nonlocal cached_blocks _chunk = 750 # 1000 throws exception for i in range(min_block, top_block + 1, _chunk): comp_range = list(filter(lambda j: j not in cached_blocks, range(i, i + _chunk))) cached_blocks = cached_blocks | {i.height for i in self.session.query(ScannedBlock).filter(ScannedBlock.height.in_(comp_range)).all()} for i in range(min_block, top_block + 1): if i not in cached_blocks: q.put(i) cached_blocks.add(i) update_queue() while True: n = min(q.qsize(), 50) if n == 0: if run_forever: print(int(time()), 'No blocks with >= %d confirmations, sleeping for %d seconds then updating...' % (CONFIRMATIONS_NEEDED, sleep_for)) sleep(sleep_for) top_block = get_latest_block().height - CONFIRMATIONS_NEEDED update_queue() continue else: break to_fetch = [q.get() for _ in range(n)] print('Fetching %d, min: %d, max: %d' % (n, min(to_fetch), max(to_fetch))) blocks = get_blocks(*to_fetch) for block in blocks: h = block['height'] t = block['timestamp'] nds = block['op_returns'] self.session.add_all([Nulldata(height=h, timestamp=t, txid=nulldata['txid'], script=nulldata['script']) for nulldata in nds]) self.session.add(ScannedBlock(height=h)) self.session.commit() print('Processed', block['height'])
def handle(self, *args, **options): import blockchain blockchain.util.TIMEOUT = 60 Last = None CurrencyInstance = Currency.objects.get(title="BTC") AccountList = PoolAccounts.objects.filter(currency_id=2) OwnAccounts = {} print "get all addresses" for i in AccountList: if i.address == '' or i.address is None or i.user is None: continue OwnAccounts[i.address] = i.user while True: try: Last = VolatileConsts.objects.get(Name="last_btc_process_block") except: print "there is no previouse info" sys.exit(0) PrevValue = int(Last.Value) time.sleep(1) NewBlock = PrevValue + 1 LatestBlock = blockexplorer.get_latest_block() print "start process new block %i %i" % (NewBlock, LatestBlock.height) if LatestBlock.height == NewBlock or LatestBlock.height < NewBlock: print "there is uncofirmed block do nothing" sys.exit(0) # try: for Block in blockexplorer.get_block_height(NewBlock): for Trans in Block.transactions: for output in Trans.outputs: if OwnAccounts.has_key(output.address): if is_out(Trans.inputs, OwnAccounts): break else: Decimal = sato2Dec(output.value) try: TransObj = CryptoTransfers.objects.get(crypto_txid=Trans.hash) print "trans %s is existed to %s amnt %s %i" % ( TransObj.crypto_txid, TransObj.user.username, TransObj.amnt, TransObj.id) except CryptoTransfers.DoesNotExist: print "trans %s to save %s amnt %s" % (Trans.hash, output.address, Decimal) TransObj = CryptoTransfers(crypto_txid=Trans.hash, status="processing", amnt=Decimal, currency=CurrencyInstance, account=output.address, user=OwnAccounts[output.address], confirms=0 ) TransObj.sign_record(crypton.settings.CRYPTO_SALT) TransObj.save() Last.Value = NewBlock Last.save()
def compressionLab(encodedFile): fileReceived = encodedFile; byteSize = 4 initLoop = 0 endLoop = byteSize length = len(fileReceived) / byteSize print(length) blockchainCoordinates = [None] * length latestBlockHeight = (blockexplorer.get_latest_block()).height for blockElement in range(latestBlockHeight, 0, -1): blocks = blockexplorer.get_block_height(blockElement) print(blockElement) for element in range(0, length): blockchainCoordinates[element] = turnIntoTransactions(latestBlockHeight, blocks, fileReceived[initLoop:endLoop]) initLoop += byteSize endLoop += byteSize if endLoop >= len(fileReceived): initLoop = 0 endLoop = byteSize
unprocessed_txs.remove(tx_hash) for out in tx.txs_out: address = out.bitcoin_address() if address not in all_addresses: continue account = Account(addr_to_uid[address]) satoshis = out.coin_value satoshis = int(satoshis / (1 + account.tip.get())) # scale for tip account.total_coins.incr(satoshis) node_minutes_d = calc_node_minutes(satoshis, exchange_rate=exchange_rate.get()) account.total_minutes.incr(node_minutes_d) total_nodeminutes.incr(node_minutes_d) nodes_recently_updated.append(account.uid) account.add_msg('Detected payment via txid: %s' % (txid,)) account.add_msg('Increased total paid by %.8f to %.8f (considering tip of %d %%)' % (satoshis / COIN, account.total_coins.get() / COIN, account.tip.get() * 100)) account.add_msg('Increased node life by %d minutes; expiring around %s' % (node_minutes_d, account.get_expiry().isoformat())) if __name__ == '__main__': while True: latest_block = get_latest_block() best_block_hash = latest_block.hash top_height = latest_block.height if best_block_hash == last_block_checked.get(): time.sleep(10) # only do this at most once per block continue logging.info('Latest block: %s' % best_block_hash) check_unprocessed(top_height) last_block_checked.set(best_block_hash) logging.info('Checked: %s' % best_block_hash)
from blockchain import blockexplorer blocklist = [] latest_block = blockexplorer.get_latest_block() block = blockexplorer.get_block(str(latest_block.block_index)) prev_block = block.previous_block for i in [1,4]: blocklist.append(block) block = blockexplorer.get_block(prev_block) prev_block = block.previous_block print(blocklist)
def updateLock(self, num): """ Checks and updates lock if ownernship has changed :return: Result of checking and updating lock ownership """ try: utxo = blockexplorer.get_unspent_outputs(self.public_address) tx_hashes = [str(i.tx_hash) for i in utxo] if any(self.transaction in tx_hashes): return 'Not Updated' else: response = 'go' j = 0 while response == 'go': old_address = blockexplorer.get_address(self.public_address) outputs = old_address.transactions[0].outputs scripts = [str(i.script) for i in outputs] num_inputs = len(old_address.transactions[0].inputs) output_index = self.ProcessTransaction(scripts, True,num_inputs) if output_index is None: output_index = 0 else: output_index = int(output_index) last_trans_output = old_address.transactions[0].outputs[output_index] included_block = old_address.transactions[0].block_height latest_block = blockexplorer.get_latest_block() if (latest_block.height - included_block < 3): if j == 0: return 'Not Updated because of lack of confidence' if j > 0: if trans == str(old_address.transaction[0].hash): return 'Not enough confidence in provided transaction (updated to new address though)' else: return 'Not enough confidence but not in the provided transaction (updated to new address though)' self.public_address = str(last_trans_output.address) self.transaction = str(old_address.transactions[0].hash) try: utxo_2 = blockexplorer.get_unspent_outputs(self.public_address) tx_hashes_2s = [str(i.tx_hash) for i in utxo_2] if any(self.transaction in tx_hashes_2): reponse = 'exit' except blockchain.exceptions.APIException: j = j + 1 f = open('lock.txt','w') f.write(self.transaction) f.write('\n') f.write(self.public_address) f.close() return 'Updated but not with transaction provided' except blockchain.exceptions.APIException: response = 'go' j = 0 while response == 'go': old_address = blockexplorer.get_address(self.public_address) outputs = old_address.transactions[0].outputs scripts = [str(i.script) for i in outputs] num_inputs = len(old_address.transactions[0].inputs) output_index = self.ProcessTransaction(scripts, True,num_inputs) if output_index is None: output_index = 0 else: output_index = int(output_index) last_trans_output = old_address.transactions[0].outputs[output_index] included_block = old_address.transactions[0].block_height latest_block = blockexplorer.get_latest_block() if (latest_block.height - included_block < 3): if j == 0: return 'Not Updated because of lack of confidence' if j > 0: if trans == str(old_address.transaction[0].hash): return 'Not enough confidence in provided transaction (updated to new address though)' else: return 'Not enough confidence but not in the provided transaction (updated to new address though)' self.public_address = str(last_trans_output.address) self.transaction = str(old_address.transactions[0].hash) try: blockexplorer.get_unspent_outputs(self.public_address) reponse = 'exit' except blockchain.exceptions.APIException: j = j + 1 f = open('lock.txt','w') f.write(self.transaction) f.write('\n') f.write(self.public_address) f.close() return 'Updated but not with transaction provided'
#!/usr/bin/env python # import blockchain library from blockchain import blockexplorer # get a particular block block = blockexplorer.get_block('0000000000000000002e90b284607359f3415647626447643b9b880ee00e41fa') print("Block Fee: %s\n" % block.fee) print("Block size: %s\n" % block.size) print("Block transactions: %s\n" % block.transactions) # get the latest block block = blockexplorer.get_latest_block()
from os.path import basename import sys import datetime from blockchain.blockexplorer import get_latest_block if __name__ == "__main__": try: number_of_raffles = int(sys.argv[1]) except: print('Wrong arguments!') print('Usage: {} number_of_raffles'.format(sys.argv[0])) exit(1) block = get_latest_block() print('Block Time:') print(datetime.datetime.fromtimestamp(block.time)) print('') hash_str = block.hash print('Hash (hex): {}'.format(hash_str)) hash_int = int(block.hash, 16) print('Hash (int): {}'.format(hash_int)) hash_mod = hash_int%number_of_raffles print('Result (hash%{}): {}'.format(number_of_raffles, hash_mod))
def get_latest_block(): """ Return the latest block in the blockchain. """ latest_block_index = blockexplorer.get_latest_block(api_code = API_CODE).block_index return blockexplorer.get_block(str(latest_block_index), api_code = API_CODE)