Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: add bip39 support (same as MyTonWallet and TonKeeper) #275

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

aitimate
Copy link

@aitimate aitimate commented Nov 8, 2024

// usage
wallet.FromSeed(nil, <seed>, version, true)
func FromSeed(api TonAPI, seed []string, version VersionConfig, isCompatBip39 ...bool) (*Wallet, error) {
	return FromSeedWithPassword(api, seed, "", version, isCompatBip39...)
}

func FromSeedWithPassword(api TonAPI, seed []string, password string, version VersionConfig, isCompatBip39 ...bool) (*Wallet, error) {
	// validate seed
	if len(seed) < 12 {
		return nil, fmt.Errorf("seed should have at least 12 words")
	}
	for _, s := range seed {
		if !words[s] {
			return nil, fmt.Errorf("unknown word '%seedBytes' in seed", s)
		}
	}
	seedBytes := []byte(strings.Join(seed, " "))
	mac := hmac.New(sha512.New, seedBytes)
	mac.Write([]byte(password))
	hash := mac.Sum(nil)

	if len(password) > 0 {
		p := pbkdf2.Key(hash, []byte(_PasswordSalt), 1, 1, sha512.New)
		if p[0] != 1 {
			// compat big39
			if len(isCompatBip39) > 0 && isCompatBip39[0] {
				pKey := pbkdf2.Key(seedBytes, []byte("mnemonic"+password), 2048, 64, sha512.New)
				dk, err := hdwallet.Derived(_Path, pKey)
				if err != nil {
					return nil, err
				}
				return FromPrivateKey(nil, ed25519.NewKeyFromSeed(dk.PrivateKey), version)
			}
			return nil, errors.New("invalid seed")
		}
	} else {
		p := pbkdf2.Key(hash, []byte(_BasicSalt), _Iterations/256, 1, sha512.New)
		if p[0] != 0 {
			// compat big39
			if len(isCompatBip39) > 0 && isCompatBip39[0] {
				pKey := pbkdf2.Key(seedBytes, []byte("mnemonic"), 2048, 64, sha512.New)
				dk, err := hdwallet.Derived(_Path, pKey)
				if err != nil {
					return nil, err
				}
				return FromPrivateKey(nil, ed25519.NewKeyFromSeed(dk.PrivateKey), version)
			}
			return nil, errors.New("invalid seed")
		}
	}

	k := pbkdf2.Key(hash, []byte(_Salt), _Iterations, 32, sha512.New)

	return FromPrivateKey(api, ed25519.NewKeyFromSeed(k), version)
}

@aitimate
Copy link
Author

aitimate commented Nov 8, 2024

#274

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant