Documentation
¶
Overview ¶
Package deadhop is a client for deadhop, an on-chain bitcoin invoice service reachable only over ContextVM (MCP JSON-RPC over Nostr).
A Client creates invoices, looks them up and waits for them to be paid:
client, err := deadhop.New(deadhop.Options{
ServerPubkey: "npub1…",
Relays: []string{"wss://relay.example.com"},
})
if err != nil { … }
defer client.Close()
invoice, err := client.CreateInvoice(ctx, deadhop.CreateInvoice{AmountSat: 5000, Memo: "Order 42"})
The client connects lazily on the first call and is safe for concurrent use; share one per process.
Relays ¶
Every request goes to every open relay and succeeds when one accepts it. Connecting gives the relays half of Options.ConnectTimeout (at most 10 s), so an unreachable relay is reported as a network error. A relay that drops later is redialed: in the background while another relay is open, so one dead relay does not slow calls down, and before the send when none is. Open connections are pinged every 20 s so a silently dead one is noticed.
Keys and proof of work ¶
Requests are signed by Options.SecretKey. Without one the client uses a throwaway key: a guest, who must mine the proof of work (NIP-13) the service asks for before creating an invoice. Mining uses every CPU and stops with the context; the client refuses up front work beyond Options.MaxPowBits. An operator's key creates invoices without work.
Trust ¶
Every reply is checked before any of it reaches the caller. A reply is only accepted when it decrypts (NIP-44), the event inside carries a valid id and signature by the service's key, and it names the request it answers. Its content must then have exactly the expected fields, in range, and an invoice's bip21 URI must pay exactly the address and amount shown. Anything else is dropped or reported as bad_response.
Errors ¶
Calls fail with an *Error carrying a stable ErrorCode and a Message fit to show to people. A context deadline gives CodeTimeout (errors.Is it against context.DeadlineExceeded too); a cancelled context gives context.Canceled.
Wire protocol ¶
A request is a JSON-RPC message in a kind 25910 event signed by the caller and addressed to the service with a "p" tag. It is encrypted with NIP-44 v2 from a fresh throwaway key and sent as a kind 21059 gift wrap to every relay. Replies come back the same way, as kind 21059 or 1059 wraps.
When a relay sends a NIP-42 challenge, the client answers it once per connection with a kind 22242 event signed by the key it reads replies for, and subscribes again (once) if the relay closed the subscription with "auth-required:". A relay that only delivers wraps to the key they name needs this; others never ask.
Index ¶
- Constants
- Variables
- func LeadingZeroBits(hexID string) int
- func NormalizePubkey(value string) (hexKey string, ok bool)
- func URIMatches(address string, amountSat int64, bip21 string) bool
- type Client
- func (c *Client) CallTool(ctx context.Context, name string, args map[string]any) (json.RawMessage, error)
- func (c *Client) Close() error
- func (c *Client) Config() ServiceConfig
- func (c *Client) CreateInvoice(ctx context.Context, req CreateInvoice) (Invoice, error)
- func (c *Client) GetInvoice(ctx context.Context, id string) (Invoice, error)
- func (c *Client) Info(ctx context.Context) (ServiceInfo, error)
- func (c *Client) Pubkey() string
- func (c *Client) WaitForInvoice(ctx context.Context, id string, opts WaitOptions) (Invoice, error)
- type CreateInvoice
- type Error
- type ErrorCode
- type Invoice
- type InvoiceStatus
- type Network
- type Options
- type ServiceConfig
- type ServiceInfo
- type WaitOptions
Examples ¶
Constants ¶
const ( // DefaultConnectTimeout is how long connecting waits for the service to // answer before giving up. DefaultConnectTimeout = 20 * time.Second // DefaultCallTimeout is how long a call waits for its answer. DefaultCallTimeout = 60 * time.Second // DefaultClientName is the name sent in the handshake. DefaultClientName = "deadhop-client-go" // DefaultWaitInterval is how often WaitForInvoice polls. DefaultWaitInterval = 5 * time.Second )
const DefaultMaxPowBits = 28
DefaultMaxPowBits is the most proof of work the client attempts unless Options.MaxPowBits says otherwise. Each bit doubles the time.
const MaxMoneySat int64 = 21_000_000 * 100_000_000
MaxMoneySat is the most satoshis any amount can be: 21 million bitcoin.
const ProtocolVersion = "2025-03-26"
ProtocolVersion is the MCP protocol version the client speaks.
const Version = "0.1.0"
Version is this client's version, sent to the service in the handshake.
Variables ¶
var ErrInvalidConfig = errors.New(`Invalid deadhop service config: it needs "server_pubkey" (hex or npub) and "relays" (ws:// or wss:// URLs).`)
ErrInvalidConfig is returned by ParseConfig and New when the service's key or relays are unusable.
var ErrInvalidSecretKey = errors.New("Enter an nsec or a 64-character hex secret key")
ErrInvalidSecretKey is returned by New when Options.SecretKey is neither an nsec nor a 64-character hex secret key.
var ErrInvalidServerKey = errors.New("Invalid deadhop service config: the server key is not a valid public key.")
ErrInvalidServerKey is returned by New when the server key has the right form but is not a valid public key (no point on the curve has it as x).
Functions ¶
func LeadingZeroBits ¶
LeadingZeroBits is the number of leading zero bits of a hex string (NIP-13). It stops at the first character that is not a hex digit.
func NormalizePubkey ¶
NormalizePubkey accepts a hex key, npub or nprofile (with or without a "nostr:" prefix) and returns lowercase hex. ok is false if value is none of those.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a deadhop service. It connects on first use and is safe for concurrent use by multiple goroutines; share one per process. Call Close when done.
func New ¶
New checks the options and returns a Client. It does not connect: the first call does. It returns ErrInvalidConfig, ErrInvalidServerKey or ErrInvalidSecretKey if the options are unusable.
func (*Client) CallTool ¶
func (c *Client) CallTool(ctx context.Context, name string, args map[string]any) (json.RawMessage, error)
CallTool calls any tool and returns its structuredContent unvalidated, as raw JSON ("null" when there is none). It is meant for operator tools.
func (*Client) Close ¶
Close closes the relay connections, and stops a connection being opened. Calls in flight fail with a network error. The client stays usable: the next call connects again.
func (*Client) Config ¶
func (c *Client) Config() ServiceConfig
Config is where the client reaches the service.
func (*Client) CreateInvoice ¶
CreateInvoice creates an invoice. A guest key first mines the proof of work the service asks for, on every CPU; an operator's key does not.
Example ¶
A guest (no secret key) creates an invoice. The client mines the proof of work the service asks for first.
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
deadhop "github.com/deadhop/client-go"
)
func main() {
client, err := deadhop.New(deadhop.Options{
ServerPubkey: "npub1…", // the service's key: hex, npub or nprofile
Relays: []string{"wss://relay.example.com"},
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
invoice, err := client.CreateInvoice(ctx, deadhop.CreateInvoice{AmountSat: 5000, Memo: "Order 42"})
var apiErr *deadhop.Error
if errors.As(err, &apiErr) {
// apiErr.Message is fit to show to people; apiErr.Code is stable.
log.Fatalf("%s: %s", apiErr.Code, apiErr.Message)
} else if err != nil {
log.Fatal(err)
}
fmt.Println("Pay", invoice.BIP21)
}
Output:
Example (Operator) ¶
An operator's key creates invoices without proof of work, and can call the operator tools.
package main
import (
"context"
"fmt"
"log"
"os"
deadhop "github.com/deadhop/client-go"
)
func main() {
client, err := deadhop.New(deadhop.Options{
ServerPubkey: "npub1…",
Relays: []string{"wss://relay.example.com"},
SecretKey: os.Getenv("DEADHOP_OPERATOR_NSEC"), // nsec or hex
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx := context.Background()
info, err := client.Info(ctx)
if err != nil {
log.Fatal(err)
}
if !info.IsAdmin {
log.Fatal("this key is not an operator of the service")
}
invoice, err := client.CreateInvoice(ctx, deadhop.CreateInvoice{AmountSat: 100_000, ExpirySecs: 600})
if err != nil {
log.Fatal(err)
}
fmt.Println(invoice.ID, invoice.Address)
}
Output:
func (*Client) GetInvoice ¶
GetInvoice looks an invoice up by id. It works for any key: the id is the capability.
func (*Client) Info ¶
func (c *Client) Info(ctx context.Context) (ServiceInfo, error)
Info is the service's name, network and limits, and the proof of work it asks of this key. It is read once, when the client connects.
func (*Client) WaitForInvoice ¶
WaitForInvoice polls an invoice until its status is one of opts.Until and returns it. Bound it with a context deadline: when the deadline is reached, or the next poll would come after it, it returns an *Error with code timeout.
Example ¶
Wait until an invoice is paid and confirmed, or it expires, or an hour has passed.
package main
import (
"context"
"fmt"
"log"
"time"
deadhop "github.com/deadhop/client-go"
)
func main() {
client, err := deadhop.New(deadhop.Options{
ServerPubkey: "npub1…",
Relays: []string{"wss://relay.example.com"},
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Hour)
defer cancel()
invoice, err := client.WaitForInvoice(ctx, "0123456789abcdef0123456789abcdef", deadhop.WaitOptions{
Until: []deadhop.InvoiceStatus{deadhop.StatusConfirmed, deadhop.StatusExpired},
Interval: 10 * time.Second,
})
if err != nil {
log.Fatal(err)
}
switch invoice.Status {
case deadhop.StatusConfirmed:
fmt.Println("paid", invoice.ConfirmedSat, "sat")
case deadhop.StatusExpired:
fmt.Println("expired; received", invoice.ReceivedSat, "sat")
}
}
Output:
type CreateInvoice ¶
type CreateInvoice struct {
// AmountSat is the amount in satoshis.
AmountSat int64
// Memo is shown to whoever pays; up to 200 characters. Empty sends none.
Memo string
// ExpirySecs is the invoice's lifetime in seconds. Zero means the
// service's default; the maximum is the service's MaxExpirySecs.
ExpirySecs int64
}
CreateInvoice is what to invoice.
type Error ¶
type Error struct {
// Code is why the call failed.
Code ErrorCode
// Message is the fixed text for Code, sometimes followed by a detail in
// parentheses (the relay's refusal, the service's reason for invalid params).
Message string
// contains filtered or unexported fields
}
Error is every failure a call reports: a stable Code and a Message fit to show to people. Use errors.As to get at it.
type ErrorCode ¶
type ErrorCode string
ErrorCode says why a call failed. The first eight come from the service itself; the rest are found by the client.
const ( CodeInvalidParams ErrorCode = "invalid_params" CodeNotFound ErrorCode = "not_found" CodePowRejected ErrorCode = "pow_rejected" CodeRateLimited ErrorCode = "rate_limited" CodeCapacity ErrorCode = "capacity" CodePaused ErrorCode = "paused" CodeInternal ErrorCode = "internal" CodeBadResponse ErrorCode = "bad_response" CodePowFailed ErrorCode = "pow_failed" CodeTimeout ErrorCode = "timeout" CodeNetwork ErrorCode = "network" )
The stable error codes. Their values never change.
func ErrorCodes ¶
func ErrorCodes() []ErrorCode
ErrorCodes returns every error code, the eight the service sends first.
type Invoice ¶
type Invoice struct {
// ID is 32 lowercase hex characters. Anyone who has the id can look the
// invoice up.
ID string `json:"id"`
// Address is the native segwit address that receives the payment (fresh
// per invoice).
Address string `json:"address"`
AmountSat int64 `json:"amount_sat"`
// Memo is written by whoever created the invoice, possibly a stranger:
// show it as plain text.
Memo string `json:"memo"`
Status InvoiceStatus `json:"status"`
// ReceivedSat is what was paid to the address so far, confirmed or not.
ReceivedSat int64 `json:"received_sat"`
// ConfirmedSat is what was paid with at least ConfirmationsRequired
// confirmations.
ConfirmedSat int64 `json:"confirmed_sat"`
// CreatedAt, ExpiresAt and SettledAt are Unix times in seconds.
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
SettledAt *int64 `json:"settled_at"`
// BIP21 is the bitcoin: payment URI for exactly Address and AmountSat.
BIP21 string `json:"bip21"`
ConfirmationsRequired int64 `json:"confirmations_required"`
}
Invoice is an invoice as the service reports it.
func ParseInvoice ¶
ParseInvoice checks an invoice from the service: exactly the expected fields, each of the right type and range, and a bip21 URI that pays exactly the address and amount shown. Anything else is an *Error with code bad_response.
type InvoiceStatus ¶
type InvoiceStatus string
InvoiceStatus is where an invoice is in its life.
const ( StatusPending InvoiceStatus = "pending" StatusDetected InvoiceStatus = "detected" StatusConfirmed InvoiceStatus = "confirmed" StatusExpired InvoiceStatus = "expired" )
The statuses an invoice can have.
type Options ¶
type Options struct {
// ServerPubkey is the service's public key: hex, npub or nprofile.
ServerPubkey string
// Relays are 1 to 8 wss:// (or ws://) relays the service listens on.
Relays []string
// SecretKey signs requests, as an nsec or 64 hex characters. Empty means
// a throwaway key: a guest, who must do proof of work to create invoices.
// An operator's key creates invoices without proof of work.
SecretKey string
// ConnectTimeout bounds connecting and the handshake. Zero means
// DefaultConnectTimeout.
ConnectTimeout time.Duration
// CallTimeout bounds the wait for each answer. Zero means
// DefaultCallTimeout. A context deadline applies as well.
CallTimeout time.Duration
// MaxPowBits is the most proof of work the client attempts. Zero means
// DefaultMaxPowBits; a negative value refuses any work.
MaxPowBits int
// ClientName is sent to the service in the handshake. Empty means
// DefaultClientName.
ClientName string
}
Options configures a Client.
type ServiceConfig ¶
type ServiceConfig struct {
// ServerPubkey is the service's public key, lowercase hex.
ServerPubkey string
// Relays are the 1 to 8 ws:// or wss:// relays shared with the service,
// exactly as given.
Relays []string
}
ServiceConfig is where to reach a deadhop service.
func ParseConfig ¶
func ParseConfig(serverPubkey string, relays []string) (ServiceConfig, error)
ParseConfig checks where to reach the service. It returns ErrInvalidConfig if the key is not a hex key, npub or nprofile, or the relays are not 1 to 8 ws:// or wss:// URLs.
type ServiceInfo ¶
type ServiceInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Network Network `json:"network"`
// PublicInvoicing is whether callers that are not operators may create
// invoices (with proof of work).
PublicInvoicing bool `json:"public_invoicing"`
// PowBits is the proof of work asked of this caller for each new invoice
// (0 for operators).
PowBits int64 `json:"pow_bits"`
PowWindowSecs int64 `json:"pow_window_secs"`
MinConfirmations int64 `json:"min_confirmations"`
DefaultExpirySecs int64 `json:"default_expiry_secs"`
MaxExpirySecs int64 `json:"max_expiry_secs"`
MinAmountSat int64 `json:"min_amount_sat"`
MaxAmountSat int64 `json:"max_amount_sat"`
// IsAdmin is whether the signing key is one of the service's operators.
IsAdmin bool `json:"is_admin"`
}
ServiceInfo is what the service tells every caller about itself and its limits.
func ParseInfo ¶
func ParseInfo(raw []byte) (ServiceInfo, error)
ParseInfo checks the service's description of itself. Anything unexpected is an *Error with code bad_response.
type WaitOptions ¶
type WaitOptions struct {
// Until is the statuses to stop at. Empty means confirmed or expired.
// The service keeps watching an expired invoice for late payments, so
// an expired invoice can still become detected or confirmed: leave
// expired out to keep waiting past it.
Until []InvoiceStatus
// Interval is how often to poll. Zero means DefaultWaitInterval.
Interval time.Duration
}
WaitOptions says when WaitForInvoice stops.