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

通过以太坊命令行客户端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 Gethapp.Action = gethapp.HideVersion = true // we have a command to print the versionapp.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)由公钥算出地址并构建一个自定义的Keyreturn 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字节作为地址

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

  1. 以太坊地址算法php,以太坊ETH源码分析(1):地址生成过程

    一.生成一个以太坊钱包地址 通过以太坊命令行客户端geth可以很简单的获得一个以太坊地址,如下: ~/go/src/github.com/ethereum/go-ethereum/build/bin$ ...

  2. 以太坊控制台源码分析

    最近有网友提到以太坊控制台的代码看不太明白,抽了点时间整理了一下. 当我们通过geth console或者geth attach与节点交互的时候,输入的命令是如何被处理的呢?看下面这张流程图就明白了: ...

  3. 以太坊DPOS源码分析

    2019独角兽企业重金招聘Python工程师标准>>> 一.前言: 任何共识机制都必须回答包括但不限于如下的问题: 下一个添加到数据库的新区块应该由谁来生成? 下一个块应该何时产生? ...

  4. 以太坊Go-ethereum源码分析之启动流程

    以太坊源码编译需要gov1.7以上,及C编译器,执行make geth 即可编译项目,编译后可执行的geth文件. Makefile文件: geth:build/env.sh go run build ...

  5. 以太坊EVM源码注释之执行流程

    以太坊EVM源码分析之执行流程 业务流程概述 EVM是用来执行智能合约的.输入一笔交易,内部会将之转换成一个Message对象,传入 EVM 执行.在合约中,msg 全局变量记录了附带当前合约的交易的 ...

  6. 以太坊EVM源码注释之数据结构

    以太坊EVM源码分析之数据结构 EVM代码整体结构 EVM相关的源码目录结构: ~/go-ethereum-master/core/vm# tree . ├── analysis.go // 分析合约 ...

  7. 以太坊EVM源码注释之State

    以太坊EVM源码注释之State Ethereum State EVM在给定的状态下使用提供的上下文(Context)运行合约,计算有效的状态转换(智能合约代码执行的结果)来更新以太坊状态(Ether ...

  8. 以太坊挖矿源码:clique算法

    链客,专为开发者而生,有问必答! 此文章来自区块链技术社区,未经允许拒绝转载. clique 以太坊的官方共识算法是ethash算法,这在前文已经有了详细的分析: 它是基于POW的共识机制的,矿工需要 ...

  9. 以太坊挖矿源码:ethash算法

    本文具体分析以太坊的共识算法之一:实现了POW的以太坊共识引擎ethash. 关键字:ethash,共识算法,pow,Dagger Hashimoto,ASIC,struct{},nonce,FNV ...

最新文章

  1. linux数字大小判断,if 判断两个数值大小--多分支if语句实现对参数的严格判断
  2. LeetCode-17-Letter Combinations of a Phone Number
  3. 软件测试江湖之公会武器之争
  4. PHP 4 中对象的比较
  5. Android studio 混淆打包 proguard-rules.pro 与 bulid.gradle 配置总结
  6. Java EE:异步构造和功能
  7. 1034. 二哥的金链
  8. PIP 安装 numpy
  9. java中file类乱,【JAVA SE基础篇】47.file类的方法
  10. 判断ImageView背景图片是否与Drawable中的某个图片一样的两个方法
  11. 如何在Mac上创建和移除替身
  12. Maven 入门 (2)—— 创建Maven项目
  13. BATJTMD,大厂招聘,都怎么面Java程序员?
  14. 阿里云Centos6.3,LANP安装
  15. Wasserstein GANs 三部曲(二):Wasserstein GAN论文的理解
  16. 等级保护体系及信息安全管理系统
  17. 软件工程 -- 状态转换图
  18. 7-176 数列求和
  19. Mybatis执行流程、缓存原理以及相关面试题
  20. 计算机复制教程,教你如何使用电脑复制粘贴快捷键

热门文章

  1. 推荐一个强大的开源的录制、直播软件(obs-studio)
  2. 最全的计算机会议排名
  3. Hugo作者、Go核心团队成员Steve Francia谈诞生13年的Go语言:生态系统、演化与未来[译]...
  4. 力扣 26.删除有序数组中的重复项
  5. html怎么做下雨效果,Canvas制作的下雨动画的示例
  6. 卡尔曼滤波器之经典卡尔曼滤波
  7. 帮助中国IT企业吃掉更多不会跳舞的大象
  8. Android 11.0 任务栏中清除掉播放器的进程,状态栏仍有音乐播放器状态问题的解决
  9. 2021 字节前端面试题汇总
  10. 怎么把PDF翻译成中文?教你便捷翻译方法