lnd: partially fix golint warnings

This commit is contained in:
Andrey Samokhvalov 2017-02-23 22:56:47 +03:00 committed by Olaoluwa Osuntokun
parent 92dec2a902
commit fd97a4bd19
38 changed files with 229 additions and 233 deletions

@ -15,12 +15,12 @@ import (
// exchange and message encryption protocol dubbed "Brontide" after initial TCP // exchange and message encryption protocol dubbed "Brontide" after initial TCP
// connection establishment. In the case of a successful handshake, all // connection establishment. In the case of a successful handshake, all
// messages sent via the .Write() method are encrypted with an AEAD cipher // messages sent via the .Write() method are encrypted with an AEAD cipher
// along with an encrypted length-prefix. See the BrontideMachine struct for // along with an encrypted length-prefix. See the Machine struct for
// additional details w.r.t to the handshake and encryption scheme. // additional details w.r.t to the handshake and encryption scheme.
type Conn struct { type Conn struct {
conn net.Conn conn net.Conn
noise *BrontideMachine noise *Machine
readBuf bytes.Buffer readBuf bytes.Buffer
} }

@ -8,8 +8,8 @@ import (
) )
// Listener is an implementation of a net.Conn which executes an authenticated // Listener is an implementation of a net.Conn which executes an authenticated
// key exchange and message encryption protocol dubeed "BrontideMachine" after // key exchange and message encryption protocol dubeed "Machine" after
// initial connection acceptance. See the BrontideMachine struct for additional // initial connection acceptance. See the Machine struct for additional
// details w.r.t the handshake and encryption scheme used within the // details w.r.t the handshake and encryption scheme used within the
// connection. // connection.
type Listener struct { type Listener struct {

@ -299,7 +299,7 @@ func newHandshakeState(initiator bool, prologue []byte,
return h return h
} }
// BrontideMachine is a state-machine which implements Brontide: an // Machine is a state-machine which implements Brontide: an
// Authenticated-key Exchange in Three Acts. Brontide is derived from the Noise // Authenticated-key Exchange in Three Acts. Brontide is derived from the Noise
// framework, specifically implementing the Noise_XK handshake. Once the // framework, specifically implementing the Noise_XK handshake. Once the
// initial 3-act handshake has completed all messages are encrypted with a // initial 3-act handshake has completed all messages are encrypted with a
@ -324,7 +324,7 @@ func newHandshakeState(initiator bool, prologue []byte,
// -> e, es // -> e, es
// <- e, ee // <- e, ee
// -> s, se // -> s, se
type BrontideMachine struct { type Machine struct {
sendCipher cipherState sendCipher cipherState
recvCipher cipherState recvCipher cipherState
@ -336,12 +336,12 @@ type BrontideMachine struct {
// be nil. The handshake state within brontide is initialized using the ascii // be nil. The handshake state within brontide is initialized using the ascii
// string "bitcoin" as the prologue. // string "bitcoin" as the prologue.
func NewBrontideMachine(initiator bool, localPub *btcec.PrivateKey, func NewBrontideMachine(initiator bool, localPub *btcec.PrivateKey,
remotePub *btcec.PublicKey) *BrontideMachine { remotePub *btcec.PublicKey) *Machine {
handshake := newHandshakeState(initiator, []byte("lightning"), localPub, handshake := newHandshakeState(initiator, []byte("lightning"), localPub,
remotePub) remotePub)
return &BrontideMachine{handshakeState: handshake} return &Machine{handshakeState: handshake}
} }
const ( const (
@ -381,7 +381,7 @@ const (
// derived from this result. // derived from this result.
// //
// -> e, es // -> e, es
func (b *BrontideMachine) GenActOne() ([ActOneSize]byte, error) { func (b *Machine) GenActOne() ([ActOneSize]byte, error) {
var ( var (
err error err error
actOne [ActOneSize]byte actOne [ActOneSize]byte
@ -413,7 +413,7 @@ func (b *BrontideMachine) GenActOne() ([ActOneSize]byte, error) {
// executes the mirrored actions to that of the initiator extending the // executes the mirrored actions to that of the initiator extending the
// handshake digest and deriving a new shared secret based on a ECDH with the // handshake digest and deriving a new shared secret based on a ECDH with the
// initiator's ephemeral key and responder's static key. // initiator's ephemeral key and responder's static key.
func (b *BrontideMachine) RecvActOne(actOne [ActOneSize]byte) error { func (b *Machine) RecvActOne(actOne [ActOneSize]byte) error {
var ( var (
err error err error
e [33]byte e [33]byte
@ -453,7 +453,7 @@ func (b *BrontideMachine) RecvActOne(actOne [ActOneSize]byte) error {
// initiator's and responder's ephemeral keys. // initiator's and responder's ephemeral keys.
// //
// <- e, ee // <- e, ee
func (b *BrontideMachine) GenActTwo() ([ActTwoSize]byte, error) { func (b *Machine) GenActTwo() ([ActTwoSize]byte, error) {
var ( var (
err error err error
actTwo [ActTwoSize]byte actTwo [ActTwoSize]byte
@ -484,7 +484,7 @@ func (b *BrontideMachine) GenActTwo() ([ActTwoSize]byte, error) {
// RecvActTwo processes the second packet (act two) sent from the responder to // RecvActTwo processes the second packet (act two) sent from the responder to
// the initiator. A successful processing of this packet authenticates the // the initiator. A successful processing of this packet authenticates the
// initiator to the responder. // initiator to the responder.
func (b *BrontideMachine) RecvActTwo(actTwo [ActTwoSize]byte) error { func (b *Machine) RecvActTwo(actTwo [ActTwoSize]byte) error {
var ( var (
err error err error
e [33]byte e [33]byte
@ -523,7 +523,7 @@ func (b *BrontideMachine) RecvActTwo(actTwo [ActTwoSize]byte) error {
// the final session. // the final session.
// //
// -> s, se // -> s, se
func (b *BrontideMachine) GenActThree() ([ActThreeSize]byte, error) { func (b *Machine) GenActThree() ([ActThreeSize]byte, error) {
var actThree [ActThreeSize]byte var actThree [ActThreeSize]byte
ourPubkey := b.localStatic.PubKey().SerializeCompressed() ourPubkey := b.localStatic.PubKey().SerializeCompressed()
@ -549,7 +549,7 @@ func (b *BrontideMachine) GenActThree() ([ActThreeSize]byte, error) {
// the responder. After processing this act, the responder learns of the // the responder. After processing this act, the responder learns of the
// initiator's static public key. Decryption of the static key serves to // initiator's static public key. Decryption of the static key serves to
// authenticate the initiator to the responder. // authenticate the initiator to the responder.
func (b *BrontideMachine) RecvActThree(actThree [ActThreeSize]byte) error { func (b *Machine) RecvActThree(actThree [ActThreeSize]byte) error {
var ( var (
err error err error
s [33 + 16]byte s [33 + 16]byte
@ -596,7 +596,7 @@ func (b *BrontideMachine) RecvActThree(actThree [ActThreeSize]byte) error {
// instances: one which is used to encrypt messages from the initiator to the // instances: one which is used to encrypt messages from the initiator to the
// responder, and another which is used to encrypt message for the opposite // responder, and another which is used to encrypt message for the opposite
// direction. // direction.
func (b *BrontideMachine) split() { func (b *Machine) split() {
var ( var (
empty []byte empty []byte
sendKey [32]byte sendKey [32]byte
@ -631,7 +631,7 @@ func (b *BrontideMachine) split() {
// ciphertext of the message is pre-pended with an encrypt+auth'd length which // ciphertext of the message is pre-pended with an encrypt+auth'd length which
// must be used as the AD to the AEAD construction when being decrypted by the // must be used as the AD to the AEAD construction when being decrypted by the
// other side. // other side.
func (b *BrontideMachine) WriteMessage(w io.Writer, p []byte) error { func (b *Machine) WriteMessage(w io.Writer, p []byte) error {
// The total length of each message payload including the MAC size // The total length of each message payload including the MAC size
// payload exceed the largest number encodable within a 16-bit unsigned // payload exceed the largest number encodable within a 16-bit unsigned
// integer. // integer.
@ -662,7 +662,7 @@ func (b *BrontideMachine) WriteMessage(w io.Writer, p []byte) error {
// ReadMessage attempts to read the next message from the passed io.Reader. In // ReadMessage attempts to read the next message from the passed io.Reader. In
// the case of an authentication error, a non-nil error is returned. // the case of an authentication error, a non-nil error is returned.
func (b *BrontideMachine) ReadMessage(r io.Reader) ([]byte, error) { func (b *Machine) ReadMessage(r io.Reader) ([]byte, error) {
var cipherLen [lengthHeaderSize + macSize]byte var cipherLen [lengthHeaderSize + macSize]byte
if _, err := io.ReadFull(r, cipherLen[:]); err != nil { if _, err := io.ReadFull(r, cipherLen[:]); err != nil {
return nil, err return nil, err

@ -114,7 +114,7 @@ func TestConnectionCorrectness(t *testing.T) {
} }
func TestMaxPayloadLength(t *testing.T) { func TestMaxPayloadLength(t *testing.T) {
b := BrontideMachine{} b := Machine{}
b.split() b.split()
// Create a payload that's juust over the maximum alloted payload // Create a payload that's juust over the maximum alloted payload

@ -591,7 +591,7 @@ type spendCancel struct {
spendID uint64 spendID uint64
} }
// RegisterSpendNotification registers an intent to be notified once the target // RegisterSpendNtfn registers an intent to be notified once the target
// outpoint has been spent by a transaction on-chain. Once a spend of the target // outpoint has been spent by a transaction on-chain. Once a spend of the target
// outpoint has been detected, the details of the spending event will be sent // outpoint has been detected, the details of the spending event will be sent
// across the 'Spend' channel. // across the 'Spend' channel.
@ -667,7 +667,7 @@ type confirmationsNotification struct {
negativeConf chan int32 // TODO(roasbeef): re-org funny business negativeConf chan int32 // TODO(roasbeef): re-org funny business
} }
// RegisterConfirmationsNotification registers a notification with BtcdNotifier // RegisterConfirmationsNtfn registers a notification with BtcdNotifier
// which will be triggered once the txid reaches numConfs number of // which will be triggered once the txid reaches numConfs number of
// confirmations. // confirmations.
func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash, func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,

@ -7,7 +7,7 @@ import (
"github.com/btcsuite/btclog" "github.com/btcsuite/btclog"
) )
// log is a logger that is initialized with no output filters. This // Log is a logger that is initialized with no output filters. This
// means the package will not perform any logging by default until the caller // means the package will not perform any logging by default until the caller
// requests it. // requests it.
var Log btclog.Logger var Log btclog.Logger

@ -212,7 +212,7 @@ func fileExists(path string) bool {
return true return true
} }
// FetchOpenChannel returns all stored currently active/open channels // FetchOpenChannels returns all stored currently active/open channels
// associated with the target nodeID. In the case that no active channels are // associated with the target nodeID. In the case that no active channels are
// known to have been created with this node, then a zero-length slice is // known to have been created with this node, then a zero-length slice is
// returned. // returned.

@ -627,7 +627,7 @@ func TestGraphTraversal(t *testing.T) {
if !c.Node.PubKey.IsEqual(secondNode.PubKey) { if !c.Node.PubKey.IsEqual(secondNode.PubKey) {
return fmt.Errorf("wrong outgoing edge") return fmt.Errorf("wrong outgoing edge")
} }
numNodeChans += 1 numNodeChans++
return nil return nil
}) })
if err != nil { if err != nil {
@ -663,7 +663,7 @@ func asserNumChans(t *testing.T, graph *ChannelGraph, n int) {
if err := graph.ForEachChannel(func(*ChannelEdgeInfo, *ChannelEdgePolicy, if err := graph.ForEachChannel(func(*ChannelEdgeInfo, *ChannelEdgePolicy,
*ChannelEdgePolicy) error { *ChannelEdgePolicy) error {
numChans += 1 numChans++
return nil return nil
}); err != nil { }); err != nil {
_, _, line, _ := runtime.Caller(1) _, _, line, _ := runtime.Caller(1)

@ -27,7 +27,7 @@ func TestVersionFetchPut(t *testing.T) {
t.Fatal("initialization of meta information wasn't performed") t.Fatal("initialization of meta information wasn't performed")
} }
var newVersion uint32 = getLatestDBVersion(dbVersions) + 1 newVersion := getLatestDBVersion(dbVersions) + 1
meta.DbVersionNumber = newVersion meta.DbVersionNumber = newVersion
if err := db.PutMeta(meta); err != nil { if err := db.PutMeta(meta); err != nil {
@ -261,7 +261,7 @@ func TestMigrationWithFatal(t *testing.T) {
} }
bucket.Put(keyPrefix, afterMigration) bucket.Put(keyPrefix, afterMigration)
return errors.New("some error!") return errors.New("some error")
} }
// Check that version of database and initial data wasn't changed. // Check that version of database and initial data wasn't changed.

@ -69,7 +69,7 @@ func (db *DB) AddPayment(payment *OutgoingPayment) error {
} }
// Obtain the new unique sequence number for this payment. // Obtain the new unique sequence number for this payment.
paymentId, err := payments.NextSequence() paymentID, err := payments.NextSequence()
if err != nil { if err != nil {
return err return err
} }
@ -77,10 +77,10 @@ func (db *DB) AddPayment(payment *OutgoingPayment) error {
// We use BigEndian for keys as it orders keys in // We use BigEndian for keys as it orders keys in
// ascending order. This allows bucket scans to order payments // ascending order. This allows bucket scans to order payments
// in the order in which they were created. // in the order in which they were created.
paymentIdBytes := make([]byte, 8) paymentIDBytes := make([]byte, 8)
binary.BigEndian.PutUint64(paymentIdBytes, paymentId) binary.BigEndian.PutUint64(paymentIDBytes, paymentID)
return payments.Put(paymentIdBytes, paymentBytes) return payments.Put(paymentIDBytes, paymentBytes)
}) })
} }

@ -26,7 +26,7 @@ import (
// TODO(roasbeef): cli logic for supporting both positional and unix style // TODO(roasbeef): cli logic for supporting both positional and unix style
// arguments. // arguments.
func printJson(resp interface{}) { func printJSON(resp interface{}) {
b, err := json.Marshal(resp) b, err := json.Marshal(resp)
if err != nil { if err != nil {
fatal(err) fatal(err)
@ -37,7 +37,7 @@ func printJson(resp interface{}) {
out.WriteTo(os.Stdout) out.WriteTo(os.Stdout)
} }
func printRespJson(resp proto.Message) { func printRespJSON(resp proto.Message) {
jsonMarshaler := &jsonpb.Marshaler{ jsonMarshaler := &jsonpb.Marshaler{
EmitDefaults: true, EmitDefaults: true,
Indent: " ", Indent: " ",
@ -92,7 +92,7 @@ func newAddress(ctx *cli.Context) error {
return err return err
} }
printRespJson(addr) printRespJSON(addr)
return nil return nil
} }
@ -165,7 +165,7 @@ func sendCoins(ctx *cli.Context) error {
return err return err
} }
printRespJson(txid) printRespJSON(txid)
return nil return nil
} }
@ -200,7 +200,7 @@ func sendMany(ctx *cli.Context) error {
return err return err
} }
printRespJson(txid) printRespJSON(txid)
return nil return nil
} }
@ -245,7 +245,7 @@ func connectPeer(ctx *cli.Context) error {
return err return err
} }
printRespJson(lnid) printRespJSON(lnid)
return nil return nil
} }
@ -380,7 +380,7 @@ func openChannel(ctx *cli.Context) error {
return err return err
} }
printJson(struct { printJSON(struct {
FundingTxid string `json:"funding_txid"` FundingTxid string `json:"funding_txid"`
}{ }{
FundingTxid: txid.String(), FundingTxid: txid.String(),
@ -399,7 +399,7 @@ func openChannel(ctx *cli.Context) error {
} }
index := channelPoint.OutputIndex index := channelPoint.OutputIndex
printJson(struct { printJSON(struct {
ChannelPoint string `json:"channel_point"` ChannelPoint string `json:"channel_point"`
}{ }{
ChannelPoint: fmt.Sprintf("%v:%v", txid, index), ChannelPoint: fmt.Sprintf("%v:%v", txid, index),
@ -410,6 +410,7 @@ func openChannel(ctx *cli.Context) error {
} }
// TODO(roasbeef): also allow short relative channel ID. // TODO(roasbeef): also allow short relative channel ID.
var CloseChannelCommand = cli.Command{ var CloseChannelCommand = cli.Command{
Name: "closechannel", Name: "closechannel",
Usage: "Close an existing channel.", Usage: "Close an existing channel.",
@ -517,7 +518,7 @@ func closeChannel(ctx *cli.Context) error {
return err return err
} }
printJson(struct { printJSON(struct {
ClosingTXID string `json:"closing_txid"` ClosingTXID string `json:"closing_txid"`
}{ }{
ClosingTXID: txid.String(), ClosingTXID: txid.String(),
@ -534,7 +535,7 @@ func closeChannel(ctx *cli.Context) error {
return err return err
} }
printJson(struct { printJSON(struct {
ClosingTXID string `json:"closing_txid"` ClosingTXID string `json:"closing_txid"`
}{ }{
ClosingTXID: txid.String(), ClosingTXID: txid.String(),
@ -560,7 +561,7 @@ func listPeers(ctx *cli.Context) error {
return err return err
} }
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }
@ -590,7 +591,7 @@ func walletBalance(ctx *cli.Context) error {
return err return err
} }
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }
@ -611,7 +612,7 @@ func channelBalance(ctx *cli.Context) error {
return err return err
} }
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }
@ -632,7 +633,7 @@ func getInfo(ctx *cli.Context) error {
return err return err
} }
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }
@ -680,7 +681,7 @@ func pendingChannels(ctx *cli.Context) error {
return err return err
} }
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }
@ -710,7 +711,7 @@ func listChannels(ctx *cli.Context) error {
// TODO(roasbeef): defer close the client for the all // TODO(roasbeef): defer close the client for the all
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }
@ -844,7 +845,7 @@ func sendPaymentCommand(ctx *cli.Context) error {
paymentStream.CloseSend() paymentStream.CloseSend()
printJson(struct { printJSON(struct {
P string `json:"payment_preimage"` P string `json:"payment_preimage"`
R *lnrpc.Route `json:"payment_route"` R *lnrpc.Route `json:"payment_route"`
}{ }{
@ -936,7 +937,7 @@ func addInvoice(ctx *cli.Context) error {
return err return err
} }
printJson(struct { printJSON(struct {
RHash string `json:"r_hash"` RHash string `json:"r_hash"`
PayReq string `json:"pay_req"` PayReq string `json:"pay_req"`
}{ }{
@ -992,7 +993,7 @@ func lookupInvoice(ctx *cli.Context) error {
return err return err
} }
printRespJson(invoice) printRespJSON(invoice)
return nil return nil
} }
@ -1028,7 +1029,7 @@ func listInvoices(ctx *cli.Context) error {
return err return err
} }
printRespJson(invoices) printRespJSON(invoices)
return nil return nil
} }
@ -1064,7 +1065,7 @@ func describeGraph(ctx *cli.Context) error {
return drawChannelGraph(graph) return drawChannelGraph(graph)
} }
printRespJson(graph) printRespJSON(graph)
return nil return nil
} }
@ -1233,7 +1234,7 @@ func listPayments(ctx *cli.Context) error {
return err return err
} }
printRespJson(payments) printRespJSON(payments)
return nil return nil
} }
@ -1280,7 +1281,7 @@ func getChanInfo(ctx *cli.Context) error {
return err return err
} }
printRespJson(chanInfo) printRespJSON(chanInfo)
return nil return nil
} }
@ -1317,7 +1318,7 @@ func getNodeInfo(ctx *cli.Context) error {
return err return err
} }
printRespJson(nodeInfo) printRespJSON(nodeInfo)
return nil return nil
} }
@ -1385,7 +1386,7 @@ func queryRoute(ctx *cli.Context) error {
return err return err
} }
printRespJson(route) printRespJSON(route)
return nil return nil
} }
@ -1409,7 +1410,7 @@ func getNetworkInfo(ctx *cli.Context) error {
return err return err
} }
printRespJson(netInfo) printRespJSON(netInfo)
return nil return nil
} }
@ -1445,7 +1446,7 @@ func debugLevel(ctx *cli.Context) error {
return err return err
} }
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }
@ -1486,7 +1487,7 @@ func decodePayReq(ctx *cli.Context) error {
return err return err
} }
printRespJson(resp) printRespJSON(resp)
return nil return nil
} }

6
lnd.go

@ -124,9 +124,9 @@ func lndMain() error {
walletConfig := &btcwallet.Config{ walletConfig := &btcwallet.Config{
PrivatePass: []byte("hello"), PrivatePass: []byte("hello"),
DataDir: filepath.Join(cfg.DataDir, "lnwallet"), DataDir: filepath.Join(cfg.DataDir, "lnwallet"),
RpcHost: btcdHost, RPCHost: btcdHost,
RpcUser: cfg.RPCUser, RPCUser: cfg.RPCUser,
RpcPass: cfg.RPCPass, RPCPass: cfg.RPCPass,
CACert: rpcCert, CACert: rpcCert,
NetParams: activeNetParams.Params, NetParams: activeNetParams.Params,
} }

@ -23,7 +23,7 @@ func (b *BtcWallet) GetBestBlock() (*chainhash.Hash, int32, error) {
return b.rpc.GetBestBlock() return b.rpc.GetBestBlock()
} }
// GetTxOut returns the original output referenced by the passed outpoint. // GetUtxo returns the original output referenced by the passed outpoint.
// //
// This method is a part of the lnwallet.BlockChainIO interface. // This method is a part of the lnwallet.BlockChainIO interface.
func (b *BtcWallet) GetUtxo(txid *chainhash.Hash, index uint32) (*wire.TxOut, error) { func (b *BtcWallet) GetUtxo(txid *chainhash.Hash, index uint32) (*wire.TxOut, error) {

@ -100,8 +100,8 @@ func New(cfg *Config) (*BtcWallet, error) {
// Create a special websockets rpc client for btcd which will be used // Create a special websockets rpc client for btcd which will be used
// by the wallet for notifications, calls, etc. // by the wallet for notifications, calls, etc.
rpcc, err := chain.NewRPCClient(cfg.NetParams, cfg.RpcHost, rpcc, err := chain.NewRPCClient(cfg.NetParams, cfg.RPCHost,
cfg.RpcUser, cfg.RpcPass, cfg.CACert, false, 20) cfg.RPCUser, cfg.RPCPass, cfg.CACert, false, 20)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -208,9 +208,9 @@ func (b *BtcWallet) NewAddress(t lnwallet.AddressType, change bool) (btcutil.Add
if change { if change {
return b.wallet.NewChangeAddress(defaultAccount, addrType) return b.wallet.NewChangeAddress(defaultAccount, addrType)
} else {
return b.wallet.NewAddress(defaultAccount, addrType)
} }
return b.wallet.NewAddress(defaultAccount, addrType)
} }
// GetPrivKey retrives the underlying private key associated with the passed // GetPrivKey retrives the underlying private key associated with the passed

@ -46,23 +46,23 @@ type Config struct {
// logger should use. // logger should use.
DebugLevel string DebugLevel string
// RpcHost is the host and port to use to reach the rpc sever. // RPCHost is the host and port to use to reach the rpc sever.
RpcHost string // localhost:18334 RPCHost string // localhost:18334
// RpcUser is the username which should be used to authentiate with the // RPCUser is the username which should be used to authentiate with the
// rpc server. // rpc server.
RpcUser string RPCUser string
// RpcPass is the password which should be used to authenticate the // RPCPass is the password which should be used to authenticate the
// connection with the RPC server. // connection with the RPC server.
RpcPass string RPCPass string
// RpcNoTLS denotes if a TLS connection should be attempted when // RPCNoTLS denotes if a TLS connection should be attempted when
// connecting to the RPC server. // connecting to the RPC server.
RpcNoTLS bool RPCNoTLS bool
// RPCCert directory where the TLS certificate of the RPC sever is // RPCCert directory where the TLS certificate of the RPC sever is
// stored. If the RpcNoTLS is false, then this value will be unused. // stored. If the RPCNoTLS is false, then this value will be unused.
RPCCert string RPCCert string
RPCKey string RPCKey string

@ -28,7 +28,7 @@ const (
// nested p2wkh output. // nested p2wkh output.
NestedWitnessPubKey NestedWitnessPubKey
// PublicKey represents a regular p2pkh output. // PubKeyHash represents a regular p2pkh output.
PubKeyHash PubKeyHash
) )

@ -1286,9 +1286,9 @@ func TestLightningWallet(t *testing.T) {
HdSeed: testHdSeed[:], HdSeed: testHdSeed[:],
DataDir: tempTestDir, DataDir: tempTestDir,
NetParams: netParams, NetParams: netParams,
RpcHost: rpcConfig.Host, RPCHost: rpcConfig.Host,
RpcUser: rpcConfig.User, RPCUser: rpcConfig.User,
RpcPass: rpcConfig.Pass, RPCPass: rpcConfig.Pass,
CACert: rpcConfig.Certificates, CACert: rpcConfig.Certificates,
} }
wc, err = walletDriver.New(btcwalletConfig) wc, err = walletDriver.New(btcwalletConfig)

@ -51,7 +51,7 @@ type ChannelContribution struct {
CsvDelay uint32 CsvDelay uint32
} }
// InputScripts represents any script inputs required to redeem a previous // InputScript represents any script inputs required to redeem a previous
// output. This struct is used rather than just a witness, or scripSig in // output. This struct is used rather than just a witness, or scripSig in
// order to accommodate nested p2sh which utilizes both types of input scripts. // order to accommodate nested p2sh which utilizes both types of input scripts.
type InputScript struct { type InputScript struct {
@ -349,7 +349,7 @@ func (r *ChannelReservation) CompleteReservationSingle(
return <-completeChan, <-errChan return <-completeChan, <-errChan
} }
// OurSignatures returns the counterparty's signatures to all inputs to the // TheirSignatures returns the counterparty's signatures to all inputs to the
// funding transaction belonging to them, as well as their signature for the // funding transaction belonging to them, as well as their signature for the
// wallet's version of the commitment transaction. This methods is provided for // wallet's version of the commitment transaction. This methods is provided for
// additional verification, such as needed by tests. // additional verification, such as needed by tests.
@ -393,7 +393,7 @@ func (r *ChannelReservation) LocalCommitTx() *wire.MsgTx {
return r.partialState.OurCommitTx return r.partialState.OurCommitTx
} }
// SetDustLimit set dust limit of the remote party. // SetTheirDustLimit set dust limit of the remote party.
func (r *ChannelReservation) SetTheirDustLimit(dustLimit btcutil.Amount) { func (r *ChannelReservation) SetTheirDustLimit(dustLimit btcutil.Amount) {
r.Lock() r.Lock()
defer r.Unlock() defer r.Unlock()

@ -20,8 +20,8 @@ import (
var ( var (
// TODO(roasbeef): remove these and use the one's defined in txscript // TODO(roasbeef): remove these and use the one's defined in txscript
// within testnet-L. // within testnet-L.
SequenceLockTimeSeconds = uint32(1 << 22) SequenceLockTimeSeconds = uint32(1 << 22)
SequenceLockTimeMask = uint32(0x0000ffff)
OP_CHECKSEQUENCEVERIFY byte = txscript.OP_NOP3 OP_CHECKSEQUENCEVERIFY byte = txscript.OP_NOP3
// TimelockShift is used to make sure the commitment transaction is // TimelockShift is used to make sure the commitment transaction is

@ -5,9 +5,6 @@ import (
) )
const ( const (
WitnessFactor = blockchain.WitnessScaleFactor
MaxTransactionWeightPolicy = blockchain.MaxBlockWeight / 10
// The weight(cost), which is different from the !size! (see BIP-141), // The weight(cost), which is different from the !size! (see BIP-141),
// is calculated as: // is calculated as:
// Weight = 4 * BaseSize + WitnessSize (weight). // Weight = 4 * BaseSize + WitnessSize (weight).
@ -15,19 +12,19 @@ const (
// WitnessSize - witness size (bytes). // WitnessSize - witness size (bytes).
// Weight - the metric for determining the cost of the transaction. // Weight - the metric for determining the cost of the transaction.
// P2WSH: 34 bytes // P2WSHSize 34 bytes
// - OP_0: 1 byte // - OP_0: 1 byte
// - OP_DATA: 1 byte (WitnessScriptSHA256 length) // - OP_DATA: 1 byte (WitnessScriptSHA256 length)
// - WitnessScriptSHA256: 32 bytes // - WitnessScriptSHA256: 32 bytes
P2WSHSize = 1 + 1 + 32 P2WSHSize = 1 + 1 + 32
// P2WPKH: 22 bytes // P2WPKHSize 22 bytes
// - OP_0: 1 byte // - OP_0: 1 byte
// - OP_DATA: 1 byte (PublicKeyHASH160 length) // - OP_DATA: 1 byte (PublicKeyHASH160 length)
// - PublicKeyHASH160: 20 bytes // - PublicKeyHASH160: 20 bytes
P2WPKHSize = 1 + 1 + 20 P2WPKHSize = 1 + 1 + 20
// MultiSig: 71 bytes // MultiSigSize 71 bytes
// - OP_2: 1 byte // - OP_2: 1 byte
// - OP_DATA: 1 byte (pubKeyAlice length) // - OP_DATA: 1 byte (pubKeyAlice length)
// - pubKeyAlice: 33 bytes // - pubKeyAlice: 33 bytes
@ -37,7 +34,7 @@ const (
// - OP_CHECKMULTISIG: 1 byte // - OP_CHECKMULTISIG: 1 byte
MultiSigSize = 1 + 1 + 33 + 1 + 33 + 1 + 1 MultiSigSize = 1 + 1 + 33 + 1 + 33 + 1 + 1
// Witness: 222 bytes // WitnessSize 222 bytes
// - NumberOfWitnessElements: 1 byte // - NumberOfWitnessElements: 1 byte
// - NilLength: 1 byte // - NilLength: 1 byte
// - sigAliceLength: 1 byte // - sigAliceLength: 1 byte
@ -48,7 +45,7 @@ const (
// - WitnessScript (MultiSig) // - WitnessScript (MultiSig)
WitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + MultiSigSize WitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + MultiSigSize
// FundingInput: 41 bytes // FundingInputSize 41 bytes
// - PreviousOutPoint: // - PreviousOutPoint:
// - Hash: 32 bytes // - Hash: 32 bytes
// - Index: 4 bytes // - Index: 4 bytes
@ -62,30 +59,30 @@ const (
// - Sequence: 4 bytes // - Sequence: 4 bytes
FundingInputSize = 32 + 4 + 1 + 4 FundingInputSize = 32 + 4 + 1 + 4
// OutputPayingToUs: 43 bytes // CommitmentDelayOutput 43 bytes
// - Value: 8 bytes // - Value: 8 bytes
// - VarInt: 1 byte (PkScript length) // - VarInt: 1 byte (PkScript length)
// - PkScript (P2WSH) // - PkScript (P2WSH)
CommitmentDelayOutput = 8 + 1 + P2WSHSize CommitmentDelayOutput = 8 + 1 + P2WSHSize
// OutputPayingToThem: 31 bytes // CommitmentKeyHashOutput 31 bytes
// - Value: 8 bytes // - Value: 8 bytes
// - VarInt: 1 byte (PkScript length) // - VarInt: 1 byte (PkScript length)
// - PkScript (P2WPKH) // - PkScript (P2WPKH)
CommitmentKeyHashOutput = 8 + 1 + P2WPKHSize CommitmentKeyHashOutput = 8 + 1 + P2WPKHSize
// HTLCOutput: 43 bytes // HTLCSize 43 bytes
// - Value: 8 bytes // - Value: 8 bytes
// - VarInt: 1 byte (PkScript length) // - VarInt: 1 byte (PkScript length)
// - PkScript (PW2SH) // - PkScript (PW2SH)
HTLCSize = 8 + 1 + P2WSHSize HTLCSize = 8 + 1 + P2WSHSize
// WitnessHeader: 2 bytes // WitnessHeaderSize 2 bytes
// - Flag: 1 byte // - Flag: 1 byte
// - Marker: 1 byte // - Marker: 1 byte
WitnessHeaderSize = 1 + 1 WitnessHeaderSize = 1 + 1
// CommitmentTransaction: 125 43 * num-htlc-outputs bytes // BaseCommitmentTxSize 125 43 * num-htlc-outputs bytes
// - Version: 4 bytes // - Version: 4 bytes
// - WitnessHeader <---- part of the witness data // - WitnessHeader <---- part of the witness data
// - CountTxIn: 1 byte // - CountTxIn: 1 byte
@ -100,14 +97,14 @@ const (
BaseCommitmentTxSize = 4 + 1 + FundingInputSize + 1 + BaseCommitmentTxSize = 4 + 1 + FundingInputSize + 1 +
CommitmentDelayOutput + CommitmentKeyHashOutput + 4 CommitmentDelayOutput + CommitmentKeyHashOutput + 4
// CommitmentTransactionCost: 500 weight // BaseCommitmentTxCost 500 weight
BaseCommitmentTxCost = WitnessFactor * BaseCommitmentTxSize BaseCommitmentTxCost = blockchain.WitnessScaleFactor * BaseCommitmentTxSize
// WitnessCommitmentTxCost: 224 weight // WitnessCommitmentTxCost 224 weight
WitnessCommitmentTxCost = WitnessHeaderSize + WitnessSize WitnessCommitmentTxCost = WitnessHeaderSize + WitnessSize
// HTLCCost: 172 weight // HTLCCost 172 weight
HTLCCost = WitnessFactor * HTLCSize HTLCCost = blockchain.WitnessScaleFactor * HTLCSize
// MaxHTLCNumber shows as the maximum number HTLCs which can be // MaxHTLCNumber shows as the maximum number HTLCs which can be
// included in commitment transaction. This numbers was calculated by // included in commitment transaction. This numbers was calculated by

@ -390,7 +390,7 @@ func (l *LightningWallet) Shutdown() error {
return nil return nil
} }
// LockOutpoints returns a list of all currently locked outpoint. // LockedOutpoints returns a list of all currently locked outpoint.
func (l *LightningWallet) LockedOutpoints() []*wire.OutPoint { func (l *LightningWallet) LockedOutpoints() []*wire.OutPoint {
outPoints := make([]*wire.OutPoint, 0, len(l.lockedOutPoints)) outPoints := make([]*wire.OutPoint, 0, len(l.lockedOutPoints))
for outPoint := range l.lockedOutPoints { for outPoint := range l.lockedOutPoints {

@ -55,17 +55,17 @@ func (a *ChannelAnnouncement) Validate() error {
// io.Reader observing the specified protocol version. // io.Reader observing the specified protocol version.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelAnnouncement) Decode(r io.Reader, pver uint32) error { func (a *ChannelAnnouncement) Decode(r io.Reader, pver uint32) error {
return readElements(r, return readElements(r,
&c.FirstNodeSig, &a.FirstNodeSig,
&c.SecondNodeSig, &a.SecondNodeSig,
&c.ChannelID, &a.ChannelID,
&c.FirstBitcoinSig, &a.FirstBitcoinSig,
&c.SecondBitcoinSig, &a.SecondBitcoinSig,
&c.FirstNodeID, &a.FirstNodeID,
&c.SecondNodeID, &a.SecondNodeID,
&c.FirstBitcoinKey, &a.FirstBitcoinKey,
&c.SecondBitcoinKey, &a.SecondBitcoinKey,
) )
} }
@ -73,17 +73,17 @@ func (c *ChannelAnnouncement) Decode(r io.Reader, pver uint32) error {
// observing the protocol version specified. // observing the protocol version specified.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelAnnouncement) Encode(w io.Writer, pver uint32) error { func (a *ChannelAnnouncement) Encode(w io.Writer, pver uint32) error {
return writeElements(w, return writeElements(w,
c.FirstNodeSig, a.FirstNodeSig,
c.SecondNodeSig, a.SecondNodeSig,
c.ChannelID, a.ChannelID,
c.FirstBitcoinSig, a.FirstBitcoinSig,
c.SecondBitcoinSig, a.SecondBitcoinSig,
c.FirstNodeID, a.FirstNodeID,
c.SecondNodeID, a.SecondNodeID,
c.FirstBitcoinKey, a.FirstBitcoinKey,
c.SecondBitcoinKey, a.SecondBitcoinKey,
) )
} }
@ -91,7 +91,7 @@ func (c *ChannelAnnouncement) Encode(w io.Writer, pver uint32) error {
// wire. // wire.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelAnnouncement) Command() uint32 { func (a *ChannelAnnouncement) Command() uint32 {
return CmdChannelAnnoucmentMessage return CmdChannelAnnoucmentMessage
} }
@ -99,7 +99,7 @@ func (c *ChannelAnnouncement) Command() uint32 {
// observing the specified protocol version. // observing the specified protocol version.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelAnnouncement) MaxPayloadLength(pver uint32) uint32 { func (a *ChannelAnnouncement) MaxPayloadLength(pver uint32) uint32 {
var length uint32 var length uint32
// FirstNodeSig - 64 bytes // FirstNodeSig - 64 bytes
@ -134,17 +134,17 @@ func (c *ChannelAnnouncement) MaxPayloadLength(pver uint32) uint32 {
// DataToSign is used to retrieve part of the announcement message which // DataToSign is used to retrieve part of the announcement message which
// should be signed. // should be signed.
func (c *ChannelAnnouncement) DataToSign() ([]byte, error) { func (a *ChannelAnnouncement) DataToSign() ([]byte, error) {
// We should not include the signatures itself. // We should not include the signatures itself.
var w bytes.Buffer var w bytes.Buffer
err := writeElements(&w, err := writeElements(&w,
c.ChannelID, a.ChannelID,
c.FirstBitcoinSig, a.FirstBitcoinSig,
c.SecondBitcoinSig, a.SecondBitcoinSig,
c.FirstNodeID, a.FirstNodeID,
c.SecondNodeID, a.SecondNodeID,
c.FirstBitcoinKey, a.FirstBitcoinKey,
c.SecondBitcoinKey, a.SecondBitcoinKey,
) )
if err != nil { if err != nil {
return nil, err return nil, err

@ -71,16 +71,16 @@ func (a *ChannelUpdateAnnouncement) Validate() error {
// passed io.Reader observing the specified protocol version. // passed io.Reader observing the specified protocol version.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelUpdateAnnouncement) Decode(r io.Reader, pver uint32) error { func (a *ChannelUpdateAnnouncement) Decode(r io.Reader, pver uint32) error {
return readElements(r, return readElements(r,
&c.Signature, &a.Signature,
&c.ChannelID, &a.ChannelID,
&c.Timestamp, &a.Timestamp,
&c.Flags, &a.Flags,
&c.TimeLockDelta, &a.TimeLockDelta,
&c.HtlcMinimumMsat, &a.HtlcMinimumMsat,
&c.FeeBaseMsat, &a.FeeBaseMsat,
&c.FeeProportionalMillionths, &a.FeeProportionalMillionths,
) )
} }
@ -88,16 +88,16 @@ func (c *ChannelUpdateAnnouncement) Decode(r io.Reader, pver uint32) error {
// io.Writer observing the protocol version specified. // io.Writer observing the protocol version specified.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelUpdateAnnouncement) Encode(w io.Writer, pver uint32) error { func (a *ChannelUpdateAnnouncement) Encode(w io.Writer, pver uint32) error {
return writeElements(w, return writeElements(w,
c.Signature, a.Signature,
c.ChannelID, a.ChannelID,
c.Timestamp, a.Timestamp,
c.Flags, a.Flags,
c.TimeLockDelta, a.TimeLockDelta,
c.HtlcMinimumMsat, a.HtlcMinimumMsat,
c.FeeBaseMsat, a.FeeBaseMsat,
c.FeeProportionalMillionths, a.FeeProportionalMillionths,
) )
} }
@ -105,7 +105,7 @@ func (c *ChannelUpdateAnnouncement) Encode(w io.Writer, pver uint32) error {
// wire. // wire.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelUpdateAnnouncement) Command() uint32 { func (a *ChannelUpdateAnnouncement) Command() uint32 {
return CmdChannelUpdateAnnoucmentMessage return CmdChannelUpdateAnnoucmentMessage
} }
@ -113,7 +113,7 @@ func (c *ChannelUpdateAnnouncement) Command() uint32 {
// observing the specified protocol version. // observing the specified protocol version.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *ChannelUpdateAnnouncement) MaxPayloadLength(pver uint32) uint32 { func (a *ChannelUpdateAnnouncement) MaxPayloadLength(pver uint32) uint32 {
var length uint32 var length uint32
// Signature - 64 bytes // Signature - 64 bytes
@ -145,18 +145,18 @@ func (c *ChannelUpdateAnnouncement) MaxPayloadLength(pver uint32) uint32 {
// DataToSign is used to retrieve part of the announcement message which // DataToSign is used to retrieve part of the announcement message which
// should be signed. // should be signed.
func (c *ChannelUpdateAnnouncement) DataToSign() ([]byte, error) { func (a *ChannelUpdateAnnouncement) DataToSign() ([]byte, error) {
// We should not include the signatures itself. // We should not include the signatures itself.
var w bytes.Buffer var w bytes.Buffer
err := writeElements(&w, err := writeElements(&w,
c.ChannelID, a.ChannelID,
c.Timestamp, a.Timestamp,
c.Flags, a.Flags,
c.TimeLockDelta, a.TimeLockDelta,
c.HtlcMinimumMsat, a.HtlcMinimumMsat,
c.FeeBaseMsat, a.FeeBaseMsat,
c.FeeProportionalMillionths, a.FeeProportionalMillionths,
) )
if err != nil { if err != nil {
return nil, err return nil, err

@ -101,7 +101,7 @@ func (c *CloseRequest) MaxPayloadLength(pver uint32) uint32 {
func (c *CloseRequest) Validate() error { func (c *CloseRequest) Validate() error {
// Fee must be greater than 0. // Fee must be greater than 0.
if c.Fee < 0 { if c.Fee < 0 {
return fmt.Errorf("Fee must be greater than zero.") return fmt.Errorf("fee must be greater than zero")
} }
// We're good! // We're good!

@ -205,12 +205,11 @@ func (f *FeatureVector) Encode(w io.Writer) error {
// were present in both remote and local feature vectors. If remote/local node // were present in both remote and local feature vectors. If remote/local node
// doesn't have the feature and local/remote node require it than such vectors // doesn't have the feature and local/remote node require it than such vectors
// are incompatible. // are incompatible.
func (local *FeatureVector) Compare(remote *FeatureVector) (*SharedFeatures, func (f *FeatureVector) Compare(f2 *FeatureVector) (*SharedFeatures, error) {
error) { shared := newSharedFeatures(f.Copy())
shared := newSharedFeatures(local.Copy())
for index, flag := range local.flags { for index, flag := range f.flags {
if _, exist := remote.flags[index]; !exist { if _, exist := f2.flags[index]; !exist {
switch flag { switch flag {
case RequiredFlag: case RequiredFlag:
return nil, errors.New("Remote node hasn't " + return nil, errors.New("Remote node hasn't " +
@ -228,8 +227,8 @@ func (local *FeatureVector) Compare(remote *FeatureVector) (*SharedFeatures,
shared.flags[index] = flag shared.flags[index] = flag
} }
for index, flag := range remote.flags { for index, flag := range f2.flags {
if _, exist := local.flags[index]; !exist { if _, exist := f.flags[index]; !exist {
switch flag { switch flag {
case RequiredFlag: case RequiredFlag:
return nil, errors.New("Local node hasn't " + return nil, errors.New("Local node hasn't " +

@ -128,7 +128,7 @@ func writeElement(w io.Writer, element interface{}) error {
// Enforce a sane number for the maximum number of signatures. // Enforce a sane number for the maximum number of signatures.
numSigs := len(e) numSigs := len(e)
if numSigs > 127 { if numSigs > 127 {
return fmt.Errorf("Too many signatures!") return fmt.Errorf("too many signatures")
} }
// First write out the the number of elements in the slice as a // First write out the the number of elements in the slice as a
@ -186,7 +186,7 @@ func writeElement(w io.Writer, element interface{}) error {
// Make sure it's P2PKH or P2SH size or less. // Make sure it's P2PKH or P2SH size or less.
scriptLength := len(e) scriptLength := len(e)
if scriptLength > 25 { if scriptLength > 25 {
return fmt.Errorf("PkScript too long!") return fmt.Errorf("'PkScript' too long")
} }
if err := wire.WriteVarBytes(w, 0, e); err != nil { if err := wire.WriteVarBytes(w, 0, e); err != nil {
@ -195,7 +195,7 @@ func writeElement(w io.Writer, element interface{}) error {
case string: case string:
strlen := len(e) strlen := len(e)
if strlen > MaxSliceLength { if strlen > MaxSliceLength {
return fmt.Errorf("String too long!") return fmt.Errorf("string too long")
} }
if err := wire.WriteVarString(w, 0, e); err != nil { if err := wire.WriteVarString(w, 0, e); err != nil {
@ -429,7 +429,7 @@ func readElement(r io.Reader, element interface{}) error {
return err return err
} }
if numSigs > 127 { if numSigs > 127 {
return fmt.Errorf("Too many signatures!") return fmt.Errorf("too many signatures")
} }
// Read that number of signatures // Read that number of signatures

@ -1,6 +1,7 @@
// Code derived from https:// github.com/btcsuite/btcd/blob/master/wire/message.go
package lnwire package lnwire
// code derived from https://github .com/btcsuite/btcd/blob/master/wire/message.go
import ( import (
"bytes" "bytes"
"fmt" "fmt"
@ -247,7 +248,7 @@ func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet wire.BitcoinNet)
return totalBytes, err return totalBytes, err
} }
// ReadMessageN reads, validates, and parses the next bitcoin Message from r for // ReadMessage reads, validates, and parses the next bitcoin Message from r for
// the provided protocol version and bitcoin network. It returns the number of // the provided protocol version and bitcoin network. It returns the number of
// bytes read in addition to the parsed Message and raw bytes which comprise the // bytes read in addition to the parsed Message and raw bytes which comprise the
// message. This function is the same as ReadMessage except it also returns the // message. This function is the same as ReadMessage except it also returns the

@ -127,15 +127,15 @@ func (a *NodeAnnouncement) Validate() error {
// io.Reader observing the specified protocol version. // io.Reader observing the specified protocol version.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *NodeAnnouncement) Decode(r io.Reader, pver uint32) error { func (a *NodeAnnouncement) Decode(r io.Reader, pver uint32) error {
return readElements(r, return readElements(r,
&c.Signature, &a.Signature,
&c.Timestamp, &a.Timestamp,
&c.Address, &a.Address,
&c.NodeID, &a.NodeID,
&c.RGBColor, &a.RGBColor,
&c.pad, &a.pad,
&c.Alias, &a.Alias,
) )
} }
@ -143,15 +143,15 @@ func (c *NodeAnnouncement) Decode(r io.Reader, pver uint32) error {
// observing the protocol version specified. // observing the protocol version specified.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *NodeAnnouncement) Encode(w io.Writer, pver uint32) error { func (a *NodeAnnouncement) Encode(w io.Writer, pver uint32) error {
return writeElements(w, return writeElements(w,
c.Signature, a.Signature,
c.Timestamp, a.Timestamp,
c.Address, a.Address,
c.NodeID, a.NodeID,
c.RGBColor, a.RGBColor,
c.pad, a.pad,
c.Alias, a.Alias,
) )
} }
@ -159,7 +159,7 @@ func (c *NodeAnnouncement) Encode(w io.Writer, pver uint32) error {
// wire. // wire.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *NodeAnnouncement) Command() uint32 { func (a *NodeAnnouncement) Command() uint32 {
return CmdNodeAnnoucmentMessage return CmdNodeAnnoucmentMessage
} }
@ -167,7 +167,7 @@ func (c *NodeAnnouncement) Command() uint32 {
// observing the specified protocol version. // observing the specified protocol version.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (c *NodeAnnouncement) MaxPayloadLength(pver uint32) uint32 { func (a *NodeAnnouncement) MaxPayloadLength(pver uint32) uint32 {
var length uint32 var length uint32
// Signature - 64 bytes // Signature - 64 bytes
@ -198,18 +198,18 @@ func (c *NodeAnnouncement) MaxPayloadLength(pver uint32) uint32 {
return length return length
} }
// dataToSign... // DataToSign returns the part of the message that should be signed.
func (c *NodeAnnouncement) DataToSign() ([]byte, error) { func (a *NodeAnnouncement) DataToSign() ([]byte, error) {
// We should not include the signatures itself. // We should not include the signatures itself.
var w bytes.Buffer var w bytes.Buffer
err := writeElements(&w, err := writeElements(&w,
c.Timestamp, a.Timestamp,
c.Address, a.Address,
c.NodeID, a.NodeID,
c.RGBColor, a.RGBColor,
c.pad, a.pad,
c.Alias, a.Alias,
) )
if err != nil { if err != nil {
return nil, err return nil, err

@ -32,10 +32,9 @@ func serializeSigToWire(b *[64]byte, e *btcec.Signature) error {
if (sLen > 33) || (sig[6+rLen] != 0x00) { if (sLen > 33) || (sig[6+rLen] != 0x00) {
return fmt.Errorf("S is over 32 bytes long " + return fmt.Errorf("S is over 32 bytes long " +
"without padding") "without padding")
} else {
sLen -= 1
copy(b[64-sLen:], sig[7+rLen:])
} }
sLen--
copy(b[64-sLen:], sig[7+rLen:])
} else { } else {
copy(b[64-sLen:], sig[6+rLen:]) copy(b[64-sLen:], sig[6+rLen:])
} }
@ -45,10 +44,9 @@ func serializeSigToWire(b *[64]byte, e *btcec.Signature) error {
if (rLen > 33) || (sig[4] != 0x00) { if (rLen > 33) || (sig[4] != 0x00) {
return fmt.Errorf("R is over 32 bytes long " + return fmt.Errorf("R is over 32 bytes long " +
"without padding") "without padding")
} else {
rLen -= 1
copy(b[32-rLen:], sig[5:5+rLen])
} }
rLen--
copy(b[32-rLen:], sig[5:5+rLen])
} else { } else {
copy(b[32-rLen:], sig[4:4+rLen]) copy(b[32-rLen:], sig[4:4+rLen])
} }
@ -96,9 +94,8 @@ func extractCanonicalPadding(b []byte) []byte {
// If the MSB is set, we need zero padding. // If the MSB is set, we need zero padding.
if b[i]&0x80 == 0x80 { if b[i]&0x80 == 0x80 {
return append([]byte{0x00}, b[i:]...) return append([]byte{0x00}, b[i:]...)
} else {
return b[i:]
} }
return b[i:]
} }
} }
return []byte{0x00} return []byte{0x00}

@ -222,22 +222,23 @@ func (c *SingleFundingRequest) MaxPayloadLength(uint32) uint32 {
func (c *SingleFundingRequest) Validate() error { func (c *SingleFundingRequest) Validate() error {
// Negative values is are allowed. // Negative values is are allowed.
if c.FeePerKb < 0 { if c.FeePerKb < 0 {
return fmt.Errorf("MinFeePerKb cannot be negative") return fmt.Errorf("'MinFeePerKb' cannot be negative")
} }
if c.FundingAmount < 0 { if c.FundingAmount < 0 {
return fmt.Errorf("FundingAmount cannot be negative") return fmt.Errorf("'FundingAmount' cannot be negative")
} }
// The CSV delay MUST be non-zero. // The CSV delay MUST be non-zero.
if c.CsvDelay == 0 { if c.CsvDelay == 0 {
return fmt.Errorf("Commitment transaction must have non-zero " + return fmt.Errorf("commitment transaction must have non-zero" +
"CSV delay") " CSV delay")
} }
// The channel derivation point must be non-nil, and have an odd // The channel derivation point must be non-nil, and have an odd
// y-coordinate. // y-coordinate.
if c.ChannelDerivationPoint == nil { if c.ChannelDerivationPoint == nil {
return fmt.Errorf("The channel derivation point must be non-nil") return fmt.Errorf("the channel derivation point must be " +
"non-nil")
} }
//if c.ChannelDerivationPoint.Y.Bit(0) != 1 { //if c.ChannelDerivationPoint.Y.Bit(0) != 1 {
//return fmt.Errorf("The channel derivation point must have an odd " + //return fmt.Errorf("The channel derivation point must have an odd " +
@ -248,12 +249,12 @@ func (c *SingleFundingRequest) Validate() error {
// templates. // templates.
if !isValidPkScript(c.DeliveryPkScript) { if !isValidPkScript(c.DeliveryPkScript) {
// TODO(roasbeef): move into actual error // TODO(roasbeef): move into actual error
return fmt.Errorf("Valid delivery public key scripts MUST be: " + return fmt.Errorf("valid delivery public key scripts MUST " +
"P2PKH, P2WKH, P2SH, or P2WSH.") "be: P2PKH, P2WKH, P2SH, or P2WSH")
} }
if c.DustLimit <= 0 { if c.DustLimit <= 0 {
return fmt.Errorf("Dust limit should be greater than zero.") return fmt.Errorf("DustLimit' should be greater than zero")
} }
if c.ConfirmationDepth == 0 { if c.ConfirmationDepth == 0 {

@ -78,8 +78,8 @@ func (c *SingleFundingSignComplete) MaxPayloadLength(uint32) uint32 {
// for field sanity. // for field sanity.
// //
// This is part of the lnwire.Message interface. // This is part of the lnwire.Message interface.
func (s *SingleFundingSignComplete) Validate() error { func (c *SingleFundingSignComplete) Validate() error {
if s.CommitSignature == nil { if c.CommitSignature == nil {
return fmt.Errorf("commitment signature must be non-nil") return fmt.Errorf("commitment signature must be non-nil")
} }

@ -126,7 +126,7 @@ func (c *UpdateAddHTLC) Validate() error {
if c.Amount < 0 { if c.Amount < 0 {
// While fees can be negative, it's too confusing to allow // While fees can be negative, it's too confusing to allow
// negative payments. Maybe for some wallets, but not this one! // negative payments. Maybe for some wallets, but not this one!
return fmt.Errorf("Amount paid cannot be negative.") return fmt.Errorf("amount paid cannot be negative")
} }
// We're good! // We're good!
return nil return nil

@ -6,7 +6,7 @@ import (
"github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcd/wire"
) )
// FailReason specifies the precise reason that an upstream HTLC was cancelled. // FailCode specifies the precise reason that an upstream HTLC was cancelled.
// Each UpdateFailHTLC message carries a FailCode which is to be passed back // Each UpdateFailHTLC message carries a FailCode which is to be passed back
// unaltered to the source of the HTLC within the route. // unaltered to the source of the HTLC within the route.
// //

@ -124,7 +124,7 @@ type aliasMap map[string]*btcec.PublicKey
// parseTestGraph returns a fully populated ChannelGraph given a path to a JSON // parseTestGraph returns a fully populated ChannelGraph given a path to a JSON
// file which encodes a test graph. // file which encodes a test graph.
func parseTestGraph(path string) (*channeldb.ChannelGraph, func(), aliasMap, error) { func parseTestGraph(path string) (*channeldb.ChannelGraph, func(), aliasMap, error) {
graphJson, err := ioutil.ReadFile(path) graphJSON, err := ioutil.ReadFile(path)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@ -133,7 +133,7 @@ func parseTestGraph(path string) (*channeldb.ChannelGraph, func(), aliasMap, err
// struct. Using the struct tags created above in the struct, the JSON // struct. Using the struct tags created above in the struct, the JSON
// will be properly parsed into the struct above. // will be properly parsed into the struct above.
var g testGraph var g testGraph
if err := json.Unmarshal(graphJson, &g); err != nil { if err := json.Unmarshal(graphJSON, &g); err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@ -177,12 +177,12 @@ func parseTestGraph(path string) (*channeldb.ChannelGraph, func(), aliasMap, err
if _, ok := aliasMap[node.Alias]; ok { if _, ok := aliasMap[node.Alias]; ok {
return nil, nil, nil, errors.New("aliases for nodes " + return nil, nil, nil, errors.New("aliases for nodes " +
"must be unique!") "must be unique!")
} else {
// If the alias is unique, then add the node to the
// alias map for easy lookup.
aliasMap[node.Alias] = pub
} }
// If the alias is unique, then add the node to the
// alias map for easy lookup.
aliasMap[node.Alias] = pub
// If the node is tagged as the source, then we create a // If the node is tagged as the source, then we create a
// pointer to is so we can mark the source in the graph // pointer to is so we can mark the source in the graph
// properly. // properly.

@ -1029,7 +1029,7 @@ type routingMsg struct {
peer *btcec.PublicKey peer *btcec.PublicKey
} }
// ProcessRoutingMessags sends a new routing message along with the peer that // ProcessRoutingMessage sends a new routing message along with the peer that
// sent the routing message to the ChannelRouter. The announcement will be // sent the routing message to the ChannelRouter. The announcement will be
// processed then added to a queue for batched tickled announcement to all // processed then added to a queue for batched tickled announcement to all
// connected peers. // connected peers.

@ -63,9 +63,9 @@ func (e *element) derive(toIndex index) (*element, error) {
} }
// isEqual returns true if two elements are identical and false otherwise. // isEqual returns true if two elements are identical and false otherwise.
func (first *element) isEqual(second *element) bool { func (e *element) isEqual(e2 *element) bool {
return (first.index == second.index) && return (e.index == e2.index) &&
(&first.hash).IsEqual(&second.hash) (&e.hash).IsEqual(&e2.hash)
} }
const ( const (

@ -18,7 +18,7 @@ func bitsToIndex(bs ...uint64) (index, error) {
" 64") " 64")
} }
var res uint64 = 0 var res uint64
for i, e := range bs { for i, e := range bs {
if e != 1 && e != 0 { if e != 1 && e != 0 {
return 0, errors.New("wrong element, should be '0' or" + return 0, errors.New("wrong element, should be '0' or" +

@ -45,7 +45,7 @@ func getPrefix(index index, position uint8) uint64 {
// | 0 | 1 | 1 | 1 | // | 0 | 1 | 1 | 1 |
// + -- + ----- + ---- + ------ + // + -- + ----- + ---- + ------ +
var zero uint64 = 0 var zero uint64
mask := (zero - 1) - uint64((1<<position)-1) mask := (zero - 1) - uint64((1<<position)-1)
return (uint64(index) & mask) return (uint64(index) & mask)
} }
@ -53,7 +53,7 @@ func getPrefix(index index, position uint8) uint64 {
// countTrailingZeros count number of of trailing zero bits, this function is // countTrailingZeros count number of of trailing zero bits, this function is
// used to determine the number of element bucket. // used to determine the number of element bucket.
func countTrailingZeros(index index) uint8 { func countTrailingZeros(index index) uint8 {
var zeros uint8 = 0 var zeros uint8
for ; zeros < maxHeight; zeros++ { for ; zeros < maxHeight; zeros++ {
if getBit(index, zeros) != 0 { if getBit(index, zeros) != 0 {