Major work toward Bitcoin Cash. Donate and Echo are now nonfunctional!
This commit is contained in:
@@ -63,9 +63,8 @@
|
||||
<HintPath>..\packages\Mono.Posix-4.5.4.5.0\lib\net45\Mono.Posix.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="NBitcoin, Version=3.0.0.84, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<Reference Include="NBitcoinDual">
|
||||
<HintPath>..\External Libraries\NBitcoinDual.dll</HintPath>
|
||||
</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>
|
||||
|
||||
@@ -8,6 +8,7 @@ using Mono.Unix.Native;
|
||||
using NBitcoin.Protocol.Behaviors;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Swarmops.Backend.SocketServices;
|
||||
using Swarmops.Common.Enums;
|
||||
using Swarmops.Common.ExtensionMethods;
|
||||
using Swarmops.Database;
|
||||
using Swarmops.Logic;
|
||||
@@ -1028,7 +1029,7 @@ namespace Swarmops.Backend
|
||||
|
||||
try
|
||||
{
|
||||
hotAddress = HotBitcoinAddress.FromAddress(addressString);
|
||||
hotAddress = HotBitcoinAddress.FromAddress(BitcoinChain.Cash, addressString);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Mono.Posix-4.5" version="4.5.0" targetFramework="net45" />
|
||||
<package id="NBitcoin" version="3.0.0.84" targetFramework="net45" />
|
||||
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
|
||||
<package id="WebSocketSharp" version="1.0.3-rc11" targetFramework="net45" />
|
||||
</packages>
|
||||
@@ -77,7 +77,7 @@ namespace Swarmops.Database
|
||||
}
|
||||
}
|
||||
|
||||
public BasicHotBitcoinAddress GetHotBitcoinAddress(string address)
|
||||
public BasicHotBitcoinAddress GetHotBitcoinAddress(BitcoinChain chain, string address)
|
||||
{
|
||||
using (DbConnection connection = GetMySqlDbConnection())
|
||||
{
|
||||
@@ -85,7 +85,7 @@ namespace Swarmops.Database
|
||||
|
||||
DbCommand command =
|
||||
GetDbCommand(
|
||||
"SELECT" + hotBitcoinAddressFieldSequence + "WHERE AddressString='" + SqlSanitize (address) + "';", connection);
|
||||
"SELECT" + hotBitcoinAddressFieldSequence + "WHERE BitcoinChainId=" + (Int32) chain + " AND AddressString='" + SqlSanitize (address) + "';", connection);
|
||||
|
||||
using (DbDataReader reader = command.ExecuteReader())
|
||||
{
|
||||
|
||||
Binary file not shown.
@@ -38,10 +38,6 @@
|
||||
<HintPath>..\packages\Mono.Posix-4.5.4.5.0\lib\net45\Mono.Posix.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="NBitcoin, Version=3.0.0.84, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.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>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Mono.Posix-4.5" version="4.5.0" targetFramework="net452" />
|
||||
<package id="NBitcoin" version="3.0.0.84" targetFramework="net45" />
|
||||
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net452" />
|
||||
<package id="WebSocketSharp" version="1.0.3-rc11" targetFramework="net452" />
|
||||
</packages>
|
||||
+361
-125
@@ -44,15 +44,15 @@ namespace Swarmops.Logic.Financial
|
||||
{
|
||||
ExtKey privateRoot = new ExtKey();
|
||||
File.WriteAllText (SystemSettings.EtcFolder + Path.DirectorySeparatorChar + "hotwallet",
|
||||
privateRoot.GetWif (Network.Main).ToWif(), Encoding.ASCII);
|
||||
privateRoot.GetWif (Network.Core).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.Main).ToWif(), Encoding.ASCII); // an extra backup
|
||||
privateRoot.GetWif (Network.Core).ToWif(), Encoding.ASCII); // an extra backup
|
||||
|
||||
if (String.IsNullOrEmpty (Persistence.Key["BitcoinHotPublicRoot"]))
|
||||
{
|
||||
Persistence.Key["BitcoinHotPublicRoot"] = privateRoot.Neuter().GetWif (Network.Main).ToWif();
|
||||
Persistence.Key["BitcoinHotPublicRoot"] = privateRoot.Neuter().GetWif (Network.Core).ToWif();
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -64,7 +64,7 @@ namespace Swarmops.Logic.Financial
|
||||
// No, it has disappeared, which can happen for a few bad reasons
|
||||
|
||||
Persistence.Key["BitcoinHotPublicRoot"] =
|
||||
BitcoinHotPrivateRoot.Neuter().GetWif (Network.Main).ToWif();
|
||||
BitcoinHotPrivateRoot.Neuter().GetWif (Network.Core).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 +75,14 @@ namespace Swarmops.Logic.Financial
|
||||
|
||||
// ReSharper disable once RedundantCheckBeforeAssignment
|
||||
if (Persistence.Key["BitcoinHotPublicRoot"] !=
|
||||
BitcoinHotPrivateRoot.Neuter().GetWif (Network.Main).ToWif() && !Debugger.IsAttached)
|
||||
BitcoinHotPrivateRoot.Neuter().GetWif (Network.Core).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.Main).ToWif();
|
||||
BitcoinHotPrivateRoot.Neuter().GetWif (Network.Core).ToWif();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,147 +102,323 @@ namespace Swarmops.Logic.Financial
|
||||
get { return ExtPubKey.Parse ((string) Persistence.Key["BitcoinHotPublicRoot"]); }
|
||||
}
|
||||
|
||||
public static string[] GetInputAddressesForTransaction (string txHash)
|
||||
public static string[] GetInputAddressesForTransaction (Network network, string txHash)
|
||||
{
|
||||
List<string> inputAddresses = new List<string>();
|
||||
var jsonResult =
|
||||
JObject.Parse (
|
||||
new WebClient().DownloadString ("https://blockchain.info/rawtx/" + txHash + "?format=json&api_key=" +
|
||||
SystemSettings.BlockchainSwarmopsApiKey));
|
||||
|
||||
foreach (var input in jsonResult["inputs"])
|
||||
JObject jsonResult = new JObject();
|
||||
|
||||
switch (network.Identity)
|
||||
{
|
||||
inputAddresses.Add ((string) (input["prev_out"]["addr"]));
|
||||
case NetworkIdentity.Core:
|
||||
jsonResult =
|
||||
JObject.Parse(
|
||||
new WebClient().DownloadString("https://blockchain.info/rawtx/" + txHash + "?format=json&api_key=" +
|
||||
SystemSettings.BlockchainSwarmopsApiKey));
|
||||
foreach (var input in jsonResult["inputs"])
|
||||
{
|
||||
inputAddresses.Add((string)(input["prev_out"]["addr"]));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case NetworkIdentity.Cash:
|
||||
jsonResult =
|
||||
JObject.Parse(
|
||||
new WebClient().DownloadString("https://bitcoincash.blockexplorer.com/api/tx/" + txHash));
|
||||
foreach (var input in jsonResult["vin"])
|
||||
{
|
||||
inputAddresses.Add((string)(input["addr"]));
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
throw new NotImplementedException("Unimplemented chain, no Explorer: " + network.Identity);
|
||||
}
|
||||
|
||||
|
||||
return inputAddresses.ToArray();
|
||||
}
|
||||
|
||||
|
||||
public static Coin[] GetSpendableCoin (BitcoinSecret secretKey)
|
||||
public static Coin[] GetSpendableCoin (Network network, BitcoinSecret secretKey)
|
||||
// we're using BitcoinSecret as arg just to reinforce caller must have privkey to spend funds
|
||||
{
|
||||
// This function queries the Blockchain API for the unspent coin.
|
||||
|
||||
string addressString = secretKey.PubKey.GetAddress (Network.Main).ToString();
|
||||
var unspentJsonResult =
|
||||
JObject.Parse (
|
||||
new WebClient().DownloadString ("https://blockchain.info/unspent?active=" + addressString +
|
||||
"&api_key=" + SystemSettings.BlockchainSwarmopsApiKey));
|
||||
|
||||
List<Coin> coinList = new List<Coin>();
|
||||
|
||||
foreach (var unspentJson in unspentJsonResult["unspent_outputs"])
|
||||
switch (network.Identity)
|
||||
{
|
||||
BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput()
|
||||
{
|
||||
BitcoinAddress = addressString,
|
||||
ConfirmationCount = (UInt32) unspentJson["confirmations"],
|
||||
Satoshis = (UInt64) unspentJson["value"],
|
||||
TransactionHash = (string) unspentJson["tx_hash_big_endian"],
|
||||
TransactionOutputIndex = (UInt32) unspentJson["tx_output_n"]
|
||||
};
|
||||
case NetworkIdentity.Core:
|
||||
|
||||
coinList.Add (txUnspent); // invokes implicit conversion to NBitcoin.Coin
|
||||
// For the Core net, we query the Blockchain API for the unspent coin.
|
||||
|
||||
string addressString = secretKey.PubKey.GetAddress(network).ToString();
|
||||
var unspentJsonResult =
|
||||
JObject.Parse(
|
||||
new WebClient().DownloadString("https://blockchain.info/unspent?active=" + addressString +
|
||||
"&api_key=" + SystemSettings.BlockchainSwarmopsApiKey));
|
||||
|
||||
foreach (var unspentJson in unspentJsonResult["unspent_outputs"])
|
||||
{
|
||||
BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput()
|
||||
{
|
||||
BitcoinAddress = addressString,
|
||||
ConfirmationCount = (UInt32)unspentJson["confirmations"],
|
||||
Satoshis = (UInt64)unspentJson["value"],
|
||||
TransactionHash = (string)unspentJson["tx_hash_big_endian"],
|
||||
TransactionOutputIndex = (UInt32)unspentJson["tx_output_n"]
|
||||
};
|
||||
|
||||
coinList.Add(txUnspent); // invokes implicit conversion to NBitcoin.Coin
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
|
||||
case NetworkIdentity.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"));
|
||||
|
||||
foreach (JObject unspentJson in unspentArray.Children())
|
||||
{
|
||||
|
||||
|
||||
BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput()
|
||||
{
|
||||
BitcoinAddress = secretKey.PubKey.GetAddress(network).ToString(),
|
||||
ConfirmationCount = (UInt32)unspentJson["confirmations"],
|
||||
Satoshis = (UInt64)unspentJson["satoshis"],
|
||||
TransactionHash = (string)unspentJson["txid"],
|
||||
TransactionOutputIndex = (UInt32)unspentJson["vout"]
|
||||
};
|
||||
|
||||
coinList.Add(txUnspent); // invokes implicit conversion to NBitcoin.Coin
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new NotImplementedException("Unimplemented network identity: " + network.Identity);
|
||||
}
|
||||
|
||||
return coinList.ToArray();
|
||||
|
||||
}
|
||||
|
||||
// TODO: Condense TestUnspents into ONE call for MULTIPLE addresses (separated by | for Unspents according to API docs)
|
||||
|
||||
// TODO: Enable backend to call a running bitcoin node for all this instead of callign third party services
|
||||
|
||||
public static bool TestUnspents (string address)
|
||||
|
||||
|
||||
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.
|
||||
bool result = false;
|
||||
HotBitcoinAddress hotAddress = null;
|
||||
|
||||
var addressInfoResult =
|
||||
JObject.Parse (
|
||||
new WebClient().DownloadString (
|
||||
"https://blockchain.info/address/" + address + "?format=json&api_key=" +
|
||||
SystemSettings.BlockchainSwarmopsApiKey));
|
||||
|
||||
if ((int) addressInfoResult["final_balance"] == 0)
|
||||
{
|
||||
return false; // no funds on address at all at this time
|
||||
}
|
||||
|
||||
JObject addressInfoResult;
|
||||
JObject unspentJsonResult;
|
||||
|
||||
try
|
||||
switch (chain)
|
||||
{
|
||||
unspentJsonResult = JObject.Parse(
|
||||
new WebClient().DownloadString("https://blockchain.info/unspent?active=" + address + "&api_key=" +
|
||||
SystemSettings.BlockchainSwarmopsApiKey));
|
||||
case BitcoinChain.Core:
|
||||
|
||||
}
|
||||
catch (WebException webException)
|
||||
{
|
||||
// A 500 on the above _may_ mean that there's no unspent outpoints. It can also mean a data
|
||||
// retrieval or network error, in which case the exception must absolutely not be interpreted
|
||||
// as valid data of zero unspent outpoints.
|
||||
addressInfoResult =
|
||||
JObject.Parse(
|
||||
new WebClient().DownloadString(
|
||||
"https://blockchain.info/address/" + address + "?format=json&api_key=" +
|
||||
SystemSettings.BlockchainSwarmopsApiKey));
|
||||
|
||||
try
|
||||
{
|
||||
if (webException.Response == null)
|
||||
if ((int)addressInfoResult["final_balance"] == 0)
|
||||
{
|
||||
throw; // if there's no response at all, we can't do shit
|
||||
return false; // no funds on address at all at this time
|
||||
}
|
||||
|
||||
string errorResponseContent =
|
||||
new StreamReader (webException.Response.GetResponseStream()).ReadToEnd();
|
||||
|
||||
if (errorResponseContent.Trim().StartsWith ("No free outputs to spend"))
|
||||
try
|
||||
{
|
||||
// all is okay network-wise, there just aren't any UTXOs so we're getting an error code for that
|
||||
unspentJsonResult = JObject.Parse(
|
||||
new WebClient().DownloadString("https://blockchain.info/unspent?active=" + address + "&api_key=" +
|
||||
SystemSettings.BlockchainSwarmopsApiKey));
|
||||
|
||||
}
|
||||
catch (WebException webException)
|
||||
{
|
||||
// A 500 on the above _may_ mean that there's no unspent outpoints. It can also mean a data
|
||||
// retrieval or network error, in which case the exception must absolutely not be interpreted
|
||||
// as valid data of zero unspent outpoints.
|
||||
|
||||
try
|
||||
{
|
||||
if (webException.Response == null)
|
||||
{
|
||||
throw; // if there's no response at all, we can't do shit
|
||||
}
|
||||
|
||||
string errorResponseContent =
|
||||
new StreamReader(webException.Response.GetResponseStream()).ReadToEnd();
|
||||
|
||||
if (errorResponseContent.Trim().StartsWith("No free outputs to spend"))
|
||||
{
|
||||
// all is okay network-wise, there just aren't any UTXOs so we're getting an error code for that
|
||||
|
||||
return false; // no further processing and there are no fresh transactions
|
||||
}
|
||||
|
||||
throw; // otherwise throw upward
|
||||
}
|
||||
catch (WebException)
|
||||
{
|
||||
// Ok, we tried, but there's apparently a network error so we need to abort this whole thing
|
||||
throw;
|
||||
}
|
||||
|
||||
return false; // no further processing and there are no fresh transactions
|
||||
}
|
||||
|
||||
throw; // otherwise throw upward
|
||||
}
|
||||
catch (WebException)
|
||||
{
|
||||
// Ok, we tried, but there's apparently a network error so we need to abort this whole thing
|
||||
throw;
|
||||
}
|
||||
|
||||
foreach (var unspentJson in unspentJsonResult["unspent_outputs"])
|
||||
{
|
||||
BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput()
|
||||
{
|
||||
BitcoinAddress = address,
|
||||
ConfirmationCount = (UInt32)unspentJson["confirmations"],
|
||||
Satoshis = (UInt64)unspentJson["value"],
|
||||
TransactionHash = (string)unspentJson["tx_hash_big_endian"],
|
||||
TransactionOutputIndex = (UInt32)unspentJson["tx_output_n"]
|
||||
};
|
||||
|
||||
if (txUnspent.ConfirmationCount < 2)
|
||||
{
|
||||
// Fresh transactions, return true
|
||||
result = true;
|
||||
}
|
||||
|
||||
// Add unspent to database
|
||||
|
||||
if (hotAddress == null)
|
||||
{
|
||||
hotAddress = HotBitcoinAddress.FromAddress(chain, address);
|
||||
}
|
||||
|
||||
SwarmDb.GetDatabaseForWriting()
|
||||
.CreateHotBitcoinAddressUnspentConditional(hotAddress.Identity, txUnspent.TransactionHash,
|
||||
(int)txUnspent.TransactionOutputIndex, (Int64)txUnspent.Satoshis,
|
||||
(int)txUnspent.ConfirmationCount);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
|
||||
|
||||
case BitcoinChain.Cash:
|
||||
|
||||
// TODO: SELECTION OF BLOCK EXPLORER, ADDRESS STRING FORMAT TO GO WITH IT
|
||||
|
||||
addressInfoResult =
|
||||
JObject.Parse(
|
||||
new WebClient().DownloadString(
|
||||
"https://bitcoincash.blockexplorer.com/api/addr/" + address));
|
||||
|
||||
JArray unspentArray;
|
||||
|
||||
if ((int)addressInfoResult["balanceSat"] == 0)
|
||||
{
|
||||
return false; // no funds on address at all at this time
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
unspentArray = JArray.Parse(
|
||||
new WebClient().DownloadString("https://bitcoincash.blockexplorer.com/api/addr/" + address + "/utxo"));
|
||||
|
||||
}
|
||||
catch (WebException webException)
|
||||
{
|
||||
// A 500 on the above _may_ mean that there's no unspent outpoints. It can also mean a data
|
||||
// retrieval or network error, in which case the exception must absolutely not be interpreted
|
||||
// as valid data of zero unspent outpoints.
|
||||
|
||||
try
|
||||
{
|
||||
if (webException.Response == null)
|
||||
{
|
||||
throw; // if there's no response at all, we can't do shit
|
||||
}
|
||||
|
||||
string errorResponseContent =
|
||||
new StreamReader(webException.Response.GetResponseStream()).ReadToEnd();
|
||||
|
||||
if (errorResponseContent.Trim().StartsWith("No free outputs to spend"))
|
||||
{
|
||||
// all is okay network-wise, there just aren't any UTXOs so we're getting an error code for that
|
||||
|
||||
return false; // no further processing and there are no fresh transactions
|
||||
}
|
||||
|
||||
throw; // otherwise throw upward
|
||||
}
|
||||
catch (WebException)
|
||||
{
|
||||
// Ok, we tried, but there's apparently a network error so we need to abort this whole thing
|
||||
throw;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
foreach (JObject unspentJson in unspentArray.Children())
|
||||
{
|
||||
BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput()
|
||||
{
|
||||
BitcoinAddress = address,
|
||||
ConfirmationCount = (UInt32)unspentJson["confirmations"],
|
||||
Satoshis = (UInt64)unspentJson["satoshis"],
|
||||
TransactionHash = (string)unspentJson["txid"],
|
||||
TransactionOutputIndex = (UInt32)unspentJson["vout"]
|
||||
};
|
||||
|
||||
if (txUnspent.ConfirmationCount < 2)
|
||||
{
|
||||
// Fresh transactions, return true
|
||||
result = true;
|
||||
}
|
||||
|
||||
// Add unspent to database
|
||||
|
||||
if (hotAddress == null)
|
||||
{
|
||||
hotAddress = HotBitcoinAddress.GetAddressOrForkCore(chain, address);
|
||||
}
|
||||
|
||||
SwarmDb.GetDatabaseForWriting()
|
||||
.CreateHotBitcoinAddressUnspentConditional(hotAddress.Identity, txUnspent.TransactionHash,
|
||||
(int)txUnspent.TransactionOutputIndex, (Int64)txUnspent.Satoshis,
|
||||
(int)txUnspent.ConfirmationCount);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
default:
|
||||
throw new NotImplementedException("Unimplemented bitcoin chain: " + chain);
|
||||
}
|
||||
|
||||
foreach (var unspentJson in unspentJsonResult["unspent_outputs"])
|
||||
{
|
||||
BitcoinUnspentTransactionOutput txUnspent = new BitcoinUnspentTransactionOutput()
|
||||
{
|
||||
BitcoinAddress = address,
|
||||
ConfirmationCount = (UInt32) unspentJson["confirmations"],
|
||||
Satoshis = (UInt64) unspentJson["value"],
|
||||
TransactionHash = (string) unspentJson["tx_hash_big_endian"],
|
||||
TransactionOutputIndex = (UInt32) unspentJson["tx_output_n"]
|
||||
};
|
||||
|
||||
if (txUnspent.ConfirmationCount < 2)
|
||||
{
|
||||
// Fresh transactions, return true
|
||||
result = true;
|
||||
}
|
||||
|
||||
// Add unspent to database
|
||||
|
||||
if (hotAddress == null)
|
||||
{
|
||||
hotAddress = HotBitcoinAddress.FromAddress (address);
|
||||
}
|
||||
|
||||
SwarmDb.GetDatabaseForWriting()
|
||||
.CreateHotBitcoinAddressUnspentConditional (hotAddress.Identity, txUnspent.TransactionHash,
|
||||
(int) txUnspent.TransactionOutputIndex, (Int64) txUnspent.Satoshis,
|
||||
(int) txUnspent.ConfirmationCount);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -589,7 +765,7 @@ namespace Swarmops.Logic.Financial
|
||||
{
|
||||
try
|
||||
{
|
||||
BitcoinAddress singleAddress = new BitcoinPubKeyAddress (address, Network.Main);
|
||||
BitcoinAddress singleAddress = new BitcoinPubKeyAddress (address, Network.Core);
|
||||
return true;
|
||||
}
|
||||
// ReSharper disable once EmptyGeneralCatchClause
|
||||
@@ -600,7 +776,7 @@ namespace Swarmops.Logic.Financial
|
||||
|
||||
try
|
||||
{
|
||||
BitcoinScriptAddress multiSigAddress = new BitcoinScriptAddress (address, Network.Main);
|
||||
BitcoinScriptAddress multiSigAddress = new BitcoinScriptAddress (address, Network.Core);
|
||||
return true;
|
||||
}
|
||||
// ReSharper disable once EmptyGeneralCatchClause
|
||||
@@ -612,38 +788,98 @@ namespace Swarmops.Logic.Financial
|
||||
}
|
||||
|
||||
|
||||
public static Int64 GetRecommendedFeePerThousandBytesSatoshis (int blocksWait = 2)
|
||||
public static Int64 GetRecommendedFeePerThousandBytesSatoshis (Network network, int blocksWait = 2)
|
||||
{
|
||||
DateTime utcNow = DateTime.UtcNow;
|
||||
if (utcNow < _lastFeeRefresh.AddHours (3))
|
||||
if (_lastFeeRefreshLookup == null)
|
||||
{
|
||||
return _lastFeeSatoshis; // cache fee estimate for three hours
|
||||
_lastFeeRefreshLookup = new Dictionary<NetworkIdentity, DateTime>();
|
||||
_lastFeeSatoshisLookup = new Dictionary<NetworkIdentity, long>();
|
||||
}
|
||||
|
||||
DateTime utcNow = DateTime.UtcNow;
|
||||
if (_lastFeeRefreshLookup.ContainsKey(network.Identity) && utcNow < _lastFeeRefreshLookup[network.Identity].AddHours (3))
|
||||
{
|
||||
return _lastFeeSatoshisLookup[network.Identity]; // cache fee estimate for three hours
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
JObject feeData = JObject.Parse(
|
||||
new WebClient().DownloadString("https://blockexplorer.com/api/utils/estimatefee?nbBlocks=" + blocksWait.ToString(CultureInfo.InvariantCulture)));
|
||||
double feeWholeCoins = Double.Parse((string)feeData[blocksWait.ToString(CultureInfo.InvariantCulture)], NumberStyles.AllowDecimalPoint);
|
||||
Int64 feeSatoshis = (Int64) (feeWholeCoins*_satoshisPerBitcoin);
|
||||
Int64 satoshisPerThousandBytes = 1010; // default for Bitcoin Cash
|
||||
|
||||
_lastFeeSatoshis = feeSatoshis;
|
||||
_lastFeeRefresh = utcNow;
|
||||
return feeSatoshis;
|
||||
if (network.Identity == NetworkIdentity.Core)
|
||||
{
|
||||
// But Core has way way WAAAAAAY higher fees
|
||||
|
||||
JObject feeData = JObject.Parse(
|
||||
new WebClient().DownloadString("https://blockexplorer.com/api/utils/estimatefee?nbBlocks=" + blocksWait.ToString(CultureInfo.InvariantCulture)));
|
||||
double feeWholeCoins = Double.Parse((string)feeData[blocksWait.ToString(CultureInfo.InvariantCulture)], NumberStyles.AllowDecimalPoint);
|
||||
satoshisPerThousandBytes = (Int64)(feeWholeCoins * _satoshisPerBitcoin);
|
||||
}
|
||||
|
||||
_lastFeeSatoshisLookup[network.Identity] = satoshisPerThousandBytes;
|
||||
_lastFeeRefreshLookup[network.Identity] = utcNow;
|
||||
return satoshisPerThousandBytes;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// TODO: Check if _lastFeeRefresh is older than a day
|
||||
|
||||
return _lastFeeSatoshis; // in the case of lookup failure, return last known good
|
||||
if (_lastFeeSatoshisLookup.ContainsKey(network.Identity))
|
||||
{
|
||||
return _lastFeeSatoshisLookup[network.Identity];
|
||||
}
|
||||
|
||||
if (network.Identity == NetworkIdentity.Cash)
|
||||
{
|
||||
return 1012; // a low standard: one sat per byte, plus some random extra
|
||||
}
|
||||
|
||||
return 1000*200; // a not so particularly low standard: 200 sat per byte
|
||||
}
|
||||
}
|
||||
|
||||
private static DateTime _lastFeeRefresh = Constants.DateTimeLow;
|
||||
private static Int64 _lastFeeSatoshis = 200 * 100; // 0.2 millibitcoins as default fee per 1000 bytes
|
||||
private static Dictionary<NetworkIdentity,DateTime> _lastFeeRefreshLookup;
|
||||
private static Dictionary<NetworkIdentity,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)
|
||||
{
|
||||
switch (chain)
|
||||
{
|
||||
case BitcoinChain.Core:
|
||||
return Currency.BitcoinCore;
|
||||
case BitcoinChain.Cash:
|
||||
return Currency.BitcoinCash;
|
||||
default:
|
||||
throw new NotImplementedException("Unimplemented BitcoinChain: " + chain);
|
||||
}
|
||||
}
|
||||
|
||||
public static Int64 SatoshisPerBitcoin
|
||||
{
|
||||
get { return _satoshisPerBitcoin; }
|
||||
}
|
||||
|
||||
public static void TestMultisigPayout()
|
||||
{
|
||||
throw new InvalidOperationException("This function is only for testing purposes. It pays real money. Don't use except for dev/test.");
|
||||
@@ -657,10 +893,10 @@ namespace Swarmops.Logic.Financial
|
||||
|
||||
// Make a small test payment to a multisig address
|
||||
|
||||
TransactionBuilder txBuilder = new TransactionBuilder();
|
||||
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() * 20; // assume max 20k transaction size
|
||||
Int64 satoshisMaximumAnticipatedFees = BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(Network.Cash) * 20; // assume max 20k transaction size
|
||||
|
||||
try
|
||||
{
|
||||
@@ -694,7 +930,7 @@ namespace Swarmops.Logic.Financial
|
||||
}
|
||||
else if (bitcoinTestAddress.StartsWith("3")) // multisig
|
||||
{
|
||||
txBuilder = txBuilder.Send(new BitcoinScriptAddress(bitcoinTestAddress, Network.Main),
|
||||
txBuilder = txBuilder.Send(new BitcoinScriptAddress(bitcoinTestAddress, Network.Cash),
|
||||
new Satoshis(satoshis));
|
||||
}
|
||||
else
|
||||
@@ -713,7 +949,7 @@ namespace Swarmops.Logic.Financial
|
||||
// +inputs.Count for size variability
|
||||
|
||||
Int64 feeSatoshis = (transactionSizeBytes/1000 + 1)*
|
||||
BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis();
|
||||
BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinUtility.GetNetworkFromChain(BitcoinChain.Cash));
|
||||
|
||||
txBuilder = txBuilder.SendFees(new Satoshis(feeSatoshis));
|
||||
satoshisUsed += feeSatoshis;
|
||||
@@ -783,7 +1019,7 @@ namespace Swarmops.Logic.Financial
|
||||
N = source.TransactionOutputIndex
|
||||
},
|
||||
new TxOut (new NBitcoin.Money (source.Satoshis),
|
||||
new BitcoinPubKeyAddress (source.BitcoinAddress, Network.Main)));
|
||||
new BitcoinPubKeyAddress (source.BitcoinAddress, Network.Core)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ namespace Swarmops.Logic.Financial
|
||||
}
|
||||
else
|
||||
{
|
||||
// Neither is bitcoin core, so go via bitcoin core
|
||||
// Neither of the currencies is bitcoin core, so go via bitcoin core
|
||||
|
||||
int bitcoinCurrencyId = Currency.BitcoinCore.Identity;
|
||||
double thisPerBitcoin = SwarmDb.GetDatabaseForReading()
|
||||
|
||||
@@ -63,8 +63,8 @@ namespace Swarmops.Logic.Financial
|
||||
}
|
||||
|
||||
derivationPathString = derivationPathString.TrimStart();
|
||||
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
|
||||
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
|
||||
|
||||
int hotBitcoinAddressId =
|
||||
SwarmDb.GetDatabaseForWriting()
|
||||
@@ -73,9 +73,26 @@ namespace Swarmops.Logic.Financial
|
||||
return FromIdentityAggressive (hotBitcoinAddressId);
|
||||
}
|
||||
|
||||
public static HotBitcoinAddress FromAddress (string bitcoinAddress)
|
||||
public static HotBitcoinAddress FromAddress (BitcoinChain chain, string bitcoinAddress)
|
||||
{
|
||||
return FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(bitcoinAddress));
|
||||
return FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(chain, bitcoinAddress));
|
||||
}
|
||||
|
||||
public static HotBitcoinAddress GetAddressOrForkCore(BitcoinChain chain, string bitcoinAddress)
|
||||
{
|
||||
try
|
||||
{
|
||||
return FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(chain, bitcoinAddress));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Forked address off of Core is not registered yet
|
||||
|
||||
HotBitcoinAddress coreAddress =
|
||||
FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(BitcoinChain.Core, bitcoinAddress));
|
||||
|
||||
return Create(coreAddress.Organization, chain, coreAddress.DerivationPathIntArray);
|
||||
}
|
||||
}
|
||||
|
||||
public static HotBitcoinAddress OrganizationWalletZero (Organization organization, BitcoinChain chain)
|
||||
@@ -96,7 +113,7 @@ namespace Swarmops.Logic.Financial
|
||||
secretExtKey = secretExtKey.Derive (UInt32.Parse (derivationString));
|
||||
}
|
||||
|
||||
return secretExtKey.PrivateKey.GetBitcoinSecret (Network.Main);
|
||||
return secretExtKey.PrivateKey.GetBitcoinSecret (Network.Core);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,5 +136,19 @@ namespace Swarmops.Logic.Financial
|
||||
return unspents.Sum (unspent => unspent.AmountSatoshis);
|
||||
}
|
||||
}
|
||||
|
||||
public int[] DerivationPathIntArray
|
||||
{
|
||||
get
|
||||
{
|
||||
List<int> result = new List<int>();
|
||||
foreach (string number in DerivationPath.Split(' '))
|
||||
{
|
||||
result.Add(Int32.Parse(number));
|
||||
}
|
||||
|
||||
return result.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,7 +487,7 @@ namespace Swarmops.Logic.Financial
|
||||
|
||||
// For each ready payout that can automate, add an output to a constructed transaction
|
||||
|
||||
TransactionBuilder txBuilder = new TransactionBuilder();
|
||||
TransactionBuilder txBuilder = null; // TODO TODO TODO TODO new TransactionBuilder();
|
||||
foreach (Payout payout in orgPayouts)
|
||||
{
|
||||
if (payout.ExpectedTransactionDate > utcNow)
|
||||
@@ -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() * 20; // assume max 20k transaction size
|
||||
Int64 satoshisMaximumAnticipatedFees = BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinUtility.GetNetworkFromChain(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.Main),
|
||||
txBuilder = txBuilder.Send(new BitcoinScriptAddress(payout.RecipientPerson.BitcoinPayoutAddress, Network.Core),
|
||||
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();
|
||||
Int64 feeSatoshis = (transactionSizeBytes/1000 + 1) * BitcoinUtility.GetRecommendedFeePerThousandBytesSatoshis(BitcoinUtility.GetNetworkFromChain(chain));
|
||||
|
||||
txBuilder = txBuilder.SendFees (new Satoshis (feeSatoshis));
|
||||
satoshisUsed += feeSatoshis;
|
||||
|
||||
+2
-3
@@ -85,9 +85,8 @@
|
||||
<HintPath>..\packages\MySql.Data.6.9.9\lib\net45\MySql.Data.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="NBitcoin, Version=3.0.0.84, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<Reference Include="NBitcoinDual">
|
||||
<HintPath>..\External Libraries\NBitcoinDual.dll</HintPath>
|
||||
</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>
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
<package id="iTextSharp-LGPL" version="4.1.6" targetFramework="net45" />
|
||||
<package id="Markdig" version="0.10.3" targetFramework="net45" />
|
||||
<package id="MySql.Data" version="6.9.9" targetFramework="net45" />
|
||||
<package id="NBitcoin" version="3.0.0.84" 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" />
|
||||
|
||||
+45
@@ -204,6 +204,51 @@ namespace Resources {
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Chain.
|
||||
/// </summary>
|
||||
internal static string Financial_BitcoinChain {
|
||||
get {
|
||||
return ResourceManager.GetString("Financial_BitcoinChain", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Cash.
|
||||
/// </summary>
|
||||
internal static string Financial_BitcoinChain_Cash {
|
||||
get {
|
||||
return ResourceManager.GetString("Financial_BitcoinChain_Cash", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Core.
|
||||
/// </summary>
|
||||
internal static string Financial_BitcoinChain_Core {
|
||||
get {
|
||||
return ResourceManager.GetString("Financial_BitcoinChain_Core", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Gold.
|
||||
/// </summary>
|
||||
internal static string Financial_BitcoinChain_Gold {
|
||||
get {
|
||||
return ResourceManager.GetString("Financial_BitcoinChain_Gold", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Legacy.
|
||||
/// </summary>
|
||||
internal static string Financial_BitcoinChain_Legacy {
|
||||
get {
|
||||
return ResourceManager.GetString("Financial_BitcoinChain_Legacy", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Bookkeeping Account.
|
||||
/// </summary>
|
||||
|
||||
@@ -930,4 +930,24 @@
|
||||
<data name="Global_SendThisInMail" xml:space="preserve">
|
||||
<value>Send this to me in mail</value>
|
||||
</data>
|
||||
<data name="Financial_BitcoinChain_Cash" xml:space="preserve">
|
||||
<value>Cash</value>
|
||||
<comment>Keep short - seven chars max</comment>
|
||||
</data>
|
||||
<data name="Financial_BitcoinChain_Core" xml:space="preserve">
|
||||
<value>Core</value>
|
||||
<comment>Keep short - seven chars max</comment>
|
||||
</data>
|
||||
<data name="Financial_BitcoinChain_Gold" xml:space="preserve">
|
||||
<value>Gold</value>
|
||||
<comment>Keep short - seven chars max</comment>
|
||||
</data>
|
||||
<data name="Financial_BitcoinChain_Legacy" xml:space="preserve">
|
||||
<value>Legacy</value>
|
||||
<comment>Keep short - seven chars max</comment>
|
||||
</data>
|
||||
<data name="Financial_BitcoinChain" xml:space="preserve">
|
||||
<value>Chain</value>
|
||||
<comment>Short for "Blockchain fork", as in "what chain are you following"</comment>
|
||||
</data>
|
||||
</root>
|
||||
@@ -92,14 +92,14 @@ namespace Swarmops.Frontend.Pages.v5.Admin
|
||||
}
|
||||
|
||||
[WebMethod]
|
||||
static public AjaxCallResult CheckTransactionReceived (string guid, string txHash)
|
||||
static public AjaxCallResult CheckTransactionReceived (string guid, BitcoinChain chain, string txHash)
|
||||
{
|
||||
AuthenticationData authData = GetAuthenticationDataAndCulture(); // just to make sure we're called properly
|
||||
|
||||
string bitcoinAddress = (string) GuidCache.Get (guid);
|
||||
if (BitcoinUtility.TestUnspents (bitcoinAddress))
|
||||
if (BitcoinUtility.TestUnspents (chain, bitcoinAddress))
|
||||
{
|
||||
HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress (bitcoinAddress).Unspents;
|
||||
HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress (chain, bitcoinAddress).Unspents;
|
||||
|
||||
// TODO: Update the HotBitcoinAddress with the new amount?
|
||||
|
||||
@@ -122,11 +122,11 @@ namespace Swarmops.Frontend.Pages.v5.Admin
|
||||
|
||||
// TODO: Get the tx, get the input
|
||||
|
||||
string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(txHash) [0]; // assumes at least one input address
|
||||
string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(BitcoinUtility.GetNetworkFromChain(chain), txHash) [0]; // assumes at least one input address
|
||||
|
||||
if (authData.CurrentOrganization.Currency.IsBitcoinCore)
|
||||
if (authData.CurrentOrganization.Currency.IsBitcoinCash)
|
||||
{
|
||||
// The ledger is native bitcoin, so units are Satoshis
|
||||
// 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)");
|
||||
@@ -156,13 +156,13 @@ namespace Swarmops.Frontend.Pages.v5.Admin
|
||||
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.BitcoinCore);
|
||||
ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, orgNativeCents, authData.CurrentUser).AmountForeignCents = new Swarmops.Logic.Financial.Money(satoshisReceived, Currency.BitcoinCash);
|
||||
ledgerTx.BlockchainHash = txHash;
|
||||
|
||||
successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceived,
|
||||
authData.CurrentOrganization.Currency.DisplayCode, orgNativeCents/100.0, satoshisReceived/100.0);
|
||||
|
||||
// TODO: Create a payout back for this amount -- needs to be specified in bitcoin -- as an inbound invoice
|
||||
// TODO: Create a payout back for this amount -- needs to be specified in bitcoin cash -- as an inbound invoice
|
||||
}
|
||||
|
||||
return new AjaxCallResult() {DisplayMessage = successMessage, Success = true};
|
||||
|
||||
@@ -88,14 +88,14 @@ namespace Swarmops.Frontend.Pages.v5.Financial
|
||||
}
|
||||
|
||||
[WebMethod]
|
||||
static public AjaxCallResult ProcessTransactionReceived (string guid, string txHash)
|
||||
static public AjaxCallResult ProcessTransactionReceived (string guid, BitcoinChain chain, string txHash)
|
||||
{
|
||||
AuthenticationData authData = GetAuthenticationDataAndCulture(); // just to make sure we're called properly
|
||||
|
||||
string bitcoinAddress = (string) GuidCache.Get (guid);
|
||||
if (BitcoinUtility.TestUnspents (bitcoinAddress))
|
||||
if (BitcoinUtility.TestUnspents (chain, bitcoinAddress))
|
||||
{
|
||||
HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress (bitcoinAddress).Unspents;
|
||||
HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress (chain, bitcoinAddress).Unspents;
|
||||
|
||||
// TODO: Update the HotBitcoinAddress with the new amount?
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers
|
||||
private void Localize()
|
||||
{
|
||||
this.LabelContentHeader.Text = Resources.Pages.Ledgers.BitcoinHotwallet_Header;
|
||||
this.LiteralHeaderDerivationPath.Text = Resources.Pages.Ledgers.BitcoinHotwallet_DerivationPath;
|
||||
this.LiteralHeaderDerivationPath.Text = Resources.Global.Financial_BitcoinChain + @", " + Resources.Pages.Ledgers.BitcoinHotwallet_DerivationPath;
|
||||
this.LiteralHeaderAddress.Text = Resources.Pages.Ledgers.BitcoinHotwallet_Address + @" / " + Resources.Pages.Ledgers.BitcoinHotWallet_TransactionHash;
|
||||
this.LiteralHeaderMicrocoins.Text = Resources.Pages.Ledgers.BitcoinHotwallet_BalanceMicrocoins;
|
||||
this.LiteralHeaderFiatValue.Text = String.Format(Resources.Pages.Ledgers.BitcoinHotwallet_ValueFiat, CurrentOrganization.Currency.DisplayCode);
|
||||
|
||||
@@ -3,8 +3,10 @@ using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Resources;
|
||||
using Swarmops.Common.Enums;
|
||||
using Swarmops.Logic.Financial;
|
||||
using Swarmops.Logic.Security;
|
||||
using Money = Swarmops.Logic.Financial.Money;
|
||||
|
||||
namespace Swarmops.Frontend.Pages.v5.Ledgers
|
||||
{
|
||||
@@ -19,6 +21,25 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers
|
||||
|
||||
HotBitcoinAddresses addresses = HotBitcoinAddresses.ForOrganization (_authenticationData.CurrentOrganization);
|
||||
|
||||
foreach (HotBitcoinAddress address in addresses)
|
||||
{
|
||||
if (address.Chain == BitcoinChain.Core)
|
||||
{
|
||||
// These shouldn't exist much, so make sure that we have the equivalent Cash address registered
|
||||
|
||||
try
|
||||
{
|
||||
HotBitcoinAddress.FromAddress(BitcoinChain.Cash, address.Address);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// We didn't have it, so create it
|
||||
BitcoinUtility.TestUnspents(BitcoinChain.Cash, address.Address);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Response.ContentType = "application/json";
|
||||
Response.Output.WriteLine(FormatJson(addresses));
|
||||
Response.End();
|
||||
@@ -30,16 +51,17 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers
|
||||
{
|
||||
StringBuilder result = new StringBuilder(16384);
|
||||
|
||||
double conversionRate = 1.0;
|
||||
if (!this._authenticationData.CurrentOrganization.Currency.IsBitcoinCore)
|
||||
{
|
||||
long fiatCentsPerCoin = new Money(100000000, Currency.BitcoinCore).ToCurrency (_authenticationData.CurrentOrganization.Currency).Cents;
|
||||
conversionRate = fiatCentsPerCoin/100000000.0; // on satoshi level
|
||||
}
|
||||
Dictionary<BitcoinChain, double> conversionRateLookup = new Dictionary<BitcoinChain, double>();
|
||||
Dictionary<BitcoinChain, Int64> satoshisTotalLookup = new Dictionary<BitcoinChain, long>();
|
||||
|
||||
long fiatCentsPerCoreCoin = new Money (BitcoinUtility.SatoshisPerBitcoin, Currency.BitcoinCore).ToCurrency(_authenticationData.CurrentOrganization.Currency).Cents;
|
||||
long fiatCentsPerCashCoin = new Money(BitcoinUtility.SatoshisPerBitcoin, Currency.BitcoinCash).ToCurrency(_authenticationData.CurrentOrganization.Currency).Cents;
|
||||
|
||||
conversionRateLookup[BitcoinChain.Cash] = fiatCentsPerCashCoin/1.0/BitcoinUtility.SatoshisPerBitcoin; // the "/1.0" converts to double implicitly
|
||||
conversionRateLookup[BitcoinChain.Core] = fiatCentsPerCoreCoin/1.0/BitcoinUtility.SatoshisPerBitcoin;
|
||||
|
||||
result.Append("{\"rows\":[");
|
||||
|
||||
Int64 satoshisTotal = 0;
|
||||
int addressesWithFunds = 0;
|
||||
|
||||
foreach (HotBitcoinAddress address in addresses)
|
||||
@@ -61,7 +83,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers
|
||||
Resources.Pages.Ledgers.BitcoinHotWallet_UnspentTransaction,
|
||||
unspent.TransactionHash,
|
||||
(unspent.AmountSatoshis/100.0).ToString ("N2"),
|
||||
(unspent.AmountSatoshis/100.0*conversionRate).ToString ("N2")
|
||||
(unspent.AmountSatoshis/100.0*conversionRateLookup[unspent.Address.Chain]).ToString ("N2")
|
||||
);
|
||||
satoshisUnspentAddress += unspent.AmountSatoshis;
|
||||
childResult.Append ("},");
|
||||
@@ -81,15 +103,22 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers
|
||||
"\"balanceMicrocoins\":\"{3}\"," +
|
||||
"\"balanceFiat\":\"{4}\",",
|
||||
address.Identity,
|
||||
address.DerivationPath,
|
||||
address.Chain.ToString() + " " + address.DerivationPath,
|
||||
address.Address,
|
||||
JsonExpandingString (address.Identity, satoshisUnspentAddress),
|
||||
JsonExpandingString (address.Identity, (Int64) (satoshisUnspentAddress*conversionRate))
|
||||
JsonExpandingString (address.Identity, (Int64) (satoshisUnspentAddress / 100.0 * conversionRateLookup[address.Chain]))
|
||||
);
|
||||
result.Append ("\"state\":\"closed\",\"children\":[" + childResult.ToString() + "]");
|
||||
result.Append ("},");
|
||||
satoshisTotal += satoshisUnspentAddress;
|
||||
addressesWithFunds++;
|
||||
|
||||
if (!satoshisTotalLookup.ContainsKey(address.Chain))
|
||||
{
|
||||
satoshisTotalLookup[address.Chain] = 0;
|
||||
}
|
||||
|
||||
satoshisTotalLookup[address.Chain] += satoshisUnspentAddress;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,14 +142,39 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers
|
||||
result.Append("}");
|
||||
}
|
||||
|
||||
result.Append("],\"footer\":[");
|
||||
result.Append("]");
|
||||
|
||||
result.Append("{");
|
||||
if (satoshisTotalLookup.Count > 0)
|
||||
{
|
||||
// We should also have a footer, because we need a total
|
||||
|
||||
result.AppendFormat("\"derivePath\":\"" + Resources.Global.Global_Total.ToUpperInvariant() + "\",\"balanceMicrocoins\":\"{0}\",\"balanceFiat\":\"{1}\"",
|
||||
(satoshisTotal / 100.0).ToString("N2"), (satoshisTotal / 100.0 * conversionRate).ToString("N2"));
|
||||
result.Append(",\"footer\":[");
|
||||
|
||||
result.Append("}]}"); // on separate line to suppress warning
|
||||
bool previousFooterRow = false;
|
||||
|
||||
foreach (BitcoinChain chain in satoshisTotalLookup.Keys)
|
||||
{
|
||||
if (previousFooterRow)
|
||||
{
|
||||
result.Append(",");
|
||||
}
|
||||
|
||||
result.Append("{");
|
||||
|
||||
result.AppendFormat(
|
||||
"\"derivePath\":\"" + Resources.Global.Global_Total.ToUpperInvariant() + " " +
|
||||
(string) chain.ToString().ToUpperInvariant() + "\",\"balanceMicrocoins\":\"{0}\",\"balanceFiat\":\"{1}\"",
|
||||
(satoshisTotalLookup[chain]/100.0).ToString("N2"), (satoshisTotalLookup[chain]/100.0*conversionRateLookup[chain]).ToString("N2"));
|
||||
|
||||
result.Append("}"); // on separate line to suppress warning*/
|
||||
|
||||
previousFooterRow = true;
|
||||
}
|
||||
|
||||
result.Append("]");
|
||||
}
|
||||
|
||||
result.Append("}");
|
||||
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
+2
-3
@@ -51,9 +51,8 @@
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="NBitcoin, Version=3.0.0.84, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<Reference Include="NBitcoinDual">
|
||||
<HintPath>..\External Libraries\NBitcoinDual.dll</HintPath>
|
||||
</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>
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
<packages>
|
||||
<package id="AutoMapper" version="3.3.1" targetFramework="net45" />
|
||||
<package id="jquery-qrcode" version="1.0" targetFramework="net45" />
|
||||
<package id="NBitcoin" version="3.0.0.84" 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" />
|
||||
|
||||
Reference in New Issue
Block a user