/
plugin.go
296 lines (251 loc) · 6.72 KB
/
plugin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package plugin
import (
"crypto/sha256"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
lightning "github.com/fiatjaf/lightningd-gjson-rpc"
)
const (
timeformat = "2006-01-02T15:04:05.000Z"
)
type Plugin struct {
Client *lightning.Client `json:"-"`
Log func(...interface{}) `json:"-"`
Logf func(string, ...interface{}) `json:"-"`
Name string `json:"-"`
Version string `json:"-"`
Network string `json:"-"`
Options []Option `json:"options"`
RPCMethods []RPCMethod `json:"rpcmethods"`
Subscriptions []Subscription `json:"subscriptions"`
Hooks []Hook `json:"hooks"`
Features Features `json:"featurebits"`
Dynamic bool `json:"dynamic"`
Notifications []NotificationTopic `json:"notifications"`
Configuration Params `json:"-"`
Args Params `json:"-"`
OnInit func(*Plugin) `json:"-"`
}
type Features struct {
Node string `json:"features"`
Channel string `json:"channel"`
Init string `json:"init"`
Invoice string `json:"invoice"`
}
type NotificationTopic struct {
Method string `json:"method"`
}
type Option struct {
Name string `json:"name"`
Type string `json:"type"`
Default interface{} `json:"default"`
Description string `json:"description"`
}
type RPCMethod struct {
Name string `json:"name"`
Usage string `json:"usage"`
Description string `json:"description"`
LongDescription string `json:"long_description"`
Handler RPCHandler `json:"-"`
}
type Subscription struct {
Type string
Handler NotificationHandler
}
func (s Subscription) MarshalJSON() ([]byte, error) { return json.Marshal(s.Type) }
type Hook struct {
Type string
Handler HookHandler
}
func (h Hook) MarshalJSON() ([]byte, error) { return json.Marshal(h.Type) }
type RPCHandler func(p *Plugin, params Params) (resp interface{}, errCode int, err error)
type NotificationHandler func(p *Plugin, params Params)
type HookHandler func(p *Plugin, params Params) (resp interface{})
type LogProxy struct {
prefix string
target io.Writer
}
func (lp *LogProxy) Write(p []byte) (n int, err error) {
timestamp := time.Now().Format(timeformat)
res := fmt.Sprintf("%s %s %s", timestamp, lp.prefix, p)
res = strings.TrimRight(res, "\n ")
return lp.target.Write([]byte(res + "\n"))
}
func (p *Plugin) Run() {
initialized := make(chan bool)
go func() {
<-initialized
if p.OnInit != nil {
p.OnInit(p)
}
}()
p.Listener(initialized)
}
func (p *Plugin) colorize(text string) string {
h := sha256.Sum256([]byte(p.Name))
n := binary.BigEndian.Uint64(h[:])
colors := []string{
"\x1B[01;91m",
"\x1B[01;92m",
"\x1B[01;93m",
"\x1B[01;94m",
"\x1B[01;95m",
"\x1B[01;96m",
"\x1B[01;97m",
}
return colors[n%uint64(len(colors))] + text + "\x1B[0m"
}
var rpcmethodmap = make(map[string]RPCMethod)
var submap = make(map[string]Subscription)
var hookmap = make(map[string]Hook)
func (p *Plugin) Listener(initialized chan<- bool) {
for _, rpcmethod := range p.RPCMethods {
rpcmethodmap[rpcmethod.Name] = rpcmethod
}
for _, sub := range p.Subscriptions {
submap[sub.Type] = sub
}
for _, hook := range p.Hooks {
hookmap[hook.Type] = hook
}
// logging
prefix := p.colorize("plugin-" + p.Name)
logproxy := &LogProxy{
prefix: prefix,
target: os.Stderr,
}
log.SetOutput(logproxy)
log.SetFlags(0)
p.Log = func(args ...interface{}) {
fmt.Fprint(logproxy, args...)
}
p.Logf = func(b string, args ...interface{}) {
fmt.Fprintf(logproxy, b, args...)
}
var msg lightning.JSONRPCMessage
incoming := json.NewDecoder(os.Stdin)
outgoing := json.NewEncoder(os.Stdout)
for {
err := incoming.Decode(&msg)
if err == io.EOF {
return
}
if err != nil {
p.Log("failed to decode request. killing: " + err.Error())
return
}
switch msg.Method {
case "getmanifest":
if p.Options == nil {
p.Options = make([]Option, 0)
}
if p.RPCMethods == nil {
p.RPCMethods = make([]RPCMethod, 0)
}
if p.Hooks == nil {
p.Hooks = make([]Hook, 0)
}
if p.Notifications == nil {
p.Notifications = make([]NotificationTopic, 0)
}
if p.Subscriptions == nil {
p.Subscriptions = make([]Subscription, 0)
}
jmanifest, _ := json.Marshal(p)
response := lightning.JSONRPCResponse{
Version: msg.Version,
Id: msg.Id,
}
json.Unmarshal([]byte(jmanifest), &response.Result)
outgoing.Encode(response)
case "init":
params := msg.Params.(map[string]interface{})
iconf := params["configuration"]
conf := iconf.(map[string]interface{})
p.Configuration = Params(conf)
p.Network = conf["network"].(string)
lnpath := conf["lightning-dir"].(string)
rpcfile := conf["rpc-file"].(string)
rpc := filepath.Join(lnpath, rpcfile)
if filepath.IsAbs(rpcfile) {
rpc = rpcfile
}
p.Client = &lightning.Client{
Path: rpc,
LightningDir: lnpath,
}
p.Args = Params(params["options"].(map[string]interface{}))
p.Log("initialized plugin " + p.Version)
initialized <- true
outgoing.Encode(lightning.JSONRPCResponse{
Version: msg.Version,
Id: msg.Id,
})
default:
go handleMessage(p, outgoing, msg)
}
}
}
func handleMessage(p *Plugin, outgoing *json.Encoder, msg lightning.JSONRPCMessage) {
response := lightning.JSONRPCResponse{
Version: msg.Version,
Id: msg.Id,
}
if rpcmethod, ok := rpcmethodmap[msg.Method]; ok {
params, err := GetParams(msg.Params, rpcmethod.Usage)
if err != nil {
p.Logf("Error decoding params '%s': %s", rpcmethod.Usage, err.Error())
response.Error = &lightning.JSONRPCError{
Code: 400,
Message: "Error decoding params: " + rpcmethod.Usage,
}
goto end
}
resp, errCode, err := rpcmethod.Handler(p, params)
if err != nil {
if errCode == 0 {
errCode = -1
}
response.Error = &lightning.JSONRPCError{
Code: errCode,
Message: err.Error(),
}
goto end
}
jresp, err := json.Marshal(resp)
if err != nil {
response.Error = &lightning.JSONRPCError{
Code: 500,
Message: "Error encoding method response.",
}
goto end
}
response.Result = jresp
}
if hook, ok := hookmap[msg.Method]; ok {
resp := hook.Handler(p, Params(msg.Params.(map[string]interface{})))
jresp, err := json.Marshal(resp)
if err != nil {
response.Error = &lightning.JSONRPCError{
Code: 500,
Message: "Error encoding hook response.",
}
goto end
}
response.Result = jresp
}
if sub, ok := submap[msg.Method]; ok {
sub.Handler(p, Params(msg.Params.(map[string]interface{})))
goto noanswer
}
end:
outgoing.Encode(response)
noanswer:
}