// V3 is just V2 but with exploding messages support. V4 is just V3, but it
// signs with the zero key when pairwise MACs are included.
434739
func (b *Boxer) boxV2orV3orV4(ctx context.Context, messagePlaintext chat1.MessagePlaintext,
	baseEncryptionKey types.CryptKey, ephemeralSeed *keybase1.TeamEk, signingKeyPair libkb.NaclSigningKeyPair,
	version chat1.MessageBoxedVersion, pairwiseMACRecipients []keybase1.KID) (res chat1.MessageBoxed, err error) {

	if messagePlaintext.ClientHeader.MerkleRoot == nil {
		return res, NewBoxingError("cannot send message without merkle root", false)
	}
	headerEncryptionKey, err := libkb.DeriveSymmetricKey(
		libkb.NaclSecretBoxKey(baseEncryptionKey.Material()), libkb.EncryptionReasonChatMessage)
	if err != nil {
		return res, err
	}

	// Regular messages use the same encryption key for the header and for the
	// body. Exploding messages use a derived ephemeral key for the body.
	bodyEncryptionKey := headerEncryptionKey
	if messagePlaintext.IsEphemeral() {
		bodyEncryptionKey, err = libkb.DeriveFromSecret(ephemeralSeed.Seed, libkb.DeriveReasonTeamEKExplodingChat)
		if err != nil {
			return res, err
		}
		// The MessagePlaintext supplied by the caller has a Lifetime, but we
		// expect the Generation is left uninitialized, and we set it here.
		messagePlaintext.ClientHeader.EphemeralMetadata.Generation = ephemeralSeed.Metadata.Generation
	}

	bodyVersioned := chat1.NewBodyPlaintextWithV1(chat1.BodyPlaintextV1{
		MessageBody: messagePlaintext.MessageBody,
	})
	bodyEncrypted, err := b.seal(bodyVersioned, bodyEncryptionKey)
	if err != nil {
		return res, err
	}

	bodyHash, err := b.makeBodyHash(*bodyEncrypted)
	if err != nil {
		return res, err
	}

	// create the v1 header, adding hash
	headerVersioned := chat1.NewHeaderPlaintextWithV1(chat1.HeaderPlaintextV1{
		Conv:              messagePlaintext.ClientHeader.Conv,
		TlfName:           messagePlaintext.ClientHeader.TlfName,
		TlfPublic:         messagePlaintext.ClientHeader.TlfPublic,
		MessageType:       messagePlaintext.ClientHeader.MessageType,
		Prev:              messagePlaintext.ClientHeader.Prev,
		Sender:            messagePlaintext.ClientHeader.Sender,
		SenderDevice:      messagePlaintext.ClientHeader.SenderDevice,
		BodyHash:          bodyHash,
		MerkleRoot:        messagePlaintext.ClientHeader.MerkleRoot,
		OutboxInfo:        messagePlaintext.ClientHeader.OutboxInfo,
		OutboxID:          messagePlaintext.ClientHeader.OutboxID,
		KbfsCryptKeysUsed: messagePlaintext.ClientHeader.KbfsCryptKeysUsed,
		EphemeralMetadata: messagePlaintext.ClientHeader.EphemeralMetadata,
		// In MessageBoxed.V2 HeaderSignature is nil.
		HeaderSignature: nil,
	})

	// signencrypt the header
	headerSealed, err := b.signEncryptMarshal(headerVersioned, headerEncryptionKey,
		signingKeyPair, kbcrypto.SignaturePrefixChatMBv2)
	if err != nil {
		return res, err
	}

	// Make pairwise MACs if there are any pairwise recipients supplied. Note
	// that we still sign+encrypt with a signing key above. If we want
	// repudiability, it's the caller's responsibility to provide a zero
	// signing key or similar. Signing with a real key and also MAC'ing is
	// redundant, but it will let us test the MAC code in prod in a backwards
	// compatible way.
	if len(pairwiseMACRecipients) > 0 {
		pairwiseMACs, err := b.makeAllPairwiseMACs(ctx, headerSealed, pairwiseMACRecipients)
		if err != nil {
			return res, err
		}
		messagePlaintext.ClientHeader.PairwiseMacs = pairwiseMACs
	}

	// verify
	verifyKey := signingKeyPair.GetBinaryKID()

	return chat1.MessageBoxed{
		Version:          version,
		ServerHeader:     nil,
		ClientHeader:     messagePlaintext.ClientHeader,
		HeaderCiphertext: headerSealed.AsSealed(),
		BodyCiphertext:   *bodyEncrypted,
		VerifyKey:        verifyKey,
		KeyGeneration:    baseEncryptionKey.Generation(),
	}, nil
}
867984
func (p *ProvisionTokenV1) V2() *ProvisionTokenV2 {
	t := &ProvisionTokenV2{
		Kind:    KindToken,
		Version: V2,
		Metadata: Metadata{
			Name:      p.Token,
			Namespace: defaults.Namespace,
		},
		Spec: ProvisionTokenSpecV2{
			Roles: p.Roles,
		},
	}
	if !p.Expires.IsZero() {
		t.SetExpiry(p.Expires)
	}
	return t
}
100808
func (m *msg) setVersion(v int) {
	m.LiVnMode = (m.LiVnMode & 0xc7) | uint8(v)<<3
}
1250744
func formatXLMigrateV2ToV3(export string) error {
	formatPath := pathJoin(export, minioMetaBucket, formatConfigFile)
	version, err := formatXLGetVersion(formatPath)
	if err != nil {
		return err
	}
	if version != formatXLVersionV2 {
		return fmt.Errorf(`Disk %s: format version expected %s, found %s`, export, formatXLVersionV2, version)
	}
	formatV2 := &formatXLV2{}
	b, err := ioutil.ReadFile(formatPath)
	if err != nil {
		return err
	}
	err = json.Unmarshal(b, formatV2)
	if err != nil {
		return err
	}

	if err = removeAll(pathJoin(export, minioMetaMultipartBucket)); err != nil {
		return err
	}

	if err = mkdirAll(pathJoin(export, minioMetaMultipartBucket), 0755); err != nil {
		return err
	}

	// format-V2 struct is exactly same as format-V1 except that version is "3"
	// which indicates the simplified multipart backend.
	formatV3 := formatXLV3{}

	formatV3.Version = formatV2.Version
	formatV3.Format = formatV2.Format
	formatV3.XL = formatV2.XL

	formatV3.XL.Version = formatXLVersionV3

	b, err = json.Marshal(formatV3)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(formatPath, b, 0644)
}
344308
func DeserializeTLFReaderKeyBundleV3(codec kbfscodec.Codec, path string) (
	TLFReaderKeyBundleV3, error) {
	var rkb TLFReaderKeyBundleV3
	err := kbfscodec.DeserializeFromFile(codec, path, &rkb)
	if err != nil {
		return TLFReaderKeyBundleV3{}, err
	}
	if len(rkb.Keys) == 0 {
		rkb.Keys = make(UserDeviceKeyInfoMapV3)
	}
	return rkb, nil
}
169005
func migrateConfigV3ToV4() {
	if !isMcConfigExists() {
		return
	}
	mcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV3())
	fatalIf(probe.NewError(e), "Unable to load mc config V2.")

	// update to newer version
	if mcCfgV3.Version() != "3" {
		return
	}

	cfgV4 := newConfigV4()
	for k, v := range mcCfgV3.Data().(*configV3).Aliases {
		cfgV4.Aliases[k] = v
	}
	// New hostConfig has API signature. All older entries were V4
	// only. So it is safe to assume V4 as default for all older
	// entries.
	// HostConfigV4 als uses JavaScript naming notation for struct JSON tags.
	for host, hostCfgV3 := range mcCfgV3.Data().(*configV3).Hosts {
		cfgV4.Hosts[host] = hostConfigV4{
			AccessKeyID:     hostCfgV3.AccessKeyID,
			SecretAccessKey: hostCfgV3.SecretAccessKey,
			Signature:       "v4",
		}
	}

	mcNewCfgV4, e := quick.NewConfig(cfgV4, nil)
	fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `4`.")

	e = mcNewCfgV4.Save(mustGetMcConfigPath())
	fatalIf(probe.NewError(e), "Unable to save config version `4`.")

	console.Infof("Successfully migrated %s from version `3` to version `4`.\n", mustGetMcConfigPath())

}
428019
func (vu versionUnifier) pairVersion(id ProjectIdentifier, v UnpairedVersion) PairedVersion {
	vl, err := vu.b.listVersions(id)
	if err != nil {
		return nil
	}

	vu.mtr.push("b-pair-version")
	// doing it like this is a bit sloppy
	for _, v2 := range vl {
		if p, ok := v2.(PairedVersion); ok {
			if p.Matches(v) {
				vu.mtr.pop()
				return p
			}
		}
	}

	vu.mtr.pop()
	return nil
}
813675
func NewStaticV4(id, secret, token string) *Credentials {
	return NewStatic(id, secret, token, SignatureV4)
}
1229676
func (s *server) signAndInsertTriples(triples []*protocol.Triple, key *crypto.PrivateKey) error {
	hashes := make(map[uint64][]*protocol.Triple)
	unix := time.Now().Unix()
	for _, triple := range triples {
		if err := key.SignTriple(triple); err != nil {
			return err
		}
		triple.Created = unix
		hash := murmur3.Sum64([]byte(triple.Subj))
		hashes[hash] = append(hashes[hash], triple)
	}

	for hash, triples := range hashes {
		msg := &protocol.Message{
			Message: &protocol.Message_InsertTriples{
				InsertTriples: &protocol.InsertTriples{
					Triples: triples,
				}},
			Gossip: true,
		}
		currentKeyspace := s.network.LocalPeer().Keyspace.Includes(hash)
		if err := s.network.Broadcast(&hash, msg); currentKeyspace && err == network.ErrNoRecipients {
		} else if err != nil {
			return err
		}
		if currentKeyspace {
			s.ts.Insert(triples)
		}
	}
	return nil
}
1094760
func (o *Generator) NewV3(namespace Implementation, names ...interface{}) UUID {
	id := UUID{}
	id.unmarshal(digest(md5.New(), namespace.Bytes(), names...))
	id.setRFC4122Version(VersionThree)
	return id
}
908422
func sb3Inv(r0, r1, r2, r3 *uint32) {
	r4 := *r2
	*r2 ^= *r1
	*r0 ^= *r2
	r4 &= *r2
	r4 ^= *r0
	*r0 &= *r1
	*r1 ^= *r3
	*r3 |= r4
	*r2 ^= *r3
	*r0 ^= *r3
	*r1 ^= r4
	*r3 &= *r2
	*r3 ^= *r1
	*r1 ^= *r0
	*r1 |= *r2
	*r0 ^= *r3
	*r1 ^= r4
	*r0 ^= *r1
	//return *r2, *r1, *r3, *r0
	r4 = *r0
	*r0 = *r2
	*r2 = *r3
	*r3 = r4
}
474541
func (c *CertAuthorityV2) V1() *CertAuthorityV1 {
	return &CertAuthorityV1{
		Type:         c.Spec.Type,
		DomainName:   c.Spec.ClusterName,
		CheckingKeys: c.Spec.CheckingKeys,
		SigningKeys:  c.Spec.SigningKeys,
	}
}
811825
func upgradeStateV2ToV3(old *State) (*State, error) {
	new := old.DeepCopy()

	// Ensure the copied version is v2 before attempting to upgrade
	if new.Version != 2 {
		return nil, fmt.Errorf("Cannot apply v2->v3 state upgrade to " +
			"a state which is not version 2.")
	}

	// Set the new version number
	new.Version = 3

	// Change the counts for things which look like maps to use the %
	// syntax. Remove counts for empty collections - they will be added
	// back in later.
	for _, module := range new.Modules {
		for _, resource := range module.Resources {
			// Upgrade Primary
			if resource.Primary != nil {
				upgradeAttributesV2ToV3(resource.Primary)
			}

			// Upgrade Deposed
			if resource.Deposed != nil {
				for _, deposed := range resource.Deposed {
					upgradeAttributesV2ToV3(deposed)
				}
			}
		}
	}

	return new, nil
}
713868
func (cli *Client) Versions() (resp *RespVersions, err error) {
	urlPath := cli.BuildBaseURL("_matrix", "client", "versions")
	_, err = cli.MakeRequest("GET", urlPath, nil, &resp)
	return
}
758095
func supportsV3(version string) error {
	// We'll split the minimum Tor version that's supported and the given
	// version in order to individually compare each number.
	requiredParts := strings.Split(MinTorVersion, ".")
	parts := strings.Split(version, ".")
	if len(parts) != 4 {
		return errors.New("version string is not of the format " +
			"major.minor.revision.build")
	}

	// It's possible that the build number (the last part of the version
	// string) includes a pre-release string, e.g. rc, beta, etc., so we'll
	// parse that as well.
	build := strings.Split(parts[len(parts)-1], "-")
	parts[len(parts)-1] = build[0]

	// Convert them each number from its string representation to integers
	// and check that they respect the minimum version.
	for i := range parts {
		n, err := strconv.Atoi(parts[i])
		if err != nil {
			return err
		}
		requiredN, err := strconv.Atoi(requiredParts[i])
		if err != nil {
			return err
		}

		if n < requiredN {
			return fmt.Errorf("version %v below minimum version "+
				"supported %v", version, MinTorVersion)
		}
	}

	return nil
}
1303069
func migrateV3ToV4() error {
	configFile := getConfigFile()

	cv3 := &configV3{}
	_, err := Load(configFile, cv3)
	if os.IsNotExist(err) {
		return nil
	} else if err != nil {
		return fmt.Errorf("Unable to load config version ‘3’. %v", err)
	}
	if cv3.Version != "3" {
		return nil
	}

	// Save only the new fields, ignore the rest.
	srvConfig := &configV4{}
	srvConfig.Version = "4"
	srvConfig.Credential = cv3.Credential
	srvConfig.Region = cv3.Region
	if srvConfig.Region == "" {
		// Region needs to be set for AWS Signature Version 4.
		srvConfig.Region = globalMinioDefaultRegion
	}
	srvConfig.Logger.Console = cv3.Logger.Console
	srvConfig.Logger.File = cv3.Logger.File
	srvConfig.Logger.Syslog = cv3.Logger.Syslog

	if err = Save(configFile, srvConfig); err != nil {
		return fmt.Errorf("Failed to migrate config from ‘%s’ to ‘%s’. %v", cv3.Version, srvConfig.Version, err)
	}

	logger.Info(configMigrateMSGTemplate, configFile, cv3.Version, srvConfig.Version)
	return nil
}
726602
func newConfigV3() *configV3 {
	conf := new(configV3)
	conf.Version = "3"
	conf.Aliases = make(map[string]string)
	conf.Hosts = make(map[string]hostConfigV3)
	return conf
}