Added BackendServiceOrders

This commit is contained in:
Rick Falkvinge
2017-11-22 18:49:08 +01:00
parent 8e07e6cf6a
commit c1be027f48
36 changed files with 1249 additions and 263 deletions
+12 -2
View File
@@ -63,16 +63,26 @@
<HintPath>..\packages\Mono.Posix-4.5.4.5.0\lib\net45\Mono.Posix.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NBitcoinDual">
<HintPath>..\External Libraries\NBitcoinDual.dll</HintPath>
<Reference Include="NBitcoinBCC, Version=1.0.16.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NBitcoinBCC.1.0.16\lib\netstandard1.1\NBitcoinBCC.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Data" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="websocket-sharp, Version=1.0.2.59611, Culture=neutral, PublicKeyToken=5660b08a1845a91e, processorArchitecture=MSIL">
<HintPath>..\packages\WebSocketSharp.1.0.3-rc11\lib\websocket-sharp.dll</HintPath>
<Private>True</Private>
-1
View File
@@ -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;
+33
View File
@@ -1,6 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.NETCore.Platforms" version="1.1.0" targetFramework="net45" />
<package id="Mono.Posix-4.5" version="4.5.0" targetFramework="net45" />
<package id="NBitcoinBCC" version="1.0.16" targetFramework="net45" />
<package id="NETStandard.Library" version="1.6.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
<package id="System.Collections" version="4.3.0" targetFramework="net45" />
<package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net45" />
<package id="System.Globalization" version="4.3.0" targetFramework="net45" />
<package id="System.IO" version="4.3.0" targetFramework="net45" />
<package id="System.IO.Compression" version="4.3.0" targetFramework="net45" />
<package id="System.Linq" version="4.3.0" targetFramework="net45" />
<package id="System.Linq.Expressions" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Http" version="4.3.2" targetFramework="net45" />
<package id="System.Net.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Requests" version="4.3.0" targetFramework="net45" />
<package id="System.ObjectModel" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net45" />
<package id="System.Threading" version="4.3.0" targetFramework="net45" />
<package id="System.Threading.Tasks" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.XDocument" version="4.3.0" targetFramework="net45" />
<package id="WebSocketSharp" version="1.0.3-rc11" targetFramework="net45" />
</packages>
+1
View File
@@ -65,6 +65,7 @@
<Compile Include="Types\Swarm\BasicPosition.cs" />
<Compile Include="Types\Swarm\BasicPositionAssignment.cs" />
<Compile Include="Types\Swarm\BasicVolunteerPosition.cs" />
<Compile Include="Types\System\BasicBackendServiceOrder.cs" />
<Compile Include="Types\System\BasicSwarmopsLogEntry.cs" />
<Compile Include="Types\Communications\BasicOutboundComm.cs" />
<Compile Include="Types\Communications\BasicOutboundCommRecipient.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(); }
}
}
}
+14
View File
@@ -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); }
}
/// <summary>
/// Used to set a high date
/// </summary>
public static DateTime DateTimeHigh
{ get { return new DateTime(2300, 12, 1); } }
/// <summary>
/// Used in comparisons to see if date is high
/// </summary>
public static DateTime DateTimeHighThreshold
{ get { return new DateTime(2299, 1, 1); } }
}
}
+1 -4
View File
@@ -12,10 +12,7 @@ namespace Swarmops.Database
/// <summary>
/// This is the IN-CODE revision of the database. The version we expect to be running against.
/// </summary>
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.
+187
View File
@@ -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<BasicBackendServiceOrder> result = new List<BasicBackendServiceOrder>();
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
}
}
+16
View File
@@ -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())
+1
View File
@@ -59,6 +59,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Configuration.cs" />
<Compile Include="Database-BackendServiceOrders.cs" />
<Compile Include="Database-ExchangeRates.cs" />
<Compile Include="Database-GeographyUpdates.cs" />
<Compile Include="Database-CashAdvances.cs" />
+2 -1
View File
@@ -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]
+160
View File
@@ -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
@@ -52,6 +52,8 @@ namespace Swarmops.Logic.Financial
{
get
{
Console.WriteLine("WTF");
List<Coin> coinList = new List<Coin>();
foreach (BitcoinTransactionInput input in this)
+100 -76
View File
@@ -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<string> inputAddresses = new List<string>();
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<Coin> coinList = new List<Coin>();
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<NetworkIdentity, DateTime>();
_lastFeeSatoshisLookup = new Dictionary<NetworkIdentity, long>();
_lastFeeRefreshLookup = new Dictionary<BitcoinChain, DateTime>();
_lastFeeSatoshisLookup = new Dictionary<BitcoinChain, long>();
}
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<NetworkIdentity,DateTime> _lastFeeRefreshLookup;
private static Dictionary<NetworkIdentity,Int64> _lastFeeSatoshisLookup;
private static Dictionary<BitcoinChain,DateTime> _lastFeeRefreshLookup;
private static Dictionary<BitcoinChain,Int64> _lastFeeSatoshisLookup;
private const Int64 _satoshisPerBitcoin = 100 * 1000 * 1000; // written this way to improve readability - important constants
/// <summary>
/// Translates the Swarmops BitcoinChain enum to the NBitcoin Network class.
/// </summary>
/// <param name="chain">The BitcoinChain to translate.</param>
/// <returns>The corresponding NBitcoin.Network.</returns>
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);
}
}
}
+8 -3
View File
@@ -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);
}
}
}
+6 -1
View File
@@ -41,7 +41,12 @@ namespace Swarmops.Logic.Financial
HotBitcoinAddressUnspentId = this.Identity
};
}
}
}
public BitcoinTransactionInputs AsInputs
{
get { return BitcoinTransactionInputs.FromSingle(AsInput); }
}
public HotBitcoinAddress Address
{
+5
View File
@@ -88,5 +88,10 @@ namespace Swarmops.Logic.Financial
return unspents;
}
}
public static void UpdateAllUnspentTotals()
{
SwarmDb.GetDatabaseForWriting().UpdateHotBitcoinAddressUnspentTotals();
}
}
}
+4 -4
View File
@@ -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
+16 -2
View File
@@ -85,8 +85,9 @@
<HintPath>..\packages\MySql.Data.6.9.9\lib\net45\MySql.Data.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NBitcoinDual">
<HintPath>..\External Libraries\NBitcoinDual.dll</HintPath>
<Reference Include="NBitcoinBCC, Version=1.0.16.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NBitcoinBCC.1.0.16\lib\netstandard1.1\NBitcoinBCC.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
@@ -105,14 +106,22 @@
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Services" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="websocket-sharp, Version=1.0.2.59611, Culture=neutral, PublicKeyToken=5660b08a1845a91e, processorArchitecture=MSIL">
<HintPath>..\packages\WebSocketSharp.1.0.3-rc11\lib\websocket-sharp.dll</HintPath>
<Private>True</Private>
@@ -208,9 +217,14 @@
<Compile Include="Communications\Payload\NotificationPayload.cs" />
<Compile Include="Security\Impersonation.cs" />
<Compile Include="SocketMessage.cs" />
<Compile Include="Support\BackendServiceOrder.cs" />
<Compile Include="Support\BackendServiceOrders.cs" />
<Compile Include="Support\BackendServices\BackendServiceOrderBase.cs" />
<Compile Include="Support\BackendServices\ReturnBitcoinEchoUtxoOrder.cs" />
<Compile Include="Support\BlockchainTransaction.cs" />
<Compile Include="Support\DocumentImage.cs" />
<Compile Include="Support\ErrorMessages.cs" />
<Compile Include="Support\IBackendServiceOrderBase.cs" />
<Compile Include="Support\LogEntries\ImpersonationLogEntry.cs" />
<Compile Include="Support\LogEntries\PersonalDataChangedLogEntry.cs" />
<Compile Include="Support\PayloadBase.cs" />
+95
View File
@@ -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.)
}
}
}
+28
View File
@@ -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<BackendServiceOrders, BackendServiceOrder, BasicBackendServiceOrder>
{
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();
}
}
}
}
@@ -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<T> : 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("&#x0;", "");
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("&#x0;", "");
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;
}
/// <summary>
/// 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()).
/// </summary>
public virtual void Run()
{
throw new NotImplementedException("The base Run() has no implementation. Derive and override!");
}
/// <summary>
/// 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.
/// </summary>
public void Close()
{
SwarmDb.GetDatabaseForWriting().SetBackendServiceOrderClosed(this.ServiceOrderIdentity);
}
/// <summary>
/// This creates the order and serializes it into the database for execution.
/// </summary>
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; }
}
}
@@ -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<ReturnBitcoinEchoUtxoOrder>
{
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; }
}
}
+12 -5
View File
@@ -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()
{
+18
View File
@@ -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; }
}
}
+33
View File
@@ -5,11 +5,44 @@
<package id="HtmlAgilityPack.CssSelectors" version="1.0.2" targetFramework="net45" />
<package id="iTextSharp-LGPL" version="4.1.6" targetFramework="net45" />
<package id="Markdig" version="0.10.3" targetFramework="net45" />
<package id="Microsoft.NETCore.Platforms" version="1.1.0" targetFramework="net45" />
<package id="MySql.Data" version="6.9.9" targetFramework="net45" />
<package id="NBitcoinBCC" version="1.0.16" targetFramework="net45" />
<package id="NETStandard.Library" version="1.6.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
<package id="NGeoIP" version="1.0.1" targetFramework="net45" />
<package id="NUnit" version="3.5.0" targetFramework="net45" />
<package id="RestSharp" version="105.2.3" targetFramework="net45" />
<package id="SharpZipLib.Portable" version="0.86.0.0003" targetFramework="net45" />
<package id="System.Collections" version="4.3.0" targetFramework="net45" />
<package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net45" />
<package id="System.Globalization" version="4.3.0" targetFramework="net45" />
<package id="System.IO" version="4.3.0" targetFramework="net45" />
<package id="System.IO.Compression" version="4.3.0" targetFramework="net45" />
<package id="System.Linq" version="4.3.0" targetFramework="net45" />
<package id="System.Linq.Expressions" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Http" version="4.3.2" targetFramework="net45" />
<package id="System.Net.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Requests" version="4.3.0" targetFramework="net45" />
<package id="System.ObjectModel" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net45" />
<package id="System.Threading" version="4.3.0" targetFramework="net45" />
<package id="System.Threading.Tasks" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.XDocument" version="4.3.0" targetFramework="net45" />
<package id="WebSocketSharp" version="1.0.3-rc11" targetFramework="net45" />
</packages>
+2 -2
View File
@@ -61,7 +61,7 @@ namespace Resources.Pages {
}
/// <summary>
/// Looks up a localized string similar to This is a QR code for bitcoin echo testing for {0}. Read it from your phone&apos;s bitcoin wallet to perform the echo test, or donate from your computer directly to [{1}] (that&apos;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&apos;s bitcoin wallet to perform the echo test, or donate from your computer directly to [{1}] (that&apos;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..
/// </summary>
internal static string BitcoinEchoTest_Explain {
get {
@@ -97,7 +97,7 @@ namespace Resources.Pages {
}
/// <summary>
/// Looks up a localized string similar to Donate.
/// Looks up a localized string similar to Bitcoin Cash Echo Test.
/// </summary>
internal static string BitcoinEchoTest_PageTitle {
get {
+2 -2
View File
@@ -118,7 +118,7 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="BitcoinEchoTest_Explain" xml:space="preserve">
<value>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.</value>
<value>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.</value>
<comment>The {0} is the organization name. {1} is the bitcoin address for donations.</comment>
</data>
<data name="BitcoinEchoTest_FundsReceived" xml:space="preserve">
@@ -133,7 +133,7 @@
<value>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.</value>
</data>
<data name="BitcoinEchoTest_PageTitle" xml:space="preserve">
<value>Donate</value>
<value>Bitcoin Cash Echo Test</value>
</data>
<data name="BitcoinEchoTest_StatusInitial" xml:space="preserve">
<value>Waiting for transaction...</value>
+6 -2
View File
@@ -224,15 +224,19 @@
<div class="mainbar">
<!--<div id="page-icon-encaps"><asp:Image ID="IconPage" runat="server" ImageUrl="~/Images/PageIcons/iconshock-steering-wheel-40px.png" /></div><h1><asp:Label ID="LabelPageTitle" Text="Dashboard" runat="server" /></h1>-->
<% if (!((this.Page as PageV5Base).SuppressStatisticHeaders))
{ %>
<div class="box" style="background-image: url(/Images/Other/coins-background-istockphoto.jpg); background-size: 700px">
<div class="content">
<div class="odometer-wrapper">
<div class="elementFloatFar odometer odometer-currency" id="odoProfitLossToDate"><%= (CurrentOrganization.GetProfitLossCents() / 100.0 + 0.001).ToString(CultureInfo.InvariantCulture) %></div><div class="odometer-label"><asp:Label runat="server" ID="MasterLabelDashboardProfitLoss">Profit To Date XYZ</asp:Label> <span class="currentYear"><%=DateTime.UtcNow.Year %></span></div>
<div class="elementFloatFar odometer odometer-currency" id="odoProfitLossToDate"><%= (CurrentOrganization.GetProfitLossCents()/100.0 + 0.001).ToString(CultureInfo.InvariantCulture) %></div><div class="odometer-label"><asp:Label runat="server" ID="MasterLabelDashboardProfitLoss">Profit To Date XYZ</asp:Label> <span class="currentYear"><%= DateTime.UtcNow.Year %></span></div>
</div>
</div>
</div>
<% if (!((this.Page as PageV5Base).IsDashboard || ((this.Page as PageV5Base).SuppressStatisticHeaders)))
<% }
if (!((this.Page as PageV5Base).IsDashboard || ((this.Page as PageV5Base).SuppressStatisticHeaders)))
{ %>
<div class="box">
<div class="content"> <% } %>
+81 -54
View File
@@ -2,96 +2,123 @@
<%@ Import Namespace="Swarmops.Logic.Support" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderHead" Runat="Server">
<script src="https://bitcoincash.blockexplorer.com/socket.io/socket.io.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// Initialize socket to wait for transaction
if (enable) {
initializeSocket();
}
// TODO: Also poll regularly in case socket fails
});
function initializeSocket() {
if (socket != null) {
socket.close();
socket = null;
}
// Socket code to listen to Cash Block Explorer
socket = new WebSocket("wss://ws.blockchain.info/inv?api_code=<%= SystemSettings.BlockchainSwarmopsApiKey %>");
eventToListenTo = 'tx';
room = 'inv';
socket.onopen = function(data) {
console.log("socket opened");
socket.send('{"op":"addr_sub","addr":"' + addressUsed + '"}');
};
socket.onclose = function (data) {
if (!completed) {
console.log("socket lost");
initializeSocket();
}
};
socket.onerror = function(data) { console.log("socket error"); };
socket.onmessage = function(data) {
var socket = io("https://bitcoincash.blockexplorer.com/");
socket.on('connect', function() {
// Join the room.
socket.emit('subscribe', room);
});
console.log(data.data);
socket.on(eventToListenTo, function(data) {
var utxoCount = data.vout.length;
for (var index = 0; index < utxoCount; index++)
{
for (var outAddress in data.vout[index]) {
var message = $.parseJSON(data.data);
if (outAddress == addressUsed) {
if (message.op == "utx") {
// transaction received at address
// call page to check if funds received server side
$('#paraStatus').text(verifyingText);
var donatedSatoshis = data.vout[index][outAddress];
sentFunds += Math.floor((donatedSatoshis * conversionRateSatoshisToCents) / 100.0);
odoSentCents.innerHTML = sentFunds; // looks weird but $('#id') not used with odo
alertify.log(decodeURIComponent('<asp:Literal ID="LiteralTxDetected" runat="server" />'));
checkTransactionReceived(message.x.hash);
}
};
}
var json = {};
json.guid = guid;
json.txHash = data.txid;
function checkTransactionReceived(hash) {
SwarmopsJS.ajaxCall('/Pages/v5/Admin/BitcoinEchoTest.aspx/ProcessTransactionReceived',
json,
function (data) {
if (data.Success) {
if (!completed) {
$('#divReturnedFunds').slideDown();
}
if (hash == null) {
hash = "";
}
minerFees += (-Math.floor(minerFeeSatoshis * conversionRateSatoshisToCents) / 100.0);
returnedFunds += (Math.floor(((donatedSatoshis - minerFeeSatoshis) * conversionRateSatoshisToCents) / 100.0));
odoMinerFeeCents.innerHTML = minerFees;
odoReturnedCents.innerHTML = returnedFunds;
$('#paraStatus').text(data.DisplayMessage);
$('#paraIntro').fadeOut().slideUp();
$('#divQr').fadeOut().slideUp();
completed = true;
}
});
SwarmopsJS.ajaxCall('/Pages/v5/Financial/Donate.aspx/CheckTransactionReceived',
{ guid: guid, txHash: hash },
function (data) {
if (data.Success) {
$('#paraStatus').text(data.DisplayMessage);
$('#paraIntro').fadeOut().slideUp();
$('#divQr').fadeOut().slideUp();
completed = true;
socket.close();
socket = null;
}
});
}
}
}
});
var addressUsed = '<asp:Literal runat="server" ID="LiteralBitcoinAddress" />';
var guid = '<asp:Literal runat="server" ID="LiteralGuid" />';
var socket = null;
var sentFunds = 0.001; // the 0.1 cents are necessary for an odometer workaround
var minerFees = -0.001; // negative, or the .1 cents will go wrong
var returnedFunds = 0.001; // as above
var addressUsed = SwarmopsJS.unescape('<%=this.BitcoinCashAddressUsed %>');
var verifyingText = SwarmopsJS.unescape('<%=this.Localized_Verifying%>');
var guid = SwarmopsJS.unescape('<%=this.TransactionGuid%>');
var conversionRateSatoshisToCents = <%= this.ConversionRateSatoshisToCents %>;
var completed = false;
var enable = <asp:Literal ID="LiteralEnable" runat="server">true</asp:Literal>;
var minerFeeSatoshis = <%= EchoFeeSatoshis %>;
var enable = <%=CurrentOrganization.FinancialAccounts.AssetsBitcoinHot == null? "false": "true"%>;
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderMain" Runat="Server">
<div class="box" style="background-image: url(/Images/Other/coins-background-istockphoto.jpg); background-size: 700px">
<div class="content">
<div class="odometer-wrapper">
<div class="elementFloatFar odometer odometer-currency" id="odoSentCents">0.001</div>
<div class="odometer-label">Received in echo test (<%=CurrentOrganization.Currency.DisplayCode %>)</div>
</div>
<div id="#divReturnedFunds" style="display:none">
<div class="odometer-wrapper">
<div class="elementFloatFar odometer odometer-currency" id="odoMinerFeeCents">-0.001</div>
<div class="odometer-label">Miner fees paid</div>
</div>
<hr/>
<div class="odometer-wrapper">
<div class="elementFloatFar odometer odometer-currency" id="odoReturnedCents">0.001</div>
<div class="odometer-label">Successfully returned</div>
</div>
</div>
</div>
</div>
<div class="box"><div class="content">
<asp:Panel runat="server" ID="PanelEnabled">
<h2><asp:Label runat="server" ID="BoxTitle" /></h2>
<p id="paraIntro"><asp:Label runat="server" ID="LabelExplainBitcoinDonation" /></p>
<p id="paraIntro"><asp:Label runat="server" ID="LabelExplainBitcoinEchoTest" /></p>
<p style="font-size:200%" id="paraStatus"><asp:Label runat="server" ID="LabelStatus" /></p>
<div align="center" id="divQr"><asp:Image ID="ImageBitcoinQr" runat="server"/></div>
</asp:Panel>
<asp:Panel runat="server" ID="PanelDisabled" Visible="false">
<h2>Bitcoin hotwallet is not enabled</h2>
<img alt="Fail symbol" src="/Images/Icons/iconshock-cross-96px.png" align="left" /><br/>
<p>This organization has not enabled its bitcoin hotwallet in Swarmops. Therefore, direct donations are not available.</p>
<p>This organization has not enabled its bitcoin hotwallet in Swarmops. Therefore, echo tests are not available.</p>
<p>Contact the administrator for <%=this.CurrentOrganization.Name %> and ask them to enable the bitcoin hotwallet.</p>
<div style="clear:both"></div>
</asp:Panel>
</div></div>
</asp:Content>
+124 -63
View File
@@ -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); }
}
}
}
+2 -38
View File
@@ -12,42 +12,6 @@ namespace Swarmops.Frontend.Pages.v5.Admin {
public partial class BitcoinEchoTest {
/// <summary>
/// LiteralTxDetected control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal LiteralTxDetected;
/// <summary>
/// LiteralBitcoinAddress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal LiteralBitcoinAddress;
/// <summary>
/// LiteralGuid control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal LiteralGuid;
/// <summary>
/// LiteralEnable control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal LiteralEnable;
/// <summary>
/// PanelEnabled control.
/// </summary>
@@ -67,13 +31,13 @@ namespace Swarmops.Frontend.Pages.v5.Admin {
protected global::System.Web.UI.WebControls.Label BoxTitle;
/// <summary>
/// LabelExplainBitcoinDonation control.
/// LabelExplainBitcoinEchoTest control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label LabelExplainBitcoinDonation;
protected global::System.Web.UI.WebControls.Label LabelExplainBitcoinEchoTest;
/// <summary>
/// LabelStatus control.
+3 -1
View File
@@ -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;
+8
View File
@@ -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); }
}
}
}
+11 -2
View File
@@ -51,8 +51,9 @@
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="NBitcoinDual">
<HintPath>..\External Libraries\NBitcoinDual.dll</HintPath>
<Reference Include="NBitcoinBCC, Version=1.0.16.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NBitcoinBCC.1.0.16\lib\netstandard1.1\NBitcoinBCC.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
@@ -66,6 +67,14 @@
<HintPath>..\packages\RestSharp.105.2.3\lib\net45\RestSharp.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
+33
View File
@@ -2,8 +2,41 @@
<packages>
<package id="AutoMapper" version="3.3.1" targetFramework="net45" />
<package id="jquery-qrcode" version="1.0" targetFramework="net45" />
<package id="Microsoft.NETCore.Platforms" version="1.1.0" targetFramework="net45" />
<package id="NBitcoinBCC" version="1.0.16" targetFramework="net45" />
<package id="NETStandard.Library" version="1.6.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
<package id="NGeoIP" version="1.0.1" targetFramework="net45" />
<package id="RestSharp" version="105.2.3" targetFramework="net45" />
<package id="System.Collections" version="4.3.0" targetFramework="net45" />
<package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net45" />
<package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net45" />
<package id="System.Globalization" version="4.3.0" targetFramework="net45" />
<package id="System.IO" version="4.3.0" targetFramework="net45" />
<package id="System.IO.Compression" version="4.3.0" targetFramework="net45" />
<package id="System.Linq" version="4.3.0" targetFramework="net45" />
<package id="System.Linq.Expressions" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Http" version="4.3.2" targetFramework="net45" />
<package id="System.Net.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.Net.Requests" version="4.3.0" targetFramework="net45" />
<package id="System.ObjectModel" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net45" />
<package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net45" />
<package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding" version="4.3.0" targetFramework="net45" />
<package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net45" />
<package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net45" />
<package id="System.Threading" version="4.3.0" targetFramework="net45" />
<package id="System.Threading.Tasks" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net45" />
<package id="System.Xml.XDocument" version="4.3.0" targetFramework="net45" />
<package id="WebSocketSharp" version="1.0.3-rc11" targetFramework="net45" />
</packages>