Address (most*) golint issues

* silence all golint complaints except for those caused by generated gRPC code in rpc.pb.go, as well as the OP_CHECKSEQUENCEVERIFY opcode in script_utils.go
This commit is contained in:
Paul Capestany 2016-01-18 02:59:01 -08:00
parent 26d9ae7f2b
commit ae0a28aea9
56 changed files with 441 additions and 300 deletions

View file

@ -12,7 +12,7 @@ import (
"github.com/lightningnetwork/lnd/chainntfs"
)
// BtcdNotifier...
// BtcdNotifier ...
type BtcdNotifier struct {
// TODO(roasbeef): refactor to use the new NotificationServer
conn ChainConnection
@ -37,7 +37,7 @@ type BtcdNotifier struct {
var _ chainntnfs.ChainNotifier = (*BtcdNotifier)(nil)
// NewBtcdNotifier...
// NewBtcdNotifier ...
func NewBtcdNotifier(c ChainConnection) (*BtcdNotifier, error) {
return &BtcdNotifier{
conn: c,
@ -57,7 +57,7 @@ func NewBtcdNotifier(c ChainConnection) (*BtcdNotifier, error) {
}, nil
}
// Start...
// Start ...
func (b *BtcdNotifier) Start() error {
// Already started?
if atomic.AddInt32(&b.started, 1) != 1 {
@ -71,7 +71,7 @@ func (b *BtcdNotifier) Start() error {
return nil
}
// Stop...
// Stop ...
func (b *BtcdNotifier) Stop() error {
// Already shutting down?
if atomic.AddInt32(&b.stopped, 1) != 1 {
@ -84,7 +84,7 @@ func (b *BtcdNotifier) Stop() error {
return nil
}
// notificationDispatcher...
// notificationDispatcher ...
func (b *BtcdNotifier) notificationDispatcher() {
out:
for {
@ -175,7 +175,7 @@ out:
}
}
// initAllNotifications...
// initAllNotifications ...
func (b *BtcdNotifier) initAllNotifications() error {
var err error
@ -195,14 +195,14 @@ func (b *BtcdNotifier) initAllNotifications() error {
return nil
}
// spendNotification....
// spendNotification ....
type spendNotification struct {
outpoint *wire.OutPoint
trigger *chainntnfs.NotificationTrigger
}
// confirmationNotification...
// confirmationNotification ...
// TODO(roasbeef): re-org funny business
type confirmationsNotification struct {
txid *wire.ShaHash
@ -213,7 +213,7 @@ type confirmationsNotification struct {
trigger *chainntnfs.NotificationTrigger
}
// RegisterSpendNotification...
// RegisterSpendNotification ...
// NOTE: eventChan MUST be buffered
func (b *BtcdNotifier) RegisterSpendNotification(outpoint *wire.OutPoint,
trigger *chainntnfs.NotificationTrigger) error {
@ -230,7 +230,7 @@ func (b *BtcdNotifier) RegisterSpendNotification(outpoint *wire.OutPoint,
return nil
}
// RegisterConfirmationsNotification...
// RegisterConfirmationsNotification ...
func (b *BtcdNotifier) RegisterConfirmationsNotification(txid *wire.ShaHash,
numConfs uint32, trigger *chainntnfs.NotificationTrigger) error {

View file

@ -5,7 +5,7 @@ import (
"github.com/btcsuite/btcwallet/wtxmgr"
)
// ChainConnection...
// ChainConnection ...
// Required in order to avoid an import cycle, and do aide in testing.
type ChainConnection interface {
ListenConnectedBlocks() (<-chan wtxmgr.BlockMeta, error)

View file

@ -11,6 +11,8 @@ import "github.com/btcsuite/btcd/wire"
// * electrum?
// * SPV bloomfilter
// * other stuff maybe...
// ChainNotifier ...
type ChainNotifier interface {
RegisterConfirmationsNotification(txid *wire.ShaHash, numConfs uint32, trigger *NotificationTrigger) error
RegisterSpendNotification(outpoint *wire.OutPoint, trigger *NotificationTrigger) error
@ -19,6 +21,7 @@ type ChainNotifier interface {
Stop() error
}
// NotificationTrigger ...
type NotificationTrigger struct {
TriggerChan chan struct{}
Callback func()

View file

@ -24,20 +24,22 @@ var (
identityKey = []byte("idkey")
// TODO(roasbeef): replace w/ tesnet-L also revisit dependancy...
// ActiveNetParams ...
ActiveNetParams = &chaincfg.TestNet3Params
)
// Payment...
// Payment ...
type Payment struct {
// r [32]byte
// path *Route
}
// ClosedChannel...
// ClosedChannel ...
type ClosedChannel struct {
}
// OpenChannel...
// OpenChannel ...
// TODO(roasbeef): store only the essentials? optimize space...
// TODO(roasbeef): switch to "column store"
type OpenChannel struct {
@ -98,8 +100,9 @@ type OpenChannel struct {
}
// These don't really belong here but not sure which other file to put them yet.
// PutIdKey saves the private key used for
func (c *DB) PutIdKey(pkh []byte) error {
// PutIDKey saves the private key used for
func (c *DB) PutIDKey(pkh []byte) error {
return c.namespace.Update(func(tx walletdb.Tx) error {
// Get the bucket dedicated to storing the meta-data for open
// channels.
@ -108,8 +111,8 @@ func (c *DB) PutIdKey(pkh []byte) error {
})
}
// GetIdKey returns the IdKey
func (c *DB) GetIdAdr() (*btcutil.AddressPubKeyHash, error) {
// GetIDAdr returns the IDKey
func (c *DB) GetIDAdr() (*btcutil.AddressPubKeyHash, error) {
var pkh []byte
err := c.namespace.View(func(tx walletdb.Tx) error {
// Get the bucket dedicated to storing the meta-data for open
@ -125,7 +128,7 @@ func (c *DB) GetIdAdr() (*btcutil.AddressPubKeyHash, error) {
return btcutil.NewAddressPubKeyHash(pkh, ActiveNetParams)
}
// PutOpenChannel...
// PutOpenChannel ...
func (c *DB) PutOpenChannel(channel *OpenChannel) error {
return c.namespace.Update(func(tx walletdb.Tx) error {
// Get the bucket dedicated to storing the meta-data for open
@ -140,7 +143,7 @@ func (c *DB) PutOpenChannel(channel *OpenChannel) error {
})
}
// GetOpenChannel...
// FetchOpenChannel ...
// TODO(roasbeef): assumes only 1 active channel per-node
func (c *DB) FetchOpenChannel(nodeID [32]byte) (*OpenChannel, error) {
var channel *OpenChannel
@ -166,7 +169,7 @@ func (c *DB) FetchOpenChannel(nodeID [32]byte) (*OpenChannel, error) {
return channel, err
}
// putChannel...
// putChannel ...
func putOpenChannel(activeChanBucket walletdb.Bucket, channel *OpenChannel,
addrmgr *waddrmgr.Manager) error {
@ -215,7 +218,7 @@ func fetchOpenChannel(bucket walletdb.Bucket, nodeID [32]byte,
return channel, nil
}
// Encode...
// Encode ...
// TODO(roasbeef): checksum
func (o *OpenChannel) Encode(b io.Writer, addrManager *waddrmgr.Manager) error {
if _, err := b.Write(o.TheirLNID[:]); err != nil {
@ -306,7 +309,7 @@ func (o *OpenChannel) Encode(b io.Writer, addrManager *waddrmgr.Manager) error {
return nil
}
// Decode...
// Decode ...
func (o *OpenChannel) Decode(b io.Reader, addrManager *waddrmgr.Manager) error {
var scratch [8]byte

View file

@ -17,7 +17,7 @@ var bufPool = &sync.Pool{
New: func() interface{} { return new(bytes.Buffer) },
}
// Store...
// DB ...
// TODO(roasbeef): CHECKSUMS, REDUNDANCY, etc etc.
type DB struct {
// TODO(roasbeef): caching, etc?
@ -26,7 +26,7 @@ type DB struct {
namespace walletdb.Namespace
}
// Wipe...
// Wipe ...
func (d *DB) Wipe() error {
return d.namespace.Update(func(tx walletdb.Tx) error {
rootBucket := tx.RootBucket()
@ -35,20 +35,20 @@ func (d *DB) Wipe() error {
})
}
// New...
// New ...
// TODO(roasbeef): re-visit this dependancy...
func New(addrmgr *waddrmgr.Manager, namespace walletdb.Namespace) *DB {
// TODO(roasbeef): create buckets if not created?
return &DB{addrmgr, namespace}
}
// Open...
// Open ...
// TODO(roasbeef): create+open, ditch New, fixes above
func Open() *DB {
return nil
}
// Create...
// Create ...
func Create() *DB {
return nil
}

View file

@ -10,7 +10,7 @@ import (
"golang.org/x/net/context"
)
func printRespJson(resp interface{}) {
func printRespJSON(resp interface{}) {
b, err := json.Marshal(resp)
if err != nil {
fatal(err)
@ -21,6 +21,7 @@ func printRespJson(resp interface{}) {
out.WriteTo(os.Stdout)
}
// ShellCommand ...
var ShellCommand = cli.Command{
Name: "shell",
Usage: "enter interactive shell",
@ -29,6 +30,7 @@ var ShellCommand = cli.Command{
},
}
// NewAddressCommand ...
var NewAddressCommand = cli.Command{
Name: "newaddress",
Usage: "gets the next address in the HD chain",
@ -44,9 +46,10 @@ func newAddress(ctx *cli.Context) {
fatal(err)
}
printRespJson(addr)
printRespJSON(addr)
}
// SendManyCommand ...
var SendManyCommand = cli.Command{
Name: "sendmany",
Usage: "create and broadcast a transaction paying the specified " +
@ -70,9 +73,10 @@ func sendMany(ctx *cli.Context) {
fatal(err)
}
printRespJson(txid)
printRespJSON(txid)
}
// ConnectCommand ...
var ConnectCommand = cli.Command{
Name: "connect",
Usage: "connect to a remote lnd peer: <lnid>@host",
@ -91,5 +95,5 @@ func connectPeer(ctx *cli.Context) {
fatal(err)
}
printRespJson(lnid)
printRespJSON(lnid)
}

View file

@ -8,8 +8,8 @@ import (
"google.golang.org/grpc"
)
// connects via grpc to the ln node. default (hardcoded?) local:10K
func RpcConnect(args []string) error {
// RPCConnect connects via grpc to the ln node. default (hardcoded?) local:10K
func RPCConnect(args []string) error {
// client := getClient(ctx)
opts := []grpc.DialOption{grpc.WithInsecure()}
conn, err := grpc.Dial("localhost:10000", opts...)
@ -38,6 +38,7 @@ func RpcConnect(args []string) error {
return nil
}
// LnConnect ...
func LnConnect(args []string) error {
if len(args) == 0 {
return fmt.Errorf("need: lnc pubkeyhash@hostname or pkh (via pbx)")

View file

@ -53,6 +53,7 @@ func shellPrompt() error {
}
}
// Shellparse ...
func Shellparse(cmdslice []string) error {
var err error
var args []string

View file

@ -34,28 +34,36 @@ as state, must store at most h+1 hashes and the index of each hash (h*(h+1)) bit
to compute a previous index, compute at most h hashes.
*/
// Node ...
// You can calculate h from i but I can't figure out how without taking
// O(i) ops. Feels like there should be a clever O(h) way. 1 byte, whatever.
type ElkremNode struct {
type Node struct {
i uint64 // index (ith node)
h uint8 // height of this node
sha *wire.ShaHash // hash
}
type ElkremSender struct {
// Sender ...
type Sender struct {
current uint64 // last sent hash index
treeHeight uint8 // height of tree (size is 2**height -1 )
maxIndex uint64 // top of the tree
root *wire.ShaHash // root hash of the tree
}
type ElkremReceiver struct {
current uint64 // last received index (actually don't need it?)
treeHeight uint8 // height of tree (size is 2**height -1 )
s []ElkremNode // store of received hashes, max size = height
// Receiver ...
type Receiver struct {
current uint64 // last received index (actually don't need it?)
treeHeight uint8 // height of tree (size is 2**height -1 )
s []Node // store of received hashes, max size = height
}
// LeftSha ...
func LeftSha(in wire.ShaHash) wire.ShaHash {
return wire.DoubleSha256SH(in.Bytes()) // left is sha(sha(in))
}
// RightSha ...
func RightSha(in wire.ShaHash) wire.ShaHash {
return wire.DoubleSha256SH(append(in.Bytes(), 0x01)) // sha(sha(in, 1))
}
@ -82,9 +90,9 @@ func descend(w, i uint64, h uint8, sha wire.ShaHash) (wire.ShaHash, error) {
return sha, nil
}
// Creates an Elkrem Sender from a root hash and tree height
func NewElkremSender(th uint8, r wire.ShaHash) ElkremSender {
var e ElkremSender
// NewSender creates an Elkrem Sender from a root hash and tree height
func NewSender(th uint8, r wire.ShaHash) Sender {
var e Sender
e.root = &r
e.treeHeight = th
// set max index based on tree height
@ -95,29 +103,31 @@ func NewElkremSender(th uint8, r wire.ShaHash) ElkremSender {
return e
}
// Creates an Elkrem Receiver from a tree height
func NewElkremReceiver(th uint8) ElkremReceiver {
var e ElkremReceiver
// NewReceiver creates an Elkrem Receiver from a tree height
func NewReceiver(th uint8) Receiver {
var e Receiver
e.treeHeight = th
return e
}
// Next() increments the index to the next hash and outputs it
func (e *ElkremSender) Next() (*wire.ShaHash, error) {
// Next increments the index to the next hash and outputs it
func (e *Sender) Next() (*wire.ShaHash, error) {
// increment index
e.current++
return e.AtIndex(e.current)
}
// AtIndex ...
// w is the wanted index, i is the root index
func (e *ElkremSender) AtIndex(w uint64) (*wire.ShaHash, error) {
func (e *Sender) AtIndex(w uint64) (*wire.ShaHash, error) {
out, err := descend(w, e.maxIndex, e.treeHeight, *e.root)
return &out, err
}
func (e *ElkremReceiver) AddNext(sha *wire.ShaHash) error {
// AddNext ...
func (e *Receiver) AddNext(sha *wire.ShaHash) error {
// note: careful about atomicity / disk writes here
var n ElkremNode
var n Node
n.sha = sha
t := len(e.s) - 1 // top of stack
if t > 0 && e.s[t-1].h == e.s[t].h { // top 2 elements are equal height
@ -140,8 +150,10 @@ func (e *ElkremReceiver) AddNext(sha *wire.ShaHash) error {
e.s = append(e.s, n) // append new node to stack
return nil
}
func (e *ElkremReceiver) AtIndex(w uint64) (*wire.ShaHash, error) {
var out ElkremNode // node we will eventually return
// AtIndex ...
func (e *Receiver) AtIndex(w uint64) (*wire.ShaHash, error) {
var out Node // node we will eventually return
for _, n := range e.s { // go through stack
if w <= n.i { // found one bigger than or equal to what we want
out = n

View file

@ -15,7 +15,7 @@ import (
"github.com/btcsuite/btcd/btcec"
)
// Conn...
// LNDConn ...
type LNDConn struct {
RemotePub *btcec.PublicKey
RemoteLNId [16]byte
@ -46,14 +46,14 @@ type LNDConn struct {
Conn net.Conn
}
// NewConn...
// NewConn ...
func NewConn(conn net.Conn) *LNDConn {
return &LNDConn{Conn: conn}
}
// Dial...
// Dial ...
func (c *LNDConn) Dial(
myId *btcec.PrivateKey, address string, remoteId []byte) error {
myID *btcec.PrivateKey, address string, remoteID []byte) error {
var err error
if !c.ViaPbx {
@ -68,19 +68,19 @@ func (c *LNDConn) Dial(
}
}
// Before dialing out to the remote host, verify that `remoteId` is either
// Before dialing out to the remote host, verify that `remoteID` is either
// a pubkey or a pubkey hash.
if len(remoteId) != 33 && len(remoteId) != 20 {
if len(remoteID) != 33 && len(remoteID) != 20 {
return fmt.Errorf("must supply either remote pubkey or " +
"pubkey hash")
}
// Calc remote LNId; need this for creating pbx connections just because
// LNid is in the struct does not mean it's authed!
if len(remoteId) == 20 {
copy(c.RemoteLNId[:], remoteId[:16])
if len(remoteID) == 20 {
copy(c.RemoteLNId[:], remoteID[:16])
} else {
theirAdr := btcutil.Hash160(remoteId)
theirAdr := btcutil.Hash160(remoteID)
copy(c.RemoteLNId[:], theirAdr[:16])
}
@ -131,12 +131,12 @@ func (c *LNDConn) Dial(
// Session is now open and confidential but not yet authenticated...
// So auth!
if len(remoteId) == 20 {
if len(remoteID) == 20 {
// Only know pubkey hash (20 bytes).
err = c.authPKH(myId, remoteId, ourEphemeralPub.SerializeCompressed())
err = c.authPKH(myID, remoteID, ourEphemeralPub.SerializeCompressed())
} else {
// Must be 33 byte pubkey.
err = c.authPubKey(myId, remoteId, ourEphemeralPub.SerializeCompressed())
err = c.authPubKey(myID, remoteID, ourEphemeralPub.SerializeCompressed())
}
if err != nil {
return err
@ -147,7 +147,7 @@ func (c *LNDConn) Dial(
// authPubKey...
func (c *LNDConn) authPubKey(
myId *btcec.PrivateKey, remotePubBytes, localEphPubBytes []byte) error {
myID *btcec.PrivateKey, remotePubBytes, localEphPubBytes []byte) error {
if c.Authed {
return fmt.Errorf("%s already authed", c.RemotePub)
}
@ -159,13 +159,13 @@ func (c *LNDConn) authPubKey(
return err
}
theirPKH := btcutil.Hash160(remotePubBytes)
idDH := fastsha256.Sum256(btcec.GenerateSharedSecret(myId, theirPub))
idDH := fastsha256.Sum256(btcec.GenerateSharedSecret(myID, theirPub))
myDHproof := btcutil.Hash160(append(c.RemotePub.SerializeCompressed(), idDH[:]...))
// Send over the 73 byte authentication message: my pubkey, their
// pubkey hash, DH proof.
var authMsg [73]byte
copy(authMsg[:33], myId.PubKey().SerializeCompressed())
copy(authMsg[:33], myID.PubKey().SerializeCompressed())
copy(authMsg[33:], theirPKH)
copy(authMsg[53:], myDHproof)
if _, err = c.Conn.Write(authMsg[:]); err != nil {
@ -196,7 +196,7 @@ func (c *LNDConn) authPubKey(
// authPKH...
func (c *LNDConn) authPKH(
myId *btcec.PrivateKey, theirPKH, localEphPubBytes []byte) error {
myID *btcec.PrivateKey, theirPKH, localEphPubBytes []byte) error {
if c.Authed {
return fmt.Errorf("%s already authed", c.RemotePub)
}
@ -207,7 +207,7 @@ func (c *LNDConn) authPKH(
// Send 53 bytes: our pubkey, and the remote's pubkey hash.
var greetingMsg [53]byte
copy(greetingMsg[:33], myId.PubKey().SerializeCompressed())
copy(greetingMsg[:33], myID.PubKey().SerializeCompressed())
copy(greetingMsg[:33], theirPKH)
if _, err := c.Conn.Write(greetingMsg[:]); err != nil {
return err
@ -227,7 +227,7 @@ func (c *LNDConn) authPKH(
if err != nil {
return err
}
idDH := fastsha256.Sum256(btcec.GenerateSharedSecret(myId, theirPub))
idDH := fastsha256.Sum256(btcec.GenerateSharedSecret(myID, theirPub))
fmt.Printf("made idDH %x\n", idDH)
theirDHproof := btcutil.Hash160(append(localEphPubBytes, idDH[:]...))

View file

@ -11,7 +11,7 @@ import (
"github.com/codahale/chacha20poly1305"
)
// Listener...
// Listener ...
type Listener struct {
longTermPriv *btcec.PrivateKey
@ -20,7 +20,7 @@ type Listener struct {
var _ net.Listener = (*Listener)(nil)
// NewListener...
// NewListener ...
func NewListener(localPriv *btcec.PrivateKey, listenAddr string) (*Listener, error) {
addr, err := net.ResolveTCPAddr("tcp", listenAddr)
if err != nil {
@ -115,7 +115,7 @@ func (l *Listener) createCipherConn(lnConn *LNDConn) (*btcec.PrivateKey, error)
// AuthListen...
func (l *Listener) authenticateConnection(
myId *btcec.PrivateKey, lnConn *LNDConn, localEphPubBytes []byte) error {
myID *btcec.PrivateKey, lnConn *LNDConn, localEphPubBytes []byte) error {
var err error
// TODO(roasbeef): should be using read/write clear here?

View file

@ -11,9 +11,9 @@ import (
"github.com/btcsuite/btcutil"
)
// lnAddr...
// LNAdr ...
type LNAdr struct {
lnId [16]byte // redundant because adr contains it
lnID [16]byte // redundant because adr contains it
PubKey *btcec.PublicKey
Base58Addr btcutil.Address // Base58 encoded address (1XXX...)
@ -25,17 +25,17 @@ type LNAdr struct {
// String...
func (l *LNAdr) String() string {
var encodedId []byte
var encodedID []byte
if l.PubKey == nil {
encodedId = l.Base58Addr.ScriptAddress()
encodedID = l.Base58Addr.ScriptAddress()
} else {
encodedId = l.PubKey.SerializeCompressed()
encodedID = l.PubKey.SerializeCompressed()
}
return fmt.Sprintf("%v@%v", encodedId, l.NetAddr)
return fmt.Sprintf("%v@%v", encodedID, l.NetAddr)
}
// newLnAddr...
// LnAddrFromString ...
func LnAddrFromString(encodedAddr string) (*LNAdr, error) {
// The format of an lnaddr is "<pubkey or pkh>@host"
idHost := strings.Split(encodedAddr, "@")
@ -86,7 +86,7 @@ func LnAddrFromString(encodedAddr string) (*LNAdr, error) {
}
// Finally, populate the lnid from the address.
copy(addr.lnId[:], addr.Base58Addr.ScriptAddress())
copy(addr.lnID[:], addr.Base58Addr.ScriptAddress())
return addr, nil
}

View file

@ -41,10 +41,11 @@ func (l *LNChannel) sendErrorPkt() {
//Will copy in code from channel.go...
// These constants are ...
const (
MAX_STAGED_HTLCS = 1000
MAX_UNREVOKED_COMMITMENTS = 16
MAX_UPDATED_HTLCS_PER_COMMITMENT = 1000
MaxStagedHTLCs = 1000
MaxUnrevokedCommitments = 16
MaxUpdatedHTLCsPerCommitment = 1000
)
//Currently, the mutex locks across the entire channel, it's possible to update
@ -69,24 +70,27 @@ const (
//signed/revoked, this means that the code is reliant upon this as knowing when
//to force close out channels, etc.
const (
//HTLC Add
ADD_PRESTAGE = 1000
ADD_STAGED = 1100
ADD_SIGNING_AND_REVOKING = 1200
ADD_COMPLETE = 1300 //Most HTLCs should be this
ADD_REJECTED = 1999 //Staging request rejected
// HTLC Add
AddPrestage = 1000
AddStaged = 1100
AddSigningAndRevoking = 1200
AddComplete = 1300 //Most HTLCs should be this
AddRejected = 1999 //Staging request rejected
//HTLC Timeout
TIMEOUT_PRESTAGE = 2000
TIMEOUT_STAGED = 2100
TIMEOUT_SIGNING_AND_REVOKING = 2200
TIMEOUT_COMPLETE = 2300
TimeoutPrestage = 2000
TimeoutStaged = 2100
TimeoutSigningAndRevoking = 2200
TimeoutComplete = 2300
//HTLC Settle
SETTLE_PRESTAGE = 3000
SETTLE_STAGED = 3100
SETTLE_SIGNING_AND_REVOKING = 3200
SETTLE_COMPLETE = 3300
SettlePrestage = 3000
SettleStaged = 3100
SettleSigningAndRevoking = 3200
SettleComplete = 3300
//TODO: Commitment states
)
@ -98,6 +102,7 @@ const (
//4. Update the state to account for revocation
//5. Both sides committed and revoked prior states, mark state as finished
// LNChannel ...
type LNChannel struct {
fundingTxIn *wire.TxIn
channelDB *channeldb.DB
@ -147,6 +152,7 @@ type LNChannel struct {
theirShaChain *shachain.HyperShaChain
}
// PaymentDescriptor ...
type PaymentDescriptor struct {
RHashes []*[20]byte
Timeout uint32
@ -179,7 +185,7 @@ type PaymentDescriptor struct {
//NOTE: **MUST** HAVE THE MUTEX LOCKED ALREADY WHEN CALLED
func (l *LNChannel) addHTLC(h *PaymentDescriptor) (lnwire.HTLCKey, error) {
//Sanity check
if h.State != ADD_PRESTAGE {
if h.State != AddPrestage {
return 0, fmt.Errorf("addHTLC can only add PRESTAGE")
}
@ -198,11 +204,11 @@ func (l *LNChannel) addHTLC(h *PaymentDescriptor) (lnwire.HTLCKey, error) {
//If it is, we iterate to the next one
if l.ourLastKey%1 == 1 {
if l.isEven {
l.ourLastKey += 1
l.ourLastKey++
}
} else {
if !l.isEven {
l.ourLastKey += 1
l.ourLastKey++
}
}
@ -213,16 +219,17 @@ func (l *LNChannel) addHTLC(h *PaymentDescriptor) (lnwire.HTLCKey, error) {
return l.ourLastKey, nil
}
// CreateHTLC ...
func (l *LNChannel) CreateHTLC(h *PaymentDescriptor) error {
l.Lock()
var err error
//if h.State == ADD_PRESTAGE {
//if h.State == AddPrestage {
// //We already have it created, but let's re-send!
// //Send a payment request LNWire
//}
if h.State > ADD_PRESTAGE {
if h.State > AddPrestage {
l.Unlock()
return fmt.Errorf("HTLC is already created!")
return fmt.Errorf("HTLC is already created")
}
if !h.PayToUs { //We created the payment
@ -233,7 +240,7 @@ func (l *LNChannel) CreateHTLC(h *PaymentDescriptor) error {
return err
}
//Update state as pre-commit
h.State = ADD_PRESTAGE
h.State = AddPrestage
if _, err := l.addHTLC(h); err != nil {
return err
}
@ -278,14 +285,14 @@ func (l *LNChannel) recvHTLCAddRequest(p *lnwire.HTLCAddRequest) error {
htlc.Timeout = p.Expiry
htlc.CreditsAmount = p.Amount
htlc.Blob = p.Blob
htlc.State = ADD_STAGED //mark as staged by both parties
htlc.PayToUs = true //assume this is paid to us, may change in the future
htlc.State = AddStaged //mark as staged by both parties
htlc.PayToUs = true //assume this is paid to us, may change in the future
//Validate the HTLC
err = l.validateHTLC(htlc, true)
if err != nil {
//Update state just in case (not used but y'know..)
htlc.State = ADD_REJECTED
htlc.State = AddRejected
//currently not yet added to staging
//so we don't need to worry about the above htlc
@ -327,10 +334,10 @@ func (l *LNChannel) recvAddReject(htlckey lnwire.HTLCKey) error {
if htlc == nil {
return fmt.Errorf("Counterparty rejected non-existent HTLC")
}
if htlc.State != ADD_PRESTAGE {
if htlc.State != AddPrestage {
return fmt.Errorf("Counterparty atttempted to reject invalid state")
}
htlc.State = ADD_REJECTED
htlc.State = AddRejected
disk()
return nil
@ -342,7 +349,7 @@ func (l *LNChannel) sendAddAccept(htlckey lnwire.HTLCKey) error {
msg := new(lnwire.HTLCAddAccept)
msg.ChannelID = l.channelID
msg.HTLCKey = htlckey
htlc.State = ADD_STAGED
htlc.State = AddStaged
disk()
net(msg)
@ -360,9 +367,9 @@ func (l *LNChannel) recvAddAccept(p *lnwire.HTLCAddAccept) error {
//Update pre-stage to staged
//Everything else it won't do anything
if htlc.State == ADD_PRESTAGE {
if htlc.State == AddPrestage {
//Update to staged
htlc.State = ADD_STAGED
htlc.State = AddStaged
disk()
}
return nil
@ -378,9 +385,9 @@ func (l *LNChannel) settleHTLC(htlcKey lnwire.HTLCKey) error {
//receive AddAcceptHTLC: Find the HTLC and call createHTLC
func (l *LNChannel) addAccept(h *PaymentDescriptor) error {
if h.State == ADD_PRESTAGE {
if h.State == AddPrestage {
//Mark stage as accepted
h.State = ADD_SIGNING_AND_REVOKING
h.State = AddSigningAndRevoking
//Write to disk
disk()
}

View file

@ -17,6 +17,8 @@ import (
const (
// TODO(roasbeef): make not random value
// MaxPendingPayments ...
MaxPendingPayments = 10
)
@ -25,7 +27,7 @@ const (
// payments requested by the wallet/daemon.
type PaymentHash [20]byte
// LightningChannel...
// LightningChannel ...
// TODO(roasbeef): future peer struct should embed this struct
type LightningChannel struct {
lnwallet *LightningWallet
@ -60,7 +62,7 @@ type LightningChannel struct {
wg sync.WaitGroup
}
// newLightningChannel...
// newLightningChannel ...
func newLightningChannel(wallet *LightningWallet, events chainntnfs.ChainNotifier,
chanDB *channeldb.DB, state *channeldb.OpenChannel) (*LightningChannel, error) {
@ -80,19 +82,19 @@ func newLightningChannel(wallet *LightningWallet, events chainntnfs.ChainNotifie
// Populate the totem.
lc.updateTotem <- struct{}{}
fundingTxId := state.FundingTx.TxSha()
fundingTxID := state.FundingTx.TxSha()
fundingPkScript, err := scriptHashPkScript(state.FundingRedeemScript)
if err != nil {
return nil, err
}
_, multiSigIndex := findScriptOutputIndex(state.FundingTx, fundingPkScript)
lc.fundingTxIn = wire.NewTxIn(wire.NewOutPoint(&fundingTxId, multiSigIndex), nil)
lc.fundingTxIn = wire.NewTxIn(wire.NewOutPoint(&fundingTxID, multiSigIndex), nil)
lc.fundingP2SH = fundingPkScript
return lc, nil
}
// PaymentDescriptor...
// PaymentDescriptor ...
type PaymentDescriptor struct {
RHash [20]byte
Timeout uint32
@ -104,7 +106,7 @@ type PaymentDescriptor struct {
PayToUs bool
}
// ChannelUpdate...
// ChannelUpdate ...
type ChannelUpdate struct {
pendingDesc *PaymentDescriptor
deletion bool
@ -124,7 +126,7 @@ type ChannelUpdate struct {
lnChannel *LightningChannel
}
// RevocationHash...
// RevocationHash ...
func (c *ChannelUpdate) RevocationHash() ([]byte, error) {
c.lnChannel.stateMtx.RLock()
defer c.lnChannel.stateMtx.RUnlock()
@ -138,7 +140,7 @@ func (c *ChannelUpdate) RevocationHash() ([]byte, error) {
return btcutil.Hash160(nextPreimage[:]), nil
}
// SignCounterPartyCommitment...
// SignCounterPartyCommitment ...
func (c *ChannelUpdate) SignCounterPartyCommitment() ([]byte, error) {
c.lnChannel.stateMtx.RLock()
defer c.lnChannel.stateMtx.RUnlock()
@ -160,7 +162,7 @@ func (c *ChannelUpdate) SignCounterPartyCommitment() ([]byte, error) {
return sig, nil
}
// PreviousRevocationPreImage...
// PreviousRevocationPreImage ...
func (c *ChannelUpdate) PreviousRevocationPreImage() ([]byte, error) {
c.lnChannel.stateMtx.RLock()
defer c.lnChannel.stateMtx.RUnlock()
@ -176,7 +178,7 @@ func (c *ChannelUpdate) PreviousRevocationPreImage() ([]byte, error) {
return revokePreImage[:], nil
}
// VerifyNewCommitmentSigs...
// VerifyNewCommitmentSigs ...
func (c *ChannelUpdate) VerifyNewCommitmentSigs(ourSig, theirSig []byte) error {
c.lnChannel.stateMtx.RLock()
defer c.lnChannel.stateMtx.RUnlock()
@ -216,7 +218,7 @@ func (c *ChannelUpdate) VerifyNewCommitmentSigs(ourSig, theirSig []byte) error {
return vm.Execute()
}
// Commit...
// Commit ...
func (c *ChannelUpdate) Commit(pastRevokePreimage []byte) error {
c.lnChannel.stateMtx.Lock()
defer c.lnChannel.stateMtx.Unlock()
@ -263,7 +265,7 @@ func (c *ChannelUpdate) Commit(pastRevokePreimage []byte) error {
return nil
}
// AddHTLC...
// AddHTLC ...
// 1. request R_Hash from receiver (only if single hop, would be out of band)
// 2. propose HTLC
// * timeout
@ -417,7 +419,7 @@ func (lc *LightningChannel) addHTLC(ourCommitTx, theirCommitTx *wire.MsgTx,
return nil
}
// SettleHTLC...
// SettleHTLC ...
// R-VALUE, NEW REVOKE HASH
// accept, sig
func (lc *LightningChannel) SettleHTLC(rValue [20]byte, newRevocation [20]byte) (*ChannelUpdate, error) {
@ -442,7 +444,7 @@ func (lc *LightningChannel) SettleHTLC(rValue [20]byte, newRevocation [20]byte)
lnChannel: lc,
}
// TODO(roasbeef): such copy pasta, make into func...
// TODO(roasbeef): such copy pasta, make into func ...
// Get next revocation hash, updating the number of updates in the
// channel as a result.
chanUpdate.currentUpdateNum = lc.channelState.NumUpdates
@ -490,7 +492,7 @@ func (lc *LightningChannel) SettleHTLC(rValue [20]byte, newRevocation [20]byte)
// TODO(roasbeef): locktimes/sequence set
// TODO(roasbeef): write checkpoint here...
// TODO(roasbeef): write checkpoint here ...
chanUpdate.ourPendingCommitTx = ourNewCommitTx
chanUpdate.theirPendingCommitTx = theirNewCommitTx
@ -498,7 +500,7 @@ func (lc *LightningChannel) SettleHTLC(rValue [20]byte, newRevocation [20]byte)
return chanUpdate, nil
}
// createNewCommitmentTxns....
// createNewCommitmentTxns ....
// NOTE: This MUST be called with stateMtx held.
func createNewCommitmentTxns(fundingTxIn *wire.TxIn, state *channeldb.OpenChannel,
chanUpdate *ChannelUpdate, amountToUs, amountToThem btcutil.Amount) (*wire.MsgTx, *wire.MsgTx, error) {
@ -522,37 +524,37 @@ func createNewCommitmentTxns(fundingTxIn *wire.TxIn, state *channeldb.OpenChanne
return ourNewCommitTx, theirNewCommitTx, nil
}
// CancelHTLC...
// CancelHTLC ...
func (lc *LightningChannel) CancelHTLC() error {
return nil
}
// OurBalance...
// OurBalance ...
func (lc *LightningChannel) OurBalance() btcutil.Amount {
lc.stateMtx.RLock()
defer lc.stateMtx.RUnlock()
return lc.channelState.OurBalance
}
// TheirBalance...
// TheirBalance ...
func (lc *LightningChannel) TheirBalance() btcutil.Amount {
lc.stateMtx.RLock()
defer lc.stateMtx.RUnlock()
return lc.channelState.TheirBalance
}
// ForceClose...
// ForceClose ...
func (lc *LightningChannel) ForceClose() error {
return nil
}
// RequestPayment...
// RequestPayment ...
func (lc *LightningChannel) RequestPayment(amount btcutil.Amount) error {
// Validate amount
return nil
}
// PaymentRequest...
// PaymentRequest ...
// TODO(roasbeef): serialization (bip 70, QR code, etc)
// * routing handled by upper layer
type PaymentRequest struct {
@ -560,8 +562,8 @@ type PaymentRequest struct {
Value btcutil.Amount
}
// createCommitTx...
// TODO(roasbeef): fix inconsistency of 32 vs 20 byte revocation hashes everywhere...
// createCommitTx ...
// TODO(roasbeef): fix inconsistency of 32 vs 20 byte revocation hashes everywhere ...
func createCommitTx(fundingOutput *wire.TxIn, selfKey, theirKey *btcec.PublicKey,
revokeHash []byte, csvTimeout uint32, amountToSelf,
amountToThem btcutil.Amount) (*wire.MsgTx, error) {

View file

@ -29,16 +29,16 @@ var (
walletDbName = "lnwallet.db"
)
// Config...
// Config ...
type Config struct {
DataDir string
LogDir string
DebugLevel string
RpcHost string // localhost:18334
RpcUser string
RpcPass string
RPCHost string // localhost:18334
RPCUser string
RPCPass string
RPCCert string
RPCKey string

View file

@ -154,7 +154,7 @@ func (r *ChannelReservation) OurContribution() *ChannelContribution {
return r.ourContribution
}
// ProcesContribution verifies the counterparty's contribution to the pending
// ProcessContribution verifies the counterparty's contribution to the pending
// payment channel. As a result of this incoming message, lnwallet is able to
// build the funding transaction, and both commitment transactions. Once this
// message has been processed, all signatures to inputs to the funding
@ -197,7 +197,7 @@ func (r *ChannelReservation) OurSignatures() ([][]byte, []byte) {
return r.ourFundingSigs, r.ourCommitmentSig
}
// CompleteFundingReservation finalizes the pending channel reservation,
// CompleteReservation finalizes the pending channel reservation,
// transitioning from a pending payment channel, to an open payment
// channel. All passed signatures to the counterparty's inputs to the funding
// transaction will be fully verified. Signatures are expected to be passed in
@ -224,7 +224,7 @@ func (r *ChannelReservation) CompleteReservation(fundingSigs [][]byte,
return <-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.

View file

@ -13,9 +13,13 @@ 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
// SequenceLockTimeSeconds ...
SequenceLockTimeSeconds = uint32(1 << 22)
// SequenceLockTimeMask ...
SequenceLockTimeMask = uint32(0x0000ffff)
// OP_CHECKSEQUENCEVERIFY ...
OP_CHECKSEQUENCEVERIFY byte = txscript.OP_NOP3
)
// scriptHashPkScript generates a pay-to-script-hash public key script paying

View file

@ -34,6 +34,7 @@ import (
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/walletdb"
// TODO: properly address golint's complaint: "a blank import should be only in a main or test package, or have a comment justifying it"
_ "github.com/btcsuite/btcwallet/walletdb/bdb"
)

View file

@ -37,12 +37,15 @@ const (
)
var (
// ErrInsufficientFunds ...
// Error types
ErrInsufficientFunds = errors.New("not enough available outputs to " +
"create funding transaction")
// Which bitcoin network are we using?
// TODO(roasbeef): config
// ActiveNetParams ...
ActiveNetParams = &chaincfg.TestNet3Params
// Namespace bucket keys.
lightningNamespaceKey = []byte("ln-wallet")
@ -60,22 +63,13 @@ var (
// NOTE: Ultimately, this will most likely be deprecated...
type FundingType uint16
// constants ...
const (
// Use SegWit, assumes CSV+CLTV
SEGWIT FundingType = iota
// Use SIGHASH_NOINPUT, assumes CSV+CLTV
SIGHASH
// Use CSV without reserve
CSV
// Use CSV with reserve
// Reserve is a permanent amount of funds locked and the capacity.
CSV_RESERVE
// CLTV with reserve.
CLTV_RESERVE
SEGWIT FundingType = iota // Use SegWit, assumes CSV+CLTV
SIGHASH // Use SIGHASH_NOINPUT, assumes CSV+CLTV
CSV // Use CSV without reserve
CSVReserve // Use CSV with reserve. Reserve is a permanent amount of funds locked and the capacity.
CLTVReserve // CLTV with reserve.
)
// initFundingReserveReq is the first message sent to initiate the workflow
@ -312,7 +306,7 @@ func NewLightningWallet(config *Config) (*LightningWallet, walletdb.DB, error) {
}
idPubkeyHash := adrs[0].Address().ScriptAddress()
if err := cdb.PutIdKey(idPubkeyHash); err != nil {
if err := cdb.PutIDKey(idPubkeyHash); err != nil {
return nil, nil, err
}
log.Printf("stored identity key pubkey hash in channeldb\n")
@ -350,7 +344,7 @@ func (l *LightningWallet) Startup() error {
// TODO(roasbeef): config...
rpcc, err := chain.NewClient(ActiveNetParams,
l.cfg.RpcHost, l.cfg.RpcUser, l.cfg.RpcPass, l.cfg.CACert, false)
l.cfg.RPCHost, l.cfg.RPCUser, l.cfg.RPCPass, l.cfg.CACert, false)
if err != nil {
return err
}

View file

@ -97,7 +97,7 @@ func (b *bobNode) Contribution() *ChannelContribution {
func (b *bobNode) signFundingTx(fundingTx *wire.MsgTx) ([][]byte, error) {
bobSigs := make([][]byte, 0, len(b.availableOutputs))
bobPkScript := b.changeOutputs[0].PkScript
for i, _ := range fundingTx.TxIn {
for i := range fundingTx.TxIn {
// Alice has already signed this input
if fundingTx.TxIn[i].SignatureScript != nil {
continue

View file

@ -2,12 +2,13 @@ package lnwire
import (
"fmt"
"io"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/wire"
"io"
)
// CloseComplete ...
type CloseComplete struct {
ReservationID uint64
@ -15,6 +16,7 @@ type CloseComplete struct {
CloseShaHash *wire.ShaHash // TxID of the Close Tx
}
// Decode ...
func (c *CloseComplete) Decode(r io.Reader, pver uint32) error {
// ReservationID (8)
// ResponderCloseSig (73)
@ -31,12 +33,12 @@ func (c *CloseComplete) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new CloseComplete
// NewCloseComplete creates a new CloseComplete
func NewCloseComplete() *CloseComplete {
return &CloseComplete{}
}
// Serializes the item from the CloseComplete struct
// Encode serializes the item from the CloseComplete struct
// Writes the data to w
func (c *CloseComplete) Encode(w io.Writer, pver uint32) error {
// ReservationID
@ -53,16 +55,18 @@ func (c *CloseComplete) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *CloseComplete) Command() uint32 {
return CmdCloseComplete
}
// MaxPayloadLength ...
func (c *CloseComplete) MaxPayloadLength(uint32) uint32 {
// 8 + 73 + 32
return 113
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *CloseComplete) Validate() error {
// We're good!
return nil

View file

@ -2,12 +2,13 @@ package lnwire
import (
"fmt"
"io"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcutil"
"io"
)
// CloseRequest ...
type CloseRequest struct {
ReservationID uint64
@ -15,6 +16,7 @@ type CloseRequest struct {
Fee btcutil.Amount
}
// Decode ...
func (c *CloseRequest) Decode(r io.Reader, pver uint32) error {
// ReservationID (8)
// RequesterCloseSig (73)
@ -31,12 +33,12 @@ func (c *CloseRequest) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new CloseRequest
// NewCloseRequest creates a new CloseRequest
func NewCloseRequest() *CloseRequest {
return &CloseRequest{}
}
// Serializes the item from the CloseRequest struct
// Encode serializes the item from the CloseRequest struct
// Writes the data to w
func (c *CloseRequest) Encode(w io.Writer, pver uint32) error {
// ReservationID
@ -53,16 +55,18 @@ func (c *CloseRequest) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *CloseRequest) Command() uint32 {
return CmdCloseRequest
}
// MaxPayloadLength ...
func (c *CloseRequest) MaxPayloadLength(uint32) uint32 {
// 8 + 73 + 8
return 89
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *CloseRequest) Validate() error {
// Fee must be greater than 0
if c.Fee < 0 {

View file

@ -1,8 +1,9 @@
package lnwire
import (
"github.com/btcsuite/btcutil"
"testing"
"github.com/btcsuite/btcutil"
)
var (

View file

@ -5,6 +5,7 @@ import (
"io"
)
// CommitRevocation ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type CommitRevocation struct {
@ -23,6 +24,7 @@ type CommitRevocation struct {
RevocationProof [20]byte
}
// Decode ...
func (c *CommitRevocation) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// CommitmentHeight(8)
@ -39,12 +41,12 @@ func (c *CommitRevocation) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new CommitRevocation
// NewCommitRevocation creates a new CommitRevocation
func NewCommitRevocation() *CommitRevocation {
return &CommitRevocation{}
}
// Serializes the item from the CommitRevocation struct
// Encode serializes the item from the CommitRevocation struct
// Writes the data to w
func (c *CommitRevocation) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -59,15 +61,17 @@ func (c *CommitRevocation) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *CommitRevocation) Command() uint32 {
return CmdCommitRevocation
}
// MaxPayloadLength ...
func (c *CommitRevocation) MaxPayloadLength(uint32) uint32 {
return 36
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *CommitRevocation) Validate() error {
// We're good!
return nil

View file

@ -2,11 +2,13 @@ package lnwire
import (
"fmt"
"io"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcutil"
"io"
)
// CommitSignature ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type CommitSignature struct {
@ -34,6 +36,7 @@ type CommitSignature struct {
CommitSig *btcec.Signature // Requester's Commitment
}
// Decode ...
func (c *CommitSignature) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// CommitmentHeight(8)
@ -56,12 +59,12 @@ func (c *CommitSignature) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new CommitSignature
// NewCommitSignature creates a new CommitSignature
func NewCommitSignature() *CommitSignature {
return &CommitSignature{}
}
// Serializes the item from the CommitSignature struct
// Encode serializes the item from the CommitSignature struct
// Writes the data to w
func (c *CommitSignature) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -79,15 +82,17 @@ func (c *CommitSignature) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *CommitSignature) Command() uint32 {
return CmdCommitSignature
}
// MaxPayloadLength ...
func (c *CommitSignature) MaxPayloadLength(uint32) uint32 {
return 8192
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *CommitSignature) Validate() error {
if c.Fee < 0 {
// While fees can be negative, it's too confusing to allow

View file

@ -1,8 +1,9 @@
package lnwire
import (
"github.com/btcsuite/btcutil"
"testing"
"github.com/btcsuite/btcutil"
)
var (

View file

@ -5,6 +5,7 @@ import (
"io"
)
// ErrorGeneric ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type ErrorGeneric struct {
@ -15,6 +16,7 @@ type ErrorGeneric struct {
Problem string
}
// Decode ...
func (c *ErrorGeneric) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// Problem
@ -29,12 +31,12 @@ func (c *ErrorGeneric) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new ErrorGeneric
// NewErrorGeneric creates a new ErrorGeneric
func NewErrorGeneric() *ErrorGeneric {
return &ErrorGeneric{}
}
// Serializes the item from the ErrorGeneric struct
// Encode serializes the item from the ErrorGeneric struct
// Writes the data to w
func (c *ErrorGeneric) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -48,16 +50,18 @@ func (c *ErrorGeneric) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *ErrorGeneric) Command() uint32 {
return CmdErrorGeneric
}
// MaxPayloadLength ...
func (c *ErrorGeneric) MaxPayloadLength(uint32) uint32 {
// 8+8192
return 8208
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *ErrorGeneric) Validate() error {
if len(c.Problem) > 8192 {
return fmt.Errorf("Problem string length too long")

View file

@ -2,12 +2,14 @@ package lnwire
import (
"fmt"
"io"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"io"
)
// FundingRequest ...
type FundingRequest struct {
ReservationID uint64
@ -53,6 +55,7 @@ type FundingRequest struct {
Inputs []*wire.TxIn
}
// Decode ...
func (c *FundingRequest) Decode(r io.Reader, pver uint32) error {
// Reservation ID (8)
// Channel Type (1)
@ -96,12 +99,12 @@ func (c *FundingRequest) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new FundingRequest
// NewFundingRequest creates a new FundingRequest
func NewFundingRequest() *FundingRequest {
return &FundingRequest{}
}
// Serializes the item from the FundingRequest struct
// Encode serializes the item from the FundingRequest struct
// Writes the data to w
func (c *FundingRequest) Encode(w io.Writer, pver uint32) error {
// Channel Type
@ -139,16 +142,18 @@ func (c *FundingRequest) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *FundingRequest) Command() uint32 {
return CmdFundingRequest
}
// MaxPayloadLength ...
func (c *FundingRequest) MaxPayloadLength(uint32) uint32 {
// 110 (base size) + 26 (pkscript) + 26 (pkscript) + 1 (numTxes) + 127*36(127 inputs * sha256+idx)
return 4735
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *FundingRequest) Validate() error {
var err error

View file

@ -1,8 +1,9 @@
package lnwire
import (
"github.com/btcsuite/btcutil"
"testing"
"github.com/btcsuite/btcutil"
)
var (

View file

@ -2,12 +2,14 @@ package lnwire
import (
"fmt"
"io"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"io"
)
// FundingResponse ...
type FundingResponse struct {
ChannelType uint8
@ -38,6 +40,7 @@ type FundingResponse struct {
Inputs []*wire.TxIn
}
// Decode ...
func (c *FundingResponse) Decode(r io.Reader, pver uint32) error {
// ReservationID (8)
// Channel Type (1)
@ -80,12 +83,12 @@ func (c *FundingResponse) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new FundingResponse
// NewFundingResponse creates a new FundingResponse
func NewFundingResponse() *FundingResponse {
return &FundingResponse{}
}
// Serializes the item from the FundingResponse struct
// Encode serializes the item from the FundingResponse struct
// Writes the data to w
func (c *FundingResponse) Encode(w io.Writer, pver uint32) error {
// ReservationID (8)
@ -123,16 +126,18 @@ func (c *FundingResponse) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *FundingResponse) Command() uint32 {
return CmdFundingResponse
}
// MaxPayloadLength ...
func (c *FundingResponse) MaxPayloadLength(uint32) uint32 {
// 86 (base size) + 26 (pkscript) + 26 (pkscript) + 74sig + 1 (numTxes) + 127*36(127 inputs * sha256+idx)
return 4785
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *FundingResponse) Validate() error {
var err error

View file

@ -1,8 +1,9 @@
package lnwire
import (
"github.com/btcsuite/btcutil"
"testing"
"github.com/btcsuite/btcutil"
)
var (

View file

@ -2,10 +2,12 @@ package lnwire
import (
"fmt"
"github.com/btcsuite/btcd/btcec"
"io"
"github.com/btcsuite/btcd/btcec"
)
// FundingSignAccept ...
type FundingSignAccept struct {
ReservationID uint64
@ -13,6 +15,7 @@ type FundingSignAccept struct {
FundingTXSigs []*btcec.Signature
}
// Decode ...
func (c *FundingSignAccept) Decode(r io.Reader, pver uint32) error {
// ReservationID (8)
// CommitSig (73)
@ -32,12 +35,12 @@ func (c *FundingSignAccept) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new FundingSignAccept
// NewFundingSignAccept creates a new FundingSignAccept
func NewFundingSignAccept() *FundingSignAccept {
return &FundingSignAccept{}
}
// Serializes the item from the FundingSignAccept struct
// Encode serializes the item from the FundingSignAccept struct
// Writes the data to w
func (c *FundingSignAccept) Encode(w io.Writer, pver uint32) error {
// ReservationID
@ -54,16 +57,18 @@ func (c *FundingSignAccept) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *FundingSignAccept) Command() uint32 {
return CmdFundingSignAccept
}
// MaxPayloadLength ...
func (c *FundingSignAccept) MaxPayloadLength(uint32) uint32 {
// 8 (base size) + 73 + (73maxSigSize*127maxInputs)
return 9352
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *FundingSignAccept) Validate() error {
// We're good!
return nil

View file

@ -2,11 +2,13 @@ package lnwire
import (
"fmt"
"io"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/wire"
"io"
)
// FundingSignComplete ...
type FundingSignComplete struct {
ReservationID uint64
@ -14,6 +16,7 @@ type FundingSignComplete struct {
FundingTXSigs []*btcec.Signature
}
// Decode ...
func (c *FundingSignComplete) Decode(r io.Reader, pver uint32) error {
// ReservationID (8)
// TxID (32)
@ -32,12 +35,12 @@ func (c *FundingSignComplete) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new FundingSignComplete
// NewFundingSignComplete creates a new FundingSignComplete
func NewFundingSignComplete() *FundingSignComplete {
return &FundingSignComplete{}
}
// Serializes the item from the FundingSignComplete struct
// Encode serializes the item from the FundingSignComplete struct
// Writes the data to w
func (c *FundingSignComplete) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -51,16 +54,18 @@ func (c *FundingSignComplete) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *FundingSignComplete) Command() uint32 {
return CmdFundingSignComplete
}
// MaxPayloadLength ...
func (c *FundingSignComplete) MaxPayloadLength(uint32) uint32 {
// 8 (base size) + 32 + (73maxSigSize*127maxInputs)
return 9311
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *FundingSignComplete) Validate() error {
// We're good!
return nil

View file

@ -5,11 +5,13 @@ import (
"io"
)
// HTLCAddAccept ...
type HTLCAddAccept struct {
ChannelID uint64
HTLCKey HTLCKey
HTLCKey HTLCKey
}
// Decode ...
func (c *HTLCAddAccept) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// HTLCKey(8)
@ -24,12 +26,12 @@ func (c *HTLCAddAccept) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new HTLCAddAccept
// NewHTLCAddAccept creates a new HTLCAddAccept
func NewHTLCAddAccept() *HTLCAddAccept {
return &HTLCAddAccept{}
}
// Serializes the item from the HTLCAddAccept struct
// Encode serializes the item from the HTLCAddAccept struct
// Writes the data to w
func (c *HTLCAddAccept) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -44,16 +46,18 @@ func (c *HTLCAddAccept) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *HTLCAddAccept) Command() uint32 {
return CmdHTLCAddAccept
}
// MaxPayloadLength ...
func (c *HTLCAddAccept) MaxPayloadLength(uint32) uint32 {
// 16 base size
return 16
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *HTLCAddAccept) Validate() error {
// We're good!
return nil

View file

@ -7,7 +7,7 @@ import (
var (
htlcAddAccept = &HTLCAddAccept{
ChannelID: uint64(12345678),
HTLCKey: HTLCKey(12345),
HTLCKey: HTLCKey(12345),
}
htlcAddAcceptSerializedString = "0000000000bc614e0000000000003039"
htlcAddAcceptSerializedMessage = "0709110b000003f2000000100000000000bc614e0000000000003039"

View file

@ -5,11 +5,13 @@ import (
"io"
)
// HTLCAddReject ...
type HTLCAddReject struct {
ChannelID uint64
HTLCKey HTLCKey
HTLCKey HTLCKey
}
// Decode ...
func (c *HTLCAddReject) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// CommitmentHeight(8)
@ -27,12 +29,12 @@ func (c *HTLCAddReject) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new HTLCAddReject
// NewHTLCAddReject creates a new HTLCAddReject
func NewHTLCAddReject() *HTLCAddReject {
return &HTLCAddReject{}
}
// Serializes the item from the HTLCAddReject struct
// Encode serializes the item from the HTLCAddReject struct
// Writes the data to w
func (c *HTLCAddReject) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -47,16 +49,18 @@ func (c *HTLCAddReject) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *HTLCAddReject) Command() uint32 {
return CmdHTLCAddReject
}
// MaxPayloadLength ...
func (c *HTLCAddReject) MaxPayloadLength(uint32) uint32 {
// 16 base size
return 16
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *HTLCAddReject) Validate() error {
// We're good!
return nil

View file

@ -7,7 +7,7 @@ import (
var (
htlcAddReject = &HTLCAddReject{
ChannelID: uint64(12345678),
HTLCKey: HTLCKey(12345),
HTLCKey: HTLCKey(12345),
}
htlcAddRejectSerializedString = "0000000000bc614e0000000000003039"
htlcAddRejectSerializedMessage = "0709110b000003fc000000100000000000bc614e0000000000003039"

View file

@ -5,6 +5,7 @@ import (
"io"
)
// HTLCAddRequest ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type HTLCAddRequest struct {
@ -37,6 +38,7 @@ type HTLCAddRequest struct {
Blob []byte
}
// Decode ...
func (c *HTLCAddRequest) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// HTLCKey(8)
@ -61,12 +63,12 @@ func (c *HTLCAddRequest) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new HTLCAddRequest
// NewHTLCAddRequest creates a new HTLCAddRequest
func NewHTLCAddRequest() *HTLCAddRequest {
return &HTLCAddRequest{}
}
// Serializes the item from the HTLCAddRequest struct
// Encode serializes the item from the HTLCAddRequest struct
// Writes the data to w
func (c *HTLCAddRequest) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -85,17 +87,19 @@ func (c *HTLCAddRequest) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *HTLCAddRequest) Command() uint32 {
return CmdHTLCAddRequest
}
// MaxPayloadLength ...
func (c *HTLCAddRequest) MaxPayloadLength(uint32) uint32 {
// base size ~110, but blob can be variable.
// shouldn't be bigger than 8K though...
return 8192
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *HTLCAddRequest) Validate() error {
if c.Amount < 0 {
// While fees can be negative, it's too confusing to allow

View file

@ -5,6 +5,7 @@ import (
"io"
)
// HTLCSettleAccept ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type HTLCSettleAccept struct {
@ -15,6 +16,7 @@ type HTLCSettleAccept struct {
HTLCKey HTLCKey
}
// Decode ...
func (c *HTLCSettleAccept) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// HTLCKey(8)
@ -29,12 +31,12 @@ func (c *HTLCSettleAccept) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new HTLCSettleAccept
// NewHTLCSettleAccept creates a new HTLCSettleAccept
func NewHTLCSettleAccept() *HTLCSettleAccept {
return &HTLCSettleAccept{}
}
// Serializes the item from the HTLCSettleAccept struct
// Encode serializes the item from the HTLCSettleAccept struct
// Writes the data to w
func (c *HTLCSettleAccept) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -48,16 +50,18 @@ func (c *HTLCSettleAccept) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *HTLCSettleAccept) Command() uint32 {
return CmdHTLCSettleAccept
}
// MaxPayloadLength ...
func (c *HTLCSettleAccept) MaxPayloadLength(uint32) uint32 {
// 16
return 16
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *HTLCSettleAccept) Validate() error {
// We're good!
return nil

View file

@ -7,7 +7,7 @@ import (
var (
htlcSettleAccept = &HTLCSettleAccept{
ChannelID: uint64(12345678),
HTLCKey: HTLCKey(12345),
HTLCKey: HTLCKey(12345),
}
htlcSettleAcceptSerializedString = "0000000000bc614e0000000000003039"
htlcSettleAcceptSerializedMessage = "0709110b00000456000000100000000000bc614e0000000000003039"

View file

@ -5,6 +5,7 @@ import (
"io"
)
// HTLCSettleRequest ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type HTLCSettleRequest struct {
@ -18,6 +19,7 @@ type HTLCSettleRequest struct {
RedemptionProofs []*[20]byte
}
// Decode ...
func (c *HTLCSettleRequest) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// HTLCKey(8)
@ -39,12 +41,12 @@ func (c *HTLCSettleRequest) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new HTLCSettleRequest
// NewHTLCSettleRequest creates a new HTLCSettleRequest
func NewHTLCSettleRequest() *HTLCSettleRequest {
return &HTLCSettleRequest{}
}
// Serializes the item from the HTLCSettleRequest struct
// Encode serializes the item from the HTLCSettleRequest struct
// Writes the data to w
func (c *HTLCSettleRequest) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -59,16 +61,18 @@ func (c *HTLCSettleRequest) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *HTLCSettleRequest) Command() uint32 {
return CmdHTLCSettleRequest
}
// MaxPayloadLength ...
func (c *HTLCSettleRequest) MaxPayloadLength(uint32) uint32 {
// 21*15+16
return 331
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *HTLCSettleRequest) Validate() error {
// We're good!
return nil

View file

@ -5,6 +5,7 @@ import (
"io"
)
// HTLCTimeoutAccept ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type HTLCTimeoutAccept struct {
@ -15,6 +16,7 @@ type HTLCTimeoutAccept struct {
HTLCKey HTLCKey
}
// Decode ...
func (c *HTLCTimeoutAccept) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// HTLCKey(8)
@ -29,12 +31,12 @@ func (c *HTLCTimeoutAccept) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new HTLCTimeoutAccept
// NewHTLCTimeoutAccept creates a new HTLCTimeoutAccept
func NewHTLCTimeoutAccept() *HTLCTimeoutAccept {
return &HTLCTimeoutAccept{}
}
// Serializes the item from the HTLCTimeoutAccept struct
// Encode serializes the item from the HTLCTimeoutAccept struct
// Writes the data to w
func (c *HTLCTimeoutAccept) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -48,16 +50,18 @@ func (c *HTLCTimeoutAccept) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *HTLCTimeoutAccept) Command() uint32 {
return CmdHTLCTimeoutAccept
}
// MaxPayloadLength ...
func (c *HTLCTimeoutAccept) MaxPayloadLength(uint32) uint32 {
// 16
return 16
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *HTLCTimeoutAccept) Validate() error {
// We're good!
return nil

View file

@ -7,7 +7,7 @@ import (
var (
htlcTimeoutAccept = &HTLCTimeoutAccept{
ChannelID: uint64(12345678),
HTLCKey: HTLCKey(12345),
HTLCKey: HTLCKey(12345),
}
htlcTimeoutAcceptSerializedString = "0000000000bc614e0000000000003039"
htlcTimeoutAcceptSerializedMessage = "0709110b0000051e000000100000000000bc614e0000000000003039"

View file

@ -5,6 +5,7 @@ import (
"io"
)
// HTLCTimeoutRequest ...
// Multiple Clearing Requests are possible by putting this inside an array of
// clearing requests
type HTLCTimeoutRequest struct {
@ -15,6 +16,7 @@ type HTLCTimeoutRequest struct {
HTLCKey HTLCKey
}
// Decode ...
func (c *HTLCTimeoutRequest) Decode(r io.Reader, pver uint32) error {
// ChannelID(8)
// HTLCKey(8)
@ -29,12 +31,12 @@ func (c *HTLCTimeoutRequest) Decode(r io.Reader, pver uint32) error {
return nil
}
// Creates a new HTLCTimeoutRequest
// NewHTLCTimeoutRequest creates a new HTLCTimeoutRequest
func NewHTLCTimeoutRequest() *HTLCTimeoutRequest {
return &HTLCTimeoutRequest{}
}
// Serializes the item from the HTLCTimeoutRequest struct
// Encode serializes the item from the HTLCTimeoutRequest struct
// Writes the data to w
func (c *HTLCTimeoutRequest) Encode(w io.Writer, pver uint32) error {
err := writeElements(w,
@ -48,16 +50,18 @@ func (c *HTLCTimeoutRequest) Encode(w io.Writer, pver uint32) error {
return nil
}
// Command ...
func (c *HTLCTimeoutRequest) Command() uint32 {
return CmdHTLCTimeoutRequest
}
// MaxPayloadLength ...
func (c *HTLCTimeoutRequest) MaxPayloadLength(uint32) uint32 {
// 16
return 16
}
// Makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
// Validate makes sure the struct data is valid (e.g. no negatives or invalid pkscripts)
func (c *HTLCTimeoutRequest) Validate() error {
// We're good!
return nil

View file

@ -7,7 +7,7 @@ import (
var (
htlcTimeoutRequest = &HTLCTimeoutRequest{
ChannelID: uint64(12345678),
HTLCKey: HTLCKey(12345),
HTLCKey: HTLCKey(12345),
}
htlcTimeoutRequestSerializedString = "0000000000bc614e0000000000003039"
htlcTimeoutRequestSerializedMessage = "0709110b00000514000000100000000000bc614e0000000000003039"

View file

@ -4,29 +4,35 @@ import (
"bytes"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"io"
"io/ioutil"
)
var MAX_SLICE_LENGTH = 65535
// MaxSliceLength ...
var MaxSliceLength = 65535
// Actual pkScript, not redeemScript
// PkScript is the actual PkScript, not redeemScript
type PkScript []byte
// HTLCKey ...
type HTLCKey uint64
// CommitHeight ...
type CommitHeight uint64
// CreditsAmount ...
// Subsatoshi amount (Micro-Satoshi, 1/1000th)
// Should be a signed int to account for negative fees
//
//
// "In any science-fiction movie, anywhere in the galaxy, currency is referred
// to as 'credits.'"
// --Sam Humphries. Ebert, Roger (1999). Ebert's bigger little movie
// glossary. Andrews McMeel. p. 172.
//
//
// https:// en.wikipedia.org/wiki/List_of_fictional_currencies
// https:// en.wikipedia.org/wiki/Fictional_currency#Trends_in_the_use_of_fictional_currencies
// http:// tvtropes.org/pmwiki/pmwiki.php/Main/WeWillSpendCreditsInTheFuture
@ -197,7 +203,7 @@ func writeElement(w io.Writer, element interface{}) error {
return nil
case []byte:
sliceLength := len(e)
if sliceLength > MAX_SLICE_LENGTH {
if sliceLength > MaxSliceLength {
return fmt.Errorf("Slice length too long!")
}
// Write the size
@ -437,7 +443,7 @@ func readElement(r io.Reader, element interface{}) error {
return err
}
if len(sig) != int(sigLength) {
return fmt.Errorf("EOF: Signature length mismatch.")
return fmt.Errorf("EOF: Signature length mismatch")
}
btcecSig, err := btcec.ParseSignature(sig, btcec.S256())
if err != nil {
@ -487,8 +493,8 @@ func readElement(r io.Reader, element interface{}) error {
}
// Shouldn't need to do this, since it's uint16, but we
// might have a different value for MAX_SLICE_LENGTH...
if int(blobLength) > MAX_SLICE_LENGTH {
// might have a different value for MaxSliceLength...
if int(blobLength) > MaxSliceLength {
return fmt.Errorf("Slice length too long!")
}
@ -499,7 +505,7 @@ func readElement(r io.Reader, element interface{}) error {
return err
}
if len(*e) != int(blobLength) {
return fmt.Errorf("EOF: Slice length mismatch.")
return fmt.Errorf("EOF: Slice length mismatch")
}
return nil
case *PkScript:
@ -521,7 +527,7 @@ func readElement(r io.Reader, element interface{}) error {
return err
}
if len(*e) != int(scriptLength) {
return fmt.Errorf("EOF: Signature length mismatch.")
return fmt.Errorf("EOF: Signature length mismatch")
}
return nil
case *string:
@ -535,7 +541,7 @@ func readElement(r io.Reader, element interface{}) error {
l := io.LimitReader(r, int64(strlen))
b, err := ioutil.ReadAll(l)
if len(b) != int(strlen) {
return fmt.Errorf("EOF: String length mismatch.")
return fmt.Errorf("EOF: String length mismatch")
}
*e = string(b)
if err != nil {
@ -603,7 +609,7 @@ func readElements(r io.Reader, elements ...interface{}) error {
return nil
}
// Validates whether a PkScript byte array is P2SH or P2PKH
// ValidatePkScript validates whether a PkScript byte array is P2SH or P2PKH
func ValidatePkScript(pkScript PkScript) error {
if &pkScript == nil {
return fmt.Errorf("PkScript should not be empty!")

View file

@ -3,12 +3,13 @@ package lnwire
import (
"bytes"
"encoding/hex"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"io/ioutil"
"reflect"
"testing"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
)
// Common variables and functions for the message tests
@ -16,8 +17,8 @@ import (
var (
// For debugging, writes to /dev/shm/
// Maybe in the future do it if you do "go test -v"
WRITE_FILE = true
filename = "/dev/shm/serialized.raw"
WriteFile = true
filename = "/dev/shm/serialized.raw"
// preimage: 9a2cbd088763db88dd8ba79e5726daa6aba4aa7e
// echo -n | openssl sha256 | openssl ripemd160 | openssl sha256 | openssl ripemd160
@ -101,7 +102,7 @@ func SerializeTest(t *testing.T, message Message, expectedString string, filenam
}
// So I can do: hexdump -C /dev/shm/fundingRequest.raw
if WRITE_FILE {
if WriteFile {
err = ioutil.WriteFile(filename, b.Bytes(), 0644)
if err != nil {
t.Error(err.Error())

View file

@ -1,3 +1,4 @@
// Package lnwire ...
// Code derived from https:// github.com/btcsuite/btcd/blob/master/wire/message.go
package lnwire
@ -11,58 +12,67 @@ import (
// message type identifyer bytes
const (
MSGID_FUNDREQUEST = 0x30
MSGID_FUNDRESPONSE = 0x31
MsgIDFundRequest = 0x30
MsgIDFundResponse = 0x31
MSGID_CLOSEREQUEST = 0x40
MSGID_CLOSERESPONSE = 0x41
MsgIDCloseRequest = 0x40
MsgIDCloseResponse = 0x41
MSGID_TEXTCHAT = 0x70
MsgIDTextChat = 0x70
MSGID_FWDMSG = 0x20
MSGID_FWDAUTHREQ = 0x21
MsgIDFwdMsg = 0x20
MsgIDFwdAuthReq = 0x21
)
// 4-byte network + 4-byte message id + payload-length 4-byte
const MessageHeaderSize = 12
const MaxMessagePayload = 1024 * 1024 * 32 // 32MB
// 32MB
const MaxMessagePayload = 1024 * 1024 * 32
// constants ...
const (
// Funding channel open
CmdFundingRequest = uint32(200)
CmdFundingResponse = uint32(210)
CmdFundingSignAccept = uint32(220)
CmdFundingSignComplete = uint32(230)
// Close channel
CmdCloseRequest = uint32(300)
CmdCloseComplete = uint32(310)
// TODO Renumber to 1100
// HTLC payment
CmdHTLCAddRequest = uint32(1000)
CmdHTLCAddAccept = uint32(1010)
CmdHTLCAddReject = uint32(1020)
// TODO Renumber to 1200
// HTLC settlement
CmdHTLCSettleRequest = uint32(1100)
CmdHTLCSettleAccept = uint32(1110)
// HTLC timeout
CmdHTLCTimeoutRequest = uint32(1300)
CmdHTLCTimeoutAccept = uint32(1310)
// Commitments
CmdCommitSignature = uint32(2000)
CmdCommitRevocation = uint32(2010)
// Error
CmdErrorGeneric = uint32(4000)
)
// Every message has these functions:
// A Message has these functions:
type Message interface {
Decode(io.Reader, uint32) error // (io, protocol version)
Encode(io.Writer, uint32) error // (io, protocol version)
@ -165,6 +175,7 @@ func discardInput(r io.Reader, n uint32) {
}
}
// WriteMessage ...
func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet wire.BitcoinNet) (int, error) {
totalBytes := 0
@ -219,6 +230,7 @@ func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet wire.BitcoinNet)
return totalBytes, nil
}
// ReadMessage ...
func ReadMessage(r io.Reader, pver uint32, btcnet wire.BitcoinNet) (int, Message, []byte, error) {
totalBytes := 0
n, hdr, err := readMessageHeader(r)
@ -229,7 +241,7 @@ func ReadMessage(r io.Reader, pver uint32, btcnet wire.BitcoinNet) (int, Message
// Enforce maximum message payload
if hdr.length > MaxMessagePayload {
return totalBytes, nil, nil, fmt.Errorf("message payload is too large - header indicates %d bytes, but max message payload is %d bytes.", hdr.length, MaxMessagePayload)
return totalBytes, nil, nil, fmt.Errorf("message payload is too large - header indicates %d bytes, but max message payload is %d bytes", hdr.length, MaxMessagePayload)
}
// Check for messages in the wrong bitcoin network
@ -250,7 +262,7 @@ func ReadMessage(r io.Reader, pver uint32, btcnet wire.BitcoinNet) (int, Message
mpl := msg.MaxPayloadLength(pver)
if hdr.length > mpl {
discardInput(r, hdr.length)
return totalBytes, nil, nil, fmt.Errorf("payload exceeds max length. indicates %v bytes, but max of message type %v is %v.", hdr.length, command, mpl)
return totalBytes, nil, nil, fmt.Errorf("payload exceeds max length. indicates %v bytes, but max of message type %v is %v", hdr.length, command, mpl)
}
// Read payload

View file

@ -55,7 +55,7 @@ type peer struct {
lightningAddr lndc.LNAdr
inbound bool
protocolVersion uint32
peerId int32
peerID int32
// For purposes of detecting retransmits, etc.
lastNMessages map[lnwire.Message]struct{}
@ -88,7 +88,7 @@ type peer struct {
func newPeer(conn net.Conn, server *server) *peer {
return &peer{
conn: conn,
peerId: atomic.AddInt32(&numNodes, 1),
peerID: atomic.AddInt32(&numNodes, 1),
lastNMessages: make(map[lnwire.Message]struct{}),

View file

@ -32,8 +32,8 @@ type rpcServer struct {
var _ lnrpc.LightningServer = (*rpcServer)(nil)
// newRpcServer...
func newRpcServer(s *server) *rpcServer {
// newRPCServer...
func newRPCServer(s *server) *rpcServer {
return &rpcServer{server: s, quit: make(chan struct{}, 1)}
}

View file

@ -66,7 +66,7 @@ func newServer(listenAddrs []string, bitcoinNet *chaincfg.Params,
quit: make(chan struct{}),
}
s.rpcServer = newRpcServer(s)
s.rpcServer = newRPCServer(s)
return s, nil
}
@ -83,7 +83,7 @@ func (s *server) addPeer(p *peer) {
return
}
s.peers[p.peerId] = p
s.peers[p.peerID] = p
}
// removePeer...
@ -142,11 +142,11 @@ out:
// For the lndc crypto handshake, we
// either need a compressed pubkey, or a
// 20-byte pkh.
var remoteId []byte
var remoteID []byte
if addr.PubKey == nil {
remoteId = addr.Base58Addr.ScriptAddress()
remoteID = addr.Base58Addr.ScriptAddress()
} else {
remoteId = addr.PubKey.SerializeCompressed()
remoteID = addr.PubKey.SerializeCompressed()
}
// Attempt to connect to the remote
@ -157,7 +157,7 @@ out:
ipAddr := addr.NetAddr.String()
conn := lndc.NewConn(nil)
if err := conn.Dial(
s.longTermPriv, ipAddr, remoteId); err != nil {
s.longTermPriv, ipAddr, remoteID); err != nil {
msg.reply <- err
}
@ -251,7 +251,7 @@ func (s *server) Stop() error {
// getIdentityPrivKey gets the identity private key out of the wallet DB.
func getIdentityPrivKey(l *lnwallet.LightningWallet) (*btcec.PrivateKey, error) {
adr, err := l.ChannelDB.GetIdAdr()
adr, err := l.ChannelDB.GetIDAdr()
if err != nil {
return nil, err
}

View file

@ -22,7 +22,7 @@ type chainBranch struct {
hash [32]byte
}
// HyperShaChain...
// HyperShaChain ...
// * https://github.com/rustyrussell/ccan/blob/master/ccan/crypto/shachain/design.txt
type HyperShaChain struct {
sync.RWMutex
@ -35,13 +35,13 @@ type HyperShaChain struct {
lastHash wire.ShaHash
}
// NewHyperShaChain
// New ...
// * used to track their pre-images
func New() *HyperShaChain {
return &HyperShaChain{lastChainIndex: 0, numValid: 0}
}
// NewHyperShaChainFromSeed...
// NewFromSeed ...
// * used to derive your own pre-images
func NewFromSeed(seed *[32]byte, deriveTo uint64) (*HyperShaChain, error) {
var shaSeed [32]byte
@ -95,7 +95,7 @@ func canDerive(from, to uint64) bool {
return ^from&to == 1
}
// getHash...
// GetHash ...
// index should be commitment #
func (h *HyperShaChain) GetHash(index uint64) (*[32]byte, error) {
for i := uint64(0); i < h.numValid; i++ {
@ -114,7 +114,7 @@ func (h *HyperShaChain) GetHash(index uint64) (*[32]byte, error) {
return nil, fmt.Errorf("unable to derive hash # %v", index)
}
// addHash
// AddNextHash ...
func (h *HyperShaChain) AddNextHash(hash [32]byte) error {
// Hashes for a remote chain must be added in order.
nextIdx := h.lastChainIndex + 1
@ -144,14 +144,14 @@ func (h *HyperShaChain) AddNextHash(hash [32]byte) error {
return nil
}
// CurrentPreImage...
// CurrentPreImage ...
func (h *HyperShaChain) CurrentPreImage() *wire.ShaHash {
h.RLock()
defer h.RUnlock()
return &h.lastHash
}
// CurrentRevocationHash...
// CurrentRevocationHash ...
// TODO(roasbeef): *wire.ShaHash vs [wire.HashSize]byte ?
func (h *HyperShaChain) CurrentRevocationHash() []byte {
h.RLock()
@ -159,7 +159,7 @@ func (h *HyperShaChain) CurrentRevocationHash() []byte {
return btcutil.Hash160(h.lastHash[:])
}
// LocatePreImage...
// LocatePreImage ...
// Alice just broadcasted an old commitment tx, we need the revocation hash to
// claim the funds so we don't get cheated. However, we aren't storing all the
// pre-images in memory. So which shachain index # did she broadcast?
@ -170,12 +170,14 @@ func (h *HyperShaChain) LocatePreImage(outputScript []byte) (uint64, *[32]byte)
return 0, nil
}
// MarshallBinary...
// Encode ...
// (MarshallBinary ...)
func (h *HyperShaChain) Encode(b io.Writer) error {
return nil
}
// UnmarshallBinary...
// Decode ...
// UnmarshallBinary ...
func (h *HyperShaChain) Decode(b io.Reader) error {
return nil
}

View file

@ -18,14 +18,18 @@ const (
headerFileName = "headers.bin"
// Except hash-160s, those aren't backwards. But anything that's 32 bytes is.
// because, cmon, 32? Gotta reverse that. But 20? 20 is OK.
// NETVERSION ...
NETVERSION = wire.TestNet3
VERSION = 70011
// VERSION ...
VERSION = 70011
)
var (
params = &chaincfg.TestNet3Params
)
// SPVCon ...
type SPVCon struct {
con net.Conn // the (probably tcp) connection to the node
headerFile *os.File // file for SPV headers
@ -45,6 +49,7 @@ type SPVCon struct {
TS *TxStore
}
// Open ...
func (s *SPVCon) Open(remoteNode string, hfn string, inTs *TxStore) error {
// open header file
err := s.openHeaderFile(headerFileName)
@ -139,6 +144,7 @@ func (s *SPVCon) openHeaderFile(hfn string) error {
return nil
}
// PongBack ...
func (s *SPVCon) PongBack(nonce uint64) {
mpong := wire.NewMsgPong(nonce)
@ -146,11 +152,13 @@ func (s *SPVCon) PongBack(nonce uint64) {
return
}
// SendFilter ...
func (s *SPVCon) SendFilter(f *bloom.Filter) {
s.outMsgQueue <- f.MsgFilterLoad()
return
}
// AskForHeaders ...
func (s *SPVCon) AskForHeaders() error {
var hdr wire.BlockHeader
ghdr := wire.NewMsgGetHeaders()
@ -194,6 +202,7 @@ func (s *SPVCon) AskForHeaders() error {
return nil
}
// IngestHeaders ...
func (s *SPVCon) IngestHeaders(m *wire.MsgHeaders) (bool, error) {
var err error
_, err = s.headerFile.Seek(-80, os.SEEK_END)
@ -274,6 +283,7 @@ func (s *SPVCon) IngestHeaders(m *wire.MsgHeaders) (bool, error) {
return true, nil
}
// AskForMerkBlocks ...
func (s *SPVCon) AskForMerkBlocks(current, last uint32) error {
var hdr wire.BlockHeader
_, err := s.headerFile.Seek(int64(current*80), os.SEEK_SET)

View file

@ -90,6 +90,7 @@ func calcDiffAdjust(start, end wire.BlockHeader, p *chaincfg.Params) uint32 {
return blockchain.BigToCompact(newTarget)
}
// CheckHeader ...
func CheckHeader(r io.ReadSeeker, height int64, p *chaincfg.Params) bool {
var err error
var cur, prev, epochStart wire.BlockHeader
@ -179,11 +180,11 @@ func CheckHeader(r io.ReadSeeker, height int64, p *chaincfg.Params) bool {
return true // it must have worked if there's no errors and got to the end.
}
/* checkrange verifies a range of headers. it checks their proof of work,
difficulty adjustments, and that they all link in to each other properly.
This is the only blockchain technology in the whole code base.
Returns false if anything bad happens. Returns true if the range checks
out with no errors. */
// CheckRange verifies a range of headers. It checks their proof of work,
// difficulty adjustments, and that they all link in to each other properly.
// This is the only blockchain technology in the whole code base.
// Returns false if anything bad happens. Returns true if the range checks
// out with no errors.
func CheckRange(r io.ReadSeeker, first, last int64, p *chaincfg.Params) bool {
for i := first; i <= last; i++ {
if !CheckHeader(r, i, p) {

View file

@ -6,6 +6,7 @@ import (
"github.com/btcsuite/btcd/wire"
)
// MakeMerkleParent ...
func MakeMerkleParent(left *wire.ShaHash, right *wire.ShaHash) *wire.ShaHash {
// this can screw things up; CVE-2012-2459
if left != nil && right != nil && left.IsEqual(right) {

View file

@ -10,6 +10,7 @@ import (
"github.com/btcsuite/btcutil/bloom"
)
// TxStore ...
type TxStore struct {
KnownTxids []*wire.ShaHash
Utxos []Utxo // stacks on stacks
@ -17,6 +18,7 @@ type TxStore struct {
Adrs []MyAdr // endeavouring to acquire capital
}
// Utxo ...
type Utxo struct { // cash money.
// combo of outpoint and txout which has all the info needed to spend
Op wire.OutPoint
@ -25,12 +27,13 @@ type Utxo struct { // cash money.
KeyIdx uint32 // index for private key needed to sign / spend
}
// MyAdr ...
type MyAdr struct { // an address I have the private key for
btcutil.Address
KeyIdx uint32 // index for private key needed to sign / spend
}
// add addresses into the TxStore
// AddAdr adds addresses into the TxStore
func (t *TxStore) AddAdr(a btcutil.Address, kidx uint32) {
var ma MyAdr
ma.Address = a
@ -39,7 +42,7 @@ func (t *TxStore) AddAdr(a btcutil.Address, kidx uint32) {
return
}
// add txid of interest
// AddTxid adds txid of interest
func (t *TxStore) AddTxid(txid *wire.ShaHash) error {
if txid == nil {
return fmt.Errorf("tried to add nil txid")
@ -48,7 +51,7 @@ func (t *TxStore) AddTxid(txid *wire.ShaHash) error {
return nil
}
// ... or I'm gonna fade away
// GimmeFilter ... or I'm gonna fade away
func (t *TxStore) GimmeFilter() (*bloom.Filter, error) {
if len(t.Adrs) == 0 {
return nil, fmt.Errorf("no addresses to filter for")
@ -60,7 +63,7 @@ func (t *TxStore) GimmeFilter() (*bloom.Filter, error) {
return f, nil
}
// Ingest a tx into wallet, dealing with both gains and losses
// IngestTx ingests a tx into wallet, dealing with both gains and losses
func (t *TxStore) IngestTx(tx *wire.MsgTx) error {
var match bool
inTxid := tx.TxSha()
@ -86,7 +89,7 @@ func (t *TxStore) IngestTx(tx *wire.MsgTx) error {
return nil
}
// Absorb money into wallet from a tx
// AbsorbTx absorbs money into wallet from a tx
func (t *TxStore) AbsorbTx(tx *wire.MsgTx) error {
if tx == nil {
return fmt.Errorf("Tried to add nil tx")
@ -120,7 +123,7 @@ func (t *TxStore) AbsorbTx(tx *wire.MsgTx) error {
return nil
}
// Expell money from wallet due to a tx
// ExpellTx expells money from wallet due to a tx
func (t *TxStore) ExpellTx(tx *wire.MsgTx) error {
if tx == nil {
return fmt.Errorf("Tried to add nil tx")