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


Python SimpleConfig.get方法代码示例

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


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

示例1: run_cmdline

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
 def run_cmdline(self, config_options):
     config = SimpleConfig(config_options)
     cmdname = config.get('cmd')
     cmd = known_commands[cmdname]
     wallet = self.load_wallet(config) if cmd.requires_wallet else None
     # arguments passed to function
     args = map(lambda x: config.get(x), cmd.params)
     # decode json arguments
     args = map(json_decode, args)
     # options
     args += map(lambda x: config.get(x), cmd.options)
     cmd_runner = Commands(config, wallet, self.network,
                           password=config_options.get('password'),
                           new_password=config_options.get('new_password'))
     func = getattr(cmd_runner, cmd.name)
     result = func(*args)
     return result
开发者ID:Emzy,项目名称:electrum,代码行数:19,代码来源:daemon.py

示例2: run_cmdline

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
 def run_cmdline(self, config_options):
     password = config_options.get("password")
     config = SimpleConfig(config_options)
     cmdname = config.get("cmd")
     cmd = known_commands[cmdname]
     wallet = self.load_wallet(config) if cmd.requires_wallet else None
     if wallet:
         wallet.wait_until_synchronized()
     # arguments passed to function
     args = map(lambda x: config.get(x), cmd.params)
     # decode json arguments
     args = map(json_decode, args)
     # options
     args += map(lambda x: config.get(x), cmd.options)
     cmd_runner = Commands(config, wallet, self.network)
     cmd_runner.password = password
     func = getattr(cmd_runner, cmd.name)
     result = func(*args)
     return result
开发者ID:nmarley,项目名称:electrum,代码行数:21,代码来源:daemon.py

示例3: run_gui

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
 def run_gui(self, config_options):
     config = SimpleConfig(config_options)
     if self.gui:
         if hasattr(self.gui, 'new_window'):
             path = config.get_wallet_path()
             self.gui.new_window(path, config.get('url'))
             response = "ok"
         else:
             response = "error: current GUI does not support multiple windows"
     else:
         response = "Error: Electrum is running in daemon mode. Please stop the daemon first."
     return response
开发者ID:ttytyper,项目名称:electrum,代码行数:14,代码来源:daemon.py

示例4: run_daemon

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
 def run_daemon(self, config_options):
     config = SimpleConfig(config_options)
     sub = config.get('subcommand')
     assert sub in [None, 'start', 'stop', 'status', 'load_wallet', 'close_wallet']
     if sub in [None, 'start']:
         response = "Daemon already running"
     elif sub == 'load_wallet':
         path = config.get_wallet_path()
         wallet = self.load_wallet(path, config.get('password'))
         self.cmd_runner.wallet = wallet
         response = True
     elif sub == 'close_wallet':
         path = config.get_wallet_path()
         if path in self.wallets:
             self.stop_wallet(path)
             response = True
         else:
             response = False
     elif sub == 'status':
         if self.network:
             p = self.network.get_parameters()
             response = {
                 'path': self.network.config.path,
                 'server': p[0],
                 'blockchain_height': self.network.get_local_height(),
                 'server_height': self.network.get_server_height(),
                 'spv_nodes': len(self.network.get_interfaces()),
                 'connected': self.network.is_connected(),
                 'auto_connect': p[4],
                 'version': ELECTRUM_VERSION,
                 'wallets': {k: w.is_up_to_date()
                             for k, w in self.wallets.items()},
                 'fee_per_kb': self.config.fee_per_kb(),
             }
         else:
             response = "Daemon offline"
     elif sub == 'stop':
         self.stop()
         response = "Daemon stopped"
     return response
开发者ID:Matoking,项目名称:electrum,代码行数:42,代码来源:daemon.py

示例5: run_cmdline

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
 def run_cmdline(self, config_options):
     password = config_options.get('password')
     new_password = config_options.get('new_password')
     config = SimpleConfig(config_options)
     config.fee_estimates = self.network.config.fee_estimates.copy()
     cmdname = config.get('cmd')
     cmd = known_commands[cmdname]
     if cmd.requires_wallet:
         path = config.get_wallet_path()
         wallet = self.wallets.get(path)
         if wallet is None:
             return {'error': 'Wallet not open. Use "electrum daemon load_wallet"'}
     else:
         wallet = None
     # arguments passed to function
     args = map(lambda x: config.get(x), cmd.params)
     # decode json arguments
     args = map(json_decode, args)
     # options
     args += map(lambda x: config.get(x), cmd.options)
     cmd_runner = Commands(config, wallet, self.network, password=password, new_password=new_password)
     func = getattr(cmd_runner, cmd.name)
     result = func(*args)
     return result
开发者ID:Matoking,项目名称:electrum,代码行数:26,代码来源:daemon.py

示例6: Network

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class Network(util.DaemonThread):
    """The Network class manages a set of connections to remote
    electrum servers, each connection is handled by its own
    thread object returned from Interface().  Its external API:

    - Member functions get_header(), get_parameters(), get_status_value(),
                       new_blockchain_height(), set_parameters(), start(),
                       stop()
    """

    def __init__(self, pipe, config=None):
        if config is None:
            config = {}  # Do not use mutables as default values!
        util.DaemonThread.__init__(self)
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.num_server = 8 if not self.config.get('oneserver') else 0
        self.blockchain = Blockchain(self.config, self)
        self.queue = Queue.Queue()
        self.requests_queue = pipe.send_queue
        self.response_queue = pipe.get_queue
        # Server for addresses and transactions
        self.default_server = self.config.get('server')
        # Sanitize default server
        try:
            deserialize_server(self.default_server)
        except:
            self.default_server = None
        if not self.default_server:
            self.default_server = pick_random_server()

        self.irc_servers = {} # returned by interface (list from irc)
        self.recent_servers = self.read_recent_servers()

        self.banner = ''
        self.heights = {}
        self.merkle_roots = {}
        self.utxo_roots = {}

        dir_path = os.path.join( self.config.path, 'certs')
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        # subscriptions and requests
        self.subscribed_addresses = set()
        # cached address status
        self.addr_responses = {}
        # unanswered requests
        self.unanswered_requests = {}
        # retry times
        self.server_retry_time = time.time()
        self.nodes_retry_time = time.time()
        # kick off the network.  interface is the main server we are currently
        # communicating with.  interfaces is the set of servers we are connecting
        # to or have an ongoing connection with
        self.interface = None
        self.interfaces = {}
        self.start_network(deserialize_server(self.default_server)[2],
                           deserialize_proxy(self.config.get('proxy')))

    def read_recent_servers(self):
        if not self.config.path:
            return []
        path = os.path.join(self.config.path, "recent_servers")
        try:
            with open(path, "r") as f:
                data = f.read()
                return json.loads(data)
        except:
            return []

    def save_recent_servers(self):
        if not self.config.path:
            return
        path = os.path.join(self.config.path, "recent_servers")
        s = json.dumps(self.recent_servers, indent=4, sort_keys=True)
        try:
            with open(path, "w") as f:
                f.write(s)
        except:
            pass

    def get_server_height(self):
        return self.heights.get(self.default_server, 0)

    def server_is_lagging(self):
        sh = self.get_server_height()
        if not sh:
            self.print_error('no height for main interface')
            return False
        lh = self.get_local_height()
        result = (lh - sh) > 1
        if result:
            self.print_error('%s is lagging (%d vs %d)' % (self.default_server, sh, lh))
        return result

    def set_status(self, status):
        self.connection_status = status
        self.notify('status')

    def is_connected(self):
#.........这里部分代码省略.........
开发者ID:alkiswani,项目名称:electrum,代码行数:103,代码来源:network.py

示例7: Network

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class Network(threading.Thread):

    def __init__(self, config = {}):
        threading.Thread.__init__(self)
        self.daemon = True
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.lock = threading.Lock()
        self.num_server = 8 if not self.config.get('oneserver') else 0
        self.blockchain = Blockchain(self.config, self)
        self.interfaces = {}
        self.queue = Queue.Queue()
        self.callbacks = {}
        self.protocol = self.config.get('protocol','s')
        self.running = False

        # Server for addresses and transactions
        self.default_server = self.config.get('server')
        if not self.default_server:
            self.default_server = pick_random_server(self.protocol)

        self.irc_servers = [] # returned by interface (list from irc)
        self.pending_servers = set([])
        self.disconnected_servers = set([])
        self.recent_servers = self.config.get('recent_servers',[]) # successful connections

        self.banner = ''
        self.interface = None
        self.proxy = self.config.get('proxy')
        self.heights = {}
        self.merkle_roots = {}
        self.utxo_roots = {}
        self.server_lag = 0

        dir_path = os.path.join( self.config.path, 'certs')
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        # default subscriptions
        self.subscriptions = {}
        self.subscriptions[self.on_banner] = [('server.banner',[])]
        self.subscriptions[self.on_peers] = [('server.peers.subscribe',[])]
        self.pending_transactions_for_notifications = []


    def is_connected(self):
        return self.interface and self.interface.is_connected


    def is_up_to_date(self):
        return self.interface.is_up_to_date()


    def main_server(self):
        return self.interface.server


    def send_subscriptions(self):
        for cb, sub in self.subscriptions.items():
            self.interface.send(sub, cb)


    def subscribe(self, messages, callback):
        with self.lock:
            if self.subscriptions.get(callback) is None: 
                self.subscriptions[callback] = []
            for message in messages:
                if message not in self.subscriptions[callback]:
                    self.subscriptions[callback].append(message)

        if self.is_connected():
            self.interface.send( messages, callback )


    def send(self, messages, callback):
        if self.is_connected():
            self.interface.send( messages, callback )
            return True
        else:
            return False


    def register_callback(self, event, callback):
        with self.lock:
            if not self.callbacks.get(event):
                self.callbacks[event] = []
            self.callbacks[event].append(callback)


    def trigger_callback(self, event):
        with self.lock:
            callbacks = self.callbacks.get(event,[])[:]
        if callbacks:
            [callback() for callback in callbacks]


    def random_server(self):
        choice_list = []
        l = filter_protocol(self.get_servers(), self.protocol)
        for s in l:
            if s in self.pending_servers or s in self.disconnected_servers or s in self.interfaces.keys():
#.........这里部分代码省略.........
开发者ID:MrBitKoin,项目名称:electrum,代码行数:103,代码来源:network.py

示例8: Network

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class Network(threading.Thread):

    def __init__(self, config = {}):
        threading.Thread.__init__(self)
        self.daemon = True
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.lock = threading.Lock()
        self.blockchain = Blockchain(self.config, self)
        self.interfaces = {}
        self.queue = Queue.Queue()
        self.callbacks = {}
        self.protocol = self.config.get('protocol','s')

        # Server for addresses and transactions
        self.default_server = self.config.get('server')
        if not self.default_server:
            self.default_server = pick_random_server(self.protocol)

        self.irc_servers = [] # returned by interface (list from irc)
        self.disconnected_servers = []
        self.recent_servers = self.config.get('recent_servers',[]) # successful connections

        self.banner = ''
        self.interface = None
        self.proxy = self.config.get('proxy')
        self.heights = {}
        self.server_lag = 0

        dir_path = os.path.join( self.config.path, 'certs')
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        # default subscriptions
        self.subscriptions = {}
        self.subscriptions[self.on_banner] = [('server.banner',[])]
        self.subscriptions[self.on_peers] = [('server.peers.subscribe',[])]


    def is_connected(self):
        return self.interface and self.interface.is_connected


    def send_subscriptions(self):
        for cb, sub in self.subscriptions.items():
            self.interface.send(sub, cb)


    def subscribe(self, messages, callback):
        with self.lock:
            if self.subscriptions.get(callback) is None: 
                self.subscriptions[callback] = []
            for message in messages:
                if message not in self.subscriptions[callback]:
                    self.subscriptions[callback].append(message)

        if self.interface and self.interface.is_connected:
            self.interface.send( messages, callback )


    def register_callback(self, event, callback):
        with self.lock:
            if not self.callbacks.get(event):
                self.callbacks[event] = []
            self.callbacks[event].append(callback)


    def trigger_callback(self, event):
        with self.lock:
            callbacks = self.callbacks.get(event,[])[:]
        if callbacks:
            [callback() for callback in callbacks]


    def random_server(self):
        choice_list = []
        l = filter_protocol(self.get_servers(), self.protocol)
        for s in l:
            if s in self.disconnected_servers or s in self.interfaces.keys():
                continue
            else:
                choice_list.append(s)
        
        if not choice_list: 
            if not self.interfaces:
                # we are probably offline, retry later
                self.disconnected_servers = []
            return
        
        server = random.choice( choice_list )
        return server


    def get_servers(self):
        out = self.irc_servers if self.irc_servers else DEFAULT_SERVERS
        for s in self.recent_servers:
            host, port, protocol = s.split(':')
            if host not in out:
                out[host] = { protocol:port }
        return out

#.........这里部分代码省略.........
开发者ID:genba,项目名称:electrum,代码行数:103,代码来源:network.py

示例9: NetworkProxy

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class NetworkProxy(threading.Thread):
    # connects to daemon
    # sends requests, runs callbacks

    def __init__(self, config = {}):
        threading.Thread.__init__(self)
        self.daemon = True
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.daemon_port = config.get('daemon_port', 8000)
        self.message_id = 0
        self.unanswered_requests = {}
        self.subscriptions = {}
        self.debug = False
        self.lock = threading.Lock()
        self.pending_transactions_for_notifications = []


    def start(self, start_daemon=False):
        daemon_started = False
        while True:
            try:
                self.socket.connect(('', self.daemon_port))
                threading.Thread.start(self)
                return True

            except socket.error:
                if not start_daemon:
                    return False

                elif not daemon_started:
                    print_stderr( "Starting daemon [%s]"%self.config.get('server'))
                    daemon_started = True
                    pid = os.fork()
                    if (pid == 0): # The first child.
                        os.chdir("/")
                        os.setsid()
                        os.umask(0)
                        pid2 = os.fork()
                        if (pid2 == 0):  # Second child
                            server = NetworkServer(self.config)
                            try:
                                server.main_loop()
                            except KeyboardInterrupt:
                                print "Ctrl C - Stopping server"
                            sys.exit(1)
                        sys.exit(0)
                else:
                    time.sleep(0.1)



    def parse_json(self, message):
        s = message.find('\n')
        if s==-1: 
            return None, message
        j = json.loads( message[0:s] )
        return j, message[s+1:]


    def run(self):
        # read responses and trigger callbacks
        message = ''
        while True:
            try:
                data = self.socket.recv(1024)
            except:
                data = ''
            if not data:
                break

            message += data
            while True:
                response, message = self.parse_json(message)
                if response is not None: 
                    self.process(response)
                else:
                    break

        print "NetworkProxy: exiting"


    def process(self, response):
        # runs callbacks
        if self.debug: print "<--", response

        msg_id = response.get('id')
        with self.lock: 
            method, params, callback = self.unanswered_requests.pop(msg_id)

        result = response.get('result')
        callback(None, {'method':method, 'params':params, 'result':result, 'id':msg_id})


    def subscribe(self, messages, callback):
        # detect if it is a subscription
        with self.lock:
            if self.subscriptions.get(callback) is None: 
                self.subscriptions[callback] = []
#.........这里部分代码省略.........
开发者ID:Geopay,项目名称:electrum-exe,代码行数:103,代码来源:daemon.py

示例10: NetworkProxy

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class NetworkProxy(util.DaemonThread):

    def __init__(self, socket, config=None):

        if config is None:
            config = {}  # Do not use mutables as default arguments!
        util.DaemonThread.__init__(self)
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.message_id = 0
        self.unanswered_requests = {}
        self.subscriptions = {}
        self.debug = False
        self.lock = threading.Lock()
        self.callbacks = {}

        if socket:
            self.pipe = util.SocketPipe(socket)
            self.network = None
        else:
            self.pipe = util.QueuePipe()
            self.network = Network(self.pipe, config)
            self.network.start()
            for key in ['fee','status','banner','updated','servers','interfaces']:
                value = self.network.get_status_value(key)
                self.pipe.get_queue.put({'method':'network.status', 'params':[key, value]})

        # status variables
        self.status = 'unknown'
        self.servers = {}
        self.banner = ''
        self.blockchain_height = 0
        self.server_height = 0
        self.interfaces = []
        # value returned by estimatefee
        self.fee = None


    def run(self):
        while self.is_running():
            self.run_jobs()    # Synchronizer and Verifier
            try:
                response = self.pipe.get()
            except util.timeout:
                continue
            if response is None:
                break
            # Protect against ill-formed or malicious server responses
            try:
                self.process(response)
            except:
                traceback.print_exc(file=sys.stderr)
        self.trigger_callback('stop')
        if self.network:
            self.network.stop()
        self.print_error("stopped")

    def process(self, response):
        if self.debug:
            self.print_error("<--", response)

        if response.get('method') == 'network.status':
            key, value = response.get('params')
            if key == 'status':
                self.status = value
            elif key == 'banner':
                self.banner = value
            elif key == 'fee':
                self.fee = value
            elif key == 'updated':
                self.blockchain_height, self.server_height = value
            elif key == 'servers':
                self.servers = value
            elif key == 'interfaces':
                self.interfaces = value
            if key in ['status', 'updated']:
                self.trigger_callback(key)
            else:
                self.trigger_callback(key, (value,))
            return

        msg_id = response.get('id')
        result = response.get('result')
        error = response.get('error')
        if msg_id is not None:
            with self.lock:
                method, params, callback = self.unanswered_requests.pop(msg_id)
        else:
            method = response.get('method')
            params = response.get('params')
            with self.lock:
                for k,v in self.subscriptions.items():
                    if (method, params) in v:
                        callback = k
                        break
                else:
                    self.print_error("received unexpected notification",
                                     method, params)
                    return

        r = {'method':method, 'params':params, 'result':result,
#.........这里部分代码省略.........
开发者ID:keepkey,项目名称:electrum,代码行数:103,代码来源:network_proxy.py

示例11: Network

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class Network(util.DaemonThread):
    """The Network class manages a set of connections to remote electrum
    servers, each connected socket is handled by an Interface() object.
    Connections are initiated by a Connection() thread which stops once
    the connection succeeds or fails.

    Our external API:

    - Member functions get_header(), get_interfaces(), get_local_height(),
          get_parameters(), get_server_height(), get_status_value(),
          is_connected(), new_blockchain_height(), set_parameters(),
          stop()
    """

    def __init__(self, config=None, plugins=None):
        if config is None:
            config = {}  # Do not use mutables as default values!
        util.DaemonThread.__init__(self)
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.num_server = 8 if not self.config.get('oneserver') else 0
        self.blockchain = Blockchain(self.config, self)
        # A deque of interface header requests, processed left-to-right
        self.bc_requests = deque()
        # Server for addresses and transactions
        self.default_server = self.config.get('server')
        # Sanitize default server
        try:
            deserialize_server(self.default_server)
        except:
            self.default_server = None
        if not self.default_server:
            self.default_server = pick_random_server()

        self.lock = Lock()
        self.pending_sends = []
        self.message_id = 0
        self.debug = False
        self.irc_servers = {} # returned by interface (list from irc)
        self.recent_servers = self.read_recent_servers()

        self.banner = ''
        self.fee = None
        self.heights = {}
        self.merkle_roots = {}
        self.utxo_roots = {}
        self.subscriptions = defaultdict(list)
        self.callbacks = defaultdict(list)

        dir_path = os.path.join( self.config.path, 'certs')
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        # subscriptions and requests
        self.subscribed_addresses = set()
        # Requests from client we've not seen a response to
        self.unanswered_requests = {}
        # retry times
        self.server_retry_time = time.time()
        self.nodes_retry_time = time.time()
        # kick off the network.  interface is the main server we are currently
        # communicating with.  interfaces is the set of servers we are connecting
        # to or have an ongoing connection with
        self.interface = None
        self.interfaces = {}
        self.auto_connect = self.config.get('auto_connect', False)
        self.connecting = set()
        self.socket_queue = Queue.Queue()
        self.start_network(deserialize_server(self.default_server)[2],
                           deserialize_proxy(self.config.get('proxy')))
        self.plugins = plugins
        if self.plugins:
            self.plugins.set_network(self)

    def register_callback(self, event, callback):
        with self.lock:
            self.callbacks[event].append(callback)

    def trigger_callback(self, event, *args):
        with self.lock:
            callbacks = self.callbacks[event][:]
        [callback(*args) for callback in callbacks]

    def read_recent_servers(self):
        if not self.config.path:
            return []
        path = os.path.join(self.config.path, "recent_servers")
        try:
            with open(path, "r") as f:
                data = f.read()
                return json.loads(data)
        except:
            return []

    def save_recent_servers(self):
        if not self.config.path:
            return
        path = os.path.join(self.config.path, "recent_servers")
        s = json.dumps(self.recent_servers, indent=4, sort_keys=True)
        try:
            with open(path, "w") as f:
#.........这里部分代码省略.........
开发者ID:huanghao2008,项目名称:electrum-grs,代码行数:103,代码来源:network.py

示例12: Network

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class Network(util.DaemonThread):
    """The Network class manages a set of connections to remote electrum
    servers, each connected socket is handled by an Interface() object.
    Connections are initiated by a Connection() thread which stops once
    the connection succeeds or fails.

    Our external API:

    - Member functions get_header(), get_interfaces(), get_local_height(),
          get_parameters(), get_server_height(), get_status_value(),
          is_connected(), set_parameters(), stop()
    """

    def __init__(self, config=None):
        if config is None:
            config = {}  # Do not use mutables as default values!
        util.DaemonThread.__init__(self)
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.num_server = 10 if not self.config.get('oneserver') else 0
        self.blockchains = read_blockchains(self.config)
        self.print_error("blockchains", self.blockchains.keys())
        self.blockchain_index = config.get('blockchain_index', 0)
        if self.blockchain_index not in self.blockchains.keys():
            self.blockchain_index = 0
        # Server for addresses and transactions
        self.default_server = self.config.get('server')
        # Sanitize default server
        try:
            deserialize_server(self.default_server)
        except:
            self.default_server = None
        if not self.default_server:
            self.default_server = pick_random_server()

        self.lock = threading.Lock()
        self.pending_sends = []
        self.message_id = 0
        self.debug = False
        self.irc_servers = {} # returned by interface (list from irc)
        self.recent_servers = self.read_recent_servers()

        self.banner = ''
        self.donation_address = ''
        self.relay_fee = None
        self.headers = {}
        # callbacks passed with subscriptions
        self.subscriptions = defaultdict(list)
        self.sub_cache = {}
        # callbacks set by the GUI
        self.callbacks = defaultdict(list)

        dir_path = os.path.join( self.config.path, 'certs')
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        # subscriptions and requests
        self.subscribed_addresses = set()
        # Requests from client we've not seen a response to
        self.unanswered_requests = {}
        # retry times
        self.server_retry_time = time.time()
        self.nodes_retry_time = time.time()
        # kick off the network.  interface is the main server we are currently
        # communicating with.  interfaces is the set of servers we are connecting
        # to or have an ongoing connection with
        self.interface = None
        self.interfaces = {}
        self.auto_connect = self.config.get('auto_connect', True)
        self.connecting = set()
        self.socket_queue = Queue.Queue()
        self.start_network(deserialize_server(self.default_server)[2],
                           deserialize_proxy(self.config.get('proxy')))

    def register_callback(self, callback, events):
        with self.lock:
            for event in events:
                self.callbacks[event].append(callback)

    def unregister_callback(self, callback):
        with self.lock:
            for callbacks in self.callbacks.values():
                if callback in callbacks:
                    callbacks.remove(callback)

    def trigger_callback(self, event, *args):
        with self.lock:
            callbacks = self.callbacks[event][:]
        [callback(event, *args) for callback in callbacks]

    def read_recent_servers(self):
        if not self.config.path:
            return []
        path = os.path.join(self.config.path, "recent_servers")
        try:
            with open(path, "r") as f:
                data = f.read()
                return json.loads(data)
        except:
            return []

#.........这里部分代码省略.........
开发者ID:samedjukic,项目名称:electrum,代码行数:103,代码来源:network.py

示例13: Network

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class Network(util.DaemonThread):
    """The Network class manages a set of connections to remote electrum
    servers, each connected socket is handled by an Interface() object.
    Connections are initiated by a Connection() thread which stops once
    the connection succeeds or fails.

    Our external API:

    - Member functions get_header(), get_parameters(), get_status_value(),
                       new_blockchain_height(), set_parameters(), start(),
                       stop()
    """

    def __init__(self, pipe, config=None):
        if config is None:
            config = {}  # Do not use mutables as default values!
        util.DaemonThread.__init__(self)
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.num_server = 8 if not self.config.get('oneserver') else 0
        self.blockchain = Blockchain(self.config, self)
        self.requests_queue = pipe.send_queue
        self.response_queue = pipe.get_queue
        # A deque of interface header requests, processed left-to-right
        self.bc_requests = deque()
        # Server for addresses and transactions
        self.default_server = self.config.get('server')
        # Sanitize default server
        try:
            deserialize_server(self.default_server)
        except:
            self.default_server = None
        if not self.default_server:
            self.default_server = pick_random_server()

        self.irc_servers = {} # returned by interface (list from irc)
        self.recent_servers = self.read_recent_servers()

        self.banner = ''
        self.fee = None
        self.heights = {}
        self.merkle_roots = {}
        self.utxo_roots = {}

        dir_path = os.path.join( self.config.path, 'certs')
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        # subscriptions and requests
        self.subscribed_addresses = set()
        # cached address status
        self.addr_responses = {}
        # Requests from client we've not seen a response to
        self.unanswered_requests = {}
        # retry times
        self.server_retry_time = time.time()
        self.nodes_retry_time = time.time()
        # kick off the network.  interface is the main server we are currently
        # communicating with.  interfaces is the set of servers we are connecting
        # to or have an ongoing connection with
        self.interface = None
        self.interfaces = {}
        self.auto_connect = self.config.get('auto_connect', False)
        self.connecting = {}
        self.socket_queue = Queue.Queue()
        self.start_network(deserialize_server(self.default_server)[2],
                           deserialize_proxy(self.config.get('proxy')))

    def read_recent_servers(self):
        if not self.config.path:
            return []
        path = os.path.join(self.config.path, "recent_servers")
        try:
            with open(path, "r") as f:
                data = f.read()
                return json.loads(data)
        except:
            return []

    def save_recent_servers(self):
        if not self.config.path:
            return
        path = os.path.join(self.config.path, "recent_servers")
        s = json.dumps(self.recent_servers, indent=4, sort_keys=True)
        try:
            with open(path, "w") as f:
                f.write(s)
        except:
            pass

    def get_server_height(self):
        return self.heights.get(self.default_server, 0)

    def server_is_lagging(self):
        sh = self.get_server_height()
        if not sh:
            self.print_error('no height for main interface')
            return False
        lh = self.get_local_height()
        result = (lh - sh) > 1
        if result:
#.........这里部分代码省略.........
开发者ID:keepkey,项目名称:electrum,代码行数:103,代码来源:network.py

示例14: NetworkProxy

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class NetworkProxy(util.DaemonThread):
    """Proxy for communicating with the daemon or Network.

    If the daemon is running when this is initialized,
    this will create a socket pipe.
    Otherwise, this will create a new Network instance."""

    def __init__(self, socket, config=None):

        if config is None:
            config = {}  # Do not use mutables as default arguments!
        util.DaemonThread.__init__(self)
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.message_id = 0
        self.unanswered_requests = {}
        self.subscriptions = {}
        self.debug = False
        self.lock = threading.Lock()
        self.pending_transactions_for_notifications = []
        self.callbacks = {}

        if socket:
            self.pipe = util.SocketPipe(socket)
            self.network = None
        else:
            self.pipe = util.QueuePipe()
            self.network = Network(self.pipe, config)
            self.network.start()
            for key in ['status','banner','updated','servers','interfaces']:
                value = self.network.get_status_value(key)
                self.pipe.get_queue.put({'method':'network.status', 'params':[key, value]})

        # status variables
        self.status = 'connecting'
        self.servers = {}
        self.banner = ''
        self.blockchain_height = 0
        self.server_height = 0
        self.interfaces = []

    def switch_to_active_chain(self):
        """Create a new Network instance or send message to daemon."""
        with self.lock:
            # for the network.switch_chains request
            message_id = self.message_id

            self.message_id = 0
            self.unanswered_requests = {}
            self.subscriptions = {}
            self.pending_transactions_for_notifications = []
            self.callbacks = {}

            self.status = 'connecting'
            self.servers = {}
            self.banner = ''
            self.blockchain_height = 0
            self.server_height = 0
            self.interfaces = []

            # Not daemon, probably running GUI
            if self.network:
                self.network.switch_chains()

                for key in ['status','banner','updated','servers','interfaces']:
                    value = self.network.get_status_value(key)
                    self.pipe.get_queue.put({'method':'network.status', 'params':[key, value]})
            # Daemon is running
            else:
                req = {'id': message_id, 'method': 'network.switch_chains', 'params':[chainparams.get_active_chain().code]}
                self.pipe.send(req)


    def run(self):
        while self.is_running():
            try:
                response = self.pipe.get()
            except util.timeout:
                continue
            if response is None:
                break
            self.process(response)

        self.trigger_callback('stop')
        if self.network:
            self.network.stop()
        self.print_error("stopped")

    def process(self, response):
        if self.debug:
            print_error("<--", response)

        if response.get('method') == 'network.status':
            key, value = response.get('params')
            if key == 'status':
                self.status = value
            elif key == 'banner':
                self.banner = value
            elif key == 'updated':
                self.blockchain_height, self.server_height = value
            elif key == 'servers':
#.........这里部分代码省略.........
开发者ID:martexcoin,项目名称:encompass,代码行数:103,代码来源:network_proxy.py

示例15: Network

# 需要导入模块: from simple_config import SimpleConfig [as 别名]
# 或者: from simple_config.SimpleConfig import get [as 别名]
class Network(threading.Thread):

    def __init__(self, config=None):
        if config is None:
            config = {}  # Do not use mutables as default values!
        threading.Thread.__init__(self)
        self.daemon = True
        self.config = SimpleConfig(config) if type(config) == type({}) else config
        self.lock = threading.Lock()
        self.num_server = 8 if not self.config.get('oneserver') else 0
        self.blockchain = Blockchain(self.config, self)
        self.interfaces = {}
        self.queue = Queue.Queue()
        self.protocol = self.config.get('protocol','s')
        self.running = False

        # Server for addresses and transactions
        self.default_server = self.config.get('server')
        if not self.default_server:
            self.default_server = pick_random_server(self.protocol)

        self.irc_servers = {} # returned by interface (list from irc)

        self.disconnected_servers = set([])
        self.disconnected_time = time.time()

        self.recent_servers = self.config.get('recent_servers',[]) # successful connections
        self.pending_servers = set()

        self.banner = ''
        self.interface = None
        self.proxy = self.config.get('proxy')
        self.heights = {}
        self.merkle_roots = {}
        self.utxo_roots = {}

        dir_path = os.path.join( self.config.path, 'certs')
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        # address subscriptions and cached results
        self.addresses = {} 
        self.connection_status = 'connecting'
        self.requests_queue = Queue.Queue()


    def get_server_height(self):
        return self.heights.get(self.default_server,0)

    def server_is_lagging(self):
        h = self.get_server_height()
        if not h:
            print_error('no height for main interface')
            return False
        lag = self.get_local_height() - self.get_server_height()
        return lag > 1

    def set_status(self, status):
        self.connection_status = status
        self.notify('status')

    def is_connected(self):
        return self.interface and self.interface.is_connected

    def send_subscriptions(self):
        for addr in self.addresses:
            self.interface.send_request({'method':'blockchain.address.subscribe', 'params':[addr]})
        self.interface.send_request({'method':'server.banner','params':[]})
        self.interface.send_request({'method':'server.peers.subscribe','params':[]})

    def get_status_value(self, key):
        if key == 'status':
            value = self.connection_status
        elif key == 'banner':
            value = self.banner
        elif key == 'updated':
            value = (self.get_local_height(), self.get_server_height())
        elif key == 'servers':
            value = self.get_servers()
        elif key == 'interfaces':
            value = self.get_interfaces()
        return value

    def notify(self, key):
        value = self.get_status_value(key)
        self.response_queue.put({'method':'network.status', 'params':[key, value]})

    def random_server(self):
        choice_list = []
        l = filter_protocol(self.get_servers(), self.protocol)
        for s in l:
            if s in self.pending_servers or s in self.disconnected_servers or s in self.interfaces.keys():
                continue
            else:
                choice_list.append(s)
        
        if not choice_list: 
            return
        
        server = random.choice( choice_list )
#.........这里部分代码省略.........
开发者ID:ixcoin123,项目名称:electrum-ixc,代码行数:103,代码来源:network.py


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