signature.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package lnwire
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/btcsuite/btcd/btcec/v2/ecdsa"
  6. "github.com/btcsuite/btcd/btcec/v2/schnorr"
  7. "github.com/lightningnetwork/lnd/input"
  8. "github.com/lightningnetwork/lnd/tlv"
  9. )
  10. var (
  11. errSigTooShort = errors.New("malformed signature: too short")
  12. errBadLength = errors.New("malformed signature: bad length")
  13. errBadRLength = errors.New("malformed signature: bogus R length")
  14. errBadSLength = errors.New("malformed signature: bogus S length")
  15. errRTooLong = errors.New("R is over 32 bytes long without padding")
  16. errSTooLong = errors.New("S is over 32 bytes long without padding")
  17. )
  18. // sigType represents the type of signature that is carried within the Sig.
  19. // Today this can either be an ECDSA sig or a schnorr sig. Both of these can
  20. // fit cleanly into 64 bytes.
  21. type sigType uint
  22. const (
  23. // sigTypeECDSA represents an ECDSA signature.
  24. sigTypeECDSA sigType = iota
  25. // sigTypeSchnorr represents a schnorr signature.
  26. sigTypeSchnorr
  27. )
  28. // Sig is a fixed-sized ECDSA signature or 64-byte schnorr signature. For the
  29. // ECDSA sig, unlike Bitcoin, we use fixed sized signatures on the wire,
  30. // instead of DER encoded signatures. This type provides several methods to
  31. // convert to/from a regular Bitcoin DER encoded signature (raw bytes and
  32. // *ecdsa.Signature).
  33. type Sig struct {
  34. bytes [64]byte
  35. sigType sigType
  36. }
  37. // ForceSchnorr forces the signature to be interpreted as a schnorr signature.
  38. // This is useful when reading an HTLC sig off the wire for a taproot channel.
  39. // In this case, in order to obtain an input.Signature, we need to know that
  40. // the sig is a schnorr sig.
  41. func (s *Sig) ForceSchnorr() {
  42. s.sigType = sigTypeSchnorr
  43. }
  44. // RawBytes returns the raw bytes of signature.
  45. func (s *Sig) RawBytes() []byte {
  46. return s.bytes[:]
  47. }
  48. // Copy copies the signature into a new Sig instance.
  49. func (s *Sig) Copy() Sig {
  50. var sCopy Sig
  51. copy(sCopy.bytes[:], s.bytes[:])
  52. sCopy.sigType = s.sigType
  53. return sCopy
  54. }
  55. // Record returns a Record that can be used to encode or decode the backing
  56. // object.
  57. //
  58. // This returns a record that serializes the sig as a 64-byte fixed size
  59. // signature.
  60. func (s *Sig) Record() tlv.Record {
  61. // We set a type here as zero as it isn't needed when used as a
  62. // RecordT.
  63. return tlv.MakePrimitiveRecord(0, &s.bytes)
  64. }
  65. // NewSigFromWireECDSA returns a Sig instance based on an ECDSA signature
  66. // that's already in the 64-byte format we expect.
  67. func NewSigFromWireECDSA(sig []byte) (Sig, error) {
  68. if len(sig) != 64 {
  69. return Sig{}, fmt.Errorf("%w: %v bytes", errSigTooShort,
  70. len(sig))
  71. }
  72. var s Sig
  73. copy(s.bytes[:], sig)
  74. return s, nil
  75. }
  76. // NewSigFromECDSARawSignature returns a Sig from a Bitcoin raw signature
  77. // encoded in the canonical DER encoding.
  78. func NewSigFromECDSARawSignature(sig []byte) (Sig, error) {
  79. var b [64]byte
  80. // Check the total length is above the minimal.
  81. if len(sig) < ecdsa.MinSigLen {
  82. return Sig{}, errSigTooShort
  83. }
  84. // The DER representation is laid out as:
  85. // 0x30 <length> 0x02 <length r> r 0x02 <length s> s
  86. // which means the length of R is the 4th byte and the length of S is
  87. // the second byte after R ends. 0x02 signifies a length-prefixed,
  88. // zero-padded, big-endian bigint. 0x30 signifies a DER signature.
  89. // See the Serialize() method for ecdsa.Signature for details.
  90. // Reading <length>, remaining: [0x02 <length r> r 0x02 <length s> s]
  91. sigLen := int(sig[1])
  92. // siglen should be less than the entire message and greater than
  93. // the minimal message size.
  94. if sigLen+2 > len(sig) || sigLen+2 < ecdsa.MinSigLen {
  95. return Sig{}, errBadLength
  96. }
  97. // Reading <length r>, remaining: [r 0x02 <length s> s]
  98. rLen := int(sig[3])
  99. // rLen must be positive and must be able to fit in other elements.
  100. // Assuming s is one byte, then we have 0x30, <length>, 0x20,
  101. // <length r>, 0x20, <length s>, s, a total of 7 bytes.
  102. if rLen <= 0 || rLen+7 > len(sig) {
  103. return Sig{}, errBadRLength
  104. }
  105. // Reading <length s>, remaining: [s]
  106. sLen := int(sig[5+rLen])
  107. // S should be the rest of the string.
  108. // sLen must be positive and must be able to fit in other elements.
  109. // We know r is rLen bytes, and we have 0x30, <length>, 0x20,
  110. // <length r>, 0x20, <length s>, a total of rLen+6 bytes.
  111. if sLen <= 0 || sLen+rLen+6 > len(sig) {
  112. return Sig{}, errBadSLength
  113. }
  114. // Check to make sure R and S can both fit into their intended buffers.
  115. // We check S first because these code blocks decrement sLen and rLen
  116. // in the case of a 33-byte 0-padded integer returned from Serialize()
  117. // and rLen is used in calculating array indices for S. We can track
  118. // this with additional variables, but it's more efficient to just
  119. // check S first.
  120. if sLen > 32 {
  121. if (sLen > 33) || (sig[6+rLen] != 0x00) {
  122. return Sig{}, errSTooLong
  123. }
  124. sLen--
  125. copy(b[64-sLen:], sig[7+rLen:])
  126. } else {
  127. copy(b[64-sLen:], sig[6+rLen:])
  128. }
  129. // Do the same for R as we did for S
  130. if rLen > 32 {
  131. if (rLen > 33) || (sig[4] != 0x00) {
  132. return Sig{}, errRTooLong
  133. }
  134. rLen--
  135. copy(b[32-rLen:], sig[5:5+rLen])
  136. } else {
  137. copy(b[32-rLen:], sig[4:4+rLen])
  138. }
  139. return Sig{
  140. bytes: b,
  141. sigType: sigTypeECDSA,
  142. }, nil
  143. }
  144. // NewSigFromSchnorrRawSignature converts a raw schnorr signature into an
  145. // lnwire.Sig.
  146. func NewSigFromSchnorrRawSignature(sig []byte) (Sig, error) {
  147. var s Sig
  148. copy(s.bytes[:], sig)
  149. s.sigType = sigTypeSchnorr
  150. return s, nil
  151. }
  152. // NewSigFromSignature creates a new signature as used on the wire, from an
  153. // existing ecdsa.Signature or schnorr.Signature.
  154. func NewSigFromSignature(e input.Signature) (Sig, error) {
  155. if e == nil {
  156. return Sig{}, fmt.Errorf("cannot decode empty signature")
  157. }
  158. // Nil is still a valid interface, apparently. So we need a more
  159. // explicit check here.
  160. if ecsig, ok := e.(*ecdsa.Signature); ok && ecsig == nil {
  161. return Sig{}, fmt.Errorf("cannot decode empty signature")
  162. }
  163. switch ecSig := e.(type) {
  164. // If this is a schnorr signature, then we can just pack it as normal,
  165. // since the default encoding is already 64 bytes.
  166. case *schnorr.Signature:
  167. return NewSigFromSchnorrRawSignature(e.Serialize())
  168. // For ECDSA signatures, we'll need to do a bit more work to map the
  169. // signature into a compact 64 byte form.
  170. case *ecdsa.Signature:
  171. // Serialize the signature with all the checks that entails.
  172. return NewSigFromECDSARawSignature(e.Serialize())
  173. default:
  174. return Sig{}, fmt.Errorf("unknown wire sig type: %T", ecSig)
  175. }
  176. }
  177. // ToSignature converts the fixed-sized signature to a input.Signature which
  178. // can be used for signature validation checks.
  179. func (s *Sig) ToSignature() (input.Signature, error) {
  180. switch s.sigType {
  181. case sigTypeSchnorr:
  182. return schnorr.ParseSignature(s.bytes[:])
  183. case sigTypeECDSA:
  184. // Parse the signature with strict checks.
  185. sigBytes := s.ToSignatureBytes()
  186. sig, err := ecdsa.ParseDERSignature(sigBytes)
  187. if err != nil {
  188. return nil, err
  189. }
  190. return sig, nil
  191. default:
  192. return nil, fmt.Errorf("unknown sig type: %v", s.sigType)
  193. }
  194. }
  195. // ToSignatureBytes serializes the target fixed-sized signature into the
  196. // encoding of the primary domain for the signature. For ECDSA signatures, this
  197. // is the raw bytes of a DER encoding.
  198. func (s *Sig) ToSignatureBytes() []byte {
  199. switch s.sigType {
  200. // For ECDSA signatures, we'll convert to DER encoding.
  201. case sigTypeECDSA:
  202. // Extract canonically-padded bigint representations from buffer
  203. r := extractCanonicalPadding(s.bytes[0:32])
  204. s := extractCanonicalPadding(s.bytes[32:64])
  205. rLen := uint8(len(r))
  206. sLen := uint8(len(s))
  207. // Create a canonical serialized signature. DER format is:
  208. // 0x30 <length> 0x02 <length r> r 0x02 <length s> s
  209. sigBytes := make([]byte, 6+rLen+sLen)
  210. sigBytes[0] = 0x30 // DER signature magic value
  211. sigBytes[1] = 4 + rLen + sLen // Length of rest of signature
  212. sigBytes[2] = 0x02 // Big integer magic value
  213. sigBytes[3] = rLen // Length of R
  214. sigBytes[rLen+4] = 0x02 // Big integer magic value
  215. sigBytes[rLen+5] = sLen // Length of S
  216. copy(sigBytes[4:], r) // Copy R
  217. copy(sigBytes[rLen+6:], s) // Copy S
  218. return sigBytes
  219. // For schnorr signatures, we can use the same internal 64 bytes.
  220. case sigTypeSchnorr:
  221. // We'll make a copy of the signature so we don't return a
  222. // reference into the raw slice.
  223. var sig [64]byte
  224. copy(sig[:], s.bytes[:])
  225. return sig[:]
  226. default:
  227. // TODO(roasbeef): can only be called via public methods so
  228. // never reachable?
  229. panic("sig type not set")
  230. }
  231. }
  232. // extractCanonicalPadding is a utility function to extract the canonical
  233. // padding of a big-endian integer from the wire encoding (a 0-padded
  234. // big-endian integer) such that it passes btcec.canonicalPadding test.
  235. func extractCanonicalPadding(b []byte) []byte {
  236. for i := 0; i < len(b); i++ {
  237. // Found first non-zero byte.
  238. if b[i] > 0 {
  239. // If the MSB is set, we need zero padding.
  240. if b[i]&0x80 == 0x80 {
  241. return append([]byte{0x00}, b[i:]...)
  242. }
  243. return b[i:]
  244. }
  245. }
  246. return []byte{0x00}
  247. }