-
Notifications
You must be signed in to change notification settings - Fork 11
/
api.go
399 lines (340 loc) · 11.1 KB
/
api.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
package wallet
import (
"encoding/hex"
corejson "github.com/Qitmeer/qitmeer/core/json"
"time"
"github.com/Qitmeer/qitmeer-wallet/config"
clijson "github.com/Qitmeer/qitmeer-wallet/json"
"github.com/Qitmeer/qitmeer-wallet/json/qitmeerjson"
"github.com/Qitmeer/qitmeer-wallet/utils"
waddrmgr "github.com/Qitmeer/qitmeer-wallet/waddrmgs"
"github.com/Qitmeer/qitmeer-wallet/wallet/txrules"
"github.com/Qitmeer/qitmeer-wallet/wtxmgr"
"github.com/Qitmeer/qitmeer/core/address"
"github.com/Qitmeer/qitmeer/core/types"
"github.com/Qitmeer/qitmeer/crypto/ecc/secp256k1"
"github.com/Qitmeer/qitmeer/log"
)
// API for wallet
type API struct {
cfg *config.Config
wt *Wallet
}
// NewAPI make api
func NewAPI(cfg *config.Config, wt *Wallet) *API {
return &API{
cfg: cfg,
wt: wt,
}
}
//SyncStats block update stats
type SyncStats struct {
Height int32
}
// SyncStats block update stats
func (api *API) SyncStats() (*SyncStats, error) {
stats := &SyncStats{}
stats.Height = api.wt.SyncHeight //api.wt.Manager.SyncedTo().Height
return stats, nil
}
//Unlock wallet
func (api *API) Unlock(walletPriPass string, second int64) error {
//if api.wSvr.Wt.Locked() {
var dur <-chan time.Time
if second < 0 {
dur = nil
} else {
dur = time.After(time.Duration(second) * time.Second)
}
err := api.wt.Unlock([]byte(walletPriPass), dur)
if err != nil {
log.Error("Failed to unlock new wallet during old wallet key import", "err", err)
return err
}
return nil
}
//Lock wallet
func (api *API) Lock() error {
api.wt.Lock()
return nil
}
// GetAccountsAndBalance List all accounts[{account,balance}]
func (api *API) GetAccountsAndBalance() (map[string]*Balance, error) {
accountsBalances := make(map[string]*Balance)
aaas, err := api.wt.GetAccountAndAddress(waddrmgr.KeyScopeBIP0044)
if err != nil {
return nil, err
}
for _, aaa := range aaas {
if _, ok := accountsBalances[aaa.AccountName]; !ok {
accountsBalances[aaa.AccountName] = &Balance{}
}
accountBalance := accountsBalances[aaa.AccountName]
for _, addr := range aaa.AddrsOutput {
accountBalance.ConfirmAmount = accountBalance.ConfirmAmount + addr.balance.ConfirmAmount
accountBalance.SpendAmount = accountBalance.SpendAmount + addr.balance.SpendAmount
accountBalance.TotalAmount = accountBalance.TotalAmount + addr.balance.TotalAmount
accountBalance.UnspendAmount = accountBalance.UnspendAmount + addr.balance.UnspendAmount
}
}
return accountsBalances, nil
}
// GetBalanceByAccount get account balance
func (api *API) GetBalanceByAccount(name string) (*Balance, error) {
results, err := api.wt.GetAccountAndAddress(waddrmgr.KeyScopeBIP0044)
if err != nil {
return nil, err
}
accountBalance := &Balance{}
for _, result := range results {
if result.AccountName == name {
for _, addr := range result.AddrsOutput {
accountBalance.ConfirmAmount = accountBalance.ConfirmAmount + addr.balance.ConfirmAmount
accountBalance.SpendAmount = accountBalance.SpendAmount + addr.balance.SpendAmount
accountBalance.TotalAmount = accountBalance.TotalAmount + addr.balance.TotalAmount
accountBalance.UnspendAmount = accountBalance.UnspendAmount + addr.balance.UnspendAmount
}
}
}
return accountBalance, nil
}
// GetUTxo addr unSpend UTxo
func (api *API) GetUTxo(addr string) ([]wtxmgr.UTxo, error) {
results, err := api.wt.GetUtxo(addr)
if err != nil {
return nil, err
}
return results, nil
}
// GetTx get transaction by ID
func (api *API) GetTx(txID string) (*corejson.TxRawResult, error) {
result, err := api.wt.GetTx(txID)
if err != nil {
return nil, err
}
return &result, nil
}
// CreateAccount create account
func (api *API) CreateAccount(name string) error {
// The wildcard * is reserved by the rpc server with the special meaning
// of "all accounts", so disallow naming accounts to this string.
if name == "*" {
return &qitmeerjson.ErrReservedAccountName
}
_, err := api.wt.NextAccount(waddrmgr.KeyScopeBIP0044, name)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
return &qitmeerjson.RPCError{
Code: qitmeerjson.ErrRPCWalletUnlockNeeded,
Message: "Creating an account requires the wallet to be unlocked. " +
"Enter the wallet passphrase with walletpassphrase to unlock",
}
}
return nil
}
// CreateAddress by accountName
func (api *API) CreateAddress(accountName string) (string, error) {
if accountName == "" {
accountName = "default"
}
account, err := api.wt.AccountNumber(waddrmgr.KeyScopeBIP0044, accountName)
if err != nil {
return "", err
}
addr, err := api.wt.NewAddress(waddrmgr.KeyScopeBIP0044, account)
if err != nil {
return "", err
}
// Return the new payment address string.
return addr.Encode(), nil
}
// GetAddressesByAccount by account
func (api *API) GetAddressesByAccount(accountName string) ([]string, error) {
account, err := api.wt.AccountNumber(waddrmgr.KeyScopeBIP0044, accountName)
if err != nil {
return nil, err
}
adds, err := api.wt.AccountAddresses(account)
if err != nil {
return nil, err
}
addrStr := make([]string, len(adds))
for i, a := range adds {
addrStr[i] = a.Encode()
}
return addrStr, nil
}
// GetAccountByAddress get account name
func (api *API) GetAccountByAddress(addrStr string) (string, error) {
addr, err := address.DecodeAddress(addrStr)
if err != nil {
return "", err
}
// Fetch the associated account
account, err := api.wt.AccountOfAddress(addr)
if err != nil {
return "", &qitmeerjson.ErrAddressNotInWallet
}
acctName, err := api.wt.AccountName(waddrmgr.KeyScopeBIP0044, account)
if err != nil {
return "", &qitmeerjson.ErrAccountNameNotFound
}
return acctName, nil
}
// DumpPrivKey dump a single address private key
//
// dumpPriKey handles a DumpPrivKey request with the private key
// for a single address, or an appropiate error if the wallet
// is locked.
func (api *API) DumpPrivKey(addrStr string) (string, error) {
addr, err := address.DecodeAddress(addrStr)
if err != nil {
return "", err
}
key, err := api.wt.DumpWIFPrivateKey(addr)
if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
// Address was found, but the private key isn't
// accessible.
return "", &qitmeerjson.ErrWalletUnlockNeeded
}
return key, err
}
// ImportWifPrivKey import a WIF-encoded private key and adding it to an account
// a WIF-encoded private key and adding it to an account.
func (api *API) ImportWifPrivKey(accountName string, key string) error {
// Ensure that private keys are only imported to the correct account.
if accountName != "" && accountName != waddrmgr.ImportedAddrAccountName {
return &qitmeerjson.ErrNotImportedAccount
}
wif, err := utils.DecodeWIF(key, api.wt.ChainParams())
if err != nil {
return &qitmeerjson.RPCError{
Code: qitmeerjson.ErrRPCInvalidAddressOrKey,
Message: "WIF decode failed: " + err.Error(),
}
}
if !wif.IsForNet(api.wt.ChainParams()) {
return &qitmeerjson.RPCError{
Code: qitmeerjson.ErrRPCInvalidAddressOrKey,
Message: "Key is not intended for " + api.wt.ChainParams().Name,
}
}
// Import the private key, handling any errors.
_, err = api.wt.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif)
switch {
case waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress):
// Do not return duplicate key errors to the client.
return nil
case waddrmgr.IsError(err, waddrmgr.ErrLocked):
return &qitmeerjson.ErrWalletUnlockNeeded
}
return err
}
// ImportPrivKey import pri key
func (api *API) ImportPrivKey(accountName string, key string) error {
// Ensure that private keys are only imported to the correct account.
//
// Yes, Label is the account name.
if accountName != "" && accountName != waddrmgr.ImportedAddrAccountName {
return &qitmeerjson.ErrNotImportedAccount
}
priHash, err := hex.DecodeString(key)
if err != nil {
return err
}
pri, _ := secp256k1.PrivKeyFromBytes(priHash)
wif, err := utils.NewWIF(pri, api.wt.ChainParams(), true)
if err != nil {
return &qitmeerjson.RPCError{
Code: qitmeerjson.ErrRPCInvalidAddressOrKey,
Message: "private key decode failed: " + err.Error(),
}
}
if !wif.IsForNet(api.wt.ChainParams()) {
return &qitmeerjson.RPCError{
Code: qitmeerjson.ErrRPCInvalidAddressOrKey,
Message: "Key is not intended for " + api.wt.ChainParams().Name,
}
}
// Import the private key, handling any errors.
_, err = api.wt.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif)
switch {
case waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress):
// Do not return duplicate key errors to the client.
return nil
case waddrmgr.IsError(err, waddrmgr.ErrLocked):
return &qitmeerjson.ErrWalletUnlockNeeded
}
return err
}
//SendToAddress handles a sendtoaddress RPC request by creating a new
//transaction spending unspent transaction outputs for a wallet to another
//payment address. Leftover inputs not sent to the payment address or a fee
//for the miner are sent back to a new address in the wallet. Upon success,
//the TxID for the created transaction is returned.
func (api *API) SendToAddress(addressStr string, amount float64) (string, error) {
amt, err := types.NewAmount(amount)
if err != nil {
return "", err
}
// Check that signed integer parameters are positive.
if amt < 0 {
return "", qitmeerjson.ErrNeedPositiveAmount
}
// Mock up map of address and amount pairs.
pairs := map[string]types.Amount{
addressStr: amt,
}
return api.wt.SendPairs(pairs, waddrmgr.AccountMergePayNum, txrules.DefaultRelayFeePerKb)
}
func (api *API) SendToMany(addAmounts map[string]float64) (string, error) {
pairs := make(map[string]types.Amount)
for addr, amount := range addAmounts {
amt, err := types.NewAmount(amount)
if err != nil {
return "", err
}
if amt < 0 {
return "", qitmeerjson.ErrNeedPositiveAmount
}
pairs[addr] = amt
}
return api.wt.SendPairs(pairs, waddrmgr.AccountMergePayNum, txrules.DefaultRelayFeePerKb)
}
// SendToAddressByAccount by account
func (api *API) SendToAddressByAccount(accountName string, addressStr string, amount float64, comment string, commentTo string) (string, error) {
accountNum, err := api.wt.AccountNumber(waddrmgr.KeyScopeBIP0044, accountName)
if err != nil {
return "", err
}
amt, err := types.NewAmount(amount)
if err != nil {
return "", err
}
// Check that signed integer parameters are positive.
if amt < 0 {
return "", qitmeerjson.ErrNeedPositiveAmount
}
// Mock up map of address and amount pairs.
pairs := map[string]types.Amount{
addressStr: amt,
}
return api.wt.SendPairs(pairs, int64(accountNum), txrules.DefaultRelayFeePerKb)
}
//GetBalanceByAddr get balance by address
func (api *API) GetBalanceByAddr(addrStr string) (*Balance, error) {
m, err := api.wt.GetBalance(addrStr)
if err != nil {
return nil, err
}
return m, nil
}
//GetTxListByAddr get transactions affecting specific address, one transaction could affect MULTIPLE addresses
func (api *API) GetTxListByAddr(addr string, sType int, page int, pageSize int) (*clijson.PageTxRawResult, error) {
rs, err := api.wt.GetListTxByAddr(addr, sType, page, pageSize)
return rs, err
}
//GetBillByAddr get bill of payments affecting specific address, one payment could affect ONE address
func (api *API) GetBillByAddr(addr string, filter int, page int, pageSize int) (*clijson.PagedBillResult, error) {
rs, err := api.wt.GetBillByAddr(addr, filter, page, pageSize)
return rs, err
}