예제 #1
0
def load_keys():
    if wallet.load_keys():
        global blockchain
        blockchain = Blockchain(wallet.public_key, port)
        response = {
            'public_key': wallet.public_key,
            'private_key': wallet.private_key,
            'funds': blockchain.get_balance()
        }
        return jsonify(response), 201
    else:
        response = {
            'message': 'Loading the keys failed.'
        }
        return jsonify(response), 500
예제 #2
0
def get_updated():
    """
    Checks if somebody in the peers has a better blockchain
    :return:
    """
    global blockchain
    best_blockchain = blockchain
    for key, value in neighbors.items():
        node_destination = get_address(value[0], value[1])
        response = requests.get(node_destination + '/blockchain/get')

        if response.status_code == 200:
            peer_blockchain = Blockchain(response.json())

            if peer_blockchain.check_blockchain(
            ) and peer_blockchain.size() > best_blockchain.size():
                best_blockchain = peer_blockchain
예제 #3
0
def post_blockchain():
    global blockchain
    posted_blockchain = json.loads(request.data)
    new_blockchain = Blockchain(posted_blockchain)
    valid_blockchain = new_blockchain.check_blockchain()
    longer_blockchain = new_blockchain.size() > blockchain.size()
    if longer_blockchain and valid_blockchain:
        blockchain = new_blockchain

        return "The blockchain has been updated", 201
    else:
        message = {
            'message':
            'Your blockchain is either invalid or smaller than mine',
            'blockchain': blockchain.to_json()
        }

        print('My blockchain size is now {}'.format(blockchain.size()))

        return jsonify(message), 409
예제 #4
0
    def __init__(self, configFileName):
        """
		Constructor for Node
		@param configFileName - Configuration file for the node

		"""
        self.peers_file = ''
        self.port_recv = 0
        self.sport = 0
        self.ip_addr = ''
        self.name = ''
        self.unSpentTransactions = {}
        self.blockChain = Blockchain()
        index = self.blockChain.getBlock(
            self.blockChain.tailBlockHash).index + 1
        prevHash = self.blockChain.tailBlockHash
        timestamp = datetime.datetime.utcnow().__str__()
        self.currBlock = Block(index, prevHash, timestamp)

        self.priv_key = SigningKey.generate(curve=NIST384p)
        self.pub_key = self.priv_key.get_verifying_key()

        f = open('nodes/' + configFileName)
        for row in f:
            line = row.split('=')
            if (line[0] == 'listeningPort'):
                self.port_recv = int(line[1].rstrip('\n'))
            if (line[0] == 'node_ip'):
                self.ip_addr = line[1].rstrip('\n')
            if (line[0] == 'node_id'):
                self.node_id = line[1].rstrip('\n')
            if (line[0] == 'node_name'):
                self.name = line[1].rstrip('\n')
            if (line[0] == 'neighbors'):
                self.peers_file = line[1].rstrip('\n')
        f.close()
        self.peer_list = self.peer_info()
예제 #5
0
import sys
from models.wallet import Wallet

app = Flask(__name__)
"""
This file represents one node in the P2P network.
Has 5 attributes:
:param blockchain - Blockchain object, which represents the current blockchain.
:param miner - Miner object, which helps the models mine if it wants.
:param neighbors - all the neighbors the models share its infromation to the in the P2P network.
:param address - the address the models is running on.
:param the port the models is running on.
"""

id = None
blockchain = Blockchain()
miner = None
neighbors = None
connector = ('127.0.0.1', '5000')
wallet = None
ip_address = None
port = None


@app.route('/peers', methods=['POST'])
def add_neighbor():
    """
    Adds a new neighbor to the current peer.
    :return:
    """
    global neighbors
예제 #6
0
class Node:
    def __init__(self, configFileName):
        """
		Constructor for Node
		@param configFileName - Configuration file for the node

		"""
        self.peers_file = ''
        self.port_recv = 0
        self.sport = 0
        self.ip_addr = ''
        self.name = ''
        self.unSpentTransactions = {}
        self.blockChain = Blockchain()
        index = self.blockChain.getBlock(
            self.blockChain.tailBlockHash).index + 1
        prevHash = self.blockChain.tailBlockHash
        timestamp = datetime.datetime.utcnow().__str__()
        self.currBlock = Block(index, prevHash, timestamp)

        self.priv_key = SigningKey.generate(curve=NIST384p)
        self.pub_key = self.priv_key.get_verifying_key()

        f = open('nodes/' + configFileName)
        for row in f:
            line = row.split('=')
            if (line[0] == 'listeningPort'):
                self.port_recv = int(line[1].rstrip('\n'))
            if (line[0] == 'node_ip'):
                self.ip_addr = line[1].rstrip('\n')
            if (line[0] == 'node_id'):
                self.node_id = line[1].rstrip('\n')
            if (line[0] == 'node_name'):
                self.name = line[1].rstrip('\n')
            if (line[0] == 'neighbors'):
                self.peers_file = line[1].rstrip('\n')
        f.close()
        self.peer_list = self.peer_info()

    def peer_info(self):
        """
		Reads info about its peers
		@return peers - list of neighbors
		"""
        f = open('peers/' + self.peers_file)
        peers = []
        header = True
        for neighbor in f:
            if header:
                header = False
            else:
                v = neighbor.split(',')
                if v[0] != self.node_id:
                    peer = Peer(v[0], v[1], v[2], v[3])
                    peers.append(peer)
        f.close()
        return peers

    def get_ip_addr(self):
        """
		Get the node's IP
		@retun ip_addr 
		"""
        return self.ip_addr

    def get_name(self):
        """
		Get the node's name
		@retun name
		"""
        return self.name

    def get_id(self):
        """
		Get the node's id
		@retun node_id
		"""
        return self.node_id

    def get_peer_list(self):
        """
		Get the node's peer list
		@retun peer_list 
		"""
        return self.peer_list

    def sendTransaction(self, transaction):
        """
		Sends transaction
		@param transaction - Transaction object
		"""
        inputs = transaction.inputs
        for input in inputs:
            if input.hash != 'BLOCK-REWARD':
                transaction_i = self.unSpentTransactions[input.hash]
                transaction_i.outputs[input.index] = None
                self.unSpentTransactions[input.hash] = transaction_i
        self.unSpentTransactions[transaction.hash] = transaction
        for peer in self.get_peer_list():
            self.sendData((3, transaction), peer)

    def signData(self, data):
        return self.priv_key.sign(data)

    def sendBlock(self):
        print("Block {} being sent...".format(self.currBlock.currHash))
        for peer in self.get_peer_list():
            self.sendData((4, self.currBlock), peer)
        self.blockChain.addBlock(self.currBlock, self.unSpentTransactions)
        self.currBlock = Block(self.currBlock.index + 1,
                               self.currBlock.currHash,
                               datetime.datetime.utcnow().__str__())

    def sendData(self, data, recv):
        """
		@param data - compsed of messageType and payload
		@param recv - node that recives the data
		"""
        print("sending data:", data, "To:", recv.name, "IP:", recv.ip_addr,
              "Port:", recv.port_recv, "From:", self.name, "IP:", self.ip_addr)
        time.sleep(1)
        s = socket(AF_INET, SOCK_STREAM)
        s.connect((recv.ip_addr, int(recv.port_recv)))
        s.send(pickle.dumps(data))
        s.close()
예제 #7
0
from flask import Flask, jsonify, request, json, redirect
from requests import Request
from uuid import uuid4
from textwrap import dedent
from models.blockchain import Blockchain

# Instantiate the server --> will move this out of this file at some point
app = Flask(__name__)

# Create a globally unique address or this node
node_identifier = str(uuid4()).replace('-', '')

# Instantiate the Blockchain
blockchain = Blockchain()


@app.route('/mine', methods=['POST'])
def mine():

    request_data = request.get_json()
    required = ['musician_id', 'user_id']

    print(request_data['user_id'] + ' is listening to ' +
          request_data['musician_id'] +
          '. 25% of this BlockNote attributed to ' + request_data['user_id'] +
          ', 50% to ' + request_data['musician_id'])

    if not all(k in request_data for k in required):
        return 'Missing Necessary Data in Request', 400

    last_block = blockchain.last_block
예제 #8
0
        return response, status_codes["CLIENT_ERROR"]
    node = node_details["node"]
    blockchain.add_peer_node(node)
    response = {
        "Message": "Node added successfully.",
        "Nodes": list(blockchain.get_peer_nodes()),
    }
    return jsonify(response), status_codes["CREATED"]


@server.route("/node/<node_url>", methods=["DELETE"])
def remove_node(node_url):
    if node_url == "" or node_url == None:
        response = {"Message": "Invalid node url"}
        return jsonify(response), status_codes["CLIENT_ERROR"]
    blockchain.remove_peer_node(node_url)
    response = {
        "Message": "Node removed successfully",
        "Nodes": list(blockchain.get_peer_nodes()),
    }
    return jsonify(response), status_codes["SUCCESS"]


if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("-p", "--port", type=int, default=8000)
    args = parser.parse_args()
    port = args.port
    wallet = Wallet(node=port)
    blockchain = Blockchain(wallet.public_key + '-' + str(port))
    server.run(host=host, port=port)
예제 #9
0
    blockchain.remove_peer_node(node_url)
    response = {
        'message': 'Node removed',
        'all_node': blockchain.get_peer_nodes()
    }
    return jsonify(response), 200


@app.route('/nodes', methods=['GET'])
def get_node():
    nodes = blockchain.get_peer_nodes()
    response = {
        'all_nodes': nodes
    }
    return jsonify(response), 200


if __name__ == '__main__':
    '''User can pass the port args in order to run app on different server'''
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('-p', '--port', type=int, default=5003)
    args = parser.parse_args()
    port = args.port

    wallet = Wallet(port)
    blockchain = Blockchain(wallet.public_key, port)

    # run() take 2 args, IP and port
    app.run(host='0.0.0.0', port=port, debug=True)