Work on bitcoin echo tests

This commit is contained in:
Rick Falkvinge
2016-01-06 10:45:07 +01:00
parent d85c6e6fe1
commit ca46764f10
14 changed files with 421 additions and 10 deletions
+6 -1
View File
@@ -361,6 +361,11 @@ namespace Swarmops.Common.Enums
/// <summary>
/// For a hotwallet transaction, the complete derivation path used for this address
/// </summary>
FinancialTransactionRowBitcoinDerivationPath
FinancialTransactionRowBitcoinDerivationPath,
/// <summary>
/// For invoices or other claims, an exact bitcoin amount that overrides native currency
/// </summary>
ExactBitcoinAmountSatoshis
}
}
@@ -178,6 +178,7 @@ namespace Swarmops.Logic.Communications.Payload
Bitcoin_Shortage,
Bitcoin_Shortage_Urgent,
Bitcoin_Shortage_Critical,
Bitcoin_Hotwallet_Outflow,
BitcoinPayoutAddress_Set,
BitcoinPayoutAddress_Bad,
BitcoinPayoutAddress_PleaseSet,
+15
View File
@@ -91,6 +91,21 @@ namespace Swarmops.Logic.Financial
}
}
static public string[] GetInputAddressesForTransaction (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"])
{
inputAddresses.Add ((string) (input["prev_out"]["addr"]));
}
return inputAddresses.ToArray();
}
static public Coin[] GetSpendableCoin (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.
+16
View File
@@ -108,6 +108,22 @@ namespace Swarmops.Logic.Financial
}
}
public Int64 ExactBitcoinAmountSatoshis
{
get
{
return
ObjectOptionalData.ForObject(this).GetOptionalDataInt64(
ObjectOptionalDataType.ExactBitcoinAmountSatoshis);
}
set
{
ObjectOptionalData.ForObject(this)
.SetOptionalDataInt64(ObjectOptionalDataType.ExactBitcoinAmountSatoshis, value);
}
}
#region IAttestable Members
public void Attest (Person attester)
+20 -2
View File
@@ -594,6 +594,10 @@ namespace Swarmops.Logic.Financial
primaryStrings[NotificationString.OrganizationName] = organization.Name;
OutboundComm.CreateNotification(organization, NotificationResource.BitcoinPayoutAddress_PleaseSet, primaryStrings, People.FromSingle(payout.RecipientPerson));
}
else if (payout.Account.StartsWith ("bitcoin:"))
{
}
}
if (bitcoinPayouts.Count == 0)
@@ -751,11 +755,25 @@ namespace Swarmops.Logic.Financial
Payout masterPayout = Payout.CreateBitcoinPayoutFromPrototype (organization, masterPayoutPrototype, txReady.GetHash().ToString());
// Finally, create ledger entries
// Finally, create ledger entries and notify
NotificationStrings masterPrimaryStrings = new NotificationStrings();
NotificationCustomStrings masterSecondaryStrings = new NotificationCustomStrings();
masterPrimaryStrings[NotificationString.OrganizationName] = organization.Name;
masterPrimaryStrings[NotificationString.CurrencyCode] = organization.Currency.DisplayCode;
masterSecondaryStrings["AmountFloat"] =
(new Swarmops.Logic.Financial.Money (satoshisUsed, Currency.Bitcoin).ToCurrency (
organization.Currency).Cents/100.0).ToString ("N2", CultureInfo.InvariantCulture);
masterSecondaryStrings["BitcoinAmountFloat"] = (satoshisUsed/100.0).ToString ("N2", CultureInfo.InvariantCulture);
masterSecondaryStrings["PayoutCount"] = bitcoinPayouts.Count.ToString("N0", CultureInfo.InvariantCulture);
OutboundComm.CreateNotification (organization, NotificationResource.Bitcoin_Hotwallet_Outflow,
masterPrimaryStrings, masterSecondaryStrings);
FinancialTransaction ledgerTransaction = FinancialTransaction.Create (organization, utcNow,
"Bitcoin automated payout");
ledgerTransaction.AddRow (organization.FinancialAccounts.AssetsBitcoinHot, -masterPayoutPrototype.AmountCents, null);
ledgerTransaction.AddRow (organization.FinancialAccounts.AssetsBitcoinHot, -masterPayoutPrototype.AmountCents, null).NativeAmountCents = new Swarmops.Logic.Financial.Money(satoshisUsed, Currency.Bitcoin);
masterPayout.BindToTransactionAndClose (ledgerTransaction, null);
}
@@ -60,6 +60,24 @@ namespace Swarmops.Logic.Resources {
}
}
/// <summary>
/// Looks up a localized string similar to The bitcoin hotwallet for [OrganizationName] just made [PaymentCount] automatic payments totalling [CurrencyCode] [AmountFloat], or expressed in bitcoin, [BitcoinAmountFloat] microbitcoins..
/// </summary>
internal static string Bitcoin_Hotwallet_Outflow_Body {
get {
return ResourceManager.GetString("Bitcoin_Hotwallet_Outflow_Body", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to [[OrganizationName]] Hotwallet Payout: [CurrencyCode] [AmountFloat].
/// </summary>
internal static string Bitcoin_Hotwallet_Outflow_Subject {
get {
return ResourceManager.GetString("Bitcoin_Hotwallet_Outflow_Subject", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to [BitcoinAmountFloat] microbitcoin (&quot;bits&quot;) was just transferred to your bitcoin address ([BitcoinAddress]) by [OrganizationName] for the following:
///
@@ -157,6 +157,12 @@ If you did not set this payout address (it may be worth double checking the addr
<data name="BitcoinPayoutAddress_Set_Subject" xml:space="preserve">
<value>[[OrganizationName]] Bitcoin payout address set</value>
</data>
<data name="Bitcoin_Hotwallet_Outflow_Body" xml:space="preserve">
<value>The bitcoin hotwallet for [OrganizationName] just made [PaymentCount] automatic payments totalling [CurrencyCode] [AmountFloat], or expressed in bitcoin, [BitcoinAmountFloat] microbitcoins.</value>
</data>
<data name="Bitcoin_Hotwallet_Outflow_Subject" xml:space="preserve">
<value>[[OrganizationName]] Hotwallet Payout: [CurrencyCode] [AmountFloat]</value>
</data>
<data name="Bitcoin_PaidOut_Body" xml:space="preserve">
<value>[BitcoinAmountFloat] microbitcoin ("bits") was just transferred to your bitcoin address ([BitcoinAddress]) by [OrganizationName] for the following:
+20 -5
View File
@@ -92,19 +92,34 @@ namespace Swarmops.Logic.Support
// All ints default to 0
public int GetOptionalDataInt (ObjectOptionalDataType key)
public int GetOptionalDataInt(ObjectOptionalDataType key)
{
if (HasData (key))
if (HasData(key))
{
return Int32.Parse (this[key]);
return Int32.Parse(this[key]);
}
return 0;
}
public void SetOptionalDataInt (ObjectOptionalDataType key, int value)
public Int64 GetOptionalDataInt64(ObjectOptionalDataType key)
{
SetOptionalData (key, value.ToString());
if (HasData(key))
{
return Int64.Parse(this[key]);
}
return 0;
}
public void SetOptionalDataInt(ObjectOptionalDataType key, int value)
{
SetOptionalData(key, value.ToString());
}
public void SetOptionalDataInt64(ObjectOptionalDataType key, Int64 value)
{
SetOptionalData(key, value.ToString());
}
@@ -117,6 +117,34 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="BitcoinEchoTest_Explain" xml:space="preserve">
<value>This is a QR code for bitcoin echo testing for {0}. Read it from your phone's bitcoin wallet to perform the echo test, or donate from your computer directly to [{1}] (that's a bitcoin address). The amount (less miner fees) will be sent back to you in the next auto-payment cycle which runs every five minutes.</value>
<comment>The {0} is the organization name. {1} is the bitcoin address for donations.</comment>
</data>
<data name="BitcoinEchoTest_FundsReceived" xml:space="preserve">
<value>Received {0} {1:N2} ({2:N0} microcoins or "bits"). They will be sent back shortly (less miner fee).</value>
<comment>{0} is native currency, {1} is amount in native currency</comment>
</data>
<data name="BitcoinEchoTest_FundsReceivedNative" xml:space="preserve">
<value>Received {0} microcoins ("bits"). They will be sent back shortly (less miner fee).</value>
<comment>Used if BTC is the org native currency.</comment>
</data>
<data name="BitcoinEchoTest_Info" xml:space="preserve">
<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.</value>
</data>
<data name="BitcoinEchoTest_PageTitle" xml:space="preserve">
<value>Donate</value>
</data>
<data name="BitcoinEchoTest_StatusInitial" xml:space="preserve">
<value>Waiting for transaction...</value>
</data>
<data name="BitcoinEchoTest_TransactionDetected" xml:space="preserve">
<value>Transaction detected, verifying...</value>
</data>
<data name="BitcoinEchoTest_TxLabel" xml:space="preserve">
<value>Bitcoin Echo Test for {0}</value>
<comment>The {0} is the organization name</comment>
</data>
<data name="CreateOrganization_ActivistTitle" xml:space="preserve">
<value>Activists will be called</value>
</data>
+3 -1
View File
@@ -38,7 +38,9 @@ namespace Swarmops
// BEGIN TEST CODE
// Salaries.CreateAnnualStatements (2015);
/* string[] testStrings =
BitcoinUtility.GetInputAddressesForTransaction (
"206a3a272d96e9cef929f88ae690c5556cee0a1e8eaca2858f8d858ee2e2cc66");*/
// END TEST CODE
+100
View File
@@ -0,0 +1,100 @@
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="BitcoinEchoTest.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Admin.BitcoinEchoTest" %>
<%@ Import Namespace="Swarmops.Logic.Support" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderHead" Runat="Server">
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// Initialize socket to wait for transaction
if (enable) {
initializeSocket();
}
// TODO: Also poll regularly in case socket fails
});
function initializeSocket() {
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket("wss://ws.blockchain.info/inv?api_code=<%= SystemSettings.BlockchainSwarmopsApiKey %>");
socket.onopen = function(data) {
console.log("socket opened");
socket.send('{"op":"addr_sub","addr":"' + addressUsed + '"}');
};
socket.onclose = function (data) {
if (!completed) {
console.log("socket lost");
initializeSocket();
}
};
socket.onerror = function(data) { console.log("socket error"); };
socket.onmessage = function(data) {
console.log(data.data);
var message = $.parseJSON(data.data);
if (message.op == "utx") {
// transaction received at address
// call page to check if funds received server side
alertify.log(decodeURIComponent('<asp:Literal ID="LiteralTxDetected" runat="server" />'));
checkTransactionReceived(message.x.hash);
}
};
}
function checkTransactionReceived(hash) {
if (hash == null) {
hash = "";
}
SwarmopsJS.ajaxCall('/Pages/v5/Financial/Donate.aspx/CheckTransactionReceived',
{ guid: guid, txHash: hash },
function (data) {
if (data.Success) {
$('#paraStatus').text(data.DisplayMessage);
$('#paraIntro').fadeOut().slideUp();
$('#divQr').fadeOut().slideUp();
completed = true;
socket.close();
socket = null;
}
});
}
var addressUsed = '<asp:Literal runat="server" ID="LiteralBitcoinAddress" />';
var guid = '<asp:Literal runat="server" ID="LiteralGuid" />';
var socket = null;
var completed = false;
var enable = <asp:Literal ID="LiteralEnable" runat="server">true</asp:Literal>;
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderMain" Runat="Server">
<asp:Panel runat="server" ID="PanelEnabled">
<h2><asp:Label runat="server" ID="BoxTitle" /></h2>
<p id="paraIntro"><asp:Label runat="server" ID="LabelExplainBitcoinDonation" /></p>
<p style="font-size:200%" id="paraStatus"><asp:Label runat="server" ID="LabelStatus" /></p>
<div align="center" id="divQr"><asp:Image ID="ImageBitcoinQr" runat="server"/></div>
</asp:Panel>
<asp:Panel runat="server" ID="PanelDisabled" Visible="false">
<h2>Bitcoin hotwallet is not enabled</h2>
<img alt="Fail symbol" src="/Images/Icons/iconshock-cross-96px.png" align="left" /><br/>
<p>This organization has not enabled its bitcoin hotwallet in Swarmops. Therefore, direct donations are not available.</p>
<p>Contact the administrator for <%=this.CurrentOrganization.Name %> and ask them to enable the bitcoin hotwallet.</p>
<div style="clear:both"></div>
</asp:Panel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PlaceHolderSide" Runat="Server">
</asp:Content>
@@ -0,0 +1,177 @@
using System;
using System.Activities.Validation;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using NBitcoin;
using Swarmops.Logic.Cache;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Satoshis = NBitcoin.Money; // Sets it apart from Swarmops' Money class
namespace Swarmops.Frontend.Pages.v5.Admin
{
public partial class BitcoinEchoTest : PageV5Base
{
protected void Page_Load (object sender, EventArgs e)
{
this.PageAccessRequired = new Access (this.CurrentOrganization, AccessAspect.Administration);
// This page is copied from Donate, with the echo payout added to the end
/* TEMP TEMP TEMP - REMOVE THIS CODE */
/*
Organization fwn = Organization.FromIdentity (2);
Salaries salaries = Salaries.ForOrganization (fwn);
foreach (Salary salary in salaries)
{
if (salary.PayrollItem.Person.BitcoinPayoutAddress.Length > 0 && salary.Attested == false)
{
salary.Attest (salary.PayrollItem.Person); // null for system apparently isn't allowed here
}
}*/
this.PageTitle = Resources.Pages.Admin.BitcoinEchoTest_PageTitle;
this.InfoBoxLiteral = Resources.Pages.Admin.BitcoinEchoTest_Info;
this.LabelStatus.Text = Resources.Pages.Admin.BitcoinEchoTest_StatusInitial;
this.LiteralTxDetected.Text = JavascriptEscape (Resources.Pages.Admin.BitcoinEchoTest_TransactionDetected);
if (this.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot == null)
{
this.PanelDisabled.Visible = true;
this.PanelEnabled.Visible = false;
this.LiteralEnable.Text = @"false";
}
HotBitcoinAddress address = HotBitcoinAddress.Create (this.CurrentOrganization,
BitcoinUtility.BitcoinDonationsIndex, this.CurrentUser.Identity);
this.LiteralBitcoinAddress.Text = address.Address;
string guid = Guid.NewGuid().ToString ("N");
GuidCache.Set (guid, address.Address);
this.LiteralGuid.Text = guid;
// TEST TEST TEST
/*
BitcoinSecret secretKey = address.PrivateKey;
Coin[] spendableCoin = BitcoinUtility.GetSpendableCoin (secretKey);
TransactionBuilder txBuild = new TransactionBuilder();
Transaction tx = txBuild.AddCoins (spendableCoin)
.AddKeys (secretKey)
.Send (new BitcoinAddress (BitcoinUtility.BitcoinTestAddress), new Satoshis (address.UnspentSatoshis - BitcoinUtility.FeeSatoshisPerThousandBytes))
.SendFees (new Satoshis(BitcoinUtility.FeeSatoshisPerThousandBytes))
.SetChange (secretKey.GetAddress())
.BuildTransaction (true);
bool test = txBuild.Verify (tx);
if (!test)
{
throw new InvalidOperationException("Tx is not properly signed");
}
BitcoinUtility.BroadcastTransaction (tx);*/
this.BoxTitle.Text = Resources.Pages.Financial.Donate_PageTitle;
this.LabelExplainBitcoinDonation.Text = String.Format (Resources.Pages.Financial.Donate_Explain,
CurrentOrganization.Name, address.Address);
this.ImageBitcoinQr.ImageUrl =
"https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=bitcoin:" +
HttpUtility.UrlEncode (address.Address + "?label=" +
Uri.EscapeDataString (String.Format (Resources.Pages.Financial.Donate_TxLabel,
CurrentOrganization.Name))); // URI scheme doesn't like &, =
}
[WebMethod]
static public AjaxCallResult CheckTransactionReceived (string guid, string txHash)
{
AuthenticationData authData = GetAuthenticationDataAndCulture(); // just to make sure we're called properly
string bitcoinAddress = (string) GuidCache.Get (guid);
if (BitcoinUtility.TestUnspents (bitcoinAddress))
{
HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress (bitcoinAddress).Unspents;
// TODO: Update the HotBitcoinAddress with the new amount?
Int64 satoshisReceived = unspents.Last().AmountSatoshis;
if (unspents.Last().TransactionHash != txHash && txHash.Length > 0)
{
// Race condition.
Debugger.Break();
}
Swarmops.Logic.Financial.Money moneyReceived = new Swarmops.Logic.Financial.Money(satoshisReceived,
Currency.Bitcoin);
// Make sure that the hotwallet native currency is bitcoin
authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot.NativeCurrency = Currency.Bitcoin;
// Create success message and ledger transaction
string successMessage = string.Empty;
// TODO: Get the tx, get the input
string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(txHash) [0]; // assumes at least one input address
if (authData.CurrentOrganization.Currency.IsBitcoin)
{
// The ledger is native bitcoin, so units are Satoshis
FinancialTransaction ledgerTx = FinancialTransaction.Create (authData.CurrentOrganization,
DateTime.UtcNow, "Bitcoin echo test (will be repaid immediately)");
ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.DebtsOther, -satoshisReceived, authData.CurrentUser);
ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, satoshisReceived, authData.CurrentUser);
ledgerTx.BlockchainHash = txHash;
if (satoshisReceived % 100 == 0)
{
successMessage = string.Format (Resources.Pages.Admin.BitcoinEchoTest_FundsReceivedNative,
(satoshisReceived/100.0).ToString ("N0"));
}
else
{
successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceivedNative,
(satoshisReceived / 100.0).ToString("N2"));
}
// TODO: Log the payout back, as an inbound invoice for immediate payout
}
else
{
// The ledger is NOT native bitcoin, so we'll need to convert currencies
long orgNativeCents = moneyReceived.ToCurrency (authData.CurrentOrganization.Currency).Cents;
FinancialTransaction ledgerTx = FinancialTransaction.Create(authData.CurrentOrganization,
DateTime.UtcNow, "Bitcoin echo test (will be repaid immediately)");
ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, -orgNativeCents, authData.CurrentUser);
ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, orgNativeCents, authData.CurrentUser).NativeAmountCents = new Swarmops.Logic.Financial.Money(satoshisReceived, Currency.Bitcoin);
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
}
return new AjaxCallResult() {DisplayMessage = successMessage, Success = true};
// TODO: Ack donation via mail?
// TODO: Notify CFO/etc of donation?
}
return new AjaxCallResult() {Success = false};
}
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="Donate.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Financial.Donate" %>
<%@ Import Namespace="Swarmops.Logic.Support" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderHead" Runat="Server">
<script type="text/javascript" language="javascript">
@@ -19,7 +20,7 @@
socket = null;
}
socket = new WebSocket("wss://ws.blockchain.info/inv");
socket = new WebSocket("wss://ws.blockchain.info/inv?api_code=<%= SystemSettings.BlockchainSwarmopsApiKey %>");
socket.onopen = function(data) {
console.log("socket opened");
@@ -47,6 +47,15 @@ namespace Swarmops.Frontend.Pages.Financial
{
if (bitcoinHotWalletActive && payout.RecipientPerson != null && payout.RecipientPerson.BitcoinPayoutAddress.Length > 0 && payout.Account.Length < 4) // 4 because an empty account will be " / ", length 3
{
// This is a person who will be paid in bitcoin per personal preferences, so don't show for manual payout
continue;
}
if (bitcoinHotWalletActive && payout.Account.StartsWith ("bitcoin:"))
{
// This is a payout registered to be paid in bitcoin, so don't show for manual payout
continue;
}