-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx.go
72 lines (54 loc) · 1.55 KB
/
tx.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
package blockchain
import (
"bytes"
"encoding/gob"
"github.com/sauzzon/golang-blockchain/wallet"
)
// input contain pub key not hashed along with signature of the transaction
// out contain hash of the pub key
type TxOutput struct {
Value int
PubKeyHash []byte
}
type TxOutputs struct {
Outputs []TxOutput
}
type TxInput struct {
ID []byte // references older output
Out int //index of output if there are many outputs
Signature []byte
PubKey []byte
}
func NewTXOutput(value int, address string) *TxOutput {
txo := &TxOutput{value, nil}
txo.Lock([]byte(address))
return txo
}
// to check if the account i.e data owns the info inside the output which is referenced by the input
func (in *TxInput) UsesKey(pubKeyHash []byte) bool {
lockingHash := wallet.PublicKeyHash(in.PubKey)
return bytes.Compare(lockingHash, pubKeyHash) == 0
}
// to check if the account i.e data owns info inside output
func (out *TxOutput) Lock(address []byte) {
pubKeyHash := wallet.Base58Decode(address)
pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4]
out.PubKeyHash = pubKeyHash
}
func (out *TxOutput) IsLockedWithKey(pubKeyHash []byte) bool {
return bytes.Compare(out.PubKeyHash, pubKeyHash) == 0
}
func (outs TxOutputs) Serialize() []byte {
var buffer bytes.Buffer
encode := gob.NewEncoder(&buffer)
err := encode.Encode(outs)
Handle(err)
return buffer.Bytes()
}
func DeserializeOutputs(data []byte) TxOutputs {
var outputs TxOutputs
decode := gob.NewDecoder(bytes.NewReader(data))
err := decode.Decode(&outputs)
Handle(err)
return outputs
}