main.go raw

   1  // Command nostrino-probe asks a gateway one question: can I open a tunnel to you, and what does
   2  // your node say? It is the cheapest liveness check that exercises the whole path a wallet uses,
   3  // so a monitor can tell "publishing announcements" from "actually serving".
   4  package main
   5  
   6  import (
   7  	"context"
   8  	"encoding/hex"
   9  	"encoding/json"
  10  	"errors"
  11  	"flag"
  12  	"fmt"
  13  	"net"
  14  	"os"
  15  	"time"
  16  
  17  	"git.smesh.lol/nostrino/pkg/chain"
  18  	"git.smesh.lol/nostrino/pkg/p2p"
  19  	"git.smesh.lol/nostrino/pkg/tunnel"
  20  )
  21  
  22  type probe struct {
  23  	OK        bool   `json:"ok"`
  24  	Chain     string `json:"chain"`
  25  	Gateway   string `json:"gateway"`
  26  	ElapsedMS int64  `json:"elapsed_ms"`
  27  	Error     string `json:"error,omitempty"`
  28  	Protocol  int32  `json:"protocol,omitempty"`
  29  	Services  uint64 `json:"services,omitempty"`
  30  	Tip       int32  `json:"tip,omitempty"`
  31  	UserAgent string `json:"user_agent,omitempty"`
  32  }
  33  
  34  func main() {
  35  	var (
  36  		relays    string
  37  		gateway   string
  38  		chainName = "blake"
  39  		transport = "btc"
  40  		timeout   = 20 * time.Second
  41  	)
  42  
  43  	flag.StringVar(&relays, "relay", "", "relay URL")
  44  	flag.StringVar(&gateway, "gateway", "", "gateway pubkey (hex)")
  45  	flag.StringVar(&chainName, "chain", chainName, "chain to ask the gateway for")
  46  	flag.StringVar(&transport, "transport", transport, "profile that supplies the P2P magic")
  47  	flag.DurationVar(&timeout, "timeout", timeout, "overall timeout")
  48  	flag.Parse()
  49  
  50  	out := probe{Chain: chainName, Gateway: gateway}
  51  
  52  	started := time.Now()
  53  
  54  	fail := func(err error) {
  55  		out.ElapsedMS = time.Since(started).Milliseconds()
  56  		out.Error = err.Error()
  57  		body, _ := json.Marshal(out)
  58  		fmt.Println(string(body))
  59  		os.Exit(1)
  60  	}
  61  
  62  	profile, err := chain.ByName(transport)
  63  
  64  	if err != nil {
  65  		fail(err)
  66  	}
  67  
  68  	if len(gateway) != 64 {
  69  		fail(errors.New("a 64-hex gateway pubkey is required"))
  70  	}
  71  
  72  	var key [32]byte
  73  
  74  	if _, err := hex.DecodeString(gateway); err != nil {
  75  		fail(err)
  76  	}
  77  
  78  	raw, _ := hex.DecodeString(gateway)
  79  	copy(key[:], raw)
  80  
  81  	list := splitList(relays)
  82  
  83  	if len(list) == 0 {
  84  		fail(errors.New("no relay"))
  85  	}
  86  
  87  	// A probe names its target, so it must dial that gateway and not whichever one discovery
  88  	// happens to return first: asking a different gateway and printing the requested key is how a
  89  	// monitor reports a dead gateway as healthy.
  90  	uri := &tunnel.URI{Gateway: key, Relays: list, Version: 1}
  91  
  92  	ctx, cancel := context.WithTimeout(context.Background(), timeout)
  93  	defer cancel()
  94  
  95  	conn, err := tunnel.Dial(ctx, tunnel.DialConfig{URI: uri, Key: key, Chain: chainName})
  96  
  97  	if err != nil {
  98  		fail(fmt.Errorf("tunnel: %w", err))
  99  	}
 100  
 101  	defer conn.Close()
 102  
 103  	peer := p2p.New(conn, p2p.Config{
 104  		Magic:     profile.Magic,
 105  		UserAgent: "/nostrino-probe:0.2/",
 106  		Services:  1 | 8,
 107  	})
 108  
 109  	version, err := peer.Handshake(ctx)
 110  
 111  	if err != nil {
 112  		fail(fmt.Errorf("handshake: %w", err))
 113  	}
 114  
 115  	out.OK = true
 116  	out.ElapsedMS = time.Since(started).Milliseconds()
 117  	out.Protocol = version.ProtocolVersion
 118  	out.Services = version.Services
 119  	out.Tip = version.LastBlock
 120  	out.UserAgent = version.UserAgent
 121  
 122  	body, _ := json.Marshal(out)
 123  	fmt.Println(string(body))
 124  }
 125  
 126  func splitList(value string) []string {
 127  	var out []string
 128  
 129  	for _, part := range stringSplit(value, ',') {
 130  		if part = trim(part); part != "" {
 131  			out = append(out, part)
 132  		}
 133  	}
 134  
 135  	return out
 136  }
 137  
 138  func stringSplit(value string, sep byte) []string {
 139  	var out []string
 140  
 141  	current := make([]byte, 0, len(value))
 142  
 143  	for i := 0; i < len(value); i++ {
 144  		if value[i] == sep {
 145  			out = append(out, string(current))
 146  			current = current[:0]
 147  
 148  			continue
 149  		}
 150  
 151  		current = append(current, value[i])
 152  	}
 153  
 154  	return append(out, string(current))
 155  }
 156  
 157  func trim(value string) string {
 158  	for len(value) > 0 && (value[0] == ' ' || value[0] == '\t') {
 159  		value = value[1:]
 160  	}
 161  
 162  	for len(value) > 0 && (value[len(value)-1] == ' ' || value[len(value)-1] == '\t') {
 163  		value = value[:len(value)-1]
 164  	}
 165  
 166  	return value
 167  }
 168  
 169  var _ = net.Dial
 170