-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathtransaction.go
631 lines (550 loc) · 16.7 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// Copyright (c) 2019-2020 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php .
// Package parser deserializes (full) transactions (zcashd).
package parser
import (
"crypto/sha256"
"fmt"
"github.com/pkg/errors"
"github.com/zcash/lightwalletd/parser/internal/bytestring"
"github.com/zcash/lightwalletd/walletrpc"
)
type rawTransaction struct {
fOverwintered bool
version uint32
nVersionGroupID uint32
consensusBranchID uint32
transparentInputs []txIn
transparentOutputs []txOut
//nLockTime uint32
//nExpiryHeight uint32
//valueBalanceSapling int64
shieldedSpends []spend
shieldedOutputs []output
joinSplits []joinSplit
//joinSplitPubKey []byte
//joinSplitSig []byte
//bindingSigSapling []byte
orchardActions []action
}
// Txin format as described in https://en.bitcoin.it/wiki/Transaction
type txIn struct {
// SHA256d of a previous (to-be-used) transaction
//PrevTxHash []byte
// Index of the to-be-used output in the previous tx
//PrevTxOutIndex uint32
// CompactSize-prefixed, could be a pubkey or a script
ScriptSig []byte
// Bitcoin: "normally 0xFFFFFFFF; irrelevant unless transaction's lock_time > 0"
//SequenceNumber uint32
}
func (tx *txIn) ParseFromSlice(data []byte) ([]byte, error) {
s := bytestring.String(data)
if !s.Skip(32) {
return nil, errors.New("could not skip PrevTxHash")
}
if !s.Skip(4) {
return nil, errors.New("could not skip PrevTxOutIndex")
}
if !s.ReadCompactLengthPrefixed((*bytestring.String)(&tx.ScriptSig)) {
return nil, errors.New("could not read ScriptSig")
}
if !s.Skip(4) {
return nil, errors.New("could not skip SequenceNumber")
}
return []byte(s), nil
}
// Txout format as described in https://en.bitcoin.it/wiki/Transaction
type txOut struct {
// Non-negative int giving the number of zatoshis to be transferred
Value uint64
// Script. CompactSize-prefixed.
//Script []byte
}
func (tx *txOut) ParseFromSlice(data []byte) ([]byte, error) {
s := bytestring.String(data)
if !s.Skip(8) {
return nil, errors.New("could not skip txOut value")
}
if !s.SkipCompactLengthPrefixed() {
return nil, errors.New("could not skip txOut script")
}
return []byte(s), nil
}
// parse the transparent parts of the transaction
func (tx *Transaction) ParseTransparent(data []byte) ([]byte, error) {
s := bytestring.String(data)
var txInCount int
if !s.ReadCompactSize(&txInCount) {
return nil, errors.New("could not read tx_in_count")
}
var err error
tx.transparentInputs = make([]txIn, txInCount)
for i := 0; i < txInCount; i++ {
ti := &tx.transparentInputs[i]
s, err = ti.ParseFromSlice([]byte(s))
if err != nil {
return nil, errors.Wrap(err, "while parsing transparent input")
}
}
var txOutCount int
if !s.ReadCompactSize(&txOutCount) {
return nil, errors.New("could not read tx_out_count")
}
tx.transparentOutputs = make([]txOut, txOutCount)
for i := 0; i < txOutCount; i++ {
to := &tx.transparentOutputs[i]
s, err = to.ParseFromSlice([]byte(s))
if err != nil {
return nil, errors.Wrap(err, "while parsing transparent output")
}
}
return []byte(s), nil
}
// spend is a Sapling Spend Description as described in 7.3 of the Zcash
// protocol specification.
type spend struct {
//cv []byte // 32
//anchor []byte // 32
nullifier []byte // 32
//rk []byte // 32
//zkproof []byte // 192
//spendAuthSig []byte // 64
}
func (p *spend) ParseFromSlice(data []byte, version uint32) ([]byte, error) {
s := bytestring.String(data)
if !s.Skip(32) {
return nil, errors.New("could not skip cv")
}
if version <= 4 && !s.Skip(32) {
return nil, errors.New("could not skip anchor")
}
if !s.ReadBytes(&p.nullifier, 32) {
return nil, errors.New("could not read nullifier")
}
if !s.Skip(32) {
return nil, errors.New("could not skip rk")
}
if version <= 4 && !s.Skip(192) {
return nil, errors.New("could not skip zkproof")
}
if version <= 4 && !s.Skip(64) {
return nil, errors.New("could not skip spendAuthSig")
}
return []byte(s), nil
}
func (p *spend) ToCompact() *walletrpc.CompactSaplingSpend {
return &walletrpc.CompactSaplingSpend{
Nf: p.nullifier,
}
}
// output is a Sapling Output Description as described in section 7.4 of the
// Zcash protocol spec.
type output struct {
//cv []byte // 32
cmu []byte // 32
ephemeralKey []byte // 32
encCiphertext []byte // 580
//outCiphertext []byte // 80
//zkproof []byte // 192
}
func (p *output) ParseFromSlice(data []byte, version uint32) ([]byte, error) {
s := bytestring.String(data)
if !s.Skip(32) {
return nil, errors.New("could not skip cv")
}
if !s.ReadBytes(&p.cmu, 32) {
return nil, errors.New("could not read cmu")
}
if !s.ReadBytes(&p.ephemeralKey, 32) {
return nil, errors.New("could not read ephemeralKey")
}
if !s.ReadBytes(&p.encCiphertext, 580) {
return nil, errors.New("could not read encCiphertext")
}
if !s.Skip(80) {
return nil, errors.New("could not skip outCiphertext")
}
if version <= 4 && !s.Skip(192) {
return nil, errors.New("could not skip zkproof")
}
return []byte(s), nil
}
func (p *output) ToCompact() *walletrpc.CompactSaplingOutput {
return &walletrpc.CompactSaplingOutput{
Cmu: p.cmu,
Epk: p.ephemeralKey,
Ciphertext: p.encCiphertext[:52],
}
}
// joinSplit is a JoinSplit description as described in 7.2 of the Zcash
// protocol spec. Its exact contents differ by transaction version and network
// upgrade level. Only version 4 is supported, no need for proofPHGR13.
type joinSplit struct {
//vpubOld uint64
//vpubNew uint64
//anchor []byte // 32
//nullifiers [2][]byte // 64 [N_old][32]byte
//commitments [2][]byte // 64 [N_new][32]byte
//ephemeralKey []byte // 32
//randomSeed []byte // 32
//vmacs [2][]byte // 64 [N_old][32]byte
//proofGroth16 []byte // 192 (version 4 only)
//encCiphertexts [2][]byte // 1202 [N_new][601]byte
}
func (p *joinSplit) ParseFromSlice(data []byte) ([]byte, error) {
s := bytestring.String(data)
if !s.Skip(8) {
return nil, errors.New("could not skip vpubOld")
}
if !s.Skip(8) {
return nil, errors.New("could not skip vpubNew")
}
if !s.Skip(32) {
return nil, errors.New("could not skip anchor")
}
for i := 0; i < 2; i++ {
if !s.Skip(32) {
return nil, errors.New("could not skip a nullifier")
}
}
for i := 0; i < 2; i++ {
if !s.Skip(32) {
return nil, errors.New("could not skip a commitment")
}
}
if !s.Skip(32) {
return nil, errors.New("could not skip ephemeralKey")
}
if !s.Skip(32) {
return nil, errors.New("could not skip randomSeed")
}
for i := 0; i < 2; i++ {
if !s.Skip(32) {
return nil, errors.New("could not skip a vmac")
}
}
if !s.Skip(192) {
return nil, errors.New("could not skip Groth16 proof")
}
for i := 0; i < 2; i++ {
if !s.Skip(601) {
return nil, errors.New("could not skip an encCiphertext")
}
}
return []byte(s), nil
}
type action struct {
//cv []byte // 32
nullifier []byte // 32
//rk []byte // 32
cmx []byte // 32
ephemeralKey []byte // 32
encCiphertext []byte // 580
//outCiphertext []byte // 80
}
func (a *action) ParseFromSlice(data []byte) ([]byte, error) {
s := bytestring.String(data)
if !s.Skip(32) {
return nil, errors.New("could not read action cv")
}
if !s.ReadBytes(&a.nullifier, 32) {
return nil, errors.New("could not read action nullifier")
}
if !s.Skip(32) {
return nil, errors.New("could not read action rk")
}
if !s.ReadBytes(&a.cmx, 32) {
return nil, errors.New("could not read action cmx")
}
if !s.ReadBytes(&a.ephemeralKey, 32) {
return nil, errors.New("could not read action ephemeralKey")
}
if !s.ReadBytes(&a.encCiphertext, 580) {
return nil, errors.New("could not read action encCiphertext")
}
if !s.Skip(80) {
return nil, errors.New("could not read action outCiphertext")
}
return []byte(s), nil
}
func (p *action) ToCompact() *walletrpc.CompactOrchardAction {
return &walletrpc.CompactOrchardAction{
Nullifier: p.nullifier,
Cmx: p.cmx,
EphemeralKey: p.ephemeralKey,
Ciphertext: p.encCiphertext[:52],
}
}
// Transaction encodes a full (zcashd) transaction.
type Transaction struct {
*rawTransaction
rawBytes []byte
cachedTxID []byte // cached for performance
}
// GetDisplayHash returns the transaction hash in big-endian display order.
func (tx *Transaction) GetDisplayHash() []byte {
if tx.cachedTxID != nil {
return tx.cachedTxID
}
// SHA256d
digest := sha256.Sum256(tx.rawBytes)
digest = sha256.Sum256(digest[:])
// Convert to big-endian
tx.cachedTxID = Reverse(digest[:])
return tx.cachedTxID
}
// GetEncodableHash returns the transaction hash in little-endian wire format order.
func (tx *Transaction) GetEncodableHash() []byte {
digest := sha256.Sum256(tx.rawBytes)
digest = sha256.Sum256(digest[:])
return digest[:]
}
// Bytes returns a full transaction's raw bytes.
func (tx *Transaction) Bytes() []byte {
return tx.rawBytes
}
// HasShieldedElements indicates whether a transaction has
// at least one shielded input or output.
func (tx *Transaction) HasShieldedElements() bool {
nshielded := len(tx.shieldedSpends) + len(tx.shieldedOutputs) + len(tx.orchardActions)
return tx.version >= 4 && nshielded > 0
}
// ToCompact converts the given (full) transaction to compact format.
func (tx *Transaction) ToCompact(index int) *walletrpc.CompactTx {
ctx := &walletrpc.CompactTx{
Index: uint64(index), // index is contextual
Hash: tx.GetEncodableHash(),
//Fee: 0, // TODO: calculate fees
Spends: make([]*walletrpc.CompactSaplingSpend, len(tx.shieldedSpends)),
Outputs: make([]*walletrpc.CompactSaplingOutput, len(tx.shieldedOutputs)),
Actions: make([]*walletrpc.CompactOrchardAction, len(tx.orchardActions)),
}
for i, spend := range tx.shieldedSpends {
ctx.Spends[i] = spend.ToCompact()
}
for i, output := range tx.shieldedOutputs {
ctx.Outputs[i] = output.ToCompact()
}
for i, a := range tx.orchardActions {
ctx.Actions[i] = a.ToCompact()
}
return ctx
}
// parse version 4 transaction data after the nVersionGroupId field.
func (tx *Transaction) parseV4(data []byte) ([]byte, error) {
s := bytestring.String(data)
var err error
if tx.nVersionGroupID != 0x892F2085 {
return nil, errors.New(fmt.Sprintf("version group ID %x must be 0x892F2085", tx.nVersionGroupID))
}
s, err = tx.ParseTransparent([]byte(s))
if err != nil {
return nil, err
}
if !s.Skip(4) {
return nil, errors.New("could not skip nLockTime")
}
if !s.Skip(4) {
return nil, errors.New("could not skip nExpiryHeight")
}
var spendCount, outputCount int
if !s.Skip(8) {
return nil, errors.New("could not skip valueBalance")
}
if !s.ReadCompactSize(&spendCount) {
return nil, errors.New("could not read nShieldedSpend")
}
tx.shieldedSpends = make([]spend, spendCount)
for i := 0; i < spendCount; i++ {
newSpend := &tx.shieldedSpends[i]
s, err = newSpend.ParseFromSlice([]byte(s), 4)
if err != nil {
return nil, errors.Wrap(err, "while parsing shielded Spend")
}
}
if !s.ReadCompactSize(&outputCount) {
return nil, errors.New("could not read nShieldedOutput")
}
tx.shieldedOutputs = make([]output, outputCount)
for i := 0; i < outputCount; i++ {
newOutput := &tx.shieldedOutputs[i]
s, err = newOutput.ParseFromSlice([]byte(s), 4)
if err != nil {
return nil, errors.Wrap(err, "while parsing shielded Output")
}
}
var joinSplitCount int
if !s.ReadCompactSize(&joinSplitCount) {
return nil, errors.New("could not read nJoinSplit")
}
tx.joinSplits = make([]joinSplit, joinSplitCount)
if joinSplitCount > 0 {
for i := 0; i < joinSplitCount; i++ {
js := &tx.joinSplits[i]
s, err = js.ParseFromSlice([]byte(s))
if err != nil {
return nil, errors.Wrap(err, "while parsing JoinSplit")
}
}
if !s.Skip(32) {
return nil, errors.New("could not skip joinSplitPubKey")
}
if !s.Skip(64) {
return nil, errors.New("could not skip joinSplitSig")
}
}
if spendCount+outputCount > 0 && !s.Skip(64) {
return nil, errors.New("could not skip bindingSigSapling")
}
return s, nil
}
// parse version 5 transaction data after the nVersionGroupId field.
func (tx *Transaction) parseV5(data []byte) ([]byte, error) {
s := bytestring.String(data)
var err error
if !s.ReadUint32(&tx.consensusBranchID) {
return nil, errors.New("could not read nVersionGroupId")
}
if tx.nVersionGroupID != 0x26A7270A {
return nil, errors.New(fmt.Sprintf("version group ID %d must be 0x26A7270A", tx.nVersionGroupID))
}
if !s.Skip(4) {
return nil, errors.New("could not skip nLockTime")
}
if !s.Skip(4) {
return nil, errors.New("could not skip nExpiryHeight")
}
s, err = tx.ParseTransparent([]byte(s))
if err != nil {
return nil, err
}
var spendCount, outputCount int
if !s.ReadCompactSize(&spendCount) {
return nil, errors.New("could not read nShieldedSpend")
}
if spendCount >= (1 << 16) {
return nil, errors.New(fmt.Sprintf("spentCount (%d) must be less than 2^16", spendCount))
}
tx.shieldedSpends = make([]spend, spendCount)
for i := 0; i < spendCount; i++ {
newSpend := &tx.shieldedSpends[i]
s, err = newSpend.ParseFromSlice([]byte(s), tx.version)
if err != nil {
return nil, errors.Wrap(err, "while parsing shielded Spend")
}
}
if !s.ReadCompactSize(&outputCount) {
return nil, errors.New("could not read nShieldedOutput")
}
if outputCount >= (1 << 16) {
return nil, errors.New(fmt.Sprintf("outputCount (%d) must be less than 2^16", outputCount))
}
tx.shieldedOutputs = make([]output, outputCount)
for i := 0; i < outputCount; i++ {
newOutput := &tx.shieldedOutputs[i]
s, err = newOutput.ParseFromSlice([]byte(s), tx.version)
if err != nil {
return nil, errors.Wrap(err, "while parsing shielded Output")
}
}
if spendCount+outputCount > 0 && !s.Skip(8) {
return nil, errors.New("could not read valueBalance")
}
if spendCount > 0 && !s.Skip(32) {
return nil, errors.New("could not skip anchorSapling")
}
if !s.Skip(192 * spendCount) {
return nil, errors.New("could not skip vSpendProofsSapling")
}
if !s.Skip(64 * spendCount) {
return nil, errors.New("could not skip vSpendAuthSigsSapling")
}
if !s.Skip(192 * outputCount) {
return nil, errors.New("could not skip vOutputProofsSapling")
}
if spendCount+outputCount > 0 && !s.Skip(64) {
return nil, errors.New("could not skip bindingSigSapling")
}
var actionsCount int
if !s.ReadCompactSize(&actionsCount) {
return nil, errors.New("could not read nActionsOrchard")
}
if actionsCount >= (1 << 16) {
return nil, errors.New(fmt.Sprintf("actionsCount (%d) must be less than 2^16", actionsCount))
}
tx.orchardActions = make([]action, actionsCount)
for i := 0; i < actionsCount; i++ {
a := &tx.orchardActions[i]
s, err = a.ParseFromSlice([]byte(s))
if err != nil {
return nil, errors.Wrap(err, "while parsing orchard action")
}
}
if actionsCount > 0 {
if !s.Skip(1) {
return nil, errors.New("could not skip flagsOrchard")
}
if !s.Skip(8) {
return nil, errors.New("could not skip valueBalanceOrchard")
}
if !s.Skip(32) {
return nil, errors.New("could not skip anchorOrchard")
}
var proofsCount int
if !s.ReadCompactSize(&proofsCount) {
return nil, errors.New("could not read sizeProofsOrchard")
}
if !s.Skip(proofsCount) {
return nil, errors.New("could not skip proofsOrchard")
}
if !s.Skip(64 * actionsCount) {
return nil, errors.New("could not skip vSpendAuthSigsOrchard")
}
if !s.Skip(64) {
return nil, errors.New("could not skip bindingSigOrchard")
}
}
return s, nil
}
// ParseFromSlice deserializes a single transaction from the given data.
func (tx *Transaction) ParseFromSlice(data []byte) ([]byte, error) {
s := bytestring.String(data)
// declare here to prevent shadowing problems in cryptobyte assignments
var err error
var header uint32
if !s.ReadUint32(&header) {
return nil, errors.New("could not read header")
}
tx.fOverwintered = (header >> 31) == 1
if !tx.fOverwintered {
return nil, errors.New("fOverwinter flag must be set")
}
tx.version = header & 0x7FFFFFFF
if tx.version < 4 {
return nil, errors.New(fmt.Sprintf("version number %d must be greater or equal to 4", tx.version))
}
if !s.ReadUint32(&tx.nVersionGroupID) {
return nil, errors.New("could not read nVersionGroupId")
}
// parse the main part of the transaction
if tx.version <= 4 {
s, err = tx.parseV4([]byte(s))
} else {
s, err = tx.parseV5([]byte(s))
}
if err != nil {
return nil, err
}
// TODO: implement rawBytes with MarshalBinary() instead
txLen := len(data) - len(s)
tx.rawBytes = data[:txLen]
return []byte(s), nil
}
// NewTransaction is the constructor for a full transaction.
func NewTransaction() *Transaction {
return &Transaction{
rawTransaction: new(rawTransaction),
}
}