forked from fiatjaf/etleneum
-
Notifications
You must be signed in to change notification settings - Fork 1
/
htlc_accepted.go
301 lines (253 loc) · 8.04 KB
/
htlc_accepted.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
297
298
299
300
301
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"strconv"
"time"
"github.com/aead/chacha20"
"github.com/btcsuite/btcd/btcec"
"github.com/fiatjaf/etleneum/data"
"github.com/fiatjaf/lightningd-gjson-rpc/plugin"
sphinx "github.com/lightningnetwork/lightning-onion"
"github.com/lightningnetwork/lnd/lnwire"
)
var continueHTLC = map[string]interface{}{"result": "continue"}
var failHTLC = map[string]interface{}{"result": "fail", "failure_code": 16392}
func htlc_accepted(p *plugin.Plugin, params plugin.Params) (resp interface{}) {
amount := params.Get("htlc.amount").String()
scid := params.Get("onion.short_channel_id").String()
if scid == "0x0x0" {
// payment coming to this node, accept it
return continueHTLC
}
hash := params.Get("htlc.payment_hash").String()
p.Logf("got HTLC. amount=%s short_channel_id=%s hash=%s", amount, scid, hash)
for rds == nil || !data.Initialized {
p.Log("htlc_accepted: waiting until redis and filesystem are available.")
time.Sleep(1 * time.Second)
}
msatoshi, err := strconv.ParseInt(amount[:len(amount)-4], 10, 64)
if err != nil {
// I don't know what is happening
p.Logf("error parsing onion.forward_amount: %s - continue", err.Error())
return continueHTLC
}
bscid, err := decodeShortChannelId(scid)
if err != nil {
p.Logf("onion.short_channel_id is not in the usual format - continue")
return continueHTLC
}
id, ok := parseShortChannelId(bscid)
if !ok {
// it's not an invoice for an etleneum call or contract
p.Logf("failed to parse onion.short_channel_id - continue")
return continueHTLC
}
if id[0] != 'c' && id[0] != 'r' {
// it's not an invoice for an etleneum call or contract
p.Logf("parsed id is not an etleneum payment (%s) - continue", id)
return continueHTLC
}
// ensure that we can derive the correct preimage for this payment
preimage := makePreimage(id)
preimageHex := hex.EncodeToString(preimage)
derivedHash := sha256.Sum256(preimage)
derivedHashHex := hex.EncodeToString(derivedHash[:])
if hash != derivedHashHex {
p.Logf("we have a preimage %s, but its hash %s didn't match the expected hash %s - fail with incorrect_or_unknown_payment_details", preimageHex, derivedHashHex, hash)
// get keys stuff so we can return a wrapped onion to pre-pay probes
nextOnion, err := hex.DecodeString(params.Get("onion.next_onion").String())
if err != nil {
p.Logf("lightningd has sent us an invalid onion.next_onion: %s",
err.Error())
return failHTLC
}
var nextOnionPacket sphinx.OnionPacket
err = nextOnionPacket.Decode(bytes.NewBuffer(nextOnion))
if err != nil {
p.Logf("couldn't parse onion.next_onion: %s", err.Error())
return failHTLC
}
// private key for the last hop
var ctid string
if id[0] == 'c' {
ctid = id
} else if id[0] == 'r' {
call, err := callFromRedis(id)
if err != nil {
return continueHTLC
}
ctid = call.ContractId
}
lastHopKey, _ := makeKeys(ctid)
// bolt04 shared key stuff: ecdh() then sha256()
s := &btcec.PublicKey{}
s.X, s.Y = btcec.S256().ScalarMult(
nextOnionPacket.EphemeralKey.X,
nextOnionPacket.EphemeralKey.Y,
lastHopKey.D.Bytes(),
)
lastHopSharedSecret := sha256.Sum256(s.SerializeCompressed())
// produce the error as if we were the last hop
failure := lnwire.NewFailIncorrectDetails(lnwire.MilliSatoshi(msatoshi), 0)
var payload bytes.Buffer
if err := lnwire.EncodeFailure(&payload, failure, 0); err != nil {
panic(err)
}
data := payload.Bytes()
// hmac the payload
umKey := generateKey("um", lastHopSharedSecret[:])
mac := hmac.New(sha256.New, umKey[:])
mac.Write(data)
h := mac.Sum(nil)
failureOnion := append(h, data...)
// obfuscate/wrap the message as if we were the last hop
ammagKey := generateKey("ammag", lastHopSharedSecret[:])
placeholder := make([]byte, len(failureOnion))
xor(
placeholder,
failureOnion,
generateCipherStream(ammagKey, uint(len(failureOnion))),
)
failureOnion = placeholder
// return the onion as failure_onion and lightningd will wrap it
return map[string]interface{}{
"result": "fail",
"failure_onion": hex.EncodeToString(failureOnion),
}
}
// run the call
if id[0] == 'c' {
ok = contractPaymentReceived(id, msatoshi)
} else if id[0] == 'r' {
ok = callPaymentReceived(id, msatoshi)
}
// after the call succeeds, we resolve the payment
if ok {
p.Logf("call went ok. we have a preimage: %s - resolve", preimageHex)
return map[string]interface{}{
"result": "resolve",
"payment_key": preimageHex,
}
} else {
// in case of call execution failure we just fail the payment
p.Logf("call failed - fail")
return failHTLC
}
}
func contractPaymentReceived(contractId string, msatoshi int64) (ok bool) {
// start the contract
logger := log.With().Str("ctid", contractId).Logger()
ct, err := contractFromRedis(contractId)
if err != nil {
logger.Warn().Err(err).Msg("failed to fetch contract from redis to activate")
dispatchContractEvent(contractId,
ctevent{contractId, "", "", 0, err.Error(), "internal"}, "contract-error")
return false
}
if getContractCost(*ct) > msatoshi {
return false
}
data.Start()
// create initial contract
err = data.CreateContract(ct.Id, ct.Name, ct.Readme, ct.Code)
if err != nil {
logger.Warn().Err(err).Msg("failed to save contract on database")
data.Abort()
dispatchContractEvent(contractId,
ctevent{contractId, "", "", 0, err.Error(), "internal"}, "contract-error")
return false
}
// instantiate call (the __init__ special kind)
call := &data.Call{
ContractId: ct.Id,
Id: ct.Id, // same
Method: "__init__",
Payload: []byte("{}"),
Cost: getContractCost(*ct),
}
err = runCallGlobal(call, false)
if err != nil {
logger.Warn().Err(err).Msg("failed to run call")
data.Abort()
dispatchContractEvent(contractId,
ctevent{contractId, "", call.Method, 0, err.Error(), "runtime"},
"contract-error")
return false
}
// commit
data.Finish("contract " + ct.Id + " created.")
dispatchContractEvent(contractId,
ctevent{contractId, "", call.Method, 0, "", ""}, "contract-created")
logger.Info().Msg("contract is live")
// saved. delete from redis.
rds.Del("contract:" + contractId)
return true
}
func callPaymentReceived(callId string, msatoshi int64) (ok bool) {
// run the call
logger := log.With().Str("callid", callId).Logger()
call, err := callFromRedis(callId)
if err != nil {
logger.Warn().Err(err).Msg("failed to fetch call from redis")
return false
}
logger = logger.With().Str("ct", call.ContractId).Logger()
if call.Msatoshi+call.Cost > msatoshi {
// TODO: this is the place where we should handle MPP payments
logger.Warn().Int64("got", msatoshi).Int64("needed", call.Msatoshi+call.Cost).
Msg("insufficient payment amount")
return false
}
// if msatoshi is bigger than needed we take it as a donation
data.Start()
logger.Info().Interface("call", call).Msg("call being made")
// a normal call
err = runCallGlobal(call, false)
if err != nil {
logger.Warn().Err(err).Msg("failed to run call")
data.Abort()
dispatchContractEvent(call.ContractId,
ctevent{callId, call.ContractId, call.Method, call.Msatoshi, err.Error(), "runtime"}, "call-error")
return false
}
// commit
data.Finish("call " + call.Id + " executed on contract " + call.ContractId + ".")
dispatchContractEvent(call.ContractId,
ctevent{callId, call.ContractId, call.Method, call.Msatoshi, "", ""}, "call-made")
// saved. delete from redis.
rds.Del("call:" + call.Id)
return true
}
func generateCipherStream(key [32]byte, numBytes uint) []byte {
var (
nonce [8]byte
)
cipher, err := chacha20.NewCipher(nonce[:], key[:])
if err != nil {
panic(err)
}
output := make([]byte, numBytes)
cipher.XORKeyStream(output, output)
return output
}
func xor(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
func generateKey(keyType string, sharedKey []byte) [32]byte {
mac := hmac.New(sha256.New, []byte(keyType))
mac.Write(sharedKey)
h := mac.Sum(nil)
var key [32]byte
copy(key[:], h[:32])
return key
}