Author

Topic: Last Block Hash (Read 433 times)

full member
Activity: 123
Merit: 100
September 12, 2013, 05:50:28 PM
#1
Recently I have started a deep dive into the Bitcoin Armory code base, and writing my own scripts to do some of the basics.

I often come here to get questions answered, so here is one script I created as a small token of my appreciation... and to get off the newbies list.

If you want to know if your block files are up to date just run the script below and compare the hash to blockchain.info.

It uses a few things from the Bitcoin Armory so get the latest source and drop this into the same directory as armoryengine.py

Code:
import sys
sys.argv.append('--nologging')
sys.argv.append('--offline')
from armoryengine import BTC_HOME_DIR, binary_to_int, LITTLEENDIAN, sha256, \
   binary_to_hex, BIGENDIAN, ARMORY_HOME_DIR
import hashlib
import os

BLOCK_SIZE_LENGTH = 4
MAGIC_NUMBER_LENGTH = 4
HEADER_LENGTH = 80

def getLastBlockFile():
   # the current last block file number
   i = 80
   blkFilePath = os.path.join(BTC_HOME_DIR, 'blocks', 'blk%05d.dat' % i)
   lastFile = None
   while True:
      try:
         with open(blkFilePath, 'rb') as f:
            lastFile = blkFilePath
      except IOError:
         break
      i += 1
      blkFilePath = os.path.join(BTC_HOME_DIR, 'blocks', 'blk%05d.dat' % i)
   return lastFile

def getFileSize(f):
   pos = f.tell()
   # Go to the end to get the file length
   f.seek(0,2)
   result = f.tell()
   f.seek(pos)
   return result


def getNextBlockHash(f):
   fileOffset = f.tell()
   f.seek(MAGIC_NUMBER_LENGTH, 1)
   blkSize = binary_to_int(f.read(BLOCK_SIZE_LENGTH), LITTLEENDIAN)
   result = None
   if blkSize > 0:
      blkString = f.read(blkSize)
      blkHdrBinary = blkString[:HEADER_LENGTH]
      result = sha256(sha256(blkHdrBinary))
   else:
      f.seek(0,2)
   return result

def getLastBlockHash(blkFile):
   result = None
   with open(blkFile, 'rb') as f:
      fSize = getFileSize(f)
      while f.tell() < fSize:
         blockHash = getNextBlockHash(f)
         if blockHash != None:
            result = blockHash
   return result


lastHashPath = os.path.join(ARMORY_HOME_DIR, 'LastBlockHash.txt')
result = binary_to_hex(getLastBlockHash(getLastBlockFile()), BIGENDIAN)
with open(lastHashPath, 'w') as f:
   f.write(result)
print result

Thanks for all of the help I've received so far.
Jump to: