Skip to content

Commit

Permalink
Hotfix: Unable to create wallets (#323)
Browse files Browse the repository at this point in the history
* Hotfix: Unable to create wallets

* Fixed unit tests
  • Loading branch information
RodriFS authored Oct 18, 2023
1 parent a2150a7 commit ccd1591
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 26 deletions.
40 changes: 20 additions & 20 deletions src/Data/Repositories/WalletRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ public async Task<List<Wallet>> GetAvailableWallets(bool includeWatchOnlyWallets
.Include(x => x.InternalWallet)
.Include(x => x.Keys)
.ToListAsync();

if (!includeWatchOnlyWallets)
{
availableWallets = availableWallets.Where(w => !w.IsWatchOnly).ToList();
}

return availableWallets;
}

Expand All @@ -120,11 +120,11 @@ public async Task<List<Wallet>> GetAvailableWallets(bool includeWatchOnlyWallets
type.SetCreationDatetime();
type.SetUpdateDatetime();


if (type.IsBIP39Imported || type.IsWatchOnly)
{
//Persist

var addResult = await _repository.AddAsync(type, applicationDbContext);

return addResult;
Expand All @@ -134,7 +134,7 @@ public async Task<List<Wallet>> GetAvailableWallets(bool includeWatchOnlyWallets
{

//We add the internal wallet of the moment and its key if it is not a BIP39 wallet

var currentInternalWallet = (await _internalWalletRepository.GetCurrentInternalWallet());
if (currentInternalWallet != null)
{
Expand All @@ -149,7 +149,7 @@ public async Task<List<Wallet>> GetAvailableWallets(bool includeWatchOnlyWallets
type.Keys = new List<Key>();

var addResult = await _repository.AddAsync(type, applicationDbContext);

if (!addResult.Item1)
return addResult;

Expand Down Expand Up @@ -230,7 +230,7 @@ public async Task<string> GetNextSubderivationPath()
{
await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync();

var lastWallet = applicationDbContext.Wallets.OrderBy(w => w.Id).LastOrDefault(w => w.IsFinalised && !w.IsBIP39Imported);
var lastWallet = applicationDbContext.Wallets.OrderBy(w => w.Id).LastOrDefault(w => w.IsFinalised && !w.IsBIP39Imported && w.InternalWalletMasterFingerprint != null);

if (lastWallet == null || string.IsNullOrEmpty(lastWallet.InternalWalletSubDerivationPath)) return "0";

Expand Down Expand Up @@ -289,10 +289,10 @@ public async Task<string> GetNextSubderivationPath()

try
{

//Validate derivation path
var keyPath = KeyPath.Parse(derivationPath);

//Mnenomic create
var mnemonic = new Mnemonic(seedphrase);

Expand Down Expand Up @@ -334,7 +334,7 @@ public async Task<string> GetNextSubderivationPath()
return (false, addResult.Item2);
}

//Create key
//Create key
var key = new Key
{
CreationDatetime = DateTimeOffset.Now,
Expand Down Expand Up @@ -388,15 +388,15 @@ public async Task<string> GetNextSubderivationPath()
}

public async Task TrackAndScanWallet(Wallet wallet){

var derivationStrategyBase = wallet.GetDerivationStrategy();
if (derivationStrategyBase == null)
{
_logger.LogError("Error while getting the derivation scheme");

throw new InvalidOperationException("Error while getting the derivation scheme for wallet with id: when rescaning" + wallet.Id);
}

_logger.LogInformation("Starting tracking and scanning wallet with id: {WalletId}", wallet.Id);

//Track wallet
Expand All @@ -415,7 +415,7 @@ public async Task TrackAndScanWallet(Wallet wallet){
throw new ArgumentException("Value cannot be null or whitespace.", nameof(outputDescriptor));

(bool, string?) result = (true, null);

try
{
var (strategyBase, tuples) = WalletParser.ParseOutputDescriptor(outputDescriptor, CurrentNetworkHelper.GetCurrentNetwork());
Expand All @@ -431,9 +431,9 @@ public async Task TrackAndScanWallet(Wallet wallet){
Path = x.Item2.KeyPath.ToString(),
IsBIP39ImportedKey = false,
UserId = userId,

}).ToList();

Wallet? wallet;
//if singlesig
if (strategyBase is DirectDerivationStrategy)
Expand Down Expand Up @@ -463,7 +463,7 @@ public async Task TrackAndScanWallet(Wallet wallet){
}
else if (strategyBase is P2WSHDerivationStrategy p2WshDerivationStrategy && p2WshDerivationStrategy.Inner is MultisigDerivationStrategy multisigDerivationStrategy)
{

wallet = new Wallet
{
Id = 0,
Expand All @@ -486,17 +486,17 @@ public async Task TrackAndScanWallet(Wallet wallet){
{
_logger.LogError("Invalid output descriptor");
return (false, "Invalid output descriptor");

}

//Persist wallet
var addResult = await AddAsync(wallet);
if (addResult.Item1 == false)
{
_logger.LogError("Error while importing wallet from output descriptor: {Error}", addResult.Item2);
return (false, addResult.Item2);
}

//Track wallet
var derivationStrategyBase = wallet.GetDerivationStrategy();
if (derivationStrategyBase == null)
Expand Down
17 changes: 11 additions & 6 deletions test/NodeGuard.Tests/Data/Repositories/WalletRepositoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ public async Task GetNextSubderivationPath_ReturnsNext()
Name = "TestWallet",
IsFinalised = true,
IsHotWallet = true,
InternalWalletMasterFingerprint = "abcd",
InternalWalletSubDerivationPath = "0"
});
context.SaveChanges();
Expand All @@ -120,13 +121,15 @@ public async Task GetNextSubderivationPath_DoesntReturnNotFinalisedWallet()
Name = "TestWallet",
IsFinalised = true,
IsHotWallet = true,
InternalWalletMasterFingerprint = "abcd",
InternalWalletSubDerivationPath = "0"
});
context.Wallets.Add(new Wallet()
{
Name = "NotFinalised",
IsFinalised = false,
IsHotWallet = true,
InternalWalletMasterFingerprint = "abcd",
InternalWalletSubDerivationPath = "1"
});
context.SaveChanges();
Expand All @@ -152,6 +155,7 @@ public async Task GetNextSubderivationPath_ReturnsSubderivedWallet()
IsFinalised = true,
IsHotWallet = true,
IsCompromised = true,
InternalWalletMasterFingerprint = "abcd",
InternalWalletSubDerivationPath = "0"
});
context.Wallets.Add(new Wallet()
Expand All @@ -161,6 +165,7 @@ public async Task GetNextSubderivationPath_ReturnsSubderivedWallet()
IsHotWallet = true,
IsBIP39Imported = true,
IsCompromised = true,
InternalWalletMasterFingerprint = "abcd",
InternalWalletSubDerivationPath = null
});
context.SaveChanges();
Expand All @@ -169,7 +174,7 @@ public async Task GetNextSubderivationPath_ReturnsSubderivedWallet()
var result = await walletRepository.GetNextSubderivationPath();
result.Should().Be("1");
}

private WalletRepository SetupTestClassForImportBIP39Wallet()
{
var keyRepositoryMock = new Mock<IKeyRepository>();
Expand Down Expand Up @@ -198,15 +203,15 @@ private WalletRepository SetupTestClassForImportBIP39Wallet()
return new WalletRepository(new Repository<Wallet>(new Mock<ILogger<Wallet>>().Object), loggerMock.Object, setupDbContextFactory.Object, internalWalletRepositoryMock.Object, keyRepositoryMock.Object, nbXplorerServiceMock.Object);
}


[Fact]
public async Task ImportBIP39Wallet_WhenValidInput_ShouldReturnSuccess()
{
// Arrange
var seedphrase = "social mango annual basic work brain economy one safe physical junk other toy valid load cook napkin maple runway island oil fan legend stem";
var derivationPath = "m/84'/1'/0'";
var userId = "testUser";

var testClass = SetupTestClassForImportBIP39Wallet();

// Act
Expand All @@ -217,7 +222,7 @@ public async Task ImportBIP39Wallet_WhenValidInput_ShouldReturnSuccess()
errorMessage.Should().BeNull();
}


[Fact]
public async Task ImportBIP39Wallet_WhenSeedPhraseIsEmpty_ShouldReturnError()
{
Expand All @@ -235,7 +240,7 @@ public async Task ImportBIP39Wallet_WhenSeedPhraseIsEmpty_ShouldReturnError()
result.Should().BeFalse();
errorMessage.Should().Be("Seedphrase is empty");
}

[Fact]
public async Task ImportBIP39Wallet_WhenDerivationPathIsEmpty_ShouldReturnError()
{
Expand All @@ -253,7 +258,7 @@ public async Task ImportBIP39Wallet_WhenDerivationPathIsEmpty_ShouldReturnError(
result.Should().BeFalse();
errorMessage.Should().Be("Derivation path is empty");
}

[Fact]
public async Task ImportBIP39Wallet_WhenSeedPhraseIsInvalid_ShouldReturnError()
{
Expand Down

0 comments on commit ccd1591

Please sign in to comment.