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

一、生成一个以太坊钱包地址

通过以太坊命令行客户端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字节16进制)就是新生成的以太坊地址。

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

从以太坊源码 https://github.com/ethereum/go-ethereum 出发,分析地址生成过程
运行命令 :geth account new
程序入口在 https://github.com/ethereum/go-ethereum/blob/master/cmd/geth/main.go

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:
    }
    ...
}

账户相关的命令在 https://github.com/ethereum/go-ethereum/blob/master/cmd/geth/accountcmd.go 里,
新建账户命令为new:

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: ``
            },
        },

关键:new一个新账户的时候,会调用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:
程序位置在 https://github.com/ethereum/go-ethereum/blob/master/accounts/keystore/keystore_passphrase.go

// 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 创建新账户
程序位置:https://github.com/ethereum/go-ethereum/blob/master/accounts/keystore/key.go

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完成的:
代码位置:https://github.com/ethereum/go-ethereum/blob/master/crypto/crypto.go

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字节的公共地址。这意味着一个账户可以有不止一个私钥。

三、总结

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

  1. 由secp256k1曲线生成私钥,是由32字节的随机数生成
  2. 采用椭圆曲线数字签名算法(ECDSA)将私钥(32字节)映射成公钥(65字节)。
  3. 公钥(去掉04后剩下64字节)经过Keccak-256单向散列函数变成了32字节,然后取后20字节作为地址
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容