// DecodeBlock decodes PEM block data, adding any crypto primitive encountered the
// store.
777689
func (s Store) DecodeBlock(block *pem.Block) error {
	switch BlockType(block.Type) {
	case PrivateKey:
		// try pkcs1 and then pkcs8 decoding
		key, err := ParsePKCSPrivateKey(block.Bytes)
		if err == nil {
			return s.add(RSAPrivateKey, key)
		}

		// must be a raw key (ie, use decoded b64 value as key)
		return s.add(PrivateKey, block.Bytes)

	case PublicKey:
		key, err := x509.ParsePKIXPublicKey(block.Bytes)
		if err != nil {
			// use the raw b64 decoded bytes
			key = block.Bytes
		}
		return s.add(PublicKey, key)

	case RSAPrivateKey:
		// try pkcs1 then pkcs8 decoding
		key, err := ParsePKCSPrivateKey(block.Bytes)
		if err != nil {
			return err
		}
		return s.add(RSAPrivateKey, key)

	case ECPrivateKey:
		key, err := x509.ParseECPrivateKey(block.Bytes)
		if err != nil {
			return err
		}
		return s.add(ECPrivateKey, key)

	case Certificate:
		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return err
		}
		return s.add(Certificate, cert)
	}

	return fmt.Errorf("unknown block type %s", block.Type)
}
726137
func (p *parser) parseBlock() *ast.BlockStatement {
	// openBlock
	result, blockParams := p.parseOpenBlock()

	// program
	program := p.parseProgram()
	program.BlockParams = blockParams
	result.Program = program

	// inverseChain?
	if p.isInverseChain() {
		result.Inverse = p.parseInverseChain()
	}

	// closeBlock
	p.parseCloseBlock(result)

	setBlockInverseStrip(result)

	return result
}
812939
func DecodeTimestampArrayBlock(block []byte, a *tsdb.TimestampArray) error {
	tb, _, err := unpackBlock(block[1:])
	if err != nil {
		return err
	}

	a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps)
	return err
}
1233918
func DecodeIntegerArrayBlock(block []byte, a *tsdb.IntegerArray) error {
	blockType := block[0]
	if blockType != BlockInteger {
		return fmt.Errorf("invalid block type: exp %d, got %d", BlockInteger, blockType)
	}

	tb, vb, err := unpackBlock(block[1:])
	if err != nil {
		return err
	}

	a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps)
	if err != nil {
		return err
	}
	a.Values, err = IntegerArrayDecodeAll(vb, a.Values)
	return err
}
919825
func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
	return nil
}
428255
func (blk *TagBlock) DecodeTagValueElem(key, value []byte, valueElem *TagBlockValueElem) bool {
	// Find key element, exit if not found.
	var keyElem TagBlockKeyElem
	if !blk.DecodeTagKeyElem(key, &keyElem) {
		return false
	}

	// Slice hash index data.
	hashData := keyElem.hashIndex.buf

	valueN := int64(binary.BigEndian.Uint64(hashData[:TagValueNSize]))
	hash := rhh.HashKey(value)
	pos := hash % valueN

	// Track current distance
	var d int64
	for {
		// Find offset of tag value.
		offset := binary.BigEndian.Uint64(hashData[TagValueNSize+(pos*TagValueOffsetSize):])
		if offset == 0 {
			return false
		}

		// Parse into element.
		valueElem.unmarshal(blk.data[offset:])

		// Return if values match.
		if bytes.Equal(valueElem.value, value) {
			return true
		}

		// Check if we've exceeded the probe distance.
		max := rhh.Dist(rhh.HashKey(valueElem.value), pos, valueN)
		if d > max {
			return false
		}

		// Move position forward.
		pos = (pos + 1) % valueN
		d++

		if d > valueN {
			return false
		}
	}
}
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")
	}
}
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
}
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
}
553165
func decodeSpecBlock(spec *hclspec.Spec, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	switch spec.Block.(type) {

	case *hclspec.Spec_Object:
		return decodeObjectSpec(spec.GetObject())

	case *hclspec.Spec_Array:
		return decodeArraySpec(spec.GetArray())

	case *hclspec.Spec_Attr:
		return decodeAttrSpec(spec.GetAttr(), impliedName)

	case *hclspec.Spec_BlockValue:
		return decodeBlockSpec(spec.GetBlockValue(), impliedName)

	case *hclspec.Spec_BlockAttrs:
		return decodeBlockAttrsSpec(spec.GetBlockAttrs(), impliedName)

	case *hclspec.Spec_BlockList:
		return decodeBlockListSpec(spec.GetBlockList(), impliedName)

	case *hclspec.Spec_BlockSet:
		return decodeBlockSetSpec(spec.GetBlockSet(), impliedName)

	case *hclspec.Spec_BlockMap:
		return decodeBlockMapSpec(spec.GetBlockMap(), impliedName)

	case *hclspec.Spec_Default:
		return decodeDefaultSpec(spec.GetDefault())

	case *hclspec.Spec_Literal:
		return decodeLiteralSpec(spec.GetLiteral())

	default:
		// Should never happen, because the above cases should be exhaustive
		// for our schema.
		var diags hcl.Diagnostics
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid spec block",
			Detail:   fmt.Sprintf("Blocks of type %T are not expected here.", spec.Block),
		})
		return nil, diags
	}
}
1215215
func DepadBlock(paddedBlock []byte) ([]byte, error) {
	totalLen := len(paddedBlock)
	if totalLen < padPrefixSize {
		return nil, errors.WithStack(io.ErrUnexpectedEOF)
	}

	blockLen := binary.LittleEndian.Uint32(paddedBlock)
	blockEndPos := int(blockLen + padPrefixSize)

	if totalLen < blockEndPos {
		return nil, errors.WithStack(
			PaddedBlockReadError{
				ActualLen:   totalLen,
				ExpectedLen: blockEndPos,
			})
	}
	return paddedBlock[padPrefixSize:blockEndPos], nil
}
1012994
func Decode(data []byte) (b *Block, rest []byte) {
	// start begins with a newline. However, at the very beginning of
	// the byte array, we'll accept the start string without it.
	rest = data
	if bytes.HasPrefix(data, start[1:]) {
		rest = rest[len(start)-1:]
	} else if i := bytes.Index(data, start); i >= 0 {
		rest = rest[i+len(start):]
	} else {
		return nil, data
	}

	// Consume the start line.
	_, rest = getLine(rest)

	var line []byte
	b = &Block{
		Headers: make(textproto.MIMEHeader),
	}

	// Next come a series of header lines.
	for {
		// This loop terminates because getLine's second result is
		// always smaller than its argument.
		if len(rest) == 0 {
			return nil, data
		}
		// An empty line marks the end of the headers.
		if line, rest = getLine(rest); len(line) == 0 {
			break
		}

		i := bytes.Index(line, []byte{':'})
		if i == -1 {
			return nil, data
		}

		key, val := line[0:i], line[i+1:]
		key = bytes.TrimSpace(key)
		val = bytes.TrimSpace(val)
		b.Headers.Add(string(key), string(val))
	}

	firstLine := true
	for {
		start := rest

		line, rest = getLine(rest)
		if bytes.Equal(line, endText) {
			// Back up to the start of the line because armor expects to see the
			// header line.
			rest = start
			break
		}

		// The final CRLF isn't included in the hash so we don't write it until
		// we've seen the next line.
		if firstLine {
			firstLine = false
		} else {
			b.Bytes = append(b.Bytes, crlf...)
		}

		if bytes.HasPrefix(line, dashEscape) {
			line = line[2:]
		}
		line = bytes.TrimRight(line, " \t")
		b.Bytes = append(b.Bytes, line...)

		b.Plaintext = append(b.Plaintext, line...)
		b.Plaintext = append(b.Plaintext, lf)
	}

	// We want to find the extent of the armored data (including any newlines at
	// the end).
	i := bytes.Index(rest, end)
	if i == -1 {
		return nil, data
	}
	i += len(end)
	for i < len(rest) && (rest[i] == '\r' || rest[i] == '\n') {
		i++
	}
	armored := rest[:i]
	rest = rest[i:]

	var err error
	b.ArmoredSignature, err = armor.Decode(bytes.NewBuffer(armored))
	if err != nil {
		return nil, data
	}

	return b, rest
}
710487
func DecodeBlock(block []byte, vals []Value) ([]Value, error) {
	if len(block) <= encodedBlockHeaderSize {
		panic(fmt.Sprintf("decode of short block: got %v, exp %v", len(block), encodedBlockHeaderSize))
	}

	blockType, err := BlockType(block)
	if err != nil {
		return nil, err
	}

	switch blockType {
	case BlockFloat64:
		var buf []FloatValue
		decoded, err := DecodeFloatBlock(block, &buf)
		if len(vals) < len(decoded) {
			vals = make([]Value, len(decoded))
		}
		for i := range decoded {
			vals[i] = decoded[i]
		}
		return vals[:len(decoded)], err
	case BlockInteger:
		var buf []IntegerValue
		decoded, err := DecodeIntegerBlock(block, &buf)
		if len(vals) < len(decoded) {
			vals = make([]Value, len(decoded))
		}
		for i := range decoded {
			vals[i] = decoded[i]
		}
		return vals[:len(decoded)], err

	case BlockUnsigned:
		var buf []UnsignedValue
		decoded, err := DecodeUnsignedBlock(block, &buf)
		if len(vals) < len(decoded) {
			vals = make([]Value, len(decoded))
		}
		for i := range decoded {
			vals[i] = decoded[i]
		}
		return vals[:len(decoded)], err

	case BlockBoolean:
		var buf []BooleanValue
		decoded, err := DecodeBooleanBlock(block, &buf)
		if len(vals) < len(decoded) {
			vals = make([]Value, len(decoded))
		}
		for i := range decoded {
			vals[i] = decoded[i]
		}
		return vals[:len(decoded)], err

	case BlockString:
		var buf []StringValue
		decoded, err := DecodeStringBlock(block, &buf)
		if len(vals) < len(decoded) {
			vals = make([]Value, len(decoded))
		}
		for i := range decoded {
			vals[i] = decoded[i]
		}
		return vals[:len(decoded)], err

	default:
		panic(fmt.Sprintf("unknown block type: %d", blockType))
	}
}
1047921
func DecodeUnsignedArrayBlock(block []byte, a *tsdb.UnsignedArray) error {
	blockType := block[0]
	if blockType != BlockUnsigned {
		return fmt.Errorf("invalid block type: exp %d, got %d", BlockUnsigned, blockType)
	}

	tb, vb, err := unpackBlock(block[1:])
	if err != nil {
		return err
	}

	a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps)
	if err != nil {
		return err
	}
	a.Values, err = UnsignedArrayDecodeAll(vb, a.Values)
	return err
}
152199
func (jl *jsonLedger) writeBlock(block *cb.Block) {
	name := jl.blockFilename(block.Header.Number)

	fileLock.Lock()
	defer fileLock.Unlock()

	file, err := os.Create(name)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	err = jl.marshaler.Marshal(file, block)
	logger.Debugf("Wrote block %d", block.Header.Number)
	if err != nil {
		logger.Panicf("Error marshalling with block number [%d]: %s", block.Header.Number, err)
	}
}
201837
func (bd *BinaryDecoder) SetBlock(block *DataBlock) {
	bd.buf = block.Data
	bd.Seek(0)
}
677758
func (od *OpenPGPDecrypter) Decrypt(ed []byte) ([]byte, error) {
	var armoredBlock *armor.Block
	var message *openpgp.MessageDetails
	var plain []byte
	var err error

	if ed == nil {
		return nil, nil
	}

	// Decode the OpenPGP armored block
	armoredBlock, err = armor.Decode(bytes.NewReader(ed))
	if err != nil {
		return nil, err
	}

	// Extract the message from the OpenPGP armored block
	message, err = openpgp.ReadMessage(armoredBlock.Body, od.Keys,
		func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
			kp := []byte(od.passphrase)

			if symmetric {
				return kp, nil
			}

			for _, k := range keys {
				err := k.PrivateKey.Decrypt(kp)
				if err == nil {
					// If no error were returned, we could succesfully
					// decrypt the message using the provided private key
					return nil, nil
				}
			}

			return nil, fmt.Errorf("Unable to decrypt trousseau data store. " +
				"Invalid passphrase supplied.")
		},
		nil)
	if err != nil {
		return nil, fmt.Errorf("unable to decrypt trousseau data store. " +
			"No private key able to decrypt it found in your keyring.")
	}

	// Read the plain message bytes
	plain, err = ioutil.ReadAll(message.UnverifiedBody)
	if err != nil {
		return nil, err
	}

	return plain, err
}