/
utils.go
200 lines (187 loc) · 4.94 KB
/
utils.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package utils
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"log"
mathRand "math/rand"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/gogo/protobuf/proto"
protoTm "github.com/ndidplatform/smart-contract/v6/protos/tendermint"
kv "github.com/tendermint/tendermint/libs/kv"
tmRand "github.com/tendermint/tendermint/libs/rand"
)
var tendermintAddr = GetEnv("TENDERMINT_ADDRESS", "http://localhost:45000")
func GetPrivateKeyFromString(privK string) *rsa.PrivateKey {
privK = strings.Replace(privK, "\t", "", -1)
block, _ := pem.Decode([]byte(privK))
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
fmt.Println(err.Error())
}
return privateKey
}
func GeneratePublicKey(publicKey *rsa.PublicKey) ([]byte, error) {
pubKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return nil, err
}
privBlock := pem.Block{
Type: "PUBLIC KEY",
Headers: nil,
Bytes: pubKeyBytes,
}
publicPEM := pem.EncodeToMemory(&privBlock)
return publicPEM, nil
}
func CreateSignatureAndNonce(fnName string, paramJSON []byte, privKey *rsa.PrivateKey) (nonce string, signature []byte) {
nonce = base64.StdEncoding.EncodeToString([]byte(tmRand.Str(12)))
tempPSSmessage := append([]byte(fnName), paramJSON...)
tempPSSmessage = append(tempPSSmessage, []byte(nonce)...)
PSSmessage := []byte(base64.StdEncoding.EncodeToString(tempPSSmessage))
newhash := crypto.SHA256
pssh := newhash.New()
pssh.Write(PSSmessage)
hashed := pssh.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, privKey, newhash, hashed)
if err != nil {
fmt.Println(err.Error())
}
return nonce, signature
}
func CreateTxn(fnName []byte, param []byte, nonce []byte, signature []byte, nodeID []byte) (interface{}, error) {
var tx protoTm.Tx
tx.Method = string(fnName)
tx.Params = string(param)
tx.Nonce = nonce
tx.Signature = signature
tx.NodeId = string(nodeID)
txByte, err := proto.Marshal(&tx)
if err != nil {
log.Printf("err: %s", err.Error())
}
txEncoded := hex.EncodeToString(txByte)
var URL *url.URL
URL, err = url.Parse(tendermintAddr)
if err != nil {
panic("boom")
}
URL.Path += "/broadcast_tx_commit"
parameters := url.Values{}
parameters.Add("tx", `0x`+txEncoded)
URL.RawQuery = parameters.Encode()
encodedURL := URL.String()
req, err := http.NewRequest("GET", encodedURL, nil)
if err != nil {
fmt.Println(err.Error())
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var body ResponseTx
json.NewDecoder(resp.Body).Decode(&body)
return body, nil
}
func Query(fnName []byte, param []byte) (interface{}, error) {
var data protoTm.Query
data.Method = string(fnName)
data.Params = string(param)
dataByte, err := proto.Marshal(&data)
if err != nil {
log.Printf("err: %s", err.Error())
}
dataEncoded := hex.EncodeToString(dataByte)
var URL *url.URL
URL, err = url.Parse(tendermintAddr)
if err != nil {
panic("boom")
}
URL.Path += "/abci_query"
parameters := url.Values{}
parameters.Add("data", `0x`+dataEncoded)
URL.RawQuery = parameters.Encode()
encodedURL := URL.String()
req, err := http.NewRequest("GET", encodedURL, nil)
if err != nil {
fmt.Println(err.Error())
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var body ResponseQuery
json.NewDecoder(resp.Body).Decode(&body)
return body, nil
}
func GetEnv(key, defaultValue string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = defaultValue
}
return value
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func RandStringRunes(n int) string {
mathRand.Seed(time.Now().UnixNano())
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[mathRand.Intn(len(letterRunes))]
}
return string(b)
}
type ResponseTx struct {
Result struct {
Height int `json:"height"`
CheckTx struct {
Code int `json:"code"`
Log string `json:"log"`
Fee struct{} `json:"fee"`
} `json:"check_tx"`
DeliverTx struct {
Log string `json:"log"`
Fee struct{} `json:"fee"`
Tags []kv.Pair
} `json:"deliver_tx"`
Hash string `json:"hash"`
} `json:"result"`
Jsonrpc string `json:"jsonrpc"`
ID string `json:"id"`
}
type ResponseQuery struct {
Jsonrpc string `json:"jsonrpc"`
ID string `json:"id"`
Result struct {
Response struct {
Log string `json:"log"`
Value string `json:"value"`
Height string `json:"height"`
} `json:"response"`
} `json:"result"`
}