Work on hotwallet

This commit is contained in:
Rick Falkvinge
2015-10-07 19:23:32 +02:00
parent 14f7f3f4df
commit 7a97f6b014
11 changed files with 331 additions and 16 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ namespace Swarmops.Database
/// </summary>
public static int DbVersionExpected
{
get { return 27; }
get { return 28; }
}
+24 -2
View File
@@ -50,7 +50,7 @@ namespace Swarmops.Database
#region Record reading code
public BasicHotBitcoinAddress GetHotBitcoinAddress (int hotBitcoinAddressId)
public BasicHotBitcoinAddress GetHotBitcoinAddress(int hotBitcoinAddressId)
{
using (DbConnection connection = GetMySqlDbConnection())
{
@@ -72,6 +72,28 @@ namespace Swarmops.Database
}
}
public BasicHotBitcoinAddress GetHotBitcoinAddress(string address)
{
using (DbConnection connection = GetMySqlDbConnection())
{
connection.Open();
DbCommand command =
GetDbCommand(
"SELECT" + hotBitcoinAddressFieldSequence + "WHERE AddressString='" + SqlSanitize (address) + "';", connection);
using (DbDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return ReadHotBitcoinAddressFromDataReader(reader);
}
throw new ArgumentException("Unknown HotBitcoinAddress: " + address);
}
}
}
public BasicHotBitcoinAddress[] GetHotBitcoinAddresses(params object[] conditions) // the typical condition would be an Organization, here
{
List<BasicHotBitcoinAddress> result = new List<BasicHotBitcoinAddress>();
@@ -107,7 +129,7 @@ namespace Swarmops.Database
DbCommand command =
GetDbCommand(
"SELECT" + hotBitcoinAddressUnspentFieldSequence + ConstructWhereClause("HotBitcoinAddressUnspents", conditions), connection);
"SELECT" + hotBitcoinAddressUnspentFieldSequence + ConstructWhereClause("HotBitcoinAddressUnspents", conditions) + " ORDER BY HotBitcoinAddressUnspentId ASC", connection);
using (DbDataReader reader = command.ExecuteReader())
{
+2 -1
View File
@@ -24,4 +24,5 @@
0024 - Maint on CreatePayrollItem [RF]
0025 - Bugfix for 0024 [RF]
0026 - Added first tables, procs for hot bitcoin wallets [RF]
0027 - Fixes and additions to HotBitcoinAddresses, -Unspents [RF]
0027 - Fixes and additions to HotBitcoinAddresses, -Unspents [RF]
0028 - Bugfix for 0027 [RF]
+31
View File
@@ -0,0 +1,31 @@
DROP procedure IF EXISTS `CreateHotBitcoinAddressConditional`
#
CREATE PROCEDURE `CreateHotBitcoinAddressConditional` (
IN organizationId INT,
IN derivationPath VARCHAR(256),
IN addressString VARCHAR(48)
)
BEGIN
IF ((SELECT COUNT(*) FROM HotBitcoinAddresses WHERE HotBitcoinAddresses.AddressString=addressString) = 0)
THEN
INSERT INTO HotBitcoinAddresses
(OrganizationId,DerivationPath,AddressString,BalanceSatoshis,ThroughputSatoshis)
VALUES
(organizationId,derivationPath,addressString,0,0);
SELECT LAST_INSERT_ID() AS Identity;
ELSE
SELECT HotBitcoinAddresses.HotBitcoinAddressId AS Identity
WHERE HotBitcoinAddresses.AddressString=addressString;
END IF;
END
+43
View File
@@ -11,6 +11,7 @@ using System.Web;
using NBitcoin;
using NBitcoin.BouncyCastle.Asn1.Ocsp;
using Newtonsoft.Json.Linq;
using Swarmops.Database;
namespace Swarmops.Logic.Financial
{
@@ -43,6 +44,48 @@ namespace Swarmops.Logic.Financial
return coinList.ToArray();
}
static public bool TestUnspents (string address)
{
// This function queries the Blockchain API for the unspent coin.
bool result = false;
HotBitcoinAddress hotAddress = null;
var unspentJsonResult =
JObject.Parse(new WebClient().DownloadString("https://blockchain.info/unspent?active=" + address));
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;
}
static public void BroadcastTransaction (Transaction transaction)
{
using (WebClient client = new WebClient())
+5
View File
@@ -73,6 +73,11 @@ namespace Swarmops.Logic.Financial
return FromIdentityAggressive (transactionId);
}
public static FinancialTransaction Create (Organization organization, DateTime dateTime, string description)
{
return FinancialTransaction.Create (organization.Identity, dateTime, description);
}
#endregion
public FinancialTransactionRows Rows
+60
View File
@@ -1,9 +1,13 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBitcoin;
using Swarmops.Basic.Types.Financial;
using Swarmops.Database;
using Swarmops.Logic.Structure;
namespace Swarmops.Logic.Financial
{
@@ -19,6 +23,62 @@ namespace Swarmops.Logic.Financial
return new HotBitcoinAddress (basic); // invoke private ctor
}
public static HotBitcoinAddress FromIdentity(int hotBitcoinAddressId)
{
return FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(hotBitcoinAddressId));
}
internal static HotBitcoinAddress FromIdentityAggressive(int hotBitcoinAddressId)
{
return FromBasic(SwarmDb.GetDatabaseForWriting().GetHotBitcoinAddress(hotBitcoinAddressId)); // "Writing" is intentional
}
public static HotBitcoinAddress Create(Organization organization, string derivationPath)
{
/*
string bitcoinAddress =
FinancialAccounts.BitcoinHotPublicRoot
.Derive((uint)this.CurrentOrganization.Identity)
.Derive(BitcoinUtility.BitcoinDonationsIndex)
.Derive((uint)this.CurrentUser.Identity)
.PubKey.GetAddress(Network.Main)
.ToString();*/
throw new NotImplementedException();
}
public static HotBitcoinAddress Create (Organization organization, params int[] derivationPath)
{
ExtPubKey extPubKey = FinancialAccounts.BitcoinHotPublicRoot;
extPubKey = extPubKey.Derive ((uint) organization.Identity);
string derivationPathString = string.Empty;
foreach (int derivation in derivationPath) // requires that order is consistent from 0 to n-1
{
extPubKey = extPubKey.Derive ((uint) derivation);
derivationPathString += " " + derivation.ToString (CultureInfo.InvariantCulture);
}
derivationPathString = derivationPathString.TrimStart();
string bitcoinAddress = extPubKey.PubKey.GetAddress (Network.Main).ToString();
int hotBitcoinAddressId =
SwarmDb.GetDatabaseForWriting()
.CreateHotBitcoinAddressConditional (organization.Identity, derivationPathString, bitcoinAddress);
return FromIdentityAggressive (hotBitcoinAddressId);
}
public static HotBitcoinAddress FromAddress (string bitcoinAddress)
{
return FromBasic(SwarmDb.GetDatabaseForReading().GetHotBitcoinAddress(bitcoinAddress));
}
public HotBitcoinAddressUnspents Unspents
{
get { return HotBitcoinAddressUnspents.ForAddress (this); }
}
}
}
+5 -1
View File
@@ -4,12 +4,16 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Swarmops.Basic.Types.Financial;
using Swarmops.Database;
using Swarmops.Logic.Support;
namespace Swarmops.Logic.Financial
{
public class HotBitcoinAddressUnspents: PluralBase<HotBitcoinAddressUnspents, HotBitcoinAddressUnspent, BasicHotBitcoinAddressUnspent>
{
// unfilled for now
static public HotBitcoinAddressUnspents ForAddress (HotBitcoinAddress address)
{
return FromArray (SwarmDb.GetDatabaseForReading().GetHotBitcoinAddressUnspents (address));
}
}
}
@@ -329,12 +329,23 @@
<value>This is a QR code for donations to {0}. Read it from your phone's bitcoin wallet to make a donation, or donate from your computer directly to [{1}] (that's a bitcoin address).</value>
<comment>The {0} is the organization name. {1} is the bitcoin address for donations.</comment>
</data>
<data name="Donate_FundsReceived" xml:space="preserve">
<value>Received {0} {1} ({2} microcoins or "bits"). Thank you!</value>
<comment>{0} is native currency, {1} is amount in native currency</comment>
</data>
<data name="Donate_FundsReceivedNative" xml:space="preserve">
<value>Received {0} microcoins ("bits"). Thank you!</value>
<comment>Used if BTC is the org native currency.</comment>
</data>
<data name="Donate_Info" xml:space="preserve">
<value>If you want to donate to the organization, your can do so here.</value>
</data>
<data name="Donate_PageTitle" xml:space="preserve">
<value>Donate</value>
</data>
<data name="Donate_StatusInitial" xml:space="preserve">
<value>Waiting for transaction...</value>
</data>
<data name="Donate_TxLabel" xml:space="preserve">
<value>Donation to {0}</value>
<comment>The {0} is the organization name</comment>
+66 -1
View File
@@ -1,12 +1,77 @@
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="Donate.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Financial.Donate" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderHead" Runat="Server">
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// Initialize socket to wait for transaction
initializeSocket();
// TODO: Also poll regularly in case socket fails
checkTransactionReceived(); // test ajax call
});
function initializeSocket() {
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket("wss://ws.blockchain.info/inv");
socket.onopen = function(data) {
console.log("socket opened");
socket.send('{"op":"addr_sub","addr":"' + addressUsed + '"}');
};
socket.onclose = function(data) {
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("Tx received on socket, checking...");
checkTransactionReceived(message.x.hash);
}
};
}
function checkTransactionReceived (hash) {
SwarmopsJS.ajaxCall('/Pages/v5/Financial/Donate.aspx/CheckTransactionReceived',
{ guid: guid, txHash: hash },
function (data) {
if (data.Success) {
$('#paraStatus').text(data.DisplayMessage);
$('#divQr').fadeOut().slideUp();
socket.close();
socket = null;
}
});
}
var addressUsed = '<asp:Literal runat="server" ID="LiteralBitcoinAddress" />';
var guid = '<asp:Literal runat="server" ID="LiteralGuid" />';
var socket = null;
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderMain" Runat="Server">
<h2><asp:Label runat="server" ID="BoxTitle" /></h2>
<p><asp:Label runat="server" ID="LabelExplainBitcoinDonation" /></p>
<div align="center"><asp:Image ID="ImageBitcoinQr" runat="server"/></div>
<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:Content>
+83 -10
View File
@@ -1,11 +1,15 @@
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;
@@ -18,14 +22,15 @@ namespace Swarmops.Frontend.Pages.v5.Financial
this.PageAccessRequired = new Access (this.CurrentOrganization, AccessAspect.Participant);
this.PageTitle = Resources.Pages.Financial.Donate_PageTitle;
this.InfoBoxLiteral = Resources.Pages.Financial.FileExpenseClaim_Info;
string bitcoinAddress =
FinancialAccounts.BitcoinHotPublicRoot
.Derive ((uint) this.CurrentOrganization.Identity)
.Derive (BitcoinUtility.BitcoinDonationsIndex)
.Derive ((uint) this.CurrentUser.Identity)
.PubKey.GetAddress (Network.Main)
.ToString();
this.InfoBoxLiteral = Resources.Pages.Financial.Donate_Info;
this.LabelStatus.Text = Resources.Pages.Financial.Donate_StatusInitial;
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);
// TEST TEST TEST
/*
@@ -55,10 +60,78 @@ namespace Swarmops.Frontend.Pages.v5.Financial
BitcoinUtility.BroadcastTransaction (tx);*/
this.BoxTitle.Text = Resources.Pages.Financial.Donate_PageTitle;
this.LabelExplainBitcoinDonation.Text = String.Format(Resources.Pages.Financial.Donate_Explain, CurrentOrganization.Name, bitcoinAddress);
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(bitcoinAddress + "?label=" + Uri.EscapeDataString(String.Format(Resources.Pages.Financial.Donate_TxLabel, CurrentOrganization.Name))); // URI scheme doesn't like &, =
"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;
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);
// Create success message and ledger transaction
string successMessage = string.Empty;
if (authData.CurrentOrganization.Currency.IsBitcoin)
{
// The ledger is native bitcoin, so units are Satoshis
FinancialTransaction ledgerTx = FinancialTransaction.Create (authData.CurrentOrganization,
DateTime.UtcNow, "Donation (bitcoin to hotwallet)");
ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.IncomeDonations, -satoshisReceived, authData.CurrentUser);
ledgerTx.AddRow (authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, satoshisReceived, authData.CurrentUser);
if (satoshisReceived % 100 == 0)
{
successMessage = string.Format (Resources.Pages.Financial.Donate_FundsReceivedNative,
(satoshisReceived/100.0).ToString ("N0"));
}
else
{
successMessage = string.Format(Resources.Pages.Financial.Donate_FundsReceivedNative,
(satoshisReceived / 100.0).ToString("N2"));
}
}
else
{
// The ledger is NOT native bitcoin, so we'll need to convert currencies
long nativeCents = moneyReceived.ToCurrency (authData.CurrentOrganization.Currency).Cents;
FinancialTransaction ledgerTx = FinancialTransaction.Create(authData.CurrentOrganization,
DateTime.UtcNow, "Donation (bitcoin to hotwallet)");
ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.IncomeDonations, -nativeCents, authData.CurrentUser);
ledgerTx.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, nativeCents, authData.CurrentUser);
}
return new AjaxCallResult() {DisplayMessage = successMessage, Success = true};
// TODO: Ack donation via mail?
// TODO: Notify CFO/etc of donation?
}
return new AjaxCallResult() {Success = false};
}
}
}