Bitcoin Echo Test seems to work all the way

This commit is contained in:
Rick Falkvinge
2017-11-23 05:20:05 +01:00
parent 24d70c4c77
commit c7efc79c62
14 changed files with 66 additions and 75 deletions
+6
View File
@@ -329,6 +329,12 @@ namespace Swarmops.Backend
{
int signalIndex = 250;
// Handle important service orders (those that can't be lost in a random loss
// of connection of a socket):
BackendServiceOrders backendOrders = BackendServiceOrders.GetNextBatch(5);
backendOrders.Execute(); // takes at most 250ms per he spec
// Block until a SIGINT or SIGTERM signal is generated, or 1/4 second has passed.
// However, we can't do that in a development environment - it won't have the
// Mono.Posix assembly, and won't understand UnixSignals. So people running this in
+11 -6
View File
@@ -80,9 +80,14 @@ namespace Swarmops.Database
{
connection.Open();
DbCommand command =
GetDbCommand( // this ORDERBY + LIMIT gets the oldest first in a FIFO queue
"SELECT " + backendServiceOrderFieldSequence + ConstructWhereClause("BackendServiceOrders", conditions) + " ORDER BY BackendServiceOrderId LIMIT " + batchMaxSize.ToString(CultureInfo.InvariantCulture), connection);
string sql = "SELECT " + backendServiceOrderFieldSequence +
ConstructWhereClause("BackendServiceOrders", conditions) +
" ORDER BY BackendServiceOrderId LIMIT " +
batchMaxSize.ToString(CultureInfo.InvariantCulture);
// this ORDERBY + LIMIT gets the oldest first in a FIFO queue
DbCommand command = GetDbCommand(sql, connection);
using (DbDataReader reader = command.ExecuteReader())
{
@@ -112,7 +117,7 @@ namespace Swarmops.Database
DbCommand command = GetDbCommand("CreateBackendServiceOrder", connection);
command.CommandType = CommandType.StoredProcedure;
AddParameterWithName(command, "dateTime", now);
AddParameterWithName(command, "nowUtc", now);
AddParameterWithName(command, "backendServiceClassName", backendServiceClassName);
AddParameterWithName(command, "orderXml", orderXml);
AddParameterWithName(command, "organizationId", organizationId);
@@ -135,7 +140,7 @@ namespace Swarmops.Database
command.CommandType = CommandType.StoredProcedure;
AddParameterWithName(command, "backendServiceOrderId", backendServiceOrderId);
AddParameterWithName(command, "dateTime", now);
AddParameterWithName(command, "nowUtc", now);
if (Convert.ToInt32(command.ExecuteScalar()) != 1) // returns count of rows updated
{
@@ -156,7 +161,7 @@ namespace Swarmops.Database
command.CommandType = CommandType.StoredProcedure;
AddParameterWithName(command, "backendServiceOrderId", backendServiceOrderId);
AddParameterWithName(command, "dateTime", now);
AddParameterWithName(command, "nowUtc", now);
if (Convert.ToInt32(command.ExecuteScalar()) != 1) // returns count of rows updated
{
+2 -2
View File
@@ -105,7 +105,7 @@ namespace Swarmops.Logic.Financial
return
ExtKey.Parse(
"Replace this with your own favorite secret root key for debugging, and remember to never commit it to Github :)");
"Write your favorite root private key here");
}
return
@@ -346,7 +346,7 @@ namespace Swarmops.Logic.Financial
JArray unspentArray;
if ((int)addressInfoResult["balanceSat"] == 0)
if ((int)addressInfoResult["balanceSat"] == 0 && (int)addressInfoResult["unconfirmedBalanceSat"] == 0)
{
return false; // no funds on address at all at this time
}
+3 -2
View File
@@ -47,7 +47,7 @@ namespace Swarmops.Logic.Support
return;
}
MethodInfo methodFromXml = serviceClassType.GetMethod("FromXml", BindingFlags.FlattenHierarchy | BindingFlags.Static);
MethodInfo methodFromXml = serviceClassType.GetMethod("FromXml", BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public);
if (methodFromXml == null)
{
@@ -56,6 +56,7 @@ namespace Swarmops.Logic.Support
}
IBackendServiceOrderBase order = (IBackendServiceOrderBase) methodFromXml.Invoke(null, new object[] { this.OrderXml });
order.ServiceOrderIdentity = this.Identity; // not part of serialization
// Mark as started
@@ -80,7 +81,7 @@ namespace Swarmops.Logic.Support
{
order.Close();
}
catch (ConcurrencyException)
catch (DatabaseConcurrencyException)
{
// Ignore if we try to close it twice in this particular failure scenario
}
@@ -21,7 +21,7 @@ namespace Swarmops.Logic.Support.BackendServices
{
public virtual string ToXml()
{
XmlSerializer serializer = new XmlSerializer(GetType());
XmlSerializer serializer = new XmlSerializer(this.GetType());
MemoryStream stream = new MemoryStream();
serializer.Serialize(stream, this);
@@ -68,7 +68,7 @@ namespace Swarmops.Logic.Support.BackendServices
/// </summary>
public virtual void Run()
{
throw new NotImplementedException("The base Run() has no implementation. Derive and override!");
throw new NotImplementedException("The base Run() has no implementation. Derive and declare 'override'!");
}
/// <summary>
@@ -14,12 +14,18 @@ namespace Swarmops.Logic.Support.BackendServices
[Serializable]
public class ReturnBitcoinEchoUtxoOrder: BackendServiceOrderBase<ReturnBitcoinEchoUtxoOrder>
{
public ReturnBitcoinEchoUtxoOrder(BasicHotBitcoinAddressUnspent utxo)
[Obsolete("Never call the parameterless ctor from code; intended for use by serialization only.", true)]
public ReturnBitcoinEchoUtxoOrder()
{
this.UtxoIdentity = utxo.Identity;
// Never call -- intended for use by serialization only
}
public new void Run()
public ReturnBitcoinEchoUtxoOrder(BasicHotBitcoinAddressUnspent utxo)
{
this.UtxoIdentity = utxo == null? 0: utxo.Identity;
}
public override void Run()
{
HotBitcoinAddressUnspent utxoToReturn = HotBitcoinAddressUnspent.FromIdentity(UtxoIdentity);
HotBitcoinAddress utxoAddress = utxoToReturn.Address;
@@ -14,5 +14,6 @@ namespace Swarmops.Logic.Support
void Close();
bool HasWorkerThread { get; set; }
Thread WorkerThread { get; set; }
int ServiceOrderIdentity { get; set; }
}
}
+9
View File
@@ -150,6 +150,15 @@ namespace Resources {
}
}
/// <summary>
/// Looks up a localized string similar to Bitcoin Hotwallet Echo Test.
/// </summary>
internal static string Menu5_Admin_Debug_BitcoinEchoTest {
get {
return ResourceManager.GetString("Menu5_Admin_Debug_BitcoinEchoTest", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Built on {0:MMM d, yyyy}.
/// </summary>
+3
View File
@@ -443,4 +443,7 @@
<value>VAT Reports</value>
<comment>This is a European thing (Value Added Tax).</comment>
</data>
<data name="Menu5_Admin_Debug_BitcoinEchoTest" xml:space="preserve">
<value>Bitcoin Hotwallet Echo Test</value>
</data>
</root>
+1 -1
View File
@@ -97,7 +97,7 @@ namespace Resources.Pages {
}
/// <summary>
/// Looks up a localized string similar to Bitcoin Cash Echo Test.
/// Looks up a localized string similar to Bitcoin Cash Hotwallet Echo Test.
/// </summary>
internal static string BitcoinEchoTest_PageTitle {
get {
+1 -1
View File
@@ -133,7 +133,7 @@
<value>This is a bitcoin echo test. It tests the hotwallet. If you send a small amount here, it will be sent back to you, minus the sendback transaction fee.</value>
</data>
<data name="BitcoinEchoTest_PageTitle" xml:space="preserve">
<value>Bitcoin Cash Echo Test</value>
<value>Bitcoin Cash Hotwallet Echo Test</value>
</data>
<data name="BitcoinEchoTest_StatusInitial" xml:space="preserve">
<value>Waiting for transaction...</value>
+10
View File
@@ -583,6 +583,16 @@
<Children />
</MainMenuItem>
<MainMenuItem>
<ResourceKey>Administration_Debug_BitcoinEchoTest</ResourceKey>
<UserLevel>4</UserLevel>
<Permissions />
<ImageUrl>iconshock-battery-drill</ImageUrl>
<NavigateUrl>/Pages/v5/Admin/BitcoinEchoTest.aspx</NavigateUrl>
<Type>Link</Type>
<Children />
</MainMenuItem>
</Children>
</MainMenuItem>
+1
View File
@@ -33,6 +33,7 @@
$('#paraStatus').text(verifyingText);
var donatedSatoshis = data.vout[index][outAddress];
console.log(donatedSatoshis);
sentFunds += Math.floor((donatedSatoshis * conversionRateSatoshisToCents) / 100.0);
odoSentCents.innerHTML = sentFunds; // looks weird but $('#id') not used with odo
+7 -58
View File
@@ -8,6 +8,7 @@ using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using NBitcoin;
using RestSharp.Serializers;
using Swarmops.Common.Enums;
using Swarmops.Logic.Cache;
using Swarmops.Logic.Communications;
@@ -15,6 +16,8 @@ using Swarmops.Logic.Communications.Payload;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Support.BackendServices;
using Satoshis = NBitcoin.Money; // Sets it apart from Swarmops' Money class
namespace Swarmops.Frontend.Pages.v5.Admin
@@ -110,59 +113,8 @@ namespace Swarmops.Frontend.Pages.v5.Admin
// Return the money, too. Set fee for a 300-byte transaction.
TransactionBuilder txBuilder = new TransactionBuilder();
txBuilder = txBuilder.SendFees(new Satoshis(EchoFeeSatoshis));
txBuilder = txBuilder.AddCoins(utxoToReturn.AsInputs.Coins);
txBuilder = txBuilder.AddKeys(utxoToReturn.AsInputs.PrivateKeys);
// change address equals return address, although it should be empty
if (returnAddress.StartsWith("1")) // regular address
{
txBuilder = txBuilder.Send(new BitcoinPubKeyAddress(returnAddress),
new Satoshis(satoshisReceived - EchoFeeSatoshis));
txBuilder.SetChange(new BitcoinPubKeyAddress(returnAddress));
}
else if (returnAddress.StartsWith("3")) // multisig
{
txBuilder = txBuilder.Send(new BitcoinScriptAddress(returnAddress, Network.Main),
new Satoshis(satoshisReceived - EchoFeeSatoshis));
txBuilder.SetChange(new BitcoinScriptAddress(returnAddress, Network.Main));
}
// Sign transaction - ready to execute
Transaction txReady = txBuilder.BuildTransaction(true);
// Verify that transaction is ready
if (!txBuilder.Verify(txReady))
{
// Transaction was not signed with the correct keys. This is a serious condition.
NotificationStrings primaryStrings = new NotificationStrings();
primaryStrings[NotificationString.OrganizationName] = authData.CurrentOrganization.Name;
OutboundComm.CreateNotification(authData.CurrentOrganization, NotificationResource.Bitcoin_PrivateKeyError,
primaryStrings);
throw new InvalidOperationException("Transaction is not signed enough");
}
// Broadcast transaction
BitcoinUtility.BroadcastTransaction(txReady, BitcoinChain.Cash);
// Note the transaction hash
string returnTxHash = txReady.GetHash().ToString();
// Delete all old inputs, adjust balance for addresses (re-register unused inputs)
utxoToReturn.Delete();
HotBitcoinAddresses.UpdateAllUnspentTotals();
ReturnBitcoinEchoUtxoOrder backendOrder = new ReturnBitcoinEchoUtxoOrder(utxoToReturn);
backendOrder.Create(authData.CurrentOrganization, authData.CurrentUser);
string tx1Description = "Bitcoin technical echo test (will be repaid immediately)";
string tx2Description = "Bitcoin echo test repayment";
@@ -182,7 +134,7 @@ namespace Swarmops.Frontend.Pages.v5.Admin
DateTime.UtcNow, tx2Description);
ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, satoshisReceived, authData.CurrentUser);
ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, -satoshisReceived, authData.CurrentUser);
ledgerTx2.BlockchainHash = returnTxHash;
// ledgerTx2.BlockchainHash = returnTxHash; // TODO? Unknown at this point
if (satoshisReceived % 100 == 0)
{
@@ -194,9 +146,6 @@ namespace Swarmops.Frontend.Pages.v5.Admin
successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceivedNative,
(satoshisReceived / 100.0).ToString("N2"));
}
// TODO: Second tx
}
else
{
@@ -213,7 +162,7 @@ namespace Swarmops.Frontend.Pages.v5.Admin
DateTime.UtcNow, tx2Description);
ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, orgNativeCents, authData.CurrentUser);
ledgerTx2.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, -orgNativeCents, authData.CurrentUser).AmountForeignCents = new Swarmops.Logic.Financial.Money(-satoshisReceived, Currency.BitcoinCash);
ledgerTx2.BlockchainHash = returnTxHash;
// ledgerTx2.BlockchainHash = returnTxHash; // TODO: How do we solve this, the recording of the return hash? It's not known here
successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceived,
authData.CurrentOrganization.Currency.DisplayCode, orgNativeCents/100.0, satoshisReceived/100.0);