forked from blockcypher/gobcy
/
tx.go
267 lines (254 loc) · 8.19 KB
/
tx.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package gobcy
import (
"appengine"
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"strconv"
"github.com/btcsuite/btcd/btcec"
)
//GetUnTX returns an array of the latest unconfirmed TXs.
func (api *API) GetUnTX(c appengine.Context) (txs []TX, err error) {
u, err := api.buildURL("/txs")
resp, err := getResponse(c, u)
if err != nil {
return
}
defer resp.Body.Close()
//decode JSON into []TX
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&txs)
return
}
//GetTX returns a TX represented by the passed hash.
func (api *API) GetTX(c appengine.Context, hash string) (tx TX, err error) {
u, err := api.buildURL("/txs/" + hash)
resp, err := getResponse(c, u)
if err != nil {
return
}
defer resp.Body.Close()
//decode JSON into TX
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&tx)
return
}
//GetTXCustom returns a TX represented by the passed hash,
//but takes additional parameters compared to GetTX:
// "limit," limits number of inputs/outputs. If not set, defaults to 20.
// Set it 0 to ignore this parameter.
// "instart," filters TX to only include inputs starting at this index.
// Set it 0 to ignore this parameter.
// "outstart", filters TX to only include outputs starting at this index.
// Set it 0 to ignore this parameter.
// "includeHex", if true, includes raw-encoded hex transaction.
// "includeConfidence," if true, includes confidence information
// for unconfirmed transactions.
func (api *API) GetTXCustom(c appengine.Context, hash string, limit int, instart int, outstart int, includeHex bool, includeConfidence bool) (tx TX, err error) {
params := map[string]string{"includeHex": strconv.FormatBool(includeHex), "includeConfidence": strconv.FormatBool(includeConfidence)}
if limit > 0 {
params["limit"] = strconv.Itoa(limit)
}
if instart > 0 {
params["instart"] = strconv.Itoa(instart)
}
if outstart > 0 {
params["outstart"] = strconv.Itoa(outstart)
}
u, err := api.buildURLParams("/txs/"+hash, params)
resp, err := getResponse(c, u)
if err != nil {
return
}
defer resp.Body.Close()
//decode JSON into TX
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&tx)
return
}
//GetTXConf returns a TXConf containing a float [0,1] that
//represents BlockCypher's confidence that an unconfirmed transaction
//won't be successfully double-spent against. If the confidence is 1,
//the transaction has already been confirmed.
func (api *API) GetTXConf(c appengine.Context, hash string) (conf TXConf, err error) {
u, err := api.buildURL("/txs/" + hash + "/confidence")
resp, err := getResponse(c, u)
if err != nil {
return
}
defer resp.Body.Close()
//decode JSON into TXConf
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&conf)
return
}
//TempNewTX creates a simple template transaction, suitable for
//use in NewTX. Takes an input/output address and amount.
func TempNewTX(c appengine.Context, inAddr string, outAddr string, amount int64) (trans TX) {
trans.Inputs = make([]TXInput, 1)
trans.Outputs = make([]TXOutput, 1)
trans.Inputs[0].Addresses = make([]string, 1)
trans.Outputs[0].Addresses = make([]string, 1)
trans.Inputs[0].Addresses[0] = inAddr
trans.Outputs[0].Addresses[0] = outAddr
trans.Outputs[0].Value = amount
return
}
//TempMultiTX creates a skeleton multisig transaction,
//suitable for use in NewTX. If outAddr == "", then the
//returned TX will be a skeleton to fund a multisig address.
//If inAddr == "", then the returned TX will be a skeleton to
//send from a multisig address (/series of public keys).
//n represents the number of valid signatures required, and m
//is derived from the number of pubkeys.
func TempMultiTX(c appengine.Context, inAddr string, outAddr string, amount int64, n int, pubkeys []string) (trans TX, err error) {
m := len(pubkeys)
if inAddr != "" && outAddr != "" {
err = errors.New("TempMultiTX: Can't have both inAddr and outAddr != \"\"")
return
}
if n > m {
err = errors.New("TempMultiTX: n cannot be greater than the number of pubkeys")
return
}
scripttype := "multisig-" + strconv.Itoa(n) + "-of-" + strconv.Itoa(m)
trans.Inputs = make([]TXInput, 1)
trans.Outputs = make([]TXOutput, 1)
if inAddr != "" {
trans.Inputs[0].Addresses = make([]string, 1)
trans.Inputs[0].Addresses[0] = inAddr
trans.Outputs[0].Addresses = pubkeys
trans.Outputs[0].ScriptType = scripttype
} else if outAddr != "" {
trans.Inputs[0].Addresses = pubkeys
trans.Inputs[0].ScriptType = scripttype
trans.Outputs[0].Addresses = make([]string, 1)
trans.Outputs[0].Addresses[0] = outAddr
}
trans.Outputs[0].Value = amount
return
}
//NewTX takes a partially formed TX and returns a TXSkel
//with the data that needs to be signed. Can use TempNewTX
//or TempMultiTX to streamline input transaction, or customize
//transaction as described in the BlockCypher docs:
//http://dev.blockcypher.com/#customizing-transaction-requests
//If verify is true, will include "ToSignTX," which can be used
//to locally verify the "ToSign" data is valid.
func (api *API) NewTX(c appengine.Context, trans TX, verify bool) (skel TXSkel, err error) {
u, err := api.buildURLParams("/txs/new",
map[string]string{"includeToSignTx": strconv.FormatBool(verify)})
if err != nil {
return
}
var data bytes.Buffer
enc := json.NewEncoder(&data)
if err = enc.Encode(&trans); err != nil {
return
}
resp, err := postResponse(c, u, &data)
if err != nil {
return
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&skel)
return
}
//Sign takes a hex-encoded string slice of private
//keys and uses them to sign the ToSign data in a
//TXSkel, generating the proper Signatures and PubKeys
//array, both hex-encoded. This is meant as a helper
//function, and leverages btcd's btcec library.
func (skel *TXSkel) Sign(c appengine.Context, priv []string) (err error) {
//num of private keys must match len(ToSign)
//Often this might mean repeating private keys
if len(priv) != len(skel.ToSign) {
err = errors.New("*TXSkel.Sign error: number of private keys != length of ToSign array")
return
}
//Loop through keys, append sigs/public key
for i, k := range priv {
privDat, err := hex.DecodeString(k)
tosign, err := hex.DecodeString(skel.ToSign[i])
if err != nil {
return err
}
privkey, pubkey := btcec.PrivKeyFromBytes(btcec.S256(), privDat)
sig, err := privkey.Sign(tosign)
if err != nil {
return err
}
skel.Signatures = append(skel.Signatures, hex.EncodeToString(sig.Serialize()))
skel.PubKeys = append(skel.PubKeys, hex.EncodeToString(pubkey.SerializeCompressed()))
}
return
}
//SendTX takes a TXSkel, returns the completed
//transaction and sends it across the Coin/Chain
//network. TXSkel requires a fully formed TX, Signatures,
//and PubKeys. PubKeys should not be included in the
//special case of multi-sig addresses.
func (api *API) SendTX(c appengine.Context, skel TXSkel) (trans TXSkel, err error) {
u, err := api.buildURL("/txs/send")
if err != nil {
return
}
var data bytes.Buffer
enc := json.NewEncoder(&data)
if err = enc.Encode(&skel); err != nil {
return
}
resp, err := postResponse(c, u, &data)
if err != nil {
return
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&trans)
return
}
//PushTX takes a hex-encoded transaction string
//and pushes it directly to the Coin/Chain network.
func (api *API) PushTX(c appengine.Context, hex string) (trans TXSkel, err error) {
u, err := api.buildURL("/txs/push")
if err != nil {
return
}
var data bytes.Buffer
enc := json.NewEncoder(&data)
if err = enc.Encode(map[string]string{"tx": hex}); err != nil {
return
}
resp, err := postResponse(c, u, &data)
if err != nil {
return
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&trans)
return
}
//DecodeTX takes a hex-encoded transaction string
//and decodes it into a TX object, without sending
//it along to the Coin/Chain network.
func (api *API) DecodeTX(c appengine.Context, hex string) (trans TXSkel, err error) {
u, err := api.buildURL("/txs/decode")
if err != nil {
return
}
var data bytes.Buffer
enc := json.NewEncoder(&data)
if err = enc.Encode(map[string]string{"tx": hex}); err != nil {
return
}
resp, err := postResponse(c, u, &data)
if err != nil {
return
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&trans)
return
}