diff --git a/Backend/Backend.csproj b/Backend/Backend.csproj index dd659c1e..cd5a065a 100644 --- a/Backend/Backend.csproj +++ b/Backend/Backend.csproj @@ -63,9 +63,8 @@ ..\packages\Mono.Posix-4.5.4.5.0\lib\net45\Mono.Posix.dll True - - ..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.dll - True + + ..\External Libraries\NBitcoinDual.dll ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll diff --git a/Backend/BackendLoop.cs b/Backend/BackendLoop.cs index 7caec5e4..46d766b8 100644 --- a/Backend/BackendLoop.cs +++ b/Backend/BackendLoop.cs @@ -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) { diff --git a/Backend/packages.config b/Backend/packages.config index 71c2fbf1..f035528a 100644 --- a/Backend/packages.config +++ b/Backend/packages.config @@ -1,7 +1,6 @@  - \ No newline at end of file diff --git a/Database/Database-HotBitcoinAddresses.cs b/Database/Database-HotBitcoinAddresses.cs index b472dc2f..ec449439 100644 --- a/Database/Database-HotBitcoinAddresses.cs +++ b/Database/Database-HotBitcoinAddresses.cs @@ -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()) { diff --git a/External Libraries/NBitcoinDual.dll b/External Libraries/NBitcoinDual.dll index acff4b0c..2424728e 100644 Binary files a/External Libraries/NBitcoinDual.dll and b/External Libraries/NBitcoinDual.dll differ diff --git a/FrontSocket/Frontend-Socket.csproj b/FrontSocket/Frontend-Socket.csproj index d6a408b8..295fad61 100644 --- a/FrontSocket/Frontend-Socket.csproj +++ b/FrontSocket/Frontend-Socket.csproj @@ -38,10 +38,6 @@ ..\packages\Mono.Posix-4.5.4.5.0\lib\net45\Mono.Posix.dll True - - ..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.dll - True - ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll True diff --git a/FrontSocket/packages.config b/FrontSocket/packages.config index 621bfc9b..3d24f69b 100644 --- a/FrontSocket/packages.config +++ b/FrontSocket/packages.config @@ -1,7 +1,6 @@  - \ No newline at end of file diff --git a/Logic/Financial/BitcoinUtility.cs b/Logic/Financial/BitcoinUtility.cs index dcac42fa..5bd93bb1 100644 --- a/Logic/Financial/BitcoinUtility.cs +++ b/Logic/Financial/BitcoinUtility.cs @@ -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 inputAddresses = new List(); - var jsonResult = - JObject.Parse ( - new WebClient().DownloadString ("https://blockchain.info/rawtx/" + txHash + "?format=json&api_key=" + - SystemSettings.BlockchainSwarmopsApiKey)); - foreach (var input in jsonResult["inputs"]) + 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 coinList = new List(); - 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(); + _lastFeeSatoshisLookup = new Dictionary(); + } + + 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 _lastFeeRefreshLookup; + private static Dictionary _lastFeeSatoshisLookup; private const Int64 _satoshisPerBitcoin = 100 * 1000 * 1000; // written this way to improve readability - important constants + + /// + /// Translates the Swarmops BitcoinChain enum to the NBitcoin Network class. + /// + /// The BitcoinChain to translate. + /// The corresponding NBitcoin.Network. + public static Network GetNetworkFromChain(BitcoinChain chain) + { + switch (chain) + { + case BitcoinChain.Core: + return Network.Core; + case BitcoinChain.Cash: + return Network.Cash; + default: + throw new NotImplementedException("Unimplemented BitcoinChain: " + chain); + } + } + + public static Currency GetCurrencyFromChain(BitcoinChain chain) + { + 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))); } } } diff --git a/Logic/Financial/Currency.cs b/Logic/Financial/Currency.cs index 3b77b342..b4f47322 100644 --- a/Logic/Financial/Currency.cs +++ b/Logic/Financial/Currency.cs @@ -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() diff --git a/Logic/Financial/HotBitcoinAddress.cs b/Logic/Financial/HotBitcoinAddress.cs index 2e776093..1e853c1b 100644 --- a/Logic/Financial/HotBitcoinAddress.cs +++ b/Logic/Financial/HotBitcoinAddress.cs @@ -63,8 +63,8 @@ namespace Swarmops.Logic.Financial } derivationPathString = derivationPathString.TrimStart(); - string bitcoinAddress = extPubKey.PubKey.GetAddress (Network.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 result = new List(); + foreach (string number in DerivationPath.Split(' ')) + { + result.Add(Int32.Parse(number)); + } + + return result.ToArray(); + } + } } } diff --git a/Logic/Financial/Payouts.cs b/Logic/Financial/Payouts.cs index 8219dee5..dd40717e 100644 --- a/Logic/Financial/Payouts.cs +++ b/Logic/Financial/Payouts.cs @@ -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; diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index 9f83d822..49f3665d 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -85,9 +85,8 @@ ..\packages\MySql.Data.6.9.9\lib\net45\MySql.Data.dll True - - ..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.dll - True + + ..\External Libraries\NBitcoinDual.dll ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll diff --git a/Logic/packages.config b/Logic/packages.config index cbe54756..c36567d0 100644 --- a/Logic/packages.config +++ b/Logic/packages.config @@ -6,7 +6,6 @@ - diff --git a/Site/App_GlobalResources/Global.designer.cs b/Site/App_GlobalResources/Global.designer.cs index 1c7b7bf6..bcfaadaf 100644 --- a/Site/App_GlobalResources/Global.designer.cs +++ b/Site/App_GlobalResources/Global.designer.cs @@ -204,6 +204,51 @@ namespace Resources { } } + /// + /// Looks up a localized string similar to Chain. + /// + internal static string Financial_BitcoinChain { + get { + return ResourceManager.GetString("Financial_BitcoinChain", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cash. + /// + internal static string Financial_BitcoinChain_Cash { + get { + return ResourceManager.GetString("Financial_BitcoinChain_Cash", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Core. + /// + internal static string Financial_BitcoinChain_Core { + get { + return ResourceManager.GetString("Financial_BitcoinChain_Core", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Gold. + /// + internal static string Financial_BitcoinChain_Gold { + get { + return ResourceManager.GetString("Financial_BitcoinChain_Gold", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Legacy. + /// + internal static string Financial_BitcoinChain_Legacy { + get { + return ResourceManager.GetString("Financial_BitcoinChain_Legacy", resourceCulture); + } + } + /// /// Looks up a localized string similar to Bookkeeping Account. /// diff --git a/Site/App_GlobalResources/Global.resx b/Site/App_GlobalResources/Global.resx index aac4f42f..c88f1863 100644 --- a/Site/App_GlobalResources/Global.resx +++ b/Site/App_GlobalResources/Global.resx @@ -930,4 +930,24 @@ Send this to me in mail + + Cash + Keep short - seven chars max + + + Core + Keep short - seven chars max + + + Gold + Keep short - seven chars max + + + Legacy + Keep short - seven chars max + + + Chain + Short for "Blockchain fork", as in "what chain are you following" + \ No newline at end of file diff --git a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs index 93ad8a32..4fa79a30 100644 --- a/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs +++ b/Site/Pages/v5/Admin/BitcoinEchoTest.aspx.cs @@ -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}; diff --git a/Site/Pages/v5/Financial/Donate.aspx.cs b/Site/Pages/v5/Financial/Donate.aspx.cs index 865c42a4..15a8339e 100644 --- a/Site/Pages/v5/Financial/Donate.aspx.cs +++ b/Site/Pages/v5/Financial/Donate.aspx.cs @@ -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? diff --git a/Site/Pages/v5/Ledgers/BitcoinHotwallet.aspx.cs b/Site/Pages/v5/Ledgers/BitcoinHotwallet.aspx.cs index a96eff2b..feba8e82 100644 --- a/Site/Pages/v5/Ledgers/BitcoinHotwallet.aspx.cs +++ b/Site/Pages/v5/Ledgers/BitcoinHotwallet.aspx.cs @@ -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); diff --git a/Site/Pages/v5/Ledgers/Json-BitcoinHotwalletData.aspx.cs b/Site/Pages/v5/Ledgers/Json-BitcoinHotwalletData.aspx.cs index 94e6ad62..ee587a81 100644 --- a/Site/Pages/v5/Ledgers/Json-BitcoinHotwalletData.aspx.cs +++ b/Site/Pages/v5/Ledgers/Json-BitcoinHotwalletData.aspx.cs @@ -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 conversionRateLookup = new Dictionary(); + Dictionary satoshisTotalLookup = new Dictionary(); + + 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(); } diff --git a/Site/Site.csproj b/Site/Site.csproj index 07f26b90..18d227c5 100644 --- a/Site/Site.csproj +++ b/Site/Site.csproj @@ -51,9 +51,8 @@ True - - ..\packages\NBitcoin.3.0.0.84\lib\net45\NBitcoin.dll - True + + ..\External Libraries\NBitcoinDual.dll ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll diff --git a/Site/packages.config b/Site/packages.config index e50285a5..8f0560c1 100644 --- a/Site/packages.config +++ b/Site/packages.config @@ -2,7 +2,6 @@ -