From 5affed38fce7074bc47512bd8900ef8d6b763cd3 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Thu, 5 Jan 2017 13:56:27 -0800 Subject: [PATCH] multi: update btcsuite API's to latest upstream changes This commit makes a large number of minor changes concerning API usage within the deamon to match the latest version on the upstream btcsuite libraries. The major changes are the switch from wire.ShaHash to chainhash.Hash, and that wire.NewMsgTx() now takes a paramter indicating the version of the transaction to be created. --- breacharbiter.go | 9 ++++---- chainntnfs/btcdnotify/btcd.go | 35 +++++++++++++++-------------- chainntnfs/interface.go | 9 ++++---- chainntnfs/interface_test.go | 17 +++++++------- channeldb/channel.go | 5 +++-- channeldb/channel_test.go | 11 ++++----- channeldb/graph.go | 7 +++--- channeldb/graph_test.go | 5 +++-- cmd/lncli/commands.go | 8 +++---- elkrem/elkrem.go | 28 +++++++++++------------ elkrem/elkrem_test.go | 6 ++--- elkrem/serdes.go | 6 ++--- fundingmanager.go | 3 ++- htlcswitch.go | 7 +++--- invoiceregistry.go | 18 +++++++-------- lnd_test.go | 28 ++++++++++++----------- lnwallet/btcwallet/blockchain.go | 11 ++++----- lnwallet/btcwallet/btcwallet.go | 7 +++--- lnwallet/channel.go | 18 +++++++-------- lnwallet/channel_test.go | 11 ++++----- lnwallet/interface.go | 17 +++++++------- lnwallet/interface_test.go | 25 +++++++++++---------- lnwallet/script_utils.go | 5 +++-- lnwallet/script_utils_test.go | 19 ++++++++-------- lnwallet/size.go | 2 +- lnwallet/wallet.go | 6 ++--- lnwire/channel_announcement.go | 8 +++---- lnwire/channel_announcement_test.go | 8 +++---- lnwire/lnwire.go | 11 ++++----- lnwire/lnwire_test.go | 9 ++++---- lnwire/node_announcement.go | 4 ++-- lnwire/node_announcement_test.go | 4 ++-- networktest.go | 29 ++++++++++++------------ peer.go | 11 ++++----- routing/pathfind_test.go | 3 ++- routing/router.go | 2 +- rpcserver.go | 15 +++++++------ shachain/shachain.go | 8 +++---- utxonursery.go | 3 +-- utxonursery_test.go | 7 +++--- 40 files changed, 234 insertions(+), 211 deletions(-) diff --git a/breacharbiter.go b/breacharbiter.go index 75c3b743..d76e3974 100644 --- a/breacharbiter.go +++ b/breacharbiter.go @@ -8,6 +8,7 @@ import ( "github.com/lightningnetwork/lnd/chainntnfs" "github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/lnwallet" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -292,7 +293,7 @@ func (b *breachArbiter) exactRetribution(confChan *chainntnfs.ConfirmationEvent, // dispatched once the justice tx is confirmed. After confirmation we // notify the caller that initiated the retribution work low that the // deed has been done. - justiceTXID := justiceTx.TxSha() + justiceTXID := justiceTx.TxHash() confChan, err = b.notifier.RegisterConfirmationsNtfn(&justiceTXID, 1) if err != nil { brarLog.Errorf("unable to register for conf for txid: %v", @@ -404,7 +405,7 @@ func (b *breachArbiter) breachObserver(contract *lnwallet.LightningChannel, // send the retribution information to the utxo nursery. // TODO(roasbeef): populate htlc breaches b.breachedContracts <- &retributionInfo{ - commitHash: breachInfo.BreachTransaction.TxSha(), + commitHash: breachInfo.BreachTransaction.TxHash(), chanPoint: *chanPoint, selfOutput: &breachedOutput{ @@ -444,7 +445,7 @@ type breachedOutput struct { // transaction which spends all outputs of the commitment transaction into an // output controlled by the wallet. type retributionInfo struct { - commitHash wire.ShaHash + commitHash chainhash.Hash chanPoint wire.OutPoint selfOutput *breachedOutput @@ -478,7 +479,7 @@ func (b *breachArbiter) createJusticeTx(r *retributionInfo) (*wire.MsgTx, error) // With the fee calculate, we can now create the justice transaction // using the information gathered above. - justiceTx := wire.NewMsgTx() + justiceTx := wire.NewMsgTx(2) justiceTx.AddTxOut(&wire.TxOut{ PkScript: pkScriptOfJustice, Value: sweepedAmt, diff --git a/chainntnfs/btcdnotify/btcd.go b/chainntnfs/btcdnotify/btcd.go index 18d41191..35c8d4fa 100644 --- a/chainntnfs/btcdnotify/btcd.go +++ b/chainntnfs/btcdnotify/btcd.go @@ -9,6 +9,7 @@ import ( "github.com/lightningnetwork/lnd/chainntnfs" "github.com/roasbeef/btcd/btcjson" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcrpcclient" "github.com/roasbeef/btcutil" @@ -30,7 +31,7 @@ var ( // used as an element within an unbounded queue in order to avoid blocking the // main rpc dispatch rule. type chainUpdate struct { - blockHash *wire.ShaHash + blockHash *chainhash.Hash blockHeight int32 } @@ -55,7 +56,7 @@ type BtcdNotifier struct { spendNotifications map[wire.OutPoint][]*spendNotification - confNotifications map[wire.ShaHash][]*confirmationsNotification + confNotifications map[chainhash.Hash][]*confirmationsNotification confHeap *confirmationHeap blockEpochClients []chan *chainntnfs.BlockEpoch @@ -85,7 +86,7 @@ func New(config *btcrpcclient.ConnConfig) (*BtcdNotifier, error) { notificationRegistry: make(chan interface{}), spendNotifications: make(map[wire.OutPoint][]*spendNotification), - confNotifications: make(map[wire.ShaHash][]*confirmationsNotification), + confNotifications: make(map[chainhash.Hash][]*confirmationsNotification), confHeap: newConfirmationHeap(), disconnectedBlockHashes: make(chan *blockNtfn, 20), @@ -180,14 +181,14 @@ func (b *BtcdNotifier) Stop() error { // blockNtfn packages a notification of a connected/disconnected block along // with its height at the time. type blockNtfn struct { - sha *wire.ShaHash + sha *chainhash.Hash height int32 } // onBlockConnected implements on OnBlockConnected callback for btcrpcclient. // Ingesting a block updates the wallet's internal utxo state based on the // outputs created and destroyed within each block. -func (b *BtcdNotifier) onBlockConnected(hash *wire.ShaHash, height int32, t time.Time) { +func (b *BtcdNotifier) onBlockConnected(hash *chainhash.Hash, height int32, t time.Time) { // Append this new chain update to the end of the queue of new chain // updates. b.chainUpdateMtx.Lock() @@ -203,7 +204,7 @@ func (b *BtcdNotifier) onBlockConnected(hash *wire.ShaHash, height int32, t time } // onBlockDisconnected implements on OnBlockDisconnected callback for btcrpcclient. -func (b *BtcdNotifier) onBlockDisconnected(hash *wire.ShaHash, height int32, t time.Time) { +func (b *BtcdNotifier) onBlockDisconnected(hash *chainhash.Hash, height int32, t time.Time) { } // onRedeemingTx implements on OnRedeemingTx callback for btcrpcclient. @@ -293,7 +294,7 @@ out: // notification on a heap to be triggered in // the future once additional confirmations are // attained. - txSha := tx.TxSha() + txSha := tx.TxHash() b.checkConfirmationTrigger(&txSha, update, i) } @@ -323,7 +324,7 @@ out: // summary, finally sending off the details to // the notification subscriber. if clients, ok := b.spendNotifications[prevOut]; ok { - spenderSha := newSpend.tx.Sha() + spenderSha := newSpend.tx.Hash() for _, ntfn := range clients { spendDetails := &chainntnfs.SpendDetail{ SpentOutPoint: ntfn.targetOutpoint, @@ -361,14 +362,14 @@ func (b *BtcdNotifier) attemptHistoricalDispatch(msg *confirmationsNotification, // If the transaction already has some or all of the confirmations, // then we may be able to dispatch it immediately. tx, err := b.chainConn.GetRawTransactionVerbose(msg.txid) - if err != nil || tx == nil { + if err != nil || tx == nil || tx.BlockHash == "" { return false } // As we need to fully populate the returned TxConfirmation struct, // grab the block in which the transaction was confirmed so we can // locate its exact index within the block. - blockHash, err := wire.NewShaHashFromStr(tx.BlockHash) + blockHash, err := chainhash.NewHashFromStr(tx.BlockHash) if err != nil { chainntnfs.Log.Errorf("unable to get block hash %v for "+ "historical dispatch: %v", tx.BlockHash, err) @@ -380,7 +381,7 @@ func (b *BtcdNotifier) attemptHistoricalDispatch(msg *confirmationsNotification, return false } - txHash, err := wire.NewShaHashFromStr(tx.Hash) + txHash, err := chainhash.NewHashFromStr(tx.Hash) if err != nil { chainntnfs.Log.Errorf("unable to convert to hash: %v", err) return false @@ -390,7 +391,7 @@ func (b *BtcdNotifier) attemptHistoricalDispatch(msg *confirmationsNotification, // block so we can give the subscriber full confirmation details. var txIndex uint32 for i, t := range block.Transactions { - h := t.TxSha() + h := t.TxHash() if txHash.IsEqual(&h) { txIndex = uint32(i) } @@ -426,7 +427,7 @@ func (b *BtcdNotifier) attemptHistoricalDispatch(msg *confirmationsNotification, // notifyBlockEpochs notifies all registered block epoch clients of the newly // connected block to the main chain. -func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32, newSha *wire.ShaHash) { +func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash) { epoch := &chainntnfs.BlockEpoch{ Height: newHeight, Hash: newSha, @@ -479,7 +480,7 @@ func (b *BtcdNotifier) notifyConfs(newBlockHeight int32) { // matches, yet needs additional confirmations, it is added to the confirmation // heap to be triggered at a later time. // TODO(roasbeef): perhaps lookup, then track by inputs instead? -func (b *BtcdNotifier) checkConfirmationTrigger(txSha *wire.ShaHash, +func (b *BtcdNotifier) checkConfirmationTrigger(txSha *chainhash.Hash, newTip *chainUpdate, txIndex int) { // If a confirmation notification has been registered @@ -573,7 +574,7 @@ func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint) (*chainntnfs.S return nil, err } - blockhash, err := wire.NewShaHashFromStr(transaction.BlockHash) + blockhash, err := chainhash.NewHashFromStr(transaction.BlockHash) if err != nil { return nil, err } @@ -591,7 +592,7 @@ func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint) (*chainntnfs.S // confirmationNotification represents a client's intent to receive a // notification once the target txid reaches numConfirmations confirmations. type confirmationsNotification struct { - txid *wire.ShaHash + txid *chainhash.Hash initialConfirmHeight uint32 numConfirmations uint32 @@ -603,7 +604,7 @@ type confirmationsNotification struct { // RegisterConfirmationsNotification registers a notification with BtcdNotifier // which will be triggered once the txid reaches numConfs number of // confirmations. -func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *wire.ShaHash, +func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash, numConfs uint32) (*chainntnfs.ConfirmationEvent, error) { ntfn := &confirmationsNotification{ diff --git a/chainntnfs/interface.go b/chainntnfs/interface.go index c68fc38c..580cb98b 100644 --- a/chainntnfs/interface.go +++ b/chainntnfs/interface.go @@ -4,6 +4,7 @@ import ( "fmt" "sync" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" ) @@ -26,7 +27,7 @@ type ChainNotifier interface { // // NOTE: Dispatching notifications to multiple clients subscribed to // the same (txid, numConfs) tuple MUST be supported. - RegisterConfirmationsNtfn(txid *wire.ShaHash, numConfs uint32) (*ConfirmationEvent, error) + RegisterConfirmationsNtfn(txid *chainhash.Hash, numConfs uint32) (*ConfirmationEvent, error) // RegisterSpendNtfn registers an intent to be notified once the target // outpoint is succesfully spent within a confirmed transaction. The @@ -62,7 +63,7 @@ type ChainNotifier interface { type TxConfirmation struct { // BlockHash is the hash of the block that confirmed the original // transition. - BlockHash *wire.ShaHash + BlockHash *chainhash.Hash // BlockHeight is the height of the block in which the transaction was // confirmed within. @@ -105,7 +106,7 @@ type ConfirmationEvent struct { // target output. type SpendDetail struct { SpentOutPoint *wire.OutPoint - SpenderTxHash *wire.ShaHash + SpenderTxHash *chainhash.Hash SpendingTx *wire.MsgTx SpenderInputIndex uint32 SpendingHeight int32 @@ -122,7 +123,7 @@ type SpendEvent struct { // main chain. type BlockEpoch struct { Height int32 - Hash *wire.ShaHash + Hash *chainhash.Hash } // BlockEpochEvent encapsulates an on-going stream of block epoch diff --git a/chainntnfs/interface_test.go b/chainntnfs/interface_test.go index f7562999..4bd9c909 100644 --- a/chainntnfs/interface_test.go +++ b/chainntnfs/interface_test.go @@ -9,6 +9,7 @@ import ( "github.com/lightningnetwork/lnd/chainntnfs" _ "github.com/lightningnetwork/lnd/chainntnfs/btcdnotify" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/btcec" "github.com/roasbeef/btcd/chaincfg" @@ -33,14 +34,14 @@ var ( testAddr = addrPk.AddressPubKeyHash() ) -func getTestTxId(miner *rpctest.Harness) (*wire.ShaHash, error) { +func getTestTxId(miner *rpctest.Harness) (*chainhash.Hash, error) { script, err := txscript.PayToAddrScript(testAddr) if err != nil { return nil, err } outputs := []*wire.TxOut{&wire.TxOut{2e8, script}} - return miner.CoinbaseSpend(outputs) + return miner.SendOutputs(outputs, 10) } func testSingleConfirmationNotification(miner *rpctest.Harness, @@ -246,7 +247,7 @@ func testSpendNotification(miner *rpctest.Harness, } // Next, create a new transaction spending that output. - spendingTx := wire.NewMsgTx() + spendingTx := wire.NewMsgTx(1) spendingTx.AddTxIn(&wire.TxIn{ PreviousOutPoint: *outpoint, }) @@ -293,10 +294,10 @@ func testSpendNotification(miner *rpctest.Harness, "%v instead of %v", ntfn.SpentOutPoint, outpoint) } - if !bytes.Equal(ntfn.SpenderTxHash.Bytes(), spenderSha.Bytes()) { + if !bytes.Equal(ntfn.SpenderTxHash[:], spenderSha[:]) { t.Fatalf("ntfn includes wrong spender tx sha, "+ "reports %v intead of %v", - ntfn.SpenderTxHash.Bytes(), spenderSha.Bytes()) + ntfn.SpenderTxHash[:], spenderSha[:]) } if ntfn.SpenderInputIndex != 0 { t.Fatalf("ntfn includes wrong spending input "+ @@ -549,7 +550,7 @@ func testSpendBeforeNtfnRegistration(miner *rpctest.Harness, outpoint := wire.NewOutPoint(txid, uint32(outIndex)) // Next, create a new transaction spending that output. - spendingTx := wire.NewMsgTx() + spendingTx := wire.NewMsgTx(1) spendingTx.AddTxIn(&wire.TxIn{ PreviousOutPoint: *outpoint, }) @@ -596,9 +597,9 @@ func testSpendBeforeNtfnRegistration(miner *rpctest.Harness, t.Fatalf("ntfn includes wrong output, reports %v instead of %v", ntfn.SpentOutPoint, outpoint) } - if !bytes.Equal(ntfn.SpenderTxHash.Bytes(), spenderSha.Bytes()) { + if !bytes.Equal(ntfn.SpenderTxHash[:], spenderSha[:]) { t.Fatalf("ntfn includes wrong spender tx sha, reports %v intead of %v", - ntfn.SpenderTxHash.Bytes(), spenderSha.Bytes()) + ntfn.SpenderTxHash[:], spenderSha[:]) } if ntfn.SpenderInputIndex != 0 { t.Fatalf("ntfn includes wrong spending input index, reports %v, should be %v", diff --git a/channeldb/channel.go b/channeldb/channel.go index 67680777..c7a0530d 100644 --- a/channeldb/channel.go +++ b/channeldb/channel.go @@ -11,6 +11,7 @@ import ( "github.com/boltdb/bolt" "github.com/lightningnetwork/lnd/elkrem" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" ) @@ -1274,7 +1275,7 @@ func fetchChanCommitTxns(nodeChanBucket *bolt.Bucket, channel *OpenChannel) erro txnBytes := bytes.NewReader(nodeChanBucket.Get(txnsKey)) - channel.OurCommitTx = wire.NewMsgTx() + channel.OurCommitTx = wire.NewMsgTx(2) if err = channel.OurCommitTx.Deserialize(txnBytes); err != nil { return err } @@ -1502,7 +1503,7 @@ func fetchChanElkremState(nodeChanBucket *bolt.Bucket, channel *OpenChannel) err if err != nil { return err } - elkremRoot, err := wire.NewShaHash(senderBytes) + elkremRoot, err := chainhash.NewHash(senderBytes) if err != nil { return err } diff --git a/channeldb/channel_test.go b/channeldb/channel_test.go index 49d823a7..adc8f9d9 100644 --- a/channeldb/channel_test.go +++ b/channeldb/channel_test.go @@ -12,6 +12,7 @@ import ( "github.com/lightningnetwork/lnd/elkrem" "github.com/roasbeef/btcd/btcec" "github.com/roasbeef/btcd/chaincfg" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -19,16 +20,16 @@ import ( ) var ( - netParams = &chaincfg.SegNet4Params + netParams = &chaincfg.TestNet3Params - key = [wire.HashSize]byte{ + key = [chainhash.HashSize]byte{ 0x81, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda, 0x68, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17, 0xd, 0xe7, 0x93, 0xe4, 0xb7, 0x25, 0xb8, 0x4d, 0x1e, 0xb, 0x4c, 0xf9, 0x9e, 0xc5, 0x8c, 0xe9, } id = &wire.OutPoint{ - Hash: [wire.HashSize]byte{ + Hash: [chainhash.HashSize]byte{ 0x51, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda, 0x48, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17, 0x2d, 0xe7, 0x93, 0xe4, 0xb7, 0x25, 0xb8, 0x4d, @@ -36,7 +37,7 @@ var ( }, Index: 9, } - rev = [wire.HashSize]byte{ + rev = [chainhash.HashSize]byte{ 0x51, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda, 0x48, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17, 0x2d, 0xe7, 0x93, 0xe4, @@ -46,7 +47,7 @@ var ( TxIn: []*wire.TxIn{ &wire.TxIn{ PreviousOutPoint: wire.OutPoint{ - Hash: wire.ShaHash{}, + Hash: chainhash.Hash{}, Index: 0xffffffff, }, SignatureScript: []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62}, diff --git a/channeldb/graph.go b/channeldb/graph.go index 1940ddb6..ed30be0b 100644 --- a/channeldb/graph.go +++ b/channeldb/graph.go @@ -10,6 +10,7 @@ import ( "github.com/boltdb/bolt" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" ) @@ -505,7 +506,7 @@ const ( // with the current UTXO state. An integer is returned which reflects the // number of channels pruned due to the new incoming block. func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint, - blockHash *wire.ShaHash, blockHeight uint32) (uint32, error) { + blockHash *chainhash.Hash, blockHeight uint32) (uint32, error) { var numChans uint32 @@ -572,10 +573,10 @@ func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint, // used to prune channels in the graph. Knowing the "prune tip" allows callers // to tell if the graph is currently in sync with the current best known UTXO // state. -func (c *ChannelGraph) PruneTip() (*wire.ShaHash, uint32, error) { +func (c *ChannelGraph) PruneTip() (*chainhash.Hash, uint32, error) { var ( currentTip [pruneTipBytes]byte - tipHash wire.ShaHash + tipHash chainhash.Hash tipHeight uint32 ) diff --git a/channeldb/graph_test.go b/channeldb/graph_test.go index 66646b1a..277cb686 100644 --- a/channeldb/graph_test.go +++ b/channeldb/graph_test.go @@ -13,6 +13,7 @@ import ( "github.com/btcsuite/fastsha256" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" ) @@ -524,7 +525,7 @@ func TestGraphTraversal(t *testing.T) { } } -func assertPruneTip(t *testing.T, graph *ChannelGraph, blockHash *wire.ShaHash, +func assertPruneTip(t *testing.T, graph *ChannelGraph, blockHash *chainhash.Hash, blockHeight uint32) { pruneHash, pruneHeight, err := graph.PruneTip() @@ -629,7 +630,7 @@ func TestGraphPruning(t *testing.T) { // First we create a mock block that ends up closing the first two // channels. - var blockHash wire.ShaHash + var blockHash chainhash.Hash copy(blockHash[:], bytes.Repeat([]byte{1}, 32)) blockHeight := uint32(1) block := channelPoints[:2] diff --git a/cmd/lncli/commands.go b/cmd/lncli/commands.go index cc8f2918..d40412a1 100644 --- a/cmd/lncli/commands.go +++ b/cmd/lncli/commands.go @@ -10,7 +10,7 @@ import ( "strings" "github.com/lightningnetwork/lnd/lnrpc" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/urfave/cli" "golang.org/x/net/context" ) @@ -250,7 +250,7 @@ func openChannel(ctx *cli.Context) error { switch update := resp.Update.(type) { case *lnrpc.OpenStatusUpdate_ChanOpen: channelPoint := update.ChanOpen.ChannelPoint - txid, err := wire.NewShaHash(channelPoint.FundingTxid) + txid, err := chainhash.NewHash(channelPoint.FundingTxid) if err != nil { return err } @@ -306,7 +306,7 @@ func closeChannel(ctx *cli.Context) error { ctxb := context.Background() client := getClient(ctx) - txid, err := wire.NewShaHashFromStr(ctx.String("funding_txid")) + txid, err := chainhash.NewHashFromStr(ctx.String("funding_txid")) if err != nil { return err } @@ -340,7 +340,7 @@ func closeChannel(ctx *cli.Context) error { switch update := resp.Update.(type) { case *lnrpc.CloseStatusUpdate_ChanClose: closingHash := update.ChanClose.ClosingTxid - txid, err := wire.NewShaHash(closingHash) + txid, err := chainhash.NewHash(closingHash) if err != nil { return err } diff --git a/elkrem/elkrem.go b/elkrem/elkrem.go index 990b14bc..53b20da7 100644 --- a/elkrem/elkrem.go +++ b/elkrem/elkrem.go @@ -3,7 +3,7 @@ package elkrem import ( "fmt" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" ) /* elkrem is a simpler alternative to the 64 dimensional sha-chain. @@ -39,27 +39,27 @@ const maxHeight = uint8(47) // You can calculate h from i but I can't figure out how without taking // O(i) ops. Feels like there should be a clever O(h) way. 1 byte, whatever. type ElkremNode struct { - h uint8 // height of this node - i uint64 // index (i'th node) - sha *wire.ShaHash // hash + h uint8 // height of this node + i uint64 // index (i'th node) + sha *chainhash.Hash // hash } type ElkremSender struct { - root *wire.ShaHash // root hash of the tree + root *chainhash.Hash // root hash of the tree } type ElkremReceiver struct { s []ElkremNode // store of received hashes } -func LeftSha(in wire.ShaHash) wire.ShaHash { - return wire.DoubleSha256SH(in.Bytes()) // left is sha(sha(in)) +func LeftSha(in chainhash.Hash) chainhash.Hash { + return chainhash.DoubleHashH(in[:]) // left is sha(sha(in)) } -func RightSha(in wire.ShaHash) wire.ShaHash { - return wire.DoubleSha256SH(append(in.Bytes(), 0x01)) // sha(sha(in, 1)) +func RightSha(in chainhash.Hash) chainhash.Hash { + return chainhash.DoubleHashH(append(in[:], 0x01)) // sha(sha(in, 1)) } // iterative descent of sub-tree. w = hash number you want. i = input index // h = height of input index. sha = input hash -func descend(w, i uint64, h uint8, sha wire.ShaHash) (wire.ShaHash, error) { +func descend(w, i uint64, h uint8, sha chainhash.Hash) (chainhash.Hash, error) { for w < i { if w <= i-(1<= cfg.MaxPendingChannels { errMsg := &lnwire.ErrorGeneric{ ChannelPoint: &wire.OutPoint{ - Hash: wire.ShaHash{}, + Hash: chainhash.Hash{}, Index: 0, }, Problem: "Number of pending channels exceed maximum", diff --git a/htlcswitch.go b/htlcswitch.go index 0bf3f13b..85a14a3d 100644 --- a/htlcswitch.go +++ b/htlcswitch.go @@ -14,6 +14,7 @@ import ( "github.com/lightningnetwork/lnd/lnrpc" "github.com/lightningnetwork/lnd/lnwire" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" "golang.org/x/crypto/ripemd160" @@ -48,7 +49,7 @@ type link struct { type htlcPacket struct { sync.RWMutex - dest wire.ShaHash + dest chainhash.Hash index uint32 srcLink wire.OutPoint @@ -120,7 +121,7 @@ type htlcSwitch struct { // currently have open with that peer. // TODO(roasbeef): combine w/ onionIndex? interfaceMtx sync.RWMutex - interfaces map[wire.ShaHash][]*link + interfaces map[chainhash.Hash][]*link // onionIndex is an index used to properly forward a message // to the next hop within a Sphinx circuit. Within the sphinx packets, @@ -159,7 +160,7 @@ type htlcSwitch struct { func newHtlcSwitch() *htlcSwitch { return &htlcSwitch{ chanIndex: make(map[wire.OutPoint]*link), - interfaces: make(map[wire.ShaHash][]*link), + interfaces: make(map[chainhash.Hash][]*link), onionIndex: make(map[[ripemd160.Size]byte][]*link), paymentCircuits: make(map[circuitKey]*paymentCircuit), linkControl: make(chan interface{}), diff --git a/invoiceregistry.go b/invoiceregistry.go index 90b6913d..89dfbdae 100644 --- a/invoiceregistry.go +++ b/invoiceregistry.go @@ -8,7 +8,7 @@ import ( "github.com/btcsuite/fastsha256" "github.com/davecgh/go-spew/spew" "github.com/lightningnetwork/lnd/channeldb" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcutil" ) @@ -18,9 +18,9 @@ var ( // All nodes initialize with the flag active will immediately settle // any incoming HTLC whose rHash is corresponds with the debug // preimage. - debugPre, _ = wire.NewShaHash(bytes.Repeat([]byte{1}, 32)) + debugPre, _ = chainhash.NewHash(bytes.Repeat([]byte{1}, 32)) - debugHash = wire.ShaHash(fastsha256.Sum256(debugPre[:])) + debugHash = chainhash.Hash(fastsha256.Sum256(debugPre[:])) ) // invoiceRegistry is a central registry of all the outstanding invoices @@ -38,7 +38,7 @@ type invoiceRegistry struct { // debugInvoices is a mp which stores special "debug" invoices which // should be only created/used when manual tests require an invoice // that *all* nodes are able to fully settle. - debugInvoices map[wire.ShaHash]*channeldb.Invoice + debugInvoices map[chainhash.Hash]*channeldb.Invoice } // newInvoiceRegistry creates a new invoice registry. The invoice registry @@ -48,7 +48,7 @@ type invoiceRegistry struct { func newInvoiceRegistry(cdb *channeldb.DB) *invoiceRegistry { return &invoiceRegistry{ cdb: cdb, - debugInvoices: make(map[wire.ShaHash]*channeldb.Invoice), + debugInvoices: make(map[chainhash.Hash]*channeldb.Invoice), notificationClients: make(map[uint32]*invoiceSubscription), } } @@ -57,8 +57,8 @@ func newInvoiceRegistry(cdb *channeldb.DB) *invoiceRegistry { // by the passed preimage. Once this invoice is added, sub-systems within the // daemon add/forward HTLC's are able to obtain the proper preimage required // for redemption in the case that we're the final destination. -func (i *invoiceRegistry) AddDebugInvoice(amt btcutil.Amount, preimage wire.ShaHash) { - paymentHash := wire.ShaHash(fastsha256.Sum256(preimage[:])) +func (i *invoiceRegistry) AddDebugInvoice(amt btcutil.Amount, preimage chainhash.Hash) { + paymentHash := chainhash.Hash(fastsha256.Sum256(preimage[:])) invoice := &channeldb.Invoice{ CreationDate: time.Now(), @@ -101,7 +101,7 @@ func (i *invoiceRegistry) AddInvoice(invoice *channeldb.Invoice) error { // lookupInvoice looks up an invoice by it's payment hash (R-Hash), if found // then we're able to pull the funds pending within an HTLC. // TODO(roasbeef): ignore if settled? -func (i *invoiceRegistry) LookupInvoice(rHash wire.ShaHash) (*channeldb.Invoice, error) { +func (i *invoiceRegistry) LookupInvoice(rHash chainhash.Hash) (*channeldb.Invoice, error) { // First check the in-memory debug invoice index to see if this is an // existing invoice added for debugging. i.RLock() @@ -121,7 +121,7 @@ func (i *invoiceRegistry) LookupInvoice(rHash wire.ShaHash) (*channeldb.Invoice, // SettleInvoice attempts to mark an invoice as settled. If the invoice is a // dbueg invoice, then this method is a nooop as debug invoices are never fully // settled. -func (i *invoiceRegistry) SettleInvoice(rHash wire.ShaHash) error { +func (i *invoiceRegistry) SettleInvoice(rHash chainhash.Hash) error { ltndLog.Debugf("Settling invoice %x", rHash[:]) // First check the in-memory debug invoice index to see if this is an diff --git a/lnd_test.go b/lnd_test.go index 7fe7ca3b..6f3f8c24 100644 --- a/lnd_test.go +++ b/lnd_test.go @@ -20,6 +20,8 @@ import ( "github.com/go-errors/errors" "github.com/lightningnetwork/lnd/lnrpc" "github.com/lightningnetwork/lnd/lnwire" + "github.com/roasbeef/btcd/chaincfg" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/rpctest" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcrpcclient" @@ -89,9 +91,9 @@ func (h *harnessTest) Log(args ...interface{}) { h.t.Log(args...) } -func assertTxInBlock(t *harnessTest, block *wire.MsgBlock, txid *wire.ShaHash) { +func assertTxInBlock(t *harnessTest, block *wire.MsgBlock, txid *chainhash.Hash) { for _, tx := range block.Transactions { - sha := tx.TxSha() + sha := tx.TxHash() if bytes.Equal(txid[:], sha[:]) { return } @@ -144,7 +146,7 @@ func openChannelAndAssert(t *harnessTest, net *networkHarness, ctx context.Conte if err != nil { t.Fatalf("error while waiting for channel open: %v", err) } - fundingTxID, err := wire.NewShaHash(fundingChanPoint.FundingTxid) + fundingTxID, err := chainhash.NewHash(fundingChanPoint.FundingTxid) if err != nil { t.Fatalf("unable to create sha hash: %v", err) } @@ -170,7 +172,7 @@ func openChannelAndAssert(t *harnessTest, net *networkHarness, ctx context.Conte // detected as closed, an assertion checks that the transaction is found within // a block. func closeChannelAndAssert(t *harnessTest, net *networkHarness, ctx context.Context, - node *lightningNode, fundingChanPoint *lnrpc.ChannelPoint, force bool) *wire.ShaHash { + node *lightningNode, fundingChanPoint *lnrpc.ChannelPoint, force bool) *chainhash.Hash { closeUpdates, _, err := net.CloseChannel(ctx, node, fundingChanPoint, force) if err != nil { @@ -371,8 +373,8 @@ func testChannelForceClosure(net *networkHarness, t *harnessTest) { // At this point, the sweeping transaction should now be broadcast. So // we fetch the node's mempool to ensure it has been properly // broadcast. - var sweepingTXID *wire.ShaHash - var mempool []*wire.ShaHash + var sweepingTXID *chainhash.Hash + var mempool []*chainhash.Hash mempoolTimeout := time.After(3 * time.Second) checkMempoolTick := time.Tick(100 * time.Millisecond) mempoolPoll: @@ -427,7 +429,7 @@ mempoolPoll: t.Fatalf("unable to get block: %v", err) } - assertTxInBlock(t, block, sweepTx.Sha()) + assertTxInBlock(t, block, sweepTx.Hash()) } func testSingleHopInvoice(net *networkHarness, t *harnessTest) { @@ -672,7 +674,7 @@ func testMultiHopPayments(net *networkHarness, t *harnessTest) { chanPointAlice := openChannelAndAssert(t, net, ctxt, net.Alice, net.Bob, chanAmt) - aliceChanTXID, err := wire.NewShaHash(chanPointAlice.FundingTxid) + aliceChanTXID, err := chainhash.NewHash(chanPointAlice.FundingTxid) if err != nil { t.Fatalf("unable to create sha hash: %v", err) } @@ -701,7 +703,7 @@ func testMultiHopPayments(net *networkHarness, t *harnessTest) { chanPointCarol := openChannelAndAssert(t, net, ctxt, carol, net.Alice, chanAmt) - carolChanTXID, err := wire.NewShaHash(chanPointCarol.FundingTxid) + carolChanTXID, err := chainhash.NewHash(chanPointCarol.FundingTxid) if err != nil { t.Fatalf("unable to create sha hash: %v", err) } @@ -1079,7 +1081,7 @@ func testMaxPendingChannels(net *networkHarness, t *harnessTest) { t.Fatalf("error while waiting for channel open: %v", err) } - fundingTxID, err := wire.NewShaHash(fundingChanPoint.FundingTxid) + fundingTxID, err := chainhash.NewHash(fundingChanPoint.FundingTxid) if err != nil { t.Fatalf("unable to create sha hash: %v", err) } @@ -1282,7 +1284,7 @@ func testRevokedCloseRetribution(net *networkHarness, t *harnessTest) { // Query the mempool for Alice's justice transaction, this should be // broadcast as Bob's contract breaching transaction gets confirmed // above. - var justiceTXID *wire.ShaHash + var justiceTXID *chainhash.Hash breakTimeout := time.After(time.Second * 5) poll: for { @@ -1328,8 +1330,8 @@ poll: if len(block.Transactions) != 2 { t.Fatalf("transaction wasn't mined") } - justiceSha := block.Transactions[1].TxSha() - if !bytes.Equal(justiceTx.Sha()[:], justiceSha[:]) { + justiceSha := block.Transactions[1].TxHash() + if !bytes.Equal(justiceTx.Hash()[:], justiceSha[:]) { t.Fatalf("justice tx wasn't mined") } diff --git a/lnwallet/btcwallet/blockchain.go b/lnwallet/btcwallet/blockchain.go index 27b64e83..f19ed9d2 100644 --- a/lnwallet/btcwallet/blockchain.go +++ b/lnwallet/btcwallet/blockchain.go @@ -5,6 +5,7 @@ import ( "errors" "github.com/lightningnetwork/lnd/lnwallet" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" ) @@ -18,14 +19,14 @@ var ( // within the main chain. // // This method is a part of the lnwallet.BlockChainIO interface. -func (b *BtcWallet) GetBestBlock() (*wire.ShaHash, int32, error) { +func (b *BtcWallet) GetBestBlock() (*chainhash.Hash, int32, error) { return b.rpc.GetBestBlock() } // GetTxOut returns the original output referenced by the passed outpoint. // // This method is a part of the lnwallet.BlockChainIO interface. -func (b *BtcWallet) GetUtxo(txid *wire.ShaHash, index uint32) (*wire.TxOut, error) { +func (b *BtcWallet) GetUtxo(txid *chainhash.Hash, index uint32) (*wire.TxOut, error) { txout, err := b.rpc.GetTxOut(txid, index, false) if err != nil { return nil, err @@ -50,7 +51,7 @@ func (b *BtcWallet) GetUtxo(txid *wire.ShaHash, index uint32) (*wire.TxOut, erro // transaction ID. // // This method is a part of the lnwallet.BlockChainIO interface. -func (b *BtcWallet) GetTransaction(txid *wire.ShaHash) (*wire.MsgTx, error) { +func (b *BtcWallet) GetTransaction(txid *chainhash.Hash) (*wire.MsgTx, error) { tx, err := b.rpc.GetRawTransaction(txid) if err != nil { return nil, err @@ -62,7 +63,7 @@ func (b *BtcWallet) GetTransaction(txid *wire.ShaHash) (*wire.MsgTx, error) { // GetBlock returns a raw block from the server given its hash. // // This method is a part of the lnwallet.BlockChainIO interface. -func (b *BtcWallet) GetBlock(blockHash *wire.ShaHash) (*wire.MsgBlock, error) { +func (b *BtcWallet) GetBlock(blockHash *chainhash.Hash) (*wire.MsgBlock, error) { block, err := b.rpc.GetBlock(blockHash) if err != nil { return nil, err @@ -75,7 +76,7 @@ func (b *BtcWallet) GetBlock(blockHash *wire.ShaHash) (*wire.MsgBlock, error) { // given height. // // This method is a part of the lnwallet.BlockChainIO interface. -func (b *BtcWallet) GetBlockHash(blockHeight int64) (*wire.ShaHash, error) { +func (b *BtcWallet) GetBlockHash(blockHeight int64) (*chainhash.Hash, error) { blockHash, err := b.rpc.GetBlockHash(blockHeight) if err != nil { return nil, err diff --git a/lnwallet/btcwallet/btcwallet.go b/lnwallet/btcwallet/btcwallet.go index e41d5fb8..db6fe3db 100644 --- a/lnwallet/btcwallet/btcwallet.go +++ b/lnwallet/btcwallet/btcwallet.go @@ -11,6 +11,7 @@ import ( "github.com/lightningnetwork/lnd/lnwallet" "github.com/roasbeef/btcd/btcec" "github.com/roasbeef/btcd/chaincfg" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -308,7 +309,7 @@ func (b *BtcWallet) FetchRootKey() (*btcec.PrivateKey, error) { // outputs are non-standard, a non-nil error will be be returned. // // This is a part of the WalletController interface. -func (b *BtcWallet) SendOutputs(outputs []*wire.TxOut) (*wire.ShaHash, error) { +func (b *BtcWallet) SendOutputs(outputs []*wire.TxOut) (*chainhash.Hash, error) { return b.wallet.SendOutputs(outputs, defaultAccount, 1) } @@ -355,7 +356,7 @@ func (b *BtcWallet) ListUnspentWitness(minConfs int32) ([]*lnwallet.Utxo, error) // the wallet are nested p2sh... if txscript.IsPayToWitnessPubKeyHash(pkScript) || txscript.IsPayToScriptHash(pkScript) { - txid, err := wire.NewShaHashFromStr(output.TxID) + txid, err := chainhash.NewHashFromStr(output.TxID) if err != nil { return nil, err } @@ -384,7 +385,7 @@ func (b *BtcWallet) PublishTransaction(tx *wire.MsgTx) error { // extractBalanceDelta extracts the net balance delta from the PoV of the // wallet given a TransactionSummary. func extractBalanceDelta(txSummary base.TransactionSummary) (btcutil.Amount, error) { - tx := wire.NewMsgTx() + tx := wire.NewMsgTx(1) txReader := bytes.NewReader(txSummary.Transaction) if err := tx.Deserialize(txReader); err != nil { return -1, nil diff --git a/lnwallet/channel.go b/lnwallet/channel.go index b7747ff2..dc62f4d5 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -11,6 +11,7 @@ import ( "github.com/lightningnetwork/lnd/chainntnfs" "github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/lnwire" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/btcec" "github.com/roasbeef/btcd/txscript" @@ -19,7 +20,7 @@ import ( "github.com/roasbeef/btcutil/txsort" ) -var zeroHash wire.ShaHash +var zeroHash chainhash.Hash var ( ErrChanClosing = fmt.Errorf("channel is being closed, operation disallowed") @@ -584,7 +585,7 @@ type BreachRetribution struct { func newBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64, broadcastCommitment *wire.MsgTx) (*BreachRetribution, error) { - commitHash := broadcastCommitment.TxSha() + commitHash := broadcastCommitment.TxHash() // Query the on-disk revocation log for the snapshot which was recorded // at this particular state num. @@ -1408,7 +1409,7 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.CommitRevocation) ( ourCommitKey := lc.channelState.OurCommitKey currentRevocationKey := lc.channelState.TheirCurrentRevocation - pendingRevocation := wire.ShaHash(revMsg.Revocation) + pendingRevocation := chainhash.Hash(revMsg.Revocation) // Ensure the new pre-image fits in properly within the elkrem receiver // tree. If this fails, then all other checks are skipped. @@ -1929,7 +1930,7 @@ func (lc *LightningChannel) ForceClose() (*ForceCloseSummary, error) { return &ForceCloseSummary{ CloseTx: commitTx, SelfOutpoint: wire.OutPoint{ - Hash: commitTx.TxSha(), + Hash: commitTx.TxHash(), Index: delayIndex, }, SelfOutputMaturity: csvTimeout, @@ -1951,7 +1952,7 @@ func (lc *LightningChannel) ForceClose() (*ForceCloseSummary, error) { // // TODO(roasbeef): caller should initiate signal to reject all incoming HTLCs, // settle any inflight. -func (lc *LightningChannel) InitCooperativeClose() ([]byte, *wire.ShaHash, error) { +func (lc *LightningChannel) InitCooperativeClose() ([]byte, *chainhash.Hash, error) { lc.Lock() defer lc.Unlock() @@ -1969,7 +1970,7 @@ func (lc *LightningChannel) InitCooperativeClose() ([]byte, *wire.ShaHash, error lc.channelState.OurBalance, lc.channelState.TheirBalance, lc.channelState.OurDeliveryScript, lc.channelState.TheirDeliveryScript, lc.channelState.IsInitiator) - closeTxSha := closeTx.TxSha() + closeTxSha := closeTx.TxHash() // Finally, sign the completed cooperative closure transaction. As the // initiator we'll simply send our signature over the the remote party, @@ -2095,8 +2096,7 @@ func CreateCommitTx(fundingOutput *wire.TxIn, selfKey, theirKey *btcec.PublicKey // Now that both output scripts have been created, we can finally create // the transaction itself. We use a transaction version of 2 since CSV // will fail unless the tx version is >= 2. - commitTx := wire.NewMsgTx() - commitTx.Version = 2 + commitTx := wire.NewMsgTx(2) commitTx.AddTxIn(fundingOutput) // Avoid creating zero value outputs within the commitment transaction. @@ -2125,7 +2125,7 @@ func CreateCooperativeCloseTx(fundingTxIn *wire.TxIn, // channel. In the event that one side doesn't have any settled funds // within the channel then a refund output for that particular side can // be omitted. - closeTx := wire.NewMsgTx() + closeTx := wire.NewMsgTx(2) closeTx.AddTxIn(fundingTxIn) // The initiator the a cooperative closure pays the fee in entirety. diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 61314333..fca83d85 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -16,6 +16,7 @@ import ( "github.com/lightningnetwork/lnd/lnwire" "github.com/roasbeef/btcd/blockchain" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -87,7 +88,7 @@ func (m *mockSigner) ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor type mockNotfier struct { } -func (m *mockNotfier) RegisterConfirmationsNtfn(txid *wire.ShaHash, numConfs uint32) (*chainntnfs.ConfirmationEvent, error) { +func (m *mockNotfier) RegisterConfirmationsNtfn(txid *chainhash.Hash, numConfs uint32) (*chainntnfs.ConfirmationEvent, error) { return nil, nil } func (m *mockNotfier) RegisterBlockEpochNtfn() (*chainntnfs.BlockEpochEvent, error) { @@ -199,7 +200,7 @@ func createTestChannels(revocationWindow int) (*LightningChannel, *LightningChan } prevOut := &wire.OutPoint{ - Hash: wire.ShaHash(testHdSeed), + Hash: chainhash.Hash(testHdSeed), Index: 0, } fundingTxIn := wire.NewTxIn(prevOut, nil, nil) @@ -614,7 +615,7 @@ func TestCheckCommitTxSize(t *testing.T) { t.Fatalf("unable to initiate alice force close: %v", err) } - actualCost := blockchain.GetMsgTxCost(commitTx) + actualCost := blockchain.GetTransactionWeight(btcutil.NewTx(commitTx)) estimatedCost := estimateCommitTxCost(count, false) diff := int(estimatedCost - actualCost) @@ -709,7 +710,7 @@ func TestCooperativeChannelClosure(t *testing.T) { if err != nil { t.Fatalf("unable to complete alice cooperative close: %v", err) } - bobCloseSha := closeTx.TxSha() + bobCloseSha := closeTx.TxHash() if !bobCloseSha.IsEqual(txid) { t.Fatalf("alice's transactions doesn't match: %x vs %x", bobCloseSha[:], txid[:]) @@ -729,7 +730,7 @@ func TestCooperativeChannelClosure(t *testing.T) { if err != nil { t.Fatalf("unable to complete bob cooperative close: %v", err) } - aliceCloseSha := closeTx.TxSha() + aliceCloseSha := closeTx.TxHash() if !aliceCloseSha.IsEqual(txid) { t.Fatalf("bob's closure transactions don't match: %x vs %x", aliceCloseSha[:], txid[:]) diff --git a/lnwallet/interface.go b/lnwallet/interface.go index eba2882d..2725194c 100644 --- a/lnwallet/interface.go +++ b/lnwallet/interface.go @@ -6,6 +6,7 @@ import ( "sync" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -42,7 +43,7 @@ type Utxo struct { // the wallet, or has outputs that pay to the wallet. type TransactionDetail struct { // Hash is the transaction hash of the transaction. - Hash wire.ShaHash + Hash chainhash.Hash // Value is the net value of this transaction (in satoshis) from the // PoV of the wallet. If this transaction purely spends from the @@ -58,7 +59,7 @@ type TransactionDetail struct { // BlockHeight is the hash of the block which includes this // transaction. Unconfirmed transactions will have a nil value for this // field. - BlockHash *wire.ShaHash + BlockHash *chainhash.Hash // BlockHeight is the height of the block including this transaction. // Unconfirmed transaction will show a height of zero. @@ -142,7 +143,7 @@ type WalletController interface { // paying out to the specified outputs. In the case the wallet has // insufficient funds, or the outputs are non-standard, an error // should be returned. - SendOutputs(outputs []*wire.TxOut) (*wire.ShaHash, error) + SendOutputs(outputs []*wire.TxOut) (*chainhash.Hash, error) // ListUnspentWitness returns all unspent outputs which are version 0 // witness programs. The 'confirms' parameter indicates the minimum @@ -203,23 +204,23 @@ type WalletController interface { type BlockChainIO interface { // GetBestBlock returns the current height and block hash of the valid // most-work chain the implementation is aware of. - GetBestBlock() (*wire.ShaHash, int32, error) + GetBestBlock() (*chainhash.Hash, int32, error) // GetTxOut returns the original output referenced by the passed // outpoint. - GetUtxo(txid *wire.ShaHash, index uint32) (*wire.TxOut, error) + GetUtxo(txid *chainhash.Hash, index uint32) (*wire.TxOut, error) // GetTransaction returns the full transaction identified by the passed // transaction ID. - GetTransaction(txid *wire.ShaHash) (*wire.MsgTx, error) + GetTransaction(txid *chainhash.Hash) (*wire.MsgTx, error) // GetBlockHash returns the hash of the block in the best block chain // at the given height. - GetBlockHash(blockHeight int64) (*wire.ShaHash, error) + GetBlockHash(blockHeight int64) (*chainhash.Hash, error) // GetBlock returns the block in the main chain identified by the given // hash. - GetBlock(blockHash *wire.ShaHash) (*wire.MsgBlock, error) + GetBlock(blockHash *chainhash.Hash) (*wire.MsgBlock, error) } // SignDescriptor houses the necessary information required to successfully sign diff --git a/lnwallet/interface_test.go b/lnwallet/interface_test.go index 5964c2c1..00e7dd72 100644 --- a/lnwallet/interface_test.go +++ b/lnwallet/interface_test.go @@ -18,6 +18,7 @@ import ( "github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/lnwallet/btcwallet" "github.com/roasbeef/btcd/chaincfg" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcutil/txsort" _ "github.com/roasbeef/btcwallet/walletdb/bdb" @@ -209,7 +210,7 @@ func newBobNode(miner *rpctest.Harness, amt btcutil.Amount) (*bobNode, error) { // Give bobNode one 7 BTC output for use in creating channels. output := &wire.TxOut{7e8, bobAddrScript} - mainTxid, err := miner.CoinbaseSpend([]*wire.TxOut{output}) + mainTxid, err := miner.SendOutputs([]*wire.TxOut{output}, 10) if err != nil { return nil, err } @@ -247,7 +248,7 @@ func newBobNode(miner *rpctest.Harness, amt btcutil.Amount) (*bobNode, error) { copy(obsfucator[:], revocation[:]) // His ID is just as creative... - var id [wire.HashSize]byte + var id [chainhash.HashSize]byte id[0] = 0xff return &bobNode{ @@ -283,7 +284,7 @@ func loadTestCredits(miner *rpctest.Harness, w *lnwallet.LightningWallet, numOut addrs = append(addrs, walletAddr) output := &wire.TxOut{satoshiPerOutput, script} - if _, err := miner.CoinbaseSpend([]*wire.TxOut{output}); err != nil { + if _, err := miner.SendOutputs([]*wire.TxOut{output}, 10); err != nil { return err } } @@ -466,7 +467,7 @@ func testDualFundingReservationWorkflow(miner *rpctest.Harness, wallet *lnwallet // txn hits a "comfortable" depth. // The resulting active channel state should have been persisted to the DB. - fundingSha := fundingTx.TxSha() + fundingSha := fundingTx.TxHash() channels, err := wallet.ChannelDB.FetchOpenChannels(bobNode.id) if err != nil { t.Fatalf("unable to retrieve channel from DB: %v", err) @@ -732,7 +733,7 @@ func testSingleFunderReservationWorkflowInitiator(miner *rpctest.Harness, // The resulting active channel state should have been persisted to the DB. // TODO(roasbeef): de-duplicate fundingTx := chanReservation.FinalFundingTx() - fundingSha := fundingTx.TxSha() + fundingSha := fundingTx.TxHash() channels, err := wallet.ChannelDB.FetchOpenChannels(bobNode.id) if err != nil { t.Fatalf("unable to retrieve channel from DB: %v", err) @@ -854,7 +855,7 @@ func testSingleFunderReservationWorkflowResponder(miner *rpctest.Harness, // At this point, we send Bob our contribution, allowing him to // construct the funding transaction, and sign our version of the // commitment transaction. - fundingTx := wire.NewMsgTx() + fundingTx := wire.NewMsgTx(1) fundingTx.AddTxIn(bobNode.availableOutputs[0]) fundingTx.AddTxOut(bobNode.changeOutputs[0]) fundingTx.AddTxOut(multiOut) @@ -866,7 +867,7 @@ func testSingleFunderReservationWorkflowResponder(miner *rpctest.Harness, // Locate the output index of the 2-of-2 in order to send back to the // wallet so it can finalize the transaction by signing bob's commitment // transaction. - fundingTxID := fundingTx.TxSha() + fundingTxID := fundingTx.TxHash() _, multiSigIndex := lnwallet.FindScriptOutputIndex(fundingTx, multiOut.PkScript) fundingOutpoint := wire.NewOutPoint(&fundingTxID, multiSigIndex) bobObsfucator := bobNode.obsfucator @@ -923,7 +924,7 @@ func testListTransactionDetails(miner *rpctest.Harness, wallet *lnwallet.Lightni // Create 5 new outputs spendable by the wallet. const numTxns = 5 const outputAmt = btcutil.SatoshiPerBitcoin - txids := make(map[wire.ShaHash]struct{}) + txids := make(map[chainhash.Hash]struct{}) for i := 0; i < numTxns; i++ { addr, err := wallet.NewAddress(lnwallet.WitnessPubKey, false) if err != nil { @@ -935,7 +936,7 @@ func testListTransactionDetails(miner *rpctest.Harness, wallet *lnwallet.Lightni } output := &wire.TxOut{outputAmt, script} - txid, err := miner.CoinbaseSpend([]*wire.TxOut{output}) + txid, err := miner.SendOutputs([]*wire.TxOut{output}, 10) if err != nil { t.Fatalf("unable to send coinbase: %v", err) } @@ -1083,7 +1084,7 @@ func testTransactionSubscriptions(miner *rpctest.Harness, w *lnwallet.LightningW } output := &wire.TxOut{outputAmt, script} - if _, err := miner.CoinbaseSpend([]*wire.TxOut{output}); err != nil { + if _, err := miner.SendOutputs([]*wire.TxOut{output}, 10); err != nil { t.Fatalf("unable to send coinbase: %v", err) } } @@ -1183,10 +1184,10 @@ func testSignOutputPrivateTweak(r *rpctest.Harness, w *lnwallet.LightningWallet, /// WIth the index located, we can create a transaction spending the //referenced output. - sweepTx := wire.NewMsgTx() + sweepTx := wire.NewMsgTx(2) sweepTx.AddTxIn(&wire.TxIn{ PreviousOutPoint: wire.OutPoint{ - Hash: tx.TxSha(), + Hash: tx.TxHash(), Index: outputIndex, }, }) diff --git a/lnwallet/script_utils.go b/lnwallet/script_utils.go index be432393..89bab136 100644 --- a/lnwallet/script_utils.go +++ b/lnwallet/script_utils.go @@ -11,6 +11,7 @@ import ( "github.com/btcsuite/fastsha256" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -749,7 +750,7 @@ func DeriveRevocationPrivKey(commitPrivKey *btcec.PrivateKey, // [2]: https://tools.ietf.org/html/rfc5869 func deriveElkremRoot(elkremDerivationRoot *btcec.PrivateKey, localMultiSigKey *btcec.PublicKey, - remoteMultiSigKey *btcec.PublicKey) wire.ShaHash { + remoteMultiSigKey *btcec.PublicKey) chainhash.Hash { secret := elkremDerivationRoot.Serialize() salt := localMultiSigKey.SerializeCompressed() @@ -760,7 +761,7 @@ func deriveElkremRoot(elkremDerivationRoot *btcec.PrivateKey, // It's safe to ignore the error her as we know for sure that we won't // be draining the HKDF past its available entropy horizon. // TODO(roasbeef): revisit... - var elkremRoot wire.ShaHash + var elkremRoot chainhash.Hash rootReader.Read(elkremRoot[:]) return elkremRoot diff --git a/lnwallet/script_utils_test.go b/lnwallet/script_utils_test.go index eda916c8..1b01cc3b 100644 --- a/lnwallet/script_utils_test.go +++ b/lnwallet/script_utils_test.go @@ -67,9 +67,8 @@ func TestCommitmentSpendValidation(t *testing.T) { if err != nil { t.Fatalf("unable to create target output: %v") } - sweepTx := wire.NewMsgTx() - sweepTx.Version = 2 - sweepTx.AddTxIn(wire.NewTxIn(&wire.OutPoint{commitmentTx.TxSha(), 0}, nil, nil)) + sweepTx := wire.NewMsgTx(2) + sweepTx.AddTxIn(wire.NewTxIn(&wire.OutPoint{commitmentTx.TxHash(), 0}, nil, nil)) sweepTx.AddTxOut(&wire.TxOut{ PkScript: targetOutput, Value: 0.5 * 10e8, @@ -267,7 +266,7 @@ func TestHTLCSenderSpendValidation(t *testing.T) { // This will be Alice's commitment transaction. In this scenario Alice // is sending an HTLC to a node she has a a path to (could be Bob, // could be multiple hops down, it doesn't really matter). - senderCommitTx := wire.NewMsgTx() + senderCommitTx := wire.NewMsgTx(2) senderCommitTx.AddTxIn(fakeFundingTxIn) senderCommitTx.AddTxOut(&wire.TxOut{ Value: int64(paymentAmt), @@ -275,11 +274,11 @@ func TestHTLCSenderSpendValidation(t *testing.T) { }) prevOut := &wire.OutPoint{ - Hash: senderCommitTx.TxSha(), + Hash: senderCommitTx.TxHash(), Index: 0, } - sweepTx := wire.NewMsgTx() + sweepTx := wire.NewMsgTx(2) sweepTx.AddTxIn(wire.NewTxIn(prevOut, nil, nil)) sweepTx.AddTxOut( &wire.TxOut{ @@ -439,7 +438,7 @@ func TestHTLCReceiverSpendValidation(t *testing.T) { // This will be Bob's commitment transaction. In this scenario Alice // is sending an HTLC to a node she has a a path to (could be Bob, // could be multiple hops down, it doesn't really matter). - recieverCommitTx := wire.NewMsgTx() + recieverCommitTx := wire.NewMsgTx(2) recieverCommitTx.AddTxIn(fakeFundingTxIn) recieverCommitTx.AddTxOut(&wire.TxOut{ Value: int64(paymentAmt), @@ -447,11 +446,11 @@ func TestHTLCReceiverSpendValidation(t *testing.T) { }) prevOut := &wire.OutPoint{ - Hash: recieverCommitTx.TxSha(), + Hash: recieverCommitTx.TxHash(), Index: 0, } - sweepTx := wire.NewMsgTx() + sweepTx := wire.NewMsgTx(2) sweepTx.AddTxIn(wire.NewTxIn(prevOut, nil, nil)) sweepTx.AddTxOut( &wire.TxOut{ @@ -559,7 +558,7 @@ func TestHTLCReceiverSpendValidation(t *testing.T) { } func TestCommitTxStateHint(t *testing.T) { - commitTx := wire.NewMsgTx() + commitTx := wire.NewMsgTx(2) commitTx.AddTxIn(&wire.TxIn{}) var obsfucator [StateHintSize]byte diff --git a/lnwallet/size.go b/lnwallet/size.go index 20f0a20e..edd12533 100644 --- a/lnwallet/size.go +++ b/lnwallet/size.go @@ -6,7 +6,7 @@ import ( const ( WitnessFactor = blockchain.WitnessScaleFactor - MaxTransactionWeightPolicy = blockchain.MaxBlockCost / 10 + MaxTransactionWeightPolicy = blockchain.MaxBlockWeight / 10 // The weight(cost), which is different from the !size! (see BIP-141), // is calculated as: diff --git a/lnwallet/wallet.go b/lnwallet/wallet.go index caf249f0..e2197247 100644 --- a/lnwallet/wallet.go +++ b/lnwallet/wallet.go @@ -661,7 +661,7 @@ func (l *LightningWallet) handleContributionMsg(req *addContributionMsg) { // Create a blank, fresh transaction. Soon to be a complete funding // transaction which will allow opening a lightning channel. - pendingReservation.fundingTx = wire.NewMsgTx() + pendingReservation.fundingTx = wire.NewMsgTx(1) fundingTx := pendingReservation.fundingTx // Some temporary variables to cut down on the resolution verbosity. @@ -739,7 +739,7 @@ func (l *LightningWallet) handleContributionMsg(req *addContributionMsg) { // Locate the index of the multi-sig outpoint in order to record it // since the outputs are canonically sorted. If this is a single funder // workflow, then we'll also need to send this to the remote node. - fundingTxID := fundingTx.TxSha() + fundingTxID := fundingTx.TxHash() _, multiSigIndex := FindScriptOutputIndex(fundingTx, multiSigOut.PkScript) fundingOutpoint := wire.NewOutPoint(&fundingTxID, multiSigIndex) pendingReservation.partialState.FundingOutpoint = fundingOutpoint @@ -1235,7 +1235,7 @@ func (l *LightningWallet) handleChannelOpen(req *channelOpenMsg) { func (l *LightningWallet) openChannelAfterConfirmations(res *ChannelReservation) { // Register with the ChainNotifier for a notification once the funding // transaction reaches `numConfs` confirmations. - txid := res.fundingTx.TxSha() + txid := res.fundingTx.TxHash() numConfs := uint32(res.numConfsToOpen) confNtfn, _ := l.chainNotifier.RegisterConfirmationsNtfn(&txid, numConfs) diff --git a/lnwire/channel_announcement.go b/lnwire/channel_announcement.go index 09243c86..64686512 100644 --- a/lnwire/channel_announcement.go +++ b/lnwire/channel_announcement.go @@ -7,7 +7,7 @@ import ( "github.com/go-errors/errors" "github.com/roasbeef/btcd/btcec" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" ) // ChannelAnnouncement message is used to announce the existence of a channel @@ -56,12 +56,12 @@ func (a *ChannelAnnouncement) Validate() error { var sigHash []byte - sigHash = wire.DoubleSha256(a.FirstNodeID.SerializeCompressed()) + sigHash = chainhash.DoubleHashB(a.FirstNodeID.SerializeCompressed()) if !a.FirstBitcoinSig.Verify(sigHash, a.FirstBitcoinKey) { return errors.New("can't verify first bitcoin signature") } - sigHash = wire.DoubleSha256(a.SecondNodeID.SerializeCompressed()) + sigHash = chainhash.DoubleHashB(a.SecondNodeID.SerializeCompressed()) if !a.SecondBitcoinSig.Verify(sigHash, a.SecondBitcoinKey) { return errors.New("can't verify second bitcoin signature") } @@ -70,7 +70,7 @@ func (a *ChannelAnnouncement) Validate() error { if err != nil { return err } - dataHash := wire.DoubleSha256(data) + dataHash := chainhash.DoubleHashB(data) if !a.FirstNodeSig.Verify(dataHash, a.FirstNodeID) { return errors.New("can't verify data in first node signature") diff --git a/lnwire/channel_announcement_test.go b/lnwire/channel_announcement_test.go index e85b2e72..d52ec51f 100644 --- a/lnwire/channel_announcement_test.go +++ b/lnwire/channel_announcement_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/roasbeef/btcd/btcec" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" ) func TestChannelAnnoucementEncodeDecode(t *testing.T) { @@ -60,10 +60,10 @@ func TestChannelAnnoucementValidation(t *testing.T) { var hash []byte - hash = wire.DoubleSha256(firstNodePubKey.SerializeCompressed()) + hash = chainhash.DoubleHashB(firstNodePubKey.SerializeCompressed()) firstBitcoinSig, _ := firstBitcoinPrivKey.Sign(hash) - hash = wire.DoubleSha256(secondNodePubKey.SerializeCompressed()) + hash = chainhash.DoubleHashB(secondNodePubKey.SerializeCompressed()) secondBitcoinSig, _ := secondBitcoinPrivKey.Sign(hash) ca := &ChannelAnnouncement{ @@ -77,7 +77,7 @@ func TestChannelAnnoucementValidation(t *testing.T) { } dataToSign, _ := ca.DataToSign() - hash = wire.DoubleSha256(dataToSign) + hash = chainhash.DoubleHashB(dataToSign) firstNodeSign, _ := firstNodePrivKey.Sign(hash) ca.FirstNodeSig = firstNodeSign diff --git a/lnwire/lnwire.go b/lnwire/lnwire.go index 8c161a92..74714a26 100644 --- a/lnwire/lnwire.go +++ b/lnwire/lnwire.go @@ -10,6 +10,7 @@ import ( "github.com/go-errors/errors" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -175,7 +176,7 @@ func writeElement(w io.Writer, element interface{}) error { if _, err = w.Write(b[:]); err != nil { return err } - case *wire.ShaHash: + case *chainhash.Hash: if _, err := w.Write(e[:]); err != nil { return err } @@ -425,8 +426,8 @@ func readElement(r io.Reader, element interface{}) error { return err } *e = btcutil.Amount(int64(binary.BigEndian.Uint64(b[:]))) - case **wire.ShaHash: - var b wire.ShaHash + case **chainhash.Hash: + var b chainhash.Hash if _, err := io.ReadFull(r, b[:]); err != nil { return err } @@ -576,7 +577,7 @@ func readElement(r io.Reader, element interface{}) error { if _, err = io.ReadFull(r, h[:]); err != nil { return err } - hash, err := wire.NewShaHash(h[:]) + hash, err := chainhash.NewHash(h[:]) if err != nil { return err } @@ -596,7 +597,7 @@ func readElement(r io.Reader, element interface{}) error { if _, err = io.ReadFull(r, h[:]); err != nil { return err } - hash, err := wire.NewShaHash(h[:]) + hash, err := chainhash.NewHash(h[:]) if err != nil { return err } diff --git a/lnwire/lnwire_test.go b/lnwire/lnwire_test.go index 715e721f..feca9d25 100644 --- a/lnwire/lnwire_test.go +++ b/lnwire/lnwire_test.go @@ -10,6 +10,7 @@ import ( "net" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" ) @@ -63,18 +64,18 @@ var ( // echo -n | openssl sha256 // This stuff gets reversed!!! shaHash1Bytes, _ = hex.DecodeString("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") - shaHash1, _ = wire.NewShaHash(shaHash1Bytes) + shaHash1, _ = chainhash.NewHash(shaHash1Bytes) outpoint1 = wire.NewOutPoint(shaHash1, 0) // echo | openssl sha256 // This stuff gets reversed!!! shaHash2Bytes, _ = hex.DecodeString("01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b") - shaHash2, _ = wire.NewShaHash(shaHash2Bytes) + shaHash2, _ = chainhash.NewHash(shaHash2Bytes) outpoint2 = wire.NewOutPoint(shaHash2, 1) // create inputs from outpoint1 and outpoint2 inputs = []*wire.TxIn{wire.NewTxIn(outpoint1, nil, nil), wire.NewTxIn(outpoint2, nil, nil)} // Commitment Signature - tx = wire.NewMsgTx() + tx = wire.NewMsgTx(1) emptybytes = new([]byte) sigStr, _ = txscript.RawTxInSignature(tx, 0, *emptybytes, txscript.SigHashAll, privKey) commitSig, _ = btcec.ParseSignature(sigStr, btcec.S256()) @@ -93,7 +94,7 @@ var ( ptrFundingTXSigs = append(*new([]*btcec.Signature), commitSig1, commitSig2) // TxID - txid = new(wire.ShaHash) + txid = new(chainhash.Hash) // Reversed when displayed txidBytes, _ = hex.DecodeString("fd95c6e5c9d5bcf9cfc7231b6a438e46c518c724d0b04b75cc8fddf84a254e3a") _ = copy(txid[:], txidBytes) diff --git a/lnwire/node_announcement.go b/lnwire/node_announcement.go index 5b523dba..aecb2661 100644 --- a/lnwire/node_announcement.go +++ b/lnwire/node_announcement.go @@ -8,7 +8,7 @@ import ( "github.com/go-errors/errors" "github.com/roasbeef/btcd/btcec" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" ) var ( @@ -119,7 +119,7 @@ func (a *NodeAnnouncement) Validate() error { return err } - dataHash := wire.DoubleSha256(data) + dataHash := chainhash.DoubleHashB(data) if !a.Signature.Verify(dataHash, a.NodeID) { return errors.New("can't check the node annoucement signature") } diff --git a/lnwire/node_announcement_test.go b/lnwire/node_announcement_test.go index 84eb1d99..0cfb6a48 100644 --- a/lnwire/node_announcement_test.go +++ b/lnwire/node_announcement_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/roasbeef/btcd/btcec" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" ) func TestNodeAnnouncementEncodeDecode(t *testing.T) { @@ -58,7 +58,7 @@ func TestNodeAnnoucementValidation(t *testing.T) { } dataToSign, _ := na.DataToSign() - hash = wire.DoubleSha256(dataToSign) + hash = chainhash.DoubleHashB(dataToSign) signature, _ := nodePrivKey.Sign(hash) na.Signature = signature diff --git a/networktest.go b/networktest.go index ea86da65..3dcda05d 100644 --- a/networktest.go +++ b/networktest.go @@ -24,6 +24,7 @@ import ( "github.com/go-errors/errors" "github.com/lightningnetwork/lnd/lnrpc" "github.com/roasbeef/btcd/chaincfg" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/rpctest" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" @@ -314,7 +315,7 @@ type networkHarness struct { Alice *lightningNode Bob *lightningNode - seenTxns chan wire.ShaHash + seenTxns chan chainhash.Hash watchRequests chan *watchRequest // Channel for transmitting stderr output from failed lightning node @@ -331,7 +332,7 @@ type networkHarness struct { func newNetworkHarness() (*networkHarness, error) { return &networkHarness{ activeNodes: make(map[int]*lightningNode), - seenTxns: make(chan wire.ShaHash), + seenTxns: make(chan chainhash.Hash), watchRequests: make(chan *watchRequest), lndErrorChan: make(chan error), }, nil @@ -442,7 +443,7 @@ func (n *networkHarness) SetUp() error { PkScript: addrScript, Value: btcutil.SatoshiPerBitcoin, } - if _, err := n.Miner.CoinbaseSpend([]*wire.TxOut{output}); err != nil { + if _, err := n.Miner.SendOutputs([]*wire.TxOut{output}, 30); err != nil { return err } } @@ -568,7 +569,7 @@ func (n *networkHarness) RestartNode(node *lightningNode, callback func() error) // dispatch a notification once a transaction with the target txid is seen // within the test network. type watchRequest struct { - txid wire.ShaHash + txid chainhash.Hash eventChan chan struct{} } @@ -576,8 +577,8 @@ type watchRequest struct { // the broadcast of a target transaction, and then dispatches the transaction // once its seen on the network. func (n *networkHarness) networkWatcher() { - seenTxns := make(map[wire.ShaHash]struct{}) - clients := make(map[wire.ShaHash][]chan struct{}) + seenTxns := make(map[chainhash.Hash]struct{}) + clients := make(map[chainhash.Hash][]chan struct{}) for { @@ -618,7 +619,7 @@ func (n *networkHarness) networkWatcher() { // OnTxAccepted is a callback to be called each time a new transaction has been // broadcast on the network. -func (n *networkHarness) OnTxAccepted(hash *wire.ShaHash, amt btcutil.Amount) { +func (n *networkHarness) OnTxAccepted(hash *chainhash.Hash, amt btcutil.Amount) { go func() { n.seenTxns <- *hash }() @@ -628,7 +629,7 @@ func (n *networkHarness) OnTxAccepted(hash *wire.ShaHash, amt btcutil.Amount) { // the transaction isn't seen within the network before the passed timeout, // then an error is returned. // TODO(roasbeef): add another method which creates queue of all seen transactions -func (n *networkHarness) WaitForTxBroadcast(ctx context.Context, txid wire.ShaHash) error { +func (n *networkHarness) WaitForTxBroadcast(ctx context.Context, txid chainhash.Hash) error { eventChan := make(chan struct{}) n.watchRequests <- &watchRequest{txid, eventChan} @@ -734,7 +735,7 @@ func (n *networkHarness) WaitForChannelOpen(ctx context.Context, // pending, then an error is returned. func (n *networkHarness) CloseChannel(ctx context.Context, lnNode *lightningNode, cp *lnrpc.ChannelPoint, - force bool) (lnrpc.Lightning_CloseChannelClient, *wire.ShaHash, error) { + force bool) (lnrpc.Lightning_CloseChannelClient, *chainhash.Hash, error) { closeReq := &lnrpc.CloseChannelRequest{ ChannelPoint: cp, @@ -746,7 +747,7 @@ func (n *networkHarness) CloseChannel(ctx context.Context, } errChan := make(chan error) - fin := make(chan *wire.ShaHash) + fin := make(chan *chainhash.Hash) go func() { // Consume the "channel close" update in order to wait for the closing // transaction to be broadcast, then wait for the closing tx to be seen @@ -763,7 +764,7 @@ func (n *networkHarness) CloseChannel(ctx context.Context, return } - closeTxid, err := wire.NewShaHash(pendingClose.ClosePending.Txid) + closeTxid, err := chainhash.NewHash(pendingClose.ClosePending.Txid) if err != nil { errChan <- err return @@ -793,7 +794,7 @@ func (n *networkHarness) CloseChannel(ctx context.Context, // passed context has a timeout, then if the timeout is reached before the // notification is received then an error is returned. func (n *networkHarness) WaitForChannelClose(ctx context.Context, - closeChanStream lnrpc.Lightning_CloseChannelClient) (*wire.ShaHash, error) { + closeChanStream lnrpc.Lightning_CloseChannelClient) (*chainhash.Hash, error) { errChan := make(chan error) updateChan := make(chan *lnrpc.CloseStatusUpdate_ChanClose) @@ -822,7 +823,7 @@ func (n *networkHarness) WaitForChannelClose(ctx context.Context, case err := <-errChan: return nil, err case update := <-updateChan: - return wire.NewShaHash(update.ChanClose.ClosingTxid) + return chainhash.NewHash(update.ChanClose.ClosingTxid) } } @@ -898,7 +899,7 @@ func (n *networkHarness) SendCoins(ctx context.Context, amt btcutil.Amount, PkScript: addrScript, Value: int64(amt), } - if _, err := n.Miner.CoinbaseSpend([]*wire.TxOut{output}); err != nil { + if _, err := n.Miner.SendOutputs([]*wire.TxOut{output}, 30); err != nil { return err } diff --git a/peer.go b/peer.go index 667a0c62..1efc28ce 100644 --- a/peer.go +++ b/peer.go @@ -20,6 +20,7 @@ import ( "github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/lnwire" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -69,7 +70,7 @@ type peer struct { conn net.Conn addr *lnwire.NetAddress - lightningID wire.ShaHash + lightningID chainhash.Hash inbound bool id int32 @@ -157,7 +158,7 @@ func newPeer(conn net.Conn, server *server, addr *lnwire.NetAddress, p := &peer{ conn: conn, - lightningID: wire.ShaHash(fastsha256.Sum256(nodePub.SerializeCompressed())), + lightningID: chainhash.Hash(fastsha256.Sum256(nodePub.SerializeCompressed())), addr: addr, id: atomic.AddInt32(&numNodes, 1), @@ -694,7 +695,7 @@ out: // cooperative channel close. The channel state machine is transitioned to the // closing phase, then our half of the closing witness is sent over to the // remote peer. -func (p *peer) executeCooperativeClose(channel *lnwallet.LightningChannel) (*wire.ShaHash, error) { +func (p *peer) executeCooperativeClose(channel *lnwallet.LightningChannel) (*chainhash.Hash, error) { // Shift the channel state machine into a 'closing' state. This // generates a signature for the closing tx, as well as a txid of the // closing tx itself, allowing us to watch the network to determine @@ -730,7 +731,7 @@ func (p *peer) executeCooperativeClose(channel *lnwallet.LightningChannel) (*wir func (p *peer) handleLocalClose(req *closeLinkReq) { var ( err error - closingTxid *wire.ShaHash + closingTxid *chainhash.Hash ) p.activeChanMtx.RLock() @@ -1417,7 +1418,7 @@ func (p *peer) handleUpstreamMsg(state *commitmentState, msg lnwire.Message) { // with this latest commitment update. // TODO(roasbeef): wait until next transition? for invoice, _ := range settledPayments { - err := p.server.invoices.SettleInvoice(wire.ShaHash(invoice)) + err := p.server.invoices.SettleInvoice(chainhash.Hash(invoice)) if err != nil { peerLog.Errorf("unable to settle invoice: %v", err) } diff --git a/routing/pathfind_test.go b/routing/pathfind_test.go index e567ab89..2a67dd45 100644 --- a/routing/pathfind_test.go +++ b/routing/pathfind_test.go @@ -14,6 +14,7 @@ import ( "github.com/lightningnetwork/lnd/channeldb" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" ) @@ -201,7 +202,7 @@ func parseTestGraph(path string) (*channeldb.ChannelGraph, func(), aliasMap, err } fundingTXID := strings.Split(edge.ChannelPoint, ":")[0] - txidBytes, err := wire.NewShaHashFromStr(fundingTXID) + txidBytes, err := chainhash.NewHashFromStr(fundingTXID) if err != nil { return nil, nil, nil, err } diff --git a/routing/router.go b/routing/router.go index d9c65b88..4452925a 100644 --- a/routing/router.go +++ b/routing/router.go @@ -752,7 +752,7 @@ func (r *ChannelRouter) fetchChanPoint(chanID *lnwire.ChannelID) (*wire.OutPoint // transaction index to obtain the funding output and txid. fundingTx := fundingBlock.Transactions[chanID.TxIndex] return &wire.OutPoint{ - Hash: fundingTx.TxSha(), + Hash: fundingTx.TxHash(), Index: uint32(chanID.TxPosition), }, nil } diff --git a/rpcserver.go b/rpcserver.go index 23eda1f7..9bf14f63 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -24,6 +24,7 @@ import ( "github.com/lightningnetwork/lnd/zpay32" "github.com/roasbeef/btcd/btcec" "github.com/roasbeef/btcd/chaincfg" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -104,7 +105,7 @@ func addrPairsToOutputs(addrPairs map[string]int64) ([]*wire.TxOut, error) { // sendCoinsOnChain makes an on-chain transaction in or to send coins to one or // more addresses specified in the passed payment map. The payment map maps an // address to a specified output value to be sent to that address. -func (r *rpcServer) sendCoinsOnChain(paymentMap map[string]int64) (*wire.ShaHash, error) { +func (r *rpcServer) sendCoinsOnChain(paymentMap map[string]int64) (*chainhash.Hash, error) { outputs, err := addrPairsToOutputs(paymentMap) if err != nil { return nil, err @@ -271,7 +272,7 @@ out: switch update := fundingUpdate.Update.(type) { case *lnrpc.OpenStatusUpdate_ChanOpen: chanPoint := update.ChanOpen.ChannelPoint - h, _ := wire.NewShaHash(chanPoint.FundingTxid) + h, _ := chainhash.NewHash(chanPoint.FundingTxid) outpoint = wire.OutPoint{ Hash: *h, Index: chanPoint.OutputIndex, @@ -354,7 +355,7 @@ func (r *rpcServer) CloseChannel(in *lnrpc.CloseChannelRequest, force := in.Force index := in.ChannelPoint.OutputIndex - txid, err := wire.NewShaHash(in.ChannelPoint.FundingTxid) + txid, err := chainhash.NewHash(in.ChannelPoint.FundingTxid) if err != nil { rpcsLog.Errorf("[closechannel] invalid txid: %v", err) return err @@ -472,7 +473,7 @@ out: // longer need to process any further updates. switch closeUpdate := closingUpdate.Update.(type) { case *lnrpc.CloseStatusUpdate_ChanClose: - h, _ := wire.NewShaHash(closeUpdate.ChanClose.ClosingTxid) + h, _ := chainhash.NewHash(closeUpdate.ChanClose.ClosingTxid) rpcsLog.Infof("[closechannel] close completed: "+ "txid(%v)", h) break out @@ -520,7 +521,7 @@ func (r *rpcServer) fetchActiveChannel(chanPoint wire.OutPoint) (*lnwallet.Light // commitment transaction has been broadcast, a struct describing the final // state of the channel is sent to the utxoNursery in order to ultimately sweep // the immature outputs. -func (r *rpcServer) forceCloseChan(channel *lnwallet.LightningChannel) (*wire.ShaHash, error) { +func (r *rpcServer) forceCloseChan(channel *lnwallet.LightningChannel) (*chainhash.Hash, error) { // Execute a unilateral close shutting down all further channel // operation. closeSummary, err := channel.ForceClose() @@ -529,7 +530,7 @@ func (r *rpcServer) forceCloseChan(channel *lnwallet.LightningChannel) (*wire.Sh } closeTx := closeSummary.CloseTx - txid := closeTx.TxSha() + txid := closeTx.TxHash() // With the close transaction in hand, broadcast the transaction to the // network, thereby entering the psot channel resolution state. @@ -1014,7 +1015,7 @@ func (r *rpcServer) constructPaymentRoute(destNode *btcec.PublicKey, } firstHopPub := route.Hops[0].Channel.Node.PubKey.SerializeCompressed() - destInterface := wire.ShaHash(fastsha256.Sum256(firstHopPub)) + destInterface := chainhash.Hash(fastsha256.Sum256(firstHopPub)) return &htlcPacket{ dest: destInterface, diff --git a/shachain/shachain.go b/shachain/shachain.go index 1d775a25..e2badb4e 100644 --- a/shachain/shachain.go +++ b/shachain/shachain.go @@ -8,7 +8,7 @@ import ( "io" "sync" - "github.com/roasbeef/btcd/wire" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcutil" ) @@ -32,7 +32,7 @@ type HyperShaChain struct { chainBranches [64]chainBranch - lastHash wire.ShaHash + lastHash chainhash.Hash } // NewHyperShaChain @@ -145,14 +145,14 @@ func (h *HyperShaChain) AddNextHash(hash [32]byte) error { } // CurrentPreImage... -func (h *HyperShaChain) CurrentPreImage() *wire.ShaHash { +func (h *HyperShaChain) CurrentPreImage() *chainhash.Hash { h.RLock() defer h.RUnlock() return &h.lastHash } // CurrentRevocationHash... -// TODO(roasbeef): *wire.ShaHash vs [wire.HashSize]byte ? +// TODO(roasbeef): *chainhash.Hash vs [wire.HashSize]byte ? func (h *HyperShaChain) CurrentRevocationHash() []byte { h.RLock() defer h.RUnlock() diff --git a/utxonursery.go b/utxonursery.go index 7b5a1dcf..e7cdbd4c 100644 --- a/utxonursery.go +++ b/utxonursery.go @@ -581,8 +581,7 @@ func createSweepTx(wallet *lnwallet.LightningWallet, matureOutputs []*kidOutput) totalSum += o.amt } - sweepTx := wire.NewMsgTx() - sweepTx.Version = 2 + sweepTx := wire.NewMsgTx(2) sweepTx.AddTxOut(&wire.TxOut{ PkScript: pkScript, Value: int64(totalSum - 5000), diff --git a/utxonursery_test.go b/utxonursery_test.go index 18df8826..d49e0602 100644 --- a/utxonursery_test.go +++ b/utxonursery_test.go @@ -8,6 +8,7 @@ import ( "github.com/lightningnetwork/lnd/lnwallet" "github.com/roasbeef/btcd/btcec" + "github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcutil" @@ -16,7 +17,7 @@ import ( var ( outPoints = []wire.OutPoint{ wire.OutPoint{ - Hash: [wire.HashSize]byte{ + Hash: [chainhash.HashSize]byte{ 0x51, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda, 0x48, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17, 0x2d, 0xe7, 0x93, 0xe4, 0xb7, 0x25, 0xb8, 0x4d, @@ -25,7 +26,7 @@ var ( Index: 9, }, wire.OutPoint{ - Hash: [wire.HashSize]byte{ + Hash: [chainhash.HashSize]byte{ 0xb7, 0x94, 0x38, 0x5f, 0x2d, 0x1e, 0xf7, 0xab, 0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4, 0x4f, 0x2f, 0x6f, 0x25, 0x88, 0xa3, 0xef, 0xb9, @@ -34,7 +35,7 @@ var ( Index: 49, }, wire.OutPoint{ - Hash: [wire.HashSize]byte{ + Hash: [chainhash.HashSize]byte{ 0x81, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda, 0x63, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17, 0xd, 0xe7, 0x95, 0xe4, 0xb7, 0x25, 0xb8, 0x4d,