1 // Copyright (c) 2015-2016 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
12 "github.com/btcsuite/btcd/chaincfg"
13 "github.com/btcsuite/btcd/peer"
14 "github.com/btcsuite/btcd/wire"
17 // mockRemotePeer creates a basic inbound peer listening on the simnet port for
18 // use with Example_peerConnection. It does not return until the listner is
20 func mockRemotePeer() error {
21 // Configure peer to act as a simnet node that offers no services.
22 peerCfg := &peer.Config{
23 UserAgentName: "peer", // User agent name to advertise.
24 UserAgentVersion: "1.0.0", // User agent version to advertise.
25 ChainParams: &chaincfg.SimNetParams,
28 // Accept connections on the simnet port.
29 listener, err := net.Listen("tcp", "127.0.0.1:18555")
34 conn, err := listener.Accept()
36 fmt.Printf("Accept: error %v\n", err)
40 // Create and start the inbound peer.
41 p := peer.NewInboundPeer(peerCfg)
42 p.AssociateConnection(conn)
48 // This example demonstrates the basic process for initializing and creating an
49 // outbound peer. Peers negotiate by exchanging version and verack messages.
50 // For demonstration, a simple handler for version message is attached to the
52 func Example_newOutboundPeer() {
53 // Ordinarily this will not be needed since the outbound peer will be
54 // connecting to a remote peer, however, since this example is executed
55 // and tested, a mock remote peer is needed to listen for the outbound
57 if err := mockRemotePeer(); err != nil {
58 fmt.Printf("mockRemotePeer: unexpected error %v\n", err)
62 // Create an outbound peer that is configured to act as a simnet node
63 // that offers no services and has listeners for the version and verack
64 // messages. The verack listener is used here to signal the code below
65 // when the handshake has been finished by signalling a channel.
66 verack := make(chan struct{})
67 peerCfg := &peer.Config{
68 UserAgentName: "peer", // User agent name to advertise.
69 UserAgentVersion: "1.0.0", // User agent version to advertise.
70 ChainParams: &chaincfg.SimNetParams,
72 Listeners: peer.MessageListeners{
73 OnVersion: func(p *peer.Peer, msg *wire.MsgVersion) {
74 fmt.Println("outbound: received version")
76 OnVerAck: func(p *peer.Peer, msg *wire.MsgVerAck) {
81 p, err := peer.NewOutboundPeer(peerCfg, "127.0.0.1:18555")
83 fmt.Printf("NewOutboundPeer: error %v\n", err)
87 // Establish the connection to the peer address and mark it connected.
88 conn, err := net.Dial("tcp", p.Addr())
90 fmt.Printf("net.Dial: error %v\n", err)
93 p.AssociateConnection(conn)
95 // Wait for the verack message or timeout in case of failure.
98 case <-time.After(time.Second * 1):
99 fmt.Printf("Example_peerConnection: verack timeout")
102 // Disconnect the peer.
104 p.WaitForDisconnect()
107 // outbound: received version