由公鑰生成比特幣地址步驟
- 隨機取一個32位隨機數作為私鑰
- 利用生產的隨機數采用橢圓加密算法生成公鑰
- 計算公鑰的sha256哈希值
- 計算RIPEMD-160哈希值
- 第4步結果加上版本號(比特幣為0x00)
- 對第5步結果取兩次sha256哈希值
- 取上一步結果的前四個字節
- 將第7步結果加到第步的結果后面作為校驗
- 利用base58對第8步結果進行變化得到地址
生成地址代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
func (w Wallet) GetAddress() []byte { pubKeyHash := HashPubKey(w.PublicKey) versionedPayload := append([]byte{version}, pubKeyHash...) checksum := checksum(versionedPayload) fullPayload := append(versionedPayload, checksum...) address := Base58Encode(fullPayload) return address } func HashPubKey(pubKey []byte) []byte { publicSHA256 := sha256.Sum256(pubKey) RIPEMD160Hasher := ripemd160.New() _, err := RIPEMD160Hasher.Write(publicSHA256[:]) publicRIPEMD160 := RIPEMD160Hasher.Sum(nil) return publicRIPEMD160 } func checksum(payload []byte) []byte { firstSHA := sha256.Sum256(payload) secondSHA := sha256.Sum256(firstSHA[:]) return secondSHA[:addressChecksumLen] } |
校驗比特幣
地址是否正確代碼
1
2
3
4
5
6
7
8
9
|
addressChecksumLen:=4 func ValidateAddress(address string) bool { pubKeyHash := Base58Decode([]byte(address)) actualChecksum := pubKeyHash[len(pubKeyHash)-addressChecksumLen:] version := pubKeyHash[0] pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-addressChecksumLen] targetChecksum := checksum(append([]byte{version}, pubKeyHash...)) return bytes.Compare(actualChecksum, targetChecksum) == 0 } |
Base58Decode是對比特幣地址進行解碼,然后取后四位校驗位actualChecksum,利用去掉校驗位的pubKeyHash再次算出校驗位與地址的校驗位做出對比,即可驗證地址的正確性。 其中用到的函數有:
1
2
3
4
5
6
7
|
func checksum(payload []byte) [] //利用兩次shah256求校驗位 byte { firstSHA := sha256.Sum256(payload) secondSHA := sha256.Sum256(firstSHA[:]) return secondSHA[:addressChecksumLen] } |
這是解碼的函數,已經有不少現有的代碼支持,故不作講解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
func Base58Decode(input []byte) []byte { result := big.NewInt(0) zeroBytes := 0 for b := range input { if b == 0x00 { zeroBytes++ } } payload := input[zeroBytes:] for _, b := range payload { charIndex := bytes.IndexByte(b58Alphabet, b) result.Mul(result, big.NewInt(58)) result.Add(result, big.NewInt(int64(charIndex))) } decoded := result.Bytes() decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...) return decoded } |
以上就是go語言實戰之實現比特幣地址校驗步驟的詳細內容,更多關于go語言比特幣地址校驗的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/m0_37719047/article/details/81945896