-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.go
70 lines (60 loc) · 1.55 KB
/
transaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"errors"
"fmt"
"log"
)
var ErrInsufficientFunds =errors.New("Unsufficient funds!")
const reward = 10 // The reward to the genesis adresses..
// See https://en.bitcoin.it/wiki/Transaction You can replace
// ScriptSig and ScriptPubKey by adresses (just names)
// TXInput represents a transaction input see
type TXInput struct {
Txid []byte
Vout int
ScriptSig string
}
// TXOutput represents a transaction output
type TXOutput struct {
Value int
ScriptPubKey string
}
// Transaction represents a Bitcoin transaction it contains a hash, as
// well as a set of input and output transactions
type Transaction struct {
Hash []byte
TxIns []TXInput
TxOuts []TXOutput
}
func NewTransaction (hash []byte, txIns []TXInput, txOuts []TXOutput)*Transaction{
var transaction Transaction
transaction.Hash = hash
transaction.TxIns = txIns
transaction.TxOuts = txOuts
return &transaction
}
// Computes the Hash of a transaction
func (tx *Transaction) ComputeHash()[]byte{
var encoded bytes.Buffer
enc := gob.NewEncoder(&encoded)
err := enc.Encode(tx)
if err != nil {
log.Panic(err)
}
result := sha256.Sum256(encoded.Bytes())
return result[:]
}
// NewCoinbaseTX creates a new coinbase transaction
func NewCoinbaseTX(to, data string) *Transaction {
if data == "" {
data = fmt.Sprintf("Reward for %s", to)
}
txin := TXInput{[]byte{}, -1, data}
txout := TXOutput{reward, to}
tx := NewTransaction([]byte{}, []TXInput{txin}, []TXOutput{txout})
tx.Hash = tx.ComputeHash()
return tx
}