Example #1
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.game.pop += 1
     self.generation = 0
     self.net = Network([[Node()
                          for _ in range(5)], [Node() for _ in range(5)]],
                        4)
     self.bomb_time = 0
     self.energy = 300
Example #2
0
 def build(self, genome):
     #Add all nodes from the genome to the network
     for n_gene in genome.getNgenes():
         self.nodes.append(
             Node(n_gene.getId(), n_gene.getMethod(), 'hidden'))
     #Sort execution order based on topologies.
     self.nodes.sort(key=lambda n: n.getId())
     #Add all axons
     for gene in genome.getCgenes():
         if gene.getEnabled():
             self.getNode(gene.getOut()).addParent(
                 self.getNode(gene.getIn()), gene.getWeight())
    def _create_nodes(self, parse_services=False, node_file=None):
        service_map = {}

        if parse_services:
            if not node_file:
                print 'Node file is not set'
            else:
                nodes = parse_objects(node_file, Node)
                for n in nodes:
                    service_map[int(n.node_id)] = [x.name for x in n.get_services()]

        for node_id, node_data in self.graph.node.iteritems():
            lat = node_data.get('Latitude', 0.)
            lon = node_data.get('Longitude', 0.)
            new_node = Node(node_id=int(node_id), lat=lat, lon=lon,
                            services_names=service_map.get(int(node_id), None)
                            )
            self.nodes[new_node.node_id] = new_node
    def getContainedNodes(self):
        '''
        Take the coordinates of the box corners, then go through the nodes file, passing the node coordinates to inBox function which checks if the node is in the box, thus appending it to the nodes attribute. If there are no contained nodes in the box, the alpha level is set to transparent grey
        '''
        self.getCornerCoords()
        with open('./resources/MapData/nodes.dat', 'r') as nodeFile:
            line = True
            while line:
                line = nodeFile.readline()
                if len(line.strip()) < 1:
                    break
                details = line.strip().split(',')
                node = Node(float(details[0]), float(details[1]), details[2])
                #print(node))
                if self.inBox(node.x, node.y):
                    self.nodes.append(node)

        if not self.nodes:
            self.alpha = random.randint(20, 70)
            self.colour = (99, 88, 88)
Example #5
0
async def collator(network, address, smc_handler):
    if address not in smc_handler.collator_pool:
        raise ValueError(
            "Collator pool in SMC does not contain the given address")
    # collation_tasks_and_periods = []  # [(coroutine, period), ...]
    collation_tasks = {}

    while True:
        # remove finished tasks
        collation_tasks = {(shard_id, period): task
                           for (shard_id,
                                period), task in collation_tasks.items()
                           if not task.done()}

        # when a new period starts, check if we're eligible for some shard and if so start to
        # collate
        for (shard_id, period) in smc_handler.get_eligible_periods(address):
            if (shard_id, period) in collation_tasks:
                continue  # collation coro already running
            logger.info(
                "Detected eligibility of collator {} for period {} in shard {}"
                .format(
                    address,
                    period,
                    shard_id,
                ))

            message_queue = asyncio.Queue()
            node_id = address + '_' + str(period)
            node = Node(network, node_id, message_queue=message_queue)
            network.login(node)
            # TODO: disconnection
            broadcast_task = asyncio.ensure_future(broadcast(network, node_id))
            network.add_peers(node, message_queue, num_peers=4)

            collate_task = asyncio.ensure_future(
                collate(network, shard_id, period, address, smc_handler,
                        node_id))
            collation_tasks[shard_id, period] = collate_task

        await smc_handler.wait_for_next_period()
Example #6
0
    def from_json(cls, data):
        try:
            o = json.loads(data)
        except json.decoder.JSONDecodeError as e:
            raise cls.InvalidBallotMessageError(e)

        if 'type_name' not in o or o['type_name'] != 'ballot-message':
            raise cls.InvalidBallotMessageError(
                '`type_name` is not "ballot-message"')

        message = None
        try:
            message = Message.from_dict(o)
        except Message.InvalidMessageError as e:
            raise cls.InvalidBallotMessageError(e)

        return cls(
            Node(o['node'], None, None),
            State.from_name(o['state']),
            message,
            BallotVoteResult.from_name(o['result']),
        )
    reactor.run(installSignalHandlers=0)


"""
Main - the entry point
"""
if __name__ == '__main__':
    # setting defaults
    log.set_level(logging.DEBUG)  # log level at INFO
    nodes = 4  # number of validator nodes in the same quorum
    trs = 80  # check threshold

    client_config = NodeConfig('client', None, None, None)
    client_node = Node(
        client_config.name,
        client_config.endpoint,
        None,
        client_config.port,
    )
    log.main.debug('client node created: %s', client_node)

    node_name_port_mapping = dict()
    nodes_config = dict()
    for i in range(nodes):
        name = 'n%d' % i
        port = 3000 + i
        endpoint = 'sock://127.0.0.1:%d' % port
        nodes_config[name] = NodeConfig(name, endpoint, port, trs)
        node_name_port_mapping[port] = name

    quorums = dict()
    for name, config in nodes_config.items():
Example #8
0
from flask import Flask, jsonify, request

from blockchain import Blockchain, _index, _transactions, _proof, _previous_hash
from network import Node

app = Flask(__name__)  # Instantiates a node

node = Node()
node_identifier = node.get_node_indentifier(
)  # create a globally unique address for this node

blockchain = Blockchain()  # instantiate a blockchain class


@app.route('/')  # create an endpoint for Welcome: A Simple Blockchain
def home():
    return "Welcome: A Simple Blockchain!"


@app.route('/chain',
           methods=['GET'])  # Create an endpoint /chain with GET method
def get_chain():
    response = {
        'chain': blockchain.chain,
        'length of chain': len(blockchain.chain),
    }
    return jsonify(response), 200


@app.route('/transactions/new', methods=['POST']
           )  # Create an endpoint /transactions/new with POST method
Example #9
0
                logger.info("Header #{} collated by {}: {}".format(
                    number, collator, header))

    # plot_shard(smc_handler.shards[0])


collator_pool = ['collator_{}'.format(i) for i in range(5)]
proposer_pool = ['proposer_{}'.format(i) for i in range(10)]

main_chain = MainChain()
smc_handler = SMCHandler(main_chain, 2, 5, collator_pool)

network = Network()

# Set the p2p connections between proposers
nodes = [Node(network, address) for address in proposer_pool]
network.nodes = nodes
network.generate_peers()

general_coros = [
    main_chain.run(),
    smc_handler.run(),
    stop(),
]

collator_coros = [
    collator(network, address, smc_handler) for address in collator_pool
]

proposer_coros = [
    proposer(network, 0, address, smc_handler)
Example #10
0
    for account in accounts:
        node_id = 0
        for server in servers:
            if str(account) == str(server.node.pub_key.to_string()):
                node_id = server.node.node_id
        print("Node {} has a balance of {} Coins".format(
            node_id, accounts[account]))
    print("=====================================================")


if __name__ == '__main__':
    listOfConfigs = ['node1.txt', 'node2.txt', 'node3.txt', 'node4.txt', \
  'node5.txt', 'node6.txt', 'node7.txt', 'node8.txt', 'node9.txt', 'node10.txt']
    servers = []
    for conf in listOfConfigs:
        node = Node(conf)
        server = Server(node)
        servers.append(server)
        server.start()

    for i in range(2):
        time.sleep(5)
        randomIndex = random.randint(0, len(servers) - 1)
        createRewardTransaction(servers[randomIndex].node)
        randomIndex = random.randint(0, len(servers) - 1)
        servers[randomIndex].node.sendBlock()
        time.sleep(12)
        print(
            "Blockchain Summaries\n====================================================="
        )
        for server in servers:
Example #11
0
 def node_mutation(self):
     con = self.network.connections[math.floor(
         len(self.network.connections) * random())]
     self.network.insert_node(Node(self.neat.node_counter), con)
Example #12
0
from network import Node, Network


def simulate_transactions(node1, node2, num=3):
    """ simulating nodes using the tokens """
    print('simulating {} transactions'.format(num))
    return [
        node1.make_transaction(node2, float(np.random.randint(10)))
        for _ in range(num)
    ]


if __name__ == '__main__':
    OVERDRAFT_LIMIT = -10

    net = Network([Node('node'), Node('other')],
                  overdraft_limit=OVERDRAFT_LIMIT)

    balances = defaultdict(int)
    for _ in range(3):
        #  simulate a few transactions between nodes
        new_transactions = simulate_transactions(net[0], net[1])

        #  check the transactions are valid
        balances, transactions = net.validate_transactions(
            balances, new_transactions)

        new_proof = net.proof_of_work()
        #  randomly select a miner
        miner = net[np.random.randint(len(net))]