The core protocol of WoopChain
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
woop/blockchain/transaction.go

97 lines
2.3 KiB

package blockchain
7 years ago
import (
7 years ago
"bytes"
"crypto/sha256"
"encoding/gob"
"encoding/hex"
"fmt"
7 years ago
"log"
7 years ago
)
// Transaction represents a Bitcoin transaction
type Transaction struct {
ID []byte // 32 byte hash
7 years ago
TxInput []TXInput
TxOutput []TXOutput
7 years ago
}
// TXOutput is the struct of transaction output in a transaction.
type TXOutput struct {
7 years ago
Value int
Address string
}
// TXInput is the struct of transaction input in a transaction.
type TXInput struct {
7 years ago
TxID []byte
TxOutputIndex int
Address string
7 years ago
}
7 years ago
// DefaultCoinbaseValue is the default value of coinbase transaction.
const DefaultCoinbaseValue = 1000
// SetID sets ID of a transaction (32 byte hash of the whole transaction)
func (tx *Transaction) SetID() {
7 years ago
var encoded bytes.Buffer
var hash [32]byte
7 years ago
7 years ago
enc := gob.NewEncoder(&encoded)
err := enc.Encode(tx)
if err != nil {
log.Panic(err)
}
hash = sha256.Sum256(encoded.Bytes())
7 years ago
tx.ID = hash[:]
}
// NewCoinbaseTX creates a new coinbase transaction
func NewCoinbaseTX(to, data string) (*Transaction, *UTXOPool) {
if data == "" {
data = fmt.Sprintf("Reward to '%s'", to)
}
txin := TXInput{[]byte{}, -1, data}
7 years ago
txout := TXOutput{DefaultCoinbaseValue, to}
tx := Transaction{nil, []TXInput{txin}, []TXOutput{txout}}
tx.SetID()
txID := hex.EncodeToString(tx.ID)
var utxoPool UTXOPool
utxoPool.utxo = make(map[string]map[string]int)
utxoPool.utxo[to] = make(map[string]int)
utxoPool.utxo[to][txID] = DefaultCoinbaseValue
return &tx, &utxoPool
}
// Used for debuging.
func (txInput *TXInput) String() string {
res := fmt.Sprintf("TxID: %v, ", hex.EncodeToString(txInput.TxID))
res += fmt.Sprintf("TxOutputIndex: %v, ", txInput.TxOutputIndex)
res += fmt.Sprintf("Address: %v", txInput.Address)
return res
}
// Used for debuging.
func (txOutput *TXOutput) String() string {
res := fmt.Sprintf("Value: %v, ", txOutput.Value)
res += fmt.Sprintf("Address: %v", txOutput.Address)
return res
}
// Used for debuging.
func (tx *Transaction) String() string {
res := fmt.Sprintf("ID: %v\n", hex.EncodeToString(tx.ID))
res += fmt.Sprintf("TxInput:\n")
for id, value := range tx.TxInput {
res += fmt.Sprintf("%v: %v\n", id, value.String())
}
res += fmt.Sprintf("TxOutput:\n")
for id, value := range tx.TxOutput {
res += fmt.Sprintf("%v: %v\n", id, value.String())
}
return res
7 years ago
}