<s> import os <EOL> import time <EOL> import threading <EOL> from datetime import datetime <EOL> from RandomIO import RandomIO <EOL> from . exc import DownstreamError <EOL> class DownstreamContract ( object ) : <EOL> def __init__ ( self , <EOL> client , <EOL> hash , <EOL> seed , <EOL> size , <EOL> challenge , <EOL> expiration , <EOL> tag , <EOL> manager , <EOL> chunk_dir , <EOL> spoof = False ) : <EOL> self . hash = hash <EOL> self . seed = seed <EOL> self . size = size <EOL> self . challenge = challenge <EOL> self . expiration = expiration <EOL> self . estimated_interval = expiration - datetime . utcnow ( ) <EOL> self . tag = tag <EOL> self . client = client <EOL> self . answered = False <EOL> self . thread_manager = manager <EOL> self . path = os . path . join ( chunk_dir , str ( self . hash ) ) <EOL> self . data_initialized = False <EOL> self . chunk_generation_rate = <NUM_LIT:0> <EOL> self . proof_data = None <EOL> self . file_lock = threading . Lock ( ) <EOL> self . spoof = spoof <EOL> def __repr__ ( self ) : <EOL> return str ( self . hash ) <EOL> def generate_data ( self ) : <EOL> start = time . clock ( ) <EOL> if ( not self . spoof ) : <EOL> RandomIO ( self . seed ) . genfile ( self . size , self . path ) <EOL> stop = time . clock ( ) <EOL> if ( stop - start > <NUM_LIT:0> ) : <EOL> self . chunk_generation_rate = float ( self . size ) / float ( stop - start ) <EOL> self . data_initialized = True <EOL> def cleanup_data ( self ) : <EOL> with self . file_lock : <EOL> if ( os . path . isfile ( self . path ) and not self . spoof ) : <EOL> os . remove ( self . path ) <EOL> self . data_initialized = False <EOL> def update_proof ( self ) : <EOL> """<STR_LIT>""" <EOL> self . proof_data = self . get_proof ( ) <EOL> if ( self . proof_data is not None ) : <EOL> return True <EOL> else : <EOL> return False <EOL> def get_proof ( self ) : <EOL> """<STR_LIT>""" <EOL> if ( self . answered ) : <EOL> return None <EOL> try : <EOL> if ( self . spoof ) : <EOL> proof = self . client . heartbeat . prove ( <EOL> RandomIO ( self . seed , self . size ) , <EOL> self . challenge , <EOL> self . tag ) <EOL> else : <EOL> with self . file_lock , open ( self . path , '<STR_LIT:rb>' ) as f : <EOL> proof = self . client . heartbeat . prove ( <EOL> f , <EOL> self . challenge , <EOL> self . tag ) <EOL> except IOError : <EOL> raise DownstreamError ( '<STR_LIT>' ) <EOL> data = dict ( file_hash = self . hash , <EOL> proof = proof . todict ( ) ) <EOL> return data </s>
