Exemplo n.º 1
0
def receive_transaction():
    values = request.get_json()
    required = [
        'sender', 'recipient', 'amount', 'timestamp', 'inputs', 'outputs',
        'id', 'signature'
    ]
    if not all(k in values for k in required):

        return 'Missing values', 400

    trans_obj = utilities.asObject(values, "transaction")

    retValue = trans_obj.verify_signature()
    if not retValue:
        return "Invalid signature", 201

    retValue = trans_obj.validate_transaction()
    if not retValue:
        return "Invalid transaction", 201

    with data.lock:
        data.current_transactions[trans_obj.id] = trans_obj
        if len(data.current_transactions) >= data.capacity:
            mining.mine()

        with data.chainLock:  #πρεπει να ανανεωσουμε τα δεδομενα για το chain endpoint
            data.current_transactionsForCons = copy.deepcopy(
                data.current_transactions)
            data.utxosForCons = copy.deepcopy(data.utxos)

    return "transaction received", 200
Exemplo n.º 2
0
 def test_mining(self):
     bch = block.Blockchain()
     bch.new_block([my_keys[1], my_keys[1], your_pub_key])
     bch.new_transaction(my_keys[1], [(0, 0)], [your_pub_key, my_keys[1]],
                         [0.5, 0.25], 'signing', my_keys[0])
     bch.new_transaction(my_keys[1], [(0, 0)], [your_pub_key, my_keys[1]],
                         [0.05, 0.95], 'signing', my_keys[0])
     bch.new_transaction(my_keys[1], [(0, 0)], ['mining', my_keys[1]],
                         [0.05, 0.95], 'signing', my_keys[0])
     bch.new_transaction(my_keys[1], [(0, 0)], ['mining', my_keys[1]],
                         [0.05, 0.95], 'signing', my_keys[0])
     bch.new_transaction(my_keys[1], [(0, 0)], ['mining', my_keys[1]],
                         [0.05, 0.95], 'signing', my_keys[0])
     n = 1000
     xs = mining.poc_mine(n, bch, my_keys[1])
     bch.add_miner([n, my_keys[1], xs], 'poc')
     bch.add_miner([n, my_keys[1], xs], 'poc')
     bch.add_miner([n, my_keys[1], xs], 'poc')
     n, t, h = mining.pow_mine(bch, 90000000000000000000000000000000000,
                               my_keys[1])
     bch.add_miner([int(h), n, my_keys[1], t], 'pow')
     bch.add_miner([int(h), n, my_keys[1], t], 'pow')
     bch.add_miner([int(h), n, my_keys[1], t], 'pow')
     bl = block.Block(n, [my_keys[1]], bch, [], [], t)
     b = mining.mine(bch)
     bch.append(b)
     print('n', bch[-1].n)
     self.assertTrue(mining.validate(bch, -1))
Exemplo n.º 3
0
def mine_request():
    block = mine(blockchain, node_identifier)

    if block is False:
        response = {'message': "Block added by the network"}
    else:
        response = {
            'message': "New Block Forged",
            'index': block['index'],
            'transactions': block['transactions'],
            'proof': block['proof'],
            'previous_hash': block['previous_hash'],
        }

    return jsonify(response), 200
Exemplo n.º 4
0
def mine():
    # demo block
    blocks = syncBlocks()
    demo_block = Block(len(blocks), 'temporary data', None, blocks[-1]['hash'],
                       str(date.datetime.now())).block
    hashString = str(demo_block['index']) + demo_block['data'] + str(
        demo_block['previousHash']) + str(demo_block['timestamp'])
    start_time = time()
    nonce, hash = mining.mine(hashString, 5)
    stop_time = time()
    print(stop_time - start_time)
    demo_block['nonce'] = nonce
    demo_block['hash'] = hash
    saveBlock(demo_block, 5)
    # broadcast to all
    syncremote.broadcastBlock(demo_block)
    return "Mined a new block"
Exemplo n.º 5
0
def test():
    # print(mine())
    # return "HELLO"
    return jsonify({'data': mine()})
Exemplo n.º 6
0
 def act(self):
     if bch[-1].is_full:
         bch.append(mining.mine(bch))
Exemplo n.º 7
0
def receive_a_block():
    values = request.get_json()

    required = [
        'index', 'transactions', 'timestamp', 'nonce', 'previous_hash',
        'current_hash'
    ]
    if not all(k in values for k in required):
        return 'Missing values', 400

    my_block = utilities.asObject(values, 'block')
    if len(data.blockchain.chain) == 0:
        with data.lock:
            for transaction in my_block.transactions:  # πρεπει να κανουμε validate το genesis transaction
                transaction.validate_transaction()
            data.blockchain.chain.append(my_block)

            with data.chainLock:  #πρεπει να ανανεωσουμε τα δεδομενα για το chain endpoint
                data.blockchainForCons = copy.deepcopy(data.blockchain)
                data.current_transactionsForCons = copy.deepcopy(
                    data.current_transactions)
                data.utxosForCons = copy.deepcopy(data.utxos)

        return "GenesisBlock added", 200

    # to hash einai ypologismeno swsta
    if my_block.hash() != my_block.current_hash:
        return "Wrong Hash", 400

    # to hash exei thn swsth morfh
    if mining.valid_proof(my_block) == False:
        return "Invalid proof", 401

    #1h to hash einai idio me to prohgoymeno hash, shmainei pws oi alysides symfvnoyn
    with data.lock:
        if my_block.previous_hash == (data.blockchain.chain[-1]).current_hash:

            for transaction in my_block.transactions:
                tran_id = transaction.id
                #if tran_id in data.transaction_pool:
                #return "Transaction already in block",402
                for bl in data.blockchain.chain:  # διατρεχουμε ολο το chain
                    for tr in bl.transactions:
                        if tr.id == tran_id:
                            if len(
                                    data.current_transactions
                            ) >= data.capacity:  #ισως ηρθαν στην ουρα πολλα ακομα transactions
                                mining.mine()
                            return "Transaction already in block", 402

                if not (tran_id in data.current_transactions):
                    if len(
                            data.current_transactions
                    ) >= data.capacity:  #ισως ηρθαν στην ουρα πολλα ακομα transactions
                        mining.mine()
                    return "Unheard transaction in new  block", 402
            #afairoyme osa exoyme koina sto current_transactions
            for trans in my_block.transactions:
                tran_id = trans.id
                data.current_transactions.pop(tran_id)
                #data.transaction_pool.append(trans.id)

            data.blockchain.chain.append(my_block)

            #for transId in utilities.getListOfKeys(data.current_transactions):
            #if transId in data.transaction_pool:
            #data.current_transactions.pop(transId)

            if len(
                    data.current_transactions
            ) >= data.capacity:  #ισως ηρθαν στην ουρα πολλα ακομα transactions
                mining.mine()

            with data.chainLock:  #πρεπει να ανανεωσουμε τα δεδομενα για το chain endpoint
                data.blockchainForCons = copy.deepcopy(data.blockchain)
                data.current_transactionsForCons = copy.deepcopy(
                    data.current_transactions)
                data.utxosForCons = copy.deepcopy(data.utxos)
                #data.transactionPoolForCons=copy.deepcopy(data.transaction_pool)
            return "Block added", 200
            #data.utxos_copy=data.utxos[:]

    #2h to hash yparxei pio ba8eia sthn oyra
        for temp_blocks in reversed(data.blockchain.chain):
            if my_block.previous_hash == temp_blocks.current_hash:
                if len(
                        data.current_transactions
                ) >= data.capacity:  #ισως ηρθαν στην ουρα πολλα ακομα transactions
                    mining.mine()
                #den kanoyme kati to aporriptoyme
                return "My chain is  not shorter,block rejected", 403

    #3h to previous hash den yparxei mesa sthn lista mas
    #consensus
        print("I will call consensus Now")
        consensus_result = utilities.consensus()

        for transId in utilities.getListOfKeys(data.current_transactions):
            if transId in data.transaction_pool:
                data.current_transactions.pop(transId)

        with data.chainLock:  #πρεπει να ανανεωσουμε τα δεδομενα για το chain endpoint
            data.blockchainForCons = copy.deepcopy(data.blockchain)
            data.current_transactionsForCons = copy.deepcopy(
                data.current_transactions)
            data.utxosForCons = copy.deepcopy(data.utxos)
            #data.transactionPoolForCons=copy.deepcopy(data.transaction_pool)

        if len(
                data.current_transactions
        ) >= data.capacity:  #ισως ηρθαν στην ουρα πολλα ακομα transactions
            mining.mine()
        return "consensus", consensus_result
Exemplo n.º 8
0
        "cutoff": cutoffRank
    }

    ## create filepaths
    # create genome folder if not already there
    if not os.path.exists(genomeDir):
        print("could not find " + genomeDir + ", attempting to make it")
        os.makedirs(genomeDir)
    # create output database if not already there
    path = databaseDir.split("/")
    databaseFolder = "/".join(path[0:len(path) - 1])
    if not os.path.exists(databaseFolder):
        print("creating database directory " + databaseFolder)
        os.makedirs(databaseFolder)
    if not os.path.exists(databaseDir):
        print("Could not find " + databaseDir + ", attempting to create...")
        Path(databaseDir).touch()

    mine(genomeDir, runName, pattern, cutoffRank, databaseDir, memeDir, motifs)
    print("finished all the runs for " + runName)

except Exception as error:
    print("An error occured while mining")
    traceback.print_tb(sys.exc_info()[2])
    print(str(error))

# Export the information into CSVs
export_to_csv(
    config["runName"], config["database"],
    os.path.join(config["database"][:config["database"].rfind('/')], 'csvs/'))