2022-06-02 03:51:11 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2022-06-02 04:02:41 +00:00
|
|
|
"time"
|
|
|
|
|
2022-06-02 03:51:11 +00:00
|
|
|
"github.com/libp2p/go-libp2p"
|
2022-08-25 18:20:41 +00:00
|
|
|
inet "github.com/libp2p/go-libp2p/core/network"
|
2022-06-02 03:51:11 +00:00
|
|
|
"github.com/urfave/cli/v2"
|
2022-06-14 15:00:51 +00:00
|
|
|
|
|
|
|
cborutil "github.com/filecoin-project/go-cbor-util"
|
|
|
|
|
|
|
|
lcli "github.com/filecoin-project/lotus/cli"
|
|
|
|
"github.com/filecoin-project/lotus/node/hello"
|
2022-06-02 03:51:11 +00:00
|
|
|
)
|
|
|
|
|
2022-06-02 08:49:59 +00:00
|
|
|
var resultCh chan bool
|
|
|
|
|
2022-06-02 03:51:11 +00:00
|
|
|
var helloCmd = &cli.Command{
|
|
|
|
Name: "hello",
|
|
|
|
Description: "Get remote peer hello message by multiaddr",
|
2022-06-02 09:22:43 +00:00
|
|
|
ArgsUsage: "[peerMultiaddr|minerActorAddress]",
|
2022-06-02 03:51:11 +00:00
|
|
|
Action: func(cctx *cli.Context) error {
|
|
|
|
ctx := lcli.ReqContext(cctx)
|
2022-06-02 08:49:59 +00:00
|
|
|
resultCh = make(chan bool, 1)
|
|
|
|
pis, err := lcli.AddrInfoFromArg(ctx, cctx)
|
2022-06-02 03:51:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-06-02 08:36:18 +00:00
|
|
|
h, err := libp2p.New()
|
2022-06-02 04:02:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-06-02 11:59:52 +00:00
|
|
|
h.SetStreamHandler(hello.ProtocolID, HandleStream)
|
2022-06-02 03:51:11 +00:00
|
|
|
err = h.Connect(ctx, pis[0])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-06-02 09:09:35 +00:00
|
|
|
ctx, done := context.WithTimeout(ctx, 5*time.Second)
|
2022-06-02 08:49:59 +00:00
|
|
|
defer done()
|
|
|
|
select {
|
|
|
|
case <-resultCh:
|
|
|
|
case <-ctx.Done():
|
|
|
|
fmt.Println("can't get hello message, please try again")
|
|
|
|
}
|
2022-06-02 03:51:11 +00:00
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
func HandleStream(s inet.Stream) {
|
|
|
|
var hmsg hello.HelloMessage
|
2024-05-14 10:12:03 +00:00
|
|
|
_ = s.SetReadDeadline(time.Now().Add(30 * time.Second))
|
2022-06-02 03:51:11 +00:00
|
|
|
if err := cborutil.ReadCborRPC(s, &hmsg); err != nil {
|
|
|
|
log.Infow("failed to read hello message, disconnecting", "error", err)
|
|
|
|
_ = s.Conn().Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
data, err := json.Marshal(hmsg)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
fmt.Println(string(data))
|
2022-06-02 08:49:59 +00:00
|
|
|
resultCh <- true
|
2022-06-02 03:51:11 +00:00
|
|
|
}
|