-
Notifications
You must be signed in to change notification settings - Fork 22
/
tx_utils.go
220 lines (180 loc) · 6.07 KB
/
tx_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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
utils for packet Transactions
*/
package packet
import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/Venachain/Venachain/cmd/ptransfer/client/utils"
"github.com/Venachain/Venachain/accounts/abi"
"github.com/Venachain/Venachain/common"
"github.com/Venachain/Venachain/common/hexutil"
"github.com/Venachain/Venachain/core/types"
)
// ContractReturn, system contract return object
type ContractReturn struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// ParseSysContractResult parsed the result to ContractReturn object
func ParseSysContractResult(result []byte) (*ContractReturn, error) {
a := ContractReturn{} //删除?
err := json.Unmarshal(result, &a)
if err != nil {
// utils.Fatalf(utl.ErrUnmarshalBytesFormat, "contract return", err.Error())
errStr := fmt.Sprintf(utils.ErrUnmarshalBytesFormat, "contract return", err.Error())
return nil, errors.New(errStr)
}
return &a, nil
}
//================================CNS=================================
type Cns struct {
To string
Name string // the cns name of contract
txType uint64 // the transaction type of the contract execution (EXECUTE_CONTRACT or CNS_TX_TYPE)
}
func NewCns(to, name string, txType uint64) *Cns {
return &Cns{
To: to,
Name: name,
txType: txType,
}
}
//================================ABI================================
// todo: change FuncDesc to Method in abi/method.go
// FuncDesc, the object of the contract abi files
type FuncDesc struct {
Name string `json:"name"`
Inputs []abi.ArgumentMarshaling `json:"inputs"`
Outputs []abi.ArgumentMarshaling `json:"outputs"`
Constant interface{} `json:"constant"` // ???
Type string `json:"type"`
StateMutability string `json:"stateMutability,omitempty"` // tag for solidity ver > 0.6.0
}
type FuncIO struct {
Name string `json:"name"`
Type string `json:"type"`
Indexed bool `json:"indexed,omitempty"`
InternalType string `json:"internalType,omitempty"`
Components []FuncIO `json:"components,omitempty"`
}
// ParseFuncFromAbi searches the function (or event) names in the []FuncDesc object array
func ParseFuncFromAbi(abiBytes []byte, name string) (*FuncDesc, error) {
funcs, err := ParseAbiFromJson(abiBytes)
if err != nil {
return nil, err
}
for _, value := range funcs {
if value.Name == name {
return &value, nil
}
}
funcList := ListAbiFuncName(funcs)
return nil, fmt.Errorf("function/event %s is not found in\n%s", name, funcList)
}
//
func ListAbiFuncName(abiFuncs []FuncDesc) string {
var result string
result = fmt.Sprintf("-------------------contract methods list------------------------\n")
for _, function := range abiFuncs {
strInput := []string{}
strOutput := []string{}
for _, param := range function.Inputs {
strInput = append(strInput, param.Name+" "+param.Type)
}
for _, param := range function.Outputs {
strOutput = append(strOutput, param.Name+" "+param.Type)
}
result += fmt.Sprintf("%s: ", function.Type)
result += fmt.Sprintf("%s(%s)%s\n", function.Name, strings.Join(strInput, ","), strings.Join(strOutput, ","))
}
return result
}
// ParseAbiFromJson parses the application binary interface(abi) files to []FuncDesc object array
func ParseAbiFromJson(abiBytes []byte) ([]FuncDesc, error) {
var a []FuncDesc
if abiBytes == nil {
return nil, errors.New("abiBytes are null")
}
if err := json.Unmarshal(abiBytes, &a); err != nil {
return nil, fmt.Errorf(utils.ErrUnmarshalBytesFormat, "abi", err.Error())
}
return a, nil
}
//=========================Transaction=================================
// TxParamsDemo, the object of the eth_call, eth_sendTransaction
type TxParams struct {
From common.Address `json:"from"` // the address used to send the transaction
To *common.Address `json:"to"` // the address receives the transactions
Gas string `json:"gas"`
GasPrice string `json:"gasPrice"`
Value string `json:"value"`
Data string `json:"data"`
}
// NewTxParams news a TxParams object
func NewTxParams(from common.Address, to *common.Address, value, gas, gasPrice, data string) *TxParams {
tx := &TxParams{
From: from,
To: to,
GasPrice: gasPrice,
Gas: gas,
Value: value,
Data: data,
}
return tx
}
// SendMode selects the rpc calls (eth_call, eth_sendTransaction, and eth_sendRawTransaction)
func (tx *TxParams) SendMode(isWrite bool, keyfileJson []byte) ([]interface{}, string) {
var action string
var params = make([]interface{}, 0)
switch {
case !isWrite:
params = append(params, tx)
params = append(params, "latest")
action = "eth_call"
case len(keyfileJson) != 0:
signedTx := tx.GetSignedTx(keyfileJson)
params = append(params, signedTx)
action = "eth_sendRawTransaction"
default:
params = append(params, tx)
action = "eth_sendTransaction"
}
return params, action
}
// GetSignedTx gets the signed transaction
func (tx *TxParams) GetSignedTx(keyfileJson []byte) string {
var txSign *types.Transaction
// convert the TxParams object to types.Transaction object
nonce := getNonceRand()
value, _ := hexutil.DecodeBig(tx.Value)
gas, _ := hexutil.DecodeUint64(tx.Gas)
gasPrice, _ := hexutil.DecodeBig(tx.GasPrice)
data, _ := hexutil.Decode(tx.Data)
if tx.To == nil {
txSign = types.NewContractCreation(nonce, value, gas, gasPrice, data)
} else {
txSign = types.NewTransaction(nonce, *tx.To, value, gas, gasPrice, data)
}
// extract pk from keystore file and sign the transaction
priv := utils.GetPrivateKey(keyfileJson)
txSign, _ = types.SignTx(txSign, types.HomesteadSigner{}, priv)
/// utl.Logger.Printf("the signed transaction is %v\n", txSign)
str, err := rlpEncode(txSign)
if err != nil {
panic(err)
}
return str
}
// getNonceRand generate a random nonce
// Warning: if the design of the nonce mechanism is modified
// this part should be modified as well
func getNonceRand() uint64 {
rand.Seed(time.Now().Unix())
return rand.Uint64()
}