From c1be027f481484e18e13d8c7696c1580b8b6de1a Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Wed, 22 Nov 2017 18:49:08 +0100 Subject: [PATCH] Added BackendServiceOrders --- Backend/Backend.csproj | 14 +- Backend/BackendLoop.cs | 1 - Backend/packages.config | 33 ++++ Basic/Basic.csproj | 1 + .../Types/System/BasicBackendServiceOrder.cs | 59 ++++++ Common/Constants.cs | 14 ++ Database/Configuration.cs | 5 +- Database/Database-BackendServiceOrders.cs | 187 ++++++++++++++++++ Database/Database-HotBitcoinAddresses.cs | 16 ++ Database/Database.csproj | 1 + Database/Schemata/revisions.txt | 3 +- Database/Schemata/upgrade-0059.sql | 160 +++++++++++++++ Logic/Financial/BitcoinTransactionInput.cs | 2 + Logic/Financial/BitcoinUtility.cs | 176 ++++++++++------- Logic/Financial/HotBitcoinAddress.cs | 11 +- Logic/Financial/HotBitcoinAddressUnspent.cs | 7 +- Logic/Financial/HotBitcoinAddresses.cs | 5 + Logic/Financial/Payouts.cs | 8 +- Logic/Logic.csproj | 18 +- Logic/Support/BackendServiceOrder.cs | 95 +++++++++ Logic/Support/BackendServiceOrders.cs | 28 +++ .../BackendServiceOrderBase.cs | 110 +++++++++++ .../ReturnBitcoinEchoUtxoOrder.cs | 54 +++++ Logic/Support/General.cs | 17 +- Logic/Support/IBackendServiceOrderBase.cs | 18 ++ Logic/packages.config | 33 ++++ .../Pages.Admin.designer.cs | 4 +- Site/App_GlobalResources/Pages.Admin.resx | 4 +- Site/Master-v5.master | 8 +- Site/Pages/v5/Admin/BitcoinEchoTest.aspx | 135 ++++++++----- Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs | 187 ++++++++++++------ .../v5/Admin/BitcoinEchoTest.aspx.designer.cs | 40 +--- Site/Pages/v5/Financial/Donate.aspx | 4 +- Site/Pages/v5/Financial/Donate.aspx.cs | 8 + Site/Site.csproj | 13 +- Site/packages.config | 33 ++++ 36 files changed, 1249 insertions(+), 263 deletions(-) create mode 100644 Basic/Types/System/BasicBackendServiceOrder.cs create mode 100644 Database/Database-BackendServiceOrders.cs create mode 100644 Database/Schemata/upgrade-0059.sql create mode 100644 Logic/Support/BackendServiceOrder.cs create mode 100644 Logic/Support/BackendServiceOrders.cs create mode 100644 Logic/Support/BackendServices/BackendServiceOrderBase.cs create mode 100644 Logic/Support/BackendServices/ReturnBitcoinEchoUtxoOrder.cs create mode 100644 Logic/Support/IBackendServiceOrderBase.cs diff --git a/Backend/Backend.csproj b/Backend/Backend.csproj index cd5a065a..2f452a99 100644 --- a/Backend/Backend.csproj +++ b/Backend/Backend.csproj @@ -63,16 +63,26 @@ ..\packages\Mono.Posix-4.5.4.5.0\lib\net45\Mono.Posix.dll True - - ..\External Libraries\NBitcoinDual.dll + + ..\packages\NBitcoinBCC.1.0.16\lib\netstandard1.1\NBitcoinBCC.dll + True ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll True + + + + + + ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll + True + + ..\packages\WebSocketSharp.1.0.3-rc11\lib\websocket-sharp.dll True diff --git a/Backend/BackendLoop.cs b/Backend/BackendLoop.cs index 46d766b8..b615ef24 100644 --- a/Backend/BackendLoop.cs +++ b/Backend/BackendLoop.cs @@ -5,7 +5,6 @@ using System.Net; using System.Threading; using Mono.Unix; using Mono.Unix.Native; -using NBitcoin.Protocol.Behaviors; using Newtonsoft.Json.Linq; using Swarmops.Backend.SocketServices; using Swarmops.Common.Enums; diff --git a/Backend/packages.config b/Backend/packages.config index f035528a..b41859c6 100644 --- a/Backend/packages.config +++ b/Backend/packages.config @@ -1,6 +1,39 @@  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Basic/Basic.csproj b/Basic/Basic.csproj index 8384d965..e9ca7e5d 100644 --- a/Basic/Basic.csproj +++ b/Basic/Basic.csproj @@ -65,6 +65,7 @@ + diff --git a/Basic/Types/System/BasicBackendServiceOrder.cs b/Basic/Types/System/BasicBackendServiceOrder.cs new file mode 100644 index 00000000..fe24ed34 --- /dev/null +++ b/Basic/Types/System/BasicBackendServiceOrder.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Common.Interfaces; + +namespace Swarmops.Basic.Types.System +{ + public class BasicBackendServiceOrder: IHasIdentity + { + + public BasicBackendServiceOrder(int backendServiceOrderId, int organizationId, int personId, + string backendServiceClassName, string orderXml, + bool open, bool active, DateTime createdDateTime, DateTime startedDateTime, DateTime closedDateTime, + string exceptionText) + { + this.BackendServiceOrderId = backendServiceOrderId; + this.OrganizationId = organizationId; + this.PersonId = personId; + this.BackendServiceClassName = backendServiceClassName; + this.OrderXml = orderXml; + this.Open = open; + this.Active = active; + this.CreatedDateTime = createdDateTime; + this.StartedDateTime = startedDateTime; + this.ClosedDateTime = closedDateTime; + this.ExceptionText = exceptionText; + } + + public BasicBackendServiceOrder(BasicBackendServiceOrder original) : + this(original.BackendServiceOrderId, original.OrganizationId, original.PersonId, + original.BackendServiceClassName, original.OrderXml, + original.Open, original.Active, original.CreatedDateTime, original.StartedDateTime, + original.ClosedDateTime, original.ExceptionText) + { + // empty copy ctor required for higher logic + } + + // fields + + public int BackendServiceOrderId { get; set; } + public int OrganizationId { get; set; } + public int PersonId { get; set; } + public string BackendServiceClassName { get; set; } + public string OrderXml { get; set; } + public bool Open { get; set; } + public bool Active { get; set; } + public DateTime CreatedDateTime { get; set; } + public DateTime StartedDateTime { get; set; } + public DateTime ClosedDateTime { get; set; } + public string ExceptionText { get; set; } + + public int Identity + { + get { return this.GetHashCode(); } + } + } +} diff --git a/Common/Constants.cs b/Common/Constants.cs index a129807d..02c8e293 100644 --- a/Common/Constants.cs +++ b/Common/Constants.cs @@ -14,7 +14,21 @@ namespace Swarmops.Common public static DateTime DateTimeLow { get { return new DateTime(1800, 1, 1); } } + public static DateTime DateTimeLowThreshold + { + get { return new DateTime(1801, 1, 1); } + } + + /// + /// Used to set a high date + /// public static DateTime DateTimeHigh { get { return new DateTime(2300, 12, 1); } } + + /// + /// Used in comparisons to see if date is high + /// + public static DateTime DateTimeHighThreshold + { get { return new DateTime(2299, 1, 1); } } } } diff --git a/Database/Configuration.cs b/Database/Configuration.cs index 401017fd..e8e0d2a2 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -12,10 +12,7 @@ namespace Swarmops.Database /// /// This is the IN-CODE revision of the database. The version we expect to be running against. /// - public static int DbVersionExpected - { - get { return 58; } - } + public static int DbVersionExpected => 59; // This class is in horrible need of serious refactoring. For its simplicity in task, it's a horrible bowl of spaghetti. diff --git a/Database/Database-BackendServiceOrders.cs b/Database/Database-BackendServiceOrders.cs new file mode 100644 index 00000000..1de80bdd --- /dev/null +++ b/Database/Database-BackendServiceOrders.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Globalization; +using Swarmops.Basic.Types; +using Swarmops.Basic.Types.Financial; +using Swarmops.Basic.Types.System; +using Swarmops.Common.Exceptions; + +namespace Swarmops.Database +{ + public partial class SwarmDb + { + #region Field reading code + + private const string backendServiceOrderFieldSequence = + " BackendServiceOrders.BackendServiceOrderId, BackendServiceOrders.CreatedDateTime, BackendServiceOrders.OrganizationId, BackendServiceOrders.PersonId, BackendServiceClasses.Name, " + // 0-4 + " BackendServiceOrders.OrderXml, BackendServiceOrders.Open, BackendServiceOrders.Active, BackendServiceOrders.StartedDateTime, BackendServiceOrders.ClosedDateTime, " + // 5-9 + " BackendServiceOrders.ExceptionText " + // 10 + " FROM BackendServiceOrders JOIN BackendServiceClasses ON (BackendServiceOrders.BackendServiceClassId=BackendServiceClasses.BackendServiceClassId) "; + + private static BasicBackendServiceOrder ReadBackendServiceOrderFromDataReader(IDataRecord reader) + { + int backendServiceOrderId = reader.GetInt32(0); + DateTime createdDateTime = reader.GetDateTime(1); + int organizationId = reader.GetInt32(2); + int personId = reader.GetInt32(3); + string backendServiceClassName = reader.GetString(4); + + string orderXml = reader.GetString(5); + bool open = reader.GetBoolean(6); + bool active = reader.GetBoolean(7); + DateTime startedDateTime = reader.GetDateTime(8); + DateTime closedDateTime = reader.GetDateTime(9); + + string exceptionText = reader.GetString(10); + + return new BasicBackendServiceOrder(backendServiceOrderId, organizationId, personId, backendServiceClassName, + orderXml, open, active, createdDateTime, startedDateTime, closedDateTime, exceptionText); + } + + #endregion + + #region Record reading - SELECT statements + + public BasicBackendServiceOrder GetBackendServiceOrder(int currencyId) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT " + backendServiceOrderFieldSequence + " WHERE BackendServiceOrderId=" + currencyId + ";", connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + return ReadBackendServiceOrderFromDataReader(reader); + } + + throw new ArgumentException("Unknown Backend Service Order Id: " + currencyId); + } + } + } + + + public BasicBackendServiceOrder[] GetBackendServiceOrders(params object[] conditions) + { + return GetBackendServiceOrderBatch(10000, conditions); // 10k is an arbitrary "everything" + } + + public BasicBackendServiceOrder[] GetBackendServiceOrderBatch(int batchMaxSize, params object[] conditions) + { + List result = new List(); + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( // this ORDERBY + LIMIT gets the oldest first in a FIFO queue + "SELECT " + backendServiceOrderFieldSequence + ConstructWhereClause("BackendServiceOrders", conditions) + " ORDER BY BackendServiceOrderId LIMIT " + batchMaxSize.ToString(CultureInfo.InvariantCulture), connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(ReadBackendServiceOrderFromDataReader(reader)); + } + + return result.ToArray(); + } + } + } + + #endregion + + + #region Creation and manipulation - stored procedures + + public int CreateBackendServiceOrder(string backendServiceClassName, string orderXml, int organizationId = 0, int personId = 0) + { + DateTime now = DateTime.UtcNow; + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("CreateBackendServiceOrder", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "dateTime", now); + AddParameterWithName(command, "backendServiceClassName", backendServiceClassName); + AddParameterWithName(command, "orderXml", orderXml); + AddParameterWithName(command, "organizationId", organizationId); + AddParameterWithName(command, "personId", personId); + + + return Convert.ToInt32(command.ExecuteScalar()); + } + } + + public void SetBackendServiceOrderActive(int backendServiceOrderId) + { + DateTime now = DateTime.UtcNow; + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetBackendServiceOrderActive", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "backendServiceOrderId", backendServiceOrderId); + AddParameterWithName(command, "dateTime", now); + + if (Convert.ToInt32(command.ExecuteScalar()) != 1) // returns count of rows updated + { + throw new DatabaseConcurrencyException(); + } + } + } + + public void SetBackendServiceOrderClosed(int backendServiceOrderId) + { + DateTime now = DateTime.UtcNow; + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetBackendServiceOrderClosed", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "backendServiceOrderId", backendServiceOrderId); + AddParameterWithName(command, "dateTime", now); + + if (Convert.ToInt32(command.ExecuteScalar()) != 1) // returns count of rows updated + { + throw new DatabaseConcurrencyException(); + } + } + } + + + public void SetBackendServiceOrderException (int backendServiceOrderId, Exception exception) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetBackendServiceOrderExceptionText", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "backendServiceOrderId", backendServiceOrderId); + AddParameterWithName(command, "exceptionText", exception.ToString()); + + command.ExecuteNonQuery(); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Database/Database-HotBitcoinAddresses.cs b/Database/Database-HotBitcoinAddresses.cs index 55681d0e..0a7ad391 100644 --- a/Database/Database-HotBitcoinAddresses.cs +++ b/Database/Database-HotBitcoinAddresses.cs @@ -255,6 +255,22 @@ namespace Swarmops.Database } + public void UpdateHotBitcoinAddressUnspentTotal(int hotBitcoinAddressId) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + using (DbCommand command = GetDbCommand("UpdateHotBitcoinAddressUnspentTotal", connection)) + { + command.CommandType = CommandType.StoredProcedure; + AddParameterWithName(command, "hotBitcoinAddressId", hotBitcoinAddressId); + + command.ExecuteNonQuery(); + } + } + } + public void UpdateHotBitcoinAddressUnspentTotals() { using (DbConnection connection = GetMySqlDbConnection()) diff --git a/Database/Database.csproj b/Database/Database.csproj index f6d601ca..c8916333 100644 --- a/Database/Database.csproj +++ b/Database/Database.csproj @@ -59,6 +59,7 @@ + diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index 74f9456a..cb2c9384 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -55,4 +55,5 @@ 0055 - Fix for bug introduced with 0054, hash collisions in index [RF] 0056 - Splitting a storedproc into two; debugging a weird multi-row select return [RF] 0057 - Bugfix for 0056: case insensitivity caused always-true comparison w/o qualifier [RF] -0058 - Fixing the other half of 0056 +0058 - Fixing the other half of 0056 [RF] +0059 - Added BackendServiceOrders, quite a bit of code too, for returning echo UTXOs from backend [RF] \ No newline at end of file diff --git a/Database/Schemata/upgrade-0059.sql b/Database/Schemata/upgrade-0059.sql new file mode 100644 index 00000000..00f10f2e --- /dev/null +++ b/Database/Schemata/upgrade-0059.sql @@ -0,0 +1,160 @@ +CREATE TABLE `BackendServiceOrders` ( + `BackendServiceOrderId` INT NOT NULL, + `CreatedDateTime` INT NOT NULL, + `OrganizationId` INT NOT NULL, + `PersonId` INT NOT NULL, + `BackendServiceClassId` INT NOT NULL, + `OrderXml` TEXT NOT NULL, + `Open` TINYINT NOT NULL DEFAULT 1, + `Active` TINYINT NOT NULL DEFAULT 0, + `StartedDateTime` DATETIME NOT NULL DEFAULT '1800-01-01', + `ClosedDateTime` DATETIME NOT NULL DEFAULT '1800-01-01', + `ExceptionText` TEXT NOT NULL DEFAULT '', + PRIMARY KEY (`BackendServiceOrderId`), + INDEX `Ix_Created` (`CreatedDateTime` ASC), + INDEX `Ix_Organization` (`OrganizationId` ASC), + INDEX `Ix_Person` (`PersonId` ASC), + INDEX `Ix_Active` (`Active` ASC), + INDEX `Ix_Open` (`Open` ASC)) + + +# + + +CREATE TABLE `BackendServiceClasses` ( + `BackendServiceClassId` INT NOT NULL, + `Name` VARCHAR(128) NOT NULL, + PRIMARY KEY (`BackendServiceClassId`), + INDEX `Ix_Name` (`Name` ASC)) + + +# + + +DROP PROCEDURE IF EXISTS `CreateBackendServiceOrder` + + +# + + +DROP PROCEDURE IF EXISTS `SetBackendServiceOrderActive` + + +# + + +DROP PROCEDURE IF EXISTS `SetBackendServiceOrderClosed` + + +# + + +DROP PROCEDURE IF EXISTS `SetBackendServiceOrderExceptionText` + + +# + + +CREATE PROCEDURE `CreateBackendServiceOrder`( + IN dateTime DATETIME, + IN organizationId INT, + IN personId INT, + IN backendServiceClassName VARCHAR(128), + IN orderXml TEXT +) +BEGIN + + DECLARE backendServiceClassId INTEGER; + + IF ((SELECT COUNT(*) FROM BackendServiceClasses WHERE BackendServiceClasses.Name=backendServiceClassName) = 0) + THEN + + INSERT INTO BackendServiceClasses + (Name) + VALUES + (backendServiceClassName); + + SELECT LAST_INSERT_ID() INTO backendServiceClassId; + + ELSE + + SELECT BackendServiceClasses.BackendServiceClassId INTO backendServiceClassId + FROM BackendServiceClasses + WHERE WHERE BackendServiceClasses.Name=backendServiceClassName; + + END IF; + + INSERT INTO BackendServiceOrders + (CreatedDateTime, OrganizationId, PersonId, BackendServiceClassId, OrderXml) + VALUES + (dateTime, organizationId, personId, backendServiceClassId, orderXml); + + SELECT LAST_INSERT_ID() AS Identity; + + +# + + +CREATE PROCEDURE `SetBackendServiceOrderActive`( + IN backendServiceOrderId INTEGER, + IN dateTime DATETIME +) +BEGIN + + UPDATE BackendServiceOrders + SET + BackendServiceOrders.Active=1, + BackendServiceOrders.StartedDateTime=dateTime + WHERE + BackendServiceOrders.BackendServiceOrderId=backendServiceOrderId AND + BackendServiceOrders.Active=0; + + SELECT ROW_COUNT() AS RecordsUpdated; + +END + + +# + + +CREATE PROCEDURE `SetBackendServiceOrderClosed`( + IN backendServiceOrderId INTEGER, + IN dateTime DATETIME +) +BEGIN + + UPDATE BackendServiceOrders + SET + BackendServiceOrders.Active=0, + BackendServiceOrders.Open=0, + BackendServiceOrders.ClosedDateTime=dateTime + WHERE + BackendServiceOrders.BackendServiceOrderId=backendServiceOrderId AND + BackendServiceOrders.Open=1; + + SELECT ROW_COUNT() AS RecordsUpdated; + +END + + +# + + +CREATE PROCEDURE `SetBackendServiceOrderExceptionText`( + IN backendServiceOrderId INTEGER, + IN exceptionText TEXT +) +BEGIN + + UPDATE BackendServiceOrders + SET + BackendServiceOrders.ExceptionText=exceptionText, + BackendServiceOrders.Open=0, + BackendServiceOrders.Active=0 + WHERE + BackendServiceOrders.BackendServiceOrderId=backendServiceOrderId; + + SELECT ROW_COUNT() AS RecordsUpdated; + +END + diff --git a/Logic/Financial/BitcoinTransactionInput.cs b/Logic/Financial/BitcoinTransactionInput.cs index 4c1c0f91..f55012f8 100644 --- a/Logic/Financial/BitcoinTransactionInput.cs +++ b/Logic/Financial/BitcoinTransactionInput.cs @@ -52,6 +52,8 @@ namespace Swarmops.Logic.Financial { get { + Console.WriteLine("WTF"); + List coinList = new List(); foreach (BitcoinTransactionInput input in this) diff --git a/Logic/Financial/BitcoinUtility.cs b/Logic/Financial/BitcoinUtility.cs index 5bd93bb1..d63deb1e 100644 --- a/Logic/Financial/BitcoinUtility.cs +++ b/Logic/Financial/BitcoinUtility.cs @@ -29,6 +29,14 @@ namespace Swarmops.Logic.Financial { public class BitcoinUtility { + static BitcoinUtility() + { + // Necessary applicatin-wide initialization + + NBitcoin.RandomUtils.Random = new NBitcoinSecureRandomizer(); + } + + public static void VerifyBitcoinHotWallet() { // This must only be run from the backend @@ -44,15 +52,15 @@ namespace Swarmops.Logic.Financial { ExtKey privateRoot = new ExtKey(); File.WriteAllText (SystemSettings.EtcFolder + Path.DirectorySeparatorChar + "hotwallet", - privateRoot.GetWif (Network.Core).ToWif(), Encoding.ASCII); + privateRoot.GetWif (Network.Main).ToWif(), Encoding.ASCII); File.WriteAllText ( SystemSettings.EtcFolder + Path.DirectorySeparatorChar + "hotwallet-created-" + DateTime.UtcNow.ToString ("yyyy-MM-dd--HH-mm-ss--fff.backup"), - privateRoot.GetWif (Network.Core).ToWif(), Encoding.ASCII); // an extra backup + privateRoot.GetWif (Network.Main).ToWif(), Encoding.ASCII); // an extra backup if (String.IsNullOrEmpty (Persistence.Key["BitcoinHotPublicRoot"])) { - Persistence.Key["BitcoinHotPublicRoot"] = privateRoot.Neuter().GetWif (Network.Core).ToWif(); + Persistence.Key["BitcoinHotPublicRoot"] = privateRoot.Neuter().GetWif (Network.Main).ToWif(); } } else @@ -64,7 +72,7 @@ namespace Swarmops.Logic.Financial // No, it has disappeared, which can happen for a few bad reasons Persistence.Key["BitcoinHotPublicRoot"] = - BitcoinHotPrivateRoot.Neuter().GetWif (Network.Core).ToWif(); + BitcoinHotPrivateRoot.Neuter().GetWif (Network.Main).ToWif(); if (!PilotInstallationIds.IsPilot (PilotInstallationIds.DevelopmentSandbox)) { // TODO: Log some sort of exception (the sandbox db is reset every night, so it's ok to lose the public key from there) @@ -75,14 +83,14 @@ namespace Swarmops.Logic.Financial // ReSharper disable once RedundantCheckBeforeAssignment if (Persistence.Key["BitcoinHotPublicRoot"] != - BitcoinHotPrivateRoot.Neuter().GetWif (Network.Core).ToWif() && !Debugger.IsAttached) + BitcoinHotPrivateRoot.Neuter().GetWif (Network.Main).ToWif() && !Debugger.IsAttached) { // SERIOUS CONDITION - the public root key did not match the private root key. This needs to be logged somewhere. OutboundComm.CreateNotification (NotificationResource.System_PublicRootReset); // Reset it Persistence.Key["BitcoinHotPublicRoot"] = - BitcoinHotPrivateRoot.Neuter().GetWif (Network.Core).ToWif(); + BitcoinHotPrivateRoot.Neuter().GetWif (Network.Main).ToWif(); } } } @@ -91,6 +99,15 @@ namespace Swarmops.Logic.Financial { get { + if (Debugger.IsAttached) + { + // REPLACE BELOW WITH YOUR FAVORITE PRIVATE KEY FOR DEBUGGING + + return + ExtKey.Parse( + "Replace this with your own favorite secret root key for debugging, and remember to never commit it to Github :)"); + } + return ExtKey.Parse (File.ReadAllText (SystemSettings.EtcFolder + Path.DirectorySeparatorChar + "hotwallet")); // will throw if hotwallet file does not exist - intentional @@ -102,15 +119,15 @@ namespace Swarmops.Logic.Financial get { return ExtPubKey.Parse ((string) Persistence.Key["BitcoinHotPublicRoot"]); } } - public static string[] GetInputAddressesForTransaction (Network network, string txHash) + public static string[] GetInputAddressesForTransaction (BitcoinChain chain, string txHash) { List inputAddresses = new List(); JObject jsonResult = new JObject(); - switch (network.Identity) + switch (chain) { - case NetworkIdentity.Core: + case BitcoinChain.Core: jsonResult = JObject.Parse( new WebClient().DownloadString("https://blockchain.info/rawtx/" + txHash + "?format=json&api_key=" + @@ -122,7 +139,7 @@ namespace Swarmops.Logic.Financial break; - case NetworkIdentity.Cash: + case BitcoinChain.Cash: jsonResult = JObject.Parse( new WebClient().DownloadString("https://bitcoincash.blockexplorer.com/api/tx/" + txHash)); @@ -133,7 +150,7 @@ namespace Swarmops.Logic.Financial break; default: - throw new NotImplementedException("Unimplemented chain, no Explorer: " + network.Identity); + throw new NotImplementedException("Unimplemented chain, no Explorer: " + chain); } @@ -141,18 +158,18 @@ namespace Swarmops.Logic.Financial } - public static Coin[] GetSpendableCoin (Network network, BitcoinSecret secretKey) + public static Coin[] GetSpendableCoin (BitcoinChain chain, BitcoinSecret secretKey) // we're using BitcoinSecret as arg just to reinforce caller must have privkey to spend funds { List coinList = new List(); - switch (network.Identity) + switch (chain) { - case NetworkIdentity.Core: + case BitcoinChain.Core: // For the Core net, we query the Blockchain API for the unspent coin. - string addressString = secretKey.PubKey.GetAddress(network).ToString(); + string addressString = secretKey.PubKey.GetAddress(Network.Main).ToString(); var unspentJsonResult = JObject.Parse( new WebClient().DownloadString("https://blockchain.info/unspent?active=" + addressString + @@ -175,14 +192,14 @@ namespace Swarmops.Logic.Financial break; - case NetworkIdentity.Cash: + case BitcoinChain.Cash: JArray unspentArray; // TODO: SELECT BLOCK EXPLORER AND ITS ACCOMPANYING ADDRESS FORMAT unspentArray = JArray.Parse( - new WebClient().DownloadString("https://bitcoincash.blockexplorer.com/api/addr/" + secretKey.PubKey.GetAddress(Network.Core) + "/utxo")); + new WebClient().DownloadString("https://bitcoincash.blockexplorer.com/api/addr/" + secretKey.PubKey.GetAddress(Network.Main) + "/utxo")); foreach (JObject unspentJson in unspentArray.Children()) { @@ -190,7 +207,7 @@ namespace Swarmops.Logic.Financial BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput() { - BitcoinAddress = secretKey.PubKey.GetAddress(network).ToString(), + BitcoinAddress = secretKey.PubKey.GetAddress(Network.Main).ToString(), ConfirmationCount = (UInt32)unspentJson["confirmations"], Satoshis = (UInt64)unspentJson["satoshis"], TransactionHash = (string)unspentJson["txid"], @@ -204,7 +221,7 @@ namespace Swarmops.Logic.Financial break; default: - throw new NotImplementedException("Unimplemented network identity: " + network.Identity); + throw new NotImplementedException("Unimplemented chain identity: " + chain); } return coinList.ToArray(); @@ -217,20 +234,6 @@ namespace Swarmops.Logic.Financial - public static BitcoinChain GetChainFromNetwork(Network network) - { - switch (network.Identity) - { - case NetworkIdentity.Cash: - return BitcoinChain.Cash; - case NetworkIdentity.Core: - return BitcoinChain.Core; - default: - throw new NotImplementedException("Unknown network identity: " + network.Identity); - } - } - - public static bool TestUnspents(BitcoinChain chain, string address) { // This function queries the Blockchain API for the unspent coin. @@ -324,6 +327,10 @@ namespace Swarmops.Logic.Financial (int)txUnspent.ConfirmationCount); } + // Update hotaddress totals + + HotBitcoinAddresses.UpdateAllUnspentTotals(); + return result; @@ -413,6 +420,10 @@ namespace Swarmops.Logic.Financial (int)txUnspent.ConfirmationCount); } + // Update hotaddress totals + + HotBitcoinAddresses.UpdateAllUnspentTotals(); + return result; default: @@ -422,16 +433,33 @@ namespace Swarmops.Logic.Financial } - public static void BroadcastTransaction (Transaction transaction) + public static void BroadcastTransaction (Transaction transaction, BitcoinChain chain) { using (WebClient client = new WebClient()) { - byte[] response = client.UploadValues ("https://blockchain.info/pushtx?cors=true", - new NameValueCollection() - { - {"tx", transaction.ToHex()} - }); + switch (chain) + { + case BitcoinChain.Core: + client.UploadValues("https://blockchain.info/pushtx?cors=true", + new NameValueCollection() + { + {"tx", transaction.ToHex()} + }); + break; // no txid given + + case BitcoinChain.Cash: + + byte[] response = client.UploadValues("https://bitcoincash.blockexplorer.com/api/tx/send", + new NameValueCollection() + { + {"rawtx", transaction.ToHex()} + }); + break; + + default: + throw new NotImplementedException("Unknown chain: " + chain); + } // TODO: Exception handling } } @@ -757,6 +785,9 @@ namespace Swarmops.Logic.Financial public const int BitcoinDonationsIndex = 2; public const int BitcoinLoansIndex = 3; public const int BitcoinAccountsReceivableIndex = 4; + public const int BitcoinEchoTestIndex = 127; + + public const int EchoFeeSatoshis = 300; // can change to property if needed public const string BitcoinTestAddress = "1JMpU3D6c5sruunMwzkt6p6PQzLcUYcL26"; @@ -765,7 +796,7 @@ namespace Swarmops.Logic.Financial { try { - BitcoinAddress singleAddress = new BitcoinPubKeyAddress (address, Network.Core); + BitcoinAddress singleAddress = new BitcoinPubKeyAddress (address, Network.Main); return true; } // ReSharper disable once EmptyGeneralCatchClause @@ -776,7 +807,7 @@ namespace Swarmops.Logic.Financial try { - BitcoinScriptAddress multiSigAddress = new BitcoinScriptAddress (address, Network.Core); + BitcoinScriptAddress multiSigAddress = new BitcoinScriptAddress (address, Network.Main); return true; } // ReSharper disable once EmptyGeneralCatchClause @@ -788,25 +819,25 @@ namespace Swarmops.Logic.Financial } - public static Int64 GetRecommendedFeePerThousandBytesSatoshis (Network network, int blocksWait = 2) + public static Int64 GetRecommendedFeePerThousandBytesSatoshis (BitcoinChain chain, int blocksWait = 2) { if (_lastFeeRefreshLookup == null) { - _lastFeeRefreshLookup = new Dictionary(); - _lastFeeSatoshisLookup = new Dictionary(); + _lastFeeRefreshLookup = new Dictionary(); + _lastFeeSatoshisLookup = new Dictionary(); } DateTime utcNow = DateTime.UtcNow; - if (_lastFeeRefreshLookup.ContainsKey(network.Identity) && utcNow < _lastFeeRefreshLookup[network.Identity].AddHours (3)) + if (_lastFeeRefreshLookup.ContainsKey(chain) && utcNow < _lastFeeRefreshLookup[chain].AddHours (3)) { - return _lastFeeSatoshisLookup[network.Identity]; // cache fee estimate for three hours + return _lastFeeSatoshisLookup[chain]; // cache fee estimate for three hours } try { Int64 satoshisPerThousandBytes = 1010; // default for Bitcoin Cash - if (network.Identity == NetworkIdentity.Core) + if (chain == BitcoinChain.Core) { // But Core has way way WAAAAAAY higher fees @@ -816,20 +847,20 @@ namespace Swarmops.Logic.Financial satoshisPerThousandBytes = (Int64)(feeWholeCoins * _satoshisPerBitcoin); } - _lastFeeSatoshisLookup[network.Identity] = satoshisPerThousandBytes; - _lastFeeRefreshLookup[network.Identity] = utcNow; + _lastFeeSatoshisLookup[chain] = satoshisPerThousandBytes; + _lastFeeRefreshLookup[chain] = utcNow; return satoshisPerThousandBytes; } catch (Exception) { // TODO: Check if _lastFeeRefresh is older than a day - if (_lastFeeSatoshisLookup.ContainsKey(network.Identity)) + if (_lastFeeSatoshisLookup.ContainsKey(chain)) { - return _lastFeeSatoshisLookup[network.Identity]; + return _lastFeeSatoshisLookup[chain]; } - if (network.Identity == NetworkIdentity.Cash) + if (chain == BitcoinChain.Cash) { return 1012; // a low standard: one sat per byte, plus some random extra } @@ -838,29 +869,12 @@ namespace Swarmops.Logic.Financial } } - private static Dictionary _lastFeeRefreshLookup; - private static Dictionary _lastFeeSatoshisLookup; + private static Dictionary _lastFeeRefreshLookup; + private static Dictionary _lastFeeSatoshisLookup; private const Int64 _satoshisPerBitcoin = 100 * 1000 * 1000; // written this way to improve readability - important constants - /// - /// Translates the Swarmops BitcoinChain enum to the NBitcoin Network class. - /// - /// The BitcoinChain to translate. - /// The corresponding NBitcoin.Network. - public static Network GetNetworkFromChain(BitcoinChain chain) - { - switch (chain) - { - case BitcoinChain.Core: - return Network.Core; - case BitcoinChain.Cash: - return Network.Cash; - default: - throw new NotImplementedException("Unimplemented BitcoinChain: " + chain); - } - } public static Currency GetCurrencyFromChain(BitcoinChain chain) { @@ -896,7 +910,7 @@ namespace Swarmops.Logic.Financial TransactionBuilder txBuilder = null; // TODO TODO TODO TODO new TransactionBuilder(); Int64 satoshis = new Money(100, Currency.FromCode ("SEK")).ToCurrency (Currency.BitcoinCore).Cents; BitcoinTransactionInputs inputs = null; - Int64 satoshisMaximumAnticipatedFees = BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(Network.Cash) * 20; // assume max 20k transaction size + Int64 satoshisMaximumAnticipatedFees = BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinChain.Cash) * 20; // assume max 20k transaction size try { @@ -930,7 +944,7 @@ namespace Swarmops.Logic.Financial } else if (bitcoinTestAddress.StartsWith("3")) // multisig { - txBuilder = txBuilder.Send(new BitcoinScriptAddress(bitcoinTestAddress, Network.Cash), + txBuilder = txBuilder.Send(new BitcoinScriptAddress(bitcoinTestAddress, Network.Main), new Satoshis(satoshis)); } else @@ -949,7 +963,7 @@ namespace Swarmops.Logic.Financial // +inputs.Count for size variability Int64 feeSatoshis = (transactionSizeBytes/1000 + 1)* - BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinUtility.GetNetworkFromChain(BitcoinChain.Cash)); + BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinChain.Cash); txBuilder = txBuilder.SendFees(new Satoshis(feeSatoshis)); satoshisUsed += feeSatoshis; @@ -975,7 +989,7 @@ namespace Swarmops.Logic.Financial // Broadcast transaction - BitcoinUtility.BroadcastTransaction(txReady); + BitcoinUtility.BroadcastTransaction(txReady, BitcoinChain.Cash); // Note the transaction hash @@ -1019,7 +1033,17 @@ namespace Swarmops.Logic.Financial N = source.TransactionOutputIndex }, new TxOut (new NBitcoin.Money (source.Satoshis), - new BitcoinPubKeyAddress (source.BitcoinAddress, Network.Core))); + new BitcoinPubKeyAddress (source.BitcoinAddress, Network.Main))); + } + } + + public class NBitcoinSecureRandomizer: NBitcoin.IRandom + { + public void GetBytes(byte[] buffer) + { + int byteCount = buffer.Length; + byte[] randomBuffer = SupportFunctions.GenerateSecureRandomBytes(byteCount); + Array.Copy(randomBuffer, buffer, byteCount); } } } diff --git a/Logic/Financial/HotBitcoinAddress.cs b/Logic/Financial/HotBitcoinAddress.cs index 1e853c1b..37b28a9c 100644 --- a/Logic/Financial/HotBitcoinAddress.cs +++ b/Logic/Financial/HotBitcoinAddress.cs @@ -63,8 +63,8 @@ namespace Swarmops.Logic.Financial } derivationPathString = derivationPathString.TrimStart(); - string bitcoinAddress = extPubKey.PubKey.GetAddress (Network.Core).ToString(); // TODO: CHANGE NETWORK.MAIN TO NEW LOOKUP - string bitcoinAddressFallback = extPubKey.PubKey.GetAddress(Network.Core).ToString(); // The fallback address would be the main address + string bitcoinAddress = extPubKey.PubKey.GetAddress (Network.Main).ToString(); // TODO: CHANGE NETWORK.MAIN TO NEW LOOKUP + string bitcoinAddressFallback = extPubKey.PubKey.GetAddress(Network.Main).ToString(); // The fallback address would be the main address int hotBitcoinAddressId = SwarmDb.GetDatabaseForWriting() @@ -113,7 +113,7 @@ namespace Swarmops.Logic.Financial secretExtKey = secretExtKey.Derive (UInt32.Parse (derivationString)); } - return secretExtKey.PrivateKey.GetBitcoinSecret (Network.Core); + return secretExtKey.PrivateKey.GetBitcoinSecret (Network.Main); } } @@ -150,5 +150,10 @@ namespace Swarmops.Logic.Financial return result.ToArray(); } } + + public void UpdateTotal() + { + SwarmDb.GetDatabaseForWriting().UpdateHotBitcoinAddressUnspentTotal(this.Identity); + } } } diff --git a/Logic/Financial/HotBitcoinAddressUnspent.cs b/Logic/Financial/HotBitcoinAddressUnspent.cs index 4e6a2375..77fd28b0 100644 --- a/Logic/Financial/HotBitcoinAddressUnspent.cs +++ b/Logic/Financial/HotBitcoinAddressUnspent.cs @@ -41,7 +41,12 @@ namespace Swarmops.Logic.Financial HotBitcoinAddressUnspentId = this.Identity }; } - } + } + + public BitcoinTransactionInputs AsInputs + { + get { return BitcoinTransactionInputs.FromSingle(AsInput); } + } public HotBitcoinAddress Address { diff --git a/Logic/Financial/HotBitcoinAddresses.cs b/Logic/Financial/HotBitcoinAddresses.cs index 51aa78b9..2207bd53 100644 --- a/Logic/Financial/HotBitcoinAddresses.cs +++ b/Logic/Financial/HotBitcoinAddresses.cs @@ -88,5 +88,10 @@ namespace Swarmops.Logic.Financial return unspents; } } + + public static void UpdateAllUnspentTotals() + { + SwarmDb.GetDatabaseForWriting().UpdateHotBitcoinAddressUnspentTotals(); + } } } diff --git a/Logic/Financial/Payouts.cs b/Logic/Financial/Payouts.cs index dd40717e..72ca5e30 100644 --- a/Logic/Financial/Payouts.cs +++ b/Logic/Financial/Payouts.cs @@ -592,7 +592,7 @@ namespace Swarmops.Logic.Financial // We now have our desired payments. The next step is to find enough inputs to reach the required amount (plus fees; we're working a little blind here still). BitcoinTransactionInputs inputs = null; - Int64 satoshisMaximumAnticipatedFees = BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinUtility.GetNetworkFromChain(chain)) * 20; // assume max 20k transaction size + Int64 satoshisMaximumAnticipatedFees = BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(chain) * 20; // assume max 20k transaction size try { @@ -676,7 +676,7 @@ namespace Swarmops.Logic.Financial } else if (payout.RecipientPerson.BitcoinPayoutAddress.StartsWith ("3")) // multisig { - txBuilder = txBuilder.Send(new BitcoinScriptAddress(payout.RecipientPerson.BitcoinPayoutAddress, Network.Core), + txBuilder = txBuilder.Send(new BitcoinScriptAddress(payout.RecipientPerson.BitcoinPayoutAddress, Network.Main), new Satoshis(satoshiPayoutLookup[payout.ProtoIdentity])); } else @@ -698,7 +698,7 @@ namespace Swarmops.Logic.Financial int transactionSizeBytes = txBuilder.EstimateSize (txBuilder.BuildTransaction (false)) + inputs.Count; // +inputs.Count for size variability - Int64 feeSatoshis = (transactionSizeBytes/1000 + 1) * BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinUtility.GetNetworkFromChain(chain)); + Int64 feeSatoshis = (transactionSizeBytes/1000 + 1) * BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(chain); txBuilder = txBuilder.SendFees (new Satoshis (feeSatoshis)); satoshisUsed += feeSatoshis; @@ -724,7 +724,7 @@ namespace Swarmops.Logic.Financial // Broadcast transaction - BitcoinUtility.BroadcastTransaction (txReady); + BitcoinUtility.BroadcastTransaction (txReady, BitcoinChain.Cash); // Note the transaction hash diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index 49f3665d..14a3f9e5 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -85,8 +85,9 @@ ..\packages\MySql.Data.6.9.9\lib\net45\MySql.Data.dll True - - ..\External Libraries\NBitcoinDual.dll + + ..\packages\NBitcoinBCC.1.0.16\lib\netstandard1.1\NBitcoinBCC.dll + True ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll @@ -105,14 +106,22 @@ True + + + + + ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll + True + + ..\packages\WebSocketSharp.1.0.3-rc11\lib\websocket-sharp.dll True @@ -208,9 +217,14 @@ + + + + + diff --git a/Logic/Support/BackendServiceOrder.cs b/Logic/Support/BackendServiceOrder.cs new file mode 100644 index 00000000..8085bced --- /dev/null +++ b/Logic/Support/BackendServiceOrder.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Basic.Types.System; +using Swarmops.Common.Exceptions; +using Swarmops.Database; +using Swarmops.Logic.Support.BackendServices; + +namespace Swarmops.Logic.Support +{ + public class BackendServiceOrder: BasicBackendServiceOrder + { + private BackendServiceOrder(BasicBackendServiceOrder basic): base (basic) + { + // private ctor prevents involuntary construction + } + + public static BackendServiceOrder FromBasic(BasicBackendServiceOrder basic) + { + return new BackendServiceOrder(basic); + } + + public static BackendServiceOrder FromIdentity(int backendServiceOrderId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetBackendServiceOrder(backendServiceOrderId)); + } + + + public void Execute() + { + // Instantiate the class + + string[] components = BackendServiceClassName.Split(','); + string assemblyName = components[0]; + string className = components[1]; + + Assembly assembly = Assembly.GetExecutingAssembly(); // TODO: Make this actually select the named assembly + + Type serviceClassType = assembly.GetType(className); + + if (serviceClassType == null) + { + SwarmDb.GetDatabaseForWriting().SetBackendServiceOrderException(this.Identity, new ArgumentNullException("ClassName", "Class failed to instantiate -- service engine is null: " + className)); + return; + } + + MethodInfo methodFromXml = serviceClassType.GetMethod("FromXml", BindingFlags.FlattenHierarchy | BindingFlags.Static); + + if (methodFromXml == null) + { + SwarmDb.GetDatabaseForWriting().SetBackendServiceOrderException(this.Identity, new ArgumentNullException("MethodName", "Class failed to instantiate -- method search returned null")); + return; + } + + IBackendServiceOrderBase order = (IBackendServiceOrderBase) methodFromXml.Invoke(null, new object[] { this.OrderXml }); + + // Mark as started + + SwarmDb.GetDatabaseForWriting().SetBackendServiceOrderActive(this.Identity); + + // Run the Run() function + + try + { + order.Run(); + } + catch (Exception exception) + { + order.Close(); + SwarmDb.GetDatabaseForWriting().SetBackendServiceOrderException(this.Identity, exception); + } + finally + { + if (!order.HasWorkerThread) + { + try + { + order.Close(); + } + catch (ConcurrencyException) + { + // Ignore if we try to close it twice in this particular failure scenario + } + } + } + + + // Mark as closed, if it has not marked itself as forked and still working + // TODO (in which case, do something else -- add to a list of still working tasks.) + } + } +} diff --git a/Logic/Support/BackendServiceOrders.cs b/Logic/Support/BackendServiceOrders.cs new file mode 100644 index 00000000..04c76afa --- /dev/null +++ b/Logic/Support/BackendServiceOrders.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Basic.Types.System; +using Swarmops.Database; + +namespace Swarmops.Logic.Support +{ + public class BackendServiceOrders:PluralBase + { + public static BackendServiceOrders GetNextBatch(int batchSize) + { + return + FromArray(SwarmDb.GetDatabaseForReading() + .GetBackendServiceOrderBatch(batchSize, DatabaseCondition.ActiveFalse, DatabaseCondition.OpenTrue)); + } + + public void Execute() + { + foreach (BackendServiceOrder order in this) + { + order.Execute(); + } + } + } +} diff --git a/Logic/Support/BackendServices/BackendServiceOrderBase.cs b/Logic/Support/BackendServices/BackendServiceOrderBase.cs new file mode 100644 index 00000000..10110a2f --- /dev/null +++ b/Logic/Support/BackendServices/BackendServiceOrderBase.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Xml.Serialization; +using Swarmops.Common.Interfaces; +using Swarmops.Database; +using Swarmops.Logic.Structure; +using Swarmops.Logic.Swarm; + + +namespace Swarmops.Logic.Support.BackendServices +{ + // This is the roughly the same base code as the LogEntryBase, plus some more processing things + + [Serializable] + public abstract class BackendServiceOrderBase : IXmlPayload, IBackendServiceOrderBase + { + public virtual string ToXml() + { + XmlSerializer serializer = new XmlSerializer(GetType()); + + MemoryStream stream = new MemoryStream(); + serializer.Serialize(stream, this); + + byte[] xmlBytes = stream.GetBuffer(); + string xml = Encoding.UTF8.GetString(xmlBytes); + + xml = xml.Replace("�", ""); + xml = xml.Replace("\x00", ""); + + return xml; + } + + public static T FromXml(string xml) // 'T' might not work here, like it didn't in ToXml() + { + // Compensate for stupid Mono encoding bugs + + if (xml.StartsWith("?")) + { + xml = xml.Substring(1); + } + + xml = xml.Replace("�", ""); + xml = xml.Replace("\x00", ""); + + XmlSerializer serializer = new XmlSerializer(typeof (T)); + + MemoryStream stream = new MemoryStream(); + byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); + stream.Write(xmlBytes, 0, xmlBytes.Length); + + stream.Position = 0; + T result = (T) serializer.Deserialize(stream); + stream.Close(); + + return result; + } + + /// + /// This function gets called by the backend for the class to carry out its mission. Override it to + /// fill it with purpose. You SHOULD return within 50 milliseconds. Start a new thread if you need + /// longer processing, and if so, set HasWorkerThread to true and point WorkerThread at your + /// thread (so it can be called to WaitForExit()). + /// + public virtual void Run() + { + throw new NotImplementedException("The base Run() has no implementation. Derive and override!"); + } + + /// + /// This function MUST be called when the task has been completed, either on completion of Run() + /// if you take a short amount of time, or at the end of your worker thread. + /// + public void Close() + { + SwarmDb.GetDatabaseForWriting().SetBackendServiceOrderClosed(this.ServiceOrderIdentity); + } + + /// + /// This creates the order and serializes it into the database for execution. + /// + public virtual void Create(Organization organization = null, Person person = null) + { + string executingAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; + string className = this.GetType().FullName; + string serviceClassName = executingAssemblyName + "," + className; + + // Create the service order through reflection and XML serialization + + this.ServiceOrderIdentity = SwarmDb.GetDatabaseForWriting() + .CreateBackendServiceOrder(serviceClassName, this.ToXml(), + organization?.Identity ?? 0, person?.Identity ?? 0); + } + + public DateTime CreatedDateTime { get; set; } + public string BackendServiceClass { get; set; } + public int ServiceOrderIdentity { get; set; } + + [XmlIgnore] + public bool HasWorkerThread { get; set; } + [XmlIgnore] + public Thread WorkerThread { get; set; } + + } +} + diff --git a/Logic/Support/BackendServices/ReturnBitcoinEchoUtxoOrder.cs b/Logic/Support/BackendServices/ReturnBitcoinEchoUtxoOrder.cs new file mode 100644 index 00000000..b18afbdb --- /dev/null +++ b/Logic/Support/BackendServices/ReturnBitcoinEchoUtxoOrder.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using NBitcoin; +using Swarmops.Basic.Types.Financial; +using Swarmops.Common.Enums; +using Swarmops.Logic.Financial; +using Satoshis = NBitcoin.Money; + +namespace Swarmops.Logic.Support.BackendServices +{ + [Serializable] + public class ReturnBitcoinEchoUtxoOrder: BackendServiceOrderBase + { + public ReturnBitcoinEchoUtxoOrder(BasicHotBitcoinAddressUnspent utxo) + { + this.UtxoIdentity = utxo.Identity; + } + + public new void Run() + { + HotBitcoinAddressUnspent utxoToReturn = HotBitcoinAddressUnspent.FromIdentity(UtxoIdentity); + HotBitcoinAddress utxoAddress = utxoToReturn.Address; + BitcoinSecret secretKey = utxoAddress.PrivateKey; + + // TODO: Verify that the utxoAddress is an EchoTest address, i.e. has second path component == BitcoinUtility.BitcoinEchoTestIndex + + string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(BitcoinChain.Cash, utxoToReturn.TransactionHash)[0]; // assumes at least one input address -- not coinbase + + BitcoinTransactionInputs inputs = utxoToReturn.AsInputs; + + Coin[] coins = inputs.Coins; + ICoin[] iCoins = coins; + ISecret[] privateKeys = utxoToReturn.AsInputs.PrivateKeys; + + TransactionBuilder txBuilder = new TransactionBuilder(); + txBuilder = txBuilder.SendFees(new Satoshis(BitcoinUtility.EchoFeeSatoshis)); + txBuilder = txBuilder.AddCoins(iCoins); + txBuilder = txBuilder.AddKeys(privateKeys); + txBuilder = txBuilder.Send(new BitcoinPubKeyAddress(returnAddress), + new Satoshis(utxoToReturn.AmountSatoshis - BitcoinUtility.EchoFeeSatoshis)); + + Transaction tx = txBuilder.BuildTransaction(true, SigHash.ForkId | SigHash.All); + + BitcoinUtility.BroadcastTransaction(tx, BitcoinChain.Cash); + utxoToReturn.Delete(); + utxoAddress.UpdateTotal(); + } + + public int UtxoIdentity { get; set; } + } +} diff --git a/Logic/Support/General.cs b/Logic/Support/General.cs index d157ae34..1b46d582 100644 --- a/Logic/Support/General.cs +++ b/Logic/Support/General.cs @@ -25,13 +25,11 @@ namespace Swarmops.Logic.Support (sender, certificate, chain, sslPolicyErrors) => true; } - public static string GenerateSecureRandomKey(int bytelength) + public static string GenerateSecureRandomKey(int byteCount) { - byte[] buffer = new byte[bytelength]; - RNGCryptoServiceProvider devRandom = new RNGCryptoServiceProvider(); - devRandom.GetBytes(buffer); + byte[] buffer = GenerateSecureRandomBytes(byteCount); - StringBuilder result = new StringBuilder(bytelength * 2); + StringBuilder result = new StringBuilder(byteCount * 2); for (int loop = 0; loop < buffer.Length; loop++) { result.AppendFormat("{0:X2}", buffer[loop]); @@ -39,6 +37,15 @@ namespace Swarmops.Logic.Support return result.ToString(); } + public static byte[] GenerateSecureRandomBytes(int byteCount) + { + byte[] buffer = new byte[byteCount]; + RNGCryptoServiceProvider devRandom = new RNGCryptoServiceProvider(); + devRandom.GetBytes(buffer); + + return buffer; + } + // ReSharper disable once InconsistentNaming -- IPAddress is the canonical writing public static string GetRemoteIPAddressChain() { diff --git a/Logic/Support/IBackendServiceOrderBase.cs b/Logic/Support/IBackendServiceOrderBase.cs new file mode 100644 index 00000000..69a0d7a3 --- /dev/null +++ b/Logic/Support/IBackendServiceOrderBase.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Xml.Serialization; + +namespace Swarmops.Logic.Support +{ + public interface IBackendServiceOrderBase + { + void Run(); + void Close(); + bool HasWorkerThread { get; set; } + Thread WorkerThread { get; set; } + } +} diff --git a/Logic/packages.config b/Logic/packages.config index c36567d0..cfdd4c8e 100644 --- a/Logic/packages.config +++ b/Logic/packages.config @@ -5,11 +5,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Site/App_GlobalResources/Pages.Admin.designer.cs b/Site/App_GlobalResources/Pages.Admin.designer.cs index b9f9f555..f038d024 100644 --- a/Site/App_GlobalResources/Pages.Admin.designer.cs +++ b/Site/App_GlobalResources/Pages.Admin.designer.cs @@ -61,7 +61,7 @@ namespace Resources.Pages { } /// - /// Looks up a localized string similar to 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.. + /// Looks up a localized string similar to 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 Cash address). The amount (less miner fees) will be sent back to you in the next auto-payment cycle which runs every five minutes.. /// internal static string BitcoinEchoTest_Explain { get { @@ -97,7 +97,7 @@ namespace Resources.Pages { } /// - /// Looks up a localized string similar to Donate. + /// Looks up a localized string similar to Bitcoin Cash Echo Test. /// internal static string BitcoinEchoTest_PageTitle { get { diff --git a/Site/App_GlobalResources/Pages.Admin.resx b/Site/App_GlobalResources/Pages.Admin.resx index bfada28a..a8d81a58 100644 --- a/Site/App_GlobalResources/Pages.Admin.resx +++ b/Site/App_GlobalResources/Pages.Admin.resx @@ -118,7 +118,7 @@ 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. + 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 Cash 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. @@ -133,7 +133,7 @@ This is a bitcoin echo test. It tests the hotwallet. If you send a small amount here, it will be sent back to you, minus the sendback transaction fee. - Donate + Bitcoin Cash Echo Test Waiting for transaction... diff --git a/Site/Master-v5.master b/Site/Master-v5.master index 74fb4b37..7265db6e 100644 --- a/Site/Master-v5.master +++ b/Site/Master-v5.master @@ -224,15 +224,19 @@
+ <% if (!((this.Page as PageV5Base).SuppressStatisticHeaders)) + { %> +
-
<%= (CurrentOrganization.GetProfitLossCents() / 100.0 + 0.001).ToString(CultureInfo.InvariantCulture) %>
Profit To Date XYZ <%=DateTime.UtcNow.Year %>
+
<%= (CurrentOrganization.GetProfitLossCents()/100.0 + 0.001).ToString(CultureInfo.InvariantCulture) %>
Profit To Date XYZ <%= DateTime.UtcNow.Year %>
- <% if (!((this.Page as PageV5Base).IsDashboard || ((this.Page as PageV5Base).SuppressStatisticHeaders))) + <% } + if (!((this.Page as PageV5Base).IsDashboard || ((this.Page as PageV5Base).SuppressStatisticHeaders))) { %>
<% } %> diff --git a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx index b18d9d92..9b75f2a0 100644 --- a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx +++ b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx @@ -2,96 +2,123 @@ <%@ Import Namespace="Swarmops.Logic.Support" %> + + +
+
+
+
0.001
+
Received in echo test (<%=CurrentOrganization.Currency.DisplayCode %>)
+
+ +
+
+ + +

-

+

Bitcoin hotwallet is not enabled

Fail symbol
-

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

+

This organization has not enabled its bitcoin hotwallet in Swarmops. Therefore, echo tests are not available.

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

+
diff --git a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs index 8e3e963d..98db4711 100644 --- a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs +++ b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs @@ -10,6 +10,8 @@ using System.Web.UI.WebControls; using NBitcoin; using Swarmops.Common.Enums; using Swarmops.Logic.Cache; +using Swarmops.Logic.Communications; +using Swarmops.Logic.Communications.Payload; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; @@ -25,74 +27,56 @@ namespace Swarmops.Frontend.Pages.v5.Admin // 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); + this.SuppressStatisticHeaders = true; if (this.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot == null) { this.PanelDisabled.Visible = true; this.PanelEnabled.Visible = false; - this.LiteralEnable.Text = @"false"; } - HotBitcoinAddress address = HotBitcoinAddress.Create (this.CurrentOrganization, BitcoinChain.Cash, - BitcoinUtility.BitcoinDonationsIndex, this.CurrentUser.Identity); + HotBitcoinAddress address = HotBitcoinAddress.Create(this.CurrentOrganization, BitcoinChain.Cash, + BitcoinUtility.BitcoinEchoTestIndex, this.CurrentUser.Identity); - this.LiteralBitcoinAddress.Text = address.Address; - string guid = Guid.NewGuid().ToString ("N"); - GuidCache.Set (guid, address.Address); - this.LiteralGuid.Text = guid; + this.BitcoinCashAddressUsed = address.Address; + string guid = Guid.NewGuid().ToString("N"); + GuidCache.Set(guid, address.Address); + this.TransactionGuid = guid; - // TEST TEST TEST - /* - BitcoinSecret secretKey = address.PrivateKey; - Coin[] spendableCoin = BitcoinUtility.GetSpendableCoin (secretKey); + // Calculate conversion rate (satoshi-cents to unit-cents, so we're good, even if the conversion rate + // is calculated on microbitcoin to whole units) - 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); + this.ConversionRateSatoshisToCents = Currency.BitcoinCash.GetConversionRate(CurrentOrganization.Currency); - bool test = txBuild.Verify (tx); - if (!test) - { - throw new InvalidOperationException("Tx is not properly signed"); - } + // BEGIN TEST CODE - BitcoinUtility.BroadcastTransaction (tx);*/ + // END TEST CODE - this.BoxTitle.Text = Resources.Pages.Financial.Donate_PageTitle; - this.LabelExplainBitcoinDonation.Text = String.Format (Resources.Pages.Financial.Donate_Explain, + this.BoxTitle.Text = Resources.Pages.Admin.BitcoinEchoTest_PageTitle; + this.LabelExplainBitcoinEchoTest.Text = String.Format (Resources.Pages.Admin.BitcoinEchoTest_Explain, CurrentOrganization.Name, address.Address); this.ImageBitcoinQr.ImageUrl = "https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=bitcoincash:" + HttpUtility.UrlEncode (address.Address + "?label=" + - Uri.EscapeDataString (String.Format (Resources.Pages.Financial.Donate_TxLabel, - CurrentOrganization.Name))); // URI scheme doesn't like &, = + Uri.EscapeDataString ("Swarmops Bitcoin Echo Test")); // URI scheme doesn't like &, = } + + public static Int64 EchoFeeSatoshis + { + get { return BitcoinUtility.EchoFeeSatoshis; } + } + + public string BitcoinCashAddressUsed { get; private set; } + public string TransactionGuid { get; private set; } + public double ConversionRateSatoshisToCents { get; private set; } + [WebMethod] - static public AjaxCallResult CheckTransactionReceived (string guid, string txHash) + static public AjaxCallResult ProcessTransactionReceived (string guid, string txHash) { AuthenticationData authData = GetAuthenticationDataAndCulture(); // just to make sure we're called properly BitcoinChain chain = BitcoinChain.Cash; @@ -101,9 +85,6 @@ namespace Swarmops.Frontend.Pages.v5.Admin if (BitcoinUtility.TestUnspents (chain, bitcoinAddress)) { HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress (chain, bitcoinAddress).Unspents; - - // TODO: Update the HotBitcoinAddress with the new amount? - Int64 satoshisReceived = unspents.Last().AmountSatoshis; if (unspents.Last().TransactionHash != txHash && txHash.Length > 0) @@ -112,28 +93,96 @@ namespace Swarmops.Frontend.Pages.v5.Admin Debugger.Break(); } + HotBitcoinAddressUnspent utxoToReturn = unspents.Last(); + Swarmops.Logic.Financial.Money moneyReceived = new Swarmops.Logic.Financial.Money(satoshisReceived, - Currency.BitcoinCore); + Currency.BitcoinCash); // Make sure that the hotwallet native currency is bitcoin - authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot.ForeignCurrency = Currency.BitcoinCore; + authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot.ForeignCurrency = Currency.BitcoinCash; // Create success message and ledger transaction string successMessage = string.Empty; // TODO: Get the tx, get the input - string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(BitcoinUtility.GetNetworkFromChain(chain), txHash) [0]; // assumes at least one input address + string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(chain, txHash) [0]; // assumes at least one input address + + // Return the money, too. Set fee for a 300-byte transaction. + + TransactionBuilder txBuilder = new TransactionBuilder(); + txBuilder = txBuilder.SendFees(new Satoshis(EchoFeeSatoshis)); + txBuilder = txBuilder.AddCoins(utxoToReturn.AsInputs.Coins); + txBuilder = txBuilder.AddKeys(utxoToReturn.AsInputs.PrivateKeys); + + // change address equals return address, although it should be empty + + if (returnAddress.StartsWith("1")) // regular address + { + txBuilder = txBuilder.Send(new BitcoinPubKeyAddress(returnAddress), + new Satoshis(satoshisReceived - EchoFeeSatoshis)); + txBuilder.SetChange(new BitcoinPubKeyAddress(returnAddress)); + } + else if (returnAddress.StartsWith("3")) // multisig + { + txBuilder = txBuilder.Send(new BitcoinScriptAddress(returnAddress, Network.Main), + new Satoshis(satoshisReceived - EchoFeeSatoshis)); + txBuilder.SetChange(new BitcoinScriptAddress(returnAddress, Network.Main)); + } + + + + // Sign transaction - ready to execute + + Transaction txReady = txBuilder.BuildTransaction(true); + + // Verify that transaction is ready + + if (!txBuilder.Verify(txReady)) + { + // Transaction was not signed with the correct keys. This is a serious condition. + + NotificationStrings primaryStrings = new NotificationStrings(); + primaryStrings[NotificationString.OrganizationName] = authData.CurrentOrganization.Name; + + OutboundComm.CreateNotification(authData.CurrentOrganization, NotificationResource.Bitcoin_PrivateKeyError, + primaryStrings); + + throw new InvalidOperationException("Transaction is not signed enough"); + } + + // Broadcast transaction + + BitcoinUtility.BroadcastTransaction(txReady, BitcoinChain.Cash); + + // Note the transaction hash + + string returnTxHash = txReady.GetHash().ToString(); + + // Delete all old inputs, adjust balance for addresses (re-register unused inputs) + + utxoToReturn.Delete(); + HotBitcoinAddresses.UpdateAllUnspentTotals(); + + string tx1Description = "Bitcoin technical echo test (will be repaid immediately)"; + string tx2Description = "Bitcoin echo test repayment"; + if (authData.CurrentOrganization.Currency.IsBitcoinCash) { // The ledger is native bitcoin, so cent 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; + FinancialTransaction ledgerTx1 = FinancialTransaction.Create(authData.CurrentOrganization, + DateTime.UtcNow, tx1Description); + ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, -(satoshisReceived), authData.CurrentUser); + ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, satoshisReceived, authData.CurrentUser); + ledgerTx1.BlockchainHash = txHash; + + FinancialTransaction ledgerTx2 = FinancialTransaction.Create(authData.CurrentOrganization, + DateTime.UtcNow, tx2Description); + ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, satoshisReceived, authData.CurrentUser); + ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, -satoshisReceived, authData.CurrentUser); + ledgerTx2.BlockchainHash = returnTxHash; if (satoshisReceived % 100 == 0) { @@ -146,24 +195,30 @@ namespace Swarmops.Frontend.Pages.v5.Admin (satoshisReceived / 100.0).ToString("N2")); } - // TODO: Log the payout back, as an inbound invoice for immediate payout + // TODO: Second tx } 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).AmountForeignCents = new Swarmops.Logic.Financial.Money(satoshisReceived, Currency.BitcoinCash); - ledgerTx.BlockchainHash = txHash; + long orgNativeCents = moneyReceived.ToCurrency(authData.CurrentOrganization.Currency).Cents; + FinancialTransaction ledgerTx1 = FinancialTransaction.Create(authData.CurrentOrganization, + DateTime.UtcNow, tx1Description); + ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, -orgNativeCents, authData.CurrentUser); + ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, orgNativeCents, authData.CurrentUser).AmountForeignCents = new Swarmops.Logic.Financial.Money(satoshisReceived, Currency.BitcoinCash); + ledgerTx1.BlockchainHash = txHash; + + FinancialTransaction ledgerTx2 = FinancialTransaction.Create(authData.CurrentOrganization, + DateTime.UtcNow, tx2Description); + ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, orgNativeCents, authData.CurrentUser); + ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, -orgNativeCents, authData.CurrentUser).AmountForeignCents = new Swarmops.Logic.Financial.Money(-satoshisReceived, Currency.BitcoinCash); + ledgerTx2.BlockchainHash = returnTxHash; 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 cash -- as an inbound invoice + // TODO: Second tx } return new AjaxCallResult() {DisplayMessage = successMessage, Success = true}; @@ -174,5 +229,11 @@ namespace Swarmops.Frontend.Pages.v5.Admin return new AjaxCallResult() {Success = false}; } + + public string Localized_Verifying + { + get { return CommonV5.JavascriptEscape(Resources.Pages.Financial.Donate_TransactionDetected); } + } + } } \ No newline at end of file diff --git a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.designer.cs b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.designer.cs index b3d800ab..cd607863 100644 --- a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.designer.cs +++ b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.designer.cs @@ -12,42 +12,6 @@ namespace Swarmops.Frontend.Pages.v5.Admin { public partial class BitcoinEchoTest { - /// - /// LiteralTxDetected control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal LiteralTxDetected; - - /// - /// LiteralBitcoinAddress control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal LiteralBitcoinAddress; - - /// - /// LiteralGuid control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal LiteralGuid; - - /// - /// LiteralEnable control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal LiteralEnable; - /// /// PanelEnabled control. /// @@ -67,13 +31,13 @@ namespace Swarmops.Frontend.Pages.v5.Admin { protected global::System.Web.UI.WebControls.Label BoxTitle; /// - /// LabelExplainBitcoinDonation control. + /// LabelExplainBitcoinEchoTest control. /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// - protected global::System.Web.UI.WebControls.Label LabelExplainBitcoinDonation; + protected global::System.Web.UI.WebControls.Label LabelExplainBitcoinEchoTest; /// /// LabelStatus control. diff --git a/Site/Pages/v5/Financial/Donate.aspx b/Site/Pages/v5/Financial/Donate.aspx index d7a6a3d5..c3d200ad 100644 --- a/Site/Pages/v5/Financial/Donate.aspx +++ b/Site/Pages/v5/Financial/Donate.aspx @@ -28,8 +28,9 @@ if (outAddress == pageDonationAddress) { + $('#paraStatus').text(verifyingText); var donatedSatoshis = data.vout[index][outAddress]; - donatedFunds += (donatedSatoshis * conversionRateSatoshisToCents / 100.0); + donatedFunds += Math.floor((donatedSatoshis * conversionRateSatoshisToCents) / 100.0); odoDonatedCents.innerHTML = donatedFunds; // looks weird but $('#id') not used with odo var json = {}; @@ -94,6 +95,7 @@ var donatedFunds = 0.001; // the 0.1 cents are necessary for an odometer workaround var pageDonationAddress = SwarmopsJS.unescape('<%=this.BitcoinCashAddressUsed %>'); + var verifyingText = SwarmopsJS.unescape('<%=this.Localized_Verifying%>'); var guid = SwarmopsJS.unescape('<%=this.TransactionGuid%>'); var conversionRateSatoshisToCents = <%= this.ConversionRateSatoshisToCents %>; var completed = false; diff --git a/Site/Pages/v5/Financial/Donate.aspx.cs b/Site/Pages/v5/Financial/Donate.aspx.cs index 3be5e710..31fecb43 100644 --- a/Site/Pages/v5/Financial/Donate.aspx.cs +++ b/Site/Pages/v5/Financial/Donate.aspx.cs @@ -196,5 +196,13 @@ namespace Swarmops.Frontend.Pages.v5.Financial return new AjaxCallResult() {Success = false}; } + + + // -- Localizations below -- + + public string Localized_Verifying + { + get { return CommonV5.JavascriptEscape(Resources.Pages.Financial.Donate_TransactionDetected); } + } } } \ No newline at end of file diff --git a/Site/Site.csproj b/Site/Site.csproj index 18d227c5..8f60f94e 100644 --- a/Site/Site.csproj +++ b/Site/Site.csproj @@ -51,8 +51,9 @@ True - - ..\External Libraries\NBitcoinDual.dll + + ..\packages\NBitcoinBCC.1.0.16\lib\netstandard1.1\NBitcoinBCC.dll + True ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll @@ -66,6 +67,14 @@ ..\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll True + + + + + + ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll + True + diff --git a/Site/packages.config b/Site/packages.config index 8f0560c1..5e345036 100644 --- a/Site/packages.config +++ b/Site/packages.config @@ -2,8 +2,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file