欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

eth hd钱包

程序员文章站 2022-03-23 14:34:37
...
熵(128位)→助记词(12个)→种子(512位)→私钥→公钥→地址

import (
	"fmt"
	"math/big"
	"strings"
	"testing"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
)

//go test -run TestAddrs
func TestAddrs(t *testing.T) {
	mnemonic, err := MnemonicFun()
	if err != nil {
		t.Error(err)
	}

	fmt.Println("mnemonic:",*mnemonic)
	//"there network sister salad scout catch embrace clinic hold jewel kingdom atom"
	wallet, err := NewFromMnemonic(*mnemonic)
	if err != nil {
		t.Error(err)
	}

	for i:=0;i<3;i++{
		path, err := ParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/0/%d",i))
		if err != nil {
			t.Error(err)
		}

		account, err := wallet.Derive(path, true)
		if err != nil {
			t.Error(err)
		}

		fmt.Println("address:",account.Address.String(),",count:",len(wallet.accounts))

		privateKeyHex, err := wallet.PrivateKeyHex(account)
		if err != nil {
			t.Error(err)
		}

		fmt.Println("privatekey:",privateKeyHex)
	}

	for i:=0;i<3;i++{
		seed, err := NewSeedFromMnemonic(*mnemonic)
		if err != nil {
			t.Error(err)
		}

		wallet, err = NewFromSeed(seed)
		if err != nil {
			t.Error(err)
		}

		path := MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/0/%d",i))
		account, err := wallet.Derive(path, false)
		if err != nil {
			t.Error(err)
		}
		wallet.PrivateKey(account)
		fmt.Println("addr:",account.Address.String())
	}
}