def check_if_initial_block(file_path, bc): if os.path.exists(os.environ['BCHOC_FILE_PATH']): return True else: initial_block = Block.create_initial_block() # create initial block block_bytes = pack_block( initial_block) #pack the inital block into bytes with open(os.environ['BCHOC_FILE_PATH'], 'wb') as fp: #open a file to store block fp.write(block_bytes) #write the initial block to binary file fp.write( initial_block.data ) # write the block data to file (make sure the string is in bytes) print('Blockchain file not found. Created INITIAL block.') bc.blocks.append(initial_block) return False
def write_to_file(block): with open(os.environ['BCHOC_FILE_PATH'], 'ab') as fp: block_bytes = pack_block(block) fp.write(block_bytes) fp.write(block.data)
block_bytes = pack_block(block) fp.write(block_bytes) fp.write(block.data) #======================================================================================================================================================= if sys.argv[1] == "init": if len(sys.argv) > 2: #make sure we aren't adding extra arguments sys.exit('Invalid Parameters') if os.path.exists( os.environ['BCHOC_FILE_PATH']) == False: # if file doesn't exist initial_block = Block.create_initial_block() # create initial block #printBlock(initial_block) block_bytes = pack_block( initial_block) #pack the inital block into bytes with open(os.environ['BCHOC_FILE_PATH'], 'wb') as fp: #open a file to store block fp.write(block_bytes) #write the initial block to binary file fp.write( initial_block.data ) # write the block data to file (make sure the string is in bytes) print('Blockchain file not found. Created INITIAL block.') else: #no blockchain file , need to create one with initial block with open(os.environ['BCHOC_FILE_PATH'], 'rb') as fp: block_bytes = fp.read(68) #read 68 bytes of struct header initial_block = unpack( block_bytes) #unpack the bytes and return a block object #printBlock(initial_block) print('Blockchain file found with INITIAL block.')