forked from Onyx-Protocol/Onyx
/
tx.go
273 lines (242 loc) · 8.06 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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package validation
import (
"bytes"
"encoding/hex"
"math"
"strings"
"chain/errors"
"chain/math/checked"
"chain/protocol/bc"
"chain/protocol/state"
"chain/protocol/vm"
"chain/protocol/vmutil"
)
var (
// ErrBadTx is returned for transactions failing validation
ErrBadTx = errors.New("invalid transaction")
// ErrFalseVMResult is one of the ways for a transaction to fail validation
ErrFalseVMResult = errors.New("false VM result")
)
// ConfirmTx validates the given transaction against the given state tree
// before it's added to a block. If tx is invalid, it returns a non-nil
// error describing why.
//
// Tx must already have undergone the well-formedness check in
// CheckTxWellFormed. This should have happened when the tx was added
// to the pool.
//
// ConfirmTx must not mutate the snapshot or the block.
func ConfirmTx(snapshot *state.Snapshot, block *bc.Block, tx *bc.Tx) error {
if block.Version == 1 && tx.Version != 1 {
return errors.WithDetailf(ErrBadTx, "unknown transaction version %d for block version 1", tx.Version)
}
if block.TimestampMS < tx.MinTime {
return errors.WithDetail(ErrBadTx, "block time is before transaction min time")
}
if tx.MaxTime > 0 && block.TimestampMS > tx.MaxTime {
return errors.WithDetail(ErrBadTx, "block time is after transaction max time")
}
for i, txin := range tx.Inputs {
if ii, ok := txin.TypedInput.(*bc.IssuanceInput); ok {
if txin.AssetVersion != 1 {
continue
}
if len(ii.Nonce) == 0 {
continue
}
if block.TimestampMS < tx.MinTime || block.TimestampMS > tx.MaxTime {
return errors.WithDetail(ErrBadTx, "timestamp outside issuance input's time window")
}
iHash, err := tx.IssuanceHash(i)
if err != nil {
return err
}
if _, ok2 := snapshot.Issuances[iHash]; ok2 {
return errors.WithDetail(ErrBadTx, "duplicate issuance transaction")
}
continue
}
// txin is a spend
// Lookup the prevout in the blockchain state tree.
k, val := state.OutputTreeItem(state.Prevout(txin))
if !snapshot.Tree.Contains(k, val) {
return errors.WithDetailf(ErrBadTx, "output %s for input %d is invalid", txin.Outpoint().String(), i)
}
}
return nil
}
// CheckTxWellFormed checks whether tx is "well-formed" (the
// context-free phase of validation):
// - inputs and outputs balance
// - no duplicate input commitments
// - input scripts pass
//
// Result is nil for well-formed transactions, ErrBadTx with
// supporting detail otherwise.
func CheckTxWellFormed(tx *bc.Tx) error {
if len(tx.Inputs) == 0 {
return errors.WithDetail(ErrBadTx, "inputs are missing")
}
if len(tx.Inputs) > math.MaxInt32 {
return errors.WithDetail(ErrBadTx, "number of inputs overflows uint32")
}
// Are all inputs issuances, all with asset version 1, and all with empty nonces?
allIssuancesWithEmptyNonces := true
for _, txin := range tx.Inputs {
if txin.AssetVersion != 1 {
allIssuancesWithEmptyNonces = false
break
}
ii, ok := txin.TypedInput.(*bc.IssuanceInput)
if !ok {
allIssuancesWithEmptyNonces = false
break
}
if len(ii.Nonce) > 0 {
allIssuancesWithEmptyNonces = false
break
}
}
if allIssuancesWithEmptyNonces {
return errors.WithDetail(ErrBadTx, "all inputs are issuances with empty nonce fields")
}
// Check that the transaction maximum time is greater than or equal to the
// minimum time, if it is greater than 0.
if tx.MaxTime > 0 && tx.MaxTime < tx.MinTime {
return errors.WithDetail(ErrBadTx, "positive maxtime must be >= mintime")
}
// Check that each input commitment appears only once. Also check that sums
// of inputs and outputs balance, and check that both input and output sums
// are less than 2^63 so that they don't overflow their int64 representation.
parity := make(map[bc.AssetID]int64)
for i, txin := range tx.Inputs {
if tx.Version == 1 && txin.AssetVersion != 1 {
return errors.WithDetailf(ErrBadTx, "unknown asset version %d in input %d for transaction version 1", txin.AssetVersion, i)
}
assetID := txin.AssetID()
if txin.Amount() > math.MaxInt64 {
return errors.WithDetail(ErrBadTx, "input value exceeds maximum value of int64")
}
sum, ok := checked.AddInt64(parity[assetID], int64(txin.Amount()))
if !ok {
return errors.WithDetailf(ErrBadTx, "adding input %d overflows the allowed asset amount", i)
}
parity[assetID] = sum
switch x := txin.TypedInput.(type) {
case *bc.IssuanceInput:
if tx.Version == 1 && x.VMVersion != 1 {
return errors.WithDetailf(ErrBadTx, "unknown vm version %d in input %d for transaction version 1", x.VMVersion, i)
}
if txin.AssetVersion != 1 {
continue
}
if len(x.Nonce) == 0 {
continue
}
if tx.MinTime == 0 || tx.MaxTime == 0 {
return errors.WithDetail(ErrBadTx, "issuance input with unbounded time window")
}
case *bc.SpendInput:
if tx.Version == 1 && x.VMVersion != 1 {
return errors.WithDetailf(ErrBadTx, "unknown vm version %d in input %d for transaction version 1", x.VMVersion, i)
}
}
for j := 0; j < i; j++ {
other := tx.Inputs[j]
if bytes.Equal(txin.InputCommitmentBytes(), other.InputCommitmentBytes()) {
return errors.WithDetailf(ErrBadTx, "input %d is a duplicate of %d", j, i)
}
}
}
if len(tx.Outputs) > math.MaxInt32 {
return errors.WithDetail(ErrBadTx, "number of outputs overflows int32")
}
// Check that every output has a valid value.
for i, txout := range tx.Outputs {
if tx.Version == 1 {
if txout.AssetVersion != 1 {
return errors.WithDetailf(ErrBadTx, "unknown asset version %d in output %d for transaction version 1", txout.AssetVersion, i)
}
if txout.VMVersion != 1 {
return errors.WithDetailf(ErrBadTx, "unknown vm version %d in output %d for transaction version 1", txout.VMVersion, i)
}
}
// Transactions cannot have zero-value outputs.
// If all inputs have zero value, tx therefore must have no outputs.
if txout.Amount == 0 {
return errors.WithDetail(ErrBadTx, "output value must be greater than 0")
}
if txout.Amount > math.MaxInt64 {
return errors.WithDetail(ErrBadTx, "output value exceeds maximum value of int64")
}
sum, ok := checked.SubInt64(parity[txout.AssetID], int64(txout.Amount))
if !ok {
return errors.WithDetailf(ErrBadTx, "adding output %d overflows the allowed asset amount", i)
}
parity[txout.AssetID] = sum
}
for asset, val := range parity {
if val != 0 {
return errors.WithDetailf(ErrBadTx, "amounts for asset %s are not balanced on inputs and outputs", asset)
}
}
if len(tx.Inputs) > math.MaxInt32 {
return errors.WithDetail(ErrBadTx, "number of inputs overflows int32")
}
for i := range tx.Inputs {
ok, err := vm.VerifyTxInput(tx, i)
if err == nil && !ok {
err = ErrFalseVMResult
}
if err != nil {
input := tx.Inputs[i]
var program []byte
if input.IsIssuance() {
program = input.IssuanceProgram()
} else {
program = input.ControlProgram()
}
scriptStr, _ := vm.Disassemble(program)
args := input.Arguments()
hexArgs := make([]string, 0, len(args))
for _, arg := range args {
hexArgs = append(hexArgs, hex.EncodeToString(arg))
}
return errors.WithDetailf(ErrBadTx, "validation failed in script execution, input %d (program [%s] args [%s]): %s", i, scriptStr, strings.Join(hexArgs, " "), err)
}
}
return nil
}
// ApplyTx updates the state tree with all the changes to the ledger.
func ApplyTx(snapshot *state.Snapshot, tx *bc.Tx) error {
for i, in := range tx.Inputs {
if ii, ok := in.TypedInput.(*bc.IssuanceInput); ok {
if len(ii.Nonce) > 0 {
iHash, err := tx.IssuanceHash(i)
if err != nil {
return err
}
snapshot.Issuances[iHash] = tx.MaxTime
}
continue
}
// Remove the consumed output from the state tree.
prevoutKey, _ := state.OutputTreeItem(state.Prevout(in))
err := snapshot.Tree.Delete(prevoutKey)
if err != nil {
return err
}
}
for i, out := range tx.Outputs {
if vmutil.IsUnspendable(out.ControlProgram) {
continue
}
// Insert new outputs into the state tree.
o := state.NewOutput(*out, bc.Outpoint{Hash: tx.Hash, Index: uint32(i)})
err := snapshot.Tree.Insert(state.OutputTreeItem(o))
if err != nil {
return err
}
}
return nil
}