package verify import ( "context" "errors" "io" "net/http" "strings" "testing" "git.smesh.lol/tinywallet/pkg/tx" ) type doer func(*http.Request) (*http.Response, error) func (d doer) Do(r *http.Request) (*http.Response, error) { return d(r) } func reply(status int, body string) *http.Response { return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body))} } func TestAdapterNeedsExplicitConfiguration(t *testing.T) { if _, err := NewHTTPAdapter("x", "", doer(nil)); err == nil { t.Fatal("an empty base URL was accepted") } if _, err := NewHTTPAdapter("", "https://a.example", doer(nil)); err == nil { t.Fatal("an unnamed indexer was accepted") } } func TestAdapterTxHashesNothingAndEngineDoes(t *testing.T) { built := buildTx(t, 0, tx.SequenceFinal, tx.Output{Value: 7, Script: []byte{0x51}}) raw := rawOf(t, built) txid, err := TxidOf(raw) if err != nil { t.Fatal(err) } adapter, err := NewHTTPAdapter("idx", "https://idx.example", doer(func(r *http.Request) (*http.Response, error) { switch { case strings.HasSuffix(r.URL.Path, "/hex"): return reply(200, hexString(raw)), nil case strings.Contains(r.URL.Path, "/tx/"): return reply(200, `{"status":{"confirmed":true,"block_height":962000}}`), nil default: return reply(404, ""), nil } })) if err != nil { t.Fatal(err) } fact, err := adapter.Tx(context.Background(), txid) if err != nil { t.Fatal(err) } if !fact.Found || fact.Height != 962000 { t.Fatalf("fact %+v", fact) } if got, err := TxidOf(fact.Raw); err != nil || got != txid { t.Fatal("the adapter's bytes do not hash to the requested txid") } } func TestAdapterTipAndFee(t *testing.T) { tipHash := strings.Repeat("11", 32) adapter, err := NewHTTPAdapter("idx", "https://idx.example", doer(func(r *http.Request) (*http.Response, error) { switch r.URL.Path { case "/blocks/tip/hash": return reply(200, tipHash), nil case "/blocks/tip/height": return reply(200, "962000"), nil case "/fee-estimates": return reply(200, `{"1":30.0,"6":12.4}`), nil default: return reply(404, ""), nil } })) if err != nil { t.Fatal(err) } tip, err := adapter.Tip(context.Background()) if err != nil { t.Fatal(err) } if tip.Height != 962000 { t.Fatalf("tip %+v", tip) } rate, err := adapter.FeeEstimate(context.Background()) if err != nil { t.Fatal(err) } if rate != 12 { t.Fatalf("fee rate %d, want 12", rate) } } func hexString(b []byte) string { const digits = "0123456789abcdef" out := make([]byte, 0, 2*len(b)) for _, v := range b { out = append(out, digits[v>>4], digits[v&0xf]) } return string(out) } var _ = errors.New