-
Notifications
You must be signed in to change notification settings - Fork 492
/
WasabiJsonRpcService.cs
612 lines (537 loc) · 19.7 KB
/
WasabiJsonRpcService.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
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.BitcoinP2p;
using WalletWasabi.Blockchain.Analysis.Clustering;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Blockchain.TransactionBuilding;
using WalletWasabi.Blockchain.TransactionOutputs;
using WalletWasabi.Blockchain.Transactions;
using WalletWasabi.Extensions;
using WalletWasabi.Helpers;
using WalletWasabi.Models;
using WalletWasabi.Rpc;
using WalletWasabi.WabiSabi.Client;
using WalletWasabi.WabiSabi.Client.Batching;
using WalletWasabi.Wallets;
using JsonRpcResult = System.Collections.Generic.Dictionary<string, object?>;
using JsonRpcResultList = System.Collections.Immutable.ImmutableArray<System.Collections.Generic.Dictionary<string, object?>>;
namespace WalletWasabi.Daemon.Rpc;
[SuppressMessage("ReSharper", "CoVariantArrayConversion")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public class WasabiJsonRpcService : IJsonRpcService
{
public WasabiJsonRpcService(Global global)
{
Global = global;
}
private Global Global { get; }
private Wallet? ActiveWallet { get; set; }
[JsonRpcMethod("listunspentcoins")]
public JsonRpcResultList GetUnspentCoinList()
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
var serverTipHeight = activeWallet.BitcoinStore.SmartHeaderChain.ServerTipHeight;
return activeWallet.Coins.Where(x => !x.IsSpent()).Select(
x => new JsonRpcResult
{
["txid"] = x.TransactionId.ToString(),
["index"] = x.Index,
["amount"] = x.Amount.Satoshi,
["anonymityScore"] = x.HdPubKey.AnonymitySet,
["confirmed"] = x.Confirmed,
["confirmations"] = x.Confirmed ? serverTipHeight - (uint)x.Height.Value + 1 : 0,
["label"] = x.HdPubKey.Labels.ToString(),
["keyPath"] = x.HdPubKey.FullKeyPath.ToString(),
["address"] = x.HdPubKey.GetAddress(Global.Network).ToString(),
["excludedFromCoinjoin"] = x.IsExcludedFromCoinJoin
}).ToImmutableArray();
}
[JsonRpcMethod("listcoins")]
public JsonRpcResultList GetCoinList()
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
var serverTipHeight = activeWallet.BitcoinStore.SmartHeaderChain.ServerTipHeight;
if (activeWallet.Coins is not CoinsRegistry coinRegistry)
{
throw new ArgumentException($"{nameof(activeWallet.Coins)} was not {typeof(CoinsRegistry)}.");
}
return coinRegistry.AsAllCoinsView().Select(
x => new JsonRpcResult
{
["txid"] = x.TransactionId.ToString(),
["index"] = x.Index,
["amount"] = x.Amount.Satoshi,
["anonymityScore"] = x.HdPubKey.AnonymitySet,
["confirmed"] = x.Confirmed,
["confirmations"] = x.Confirmed ? serverTipHeight - (uint)x.Height.Value + 1 : 0,
["keyPath"] = x.HdPubKey.FullKeyPath.ToString(),
["address"] = x.HdPubKey.GetAddress(Global.Network).ToString(),
["spentBy"] = x.SpenderTransaction?.GetHash().ToString()
}).ToImmutableArray();
}
[JsonRpcMethod("createwallet", initializable: false)]
public object CreateWallet(string walletName, string password)
{
var walletGenerator = new WalletGenerator(Global.WalletManager.WalletDirectories.WalletsDir, Global.Network);
walletGenerator.TipHeight = Global.BitcoinStore.SmartHeaderChain.TipHeight;
var (keyManager, mnemonic) = walletGenerator.GenerateWallet(walletName, password);
Global.WalletManager.AddWallet(keyManager);
return mnemonic.ToString();
}
[JsonRpcMethod("recoverwallet", initializable: false)]
public void RecoverWallet(string walletName, string mnemonicStr, string password = "")
{
var walletGenerator = new WalletGenerator(Global.WalletManager.WalletDirectories.WalletsDir, Global.Network);
walletGenerator.TipHeight = 0;
if (!TryParseMnemonic(mnemonicStr, out var mnemonic))
{
throw new ArgumentException("Invalid value for mnemonic");
}
var (keyManager, _) = walletGenerator.GenerateWallet(walletName, password, mnemonic);
Global.WalletManager.AddWallet(keyManager);
}
[JsonRpcMethod("loadwallet", initializable: false)]
public void LoadWallet(string walletName)
{
SelectWallet(walletName);
}
[JsonRpcMethod("getwalletinfo")]
public JsonRpcResult WalletInfo()
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
var km = activeWallet.KeyManager;
var segwit = new JsonRpcResult
{
["name"] = "segwit",
["publicKey"] = km.SegwitExtPubKey.ToString(Global.Network),
["keyPath"] = $"m/{km.SegwitAccountKeyPath}"
};
var info = new JsonRpcResult
{
["walletName"] = activeWallet.WalletName,
["walletFile"] = km.FilePath,
["state"] = activeWallet.State.ToString(),
["masterKeyFingerprint"] = km.MasterFingerprint?.ToString() ?? "",
["anonScoreTarget"] = activeWallet.AnonScoreTarget,
["isWatchOnly"] = activeWallet.KeyManager.IsWatchOnly,
["isHardwareWallet"] = activeWallet.KeyManager.IsHardwareWallet,
["isAutoCoinjoin"] = activeWallet.KeyManager.AutoCoinJoin,
["isRedCoinIsolation"] = activeWallet.KeyManager.RedCoinIsolation,
["accounts"] = new[] { segwit }
};
if (km.TaprootExtPubKey is { } taprootExtPubKey)
{
info["accounts"] = new[]
{
segwit,
new JsonRpcResult
{
["name"] = "taproot",
["publicKey"] = taprootExtPubKey.ToString(Global.Network),
["keyPath"] = $"m/{km.TaprootAccountKeyPath}"
}
};
}
if (activeWallet.State == WalletState.Started)
{
// The following elements are valid only after the wallet is fully synchronized
info["balance"] = activeWallet.Coins
.Where(c => !c.IsSpent() && !c.SpentAccordingToBackend)
.Sum(c => c.Amount.Satoshi);
info["coinjoinStatus"] = GetCoinjoinStatus(activeWallet);
}
return info;
}
[JsonRpcMethod("getnewaddress")]
public JsonRpcResult GenerateReceiveAddress(string label)
{
AssertWalletIsLoaded();
label = Guard.NotNullOrEmptyOrWhitespace(nameof(label), label, true);
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
var hdKey = activeWallet.KeyManager.GetNextReceiveKey(new LabelsArray(label));
return new JsonRpcResult
{
["address"] = hdKey.GetAddress(Global.Network).ToString(),
["keyPath"] = hdKey.FullKeyPath.ToString(),
["label"] = hdKey.Labels.ToString(),
["publicKey"] = hdKey.PubKey.ToHex(),
["scriptPubKey"] = hdKey.GetAssumedScriptPubKey().ToHex()
};
}
[JsonRpcMethod("getstatus", initializable: false)]
public JsonRpcResult GetStatus()
{
var sync = Global.Synchronizer;
var smartHeaderChain = Global.BitcoinStore.SmartHeaderChain;
return new JsonRpcResult
{
["torStatus"] = sync.TorStatus switch
{
TorStatus.NotRunning => "Not running",
TorStatus.Running => "Running",
_ => "Turned off"
},
["onionService"] = Global.OnionServiceUri?.ToString() ?? "Unavailable",
["backendStatus"] = sync.BackendStatus == BackendStatus.Connected ? "Connected" : "Disconnected",
["bestBlockchainHeight"] = smartHeaderChain.TipHeight.ToString(),
["bestBlockchainHash"] = smartHeaderChain.TipHash?.ToString() ?? "",
["filtersCount"] = smartHeaderChain.HashCount,
["filtersLeft"] = smartHeaderChain.HashesLeft,
["network"] = Global.Network.Name,
["exchangeRate"] = sync.UsdExchangeRate,
["peers"] = Global.HostedServices.Get<P2pNetwork>().Nodes.ConnectedNodes.Select(
x => new JsonRpcResult
{
["isConnected"] = x.IsConnected,
["lastSeen"] = x.LastSeen,
["endpoint"] = x.Peer.Endpoint.ToString(),
["userAgent"] = x.PeerVersion.UserAgent,
}).ToArray(),
};
}
[JsonRpcMethod("build")]
public string BuildTransaction(PaymentInfo[] payments, OutPoint[] coins, int? feeTarget = null, decimal? feeRate = null, string? password = null)
{
Guard.NotNull(nameof(payments), payments);
Guard.NotNull(nameof(coins), coins);
password = Guard.Correct(password);
static bool InRange<T>(IComparable<T> val, T min, T max) =>
val.CompareTo(min) >= 0 && val.CompareTo(max) <= 0;
var satsPerByte = feeRate is { } nonNullSatsPerByte ? new FeeRate(nonNullSatsPerByte) : FeeRate.Zero;
var feeStrategy = (feeRate, feeTarget) switch
{
(not null, null) when InRange(satsPerByte, Constants.MinRelayFeeRate, Constants.AbsurdlyHighFeeRate) =>
FeeStrategy.CreateFromFeeRate(satsPerByte),
(null, { } argFeeTarget) when InRange(argFeeTarget, Constants.TwentyMinutesConfirmationTarget, Constants.SevenDaysConfirmationTarget) =>
FeeStrategy.CreateFromConfirmationTarget(argFeeTarget),
_ => throw new ArgumentException("Fee parameters are missing, inconsistent or out of range.")
};
AssertWalletIsLoaded();
var payment = new PaymentIntent(
payments.Select(
p =>
new DestinationRequest(p.Sendto.ScriptPubKey, MoneyRequest.Create(p.Amount, p.SubtractFee), new LabelsArray(p.Label))));
var result = ActiveWallet!.BuildTransaction(
password,
payment,
feeStrategy,
allowUnconfirmed: true,
allowedInputs: coins);
var smartTx = result.Transaction;
return smartTx.Transaction.ToHex();
}
[JsonRpcMethod("payincoinjoin")]
public string PayInCoinJoin(BitcoinAddress address, Money amount)
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
return activeWallet.AddCoinJoinPayment(address, amount);
}
[JsonRpcMethod("listpaymentsincoinjoin")]
public JsonRpcResultList ListPaymentsInCoinJoin()
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
var payments = activeWallet.BatchedPayments.GetPayments();
return payments.Select(x =>
{
var paymentResult = new JsonRpcResult
{
["id"] = x.Id,
["amount"] = x.Amount.Satoshi,
["destination"] = x.Destination.ScriptPubKey.ToHex()
};
var state = x.State;
var stateHistory = new List<JsonRpcResult>();
while (state != null)
{
switch (state)
{
case PendingPayment pending:
stateHistory.Add(new JsonRpcResult
{
["status"] = "Pending"
});
break;
case InProgressPayment inProgress:
stateHistory.Add(new JsonRpcResult
{
["status"] = "In progress",
["round"] = inProgress.RoundId.ToString()
});
break;
case FinishedPayment finished:
stateHistory.Add(new JsonRpcResult
{
["status"] = "Finished",
["txid"] = finished.TransactionId.ToString()
});
break;
default:
throw new NotSupportedException($"Unrecognized state: {state.GetType().Name}.");
}
state = state.PreviousState;
}
paymentResult["state"] = stateHistory;
if (x.Destination.ScriptPubKey.GetDestinationAddress(activeWallet.Network) is { } address)
{
paymentResult["address"] = address;
}
return paymentResult;
}).ToImmutableArray();
}
[JsonRpcMethod("cancelpaymentincoinjoin")]
public void CancelPayment(Guid paymentId)
{
AssertWalletIsLoaded();
ActiveWallet!.BatchedPayments.AbortPayment(paymentId);
}
[JsonRpcMethod("send")]
public async Task<JsonRpcResult> SendTransactionAsync(PaymentInfo[] payments, OutPoint[] coins, int? feeTarget = null, int? feeRate = null, string? password = null)
{
password = Guard.Correct(password);
var txHex = BuildTransaction(payments, coins, feeTarget, feeRate, password);
var smartTx = new SmartTransaction(Transaction.Parse(txHex, Global.Network), Height.Mempool);
await Global.TransactionBroadcaster.SendTransactionAsync(smartTx).ConfigureAwait(false);
return new JsonRpcResult
{
["txid"] = smartTx.Transaction.GetHash(),
["tx"] = txHex
};
}
[JsonRpcMethod("canceltransaction")]
public string BuildCancelTransaction(uint256 txId, string password = "")
{
Guard.NotNull(nameof(txId), txId);
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
activeWallet.Kitchen.Cook(password);
var mempoolStore = Global.BitcoinStore.TransactionStore.MempoolStore;
if (!mempoolStore.TryGetTransaction(txId, out var smartTransactionToCancel))
{
throw new NotSupportedException($"Unknown transaction {txId}");
}
var cancellationResult = activeWallet.CancelTransaction(smartTransactionToCancel);
var cancellationSmartTransaction = cancellationResult.Transaction;
return cancellationSmartTransaction.Transaction.ToHex();
}
[JsonRpcMethod("speeduptransaction")]
public string SpeedUpTransaction(uint256 txId, string password = "")
{
Guard.NotNull(nameof(txId), txId);
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
activeWallet.Kitchen.Cook(password);
var mempoolStore = Global.BitcoinStore.TransactionStore.MempoolStore;
if (!mempoolStore.TryGetTransaction(txId, out var smartTransactionToSpeedUp))
{
throw new NotSupportedException($"Unknown transaction {txId}");
}
var speedUpResult = activeWallet.SpeedUpTransaction(smartTransactionToSpeedUp);
var speedUpSmartTransaction = speedUpResult.Transaction;
return speedUpSmartTransaction.Transaction.ToHex();
}
[JsonRpcMethod("broadcast", initializable: false)]
public async Task<JsonRpcResult> SendRawTransactionAsync(string txHex)
{
txHex = Guard.Correct(txHex);
var smartTx = new SmartTransaction(Transaction.Parse(txHex, Global.Network), Height.Mempool);
await Global.TransactionBroadcaster.SendTransactionAsync(smartTx).ConfigureAwait(false);
return new JsonRpcResult
{
["txid"] = smartTx.Transaction.GetHash()
};
}
[JsonRpcMethod("gethistory")]
public JsonRpcResultList GetHistory()
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
var summary = activeWallet.BuildHistorySummary();
return summary.Select(
x => new JsonRpcResult
{
["datetime"] = x.FirstSeen,
["height"] = x.Height.Value,
["amount"] = x.Amount.Satoshi,
["label"] = x.Labels.ToString(),
["tx"] = x.GetHash(),
["islikelycoinjoin"] = x.IsOwnCoinjoin()
}).ToImmutableArray();
}
[JsonRpcMethod("excludefromcoinjoin")]
public void ExcludeCoinsFromCoinjoin(uint256 transactionId, int n, bool exclude = true)
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
activeWallet.ExcludeCoinFromCoinJoin(new OutPoint(transactionId, n), exclude);
}
[JsonRpcMethod("listkeys")]
public JsonRpcResultList GetAllKeys()
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
var keys = activeWallet.KeyManager.GetKeys();
return keys.Select(
x => new JsonRpcResult
{
["fullKeyPath"] = x.FullKeyPath.ToString(),
["internal"] = x.IsInternal,
["keyState"] = x.KeyState,
["label"] = x.Labels.ToString(),
["scriptPubKey"] = x.GetAssumedScriptPubKey().ToString(),
["pubkey"] = x.PubKey.ToString(),
["pubKeyHash"] = x.PubKey.Hash.ToString(),
["address"] = x.GetAddress(Global.Network).ToString()
}).ToImmutableArray();
}
[JsonRpcMethod("startcoinjoin")]
public void StartCoinJoining(string? password = null, bool stopWhenAllMixed = true, bool overridePlebStop = true)
{
var coinJoinManager = Global.HostedServices.Get<CoinJoinManager>();
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
AssertWalletIsLoggedIn(activeWallet, password ?? "");
coinJoinManager.StartAsync(activeWallet, activeWallet, stopWhenAllMixed, overridePlebStop, CancellationToken.None).ConfigureAwait(false);
}
[JsonRpcMethod("startcoinjoinsweep")]
public void StartCoinjoinSweeping(string? password = null, string? outputWalletName = null)
{
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
AssertWalletIsLoggedIn(activeWallet, password ?? "");
if (outputWalletName is null || outputWalletName == activeWallet.WalletName)
{
throw new InvalidOperationException("Output wallet name is invalid.");
}
var outputWallet = Global.WalletManager.GetWalletByName(outputWalletName);
StartCoinjoinSweepAsync(activeWallet, outputWallet).ConfigureAwait(false);
}
private async Task StartCoinjoinSweepAsync(Wallet activeWallet, Wallet outputWallet)
{
activeWallet.ConsolidationMode = true;
// If output wallet isn't initialized, then load it.
if (outputWallet.State == WalletState.Uninitialized)
{
await Global.WalletManager.StartWalletAsync(outputWallet).ConfigureAwait(false);
}
var coinJoinManager = Global.HostedServices.Get<CoinJoinManager>();
await coinJoinManager.StartAsync(activeWallet, outputWallet, stopWhenAllMixed: false, overridePlebStop: true, CancellationToken.None).ConfigureAwait(false);
}
[JsonRpcMethod("stopcoinjoin")]
public void StopCoinJoining()
{
var coinJoinManager = Global.HostedServices.Get<CoinJoinManager>();
var activeWallet = Guard.NotNull(nameof(ActiveWallet), ActiveWallet);
AssertWalletIsLoaded();
coinJoinManager.StopAsync(activeWallet, CancellationToken.None).ConfigureAwait(false);
}
[JsonRpcMethod("getfeerates", initializable: false)]
public object GetFeeRate()
{
if (Global.Synchronizer.LastAllFeeEstimate is { } nonNullFeeRates)
{
return nonNullFeeRates.Estimations;
}
return new Dictionary<int, int>();
}
[JsonRpcMethod("listwallets", initializable: false)]
public async Task<JsonRpcResultList> ListWalletsAsync()
{
var wallets = await Global.WalletManager.GetWalletsAsync().ConfigureAwait(false);
return wallets
.Cast<Wallet>()
.Select(x => new JsonRpcResult
{
["walletName"] = x.WalletName
})
.ToImmutableArray();
}
[JsonRpcMethod(IJsonRpcService.StopRpcCommand, initializable: false)]
public Task StopAsync()
{
throw new InvalidOperationException("This RPC method is special and the handling method should not be called.");
}
private string GetCoinjoinStatus(Wallet wallet)
{
var coinJoinManager = Global.HostedServices.Get<CoinJoinManager>();
var walletCoinjoinClientState = coinJoinManager.GetCoinjoinClientState(wallet.WalletName);
return walletCoinjoinClientState switch
{
CoinJoinClientState.Idle => "Idle",
CoinJoinClientState.InProgress => "In progress",
CoinJoinClientState.InSchedule => "In schedule",
CoinJoinClientState.InCriticalPhase => "In critical phase",
_ => throw new Exception($"The state {walletCoinjoinClientState.FriendlyName()} is unknown.")
};
}
private void SelectWallet(string walletName)
{
walletName = Guard.NotNullOrEmptyOrWhitespace(nameof(walletName), walletName);
try
{
var wallet = Global.WalletManager.GetWalletByName(walletName);
ActiveWallet = wallet;
if (wallet.State == WalletState.Uninitialized)
{
Global.WalletManager.StartWalletAsync(wallet).ConfigureAwait(false);
}
}
catch (InvalidOperationException) // wallet not found
{
throw new Exception($"Wallet '{walletName}' not found.");
}
}
private void AssertWalletIsLoaded()
{
if (ActiveWallet is null)
{
throw new InvalidOperationException("There is no wallet loaded.");
}
if (ActiveWallet.State < WalletState.Started)
{
throw new InvalidOperationException("Wallet is not fully loaded yet.");
}
}
private void AssertWalletIsLoggedIn(Wallet activeWallet, string password)
{
if (!activeWallet.IsLoggedIn && !activeWallet.TryLogin(password, out _))
{
throw new Exception($"'{activeWallet.WalletName}' wallet requires the password to start coinjoining.");
}
}
[JsonRpcInitialization]
public void Initialize(string path, bool needsWallet)
{
var parts = path.Split("/", StringSplitOptions.RemoveEmptyEntries);
var walletName = parts.Length == 1 ? parts[0] : string.Empty;
if (needsWallet && !string.IsNullOrEmpty(walletName))
{
SelectWallet(walletName);
}
else
{
throw new InvalidOperationException("Wallet name is invalid or not allowed.");
}
}
private static bool TryParseMnemonic(string mnemonicStr, [NotNullWhen(true)] out Mnemonic? mnemonic)
{
try
{
mnemonic = new Mnemonic(mnemonicStr);
return true;
}
catch (Exception)
{
mnemonic = null;
return false;
}
}
}