diff --git a/Common/Enums/ObjectOptionalDataType.cs b/Common/Enums/ObjectOptionalDataType.cs index 67727d6a..f576bf3f 100644 --- a/Common/Enums/ObjectOptionalDataType.cs +++ b/Common/Enums/ObjectOptionalDataType.cs @@ -361,6 +361,11 @@ namespace Swarmops.Common.Enums /// /// For a hotwallet transaction, the complete derivation path used for this address /// - FinancialTransactionRowBitcoinDerivationPath + FinancialTransactionRowBitcoinDerivationPath, + + /// + /// For invoices or other claims, an exact bitcoin amount that overrides native currency + /// + ExactBitcoinAmountSatoshis } } \ No newline at end of file diff --git a/Logic/Communications/Payload/NotificationPayload.cs b/Logic/Communications/Payload/NotificationPayload.cs index 4ed163ae..e0cc42ab 100644 --- a/Logic/Communications/Payload/NotificationPayload.cs +++ b/Logic/Communications/Payload/NotificationPayload.cs @@ -178,6 +178,7 @@ namespace Swarmops.Logic.Communications.Payload Bitcoin_Shortage, Bitcoin_Shortage_Urgent, Bitcoin_Shortage_Critical, + Bitcoin_Hotwallet_Outflow, BitcoinPayoutAddress_Set, BitcoinPayoutAddress_Bad, BitcoinPayoutAddress_PleaseSet, diff --git a/Logic/Financial/BitcoinUtility.cs b/Logic/Financial/BitcoinUtility.cs index b397981e..76734c1f 100644 --- a/Logic/Financial/BitcoinUtility.cs +++ b/Logic/Financial/BitcoinUtility.cs @@ -91,6 +91,21 @@ namespace Swarmops.Logic.Financial } } + static public string[] GetInputAddressesForTransaction (string txHash) + { + List inputAddresses = new List(); + var jsonResult = + JObject.Parse(new WebClient().DownloadString("https://blockchain.info/rawTx/" + txHash + "?format=json&api_key=" + SystemSettings.BlockchainSwarmopsApiKey)); + + foreach (var input in jsonResult["inputs"]) + { + inputAddresses.Add ((string) (input["prev_out"]["addr"])); + } + + return inputAddresses.ToArray(); + } + + static public Coin[] GetSpendableCoin (BitcoinSecret secretKey) // we're using BitcoinSecret as arg just to reinforce caller must have privkey to spend funds { // This function queries the Blockchain API for the unspent coin. diff --git a/Logic/Financial/InboundInvoice.cs b/Logic/Financial/InboundInvoice.cs index 3871b331..ed4b667b 100644 --- a/Logic/Financial/InboundInvoice.cs +++ b/Logic/Financial/InboundInvoice.cs @@ -108,6 +108,22 @@ namespace Swarmops.Logic.Financial } } + public Int64 ExactBitcoinAmountSatoshis + { + get + { + return + ObjectOptionalData.ForObject(this).GetOptionalDataInt64( + ObjectOptionalDataType.ExactBitcoinAmountSatoshis); + } + set + { + ObjectOptionalData.ForObject(this) + .SetOptionalDataInt64(ObjectOptionalDataType.ExactBitcoinAmountSatoshis, value); + } + + } + #region IAttestable Members public void Attest (Person attester) diff --git a/Logic/Financial/Payouts.cs b/Logic/Financial/Payouts.cs index 00ca0263..1c8ab9fd 100644 --- a/Logic/Financial/Payouts.cs +++ b/Logic/Financial/Payouts.cs @@ -594,6 +594,10 @@ namespace Swarmops.Logic.Financial primaryStrings[NotificationString.OrganizationName] = organization.Name; OutboundComm.CreateNotification(organization, NotificationResource.BitcoinPayoutAddress_PleaseSet, primaryStrings, People.FromSingle(payout.RecipientPerson)); } + else if (payout.Account.StartsWith ("bitcoin:")) + { + + } } if (bitcoinPayouts.Count == 0) @@ -751,11 +755,25 @@ namespace Swarmops.Logic.Financial Payout masterPayout = Payout.CreateBitcoinPayoutFromPrototype (organization, masterPayoutPrototype, txReady.GetHash().ToString()); - // Finally, create ledger entries + // Finally, create ledger entries and notify + + NotificationStrings masterPrimaryStrings = new NotificationStrings(); + NotificationCustomStrings masterSecondaryStrings = new NotificationCustomStrings(); + + masterPrimaryStrings[NotificationString.OrganizationName] = organization.Name; + masterPrimaryStrings[NotificationString.CurrencyCode] = organization.Currency.DisplayCode; + masterSecondaryStrings["AmountFloat"] = + (new Swarmops.Logic.Financial.Money (satoshisUsed, Currency.Bitcoin).ToCurrency ( + organization.Currency).Cents/100.0).ToString ("N2", CultureInfo.InvariantCulture); + masterSecondaryStrings["BitcoinAmountFloat"] = (satoshisUsed/100.0).ToString ("N2", CultureInfo.InvariantCulture); + masterSecondaryStrings["PayoutCount"] = bitcoinPayouts.Count.ToString("N0", CultureInfo.InvariantCulture); + + OutboundComm.CreateNotification (organization, NotificationResource.Bitcoin_Hotwallet_Outflow, + masterPrimaryStrings, masterSecondaryStrings); FinancialTransaction ledgerTransaction = FinancialTransaction.Create (organization, utcNow, "Bitcoin automated payout"); - ledgerTransaction.AddRow (organization.FinancialAccounts.AssetsBitcoinHot, -masterPayoutPrototype.AmountCents, null); + ledgerTransaction.AddRow (organization.FinancialAccounts.AssetsBitcoinHot, -masterPayoutPrototype.AmountCents, null).NativeAmountCents = new Swarmops.Logic.Financial.Money(satoshisUsed, Currency.Bitcoin); masterPayout.BindToTransactionAndClose (ledgerTransaction, null); } diff --git a/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.Designer.cs b/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.Designer.cs index 04c5d8a7..f288b895 100644 --- a/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.Designer.cs +++ b/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.Designer.cs @@ -60,6 +60,24 @@ namespace Swarmops.Logic.Resources { } } + /// + /// Looks up a localized string similar to The bitcoin hotwallet for [OrganizationName] just made [PaymentCount] automatic payments totalling [CurrencyCode] [AmountFloat], or expressed in bitcoin, [BitcoinAmountFloat] microbitcoins.. + /// + internal static string Bitcoin_Hotwallet_Outflow_Body { + get { + return ResourceManager.GetString("Bitcoin_Hotwallet_Outflow_Body", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [[OrganizationName]] Hotwallet Payout: [CurrencyCode] [AmountFloat]. + /// + internal static string Bitcoin_Hotwallet_Outflow_Subject { + get { + return ResourceManager.GetString("Bitcoin_Hotwallet_Outflow_Subject", resourceCulture); + } + } + /// /// Looks up a localized string similar to [BitcoinAmountFloat] microbitcoin ("bits") was just transferred to your bitcoin address ([BitcoinAddress]) by [OrganizationName] for the following: /// diff --git a/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.resx b/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.resx index a8576878..170ecc78 100644 --- a/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.resx +++ b/Logic/Resources/Logic.Communications.Transmission.NotificationPayload.resx @@ -157,6 +157,12 @@ If you did not set this payout address (it may be worth double checking the addr [[OrganizationName]] Bitcoin payout address set + + The bitcoin hotwallet for [OrganizationName] just made [PaymentCount] automatic payments totalling [CurrencyCode] [AmountFloat], or expressed in bitcoin, [BitcoinAmountFloat] microbitcoins. + + + [[OrganizationName]] Hotwallet Payout: [CurrencyCode] [AmountFloat] + [BitcoinAmountFloat] microbitcoin ("bits") was just transferred to your bitcoin address ([BitcoinAddress]) by [OrganizationName] for the following: diff --git a/Logic/Support/ObjectOptionalData.cs b/Logic/Support/ObjectOptionalData.cs index c39e0ad6..eb4d103a 100644 --- a/Logic/Support/ObjectOptionalData.cs +++ b/Logic/Support/ObjectOptionalData.cs @@ -92,19 +92,34 @@ namespace Swarmops.Logic.Support // All ints default to 0 - public int GetOptionalDataInt (ObjectOptionalDataType key) + public int GetOptionalDataInt(ObjectOptionalDataType key) { - if (HasData (key)) + if (HasData(key)) { - return Int32.Parse (this[key]); + return Int32.Parse(this[key]); } return 0; } - public void SetOptionalDataInt (ObjectOptionalDataType key, int value) + public Int64 GetOptionalDataInt64(ObjectOptionalDataType key) { - SetOptionalData (key, value.ToString()); + if (HasData(key)) + { + return Int64.Parse(this[key]); + } + + return 0; + } + + public void SetOptionalDataInt(ObjectOptionalDataType key, int value) + { + SetOptionalData(key, value.ToString()); + } + + public void SetOptionalDataInt64(ObjectOptionalDataType key, Int64 value) + { + SetOptionalData(key, value.ToString()); } diff --git a/Site5/App_GlobalResources/Pages.Admin.resx b/Site5/App_GlobalResources/Pages.Admin.resx index ddaf2ecb..19bef348 100644 --- a/Site5/App_GlobalResources/Pages.Admin.resx +++ b/Site5/App_GlobalResources/Pages.Admin.resx @@ -117,6 +117,34 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + This is a QR code for bitcoin echo testing for {0}. Read it from your phone's bitcoin wallet to perform the echo test, or donate from your computer directly to [{1}] (that's a bitcoin address). The amount (less miner fees) will be sent back to you in the next auto-payment cycle which runs every five minutes. + The {0} is the organization name. {1} is the bitcoin address for donations. + + + Received {0} {1:N2} ({2:N0} microcoins or "bits"). They will be sent back shortly (less miner fee). + {0} is native currency, {1} is amount in native currency + + + Received {0} microcoins ("bits"). They will be sent back shortly (less miner fee). + Used if BTC is the org native currency. + + + This is a bitcoin echo test. It tests the hotwallet. If you send a small amount here, it will be sent back to you. + + + Donate + + + Waiting for transaction... + + + Transaction detected, verifying... + + + Bitcoin Echo Test for {0} + The {0} is the organization name + Activists will be called diff --git a/Site5/Master-v5.master.cs b/Site5/Master-v5.master.cs index 3297d7c6..4beb121c 100644 --- a/Site5/Master-v5.master.cs +++ b/Site5/Master-v5.master.cs @@ -38,7 +38,9 @@ namespace Swarmops // BEGIN TEST CODE - // Salaries.CreateAnnualStatements (2015); + /* string[] testStrings = + BitcoinUtility.GetInputAddressesForTransaction ( + "206a3a272d96e9cef929f88ae690c5556cee0a1e8eaca2858f8d858ee2e2cc66");*/ // END TEST CODE diff --git a/Site5/Pages/v5/Admin/BitcoinEchoTest.aspx b/Site5/Pages/v5/Admin/BitcoinEchoTest.aspx new file mode 100644 index 00000000..95c1cf92 --- /dev/null +++ b/Site5/Pages/v5/Admin/BitcoinEchoTest.aspx @@ -0,0 +1,100 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="BitcoinEchoTest.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Admin.BitcoinEchoTest" %> +<%@ Import Namespace="Swarmops.Logic.Support" %> + + + + + + + +

+

+

+
+
+ +

Bitcoin hotwallet is not enabled

+ Fail symbol
+

This organization has not enabled its bitcoin hotwallet in Swarmops. Therefore, direct donations are not available.

+

Contact the administrator for <%=this.CurrentOrganization.Name %> and ask them to enable the bitcoin hotwallet.

+
+
+ +
+ + + + diff --git a/Site5/Pages/v5/Admin/BitcoinEchoTest.aspx.cs b/Site5/Pages/v5/Admin/BitcoinEchoTest.aspx.cs new file mode 100644 index 00000000..acf18239 --- /dev/null +++ b/Site5/Pages/v5/Admin/BitcoinEchoTest.aspx.cs @@ -0,0 +1,177 @@ +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; +using Swarmops.Logic.Structure; +using Satoshis = NBitcoin.Money; // Sets it apart from Swarmops' Money class + +namespace Swarmops.Frontend.Pages.v5.Admin +{ + public partial class BitcoinEchoTest : PageV5Base + { + protected void Page_Load (object sender, EventArgs e) + { + this.PageAccessRequired = new Access (this.CurrentOrganization, AccessAspect.Administration); + + // This page is copied from Donate, with the echo payout added to the end + + + /* TEMP TEMP TEMP - REMOVE THIS CODE */ + /* + Organization fwn = Organization.FromIdentity (2); + + Salaries salaries = Salaries.ForOrganization (fwn); + foreach (Salary salary in salaries) + { + if (salary.PayrollItem.Person.BitcoinPayoutAddress.Length > 0 && salary.Attested == false) + { + salary.Attest (salary.PayrollItem.Person); // null for system apparently isn't allowed here + } + }*/ + + this.PageTitle = Resources.Pages.Admin.BitcoinEchoTest_PageTitle; + this.InfoBoxLiteral = Resources.Pages.Admin.BitcoinEchoTest_Info; + this.LabelStatus.Text = Resources.Pages.Admin.BitcoinEchoTest_StatusInitial; + this.LiteralTxDetected.Text = JavascriptEscape (Resources.Pages.Admin.BitcoinEchoTest_TransactionDetected); + + if (this.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot == null) + { + this.PanelDisabled.Visible = true; + this.PanelEnabled.Visible = false; + this.LiteralEnable.Text = @"false"; + } + + 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); + this.LiteralGuid.Text = guid; + + // TEST TEST TEST + /* + BitcoinSecret secretKey = address.PrivateKey; + Coin[] spendableCoin = BitcoinUtility.GetSpendableCoin (secretKey); + + TransactionBuilder txBuild = new TransactionBuilder(); + Transaction tx = txBuild.AddCoins (spendableCoin) + .AddKeys (secretKey) + .Send (new BitcoinAddress (BitcoinUtility.BitcoinTestAddress), new Satoshis (address.UnspentSatoshis - BitcoinUtility.FeeSatoshisPerThousandBytes)) + .SendFees (new Satoshis(BitcoinUtility.FeeSatoshisPerThousandBytes)) + .SetChange (secretKey.GetAddress()) + .BuildTransaction (true); + + bool test = txBuild.Verify (tx); + if (!test) + { + throw new InvalidOperationException("Tx is not properly signed"); + } + + BitcoinUtility.BroadcastTransaction (tx);*/ + + this.BoxTitle.Text = Resources.Pages.Financial.Donate_PageTitle; + 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 (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; + + // TODO: Update the HotBitcoinAddress with the new amount? + + 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); + + // Make sure that the hotwallet native currency is bitcoin + authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot.NativeCurrency = Currency.Bitcoin; + + // Create success message and ledger transaction + string successMessage = string.Empty; + + // TODO: Get the tx, get the input + + string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(txHash) [0]; // assumes at least one input address + + if (authData.CurrentOrganization.Currency.IsBitcoin) + { + // The ledger is native bitcoin, so units are Satoshis + + FinancialTransaction ledgerTx = FinancialTransaction.Create (authData.CurrentOrganization, + DateTime.UtcNow, "Bitcoin echo test (will be repaid immediately)"); + ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.DebtsOther, -satoshisReceived, authData.CurrentUser); + ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, satoshisReceived, authData.CurrentUser); + ledgerTx.BlockchainHash = txHash; + + if (satoshisReceived % 100 == 0) + { + successMessage = string.Format (Resources.Pages.Admin.BitcoinEchoTest_FundsReceivedNative, + (satoshisReceived/100.0).ToString ("N0")); + } + else + { + successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceivedNative, + (satoshisReceived / 100.0).ToString("N2")); + } + + // TODO: Log the payout back, as an inbound invoice for immediate payout + + } + else + { + // The ledger is NOT native bitcoin, so we'll need to convert currencies + + long orgNativeCents = moneyReceived.ToCurrency (authData.CurrentOrganization.Currency).Cents; + FinancialTransaction ledgerTx = FinancialTransaction.Create(authData.CurrentOrganization, + DateTime.UtcNow, "Bitcoin echo test (will be repaid immediately)"); + ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, -orgNativeCents, authData.CurrentUser); + ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, orgNativeCents, authData.CurrentUser).NativeAmountCents = new Swarmops.Logic.Financial.Money(satoshisReceived, Currency.Bitcoin); + ledgerTx.BlockchainHash = txHash; + + successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceived, + authData.CurrentOrganization.Currency.DisplayCode, orgNativeCents/100.0, satoshisReceived/100.0); + + // TODO: Create a payout back for this amount -- needs to be specified in bitcoin -- as an inbound invoice + } + + 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 diff --git a/Site5/Pages/v5/Financial/Donate.aspx b/Site5/Pages/v5/Financial/Donate.aspx index f85ada57..097638d4 100644 --- a/Site5/Pages/v5/Financial/Donate.aspx +++ b/Site5/Pages/v5/Financial/Donate.aspx @@ -1,4 +1,5 @@ <%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="Donate.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Financial.Donate" %> +<%@ Import Namespace="Swarmops.Logic.Support" %>