-
Notifications
You must be signed in to change notification settings - Fork 43
/
signer_client.go
596 lines (498 loc) · 18.9 KB
/
signer_client.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package lndclient
import (
"context"
"fmt"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
"google.golang.org/grpc"
)
// SignerClient exposes sign functionality.
type SignerClient interface {
// SignOutputRaw is a method that can be used to generate a signature
// for a set of inputs/outputs to a transaction. Each request specifies
// details concerning how the outputs should be signed, which keys they
// should be signed with, and also any optional tweaks.
SignOutputRaw(ctx context.Context, tx *wire.MsgTx,
signDescriptors []*SignDescriptor,
prevOutputs []*wire.TxOut) ([][]byte, error)
// ComputeInputScript generates the proper input script for P2WPKH
// output and NP2WPKH outputs. This method only requires that the
// `Output`, `HashType`, `SigHashes` and `InputIndex` fields are
// populated within the sign descriptors.
ComputeInputScript(ctx context.Context, tx *wire.MsgTx,
signDescriptors []*SignDescriptor, prevOutputs []*wire.TxOut) (
[]*input.Script, error)
// SignMessage signs a message with the key specified in the key
// locator. The returned signature is fixed-size LN wire format encoded.
SignMessage(ctx context.Context, msg []byte,
locator keychain.KeyLocator) ([]byte, error)
// VerifyMessage verifies a signature over a message using the public
// key provided. The signature must be fixed-size LN wire format
// encoded.
VerifyMessage(ctx context.Context, msg, sig []byte, pubkey [33]byte) (
bool, error)
// DeriveSharedKey returns a shared secret key by performing
// Diffie-Hellman key derivation between the ephemeral public key and
// the key specified by the key locator (or the node's identity private
// key if no key locator is specified):
//
// P_shared = privKeyNode * ephemeralPubkey
//
// The resulting shared public key is serialized in the compressed
// format and hashed with SHA256, resulting in a final key length of 256
// bits.
DeriveSharedKey(ctx context.Context, ephemeralPubKey *btcec.PublicKey,
keyLocator *keychain.KeyLocator) ([32]byte, error)
// MuSig2CreateSession creates a new musig session with the key and
// signers provided.
MuSig2CreateSession(ctx context.Context,
signerLoc *keychain.KeyLocator, signers [][32]byte,
opts ...MuSig2SessionOpts) (*input.MuSig2SessionInfo, error)
// MuSig2RegisterNonces registers additional public nonces for a musig2
// session. It returns a boolean indicating whether we have all of our
// nonces present.
MuSig2RegisterNonces(ctx context.Context, sessionID [32]byte,
nonces [][66]byte) (bool, error)
// MuSig2Sign creates a partial signature for the 32 byte SHA256 digest
// of a message. This can only be called once all public nonces have
// been created. If the caller will not be responsible for combining
// the signatures, the cleanup bool should be set.
MuSig2Sign(ctx context.Context, sessionID [32]byte,
message [32]byte, cleanup bool) ([]byte, error)
// MuSig2CombineSig combines the given partial signature(s) with the
// local one, if it already exists. Once a partial signature of all
// participants are registered, the final signature will be combined
// and returned.
MuSig2CombineSig(ctx context.Context, sessionID [32]byte,
otherPartialSigs [][]byte) (bool, []byte, error)
// MuSig2Cleanup removes a session from memory to free up resources.
MuSig2Cleanup(ctx context.Context, sessionID [32]byte) error
}
// SignDescriptor houses the necessary information required to successfully
// sign a given segwit output. This struct is used by the Signer interface in
// order to gain access to critical data needed to generate a valid signature.
type SignDescriptor struct {
// KeyDesc is a descriptor that precisely describes *which* key to use
// for signing. This may provide the raw public key directly, or
// require the Signer to re-derive the key according to the populated
// derivation path.
KeyDesc keychain.KeyDescriptor
// SingleTweak is a scalar value that will be added to the private key
// corresponding to the above public key to obtain the private key to
// be used to sign this input. This value is typically derived via the
// following computation:
//
// * derivedKey = privkey + sha256(perCommitmentPoint || pubKey) mod N
//
// NOTE: If this value is nil, then the input can be signed using only
// the above public key. Either a SingleTweak should be set or a
// DoubleTweak, not both.
SingleTweak []byte
// DoubleTweak is a private key that will be used in combination with
// its corresponding private key to derive the private key that is to
// be used to sign the target input. Within the Lightning protocol,
// this value is typically the commitment secret from a previously
// revoked commitment transaction. This value is in combination with
// two hash values, and the original private key to derive the private
// key to be used when signing.
//
// * k = (privKey*sha256(pubKey || tweakPub) +
// tweakPriv*sha256(tweakPub || pubKey)) mod N
//
// NOTE: If this value is nil, then the input can be signed using only
// the above public key. Either a SingleTweak should be set or a
// DoubleTweak, not both.
DoubleTweak *btcec.PrivateKey
// The 32 byte input to the taproot tweak derivation that is used to
// derive the output key from an internal key: outputKey = internalKey +
// tagged_hash("tapTweak", internalKey || tapTweak).
//
// When doing a BIP 86 spend, this field can be an empty byte slice.
//
// When doing a normal key path spend, with the output key committing to
// an actual script root, then this field should be: the tapscript root
// hash.
TapTweak []byte
// WitnessScript is the full script required to properly redeem the
// output. This field should be set to the full script if a p2wsh or
// p2tr output is being signed. For p2wkh it should be set to the hashed
// script (PkScript), for p2tr this should be the raw leaf script that's
// being spent.
WitnessScript []byte
// TaprootKeySpend specifies how the input should be signed. Depending
// on the method, either the tap_tweak, witness_script or both need to
// be specified. Defaults to SegWit v0 signing to be backward compatible
// with older RPC clients.
SignMethod input.SignMethod
// Output is the target output which should be signed. The PkScript and
// Value fields within the output should be properly populated,
// otherwise an invalid signature may be generated.
Output *wire.TxOut
// HashType is the target sighash type that should be used when
// generating the final sighash, and signature.
HashType txscript.SigHashType
// InputIndex is the target input within the transaction that should be
// signed.
InputIndex int
}
// MarshalSignMethod turns the native sign method into the RPC counterpart.
func MarshalSignMethod(signMethod input.SignMethod) signrpc.SignMethod {
switch signMethod {
case input.TaprootKeySpendBIP0086SignMethod:
return signrpc.SignMethod_SIGN_METHOD_TAPROOT_KEY_SPEND_BIP0086
case input.TaprootKeySpendSignMethod:
return signrpc.SignMethod_SIGN_METHOD_TAPROOT_KEY_SPEND
case input.TaprootScriptSpendSignMethod:
return signrpc.SignMethod_SIGN_METHOD_TAPROOT_SCRIPT_SPEND
default:
return signrpc.SignMethod_SIGN_METHOD_WITNESS_V0
}
}
type signerClient struct {
client signrpc.SignerClient
signerMac serializedMacaroon
timeout time.Duration
}
func newSignerClient(conn grpc.ClientConnInterface,
signerMac serializedMacaroon, timeout time.Duration) *signerClient {
return &signerClient{
client: signrpc.NewSignerClient(conn),
signerMac: signerMac,
timeout: timeout,
}
}
func marshallSignDescriptors(
signDescriptors []*SignDescriptor) []*signrpc.SignDescriptor {
rpcSignDescs := make([]*signrpc.SignDescriptor, len(signDescriptors))
for i, signDesc := range signDescriptors {
var keyBytes []byte
var keyLocator *signrpc.KeyLocator
if signDesc.KeyDesc.PubKey != nil {
keyBytes = signDesc.KeyDesc.PubKey.SerializeCompressed()
} else {
keyLocator = &signrpc.KeyLocator{
KeyFamily: int32(
signDesc.KeyDesc.KeyLocator.Family,
),
KeyIndex: int32(
signDesc.KeyDesc.KeyLocator.Index,
),
}
}
var doubleTweak []byte
if signDesc.DoubleTweak != nil {
doubleTweak = signDesc.DoubleTweak.Serialize()
}
rpcSignDescs[i] = &signrpc.SignDescriptor{
WitnessScript: signDesc.WitnessScript,
SignMethod: MarshalSignMethod(signDesc.SignMethod),
Output: &signrpc.TxOut{
PkScript: signDesc.Output.PkScript,
Value: signDesc.Output.Value,
},
Sighash: uint32(signDesc.HashType),
InputIndex: int32(signDesc.InputIndex),
KeyDesc: &signrpc.KeyDescriptor{
RawKeyBytes: keyBytes,
KeyLoc: keyLocator,
},
SingleTweak: signDesc.SingleTweak,
DoubleTweak: doubleTweak,
TapTweak: signDesc.TapTweak,
}
}
return rpcSignDescs
}
// marshallTxOut marshals the transaction outputs as their RPC counterparts.
func marshallTxOut(outputs []*wire.TxOut) []*signrpc.TxOut {
rpcOutputs := make([]*signrpc.TxOut, len(outputs))
for i, output := range outputs {
rpcOutputs[i] = &signrpc.TxOut{
PkScript: output.PkScript,
Value: output.Value,
}
}
return rpcOutputs
}
// SignOutputRaw is a method that can be used to generate a signature for a set
// of inputs/outputs to a transaction. Each request specifies details concerning
// how the outputs should be signed, which keys they should be signed with, and
// also any optional tweaks.
func (s *signerClient) SignOutputRaw(ctx context.Context, tx *wire.MsgTx,
signDescriptors []*SignDescriptor, prevOutputs []*wire.TxOut) ([][]byte,
error) {
txRaw, err := encodeTx(tx)
if err != nil {
return nil, err
}
rpcSignDescs := marshallSignDescriptors(signDescriptors)
rpcPrevOutputs := marshallTxOut(prevOutputs)
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.SignOutputRaw(rpcCtx,
&signrpc.SignReq{
RawTxBytes: txRaw,
SignDescs: rpcSignDescs,
PrevOutputs: rpcPrevOutputs,
},
)
if err != nil {
return nil, err
}
return resp.RawSigs, nil
}
// ComputeInputScript generates the proper input script for P2TR, P2WPKH and
// NP2WPKH outputs. This method only requires that the `Output`, `HashType`,
// `SigHashes` and `InputIndex` fields are populated within the sign
// descriptors. Passing in the previous outputs is required when spending one
// or more taproot (SegWit v1) outputs.
func (s *signerClient) ComputeInputScript(ctx context.Context, tx *wire.MsgTx,
signDescriptors []*SignDescriptor, prevOutputs []*wire.TxOut) (
[]*input.Script, error) {
txRaw, err := encodeTx(tx)
if err != nil {
return nil, err
}
rpcSignDescs := marshallSignDescriptors(signDescriptors)
rpcPrevOutputs := marshallTxOut(prevOutputs)
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.ComputeInputScript(
rpcCtx, &signrpc.SignReq{
RawTxBytes: txRaw,
SignDescs: rpcSignDescs,
PrevOutputs: rpcPrevOutputs,
},
)
if err != nil {
return nil, err
}
inputScripts := make([]*input.Script, 0, len(resp.InputScripts))
for _, inputScript := range resp.InputScripts {
inputScripts = append(inputScripts, &input.Script{
SigScript: inputScript.SigScript,
Witness: inputScript.Witness,
})
}
return inputScripts, nil
}
// SignMessage signs a message with the key specified in the key locator. The
// returned signature is fixed-size LN wire format encoded.
func (s *signerClient) SignMessage(ctx context.Context, msg []byte,
locator keychain.KeyLocator) ([]byte, error) {
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcIn := &signrpc.SignMessageReq{
Msg: msg,
KeyLoc: &signrpc.KeyLocator{
KeyFamily: int32(locator.Family),
KeyIndex: int32(locator.Index),
},
}
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.SignMessage(rpcCtx, rpcIn)
if err != nil {
return nil, err
}
return resp.Signature, nil
}
// VerifyMessage verifies a signature over a message using the public key
// provided. The signature must be fixed-size LN wire format encoded.
func (s *signerClient) VerifyMessage(ctx context.Context, msg, sig []byte,
pubkey [33]byte) (bool, error) {
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcIn := &signrpc.VerifyMessageReq{
Msg: msg,
Signature: sig,
Pubkey: pubkey[:],
}
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.VerifyMessage(rpcCtx, rpcIn)
if err != nil {
return false, err
}
return resp.Valid, nil
}
// DeriveSharedKey returns a shared secret key by performing Diffie-Hellman key
// derivation between the ephemeral public key and the key specified by the key
// locator (or the node's identity private key if no key locator is specified):
//
// P_shared = privKeyNode * ephemeralPubkey
//
// The resulting shared public key is serialized in the compressed format and
// hashed with SHA256, resulting in a final key length of 256 bits.
func (s *signerClient) DeriveSharedKey(ctx context.Context,
ephemeralPubKey *btcec.PublicKey,
keyLocator *keychain.KeyLocator) ([32]byte, error) {
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcIn := &signrpc.SharedKeyRequest{
EphemeralPubkey: ephemeralPubKey.SerializeCompressed(),
KeyLoc: &signrpc.KeyLocator{
KeyFamily: int32(keyLocator.Family),
KeyIndex: int32(keyLocator.Index),
},
}
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.DeriveSharedKey(rpcCtx, rpcIn)
if err != nil {
return [32]byte{}, err
}
var sharedKey [32]byte
copy(sharedKey[:], resp.SharedKey)
return sharedKey, nil
}
// MuSig2SessionOpts is the signature used to apply functional options to
// musig session requests.
type MuSig2SessionOpts func(*signrpc.MuSig2SessionRequest)
// noncesToBytes converts a set of public nonces to a [][]byte.
func noncesToBytes(nonces [][musig2.PubNonceSize]byte) [][]byte {
nonceBytes := make([][]byte, len(nonces))
for i := range nonces {
nonceBytes[i] = nonces[i][:]
}
return nonceBytes
}
// MuSig2NonceOpt adds an optional set of nonces to a musig session request.
func MuSig2NonceOpt(nonces [][musig2.PubNonceSize]byte) MuSig2SessionOpts {
return func(s *signrpc.MuSig2SessionRequest) {
s.OtherSignerPublicNonces = noncesToBytes(nonces)
}
}
// MuSig2TaprootTweakOpt adds an optional taproot tweak to the musig session
// request.
func MuSig2TaprootTweakOpt(scriptRoot []byte,
keySpendOnly bool) MuSig2SessionOpts {
return func(s *signrpc.MuSig2SessionRequest) {
s.TaprootTweak = &signrpc.TaprootTweakDesc{
ScriptRoot: scriptRoot,
KeySpendOnly: keySpendOnly,
}
}
}
// MuSig2CreateSession creates a new musig session with the key and signers
// provided.
func (s *signerClient) MuSig2CreateSession(ctx context.Context,
signerLoc *keychain.KeyLocator, signers [][32]byte,
opts ...MuSig2SessionOpts) (*input.MuSig2SessionInfo, error) {
signerBytes := make([][]byte, len(signers))
for i, signer := range signers {
signerBytes[i] = make([]byte, 32)
copy(signerBytes[i], signer[:])
}
req := &signrpc.MuSig2SessionRequest{
KeyLoc: &signrpc.KeyLocator{
KeyFamily: int32(signerLoc.Family),
KeyIndex: int32(signerLoc.Index),
},
AllSignerPubkeys: signerBytes,
}
for _, opt := range opts {
opt(req)
}
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.MuSig2CreateSession(rpcCtx, req)
if err != nil {
return nil, err
}
combinedKey, err := schnorr.ParsePubKey(resp.CombinedKey)
if err != nil {
return nil, fmt.Errorf("could not parse combined key: %v", err)
}
session := &input.MuSig2SessionInfo{
CombinedKey: combinedKey,
HaveAllNonces: resp.HaveAllNonces,
}
if len(resp.LocalPublicNonces) != musig2.PubNonceSize {
return nil, fmt.Errorf("unexpected local nonce size: %v",
len(resp.LocalPublicNonces))
}
copy(session.PublicNonce[:], resp.LocalPublicNonces)
if len(resp.SessionId) != 32 {
return nil, fmt.Errorf("unexpected session ID length: %v",
len(resp.SessionId))
}
copy(session.SessionID[:], resp.SessionId)
return session, nil
}
// MuSig2RegisterNonces registers additional public nonces for a musig2 session.
// It returns a boolean indicating whether we have all of our nonces present.
func (s *signerClient) MuSig2RegisterNonces(ctx context.Context,
sessionID [32]byte, nonces [][66]byte) (bool, error) {
req := &signrpc.MuSig2RegisterNoncesRequest{
SessionId: sessionID[:],
OtherSignerPublicNonces: noncesToBytes(nonces),
}
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.MuSig2RegisterNonces(rpcCtx, req)
if err != nil {
return false, err
}
return resp.HaveAllNonces, nil
}
// MuSig2Sign creates a partial signature for the 32 byte SHA256 digest of a
// message. This can only be called once all public nonces have been created.
// If the caller will not be responsible for combining the signatures, the
// cleanup bool should be set.
func (s *signerClient) MuSig2Sign(ctx context.Context, sessionID [32]byte,
message [32]byte, cleanup bool) ([]byte, error) {
req := &signrpc.MuSig2SignRequest{
SessionId: sessionID[:],
MessageDigest: message[:],
Cleanup: cleanup,
}
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.MuSig2Sign(rpcCtx, req)
if err != nil {
return nil, err
}
return resp.LocalPartialSignature, nil
}
// MuSig2CombineSig combines the given partial signature(s) with the local one,
// if it already exists. Once a partial signature of all participants are
// registered, the final signature will be combined and returned.
func (s *signerClient) MuSig2CombineSig(ctx context.Context, sessionID [32]byte,
otherPartialSigs [][]byte) (bool, []byte, error) {
req := &signrpc.MuSig2CombineSigRequest{
SessionId: sessionID[:],
OtherPartialSignatures: otherPartialSigs,
}
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
resp, err := s.client.MuSig2CombineSig(rpcCtx, req)
if err != nil {
return false, nil, err
}
return resp.HaveAllSignatures, resp.FinalSignature, nil
}
// MuSig2Cleanup allows a caller to clean up a session early in case where it's
// obvious that the signing session won't succeed and the resources can be
// released.
func (s *signerClient) MuSig2Cleanup(ctx context.Context,
sessionID [32]byte) error {
req := &signrpc.MuSig2CleanupRequest{
SessionId: sessionID[:],
}
rpcCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rpcCtx = s.signerMac.WithMacaroonAuth(rpcCtx)
_, err := s.client.MuSig2Cleanup(rpcCtx, req)
return err
}