// newKeyValueFromJSONConfig returns a KeyValue implementation on top of a
// github.com/syndtr/goleveldb/leveldb file.
777731
func newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) {
	file := cfg.RequiredString("file")
	if err := cfg.Validate(); err != nil {
		return nil, err
	}
	strictness := opt.DefaultStrict
	if env.IsDev() {
		// Be more strict in dev mode.
		strictness = opt.StrictAll
	}
	opts := &opt.Options{
		// The default is 10,
		// 8 means 2.126% or 1/47th disk check rate,
		// 10 means 0.812% error rate (1/2^(bits/1.44)) or 1/123th disk check rate,
		// 12 means 0.31% or 1/322th disk check rate.
		// TODO(tgulacsi): decide which number is the best here. Till that go with the default.
		Filter: filter.NewBloomFilter(10),
		Strict: strictness,
	}
	db, err := leveldb.OpenFile(file, opts)
	if err != nil {
		return nil, err
	}
	is := &kvis{
		db:       db,
		path:     file,
		opts:     opts,
		readOpts: &opt.ReadOptions{Strict: strictness},
		// On machine crash we want to reindex anyway, and
		// fsyncs may impose great performance penalty.
		writeOpts: &opt.WriteOptions{Sync: false},
	}
	return is, nil
}
1107566
func (b *Builder) AddKeyValuesFromIterator(it *ObjectIterator) error {
	if b.stack.IsEmpty() {
		return WithStack(BuilderNeedOpenObjectError)
	}
	tos, _ := b.stack.Tos()
	h := b.buf[tos]
	if h != 0x0b && h != 0x14 {
		return WithStack(BuilderNeedOpenObjectError)
	}
	if b.keyWritten {
		return WithStack(BuilderKeyAlreadyWrittenError)
	}
	for it.IsValid() {
		k, err := it.Key(true)
		if err != nil {
			return WithStack(err)
		}
		key, err := k.GetString()
		if err != nil {
			return WithStack(err)
		}
		v, err := it.Value()
		if err != nil {
			return WithStack(err)
		}
		if err := b.addInternalKeyValue(key, NewSliceValue(v)); err != nil {
			return WithStack(err)
		}
		if err := it.Next(); err != nil {
			return WithStack(err)
		}
	}
	return nil
}
442551
func NewMissingConfigValue(key, field string) error {
	return NewInvalidConfigValueError(key, "", errors.New("missing "+field))
}
760101
func NewKeyFromString(key string) (*ExtendedKey, error) {
	// The base58-decoded extended key must consist of a serialized payload
	// plus an additional 4 bytes for the checksum.
	decoded := base58.Decode(key)
	if len(decoded) != serializedKeyLen+4 {
		return nil, ErrInvalidKeyLen
	}

	// The serialized format is:
	//   version (4) || depth (1) || parent fingerprint (4)) ||
	//   child num (4) || chain code (32) || key data (33) || checksum (4)

	// Split the payload and checksum up and ensure the checksum matches.
	payload := decoded[:len(decoded)-4]
	checkSum := decoded[len(decoded)-4:]
	expectedCheckSum := chainhash.DoubleHashB(payload)[:4]
	if !bytes.Equal(checkSum, expectedCheckSum) {
		return nil, ErrBadChecksum
	}

	// Deserialize each of the payload fields.
	version := payload[:4]
	depth := payload[4:5][0]
	parentFP := payload[5:9]
	childNum := binary.BigEndian.Uint32(payload[9:13])
	chainCode := payload[13:45]
	keyData := payload[45:78]

	// The key data is a private key if it starts with 0x00.  Serialized
	// compressed pubkeys either start with 0x02 or 0x03.
	isPrivate := keyData[0] == 0x00
	if isPrivate {
		// Ensure the private key is valid.  It must be within the range
		// of the order of the secp256k1 curve and not be 0.
		keyData = keyData[1:]
		keyNum := new(big.Int).SetBytes(keyData)
		if keyNum.Cmp(btcec.S256().N) >= 0 || keyNum.Sign() == 0 {
			return nil, ErrUnusableSeed
		}
	} else {
		// Ensure the public key parses correctly and is actually on the
		// secp256k1 curve.
		_, err := btcec.ParsePubKey(keyData, btcec.S256())
		if err != nil {
			return nil, err
		}
	}

	return NewExtendedKey(version, keyData, chainCode, parentFP, depth,
		childNum, isPrivate), nil
}
602707
func NewCloneDatabaseValue(db *Database) *CreateDatabaseValue {
	return &CreateDatabaseValue{
		DatabaseName:    db.Remark.DBConf.Common.DatabaseName,
		DatabaseVersion: db.Remark.DBConf.Common.DatabaseVersion,
		SourceAppliance: NewResource(db.ID),
	}
}
983542
func NewKeyValuePair(pos position, key, ws string, value *string, comment *Comment) *KeyValuePair {
	return &KeyValuePair{
		pos: pos,

		key:     key,
		ws:      ws,
		value:   value,
		comment: comment,
	}
}
230283
func newIndex(root string, indexConf jsonconfig.Obj) (sorted.KeyValue, error) {
	if len(indexConf) > 0 {
		return sorted.NewKeyValueMaybeWipe(indexConf)
	}
	return sorted.NewKeyValueMaybeWipe(jsonconfig.Obj{
		"type": defaultIndexType,
		"file": filepath.Join(root, defaultIndexFile),
	})
}
10079
func NewMemoryKeyValue() KeyValue {
	db := memdb.New(comparer.DefaultComparer, 128)
	return &memKeys{db: db}
}
970049
func NewKeyValue(host *Host, name string) (*KeyValue, error) {
	kv := &KeyValue{host, name}
	query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (%s %s, %s %s)", name, keyCol, defaultStringType, valCol, defaultStringType)
	if _, err := kv.host.db.Exec(query); err != nil {
		return nil, err
	}
	if Verbose {
		log.Println("Created table " + name + " in database " + host.dbname)
	}
	return kv, nil

}
510748
func (c *Config) NewKey(k string) Key {
	return c.KeyParser.Parse(k)
}
1276752
func (b *BoltCreator) NewKeyValue(id string) (pinterface.IKeyValue, error) {
	return NewKeyValue(b.db, id)
}
1341324
func (kv KeyVal) NewValue(newval string) KeyVal {
	return KeyVal(fmt.Sprintf("%s=%s", kv.Keyword(), newval))
}
1119706
func NewKeyObject(key interface{}, expiryTime int64) KeyObject {
	k := KeyObject{
		Key: key,
	}
	if expiryTime >= 0 {
		k.ExpiryTime = time.Unix(expiryTime/1000, 0).UTC()
	}

	return k
}
682542
func NewConfig() Config {
	cfg := make(Config)
	cfg[Globals] = make(map[GlobalOption]string)
	return cfg
}
1267434
func NewValue(val interface{}, err error) Value {
	confVal := new(configValue)
	confVal.value = val
	confVal.err = err
	return confVal
}
785185
func NewConfig(torusRoot string) (*Config, error) {
	preferences, err := prefs.NewPreferences()
	if err != nil {
		return nil, err
	}

	publicKey, err := prefs.LoadPublicKey(preferences)
	if err != nil {
		return nil, fmt.Errorf("failed to load public key")
	}

	caBundle, err := loadCABundle(preferences.Core.CABundleFile)
	if err != nil {
		return nil, err
	}

	registryURI, err := url.Parse(preferences.Core.RegistryURI)
	if err != nil {
		return nil, fmt.Errorf("invalid registry_uri")
	}

	manifestURI, err := url.Parse(preferences.Core.ManifestURI)
	if err != nil {
		return nil, fmt.Errorf("invalid manifest_uri")
	}

	_, _, err = net.SplitHostPort(preferences.Core.GatekeeperAddress)
	if err != nil {
		return nil, fmt.Errorf("invalid gatekeeper listener address")
	}

	cfg := &Config{
		APIVersion: apiVersion,
		Version:    Version,

		TorusRoot:         torusRoot,
		PidPath:           path.Join(torusRoot, "daemon.pid"),
		GatekeeperPidPath: path.Join(torusRoot, "gateway.pid"),
		DBPath:            path.Join(torusRoot, "daemon.db"),
		LastUpdatePath:    path.Join(torusRoot, "last_update"),

		RegistryURI:       registryURI,
		ManifestURI:       manifestURI,
		GatekeeperAddress: preferences.Core.GatekeeperAddress,
		CABundle:          caBundle,
		PublicKey:         publicKey,
	}

	// set OS specific transport address
	setTransportAddress(cfg)

	return cfg, nil
}
865875
func NewDefaultConfig() (*Config, error) {
	c := newConfig()

	err := normalize(c)
	if err != nil {
		return nil, err
	}

	return c, nil
}