Ejemplo n.º 1
0
    def __init__(self, store_file, my_market_ip, my_market_port, my_node_port,
                 my_node_file, seed_uri, market_id):

        self.transport = CryptoTransportLayer(my_market_ip, my_market_port,
                                              market_id, store_file)
        self.transport.join_network(seed_uri)

        data_store = SQLiteDataStore(
        )  # creates in-memory database, should be persistent
        known_nodes = self.known_entangled_nodes(my_node_file, seed_uri,
                                                 my_node_port)
        # initializes node with specified port and an in-memory SQLite database
        self.node = entangled.node.EntangledNode(udpPort=my_node_port,
                                                 dataStore=data_store)

        self.node.joinNetwork(known_nodes)

        self.market = Market(self.transport, self.node, store_file)

        handlers = [(r"/", MainHandler), (r"/main", MainHandler),
                    (r"/html/(.*)", tornado.web.StaticFileHandler, {
                        'path': './html'
                    }),
                    (r"/ws", WebSocketHandler,
                     dict(transport=self.transport, node=self.market))]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)
Ejemplo n.º 2
0
def sender(knownNodes):
    #if os.path.isfile('/tmp/dbFile%s.db' % sys.argv[1]):
    #os.remove('/tmp/dbFile%s.db' % sys.argv[1])
    dataStore = SQLiteDataStore(dbFile='/tmp/dbFile%s.db' % 5000)

    node = EntangledNode(udpPort=int(sys.argv[1]), dataStore=dataStore)
    node.joinNetwork(knownNodes)

    print("Enter the receiver's email:")
    rcv_id = str(raw_input())
    print("Enter your message:")
    msg = str(raw_input())
    session_key = generate_session_key()
    msgid = make_msgid()

    #stroe the messageid and message in the DHT ?????????
    #node.store(str(msgid),msg)
    store(node, msgid[0:12], msg)

    #generate email header
    hash_sha1 = hashlib.sha1(msg)
    #header = Emailheader(session_key,msgid,hash_sha1.digest())

    #stroe the email address and email head in the DHT
    append_Inbox(node, rcv_id, msgid[0:12])
    '''print("Enter your email:")
Ejemplo n.º 3
0
def main():
    import sys, os
    if len(sys.argv) < 2:
        print 'Usage:\n%s UDP_PORT [KNOWN_NODE_IP  KNOWN_NODE_PORT]' % sys.argv[0]
        print 'or:\n%s UDP_PORT [FILE_WITH_KNOWN_NODES]' % sys.argv[0]
        print '\nIf a file is specified, it should containg one IP address and UDP port\nper line, seperated by a space.'
        sys.exit(1)
    try:
        int(sys.argv[1])
    except ValueError:
        print '\nUDP_PORT must be an integer value.\n'
        print 'Usage:\n%s UDP_PORT  [KNOWN_NODE_IP  KNOWN_NODE_PORT]' % sys.argv[0]
        print 'or:\n%s UDP_PORT  [FILE_WITH_KNOWN_NODES]' % sys.argv[0]
        print '\nIf a file is specified, it should contain one IP address and UDP port\nper line, seperated by a space.'
        sys.exit(1)

    if len(sys.argv) == 4:
        knownNodes = [(sys.argv[2], int(sys.argv[3]))]
    elif len(sys.argv) == 3:
        knownNodes = []
        f = open(sys.argv[2], 'r')
        lines = f.readlines()
        f.close()
        for line in lines:
            ipAddress, udpPort = line.split()
            knownNodes.append((ipAddress, int(udpPort)))
    else:
        knownNodes = None
        print '\nNOTE: You have not specified any remote DHT node(s) to connect to'
        print 'It will thus not be aware of any existing DHT, but will still function as a self-contained DHT (until another node contacts it).'
        print 'Run this script without any arguments for info.\n'
    # Set up SQLite-based data store (you could use an in-memory store instead, for example)
    if os.path.isfile('/tmp/dbFile%s.db' % sys.argv[1]):
        os.remove('/tmp/dbFile%s.db' % sys.argv[1])
    dataStore = SQLiteDataStore(dbFile = '/tmp/dbFile%s.db' % sys.argv[1])
    
    node = EntangledNode( udpPort=int(sys.argv[1]), dataStore=dataStore )
    node.joinNetwork(knownNodes)

    print("Enter the receiver's email:")
    rcv_id = str(raw_input())
    print("Enter your message:")
    msg = str(raw_input())
    session_key = generate_session_key()
    msgid = make_msgid()

    #stroe the messageid and message in the DHT ?????????
    #node.store(str(msgid),msg)
    store(node,msgid[0:12],msg)
    
    #generate email header
    hash_sha1 = hashlib.sha1(msg)
    #header = Emailheader(session_key,msgid,hash_sha1.digest())
    
    #stroe the email address and email head in the DHT
    append_Inbox(node,rcv_id, msgid[0:12])

    '''print("Enter your email:")
Ejemplo n.º 4
0
    def cbConnect(self, directoryService):
        """
        Callback from the directory service.

        From this point we're connected and authenticated.
        """
        basepath = FilePath(os.path.expanduser('~/.distfs'))
        if not basepath.exists():
            basepath.createDirectory()

        store = FileSystemStore(basepath.child('store').path)
        chunkFactory = Site(server.StoreResource(store))

        locname = self['alias'] or directoryService.service

        # Listen for remote connections.  This is for the other nodes
        # to access our store.
        port = self['port'] and int(self['port']) or 0
        listeningPort = reactor.listenTCP(port, chunkFactory)

        keyStore = SQLiteDataStore(basepath.child('%s.db' % locname).path)
        dhtNode = KademliaNode(listeningPort.getHost().port,
                               keyStore,
                               reactor=reactor)

        # Listen locally so that applications can easily access the
        # store.
        reactor.listenUNIX(
            basepath.child('%s.http' % locname).path, chunkFactory)

        resolverPublisher = ResolverPublisher(dhtNode)

        controlFactory = control.ControlFactory(store, directoryService,
                                                dhtNode, resolverPublisher)
        reactor.listenUNIX(
            basepath.child('%s.ctrl' % locname).path, controlFactory)

        # Start a looping call that will publish chunks to the
        # overlay; do that every 6th hour.  Delay the procedure a bit
        # so that the node has a chance to join the network.
        looping = task.LoopingCall(publishChunks, store, resolverPublisher)
        reactor.callLater(10, looping.start, 6 * 60 * 60, True)

        # Try joining the network.
        introducers = list()
        if self['introducer']:
            try:
                address, port = self['introducer'].split(':')
            except ValueError:
                address, port = self['introducer'], 8033
            introducers.append((address, int(port)))
        dhtNode.joinNetwork(introducers)

        # At this point everything that can go (majorly) wrong has
        # been initialized and we can daemonize.
        if not self['no-daemon']:
            daemonize()
Ejemplo n.º 5
0
def receiver(knownNodes):

    dataStore = SQLiteDataStore(dbFile='/tmp/dbFile%s.db' % 5000)

    node = EntangledNode(udpPort=int(sys.argv[1]), dataStore=dataStore)
    node.joinNetwork(knownNodes)
    print("Enter your email:")
    rcv_id = str(raw_input())
    read_Inbox(node, rcv_id)
Ejemplo n.º 6
0
def newNode(node_list):
    global port
    global sybil
    print 'Creating Sybil Node...'
    if os.path.isfile('/tmp/dbFile%s.db' % port):
        os.remove('/tmp/dbFile%s.db' % port)
    dataStore = SQLiteDataStore(dbFile='/tmp/dbFile%s.db' % port)

    sybil = SybilNode(udpPort=port, dataStore=dataStore)

    sybil.joinNetwork(node_list)
Ejemplo n.º 7
0
class KadFacade(object):

  def __init__(self, start_port):
    self.dbpath = settings.DBPATH + '/buddydht-%s.db' % start_port
    self.kadstore = SQLiteDataStore(dbFile = self.dbpath)

  def get_all_peers_from_dht(self, pubkeys):
    """ Getting the list of all public keys on a circle's DHT is tough because there is no content specific flag on the hash table entries. """
    keys = self.kadstore.keys()
    return keys
   
   
  def get_peers(pubkeys):
   all_peers = get_all_peers_from_dht() 
Ejemplo n.º 8
0
class KadFacade(object):
    def __init__(self, start_port):
        self.dbpath = settings.DBPATH + '/buddydht-%s.db' % start_port
        self.kadstore = SQLiteDataStore(dbFile=self.dbpath)

    def get_all_peers_from_dht(self, pubkeys):
        """ Getting the list of all public keys on a circle's DHT is tough
            because there is no content specific flag on the hash table
            entries. """
        keys = self.kadstore.keys()
        return keys

    def get_peers(pubkeys):
        all_peers = get_all_peers_from_dht()
Ejemplo n.º 9
0
    def get_node(cls, start_port, known_ip=None, known_port=None):
        if BuddyNode.node is not None:
            return BuddyNode.node

        dbpath = settings.DBPATH + '/buddydht-%s.db' % start_port
        datastore = SQLiteDataStore(dbFile=dbpath)
        logger.info('Starting buddy-daemon on port %d', start_port)
        BuddyNode.node = BuddyNode(None, start_port, datastore)
        if known_ip is None or known_port is None:
            BuddyNode.node.joinNetwork([])
        else:
            BuddyNode.node.joinNetwork([(known_ip, known_port)])
            logger.debug('Bootstrap with node %s:%s', known_ip, known_port)

        return BuddyNode.node
Ejemplo n.º 10
0
def init(udp_port, db_file_path=None):
    global _MyNode
    if _MyNode is not None:
        if _Debug:
            lg.out(_DebugLevel,
                   'dht_service.init SKIP, already created a DHTNode')
        return
    if _Debug:
        lg.out(_DebugLevel, 'dht_service.init UDP port is %d' % udp_port)
    if db_file_path is None:
        db_file_path = settings.DHTDBFile()
    dbPath = bpio.portablePath(db_file_path)
    lg.out(
        4, 'dht_service.init UDP port is %d, DB file path: %s' %
        (udp_port, dbPath))
    dataStore = SQLiteDataStore(dbFile=dbPath)
    networkProtocol = KademliaProtocolConveyor
    # None, encoding.Bencode(), msgformat.DefaultFormat())
    _MyNode = DHTNode(udp_port, dataStore, networkProtocol=networkProtocol)
Ejemplo n.º 11
0
 def __init__(self, start_port):
   self.dbpath = settings.DBPATH + '/buddydht-%s.db' % start_port
   self.kadstore = SQLiteDataStore(dbFile = self.dbpath)
Ejemplo n.º 12
0
        knownNodes = [(sys.argv[2], int(sys.argv[3]))]
    elif len(sys.argv) == 3:
        knownNodes = []
        f = open(sys.argv[2], 'r')
        lines = f.readlines()
        f.close()
        for line in lines:
            ipAddress, udpPort = line.split()
            knownNodes.append((ipAddress, int(udpPort)))
    else:
        knownNodes = None
        print '\nNOTE: You have not specified any remote DHT node(s) to connect to'
        print 'It will thus not be aware of any existing DHT, but will still function as a self-contained DHT (until another node contacts it).'
        print 'Run this script without any arguments for info.\n'

    # Set up SQLite-based data store (you could use an in-memory store instead, for example)
    if os.path.isfile('/tmp/dbFile%s.db' % sys.argv[1]):
        os.remove('/tmp/dbFile%s.db' % sys.argv[1])
    dataStore = SQLiteDataStore(dbFile='/tmp/dbFile%s.db' % sys.argv[1])
    # Create the Entangled node. It extends the functionality of a basic Kademlia node (but is fully backwards-compatible with a Kademlia-only network)
    # If you wish to have a pure Kademlia network, use the entangled.kademlia.node.Node class instead
    print 'Creating Entangled Node...'
    node = EntangledNode(udpPort=int(sys.argv[1]), dataStore=dataStore)
    # Schedule the node to join the Kademlia/Entangled DHT
    node.joinNetwork(knownNodes)
    # Schedule the "storeValue() call to be invoked after 2.5 seconds, using KEY and VALUE as arguments
    twisted.internet.reactor.callLater(2.5, storeValue, KEY, VALUE)
    # Start the Twisted reactor - this fires up all networking, and allows the scheduled join operation to take place
    print 'Twisted reactor started (script will commence in 2.5 seconds)'
    twisted.internet.reactor.run()
Ejemplo n.º 13
0
 def __init__(self, start_port):
     self.dbpath = settings.DBPATH + '/buddydht-%s.db' % start_port
     self.kadstore = SQLiteDataStore(dbFile=self.dbpath)
Ejemplo n.º 14
0
 def set_root(self, pubkey, root_inode):
     datastore = SQLiteDataStore(dbFile=settings.DBPATH + '/buddydht.db')
     key = hashlib.sha1('root_' + pubkey).digest()
     self.iterativeStore(key, root_inode, self.get_node_id(), 0)
Ejemplo n.º 15
0
 def get_root(self, pubkey):
     datastore = SQLiteDataStore(dbFile=settings.DBPATH + '/buddydht.db')
     key = hashlib.sha1('root_' + pubkey).digest()
     return self.iterativeFindValue(key)