-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
63 lines (49 loc) 路 1.02 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
package blockchain
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"fmt"
)
type Transaction struct {
ID []byte
Inputs []TxInput
Outputs []TxOutput
}
type TxOutput struct {
Value int
PubKey string
}
type TxInput struct {
ID []byte
Out int
Sig string
}
func (tx *Transaction) SetID() {
var encoded bytes.Buffer
var hash [32]byte
encode := gob.NewEncoder(&encoded)
err := encode.Encode(tx)
Handler(err)
hash = sha256.Sum256(encoded.Bytes())
tx.ID = hash[:]
}
func CoinbaseTx(to, data string) *Transaction {
if data == "" {
data = fmt.Sprintf("Coins to %s", to)
}
txin := TxInput{[]byte{}, -1, data}
txout := TxOutput{100, to}
tx := Transaction{nil, []TxInput{txin}, []TxOutput{txout}}
tx.SetID()
return &tx
}
func (tx *Transaction) IsCoinbase() bool {
return len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1
}
func (in *TxInput) CanUnlock(data string) bool {
return in.Sig == data
}
func (out *TxOutput) CanBeUnlocked(data string) bool {
return out.PubKey == data
}