-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchain.go
84 lines (80 loc) · 2.04 KB
/
chain.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
package main
import (
"io/ioutil"
"net/http"
"bytes"
"encoding/json"
"errors"
)
//returns info from node chain api
func getInfo(seedNode string) (*ChainGetInfoResult, error) {
if len(seedNode) > 0 && seedNode[len(seedNode)-1] != '/' {
seedNode = seedNode + "/"
}
resp, err := http.Get(seedNode + "v1/chain/get_info")
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}
result := new(ChainGetInfoResult)
err = json.Unmarshal(bytes, &result)
return result, err
}
//takes blockNum and transactionId as arguments
//retrieves block from node chain api
//searches requested transaction in retrieved block
//returns the trx->trx field contents in the correct format
func getTransactionFromBlock(seedNode string, blockNum json.RawMessage, txId string) (json.RawMessage, error) {
if len(seedNode) > 0 && seedNode[len(seedNode)-1] != '/' {
seedNode = seedNode + "/"
}
var result json.RawMessage
u := GetBlockParams { BlockNum: blockNum }
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(u)
resp, err := http.Post(seedNode + "v1/chain/get_block", "application/json", b)
if err != nil {
return result, err
}
bytes, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return result, err
}
var getBlockResult ChainGetBlockResult
err = json.Unmarshal(bytes, &getBlockResult)
if err != nil {
return result, err
}
for _, trx := range getBlockResult.Transactions {
var tmp interface{}
err = json.Unmarshal(trx.Trx, &tmp)
if err != nil {
return result, err
}
if s, ok := tmp.(string); ok {
if s != txId {
continue
}
result, err := json.Marshal([]interface{}{0, s})
return result, err
} else {
var resTrx TransactionFromBlock
err = json.Unmarshal(trx.Trx, &resTrx)
if err != nil {
return result, err
}
if resTrx.Id != txId {
continue
}
resTrx.Id = ""
result, err := json.Marshal([]interface{}{1, resTrx})
return result, err
}
}
return result, errors.New("Transaction not found")
}