2020-06-29 04:44:35 +02:00
|
|
|
using System;
|
2018-03-24 12:40:26 +01:00
|
|
|
using System.Collections.Generic;
|
2024-01-17 10:08:39 +01:00
|
|
|
using System.Diagnostics;
|
2018-03-24 12:40:26 +01:00
|
|
|
using System.Linq;
|
|
|
|
using NBitcoin;
|
2021-01-11 03:22:42 +01:00
|
|
|
using NBitcoin.Scripting;
|
2018-03-24 12:40:26 +01:00
|
|
|
using NBXplorer.DerivationStrategy;
|
|
|
|
|
|
|
|
namespace BTCPayServer
|
|
|
|
{
|
|
|
|
public class DerivationSchemeParser
|
|
|
|
{
|
2019-05-09 11:11:39 +02:00
|
|
|
public BTCPayNetwork BtcPayNetwork { get; }
|
2018-03-24 12:40:26 +01:00
|
|
|
|
2019-05-09 09:05:18 +02:00
|
|
|
public Network Network => BtcPayNetwork.NBitcoinNetwork;
|
|
|
|
|
|
|
|
public DerivationSchemeParser(BTCPayNetwork expectedNetwork)
|
2018-03-24 12:40:26 +01:00
|
|
|
{
|
2021-12-28 09:39:54 +01:00
|
|
|
ArgumentNullException.ThrowIfNull(expectedNetwork);
|
2019-05-09 09:05:18 +02:00
|
|
|
BtcPayNetwork = expectedNetwork;
|
2018-03-24 12:40:26 +01:00
|
|
|
}
|
|
|
|
|
2021-01-11 03:22:42 +01:00
|
|
|
public (DerivationStrategyBase, RootedKeyPath[]) ParseOutputDescriptor(string str)
|
|
|
|
{
|
|
|
|
(DerivationStrategyBase, RootedKeyPath[]) ExtractFromPkProvider(PubKeyProvider pubKeyProvider,
|
|
|
|
string suffix = "")
|
|
|
|
{
|
|
|
|
switch (pubKeyProvider)
|
|
|
|
{
|
|
|
|
case PubKeyProvider.Const _:
|
|
|
|
throw new FormatException("Only HD output descriptors are supported.");
|
|
|
|
case PubKeyProvider.HD hd:
|
|
|
|
if (hd.Path != null && hd.Path.ToString() != "0")
|
|
|
|
{
|
|
|
|
throw new FormatException("Custom change paths are not supported.");
|
|
|
|
}
|
2024-01-24 09:49:15 +01:00
|
|
|
return (Parse($"{hd.Extkey}{suffix}"), null);
|
2021-01-11 03:22:42 +01:00
|
|
|
case PubKeyProvider.Origin origin:
|
|
|
|
var innerResult = ExtractFromPkProvider(origin.Inner, suffix);
|
2021-12-31 08:59:02 +01:00
|
|
|
return (innerResult.Item1, new[] { origin.KeyOriginInfo });
|
2021-01-11 03:22:42 +01:00
|
|
|
default:
|
|
|
|
throw new ArgumentOutOfRangeException();
|
|
|
|
}
|
|
|
|
}
|
2023-01-06 14:18:07 +01:00
|
|
|
|
2022-12-07 12:18:17 +01:00
|
|
|
(DerivationStrategyBase, RootedKeyPath[]) ExtractFromMulti(OutputDescriptor.Multi multi)
|
|
|
|
{
|
|
|
|
var xpubs = multi.PkProviders.Select(provider => ExtractFromPkProvider(provider));
|
|
|
|
return (
|
|
|
|
Parse(
|
2024-01-24 09:49:15 +01:00
|
|
|
$"{multi.Threshold}-of-{(string.Join('-', xpubs.Select(tuple => tuple.Item1.ToString())))}{(multi.IsSorted ? "" : "-[keeporder]")}"),
|
2022-12-07 12:18:17 +01:00
|
|
|
xpubs.SelectMany(tuple => tuple.Item2).ToArray());
|
|
|
|
}
|
2023-01-06 14:18:07 +01:00
|
|
|
|
2021-12-28 09:39:54 +01:00
|
|
|
ArgumentNullException.ThrowIfNull(str);
|
2021-01-11 03:22:42 +01:00
|
|
|
str = str.Trim();
|
2024-01-17 10:08:39 +01:00
|
|
|
//nbitcoin output descriptor does not support taproot, so let's check if it is a taproot descriptor and fake until it is supported
|
2024-01-24 09:49:15 +01:00
|
|
|
|
2021-07-29 13:29:34 +02:00
|
|
|
var outputDescriptor = OutputDescriptor.Parse(str, Network);
|
2021-12-31 08:59:02 +01:00
|
|
|
switch (outputDescriptor)
|
2021-01-11 03:22:42 +01:00
|
|
|
{
|
|
|
|
case OutputDescriptor.PK _:
|
|
|
|
case OutputDescriptor.Raw _:
|
|
|
|
case OutputDescriptor.Addr _:
|
|
|
|
throw new FormatException("Only HD output descriptors are supported.");
|
|
|
|
case OutputDescriptor.Combo _:
|
|
|
|
throw new FormatException("Only output descriptors of one format are supported.");
|
|
|
|
case OutputDescriptor.Multi multi:
|
2022-12-07 12:18:17 +01:00
|
|
|
return ExtractFromMulti(multi);
|
2021-01-11 03:22:42 +01:00
|
|
|
case OutputDescriptor.PKH pkh:
|
|
|
|
return ExtractFromPkProvider(pkh.PkProvider, "-[legacy]");
|
|
|
|
case OutputDescriptor.SH sh:
|
|
|
|
var suffix = "-[p2sh]";
|
|
|
|
if (sh.Inner is OutputDescriptor.Multi)
|
|
|
|
{
|
|
|
|
//non segwit
|
|
|
|
suffix = "-[legacy]";
|
|
|
|
}
|
|
|
|
|
|
|
|
if (sh.Inner is OutputDescriptor.Multi || sh.Inner is OutputDescriptor.WPKH ||
|
|
|
|
sh.Inner is OutputDescriptor.WSH)
|
|
|
|
{
|
|
|
|
var ds = ParseOutputDescriptor(sh.Inner.ToString());
|
2024-01-24 09:49:15 +01:00
|
|
|
return (Parse(ds.Item1 + suffix), ds.Item2);
|
2021-01-11 03:22:42 +01:00
|
|
|
};
|
|
|
|
throw new FormatException("sh descriptors are only supported with multsig(legacy or p2wsh) and segwit(p2wpkh)");
|
2024-01-17 10:08:39 +01:00
|
|
|
case OutputDescriptor.Tr tr:
|
|
|
|
return ExtractFromPkProvider(tr.InnerPubkey, "-[taproot]");
|
2021-01-11 03:22:42 +01:00
|
|
|
case OutputDescriptor.WPKH wpkh:
|
2024-01-17 10:08:39 +01:00
|
|
|
return ExtractFromPkProvider(wpkh.PkProvider);
|
2022-12-07 12:18:17 +01:00
|
|
|
case OutputDescriptor.WSH { Inner: OutputDescriptor.Multi multi }:
|
|
|
|
return ExtractFromMulti(multi);
|
|
|
|
case OutputDescriptor.WSH:
|
2021-01-11 03:22:42 +01:00
|
|
|
throw new FormatException("wsh descriptors are only supported with multisig");
|
|
|
|
default:
|
|
|
|
throw new ArgumentOutOfRangeException(nameof(outputDescriptor));
|
|
|
|
}
|
|
|
|
}
|
2024-01-24 09:49:15 +01:00
|
|
|
public DerivationStrategyBase Parse(string str)
|
2018-03-24 12:40:26 +01:00
|
|
|
{
|
2021-12-28 09:39:54 +01:00
|
|
|
ArgumentNullException.ThrowIfNull(str);
|
2018-03-24 12:40:26 +01:00
|
|
|
str = str.Trim();
|
|
|
|
HashSet<string> hintedLabels = new HashSet<string>();
|
2019-05-08 17:40:30 +02:00
|
|
|
if (!Network.Consensus.SupportSegwit)
|
2020-01-14 16:00:36 +01:00
|
|
|
{
|
2018-04-10 12:07:57 +02:00
|
|
|
hintedLabels.Add("legacy");
|
2020-01-14 16:00:36 +01:00
|
|
|
str = str.Replace("-[p2sh]", string.Empty, StringComparison.OrdinalIgnoreCase);
|
|
|
|
}
|
2018-04-10 12:07:57 +02:00
|
|
|
|
2024-01-24 09:49:15 +01:00
|
|
|
try
|
|
|
|
{
|
|
|
|
return BtcPayNetwork.NBXplorerNetwork.DerivationStrategyFactory.Parse(str);
|
|
|
|
}
|
|
|
|
catch
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2018-03-24 12:40:26 +01:00
|
|
|
var parts = str.Split('-');
|
2018-11-16 17:21:34 +01:00
|
|
|
bool hasLabel = false;
|
2018-03-24 12:40:26 +01:00
|
|
|
for (int i = 0; i < parts.Length; i++)
|
|
|
|
{
|
|
|
|
if (IsLabel(parts[i]))
|
|
|
|
{
|
2018-11-16 17:21:34 +01:00
|
|
|
if (!hasLabel)
|
2018-11-16 17:39:32 +01:00
|
|
|
{
|
2018-11-16 17:21:34 +01:00
|
|
|
hintedLabels.Clear();
|
2018-11-16 17:39:32 +01:00
|
|
|
if (!Network.Consensus.SupportSegwit)
|
|
|
|
hintedLabels.Add("legacy");
|
|
|
|
}
|
2018-11-16 17:21:34 +01:00
|
|
|
hasLabel = true;
|
2018-03-24 12:40:26 +01:00
|
|
|
hintedLabels.Add(parts[i].Substring(1, parts[i].Length - 2).ToLowerInvariant());
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
try
|
|
|
|
{
|
2018-06-23 17:45:57 +02:00
|
|
|
var data = Network.GetBase58CheckEncoder().DecodeData(parts[i]);
|
2018-03-24 12:40:26 +01:00
|
|
|
if (data.Length < 4)
|
|
|
|
continue;
|
|
|
|
var prefix = Utils.ToUInt32(data, false);
|
2019-05-08 17:40:30 +02:00
|
|
|
var standardPrefix = Utils.ToBytes(0x0488b21eU, false);
|
2018-03-24 12:40:26 +01:00
|
|
|
for (int ii = 0; ii < 4; ii++)
|
|
|
|
data[ii] = standardPrefix[ii];
|
2020-06-28 10:55:27 +02:00
|
|
|
|
2020-06-25 10:51:27 +02:00
|
|
|
var derivationScheme = GetBitcoinExtPubKeyByNetwork(Network, data).ToString();
|
2018-03-24 12:40:26 +01:00
|
|
|
|
2024-01-24 09:49:15 +01:00
|
|
|
if (BtcPayNetwork.ElectrumMapping.TryGetValue(prefix, out var type))
|
2019-05-09 12:05:08 +02:00
|
|
|
{
|
2019-05-09 12:14:01 +02:00
|
|
|
switch (type)
|
2018-03-24 12:40:26 +01:00
|
|
|
{
|
2024-01-24 09:49:15 +01:00
|
|
|
case DerivationType.Legacy:
|
2019-05-09 12:14:01 +02:00
|
|
|
hintedLabels.Add("legacy");
|
|
|
|
break;
|
|
|
|
case DerivationType.SegwitP2SH:
|
|
|
|
hintedLabels.Add("p2sh");
|
|
|
|
break;
|
2018-03-24 12:40:26 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
parts[i] = derivationScheme;
|
|
|
|
}
|
|
|
|
catch { continue; }
|
|
|
|
}
|
|
|
|
|
|
|
|
str = string.Join('-', parts.Where(p => !IsLabel(p)));
|
|
|
|
foreach (var label in hintedLabels)
|
|
|
|
{
|
|
|
|
str = $"{str}-[{label}]";
|
|
|
|
}
|
2021-06-17 07:11:01 +02:00
|
|
|
return BtcPayNetwork.NBXplorerNetwork.DerivationStrategyFactory.Parse(str);
|
2018-03-24 12:40:26 +01:00
|
|
|
}
|
|
|
|
|
2024-01-24 09:49:15 +01:00
|
|
|
internal DerivationStrategyBase ParseElectrum(string str)
|
|
|
|
{
|
|
|
|
ArgumentNullException.ThrowIfNull(str);
|
|
|
|
str = str.Trim();
|
|
|
|
var data = Network.GetBase58CheckEncoder().DecodeData(str);
|
|
|
|
if (data.Length < 4)
|
|
|
|
throw new FormatException();
|
|
|
|
var prefix = Utils.ToUInt32(data, false);
|
|
|
|
|
|
|
|
var standardPrefix = Utils.ToBytes(0x0488b21eU, false);
|
|
|
|
for (int ii = 0; ii < 4; ii++)
|
|
|
|
data[ii] = standardPrefix[ii];
|
|
|
|
var extPubKey = GetBitcoinExtPubKeyByNetwork(Network, data);
|
|
|
|
if (!BtcPayNetwork.ElectrumMapping.TryGetValue(prefix, out var type))
|
|
|
|
{
|
|
|
|
throw new FormatException();
|
|
|
|
}
|
|
|
|
if (type == DerivationType.Segwit)
|
|
|
|
return new DirectDerivationStrategy(extPubKey, true);
|
|
|
|
if (type == DerivationType.Legacy)
|
|
|
|
return new DirectDerivationStrategy(extPubKey, false);
|
|
|
|
if (type == DerivationType.SegwitP2SH)
|
|
|
|
return BtcPayNetwork.NBXplorerNetwork.DerivationStrategyFactory.Parse(extPubKey.ToString() + "-[p2sh]");
|
|
|
|
throw new FormatException();
|
|
|
|
}
|
|
|
|
|
2020-06-25 10:51:27 +02:00
|
|
|
public static BitcoinExtPubKey GetBitcoinExtPubKeyByNetwork(Network network, byte[] data)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
return new BitcoinExtPubKey(network.GetBase58CheckEncoder().EncodeData(data), network.NetworkSet.Mainnet).ToNetwork(network);
|
|
|
|
}
|
2020-06-26 13:52:39 +02:00
|
|
|
catch (Exception)
|
2020-06-25 10:51:27 +02:00
|
|
|
{
|
|
|
|
return new BitcoinExtPubKey(network.GetBase58CheckEncoder().EncodeData(data), Network.Main).ToNetwork(network);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-24 12:40:26 +01:00
|
|
|
|
|
|
|
private static bool IsLabel(string v)
|
|
|
|
{
|
|
|
|
return v.StartsWith('[') && v.EndsWith(']');
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2019-05-08 17:40:30 +02:00
|
|
|
/// Method to create lists containing possible combinations of an input list of items. This is
|
|
|
|
/// basically copied from code by user "jaolho" on this thread:
|
|
|
|
/// http://stackoverflow.com/questions/7802822/all-possible-combinations-of-a-list-of-values
|
|
|
|
/// </summary>
|
|
|
|
/// <typeparam name="T">type of the items on the input list</typeparam>
|
|
|
|
/// <param name="inputList">list of items</param>
|
|
|
|
/// <param name="minimumItems">minimum number of items wanted in the generated combinations,
|
|
|
|
/// if zero the empty combination is included,
|
|
|
|
/// default is one</param>
|
|
|
|
/// <param name="maximumItems">maximum number of items wanted in the generated combinations,
|
|
|
|
/// default is no maximum limit</param>
|
|
|
|
/// <returns>list of lists for possible combinations of the input items</returns>
|
|
|
|
public static List<List<T>> ItemCombinations<T>(List<T> inputList, int minimumItems = 1,
|
|
|
|
int maximumItems = int.MaxValue)
|
2018-03-24 12:40:26 +01:00
|
|
|
{
|
|
|
|
int nonEmptyCombinations = (int)Math.Pow(2, inputList.Count) - 1;
|
|
|
|
List<List<T>> listOfLists = new List<List<T>>(nonEmptyCombinations + 1);
|
|
|
|
|
|
|
|
if (minimumItems == 0) // Optimize default case
|
|
|
|
listOfLists.Add(new List<T>());
|
|
|
|
|
|
|
|
for (int i = 1; i <= nonEmptyCombinations; i++)
|
|
|
|
{
|
|
|
|
List<T> thisCombination = new List<T>(inputList.Count);
|
|
|
|
for (int j = 0; j < inputList.Count; j++)
|
|
|
|
{
|
|
|
|
if ((i >> j & 1) == 1)
|
|
|
|
thisCombination.Add(inputList[j]);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (thisCombination.Count >= minimumItems && thisCombination.Count <= maximumItems)
|
|
|
|
listOfLists.Add(thisCombination);
|
|
|
|
}
|
|
|
|
|
|
|
|
return listOfLists;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|