// LoadKeyByUUID loads the key referenced by UUID. The storetype argument
// indicates whether the key should be obtained from the system or user
// stores. It returns a reference to the key and any error.
550280
func (context *Context) LoadKeyByUUID(storetype int, uuid C.TSS_UUID) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_LoadKeyByUUID(context.context, (C.TSS_FLAG)(storetype), uuid, &handle))
	return &Key{handle: handle, context: context.context}, err
}
155897
func (m *Map) Load(key interface{}) (elem interface{}, found bool) {
	m.lock.RLock()
	elem, found = m.data[key]
	m.lock.RUnlock()
	return
}
306593
func (u *CachedUPAKLoader) LoadUPAKWithDeviceID(ctx context.Context, uid keybase1.UID, deviceID keybase1.DeviceID) (*keybase1.UserPlusKeysV2AllIncarnations, error) {
	var info CachedUserLoadInfo
	larg := NewLoadUserByUIDArg(ctx, u.G(), uid).WithPublicKeyOptional()
	upakV2, _, err := u.loadWithInfo(larg, &info, nil, false)
	if err != nil {
		return nil, err
	}

	for _, device := range upakV2.Current.DeviceKeys {
		if device.DeviceID.Eq(deviceID) {
			// Early success, return
			return upakV2, nil
		}
	}

	// Try again with a forced load in case the device is very new.
	larg = larg.WithForcePoll(true)
	upakV2, _, err = u.loadWithInfo(larg, nil, nil, false)
	if err != nil {
		return nil, err
	}
	return upakV2, nil
}
1349790
func (u *CachedUPAKLoader) LoadKeyV2(ctx context.Context, uid keybase1.UID, kid keybase1.KID) (ret *keybase1.UserPlusKeysV2,
	upak *keybase1.UserPlusKeysV2AllIncarnations, key *keybase1.PublicKeyV2NaCl, err error) {
	ctx = WithLogTag(ctx, "LK") // Load key
	defer u.G().CVTraceTimed(ctx, VLog0, fmt.Sprintf("LoadKeyV2 uid:%s,kid:%s", uid, kid), func() error { return err })()
	ctx, tbs := u.G().CTimeBuckets(ctx)
	defer tbs.Record("CachedUPAKLoader.LoadKeyV2")()
	if uid.IsNil() {
		return nil, nil, nil, NoUIDError{}
	}

	argBase := NewLoadUserArg(u.G()).WithUID(uid).WithPublicKeyOptional().WithNetContext(ctx)

	// Make the retry mechanism increasingly aggressive. See CORE-8851.
	// It should be that a ForcePoll is good enough, but in some rare cases,
	// people have cached values for previous pre-reset user incarnations that
	// were incorrect. So clobber over that if it comes to it.
	attempts := []LoadUserArg{
		argBase,
		argBase.WithForcePoll(true),
		argBase.WithForceReload(),
	}

	for i, arg := range attempts {

		if i > 0 {
			u.G().VDL.CLogf(ctx, VLog0, "| reloading with arg: %s", arg.String())
		}

		upak, _, err := u.LoadV2(arg)
		if err != nil {
			return nil, nil, nil, err
		}
		if upak == nil {
			return nil, nil, nil, fmt.Errorf("Nil user, nil error from LoadUser")
		}

		ret, key := upak.FindKID(kid)
		if key != nil {
			u.G().VDL.CLogf(ctx, VLog1, "- found kid in UPAK: %v", ret.Uid)
			return ret, upak, key, nil
		}
	}

	return nil, nil, nil, NotFoundError{Msg: "Not found: Key for user"}
}
1142046
func (k KeybaseServiceMeasured) LoadUserPlusKeys(
	ctx context.Context, uid keybase1.UID, pollForKID keybase1.KID,
	offline keybase1.OfflineAvailability) (userInfo idutil.UserInfo, err error) {
	k.loadUserPlusKeysTimer.Time(func() {
		userInfo, err = k.delegate.LoadUserPlusKeys(
			ctx, uid, pollForKID, offline)
	})
	return userInfo, err
}
249483
func (r *GormWorkItemRepository) LoadByID(ctx context.Context, id uuid.UUID) (*WorkItem, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitem", "loadById"}, time.Now())
	res, err := r.LoadFromDB(ctx, id)
	if err != nil {
		return nil, errs.WithStack(err)
	}
	wiType, err := r.witr.Load(ctx, res.Type)
	if err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}
	return ConvertWorkItemStorageToModel(wiType, res)
}
259661
func (k *KeybaseServiceBase) LoadUserPlusKeys(
	ctx context.Context, uid keybase1.UID, pollForKID keybase1.KID,
	offline keybase1.OfflineAvailability) (idutil.UserInfo, error) {
	cachedUserInfo := k.getCachedUserInfo(uid)
	if cachedUserInfo.Name != kbname.NormalizedUsername("") {
		if pollForKID == keybase1.KID("") {
			return cachedUserInfo, nil
		}
		// Skip the cache if pollForKID isn't present in
		// `VerifyingKeys` or one of the revoked verifying keys.
		for _, key := range cachedUserInfo.VerifyingKeys {
			if key.KID().Equal(pollForKID) {
				return cachedUserInfo, nil
			}
		}

		// Check if the key is revoked, and fill in the merkle info in
		// that case.
		cachedUserInfo, exists, err := k.checkForRevokedVerifyingKey(
			ctx, cachedUserInfo, pollForKID)
		if err != nil {
			return idutil.UserInfo{}, err
		}
		if exists {
			return cachedUserInfo, nil
		}
	}

	arg := keybase1.LoadUserPlusKeysV2Arg{
		Uid:        uid,
		PollForKID: pollForKID,
		Oa:         offline,
	}
	res, err := k.userClient.LoadUserPlusKeysV2(ctx, arg)
	if err != nil {
		return idutil.UserInfo{}, err
	}

	userInfo, err := k.processUserPlusKeys(ctx, res)
	if err != nil {
		return idutil.UserInfo{}, err
	}

	if pollForKID != keybase1.KID("") {
		// Fill in merkle info if we were explicitly trying to load a
		// revoked key.
		userInfo, _, err = k.checkForRevokedVerifyingKey(
			ctx, userInfo, pollForKID)
		if err != nil {
			return idutil.UserInfo{}, err
		}
	}
	return userInfo, nil
}
989452
func (m *GormLabelRepository) Load(ctx context.Context, ID uuid.UUID) (*Label, error) {
	defer goa.MeasureSince([]string{"goa", "db", "label", "show"}, time.Now())
	lbl := Label{}
	tx := m.db.Where("id = ?", ID).First(&lbl)
	if tx.RecordNotFound() {
		log.Error(ctx, map[string]interface{}{
			"label_id": ID.String(),
		}, "state or known referer was empty")
		return nil, errors.NewNotFoundError("label", ID.String())
	}
	if tx.Error != nil {
		log.Error(ctx, map[string]interface{}{
			"err":      tx.Error,
			"label_id": ID.String(),
		}, "unable to load the label by ID")
		return nil, errors.NewInternalError(ctx, tx.Error)
	}
	return &lbl, nil
}
493388
func (s *CertFileUserStore) Load(key msp.IdentityIdentifier) (*msp.UserData, error) {
	cert, err := s.store.Load(storeKeyFromUserIdentifier(key))
	if err != nil {
		if err == core.ErrKeyValueNotFound {
			return nil, msp.ErrUserNotFound
		}
		return nil, err
	}
	certBytes, ok := cert.([]byte)
	if !ok {
		return nil, errors.New("user is not of proper type")
	}
	userData := &msp.UserData{
		MSPID:                 key.MSPID,
		ID:                    key.ID,
		EnrollmentCertificate: certBytes,
	}
	return userData, nil
}
1090300
func (t *Table) loadKeys(db *sql.DB) error {
	rows, err := db.Query("SHOW INDEX FROM " + t.Name)
	if err != nil {
		return err
	}
	defer rows.Close()

	cols, err := rows.Columns()
	if err != nil {
		return err
	}

	var (
		nonUnique bool
		keyName   string
		seq       int
		colName   string
	)
	m := map[string]interface{}{
		"Non_unique":   &nonUnique,
		"Key_name":     &keyName,
		"Seq_in_index": &seq,
		"Column_name":  &colName,
	}

	vals := make([]interface{}, len(cols))
	for i, n := range cols {
		if v, ok := m[n]; ok {
			vals[i] = v
		} else {
			vals[i] = &sql.RawBytes{}
		}
	}

	keys := map[string][]keyColumn{}
	for rows.Next() {
		err := rows.Scan(vals...)
		if err != nil {
			return err
		}
		keys[keyName] = append(keys[keyName], keyColumn{
			seq:  seq,
			name: colName,
		})

		if _, ok := t.KeyMap[keyName]; !ok {
			k := &Key{
				Name:   keyName,
				Unique: !nonUnique,
			}
			t.Keys = append(t.Keys, k)
			t.KeyMap[keyName] = k
		}
	}

	for n, k := range keys {
		sort.Sort(bySeq(k))
		var cols []*Column
		for _, c := range k {
			cols = append(cols, t.ColumnMap[c.name])
		}
		t.KeyMap[n].Columns = cols
	}

	t.PrimaryKey = t.KeyMap["PRIMARY"]
	if t.PrimaryKey != nil {
		t.PrimaryKey.Primary = true
	}

	return nil
}
245321
func (u *CachedUPAKLoader) LookupUID(ctx context.Context, un NormalizedUsername) (keybase1.UID, error) {
	m := NewMetaContext(ctx, u.G())
	rres := u.G().Resolver.Resolve(m, un.String())
	if err := rres.GetError(); err != nil {
		return keybase1.UID(""), err
	}
	un2, err := u.LookupUsername(ctx, rres.GetUID())
	if err != nil {
		return keybase1.UID(""), err
	}
	if !un.Eq(un2) {
		m.Warning("Unexpected mismatched usernames (uid=%s): %s != %s", rres.GetUID(), un.String(), un2.String())
		return keybase1.UID(""), NewBadUsernameError(un.String())
	}
	return rres.GetUID(), nil
}
101647
func (tl TypeLoader) LoadTableForeignKeys(args *ArgType, tableMap map[string]*Type, typeTpl *Type, fkMap map[string]*ForeignKey) error {
	var err error

	// load foreign keys
	foreignKeyList, err := tl.ForeignKeyList(args.DB, args.Schema, typeTpl.Table.TableName)
	if err != nil {
		return err
	}

	// loop over foreign keys for table
	for _, fk := range foreignKeyList {
		var refTpl *Type
		var col, refCol *Field

	colLoop:
		// find column
		for _, f := range typeTpl.Fields {
			if f.Col.ColumnName == fk.ColumnName {
				col = f
				break colLoop
			}
		}

	refTplLoop:
		// find ref table
		for _, t := range tableMap {
			if t.Table.TableName == fk.RefTableName {
				refTpl = t
				break refTplLoop
			}
		}

	refColLoop:
		// find ref column
		for _, f := range refTpl.Fields {
			if f.Col.ColumnName == fk.RefColumnName {
				refCol = f
				break refColLoop
			}
		}

		// no ref col, but have ref tpl, so use primary key
		if refTpl != nil && refCol == nil {
			refCol = refTpl.PrimaryKey
		}

		// check everything was found
		if col == nil || refTpl == nil || refCol == nil {
			return errors.New("could not find col, refTpl, or refCol")
		}

		// foreign key name
		if fk.ForeignKeyName == "" {
			fk.ForeignKeyName = typeTpl.Table.TableName + "_" + col.Col.ColumnName + "_fkey"
		}

		// create foreign key template
		fkMap[fk.ForeignKeyName] = &ForeignKey{
			Schema:     args.Schema,
			Type:       typeTpl,
			Field:      col,
			RefType:    refTpl,
			RefField:   refCol,
			ForeignKey: fk,
		}
	}

	return nil
}
457236
func LookupUID(uid int) (user.User, error) {
	// first try a local system files lookup using existing capabilities
	usr, err := user.LookupUid(uid)
	if err == nil {
		return usr, nil
	}
	// local files lookup failed; attempt to call `getent` to query configured passwd dbs
	return getentUser(fmt.Sprintf("%s %d", "passwd", uid))
}
1145664
func LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) {
	loadedData, err := ioutil.ReadFile(keyPath)
	// Call verifyKeyData to ensure the file wasn't empty/corrupt.
	if err == nil && verifyKeyData(loadedData) {
		return loadedData, false, err
	}
	if !os.IsNotExist(err) {
		return nil, false, fmt.Errorf("error loading key from %s: %v", keyPath, err)
	}

	generatedData, err := MakeEllipticPrivateKeyPEM()
	if err != nil {
		return nil, false, fmt.Errorf("error generating key: %v", err)
	}
	if err := WriteKey(keyPath, generatedData); err != nil {
		return nil, false, fmt.Errorf("error writing key to %s: %v", keyPath, err)
	}
	return generatedData, true, nil
}
481123
func (r *GormWorkItemTypeRepository) Load(ctx context.Context, id uuid.UUID) (*WorkItemType, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitemtype", "load"}, time.Now())
	log.Debug(ctx, map[string]interface{}{
		"wit_id": id,
	}, "Loading work item type")
	res, ok := cache.Get(id)
	if !ok {
		log.Info(ctx, map[string]interface{}{
			"wit_id": id,
		}, "Work item type doesn't exist in the cache. Loading from DB...")
		res = WorkItemType{}

		db := r.db.Model(&res).Where("id=?", id).First(&res)
		if db.RecordNotFound() {
			log.Error(ctx, map[string]interface{}{
				"wit_id": id,
			}, "work item type not found")
			return nil, errors.NewNotFoundError("work item type", id.String())
		}
		if err := db.Error; err != nil {
			return nil, errors.NewInternalError(ctx, err)
		}
		childTypes, err := r.loadChildTypeList(ctx, res.ID)
		if err != nil {
			return nil, errs.Wrapf(err, `failed to load child types for WIT "%s" (%s)`, res.Name, res.ID)
		}
		res.ChildTypeIDs = childTypes
		cache.Put(res)
	}
	return &res, nil
}
597128
func LoadPublicKey(prefs *Preferences) (*PublicKey, error) {
	filePath := prefs.Core.PublicKeyFile

	var fd io.Reader
	var err error

	if filePath == "" {
		var b []byte
		b, err = data.Asset("data/public_key.json")

		if err == nil {
			fd = bytes.NewReader(b)
		}
	} else {
		fd, err = readPublicKeyFile(filePath)
	}

	if err != nil {
		return nil, err
	}

	key, err := parsePublicKeyFile(fd)
	if err != nil {
		return nil, err
	}

	return key, nil
}
643174
func LoadTokenVerifyKey() error {
	tokenVerifyKeyPath := os.Getenv(EnvTokenVerifyKey)
	if tokenVerifyKeyPath == "" {
		tokenVerifyKeyPath = TokenVerifyKeyDefault
	}
	tokenVerifyKeyPem, err := ioutil.ReadFile(tokenVerifyKeyPath)
	if err != nil {
		return err
	}
	pemBlock, _ := pem.Decode(tokenVerifyKeyPem)
	if pemBlock.Type != "PUBLIC KEY" {
		return errors.New("Key type was not PUBLIC KEY")
	}
	tokenVerifyKey, err := x509.ParsePKIXPublicKey(pemBlock.Bytes)
	if err != nil {
		return err
	}
	var ok bool
	TokenVerifyKey, ok = tokenVerifyKey.(*rsa.PublicKey)
	if !ok {
		return errors.New(tokenVerifyKeyPath + " could not be loaded")
	}
	return nil
}