From 7a97f6b014afc06d149b9f5345a0c0b1c91cdee1 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Wed, 7 Oct 2015 19:23:32 +0200 Subject: [PATCH] Work on hotwallet --- Database/Configuration.cs | 2 +- Database/Database-HotBitcoinAddresses.cs | 26 +++++- Database/Schemata/revisions.txt | 3 +- Database/Schemata/upgrade-0028.sql | 31 +++++++ Logic/Financial/BitcoinUtility.cs | 43 +++++++++ Logic/Financial/FinancialTransaction.cs | 5 + Logic/Financial/HotBitcoinAddress.cs | 60 ++++++++++++ Logic/Financial/HotBitcoinAddressUnspents.cs | 6 +- .../App_GlobalResources/Pages.Financial.resx | 11 +++ Site5/Pages/v5/Financial/Donate.aspx | 67 ++++++++++++- Site5/Pages/v5/Financial/Donate.aspx.cs | 93 +++++++++++++++++-- 11 files changed, 331 insertions(+), 16 deletions(-) create mode 100644 Database/Schemata/upgrade-0028.sql diff --git a/Database/Configuration.cs b/Database/Configuration.cs index 80bde133..cd97122f 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -14,7 +14,7 @@ namespace Swarmops.Database /// public static int DbVersionExpected { - get { return 27; } + get { return 28; } } diff --git a/Database/Database-HotBitcoinAddresses.cs b/Database/Database-HotBitcoinAddresses.cs index 83accce2..01eec39b 100644 --- a/Database/Database-HotBitcoinAddresses.cs +++ b/Database/Database-HotBitcoinAddresses.cs @@ -50,7 +50,7 @@ namespace Swarmops.Database #region Record reading code - public BasicHotBitcoinAddress GetHotBitcoinAddress (int hotBitcoinAddressId) + public BasicHotBitcoinAddress GetHotBitcoinAddress(int hotBitcoinAddressId) { using (DbConnection connection = GetMySqlDbConnection()) { @@ -72,6 +72,28 @@ namespace Swarmops.Database } } + public BasicHotBitcoinAddress GetHotBitcoinAddress(string address) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT" + hotBitcoinAddressFieldSequence + "WHERE AddressString='" + SqlSanitize (address) + "';", connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + return ReadHotBitcoinAddressFromDataReader(reader); + } + + throw new ArgumentException("Unknown HotBitcoinAddress: " + address); + } + } + } + public BasicHotBitcoinAddress[] GetHotBitcoinAddresses(params object[] conditions) // the typical condition would be an Organization, here { List result = new List(); @@ -107,7 +129,7 @@ namespace Swarmops.Database DbCommand command = GetDbCommand( - "SELECT" + hotBitcoinAddressUnspentFieldSequence + ConstructWhereClause("HotBitcoinAddressUnspents", conditions), connection); + "SELECT" + hotBitcoinAddressUnspentFieldSequence + ConstructWhereClause("HotBitcoinAddressUnspents", conditions) + " ORDER BY HotBitcoinAddressUnspentId ASC", connection); using (DbDataReader reader = command.ExecuteReader()) { diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index 66cb7c93..efe4cdcd 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -24,4 +24,5 @@ 0024 - Maint on CreatePayrollItem [RF] 0025 - Bugfix for 0024 [RF] 0026 - Added first tables, procs for hot bitcoin wallets [RF] -0027 - Fixes and additions to HotBitcoinAddresses, -Unspents [RF] \ No newline at end of file +0027 - Fixes and additions to HotBitcoinAddresses, -Unspents [RF] +0028 - Bugfix for 0027 [RF] \ No newline at end of file diff --git a/Database/Schemata/upgrade-0028.sql b/Database/Schemata/upgrade-0028.sql new file mode 100644 index 00000000..4afc2d32 --- /dev/null +++ b/Database/Schemata/upgrade-0028.sql @@ -0,0 +1,31 @@ +DROP procedure IF EXISTS `CreateHotBitcoinAddressConditional` + + +# + + +CREATE PROCEDURE `CreateHotBitcoinAddressConditional` ( + IN organizationId INT, + IN derivationPath VARCHAR(256), + IN addressString VARCHAR(48) +) +BEGIN + + IF ((SELECT COUNT(*) FROM HotBitcoinAddresses WHERE HotBitcoinAddresses.AddressString=addressString) = 0) + THEN + + INSERT INTO HotBitcoinAddresses + (OrganizationId,DerivationPath,AddressString,BalanceSatoshis,ThroughputSatoshis) + VALUES + (organizationId,derivationPath,addressString,0,0); + + SELECT LAST_INSERT_ID() AS Identity; + + ELSE + + SELECT HotBitcoinAddresses.HotBitcoinAddressId AS Identity + WHERE HotBitcoinAddresses.AddressString=addressString; + + END IF; + +END diff --git a/Logic/Financial/BitcoinUtility.cs b/Logic/Financial/BitcoinUtility.cs index e605a11b..2a87054b 100644 --- a/Logic/Financial/BitcoinUtility.cs +++ b/Logic/Financial/BitcoinUtility.cs @@ -11,6 +11,7 @@ using System.Web; using NBitcoin; using NBitcoin.BouncyCastle.Asn1.Ocsp; using Newtonsoft.Json.Linq; +using Swarmops.Database; namespace Swarmops.Logic.Financial { @@ -43,6 +44,48 @@ namespace Swarmops.Logic.Financial return coinList.ToArray(); } + static public bool TestUnspents (string address) + { + // This function queries the Blockchain API for the unspent coin. + bool result = false; + HotBitcoinAddress hotAddress = null; + + var unspentJsonResult = + JObject.Parse(new WebClient().DownloadString("https://blockchain.info/unspent?active=" + address)); + + foreach (var unspentJson in unspentJsonResult["unspent_outputs"]) + { + BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput() + { + BitcoinAddress = address, + ConfirmationCount = (UInt32)unspentJson["confirmations"], + Satoshis = (UInt64)unspentJson["value"], + TransactionHash = (string)unspentJson["tx_hash_big_endian"], + TransactionOutputIndex = (UInt32)unspentJson["tx_output_n"] + }; + + if (txUnspent.ConfirmationCount < 2) + { + // Fresh transactions, return true + result = true; + } + + // Add unspent to database + + if (hotAddress == null) + { + hotAddress = HotBitcoinAddress.FromAddress (address); + } + + SwarmDb.GetDatabaseForWriting() + .CreateHotBitcoinAddressUnspentConditional (hotAddress.Identity, txUnspent.TransactionHash, + (int) txUnspent.TransactionOutputIndex, (Int64) txUnspent.Satoshis, (int) txUnspent.ConfirmationCount); + } + + return result; + } + + static public void BroadcastTransaction (Transaction transaction) { using (WebClient client = new WebClient()) diff --git a/Logic/Financial/FinancialTransaction.cs b/Logic/Financial/FinancialTransaction.cs index 501eafcb..831c98ab 100644 --- a/Logic/Financial/FinancialTransaction.cs +++ b/Logic/Financial/FinancialTransaction.cs @@ -73,6 +73,11 @@ namespace Swarmops.Logic.Financial return FromIdentityAggressive (transactionId); } + public static FinancialTransaction Create (Organization organization, DateTime dateTime, string description) + { + return FinancialTransaction.Create (organization.Identity, dateTime, description); + } + #endregion public FinancialTransactionRows Rows diff --git a/Logic/Financial/HotBitcoinAddress.cs b/Logic/Financial/HotBitcoinAddress.cs index 19f7b10f..81de1cd8 100644 --- a/Logic/Financial/HotBitcoinAddress.cs +++ b/Logic/Financial/HotBitcoinAddress.cs @@ -1,9 +1,13 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; +using NBitcoin; using Swarmops.Basic.Types.Financial; +using Swarmops.Database; +using Swarmops.Logic.Structure; namespace Swarmops.Logic.Financial { @@ -19,6 +23,62 @@ namespace Swarmops.Logic.Financial return new HotBitcoinAddress (basic); // invoke private ctor } + public static HotBitcoinAddress FromIdentity(int hotBitcoinAddressId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(hotBitcoinAddressId)); + } + internal static HotBitcoinAddress FromIdentityAggressive(int hotBitcoinAddressId) + { + return FromBasic(SwarmDb.GetDatabaseForWriting().GetHotBitcoinAddress(hotBitcoinAddressId)); // "Writing" is intentional + } + + public static HotBitcoinAddress Create(Organization organization, string derivationPath) + { + + +/* + string bitcoinAddress = + FinancialAccounts.BitcoinHotPublicRoot + .Derive((uint)this.CurrentOrganization.Identity) + .Derive(BitcoinUtility.BitcoinDonationsIndex) + .Derive((uint)this.CurrentUser.Identity) + .PubKey.GetAddress(Network.Main) + .ToString();*/ + + throw new NotImplementedException(); + } + + public static HotBitcoinAddress Create (Organization organization, params int[] derivationPath) + { + ExtPubKey extPubKey = FinancialAccounts.BitcoinHotPublicRoot; + extPubKey = extPubKey.Derive ((uint) organization.Identity); + string derivationPathString = string.Empty; + + foreach (int derivation in derivationPath) // requires that order is consistent from 0 to n-1 + { + extPubKey = extPubKey.Derive ((uint) derivation); + derivationPathString += " " + derivation.ToString (CultureInfo.InvariantCulture); + } + + derivationPathString = derivationPathString.TrimStart(); + string bitcoinAddress = extPubKey.PubKey.GetAddress (Network.Main).ToString(); + + int hotBitcoinAddressId = + SwarmDb.GetDatabaseForWriting() + .CreateHotBitcoinAddressConditional (organization.Identity, derivationPathString, bitcoinAddress); + + return FromIdentityAggressive (hotBitcoinAddressId); + } + + public static HotBitcoinAddress FromAddress (string bitcoinAddress) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(bitcoinAddress)); + } + + public HotBitcoinAddressUnspents Unspents + { + get { return HotBitcoinAddressUnspents.ForAddress (this); } + } } } diff --git a/Logic/Financial/HotBitcoinAddressUnspents.cs b/Logic/Financial/HotBitcoinAddressUnspents.cs index 7f6743bc..7cfd4335 100644 --- a/Logic/Financial/HotBitcoinAddressUnspents.cs +++ b/Logic/Financial/HotBitcoinAddressUnspents.cs @@ -4,12 +4,16 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Swarmops.Basic.Types.Financial; +using Swarmops.Database; using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { public class HotBitcoinAddressUnspents: PluralBase { - // unfilled for now + static public HotBitcoinAddressUnspents ForAddress (HotBitcoinAddress address) + { + return FromArray (SwarmDb.GetDatabaseForReading().GetHotBitcoinAddressUnspents (address)); + } } } diff --git a/Site5/App_GlobalResources/Pages.Financial.resx b/Site5/App_GlobalResources/Pages.Financial.resx index 43f9feb5..4a917337 100644 --- a/Site5/App_GlobalResources/Pages.Financial.resx +++ b/Site5/App_GlobalResources/Pages.Financial.resx @@ -329,12 +329,23 @@ This is a QR code for donations to {0}. Read it from your phone's bitcoin wallet to make a donation, or donate from your computer directly to [{1}] (that's a bitcoin address). The {0} is the organization name. {1} is the bitcoin address for donations. + + Received {0} {1} ({2} microcoins or "bits"). Thank you! + {0} is native currency, {1} is amount in native currency + + + Received {0} microcoins ("bits"). Thank you! + Used if BTC is the org native currency. + If you want to donate to the organization, your can do so here. Donate + + Waiting for transaction... + Donation to {0} The {0} is the organization name diff --git a/Site5/Pages/v5/Financial/Donate.aspx b/Site5/Pages/v5/Financial/Donate.aspx index d546d7f0..04b30b95 100644 --- a/Site5/Pages/v5/Financial/Donate.aspx +++ b/Site5/Pages/v5/Financial/Donate.aspx @@ -1,12 +1,77 @@ <%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="Donate.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Financial.Donate" %> +

-
+

+
diff --git a/Site5/Pages/v5/Financial/Donate.aspx.cs b/Site5/Pages/v5/Financial/Donate.aspx.cs index 688227dc..fe0a206a 100644 --- a/Site5/Pages/v5/Financial/Donate.aspx.cs +++ b/Site5/Pages/v5/Financial/Donate.aspx.cs @@ -1,11 +1,15 @@ using System; using System.Activities.Validation; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; +using System.Runtime.CompilerServices; using System.Web; +using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; using NBitcoin; +using Swarmops.Logic.Cache; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; @@ -18,14 +22,15 @@ namespace Swarmops.Frontend.Pages.v5.Financial this.PageAccessRequired = new Access (this.CurrentOrganization, AccessAspect.Participant); this.PageTitle = Resources.Pages.Financial.Donate_PageTitle; - this.InfoBoxLiteral = Resources.Pages.Financial.FileExpenseClaim_Info; - string bitcoinAddress = - FinancialAccounts.BitcoinHotPublicRoot - .Derive ((uint) this.CurrentOrganization.Identity) - .Derive (BitcoinUtility.BitcoinDonationsIndex) - .Derive ((uint) this.CurrentUser.Identity) - .PubKey.GetAddress (Network.Main) - .ToString(); + this.InfoBoxLiteral = Resources.Pages.Financial.Donate_Info; + this.LabelStatus.Text = Resources.Pages.Financial.Donate_StatusInitial; + + HotBitcoinAddress address = HotBitcoinAddress.Create (this.CurrentOrganization, + BitcoinUtility.BitcoinDonationsIndex, this.CurrentUser.Identity); + + this.LiteralBitcoinAddress.Text = address.Address; + string guid = Guid.NewGuid().ToString ("N"); + GuidCache.Set (guid, address.Address); // TEST TEST TEST /* @@ -55,10 +60,78 @@ namespace Swarmops.Frontend.Pages.v5.Financial BitcoinUtility.BroadcastTransaction (tx);*/ this.BoxTitle.Text = Resources.Pages.Financial.Donate_PageTitle; - this.LabelExplainBitcoinDonation.Text = String.Format(Resources.Pages.Financial.Donate_Explain, CurrentOrganization.Name, bitcoinAddress); + this.LabelExplainBitcoinDonation.Text = String.Format (Resources.Pages.Financial.Donate_Explain, + CurrentOrganization.Name, address.Address); this.ImageBitcoinQr.ImageUrl = - "https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=bitcoin:" + HttpUtility.UrlEncode(bitcoinAddress + "?label=" + Uri.EscapeDataString(String.Format(Resources.Pages.Financial.Donate_TxLabel, CurrentOrganization.Name))); // URI scheme doesn't like &, = + "https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=bitcoin:" + + HttpUtility.UrlEncode (address.Address + "?label=" + + Uri.EscapeDataString (String.Format (Resources.Pages.Financial.Donate_TxLabel, + CurrentOrganization.Name))); // URI scheme doesn't like &, = + } + + [WebMethod] + static public AjaxCallResult CheckTransactionReceived (string guid, string txHash) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); // just to make sure we're called properly + + string bitcoinAddress = (string) GuidCache.Get (guid); + if (BitcoinUtility.TestUnspents (bitcoinAddress)) + { + HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress (bitcoinAddress).Unspents; + + Int64 satoshisReceived = unspents.Last().AmountSatoshis; + + if (unspents.Last().TransactionHash != txHash && txHash.Length > 0) + { + // Race condition. + Debugger.Break(); + } + + Swarmops.Logic.Financial.Money moneyReceived = new Swarmops.Logic.Financial.Money (satoshisReceived, + Currency.Bitcoin); + + // Create success message and ledger transaction + string successMessage = string.Empty; + + if (authData.CurrentOrganization.Currency.IsBitcoin) + { + // The ledger is native bitcoin, so units are Satoshis + + FinancialTransaction ledgerTx = FinancialTransaction.Create (authData.CurrentOrganization, + DateTime.UtcNow, "Donation (bitcoin to hotwallet)"); + ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.IncomeDonations, -satoshisReceived, authData.CurrentUser); + ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, satoshisReceived, authData.CurrentUser); + + if (satoshisReceived % 100 == 0) + { + successMessage = string.Format (Resources.Pages.Financial.Donate_FundsReceivedNative, + (satoshisReceived/100.0).ToString ("N0")); + } + else + { + successMessage = string.Format(Resources.Pages.Financial.Donate_FundsReceivedNative, + (satoshisReceived / 100.0).ToString("N2")); + } + } + else + { + // The ledger is NOT native bitcoin, so we'll need to convert currencies + + long nativeCents = moneyReceived.ToCurrency (authData.CurrentOrganization.Currency).Cents; + FinancialTransaction ledgerTx = FinancialTransaction.Create(authData.CurrentOrganization, + DateTime.UtcNow, "Donation (bitcoin to hotwallet)"); + ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.IncomeDonations, -nativeCents, authData.CurrentUser); + ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, nativeCents, authData.CurrentUser); + } + + return new AjaxCallResult() {DisplayMessage = successMessage, Success = true}; + + // TODO: Ack donation via mail? + // TODO: Notify CFO/etc of donation? + } + + return new AjaxCallResult() {Success = false}; } } } \ No newline at end of file