package gate import ( "bytes" "encoding/json" "net/http" "strings" "testing" "time" "git.smesh.lol/btcd-lite/internal/relay" ) // submitTx posts a transaction to an instance's relay endpoint. func submitTx(t *testing.T, base, chain, rawHex string, dependsOn []string) (int, relay.SubmitResponse) { t.Helper() body, err := json.Marshal(relay.SubmitRequest{Tx: rawHex, DependsOn: dependsOn}) if err != nil { t.Fatal(err) } resp, err := http.Post(base+"/v1/chains/"+chain+"/tx", "application/json", bytes.NewReader(body)) if err != nil { t.Fatalf("submit: %v", err) } defer resp.Body.Close() var out relay.SubmitResponse _ = json.NewDecoder(resp.Body).Decode(&out) return resp.StatusCode, out } // coinbaseOutpoint picks the outpoint of the first spendable output in the // node's unspent list. Whether it is a coinbase does not matter: what matters // is that no transaction spending it exists yet, so the node cannot be holding // the relayed transaction already. func coinbaseOutpoint(t *testing.T, r *rig, listunspent string) string { t.Helper() var rows []struct { TxID string `json:"txid"` Vout uint32 `json:"vout"` Amount float64 `json:"amount"` Coinbase bool `json:"coinbase"` } unmarshalStrict(t, listunspent, &rows) t.Logf("the node has %d unspent outputs", len(rows)) for _, row := range rows { if row.Amount >= 0.5 { return row.TxID } } t.Fatalf("the node has no unspent output of half a coin") return "" } // signedHex reads the signed transaction and whether signing completed. func signedHex(t *testing.T, raw string) (string, bool) { t.Helper() var out struct { Hex string `json:"hex"` Complete bool `json:"complete"` } unmarshalStrict(t, raw, &out) return out.Hex, out.Complete } // decodeTxID is the txid of a signed transaction, read by the node. func decodeTxID(t *testing.T, r *rig, hexTx string) string { t.Helper() out, err := r.cli("decoderawtransaction", hexTx) if err != nil { t.Fatalf("decoderawtransaction: %v\n%s", err, out) } var d struct { TxID string `json:"txid"` } unmarshalStrict(t, out, &d) return d.TxID } // unmarshalStrict decodes one JSON value and refuses trailing output, which is // how a cli error gets caught here rather than at the next step. func unmarshalStrict(t *testing.T, raw string, out any) { t.Helper() dec := json.NewDecoder(strings.NewReader(strings.TrimSpace(raw))) if err := dec.Decode(out); err != nil { t.Fatalf("json: %v\n%s", err, raw) } } func min(a, b int) int { if a < b { return a } return b } // waitForMempool waits until the node's mempool holds or lacks a transaction. func waitForMempool(t *testing.T, r *rig, txid string, want bool) { t.Helper() deadline := time.Now().Add(30 * time.Second) for { out, err := r.cli("getmempoolentry", txid) has := err == nil if has == want { if want { t.Logf("the node's mempool holds %s: %s", txid, trim(out)) } return } if time.Now().After(deadline) { state := "lacks" if want { state = "never held" } t.Fatalf("the node's mempool %s %s", state, txid) } time.Sleep(250 * time.Millisecond) } }