blockchain_go/transaction.go

219 lines
5.0 KiB
Go
Raw Normal View History

2017-09-02 21:20:47 -05:00
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"math/big"
2017-09-07 23:31:34 -05:00
"encoding/gob"
2017-09-02 22:41:45 -05:00
"encoding/hex"
2017-09-03 23:02:24 -05:00
"fmt"
"log"
"strings"
)
2017-09-02 21:20:47 -05:00
const subsidy = 10
// Transaction represents a Bitcoin transaction
type Transaction struct {
ID []byte
2017-09-02 21:20:47 -05:00
Vin []TXInput
Vout []TXOutput
}
// IsCoinbase checks whether the transaction is coinbase
func (tx Transaction) IsCoinbase() bool {
2017-09-02 22:41:45 -05:00
return len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1
2017-09-02 21:20:47 -05:00
}
// SetID sets ID of a transaction
2017-09-07 22:09:04 -05:00
func (tx *Transaction) SetID() {
var encoded bytes.Buffer
var hash [32]byte
enc := gob.NewEncoder(&encoded)
err := enc.Encode(tx)
if err != nil {
log.Panic(err)
}
hash = sha256.Sum256(encoded.Bytes())
tx.ID = hash[:]
}
// Sign signs each input of a Transaction
func (tx *Transaction) Sign(privKey ecdsa.PrivateKey, prevTXs map[string]Transaction) {
if tx.IsCoinbase() {
return
}
for _, vin := range tx.Vin {
if prevTXs[hex.EncodeToString(vin.Txid)].ID == nil {
log.Panic("ERROR: Previous transaction is not correct")
}
}
txCopy := tx.TrimmedCopy()
for inID, vin := range txCopy.Vin {
prevTx := prevTXs[hex.EncodeToString(vin.Txid)]
txCopy.Vin[inID].ScriptSig = prevTx.Vout[vin.Vout].ScriptPubKey
txCopy.SetID()
txCopy.Vin[inID].ScriptSig = []byte{}
r, s, err := ecdsa.Sign(rand.Reader, &privKey, txCopy.ID)
if err != nil {
log.Panic(err)
}
signature := append(r.Bytes(), s.Bytes()...)
tx.Vin[inID].ScriptSig = append(signature, tx.Vin[inID].ScriptSig...)
}
}
// String returns a human-readable representation of a transaction
func (tx Transaction) String() string {
var lines []string
lines = append(lines, fmt.Sprintf("Transaction %x:", tx.ID))
for i, input := range tx.Vin {
lines = append(lines, fmt.Sprintf(" Input %d:", i))
lines = append(lines, fmt.Sprintf(" TXID: %x", input.Txid))
lines = append(lines, fmt.Sprintf(" Out: %d", input.Vout))
lines = append(lines, fmt.Sprintf(" Script: %x", input.ScriptSig))
}
for i, output := range tx.Vout {
lines = append(lines, fmt.Sprintf(" Output %d:", i))
lines = append(lines, fmt.Sprintf(" Value: %d", output.Value))
lines = append(lines, fmt.Sprintf(" Script: %x", output.ScriptPubKey))
}
return strings.Join(lines, "\n")
}
// TrimmedCopy creates a trimmed copy of Transaction to be used in signing
func (tx *Transaction) TrimmedCopy() Transaction {
var inputs []TXInput
var outputs []TXOutput
for _, vin := range tx.Vin {
inputs = append(inputs, TXInput{vin.Txid, vin.Vout, []byte{}})
}
for _, vout := range tx.Vout {
outputs = append(outputs, TXOutput{vout.Value, vout.ScriptPubKey})
}
txCopy := Transaction{tx.ID, inputs, outputs}
return txCopy
}
// Verify verifies signatures of Transaction inputs
func (tx *Transaction) Verify(prevTXs map[string]Transaction) bool {
sigLen := 64
if tx.IsCoinbase() {
return true
}
for _, vin := range tx.Vin {
if prevTXs[hex.EncodeToString(vin.Txid)].ID == nil {
log.Panic("ERROR: Previous transaction is not correct")
}
}
txCopy := tx.TrimmedCopy()
curve := elliptic.P256()
for inID, vin := range tx.Vin {
prevTx := prevTXs[hex.EncodeToString(vin.Txid)]
txCopy.Vin[inID].ScriptSig = prevTx.Vout[vin.Vout].ScriptPubKey
txCopy.SetID()
txCopy.Vin[inID].ScriptSig = []byte{}
signature := vin.ScriptSig[:sigLen]
pubKey := vin.ScriptSig[sigLen:]
r := big.Int{}
s := big.Int{}
r.SetBytes(signature[:(sigLen / 2)])
s.SetBytes(signature[(sigLen / 2):])
x := big.Int{}
y := big.Int{}
keyLen := len(pubKey)
x.SetBytes(pubKey[:(keyLen / 2)])
y.SetBytes(pubKey[(keyLen / 2):])
rawPubKey := ecdsa.PublicKey{curve, &x, &y}
if ecdsa.Verify(&rawPubKey, txCopy.ID, &r, &s) == false {
return false
}
}
return true
}
2017-09-02 21:20:47 -05:00
// NewCoinbaseTX creates a new coinbase transaction
func NewCoinbaseTX(to, data string) *Transaction {
if data == "" {
2017-09-03 23:02:24 -05:00
data = fmt.Sprintf("Reward to '%s'", to)
}
2017-09-07 23:31:34 -05:00
txin := TXInput{[]byte{}, -1, []byte(data)}
txout := NewTXOutput(subsidy, to)
tx := Transaction{nil, []TXInput{txin}, []TXOutput{*txout}}
tx.SetID()
2017-09-02 21:20:47 -05:00
return &tx
}
// NewUTXOTransaction creates a new transaction
2017-09-05 09:35:45 -05:00
func NewUTXOTransaction(from, to string, amount int, bc *Blockchain) *Transaction {
2017-09-02 21:20:47 -05:00
var inputs []TXInput
var outputs []TXOutput
2017-09-07 23:31:34 -05:00
wallets, err := NewWallets()
if err != nil {
log.Panic(err)
}
wallet := wallets.GetWallet(from)
pubKeyHash := HashPubKey(wallet.PublicKey)
acc, validOutputs := bc.FindSpendableOutputs(pubKeyHash, amount)
2017-09-02 21:20:47 -05:00
2017-09-05 09:35:45 -05:00
if acc < amount {
2017-09-02 21:20:47 -05:00
log.Panic("ERROR: Not enough funds")
}
// Build a list of inputs
for txid, outs := range validOutputs {
2017-09-05 09:35:45 -05:00
txID, err := hex.DecodeString(txid)
if err != nil {
log.Panic(err)
}
2017-09-02 22:41:45 -05:00
2017-09-05 09:35:45 -05:00
for _, out := range outs {
2017-09-07 23:31:34 -05:00
input := TXInput{txID, out, wallet.PublicKey}
2017-09-02 21:20:47 -05:00
inputs = append(inputs, input)
}
}
// Build a list of outputs
2017-09-07 23:31:34 -05:00
outputs = append(outputs, *NewTXOutput(amount, to))
2017-09-05 09:35:45 -05:00
if acc > amount {
2017-09-07 23:31:34 -05:00
outputs = append(outputs, *NewTXOutput(acc-amount, from)) // a change
2017-09-02 21:20:47 -05:00
}
tx := Transaction{nil, inputs, outputs}
tx.SetID()
bc.SignTransaction(&tx, wallet.PrivateKey)
2017-09-02 21:20:47 -05:00
return &tx
}