-
Notifications
You must be signed in to change notification settings - Fork 15
/
sendtransaction.go
52 lines (44 loc) · 1.11 KB
/
sendtransaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"bytes"
"encoding/hex"
"io"
"net/http"
"github.com/btcsuite/btcd/wire"
)
type RawTransactionResponse struct {
Success bool `json:"success"`
ErrMsg string `json:"errmsg"`
}
func sendRawTransaction(txHex string) (resp RawTransactionResponse) {
// try bitcoind first
if bitcoind != nil {
tx := &wire.MsgTx{}
if txBytes, err := hex.DecodeString(txHex); err == nil {
txBuf := bytes.NewBuffer(txBytes)
if err := tx.BtcDecode(txBuf, wire.ProtocolVersion, wire.WitnessEncoding); err == nil {
if _, err := bitcoind.SendRawTransaction(tx, true); err == nil {
return RawTransactionResponse{true, ""}
}
}
}
}
// then try explorers
tx := bytes.NewBufferString(txHex)
for _, endpoint := range esploras(network) {
w, err := http.Post(endpoint+"/tx", "text/plain", tx)
if err != nil {
resp = RawTransactionResponse{false, err.Error()}
continue
}
defer w.Body.Close()
if w.StatusCode >= 300 {
msg, _ := io.ReadAll(w.Body)
resp = RawTransactionResponse{false, string(msg)}
err = nil
continue
}
return RawTransactionResponse{true, ""}
}
return resp
}