以太坊原始碼分析(43)node原始碼分析

尹成發表於2018-05-14
node在go ethereum中代表了一個節點。 可能是全節點,可能是輕量級節點。 node可以理解為一個程式,以太坊由執行在世界各地的很多中型別的node組成。

一個典型的node就是一個p2p的節點。 執行了p2p網路協議,同時根據節點型別不同,執行了不同的業務層協議(以區別網路層協議。 參考p2p peer中的Protocol介面)。
    
node的結構。
    
    // Node is a container on which services can be registered.
    type Node struct {
        eventmux *event.TypeMux // Event multiplexer used between the services of a stack
        config *Config
        accman *accounts.Manager
    
        ephemeralKeystore string // if non-empty, the key directory that will be removed by Stop
        instanceDirLock flock.Releaser // prevents concurrent use of instance directory
    
        serverConfig p2p.Config
        server *p2p.Server // Currently running P2P networking layer
    
        serviceFuncs []ServiceConstructor // Service constructors (in dependency order)
        services map[reflect.Type]Service // Currently running services
    
        rpcAPIs []rpc.API // List of APIs currently provided by the node
        inprocHandler *rpc.Server // In-process RPC request handler to process the API requests
    
        ipcEndpoint string // IPC endpoint to listen at (empty = IPC disabled)
        ipcListener net.Listener // IPC RPC listener socket to serve API requests
        ipcHandler *rpc.Server // IPC RPC request handler to process the API requests
    
        httpEndpoint string // HTTP endpoint (interface + port) to listen at (empty = HTTP disabled)
        httpWhitelist []string // HTTP RPC modules to allow through this endpoint
        httpListener net.Listener // HTTP RPC listener socket to server API requests
        httpHandler *rpc.Server // HTTP RPC request handler to process the API requests
    
        wsEndpoint string // Websocket endpoint (interface + port) to listen at (empty = websocket disabled)
        wsListener net.Listener // Websocket RPC listener socket to server API requests
        wsHandler *rpc.Server // Websocket RPC request handler to process the API requests
    
        stop chan struct{} // Channel to wait for termination notifications
        lock sync.RWMutex
    }


節點的初始化, 節點的初始化並不依賴其他的外部元件, 只依賴一個Config物件。
    
    // New creates a new P2P node, ready for protocol registration.
    func New(conf *Config) (*Node, error) {
        // Copy config and resolve the datadir so future changes to the current
        // working directory don't affect the node.
        confCopy := *conf
        conf = &confCopy
        if conf.DataDir != "" { //轉化為絕對路徑。
            absdatadir, err := filepath.Abs(conf.DataDir)
            if err != nil {
                return nil, err
            }
            conf.DataDir = absdatadir
        }
        // Ensure that the instance name doesn't cause weird conflicts with
        // other files in the data directory.
        if strings.ContainsAny(conf.Name, `/\`) {
            return nil, errors.New(`Config.Name must not contain '/' or '\'`)
        }
        if conf.Name == datadirDefaultKeyStore {
            return nil, errors.New(`Config.Name cannot be "` + datadirDefaultKeyStore + `"`)
        }
        if strings.HasSuffix(conf.Name, ".ipc") {
            return nil, errors.New(`Config.Name cannot end in ".ipc"`)
        }
        // Ensure that the AccountManager method works before the node has started.
        // We rely on this in cmd/geth.
        am, ephemeralKeystore, err := makeAccountManager(conf)
        if err != nil {
            return nil, err
        }
        // Note: any interaction with Config that would create/touch files
        // in the data directory or instance directory is delayed until Start.
        return &Node{
            accman: am,
            ephemeralKeystore: ephemeralKeystore,
            config: conf,
            serviceFuncs: []ServiceConstructor{},
            ipcEndpoint: conf.IPCEndpoint(),
            httpEndpoint: conf.HTTPEndpoint(),
            wsEndpoint: conf.WSEndpoint(),
            eventmux: new(event.TypeMux),
        }, nil
    }


### node 服務和協議的註冊
因為node並沒有負責具體的業務邏輯。所以具體的業務邏輯是通過註冊的方式來註冊到node裡面來的。
其他模組通過Register方法來註冊了一個 服務建構函式。 使用這個服務建構函式可以生成服務。


    // Register injects a new service into the node's stack. The service created by
    // the passed constructor must be unique in its type with regard to sibling ones.
    func (n *Node) Register(constructor ServiceConstructor) error {
        n.lock.Lock()
        defer n.lock.Unlock()
    
        if n.server != nil {
            return ErrNodeRunning
        }
        n.serviceFuncs = append(n.serviceFuncs, constructor)
        return nil
    }

服務是什麼

    type ServiceConstructor func(ctx *ServiceContext) (Service, error)
    // Service is an individual protocol that can be registered into a node.
    //
    // Notes:
    //
    // • Service life-cycle management is delegated to the node. The service is allowed to
    // initialize itself upon creation, but no goroutines should be spun up outside of the
    // Start method.
    //
    // • Restart logic is not required as the node will create a fresh instance
    // every time a service is started.

    // 服務的生命週期管理已經代理給node管理。該服務允許在建立時自動初始化,但是在Start方法之外不應該啟動goroutines。
    // 重新啟動邏輯不是必需的,因為節點將在每次啟動服務時建立一個新的例項。
    type Service interface {
        // Protocols retrieves the P2P protocols the service wishes to start.
        // 服務希望提供的p2p協議
        Protocols() []p2p.Protocol
        
        // APIs retrieves the list of RPC descriptors the service provides
        // 服務希望提供的RPC方法的描述
        APIs() []rpc.API
    
        // Start is called after all services have been constructed and the networking
        // layer was also initialized to spawn any goroutines required by the service.
        // 所有服務已經構建完成後,呼叫開始,並且網路層也被初始化以產生服務所需的任何goroutine。
        Start(server *p2p.Server) error
    
        // Stop terminates all goroutines belonging to the service, blocking until they
        // are all terminated.
        
        // Stop方法會停止這個服務擁有的所有goroutine。 需要阻塞到所有的goroutine都已經終止
        Stop() error
    }


### node的啟動
node的啟動過程會建立和執行一個p2p的節點。

    // Start create a live P2P node and starts running it.
    func (n *Node) Start() error {
        n.lock.Lock()
        defer n.lock.Unlock()
    
        // Short circuit if the node's already running
        if n.server != nil {
            return ErrNodeRunning
        }
        if err := n.openDataDir(); err != nil {
            return err
        }
    
        // Initialize the p2p server. This creates the node key and
        // discovery databases.
        n.serverConfig = n.config.P2P
        n.serverConfig.PrivateKey = n.config.NodeKey()
        n.serverConfig.Name = n.config.NodeName()
        if n.serverConfig.StaticNodes == nil {
            // 處理配置檔案static-nodes.json
            n.serverConfig.StaticNodes = n.config.StaticNodes()
        }
        if n.serverConfig.TrustedNodes == nil {
            // 處理配置檔案trusted-nodes.json
            n.serverConfig.TrustedNodes = n.config.TrustedNodes()
        }
        if n.serverConfig.NodeDatabase == "" {
            n.serverConfig.NodeDatabase = n.config.NodeDB()
        }
        //建立了p2p伺服器
        running := &p2p.Server{Config: n.serverConfig}
        log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name)
    
        // Otherwise copy and specialize the P2P configuration
        services := make(map[reflect.Type]Service)
        for _, constructor := range n.serviceFuncs {
            // Create a new context for the particular service
            ctx := &ServiceContext{
                config: n.config,
                services: make(map[reflect.Type]Service),
                EventMux: n.eventmux,
                AccountManager: n.accman,
            }
            for kind, s := range services { // copy needed for threaded access
                ctx.services[kind] = s
            }
            // Construct and save the service
            // 建立所有註冊的服務。
            service, err := constructor(ctx)
            if err != nil {
                return err
            }
            kind := reflect.TypeOf(service)
            if _, exists := services[kind]; exists {
                return &DuplicateServiceError{Kind: kind}
            }
            services[kind] = service
        }
        // Gather the protocols and start the freshly assembled P2P server
        // 收集所有的p2p的protocols並插入p2p.Rrotocols
        for _, service := range services {
            running.Protocols = append(running.Protocols, service.Protocols()...)
        }
        // 啟動了p2p伺服器
        if err := running.Start(); err != nil {
            return convertFileLockError(err)
        }
        // Start each of the services
        // 啟動每一個服務
        started := []reflect.Type{}
        for kind, service := range services {
            // Start the next service, stopping all previous upon failure
            if err := service.Start(running); err != nil {
                for _, kind := range started {
                    services[kind].Stop()
                }
                running.Stop()
    
                return err
            }
            // Mark the service started for potential cleanup
            started = append(started, kind)
        }
        // Lastly start the configured RPC interfaces
        // 最後啟動RPC服務
        if err := n.startRPC(services); err != nil {
            for _, service := range services {
                service.Stop()
            }
            running.Stop()
            return err
        }
        // Finish initializing the startup
        n.services = services
        n.server = running
        n.stop = make(chan struct{})
    
        return nil
    }


startRPC,這個方法收集所有的apis。 並依次呼叫啟動各個RPC伺服器, 預設是啟動InProc和IPC。 如果指定也可以配置是否啟動HTTP和websocket。

    // startRPC is a helper method to start all the various RPC endpoint during node
    // startup. It's not meant to be called at any time afterwards as it makes certain
    // assumptions about the state of the node.
    func (n *Node) startRPC(services map[reflect.Type]Service) error {
        // Gather all the possible APIs to surface
        apis := n.apis()
        for _, service := range services {
            apis = append(apis, service.APIs()...)
        }
        // Start the various API endpoints, terminating all in case of errors
        if err := n.startInProc(apis); err != nil {
            return err
        }
        if err := n.startIPC(apis); err != nil {
            n.stopInProc()
            return err
        }
        if err := n.startHTTP(n.httpEndpoint, apis, n.config.HTTPModules, n.config.HTTPCors); err != nil {
            n.stopIPC()
            n.stopInProc()
            return err
        }
        if err := n.startWS(n.wsEndpoint, apis, n.config.WSModules, n.config.WSOrigins, n.config.WSExposeAll); err != nil {
            n.stopHTTP()
            n.stopIPC()
            n.stopInProc()
            return err
        }
        // All API endpoints started successfully
        n.rpcAPIs = apis
        return nil
    }


startXXX 是具體的RPC的啟動。 流程都是大同小異。 這裡就只看startWS了

    // startWS initializes and starts the websocket RPC endpoint.
    func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool) error {
        // Short circuit if the WS endpoint isn't being exposed
        if endpoint == "" {
            return nil
        }
        // Generate the whitelist based on the allowed modules
        // 生成白名單
        whitelist := make(map[string]bool)
        for _, module := range modules {
            whitelist[module] = true
        }
        // Register all the APIs exposed by the services
        handler := rpc.NewServer()
        for _, api := range apis {
            if exposeAll || whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
            // 只有這集中情況下才會把這個api進行註冊。
                if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
                    return err
                }
                log.Debug(fmt.Sprintf("WebSocket registered %T under '%s'", api.Service, api.Namespace))
            }
        }
        // All APIs registered, start the HTTP listener
        var (
            listener net.Listener
            err error
        )
        if listener, err = net.Listen("tcp", endpoint); err != nil {
            return err
        }
        go rpc.NewWSServer(wsOrigins, handler).Serve(listener)
        log.Info(fmt.Sprintf("WebSocket endpoint opened: ws://%s", listener.Addr()))
    
        // All listeners booted successfully
        n.wsEndpoint = endpoint
        n.wsListener = listener
        n.wsHandler = handler
    
        return nil

    }





網址:http://www.qukuailianxueyuan.io/



欲領取造幣技術與全套虛擬機器資料

區塊鏈技術交流QQ群:756146052  備註:CSDN

尹成學院微信:備註:CSDN



相關文章