forked from Jeiwan/blockchain_go
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtransaction_output.go
68 lines (53 loc) · 1.38 KB
/
transaction_output.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
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
"github.com/btcsuite/btcutil/base58"
)
// TxOutput is output component of a transaction
type TxOutput struct {
Value int `json:"Value"`
PubKeyHash []byte `json:"PubKeyHash"`
}
func (txOut *TxOutput) lock(address string) {
decodedAddr := base58.Decode(address)
pubKeyHash := decodedAddr[1 : len(decodedAddr)-4]
txOut.PubKeyHash = pubKeyHash
}
func (txOut TxOutput) isLockedWithKey(pubKeyHash []byte) bool {
return bytes.Compare(txOut.PubKeyHash, pubKeyHash) == 0
}
func newTxOutput(value int, address string) *TxOutput {
txo := &TxOutput{value, nil}
txo.lock(address)
return txo
}
func (txOut TxOutput) String() string {
str := fmt.Sprintf("Value : %d\n", txOut.Value)
str += fmt.Sprintf(" PubKeyHash : %x ", txOut.PubKeyHash)
return str
}
// TxOutputMap is map of TxOutput
type TxOutputMap map[int]TxOutput
// Serialize serialize txoutouts
func (txOutputMap *TxOutputMap) Serialize() []byte {
var buff bytes.Buffer
enc := gob.NewEncoder(&buff)
err := enc.Encode(txOutputMap)
if err != nil {
log.Panic(err)
}
return buff.Bytes()
}
// DeserializeTxOutputMap deserialize txoutouts
func DeserializeTxOutputMap(data []byte) TxOutputMap {
var txOutputMap TxOutputMap
dec := gob.NewDecoder(bytes.NewReader(data))
err := dec.Decode(&txOutputMap)
if err != nil {
log.Panic(err)
}
return txOutputMap
}