This repository has been archived by the owner on Feb 24, 2023. It is now read-only.
/
rpc.go
224 lines (190 loc) · 5.37 KB
/
rpc.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
package eth
import (
"crypto/ecdsa"
"encoding/hex"
"errors"
"fmt"
"math/big"
"strconv"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rpc"
)
type Signature struct {
V uint8 `json:"v"`
R common.Hash `json:"r"`
S common.Hash `json:"s"`
}
func (sig Signature) String() string {
return fmt.Sprintf("%d,%s,%s", sig.V, sig.R.Hex(), sig.S.Hex())
}
var pk *ecdsa.PrivateKey
var rpcClient *rpc.Client
// SetPrivateKey transform private key string to ECDSA Key
func SetPrivateKey(newPrivateKey string) error {
_pk, err := crypto.HexToECDSA(newPrivateKey)
if err != nil {
return err
}
pk = _pk
return nil
}
// SetRpcClient receive url of ethereum node to initiate rpcClient
func SetRpcClient(rpcUrl string) error {
var err error
rpcClient, err = rpc.Dial(rpcUrl)
if err != nil {
return err
}
return nil
}
// GetAddress returns the address of the
func GetAddress() (common.Address, error) {
if pk != nil {
return crypto.PubkeyToAddress(pk.PublicKey), nil
}
var result []string
err := rpcClient.Call(&result, "eth_accounts")
if err != nil {
return common.Address{}, err
}
if len(result) == 0 {
return common.Address{}, errors.New("GetAddress: no address found")
}
return common.HexToAddress(result[0]), nil
}
// GetStorageAt returns the value at the given storage location of the given Ethereum
// contract address.
func GetStorageAt(contract common.Address, location common.Hash) (common.Hash, error) {
if rpcClient == nil {
return common.Hash{}, errors.New("GetStorageAt: Initialization is required")
}
var result string
err := rpcClient.Call(&result, "eth_getStorageAt", contract.Hex(), location.Hex(), "latest")
if err != nil {
return common.Hash{}, err
}
return common.HexToHash(result), nil
}
// SignMessage returns the signature of signing the given message using Ethereum's message
// signing scheme.
func SignMessage(message []byte) (Signature, error) {
withPrefix := append([]byte("\x19Ethereum Signed Message:\n32"), crypto.Keccak256(message)...)
msgHash := crypto.Keccak256(withPrefix)
if pk != nil {
signature, _ := crypto.Sign(msgHash, pk)
signature[len(signature)-1] += 27
return Signature{
uint8(int(signature[64])),
common.BytesToHash(signature[0:32]),
common.BytesToHash(signature[32:64]),
}, nil
}
if rpcClient == nil {
return Signature{}, errors.New("SignMessage: Initialization is required")
}
signerAddress, err := GetAddress()
if err != nil {
return Signature{}, errors.New("SignMessage: Can not get signer address")
}
var result string
err = rpcClient.Call(&result, "eth_sign", signerAddress.Hex(), "0x"+common.Bytes2Hex(crypto.Keccak256(message)))
if err != nil {
return Signature{}, err
}
if len(result) != 132 {
return Signature{}, errors.New("SignMessage: wrong signature format")
}
signature, err := hex.DecodeString(result[2:])
if err != nil {
return Signature{}, err
}
return Signature{
uint8(int(signature[64])),
common.BytesToHash(signature[0:32]),
common.BytesToHash(signature[32:64]),
}, nil
}
func CallContract(to common.Address, data []byte) ([]byte, error) {
var result string
params := make(map[string]string)
from, err := GetAddress()
if err == nil {
params["from"] = from.Hex()
}
// Mock gas price and gas limit for kovan
params["to"] = to.Hex()
params["gas"] = "0xf4240"
params["gasPrice"] = "0x0"
params["value"] = "0x0"
params["data"] = fmt.Sprintf("0x%x", data)
err = rpcClient.Call(&result, "eth_call", params, "latest")
if err != nil {
return []byte{}, err
}
return hex.DecodeString(result[2:])
}
func GetNonce() (uint64, error) {
sender, err := GetAddress()
if err != nil {
return 0, err
}
var result string
err = rpcClient.Call(&result, "eth_getTransactionCount", sender.Hex(), "latest")
if err != nil {
return 0, err
}
if len(result) < 2 {
return 0, errors.New(fmt.Sprintf("wrong result format %s", result))
}
return strconv.ParseUint(result[2:], 16, 64)
}
// SendTransaction broadcasts the given message to the Ethereum network. This function also
// handles transaction signing.
func SendTransaction(to common.Address, data []byte) (common.Hash, error) {
// TODO : revisit -> chainId , gas , gasPrice
nonce, err := GetNonce()
if err != nil {
return common.Hash{}, err
}
var signedTx *types.Transaction
if pk != nil {
// TODO: Remove hard code gas price and gas limit.
tx := types.NewTransaction(
nonce,
to,
big.NewInt(0),
1000000,
big.NewInt(1e9),
data,
)
signer := types.NewEIP155Signer(big.NewInt(42)) // kovan
signedTx, err = types.SignTx(tx, signer, pk)
if err != nil {
return common.Hash{}, err
}
txRlp := "0x" + common.Bytes2Hex(types.Transactions{signedTx}.GetRlp(0))
var txHash string
err = rpcClient.Call(&txHash, "eth_sendRawTransaction", txRlp)
if err != nil {
return common.Hash{}, err
}
return common.HexToHash(txHash), nil
}
var txHash string
params := make(map[string]string)
from, err := GetAddress()
params["nonce"] = fmt.Sprintf("0x%x", nonce)
params["from"] = from.Hex()
params["to"] = to.Hex()
params["gas"] = "0xf4240"
params["gasPrice"] = "0x2540be400"
params["value"] = "0x0"
params["data"] = fmt.Sprintf("0x%x", data)
err = rpcClient.Call(&txHash, "eth_sendTransaction", params)
if err != nil {
return common.Hash{}, err
}
return common.HexToHash(txHash), nil
}