github.com/linapex/ethereum-dpos-chinese@v0.0.0-20190316121959-b78b3a4a1ece/swarm/pss/ping.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 12:09:48</date>
    10  //</624342677931954176>
    11  
    12  //
    13  //
    14  //
    15  //
    16  //
    17  //
    18  //
    19  //
    20  //
    21  //
    22  //
    23  //
    24  //
    25  //
    26  //
    27  
    28  //
    29  
    30  package pss
    31  
    32  import (
    33  	"context"
    34  	"errors"
    35  	"time"
    36  
    37  	"github.com/ethereum/go-ethereum/p2p"
    38  	"github.com/ethereum/go-ethereum/p2p/protocols"
    39  	"github.com/ethereum/go-ethereum/swarm/log"
    40  )
    41  
    42  //
    43  //
    44  type PingMsg struct {
    45  	Created time.Time
    46  Pong    bool //
    47  }
    48  
    49  type Ping struct {
    50  Pong bool      //
    51  OutC chan bool //
    52  InC  chan bool //
    53  }
    54  
    55  func (p *Ping) pingHandler(ctx context.Context, msg interface{}) error {
    56  	var pingmsg *PingMsg
    57  	var ok bool
    58  	if pingmsg, ok = msg.(*PingMsg); !ok {
    59  		return errors.New("invalid msg")
    60  	}
    61  	log.Debug("ping handler", "msg", pingmsg, "outc", p.OutC)
    62  	if p.InC != nil {
    63  		p.InC <- pingmsg.Pong
    64  	}
    65  	if p.Pong && !pingmsg.Pong {
    66  		p.OutC <- true
    67  	}
    68  	return nil
    69  }
    70  
    71  var PingProtocol = &protocols.Spec{
    72  	Name:       "psstest",
    73  	Version:    1,
    74  	MaxMsgSize: 1024,
    75  	Messages: []interface{}{
    76  		PingMsg{},
    77  	},
    78  }
    79  
    80  var PingTopic = ProtocolTopic(PingProtocol)
    81  
    82  func NewPingProtocol(ping *Ping) *p2p.Protocol {
    83  	return &p2p.Protocol{
    84  		Name:    PingProtocol.Name,
    85  		Version: PingProtocol.Version,
    86  		Length:  uint64(PingProtocol.MaxMsgSize),
    87  		Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
    88  			quitC := make(chan struct{})
    89  			pp := protocols.NewPeer(p, rw, PingProtocol)
    90  			log.Trace("running pss vprotocol", "peer", p, "outc", ping.OutC)
    91  			go func() {
    92  				for {
    93  					select {
    94  					case ispong := <-ping.OutC:
    95  						pp.Send(context.TODO(), &PingMsg{
    96  							Created: time.Now(),
    97  							Pong:    ispong,
    98  						})
    99  					case <-quitC:
   100  					}
   101  				}
   102  			}()
   103  			err := pp.Run(ping.pingHandler)
   104  			quitC <- struct{}{}
   105  			return err
   106  		},
   107  	}
   108  }
   109