-
Notifications
You must be signed in to change notification settings - Fork 0
/
walletdRpc.go
427 lines (331 loc) · 14.6 KB
/
walletdRpc.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
421
422
423
424
425
426
427
// Copyright (c) 2018, The TurtleCoin Developers
// Copyright (c) 2019-2020 The Lithe Project
//
// Please see the included LICENSE file for more information.
// Package walletdrpc handles the the rpc connection between your app and walletd
package walletdrpc
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// Transfer contains all the information about a specific transfer
type Transfer struct {
PaymentID string
TxID string
Timestamp time.Time
Amount float64
Fee float64
Block int
Confirmations int
IsRecievingTransaction bool
}
var (
rpcURL = "http://127.0.0.1:8070/json_rpc"
)
// CreateDeposit creates a new deposit using an address, the amount and term expressed in blocks.
// i.e: term = 21900 means 21900 Blocks which is 1 Month on the Blockchain.
func CreateDeposit(sourceAddress string, amount float64, term int, rpcPassword string) (transactionHash string, err error) {
amountInt := uint64(amount * 1000000) // expressed in 6* of CCX
args := make(map[string]interface{})
args["amount"] = amountInt
args["sourceAddress"] = sourceAddress
args["term"] = term
payload := rpcPayloadCreateDeposit(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return "", errors.Wrap(err, "httpRequest failed")
}
responseError := responseMap["error"]
if responseError != nil {
return "", errors.Wrap(errors.New(responseError.(map[string]interface{})["message"].(string)), "response with error")
}
return responseMap["result"].(map[string]interface{})["transactionHash"].(string), nil
}
// GetDeposit shows the details of a deposit given the depositId.
func GetDeposit(id string, rpcPassword string) (amount float64, height int, intrest float64, locked bool, term int, unlockHeight int, err error) {
args := make(map[string]interface{})
args["depositId"] = id
payload := rpcPayloadGetDeposit(0, rpcPassword, args)
amountInt = int(responseMap["result"].(map[string]interface{})["amount"].(float64))
height = int(responseMap["result"].(map[string]interface{})["height"].(float64))
intrestInt = int(responseMap["result"].(map[string]interface{})["intrest"].(float64))
locked = bool(responseMap["result"].(map[string]interface{})["locked"].(bool))
term = int(responseMap["result"].(map[string]interface{})["term"].(float64))
unlockHeight = int(responseMap["result"].(map[string]interface{})["unlockHeight"].(float64))
amountInt := uint64(amount * 1000000) // expressed in 6* of CCX
intrestInt := uint64(intrest * 1000000) // expressed in 6* of CCX
responseMap, err := httpRequest(payload)
if err != nil {
return "", errors.Wrap(err, "httpRequest failed")
}
responseError := responseMap["error"]
if responseError != nil {
return "", errors.Wrap(errors.New(responseError.(map[string]interface{})["message"].(string)), "response with error")
}
return amount, height, intrest, locked, term, unlockHeight, nil
}
// RequestBalance provides the available and locked balances of the current wallet
// returned balances are expressed in CCX, not in 0.001 CCX
func RequestBalance(rpcPassword string) (availableBalance float64, lockedBalance float64, totalBalance float64, err error) {
args := make(map[string]interface{})
payload := rpcPayloadGetBalance(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return 0, 0, 0, errors.Wrap(err, "httpRequest failed")
}
if responseMap["result"] == nil {
return 0, 0, 0, errors.Wrap(err, "getBalance result is nil")
}
availableBalance = responseMap["result"].(map[string]interface{})["availableBalance"].(float64) / 100
lockedBalance = responseMap["result"].(map[string]interface{})["lockedAmount"].(float64) / 100
totalBalance = availableBalance + lockedBalance
return availableBalance, lockedBalance, totalBalance, nil
}
// RequestAddress provides the address of the current wallet
func RequestAddress(rpcPassword string) (address string, err error) {
args := make(map[string]interface{})
payload := rpcPayloadGetAddresses(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return "", errors.Wrap(err, "httpRequest failed")
}
walletAddresses := responseMap["result"].(map[string]interface{})["addresses"].([]interface{})
address = walletAddresses[0].(string)
return address, nil
}
// RequestListTransactions provides the list of transactions of current wallet
func RequestListTransactions(blockCount int, firstBlockIndex int, addresses []string, rpcPassword string) (transfers []Transfer, err error) {
args := make(map[string]interface{})
args["blockCount"] = blockCount
args["firstBlockIndex"] = firstBlockIndex
args["addresses"] = addresses
payload := rpcPayloadGetTransactions(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return nil, errors.Wrap(err, "httpRequest failed")
}
if responseMap["result"] == nil {
return nil, nil
}
blocks := responseMap["result"].(map[string]interface{})["items"].([]interface{})
for _, block := range blocks {
transactions := block.(map[string]interface{})["transactions"].([]interface{})
for _, transaction := range transactions {
mapTransaction := transaction.(map[string]interface{})
var transfer Transfer
transfer.PaymentID = mapTransaction["paymentId"].(string)
transfer.TxID = mapTransaction["transactionHash"].(string)
transfer.Timestamp = time.Unix(int64(mapTransaction["timestamp"].(float64)), 0)
transfer.Amount = mapTransaction["amount"].(float64) / 100
transfer.Fee = mapTransaction["fee"].(float64) / 100
transfer.Block = int(mapTransaction["blockIndex"].(float64))
transfer.Confirmations = blockCount - transfer.Block + 1
transfer.IsRecievingTransaction = transfer.Amount >= 0
transfers = append(transfers, transfer)
}
}
return transfers, nil
}
// RequestStatus requests walletd connection and sync status
func RequestStatus(rpcPassword string) (walletBlockCount int, knownBlockCount int, peerCount int, err error) {
args := make(map[string]interface{})
payload := rpcPayloadGetStatus(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return 0, 0, 0, errors.Wrap(err, "httpRequest failed")
}
walletBlockCount = int(responseMap["result"].(map[string]interface{})["blockCount"].(float64))
knownBlockCount = int(responseMap["result"].(map[string]interface{})["knownBlockCount"].(float64))
peerCount = int(responseMap["result"].(map[string]interface{})["peerCount"].(float64))
return walletBlockCount, knownBlockCount, peerCount, nil
}
// SendTransaction makes a transfer with the provided information.
// parameters amount and fee are expressed in CCX, not 0.001 CCX
func SendTransaction(addressRecipient string, amount float64, paymentID string, fee float64, rpcPassword string) (transactionHash string, err error) {
amountInt := uint64(amount * 1000000) // expressed in 6* of CCX
feeInt := uint64(fee * 1000000) // expressed in 6* of CCX
args := make(map[string]interface{})
args["fee"] = feeInt
args["paymentId"] = paymentID
var transfers [1]map[string]interface{}
transfer := make(map[string]interface{})
transfer["amount"] = amountInt
transfer["address"] = addressRecipient
transfers[0] = transfer
args["transfers"] = transfers
payload := rpcPayloadSendTransaction(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return "", errors.Wrap(err, "httpRequest failed")
}
responseError := responseMap["error"]
if responseError != nil {
return "", errors.Wrap(errors.New(responseError.(map[string]interface{})["message"].(string)), "response with error")
}
return responseMap["result"].(map[string]interface{})["transactionHash"].(string), nil
}
// GetViewKey provides the private view key
func GetViewKey(rpcPassword string) (privateViewKey string, err error) {
args := make(map[string]interface{})
payload := rpcPayloadGetViewKey(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return "", errors.Wrap(err, "httpRequest failed")
}
privateViewKey = responseMap["result"].(map[string]interface{})["viewSecretKey"].(string)
return privateViewKey, nil
}
// GetSpendKeys provides the private and public spend keys
func GetSpendKeys(address string, rpcPassword string) (spendSecretKey string, spendPublicKey string, err error) {
args := make(map[string]interface{})
args["address"] = address
payload := rpcPayloadGetSpendKeys(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return "", "", err
}
spendSecretKey = responseMap["result"].(map[string]interface{})["spendSecretKey"].(string)
spendPublicKey = responseMap["result"].(map[string]interface{})["spendSecretKey"].(string)
return spendSecretKey, spendPublicKey, nil
}
/*
// GetMnemonicSeed provides the mnemonic seed.
func GetMnemonicSeed(address string, rpcPassword string) (isDeterministicWallet bool, mnemonicSeed string, err error) {
args := make(map[string]interface{})
args["address"] = address
payload := rpcPayloadGetMnemonicSeed(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return false, "", err
}
if responseMap["result"] == nil { // wallet is not deterministic. error in the response is: application_code:6 message:"Keys not deterministic"
return false, "", nil
}
mnemonicSeed = responseMap["result"].(map[string]interface{})["mnemonicSeed"].(string)
return true, mnemonicSeed, nil
}
*/
// SaveWallet saves the sync info in the wallet
func SaveWallet(rpcPassword string) (err error) {
args := make(map[string]interface{})
payload := rpcPayloadSave(0, rpcPassword, args)
_, err = httpRequest(payload)
if err != nil {
return errors.Wrap(err, "httpRequest failed")
}
return nil
}
// EstimateFusion counts the number of unspent outputs of the specified addresses and returns how many of those outputs can be optimized. This method is used to understand if a fusion transaction can be created. If fusionReadyCount returns a value = 0, then a fusion transaction cannot be created.
// threshold is the value that determines which outputs will be optimized. Only the outputs, lesser than the threshold value, will be included into a fusion transaction (threshold is expressed in CCX, not 0.001 CCX).
// fusionReadyCount is the number of outputs that can be optimized.
// totalOutputCount is the total number of unspent outputs of the specified addresses.
func EstimateFusion(threshold int, addresses []string, rpcPassword string) (fusionReadyCount int, totalOutputCount int, err error) {
threshold *= 1000000 // expressed in 6* of CCX
args := make(map[string]interface{})
args["threshold"] = threshold
args["addresses"] = addresses
payload := rpcPayloadEstimateFusion(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return 0, 0, errors.Wrap(err, "httpRequest failed")
}
fusionReadyCount = int(responseMap["result"].(map[string]interface{})["fusionReadyCount"].(float64))
totalOutputCount = int(responseMap["result"].(map[string]interface{})["totalOutputCount"].(float64))
return fusionReadyCount, totalOutputCount, nil
}
// SendFusionTransaction allows you to send a fusion transaction, by taking funds from selected addresses and transferring them to the destination address.
// threshold is the value that determines which outputs will be optimized. Only the outputs, lesser than the threshold value, will be included into a fusion transaction (threshold is expressed in CCX, not 0.001 CCX).
// parameters amount and fee are expressed in CCX, not 0.001 CCX
func SendFusionTransaction(threshold int, addresses []string, destinationAddress string, rpcPassword string) (transactionHash string, err error) {
threshold *= 100 // expressed in hundredth of CCX
args := make(map[string]interface{})
args["threshold"] = threshold
args["addresses"] = addresses
args["destinationAddress"] = destinationAddress
payload := rpcPayloadSendFusionTransaction(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return "", errors.Wrap(err, "httpRequest failed")
}
responseError := responseMap["error"]
if responseError != nil {
return "", errors.Wrap(errors.New(responseError.(map[string]interface{})["message"].(string)), "response with error")
}
return responseMap["result"].(map[string]interface{})["transactionHash"].(string), nil
}
/*
// GetFeeInfo returns info on the fee requested by the remote node for every transactions
// returned fee is expressed in CCX, not in 0.001 CCX
func GetFeeInfo(rpcPassword string) (address string, fee float64, status string, err error) {
args := make(map[string]interface{})
payload := rpcPayloadGetFeeInfo(0, rpcPassword, args)
responseMap, err := httpRequest(payload)
if err != nil {
return "", 0, "", errors.Wrap(err, "httpRequest failed")
}
responseError := responseMap["error"]
if responseError != nil {
return "", 0, "", errors.Wrap(errors.New(responseError.(map[string]interface{})["message"].(string)), "response with error")
}
result := responseMap["result"]
if result == nil {
return "", 0, "", errors.New("result from feeinfo request is nil")
}
resultAddress := result.(map[string]interface{})["address"]
if resultAddress != nil {
address = resultAddress.(string)
} else {
address = ""
}
resultAmount := result.(map[string]interface{})["amount"]
if resultAmount != nil {
fee = resultAmount.(float64) / 100
} else {
fee = 0
}
if address == "" && fee > 0 {
return "", 0, "", errors.New("fee info is not valid")
}
resultStatus := result.(map[string]interface{})["status"]
if resultStatus != nil {
status = resultStatus.(string)
} else {
status = ""
}
return address, fee, status, nil
}
*/
func httpRequest(payload rpcPayload) (responseMap map[string]interface{}, err error) {
payloadjson, err := json.Marshal(payload)
if err != nil {
log.Fatal("error json marshal: ", err)
}
req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson))
if err != nil {
log.Fatal("error creating http request: ", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("error reading result from rpc request getSpendKey:", err)
} else {
var responseBodyInterface interface{}
if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil {
log.Fatal("JSON unmarshaling with interface failed:", err)
} else {
responseMap := responseBodyInterface.(map[string]interface{})
return responseMap, nil
}
}
return nil, errors.New("unknown error")
}