主页 > imtoken官网是哪个 > 以太坊ETH源码解析(1):地址生成过程

以太坊ETH源码解析(1):地址生成过程

imtoken官网是哪个 2023-01-17 11:25:13

一、生成以太坊钱包地址

您可以通过以太坊命令行客户端geth轻松获取以太坊地址,如下:

~/go/src/github.com/ethereum/go-ethereum/build/bin$geth account new
INFO [11-03|20:09:33.219] Maximum peer count                       ETH=25 LES=0 total=25
keydir=/Users/wujinquan/Library/Ethereum/keystore
Your new account is locked with a password. Please give a password. Do not forget this password.
Passphrase:
Repeat passphrase:
Address: {8011cf2892985cdc58f447063bc6a089ba89f514}
~/go/src/github.com/ethereum/go-ethereum/build/bin$

地址0x8011cf2892985cdc58f447063bc6a089ba89f514(20字节十六进制)是新生成的以太坊地址

二、根据源码分析地址生成过程

从以太坊源码入手,分析地址生成过程

以太坊地址区分大小写_以太坊下载地址_以太坊地址

运行命令:geth account new

节目入口在

func init() {
    // Initialize the CLI app and start Geth
    app.Action = geth
    app.HideVersion = true // we have a command to print the version
    app.Copyright = "Copyright 2013-2018 The go-ethereum Authors"
    app.Commands = []cli.Command{
        // See chaincmd.go:
        initCommand,
        ...
        // See monitorcmd.go:
        monitorCommand,
        // See accountcmd.go:账户相关
        accountCommand,
        // See consolecmd.go:
    }
    ...
}

账户相关的命令在,

创建账户的命令是新的:

var (
    ...
    accountCommand = cli.Command{
        Name:     "account",
        Usage:    "Manage accounts",
        Category: "ACCOUNT COMMANDS",
        Description: ``
        Subcommands: []cli.Command{
            {
                Name:   "list",
                Usage:  "Print summary of existing accounts",
                Action: utils.MigrateFlags(accountList),
                Flags: []cli.Flag{
                    utils.DataDirFlag,
                    utils.KeyStoreDirFlag,
                },
                Description: `
Print a short summary of all accounts`,
            },
            {
                Name:   "new",
                Usage:  "Create a new account",
                Action: utils.MigrateFlags(accountCreate),
                Flags: []cli.Flag{
                    utils.DataDirFlag,
                    utils.KeyStoreDirFlag,
                    utils.PasswordFileFlag,
                    utils.LightKDFFlag,
                },
                Description: ``
            },
        },

以太坊地址区分大小写_以太坊地址_以太坊下载地址

Key:创建新账户时,会调用accountCreate:

// accountCreate creates a new account into the keystore defined by the CLI flags.
func accountCreate(ctx *cli.Context) error {
    // (1)获取配置
    cfg := gethConfig{Node: defaultNodeConfig()}
    // Load config file.
    if file := ctx.GlobalString(configFileFlag.Name); file != "" {
        if err := loadConfig(file, &cfg); err != nil {
            utils.Fatalf("%v", err)
        }
    }
    utils.SetNodeConfig(ctx, &cfg.Node)
    //  (1.1) 从节点配置中取出相关配置信息
    scryptN, scryptP, keydir, err := cfg.Node.AccountConfig()
    if err != nil {
        utils.Fatalf("Failed to read configuration: %v", err)
    }
    // (2)解析用户密码
    password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
    // (3)生成地址
    address, err := keystore.StoreKey(keydir, password, scryptN, scryptP) //创建地址的外层函数
    if err != nil {
        utils.Fatalf("Failed to create account: %v", err)
    }
    fmt.Printf("Address: {%x}\n", address)
    return nil
}

可以看出accountCreate分为三个步骤,其中最关键的是第三步

(1)获取配置

(2)解析用户密码

(3)生成地址

以太坊地址区分大小写_以太坊地址_以太坊下载地址

第三步,生成地址调用的keystore.StoreKey:

节目地点是

// StoreKey generates a key, encrypts with 'auth' and stores in the given directory
func StoreKey(dir, auth string, scryptN, scryptP int) (common.Address, error) {
    //返回Key{Id uuid.UUID ,Address common.Address,PrivateKey *ecdsa.PrivateKey}
    _, a, err := storeNewKey(&keyStorePassphrase{dir, scryptN, scryptP, false}, rand.Reader, auth)
    return a.Address, err
}

直接调用storeNewKey创建新账号

节目地点:

func storeNewKey(ks keyStore, rand io.Reader, auth string) (*Key, accounts.Account, error) {
    // 创建一个新的账户
    key, err := newKey(rand)
    fmt.Printf("key.Id=%v,key.Address=%x,key.PrivateKey=%v\n",key.Id,key.Address,key.PrivateKey)
    if err != nil {
        return nil, accounts.Account{}, err
    }
    a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.JoinPath(keyFileName(key.Address))}}
    if err := ks.StoreKey(a.URL.Path, key, auth); err != nil {
        zeroKey(key.PrivateKey)
        return nil, a, err
    }
    return key, a, err
}
func newKey(rand io.Reader) (*Key, error) {
    // (1) 选择secp256k1曲线、采用椭圆曲线数字签名算法(ECDSA)生成公私钥对
    privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand)
    if err != nil {
        return nil, err
    }
    // (2)由公钥算出地址并构建一个自定义的Key
    return newKeyFromECDSA(privateKeyECDSA), nil
}

以太坊下载地址_以太坊地址_以太坊地址区分大小写

可以看到,当newKey创建一个新账户时,

1、私钥由secp256k1曲线生成,由32字节的随机数组成

2、椭圆曲线数字签名算法(ECDSA)用于将私钥映射到公钥,一个私钥只能映射到一个公钥。

3、然后根据公钥计算地址,构建自定义Key

继续看公钥如何计算地址并构建自定义Key

func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
    id := uuid.NewRandom()
    key := &Key{
        Id:         id,
        //由公钥推出地址
        Address:    crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
        PrivateKey: privateKeyECDSA,
    }
    return key
}

以太坊下载地址_以太坊地址区分大小写_以太坊地址

从公钥计算地址是由crypto.PubkeyToAddress完成的:

代码位置:

func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
    // (1) 将pubkey转换为字节序列
    pubBytes := FromECDSAPub(&p)
    // (2) pubBytes为04 开头的65字节公钥,去掉04后剩下64字节进行Keccak256运算
    // (3) 经过Keccak256运算后变成32字节,最终取这32字节的后20字节作为真正的地址
    return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
}
// Keccak256 calculates and returns the Keccak256 hash of the input data.
func Keccak256(data ...[]byte) []byte {
    d := sha3.NewKeccak256()
    for _, b := range data {
        d.Write(b)
    }
    return d.Sum(nil)
}

可以看到公钥(64字节)通过Keccak-256单向哈希函数转换成32字节,然后取最后20字节作为地址。本质上是从 32 字节的私钥映射到 20 字节的公共地址。这意味着一个帐户可以拥有多个私钥。

三、总结

以太坊地址的生成过程如下:

私钥由secp256k1曲线生成以太坊地址,该曲线由32字节的随机数生成以太坊地址,并使用椭圆曲线数字签名算法(ECDSA)将私钥(32字节)映射到公钥(65字节) )。公钥(去掉04后剩下64字节)通过Keccak-256单向哈希函数转换成32字节,然后取最后20字节作为地址