|
| 1 | +package session |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/binary" |
| 6 | + "encoding/hex" |
| 7 | + "strconv" |
| 8 | + |
| 9 | + "github.com/lightningnetwork/lnd/lnrpc" |
| 10 | + "google.golang.org/protobuf/proto" |
| 11 | + "gopkg.in/macaroon-bakery.v2/bakery" |
| 12 | + "gopkg.in/macaroon.v2" |
| 13 | +) |
| 14 | + |
| 15 | +var ( |
| 16 | + // SuperMacaroonRootKeyPrefix is the prefix we set on a super macaroon's |
| 17 | + // root key to clearly mark it as such. |
| 18 | + SuperMacaroonRootKeyPrefix = [4]byte{0xFF, 0xEE, 0xDD, 0xCC} |
| 19 | +) |
| 20 | + |
| 21 | +// NewSuperMacaroonRootKeyID returns a new macaroon root key ID that has the |
| 22 | +// prefix to mark it as a super macaroon root key. |
| 23 | +func NewSuperMacaroonRootKeyID(id [4]byte) uint64 { |
| 24 | + rootKeyBytes := make([]byte, 8) |
| 25 | + copy(rootKeyBytes[:], SuperMacaroonRootKeyPrefix[:]) |
| 26 | + copy(rootKeyBytes[4:], id[:]) |
| 27 | + return binary.BigEndian.Uint64(rootKeyBytes) |
| 28 | +} |
| 29 | + |
| 30 | +// ParseMacaroon parses a hex encoded macaroon into its native struct. |
| 31 | +func ParseMacaroon(macHex string) (*macaroon.Macaroon, error) { |
| 32 | + macBytes, err := hex.DecodeString(macHex) |
| 33 | + if err != nil { |
| 34 | + return nil, err |
| 35 | + } |
| 36 | + |
| 37 | + mac := &macaroon.Macaroon{} |
| 38 | + if err := mac.UnmarshalBinary(macBytes); err != nil { |
| 39 | + return nil, err |
| 40 | + } |
| 41 | + |
| 42 | + return mac, nil |
| 43 | +} |
| 44 | + |
| 45 | +// IsSuperMacaroon returns true if the given hex encoded macaroon is a super |
| 46 | +// macaroon baked by LiT which can be identified by its root key ID. |
| 47 | +func IsSuperMacaroon(macHex string) bool { |
| 48 | + mac, err := ParseMacaroon(macHex) |
| 49 | + if err != nil { |
| 50 | + return false |
| 51 | + } |
| 52 | + |
| 53 | + rawID := mac.Id() |
| 54 | + if rawID[0] != byte(bakery.LatestVersion) { |
| 55 | + return false |
| 56 | + } |
| 57 | + decodedID := &lnrpc.MacaroonId{} |
| 58 | + idProto := rawID[1:] |
| 59 | + err = proto.Unmarshal(idProto, decodedID) |
| 60 | + if err != nil { |
| 61 | + return false |
| 62 | + } |
| 63 | + |
| 64 | + // The storage ID is a string representation of a 64bit unsigned number. |
| 65 | + rootKeyID, err := strconv.ParseUint(string(decodedID.StorageId), 10, 64) |
| 66 | + if err != nil { |
| 67 | + return false |
| 68 | + } |
| 69 | + |
| 70 | + return isSuperMacaroonRootKeyID(rootKeyID) |
| 71 | +} |
| 72 | + |
| 73 | +// isSuperMacaroonRootKeyID returns true if the given macaroon root key ID (also |
| 74 | +// known as storage ID) is a super macaroon, which can be identified by its |
| 75 | +// first 4 bytes. |
| 76 | +func isSuperMacaroonRootKeyID(rootKeyID uint64) bool { |
| 77 | + rootKeyBytes := make([]byte, 8) |
| 78 | + binary.BigEndian.PutUint64(rootKeyBytes, rootKeyID) |
| 79 | + return bytes.HasPrefix(rootKeyBytes, SuperMacaroonRootKeyPrefix[:]) |
| 80 | +} |
0 commit comments