diff --git a/channeldb/graph.go b/channeldb/graph.go index c567711da..72dd0d17d 100644 --- a/channeldb/graph.go +++ b/channeldb/graph.go @@ -630,6 +630,42 @@ func (c *ChannelGraph) DeleteChannelEdge(chanPoint *wire.OutPoint) error { }) } +// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the +// passed channel point (outpoint). If the passed channel doesn't exist within +// the database, then ErrEdgeNotFound is returned. +func (c *ChannelGraph) ChannelID(chanPoint *wire.OutPoint) (uint64, error) { + var chanID uint64 + + var b bytes.Buffer + if err := writeOutpoint(&b, chanPoint); err != nil { + return 0, nil + } + + if err := c.db.View(func(tx *bolt.Tx) error { + edges := tx.Bucket(edgeBucket) + if edges == nil { + return ErrGraphNoEdgesFound + } + chanIndex := edges.Bucket(channelPointBucket) + if edges == nil { + return ErrGraphNoEdgesFound + } + + chanIDBytes := chanIndex.Get(b.Bytes()) + if chanIDBytes == nil { + return ErrEdgeNotFound + } + + chanID = byteOrder.Uint64(chanIDBytes) + + return nil + }); err != nil { + return 0, err + } + + return chanID, nil +} + func delChannelByEdge(edges *bolt.Bucket, edgeIndex *bolt.Bucket, chanIndex *bolt.Bucket, chanPoint *wire.OutPoint) error { var b bytes.Buffer diff --git a/channeldb/graph_test.go b/channeldb/graph_test.go index 03e8f5627..66646b1aa 100644 --- a/channeldb/graph_test.go +++ b/channeldb/graph_test.go @@ -335,6 +335,17 @@ func TestEdgeInfoUpdates(t *testing.T) { t.Fatalf("graph should have of inserted edge") } + // We should also be able to retrieved the channelID only knowing the + // channel point of the channel. + dbChanID, err := graph.ChannelID(&outpoint) + if err != nil { + t.Fatalf("unable to retrieve channel ID: %v", err) + } + if dbChanID != chanID { + t.Fatalf("chan ID's mismatch, expected %v got %v", dbChanID, + chanID) + } + // With the edges inserted, perform some queries to ensure that they've // been inserted properly. dbEdge1, dbEdge2, err := graph.FetchChannelEdgesByID(chanID)