github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/lnutil/msglib.go (about) 1 package lnutil 2 3 import ( 4 "bufio" 5 "bytes" 6 "encoding/binary" 7 "fmt" 8 9 "github.com/mit-dci/lit/btcutil/chaincfg/chainhash" 10 "github.com/mit-dci/lit/wire" 11 ) 12 13 //id numbers for messages, semi-arbitrary 14 const ( 15 MSGID_TEXTCHAT = 0x00 // send a text message 16 17 //Channel creation messages 18 MSGID_POINTREQ = 0x10 19 MSGID_POINTRESP = 0x11 20 MSGID_CHANDESC = 0x12 21 MSGID_CHANACK = 0x13 22 MSGID_SIGPROOF = 0x14 23 24 //Channel destruction messages 25 MSGID_CLOSEREQ = 0x20 // close channel 26 MSGID_CLOSERESP = 0x21 27 28 //Push Pull Messages 29 MSGID_DELTASIG = 0x30 // pushing funds in channel; request to send 30 MSGID_SIGREV = 0x31 // pulling funds; signing new state and revoking old 31 MSGID_GAPSIGREV = 0x32 // resolving collision 32 MSGID_REV = 0x33 // pushing funds; revoking previous channel state 33 34 // HTLC messages 35 MSGID_HASHSIG = 0x34 // Like a deltasig but offers an HTLC 36 MSGID_PREIMAGESIG = 0x35 // Like a hashsig but clears an HTLC 37 38 //not implemented 39 MSGID_FWDMSG = 0x40 40 MSGID_FWDAUTHREQ = 0x41 41 42 //not implemented 43 MSGID_SELFPUSH = 0x50 44 45 //Tower Messages 46 MSGID_WATCH_DESC = 0x60 // desc describes a new channel 47 MSGID_WATCH_STATEMSG = 0x61 // commsg is a single state in the channel 48 MSGID_WATCH_DELETE = 0x62 // Watch_clear marks a channel as ok to delete. No further updates possible. 49 50 //Routing messages 51 MSGID_LINK_DESC = 0x70 // Describes a new channel for routing 52 53 //Multihop payment messages 54 MSGID_PAY_REQ = 0x75 // Request payment 55 MSGID_PAY_ACK = 0x76 // Acknowledge payment (share preimage hash) 56 MSGID_PAY_SETUP = 0x77 // Setup a payment route 57 58 //Discreet log contracts messages 59 MSGID_DLC_OFFER = 0x90 // Offer a contract 60 MSGID_DLC_ACCEPTOFFER = 0x91 // Accept the contract 61 MSGID_DLC_DECLINEOFFER = 0x92 // Decline the contract 62 MSGID_DLC_CONTRACTACK = 0x93 // Acknowledge an acceptance 63 MSGID_DLC_CONTRACTFUNDINGSIGS = 0x94 // Funding signatures 64 MSGID_DLC_SIGPROOF = 0x95 // Sigproof 65 66 //Dual funding messages 67 MSGID_DUALFUNDINGREQ = 0xA0 // Requests funding details (UTXOs, Change address, Pubkey), including our own details and amount needed. 68 MSGID_DUALFUNDINGACCEPT = 0xA1 // Responds with funding details 69 MSGID_DUALFUNDINGDECL = 0xA2 // Declines the funding request 70 MSGID_DUALFUNDINGCHANACK = 0xA3 // Acknowledges channel and sends along signatures for funding 71 72 //Remote control messages 73 MSGID_REMOTE_RPCREQUEST = 0xB0 // Contains an RPC request from a remote peer 74 MSGID_REMOTE_RPCRESPONSE = 0xB1 // Contains an RPC response to send to a remote peer 75 76 DIGEST_TYPE_SHA256 = 0x00 77 DIGEST_TYPE_RIPEMD160 = 0x01 78 ) 79 80 //interface that all messages follow, for easy use 81 type LitMsg interface { 82 Peer() uint32 //return PeerIdx 83 MsgType() uint8 //returns Message Type (see constants above) 84 Bytes() []byte //returns data of message as []byte with the MsgType() preceding it 85 } 86 87 func LitMsgEqual(msg LitMsg, msg2 LitMsg) bool { 88 if msg.Peer() != msg2.Peer() || msg.MsgType() != msg2.MsgType() || !bytes.Equal(msg.Bytes(), msg2.Bytes()) { 89 return false 90 } 91 return true 92 } 93 94 //method for finding what type of message a generic []byte is 95 func LitMsgFromBytes(b []byte, peerid uint32) (LitMsg, error) { 96 if len(b) < 1 { 97 return nil, fmt.Errorf("The byte slice sent is empty") 98 } 99 msgType := b[0] // first byte signifies what type of message is 100 101 switch msgType { 102 case MSGID_TEXTCHAT: 103 return NewChatMsgFromBytes(b, peerid) 104 case MSGID_POINTREQ: 105 return NewPointReqMsgFromBytes(b, peerid) 106 case MSGID_POINTRESP: 107 return NewPointRespMsgFromBytes(b, peerid) 108 case MSGID_CHANDESC: 109 return NewChanDescMsgFromBytes(b, peerid) 110 case MSGID_CHANACK: 111 return NewChanAckMsgFromBytes(b, peerid) 112 case MSGID_SIGPROOF: 113 return NewSigProofMsgFromBytes(b, peerid) 114 115 case MSGID_CLOSEREQ: 116 return NewCloseReqMsgFromBytes(b, peerid) 117 /* not implemented 118 case MSGID_CLOSERESP: 119 */ 120 121 case MSGID_DELTASIG: 122 return NewDeltaSigMsgFromBytes(b, peerid) 123 case MSGID_SIGREV: 124 return NewSigRevFromBytes(b, peerid) 125 case MSGID_GAPSIGREV: 126 return NewGapSigRevFromBytes(b, peerid) 127 case MSGID_REV: 128 return NewRevMsgFromBytes(b, peerid) 129 case MSGID_HASHSIG: 130 return NewHashSigMsgFromBytes(b, peerid) 131 case MSGID_PREIMAGESIG: 132 return NewPreimageSigMsgFromBytes(b, peerid) 133 134 /* 135 case MSGID_FWDMSG: 136 case MSGID_FWDAUTHREQ: 137 138 case MSGID_SELFPUSH: 139 */ 140 141 case MSGID_WATCH_DESC: 142 return NewWatchDescMsgFromBytes(b, peerid) 143 case MSGID_WATCH_STATEMSG: 144 return NewWatchStateMsgFromBytes(b, peerid) 145 /* 146 case MSGID_WATCH_DELETE: 147 */ 148 149 case MSGID_LINK_DESC: 150 return NewLinkMsgFromBytes(b, peerid) 151 152 case MSGID_PAY_REQ: 153 return NewMultihopPaymentRequestMsgFromBytes(b, peerid) 154 case MSGID_PAY_ACK: 155 return NewMultihopPaymentAckMsgFromBytes(b, peerid) 156 case MSGID_PAY_SETUP: 157 return NewMultihopPaymentSetupMsgFromBytes(b, peerid) 158 159 case MSGID_DUALFUNDINGREQ: 160 return NewDualFundingReqMsgFromBytes(b, peerid) 161 case MSGID_DUALFUNDINGACCEPT: 162 return NewDualFundingAcceptMsgFromBytes(b, peerid) 163 case MSGID_DUALFUNDINGDECL: 164 return NewDualFundingDeclMsgFromBytes(b, peerid) 165 case MSGID_DUALFUNDINGCHANACK: 166 return NewDualFundingChanAckMsgFromBytes(b, peerid) 167 168 case MSGID_DLC_OFFER: 169 return NewDlcOfferMsgFromBytes(b, peerid) 170 case MSGID_DLC_ACCEPTOFFER: 171 return NewDlcOfferAcceptMsgFromBytes(b, peerid) 172 case MSGID_DLC_DECLINEOFFER: 173 return NewDlcOfferDeclineMsgFromBytes(b, peerid) 174 case MSGID_DLC_CONTRACTACK: 175 return NewDlcContractAckMsgFromBytes(b, peerid) 176 case MSGID_DLC_CONTRACTFUNDINGSIGS: 177 return NewDlcContractFundingSigsMsgFromBytes(b, peerid) 178 case MSGID_DLC_SIGPROOF: 179 return NewDlcContractSigProofMsgFromBytes(b, peerid) 180 181 case MSGID_REMOTE_RPCREQUEST: 182 return NewRemoteControlRpcRequestMsgFromBytes(b, peerid) 183 case MSGID_REMOTE_RPCRESPONSE: 184 return NewRemoteControlRpcResponseMsgFromBytes(b, peerid) 185 186 default: 187 return nil, fmt.Errorf("Unknown message of type %d ", msgType) 188 } 189 } 190 191 //---------- 192 193 //text message 194 type ChatMsg struct { 195 PeerIdx uint32 196 Text string 197 } 198 199 func NewChatMsg(peerid uint32, text string) ChatMsg { 200 t := new(ChatMsg) 201 t.PeerIdx = peerid 202 t.Text = text 203 return *t 204 } 205 206 func NewChatMsgFromBytes(b []byte, peerid uint32) (ChatMsg, error) { 207 c := new(ChatMsg) 208 c.PeerIdx = peerid 209 210 if len(b) <= 1 { 211 return *c, fmt.Errorf("got %d bytes, expect 2 or more", len(b)) 212 } 213 214 b = b[1:] 215 c.Text = string(b) 216 217 return *c, nil 218 } 219 220 func (self ChatMsg) Bytes() []byte { 221 var msg []byte 222 msg = append(msg, self.MsgType()) 223 msg = append(msg, []byte(self.Text)...) 224 return msg 225 } 226 227 func (self ChatMsg) Peer() uint32 { return self.PeerIdx } 228 func (self ChatMsg) MsgType() uint8 { return MSGID_TEXTCHAT } 229 230 //---------- 231 232 //message with no information, just shows a point is requested 233 type PointReqMsg struct { 234 PeerIdx uint32 235 Cointype uint32 236 } 237 238 func NewPointReqMsg(peerid uint32, cointype uint32) PointReqMsg { 239 p := new(PointReqMsg) 240 p.PeerIdx = peerid 241 p.Cointype = cointype 242 return *p 243 } 244 245 func NewPointReqMsgFromBytes(b []byte, peerid uint32) (PointReqMsg, error) { 246 247 pr := new(PointReqMsg) 248 pr.PeerIdx = peerid 249 250 if len(b) < 5 { 251 return *pr, fmt.Errorf("PointReq msg %d bytes, expect 5\n", len(b)) 252 } 253 254 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 255 coin := buf.Next(4) 256 pr.Cointype = BtU32(coin) 257 258 return *pr, nil 259 } 260 261 func (self PointReqMsg) Bytes() []byte { 262 var msg []byte 263 msg = append(msg, self.MsgType()) 264 coin := U32tB(self.Cointype) 265 msg = append(msg, coin[:]...) 266 return msg 267 } 268 269 func (self PointReqMsg) Peer() uint32 { return self.PeerIdx } 270 func (self PointReqMsg) MsgType() uint8 { return MSGID_POINTREQ } 271 272 //message to be used for reply to point request 273 type PointRespMsg struct { 274 PeerIdx uint32 275 ChannelPub [33]byte 276 RefundPub [33]byte 277 HAKDbase [33]byte 278 279 NextHTLCBase [33]byte 280 N2HTLCBase [33]byte 281 } 282 283 func NewPointRespMsg(peerid uint32, chanpub [33]byte, refundpub [33]byte, 284 HAKD [33]byte, nextHTLCBase [33]byte, N2HTLCBase [33]byte) PointRespMsg { 285 pr := new(PointRespMsg) 286 pr.PeerIdx = peerid 287 pr.ChannelPub = chanpub 288 pr.RefundPub = refundpub 289 pr.HAKDbase = HAKD 290 pr.NextHTLCBase = nextHTLCBase 291 pr.N2HTLCBase = N2HTLCBase 292 return *pr 293 } 294 295 // NewPointRespMsgFromBytes takes a byte slice and a peerid and constructs a 296 // PointRespMsg object from the bytes. Expects at least 1 + 33 + 33 + 33 + 297 // 33 + 33 = 166. 298 func NewPointRespMsgFromBytes(b []byte, peerid uint32) (PointRespMsg, error) { 299 pm := new(PointRespMsg) 300 301 if len(b) < 166 { 302 return *pm, fmt.Errorf("PointResp err: msg %d bytes, expect 166\n", len(b)) 303 } 304 305 pm.PeerIdx = peerid 306 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 307 copy(pm.ChannelPub[:], buf.Next(33)) 308 copy(pm.RefundPub[:], buf.Next(33)) 309 copy(pm.HAKDbase[:], buf.Next(33)) 310 copy(pm.NextHTLCBase[:], buf.Next(33)) 311 copy(pm.N2HTLCBase[:], buf.Next(33)) 312 313 return *pm, nil 314 } 315 316 func (self PointRespMsg) Bytes() []byte { 317 var msg []byte 318 msg = append(msg, self.MsgType()) 319 msg = append(msg, self.ChannelPub[:]...) 320 msg = append(msg, self.RefundPub[:]...) 321 msg = append(msg, self.HAKDbase[:]...) 322 msg = append(msg, self.NextHTLCBase[:]...) 323 msg = append(msg, self.N2HTLCBase[:]...) 324 return msg 325 } 326 327 func (self PointRespMsg) Peer() uint32 { return self.PeerIdx } 328 func (self PointRespMsg) MsgType() uint8 { return MSGID_POINTRESP } 329 330 //message with a channel's description 331 type ChanDescMsg struct { 332 PeerIdx uint32 333 Outpoint wire.OutPoint 334 PubKey [33]byte 335 RefundPub [33]byte 336 HAKDbase [33]byte 337 338 NextHTLCBase [33]byte 339 N2HTLCBase [33]byte 340 341 CoinType uint32 342 Capacity int64 343 InitPayment int64 344 345 ElkZero [33]byte //consider changing into array in future 346 ElkOne [33]byte 347 ElkTwo [33]byte 348 349 Data [32]byte 350 } 351 352 func NewChanDescMsg( 353 peerid uint32, OP wire.OutPoint, 354 pubkey, refund, hakd [33]byte, nextHTLCBase [33]byte, N2HTLCBase [33]byte, 355 cointype uint32, 356 capacity int64, payment int64, 357 ELKZero, ELKOne, ELKTwo [33]byte, data [32]byte) ChanDescMsg { 358 359 cd := new(ChanDescMsg) 360 cd.PeerIdx = peerid 361 cd.Outpoint = OP 362 cd.PubKey = pubkey 363 cd.RefundPub = refund 364 cd.HAKDbase = hakd 365 cd.NextHTLCBase = nextHTLCBase 366 cd.N2HTLCBase = N2HTLCBase 367 cd.CoinType = cointype 368 cd.Capacity = capacity 369 cd.InitPayment = payment 370 cd.ElkZero = ELKZero 371 cd.ElkOne = ELKOne 372 cd.ElkTwo = ELKTwo 373 cd.Data = data 374 return *cd 375 } 376 377 func NewChanDescMsgFromBytes(b []byte, peerid uint32) (ChanDescMsg, error) { 378 cm := new(ChanDescMsg) 379 cm.PeerIdx = peerid 380 381 if len(b) < 283 { 382 return *cm, fmt.Errorf("got %d byte channel description, expect 283", len(b)) 383 } 384 385 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 386 var op [36]byte 387 copy(op[:], buf.Next(36)) 388 cm.Outpoint = *OutPointFromBytes(op) 389 copy(cm.PubKey[:], buf.Next(33)) 390 copy(cm.RefundPub[:], buf.Next(33)) 391 copy(cm.HAKDbase[:], buf.Next(33)) 392 copy(cm.NextHTLCBase[:], buf.Next(33)) 393 copy(cm.N2HTLCBase[:], buf.Next(33)) 394 cm.CoinType = BtU32(buf.Next(4)) 395 cm.Capacity = BtI64(buf.Next(8)) 396 cm.InitPayment = BtI64(buf.Next(8)) 397 copy(cm.ElkZero[:], buf.Next(33)) 398 copy(cm.ElkOne[:], buf.Next(33)) 399 copy(cm.ElkTwo[:], buf.Next(33)) 400 copy(cm.Data[:], buf.Next(32)) 401 402 return *cm, nil 403 } 404 405 func (self ChanDescMsg) Bytes() []byte { 406 coinTypeBin := U32tB(self.CoinType) 407 capBin := I64tB(self.Capacity) 408 initBin := I64tB(self.InitPayment) 409 410 var msg []byte 411 opArr := OutPointToBytes(self.Outpoint) 412 msg = append(msg, self.MsgType()) 413 msg = append(msg, opArr[:]...) 414 msg = append(msg, self.PubKey[:]...) 415 msg = append(msg, self.RefundPub[:]...) 416 msg = append(msg, self.HAKDbase[:]...) 417 msg = append(msg, self.NextHTLCBase[:]...) 418 msg = append(msg, self.N2HTLCBase[:]...) 419 msg = append(msg, coinTypeBin[:]...) 420 msg = append(msg, capBin[:]...) 421 msg = append(msg, initBin[:]...) 422 msg = append(msg, self.ElkZero[:]...) 423 msg = append(msg, self.ElkOne[:]...) 424 msg = append(msg, self.ElkTwo[:]...) 425 msg = append(msg, self.Data[:]...) 426 return msg 427 } 428 429 func (self ChanDescMsg) Peer() uint32 { return self.PeerIdx } 430 func (self ChanDescMsg) MsgType() uint8 { return MSGID_CHANDESC } 431 432 //message for channel acknowledgement after description message 433 type ChanAckMsg struct { 434 PeerIdx uint32 435 Outpoint wire.OutPoint 436 ElkZero [33]byte 437 ElkOne [33]byte 438 ElkTwo [33]byte 439 Signature [64]byte 440 } 441 442 func NewChanAckMsg(peerid uint32, OP wire.OutPoint, ELKZero [33]byte, ELKOne [33]byte, ELKTwo [33]byte, SIG [64]byte) ChanAckMsg { 443 ca := new(ChanAckMsg) 444 ca.PeerIdx = peerid 445 ca.Outpoint = OP 446 ca.ElkZero = ELKZero 447 ca.ElkOne = ELKOne 448 ca.ElkTwo = ELKTwo 449 ca.Signature = SIG 450 return *ca 451 } 452 453 func NewChanAckMsgFromBytes(b []byte, peerid uint32) (ChanAckMsg, error) { 454 cm := new(ChanAckMsg) 455 cm.PeerIdx = peerid 456 457 if len(b) < 200 { 458 return *cm, fmt.Errorf("got %d byte multiAck, expect 200", len(b)) 459 } 460 461 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 462 463 var op [36]byte 464 copy(op[:], buf.Next(36)) 465 cm.Outpoint = *OutPointFromBytes(op) 466 copy(cm.ElkZero[:], buf.Next(33)) 467 copy(cm.ElkOne[:], buf.Next(33)) 468 copy(cm.ElkTwo[:], buf.Next(33)) 469 copy(cm.Signature[:], buf.Next(64)) 470 return *cm, nil 471 } 472 473 func (self ChanAckMsg) Bytes() []byte { 474 var msg []byte 475 opArr := OutPointToBytes(self.Outpoint) 476 msg = append(msg, self.MsgType()) 477 msg = append(msg, opArr[:]...) 478 msg = append(msg, self.ElkZero[:]...) 479 msg = append(msg, self.ElkOne[:]...) 480 msg = append(msg, self.ElkTwo[:]...) 481 msg = append(msg, self.Signature[:]...) 482 return msg 483 } 484 485 func (self ChanAckMsg) Peer() uint32 { return self.PeerIdx } 486 func (self ChanAckMsg) MsgType() uint8 { return MSGID_CHANACK } 487 488 //message for proof for a signature 489 type SigProofMsg struct { 490 PeerIdx uint32 491 Outpoint wire.OutPoint 492 Signature [64]byte 493 } 494 495 func NewSigProofMsg(peerid uint32, OP wire.OutPoint, SIG [64]byte) SigProofMsg { 496 sp := new(SigProofMsg) 497 sp.PeerIdx = peerid 498 sp.Outpoint = OP 499 sp.Signature = SIG 500 return *sp 501 } 502 503 func NewSigProofMsgFromBytes(b []byte, peerid uint32) (SigProofMsg, error) { 504 sm := new(SigProofMsg) 505 sm.PeerIdx = peerid 506 507 if len(b) < 101 { 508 return *sm, fmt.Errorf("got %d byte Sigproof, expect ~101\n", len(b)) 509 } 510 511 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 512 513 var op [36]byte 514 copy(op[:], buf.Next(36)) 515 sm.Outpoint = *OutPointFromBytes(op) 516 copy(sm.Signature[:], buf.Next(64)) 517 return *sm, nil 518 } 519 520 func (self SigProofMsg) Bytes() []byte { 521 var msg []byte 522 msg = append(msg, self.MsgType()) 523 opArr := OutPointToBytes(self.Outpoint) 524 msg = append(msg, opArr[:]...) 525 msg = append(msg, self.Signature[:]...) 526 return msg 527 } 528 529 func (self SigProofMsg) Peer() uint32 { return self.PeerIdx } 530 func (self SigProofMsg) MsgType() uint8 { return MSGID_SIGPROOF } 531 532 //---------- 533 534 //message for closing a channel 535 type CloseReqMsg struct { 536 PeerIdx uint32 537 Outpoint wire.OutPoint 538 Signature [64]byte 539 } 540 541 func NewCloseReqMsg(peerid uint32, OP wire.OutPoint, SIG [64]byte) CloseReqMsg { 542 cr := new(CloseReqMsg) 543 cr.PeerIdx = peerid 544 cr.Outpoint = OP 545 cr.Signature = SIG 546 return *cr 547 } 548 549 func NewCloseReqMsgFromBytes(b []byte, peerid uint32) (CloseReqMsg, error) { 550 crm := new(CloseReqMsg) 551 crm.PeerIdx = peerid 552 553 if len(b) < 101 { 554 return *crm, fmt.Errorf("got %d byte closereq, expect 101ish\n", len(b)) 555 } 556 557 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 558 559 var op [36]byte 560 copy(op[:], buf.Next(36)) 561 crm.Outpoint = *OutPointFromBytes(op) 562 563 copy(crm.Signature[:], buf.Next(64)) 564 return *crm, nil 565 } 566 567 func (self CloseReqMsg) Bytes() []byte { 568 var msg []byte 569 msg = append(msg, self.MsgType()) 570 opArr := OutPointToBytes(self.Outpoint) 571 msg = append(msg, opArr[:]...) 572 msg = append(msg, self.Signature[:]...) 573 return msg 574 } 575 576 func (self CloseReqMsg) Peer() uint32 { return self.PeerIdx } 577 func (self CloseReqMsg) MsgType() uint8 { return MSGID_CLOSEREQ } 578 579 //---------- 580 581 //message for sending an amount with the signature 582 type DeltaSigMsg struct { 583 PeerIdx uint32 584 Outpoint wire.OutPoint 585 Delta int32 586 Signature [64]byte 587 Data [32]byte 588 HTLCSigs [][64]byte 589 } 590 591 func NewDeltaSigMsg(peerid uint32, OP wire.OutPoint, DELTA int32, SIG [64]byte, HTLCSigs [][64]byte, data [32]byte) DeltaSigMsg { 592 d := new(DeltaSigMsg) 593 d.PeerIdx = peerid 594 d.Outpoint = OP 595 d.Delta = DELTA 596 d.Signature = SIG 597 d.Data = data 598 d.HTLCSigs = HTLCSigs 599 return *d 600 } 601 602 func NewDeltaSigMsgFromBytes(b []byte, peerid uint32) (DeltaSigMsg, error) { 603 ds := new(DeltaSigMsg) 604 ds.PeerIdx = peerid 605 606 if len(b) < 105 { 607 return *ds, fmt.Errorf("got %d byte DeltaSig, expect 105", len(b)) 608 } 609 610 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 611 612 var op [36]byte 613 copy(op[:], buf.Next(36)) 614 ds.Outpoint = *OutPointFromBytes(op) 615 616 // deserialize DeltaSig 617 ds.Delta = BtI32(buf.Next(4)) 618 copy(ds.Signature[:], buf.Next(64)) 619 copy(ds.Data[:], buf.Next(32)) 620 621 nHTLCs := buf.Len() / 64 622 for i := 0; i < nHTLCs; i++ { 623 var HTLCSig [64]byte 624 copy(HTLCSig[:], buf.Next(64)) 625 ds.HTLCSigs = append(ds.HTLCSigs, HTLCSig) 626 } 627 628 return *ds, nil 629 } 630 631 func (self DeltaSigMsg) Bytes() []byte { 632 var msg []byte 633 msg = append(msg, self.MsgType()) 634 opArr := OutPointToBytes(self.Outpoint) 635 msg = append(msg, opArr[:]...) 636 msg = append(msg, I32tB(self.Delta)...) 637 msg = append(msg, self.Signature[:]...) 638 msg = append(msg, self.Data[:]...) 639 for _, sig := range self.HTLCSigs { 640 msg = append(msg, sig[:]...) 641 } 642 return msg 643 } 644 645 func (self DeltaSigMsg) Peer() uint32 { return self.PeerIdx } 646 func (self DeltaSigMsg) MsgType() uint8 { return MSGID_DELTASIG } 647 648 //a message that pushes using channel information 649 type SigRevMsg struct { 650 PeerIdx uint32 651 Outpoint wire.OutPoint 652 Signature [64]byte 653 Elk chainhash.Hash 654 N2ElkPoint [33]byte 655 HTLCSigs [][64]byte 656 N2HTLCBase [33]byte 657 } 658 659 func NewSigRev(peerid uint32, OP wire.OutPoint, SIG [64]byte, ELK chainhash.Hash, 660 N2ELK [33]byte, HTLCSigs [][64]byte, N2HTLCBase [33]byte) SigRevMsg { 661 s := new(SigRevMsg) 662 s.PeerIdx = peerid 663 s.Outpoint = OP 664 s.Signature = SIG 665 s.Elk = ELK 666 s.N2ElkPoint = N2ELK 667 s.HTLCSigs = HTLCSigs 668 s.N2HTLCBase = N2HTLCBase 669 return *s 670 } 671 672 func NewSigRevFromBytes(b []byte, peerid uint32) (SigRevMsg, error) { 673 sr := new(SigRevMsg) 674 sr.PeerIdx = peerid 675 676 if len(b) < 166 { 677 return *sr, fmt.Errorf("got %d byte SIGREV, expect 166", len(b)) 678 } 679 680 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 681 682 var op [36]byte 683 copy(op[:], buf.Next(36)) 684 sr.Outpoint = *OutPointFromBytes(op) 685 copy(sr.Signature[:], buf.Next(64)) 686 elk, _ := chainhash.NewHash(buf.Next(32)) 687 sr.Elk = *elk 688 copy(sr.N2ElkPoint[:], buf.Next(33)) 689 690 nHTLCs := (buf.Len() - 33) / 64 691 for i := 0; i < nHTLCs; i++ { 692 var HTLCSig [64]byte 693 copy(HTLCSig[:], buf.Next(64)) 694 sr.HTLCSigs = append(sr.HTLCSigs, HTLCSig) 695 } 696 697 copy(sr.N2HTLCBase[:], buf.Next(33)) 698 699 return *sr, nil 700 } 701 702 func (self SigRevMsg) Bytes() []byte { 703 var msg []byte 704 msg = append(msg, self.MsgType()) 705 opArr := OutPointToBytes(self.Outpoint) 706 msg = append(msg, opArr[:]...) 707 msg = append(msg, self.Signature[:]...) 708 msg = append(msg, self.Elk[:]...) 709 msg = append(msg, self.N2ElkPoint[:]...) 710 for _, sig := range self.HTLCSigs { 711 msg = append(msg, sig[:]...) 712 } 713 msg = append(msg, self.N2HTLCBase[:]...) 714 return msg 715 } 716 717 func (self SigRevMsg) Peer() uint32 { return self.PeerIdx } 718 func (self SigRevMsg) MsgType() uint8 { return MSGID_SIGREV } 719 720 //message for signaling state has moved, revoking old state 721 type GapSigRevMsg struct { 722 PeerIdx uint32 723 Outpoint wire.OutPoint 724 Signature [64]byte 725 Elk chainhash.Hash 726 N2ElkPoint [33]byte 727 N2HTLCBase [33]byte 728 HTLCSigs [][64]byte 729 } 730 731 func NewGapSigRev(peerid uint32, OP wire.OutPoint, SIG [64]byte, ELK chainhash.Hash, N2ELK [33]byte, HTLCSigs [][64]byte, N2HTLCBase [33]byte) GapSigRevMsg { 732 g := new(GapSigRevMsg) 733 g.PeerIdx = peerid 734 g.Outpoint = OP 735 g.Signature = SIG 736 g.Elk = ELK 737 g.N2ElkPoint = N2ELK 738 g.N2HTLCBase = N2HTLCBase 739 g.HTLCSigs = HTLCSigs 740 return *g 741 } 742 743 func NewGapSigRevFromBytes(b []byte, peerId uint32) (GapSigRevMsg, error) { 744 gs := new(GapSigRevMsg) 745 gs.PeerIdx = peerId 746 747 if len(b) < 166 { 748 return *gs, fmt.Errorf("got %d byte GAPSIGREV, expect 166", len(b)) 749 } 750 751 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 752 753 var op [36]byte 754 copy(op[:], buf.Next(36)) 755 gs.Outpoint = *OutPointFromBytes(op) 756 copy(gs.Signature[:], buf.Next(64)) 757 elk, _ := chainhash.NewHash(buf.Next(32)) 758 gs.Elk = *elk 759 copy(gs.N2ElkPoint[:], buf.Next(33)) 760 copy(gs.N2HTLCBase[:], buf.Next(33)) 761 762 nHTLCs := buf.Len() / 64 763 for i := 0; i < nHTLCs; i++ { 764 var HTLCSig [64]byte 765 copy(HTLCSig[:], buf.Next(64)) 766 gs.HTLCSigs = append(gs.HTLCSigs, HTLCSig) 767 } 768 769 return *gs, nil 770 } 771 772 func (self GapSigRevMsg) Bytes() []byte { 773 var msg []byte 774 msg = append(msg, self.MsgType()) 775 opArr := OutPointToBytes(self.Outpoint) 776 msg = append(msg, opArr[:]...) 777 msg = append(msg, self.Signature[:]...) 778 msg = append(msg, self.Elk[:]...) 779 msg = append(msg, self.N2ElkPoint[:]...) 780 msg = append(msg, self.N2HTLCBase[:]...) 781 for _, sig := range self.HTLCSigs { 782 msg = append(msg, sig[:]...) 783 } 784 return msg 785 } 786 787 func (self GapSigRevMsg) Peer() uint32 { return self.PeerIdx } 788 func (self GapSigRevMsg) MsgType() uint8 { return MSGID_GAPSIGREV } 789 790 //send message across channel using Elk info 791 type RevMsg struct { 792 PeerIdx uint32 793 Outpoint wire.OutPoint 794 Elk chainhash.Hash 795 N2ElkPoint [33]byte 796 N2HTLCBase [33]byte 797 } 798 799 func NewRevMsg(peerid uint32, OP wire.OutPoint, ELK chainhash.Hash, N2ELK [33]byte, N2HTLCBase [33]byte) RevMsg { 800 r := new(RevMsg) 801 r.PeerIdx = peerid 802 r.Outpoint = OP 803 r.Elk = ELK 804 r.N2ElkPoint = N2ELK 805 r.N2HTLCBase = N2HTLCBase 806 return *r 807 } 808 809 func NewRevMsgFromBytes(b []byte, peerId uint32) (RevMsg, error) { 810 rv := new(RevMsg) 811 rv.PeerIdx = peerId 812 813 if len(b) < 102 { 814 return *rv, fmt.Errorf("got %d byte REV, expect 102", len(b)) 815 } 816 817 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 818 819 var op [36]byte 820 copy(op[:], buf.Next(36)) 821 rv.Outpoint = *OutPointFromBytes(op) 822 elk, _ := chainhash.NewHash(buf.Next(32)) 823 rv.Elk = *elk 824 copy(rv.N2ElkPoint[:], buf.Next(33)) 825 copy(rv.N2HTLCBase[:], buf.Next(33)) 826 return *rv, nil 827 } 828 829 func (self RevMsg) Bytes() []byte { 830 var msg []byte 831 msg = append(msg, self.MsgType()) 832 opArr := OutPointToBytes(self.Outpoint) 833 msg = append(msg, opArr[:]...) 834 msg = append(msg, self.Elk[:]...) 835 msg = append(msg, self.N2ElkPoint[:]...) 836 msg = append(msg, self.N2HTLCBase[:]...) 837 return msg 838 } 839 840 func (self RevMsg) Peer() uint32 { return self.PeerIdx } 841 func (self RevMsg) MsgType() uint8 { return MSGID_REV } 842 843 //---------- 844 845 //message for offering an HTLC 846 type HashSigMsg struct { 847 PeerIdx uint32 848 Outpoint wire.OutPoint 849 850 Amt int64 851 Locktime uint32 852 RHash [32]byte 853 854 Data [32]byte 855 856 CommitmentSignature [64]byte 857 // must be at least 36 + 4 + 32 + 33 + 32 + 64 = 169 bytes 858 HTLCSigs [][64]byte 859 } 860 861 func NewHashSigMsg(peerid uint32, OP wire.OutPoint, amt int64, locktime uint32, RHash [32]byte, sig [64]byte, HTLCSigs [][64]byte, data [32]byte) HashSigMsg { 862 d := new(HashSigMsg) 863 d.PeerIdx = peerid 864 d.Outpoint = OP 865 d.Amt = amt 866 d.CommitmentSignature = sig 867 d.Data = data 868 d.RHash = RHash 869 d.Locktime = locktime 870 d.HTLCSigs = HTLCSigs 871 return *d 872 } 873 874 func NewHashSigMsgFromBytes(b []byte, peerid uint32) (HashSigMsg, error) { 875 ds := new(HashSigMsg) 876 ds.PeerIdx = peerid 877 878 if len(b) < 169 { 879 return *ds, fmt.Errorf("got %d byte HashSig, expect at least 169 bytes", len(b)) 880 } 881 882 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 883 884 var op [36]byte 885 copy(op[:], buf.Next(36)) 886 ds.Outpoint = *OutPointFromBytes(op) 887 888 // deserialize DeltaSig 889 ds.Amt = BtI64(buf.Next(8)) 890 ds.Locktime = BtU32(buf.Next(4)) 891 copy(ds.RHash[:], buf.Next(32)) 892 893 copy(ds.Data[:], buf.Next(32)) 894 895 copy(ds.CommitmentSignature[:], buf.Next(64)) 896 897 nHTLCSigs := buf.Len() / 64 898 899 for i := 0; i < nHTLCSigs; i++ { 900 var sig [64]byte 901 copy(sig[:], buf.Next(64)) 902 ds.HTLCSigs = append(ds.HTLCSigs, sig) 903 } 904 905 return *ds, nil 906 } 907 908 func (self HashSigMsg) Bytes() []byte { 909 var msg []byte 910 msg = append(msg, self.MsgType()) 911 opArr := OutPointToBytes(self.Outpoint) 912 msg = append(msg, opArr[:]...) 913 msg = append(msg, I64tB(self.Amt)...) 914 msg = append(msg, U32tB(self.Locktime)...) 915 msg = append(msg, self.RHash[:]...) 916 msg = append(msg, self.Data[:]...) 917 msg = append(msg, self.CommitmentSignature[:]...) 918 for _, sig := range self.HTLCSigs { 919 msg = append(msg, sig[:]...) 920 } 921 return msg 922 } 923 924 func (self HashSigMsg) Peer() uint32 { return self.PeerIdx } 925 func (self HashSigMsg) MsgType() uint8 { return MSGID_HASHSIG } 926 927 //---------- 928 929 //message for clearing an HTLC 930 type PreimageSigMsg struct { 931 PeerIdx uint32 932 Outpoint wire.OutPoint 933 934 Idx uint32 935 R [16]byte 936 937 Data [32]byte 938 939 CommitmentSignature [64]byte 940 // must be at least 36 + 4 + 16 + 32 + 64 = 152 bytes 941 HTLCSigs [][64]byte 942 } 943 944 func NewPreimageSigMsg(peerid uint32, OP wire.OutPoint, Idx uint32, R [16]byte, sig [64]byte, HTLCSigs [][64]byte, data [32]byte) PreimageSigMsg { 945 d := new(PreimageSigMsg) 946 d.PeerIdx = peerid 947 d.Outpoint = OP 948 d.CommitmentSignature = sig 949 d.Data = data 950 d.R = R 951 d.Idx = Idx 952 d.HTLCSigs = HTLCSigs 953 return *d 954 } 955 956 func NewPreimageSigMsgFromBytes(b []byte, peerid uint32) (PreimageSigMsg, error) { 957 ps := new(PreimageSigMsg) 958 ps.PeerIdx = peerid 959 960 if len(b) < 152 { 961 return *ps, fmt.Errorf("got %d byte PreimageSig, expect at least 152 bytes", len(b)) 962 } 963 964 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 965 966 var op [36]byte 967 copy(op[:], buf.Next(36)) 968 ps.Outpoint = *OutPointFromBytes(op) 969 970 ps.Idx = BtU32(buf.Next(4)) 971 972 copy(ps.R[:], buf.Next(16)) 973 974 copy(ps.Data[:], buf.Next(32)) 975 976 copy(ps.CommitmentSignature[:], buf.Next(64)) 977 978 nHTLCSigs := buf.Len() / 64 979 980 for i := 0; i < nHTLCSigs; i++ { 981 var sig [64]byte 982 copy(sig[:], buf.Next(64)) 983 ps.HTLCSigs = append(ps.HTLCSigs, sig) 984 } 985 986 return *ps, nil 987 } 988 989 func (self PreimageSigMsg) Bytes() []byte { 990 var msg []byte 991 msg = append(msg, self.MsgType()) 992 opArr := OutPointToBytes(self.Outpoint) 993 msg = append(msg, opArr[:]...) 994 msg = append(msg, U32tB(self.Idx)...) 995 msg = append(msg, self.R[:]...) 996 msg = append(msg, self.Data[:]...) 997 msg = append(msg, self.CommitmentSignature[:]...) 998 for _, sig := range self.HTLCSigs { 999 msg = append(msg, sig[:]...) 1000 } 1001 return msg 1002 } 1003 1004 func (self PreimageSigMsg) Peer() uint32 { return self.PeerIdx } 1005 func (self PreimageSigMsg) MsgType() uint8 { return MSGID_PREIMAGESIG } 1006 1007 //---------- 1008 1009 // 2 structs that the watchtower gets from clients: Descriptors and Msgs 1010 1011 // Descriptors are 128 bytes 1012 // PKH 20 1013 // Delay 2 1014 // Fee 8 1015 // HAKDbase 33 1016 // Timebase 33 1017 // Elk0 32 1018 1019 // WatchannelDescriptor is the initial message setting up a Watchannel 1020 type WatchDescMsg struct { 1021 PeerIdx uint32 1022 CoinType uint32 // what network this channel is on 1023 DestPKHScript [20]byte // PKH to grab to; main unique identifier. 1024 1025 Delay uint16 // timeout in blocks 1026 Fee int64 // fee to use for grab tx. Or fee rate...? 1027 1028 CustomerBasePoint [33]byte // client's HAKD key base point 1029 AdversaryBasePoint [33]byte // potential attacker's timeout basepoint 1030 } 1031 1032 // NewWatchDescMsg turns 96 bytes into a WatchannelDescriptor 1033 // Silently fails with incorrect size input, watch out. 1034 func NewWatchDescMsg( 1035 peeridx, coinType uint32, destScript [20]byte, 1036 delay uint16, fee int64, customerBase [33]byte, 1037 adversaryBase [33]byte) WatchDescMsg { 1038 1039 wd := new(WatchDescMsg) 1040 wd.PeerIdx = peeridx 1041 wd.CoinType = coinType 1042 wd.DestPKHScript = destScript 1043 wd.Delay = delay 1044 wd.Fee = fee 1045 wd.CustomerBasePoint = customerBase 1046 wd.AdversaryBasePoint = adversaryBase 1047 return *wd 1048 } 1049 1050 func NewWatchDescMsgFromBytes(b []byte, peerIDX uint32) (WatchDescMsg, error) { 1051 sd := new(WatchDescMsg) 1052 sd.PeerIdx = peerIDX 1053 1054 if len(b) < 97 { 1055 return *sd, fmt.Errorf("WatchannelDescriptor %d bytes, expect 97", len(b)) 1056 } 1057 1058 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1059 1060 _ = binary.Read(buf, binary.BigEndian, &sd.CoinType) 1061 1062 copy(sd.DestPKHScript[:], buf.Next(20)) 1063 _ = binary.Read(buf, binary.BigEndian, &sd.Delay) 1064 1065 _ = binary.Read(buf, binary.BigEndian, &sd.Fee) 1066 1067 copy(sd.CustomerBasePoint[:], buf.Next(33)) 1068 copy(sd.AdversaryBasePoint[:], buf.Next(33)) 1069 1070 return *sd, nil 1071 } 1072 1073 // Bytes turns a WatchannelDescriptor into 100 bytes 1074 func (self WatchDescMsg) Bytes() []byte { 1075 var buf bytes.Buffer 1076 buf.WriteByte(self.MsgType()) 1077 binary.Write(&buf, binary.BigEndian, self.CoinType) 1078 buf.Write(self.DestPKHScript[:]) 1079 binary.Write(&buf, binary.BigEndian, self.Delay) 1080 binary.Write(&buf, binary.BigEndian, self.Fee) 1081 buf.Write(self.CustomerBasePoint[:]) 1082 buf.Write(self.AdversaryBasePoint[:]) 1083 return buf.Bytes() 1084 } 1085 1086 func (self WatchDescMsg) Peer() uint32 { return self.PeerIdx } 1087 func (self WatchDescMsg) MsgType() uint8 { return MSGID_WATCH_DESC } 1088 1089 // the message describing the next commitment tx, sent from the client to the watchtower 1090 1091 // ComMsg are 137 bytes. 1092 // msgtype 1093 // CoinType 4 1094 // PKH 20 1095 // txid 16 1096 // sig 64 1097 // elk 32 1098 type WatchStateMsg struct { 1099 PeerIdx uint32 1100 CoinType uint32 // could figure it out from PKH but this is easier 1101 DestPKH [20]byte // identifier for channel; could be optimized away 1102 Elk chainhash.Hash // elkrem for this state index 1103 ParTxid [16]byte // 16 bytes of txid 1104 Sig [64]byte // 64 bytes of sig 1105 } 1106 1107 func NewComMsg(peerIdx, cointype uint32, destPKH [20]byte, 1108 elk chainhash.Hash, parTxid [16]byte, sig [64]byte) WatchStateMsg { 1109 cm := new(WatchStateMsg) 1110 cm.PeerIdx = peerIdx 1111 cm.CoinType = cointype 1112 cm.DestPKH = destPKH 1113 cm.Elk = elk 1114 cm.ParTxid = parTxid 1115 cm.Sig = sig 1116 return *cm 1117 } 1118 1119 // ComMsgFromBytes turns 132 bytes into a SourceMsg 1120 // Silently fails with wrong size input. 1121 func NewWatchStateMsgFromBytes(b []byte, peerIDX uint32) (WatchStateMsg, error) { 1122 sm := new(WatchStateMsg) 1123 sm.PeerIdx = peerIDX 1124 1125 if len(b) < 137 { 1126 return *sm, fmt.Errorf("WatchComMsg %d bytes, expect 137", len(b)) 1127 } 1128 1129 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1130 _ = binary.Read(buf, binary.BigEndian, &sm.CoinType) 1131 copy(sm.DestPKH[:], buf.Next(20)) 1132 copy(sm.ParTxid[:], buf.Next(16)) 1133 copy(sm.Sig[:], buf.Next(64)) 1134 copy(sm.Elk[:], buf.Next(32)) 1135 1136 return *sm, nil 1137 } 1138 1139 // ToBytes turns a ComMsg into 132 bytes 1140 func (self WatchStateMsg) Bytes() []byte { 1141 var buf bytes.Buffer 1142 buf.WriteByte(self.MsgType()) 1143 binary.Write(&buf, binary.BigEndian, self.CoinType) 1144 buf.Write(self.DestPKH[:]) 1145 buf.Write(self.ParTxid[:]) 1146 buf.Write(self.Sig[:]) 1147 buf.Write(self.Elk.CloneBytes()) 1148 return buf.Bytes() 1149 } 1150 1151 func (self WatchStateMsg) Peer() uint32 { return self.PeerIdx } 1152 func (self WatchStateMsg) MsgType() uint8 { return MSGID_WATCH_STATEMSG } 1153 1154 //---------- 1155 1156 type WatchDelMsg struct { 1157 PeerIdx uint32 1158 DestPKH [20]byte // identifier for channel; could be optimized away 1159 RevealPK [33]byte // reveal this pubkey, matches DestPKH 1160 // Don't actually have to send DestPKH huh. Send anyway. 1161 } 1162 1163 // Bytes turns a ComMsg into 132 bytes 1164 func (self WatchDelMsg) Bytes() []byte { 1165 var buf bytes.Buffer 1166 buf.WriteByte(self.MsgType()) 1167 buf.Write(self.DestPKH[:]) 1168 buf.Write(self.RevealPK[:]) 1169 return buf.Bytes() 1170 } 1171 1172 // ComMsgFromBytes turns 132 bytes into a SourceMsg 1173 // Silently fails with wrong size input. 1174 func NewWatchDelMsgFromBytes(b []byte, peerIDX uint32) (WatchDelMsg, error) { 1175 sm := new(WatchDelMsg) 1176 sm.PeerIdx = peerIDX 1177 1178 if len(b) < 54 { 1179 return *sm, fmt.Errorf("WatchDelMsg %d bytes, expect 54", len(b)) 1180 } 1181 1182 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1183 1184 copy(sm.DestPKH[:], buf.Next(20)) 1185 copy(sm.RevealPK[:], buf.Next(33)) 1186 1187 return *sm, nil 1188 } 1189 func (self WatchDelMsg) Peer() uint32 { return self.PeerIdx } 1190 func (self WatchDelMsg) MsgType() uint8 { return MSGID_WATCH_DELETE } 1191 1192 // Link message 1193 1194 // To find how much 1 satoshi of coin type A will cost you in coin type B, 1195 // if Reciprocal is false, 1 satoshi of A will buy you `rate` satoshis of B. 1196 // Otherwise, 1 satoshi of B will buy you `rate` satoshis of A. This avoids the 1197 // use of floating point for deciding price. 1198 type RateDesc struct { 1199 CoinType uint32 1200 Rate int64 1201 Reciprocal bool 1202 } 1203 1204 func NewRateDescFromBytes(b []byte) (RateDesc, error) { 1205 var rd RateDesc 1206 1207 buf := bytes.NewBuffer(b) 1208 1209 err := binary.Read(buf, binary.BigEndian, &rd.CoinType) 1210 if err != nil { 1211 return rd, err 1212 } 1213 1214 err = binary.Read(buf, binary.BigEndian, &rd.Rate) 1215 if err != nil { 1216 return rd, err 1217 } 1218 1219 err = binary.Read(buf, binary.BigEndian, &rd.Reciprocal) 1220 if err != nil { 1221 return rd, err 1222 } 1223 1224 return rd, nil 1225 } 1226 1227 func (rd *RateDesc) Bytes() []byte { 1228 var buf bytes.Buffer 1229 1230 binary.Write(&buf, binary.BigEndian, rd.CoinType) 1231 binary.Write(&buf, binary.BigEndian, rd.Rate) 1232 binary.Write(&buf, binary.BigEndian, rd.Reciprocal) 1233 1234 return buf.Bytes() 1235 } 1236 1237 type LinkMsg struct { 1238 PeerIdx uint32 1239 APKH [20]byte // APKH (A's LN address) 1240 ACapacity int64 // ACapacity (A's channel balance) 1241 BPKH [20]byte // BPKH (B's LN address) 1242 CoinType uint32 // CoinType (Network of the channel) 1243 Seq uint32 // seq (Link state sequence #) 1244 Timestamp int64 1245 Rates []RateDesc 1246 } 1247 1248 func NewLinkMsgFromBytes(b []byte, peerIDX uint32) (LinkMsg, error) { 1249 sm := new(LinkMsg) 1250 sm.PeerIdx = peerIDX 1251 1252 if len(b) < 61 { 1253 return *sm, fmt.Errorf("LinkMsg %d bytes, expect at least 61", len(b)) 1254 } 1255 1256 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1257 1258 copy(sm.APKH[:], buf.Next(20)) 1259 err := binary.Read(buf, binary.BigEndian, &sm.ACapacity) 1260 if err != nil { 1261 return *sm, err 1262 } 1263 copy(sm.BPKH[:], buf.Next(20)) 1264 err = binary.Read(buf, binary.BigEndian, &sm.CoinType) 1265 if err != nil { 1266 return *sm, err 1267 } 1268 err = binary.Read(buf, binary.BigEndian, &sm.Seq) 1269 if err != nil { 1270 return *sm, err 1271 } 1272 1273 var nRates uint32 1274 err = binary.Read(buf, binary.BigEndian, &nRates) 1275 if err != nil { 1276 return *sm, err 1277 } 1278 1279 for i := uint32(0); i < nRates; i++ { 1280 rd, err := NewRateDescFromBytes(buf.Next(13)) 1281 if err != nil { 1282 return *sm, err 1283 } 1284 1285 sm.Rates = append(sm.Rates, rd) 1286 } 1287 1288 return *sm, nil 1289 } 1290 1291 // ToBytes turns a LinkMsg into 88 bytes 1292 func (self LinkMsg) Bytes() []byte { 1293 var buf bytes.Buffer 1294 1295 buf.WriteByte(self.MsgType()) 1296 1297 buf.Write(self.APKH[:]) 1298 binary.Write(&buf, binary.BigEndian, self.ACapacity) 1299 1300 buf.Write(self.BPKH[:]) 1301 1302 binary.Write(&buf, binary.BigEndian, self.CoinType) 1303 binary.Write(&buf, binary.BigEndian, self.Seq) 1304 1305 nRates := uint32(len(self.Rates)) 1306 binary.Write(&buf, binary.BigEndian, nRates) 1307 1308 for _, rate := range self.Rates { 1309 buf.Write(rate.Bytes()) 1310 } 1311 1312 return buf.Bytes() 1313 } 1314 1315 func (self LinkMsg) Peer() uint32 { return self.PeerIdx } 1316 func (self LinkMsg) MsgType() uint8 { return MSGID_LINK_DESC } 1317 1318 // Dual funding messages 1319 1320 type DualFundingReqMsg struct { 1321 PeerIdx uint32 1322 CoinType uint32 // Cointype we are funding 1323 OurAmount int64 // The amount we are funding 1324 TheirAmount int64 // The amount we are requesting the counterparty to fund 1325 OurPub [33]byte 1326 OurRefundPub [33]byte 1327 OurHAKDBase [33]byte 1328 OurChangeAddressPKH [20]byte // The address we want to receive change for funding 1329 OurInputs []DualFundingInput // The inputs we will use for funding 1330 } 1331 1332 type DualFundingInput struct { 1333 Outpoint wire.OutPoint 1334 Value int64 1335 } 1336 1337 func NewDualFundingReqMsg(peerIdx, cointype uint32, ourAmount int64, theirAmount int64, ourPub [33]byte, ourRefundPub [33]byte, ourHAKDBase [33]byte, ourChangeAddressPKH [20]byte, ourInputs []DualFundingInput) DualFundingReqMsg { 1338 msg := new(DualFundingReqMsg) 1339 msg.PeerIdx = peerIdx 1340 msg.CoinType = cointype 1341 msg.OurAmount = ourAmount 1342 msg.TheirAmount = theirAmount 1343 msg.OurPub = ourPub 1344 msg.OurRefundPub = ourRefundPub 1345 msg.OurHAKDBase = ourHAKDBase 1346 msg.OurChangeAddressPKH = ourChangeAddressPKH 1347 msg.OurInputs = ourInputs 1348 1349 return *msg 1350 } 1351 1352 func NewDualFundingReqMsgFromBytes(b []byte, peerIdx uint32) (DualFundingReqMsg, error) { 1353 msg := new(DualFundingReqMsg) 1354 msg.PeerIdx = peerIdx 1355 1356 if len(b) < 144 { 1357 return *msg, fmt.Errorf("DualFundingReqMsg %d bytes, expect at least 144", len(b)) 1358 } 1359 1360 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1361 _ = binary.Read(buf, binary.BigEndian, &msg.CoinType) 1362 _ = binary.Read(buf, binary.BigEndian, &msg.OurAmount) 1363 _ = binary.Read(buf, binary.BigEndian, &msg.TheirAmount) 1364 copy(msg.OurPub[:], buf.Next(33)) 1365 copy(msg.OurRefundPub[:], buf.Next(33)) 1366 copy(msg.OurHAKDBase[:], buf.Next(33)) 1367 copy(msg.OurChangeAddressPKH[:], buf.Next(20)) 1368 1369 var utxoCount uint32 1370 _ = binary.Read(buf, binary.BigEndian, &utxoCount) 1371 expectedLength := uint32(144) + 44*utxoCount 1372 1373 if uint32(len(b)) < expectedLength { 1374 return *msg, fmt.Errorf("DualFundingReqMsg %d bytes, expect at least %d for %d txos", len(b), expectedLength, utxoCount) 1375 } 1376 1377 msg.OurInputs = make([]DualFundingInput, utxoCount) 1378 var op [36]byte 1379 for i := uint32(0); i < utxoCount; i++ { 1380 copy(op[:], buf.Next(36)) 1381 msg.OurInputs[i].Outpoint = *OutPointFromBytes(op) 1382 _ = binary.Read(buf, binary.BigEndian, &msg.OurInputs[i].Value) 1383 } 1384 1385 return *msg, nil 1386 } 1387 1388 // ToBytes turns a DualFundingReqMsg into bytes 1389 func (self DualFundingReqMsg) Bytes() []byte { 1390 var buf bytes.Buffer 1391 1392 buf.WriteByte(self.MsgType()) 1393 1394 binary.Write(&buf, binary.BigEndian, self.CoinType) 1395 binary.Write(&buf, binary.BigEndian, self.OurAmount) 1396 binary.Write(&buf, binary.BigEndian, self.TheirAmount) 1397 buf.Write(self.OurPub[:]) 1398 buf.Write(self.OurRefundPub[:]) 1399 buf.Write(self.OurHAKDBase[:]) 1400 buf.Write(self.OurChangeAddressPKH[:]) 1401 1402 binary.Write(&buf, binary.BigEndian, uint32(len(self.OurInputs))) 1403 1404 for i := 0; i < len(self.OurInputs); i++ { 1405 opArr := OutPointToBytes(self.OurInputs[i].Outpoint) 1406 buf.Write(opArr[:]) 1407 binary.Write(&buf, binary.BigEndian, self.OurInputs[i].Value) 1408 } 1409 1410 return buf.Bytes() 1411 } 1412 1413 func (self DualFundingReqMsg) Peer() uint32 { return self.PeerIdx } 1414 func (self DualFundingReqMsg) MsgType() uint8 { return MSGID_DUALFUNDINGREQ } 1415 1416 type DualFundingDeclMsg struct { 1417 PeerIdx uint32 1418 Reason uint8 // Reason for declining the funding request 1419 } 1420 1421 func NewDualFundingDeclMsg(peerIdx uint32, reason uint8) DualFundingDeclMsg { 1422 msg := new(DualFundingDeclMsg) 1423 msg.PeerIdx = peerIdx 1424 msg.Reason = reason 1425 return *msg 1426 } 1427 1428 func NewDualFundingDeclMsgFromBytes(b []byte, peerIdx uint32) (DualFundingDeclMsg, error) { 1429 msg := new(DualFundingDeclMsg) 1430 msg.PeerIdx = peerIdx 1431 1432 if len(b) < 2 { 1433 return *msg, fmt.Errorf("DualFundingDeclMsg %d bytes, expect at least 2", len(b)) 1434 } 1435 1436 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1437 1438 _ = binary.Read(buf, binary.BigEndian, &msg.Reason) 1439 return *msg, nil 1440 } 1441 1442 // ToBytes turns a DualFundingReqMsg into bytes 1443 func (self DualFundingDeclMsg) Bytes() []byte { 1444 var buf bytes.Buffer 1445 1446 buf.WriteByte(self.MsgType()) 1447 1448 binary.Write(&buf, binary.BigEndian, self.Reason) 1449 return buf.Bytes() 1450 } 1451 1452 func (self DualFundingDeclMsg) Peer() uint32 { return self.PeerIdx } 1453 func (self DualFundingDeclMsg) MsgType() uint8 { return MSGID_DUALFUNDINGDECL } 1454 1455 type DualFundingAcceptMsg struct { 1456 PeerIdx uint32 1457 CoinType uint32 // Cointype we are funding 1458 OurPub [33]byte 1459 OurRefundPub [33]byte 1460 OurHAKDBase [33]byte 1461 OurChangeAddressPKH [20]byte // The address we want to receive change for funding 1462 OurNextHTLCBase [33]byte 1463 OurN2HTLCBase [33]byte 1464 OurInputs []DualFundingInput // The inputs we will use for funding 1465 } 1466 1467 func NewDualFundingAcceptMsg(peerIdx uint32, coinType uint32, ourPub [33]byte, ourRefundPub [33]byte, ourHAKDBase [33]byte, ourChangeAddress [20]byte, ourInputs []DualFundingInput, ourNextHTLCBase [33]byte, ourN2HTLCBase [33]byte) DualFundingAcceptMsg { 1468 msg := new(DualFundingAcceptMsg) 1469 msg.PeerIdx = peerIdx 1470 msg.CoinType = coinType 1471 msg.OurPub = ourPub 1472 msg.OurRefundPub = ourRefundPub 1473 msg.OurHAKDBase = ourHAKDBase 1474 msg.OurChangeAddressPKH = ourChangeAddress 1475 msg.OurInputs = ourInputs 1476 msg.OurNextHTLCBase = ourNextHTLCBase 1477 msg.OurN2HTLCBase = ourN2HTLCBase 1478 return *msg 1479 } 1480 1481 func NewDualFundingAcceptMsgFromBytes(b []byte, peerIdx uint32) (DualFundingAcceptMsg, error) { 1482 msg := new(DualFundingAcceptMsg) 1483 msg.PeerIdx = peerIdx 1484 1485 if len(b) < 29 { 1486 return *msg, fmt.Errorf("DualFundingAcceptMsg %d bytes, expect at least 29", len(b)) 1487 } 1488 1489 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1490 1491 _ = binary.Read(buf, binary.BigEndian, &msg.CoinType) 1492 copy(msg.OurPub[:], buf.Next(33)) 1493 copy(msg.OurRefundPub[:], buf.Next(33)) 1494 copy(msg.OurHAKDBase[:], buf.Next(33)) 1495 copy(msg.OurChangeAddressPKH[:], buf.Next(20)) 1496 copy(msg.OurNextHTLCBase[:], buf.Next(33)) 1497 copy(msg.OurN2HTLCBase[:], buf.Next(33)) 1498 1499 var utxoCount uint32 1500 _ = binary.Read(buf, binary.BigEndian, &utxoCount) 1501 expectedLength := uint32(29) + 44*utxoCount 1502 1503 if uint32(len(b)) < expectedLength { 1504 return *msg, fmt.Errorf("DualFundingReqMsg %d bytes, expect at least %d for %d txos", len(b), expectedLength, utxoCount) 1505 } 1506 1507 msg.OurInputs = make([]DualFundingInput, utxoCount) 1508 var op [36]byte 1509 for i := uint32(0); i < utxoCount; i++ { 1510 copy(op[:], buf.Next(36)) 1511 msg.OurInputs[i].Outpoint = *OutPointFromBytes(op) 1512 _ = binary.Read(buf, binary.BigEndian, &msg.OurInputs[i].Value) 1513 } 1514 return *msg, nil 1515 } 1516 1517 // ToBytes turns a DualFundingReqMsg into bytes 1518 func (self DualFundingAcceptMsg) Bytes() []byte { 1519 var buf bytes.Buffer 1520 1521 buf.WriteByte(self.MsgType()) 1522 binary.Write(&buf, binary.BigEndian, self.CoinType) 1523 buf.Write(self.OurPub[:]) 1524 buf.Write(self.OurRefundPub[:]) 1525 buf.Write(self.OurHAKDBase[:]) 1526 buf.Write(self.OurChangeAddressPKH[:]) 1527 buf.Write(self.OurNextHTLCBase[:]) 1528 buf.Write(self.OurN2HTLCBase[:]) 1529 1530 binary.Write(&buf, binary.BigEndian, uint32(len(self.OurInputs))) 1531 1532 for i := 0; i < len(self.OurInputs); i++ { 1533 opArr := OutPointToBytes(self.OurInputs[i].Outpoint) 1534 buf.Write(opArr[:]) 1535 binary.Write(&buf, binary.BigEndian, self.OurInputs[i].Value) 1536 } 1537 1538 return buf.Bytes() 1539 } 1540 1541 func (self DualFundingAcceptMsg) Peer() uint32 { return self.PeerIdx } 1542 func (self DualFundingAcceptMsg) MsgType() uint8 { return MSGID_DUALFUNDINGACCEPT } 1543 1544 //message for channel acknowledgement and funding signatures 1545 type DualFundingChanAckMsg struct { 1546 PeerIdx uint32 1547 Outpoint wire.OutPoint 1548 ElkZero [33]byte 1549 ElkOne [33]byte 1550 ElkTwo [33]byte 1551 Signature [64]byte 1552 SignedFundingTx *wire.MsgTx 1553 } 1554 1555 func NewDualFundingChanAckMsg(peerid uint32, OP wire.OutPoint, ELKZero [33]byte, ELKOne [33]byte, ELKTwo [33]byte, SIG [64]byte, signedFundingTx *wire.MsgTx) DualFundingChanAckMsg { 1556 ca := new(DualFundingChanAckMsg) 1557 ca.PeerIdx = peerid 1558 ca.Outpoint = OP 1559 ca.ElkZero = ELKZero 1560 ca.ElkOne = ELKOne 1561 ca.ElkTwo = ELKTwo 1562 ca.Signature = SIG 1563 ca.SignedFundingTx = signedFundingTx 1564 return *ca 1565 } 1566 1567 func NewDualFundingChanAckMsgFromBytes(b []byte, peerid uint32) (DualFundingChanAckMsg, error) { 1568 cm := new(DualFundingChanAckMsg) 1569 cm.PeerIdx = peerid 1570 1571 if len(b) < 208 { 1572 return *cm, fmt.Errorf("got %d byte DualFundingChanAck, expect 212 or more", len(b)) 1573 } 1574 1575 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1576 1577 var op [36]byte 1578 copy(op[:], buf.Next(36)) 1579 cm.Outpoint = *OutPointFromBytes(op) 1580 copy(cm.ElkZero[:], buf.Next(33)) 1581 copy(cm.ElkOne[:], buf.Next(33)) 1582 copy(cm.ElkTwo[:], buf.Next(33)) 1583 copy(cm.Signature[:], buf.Next(64)) 1584 1585 var txLen uint64 1586 _ = binary.Read(buf, binary.BigEndian, &txLen) 1587 expectedLength := uint64(208) + txLen 1588 1589 if uint64(len(b)) < expectedLength { 1590 return *cm, fmt.Errorf("DualFundingChanAckMsg %d bytes, expect at least %d for %d byte tx", len(b), expectedLength, txLen) 1591 } 1592 1593 cm.SignedFundingTx = wire.NewMsgTx() 1594 cm.SignedFundingTx.Deserialize(buf) 1595 1596 return *cm, nil 1597 } 1598 1599 func (self DualFundingChanAckMsg) Bytes() []byte { 1600 var buf bytes.Buffer 1601 1602 opArr := OutPointToBytes(self.Outpoint) 1603 buf.WriteByte(self.MsgType()) 1604 buf.Write(opArr[:]) 1605 buf.Write(self.ElkZero[:]) 1606 buf.Write(self.ElkOne[:]) 1607 buf.Write(self.ElkTwo[:]) 1608 buf.Write(self.Signature[:]) 1609 1610 binary.Write(&buf, binary.BigEndian, uint64(self.SignedFundingTx.SerializeSize())) 1611 writer := bufio.NewWriter(&buf) 1612 self.SignedFundingTx.Serialize(writer) 1613 writer.Flush() 1614 1615 return buf.Bytes() 1616 } 1617 1618 func (self DualFundingChanAckMsg) Peer() uint32 { return self.PeerIdx } 1619 func (self DualFundingChanAckMsg) MsgType() uint8 { return MSGID_DUALFUNDINGCHANACK } 1620 1621 // DlcOfferMsg is the message we send to a peer to offer that peer a 1622 // particular contract 1623 type DlcOfferMsg struct { 1624 PeerIdx uint32 1625 Contract *DlcContract 1626 } 1627 1628 // NewDlcOfferMsg creates a new DlcOfferMsg based on a peer and contract 1629 func NewDlcOfferMsg(peerIdx uint32, contract *DlcContract) DlcOfferMsg { 1630 msg := new(DlcOfferMsg) 1631 msg.PeerIdx = peerIdx 1632 msg.Contract = contract 1633 return *msg 1634 } 1635 1636 // NewDlcOfferMsgFromBytes parses a byte array back into a DlcOfferMsg 1637 func NewDlcOfferMsgFromBytes(b []byte, peerIDX uint32) (DlcOfferMsg, error) { 1638 var err error 1639 sm := new(DlcOfferMsg) 1640 sm.PeerIdx = peerIDX 1641 sm.Contract, err = DlcContractFromBytes(b[1:]) 1642 if err != nil { 1643 return *sm, err 1644 } 1645 return *sm, nil 1646 } 1647 1648 // Bytes serializes a DlcOfferMsg into a byte array 1649 func (msg DlcOfferMsg) Bytes() []byte { 1650 var buf bytes.Buffer 1651 1652 buf.WriteByte(msg.MsgType()) 1653 buf.Write(msg.Contract.Bytes()) 1654 1655 return buf.Bytes() 1656 } 1657 1658 // Peer returns the peer index this message was received from/sent to 1659 func (msg DlcOfferMsg) Peer() uint32 { return msg.PeerIdx } 1660 1661 // MsgType returns the type of this message 1662 func (msg DlcOfferMsg) MsgType() uint8 { return MSGID_DLC_OFFER } 1663 1664 type DlcOfferDeclineMsg struct { 1665 PeerIdx uint32 1666 Idx uint64 // The contract we are declining 1667 Reason uint8 // Reason for declining the funding request 1668 1669 } 1670 1671 // NewDlcOfferDeclineMsg creates a new DlcOfferDeclineMsg based on a peer, a 1672 // reason for declining and the index of the contract we're declining 1673 func NewDlcOfferDeclineMsg(peerIdx uint32, reason uint8, 1674 theirIdx uint64) DlcOfferDeclineMsg { 1675 msg := new(DlcOfferDeclineMsg) 1676 msg.PeerIdx = peerIdx 1677 msg.Reason = reason 1678 msg.Idx = theirIdx 1679 return *msg 1680 } 1681 1682 // NewDlcOfferDeclineMsgFromBytes deserializes a byte array into a 1683 // DlcOfferDeclineMsg 1684 func NewDlcOfferDeclineMsgFromBytes(b []byte, 1685 peerIdx uint32) (DlcOfferDeclineMsg, error) { 1686 1687 msg := new(DlcOfferDeclineMsg) 1688 msg.PeerIdx = peerIdx 1689 1690 if len(b) < 2 { 1691 return *msg, fmt.Errorf("DlcOfferDeclineMsg %d bytes, expect at"+ 1692 " least 2", len(b)) 1693 } 1694 1695 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1696 _ = binary.Read(buf, binary.BigEndian, &msg.Reason) 1697 msg.Idx, _ = wire.ReadVarInt(buf, 0) 1698 1699 return *msg, nil 1700 } 1701 1702 // Bytes serializes a DlcOfferDeclineMsg into a byte array 1703 func (msg DlcOfferDeclineMsg) Bytes() []byte { 1704 var buf bytes.Buffer 1705 1706 buf.WriteByte(msg.MsgType()) 1707 1708 binary.Write(&buf, binary.BigEndian, msg.Reason) 1709 wire.WriteVarInt(&buf, 0, msg.Idx) 1710 return buf.Bytes() 1711 } 1712 1713 // Peer returns the peer index this message was received from/sent to 1714 func (msg DlcOfferDeclineMsg) Peer() uint32 { return msg.PeerIdx } 1715 1716 // MsgType returns the type of this message 1717 func (msg DlcOfferDeclineMsg) MsgType() uint8 { return MSGID_DLC_DECLINEOFFER } 1718 1719 // DlcContractSettlementSignature contains the signature for a particular 1720 // settlement transaction 1721 type DlcContractSettlementSignature struct { 1722 // The oracle value for which transaction these are the signatures 1723 Outcome int64 1724 // The signature for the transaction 1725 Signature [64]byte 1726 } 1727 1728 // DlcOfferAcceptMsg is a message indicating we are accepting the contract 1729 type DlcOfferAcceptMsg struct { 1730 // Index of the peer we are forming the contract with 1731 PeerIdx uint32 1732 // The index of the contract on the peer we're receiving this message on 1733 Idx uint64 1734 // The index of the contract on our side, so they know how to reference it 1735 OurIdx uint64 1736 // The PKH we want the change from funding to be paid back to 1737 OurChangePKH [20]byte 1738 // The Pubkey that is part of the multisig for spending the contract funds 1739 OurFundMultisigPub [33]byte 1740 // The Pubkey to be used to in the contract settlement 1741 OurPayoutBase [33]byte 1742 // The PKH to be paid to in the contract settlement 1743 OurPayoutPKH [20]byte 1744 // The UTXOs we are using to fund the contract 1745 FundingInputs []DlcContractFundingInput 1746 // The signatures for settling the contract at various values 1747 SettlementSignatures []DlcContractSettlementSignature 1748 } 1749 1750 // NewDlcOfferAcceptMsg generates a new DlcOfferAcceptMsg struct based on the 1751 // passed contract and signatures 1752 func NewDlcOfferAcceptMsg(contract *DlcContract, 1753 signatures []DlcContractSettlementSignature) DlcOfferAcceptMsg { 1754 1755 msg := new(DlcOfferAcceptMsg) 1756 msg.PeerIdx = contract.PeerIdx 1757 msg.Idx = contract.TheirIdx 1758 msg.OurIdx = contract.Idx 1759 msg.FundingInputs = contract.OurFundingInputs 1760 msg.OurChangePKH = contract.OurChangePKH 1761 msg.OurFundMultisigPub = contract.OurFundMultisigPub 1762 msg.OurPayoutBase = contract.OurPayoutBase 1763 msg.OurPayoutPKH = contract.OurPayoutPKH 1764 msg.SettlementSignatures = signatures 1765 return *msg 1766 } 1767 1768 // NewDlcOfferAcceptMsgFromBytes parses a byte array back into a 1769 // DlcOfferAcceptMsg struct 1770 func NewDlcOfferAcceptMsgFromBytes(b []byte, 1771 peerIdx uint32) (DlcOfferAcceptMsg, error) { 1772 1773 msg := new(DlcOfferAcceptMsg) 1774 msg.PeerIdx = peerIdx 1775 1776 if len(b) < 34 { 1777 return *msg, fmt.Errorf("DlcOfferAcceptMsg %d bytes, expect at"+ 1778 " least 34", len(b)) 1779 } 1780 1781 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1782 msg.Idx, _ = wire.ReadVarInt(buf, 0) 1783 msg.OurIdx, _ = wire.ReadVarInt(buf, 0) 1784 1785 copy(msg.OurChangePKH[:], buf.Next(20)) 1786 copy(msg.OurFundMultisigPub[:], buf.Next(33)) 1787 copy(msg.OurPayoutBase[:], buf.Next(33)) 1788 copy(msg.OurPayoutPKH[:], buf.Next(20)) 1789 1790 inputCount, _ := wire.ReadVarInt(buf, 0) 1791 1792 msg.FundingInputs = make([]DlcContractFundingInput, inputCount) 1793 var op [36]byte 1794 for i := uint64(0); i < inputCount; i++ { 1795 val, _ := wire.ReadVarInt(buf, 0) 1796 msg.FundingInputs[i].Value = int64(val) 1797 copy(op[:], buf.Next(36)) 1798 msg.FundingInputs[i].Outpoint = *OutPointFromBytes(op) 1799 1800 } 1801 1802 sigCount, _ := wire.ReadVarInt(buf, 0) 1803 msg.SettlementSignatures = make([]DlcContractSettlementSignature, sigCount) 1804 1805 for i := uint64(0); i < sigCount; i++ { 1806 val, _ := wire.ReadVarInt(buf, 0) 1807 msg.SettlementSignatures[i].Outcome = int64(val) 1808 copy(msg.SettlementSignatures[i].Signature[:], buf.Next(64)) 1809 } 1810 1811 return *msg, nil 1812 } 1813 1814 // Bytes turns a DlcOfferAcceptMsg into bytes 1815 func (msg DlcOfferAcceptMsg) Bytes() []byte { 1816 var buf bytes.Buffer 1817 1818 buf.WriteByte(msg.MsgType()) 1819 1820 wire.WriteVarInt(&buf, 0, msg.Idx) 1821 wire.WriteVarInt(&buf, 0, msg.OurIdx) 1822 1823 buf.Write(msg.OurChangePKH[:]) 1824 buf.Write(msg.OurFundMultisigPub[:]) 1825 buf.Write(msg.OurPayoutBase[:]) 1826 buf.Write(msg.OurPayoutPKH[:]) 1827 1828 inputCount := uint64(len(msg.FundingInputs)) 1829 wire.WriteVarInt(&buf, 0, inputCount) 1830 1831 for i := uint64(0); i < inputCount; i++ { 1832 wire.WriteVarInt(&buf, 0, uint64(msg.FundingInputs[i].Value)) 1833 op := OutPointToBytes(msg.FundingInputs[i].Outpoint) 1834 buf.Write(op[:]) 1835 } 1836 1837 signatureCount := uint64(len(msg.SettlementSignatures)) 1838 wire.WriteVarInt(&buf, 0, signatureCount) 1839 1840 for i := uint64(0); i < signatureCount; i++ { 1841 wire.WriteVarInt(&buf, 0, uint64(msg.SettlementSignatures[i].Outcome)) 1842 buf.Write(msg.SettlementSignatures[i].Signature[:]) 1843 } 1844 return buf.Bytes() 1845 } 1846 1847 // Peer returns the peer index this message was received from/sent to 1848 func (msg DlcOfferAcceptMsg) Peer() uint32 { 1849 return msg.PeerIdx 1850 } 1851 1852 // MsgType returns the type of this message 1853 func (msg DlcOfferAcceptMsg) MsgType() uint8 { 1854 return MSGID_DLC_ACCEPTOFFER 1855 } 1856 1857 // DlcContractAckMsg is sent from the offering party back to the peer when the 1858 // contract acceptance is acknowledged. Includes the signatures from this peer 1859 // for the settlement TXes. 1860 type DlcContractAckMsg struct { 1861 // Peer we're sending the Ack to (or received it from) 1862 PeerIdx uint32 1863 // The index of the contract we're acknowledging 1864 Idx uint64 1865 // The settlement signatures of the party acknowledging 1866 SettlementSignatures []DlcContractSettlementSignature 1867 } 1868 1869 // NewDlcContractAckMsg generates a new DlcContractAckMsg struct based on the 1870 // passed contract and signatures 1871 func NewDlcContractAckMsg(contract *DlcContract, 1872 signatures []DlcContractSettlementSignature) DlcContractAckMsg { 1873 1874 msg := new(DlcContractAckMsg) 1875 msg.PeerIdx = contract.PeerIdx 1876 msg.Idx = contract.TheirIdx 1877 msg.SettlementSignatures = signatures 1878 return *msg 1879 } 1880 1881 // NewDlcContractAckMsgFromBytes deserializes a byte array into a 1882 // DlcContractAckMsg 1883 func NewDlcContractAckMsgFromBytes(b []byte, 1884 peerIdx uint32) (DlcContractAckMsg, error) { 1885 1886 msg := new(DlcContractAckMsg) 1887 msg.PeerIdx = peerIdx 1888 1889 // TODO 1890 if len(b) < 34 { 1891 return *msg, fmt.Errorf("DlcContractAckMsg %d bytes, expect at"+ 1892 " least 34", len(b)) 1893 } 1894 1895 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1896 msg.Idx, _ = wire.ReadVarInt(buf, 0) 1897 1898 var sigCount uint32 1899 binary.Read(buf, binary.BigEndian, &sigCount) 1900 msg.SettlementSignatures = make([]DlcContractSettlementSignature, sigCount) 1901 1902 for i := uint32(0); i < sigCount; i++ { 1903 binary.Read(buf, binary.BigEndian, &msg.SettlementSignatures[i].Outcome) 1904 copy(msg.SettlementSignatures[i].Signature[:], buf.Next(64)) 1905 } 1906 return *msg, nil 1907 } 1908 1909 // Bytes serializes a DlcContractAckMsg into a byte array 1910 func (msg DlcContractAckMsg) Bytes() []byte { 1911 var buf bytes.Buffer 1912 1913 buf.WriteByte(msg.MsgType()) 1914 wire.WriteVarInt(&buf, 0, msg.Idx) 1915 1916 signatureCount := uint32(len(msg.SettlementSignatures)) 1917 binary.Write(&buf, binary.BigEndian, signatureCount) 1918 1919 for i := uint32(0); i < signatureCount; i++ { 1920 outcome := msg.SettlementSignatures[i].Outcome 1921 binary.Write(&buf, binary.BigEndian, outcome) 1922 buf.Write(msg.SettlementSignatures[i].Signature[:]) 1923 } 1924 return buf.Bytes() 1925 } 1926 1927 // Peer returns the peer index this message was received from/sent to 1928 func (msg DlcContractAckMsg) Peer() uint32 { 1929 return msg.PeerIdx 1930 } 1931 1932 // MsgType returns the type of this message 1933 func (msg DlcContractAckMsg) MsgType() uint8 { 1934 return MSGID_DLC_CONTRACTACK 1935 } 1936 1937 // DlcContractFundingSigsMsg is sent by the counter party once the signatures 1938 // for the settlement are verified and accepted. These signatures can be used 1939 // to spend the peer's UTXOs for funding the contract into the actual contract 1940 // output. 1941 type DlcContractFundingSigsMsg struct { 1942 PeerIdx uint32 // Peer we're exchanging the message with 1943 Idx uint64 // The index of the concerning contract 1944 SignedFundingTx *wire.MsgTx // The funding TX containing the signatures 1945 } 1946 1947 // NewDlcContractFundingSigsMsg creates a new DlcContractFundingSigsMsg based 1948 // on the passed contract and signed funding TX 1949 func NewDlcContractFundingSigsMsg(contract *DlcContract, 1950 signedTx *wire.MsgTx) DlcContractFundingSigsMsg { 1951 1952 msg := new(DlcContractFundingSigsMsg) 1953 msg.PeerIdx = contract.PeerIdx 1954 msg.Idx = contract.TheirIdx 1955 msg.SignedFundingTx = signedTx 1956 return *msg 1957 } 1958 1959 // NewDlcContractFundingSigsMsgFromBytes deserializes a byte array into a 1960 // DlcContractFundingSigsMsg 1961 func NewDlcContractFundingSigsMsgFromBytes(b []byte, 1962 peerIdx uint32) (DlcContractFundingSigsMsg, error) { 1963 1964 msg := new(DlcContractFundingSigsMsg) 1965 msg.PeerIdx = peerIdx 1966 1967 // TODO 1968 if len(b) < 34 { 1969 return *msg, fmt.Errorf("DlcContractFundingSigsMsg %d bytes, expect"+ 1970 "at least 34", len(b)) 1971 } 1972 1973 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 1974 msg.Idx, _ = wire.ReadVarInt(buf, 0) 1975 1976 msg.SignedFundingTx = wire.NewMsgTx() 1977 msg.SignedFundingTx.Deserialize(buf) 1978 1979 return *msg, nil 1980 } 1981 1982 // Bytes serializes a DlcContractFundingSigsMsg into a byte array 1983 func (msg DlcContractFundingSigsMsg) Bytes() []byte { 1984 var buf bytes.Buffer 1985 1986 buf.WriteByte(msg.MsgType()) 1987 wire.WriteVarInt(&buf, 0, msg.Idx) 1988 1989 writer := bufio.NewWriter(&buf) 1990 msg.SignedFundingTx.Serialize(writer) 1991 writer.Flush() 1992 return buf.Bytes() 1993 } 1994 1995 // Peer returns the peer index this message was received from/sent to 1996 func (msg DlcContractFundingSigsMsg) Peer() uint32 { 1997 return msg.PeerIdx 1998 } 1999 2000 // MsgType returns the type of this message 2001 func (msg DlcContractFundingSigsMsg) MsgType() uint8 { 2002 return MSGID_DLC_CONTRACTFUNDINGSIGS 2003 } 2004 2005 // DlcContractSigProofMsg acknowledges the funding of the contract to a peer. 2006 // It contains the fully signed funding transaction that has already been 2007 // published to the blockchain 2008 type DlcContractSigProofMsg struct { 2009 // The index of the peer we're communicating with 2010 PeerIdx uint32 2011 // The contract we're communicating about 2012 Idx uint64 2013 // The fully signed funding transaction 2014 SignedFundingTx *wire.MsgTx 2015 } 2016 2017 // NewDlcContractSigProofMsg creates a new DlcContractSigProofMsg based on the 2018 // passed contract and signed funding TX 2019 func NewDlcContractSigProofMsg(contract *DlcContract, 2020 signedTx *wire.MsgTx) DlcContractSigProofMsg { 2021 2022 msg := new(DlcContractSigProofMsg) 2023 msg.PeerIdx = contract.PeerIdx 2024 msg.Idx = contract.TheirIdx 2025 msg.SignedFundingTx = signedTx 2026 return *msg 2027 } 2028 2029 // NewDlcContractSigProofMsgFromBytes deserializes a byte array into a 2030 // DlcContractSigProofMsg 2031 func NewDlcContractSigProofMsgFromBytes(b []byte, 2032 peerIdx uint32) (DlcContractSigProofMsg, error) { 2033 2034 msg := new(DlcContractSigProofMsg) 2035 msg.PeerIdx = peerIdx 2036 2037 // TODO 2038 if len(b) < 34 { 2039 return *msg, fmt.Errorf("DlcContractSigProofMsg %d bytes, expect"+ 2040 " at least 34", len(b)) 2041 } 2042 2043 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 2044 msg.Idx, _ = wire.ReadVarInt(buf, 0) 2045 2046 msg.SignedFundingTx = wire.NewMsgTx() 2047 msg.SignedFundingTx.Deserialize(buf) 2048 2049 return *msg, nil 2050 } 2051 2052 // Bytes serializes a DlcContractSigProofMsg into a byte array 2053 func (msg DlcContractSigProofMsg) Bytes() []byte { 2054 var buf bytes.Buffer 2055 2056 buf.WriteByte(msg.MsgType()) 2057 wire.WriteVarInt(&buf, 0, msg.Idx) 2058 2059 writer := bufio.NewWriter(&buf) 2060 msg.SignedFundingTx.Serialize(writer) 2061 writer.Flush() 2062 return buf.Bytes() 2063 } 2064 2065 // Peer returns the peer index this message was received from/sent to 2066 func (msg DlcContractSigProofMsg) Peer() uint32 { 2067 return msg.PeerIdx 2068 } 2069 2070 // MsgType returns the type of this message 2071 func (msg DlcContractSigProofMsg) MsgType() uint8 { 2072 return MSGID_DLC_SIGPROOF 2073 } 2074 2075 // MultihopPaymentRequestMsg initiates a new multihop payment. It is sent to 2076 // the peer that will ultimately receive the payment. 2077 type MultihopPaymentRequestMsg struct { 2078 // The index of the peer we're communicating with 2079 PeerIdx uint32 2080 // The type of coin we're requesting to send 2081 Cointype uint32 2082 } 2083 2084 func NewMultihopPaymentRequestMsg(peerIdx uint32, cointype uint32) MultihopPaymentRequestMsg { 2085 msg := new(MultihopPaymentRequestMsg) 2086 msg.PeerIdx = peerIdx 2087 msg.Cointype = cointype 2088 return *msg 2089 } 2090 2091 func NewMultihopPaymentRequestMsgFromBytes(b []byte, 2092 peerIdx uint32) (MultihopPaymentRequestMsg, error) { 2093 2094 msg := new(MultihopPaymentRequestMsg) 2095 msg.PeerIdx = peerIdx 2096 2097 buf := bytes.NewBuffer(b[1:]) 2098 2099 err := binary.Read(buf, binary.BigEndian, &msg.Cointype) 2100 if err != nil { 2101 return *msg, err 2102 } 2103 2104 return *msg, nil 2105 } 2106 2107 // Bytes serializes a MultihopPaymentRequestMsg into a byte array 2108 func (msg MultihopPaymentRequestMsg) Bytes() []byte { 2109 var buf bytes.Buffer 2110 2111 buf.WriteByte(msg.MsgType()) 2112 binary.Write(&buf, binary.BigEndian, msg.Cointype) 2113 return buf.Bytes() 2114 } 2115 2116 // Peer returns the peer index this message was received from/sent to 2117 func (msg MultihopPaymentRequestMsg) Peer() uint32 { 2118 return msg.PeerIdx 2119 } 2120 2121 // MsgType returns the type of this message 2122 func (msg MultihopPaymentRequestMsg) MsgType() uint8 { 2123 return MSGID_PAY_REQ 2124 } 2125 2126 // MultihopPaymentRequestMsg initiates a new multihop payment. It is sent to 2127 // the peer that will ultimately send the payment. 2128 type MultihopPaymentAckMsg struct { 2129 // The index of the peer we're communicating with 2130 PeerIdx uint32 2131 // The hash to the preimage we use to clear out the HTLCs 2132 HHash [32]byte 2133 } 2134 2135 func NewMultihopPaymentAckMsg(peerIdx uint32, hHash [32]byte) MultihopPaymentAckMsg { 2136 msg := new(MultihopPaymentAckMsg) 2137 msg.PeerIdx = peerIdx 2138 msg.HHash = hHash 2139 return *msg 2140 } 2141 2142 func NewMultihopPaymentAckMsgFromBytes(b []byte, 2143 peerIdx uint32) (MultihopPaymentAckMsg, error) { 2144 2145 msg := new(MultihopPaymentAckMsg) 2146 msg.PeerIdx = peerIdx 2147 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 2148 copy(msg.HHash[:], buf.Next(32)) 2149 return *msg, nil 2150 } 2151 2152 // Bytes serializes a MultihopPaymentAckMsg into a byte array 2153 func (msg MultihopPaymentAckMsg) Bytes() []byte { 2154 var buf bytes.Buffer 2155 2156 buf.WriteByte(msg.MsgType()) 2157 buf.Write(msg.HHash[:]) 2158 2159 return buf.Bytes() 2160 } 2161 2162 func (msg MultihopPaymentAckMsg) Peer() uint32 { 2163 return msg.PeerIdx 2164 } 2165 2166 // MsgType returns the type of this message 2167 func (msg MultihopPaymentAckMsg) MsgType() uint8 { 2168 return MSGID_PAY_ACK 2169 } 2170 2171 // RemoteControlRpcRequestMsg contains a request to be executed by the local 2172 // lit node, when the remote node has been authorized to do so. 2173 type RemoteControlRpcRequestMsg struct { 2174 PeerIdx uint32 2175 // The pubkey of the node remote controlling. Can be null, in which case 2176 // the pubkey of the peer sending the message is used to determine the 2177 // authorization 2178 PubKey [33]byte 2179 2180 // The method being called, for example "LitRPC.Send" 2181 Method string 2182 2183 // A unique nonce that will be used to match the response that is sent 2184 // back in reply to this request. 2185 Idx uint64 2186 2187 // The JSON serialized arguments to the RPC method 2188 Args []byte 2189 2190 // If PubKey is passed, this should contain a signature made with the 2191 // corresponding private key of the Bytes() method of this message type, 2192 // containing a zero Sig 2193 Sig [64]byte 2194 2195 // The digest used for the signature. Can be one of 2196 // DIGEST_TYPE_SHA256 = 0x00 (Default) 2197 // DIGEST_TYPE_RIPEMD160 = 0x01 2198 // Different digest is supported to allow the use of embedded devices 2199 // such as smart cards that do not support signing SHA256 digests. 2200 // They exist, really. 2201 DigestType uint8 2202 } 2203 2204 func NewRemoteControlRpcRequestMsgFromBytes(b []byte, 2205 peerIdx uint32) (RemoteControlRpcRequestMsg, error) { 2206 2207 msg := new(RemoteControlRpcRequestMsg) 2208 msg.PeerIdx = peerIdx 2209 2210 buf := bytes.NewBuffer(b[1:]) 2211 copy(msg.PubKey[:], buf.Next(33)) 2212 copy(msg.Sig[:], buf.Next(64)) 2213 binary.Read(buf, binary.BigEndian, &msg.DigestType) 2214 binary.Read(buf, binary.BigEndian, &msg.Idx) 2215 2216 methodLength, _ := wire.ReadVarInt(buf, 0) 2217 msg.Method = string(buf.Next(int(methodLength))) 2218 2219 argsLength, _ := wire.ReadVarInt(buf, 0) 2220 msg.Args = buf.Next(int(argsLength)) 2221 return *msg, nil 2222 } 2223 2224 // Bytes serializes a RemoteControlRpcRequestMsg into a byte array 2225 func (msg RemoteControlRpcRequestMsg) Bytes() []byte { 2226 var buf bytes.Buffer 2227 2228 buf.WriteByte(msg.MsgType()) 2229 buf.Write(msg.PubKey[:]) 2230 buf.Write(msg.Sig[:]) 2231 binary.Write(&buf, binary.BigEndian, msg.DigestType) 2232 binary.Write(&buf, binary.BigEndian, msg.Idx) 2233 2234 methodBytes := []byte(msg.Method) 2235 wire.WriteVarInt(&buf, 0, uint64(len(methodBytes))) 2236 buf.Write(methodBytes) 2237 2238 wire.WriteVarInt(&buf, 0, uint64(len(msg.Args))) 2239 buf.Write(msg.Args) 2240 2241 return buf.Bytes() 2242 } 2243 2244 // Peer returns the peer index this message was received from/sent to 2245 func (msg RemoteControlRpcRequestMsg) Peer() uint32 { 2246 return msg.PeerIdx 2247 } 2248 2249 func (msg RemoteControlRpcRequestMsg) MsgType() uint8 { 2250 return MSGID_REMOTE_RPCREQUEST 2251 } 2252 2253 type RouteHop struct { 2254 Node [20]byte 2255 CoinType uint32 2256 } 2257 2258 func (rh *RouteHop) Bytes() []byte { 2259 var buf bytes.Buffer 2260 2261 buf.Write(rh.Node[:]) 2262 binary.Write(&buf, binary.BigEndian, rh.CoinType) 2263 2264 return buf.Bytes() 2265 } 2266 2267 func NewRouteHopFromBytes(b []byte) (*RouteHop, error) { 2268 buf := bytes.NewBuffer(b) 2269 2270 if buf.Len() < 24 { 2271 return nil, fmt.Errorf("not enough bytes for RouteHop") 2272 } 2273 2274 rh := new(RouteHop) 2275 2276 copy(rh.Node[:], buf.Next(20)) 2277 2278 err := binary.Read(buf, binary.BigEndian, &rh.CoinType) 2279 if err != nil { 2280 return nil, err 2281 } 2282 2283 return rh, nil 2284 } 2285 2286 // MultihopPaymentSetupMsg forms a new multihop payment. It is sent to 2287 // the next-in-line peer, which will forward it to the next hop until 2288 // the target is reached 2289 type MultihopPaymentSetupMsg struct { 2290 // The index of the peer we're communicating with 2291 PeerIdx uint32 2292 // The hash to the preimage we use to clear out the HTLCs 2293 HHash [32]byte 2294 // The PKHs (in order) of the nodes we're using. 2295 NodeRoute []RouteHop 2296 // Data associated with the payment 2297 Data [32]byte 2298 } 2299 2300 // NewMultihopPaymentSetupMsg does... 2301 func NewMultihopPaymentSetupMsg(peerIdx uint32, hHash [32]byte, nodeRoute []RouteHop, data [32]byte) MultihopPaymentSetupMsg { 2302 msg := new(MultihopPaymentSetupMsg) 2303 msg.PeerIdx = peerIdx 2304 msg.HHash = hHash 2305 msg.NodeRoute = nodeRoute 2306 msg.Data = data 2307 return *msg 2308 } 2309 2310 func NewMultihopPaymentSetupMsgFromBytes(b []byte, 2311 peerIdx uint32) (MultihopPaymentSetupMsg, error) { 2312 2313 msg := new(MultihopPaymentSetupMsg) 2314 msg.PeerIdx = peerIdx 2315 buf := bytes.NewBuffer(b[1:]) // get rid of messageType 2316 copy(msg.HHash[:], buf.Next(32)) 2317 2318 hops, _ := wire.ReadVarInt(buf, 0) 2319 for i := uint64(0); i < hops; i++ { 2320 rh, err := NewRouteHopFromBytes(buf.Next(24)) 2321 if err != nil { 2322 return *msg, err 2323 } 2324 2325 msg.NodeRoute = append(msg.NodeRoute, *rh) 2326 } 2327 2328 copy(msg.Data[:], buf.Next(32)) 2329 2330 return *msg, nil 2331 } 2332 2333 // Bytes serializes a MultihopPaymentSetupMsg into a byte array 2334 func (msg MultihopPaymentSetupMsg) Bytes() []byte { 2335 var buf bytes.Buffer 2336 2337 buf.WriteByte(msg.MsgType()) 2338 buf.Write(msg.HHash[:]) 2339 wire.WriteVarInt(&buf, 0, uint64(len(msg.NodeRoute))) 2340 for _, nd := range msg.NodeRoute { 2341 buf.Write(nd.Bytes()) 2342 } 2343 2344 buf.Write(msg.Data[:]) 2345 2346 return buf.Bytes() 2347 } 2348 2349 func (msg MultihopPaymentSetupMsg) Peer() uint32 { 2350 return msg.PeerIdx 2351 } 2352 2353 // MsgType returns the type of this message 2354 func (msg MultihopPaymentSetupMsg) MsgType() uint8 { 2355 return MSGID_PAY_SETUP 2356 } 2357 2358 // RemoteControlRpcResponseMsg is sent in response to a request message 2359 // and contains the output of the command that was executed 2360 type RemoteControlRpcResponseMsg struct { 2361 PeerIdx uint32 2362 Idx uint64 // Unique nonce that was sent in the request 2363 Error bool // Indicates that the reply is an error 2364 Result []byte // JSON serialization of the reply object 2365 } 2366 2367 func NewRemoteControlRpcResponseMsg(peerIdx uint32, msgIdx uint64, isError bool, json []byte) RemoteControlRpcResponseMsg { 2368 2369 msg := new(RemoteControlRpcResponseMsg) 2370 msg.PeerIdx = peerIdx 2371 msg.Idx = msgIdx 2372 msg.Error = isError 2373 msg.Result = json 2374 return *msg 2375 } 2376 2377 func NewRemoteControlRpcResponseMsgFromBytes(b []byte, 2378 peerIdx uint32) (RemoteControlRpcResponseMsg, error) { 2379 2380 msg := new(RemoteControlRpcResponseMsg) 2381 buf := bytes.NewBuffer(b[1:]) 2382 2383 msg.PeerIdx = peerIdx 2384 binary.Read(buf, binary.BigEndian, &msg.Idx) 2385 binary.Read(buf, binary.BigEndian, &msg.Error) 2386 2387 resultLength, _ := wire.ReadVarInt(buf, 0) 2388 msg.Result = buf.Next(int(resultLength)) 2389 2390 return *msg, nil 2391 } 2392 2393 // Bytes serializes a RemoteControlRpcRequestMsg into a byte array 2394 func (msg RemoteControlRpcResponseMsg) Bytes() []byte { 2395 var buf bytes.Buffer 2396 2397 buf.WriteByte(msg.MsgType()) 2398 binary.Write(&buf, binary.BigEndian, msg.Idx) 2399 binary.Write(&buf, binary.BigEndian, msg.Error) 2400 2401 wire.WriteVarInt(&buf, 0, uint64(len(msg.Result))) 2402 buf.Write(msg.Result) 2403 return buf.Bytes() 2404 } 2405 2406 // Peer returns the peer index this message was received from/sent to 2407 func (msg RemoteControlRpcResponseMsg) Peer() uint32 { 2408 return msg.PeerIdx 2409 } 2410 2411 // MsgType returns the type of this message 2412 func (msg RemoteControlRpcResponseMsg) MsgType() uint8 { 2413 return MSGID_REMOTE_RPCRESPONSE 2414 }