-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtransactions.go
420 lines (352 loc) · 11.6 KB
/
transactions.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package whatsonchain
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
// GetTxByHash this endpoint retrieves transaction details with given transaction hash
//
// For more information: https://developers.whatsonchain.com/#get-by-tx-hash
func (c *Client) GetTxByHash(ctx context.Context, hash string) (txInfo *TxInfo, err error) {
var resp string
// https://api.whatsonchain.com/v1/bsv/<network>/tx/hash/<hash>
if resp, err = c.request(
ctx,
fmt.Sprintf("%s%s/tx/hash/%s", apiEndpoint, c.Network(), hash),
http.MethodGet, nil,
); err != nil {
return
}
if len(resp) == 0 {
return nil, ErrTransactionNotFound
}
err = json.Unmarshal([]byte(resp), &txInfo)
return
}
// BulkTransactionDetails this fetches details for multiple transactions in single request
// Max 20 transactions per request
//
// For more information: https://developers.whatsonchain.com/#bulk-transaction-details
func (c *Client) BulkTransactionDetails(ctx context.Context, hashes *TxHashes) (txList TxList, err error) {
// The max limit by WOC
if len(hashes.TxIDs) > MaxTransactionsUTXO {
err = fmt.Errorf(
"max limit of utxos is %d and you sent %d",
MaxTransactionsUTXO, len(hashes.TxIDs),
)
return
}
// Convert to JSON
var postData []byte
if postData, err = json.Marshal(hashes); err != nil {
return
}
var resp string
// https://api.whatsonchain.com/v1/bsv/<network>/txs
if resp, err = c.request(
ctx,
fmt.Sprintf("%s%s/txs", apiEndpoint, c.Network()),
http.MethodPost, postData,
); err != nil {
return
}
if len(resp) > 0 {
err = json.Unmarshal([]byte(resp), &txList)
}
return
}
// BulkTransactionDetailsProcessor will get the details for ALL transactions in batches
// Processes 20 transactions per request
// See: BulkTransactionDetails()
func (c *Client) BulkTransactionDetailsProcessor(ctx context.Context, hashes *TxHashes) (txList TxList, err error) {
// Break up the transactions into batches
var batches [][]string
chunkSize := MaxTransactionsUTXO
for i := 0; i < len(hashes.TxIDs); i += chunkSize {
end := i + chunkSize
if end > len(hashes.TxIDs) {
end = len(hashes.TxIDs)
}
batches = append(batches, hashes.TxIDs[i:end])
}
var currentRateLimit int
// Loop Batches - and get each batch (multiple batches of MaxTransactionsUTXO)
for _, batch := range batches {
txHashes := new(TxHashes)
// Loop the batch (max MaxTransactionsUTXO)
txHashes.TxIDs = append(txHashes.TxIDs, batch...)
// Get the tx details (max of MaxTransactionsUTXO)
var returnedList TxList
if returnedList, err = c.BulkTransactionDetails(
ctx, txHashes,
); err != nil {
return
}
// Add to the list
txList = append(txList, returnedList...)
// Accumulate / sleep to prevent rate limiting
currentRateLimit++
if currentRateLimit >= c.RateLimit() {
time.Sleep(1 * time.Second)
currentRateLimit = 0
}
}
return
}
// GetMerkleProof this endpoint returns merkle branch to a confirmed transaction
//
// For more information: https://developers.whatsonchain.com/#get-merkle-proof
func (c *Client) GetMerkleProof(ctx context.Context, hash string) (merkleResults MerkleResults, err error) {
var resp string
// https://api.whatsonchain.com/v1/bsv/<network>/tx/<hash>/proof
if resp, err = c.request(
ctx,
fmt.Sprintf("%s%s/tx/%s/proof", apiEndpoint, c.Network(), hash),
http.MethodGet, nil,
); err != nil {
return
}
if len(resp) == 0 {
return nil, ErrTransactionNotFound
}
err = json.Unmarshal([]byte(resp), &merkleResults)
return
}
// GetMerkleProofTSC this endpoint returns TSC compliant proof to a confirmed transaction
//
// For more information: TODO! No link today
func (c *Client) GetMerkleProofTSC(ctx context.Context, hash string) (merkleResults MerkleTSCResults, err error) {
var resp string
// https://api.whatsonchain.com/v1/bsv/<network>/tx/<hash>/proof/tsc
if resp, err = c.request(
ctx,
fmt.Sprintf("%s%s/tx/%s/proof/tsc", apiEndpoint, c.Network(), hash),
http.MethodGet, nil,
); err != nil {
return
}
if len(resp) == 0 {
return nil, ErrTransactionNotFound
}
err = json.Unmarshal([]byte(resp), &merkleResults)
return
}
// GetRawTransactionData this endpoint returns raw hex for the transaction with given hash
//
// For more information: https://developers.whatsonchain.com/#get-raw-transaction-data
func (c *Client) GetRawTransactionData(ctx context.Context, hash string) (string, error) {
// https://api.whatsonchain.com/v1/bsv/<network>/tx/<hash>/hex
return c.request(
ctx,
fmt.Sprintf("%s%s/tx/%s/hex", apiEndpoint, c.Network(), hash),
http.MethodGet, nil,
)
}
// BulkRawTransactionData this fetches raw hex data for multiple
// transactions in single request
// Max 20 transactions per request
//
// For more information: https://developers.whatsonchain.com/#bulk-raw-transaction-data
func (c *Client) BulkRawTransactionData(ctx context.Context, hashes *TxHashes) (txList TxList, err error) {
// The max limit by WOC
if len(hashes.TxIDs) > MaxTransactionsRaw {
err = fmt.Errorf(
"max limit of transactions is %d and you sent %d",
MaxTransactionsRaw, len(hashes.TxIDs),
)
return
}
// Convert to JSON
var postData []byte
if postData, err = json.Marshal(hashes); err != nil {
return
}
var resp string
// https://api.whatsonchain.com/v1/bsv/<network>/txs/hex
if resp, err = c.request(
ctx,
fmt.Sprintf("%s%s/txs/hex", apiEndpoint, c.Network()),
http.MethodPost, postData,
); err != nil {
return
}
if len(resp) > 0 {
err = json.Unmarshal([]byte(resp), &txList)
}
return
}
// BulkRawTransactionDataProcessor this fetches raw hex data for
// multiple transactions in single request and handles chunking
// Max 20 transactions per request
//
// For more information: https://developers.whatsonchain.com/#bulk-raw-transaction-data
func (c *Client) BulkRawTransactionDataProcessor(ctx context.Context, hashes *TxHashes) (txList TxList, err error) {
// Break up the transactions into batches
var batches [][]string
chunkSize := MaxTransactionsRaw
for i := 0; i < len(hashes.TxIDs); i += chunkSize {
end := i + chunkSize
if end > len(hashes.TxIDs) {
end = len(hashes.TxIDs)
}
batches = append(batches, hashes.TxIDs[i:end])
}
var currentRateLimit int
// Loop Batches - and get each batch (multiple batches of MaxTransactionsRaw)
for _, batch := range batches {
txHashes := new(TxHashes)
// Loop the batch (max MaxTransactionsRaw)
txHashes.TxIDs = append(txHashes.TxIDs, batch...)
// Get the tx details (max of MaxTransactionsUTXO)
var returnedList TxList
if returnedList, err = c.BulkRawTransactionData(
ctx, txHashes,
); err != nil {
return
}
// Add to the list
txList = append(txList, returnedList...)
// Accumulate / sleep to prevent rate limiting
currentRateLimit++
if currentRateLimit >= c.RateLimit() {
time.Sleep(1 * time.Second)
currentRateLimit = 0
}
}
return
}
// GetRawTransactionOutputData this endpoint returns raw hex for the transaction output with given hash and index
//
// For more information: https://developers.whatsonchain.com/#get-raw-transaction-output-data
func (c *Client) GetRawTransactionOutputData(ctx context.Context, hash string, vOutIndex int) (string, error) {
// https://api.whatsonchain.com/v1/bsv/<network>/tx/<hash>/out/<index>/hex
return c.request(
ctx,
fmt.Sprintf("%s%s/tx/%s/out/%d/hex", apiEndpoint, c.Network(), hash, vOutIndex),
http.MethodGet, nil,
)
}
// BroadcastTx will broadcast transaction using this endpoint.
// Get tx_id in response or error msg from node.
//
// For more information: https://developers.whatsonchain.com/#broadcast-transaction
func (c *Client) BroadcastTx(ctx context.Context, txHex string) (txID string, err error) {
// Start the post data
postData := []byte(fmt.Sprintf(`{"txhex":"%s"}`, txHex))
// https://api.whatsonchain.com/v1/bsv/<network>/tx/raw
if txID, err = c.request(
ctx,
fmt.Sprintf("%s%s/tx/raw", apiEndpoint, c.Network()),
http.MethodPost, postData,
); err != nil {
return
}
// Got an error
if c.lastRequest.StatusCode > http.StatusOK {
err = fmt.Errorf("error broadcasting: %s", txID)
txID = "" // remove the error message
} else {
// Remove quotes or spaces
txID = strings.TrimSpace(strings.Replace(txID, `"`, "", -1))
}
return
}
// BulkBroadcastTx will broadcast many transactions at once
// You can bulk broadcast transactions using this endpoint.
//
// Size per transaction should be less than 100KB
// Overall payload per request should be less than 10MB
// Max 100 transactions per request
// Only available for mainnet
//
// Tip: First transaction in the list should have an output to WOC tip address '16ZqP5Tb22KJuvSAbjNkoiZs13mmRmexZA'
//
// Feedback: true/false: true if response from the node is required for each transaction, otherwise, set it to false.
// (For stress testing set it to false). When set to true a unique url is provided to check the progress of the
// submitted transactions, eg 'QUEUED' or 'PROCESSED', with response data from node. You can poll the provided unique
// url until all transactions are marked as 'PROCESSED'. Progress of the transactions are tracked on this unique url
// for up to 5 hours.
//
// For more information: https://developers.whatsonchain.com/#bulk-broadcast
func (c *Client) BulkBroadcastTx(ctx context.Context, rawTxs []string,
feedback bool) (response *BulkBroadcastResponse, err error) {
// Set a max (from WOC)
if len(rawTxs) > MaxBroadcastTransactions {
err = fmt.Errorf("max transactions are %d", MaxBroadcastTransactions)
return
}
// Set a total max
if len(strings.Join(rawTxs[:], ",")) > MaxCombinedTransactionSize {
err = fmt.Errorf("max overall payload of 10MB (%f bytes)", MaxCombinedTransactionSize)
return
}
// Check size of each tx
for _, tx := range rawTxs {
if len(tx) > MaxSingleTransactionSize {
err = fmt.Errorf("max tx size of 100kb (%d bytes)", MaxSingleTransactionSize)
return
}
}
// Start the post data
var postData []byte
if postData, err = json.Marshal(rawTxs); err != nil {
return nil, err
}
var resp string
// https://api.whatsonchain.com/v1/bsv/tx/broadcast?feedback=<feedback>
if resp, err = c.request(
ctx,
fmt.Sprintf("%stx/broadcast?feedback=%t", apiEndpoint, feedback),
http.MethodPost, postData,
); err != nil {
return
}
response = &BulkBroadcastResponse{Feedback: feedback}
if feedback {
if err = json.Unmarshal([]byte(resp), response); err != nil {
return
}
}
// Got an error
if c.lastRequest.StatusCode > http.StatusOK {
err = fmt.Errorf("error broadcasting: %s", resp)
}
return
}
// DecodeTransaction this endpoint decodes raw transaction
//
// For more information: https://developers.whatsonchain.com/#decode-transaction
func (c *Client) DecodeTransaction(ctx context.Context, txHex string) (txInfo *TxInfo, err error) {
// Start the post data
postData := []byte(fmt.Sprintf(`{"txhex":"%s"}`, txHex))
var resp string
// https://api.whatsonchain.com/v1/bsv/<network>/tx/decode
if resp, err = c.request(
ctx,
fmt.Sprintf("%s%s/tx/decode", apiEndpoint, c.Network()),
http.MethodPost, postData,
); err != nil {
return
}
if len(resp) == 0 {
return nil, ErrTransactionNotFound
}
err = json.Unmarshal([]byte(resp), &txInfo)
return
}
// DownloadReceipt this endpoint downloads a transaction receipt (PDF)
// The contents will be returned in plain-text and need to be converted to a file.pdf
//
// For more information: https://developers.whatsonchain.com/#download-receipt
func (c *Client) DownloadReceipt(ctx context.Context, hash string) (string, error) {
// https://<network>.whatsonchain.com/receipt/<hash>
// todo: this endpoint does not follow the convention of the WOC API v1
return c.request(
ctx,
fmt.Sprintf("https://%s.whatsonchain.com/receipt/%s", c.Network(), hash),
http.MethodGet, nil,
)
}