// Package litedial is the instance's one dialler, so the daemon, the gates and // the handshake tests all build the same connection. // // It exists because a test and the daemon disagreed about whether the same node // completes a BIP324 handshake: the test dialed with net.Dial and completed, the // daemon dialed with a context and did not. The connection is now built in one // place, so a disagreement cannot be a difference in the connection. package litedial import ( "context" "fmt" "net" "time" btcdwire "github.com/btcsuite/btcd/wire/v2" "git.smesh.lol/btcd-lite/internal/v2peer" ) // Connect dials addr and negotiates with userAgent, in one call. It tries // BIP324 first and falls back to v1 on a second connection, because a public // node that does not speak v2 answers the ellswift with nothing and closes, // and a fill that only speaks v2 cannot use most of the network. // // The dial takes ctx for cancellation and has its own deadline, and the // resulting socket carries no deadline into the handshake: v2peer sets its own // and a leftover one is a deadline nobody meant. func Connect(ctx context.Context, addr, userAgent string, magic btcdwire.BitcoinNet, timeout time.Duration, useV2 bool, logf func(string, ...any)) (*v2peer.Peer, error) { if timeout <= 0 { timeout = 2 * time.Minute } dial := func(ctx context.Context, a string) (net.Conn, error) { dialCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() start := time.Now() nc, err := (&net.Dialer{Timeout: 30 * time.Second}).DialContext(dialCtx, "tcp", a) if err != nil { return nil, fmt.Errorf("dial %s after %s: %w", a, time.Since(start).Round(time.Millisecond), err) } if logf != nil { logf("dial: tcp to %s in %s", a, time.Since(start).Round(time.Millisecond)) } return nc, nil } cfg := v2peer.Config{ Net: magic, UserAgent: userAgent, // NODE_COMPACT_FILTERS is not advertised: it says a peer can *serve* // filters, which an instance that asks for them cannot. A node decides // whether to answer from its own services, not from this field. Services: btcdwire.SFNodeNetwork, Timeout: timeout, Remote: addr, Logf: logf, } if !useV2 { // v1 only: a plaintext connection is what every node accepts, and the // BIP324 path closes connections part way through a sync against some // real peers. See docs/STATUS.md. nc, err := dial(ctx, addr) if err != nil { return nil, err } cfg.Conn = nc p, err := v2peer.Dial(cfg) if err != nil { _ = nc.Close() return nil, err } return p, nil } return v2peer.DialWithFallback(ctx, dial, addr, cfg) }