multi: replace usage of fastsha256 with crypto/sha256

This commit removes all instances of the fastsha256 library and
replaces it with the sha256 library in the standard library. This
change should see a number of performance improvements as the standard
library has highly optimized assembly instructions with use vectorized
instructions as the platform supports.
This commit is contained in:
Olaoluwa Osuntokun 2017-03-15 18:56:25 -07:00
parent d723aada30
commit f217093c00
No known key found for this signature in database
GPG Key ID: 9CC5B105D03521A2
16 changed files with 53 additions and 55 deletions

@ -12,7 +12,6 @@ import (
"golang.org/x/crypto/hkdf"
"github.com/aead/chacha20"
"github.com/btcsuite/fastsha256"
"github.com/roasbeef/btcd/btcec"
)
@ -53,7 +52,7 @@ func ecdh(pub *btcec.PublicKey, priv *btcec.PrivateKey) []byte {
s.X = x
s.Y = y
h := fastsha256.Sum256(s.SerializeCompressed())
h := sha256.Sum256(s.SerializeCompressed())
return h[:]
}

@ -2,6 +2,7 @@ package channeldb
import (
"bytes"
"crypto/sha256"
"fmt"
"image/color"
"math/big"
@ -12,7 +13,6 @@ import (
"testing"
"time"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/roasbeef/btcd/btcec"
"github.com/roasbeef/btcd/chaincfg/chainhash"
@ -554,7 +554,7 @@ func TestGraphTraversal(t *testing.T) {
const numChannels = 5
chanIndex := map[uint64]struct{}{}
for i := 0; i < numChannels; i++ {
txHash := fastsha256.Sum256([]byte{byte(i)})
txHash := sha256.Sum256([]byte{byte(i)})
chanID := uint64(i + 1)
op := wire.OutPoint{
Hash: txHash,
@ -706,7 +706,7 @@ func TestGraphPruning(t *testing.T) {
// between them.
channelPoints := make([]*wire.OutPoint, 0, numNodes-1)
for i := 0; i < numNodes-1; i++ {
txHash := fastsha256.Sum256([]byte{byte(i)})
txHash := sha256.Sum256([]byte{byte(i)})
chanID := uint64(i + 1)
op := wire.OutPoint{
Hash: txHash,
@ -781,12 +781,12 @@ func TestGraphPruning(t *testing.T) {
// Next we'll create a block that doesn't close any channels within the
// graph to test the negative error case.
fakeHash := fastsha256.Sum256([]byte("test prune"))
fakeHash := sha256.Sum256([]byte("test prune"))
nonChannel := &wire.OutPoint{
Hash: fakeHash,
Index: 9,
}
blockHash = fastsha256.Sum256(blockHash[:])
blockHash = sha256.Sum256(blockHash[:])
blockHeight = 2
prunedChans, err = graph.PruneGraph([]*wire.OutPoint{nonChannel},
&blockHash, blockHeight)
@ -805,7 +805,7 @@ func TestGraphPruning(t *testing.T) {
// Finally, create a block that prunes the remainder of the channels
// from the graph.
blockHash = fastsha256.Sum256(blockHash[:])
blockHash = sha256.Sum256(blockHash[:])
blockHeight = 3
prunedChans, err = graph.PruneGraph(channelPoints[2:], &blockHash,
blockHeight)

@ -2,11 +2,11 @@ package channeldb
import (
"crypto/rand"
"crypto/sha256"
"reflect"
"testing"
"time"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/roasbeef/btcutil"
)
@ -58,7 +58,7 @@ func TestInvoiceWorkflow(t *testing.T) {
// Attempt to retrieve the invoice which was just added to the
// database. It should be found, and the invoice returned should be
// identical to the one created above.
paymentHash := fastsha256.Sum256(fakeInvoice.Terms.PaymentPreimage[:])
paymentHash := sha256.Sum256(fakeInvoice.Terms.PaymentPreimage[:])
dbInvoice, err := db.LookupInvoice(paymentHash)
if err != nil {
t.Fatalf("unable to find invoice: %v", err)

@ -2,12 +2,12 @@ package channeldb
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"time"
"github.com/boltdb/bolt"
"github.com/btcsuite/fastsha256"
"github.com/roasbeef/btcd/wire"
"github.com/roasbeef/btcutil"
)
@ -132,7 +132,7 @@ func (d *DB) AddInvoice(i *Invoice) error {
// Ensure that an invoice an identical payment hash doesn't
// already exist within the index.
paymentHash := fastsha256.Sum256(i.Terms.PaymentPreimage[:])
paymentHash := sha256.Sum256(i.Terms.PaymentPreimage[:])
if invoiceIndex.Get(paymentHash[:]) != nil {
return ErrDuplicateInvoice
}
@ -285,7 +285,7 @@ func putInvoice(invoices *bolt.Bucket, invoiceIndex *bolt.Bucket,
// Add the payment hash to the invoice index. This'll let us quickly
// identify if we can settle an incoming payment, and also to possibly
// allow a single invoice to have multiple payment installations.
paymentHash := fastsha256.Sum256(i.Terms.PaymentPreimage[:])
paymentHash := sha256.Sum256(i.Terms.PaymentPreimage[:])
if err := invoiceIndex.Put(paymentHash[:], invoiceKey[:]); err != nil {
return err
}

@ -2,13 +2,13 @@ package channeldb
import (
"bytes"
"crypto/sha256"
"fmt"
"math/rand"
"reflect"
"testing"
"time"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/roasbeef/btcutil"
)
@ -33,7 +33,7 @@ func makeFakePayment() *OutgoingPayment {
Fee: 101,
Path: fakePath,
TimeLockLength: 1000,
PaymentHash: fastsha256.Sum256(rev[:]),
PaymentHash: sha256.Sum256(rev[:]),
}
}
@ -83,7 +83,7 @@ func makeRandomFakePayment() (*OutgoingPayment, error) {
copy(fakePath[i][:], b)
}
rHash := fastsha256.Sum256(fakeInvoice.Terms.PaymentPreimage[:])
rHash := sha256.Sum256(fakeInvoice.Terms.PaymentPreimage[:])
fakePayment := &OutgoingPayment{
Invoice: *fakeInvoice,
Fee: btcutil.Amount(rand.Intn(1001)),

@ -3,7 +3,6 @@ import:
- package: github.com/boltdb/bolt
version: ^1.2.1
- package: github.com/btcsuite/btclog
- package: github.com/btcsuite/fastsha256
- package: github.com/btcsuite/go-flags
- package: github.com/btcsuite/seelog
version: ^2.1.0

@ -1,13 +1,13 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lightning-onion"
"github.com/lightningnetwork/lnd/channeldb"
@ -402,7 +402,7 @@ out:
// settle msg to the link which initially created the
// circuit.
case *lnwire.UpdateFufillHTLC:
rHash := fastsha256.Sum256(wireMsg.PaymentPreimage[:])
rHash := sha256.Sum256(wireMsg.PaymentPreimage[:])
var cKey circuitKey
copy(cKey[:], rHash[:])
@ -731,7 +731,7 @@ func (h *htlcSwitch) UnregisterLink(remotePub *btcec.PublicKey, chanPoint *wire.
rawPub := remotePub.SerializeCompressed()
h.linkControl <- &unregisterLinkMsg{
chanInterface: fastsha256.Sum256(rawPub),
chanInterface: sha256.Sum256(rawPub),
chanPoint: chanPoint,
remoteID: rawPub,
done: done,

@ -2,10 +2,10 @@ package main
import (
"bytes"
"crypto/sha256"
"sync"
"time"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/roasbeef/btcd/chaincfg/chainhash"
@ -20,7 +20,7 @@ var (
// preimage.
debugPre, _ = chainhash.NewHash(bytes.Repeat([]byte{1}, 32))
debugHash = chainhash.Hash(fastsha256.Sum256(debugPre[:]))
debugHash = chainhash.Hash(sha256.Sum256(debugPre[:]))
)
// invoiceRegistry is a central registry of all the outstanding invoices
@ -58,7 +58,7 @@ func newInvoiceRegistry(cdb *channeldb.DB) *invoiceRegistry {
// daemon add/forward HTLCs 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 chainhash.Hash) {
paymentHash := chainhash.Hash(fastsha256.Sum256(preimage[:]))
paymentHash := chainhash.Hash(sha256.Sum256(preimage[:]))
invoice := &channeldb.Invoice{
CreationDate: time.Now(),

@ -3,11 +3,11 @@ package lnwallet
import (
"bytes"
"container/list"
"crypto/sha256"
"fmt"
"sync"
"sync/atomic"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/chainntnfs"
"github.com/lightningnetwork/lnd/channeldb"
@ -1500,7 +1500,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(rawSig []byte) error {
return err
}
revocationKey := DeriveRevocationPubkey(theirCommitKey, revocation[:])
revocationHash := fastsha256.Sum256(revocation[:])
revocationHash := sha256.Sum256(revocation[:])
// With the revocation information calculated, construct the new
// commitment view which includes all the entries we know of in their
@ -1605,7 +1605,7 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, err
}
revocationMsg.NextRevocationKey = DeriveRevocationPubkey(theirCommitKey,
revocationEdge[:])
revocationMsg.NextRevocationHash = fastsha256.Sum256(revocationEdge[:])
revocationMsg.NextRevocationHash = sha256.Sum256(revocationEdge[:])
walletLog.Tracef("ChannelPoint(%v): revoking height=%v, now at height=%v, window_edge=%v",
lc.channelState.ChanID, lc.localCommitChain.tail().height,
@ -1686,7 +1686,7 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) ([]*P
// Additionally, we need to ensure we were given the proper preimage
// to the revocation hash used within any current HTLCs.
if !bytes.Equal(lc.channelState.TheirCurrentRevocationHash[:], zeroHash[:]) {
revokeHash := fastsha256.Sum256(pendingRevocation[:])
revokeHash := sha256.Sum256(pendingRevocation[:])
// TODO(roasbeef): rename to drop the "Their"
if !bytes.Equal(lc.channelState.TheirCurrentRevocationHash[:], revokeHash[:]) {
return nil, fmt.Errorf("revocation hash mismatch")
@ -1798,7 +1798,7 @@ func (lc *LightningChannel) ExtendRevocationWindow() (*lnwire.RevokeAndAck, erro
theirCommitKey := lc.channelState.TheirCommitKey
revMsg.NextRevocationKey = DeriveRevocationPubkey(theirCommitKey,
revocation[:])
revMsg.NextRevocationHash = fastsha256.Sum256(revocation[:])
revMsg.NextRevocationHash = sha256.Sum256(revocation[:])
lc.revocationWindowEdge++
@ -1888,8 +1888,7 @@ func (lc *LightningChannel) SettleHTLC(preimage [32]byte) (uint64, error) {
lc.Lock()
defer lc.Unlock()
paymentHash := fastsha256.Sum256(preimage[:])
paymentHash := sha256.Sum256(preimage[:])
targetHTLCs, ok := lc.rHashMap[paymentHash]
if !ok {
return 0, fmt.Errorf("invalid payment hash")
@ -1923,10 +1922,10 @@ func (lc *LightningChannel) ReceiveHTLCSettle(preimage [32]byte, logIndex uint64
lc.Lock()
defer lc.Unlock()
paymentHash := fastsha256.Sum256(preimage[:])
paymentHash := sha256.Sum256(preimage[:])
htlc := lc.localUpdateLog.lookup(logIndex)
if htlc == nil {
return fmt.Errorf("non existent log entry")
return fmt.Errorf("non existant log entry")
}
if !bytes.Equal(htlc.RHash[:], paymentHash[:]) {

@ -2,6 +2,7 @@ package lnwallet
import (
"bytes"
"crypto/sha256"
"io/ioutil"
"os"
"testing"
@ -357,7 +358,7 @@ func TestSimpleAddSettleWorkflow(t *testing.T) {
}
paymentPreimage := bytes.Repeat([]byte{1}, 32)
paymentHash := fastsha256.Sum256(paymentPreimage)
paymentHash := sha256.Sum256(paymentPreimage)
htlc := &lnwire.UpdateAddHTLC{
PaymentHash: paymentHash,
Amount: btcutil.SatoshiPerBitcoin,
@ -622,7 +623,7 @@ func TestCheckCommitTxSize(t *testing.T) {
createHTLC := func(i int) (*lnwire.UpdateAddHTLC, [32]byte) {
preimage := bytes.Repeat([]byte{byte(i)}, 32)
paymentHash := fastsha256.Sum256(preimage)
paymentHash := sha256.Sum256(preimage)
var returnPreimage [32]byte
copy(returnPreimage[:], preimage)
@ -744,7 +745,7 @@ func TestCooperativeChannelClosure(t *testing.T) {
func TestCheckHTLCNumberConstraint(t *testing.T) {
createHTLC := func(i int) *lnwire.UpdateAddHTLC {
preimage := bytes.Repeat([]byte{byte(i)}, 32)
paymentHash := fastsha256.Sum256(preimage)
paymentHash := sha256.Sum256(preimage)
return &lnwire.UpdateAddHTLC{
PaymentHash: paymentHash,
Amount: btcutil.Amount(1e7),
@ -1025,7 +1026,7 @@ func TestCheckDustLimit(t *testing.T) {
createHTLC := func(data, amount btcutil.Amount) (*lnwire.UpdateAddHTLC,
[32]byte) {
preimage := bytes.Repeat([]byte{byte(data)}, 32)
paymentHash := fastsha256.Sum256(preimage)
paymentHash := sha256.Sum256(preimage)
var returnPreimage [32]byte
copy(returnPreimage[:], preimage)
@ -1243,7 +1244,7 @@ func TestStateUpdatePersistence(t *testing.T) {
var bobPreimage [32]byte
copy(bobPreimage[:], bytes.Repeat([]byte{0xbb}, 32))
for i := 0; i < 3; i++ {
rHash := fastsha256.Sum256(alicePreimage[:])
rHash := sha256.Sum256(alicePreimage[:])
h := &lnwire.UpdateAddHTLC{
PaymentHash: rHash,
Amount: btcutil.Amount(1000),
@ -1257,7 +1258,7 @@ func TestStateUpdatePersistence(t *testing.T) {
t.Fatalf("unable to recv alice's htlc: %v", err)
}
}
rHash := fastsha256.Sum256(bobPreimage[:])
rHash := sha256.Sum256(bobPreimage[:])
bobh := &lnwire.UpdateAddHTLC{
PaymentHash: rHash,
Amount: btcutil.Amount(1000),
@ -1467,7 +1468,7 @@ func TestCancelHTLC(t *testing.T) {
var preImage [32]byte
copy(preImage[:], bytes.Repeat([]byte{0xaa}, 32))
htlc := &lnwire.UpdateAddHTLC{
PaymentHash: fastsha256.Sum256(preImage[:]),
PaymentHash: sha256.Sum256(preImage[:]),
Amount: htlcAmt,
Expiry: 10,
}

@ -9,7 +9,6 @@ import (
"golang.org/x/crypto/hkdf"
"github.com/btcsuite/fastsha256"
"github.com/roasbeef/btcd/btcec"
"github.com/roasbeef/btcd/chaincfg/chainhash"
"github.com/roasbeef/btcd/txscript"
@ -56,7 +55,7 @@ func witnessScriptHash(witnessScript []byte) ([]byte, error) {
bldr := txscript.NewScriptBuilder()
bldr.AddOp(txscript.OP_0)
scriptHash := fastsha256.Sum256(witnessScript)
scriptHash := sha256.Sum256(witnessScript)
bldr.AddData(scriptHash[:])
return bldr.Script()
}

@ -2,11 +2,11 @@ package lnwallet
import (
"bytes"
"crypto/sha256"
"fmt"
"testing"
"time"
"github.com/btcsuite/fastsha256"
"github.com/roasbeef/btcd/btcec"
"github.com/roasbeef/btcd/txscript"
"github.com/roasbeef/btcd/wire"
@ -245,10 +245,10 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
// Generate a payment and revocation preimage to be used below.
revokePreimage := testHdSeed[:]
revokeHash := fastsha256.Sum256(revokePreimage)
revokeHash := sha256.Sum256(revokePreimage)
paymentPreimage := revokeHash
paymentPreimage[0] ^= 1
paymentHash := fastsha256.Sum256(paymentPreimage[:])
paymentHash := sha256.Sum256(paymentPreimage[:])
// We'll also need some tests keys for alice and bob, and metadata of
// the HTLC output.
@ -417,10 +417,10 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
// Generate a payment and revocation preimage to be used below.
revokePreimage := testHdSeed[:]
revokeHash := fastsha256.Sum256(revokePreimage)
revokeHash := sha256.Sum256(revokePreimage)
paymentPreimage := revokeHash
paymentPreimage[0] ^= 1
paymentHash := fastsha256.Sum256(paymentPreimage[:])
paymentHash := sha256.Sum256(paymentPreimage[:])
// We'll also need some tests keys for alice and bob, and metadata of
// the HTLC output.

@ -1,12 +1,12 @@
package lnwallet
import (
"crypto/sha256"
"fmt"
"net"
"sync"
"sync/atomic"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/chainntnfs"
"github.com/lightningnetwork/lnd/channeldb"
@ -1287,7 +1287,7 @@ func deriveStateHintObfuscator(producer shachain.Producer) ([StateHintSize]byte,
return obfuscator, err
}
grandChild := fastsha256.Sum256(firstChild[:])
grandChild := sha256.Sum256(firstChild[:])
copy(obfuscator[:], grandChild[:])
return obfuscator, nil

@ -4,6 +4,7 @@ import (
"bytes"
"container/list"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"fmt"
"net"
@ -11,7 +12,6 @@ import (
"sync/atomic"
"time"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/go-errors/errors"
"github.com/lightningnetwork/lightning-onion"
@ -175,7 +175,7 @@ func newPeer(conn net.Conn, connReq *connmgr.ConnReq, server *server,
p := &peer{
conn: conn,
lightningID: chainhash.Hash(fastsha256.Sum256(nodePub.SerializeCompressed())),
lightningID: chainhash.Hash(sha256.Sum256(nodePub.SerializeCompressed())),
addr: addr,
id: atomic.AddInt32(&numNodes, 1),

@ -2,6 +2,7 @@ package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
@ -14,7 +15,6 @@ import (
"sync"
"sync/atomic"
"github.com/btcsuite/fastsha256"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/lnrpc"
@ -1152,7 +1152,7 @@ func (r *rpcServer) AddInvoice(ctx context.Context,
// Next, generate the payment hash itself from the preimage. This will
// be used by clients to query for the state of a particular invoice.
rHash := fastsha256.Sum256(paymentPreimage[:])
rHash := sha256.Sum256(paymentPreimage[:])
// Finally we also create an encoded payment request which allows the
// caller to comactly send the invoice to the payer.
@ -1220,7 +1220,7 @@ func (r *rpcServer) LookupInvoice(ctx context.Context,
Settled: invoice.Terms.Settled,
PaymentRequest: zpay32.Encode(&zpay32.PaymentRequest{
Destination: r.server.identityPriv.PubKey(),
PaymentHash: fastsha256.Sum256(preimage[:]),
PaymentHash: sha256.Sum256(preimage[:]),
Amount: invoice.Terms.Value,
}),
}, nil
@ -1249,7 +1249,7 @@ func (r *rpcServer) ListInvoices(ctx context.Context,
CreationDate: dbInvoice.CreationDate.Unix(),
PaymentRequest: zpay32.Encode(&zpay32.PaymentRequest{
Destination: r.server.identityPriv.PubKey(),
PaymentHash: fastsha256.Sum256(paymentPreimge),
PaymentHash: sha256.Sum256(paymentPreimge),
Amount: invoiceAmount,
}),
}

@ -1,6 +1,7 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
@ -124,7 +125,7 @@ func newServer(listenAddrs []string, notifier chainntnfs.ChainNotifier,
// TODO(roasbeef): derive proper onion key based on rotation
// schedule
sphinx: sphinx.NewRouter(privKey, activeNetParams.Params),
lightningID: fastsha256.Sum256(serializedPubKey),
lightningID: sha256.Sum256(serializedPubKey),
persistentConnReqs: make(map[string]*connmgr.ConnReq),