示例#1
0
def run_lan_node(name=None):
    node_name = name or os.getpid()

    lan = UDPLink('en0', 2010)
    node = Node((lan, ), node_name,
                Program=BlockchainNode)  # Filters=(UniqueFilter,),
    lan.start()
    node.start()
    node.program.setup(node_name)

    subprocess.Popen([NODE_BINARY, name] if name else [NODE_BINARY],
                     stdin=subprocess.PIPE,
                     stdout=sys.stdout,
                     stderr=sys.stderr)

    return node
示例#2
0
    def __init__(self, name, port=5000, blockchain=Blockchain()):
        threading.Thread.__init__(self)

        self.name = name
        self.address = ni.ifaddresses('en0')[ni.AF_INET][0]['addr']

        self.blockchain = blockchain

        self.peer_info = {}
        self.peers = set()

        self.links = [UDPLink('en0', port=port)]
        self.network = NetworkComponent(self.links,
                                        name,
                                        Filters=(DuplicateFilter, ))

        self.keep_listening = True
        self.ready = False
        self.synced = False

        self.heartbeat_thread = threading.Thread(target=self.send_heartbeat)

        # Start Network Component
        [link.start() for link in self.links]
        self.network.start()
        self.heartbeat_thread.start()
        self.start()
示例#3
0
class NodeProgram(BaseProgram):
    def recv(self, packet, interface):
        print("\n\n[USER] Received packet on interface: "+str(interface))
        s = packet.decode()
        print('\n[USER] Received message>> {}'.format(s))


##--------------------------------------------------------------------##
##                        MAIN
## Se genera una red mesh virtual previamente negociada
##--------------------------------------------------------------------##

if __name__ == "__main__":
    links = (VirtualLink('vl1'),VirtualLink('vl2'))
    nodes = (
         Node([links[0]], 'QRReceptor', mac_addr='5D-A2-A5-51-96-4E',Filters=(UniqueFilter,), Program=NodeProgram),
         Node([links[0]], 'UserNode3', mac_addr='2A-B5-87-59-96-4E', Filters=(UniqueFilter,), Program=NodeProgram)
    )
    [l.start() for l in links]
    [n.start() for n in nodes]

    try:
        #Open QR reader
        DL = DispositivoLector()
        while True:
            if(len(DL.lista) > 0):
                print("HAY DATOS")
            #message = input("Type a message: ")
            #nodes[0].send(bytes(message, 'UTF-8',))
            time.sleep(0.3)
示例#4
0
    real_link = ask(bool, "Link to local networks?        [y]/n:", True)

    print('Reaching Out')
    links = []
    if real_link:
        links += [
            UDPLink('en0', port),
            UDPLink('en1', port + 1),
            UDPLink('en2', port + 2)
        ]
    links += [VirtualLink("vl%s" % (x + 1)) for x in range(num_links)]

    print('Establishing connection')
    nodes = [
        Node(None,
             "n%s" % x,
             Filters=[UniqueFilter],
             Program=random.choice((Printer, Switch)))
        for x in range(num_nodes)
    ]

    print("You are now a part of something bigger")
    [link.start() for link in links]
    for node in nodes:
        node.start()
        print("%s:%s" % (node, node.interfaces))

    gpsp = GpsPoller()
    gpsp.start()
    command = "admin"
    if command[:1] == "l":
        link = [l for l in links if l.name[1:] == command[1:]]
示例#5
0
# -*- coding: utf-8 -*-
# MIT License: Nick Sweeting
import time

from mesh.links import UDPLink
from mesh.programs import Printer
from mesh.filters import UniqueFilter
from mesh.node import Node

links = [
    UDPLink('en0', 2010),
    UDPLink('en1', 2011),
    UDPLink('en2', 2012),
    UDPLink('en3', 2013)
]
node = Node(links, 'me', Filters=(UniqueFilter, ), Program=Printer)
[link.start() for link in links]
node.start()

if __name__ == "__main__":
    print(
        "Run lan-chat.py on another laptop to talk between the two of you on en0."
    )
    try:
        while True:
            print("------------------------------")
            message = input("[me]  OUT:".ljust(49))
            node.send(bytes(message, 'UTF-8'))
            time.sleep(0.3)

    except (EOFError, KeyboardInterrupt):  # CTRL-D, CTRL-C
    print('Creating Links...')
    links = []
    if real_link:
        links += [
            UDPLink('en0', port),
            UDPLink('en1', port + 1),
            UDPLink('en2', port + 2)
        ]
    if irc_link:
        links += [IRCLink('irc0')]
    links += [VirtualLink("vl%s" % (x + 1)) for x in range(num_links)]

    print('Creating Nodes...')
    nodes = [
        Node(None,
             "n%s" % x,
             Filters=[UniqueFilter],
             Program=random.choice((Printer, Switch)))
        for x in range(num_nodes)
    ]

    if randomize:
        desired_min_eigenvalue = 4 if num_links > 4 else (
            len(links) - 2)  # must be less than the total number of nodes!!!
        even_eigen_randomize(nodes, links, desired_min_eigenvalue)

    print("Let there be life.")
    [link.start() for link in links]
    for node in nodes:
        node.start()
        print("%s:%s" % (node, node.interfaces))
        row = []
        for col_idx in range(num_cols):
            # add input node
            if col_idx == 0:
                addr = IN_ADDRESSES[row_idx]
                Program = None
            # add output node
            elif col_idx == num_cols - 1:
                addr = OUT_ADDRESSES[row_idx]
                Program = Cache
            # out middle node
            else:
                addr = 'row:{};col{}'.format(row_idx, col_idx)
                Program = ButterflySwitch

            row.append(Node(name=addr, mac_addr=addr, Program=Program))

        NODES.append(row)

    print('Creating Butterfly Links...')

    # make the first links going directly across each row
    for row_idx in range(num_rows):
        for col_idx in range(num_cols - 1):
            bridge = VirtualLink(
                name='{}<{}>{}'.format(col_idx, row_idx, col_idx + 1))
            NODES[row_idx][col_idx].interfaces.append(bridge)

            # node directly to the right
            NODES[row_idx][col_idx + 1].interfaces.append(bridge)
            bridge.start()
示例#8
0
from mesh.links import UDPLink
from mesh.programs import BaseProgram
from mesh.filters import UniqueFilter
from mesh.node import Node



class ChatProgram(BaseProgram):
    def recv(self, packet, interface):
        print('\n>> {}'.format(packet.decode()))


if __name__ == "__main__":
    links = [UDPLink('en0', 2010), UDPLink('en1', 2011), UDPLink('en2', 2012), UDPLink('en3', 2013)]
    node = Node(links, 'me', Filters=(UniqueFilter,), Program=ChatProgram)
    [link.start() for link in links]
    node.start()

    print("Run lan-chat.py on another laptop to talk between the two of you on en0.")
    try:
        while True:
            print("------------------------------")
            message = input('<< ')
            node.send(bytes(message, 'UTF-8'))
            time.sleep(0.3)

    except (EOFError, KeyboardInterrupt):   # graceful CTRL-D & CTRL-C
        node.stop()
        [link.stop() for link in links]
示例#9
0
        'available_input_devices': [],
        'available_output_devices': ['speaker']
    }

    bedroom_config = {
        'node_name': 'alpha',
        'node_location': 'bedroom',
        'available_input_devices': ['microphone'],
        'available_output_devices': []
    }

    config = bedroom_config

    links = [UDPLink('en0', 2010)]

    node = Node(links, config['node_name'], Filters=[], Program=Albus)

    node.program.apply_config(config)

    [link.start() for link in links]
    node.start()

    print(
        "Run lan-chat.py on another laptop to talk between the two of you on en0."
    )
    try:
        while True:
            message = input('<< ')

            message_dict = create_message_dict('Light On', '',
                                               config['node_name'], 'light')
'''
Simple Star Topology Example:
         n1
         |
       (star)
        /  \
      n2    n3

Star Node is a switch that forwards all packets to all its links
Each Node is a printer that Prints its packets
'''

ls = (VirtualLink('vl1'), VirtualLink('vl2'), VirtualLink('vl3'))

nodes = (
    Node([ls[0], ls[1], ls[2]], 'star', Program=Switch),
    Node([ls[0]], 'n1', Program=Printer),
    Node([ls[1]], 'n2', Program=Printer),
    Node([ls[2]], 'n3', Program=Printer)
)

[l.start() for l in ls]
[n.start() for n in nodes]


if __name__ == "__main__":
    print('\n', nodes)
    print("Experiment by typing packets for [n1] to send out, and seeing if they make it to the [n2], [n3]")

    try:
        while True:
示例#11
0
from time import sleep

from mesh.linker import VirtualLink, UDPLink
from mesh.program import Switch, Printer
from mesh.filters import DuplicateFilter, StringFilter
from mesh.node import Node


ls = (UPDLink('en0', 2010), VirtualLink('vl1'), VirtualLink('vl2'), UDPLink('irc3', 2013), UPDLink('en4', 2014), UDPLink('irc5', 2013))
nodes = (
    Node('start', [ls[0]]),
    Node('l1', [ls[0], ls[2]], Program=Switch),
    Node('r1', [ls[0], ls[1]], Program=Switch),
    Node('l2', [ls[2], ls[3]], Program=Switch, Filters=(DuplicateFilter)),
    Node('r2', [ls[1], ls[4]], Program=Switch, Filters=(StringFilter.match(b'red'),) ),
    Node('end', [ls[4], ls[5]])
)

[l.start() for l in ls]
[n.start() for n in nodes]


if __name__ == "__main__":
    print("Using a mix of real and vitual links to make a little network...\n")
    print("          /[r1]<--vlan1-->[r2]<----vlan4---\\")
    print("[start]-en0                                [end]")
    print("          \[l1]<--vlan2-->[l2]<--irc3:irc5-/\n")


    print('\n', nodes)
    print("l2 wont forward two of the same packet in a row.")
示例#12
0
class Node(threading.Thread):
    def __init__(self, name, port=5000, blockchain=Blockchain()):
        threading.Thread.__init__(self)

        self.name = name
        self.address = ni.ifaddresses('en0')[ni.AF_INET][0]['addr']

        self.blockchain = blockchain

        self.peer_info = {}
        self.peers = set()

        self.links = [UDPLink('en0', port=port)]
        self.network = NetworkComponent(self.links,
                                        name,
                                        Filters=(DuplicateFilter, ))

        self.keep_listening = True
        self.ready = False
        self.synced = False

        self.heartbeat_thread = threading.Thread(target=self.send_heartbeat)

        # Start Network Component
        [link.start() for link in self.links]
        self.network.start()
        self.heartbeat_thread.start()
        self.start()

    @property
    def identifier(self):
        parsed_url = urlparse(self.address)
        return f'{parsed_url.path}:{self.name}'

    # Threading
    def run(self):
        while self.keep_listening:
            # Remove peers who have disconnected after 30 mins
            disconnected_peers = []
            for peer_id, info in self.peer_info.items():
                if info['lastsend'] - info['lastrecv'] > 60 * 30:
                    disconnected_peers.append(peer_id)

            for peer_id in disconnected_peers:
                print(f'Disconnecting {peer_id} for being idle for 30 minutes')
                self.peer_info.pop(peer_id)
                self.peers.remove(peer_id)

            # Check for new packets
            for interface in self.network.interfaces:
                try:
                    self.recv(self.network.inq[interface].get(timeout=0),
                              interface)
                except Empty:
                    sleep(0.1)

    def stop(self):
        self.keep_listening = False

        self.network.stop()
        [link.stop() for link in self.links]

        self.heartbeat_thread.join()
        self.join()

    # I/O
    def send(self, type, message='', target='', encoding='UTF-8'):
        data = json.dumps({
            'type': type,
            'identifier': self.identifier,
            'message': message,
            'target': target
        })

        print('\nsending {}'.format(data))

        self.network.send(bytes(data, encoding))

        # Update Peer Info
        if target:
            self.peer_info[target]['lastsend'] = time()
        else:
            for peer in self.peers:
                self.peer_info[peer]['lastsend'] = time()

    def recv(self, packet, interface):
        data = json.loads(packet.decode())

        # Filter Packets not targeted to you
        if len(data['target']) != 0 and data['target'] != self.identifier:
            return

        print('\nreceived {}'.format(data))

        self.handle_data(data)

        # Update Peer Info
        sender = data['identifier']
        if sender in self.peers:
            self.peer_info[sender]['lastrecv'] = time()

    def handle_data(self, data):
        # Handle Request
        msg_type = data['type']
        sender = data['identifier']
        message = json.loads(data['message']) if data['message'] else {}

        if msg_type == 'version':
            registered = self.register_peer(sender,
                                            height=message.get('height'))

            if registered:
                self.send('verack', target=sender)
                self.send('version',
                          target=sender,
                          message=json.dumps(
                              {'height': len(self.blockchain.chain)}))
            print(self.peers)

        elif msg_type == 'verack':
            self.ready = True

        if self.ready:
            if msg_type == 'heartbeat':
                self.send('heartbeatack', target=sender)

            elif msg_type == 'heartbeatack':
                pass

    def send_heartbeat(self):
        while self.keep_listening and self.ready:
            sleep(60 * 30)
            self.send('heartbeat')

    # Methods
    def register_peer(self, identifier, height):
        """
        Add a new node to the list of nodes

        @param identifier: <str> Identifier of the node (eg: 'address:name')

        @return: <bool> True if a new peer was registered, False otherwise
        """

        if identifier not in self.peers:
            self.peers.add(identifier)
            self.peer_info[identifier] = {
                'identifier': identifier,
                'lastrecv': time(),
                'lastsend': 0,
                'height': height
            }

            return True
        else:
            return False

    def get_peer(self, index=None):
        """
        Returns a random peer identifier unless specified by the parameter

        @param index: <int> Index of the peer in the peer list

        @return: <str> Peer identifier
        """

        if index is None:
            index = randint(0, len(self.peers) - 1)

        i = 0
        for p in self.peers:
            if i == index:
                return p
            i += 1
示例#13
0
文件: QRNET.py 项目: lAleRojasl/qrnet
        if(str(interface) == '<vl4>'):
            #create QR
            DispositivoLuzAdaptador(s)
        else:
            print('\n[USER] Received message>> {}'.format(s))


##--------------------------------------------------------------------##
##                        MAIN
## Se genera una red mesh virtual previamente negociada
##--------------------------------------------------------------------##

if __name__ == "__main__":
    links = (IRCLink('irc1'),VirtualLink('vl1'),VirtualLink('vl2'),VirtualLink('vl3'),VirtualLink('vl4'))
    nodes = (
         Node([links[0], links[1]], 'ClearnetNode',mac_addr='1C-C2-87-54-96-4E', Filters=(UniqueFilter,), Program=IRCProgram),
         Node([links[1],links[2],links[3]], 'RouterNode',mac_addr='2C-C3-87-54-96-4E', Filters=(UniqueFilter,), Program=RouterProgram),
         Node([links[2]], 'UserNode1', mac_addr='1A-B5-87-59-96-4E', Filters=(UniqueFilter,), Program=NodeProgram),
         Node([links[3]], 'UserNode2', mac_addr='3D-C2-45-51-96-4E',Filters=(UniqueFilter,), Program=NodeProgram),
         Node([links[4]], 'QRTransmisor', mac_addr='3D-A2-A5-51-96-4E',Filters=(UniqueFilter,), Program=NodeProgram)
    )
    [l.start() for l in links]
    [n.start() for n in nodes]

    try:
        while True:
            #message = input("Type a message: ")
            #nodes[0].send(bytes(message, 'UTF-8',))
            time.sleep(0.3)

    except (EOFError, KeyboardInterrupt):   # graceful CTRL-D & CTRL-C
示例#14
0
# -*- coding: utf-8 -*-
# MIT Liscence : Nick Sweeting

from time import sleep

from mesh.links import VirtualLink, UDPLink
from mesh.programs import Switch, Printer
from mesh.filters import DuplicateFilter, StringFilter
from mesh.node import Node


# ls = (UDPLink('en0', 2014), VirtualLink('vl1'), VirtualLink('vl2'), IRCLink('irc3'), UDPLink('en4', 2016), IRCLink('irc5'))          # slow, but impressive to connect over IRC
ls = (UDPLink('en0', 2010), VirtualLink('vl1'), VirtualLink('vl2'), UDPLink('irc3', 2013), UDPLink('en4', 2014), UDPLink('irc5', 2013))    # faster setup for quick testing
nodes = (
    Node([ls[0]], 'start'),
    Node([ls[0], ls[2]], 'l1', Program=Switch),
    Node([ls[0], ls[1]], 'r1', Program=Switch),
    Node([ls[2], ls[3]], 'l2', Filters=(DuplicateFilter,), Program=Switch),              # l2 wont forward two of the same packet in a row
    Node([ls[1], ls[4]], 'r2', Filters=(StringFilter.match(b'red'),), Program=Switch),   # r2 wont forward any packet unless it contains the string 'red'
    Node([ls[4], ls[5]], 'end', Program=Printer),
)
[l.start() for l in ls]
[n.start() for n in nodes]


if __name__ == "__main__":
    print("Using a mix of real and vitual links to make a little network...\n")
    print("          /[r1]<--vlan1-->[r2]<----vlan4---\\")
    print("[start]-en0                                [end]")
    print("          \[l1]<--vlan2-->[l2]<--irc3:irc5-/\n")
示例#15
0
from mesh.programs import BaseProgram, Switch


class IRCProgram(BaseProgram):
    def recv(self, packet, interface):
        s = packet.decode()
        print("Received IRC packet on interface: " + str(interface))
        print("My MAC Address: " + self.node.mac_addr)
        print("My Name: " + self.node.name)
        print('\nCreating QR for message>> {}'.format(s))


if __name__ == "__main__":
    links = (IRCLink('irc1'), VirtualLink('vl2'))
    nodes = (Node([links[0]],
                  'Alejandro',
                  Filters=(UniqueFilter, ),
                  Program=IRCProgram),
             Node([links[0], links[1]],
                  'Alejandro',
                  Filters=(UniqueFilter, ),
                  Program=IRCProgram),
             Node([links[1]],
                  'Alejandro',
                  Filters=(UniqueFilter, ),
                  Program=IRCProgram))
    [l.start() for l in links]
    [n.start() for n in nodes]

    print(
        "Run lan-chat.py on another laptop to talk between the two of you on en0."
    )