From fa13190595d591ecc4dee5aaf531acab0cfd65a0 Mon Sep 17 00:00:00 2001 From: Christian Decker Date: Fri, 1 Sep 2017 14:40:52 +0200 Subject: [PATCH] wallet: Hook into the hsm_funding_sig to extract change outputs This is the step where we broadcast the transaction to the network and a nice place to extract the change from the transaction. Signed-off-by: Christian Decker --- lightningd/peer_control.c | 4 ++++ tests/test_lightningd.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/lightningd/peer_control.c b/lightningd/peer_control.c index 82a91e368..812c88d5f 100644 --- a/lightningd/peer_control.c +++ b/lightningd/peer_control.c @@ -1378,6 +1378,7 @@ static void opening_got_hsm_funding_sig(struct funding_channel *fc, { secp256k1_ecdsa_signature *sigs; struct bitcoin_tx *tx = fc->funding_tx; + u64 change_satoshi; size_t i; if (!fromwire_hsmctl_sign_funding_reply(fc, resp, NULL, &sigs)) @@ -1407,6 +1408,9 @@ static void opening_got_hsm_funding_sig(struct funding_channel *fc, watch_tx(fc->peer, fc->peer->ld->topology, fc->peer, tx, funding_lockin_cb, NULL); + /* Extract the change output and add it to the DB */ + wallet_extract_owned_outputs(fc->peer->ld->wallet, tx, &change_satoshi); + /* FIXME: Remove arg from cb? */ watch_txo(fc->peer, fc->peer->ld->topology, fc->peer, fc->peer->funding_txid, fc->peer->funding_outnum, diff --git a/tests/test_lightningd.py b/tests/test_lightningd.py index 4f4736c89..149d78a15 100644 --- a/tests/test_lightningd.py +++ b/tests/test_lightningd.py @@ -1056,6 +1056,25 @@ class LightningDTests(BaseLightningDTests): c.execute('SELECT COUNT(*) FROM outputs WHERE status=2') assert(c.fetchone()[0] == 2) + def test_funding_change(self): + """Add some funds, fund a channel, and make sure we remember the change + """ + l1, l2 = self.connect() + addr = l1.rpc.newaddr()['address'] + txid = l1.bitcoin.rpc.sendtoaddress(addr, 0.1) + tx = l1.bitcoin.rpc.getrawtransaction(txid) + l1.rpc.addfunds(tx) + outputs = l1.db_query('SELECT value FROM outputs WHERE status=0;') + assert len(outputs) == 1 and outputs[0]['value'] == 10000000 + + l1.rpc.fundchannel(l2.info['id'], 1000000) + outputs = {r['status']: r['value'] for r in l1.db_query( + 'SELECT status, SUM(value) AS value FROM outputs GROUP BY status;')} + + # The 10m out is spent and we have a change output of 9m-fee + assert outputs[0] > 8990000 + assert outputs[2] == 10000000 + def test_channel_persistence(self): # Start two nodes and open a channel (to remember) l1, l2 = self.connect()