-
Notifications
You must be signed in to change notification settings - Fork 100
/
RpcServer.Wallet.cs
352 lines (324 loc) · 13.3 KB
/
RpcServer.Wallet.cs
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
#pragma warning disable IDE0051
#pragma warning disable IDE0060
using Akka.Actor;
using Neo.IO;
using Neo.IO.Json;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.Wallets;
using Neo.Wallets.NEP6;
using Neo.Wallets.SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using static System.IO.Path;
namespace Neo.Plugins
{
partial class RpcServer
{
private class DummyWallet : Wallet
{
public DummyWallet() : base("") { }
public override string Name => "";
public override Version Version => new Version();
public override bool ChangePassword(string oldPassword, string newPassword) => false;
public override bool Contains(UInt160 scriptHash) => false;
public override WalletAccount CreateAccount(byte[] privateKey) => null;
public override WalletAccount CreateAccount(Contract contract, KeyPair key = null) => null;
public override WalletAccount CreateAccount(UInt160 scriptHash) => null;
public override bool DeleteAccount(UInt160 scriptHash) => false;
public override WalletAccount GetAccount(UInt160 scriptHash) => null;
public override IEnumerable<WalletAccount> GetAccounts() => Array.Empty<WalletAccount>();
public override bool VerifyPassword(string password) => false;
}
private Wallet wallet;
private void CheckWallet()
{
if (wallet is null)
throw new RpcException(-400, "Access denied");
}
[RpcMethod]
private JObject CloseWallet(JArray _params)
{
wallet = null;
return true;
}
[RpcMethod]
private JObject DumpPrivKey(JArray _params)
{
CheckWallet();
UInt160 scriptHash = AddressToScriptHash(_params[0].AsString());
WalletAccount account = wallet.GetAccount(scriptHash);
return account.GetKey().Export();
}
[RpcMethod]
private JObject GetNewAddress(JArray _params)
{
CheckWallet();
WalletAccount account = wallet.CreateAccount();
if (wallet is NEP6Wallet nep6)
nep6.Save();
return account.Address;
}
[RpcMethod]
private JObject GetWalletBalance(JArray _params)
{
CheckWallet();
UInt160 asset_id = UInt160.Parse(_params[0].AsString());
JObject json = new JObject();
json["balance"] = wallet.GetAvailable(asset_id).Value.ToString();
return json;
}
[RpcMethod]
private JObject GetWalletUnclaimedGas(JArray _params)
{
CheckWallet();
BigInteger gas = BigInteger.Zero;
using (SnapshotView snapshot = Blockchain.Singleton.GetSnapshot())
foreach (UInt160 account in wallet.GetAccounts().Select(p => p.ScriptHash))
{
gas += NativeContract.NEO.UnclaimedGas(snapshot, account, snapshot.Height + 1);
}
return gas.ToString();
}
[RpcMethod]
private JObject ImportPrivKey(JArray _params)
{
CheckWallet();
string privkey = _params[0].AsString();
WalletAccount account = wallet.Import(privkey);
if (wallet is NEP6Wallet nep6wallet)
nep6wallet.Save();
return new JObject
{
["address"] = account.Address,
["haskey"] = account.HasKey,
["label"] = account.Label,
["watchonly"] = account.WatchOnly
};
}
[RpcMethod]
private JObject CalculateNetworkFee(JArray _params)
{
byte[] tx = Convert.FromBase64String(_params[0].AsString());
JObject account = new JObject();
account["networkfee"] = (wallet ?? new DummyWallet()).CalculateNetworkFee(Blockchain.Singleton.GetSnapshot(), tx.AsSerializable<Transaction>());
return account;
}
[RpcMethod]
private JObject ListAddress(JArray _params)
{
CheckWallet();
return wallet.GetAccounts().Select(p =>
{
JObject account = new JObject();
account["address"] = p.Address;
account["haskey"] = p.HasKey;
account["label"] = p.Label;
account["watchonly"] = p.WatchOnly;
return account;
}).ToArray();
}
[RpcMethod]
private JObject OpenWallet(JArray _params)
{
string path = _params[0].AsString();
string password = _params[1].AsString();
if (!File.Exists(path)) throw new FileNotFoundException();
switch (GetExtension(path))
{
case ".db3":
{
wallet = UserWallet.Open(path, password);
break;
}
case ".json":
{
NEP6Wallet nep6wallet = new NEP6Wallet(path);
nep6wallet.Unlock(password);
wallet = nep6wallet;
break;
}
default:
throw new NotSupportedException();
}
return true;
}
private void ProcessInvokeWithWallet(JObject result, UInt160 sender = null, Signers signers = null)
{
Transaction tx = null;
if (wallet != null && signers != null)
{
Signer[] witnessSigners = signers.GetSigners().ToArray();
UInt160[] signersAccounts = signers.GetScriptHashesForVerifying(null);
if (sender != null)
{
if (!signersAccounts.Contains(sender))
witnessSigners = witnessSigners.Prepend(new Signer() { Account = sender, Scopes = WitnessScope.CalledByEntry }).ToArray();
else if (signersAccounts[0] != sender)
throw new RpcException(-32602, "The sender must be the first element of signers.");
}
if (witnessSigners.Count() > 0)
{
tx = wallet.MakeTransaction(result["script"].AsString().HexToBytes(), sender, witnessSigners);
ContractParametersContext context = new ContractParametersContext(tx);
wallet.Sign(context);
if (context.Completed)
tx.Witnesses = context.GetWitnesses();
else
tx = null;
}
}
result["tx"] = tx?.ToArray().ToHexString();
}
[RpcMethod]
private JObject SendFrom(JArray _params)
{
CheckWallet();
UInt160 assetId = UInt160.Parse(_params[0].AsString());
UInt160 from = AddressToScriptHash(_params[1].AsString());
UInt160 to = AddressToScriptHash(_params[2].AsString());
AssetDescriptor descriptor = new AssetDescriptor(assetId);
BigDecimal amount = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals);
if (amount.Sign <= 0)
throw new RpcException(-32602, "Invalid params");
Signer[] signers = _params.Count >= 5 ? ((JArray)_params[4]).Select(p => new Signer() { Account = AddressToScriptHash(p.AsString()), Scopes = WitnessScope.CalledByEntry }).ToArray() : null;
Transaction tx = wallet.MakeTransaction(new[]
{
new TransferOutput
{
AssetId = assetId,
Value = amount,
ScriptHash = to
}
}, from, signers);
if (tx == null)
throw new RpcException(-300, "Insufficient funds");
ContractParametersContext transContext = new ContractParametersContext(tx);
wallet.Sign(transContext);
if (!transContext.Completed)
return transContext.ToJson();
tx.Witnesses = transContext.GetWitnesses();
if (tx.Size > 1024)
{
long calFee = tx.Size * 1000 + 100000;
if (tx.NetworkFee < calFee)
tx.NetworkFee = calFee;
}
if (tx.NetworkFee > settings.MaxFee)
throw new RpcException(-301, "The necessary fee is more than the Max_fee, this transaction is failed. Please increase your Max_fee value.");
return SignAndRelay(tx);
}
[RpcMethod]
private JObject SendMany(JArray _params)
{
CheckWallet();
int to_start = 0;
UInt160 from = null;
if (_params[0] is JString)
{
from = AddressToScriptHash(_params[0].AsString());
to_start = 1;
}
JArray to = (JArray)_params[to_start];
if (to.Count == 0)
throw new RpcException(-32602, "Invalid params");
Signer[] signers = _params.Count >= to_start + 2 ? ((JArray)_params[to_start + 1]).Select(p => new Signer() { Account = AddressToScriptHash(p.AsString()), Scopes = WitnessScope.CalledByEntry }).ToArray() : null;
TransferOutput[] outputs = new TransferOutput[to.Count];
for (int i = 0; i < to.Count; i++)
{
UInt160 asset_id = UInt160.Parse(to[i]["asset"].AsString());
AssetDescriptor descriptor = new AssetDescriptor(asset_id);
outputs[i] = new TransferOutput
{
AssetId = asset_id,
Value = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
ScriptHash = AddressToScriptHash(to[i]["address"].AsString())
};
if (outputs[i].Value.Sign <= 0)
throw new RpcException(-32602, "Invalid params");
}
Transaction tx = wallet.MakeTransaction(outputs, from, signers);
if (tx == null)
throw new RpcException(-300, "Insufficient funds");
ContractParametersContext transContext = new ContractParametersContext(tx);
wallet.Sign(transContext);
if (!transContext.Completed)
return transContext.ToJson();
tx.Witnesses = transContext.GetWitnesses();
if (tx.Size > 1024)
{
long calFee = tx.Size * 1000 + 100000;
if (tx.NetworkFee < calFee)
tx.NetworkFee = calFee;
}
if (tx.NetworkFee > settings.MaxFee)
throw new RpcException(-301, "The necessary fee is more than the Max_fee, this transaction is failed. Please increase your Max_fee value.");
return SignAndRelay(tx);
}
[RpcMethod]
private JObject SendToAddress(JArray _params)
{
CheckWallet();
UInt160 assetId = UInt160.Parse(_params[0].AsString());
UInt160 to = AddressToScriptHash(_params[1].AsString());
AssetDescriptor descriptor = new AssetDescriptor(assetId);
BigDecimal amount = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals);
if (amount.Sign <= 0)
throw new RpcException(-32602, "Invalid params");
Transaction tx = wallet.MakeTransaction(new[]
{
new TransferOutput
{
AssetId = assetId,
Value = amount,
ScriptHash = to
}
});
if (tx == null)
throw new RpcException(-300, "Insufficient funds");
ContractParametersContext transContext = new ContractParametersContext(tx);
wallet.Sign(transContext);
if (!transContext.Completed)
return transContext.ToJson();
tx.Witnesses = transContext.GetWitnesses();
if (tx.Size > 1024)
{
long calFee = tx.Size * 1000 + 100000;
if (tx.NetworkFee < calFee)
tx.NetworkFee = calFee;
}
if (tx.NetworkFee > settings.MaxFee)
throw new RpcException(-301, "The necessary fee is more than the Max_fee, this transaction is failed. Please increase your Max_fee value.");
return SignAndRelay(tx);
}
private JObject SignAndRelay(Transaction tx)
{
ContractParametersContext context = new ContractParametersContext(tx);
wallet.Sign(context);
if (context.Completed)
{
tx.Witnesses = context.GetWitnesses();
system.Blockchain.Tell(tx);
return tx.ToJson();
}
else
{
return context.ToJson();
}
}
internal static UInt160 AddressToScriptHash(string address)
{
if (UInt160.TryParse(address, out var scriptHash))
{
return scriptHash;
}
return address.ToScriptHash();
}
}
}