Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Wallet domain model and abstractions #262

Merged
merged 3 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/Angor.Avalonia.sln
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Angor.UI.Model.Implementati
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{5B7EE527-242E-4C87-9BB7-AD4E05EABC4C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Angor.Wallet", "Angor\Avalonia\Angor.Wallet\Angor.Wallet.csproj", "{287F370D-D680-4BE5-8577-7A180BD0A0E3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -52,6 +54,10 @@ Global
{B84751C6-1B82-4DE8-9FBE-F0A67D981C43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B84751C6-1B82-4DE8-9FBE-F0A67D981C43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B84751C6-1B82-4DE8-9FBE-F0A67D981C43}.Release|Any CPU.Build.0 = Release|Any CPU
{287F370D-D680-4BE5-8577-7A180BD0A0E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{287F370D-D680-4BE5-8577-7A180BD0A0E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{287F370D-D680-4BE5-8577-7A180BD0A0E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{287F370D-D680-4BE5-8577-7A180BD0A0E3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -64,5 +70,6 @@ Global
{539B4D21-F2A9-46A6-84F1-9A51884A62E9} = {5B7EE527-242E-4C87-9BB7-AD4E05EABC4C}
{B84751C6-1B82-4DE8-9FBE-F0A67D981C43} = {5B7EE527-242E-4C87-9BB7-AD4E05EABC4C}
{700DF0C4-C965-4662-A91F-CD3BE043AC9E} = {5B7EE527-242E-4C87-9BB7-AD4E05EABC4C}
{287F370D-D680-4BE5-8577-7A180BD0A0E3} = {5B7EE527-242E-4C87-9BB7-AD4E05EABC4C}
EndGlobalSection
EndGlobal
13 changes: 13 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Angor.Wallet.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were having issues with NBitcoin package and .net 9 this might come up as a problem when you plug in the shared project

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh... Could you provide more details about the NBitcoin issues with .NET 9? I wasn't aware of any specific incompatibilities and it would help me better understand what we might need to address. We can switch to .NET 8 if needed, but I would like to keep current due to the performance improvements that were introduced lately :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the issue was with the latest version of NBitccoin not dotnet9, I recall the issue with dotnet9 was packaging the blazor application did not work well.
Here is the pr changes with NBitcoin that we made to make it work

I think it is not an issue for avalonia packaging and it will be backwards compatible so it is ok

<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CSharpFunctionalExtensions" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Angor.Wallet.Domain;

namespace Angor.Wallet.Application;

public interface ITransactionWatcher
{
IObservable<BroadcastedTransaction> Watch(WalletId id);
}
15 changes: 15 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Application/IWalletAppService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Angor.Wallet.Domain;
using CSharpFunctionalExtensions;

namespace Angor.Wallet.Application;

public interface IWalletAppService
{
Task<Result<TxId>> SendAmount(WalletId walletId, Amount amount, Address address, DomainFeeRate feeRate);
Task<Result<IEnumerable<(WalletId Id, string Name)>>> GetWallets();
Task<Result<IEnumerable<BroadcastedTransaction>>> GetTransactions(WalletId walletId);
Task<Result<Balance>> GetBalance(WalletId walletId);
Task<Result<Fee>> EstimateFee(WalletId walletId, Amount amount, Address address, DomainFeeRate feeRate);
Task<Result<Address>> GetNextReceiveAddress(WalletId id);
Task<Result<WalletId>> ImportWallet(string name, string seedwords, Maybe<string> passphrase, string encryptionKey, BitcoinNetwork network);
}
3 changes: 3 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/Address.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record Address(string Value);
3 changes: 3 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/Amount.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record Amount(long Value);
3 changes: 3 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/Balance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record Balance(long Value);
7 changes: 7 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/BitcoinNetwork.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Angor.Wallet.Domain;

public enum BitcoinNetwork
{
Mainnet,
Testnet
}
15 changes: 15 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/BroadcastedTransaction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Angor.Wallet.Domain;

public record BroadcastedTransaction(
Balance Balance,
string Id,
IEnumerable<TransactionInputInfo> WalletInputs,
IEnumerable<TransactionOutputInfo> WalletOutputs,
IEnumerable<TransactionAddressInfo> AllInputs,
IEnumerable<TransactionAddressInfo> AllOutputs,
ulong Fee,
bool IsConfirmed,
int? BlockHeight,
DateTimeOffset? BlockTime,
string RawJson
);
20 changes: 20 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/DerivationPath.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace Angor.Wallet.Domain;

public record DerivationPath
{
public uint Purpose { get; }
public uint CoinType { get; }
public uint Account { get; }

private DerivationPath(uint purpose, uint coinType, uint account)
{
Purpose = purpose;
CoinType = coinType;
Account = account;
}

public static DerivationPath Create(uint purpose, uint coinType, uint account) =>
new(purpose, coinType, account);

public override string ToString() => $"{Purpose}'{CoinType}'{Account}'";
}
7 changes: 7 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/DerivationType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Angor.Wallet.Domain;

public enum DerivationType
{
Receive = 0,
Change = 1
}
3 changes: 3 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/DomainException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public class DomainException(string message) : Exception(message);
3 changes: 3 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/DomainFeeRate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record DomainFeeRate(long Value);
11 changes: 11 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/DomainScriptType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Angor.Wallet.Domain;

public enum DomainScriptType
{
Invalid,
SegWit,
Taproot,
Legacy,
P2SH,
P2WSH
}
3 changes: 3 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/Fee.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record Fee(long Value);
9 changes: 9 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/IWalletRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using CSharpFunctionalExtensions;

namespace Angor.Wallet.Domain;

public interface IWalletRepository
{
Task<Result<IEnumerable<(WalletId Id, string Name)>>> ListWallets();
Task<Result<Wallet>> Get(WalletId id);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Angor.Wallet.Domain;

public record TransactionAddressInfo(
string Address,
ulong TotalAmount
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record TransactionInputInfo(TransactionAddressInfo Address);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record TransactionOutputInfo(TransactionAddressInfo Address);
3 changes: 3 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/TxId.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Angor.Wallet.Domain;

public record TxId(string Value);
13 changes: 13 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/Wallet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Angor.Wallet.Domain;

public class Wallet
{
public Wallet(WalletId id, WalletDescriptor descriptor)
{
Id = id;
Descriptor = descriptor;
}

public WalletId Id { get; }
public WalletDescriptor Descriptor { get; }
}
28 changes: 28 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/WalletDescriptor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Text.RegularExpressions;

namespace Angor.Wallet.Domain;

public sealed record WalletDescriptor
{
public string Fingerprint { get; }
Copy link
Collaborator

@DavidGershony DavidGershony Feb 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this all go in a DB once we plug one in?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have just removed the Fingerprint because we won't need it. It was used in the first iterations of the model and I think it's safe to just delete it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To clarify the persistence model, here are the contents of wallets.json from the implementation in the next follow-up PRs:

[
  {
    "Id": "c3e98932-4756-43c8-87be-cdf35c5a1e40",
    "EncryptedData": "O9kjcVa90lx\u002BuXr/6bRxUtwjRAJ4/St147ry6wVt5RF5zsTXOWNaA\u002BTm7y2xqlRGsWrFH20UBMyKfSemJxb/PgEaM1mv6CPs1wb/Minkuhw33wKSBFYCncBtmeZPgdX/KznwjUDfe6cvGpWUhC/DuevRb\u002BDZ5K4nZTx50CyEmc4LiQ\u002B/bY/3GXcdSmVT6NfnEk\u002BH/R1ufbt85IycfReOhHLloZK6zw6monwLEhuWS0hoZ9ufgUazFcjTs5Kt8UNbB3hgLqzbEls/7i5m8qWkV\u002BPNrKf6FdDT3Qlxkuq\u002B4GYhVhBcNGkhaXP5\u002BDYpApIClBC0c27TMChAJiJ7ni2L88th5Ss45abC71cWRPlyAWG5sD7oZQAezGLcee1cTQTGVw83/hwPcswpefskQReNfek4ySIdpzEMNS3LW9crEbHH0WZR3wMDea0pg/SEGoNp1WOUHBSZsBuBFN5zt7W8TyeDMslHAtJcvJW3OOe84L9/Sven245lKo4A7AacUedLZTCUSqBFs8uwqGG2kDFE4EPh6TeaOUTSOYFRHYKRhR4Uf\u002BsRq1O\u002Btd\u002B9kl6xiZY0q0\u002BlF8FsoRWJj00rGSvp3in3u/zmwkxAWylZ9K\u002BKnQV7s7h3NT2\u002BtUq/sfYn/up/epHzdKFTvadcbwcjZA0VGzg1Uq0v3MoVadaEH8RO3AzCDnq0nvRgL3ncMXM/OVME4mLITI53n\u002BZF6F1iHc69Qjw9aBZr\u002BQNwBiDP2N36aab0MTLnQVhtsu/8OHNm0v4XsyA/nZktvJE87bvcKiTmwWfMoYzG2OU23lTtqskQF\u002B7SNZ9j5dxJLTG92Iu42kqAFxvJzLcwCr\u002BTud10MRRbNA5\u002Bm4gER0WvoCqUOgvQegBQUIOxlZUWY1An0RDkShKk5mR\u002Ba51zgv1cv5hfded2uCM2skNRTpBXeVt0y7Mwt7m\u002BGIpFypbZ\u002BaqD23y6uyB0hmwJ6efgxbIFnDdGdIeL\u002BRDh2upUNVBMjI9081nX1Nk=",
    "Salt": "4XDdhcCEQXzoKwCYipFmSJojY7DyFOh89j1jEfe6fyE=",
    "IV": "4sa1cnbbGe1zn75BMVHoGw=="
  }
]

Note: Since we only support 1 single wallet right now, the Guid is prefixed and always the same. The wallet's essential data (including xpubs) is stored in the EncryptedData field. If we ever support multiple wallets, we'll already have the domain and services parts covered.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of a random generated gui why not use the wallet xpub as the id?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a a good question! I went with a GUID for WalletId instead of using the xpub for several reasons:

  1. Separation of "identity" from "capabilities":

    • The GUID solely identifies the wallet in the system (even if we allow 1 wallet only)
    • The xpubs define what the wallet can do (derive addresses, etc.)
    • This separation makes the model cleaner and more flexible
  2. Security considerations:

    • A GUID doesn't leak any information about the wallet's structure
    • Xpubs are sensitive data that we want to keep encrypted
    • Using xpubs as IDs would expose them in logs, URLs, etc.
  3. Multiple xpubs support:

    • A wallet can have multiple xpubs (for different script types)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

xpubs are not really sensitive information AFAIK, on the contrary they are designed to be passed to a 3rd party watch node or so. maybe from a privacy point of view, but still I don't think it is such an issue.

None the less I don't think it is such a big deal we can keep using guids just guids just add unnecessary metadata IMO

public BitcoinNetwork Network { get; }
public XPubCollection XPubs { get; }

private WalletDescriptor(string fingerprint, BitcoinNetwork network, XPubCollection xpubs)
{
Fingerprint = fingerprint;
Network = network;
XPubs = xpubs;
}

public static WalletDescriptor Create(string fingerprint, BitcoinNetwork network, XPubCollection xpubs)
{
if (string.IsNullOrWhiteSpace(fingerprint) || !IsValidFingerprint(fingerprint))
throw new DomainException("Invalid wallet fingerprint");

return new WalletDescriptor(fingerprint, network, xpubs);
}

private static bool IsValidFingerprint(string fingerprint) =>
Regex.IsMatch(fingerprint, "^[0-9a-f]{8}$", RegexOptions.IgnoreCase);
}
12 changes: 12 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/WalletDomainService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using CSharpFunctionalExtensions;

namespace Angor.Wallet.Domain;

public static class WalletDomainService
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bit confusing to me, are the transactions part of the wallet? where is the data coming from?

Copy link
Contributor Author

@SuperJMN SuperJMN Feb 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right - I initially created a WalletDomainService thinking we needed domain logic for balance calculation, but I realized it wasn't necessary because:

  1. Transactions aren't part of the Wallet entity:

    • They live in the blockchain (our source of truth)
    • The balance is just a derived value from these transactions
  2. The data flow is straightforward:

    • Transactions come from our blockchain node
    • Balance is a simple sum of unspent outputs
    • No complex domain rules are involved

I'll remove the WalletDomainService since it's adding unnecessary complexity. The balance calculation can be handled directly in the infrastructure layer.

{
public static Result<Balance> CalculateBalance(IEnumerable<BroadcastedTransaction> transactions)
{
var sum = transactions.Sum(t => t.Balance.Value);
return Result.Success(new Balance(sum));
}
}
9 changes: 9 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/WalletId.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Angor.Wallet.Domain;

public record WalletId(Guid Id)
{
public static WalletId New()
{
return new WalletId(Guid.NewGuid());
}
}
35 changes: 35 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/XPub.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
namespace Angor.Wallet.Domain;

public sealed record XPub
{
public string Value { get; }
public DomainScriptType ScriptType { get; }
public DerivationPath Path { get; }

private XPub(string value, DomainScriptType scriptType, DerivationPath path)
{
Value = value;
ScriptType = scriptType;
Path = path;
}

public static XPub Create(string value, DomainScriptType scriptType, DerivationPath path)
{
if (string.IsNullOrWhiteSpace(value))
throw new DomainException("XPub value cannot be empty");

return new XPub(value, scriptType, path);
}

public string ToDescriptor(DerivationType derivationType)
{
var descriptor = ScriptType switch
{
DomainScriptType.SegWit => $"wpkh({Value}/{(int)derivationType}/*)",
DomainScriptType.Taproot => $"tr({Value}/{(int)derivationType}/*)",
_ => throw new NotSupportedException($"Script type {ScriptType} not supported")
};

return descriptor;
}
}
29 changes: 29 additions & 0 deletions src/Angor/Avalonia/Angor.Wallet/Domain/XPubCollection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Collections;

namespace Angor.Wallet.Domain;

public sealed record XPubCollection : IEnumerable<XPub>
{
private readonly Dictionary<DomainScriptType, XPub> xpubs;

private XPubCollection(Dictionary<DomainScriptType, XPub> xpubs)
{
this.xpubs = xpubs;
}

public static XPubCollection Create(XPub segwitXPub, XPub taprootXPub)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this used for testing? seems very specific

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, this is not just for testing - let me explain the design:

XPubCollection contains the extended public keys that define what a wallet can do. We need this specific implementation because the Infrastructure layer needs these xpubs to:

  • Derive addresses
  • Track UTXOs
  • Calculate balances
  • Monitor transactions

To simplify things even more I've changed XPubCollection to derive from Collection to remove unnecessary complexity, while still retaining its domain meaning and purpose.

{
return new XPubCollection(new Dictionary<DomainScriptType, XPub>
{
{ DomainScriptType.SegWit, segwitXPub },
{ DomainScriptType.Taproot, taprootXPub }
});
}

public IEnumerator<XPub> GetEnumerator() => xpubs.Values.GetEnumerator();

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}