-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathDerivationSchemesController.cs
357 lines (337 loc) · 15 KB
/
DerivationSchemesController.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
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using NBXplorer.Backend;
using NBXplorer.DerivationStrategy;
using NBXplorer.Models;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Globalization;
using System;
using System.Threading.Tasks;
using NBitcoin.RPC;
using NBitcoin.Scripting;
using System.Linq;
using NBXplorer.Logging;
using Microsoft.Extensions.Logging;
namespace NBXplorer.Controllers
{
[Route($"v1/{CommonRoutes.BaseDerivationEndpoint}")]
public class DerivationSchemesController : Controller
{
public ScanUTXOSetService ScanUTXOSetService { get; }
public MainController MainController { get; }
public RepositoryProvider RepositoryProvider { get; }
public KeyPathTemplates KeyPathTemplates { get; }
public Indexers Indexers { get; }
public AddressPoolService AddressPoolService { get; }
public DerivationSchemesController(
MainController mainController,
ScanUTXOSetServiceAccessor scanUTXOSetService,
RepositoryProvider repositoryProvider,
KeyPathTemplates keyPathTemplates,
Indexers indexers,
AddressPoolService addressPoolService)
{
ScanUTXOSetService = scanUTXOSetService.Instance;
MainController = mainController;
RepositoryProvider = repositoryProvider;
KeyPathTemplates = keyPathTemplates;
Indexers = indexers;
AddressPoolService = addressPoolService;
}
[HttpPost($"~/v1/{CommonRoutes.DerivationEndpoint}")]
[HttpPost($"~/v1/{CommonRoutes.AddressEndpoint}")]
public async Task<IActionResult> TrackWallet(
TrackedSourceContext trackedSourceContext,
[FromBody] JObject rawRequest = null)
{
var network = trackedSourceContext.Network;
var trackedSource = trackedSourceContext.TrackedSource;
var request = network.ParseJObject<TrackWalletRequest>(rawRequest ?? new JObject());
if (trackedSource is DerivationSchemeTrackedSource dts)
{
if (request.Wait)
{
foreach (var feature in dts.GetDerivationFeatures(KeyPathTemplates))
{
await RepositoryProvider.GetRepository(network).GenerateAddresses(dts.DerivationStrategy, feature, GenerateAddressQuery(request, feature));
}
}
else
{
foreach (var feature in dts.GetDerivationFeatures(KeyPathTemplates))
{
await RepositoryProvider.GetRepository(network).GenerateAddresses(dts.DerivationStrategy, feature, new GenerateAddressQuery(minAddresses: 3, null));
}
foreach (var feature in dts.GetDerivationFeatures(KeyPathTemplates))
{
_ = AddressPoolService.GenerateAddresses(network, dts.DerivationStrategy, feature, GenerateAddressQuery(request, feature));
}
}
}
else if (trackedSource is IDestination ats)
{
await RepositoryProvider.GetRepository(network).Track(ats);
}
return Ok();
}
private GenerateAddressQuery GenerateAddressQuery(TrackWalletRequest request, DerivationFeature feature)
{
if (request?.DerivationOptions == null)
return null;
foreach (var derivationOption in request.DerivationOptions)
{
if ((derivationOption.Feature is DerivationFeature f && f == feature) || derivationOption.Feature is null)
{
return new GenerateAddressQuery(derivationOption.MinAddresses, derivationOption.MaxAddresses);
}
}
return null;
}
[HttpPost($"~/v1/{CommonRoutes.DerivationEndpoint}/utxos/wipe")]
public async Task<IActionResult> Wipe(TrackedSourceContext trackedSourceContext)
{
var repo = trackedSourceContext.Repository;
var ts = trackedSourceContext.TrackedSource;
var txs = await repo.GetTransactions(GetTransactionQuery.Create(trackedSourceContext.TrackedSource));
await repo.Prune(txs);
return Ok();
}
[HttpPost("utxos/scan")]
[HttpPost($"~/v1/{CommonRoutes.DerivationEndpoint}/utxos/scan")]
[TrackedSourceContext.TrackedSourceContextRequirement(requireRPC: true, allowedTrackedSourceTypes: typeof(DerivationSchemeTrackedSource))]
public IActionResult ScanUTXOSet(TrackedSourceContext trackedSourceContext, int? batchSize = null, int? gapLimit = null, int? from = null)
{
var network = trackedSourceContext.Network;
var rpc = trackedSourceContext.RpcClient;
var derivationScheme = ((DerivationSchemeTrackedSource)trackedSourceContext.TrackedSource).DerivationStrategy;
if (!rpc.Capabilities.SupportScanUTXOSet)
throw new NBXplorerError(405, "scanutxoset-not-suported", "ScanUTXOSet is not supported for this currency").AsException();
ScanUTXOSetOptions options = new ScanUTXOSetOptions();
if (batchSize != null)
options.BatchSize = batchSize.Value;
if (gapLimit != null)
options.GapLimit = gapLimit.Value;
if (from != null)
options.From = from.Value;
if (!ScanUTXOSetService.EnqueueScan(network, derivationScheme, options))
throw new NBXplorerError(409, "scanutxoset-in-progress", "ScanUTXOSet has already been called for this derivationScheme").AsException();
return Ok();
}
[HttpGet($"~/v1/{CommonRoutes.DerivationEndpoint}/utxos/scan")]
[TrackedSourceContext.TrackedSourceContextRequirement(allowedTrackedSourceTypes: typeof(DerivationSchemeTrackedSource))]
public IActionResult GetScanUTXOSetInformation(TrackedSourceContext trackedSourceContext)
{
var network = trackedSourceContext.Network;
var derivationScheme = ((DerivationSchemeTrackedSource)trackedSourceContext.TrackedSource).DerivationStrategy;
var info = ScanUTXOSetService.GetInformation(network, derivationScheme);
if (info == null)
throw new NBXplorerError(404, "scanutxoset-info-not-found", "ScanUTXOSet has not been called with this derivationScheme of the result has expired").AsException();
return Json(info, network.Serializer.Settings);
}
[HttpPost($"~/v1/{CommonRoutes.DerivationEndpoint}/prune")]
[TrackedSourceContext.TrackedSourceContextRequirement(allowedTrackedSourceTypes: [typeof(DerivationSchemeTrackedSource)])]
public async Task<PruneResponse> Prune(TrackedSourceContext trackedSourceContext, [FromBody] PruneRequest request)
{
request ??= new PruneRequest();
request.DaysToKeep ??= 1.0;
var trackedSource = trackedSourceContext.TrackedSource;
var network = trackedSourceContext.Network;
var repo = trackedSourceContext.Repository;
var transactions = await MainController.GetAnnotatedTransactions(repo, GetTransactionQuery.Create(trackedSource), false);
var state = transactions.ConfirmedState;
var prunableIds = new HashSet<uint256>();
var keepConfMax = network.NBitcoinNetwork.Consensus.GetExpectedBlocksFor(TimeSpan.FromDays(request.DaysToKeep.Value));
var tip = (await repo.GetTip()).Height;
// Step 1. We can prune if all UTXOs are spent
foreach (var tx in transactions.ConfirmedTransactions)
{
if (tx.Height is long h && tip - h + 1 > keepConfMax)
{
if (tx.Record.MatchedOutputs.All(c => state.SpentUTXOs.Contains(new OutPoint(tx.Record.TransactionHash, c.Index))))
{
prunableIds.Add(tx.Record.Key.TxId);
}
}
}
// Step2. However, we need to remove those who are spending a UTXO from a transaction that is not pruned
retry:
bool removedPrunables = false;
if (prunableIds.Count != 0)
{
foreach (var tx in transactions.ConfirmedTransactions)
{
if (prunableIds.Count == 0)
break;
if (!prunableIds.Contains(tx.Record.TransactionHash))
continue;
foreach (var parent in tx.Record.SpentOutpoints
.Select(spent => transactions.GetByTxId(spent.Outpoint.Hash))
.Where(parent => parent != null)
.Where(parent => !prunableIds.Contains(parent.Record.TransactionHash)))
{
prunableIds.Remove(tx.Record.TransactionHash);
removedPrunables = true;
}
}
}
// If we removed some prunable, it may have made other transactions unprunable.
if (removedPrunables)
goto retry;
if (prunableIds.Count != 0)
{
await repo.Prune(prunableIds
.Select(id => transactions.GetByTxId(id).Record)
.ToList());
Logs.Explorer.LogInformation($"{network.CryptoCode}: Pruned {prunableIds.Count} transactions");
}
return new PruneResponse() { TotalPruned = prunableIds.Count };
}
[HttpPost]
[TrackedSourceContext.TrackedSourceContextRequirement(false, false)]
public async Task<IActionResult> GenerateWallet(TrackedSourceContext trackedSourceContext, [FromBody] JObject rawRequest = null)
{
var network = trackedSourceContext.Network;
var request = network.ParseJObject<GenerateWalletRequest>(rawRequest) ?? new GenerateWalletRequest();
if (request.ImportKeysToRPC && trackedSourceContext.RpcClient is null)
{
TrackedSourceContext.TrackedSourceContextModelBinder.ThrowRpcUnavailableException();
}
if (network.CoinType == null)
// Don't document, only shitcoins nobody use goes into this
throw new NBXplorerException(new NBXplorerError(400, "not-supported", "This feature is not supported for this coin because we don't have CoinType information"));
request.WordList ??= Wordlist.English;
request.WordCount ??= WordCount.Twelve;
request.ScriptPubKeyType ??= ScriptPubKeyType.Segwit;
if (request.ScriptPubKeyType is null)
{
request.ScriptPubKeyType = network.NBitcoinNetwork.Consensus.SupportSegwit ? ScriptPubKeyType.Segwit : ScriptPubKeyType.Legacy;
}
if (!network.NBitcoinNetwork.Consensus.SupportSegwit && request.ScriptPubKeyType != ScriptPubKeyType.Legacy)
throw new NBXplorerException(new NBXplorerError(400, "segwit-not-supported", "Segwit is not supported, please explicitely set scriptPubKeyType to Legacy"));
var repo = RepositoryProvider.GetRepository(network);
Mnemonic mnemonic = null;
if (request.ExistingMnemonic != null)
{
try
{
mnemonic = new Mnemonic(request.ExistingMnemonic, request.WordList);
}
catch
{
throw new NBXplorerException(new NBXplorerError(400, "invalid-mnemonic", "Invalid mnemonic words"));
}
}
else
{
mnemonic = new Mnemonic(request.WordList, request.WordCount.Value);
}
var masterKey = mnemonic.DeriveExtKey(request.Passphrase).GetWif(network.NBitcoinNetwork);
var keyPath = GetDerivationKeyPath(request.ScriptPubKeyType.Value, request.AccountNumber, network);
var accountKey = masterKey.Derive(keyPath);
DerivationStrategyBase derivation = network.DerivationStrategyFactory.CreateDirectDerivationStrategy(accountKey.Neuter(), new DerivationStrategyOptions()
{
ScriptPubKeyType = request.ScriptPubKeyType.Value,
AdditionalOptions = request.AdditionalOptions is not null ? new System.Collections.ObjectModel.ReadOnlyDictionary<string, string>(request.AdditionalOptions) : null
});
await RepositoryProvider.GetRepository(network).EnsureWalletCreated(derivation);
var derivationTrackedSource = new DerivationSchemeTrackedSource(derivation);
List<Task> saveMetadata = new List<Task>();
if (request.SavePrivateKeys)
{
saveMetadata.AddRange(
new[] {
repo.SaveMetadata(derivationTrackedSource, WellknownMetadataKeys.Mnemonic, mnemonic.ToString()),
repo.SaveMetadata(derivationTrackedSource, WellknownMetadataKeys.MasterHDKey, masterKey),
repo.SaveMetadata(derivationTrackedSource, WellknownMetadataKeys.AccountHDKey, accountKey),
repo.SaveMetadata(derivationTrackedSource, WellknownMetadataKeys.Birthdate, DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture))
});
}
var accountKeyPath = new RootedKeyPath(masterKey.GetPublicKey().GetHDFingerPrint(), keyPath);
saveMetadata.Add(repo.SaveMetadata(derivationTrackedSource, WellknownMetadataKeys.AccountKeyPath, accountKeyPath));
var importAddressToRPC = await GetImportAddressToRPC(request, network);
saveMetadata.Add(repo.SaveMetadata<string>(derivationTrackedSource, WellknownMetadataKeys.ImportAddressToRPC, (importAddressToRPC?.ToString() ?? "False")));
var descriptor = GetDescriptor(accountKeyPath, accountKey.Neuter(), request.ScriptPubKeyType.Value);
saveMetadata.Add(repo.SaveMetadata<string>(derivationTrackedSource, WellknownMetadataKeys.AccountDescriptor, descriptor));
await Task.WhenAll(saveMetadata.ToArray());
await TrackWallet(new TrackedSourceContext()
{
Indexer = trackedSourceContext.Indexer,
Network = network,
RpcClient = trackedSourceContext.RpcClient,
TrackedSource = new DerivationSchemeTrackedSource(derivation)
});
return Json(new GenerateWalletResponse()
{
TrackedSource = new DerivationSchemeTrackedSource(derivation).ToString(),
MasterHDKey = masterKey,
AccountHDKey = accountKey,
AccountKeyPath = accountKeyPath,
AccountDescriptor = descriptor,
DerivationScheme = derivation,
Mnemonic = mnemonic.ToString(),
Passphrase = request.Passphrase ?? string.Empty,
WordCount = request.WordCount.Value,
WordList = request.WordList
}, network.Serializer.Settings);
}
private KeyPath GetDerivationKeyPath(ScriptPubKeyType scriptPubKeyType, int accountNumber, NBXplorerNetwork network)
{
var path = scriptPubKeyType switch
{
ScriptPubKeyType.Legacy => "44'",
ScriptPubKeyType.Segwit => "84'",
ScriptPubKeyType.SegwitP2SH => "49'",
ScriptPubKeyType.TaprootBIP86 => "86'",
_ => throw new NotSupportedException(scriptPubKeyType.ToString())
};
var keyPath = new KeyPath(path);
return keyPath.Derive(network.CoinType)
.Derive(accountNumber, true);
}
private async Task<ImportRPCMode> GetImportAddressToRPC(GenerateWalletRequest request, NBXplorerNetwork network)
{
ImportRPCMode importAddressToRPC = null;
if (request.ImportKeysToRPC is true)
{
var rpc = Indexers.GetIndexer(network)?.GetConnectedClient();;
try
{
var walletInfo = await rpc.SendCommandAsync("getwalletinfo");
if (walletInfo.Result["descriptors"]?.Value<bool>() is true)
{
var readOnly = walletInfo.Result["private_keys_enabled"]?.Value<bool>() is false;
importAddressToRPC = readOnly ? ImportRPCMode.DescriptorsReadOnly : ImportRPCMode.Descriptors;
if (!readOnly && request.SavePrivateKeys is false)
throw new NBXplorerError(400, "wallet-unavailable", $"Your RPC wallet must include private keys, but savePrivateKeys is false").AsException();
}
else
{
importAddressToRPC = ImportRPCMode.Legacy;
}
}
catch (RPCException ex) when (ex.RPCCode == RPCErrorCode.RPC_METHOD_NOT_FOUND)
{
}
catch (RPCException ex) when (ex.RPCCode == RPCErrorCode.RPC_WALLET_NOT_FOUND)
{
throw new NBXplorerError(400, "wallet-unavailable", $"No wallet is loaded. Load a wallet using loadwallet or create a new one with createwallet. (Note: A default wallet is no longer automatically created)").AsException();
}
}
return importAddressToRPC;
}
private string GetDescriptor(RootedKeyPath accountKeyPath, BitcoinExtPubKey accountKey, ScriptPubKeyType scriptPubKeyType)
{
var imported = $"[{accountKeyPath}]{accountKey}";
var descriptor = scriptPubKeyType switch
{
ScriptPubKeyType.Legacy => $"pkh({imported})",
ScriptPubKeyType.Segwit => $"wpkh({imported})",
ScriptPubKeyType.SegwitP2SH => $"sh(wpkh({imported}))",
ScriptPubKeyType.TaprootBIP86 => $"tr({imported})",
_ => throw new NotSupportedException($"Bug of NBXplorer (ERR 3082), please notify the developers ({scriptPubKeyType})")
};
return OutputDescriptor.AddChecksum(descriptor);
}
}
}