// Create a ledger key for a redeem output in a token transaction, as a function of
// the transaction ID, and the index of the output
170801
func createRedeemKey(txID string, index int) (string, error) {
	return createCompositeKey(tokenRedeem, []string{txID, strconv.Itoa(index)})
}
150129
func (p *Params) Generate(id string) string {
	buf := make([]byte, dataSize, dataSize+macSize)
	binary.BigEndian.PutUint32(buf, uint32(p.timer().Unix()))
	token := append(buf, hmacSHA256(p.key, buf, id)...)
	return base64.URLEncoding.EncodeToString(token)
}
1328438
func (c *Client) KeyCreate(publicKey string) (*Key, error) {
	params := struct {
		PublicKey string `json:"public_key"`
	}{
		PublicKey: publicKey,
	}
	var keyRes Key
	return &keyRes, c.Post(&keyRes, "/account/keys", params)
}
1058121
func (instance *PublicKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) {
	if err := AssertPublicKeyAndTokenCombination(instance.publicKey, token); err != nil {
		return nil, err
	}
	return instance.publicKey, nil
}
939124
func createMultiSig(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
	cmd := icmd.(*btcjson.CreateMultisigCmd)

	script, err := makeMultiSigScript(w, cmd.Keys, cmd.NRequired)
	if err != nil {
		return nil, ParseError{err}
	}

	address, err := btcutil.NewAddressScriptHash(script, w.ChainParams())
	if err != nil {
		// above is a valid script, shouldn't happen.
		return nil, err
	}

	return btcjson.CreateMultiSigResult{
		Address:      address.EncodeAddress(),
		RedeemScript: hex.EncodeToString(script),
	}, nil
}
1149621
func ExportPrivateKey(ctx context.Context, c *cli.Context) error {
	if err := initCrypto(); err != nil {
		return action.ExitError(ctx, action.ExitUnknown, err, "failed to init XC")
	}

	id := c.String("id")
	file := c.String("file")

	if id == "" {
		return action.ExitError(ctx, action.ExitUsage, nil, "need id")
	}
	if file == "" {
		return action.ExitError(ctx, action.ExitUsage, nil, "need file")
	}

	if fsutil.IsFile(file) {
		return action.ExitError(ctx, action.ExitUnknown, nil, "output file already exists")
	}

	pk, err := crypto.ExportPrivateKey(ctx, id)
	if err != nil {
		return action.ExitError(ctx, action.ExitUnknown, err, "failed to export key: %s", err)
	}

	if err := ioutil.WriteFile(file, pk, 0600); err != nil {
		return action.ExitError(ctx, action.ExitIO, err, "failed to write file")
	}
	return nil
}
559406
func createSpentDelegatedOutputKey(txID string, index int) (string, error) {
	return createCompositeKey(tokenDelegatedInput, []string{txID, strconv.Itoa(index)})
}
138747
func (sbc *SandboxConn) CreateTransaction(ctx context.Context, target *querypb.Target, dtid string, participants []*querypb.Target) (err error) {
	sbc.CreateTransactionCount.Add(1)
	if sbc.MustFailCreateTransaction > 0 {
		sbc.MustFailCreateTransaction--
		return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "error: err")
	}
	return sbc.getError()
}
1251366
func (a *ACLTokens) Create(token *ACLToken, q *WriteOptions) (*ACLToken, *WriteMeta, error) {
	if token.AccessorID != "" {
		return nil, nil, fmt.Errorf("cannot specify Accessor ID")
	}
	var resp ACLToken
	wm, err := a.client.write("/v1/acl/token", token, &resp, q)
	if err != nil {
		return nil, nil, err
	}
	return &resp, wm, nil
}
1303687
func (x *XC) CreatePrivateKeyBatch(ctx context.Context, name, email, passphrase string) error {
	k, err := keyring.GenerateKeypair(passphrase)
	if err != nil {
		return errors.Wrapf(err, "failed to generate keypair: %s", err)
	}
	k.Identity.Name = name
	k.Identity.Email = email
	if err := x.secring.Set(k); err != nil {
		return errors.Wrapf(err, "failed to set %v to secring: %s", k, err)
	}
	return x.secring.Save()
}
1310260
func (m *GormTokenRepository) Create(ctx context.Context, token *Token) error {
	defer goa.MeasureSince([]string{"goa", "db", "token", "create"}, time.Now())

	// If no identifier has been specified for the new token, then generate one
	if token.TokenID == uuid.Nil {
		token.TokenID = uuid.NewV4()
	}

	err := m.db.Create(token).Error
	if err != nil {
		if gormsupport.IsUniqueViolation(err, "token_pkey") {
			return errors.NewDataConflictError(fmt.Sprintf("token with ID %s already exists", token.TokenID))
		}

		log.Error(ctx, map[string]interface{}{
			"token_id": token.TokenID,
			"err":      err,
		}, "unable to create the token")
		return errs.WithStack(err)
	}

	log.Info(ctx, map[string]interface{}{
		"token_id": token.TokenID,
	}, "Token created!")
	return nil
}
979389
func (pq *PriorityQueue) generateKey(priority uint8, id uint64) []byte {
	// prefix + key = 2 + 8 = 10
	key := make([]byte, 10)
	copy(key[0:2], pq.generatePrefix(priority))
	copy(key[2:], idToKey(id))
	return key
}
169875
func GenerateToken(claims map[string]interface{}, expiration time.Time) (s string, err error) {
	t := jwt.New(jwt.GetSigningMethod("RS256"))
	t.Header["typ"] = "JWT"
	t.Header["alg"] = "RS256"
	t.Header["kid"] = pubKeyId
	claims["exp"] = expiration.Unix()
	t.Claims = jwt.MapClaims(claims)
	privKey, err := jwt.ParseRSAPrivateKeyFromPEM(privKeyPEMEncoded)
	if err != nil {
		return "", err
	}
	return t.SignedString(privKey)
}
321384
func (instance *LazyHmacKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) {
	err := instance.loadIfRequired()
	if err != nil {
		return nil, err
	}
	if err := AssertHmacToken(token); err != nil {
		return nil, err
	}
	return instance.secret, nil
}
632895
func Create(in Input) (res Output, err error) {
	_, _, senderKp, err := libkb.ParseStellarSecretKey(string(in.From))
	if err != nil {
		return res, err
	}
	senderSeed, err := stellarnet.NewSeedStr(senderKp.Seed())
	if err != nil {
		return res, err
	}
	relayKp, err := keypair.Random()
	if err != nil {
		return res, err
	}
	relayAccountID, err := stellarnet.NewAddressStr(relayKp.Address())
	if err != nil {
		return res, err
	}
	sig, err := stellarnet.CreateAccountXLMTransaction(senderSeed, relayAccountID, in.AmountXLM,
		in.PublicMemo, in.SeqnoProvider, in.Timebounds, in.BaseFee)
	if err != nil {
		return res, err
	}
	enc, err := Encrypt(stellar1.RelayContents{
		StellarID: stellar1.TransactionID(sig.TxHash),
		Sk:        stellar1.SecretKey(relayKp.Seed()),
		Note:      in.Note,
	}, in.EncryptFor)
	if err != nil {
		return res, err
	}
	pack, err := libkb.MsgpackEncode(enc)
	if err != nil {
		return res, err
	}
	return Output{
		RelayAccountID: stellar1.AccountID(relayKp.Address()),
		EncryptedB64:   base64.StdEncoding.EncodeToString(pack),
		FundTx:         sig,
	}, nil
}
685100
func (w *WalletKit) DeriveKey(ctx context.Context,
	req *signrpc.KeyLocator) (*signrpc.KeyDescriptor, error) {

	keyDesc, err := w.cfg.KeyRing.DeriveKey(keychain.KeyLocator{
		Family: keychain.KeyFamily(req.KeyFamily),
		Index:  uint32(req.KeyIndex),
	})
	if err != nil {
		return nil, err
	}

	return &signrpc.KeyDescriptor{
		KeyLoc: &signrpc.KeyLocator{
			KeyFamily: int32(keyDesc.Family),
			KeyIndex:  int32(keyDesc.Index),
		},
		RawKeyBytes: keyDesc.PubKey.SerializeCompressed(),
	}, nil
}
1266508
func (v *Verifier) commitTransferAction(transferAction *token.PlainTransfer, txID string, simulator ledger.LedgerWriter) error {
	var outputID string
	var err error
	for i, output := range transferAction.GetOutputs() {
		if output.Owner != nil {
			outputID, err = createOutputKey(txID, i)
		} else {
			outputID, err = createRedeemKey(txID, i)
		}
		if err != nil {
			return &customtx.InvalidTxError{Msg: fmt.Sprintf("error creating output ID: %s", err)}
		}

		err = v.addOutput(outputID, output, simulator)
		if err != nil {
			return err
		}
	}
	return v.markInputsSpent(txID, transferAction.GetInputs(), simulator)
}