进入go-ethereum的代码目录
1.1.初始化节点
创建文件夹dev_data, 子文件夹node1 和文件genesis.json
终端执行: ./build/bin/geth --datadir ./dev_data/node1/ init ./dev_data/genesis.json
1.2.启动控制台
终端执行: ./build/bin/geth --datadir dev_data/node1 --networkid 314590 --ipcdisable --port 61910 --rpcport 8200 console
2.1./go-ethereum/internal/ethapi/api.go
func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
acc, err := fetchKeystore(s.am).NewAccount(password)
}
2.2.go-ethereum/accounts/keystore/keystore.go
func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase) //创建私钥
// Add the account to the cache immediately rather than waiting for file system notifications to pick it up.
ks.cache.add(account) //accountCache的数组all: 根据URL从低到高排列 加入accountCache的map byAddr
ks.refreshWallets()
return account, nil
}
2.3.go-ethereum/accounts/keystore/key.go
func storeNewKey(ks keyStore, rand io.Reader, auth string) (*Key, accounts.Account, error) {
key, err := newKey(rand) //生成私钥
a := accounts.Account{Address: key.Address,
URL: accounts.URL{Scheme: KeyStoreScheme, Path:ks.JoinPath(keyFileName(key.Address))}}
//将keystore写入文件go-ethereum/dev_data/node1/
UTC--2018-05-09T09-22-01.825676850Z--d4c3b95bf0bbf0fd00870621
if err := ks.StoreKey(a.URL.Path, key, auth); err != nil { //存储keystore文件
zeroKey(key.PrivateKey)
return nil, a, err
}
return key, a, err
}
2.4.生成私钥 go-ethereum/accounts/keystore/key.go
func newKey(rand io.Reader) (*Key, error) {
privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand) //生成私钥
return newKeyFromECDSA(privateKeyECDSA), nil
}
type PrivateKey struct {
PublicKey
D *big.Int //随机数
}
2.5. 生成随机数 /usr/lib/go-1.10/src/crypto/ecdsa/ecdsa.go
// GenerateKey generates a public and private key pair.
func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
k, err := randFieldElement(c, rand) //所以以太坊的随机数生成采用的是go的api?
if err != nil {
return nil, err
}
priv := new(PrivateKey)
priv.PublicKey.Curve = c
priv.D = k
priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
return priv, nil
}