Beispiel #1
0
    def __init__(self, block):
        func = inspect.currentframe().f_back.f_code
        self.connection = sqlite3.connect('blockchain.db',
                                          check_same_thread=False)
        self.cursor = self.connection.cursor()
        self.connection.commit()
        self.__check_delete()
        self.cursor.execute(
            "SELECT hash FROM unverified_blocks WHERE `index`=0")
        unverified_response = self.cursor.fetchone()
        self.cursor.execute("SELECT hash FROM verified_blocks WHERE `index`=0")
        verified_response = self.cursor.fetchone()
        if unverified_response is None and verified_response is None:
            self.add(block)
        else:
            self.cursor.execute("SELECT * FROM unverified_blocks")

            unverified_all = self.cursor.fetchall()
            for db_block_info in unverified_all:
                b = Block()
                b.import_from_database(db_block_info)
                self.add(b, update_db=False)
            self.cursor.execute("SELECT * FROM verified_blocks")
            verified_all = self.cursor.fetchall()
            if verified_all is not None:
                self.__added_to_db += len(verified_all)
                self.__added_to_db += len(unverified_all)
                print("total of {}".format(self.__added_to_db))
            print("Done reloading")
Beispiel #2
0
 def add(self,
         index=-1,
         timemade=-1,
         proof_of_work_input=-1,
         effort=-1,
         transactions=-1,
         previous_hash=-1,
         update_db=True):
     func = inspect.currentframe().f_back.f_code
     block = Block(index, timemade, proof_of_work_input, effort,
                   transactions, previous_hash)
     execute_sql = False
     if self.__root is None:
         execute_sql = True
         self.__root = block
     else:
         found = search.find(self.__root,
                             lambda node: node.hash == previous_hash)
         if found != None:
             block.parent = found
             execute_sql = True
             self.__analyze()
     self.__set_last_added(block)
     if execute_sql and update_db:
         dict_to_use = block.getdict()
         self.cursor.execute(
             "INSERT INTO unverified_blocks VALUES (:index,:timemade,:proof_of_work,:effort,:transactions,:hash,:previous_hash)",
             dict_to_use)
         self.connection.commit()
         self.__added_to_db += 1
     self.__to_store()
Beispiel #3
0
 def __init__(self,
              index=-1,
              timemade=-1,
              proof_of_work_input=-1,
              effort=-1,
              transactions=-1,
              previous_hash=-1):
     func = inspect.currentframe().f_back.f_code
     self.connection = sqlite3.connect('blockchain.db')
     self.cursor = self.connection.cursor()
     self.connection.commit()
     self.__check_delete()
     self.cursor.execute(
         "SELECT hash FROM unverified_blocks WHERE `index`=0")
     response = self.cursor.fetchone()
     if response == None or len(str(response[0])) != 64:
         self.add(index, timemade, proof_of_work_input, effort,
                  transactions, previous_hash)
     else:
         self.cursor.execute("SELECT * FROM unverified_blocks")
         all = self.cursor.fetchall()
         for db_block_info in all:
             b = Block()
             b.import_from_db(db_block_info)
             self.add(b.index,
                      b.timemade,
                      b.proof_of_work,
                      b.effort,
                      b.transactions,
                      b.previous_hash,
                      update_db=False)
Beispiel #4
0
def get_last_block():
    url = "http://" + Variables.MINER_NODE_URL + ":" + str(
        Variables.PORT) + "/lastblock"
    last_block_xml = requests.post(url)
    parsed = xmltodict.parse(last_block_xml.content)
    last_block = Block()
    last_block.import_from_xml(parsed['block'])
    return last_block
Beispiel #5
0
def create_genesis_block():
    func = inspect.currentframe().f_back.f_code
    # logging.info("Creating a genesis block")
    # logging.debug("Work:{}".format(variables.WORK))
    work_ez = int(variables.WORK / 4) + 1
    proof_of_work = "0" * work_ez
    pad = "1337"
    for i in range(4, 64):
        proof_of_work += pad[i % len(pad)]
    while len(proof_of_work) < 64:
        proof_of_work += "1"
    b = Block(0, time.time(), proof_of_work, "e", [], "0")
    b.transactions = [{"from": '0', "to": '0', "amount": '0'}]
    # logging.info("Returning block: {}".format(b))
    return b
Beispiel #6
0
def block():
    global blockchain
    ip = request.remote_addr
    if request.method == 'POST':

        raw = request.data.decode('utf-8')
        print(raw)
        parsed = xmltodict.parse(raw)
        b = Block()
        b.importXml(parsed['block'])
        blockchain.add(b.index, b.timemade, b.proof_of_work, b.effort,
                       b.transactions, b.previous_hash)
    else:
        block_number = str(int(request.args['block_number']))

    return "0\n"
Beispiel #7
0
def block():

    global blockchain
    ip = request.remote_addr
    if ip != "127.0.0.1" and ip not in Variables.PEER_NODES:
        Variables.PEER_NODES.append(ip)
    if ip == '127.0.0.1':
        raw = request.data.decode('utf-8')
        parsed = xmltodict.parse(raw)
        b = Block()
        b.import_from_xml(parsed['block'])
        print("I made", b)
        blockchain.add(b)

        #Distribute the block to our peers

        for peer in Variables.PEER_NODES:
            try:
                url = "http://" + peer + ":" + str(Variables.PORT) + "/block"
                xml = b.export_to_xml()
                headers = {'Content-Type': 'application/xml'}
                resp = requests.post(url, data=xml, headers=headers).text
            except:
                Variables.PEER_NODES.remove(peer)
    else:
        block_number = None

        try:
            block_number = int(request.args['block_number'])
        except:
            pass
        if block_number is not None:
            return blockchain.get(block_number).export_to_xml()
        else:
            raw = request.data.decode('utf-8')
            parsed = xmltodict.parse(raw)
            b = Block()
            b.import_from_xml(parsed['block'])
            print("receiv", b)
            if Utility.validate(b):
                blockchain.add(b)
                global event
                event.set()
            else:
                print("Block did not validate",ip)
    return "0"
Beispiel #8
0
def consensus():
    global blockchain
    max = 0
    max_ip = None
    for ip in Variables.PEER_NODES:
        url = "http://" + ip + ":" + str(Variables.PORT) + "/numblocks"
        numblocks = requests.post(url)
        numblocks = int(numblocks.content.decode('utf-8'))
        if numblocks > max:
            max = numblocks
            max_ip = ip
    for i in range(0,max):
        url = "http://" + max_ip + ":" + str(Variables.PORT) + "/block?block_number={}".format(i)
        block_xml = requests.post(url)
        parsed = xmltodict.parse(block_xml.content)
        block = Block()
        block.import_from_xml(parsed['block'])
        if blockchain is None:
            blockchain = Blockchain(block)
        else:
            blockchain.add(block)
Beispiel #9
0
 def get(self, number):
     self.cursor.execute("SELECT * FROM verified_blocks WHERE `index` = ?",
                         (number, ))
     verified_response = self.cursor.fetchone()
     if verified_response is not None:
         b = Block()
         b.import_from_database(verified_response)
         return b
     self.cursor.execute(
         "SELECT * FROM unverified_blocks WHERE `index` = ?", (number, ))
     unverified_response = self.cursor.fetchone()
     if unverified_response is not None:
         b = Block()
         b.import_from_database(unverified_response)
         return b
Beispiel #10
0
def mine():
    func = inspect.currentframe().f_back.f_code
    logging.info("Starting to mine")
    # See if other blockchains exist
    #TODO add consensus back
    i = 0
    while i < 10:
        url = "http://" + variables.MINER_NODE_URL + ":" + str(
            variables.PORT) + "/lastblock"
        last_block_xml = requests.post(url)
        parsed = xmltodict.parse(last_block_xml.content)
        print(last_block_xml.content.decode('utf-8'))
        last_block = Block()
        last_block.importXml(parsed['block'])
        transactions = {"from": "network", "to": User.public_key, "amount": 1}
        pow_output = proof_of_work(last_block, transactions)
        url = "http://" + variables.MINER_NODE_URL + ":" + str(
            variables.PORT) + "/block"
        xml = pow_output.exportXml()
        headers = {'Content-Type': 'application/xml'}
        requests.post(url, data=xml, headers=headers).text
        sys.exit()
        i += 1
Beispiel #11
0
def proof_of_work(last_block, data):
    index_to_use = last_block.index + 1
    func = inspect.currentframe().f_back.f_code
    logging.info("Starting proof of work")
    done = False
    while not done:
        now = time.time()
        effort, pow_hash_object = Utility.genhash(index_to_use, now, data,
                                                  last_block.hash)
        leading_zeroes = Utility.leadingzeroes(pow_hash_object.digest())
        if leading_zeroes >= variables.WORK:
            done = True
    retBlock = Block(index_to_use, now, pow_hash_object.hexdigest(), effort,
                     data, last_block.hash)
    logging.info("Farmed a block returning: {}".format(retBlock))
    return retBlock
Beispiel #12
0
def proof_of_work(last_block, data):
    global event
    func = inspect.currentframe().f_back.f_code
    done = False
    now = None
    pow_hash_object = None
    effort = None
    while not done:
        if event.is_set():
            print("Exiting block creation")
            return False
        now = time.time()
        index_to_use = last_block.index + 1
        effort, pow_hash_object = Utility.genhash(index_to_use, now, data,
                                                  last_block.hash)
        leading_zeroes = Utility.leadingzeroes(pow_hash_object.digest())
        if leading_zeroes >= Variables.WORK:
            done = True
    return_block = Block(index_to_use, now, pow_hash_object.hexdigest(),
                         effort, data, last_block.hash)
    return return_block
Beispiel #13
0
import User_classes.User as User
import Utilities.Utility as Utility

WORK = 5
genesis = Utility.create_genesis_block()

added = 0

blockchain = Blockchain(genesis)
while added < 100:
    last_block = blockchain.last_added()

    now = time.time()
    data = [{"from": "network", "to": User.public_key, "amount": 1.0}]
    done = False
    block = None
    while not done:
        effort, pow_hash_object = Utility.genhash(last_block.index + 1, now,
                                                  data, last_block.hash)
        #this is a test ....
        leading_zeroes = Utility.leadingzeroes(pow_hash_object.digest())
        if leading_zeroes >= WORK:
            done = True
    added += 1
    b = Block(last_block.index + 1, now, pow_hash_object.hexdigest(), effort,
              data, last_block.hash)
    blockchain.add(b)
    print("farmed", b)

print(str(blockchain))