77 "encoding/hex"
88 "fmt"
99 "log"
10+
11+ "github.com/dqx0/blockchain/wallet"
1012)
1113
1214type Transaction struct {
@@ -15,6 +17,29 @@ type Transaction struct {
1517 Outputs []TxOutput // 出力トランザクションのリスト
1618}
1719
20+ func (tx * Transaction ) Hash () []byte {
21+ var hash [32 ]byte
22+
23+ txCopy := * tx
24+ txCopy .ID = []byte {}
25+
26+ hash = sha256 .Sum256 (txCopy .Serialize ())
27+
28+ return hash [:]
29+ }
30+
31+ func (tx Transaction ) Serialize () []byte {
32+ var encoded bytes.Buffer
33+
34+ enc := gob .NewEncoder (& encoded )
35+ err := enc .Encode (tx )
36+ if err != nil {
37+ log .Panic (err )
38+ }
39+
40+ return encoded .Bytes ()
41+ }
42+
1843// トランザクションのハッシュIDを生成
1944// トランザクションの内容をgobでエンコードし、SHA-256ハッシュを計算
2045func (tx * Transaction ) SetID () {
@@ -40,10 +65,10 @@ func CoinbaseTx(to, data string) *Transaction {
4065 }
4166
4267 // コインベーストランザクションは過去の参照を持たない特殊なインプット
43- txin := TxInput {[]byte {}, - 1 , data }
68+ txin := TxInput {[]byte {}, - 1 , nil , [] byte ( data ) }
4469 // 報酬として100コインを設定
45- txout := TxOutput { 100 , to }
46- tx := Transaction {nil , []TxInput {txin }, []TxOutput {txout }}
70+ txout := NewTXOutput ( 100 , to )
71+ tx := Transaction {nil , []TxInput {txin }, []TxOutput {* txout }}
4772 tx .SetID ()
4873
4974 return & tx
@@ -59,8 +84,13 @@ func CoinbaseTx(to, data string) *Transaction {
5984func NewTransaction (from , to string , amount int , bc * BlockChain ) * Transaction {
6085 var inputs []TxInput
6186 var outputs []TxOutput
87+
88+ wallets , err := wallet .CreateWallets ()
89+ Handle (err )
90+ w := wallets .GetWallet (from )
91+ pubKeyHash := wallet .PublicKeyHash (w .PublicKey )
6292 // 利用可能なUTXOを検索
63- acc , validOutputs := bc .FindSpendableOutputs (from , amount )
93+ acc , validOutputs := bc .FindSpendableOutputs (pubKeyHash , amount )
6494
6595 if acc < amount {
6696 log .Panic ("Error: Not enough funds" )
@@ -72,16 +102,16 @@ func NewTransaction(from, to string, amount int, bc *BlockChain) *Transaction {
72102 Handle (err )
73103
74104 for _ , out := range outs {
75- input := TxInput {txID , out , from }
105+ input := TxInput {txID , out , nil , w . PublicKey }
76106 inputs = append (inputs , input )
77107 }
78108 }
79109
80110 // 出力トランザクションの作成
81- outputs = append (outputs , TxOutput { amount , to } )
111+ outputs = append (outputs , * NewTXOutput ( amount , to ) )
82112 // おつりがある場合は送金元に返す
83113 if acc > amount {
84- outputs = append (outputs , TxOutput { acc - amount , from } )
114+ outputs = append (outputs , * NewTXOutput ( acc - amount , from ) )
85115 }
86116
87117 tx := Transaction {nil , inputs , outputs }
0 commit comments