|
| 1 | +package rules |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/lightninglabs/lightning-terminal/litrpc" |
| 8 | +) |
| 9 | + |
| 10 | +// ErrUnknownRule indicates that LiT is unaware of a values name. |
| 11 | +var ErrUnknownRule = fmt.Errorf("unknown rule") |
| 12 | + |
| 13 | +// ManagerSet is a map from a rule name to a rule Manager. |
| 14 | +type ManagerSet map[string]Manager |
| 15 | + |
| 16 | +// NewRuleManagerSet creates a new map of the supported rule ManagerSet. |
| 17 | +func NewRuleManagerSet() ManagerSet { |
| 18 | + return map[string]Manager{} |
| 19 | +} |
| 20 | + |
| 21 | +// InitEnforcer gets the appropriate rule Manager for the given name and uses it |
| 22 | +// to create an appropriate rule Enforcer. |
| 23 | +func (m ManagerSet) InitEnforcer(cfg Config, name string, |
| 24 | + values Values) (Enforcer, error) { |
| 25 | + |
| 26 | + mgr, ok := m[name] |
| 27 | + if !ok { |
| 28 | + return nil, ErrUnknownRule |
| 29 | + } |
| 30 | + |
| 31 | + return mgr.NewEnforcer(cfg, values) |
| 32 | +} |
| 33 | + |
| 34 | +// GetAllRules returns a map of names of all the rules supported by rule |
| 35 | +// ManagerSet. |
| 36 | +func (m ManagerSet) GetAllRules() map[string]bool { |
| 37 | + rules := make(map[string]bool, len(m)) |
| 38 | + for name := range m { |
| 39 | + rules[name] = true |
| 40 | + } |
| 41 | + return rules |
| 42 | +} |
| 43 | + |
| 44 | +// UnmarshalRuleValues identifies the appropriate rule Manager based on the |
| 45 | +// given rule name and uses that to parse the proto value into a Value object. |
| 46 | +func (m ManagerSet) UnmarshalRuleValues(name string, proto *litrpc.RuleValue) ( |
| 47 | + Values, error) { |
| 48 | + |
| 49 | + mgr, ok := m[name] |
| 50 | + if !ok { |
| 51 | + return nil, ErrUnknownRule |
| 52 | + } |
| 53 | + |
| 54 | + return mgr.NewValueFromProto(proto) |
| 55 | +} |
| 56 | + |
| 57 | +// InitRuleValues can be used to construct a Values object given raw rule |
| 58 | +// value bytes along with the name of the appropriate rule. |
| 59 | +func (m ManagerSet) InitRuleValues(name string, valueBytes []byte) (Values, |
| 60 | + error) { |
| 61 | + |
| 62 | + mgr, ok := m[name] |
| 63 | + if !ok { |
| 64 | + return nil, ErrUnknownRule |
| 65 | + } |
| 66 | + |
| 67 | + v := mgr.EmptyValue() |
| 68 | + if err := json.Unmarshal(valueBytes, v); err != nil { |
| 69 | + return nil, err |
| 70 | + } |
| 71 | + |
| 72 | + return v, nil |
| 73 | +} |
| 74 | + |
| 75 | +// Stop stops all the managers in the set. |
| 76 | +func (m ManagerSet) Stop() error { |
| 77 | + var returnErr error |
| 78 | + for _, mgr := range m { |
| 79 | + err := mgr.Stop() |
| 80 | + if err != nil { |
| 81 | + returnErr = err |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return returnErr |
| 86 | +} |
0 commit comments