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
// connection establishment. In the case of a successful handshake, all
// 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.
type Conn struct {
conn net.Conn
noise *BrontideMachine
noise *Machine
readBuf bytes.Buffer
}

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

@ -299,7 +299,7 @@ func newHandshakeState(initiator bool, prologue []byte,
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
// framework, specifically implementing the Noise_XK handshake. Once the
// 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, ee
// -> s, se
type BrontideMachine struct {
type Machine struct {
sendCipher cipherState
recvCipher cipherState
@ -336,12 +336,12 @@ type BrontideMachine struct {
// be nil. The handshake state within brontide is initialized using the ascii
// string "bitcoin" as the prologue.
func NewBrontideMachine(initiator bool, localPub *btcec.PrivateKey,
remotePub *btcec.PublicKey) *BrontideMachine {
remotePub *btcec.PublicKey) *Machine {
handshake := newHandshakeState(initiator, []byte("lightning"), localPub,
remotePub)
return &BrontideMachine{handshakeState: handshake}
return &Machine{handshakeState: handshake}
}
const (
@ -381,7 +381,7 @@ const (
// derived from this result.
//
// -> e, es
func (b *BrontideMachine) GenActOne() ([ActOneSize]byte, error) {
func (b *Machine) GenActOne() ([ActOneSize]byte, error) {
var (
err error
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
// handshake digest and deriving a new shared secret based on a ECDH with the
// 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 (
err error
e [33]byte
@ -453,7 +453,7 @@ func (b *BrontideMachine) RecvActOne(actOne [ActOneSize]byte) error {
// initiator's and responder's ephemeral keys.
//
// <- e, ee
func (b *BrontideMachine) GenActTwo() ([ActTwoSize]byte, error) {
func (b *Machine) GenActTwo() ([ActTwoSize]byte, error) {
var (
err error
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
// the initiator. A successful processing of this packet authenticates the
// initiator to the responder.
func (b *BrontideMachine) RecvActTwo(actTwo [ActTwoSize]byte) error {
func (b *Machine) RecvActTwo(actTwo [ActTwoSize]byte) error {
var (
err error
e [33]byte
@ -523,7 +523,7 @@ func (b *BrontideMachine) RecvActTwo(actTwo [ActTwoSize]byte) error {
// the final session.
//
// -> s, se
func (b *BrontideMachine) GenActThree() ([ActThreeSize]byte, error) {
func (b *Machine) GenActThree() ([ActThreeSize]byte, error) {
var actThree [ActThreeSize]byte
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
// initiator's static public key. Decryption of the static key serves to
// authenticate the initiator to the responder.
func (b *BrontideMachine) RecvActThree(actThree [ActThreeSize]byte) error {
func (b *Machine) RecvActThree(actThree [ActThreeSize]byte) error {
var (
err error
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
// responder, and another which is used to encrypt message for the opposite
// direction.
func (b *BrontideMachine) split() {
func (b *Machine) split() {
var (
empty []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
// must be used as the AD to the AEAD construction when being decrypted by the
// 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
// payload exceed the largest number encodable within a 16-bit unsigned
// 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
// 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
if _, err := io.ReadFull(r, cipherLen[:]); err != nil {
return nil, err

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

@ -591,7 +591,7 @@ type spendCancel struct {
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 detected, the details of the spending event will be sent
// across the 'Spend' channel.
@ -667,7 +667,7 @@ type confirmationsNotification struct {
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
// confirmations.
func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,

@ -7,7 +7,7 @@ import (
"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
// requests it.
var Log btclog.Logger

@ -212,7 +212,7 @@ func fileExists(path string) bool {
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
// known to have been created with this node, then a zero-length slice is
// returned.

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

@ -27,7 +27,7 @@ func TestVersionFetchPut(t *testing.T) {
t.Fatal("initialization of meta information wasn't performed")
}
var newVersion uint32 = getLatestDBVersion(dbVersions) + 1
newVersion := getLatestDBVersion(dbVersions) + 1
meta.DbVersionNumber = newVersion
if err := db.PutMeta(meta); err != nil {
@ -261,7 +261,7 @@ func TestMigrationWithFatal(t *testing.T) {
}
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.

@ -69,7 +69,7 @@ func (db *DB) AddPayment(payment *OutgoingPayment) error {
}
// Obtain the new unique sequence number for this payment.
paymentId, err := payments.NextSequence()
paymentID, err := payments.NextSequence()
if err != nil {
return err
}
@ -77,10 +77,10 @@ func (db *DB) AddPayment(payment *OutgoingPayment) error {
// We use BigEndian for keys as it orders keys in
// ascending order. This allows bucket scans to order payments
// in the order in which they were created.
paymentIdBytes := make([]byte, 8)
binary.BigEndian.PutUint64(paymentIdBytes, paymentId)
paymentIDBytes := make([]byte, 8)
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
// arguments.
func printJson(resp interface{}) {
func printJSON(resp interface{}) {
b, err := json.Marshal(resp)
if err != nil {
fatal(err)
@ -37,7 +37,7 @@ func printJson(resp interface{}) {
out.WriteTo(os.Stdout)
}
func printRespJson(resp proto.Message) {
func printRespJSON(resp proto.Message) {
jsonMarshaler := &jsonpb.Marshaler{
EmitDefaults: true,
Indent: " ",
@ -92,7 +92,7 @@ func newAddress(ctx *cli.Context) error {
return err
}
printRespJson(addr)
printRespJSON(addr)
return nil
}
@ -165,7 +165,7 @@ func sendCoins(ctx *cli.Context) error {
return err
}
printRespJson(txid)
printRespJSON(txid)
return nil
}
@ -200,7 +200,7 @@ func sendMany(ctx *cli.Context) error {
return err
}
printRespJson(txid)
printRespJSON(txid)
return nil
}
@ -245,7 +245,7 @@ func connectPeer(ctx *cli.Context) error {
return err
}
printRespJson(lnid)
printRespJSON(lnid)
return nil
}
@ -380,7 +380,7 @@ func openChannel(ctx *cli.Context) error {
return err
}
printJson(struct {
printJSON(struct {
FundingTxid string `json:"funding_txid"`
}{
FundingTxid: txid.String(),
@ -399,7 +399,7 @@ func openChannel(ctx *cli.Context) error {
}
index := channelPoint.OutputIndex
printJson(struct {
printJSON(struct {
ChannelPoint string `json:"channel_point"`
}{
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.
var CloseChannelCommand = cli.Command{
Name: "closechannel",
Usage: "Close an existing channel.",
@ -517,7 +518,7 @@ func closeChannel(ctx *cli.Context) error {
return err
}
printJson(struct {
printJSON(struct {
ClosingTXID string `json:"closing_txid"`
}{
ClosingTXID: txid.String(),
@ -534,7 +535,7 @@ func closeChannel(ctx *cli.Context) error {
return err
}
printJson(struct {
printJSON(struct {
ClosingTXID string `json:"closing_txid"`
}{
ClosingTXID: txid.String(),
@ -560,7 +561,7 @@ func listPeers(ctx *cli.Context) error {
return err
}
printRespJson(resp)
printRespJSON(resp)
return nil
}
@ -590,7 +591,7 @@ func walletBalance(ctx *cli.Context) error {
return err
}
printRespJson(resp)
printRespJSON(resp)
return nil
}
@ -611,7 +612,7 @@ func channelBalance(ctx *cli.Context) error {
return err
}
printRespJson(resp)
printRespJSON(resp)
return nil
}
@ -632,7 +633,7 @@ func getInfo(ctx *cli.Context) error {
return err
}
printRespJson(resp)
printRespJSON(resp)
return nil
}
@ -680,7 +681,7 @@ func pendingChannels(ctx *cli.Context) error {
return err
}
printRespJson(resp)
printRespJSON(resp)
return nil
}
@ -710,7 +711,7 @@ func listChannels(ctx *cli.Context) error {
// TODO(roasbeef): defer close the client for the all
printRespJson(resp)
printRespJSON(resp)
return nil
}
@ -844,7 +845,7 @@ func sendPaymentCommand(ctx *cli.Context) error {
paymentStream.CloseSend()
printJson(struct {
printJSON(struct {
P string `json:"payment_preimage"`
R *lnrpc.Route `json:"payment_route"`
}{
@ -936,7 +937,7 @@ func addInvoice(ctx *cli.Context) error {
return err
}
printJson(struct {
printJSON(struct {
RHash string `json:"r_hash"`
PayReq string `json:"pay_req"`
}{
@ -992,7 +993,7 @@ func lookupInvoice(ctx *cli.Context) error {
return err
}
printRespJson(invoice)
printRespJSON(invoice)
return nil
}
@ -1028,7 +1029,7 @@ func listInvoices(ctx *cli.Context) error {
return err
}
printRespJson(invoices)
printRespJSON(invoices)
return nil
}
@ -1064,7 +1065,7 @@ func describeGraph(ctx *cli.Context) error {
return drawChannelGraph(graph)
}
printRespJson(graph)
printRespJSON(graph)
return nil
}
@ -1233,7 +1234,7 @@ func listPayments(ctx *cli.Context) error {
return err
}
printRespJson(payments)
printRespJSON(payments)
return nil
}
@ -1280,7 +1281,7 @@ func getChanInfo(ctx *cli.Context) error {
return err
}
printRespJson(chanInfo)
printRespJSON(chanInfo)
return nil
}
@ -1317,7 +1318,7 @@ func getNodeInfo(ctx *cli.Context) error {
return err
}
printRespJson(nodeInfo)
printRespJSON(nodeInfo)
return nil
}
@ -1385,7 +1386,7 @@ func queryRoute(ctx *cli.Context) error {
return err
}
printRespJson(route)
printRespJSON(route)
return nil
}
@ -1409,7 +1410,7 @@ func getNetworkInfo(ctx *cli.Context) error {
return err
}
printRespJson(netInfo)
printRespJSON(netInfo)
return nil
}
@ -1445,7 +1446,7 @@ func debugLevel(ctx *cli.Context) error {
return err
}
printRespJson(resp)
printRespJSON(resp)
return nil
}
@ -1486,7 +1487,7 @@ func decodePayReq(ctx *cli.Context) error {
return err
}
printRespJson(resp)
printRespJSON(resp)
return nil
}

6
lnd.go

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

@ -23,7 +23,7 @@ func (b *BtcWallet) GetBestBlock() (*chainhash.Hash, int32, error) {
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.
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
// by the wallet for notifications, calls, etc.
rpcc, err := chain.NewRPCClient(cfg.NetParams, cfg.RpcHost,
cfg.RpcUser, cfg.RpcPass, cfg.CACert, false, 20)
rpcc, err := chain.NewRPCClient(cfg.NetParams, cfg.RPCHost,
cfg.RPCUser, cfg.RPCPass, cfg.CACert, false, 20)
if err != nil {
return nil, err
}
@ -208,9 +208,9 @@ func (b *BtcWallet) NewAddress(t lnwallet.AddressType, change bool) (btcutil.Add
if change {
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

@ -46,23 +46,23 @@ type Config struct {
// logger should use.
DebugLevel string
// RpcHost is the host and port to use to reach the rpc sever.
RpcHost string // localhost:18334
// RPCHost is the host and port to use to reach the rpc sever.
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.
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.
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.
RpcNoTLS bool
RPCNoTLS bool
// 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
RPCKey string

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

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

@ -51,7 +51,7 @@ type ChannelContribution struct {
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
// order to accommodate nested p2sh which utilizes both types of input scripts.
type InputScript struct {
@ -349,7 +349,7 @@ func (r *ChannelReservation) CompleteReservationSingle(
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
// wallet's version of the commitment transaction. This methods is provided for
// additional verification, such as needed by tests.
@ -393,7 +393,7 @@ func (r *ChannelReservation) LocalCommitTx() *wire.MsgTx {
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) {
r.Lock()
defer r.Unlock()

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

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

@ -390,7 +390,7 @@ func (l *LightningWallet) Shutdown() error {
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 {
outPoints := make([]*wire.OutPoint, 0, len(l.lockedOutPoints))
for outPoint := range l.lockedOutPoints {

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

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

@ -101,7 +101,7 @@ func (c *CloseRequest) MaxPayloadLength(pver uint32) uint32 {
func (c *CloseRequest) Validate() error {
// Fee must be greater than 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!

@ -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
// doesn't have the feature and local/remote node require it than such vectors
// are incompatible.
func (local *FeatureVector) Compare(remote *FeatureVector) (*SharedFeatures,
error) {
shared := newSharedFeatures(local.Copy())
func (f *FeatureVector) Compare(f2 *FeatureVector) (*SharedFeatures, error) {
shared := newSharedFeatures(f.Copy())
for index, flag := range local.flags {
if _, exist := remote.flags[index]; !exist {
for index, flag := range f.flags {
if _, exist := f2.flags[index]; !exist {
switch flag {
case RequiredFlag:
return nil, errors.New("Remote node hasn't " +
@ -228,8 +227,8 @@ func (local *FeatureVector) Compare(remote *FeatureVector) (*SharedFeatures,
shared.flags[index] = flag
}
for index, flag := range remote.flags {
if _, exist := local.flags[index]; !exist {
for index, flag := range f2.flags {
if _, exist := f.flags[index]; !exist {
switch flag {
case RequiredFlag:
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.
numSigs := len(e)
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
@ -186,7 +186,7 @@ func writeElement(w io.Writer, element interface{}) error {
// Make sure it's P2PKH or P2SH size or less.
scriptLength := len(e)
if scriptLength > 25 {
return fmt.Errorf("PkScript too long!")
return fmt.Errorf("'PkScript' too long")
}
if err := wire.WriteVarBytes(w, 0, e); err != nil {
@ -195,7 +195,7 @@ func writeElement(w io.Writer, element interface{}) error {
case string:
strlen := len(e)
if strlen > MaxSliceLength {
return fmt.Errorf("String too long!")
return fmt.Errorf("string too long")
}
if err := wire.WriteVarString(w, 0, e); err != nil {
@ -429,7 +429,7 @@ func readElement(r io.Reader, element interface{}) error {
return err
}
if numSigs > 127 {
return fmt.Errorf("Too many signatures!")
return fmt.Errorf("too many 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
// code derived from https://github .com/btcsuite/btcd/blob/master/wire/message.go
import (
"bytes"
"fmt"
@ -247,7 +248,7 @@ func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet wire.BitcoinNet)
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
// 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

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

@ -32,10 +32,9 @@ func serializeSigToWire(b *[64]byte, e *btcec.Signature) error {
if (sLen > 33) || (sig[6+rLen] != 0x00) {
return fmt.Errorf("S is over 32 bytes long " +
"without padding")
} else {
sLen -= 1
copy(b[64-sLen:], sig[7+rLen:])
}
sLen--
copy(b[64-sLen:], sig[7+rLen:])
} else {
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) {
return fmt.Errorf("R is over 32 bytes long " +
"without padding")
} else {
rLen -= 1
copy(b[32-rLen:], sig[5:5+rLen])
}
rLen--
copy(b[32-rLen:], sig[5:5+rLen])
} else {
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 b[i]&0x80 == 0x80 {
return append([]byte{0x00}, b[i:]...)
} else {
return b[i:]
}
return b[i:]
}
}
return []byte{0x00}

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

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

@ -126,7 +126,7 @@ func (c *UpdateAddHTLC) Validate() error {
if c.Amount < 0 {
// While fees can be negative, it's too confusing to allow
// 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!
return nil

@ -6,7 +6,7 @@ import (
"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
// 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
// file which encodes a test graph.
func parseTestGraph(path string) (*channeldb.ChannelGraph, func(), aliasMap, error) {
graphJson, err := ioutil.ReadFile(path)
graphJSON, err := ioutil.ReadFile(path)
if err != nil {
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
// will be properly parsed into the struct above.
var g testGraph
if err := json.Unmarshal(graphJson, &g); err != nil {
if err := json.Unmarshal(graphJSON, &g); err != nil {
return nil, nil, nil, err
}
@ -177,12 +177,12 @@ func parseTestGraph(path string) (*channeldb.ChannelGraph, func(), aliasMap, err
if _, ok := aliasMap[node.Alias]; ok {
return nil, nil, nil, errors.New("aliases for nodes " +
"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
// pointer to is so we can mark the source in the graph
// properly.

@ -1029,7 +1029,7 @@ type routingMsg struct {
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
// processed then added to a queue for batched tickled announcement to all
// 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.
func (first *element) isEqual(second *element) bool {
return (first.index == second.index) &&
(&first.hash).IsEqual(&second.hash)
func (e *element) isEqual(e2 *element) bool {
return (e.index == e2.index) &&
(&e.hash).IsEqual(&e2.hash)
}
const (

@ -18,7 +18,7 @@ func bitsToIndex(bs ...uint64) (index, error) {
" 64")
}
var res uint64 = 0
var res uint64
for i, e := range bs {
if e != 1 && e != 0 {
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 |
// + -- + ----- + ---- + ------ +
var zero uint64 = 0
var zero uint64
mask := (zero - 1) - uint64((1<<position)-1)
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
// used to determine the number of element bucket.
func countTrailingZeros(index index) uint8 {
var zeros uint8 = 0
var zeros uint8
for ; zeros < maxHeight; zeros++ {
if getBit(index, zeros) != 0 {