htlcswitch/payment_result: add (de)serialization of networkResult + test

This commit is contained in:
Johan T. Halseth 2019-06-07 16:42:25 +02:00
parent f5dee02ff4
commit df3f5d02ad
No known key found for this signature in database
GPG Key ID: 15BAADA29DA20D26
2 changed files with 123 additions and 0 deletions

@ -2,7 +2,9 @@ package htlcswitch
import ( import (
"errors" "errors"
"io"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
) )
@ -46,3 +48,34 @@ type networkResult struct {
// which the failure reason might not be included. // which the failure reason might not be included.
isResolution bool isResolution bool
} }
// serializeNetworkResult serializes the networkResult.
func serializeNetworkResult(w io.Writer, n *networkResult) error {
if _, err := lnwire.WriteMessage(w, n.msg, 0); err != nil {
return err
}
return channeldb.WriteElements(w, n.unencrypted, n.isResolution)
}
// deserializeNetworkResult deserializes the networkResult.
func deserializeNetworkResult(r io.Reader) (*networkResult, error) {
var (
err error
)
n := &networkResult{}
n.msg, err = lnwire.ReadMessage(r, 0)
if err != nil {
return nil, err
}
if err := channeldb.ReadElements(r,
&n.unencrypted, &n.isResolution,
); err != nil {
return nil, err
}
return n, nil
}

@ -0,0 +1,90 @@
package htlcswitch
import (
"bytes"
"math/rand"
"reflect"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
)
// TestNetworkResultSerialization checks that NetworkResults are properly
// (de)serialized.
func TestNetworkResultSerialization(t *testing.T) {
t.Parallel()
var preimage lntypes.Preimage
if _, err := rand.Read(preimage[:]); err != nil {
t.Fatalf("unable gen rand preimag: %v", err)
}
var chanID lnwire.ChannelID
if _, err := rand.Read(chanID[:]); err != nil {
t.Fatalf("unable gen rand chanid: %v", err)
}
var reason [256]byte
if _, err := rand.Read(reason[:]); err != nil {
t.Fatalf("unable gen rand reason: %v", err)
}
settle := &lnwire.UpdateFulfillHTLC{
ChanID: chanID,
ID: 2,
PaymentPreimage: preimage,
}
fail := &lnwire.UpdateFailHTLC{
ChanID: chanID,
ID: 1,
Reason: []byte{},
}
fail2 := &lnwire.UpdateFailHTLC{
ChanID: chanID,
ID: 1,
Reason: reason[:],
}
testCases := []*networkResult{
{
msg: settle,
},
{
msg: fail,
unencrypted: false,
isResolution: false,
},
{
msg: fail,
unencrypted: false,
isResolution: true,
},
{
msg: fail2,
unencrypted: true,
isResolution: false,
},
}
for _, p := range testCases {
var buf bytes.Buffer
if err := serializeNetworkResult(&buf, p); err != nil {
t.Fatalf("serialize failed: %v", err)
}
r := bytes.NewReader(buf.Bytes())
p1, err := deserializeNetworkResult(r)
if err != nil {
t.Fatalf("unable to deserizlize: %v", err)
}
if !reflect.DeepEqual(p, p1) {
t.Fatalf("not equal. %v vs %v", spew.Sdump(p),
spew.Sdump(p1))
}
}
}