比特币地址是如何生成编码的

简介

Public Key为椭圆曲线加密的公钥,Checksum是校验和:
注意:图中校验和的计算有误
S H A 256 ( S H A 256 ( P u b K e y H a s h ) )
应该改为
S H A 256 ( S H A 256 ( V e r s i o n + P u b K e y H a s h ) )
这里写图片描述

  1. 选择椭圆曲线以及随机数生成公钥PubicKey
curve := elliptic.P256()
private, err := ecdsa.GenerateKey(curve, rand.Reader)
pubKey := append(private.PublicKey.X.Bytes(), private.PublicKey.Y.Bytes()...)
  1. 生成PublicKeyHash: RIPMD160(SHA256(PubKey))
publicSHA256 := sha256.Sum256(pubKey)

RIPEMD160Hasher := ripemd160.New()
_, err := RIPEMD160Hasher.Write(publicSHA256[:])

publicRIPEMD160 := RIPEMD160Hasher.Sum(nil)
  1. Version+RIPMD160(SHA256(PubKey))
  2. 生成4字节Checksum:SHA256(SHA256(Version+PublicKeyHash))
func checksum(payload []byte) []byte { addressChecksumLen := 4 firstSHA := sha256.Sum256(payload) secondSHA := sha256.Sum256(firstSHA[:]) return secondSHA[:addressChecksumLen] }
  1. Version+PublicKeyHash+Checksum
  2. Base56编码
    Base56(Version+PublicKeyHash+Checksum)

例子

地址的具体形式:

Version  Public key hash                           Checksum
00       62E907B15CBF27D5425399EBF6F0FB50EBB88F18  C29B7D93

地址生成的流程

0 - Having a private ECDSA key

18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725

1 - Take the corresponding public key generated with it (65 bytes, 1 byte 0x04, 32 bytes corresponding to X coordinate, 32 bytes corresponding to Y coordinate)

0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6

2 - Perform SHA-256 hashing on the public key

600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408

3 - Perform RIPEMD-160 hashing on the result of SHA-256

010966776006953D5567439E5E39F86A0D273BEE

4 - Add version byte in front of RIPEMD-160 hash (0x00 for Main Network)

00010966776006953D5567439E5E39F86A0D273BEE

(note that below steps are the Base58Check encoding, which has multiple library options available implementing it)
5 - Perform SHA-256 hash on the extended RIPEMD-160 result

445C7A8007A93D8733188288BB320A8FE2DEBD2AE1B47F0F50BC10BAE845C094

6 - Perform SHA-256 hash on the result of the previous SHA-256 hash

D61967F63C7DD183914A4AE452C9F6AD5D462CE3D277798075B107615C1A8A30

7 - Take the first 4 bytes of the second SHA-256 hash. This is the address checksum

D61967F6

8 - Add the 4 checksum bytes from stage 7 at the end of extended RIPEMD-160 hash from stage 4. This is the 25-byte binary Bitcoin Address.

00010966776006953D5567439E5E39F86A0D273BEED61967F6

9 - Convert the result from a byte string into a base58 string using Base58Check encoding. This is the most commonly used Bitcoin Address format

16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM

Go语言实现

阅读更多

更多精彩内容