Commit c0070c3b authored by Jeremy Bokobza's avatar Jeremy Bokobza Committed by GitHub

Merge pull request #60 from bokobza/master

History work
parents a37e8004 848c1a11
......@@ -235,20 +235,28 @@ This endpoint will get the last address containing no transaction or will create
### Responses
```
{
"transactions": [
"transactionsHistory": [
{
"address": "1H2jbtknP6jRYx2riaXJf3H9Mb1JC6kcL2",
"txId": "b800f9b24a9c49a375cddf4fc8c484722af0bec7d23ac65b782daf1b0089bb29",
"amount": -50360386,
"confirmed": true,
"timestamp": "1337803568"
"type": "send",
"id": "6358161c713688e372481fce7f20f3f8692ab2e4e657f3d9afa750ebee54e6c3",
"amount": 500000,
"payments": [
{
"destinationAddress": "mt7W2Zf69KC9472TPCzUeLLhBDSmC82AWz",
"amount": 500000
}
],
"fee": 100000,
"confirmedInBlock": 1122310,
"timestamp": "1494594937"
},
{
"address": "1H2jbtknP6jRYx2riaXJf3H9Mb1JC6kcL2",
"txId": "9c0560a34f88573a71ebf68a2540cb7215b55bc2ddee0af3cb1dc343f2f3e0da",
"amount": 53845026,
"confirmed": true,
"timestamp": "1337605326"
"type": "received",
"toAddress": "mnDsG7kTYCeVNqnEmfvdYeNgZwxhjqm2jc",
"id": "75ce74643aae01ccbe2bbc05efb4788cc9a16a9192add4d7082561a40a541057",
"amount": 110000000,
"confirmedInBlock": 1122292,
"timestamp": "1494591670"
}
]
}
......
......@@ -15,7 +15,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0-preview-20170106-08" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="NStratis" Version="3.0.2.23" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0-beta5-build1225" />
<PackageReference Include="System.Runtime.Serialization.Primitives" Version="4.3.0" />
......
......@@ -16,19 +16,19 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="1.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Routing" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Routing" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.2" />
<PackageReference Include="Stratis.Bitcoin" Version="1.0.1.6-alpha" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0-rc3" />
<PackageReference Include="System.Reactive" Version="3.1.1" />
......
......@@ -18,8 +18,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
<PackageReference Include="Stratis.Bitcoin" Version="1.0.1.6-alpha" />
</ItemGroup>
......
......@@ -185,26 +185,50 @@ namespace Breeze.Wallet.Controllers
try
{
WalletHistoryModel model = new WalletHistoryModel { Transactions = new List<TransactionItem>() };
WalletHistoryModel model = new WalletHistoryModel { TransactionsHistory = new List<TransactionItemModel>() };
// get transactions contained in the wallet
var addresses = this.walletManager.GetHistoryByCoinType(request.WalletName, request.CoinType);
foreach (var address in addresses)
foreach (var address in addresses.Where(a => !a.IsChangeAddress()))
{
foreach (var transaction in address.Transactions)
{
model.Transactions.Add(new TransactionItem
TransactionItemModel item = new TransactionItemModel();
if (transaction.Amount > Money.Zero)
{
Amount = transaction.Amount,
Confirmed = transaction.Confirmed,
Timestamp = transaction.CreationTime,
TransactionId = transaction.Id,
Address = address.Address
});
item.Type = TransactionItemType.Received;
item.ToAddress = address.Address;
item.Amount = transaction.Amount;
}
else
{
item.Type = TransactionItemType.Send;
item.Amount = Money.Zero;
item.Payments = new List<PaymentDetailModel>();
foreach (var payment in transaction.Payments)
{
item.Payments.Add(new PaymentDetailModel
{
DestinationAddress = payment.DestinationAddress,
Amount = payment.Amount
});
item.Amount += payment.Amount;
}
var changeAddress = addresses.Single(a => a.IsChangeAddress() && a.Transactions.Any(t => t.Id == transaction.Id));
item.Fee = transaction.Amount.Abs() - item.Amount - changeAddress.Transactions.First(t => t.Id == transaction.Id).Amount;
}
item.Id = transaction.Id;
item.Timestamp = transaction.CreationTime;
item.ConfirmedInBlock = transaction.BlockHeight;
model.TransactionsHistory.Add(item);
}
}
model.Transactions = model.Transactions.OrderByDescending(t => t.Timestamp).ToList();
model.TransactionsHistory = model.TransactionsHistory.OrderByDescending(t => t.Timestamp).ToList();
return this.Json(model);
}
catch (Exception e)
......@@ -244,8 +268,8 @@ namespace Breeze.Wallet.Controllers
CoinType = request.CoinType,
Name = account.Name,
HdPath = account.HdPath,
AmountConfirmed = allTransactions.Where(t => t.Confirmed).Sum(t => t.Amount),
AmountUnconfirmed = allTransactions.Where(t => !t.Confirmed).Sum(t => t.Amount)
AmountConfirmed = allTransactions.Where(t => t.IsConfirmed()).Sum(t => t.Amount),
AmountUnconfirmed = allTransactions.Where(t => !t.IsConfirmed()).Sum(t => t.Amount)
};
model.AccountsBalances.Add(balance);
}
......
......@@ -4,35 +4,75 @@ using Breeze.Wallet.JsonConverters;
using NBitcoin;
using NBitcoin.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Breeze.Wallet.Models
{
public class WalletHistoryModel
{
[JsonProperty(PropertyName = "transactions")]
public List<TransactionItem> Transactions { get; set; }
[JsonProperty(PropertyName = "transactionsHistory")]
public List<TransactionItemModel> TransactionsHistory { get; set; }
}
public class TransactionItem
public class TransactionItemModel
{
[JsonProperty(PropertyName = "type")]
[JsonConverter(typeof(StringEnumConverter), true)]
public TransactionItemType Type { get; set; }
/// <summary>
/// The Base58 representation of this address.
/// </summary>
[JsonProperty(PropertyName = "address")]
public string Address { get; set; }
[JsonProperty(PropertyName = "toAddress", NullValueHandling = NullValueHandling.Ignore)]
public string ToAddress { get; set; }
[JsonProperty(PropertyName = "txId")]
[JsonProperty(PropertyName = "id")]
[JsonConverter(typeof(UInt256JsonConverter))]
public uint256 TransactionId { get; set; }
public uint256 Id { get; set; }
[JsonProperty(PropertyName = "amount")]
public Money Amount { get; set; }
[JsonProperty(PropertyName = "confirmed")]
public bool Confirmed { get; set; }
/// <summary>
/// A list of payments made out in this transaction.
/// </summary>
[JsonProperty(PropertyName = "payments", NullValueHandling = NullValueHandling.Ignore)]
public ICollection<PaymentDetailModel> Payments { get; set; }
[JsonProperty(PropertyName = "fee", NullValueHandling = NullValueHandling.Ignore)]
public Money Fee { get; set; }
/// <summary>
/// The height of the block in which this transaction was confirmed.
/// </summary>
[JsonProperty(PropertyName = "confirmedInBlock", NullValueHandling = NullValueHandling.Ignore)]
public int? ConfirmedInBlock { get; set; }
[JsonProperty(PropertyName = "timestamp")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset Timestamp { get; set; }
}
public class PaymentDetailModel
{
/// <summary>
/// The Base58 representation of the destination address.
/// </summary>
[JsonProperty(PropertyName = "destinationAddress")]
public string DestinationAddress { get; set; }
/// <summary>
/// The transaction amount.
/// </summary>
[JsonProperty(PropertyName = "amount")]
[JsonConverter(typeof(MoneyJsonConverter))]
public Money Amount { get; set; }
}
public enum TransactionItemType
{
Received,
Send
}
}
......@@ -155,10 +155,7 @@ namespace Breeze.Wallet
throw new Exception($"No account with name {accountName} could be found.");
}
return account;
}
}
}
/// <summary>
......@@ -378,6 +375,17 @@ namespace Breeze.Wallet
/// </summary>
[JsonProperty(PropertyName = "transactions")]
public ICollection<TransactionData> Transactions { get; set; }
/// <summary>
/// Determines whether this is a change address or a receive address.
/// </summary>
/// <returns>
/// <c>true</c> if it is a change address; otherwise, <c>false</c>.
/// </returns>
public bool IsChangeAddress()
{
return int.Parse(this.HdPath.Split('/')[4]) == 1;
}
}
/// <summary>
......@@ -406,6 +414,12 @@ namespace Breeze.Wallet
[JsonConverter(typeof(MoneyJsonConverter))]
public Money Amount { get; set; }
/// <summary>
/// A list of payments made out in this transaction.
/// </summary>
[JsonProperty(PropertyName = "payments", NullValueHandling = NullValueHandling.Ignore)]
public ICollection<PaymentDetails> Payments { get; set; }
/// <summary>
/// The index of this scriptPubKey in the transaction it is contained.
/// </summary>
......@@ -417,19 +431,46 @@ namespace Breeze.Wallet
/// </summary>
[JsonProperty(PropertyName = "blockHeight", NullValueHandling = NullValueHandling.Ignore)]
public int? BlockHeight { get; set; }
/// <summary>
/// Whether this transaction has been confirmed or not.
/// </summary>
[JsonProperty(PropertyName = "confirmed")]
public bool Confirmed { get; set; }
/// <summary>
/// Gets or sets the creation time.
/// </summary>
[JsonProperty(PropertyName = "creationTime")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreationTime { get; set; }
/// <summary>
/// Determines whether this transaction is confirmed.
/// </summary>
public bool IsConfirmed()
{
return this.BlockHeight != null;
}
}
/// <summary>
/// An object representing a payment.
/// </summary>
public class PaymentDetails
{
/// <summary>
/// The script pub key of the destination address.
/// </summary>
[JsonProperty(PropertyName = "destinationScriptPubKey")]
[JsonConverter(typeof(ScriptJsonConverter))]
public Script DestinationScriptPubKey { get; set; }
/// <summary>
/// The Base58 representation of the destination address.
/// </summary>
[JsonProperty(PropertyName = "destinationAddress")]
public string DestinationAddress { get; set; }
/// <summary>
/// The transaction amount.
/// </summary>
[JsonProperty(PropertyName = "amount")]
[JsonConverter(typeof(MoneyJsonConverter))]
public Money Amount { get; set; }
}
}
\ No newline at end of file
......@@ -29,16 +29,18 @@ namespace Breeze.Wallet
private readonly CoinType coinType;
private readonly Network network;
private readonly ConnectionManager connectionManager;
private Dictionary<Script, ICollection<TransactionData>> keysLookup;
private Dictionary<Script, HdAddress> keysLookup;
/// <summary>
/// Occurs when a transaction is found.
/// </summary>
public event EventHandler<TransactionFoundEventArgs> TransactionFound;
public WalletManager(ConnectionManager connectionManager, Network netwrok)
public WalletManager(ConnectionManager connectionManager, Network network)
{
this.Wallets = new List<Wallet>();
......@@ -49,7 +51,8 @@ namespace Breeze.Wallet
}
this.connectionManager = connectionManager;
this.coinType = (CoinType)netwrok.Consensus.CoinType;
this.network = network;
this.coinType = (CoinType)network.Consensus.CoinType;
// load data in memory for faster lookups
this.LoadKeysLookup();
......@@ -467,13 +470,17 @@ namespace Breeze.Wallet
}
// check the inputs - include those that have a reference to a transaction containing one of our scripts and the same index
foreach (TxIn input in transaction.Inputs.Where(txIn => this.keysLookup.Values.SelectMany(v => v).Any(trackedTx => trackedTx.Id == txIn.PrevOut.Hash && trackedTx.Index == txIn.PrevOut.N)))
foreach (TxIn input in transaction.Inputs.Where(txIn => this.keysLookup.Values.SelectMany(v => v.Transactions).Any(trackedTx => trackedTx.Id == txIn.PrevOut.Hash && trackedTx.Index == txIn.PrevOut.N)))
{
TransactionData tTx = this.keysLookup.Values.SelectMany(v => v).Single(trackedTx => trackedTx.Id == input.PrevOut.Hash && trackedTx.Index == input.PrevOut.N);
TransactionData tTx = this.keysLookup.Values.SelectMany(v => v.Transactions).Single(trackedTx => trackedTx.Id == input.PrevOut.Hash && trackedTx.Index == input.PrevOut.N);
// find the script this input references
var keyToSpend = this.keysLookup.Single(v => v.Value.Contains(tTx)).Key;
AddTransactionToWallet(transaction.GetHash(), transaction.Time, null, -tTx.Amount, keyToSpend, blockHeight, blockTime, tTx.Id, tTx.Index);
var keyToSpend = this.keysLookup.Single(v => v.Value.Transactions.Contains(tTx)).Key;
// get the details of the outputs paid out
IEnumerable<TxOut> paidoutto = transaction.Outputs.Where(o => !this.keysLookup.Keys.Contains(o.ScriptPubKey));
AddTransactionToWallet(transaction.GetHash(), transaction.Time, null, -tTx.Amount, keyToSpend, blockHeight, blockTime, tTx.Id, tTx.Index, paidoutto);
}
}
......@@ -489,41 +496,68 @@ namespace Breeze.Wallet
/// <param name="blockTime">The block time.</param>
/// <param name="spendingTransactionId">The id of the transaction containing the output being spent, if this is a spending transaction.</param>
/// <param name="spendingTransactionIndex">The index of the output in the transaction being referenced, if this is a spending transaction.</param>
private void AddTransactionToWallet(uint256 transactionHash, uint time, int? index, Money amount, Script script, int? blockHeight = null, uint? blockTime = null, uint256 spendingTransactionId = null, int? spendingTransactionIndex = null)
private void AddTransactionToWallet(uint256 transactionHash, uint time, int? index, Money amount, Script script, int? blockHeight = null, uint? blockTime = null, uint256 spendingTransactionId = null, int? spendingTransactionIndex = null, IEnumerable<TxOut> paidToOutputs = null)
{
// get the collection of transactions to add to.
this.keysLookup.TryGetValue(script, out ICollection<TransactionData> trans);
this.keysLookup.TryGetValue(script, out HdAddress address);
var trans = address.Transactions;
// if it's the first time we see this transaction
if (trans != null && trans.All(t => t.Id != transactionHash))
if (trans.All(t => t.Id != transactionHash))
{
trans.Add(new TransactionData
var newTransaction = new TransactionData
{
Amount = amount,
BlockHeight = blockHeight,
Confirmed = blockHeight.HasValue,
Id = transactionHash,
CreationTime = DateTimeOffset.FromUnixTimeMilliseconds(blockTime ?? time),
Index = index
});
};
trans.Add(newTransaction);
// if this is a spending transaction, keep a record of the payments made out to other scripts.
if (paidToOutputs != null && paidToOutputs.Any())
{
List<PaymentDetails> payments = new List<PaymentDetails>();
foreach (var paidToOutput in paidToOutputs)
{
payments.Add(new PaymentDetails
{
DestinationScriptPubKey = paidToOutput.ScriptPubKey,
DestinationAddress = paidToOutput.ScriptPubKey.GetDestinationAddress(this.network).ToString(),
Amount = paidToOutput.Value
});
}
newTransaction.Payments = payments;
}
// if this is a spending transaction, mark the spent transaction as such
if (spendingTransactionId != null)
{
var transactions = this.keysLookup.Values.SelectMany(v => v).Where(t => t.Id == spendingTransactionId);
var transactions = this.keysLookup.Values.SelectMany(v => v.Transactions).Where(t => t.Id == spendingTransactionId);
if (transactions.Any())
{
transactions.Single(t => t.Index == spendingTransactionIndex).SpentInTransaction = transactionHash;
}
}
}
else if (trans.Any(t => t.Id == transactionHash && !t.Confirmed)) // if this is an unconfirmed transaction now received in a block
else if (trans.Any(t => t.Id == transactionHash)) // if this is an unconfirmed transaction now received in a block
{
var foundTransaction = trans.Single(t => t.Id == transactionHash && !t.Confirmed);
if (blockHeight != null)
var foundTransaction = trans.Single(t => t.Id == transactionHash);
// update the block height
if (foundTransaction.BlockHeight == null && blockHeight != null)
{
foundTransaction.Confirmed = true;
foundTransaction.BlockHeight = blockHeight;
}
// update the block time
if (blockTime != null)
{
foundTransaction.CreationTime = DateTimeOffset.FromUnixTimeMilliseconds(blockTime.Value);
}
}
// notify a transaction has been found
......@@ -715,7 +749,7 @@ namespace Breeze.Wallet
/// <returns></returns>
private void LoadKeysLookup()
{
this.keysLookup = new Dictionary<Script, ICollection<TransactionData>>();
this.keysLookup = new Dictionary<Script, HdAddress>();
foreach (var wallet in this.Wallets)
{
var accounts = wallet.GetAccountsByCoinType(this.coinType);
......@@ -724,7 +758,7 @@ namespace Breeze.Wallet
var addresses = account.ExternalAddresses.Concat(account.InternalAddresses);
foreach (var address in addresses)
{
this.keysLookup.Add(address.ScriptPubKey, address.Transactions);
this.keysLookup.Add(address.ScriptPubKey, address);
}
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment