-
Notifications
You must be signed in to change notification settings - Fork 33
/
broadcast.go
90 lines (83 loc) · 2.04 KB
/
broadcast.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"bytes"
"encoding/base64"
"encoding/hex"
"io/ioutil"
"net/http"
"github.com/tendermint/tendermint/crypto/ed25519"
)
type MsgTx struct {
PrivateKey string
PublicKey string
Msg string
}
type ResultObj struct {
Result bool
Info string
Error string
}
// post {method jsonrpc params id} to 26657/broadcast_tx_commit
func BroadCastMsg(json MsgTx) ResultObj {
// encode msg
var base64msg = base64.StdEncoding.EncodeToString([]byte(json.Msg))
// sign
_privatekey, _ := hex.DecodeString(json.PrivateKey)
var privateKey ed25519.PrivKeyEd25519
copy(privateKey[:], _privatekey)
signStr, err := privateKey.Sign([]byte(base64msg))
// define response
var res ResultObj
if err == nil {
// sign successfully
sign := hex.EncodeToString(signStr)
url := "http://localhost:26657"
// defined struct
var baseInitData = "{" +
"\"publickey\":\"" + json.PublicKey + "\"," +
"\"sign\":\"" + sign + "\"," +
"\"msg\":\"" + base64msg + "\"" +
"}"
var baseInput = []byte(baseInitData)
var encodingString = base64.StdEncoding.EncodeToString(baseInput)
var post = "{\"method\":\"broadcast_tx_commit\",\"jsonrpc\":\"2.0\",\"params\":{\"tx\":\"" + encodingString + "\"},\"id\":\"\"}"
var jsonStr = []byte(post)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
res.Result = false
res.Info = ""
res.Error = err.Error()
return res
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := &http.Client{}
// send request
resp, err := client.Do(req)
if err != nil {
res.Result = false
res.Info = ""
res.Error = err.Error()
return res
}
defer resp.Body.Close()
// reponse result
body, err := ioutil.ReadAll((resp.Body))
if resp.StatusCode == 200 {
res.Result = true
res.Info = string(body)
res.Error = ""
return res
} else {
// sign failed
res.Result = false
res.Info = ""
res.Error = err.Error()
return res
}
} else {
res.Result = false
res.Info = ""
res.Error = err.Error()
return res
}
}