-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.go
116 lines (94 loc) · 2.6 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package core
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"encoding/hex"
"fmt"
"log"
)
const subsidy = 10
// Transaction 由交易 ID,输入和输出构成
type Transaction struct {
ID []byte
Vin []TXInput
Vout []TXOutput
}
// TXInput 包含 3 部分
// Txid: 一个交易输入引用了之前一笔交易的一个输出, ID 表明是之前哪笔交易
// Vout: 一笔交易可能有多个输出,Vout 为输出的索引
// ScriptSig: 提供解锁输出 Txid:Vout 的数据
type TXInput struct {
Txid []byte
Vout int
ScriptSig string
}
// TXOutput 包含两部分
// Value: 有多少币,就是存储在 Value 里面
// ScriptPubKey: 对输出进行锁定
// 在当前实现中,ScriptPubKey 将仅用一个字符串来代替
type TXOutput struct {
Value int
ScriptPubKey string
}
// IsCoinbase 判断是否是 coinbase 交易
func (tx Transaction) IsCoinbase() bool {
return len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1
}
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[:]
}
// 这里的 unlockingData 可以理解为地址
func (in *TXInput) CanUnlockOutputWith(unlockingData string) bool {
return in.ScriptSig == unlockingData
}
func (out *TXOutput) CanBeUnlockedWith(unlockingData string) bool {
return out.ScriptPubKey == unlockingData
}
// NewCoinbaseTX 构建 coinbase 交易,该没有输入,只有一个输出
func NewCoinbaseTX(to, data string) *Transaction {
if data == "" {
data = fmt.Sprintf("Reward to '%s'", to)
}
txin := TXInput{[]byte{}, -1, data}
txout := TXOutput{subsidy, to}
tx := Transaction{nil, []TXInput{txin}, []TXOutput{txout}}
tx.SetID()
return &tx
}
// NewUTXOTransaction 创建一笔新的交易
func NewUTXOTransaction(from, to string, amount int, bc *BlockChain) *Transaction {
var inputs []TXInput
var outputs []TXOutput
// 找到足够的未花费输出
acc, validOutputs := bc.FindSpendableOutputs(from, amount)
if acc < amount {
log.Panic("ERROR: Not enough funds")
}
for txid, outs := range validOutputs {
txID, err := hex.DecodeString(txid)
if err != nil {
log.Panic(err)
}
for _, out := range outs {
input := TXInput{txID, out, from}
inputs = append(inputs, input)
}
}
outputs = append(outputs, TXOutput{amount, to})
// 如果 UTXO 总数超过所需,则产生找零
if acc > amount {
outputs = append(outputs, TXOutput{acc - amount, from})
}
tx := Transaction{nil, inputs, outputs}
tx.SetID()
return &tx
}