// settleHTLC settles the HTLC on the channel.
543649
func (l *channelLink) settleHTLC(preimage lntypes.Preimage, htlcIndex uint64,
	sourceRef *channeldb.AddRef) error {

	hash := preimage.Hash()

	l.infof("settling htlc %v as exit hop", hash)

	err := l.channel.SettleHTLC(
		preimage, htlcIndex, sourceRef, nil, nil,
	)
	if err != nil {
		return fmt.Errorf("unable to settle htlc: %v", err)
	}

	// If the link is in hodl.BogusSettle mode, replace the preimage with a
	// fake one before sending it to the peer.
	if l.cfg.DebugHTLC && l.cfg.HodlMask.Active(hodl.BogusSettle) {
		l.warnf(hodl.BogusSettle.Warning())
		preimage = [32]byte{}
		copy(preimage[:], bytes.Repeat([]byte{2}, 32))
	}

	// HTLC was successfully settled locally send notification about it
	// remote peer.
	l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
		ChanID:          l.ChanID(),
		ID:              htlcIndex,
		PaymentPreimage: preimage,
	})

	return nil
}
1262755
func (conn *Conn) h_CTCP(line *Line) {
	if line.Args[0] == VERSION {
		conn.CtcpReply(line.Nick, VERSION, conn.cfg.Version)
	} else if line.Args[0] == PING && line.argslen(2) {
		conn.CtcpReply(line.Nick, PING, line.Args[2])
	}
}
1078751
func Hlc3(highs []float64, lows []float64, closes []float64) []float64 {
	N := len(highs)
	result := make([]float64, N)
	for i := range highs {
		result[i] = (highs[i] + lows[i] + closes[i]) / 3
	}

	return result
}
1279031
func (rp *Ringpop) channelAddressResolver() (string, error) {
	peerInfo := rp.channel.PeerInfo()
	// Check that TChannel is listening on a real hostport. By default,
	// TChannel listens on an ephemeral host/port. The real port is then
	// assigned by the OS when ListenAndServe is called. If the hostport is
	// ephemeral, it means TChannel is not yet listening and the hostport
	// cannot be resolved.
	if peerInfo.IsEphemeralHostPort() {
		return "", ErrEphemeralAddress
	}
	return peerInfo.HostPort, nil
}
351027
func (l *channelLink) handleBatchFwdErrs(errChan chan error) {
	for {
		err, ok := <-errChan
		if !ok {
			// Err chan has been drained or switch is shutting
			// down.  Either way, return.
			return
		}

		if err == nil {
			continue
		}

		l.errorf("unhandled error while forwarding htlc packet over "+
			"htlcswitch: %v", err)
	}
}
773040
func HaltChannel(channel int) {
	_channel := (C.int)(channel)
	C.Mix_HaltChannel(_channel)
}
185322
func (h *htlcSuccessResolver) Decode(r io.Reader) error {
	// First we'll decode our inner HTLC resolution.
	if err := decodeIncomingResolution(r, &h.htlcResolution); err != nil {
		return err
	}

	// Next, we'll read all the fields that are specified to the contract
	// resolver.
	if err := binary.Read(r, endian, &h.outputIncubating); err != nil {
		return err
	}
	if err := binary.Read(r, endian, &h.resolved); err != nil {
		return err
	}
	if err := binary.Read(r, endian, &h.broadcastHeight); err != nil {
		return err
	}
	if _, err := io.ReadFull(r, h.payHash[:]); err != nil {
		return err
	}

	return nil
}
449035
func (c *ChainArbitrator) resolveContract(chanPoint wire.OutPoint,
	arbLog ArbitratorLog) error {

	log.Infof("Marking ChannelPoint(%v) fully resolved", chanPoint)

	// First, we'll we'll mark the channel as fully closed from the PoV of
	// the channel source.
	err := c.chanSource.MarkChanFullyClosed(&chanPoint)
	if err != nil {
		log.Errorf("ChainArbitrator: unable to mark ChannelPoint(%v) "+
			"fully closed: %v", chanPoint, err)
		return err
	}

	if arbLog != nil {
		// Once this has been marked as resolved, we'll wipe the log
		// that the channel arbitrator was using to store its
		// persistent state. We do this after marking the channel
		// resolved, as otherwise, the arbitrator would be re-created,
		// and think it was starting from the default state.
		if err := arbLog.WipeHistory(); err != nil {
			return err
		}
	}

	c.Lock()
	delete(c.activeChannels, chanPoint)

	chainWatcher, ok := c.activeWatchers[chanPoint]
	if ok {
		chainWatcher.Stop()
	}
	delete(c.activeWatchers, chanPoint)
	c.Unlock()

	return nil
}
617362
func (c *OpenChannel) AckAddHtlcs(addRefs ...AddRef) error {
	c.Lock()
	defer c.Unlock()

	return c.Db.Update(func(tx *bbolt.Tx) error {
		return c.Packager.AckAddHtlcs(tx, addRefs...)
	})
}
1284536
func (l *channelLink) processHodlQueue(firstHodlEvent invoices.HodlEvent) error {
	// Try to read all waiting resolution messages, so that they can all be
	// processed in a single commitment tx update.
	hodlEvent := firstHodlEvent
loop:
	for {
		if err := l.processHodlMapEvent(hodlEvent); err != nil {
			return err
		}

		select {
		case item := <-l.hodlQueue.ChanOut():
			hodlEvent = item.(invoices.HodlEvent)
		default:
			break loop
		}
	}

	// Update the commitment tx.
	if err := l.updateCommitTx(); err != nil {
		return fmt.Errorf("unable to update commitment: %v", err)
	}

	return nil
}
778390
func ChannelClose(ch chan *Message) bool {
	select {
	case _, ok := <-ch:
		if ok {
			close(ch)
			return true
		}
	default:
	}
	return false
}
752729
func (p *peer) handleLocalCloseReq(req *htlcswitch.ChanClose) {
	chanID := lnwire.NewChanIDFromOutPoint(req.ChanPoint)

	p.activeChanMtx.RLock()
	channel, ok := p.activeChannels[chanID]
	p.activeChanMtx.RUnlock()
	if !ok {
		err := fmt.Errorf("unable to close channel, ChannelID(%v) is "+
			"unknown", chanID)
		peerLog.Errorf(err.Error())
		req.Err <- err
		return
	}

	switch req.CloseType {

	// A type of CloseRegular indicates that the user has opted to close
	// out this channel on-chain, so we execute the cooperative channel
	// closure workflow.
	case htlcswitch.CloseRegular:
		// First, we'll fetch a fresh delivery address that we'll use
		// to send the funds to in the case of a successful
		// negotiation.
		deliveryAddr, err := p.genDeliveryScript()
		if err != nil {
			peerLog.Errorf(err.Error())
			req.Err <- err
			return
		}

		// Next, we'll create a new channel closer state machine to
		// handle the close negotiation.
		_, startingHeight, err := p.server.cc.chainIO.GetBestBlock()
		if err != nil {
			peerLog.Errorf(err.Error())
			req.Err <- err
			return
		}

		chanCloser := newChannelCloser(
			chanCloseCfg{
				channel:           channel,
				unregisterChannel: p.server.htlcSwitch.RemoveLink,
				broadcastTx:       p.server.cc.wallet.PublishTransaction,
				disableChannel:    p.server.chanStatusMgr.RequestDisable,
				quit:              p.quit,
			},
			deliveryAddr,
			req.TargetFeePerKw,
			uint32(startingHeight),
			req,
		)
		p.activeChanCloses[chanID] = chanCloser

		// Finally, we'll initiate the channel shutdown within the
		// chanCloser, and send the shutdown message to the remote
		// party to kick things off.
		shutdownMsg, err := chanCloser.ShutdownChan()
		if err != nil {
			peerLog.Errorf(err.Error())
			req.Err <- err
			delete(p.activeChanCloses, chanID)

			// As we were unable to shutdown the channel, we'll
			// return it back to its normal state.
			channel.ResetState()
			return
		}

		p.queueMsg(shutdownMsg, nil)

	// A type of CloseBreach indicates that the counterparty has breached
	// the channel therefore we need to clean up our local state.
	case htlcswitch.CloseBreach:
		// TODO(roasbeef): no longer need with newer beach logic?
		peerLog.Infof("ChannelPoint(%v) has been breached, wiping "+
			"channel", req.ChanPoint)
		if err := p.WipeChannel(req.ChanPoint); err != nil {
			peerLog.Infof("Unable to wipe channel after detected "+
				"breach: %v", err)
			req.Err <- err
			return
		}
		return
	}
}
323955
func (c *ChannelUpdateCall) Header() http.Header {
	if c.header_ == nil {
		c.header_ = make(http.Header)
	}
	return c.header_
}
39504
func extractHtlcResolutions(feePerKw SatPerKWeight, ourCommit bool,
	signer input.Signer, htlcs []channeldb.HTLC, keyRing *CommitmentKeyRing,
	localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
	commitHash chainhash.Hash, pCache PreimageCache) (*HtlcResolutions, error) {

	// TODO(roasbeef): don't need to swap csv delay?
	dustLimit := remoteChanCfg.DustLimit
	csvDelay := remoteChanCfg.CsvDelay
	if ourCommit {
		dustLimit = localChanCfg.DustLimit
		csvDelay = localChanCfg.CsvDelay
	}

	incomingResolutions := make([]IncomingHtlcResolution, 0, len(htlcs))
	outgoingResolutions := make([]OutgoingHtlcResolution, 0, len(htlcs))
	for _, htlc := range htlcs {
		// We'll skip any HTLC's which were dust on the commitment
		// transaction, as these don't have a corresponding output
		// within the commitment transaction.
		if htlcIsDust(htlc.Incoming, ourCommit, feePerKw,
			htlc.Amt.ToSatoshis(), dustLimit) {
			continue
		}

		// If the HTLC is incoming, then we'll attempt to see if we
		// know the pre-image to the HTLC.
		if htlc.Incoming {
			// We'll now query the preimage cache for the preimage
			// for this HTLC. If it's present then we can fully
			// populate this resolution.
			preimage, _ := pCache.LookupPreimage(htlc.RHash)

			// Otherwise, we'll create an incoming HTLC resolution
			// as we can satisfy the contract.
			var pre [32]byte
			copy(pre[:], preimage[:])
			ihr, err := newIncomingHtlcResolution(
				signer, localChanCfg, commitHash, &htlc, keyRing,
				feePerKw, dustLimit, uint32(csvDelay), ourCommit,
				pre,
			)
			if err != nil {
				return nil, err
			}

			incomingResolutions = append(incomingResolutions, *ihr)
			continue
		}

		ohr, err := newOutgoingHtlcResolution(
			signer, localChanCfg, commitHash, &htlc, keyRing,
			feePerKw, dustLimit, uint32(csvDelay), ourCommit,
		)
		if err != nil {
			return nil, err
		}

		outgoingResolutions = append(outgoingResolutions, *ohr)
	}

	return &HtlcResolutions{
		IncomingHTLCs: incomingResolutions,
		OutgoingHTLCs: outgoingResolutions,
	}, nil
}
380004
func (c *Connection) releaseAPIChannel(ch *Channel) {
	log.WithFields(logger.Fields{
		"channel": ch.id,
	}).Debug("API channel released")

	// delete the channel from channels map
	c.channelsLock.Lock()
	delete(c.channels, ch.id)
	c.channelsLock.Unlock()
}
240703
func (c *ChannelInsertCall) Header() http.Header {
	if c.header_ == nil {
		c.header_ = make(http.Header)
	}
	return c.header_
}
618669
func (d Delivery) SettleAs(disposition uint64) {
	d.Update(disposition)
	d.Settle()
}