Beispiel #1
0
def add_block():
    try:
        block_json = request.get_json(force=True)
        block = Block.from_dict(block_json)
        rs = (grequests.post(f'{node["address"]}/validate', data=request.data) for node in json.loads(get_nodes()))
        responses = grequests.map(rs)
        validated_chains = 1
        unvalidated_chains = 0
        total_valids = 2
        total_unvalids = 4
        for response in responses:
            if response.status_code == 201:
                validated_chains += 1
            if validated_chains == total_valids:
                break 
            elif response.status_code == 400:
                unvalidated_chains += 1
                if unvalidated_chains == total_unvalids:
                    break
        if validated_chains == total_valids:
            blockchain.add_block(block)
            announce_new_block(block_json)
            return jsonify({'message': f'Block #{block.index} added to the Blockchain'}), 201
        elif unvalidated_chains == total_unvalids:    
            consensus()
            return jsonify({'message': 'Blockchain was Outdated'}), 400
        else:
            return jsonify({'message': f'Block rejected: {block}'}), 400
    except (KeyError, TypeError, ValueError):
        return jsonify({'message': f'Invalid block format'}), 400
    except BlockchainException as bce:
        return jsonify({'message': f'Block rejected: {block}'}), 400
Beispiel #2
0
def validate_block():
    try:
        block = request.get_json(force=True)
        block = Block.from_dict(block)
        return jsonify({'message': f'Block #{block.index} is a valid block!'}), 201
    except (KeyError, TypeError, ValueError):
        return jsonify({'message': f'Invalid block format'}), 400
    except BlockchainException as bce:
        return jsonify({'message': f'Invalid block: {bce}'}), 400
Beispiel #3
0
def add_block():
    try:
        block = request.get_json(force=True)
        block = Block.from_dict(block)
        blockchain.add_block(block)
        return jsonify(
            {'message': f'Block #{block.index} added to the Blockchain'}), 201
    except (KeyError, TypeError, ValueError):
        return jsonify({'message': f'Invalid block format'}), 400
    except BlockchainException as bce:
        return jsonify({'message': f'Block rejected: {bce}'}), 400
Beispiel #4
0
def add_block():
    try:
        block_json = request.get_json(force=True)
        block = Block.from_dict(block_json)
        rs = (grequests.post(f'{node["address"]}/validate', data=request.data) for node in json.loads(get_nodes()))
        responses = grequests.map(rs)
        validated_chains = 1
        unvalidated_chains = 0
        total_valids = 2
        total_unvalids = 4
        for response in responses:
            if response.status_code == 201:
                validated_chains += 1
            if validated_chains == total_valids:
                break
            elif response.status_code == 400:
                unvalidated_chains += 1
                if unvalidated_chains == total_unvalids:
                    break
Beispiel #5
0
    def minerarBloco(self, address):
        wallet = KeyPair(address)
        r = requests.get('https://uclcriptocoin.herokuapp.com/block/minable/' +
                         wallet.public_key)
        print(r.text)
        last_block = json.loads(r.text)
        block = Block.from_dict(last_block["block"])
        difficulty = last_block["difficulty"]

        while block.current_hash[:difficulty].count('0') < difficulty:
            block.nonce += 1
            block.recalculate_hash()

        data = json.dumps(block, default=lambda x: x.__dict__)

        r = requests.post('https://uclcriptocoin.herokuapp.com/block',
                          data,
                          json=True)
        print(r.text)
Beispiel #6
0
def consensus():
    """
        Our simple consnsus algorithm. If a longer valid chain is
        found, our chain is replaced with it.
        """
    global blockchain
    
    result = False
    current_len = blockchain._blocks.count()
    rs = (grequests.get(f'{node["address"]}/chain') for node in json.loads(get_nodes()))
    responses = grequests.map(rs)
    for response in responses:
        if response != None and response.status_code == 200:
            blocks = response.json()
            if len(blocks) > current_len:
                current_len = len(blocks)
                blockchain.clear()
                for block in blocks:
                    temp_block = Block.from_dict(block)
                    blockchain.add_block(temp_block)
                result = True
Beispiel #7
0
from uclcoin import Block
import requests
import json
from collections import namedtuple

r = requests.get(
    'http://127.0.0.1:5000/block/minable/036b86d828203c1d2f30d689b45fcae5bc700358afafd18012f15121220de17662'
)
last_block = json.loads(r.text)
block = Block.from_dict(last_block["block"])
difficulty = last_block["difficulty"]

while block.current_hash[:difficulty].count('0') < difficulty:
    block.nonce += 1
    block.recalculate_hash()

data = json.dumps(block, default=lambda x: x.__dict__)

r = requests.post('http://127.0.0.1:5000/block', data, json=True)
print(r.text)
Beispiel #8
0
def verify_and_add_block():
    block_data = request.get_json()
    block = Block.from_dict(block_data)
    blockchain.add_block(block)

    return "The block was added", 200
def opcMineracao(chave):

    inicio = fim = block_time = 0
    max_iteration = 10000000
    count_iteration = 0
    res = requests.get(f'{url}/block/minable/{chave}')
    res = res.json()
    dificuldade = res['difficulty']
    block = res['block']
    currentblock = block['index']
    print('Bloco para Mineração Carregado... \nÍndice: ', currentblock)
    block = Block.from_dict(block)
    print('\n... INICIANDO ...\n')

    inicio = time.time()
    while (block.current_hash[:dificuldade].count('0') < dificuldade):
        block.nonce += 1
        block.recalculate_hash()
        count_iteration = count_iteration + 1

        if (count_iteration == max_iteration):
            fim = time.time()
            block_time = int((fim - inicio) / 60)
            addpoint(block_time, balancekey(chave))
            count_iteration = 0
            res = requests.get(f'{url}/block/minable/{chave}')
            res = res.json()
            requestedblock = res['block']
            requestedblock = requestedblock['index']

            try:
                print('...')
            except KeyboardInterrupt:
                return

            if (currentblock != requestedblock):
                block_point = point(currentblock, 'Perda', block_time,
                                    balancekey(chave))
                plotpoint(block_point)
                print('\nBloco Perdido, Iniciando novo Bloco!\n')
                opcMineracao(chave)

    fim = time.time()
    block_time = int((fim - inicio) / 60)
    print('\n   Mineração do Bloco Finalizada!\nTempo Decorrido: ', block_time,
          ' min')
    res = requests.post(f'{url}/block', json=dict(block))

    if res.ok:
        print('\nMineração Aceita pela BlockChain!')
        addpoint(block_time, balancekey(chave))
        block_point = point(currentblock, 'Aceito', block_time,
                            balancekey(chave))
        plotpoint(block_point)

    else:
        print('\nMineração Rejeitada pela BlockChain!')
        addpoint(block_time, balancekey(chave))
        block_point = point(currentblock, 'Rejeitado', block_time,
                            balancekey(chave))
        plotpoint(block_point)
    opcMineracao(chave)