当前位置: 首页>>代码示例>>Python>>正文


Python Server.bootstrap方法代码示例

本文整理汇总了Python中kademlia.network.Server.bootstrap方法的典型用法代码示例。如果您正苦于以下问题:Python Server.bootstrap方法的具体用法?Python Server.bootstrap怎么用?Python Server.bootstrap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在kademlia.network.Server的用法示例。


在下文中一共展示了Server.bootstrap方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: refresh_mirror

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
def refresh_mirror( working_dir, first_block, last_block ):
   """
   Refresh the mirror:
   * process all new invalidations
   * grab and mirror any new profiles from the DHT
   
   This gets called by Twisted every time there ought to be a new block.
   """

   from twisted.python import log
   from kademlia.network import Server 
   
   # make soure our bitcoind cached block index is up-to-speed 
   nameop_sequence = sync_blockchain( working_dir, first_block, last_block )
   if nameop_sequence is None:
      
      log.error("sync_blockchain(%s-%s) failed" % (first_block, last_block))
      return None
   
   # synchronize name registrations...
   
   
   server = Server()
   server.listen( dht.plugin.DHT_SERVER_PORT )
   server.bootstrap( dht.plugin.DEFAULT_DHT_SERVERS ).addCallback( connect_done, server )
   
   pass
开发者ID:hotelzululima,项目名称:blockstore,代码行数:29,代码来源:blockmirrord.py

示例2: test_get

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
    def test_get(self):
        expected = "rohan"
        key = "A"
        # getkey("127.0.0.1",8468,key)
        # self.assertEqual(expected,result)
        def done(result):
            # print "Key result:"
            # print result
            self.assertEqual(expected, result)
            reactor.stop()

        def bootstrapDone(found, server, key):
            if len(found) == 0:
                print "Could not connect to the bootstrap server."
                reactor.stop()
            server.get(key).addCallback(done)

        server = Server()
        temp_port = random.randint(9000, 9999)
        server.listen(
            temp_port
        )  #  Any node wishing to query the network essentially registers itself as a server/node with every node it communicates with
        server.bootstrap([("127.0.0.1", 8468)]).addCallback(bootstrapDone, server, key)

        reactor.run()
开发者ID:rohanbharadwaj,项目名称:correctness-chord,代码行数:27,代码来源:test_kademila.py

示例3: connect

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
    def connect(self, port):
        
        if(self._app_deployer):
            from twisted.application import service, internet
            from twisted.python.log import ILogObserver
            from twisted.internet import reactor, task

            import sys, os
            sys.path.append(os.path.dirname(__file__))
            from kademlia.network import Server
            from kademlia import log

            application = service.Application("kademlia")
            application.setComponent(ILogObserver, log.FileLogObserver(sys.stdout, log.INFO).emit)

            if os.path.isfile('cache.pickle'):
                kserver = Server.loadState('cache.pickle')
            else:
                kserver = Server()
                kserver.bootstrap([("127.0.0.1", port)])
                kserver.saveStateRegularly('cache.pickle', 10)
                
            server = internet.UDPServer(8468, kserver.protocol)
            server.setServiceParent(application)    
        else:
            self._node.listen(port)
            self._node.bootstrap([("127.0.0.1",port)]).addCallback(self.bootStrapDone)
开发者ID:dwils098,项目名称:Masters,代码行数:29,代码来源:.#networkInterface.py

示例4: DHTResolver

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
class DHTResolver(object):
    def __init__(self, config, bootstrapNeighbors):
        self.config = config
        self.log = Logger(system=self)
        if os.path.isfile(config['dht.state.cache']):
            self.kserver = Server.loadState(config['dht.state.cache'])
        else:
            self.kserver = Server()
            self.kserver.bootstrap(bootstrapNeighbors)
        self.kserver.saveStateRegularly(config['dht.state.cache'], 60)

    def getProtocol(self):
        return self.kserver.protocol

    def getPublicKey(self, keyId):
        """
        Get the public key from the network, and return only if the key is
        the one that matches the keyId based on hash.
        """
        def verify(key):
            if key is not None and PublicKey(key).getKeyId() == keyId:
                return key
            return None

        self.log.debug("Getting key text for key id %s" % keyId)
        return self.kserver.get(keyId).addCallback(verify)

    def resolve(self, keyId):
        def parse(locations):
            self.log.debug("Locations for %s: %s" % (keyId, locations))
            results = []
            if locations is None or locations == "":
                return results
            for location in locations.split(','):
                host, port = location.split(':')
                results.append((host, int(port)))
            return results
        d = self.kserver.get("%s-location" % keyId)
        return d.addCallback(parse)

    def announceLocation(self, myKeyId, myPublicKey):
        def announce(ips):
            ips = self.localAddresses() + ips
            ipports = map(lambda ip: "%s:%i" % (ip, self.config['s2s.port']), ips)
            return self.kserver.set("%s-location" % myKeyId, ",".join(ipports))
        d = self.kserver.set(myKeyId, str(myPublicKey))
        d.addCallback(lambda _: self.kserver.inetVisibleIP())
        return d.addCallback(announce)

    def localAddresses(self):
        result = []
        for iface in netifaces.interfaces():
            addys = netifaces.ifaddresses(iface).get(netifaces.AF_INET)
            result += [ addy['addr'] for addy in (addys or []) if addy['addr'] != '127.0.0.1' ]
        return result
开发者ID:tintfoundation,项目名称:tint,代码行数:57,代码来源:resolution.py

示例5: dht_init

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
def dht_init(blockchain_index):
    """
    Establish our connection to the DHT, and give
    it the requisite state it needs (i.e. the index
    over the blockchain).
    """

    global dht_server
    global dht_blockchain_index

    dht_blockchain_index = blockchain_index

    dht_server = Server(storage=BlockStorage())
    dht_server.listen(DHT_SERVER_PORT)
    bootstrap_servers = hostname_to_ip(DEFAULT_DHT_SERVERS)
    dht_server.bootstrap(bootstrap_servers)
开发者ID:ChairmanTubeAmp,项目名称:blockstack-server,代码行数:18,代码来源:plugin.py

示例6: uat

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
def uat(wc, option_flags, option_format, myReason):
    from twisted.internet import reactor
    from twisted.python import log
    from kademlia.network import Server
    import sys
    
    log.startLogging(sys.stdout)

    def query(wc, query_string):
        wc = wc.canonicalize()
        query_string = "@prefix : <http://test#>.\n" + query_string
        query_file = "query.tmp.n3"
        o = open(query_file, "w")
        o.write(query_string)
        o.close()

        filterContext = _store.load(query_file, 
                            flags=option_flags[option_format],
                            referer="",
                            why=myReason, topLevel=True)
        wc.reopen()
        print "applying...", filterContext, "to", wc
        applyRules(wc, filterContext);
        return wc



    def done(result):
        print "Key result:", result
        #reactor.stop()

    def setDone(result, server):
        server.get("a key").addCallback(done)

    def kademliaBootstrapDone(found, server):
        server.set("a key", "a value").addCallback(setDone, server)

    server = Server()
    server.listen(8468)
    server.bootstrap([("1.2.3.4", 8468)]).addCallback(kademliaBootstrapDone, server)


    wc = query(wc, "[ a :banana ].")

    #reactor.run()

    return wc
开发者ID:koo5,项目名称:hackery,代码行数:49,代码来源:cwm.py

示例7: getKey

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
def getKey(ip,port,key):
	def done(result):
	    print "Key result:"
	    print result
	    reactor.stop()

	def bootstrapDone(found, server, key):
	    if len(found) == 0:
	        print "Could not connect to the bootstrap server."
	        reactor.stop()
	    server.get(key).addCallback(done)

	server = Server()
	temp_port = random.randint(9000,9999)
	server.listen(temp_port) #  Any node wishing to query the network essentially registers itself as a server/node with every node it communicates with
	server.bootstrap([(ip, port)]).addCallback(bootstrapDone, server, key)

	reactor.run()
开发者ID:rohanbharadwaj,项目名称:correctness-chord,代码行数:20,代码来源:driver_util.py

示例8: helper

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
def helper(file, ip, bootstrapPort, localPort, send, debug):

    # No loss yet !
    config.totalLoss = 0
    config.debug = debug

    # Start Server
    if debug == 'loads': log.startLogging(sys.stdout)
    server = Server()

    # Start own server on port 5678
    server.listen(localPort)

    # Bootstrap with a known ip address of an existing kad server
    server.bootstrap([(ip, bootstrapPort)]).addCallback(started, server, send, file, debug)


    reactor.run()
开发者ID:pldubouilh,项目名称:maidsafe,代码行数:20,代码来源:main.py

示例9: dht_run

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
def dht_run(config_file=DEFAULT_CONFIG_FILE):
    """
    Run the blockstackd RPC server, optionally in the foreground.
    """
    # start DHT server
    observer = log.FileLogObserver(sys.stdout, log.INFO)
    observer.start()

    dht_opts = get_dht_opts(config_file)
    dht_servers_str = dht_opts['servers']
    dht_port = dht_opts['port']
    dht_servers = parse_dht_servers( dht_servers_str )

    dht_server = Server(storage=BlockStorage())
    bootstrap_servers = hostname_to_ip(dht_servers)
    dht_server.bootstrap(bootstrap_servers)

    reactor.listenUDP( dht_port, dht_server.protocol )
    reactor.run()
开发者ID:blockstack,项目名称:blockstack-dht,代码行数:21,代码来源:blockstack_dht.py

示例10: __init__

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
class BitHaikuDHT:
    log = logging.getLogger(__name__)

    def __init__(self, configuration):
        self.configuration = configuration
        self.server = Server()
        self.server.listen(configuration.ports.dht)
        self.server.bootstrap([(configuration.local_address, configuration.ports.dht)])

    def add(self, ip):
        self.log.error("Bootstrapping " + ip)
        self.server.bootstrap([(ip, self.configuration.ports.dht)])

    def find_owner(self, data):
        key = value = hashlib.sha256(data).hexdigest()
        self.server.set(key, value)

        digest = kademlia.utils.digest(hash)
        node = Node(digest)
        nearest = self.server.protocol.router.findNeighbors(node)
        return nearest[0].ip
开发者ID:BrandonHaynes,项目名称:bithaiku,代码行数:23,代码来源:dht.py

示例11: DHTResolver

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
class DHTResolver(object):
    def __init__(self, config, bootstrapNeighbors):
        if os.path.isfile(config['dht.state.cache']):
            self.kserver = Server.loadState(config['dht.state.cache'])
        else:
            self.kserver = Server()
            self.kserver.bootstrap(bootstrapNeighbors)
            self.kserver.saveStateRegularly(config['dht.state.cache'], 60)

    def getProtocol(self):
        return self.kserver.protocol

    def resolve(self, keyId):
        return self.kserver.get(keyId)

    def announceLocation(self, myKeyId):
        def announce(ips):
            if len(ips) == 0:
                return defer.succeed(False)
            return self.kserver.set(myKeyId, ips[0])
        d = self.kserver.inetVisibleIP()
        return d.addCallback(announce)
开发者ID:krahimian,项目名称:tint,代码行数:24,代码来源:resolution.py

示例12: bootstrap

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
    def bootstrap(self, addrs):
        """
        Bootstrap the server by connecting to other known nodes in the network.

        Args:
            addrs: A `list` of (ip, port) `tuple` pairs.  Note that only IP addresses
                   are acceptable - hostnames will cause an error.
        """
        # if the transport hasn't been initialized yet, wait a second
        if self.protocol.transport is None:
            return task.deferLater(reactor, .2, self.bootstrap, addrs)
        else:
            return Server.bootstrap(self, addrs)
开发者ID:KaptenJon,项目名称:calvin-base,代码行数:15,代码来源:append_server.py

示例13: KademliaUser

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
class KademliaUser(Runnable):
    """Allows the KademliaUser to be run in its own thread."""

    def __init__(self, name="KademliaUser%d"%random.randint(1, 1000),
                 port=emu_config.kademlia_default_port, peerlist=None):
        super(KademliaUser, self).__init__(name=name)
        self.kademliaServer = Server()
        self.port = port
        self.peerlist = peerlist if peerlist is not None else []

    def start(self):
        """Implements start() from the superclass."""
        self._startKademlia()
        try:
            IOLoop.current().start()
        except socket.error as ex:
            logging.warning("Could not start the KademliaUser: %s"%ex)

    def _startKademlia(self):
        possible_interfaces = [iface for iface in netifaces.interfaces() if iface_searchterm in iface
                               and netifaces.ifaddresses(iface).has_key(netifaces.AF_INET)]
        if len(possible_interfaces) == 0:
            logging.error("No suitable interfaces found, tried the following: %s"%netifaces.interfaces())
        logging.debug("Interfaces: %s"%netifaces.ifaddresses(possible_interfaces[0]))
        ipAddr = netifaces.ifaddresses(possible_interfaces[0])[netifaces.AF_INET][0]["addr"]
        logging.debug("Node %s starts with %s on %s"%(self.name, self.peerlist, ipAddr))

        self.kademliaServer.listen(self.port, interface=ipAddr)
        serverDeferred = self.kademliaServer.bootstrap([(peer, emu_config.kademlia_default_port) for peer in self.peerlist])
        serverDeferred.addCallback(self.executeBot)
        serverDeferred.addErrback(self.errback)

    def executeBot(self, peersfound=None):
        """Method that is called regularly and checks for new commands"""
        self.kademliaServer.get(generateRandomString(length=2)).addCallbacks(self.ignoreInput, self.errback)
        self.kademliaServer.set(generateRandomString(length=2), generateRandomString()).addCallbacks(self.ignoreInput,
                                                                                                     self.errback)
        reactor.callLater(emu_config.botcommand_timeout, self.executeBot)

    def ignoreInput(self, *args, **kwargs):
        """Gets whatever is the result of the Kademlia GET request and ignores it"""
        pass

    def errback(self, failure, *args, **kwargs):
        """Given to defereds to report errors. Ignores those errors."""
        logging.debug(
            "Kademlia Error (for the legitimate user, so non-existing keys are not a problem) in %s: %s"%(self.name, failure))
        pass
开发者ID:icehawk1,项目名称:GameoverZeus,代码行数:50,代码来源:User.py

示例14: setUp

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
    def setUp(self):

        # create peers
        self.swarm = []
        for i in range(TEST_SWARM_SIZE):
            peer = Server()
            bootstrap_peers = [
                ("127.0.0.1", PORT + x) for x in range(i)
            ][-1:]  # each peer only knows of the last peer
            peer.bootstrap(bootstrap_peers)
            peer.listen(PORT + i)
            self.swarm.append(peer)

        # stabalize network overlay
        time.sleep(10)
        for peer in self.swarm:
            peer.bootstrap(peer.bootstrappableNeighbors())
        time.sleep(10)
        for peer in self.swarm:
            peer.bootstrap(peer.bootstrappableNeighbors())
        time.sleep(10)
开发者ID:F483,项目名称:kademlia,代码行数:23,代码来源:test_swarm.py

示例15: done

# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import bootstrap [as 别名]
from __future__ import print_function

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from twisted.internet import reactor
from twisted.python import log
from kademlia.network import Server

log.startLogging(sys.stdout)

def done(result):
    print("Key result:", result)
    reactor.stop()

def setDone(result, server):
    server.get("a key").addCallback(done)

def bootstrapDone(found, server):
    server.set("a key", "a value").addCallback(setDone, server)

server = Server()
server.listen(8469)
bootstrap_nodes = [("127.0.0.1", 8468)]  # twistd -noy examples/server.tac
server.bootstrap(bootstrap_nodes).addCallback(bootstrapDone, server)

reactor.run()
开发者ID:F483,项目名称:kademlia,代码行数:29,代码来源:example.py


注:本文中的kademlia.network.Server.bootstrap方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。