// decodeAsync will prepare decoding the block when it receives the history.
// If history is provided, it will not fetch it from the channel.
184842
func (b *blockDec) decodeBuf(hist *history) error {
	switch b.Type {
	case blockTypeRLE:
		if cap(b.dst) < int(b.RLESize) {
			if b.lowMem {
				b.dst = make([]byte, b.RLESize)
			} else {
				b.dst = make([]byte, maxBlockSize)
			}
		}
		b.dst = b.dst[:b.RLESize]
		v := b.data[0]
		for i := range b.dst {
			b.dst[i] = v
		}
		hist.appendKeep(b.dst)
		return nil
	case blockTypeRaw:
		hist.appendKeep(b.data)
		return nil
	case blockTypeCompressed:
		saved := b.dst
		b.dst = hist.b
		hist.b = nil
		err := b.decodeCompressed(hist)
		if debug {
			println("Decompressed to total", len(b.dst), "bytes, error:", err)
		}
		hist.b = b.dst
		b.dst = saved
		return err
	case blockTypeReserved:
		// Used for returning errors.
		return b.err
	default:
		panic("Invalid block type")
	}
}
1184345
func (d *Decoder) Decode(idx *MemoryIndex) error {
	if err := validateHeader(d); err != nil {
		return err
	}

	flow := []func(*MemoryIndex, io.Reader) error{
		readVersion,
		readFanout,
		readObjectNames,
		readCRC32,
		readOffsets,
		readChecksums,
	}

	for _, f := range flow {
		if err := f(idx, d); err != nil {
			return err
		}
	}

	return nil
}
849365
func (dc *DispatcherClient) CallAsync(funcName string, request interface{}) (*AsyncResult, error) {
	req := dc.getRequest(funcName, request)

	innerAr, err := dc.c.CallAsync(req)
	if err != nil {
		return nil, err
	}

	ch := make(chan struct{})
	ar := &AsyncResult{
		Done: ch,
	}

	go func() {
		<-innerAr.Done
		ar.Response, ar.Error = getResponse(innerAr.Response, innerAr.Error)
		close(ch)
	}()

	return ar, nil
}
148113
func (s *sequenceDecs) decode(seqs int, br *bitReader, hist []byte) error {
	startSize := len(s.out)
	for i := seqs - 1; i >= 0; i-- {
		if br.overread() {
			printf("reading sequence %d, exceeded available data\n", seqs-i)
			return io.ErrUnexpectedEOF
		}
		var litLen, matchOff, matchLen int
		if br.off > 4+((maxOffsetBits+16+16)>>3) {
			litLen, matchOff, matchLen = s.nextFast(br)
			br.fillFast()
		} else {
			litLen, matchOff, matchLen = s.next(br)
			br.fill()
		}

		if debug {
			//println("Seq", seqs-i, "Litlen:", litLen, "matchOff:", matchOff, "matchLen:", matchLen)
		}

		if litLen > len(s.literals) {
			return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", litLen, len(s.literals))
		}
		size := litLen + matchLen + len(s.out)
		if size-startSize > maxBlockSize {
			return fmt.Errorf("output (%d) bigger than max block size", size)
		}
		if size > cap(s.out) {
			// Not enough size, will be extremely rarely triggered,
			// but could be if destination slice is too small for sync operations.
			// We add maxBlockSize to the capacity.
			s.out = append(s.out, make([]byte, maxBlockSize)...)
			s.out = s.out[:len(s.out)-maxBlockSize]
		}
		if matchLen > maxMatchLen {
			return fmt.Errorf("match len (%d) bigger than max allowed length", matchLen)
		}
		if matchOff > len(s.out)+len(hist)+litLen {
			return fmt.Errorf("match offset (%d) bigger than current history (%d)", matchOff, len(s.out)+len(hist)+litLen)
		}
		if matchOff == 0 && matchLen > 0 {
			return fmt.Errorf("zero matchoff and matchlen > 0")
		}

		s.out = append(s.out, s.literals[:litLen]...)
		s.literals = s.literals[litLen:]
		out := s.out

		// Copy from history.
		// TODO: Blocks without history could be made to ignore this completely.
		if v := matchOff - len(s.out); v > 0 {
			// v is the start position in history from end.
			start := len(s.hist) - v
			if matchLen > v {
				// Some goes into current block.
				// Copy remainder of history
				out = append(out, s.hist[start:]...)
				matchOff -= v
				matchLen -= v
			} else {
				out = append(out, s.hist[start:start+matchLen]...)
				matchLen = 0
			}
		}
		// We must be in current buffer now
		if matchLen > 0 {
			start := len(s.out) - matchOff
			if matchLen <= len(s.out)-start {
				// No overlap
				out = append(out, s.out[start:start+matchLen]...)
			} else {
				// Overlapping copy
				// Extend destination slice and copy one byte at the time.
				out = out[:len(out)+matchLen]
				src := out[start : start+matchLen]
				// Destination is the space we just added.
				dst := out[len(out)-matchLen:]
				dst = dst[:len(src)]
				for i := range src {
					dst[i] = src[i]
				}
			}
		}
		s.out = out
		if i == 0 {
			// This is the last sequence, so we shouldn't update state.
			break
		}
		if true {
			// Manually inlined, ~ 5-20% faster
			// Update all 3 states at once. Approx 20% faster.
			a, b, c := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state

			nBits := a.nbBits + b.nbBits + c.nbBits
			if nBits == 0 {
				s.litLengths.state.state = s.litLengths.state.dt[a.newState]
				s.matchLengths.state.state = s.matchLengths.state.dt[b.newState]
				s.offsets.state.state = s.offsets.state.dt[c.newState]
			} else {
				bits := br.getBitsFast(nBits)
				lowBits := uint16(bits >> ((c.nbBits + b.nbBits) & 31))
				s.litLengths.state.state = s.litLengths.state.dt[a.newState+lowBits]

				lowBits = uint16(bits >> (c.nbBits & 31))
				lowBits &= bitMask[b.nbBits&15]
				s.matchLengths.state.state = s.matchLengths.state.dt[b.newState+lowBits]

				lowBits = uint16(bits) & bitMask[c.nbBits&15]
				s.offsets.state.state = s.offsets.state.dt[c.newState+lowBits]
			}
		} else {
			s.updateAlt(br)
		}
	}

	// Add final literals
	s.out = append(s.out, s.literals...)
	return nil
}
43740
func (d *YAMLOrJSONDecoder) Decode(into interface{}) error {
	if d.decoder == nil {
		buffer, isJSON := guessJSONStream(d.r, d.bufferSize)
		if isJSON {
			glog.V(4).Infof("decoding stream as JSON")
			d.decoder = json.NewDecoder(buffer)
		} else {
			glog.V(4).Infof("decoding stream as YAML")
			d.decoder = NewYAMLToJSONDecoder(buffer)
		}
	}
	return d.decoder.Decode(into)
}
360732
func (jsonEncoderDecoder) Decode(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}
858311
func (sw *streamWatcher) Decode() (Event, error) {
	var got Event
	if err := sw.decoder.Decode(&got); err != nil {
		return Event{}, err
	}
	switch got.Type {
	case Added, Modified, Deleted, Error:
		return got, nil
	default:
		return Event{}, fmt.Errorf("got invalid watch event type: %v", got.Type)
	}
}
628390
func (mr *Reader) decodeBlock() (err error) {
	defer errors.Recover(&err)

	// Update the number of bytes read from underlying Reader.
	offset := mr.rd.Offset
	defer func() {
		if _, errFl := mr.rd.Flush(); errFl != nil {
			err = errFl
		}
		mr.InputOffset += mr.rd.Offset - offset
	}()

	mr.bb.Reset()
	mr.bw.Init(&mr.bb, false)

	if err := mr.rd.PullBits(1); err != nil {
		if err == io.ErrUnexpectedEOF {
			return io.EOF // EOF is okay for first bit
		}
		return err
	}
	magic := mr.rd.ReadBits(32)
	if uint32(magic)&magicMask != magicVals {
		return errorf(errors.Corrupted, "invalid meta magic value")
	}

	// Decode header.
	var fail bool
	finalStream := (magic>>0)&1 > 0
	pads := (magic >> 3) & 7       // 0..7
	numHCLen := 4 + (magic>>13)&15 // 6..18, always even
	fail = fail || numHCLen < 6
	for i := uint(5); i < numHCLen-1; i++ {
		fail = fail || mr.rd.ReadBits(3) != 0 // Empty HCLen code
	}
	fail = fail || mr.rd.ReadBits(3) != 2 // Final HCLen code
	fail = fail || mr.rd.ReadBits(1) != 0 // First symbol always symZero
	if fail {
		return errorf(errors.Corrupted, "invalid meta header")
	}

	huffLen := 8 - (numHCLen-4)/2 // Based on XFLATE specification
	huffRange := 1 << huffLen

	// Read symbols.
	var bit, ones uint
	fifo := byte(0xff)
	mr.bw.WriteBits(0, 1) // First symbol is symZero
	for idx := 0; idx < maxSyms-1; {
		cnt := 1
		sym, ok := mr.rd.TryReadSymbol(&decHuff)
		if !ok {
			sym = mr.rd.ReadSymbol(&decHuff)
		}
		switch sym {
		case symZero:
			bit = 0
			fifo = (fifo >> 1) | byte(0<<7)
		case symOne:
			bit = 1
			fifo = (fifo >> 2) | byte(1<<6)
		case symRepLast:
			val, ok := mr.rd.TryReadBits(2)
			if !ok {
				val = mr.rd.ReadBits(2)
			}
			cnt = int(val + minRepLast)
			fifo = (fifo >> 3) | byte(3<<5)
			fifo = (fifo >> 2) | byte(val<<6)
		case symRepZero:
			bit = 0
			val, ok := mr.rd.TryReadBits(7)
			if !ok {
				val = mr.rd.ReadBits(7)
			}
			cnt = int(val + minRepZero)
			fifo = (fifo >> 3) | byte(7<<5)
			fifo = (fifo >> 7) | byte(val<<1)
		}

		if fifo == 0x00 {
			// The specification forbids a sequence of 8 zero bits to appear
			// in the data section. This ensures that the magic value never
			// appears in the meta encoding by accident.
			return errorf(errors.Corrupted, "invalid sequence of meta symbols")
		}
		for i := 0; i < cnt; i++ {
			if ok := mr.bw.TryWriteBits(bit, 1); !ok {
				mr.bw.WriteBits(bit, 1)
			}
			ones += bit
		}
		idx += cnt
	}
	if mr.bw.BitsWritten() != maxSyms {
		return errorf(errors.Corrupted, "excessive number of meta symbols")
	}
	mr.bw.WriteBits(0, numPads(maxSyms)) // Flush to byte boundary

	// Decode data segment.
	const idxEOB = maxSyms - 1
	mr.bw.Flush()
	syms := mr.bb.Bytes() // Exactly 33 bytes
	if int(ones) != huffRange {
		return errorf(errors.Corrupted, "degenerate meta prefix tree")
	}
	if syms[idxEOB/8]&(1<<(idxEOB%8)) == 0 {
		return errorf(errors.Corrupted, "missing meta terminator symbol")
	}

	flags := syms[0]
	finalMeta := (flags>>1)&1 > 0
	invert := (flags>>2)&1 > 0
	size := (flags >> 3) & 31 // 0..31

	buf := syms[1 : 1+size] // Skip first header byte
	if invert {
		for i, b := range buf {
			buf[i] = ^b
		}
	}

	final := FinalMode(btoi(finalMeta) + btoi(finalStream))
	if finalStream && !finalMeta {
		return errorf(errors.Corrupted, "invalid combination of final bits")
	}

	// Decode footer.
	fail = fail || mr.rd.ReadBits(pads) > 0                     // Pads must be zero
	fail = fail || mr.rd.ReadBits(1) > 0                        // HDistTree must be empty
	fail = fail || mr.rd.ReadBits(huffLen) != uint(huffRange-1) // EOB marker
	fail = fail || mr.rd.BitsRead()%8 > 0                       // Bit reader not byte-aligned
	if fail {
		return errorf(errors.Corrupted, "invalid meta footer")
	}

	mr.buf, mr.final = buf, final
	mr.NumBlocks++
	return nil
}
526879
func decode(packet []byte) (interface{}, error) {
	var msg interface{}
	switch packet[0] {
	case msgDisconnect:
		msg = new(disconnectMsg)
	case msgServiceRequest:
		msg = new(serviceRequestMsg)
	case msgServiceAccept:
		msg = new(serviceAcceptMsg)
	case msgKexInit:
		msg = new(kexInitMsg)
	case msgKexDHInit:
		msg = new(kexDHInitMsg)
	case msgKexDHReply:
		msg = new(kexDHReplyMsg)
	case msgUserAuthRequest:
		msg = new(userAuthRequestMsg)
	case msgUserAuthFailure:
		msg = new(userAuthFailureMsg)
	case msgUserAuthPubKeyOk:
		msg = new(userAuthPubKeyOkMsg)
	case msgGlobalRequest:
		msg = new(globalRequestMsg)
	case msgRequestSuccess:
		msg = new(globalRequestSuccessMsg)
	case msgRequestFailure:
		msg = new(globalRequestFailureMsg)
	case msgChannelOpen:
		msg = new(channelOpenMsg)
	case msgChannelOpenConfirm:
		msg = new(channelOpenConfirmMsg)
	case msgChannelOpenFailure:
		msg = new(channelOpenFailureMsg)
	case msgChannelWindowAdjust:
		msg = new(windowAdjustMsg)
	case msgChannelEOF:
		msg = new(channelEOFMsg)
	case msgChannelClose:
		msg = new(channelCloseMsg)
	case msgChannelRequest:
		msg = new(channelRequestMsg)
	case msgChannelSuccess:
		msg = new(channelRequestSuccessMsg)
	case msgChannelFailure:
		msg = new(channelRequestFailureMsg)
	default:
		return nil, unexpectedMessageError(0, packet[0])
	}
	if err := Unmarshal(packet, msg); err != nil {
		return nil, err
	}
	return msg, nil
}
1067734
func (r *reader) decodeBlock(w io.Writer) (int, error) {
	// read compressed block data and determine if uncompressed data is too
	// large.
	buf, err := r.readBlock()
	if err != nil {
		return 0, err
	}
	declen := len(buf[4:])
	if r.hdr[0] == blockCompressed {
		declen, err = snappy.DecodedLen(buf[4:])
		if err != nil {
			return 0, err
		}
	}
	if declen > MaxBlockSize {
		return 0, fmt.Errorf("decoded block data too large %d > %d", declen, MaxBlockSize)
	}

	// decode data and verify its integrity using the little-endian crc32
	// preceding encoded data
	crc32le, blockdata := buf[:4], buf[4:]
	if r.hdr[0] == blockCompressed {
		r.dst, err = snappy.Decode(r.dst, blockdata)
		if err != nil {
			return 0, err
		}
		blockdata = r.dst
	}
	if r.verifyChecksum {
		checksum := unmaskChecksum(uint32(crc32le[0]) | uint32(crc32le[1])<<8 | uint32(crc32le[2])<<16 | uint32(crc32le[3])<<24)
		actualChecksum := crc32.Checksum(blockdata, crcTable)
		if checksum != actualChecksum {
			return 0, fmt.Errorf("checksum does not match %x != %x", checksum, actualChecksum)
		}
	}
	return w.Write(blockdata)
}
109911
func (c *Client) WalletLockAsync() FutureWalletLockResult {
	cmd := btcjson.NewWalletLockCmd()
	return c.sendCmd(cmd)
}
230228
func (a *AcceptChannel) Decode(r io.Reader, pver uint32) error {
	return ReadElements(r,
		a.PendingChannelID[:],
		&a.DustLimit,
		&a.MaxValueInFlight,
		&a.ChannelReserve,
		&a.HtlcMinimum,
		&a.MinAcceptDepth,
		&a.CsvDelay,
		&a.MaxAcceptedHTLCs,
		&a.FundingKey,
		&a.RevocationPoint,
		&a.PaymentPoint,
		&a.DelayedPaymentPoint,
		&a.HtlcPoint,
		&a.FirstCommitmentPoint,
	)
}
297452
func (e Erasure) Decode(ctx context.Context, writer io.Writer, readers []io.ReaderAt, offset, length, totalLength int64) error {
	if offset < 0 || length < 0 {
		logger.LogIf(ctx, errInvalidArgument)
		return errInvalidArgument
	}
	if offset+length > totalLength {
		logger.LogIf(ctx, errInvalidArgument)
		return errInvalidArgument
	}
	if length == 0 {
		return nil
	}

	reader := newParallelReader(readers, e, offset, totalLength)

	startBlock := offset / e.blockSize
	endBlock := (offset + length) / e.blockSize

	var bytesWritten int64
	for block := startBlock; block <= endBlock; block++ {
		var blockOffset, blockLength int64
		switch {
		case startBlock == endBlock:
			blockOffset = offset % e.blockSize
			blockLength = length
		case block == startBlock:
			blockOffset = offset % e.blockSize
			blockLength = e.blockSize - blockOffset
		case block == endBlock:
			blockOffset = 0
			blockLength = (offset + length) % e.blockSize
		default:
			blockOffset = 0
			blockLength = e.blockSize
		}
		if blockLength == 0 {
			break
		}
		bufs, err := reader.Read()
		if err != nil {
			return err
		}
		if err = e.DecodeDataBlocks(bufs); err != nil {
			logger.LogIf(ctx, err)
			return err
		}
		n, err := writeDataBlocks(ctx, writer, bufs, e.dataBlocks, blockOffset, blockLength)
		if err != nil {
			return err
		}
		bytesWritten += n
	}
	if bytesWritten != length {
		logger.LogIf(ctx, errLessData)
		return errLessData
	}
	return nil
}
494424
func (dec *Decoder) Decode(v interface{}) error {
	if dec.err != nil {
		return dec.err
	}

	if err := dec.tokenPrepareForDecode(); err != nil {
		return err
	}

	if !dec.tokenValueAllowed() {
		return &SyntaxError{msg: "not at beginning of value"}
	}

	// Read whole value into buffer.
	n, err := dec.readValue()
	if err != nil {
		return err
	}
	dec.d.init(dec.buf[dec.scanp : dec.scanp+n])
	dec.scanp += n

	// Don't save err from unmarshal into dec.err:
	// the connection is still usable since we read a complete JSON
	// object from it before the error happened.
	err = dec.d.unmarshal(v)

	// fixup token streaming state
	dec.tokenValueEnd()

	return err
}
871372
func (c *Client) ExecuteAsync(a *Async) error {
	return c.cluster.ExecuteAsync(a)
}
361892
func (u *DefaultDecoder) Decode(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}
324676
func (p *BlockPrefetchClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) {
	msgBlock, _, err := p.GetBlockData(hash)
	return msgBlock, err
}