Rename Transaction.GetHash to SetID; add Transaction.ID field

This commit is contained in:
Ivan Kuznetsov 2017-09-04 11:32:24 +07:00
parent 326ecb828c
commit 32dd771eef
3 changed files with 11 additions and 9 deletions

View File

@ -36,7 +36,7 @@ func (b *Block) HashTransactions() []byte {
var txHash [32]byte
for _, tx := range b.Transactions {
txHashes = append(txHashes, tx.GetHash())
txHashes = append(txHashes, tx.ID)
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))

View File

@ -70,7 +70,7 @@ func (bc *Blockchain) FindUnspentTransactions(address string) []*Transaction {
block := bci.Next()
for _, tx := range block.Transactions {
txID := hex.EncodeToString(tx.GetHash())
txID := hex.EncodeToString(tx.ID)
Outputs:
for outIdx, out := range tx.Vout {
@ -115,7 +115,7 @@ func (bc *Blockchain) FindUTXOs(address string, amount int) (int, map[string][]i
Work:
for _, tx := range unspentTXs {
txID := hex.EncodeToString(tx.GetHash())
txID := hex.EncodeToString(tx.ID)
for outIdx, out := range tx.Vout {
if out.CanBeUnlockedWith(address) && accumulated < amount {

View File

@ -13,6 +13,7 @@ const subsidy = 10
// Transaction represents a Bitcoin transaction
type Transaction struct {
ID []byte
Vin []TXInput
Vout []TXOutput
}
@ -22,8 +23,8 @@ func (tx Transaction) IsCoinbase() bool {
return len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1
}
// GetHash hashes the transaction and returns the hash
func (tx Transaction) GetHash() []byte {
// SetID sets ID of a transaction
func (tx Transaction) SetID() {
var encoded bytes.Buffer
var hash [32]byte
@ -33,8 +34,7 @@ func (tx Transaction) GetHash() []byte {
log.Panic(err)
}
hash = sha256.Sum256(encoded.Bytes())
return hash[:]
tx.ID = hash[:]
}
// TXInput represents a transaction input
@ -68,7 +68,8 @@ func NewCoinbaseTX(to, data string) *Transaction {
txin := TXInput{[]byte{}, -1, data}
txout := TXOutput{subsidy, to}
tx := Transaction{[]TXInput{txin}, []TXOutput{txout}}
tx := Transaction{nil, []TXInput{txin}, []TXOutput{txout}}
tx.SetID()
return &tx
}
@ -103,7 +104,8 @@ func NewUTXOTransaction(from, to string, value int, bc *Blockchain) *Transaction
outputs = append(outputs, TXOutput{acc - value, from}) // a change
}
tx := Transaction{inputs, outputs}
tx := Transaction{nil, inputs, outputs}
tx.SetID()
return &tx
}