package tunnel import ( "encoding/json" "errors" "fmt" ) // Frame types carried inside the NIP-44 payload. The outer event kind only // says which direction a frame travels; the type inside the ciphertext is // authoritative, and is checked against the direction. const ( frameHello = "hello" frameHelloAck = "hello_ack" frameData = "data" frameAck = "ack" frameNack = "nack" framePing = "ping" framePong = "pong" frameClose = "close" frameReset = "reset" ) // envelope is the plaintext of one tunnel event. type envelope struct { V int `json:"v"` S string `json:"s"` T string `json:"t"` Seq uint32 `json:"q,omitempty"` Ack uint32 `json:"a,omitempty"` Data []byte `json:"d,omitempty"` Nack []uint32 `json:"x,omitempty"` MTU int `json:"m,omitempty"` Win int `json:"w,omitempty"` PV int `json:"pv,omitempty"` Chain string `json:"c,omitempty"` Nonce uint64 `json:"n,omitempty"` Reason string `json:"r,omitempty"` } func (e *envelope) marshal() ([]byte, error) { b, err := json.Marshal(e) if err != nil { return nil, fmt.Errorf("tunnel: encode envelope: %w", err) } return b, nil } func parseEnvelope(raw []byte) (*envelope, error) { var e envelope if err := json.Unmarshal(raw, &e); err != nil { return nil, fmt.Errorf("tunnel: decode envelope: %w", err) } if e.V != protocolVersion { return nil, fmt.Errorf("tunnel: unsupported envelope version %d", e.V) } if e.S == "" { return nil, errors.New("tunnel: envelope has no session") } return &e, nil }