計算機科学のブログ

シリアライズ 非圧縮SECフォーマット 秘密鍵、公開鍵

プログラミング・ビットコイン ―ゼロからビットコインをプログラムする方法 (Jimmy Song(著)、中川 卓俊(監修)、住田 和則(監修)、中村 昭雄(監修)、星野 靖子(翻訳)、オライリー・ジャパン)の4章(シラアライズ)、4.1(非圧縮SECフォーマット)の練習問題1の解答をPythonではなくGoで求めてみる。

コード

ecc.go


// ...

// Sec SECフォーマットをバイナリ形式にて返す
func (px S256Point) Sec() []byte {
	buf := make([]byte, 32)
	px.X.Num.FillBytes(buf)
	buf[0] = 4
	return buf
}
package main

import (
	"bitcoin/ecc"
	"fmt"
	"math/big"
)

func main() {
	fmt.Println("5000")
	secret := big.NewInt(5000)
	pk := ecc.NewPrivateKey(secret)
	bs := pk.Sec()
	fmt.Println(bs)
	for _, b := range bs {
		fmt.Printf("%02x", b)
	}
	fmt.Println("\n2,018^5")
	secret = big.NewInt(1)
	n := big.NewInt(2018)
	for i := 0; i < 5; i++ {
		secret.Mul(secret, n)
	}
	pk = ecc.NewPrivateKey(secret)
	bs = pk.Sec()
	fmt.Println(bs)
	for _, b := range bs {
		fmt.Printf("%02x", b)
	}
	fmt.Println("\n0xdeadbeef12345")
	secret.SetString("deadgbeef12345", 16)
	pk = ecc.NewPrivateKey(secret)
	bs = pk.Sec()
	fmt.Println(bs)
	for _, b := range bs {
		fmt.Printf("%02x", b)
	}
	fmt.Println()
}

入出力結果(Terminal, Zsh)

% go run ./main.go
5000
[4 229 88 227 136 133 47 1 32 228 106 242 209 179 112 248 88 84 168 235 8 65 129 30 206 14 62 3 210 130 213 124]
04e558e388852f0120e46af2d1b370f85854a8eb0841811ece0e3e03d282d57c
2,018^5
[4 127 61 161 145 132 85 224 60 70 246 89 38 106 27 181 32 78 149 157 183 54 77 47 71 59 223 143 10 19 204 157]
047f3da1918455e03c46f659266a1bb5204e959db7364d2f473bdf8f0a13cc9d
0xdeadbeef12345
[4 196 122 230 150 44 94 161 85 159 72 180 55 193 147 161 188 177 215 45 8 215 93 116 59 163 203 251 142 122 251 235]
04c47ae6962c5ea1559f48b437c193a1bcb1d72d08d75d743ba3cbfb8e7afbeb
%