-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.go
103 lines (79 loc) · 2.16 KB
/
models.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
package inspector
import (
"encoding/binary"
"io"
"github.com/tokenized/pkg/bitcoin"
"github.com/tokenized/pkg/wire"
"github.com/tokenized/specification/dist/golang/actions"
"github.com/pkg/errors"
)
type Input struct {
Value uint64 `json:"value"`
LockingScript bitcoin.Script `json:"locking_script"`
Action actions.Action `json:"action"`
}
type Output struct {
Action actions.Action `json:"action"`
}
// UTXOs is a wrapper for a []UTXO.
type UTXOs []bitcoin.UTXO
// Value returns the total value of the set of UTXO's.
func (utxos UTXOs) Value() uint64 {
v := uint64(0)
for _, utxo := range utxos {
v += utxo.Value
}
return v
}
// ForLockingScript returns UTXOs that match the given locking script.
func (utxos UTXOs) ForLockingScript(lockingScript bitcoin.Script) (UTXOs, error) {
filtered := UTXOs{}
for _, utxo := range utxos {
if utxo.LockingScript.Equal(lockingScript) {
filtered = append(filtered, utxo)
}
}
return filtered, nil
}
func (in Input) Write(w io.Writer) error {
if err := binary.Write(w, binary.LittleEndian, in.Value); err != nil {
return errors.Wrap(err, "write value")
}
if err := wire.WriteVarInt(w, 0, uint64(len(in.LockingScript))); err != nil {
return errors.Wrap(err, "write script length")
}
if _, err := w.Write(in.LockingScript); err != nil {
return errors.Wrap(err, "write script")
}
return nil
}
func (in *Input) Read(version uint8, r io.Reader) error {
switch version {
case 0:
// Read full tx
msg := wire.MsgTx{}
if err := msg.Deserialize(r); err != nil {
return errors.Wrap(err, "read tx")
}
case 1, 2:
utxo := bitcoin.UTXO{}
if err := utxo.Read(r); err != nil {
return errors.Wrap(err, "read utxo")
}
in.Value = utxo.Value
in.LockingScript = utxo.LockingScript
default:
if err := binary.Read(r, binary.LittleEndian, &in.Value); err != nil {
return errors.Wrap(err, "read value")
}
length, err := wire.ReadVarInt(r, 0)
if err != nil {
return errors.Wrap(err, "read script length")
}
in.LockingScript = make(bitcoin.Script, length)
if _, err := io.ReadFull(r, in.LockingScript); err != nil {
return errors.Wrap(err, "read script")
}
}
return nil
}