github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/p2p/simulations/network.go (about) 1 2 //此源码被清华学神尹成大魔王专业翻译分析并修改 3 //尹成QQ77025077 4 //尹成微信18510341407 5 //尹成所在QQ群721929980 6 //尹成邮箱 yinc13@mails.tsinghua.edu.cn 7 //尹成毕业于清华大学,微软区块链领域全球最有价值专家 8 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 9 //版权所有2017 Go Ethereum作者 10 //此文件是Go以太坊库的一部分。 11 // 12 //Go-Ethereum库是免费软件:您可以重新分发它和/或修改 13 //根据GNU发布的较低通用公共许可证的条款 14 //自由软件基金会,或者许可证的第3版,或者 15 //(由您选择)任何更高版本。 16 // 17 //Go以太坊图书馆的发行目的是希望它会有用, 18 //但没有任何保证;甚至没有 19 //适销性或特定用途的适用性。见 20 //GNU较低的通用公共许可证,了解更多详细信息。 21 // 22 //你应该收到一份GNU较低级别的公共许可证副本 23 //以及Go以太坊图书馆。如果没有,请参见<http://www.gnu.org/licenses/>。 24 25 package simulations 26 27 import ( 28 "bytes" 29 "context" 30 "encoding/json" 31 "fmt" 32 "sync" 33 "time" 34 35 "github.com/ethereum/go-ethereum/event" 36 "github.com/ethereum/go-ethereum/log" 37 "github.com/ethereum/go-ethereum/p2p" 38 "github.com/ethereum/go-ethereum/p2p/discover" 39 "github.com/ethereum/go-ethereum/p2p/simulations/adapters" 40 ) 41 42 var DialBanTimeout = 200 * time.Millisecond 43 44 //networkconfig定义用于启动网络的配置选项 45 type NetworkConfig struct { 46 ID string `json:"id"` 47 DefaultService string `json:"default_service,omitempty"` 48 } 49 50 //网络模型一个P2P仿真网络,它由一组 51 //模拟节点及其之间存在的连接。 52 // 53 //网络有一个单独的节点适配器,它实际上负责 54 //启动节点并将它们连接在一起。 55 // 56 //当节点启动和停止时,网络会发出事件 57 //连接和断开连接,以及在节点之间发送消息时。 58 type Network struct { 59 NetworkConfig 60 61 Nodes []*Node `json:"nodes"` 62 nodeMap map[discover.NodeID]int 63 64 Conns []*Conn `json:"conns"` 65 connMap map[string]int 66 67 nodeAdapter adapters.NodeAdapter 68 events event.Feed 69 lock sync.RWMutex 70 quitc chan struct{} 71 } 72 73 //newnetwork返回使用给定nodeadapter和networkconfig的网络 74 func NewNetwork(nodeAdapter adapters.NodeAdapter, conf *NetworkConfig) *Network { 75 return &Network{ 76 NetworkConfig: *conf, 77 nodeAdapter: nodeAdapter, 78 nodeMap: make(map[discover.NodeID]int), 79 connMap: make(map[string]int), 80 quitc: make(chan struct{}), 81 } 82 } 83 84 //事件返回网络的输出事件源。 85 func (net *Network) Events() *event.Feed { 86 return &net.events 87 } 88 89 //new node with config使用给定的配置向网络添加新节点, 90 //如果已存在具有相同ID或名称的节点,则返回错误 91 func (net *Network) NewNodeWithConfig(conf *adapters.NodeConfig) (*Node, error) { 92 net.lock.Lock() 93 defer net.lock.Unlock() 94 95 if conf.Reachable == nil { 96 conf.Reachable = func(otherID discover.NodeID) bool { 97 _, err := net.InitConn(conf.ID, otherID) 98 if err != nil && bytes.Compare(conf.ID.Bytes(), otherID.Bytes()) < 0 { 99 return false 100 } 101 return true 102 } 103 } 104 105 //检查节点是否已存在 106 if node := net.getNode(conf.ID); node != nil { 107 return nil, fmt.Errorf("node with ID %q already exists", conf.ID) 108 } 109 if node := net.getNodeByName(conf.Name); node != nil { 110 return nil, fmt.Errorf("node with name %q already exists", conf.Name) 111 } 112 113 //如果未配置任何服务,请使用默认服务 114 if len(conf.Services) == 0 { 115 conf.Services = []string{net.DefaultService} 116 } 117 118 //使用nodeadapter创建节点 119 adapterNode, err := net.nodeAdapter.NewNode(conf) 120 if err != nil { 121 return nil, err 122 } 123 node := &Node{ 124 Node: adapterNode, 125 Config: conf, 126 } 127 log.Trace(fmt.Sprintf("node %v created", conf.ID)) 128 net.nodeMap[conf.ID] = len(net.Nodes) 129 net.Nodes = append(net.Nodes, node) 130 131 //发出“控制”事件 132 net.events.Send(ControlEvent(node)) 133 134 return node, nil 135 } 136 137 //config返回网络配置 138 func (net *Network) Config() *NetworkConfig { 139 return &net.NetworkConfig 140 } 141 142 //StartAll启动网络中的所有节点 143 func (net *Network) StartAll() error { 144 for _, node := range net.Nodes { 145 if node.Up { 146 continue 147 } 148 if err := net.Start(node.ID()); err != nil { 149 return err 150 } 151 } 152 return nil 153 } 154 155 //stopall停止网络中的所有节点 156 func (net *Network) StopAll() error { 157 for _, node := range net.Nodes { 158 if !node.Up { 159 continue 160 } 161 if err := net.Stop(node.ID()); err != nil { 162 return err 163 } 164 } 165 return nil 166 } 167 168 //Start用给定的ID启动节点 169 func (net *Network) Start(id discover.NodeID) error { 170 return net.startWithSnapshots(id, nil) 171 } 172 173 //StartWithSnapshots使用给定的ID启动节点 174 //快照 175 func (net *Network) startWithSnapshots(id discover.NodeID, snapshots map[string][]byte) error { 176 net.lock.Lock() 177 defer net.lock.Unlock() 178 node := net.getNode(id) 179 if node == nil { 180 return fmt.Errorf("node %v does not exist", id) 181 } 182 if node.Up { 183 return fmt.Errorf("node %v already up", id) 184 } 185 log.Trace(fmt.Sprintf("starting node %v: %v using %v", id, node.Up, net.nodeAdapter.Name())) 186 if err := node.Start(snapshots); err != nil { 187 log.Warn(fmt.Sprintf("start up failed: %v", err)) 188 return err 189 } 190 node.Up = true 191 log.Info(fmt.Sprintf("started node %v: %v", id, node.Up)) 192 193 net.events.Send(NewEvent(node)) 194 195 //订阅对等事件 196 client, err := node.Client() 197 if err != nil { 198 return fmt.Errorf("error getting rpc client for node %v: %s", id, err) 199 } 200 events := make(chan *p2p.PeerEvent) 201 sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents") 202 if err != nil { 203 return fmt.Errorf("error getting peer events for node %v: %s", id, err) 204 } 205 go net.watchPeerEvents(id, events, sub) 206 return nil 207 } 208 209 //WatchPeerEvents从给定通道读取对等事件并发出 210 //相应的网络事件 211 func (net *Network) watchPeerEvents(id discover.NodeID, events chan *p2p.PeerEvent, sub event.Subscription) { 212 defer func() { 213 sub.Unsubscribe() 214 215 //假设节点现在已关闭 216 net.lock.Lock() 217 defer net.lock.Unlock() 218 node := net.getNode(id) 219 if node == nil { 220 log.Error("Can not find node for id", "id", id) 221 return 222 } 223 node.Up = false 224 net.events.Send(NewEvent(node)) 225 }() 226 for { 227 select { 228 case event, ok := <-events: 229 if !ok { 230 return 231 } 232 peer := event.Peer 233 switch event.Type { 234 235 case p2p.PeerEventTypeAdd: 236 net.DidConnect(id, peer) 237 238 case p2p.PeerEventTypeDrop: 239 net.DidDisconnect(id, peer) 240 241 case p2p.PeerEventTypeMsgSend: 242 net.DidSend(id, peer, event.Protocol, *event.MsgCode) 243 244 case p2p.PeerEventTypeMsgRecv: 245 net.DidReceive(peer, id, event.Protocol, *event.MsgCode) 246 247 } 248 249 case err := <-sub.Err(): 250 if err != nil { 251 log.Error(fmt.Sprintf("error getting peer events for node %v", id), "err", err) 252 } 253 return 254 } 255 } 256 } 257 258 //stop停止具有给定ID的节点 259 func (net *Network) Stop(id discover.NodeID) error { 260 net.lock.Lock() 261 defer net.lock.Unlock() 262 node := net.getNode(id) 263 if node == nil { 264 return fmt.Errorf("node %v does not exist", id) 265 } 266 if !node.Up { 267 return fmt.Errorf("node %v already down", id) 268 } 269 if err := node.Stop(); err != nil { 270 return err 271 } 272 node.Up = false 273 log.Info(fmt.Sprintf("stop node %v: %v", id, node.Up)) 274 275 net.events.Send(ControlEvent(node)) 276 return nil 277 } 278 279 //connect通过调用“admin_addpeer”rpc将两个节点连接在一起 280 //方法,以便它连接到“另一个”节点 281 func (net *Network) Connect(oneID, otherID discover.NodeID) error { 282 log.Debug(fmt.Sprintf("connecting %s to %s", oneID, otherID)) 283 conn, err := net.InitConn(oneID, otherID) 284 if err != nil { 285 return err 286 } 287 client, err := conn.one.Client() 288 if err != nil { 289 return err 290 } 291 net.events.Send(ControlEvent(conn)) 292 return client.Call(nil, "admin_addPeer", string(conn.other.Addr())) 293 } 294 295 //断开连接通过调用“admin-removepeer”rpc断开两个节点的连接 296 //方法,以便它与“另一个”节点断开连接 297 func (net *Network) Disconnect(oneID, otherID discover.NodeID) error { 298 conn := net.GetConn(oneID, otherID) 299 if conn == nil { 300 return fmt.Errorf("connection between %v and %v does not exist", oneID, otherID) 301 } 302 if !conn.Up { 303 return fmt.Errorf("%v and %v already disconnected", oneID, otherID) 304 } 305 client, err := conn.one.Client() 306 if err != nil { 307 return err 308 } 309 net.events.Send(ControlEvent(conn)) 310 return client.Call(nil, "admin_removePeer", string(conn.other.Addr())) 311 } 312 313 //didconnect跟踪“一个”节点连接到“另一个”节点的事实 314 func (net *Network) DidConnect(one, other discover.NodeID) error { 315 net.lock.Lock() 316 defer net.lock.Unlock() 317 conn, err := net.getOrCreateConn(one, other) 318 if err != nil { 319 return fmt.Errorf("connection between %v and %v does not exist", one, other) 320 } 321 if conn.Up { 322 return fmt.Errorf("%v and %v already connected", one, other) 323 } 324 conn.Up = true 325 net.events.Send(NewEvent(conn)) 326 return nil 327 } 328 329 //didisconnect跟踪“one”节点与 330 //“其他”节点 331 func (net *Network) DidDisconnect(one, other discover.NodeID) error { 332 net.lock.Lock() 333 defer net.lock.Unlock() 334 conn := net.getConn(one, other) 335 if conn == nil { 336 return fmt.Errorf("connection between %v and %v does not exist", one, other) 337 } 338 if !conn.Up { 339 return fmt.Errorf("%v and %v already disconnected", one, other) 340 } 341 conn.Up = false 342 conn.initiated = time.Now().Add(-DialBanTimeout) 343 net.events.Send(NewEvent(conn)) 344 return nil 345 } 346 347 //didsend跟踪“sender”向“receiver”发送消息的事实 348 func (net *Network) DidSend(sender, receiver discover.NodeID, proto string, code uint64) error { 349 msg := &Msg{ 350 One: sender, 351 Other: receiver, 352 Protocol: proto, 353 Code: code, 354 Received: false, 355 } 356 net.events.Send(NewEvent(msg)) 357 return nil 358 } 359 360 //DidReceive跟踪“Receiver”从“Sender”收到消息的事实 361 func (net *Network) DidReceive(sender, receiver discover.NodeID, proto string, code uint64) error { 362 msg := &Msg{ 363 One: sender, 364 Other: receiver, 365 Protocol: proto, 366 Code: code, 367 Received: true, 368 } 369 net.events.Send(NewEvent(msg)) 370 return nil 371 } 372 373 //getnode获取具有给定ID的节点,如果该节点没有,则返回nil 374 //存在 375 func (net *Network) GetNode(id discover.NodeID) *Node { 376 net.lock.Lock() 377 defer net.lock.Unlock() 378 return net.getNode(id) 379 } 380 381 //getnode获取具有给定名称的节点,如果该节点执行此操作,则返回nil 382 //不存在 383 func (net *Network) GetNodeByName(name string) *Node { 384 net.lock.Lock() 385 defer net.lock.Unlock() 386 return net.getNodeByName(name) 387 } 388 389 //GetNodes返回现有节点 390 func (net *Network) GetNodes() (nodes []*Node) { 391 net.lock.Lock() 392 defer net.lock.Unlock() 393 394 nodes = append(nodes, net.Nodes...) 395 return nodes 396 } 397 398 func (net *Network) getNode(id discover.NodeID) *Node { 399 i, found := net.nodeMap[id] 400 if !found { 401 return nil 402 } 403 return net.Nodes[i] 404 } 405 406 func (net *Network) getNodeByName(name string) *Node { 407 for _, node := range net.Nodes { 408 if node.Config.Name == name { 409 return node 410 } 411 } 412 return nil 413 } 414 415 //getconn返回“一”和“另一”之间存在的连接 416 //无论哪个节点启动了连接 417 func (net *Network) GetConn(oneID, otherID discover.NodeID) *Conn { 418 net.lock.Lock() 419 defer net.lock.Unlock() 420 return net.getConn(oneID, otherID) 421 } 422 423 //getorCreateConn与getconn类似,但如果不相同,则创建连接 424 //已经存在 425 func (net *Network) GetOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) { 426 net.lock.Lock() 427 defer net.lock.Unlock() 428 return net.getOrCreateConn(oneID, otherID) 429 } 430 431 func (net *Network) getOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) { 432 if conn := net.getConn(oneID, otherID); conn != nil { 433 return conn, nil 434 } 435 436 one := net.getNode(oneID) 437 if one == nil { 438 return nil, fmt.Errorf("node %v does not exist", oneID) 439 } 440 other := net.getNode(otherID) 441 if other == nil { 442 return nil, fmt.Errorf("node %v does not exist", otherID) 443 } 444 conn := &Conn{ 445 One: oneID, 446 Other: otherID, 447 one: one, 448 other: other, 449 } 450 label := ConnLabel(oneID, otherID) 451 net.connMap[label] = len(net.Conns) 452 net.Conns = append(net.Conns, conn) 453 return conn, nil 454 } 455 456 func (net *Network) getConn(oneID, otherID discover.NodeID) *Conn { 457 label := ConnLabel(oneID, otherID) 458 i, found := net.connMap[label] 459 if !found { 460 return nil 461 } 462 return net.Conns[i] 463 } 464 465 //initconn(一个,另一个)为 466 //彼此对等,如果不存在则创建一个新的 467 //节点顺序无关紧要,即conn(i,j)==conn(j,i) 468 //它检查连接是否已经启动,以及节点是否正在运行 469 //注: 470 //它还检查最近是否有连接对等端的尝试 471 //这是欺骗,因为模拟被用作甲骨文并知道 472 //远程对等机尝试连接到一个节点,该节点随后将不会启动连接。 473 func (net *Network) InitConn(oneID, otherID discover.NodeID) (*Conn, error) { 474 net.lock.Lock() 475 defer net.lock.Unlock() 476 if oneID == otherID { 477 return nil, fmt.Errorf("refusing to connect to self %v", oneID) 478 } 479 conn, err := net.getOrCreateConn(oneID, otherID) 480 if err != nil { 481 return nil, err 482 } 483 if conn.Up { 484 return nil, fmt.Errorf("%v and %v already connected", oneID, otherID) 485 } 486 if time.Since(conn.initiated) < DialBanTimeout { 487 return nil, fmt.Errorf("connection between %v and %v recently attempted", oneID, otherID) 488 } 489 490 err = conn.nodesUp() 491 if err != nil { 492 log.Trace(fmt.Sprintf("nodes not up: %v", err)) 493 return nil, fmt.Errorf("nodes not up: %v", err) 494 } 495 log.Debug("InitConn - connection initiated") 496 conn.initiated = time.Now() 497 return conn, nil 498 } 499 500 //shutdown停止网络中的所有节点并关闭退出通道 501 func (net *Network) Shutdown() { 502 for _, node := range net.Nodes { 503 log.Debug(fmt.Sprintf("stopping node %s", node.ID().TerminalString())) 504 if err := node.Stop(); err != nil { 505 log.Warn(fmt.Sprintf("error stopping node %s", node.ID().TerminalString()), "err", err) 506 } 507 } 508 close(net.quitc) 509 } 510 511 //重置重置所有网络属性: 512 //emtpies节点和连接列表 513 func (net *Network) Reset() { 514 net.lock.Lock() 515 defer net.lock.Unlock() 516 517 //重新初始化映射 518 net.connMap = make(map[string]int) 519 net.nodeMap = make(map[discover.NodeID]int) 520 521 net.Nodes = nil 522 net.Conns = nil 523 } 524 525 //node是围绕adapters.node的包装器,用于跟踪状态 526 //网络中节点的 527 type Node struct { 528 adapters.Node `json:"-"` 529 530 //如果用于创建节点的配置 531 Config *adapters.NodeConfig `json:"config"` 532 533 //向上跟踪节点是否正在运行 534 Up bool `json:"up"` 535 } 536 537 //ID返回节点的ID 538 func (n *Node) ID() discover.NodeID { 539 return n.Config.ID 540 } 541 542 //字符串返回日志友好的字符串 543 func (n *Node) String() string { 544 return fmt.Sprintf("Node %v", n.ID().TerminalString()) 545 } 546 547 //nodeinfo返回有关节点的信息 548 func (n *Node) NodeInfo() *p2p.NodeInfo { 549 //如果节点尚未启动,请避免出现恐慌。 550 if n.Node == nil { 551 return nil 552 } 553 info := n.Node.NodeInfo() 554 info.Name = n.Config.Name 555 return info 556 } 557 558 //marshaljson实现json.marshaler接口,以便 559 //json包括nodeinfo 560 func (n *Node) MarshalJSON() ([]byte, error) { 561 return json.Marshal(struct { 562 Info *p2p.NodeInfo `json:"info,omitempty"` 563 Config *adapters.NodeConfig `json:"config,omitempty"` 564 Up bool `json:"up"` 565 }{ 566 Info: n.NodeInfo(), 567 Config: n.Config, 568 Up: n.Up, 569 }) 570 } 571 572 //conn表示网络中两个节点之间的连接 573 type Conn struct { 574 //一个是启动连接的节点 575 One discover.NodeID `json:"one"` 576 577 //另一个是连接到的节点 578 Other discover.NodeID `json:"other"` 579 580 //向上跟踪连接是否处于活动状态 581 Up bool `json:"up"` 582 //当连接被抓取拨号时注册 583 initiated time.Time 584 585 one *Node 586 other *Node 587 } 588 589 //nodes up返回两个节点当前是否都已启动 590 func (c *Conn) nodesUp() error { 591 if !c.one.Up { 592 return fmt.Errorf("one %v is not up", c.One) 593 } 594 if !c.other.Up { 595 return fmt.Errorf("other %v is not up", c.Other) 596 } 597 return nil 598 } 599 600 //字符串返回日志友好的字符串 601 func (c *Conn) String() string { 602 return fmt.Sprintf("Conn %v->%v", c.One.TerminalString(), c.Other.TerminalString()) 603 } 604 605 //msg表示网络中两个节点之间发送的P2P消息 606 type Msg struct { 607 One discover.NodeID `json:"one"` 608 Other discover.NodeID `json:"other"` 609 Protocol string `json:"protocol"` 610 Code uint64 `json:"code"` 611 Received bool `json:"received"` 612 } 613 614 //字符串返回日志友好的字符串 615 func (m *Msg) String() string { 616 return fmt.Sprintf("Msg(%d) %v->%v", m.Code, m.One.TerminalString(), m.Other.TerminalString()) 617 } 618 619 //connlabel生成表示连接的确定字符串 620 //两个节点之间,用于比较两个连接是否相同 621 //结点 622 func ConnLabel(source, target discover.NodeID) string { 623 var first, second discover.NodeID 624 if bytes.Compare(source.Bytes(), target.Bytes()) > 0 { 625 first = target 626 second = source 627 } else { 628 first = source 629 second = target 630 } 631 return fmt.Sprintf("%v-%v", first, second) 632 } 633 634 //快照表示网络在单个时间点的状态,可以 635 //用于恢复网络状态 636 type Snapshot struct { 637 Nodes []NodeSnapshot `json:"nodes,omitempty"` 638 Conns []Conn `json:"conns,omitempty"` 639 } 640 641 //nodesnapshot表示网络中节点的状态 642 type NodeSnapshot struct { 643 Node Node `json:"node,omitempty"` 644 645 //快照是从调用节点收集的任意数据。快照() 646 Snapshots map[string][]byte `json:"snapshots,omitempty"` 647 } 648 649 //快照创建网络快照 650 func (net *Network) Snapshot() (*Snapshot, error) { 651 net.lock.Lock() 652 defer net.lock.Unlock() 653 snap := &Snapshot{ 654 Nodes: make([]NodeSnapshot, len(net.Nodes)), 655 Conns: make([]Conn, len(net.Conns)), 656 } 657 for i, node := range net.Nodes { 658 snap.Nodes[i] = NodeSnapshot{Node: *node} 659 if !node.Up { 660 continue 661 } 662 snapshots, err := node.Snapshots() 663 if err != nil { 664 return nil, err 665 } 666 snap.Nodes[i].Snapshots = snapshots 667 } 668 for i, conn := range net.Conns { 669 snap.Conns[i] = *conn 670 } 671 return snap, nil 672 } 673 674 //加载加载网络快照 675 func (net *Network) Load(snap *Snapshot) error { 676 for _, n := range snap.Nodes { 677 if _, err := net.NewNodeWithConfig(n.Node.Config); err != nil { 678 return err 679 } 680 if !n.Node.Up { 681 continue 682 } 683 if err := net.startWithSnapshots(n.Node.Config.ID, n.Snapshots); err != nil { 684 return err 685 } 686 } 687 for _, conn := range snap.Conns { 688 689 if !net.GetNode(conn.One).Up || !net.GetNode(conn.Other).Up { 690 //在这种情况下,连接的至少一个节点没有启动, 691 //所以会导致快照“加载”失败 692 continue 693 } 694 if err := net.Connect(conn.One, conn.Other); err != nil { 695 return err 696 } 697 } 698 return nil 699 } 700 701 //订阅从通道读取控制事件并执行它们 702 func (net *Network) Subscribe(events chan *Event) { 703 for { 704 select { 705 case event, ok := <-events: 706 if !ok { 707 return 708 } 709 if event.Control { 710 net.executeControlEvent(event) 711 } 712 case <-net.quitc: 713 return 714 } 715 } 716 } 717 718 func (net *Network) executeControlEvent(event *Event) { 719 log.Trace("execute control event", "type", event.Type, "event", event) 720 switch event.Type { 721 case EventTypeNode: 722 if err := net.executeNodeEvent(event); err != nil { 723 log.Error("error executing node event", "event", event, "err", err) 724 } 725 case EventTypeConn: 726 if err := net.executeConnEvent(event); err != nil { 727 log.Error("error executing conn event", "event", event, "err", err) 728 } 729 case EventTypeMsg: 730 log.Warn("ignoring control msg event") 731 } 732 } 733 734 func (net *Network) executeNodeEvent(e *Event) error { 735 if !e.Node.Up { 736 return net.Stop(e.Node.ID()) 737 } 738 739 if _, err := net.NewNodeWithConfig(e.Node.Config); err != nil { 740 return err 741 } 742 return net.Start(e.Node.ID()) 743 } 744 745 func (net *Network) executeConnEvent(e *Event) error { 746 if e.Conn.Up { 747 return net.Connect(e.Conn.One, e.Conn.Other) 748 } else { 749 return net.Disconnect(e.Conn.One, e.Conn.Other) 750 } 751 }