Checkpoint commit: working on cold storage accounting

This commit is contained in:
Rick Falkvinge
2016-01-14 00:06:37 +01:00
parent 6e21e439bc
commit f73e6cf3b8
8 changed files with 111 additions and 27 deletions
@@ -117,6 +117,11 @@
/// </summary>
CostsBankFees,
/// <summary>
/// Miner's fees on the bitcoin network
/// </summary>
CostsBitcoinFees,
/// <summary>
/// IT and such - default SMS charges, etc, here
/// </summary>
+57 -19
View File
@@ -5,6 +5,7 @@ using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Security.Cryptography;
using System.Text;
@@ -14,6 +15,7 @@ using System.Web.Configuration;
using NBitcoin;
using NBitcoin.BouncyCastle.Asn1.Ocsp;
using Newtonsoft.Json.Linq;
using NUnit.Framework.Constraints;
using Swarmops.Database;
using Swarmops.Logic.Communications;
using Swarmops.Logic.Communications.Payload;
@@ -166,11 +168,47 @@ namespace Swarmops.Logic.Financial
return false; // no funds on address at all at this time
}
var unspentJsonResult =
JObject.Parse (
new WebClient().DownloadString ("https://blockchain.info/unspent?active=" + address + "&api_key=" +
JObject unspentJsonResult;
try
{
unspentJsonResult = JObject.Parse(
new WebClient().DownloadString("https://blockchain.info/unspent?active=" + address + "&api_key=" +
SystemSettings.BlockchainSwarmopsApiKey));
// warn: will 500 if no unspent outpoints
}
catch (WebException webException)
{
// A 500 on the above _may_ mean that there's no unspent outpoints. It can also mean a data
// retrieval or network error, in which case the exception must absolutely not be interpreted
// as valid data of zero unspent outpoints.
try
{
if (webException.Response == null)
{
throw; // if there's no response at all, we can't do shit
}
string errorResponseContent =
new StreamReader (webException.Response.GetResponseStream()).ReadToEnd();
if (errorResponseContent.Trim().StartsWith ("No free outputs to spend"))
{
// all is okay network-wise, there just aren't any UTXOs so we're getting an error code for that
return false; // no further processing and there are no fresh transactions
}
throw; // otherwise throw upward
}
catch (WebException webExceptionInner)
{
// Ok, we tried, but there's apparently a network error so we need to abort this whole thing
throw;
}
}
foreach (var unspentJson in unspentJsonResult["unspent_outputs"])
{
@@ -276,6 +314,15 @@ namespace Swarmops.Logic.Financial
}
}
private static Dictionary<string, int> GetAddressToAccountMap (Organization organization)
{
Dictionary<string, int> result = new Dictionary<string, int>();
// Create a map of address-to-account for an org, use it to parse cold storage txs
return result;
}
private static void CheckColdStorageRecurse (FinancialAccount parent)
{
foreach (FinancialAccount child in parent.Children)
@@ -289,24 +336,15 @@ namespace Swarmops.Logic.Financial
string address = parent.Name.Trim();
try
if (!BitcoinUtility.IsValidBitcoinAddress (address))
{
BitcoinAddress addressTest = new BitcoinAddress (BitcoinTestAddress, Network.Main);
}
catch (Exception)
{
// the name wasn't an address, so return
return;
return; // not a bitcoin address but something else
}
var addressData =
JObject.Parse (
new WebClient().DownloadString ("https://blockchain.info/address/" + address +
"?format=json&api_key=" +
SystemSettings.BlockchainSwarmopsApiKey));
// warn: will 500 if no unspent outpoints
JObject addressData = JObject.Parse(
new WebClient().DownloadString("https://blockchain.info/address/" + address +
"?format=json&api_key=" +
SystemSettings.BlockchainSwarmopsApiKey));
int transactionCount = (int) (addressData["n_tx"]);
foreach (var tx in addressData["txs"])
@@ -1,3 +1,4 @@
using System.Runtime.CompilerServices;
using Swarmops.Common.Enums;
using Swarmops.Database;
using Swarmops.Logic.Structure;
@@ -90,6 +91,11 @@ namespace Swarmops.Logic.Financial
get { return this[OrganizationFinancialAccountType.CostsBankFees]; }
}
public FinancialAccount CostsBitcoinFees
{
get { return this[OrganizationFinancialAccountType.CostsBitcoinFees]; }
}
public FinancialAccount CostsAllocatedFunds
{
get { return this[OrganizationFinancialAccountType.CostsAllocatedFunds]; }
+18 -4
View File
@@ -649,7 +649,12 @@ namespace Swarmops.Logic.Financial
continue; // with next organization
}
// If we arrive at this point, the previous function didn't throw, and we have enough money. Add the inputs to the transaction.
// If we arrive at this point, the previous function didn't throw, and we have enough money.
// Ensure the existence of a cost account for bitcoin miner fees.
organization.EnsureMinerFeeAccountExists();
// Add the inputs to the transaction.
txBuilder = txBuilder.AddCoins (inputs.Coins);
txBuilder = txBuilder.AddKeys (inputs.PrivateKeys);
@@ -804,11 +809,20 @@ namespace Swarmops.Logic.Financial
FinancialTransaction ledgerTransaction = FinancialTransaction.Create (organization, utcNow,
"Bitcoin automated payout");
ledgerTransaction.AddRow(organization.FinancialAccounts.AssetsBitcoinHot, -masterPayoutPrototype.AmountCents, null).NativeAmountCents = new Swarmops.Logic.Financial.Money(satoshisUsed, Currency.Bitcoin);
// Right now, exchange rate becomes slightly fudged to include fees in fiat amount paid
if (organization.Currency.IsBitcoin)
{
ledgerTransaction.AddRow(organization.FinancialAccounts.AssetsBitcoinHot, -(masterPayoutPrototype.AmountCents + feeSatoshis), null);
ledgerTransaction.AddRow (organization.FinancialAccounts.CostsBitcoinFees, feeSatoshis, null);
}
else
{
// If the ledger isn't using bitcoin natively, we need to translate the fee paid to ledger cents before entering it into ledger
// TODO: ADD FEES, MAKE SURE CENTS ADD UP
Int64 feeCentsLedger = new Money (feeSatoshis, Currency.Bitcoin).ToCurrency (organization.Currency).Cents;
ledgerTransaction.AddRow(organization.FinancialAccounts.AssetsBitcoinHot, -(masterPayoutPrototype.AmountCents + feeCentsLedger), null).NativeAmountCents = new Money(satoshisUsed, Currency.Bitcoin);
ledgerTransaction.AddRow (organization.FinancialAccounts.CostsBitcoinFees, feeCentsLedger, null);
}
ledgerTransaction.BlockchainHash = transactionHash;
+11 -2
View File
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -169,7 +169,7 @@ namespace Swarmops.Logic.Resources {
}
/// <summary>
/// Looks up a localized string similar to Bank Fees.
/// Looks up a localized string similar to Financial Fees.
/// </summary>
internal static string Cost_BankFees {
get {
@@ -177,6 +177,15 @@ namespace Swarmops.Logic.Resources {
}
}
/// <summary>
/// Looks up a localized string similar to Bitcoin Miner Fees.
/// </summary>
internal static string Cost_BitcoinFees {
get {
return ResourceManager.GetString("Cost_BitcoinFees", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cent Rounding.
/// </summary>
@@ -156,7 +156,10 @@
<value>Asset Depreciation</value>
</data>
<data name="Cost_BankFees" xml:space="preserve">
<value>Bank Fees</value>
<value>Financial Fees</value>
</data>
<data name="Cost_BitcoinFees" xml:space="preserve">
<value>Bitcoin Miner Fees</value>
</data>
<data name="Cost_CentRounding" xml:space="preserve">
<value>Cent Rounding</value>
+9
View File
@@ -526,6 +526,15 @@ namespace Swarmops.Logic.Structure
OptionalData.SetOptionalDataBool (ObjectOptionalDataType.OrgEconomyEnabled, true);
}
public void EnsureMinerFeeAccountExists()
{
if (FinancialAccounts[OrganizationFinancialAccountType.CostsBitcoinFees] == null)
{
FinancialAccounts[OrganizationFinancialAccountType.CostsBitcoinFees] =
FinancialAccount.Create(this, "[LOC]Cost_BitcoinFees", FinancialAccountType.Cost, FinancialAccounts.CostsBankFees);
}
}
#endregion
#region Public properties
+1 -1
View File
@@ -41,7 +41,7 @@ namespace Swarmops
// HotBitcoinAddresses testAddresses = HotBitcoinAddresses.ForOrganization (Organization.FromIdentity (2));
// testAddresses.UpdateBalances();
// BitcoinUtility.TestUnspents ("1C2PCniG1gSLNgTqXUNErXTbUiz6tYi84");
BitcoinUtility.TestUnspents("18GkxU6Y6cFMfT5wxZiQi15DAMZMX2PWSB");
// BitcoinUtility.TestMultisigPayout();