forked from paulbellamy/zcash-light
/
transaction.go
875 lines (778 loc) · 23.6 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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
package zcash
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
"reflect"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
)
var (
ErrOverwinterTxVersionTooLow = fmt.Errorf("overwinter transaction version too low")
ErrUnknownTxVersionGroupID = fmt.Errorf("transaction has unknown version group id")
ErrTxExpiryHeightIsTooHigh = fmt.Errorf("transaction expiry height is too high")
ErrTxVersionTooLow = fmt.Errorf("transaction version too low")
ErrTxVersionTooHigh = fmt.Errorf("transaction version too high")
ErrNoTxInputs = fmt.Errorf("transaction has no inputs")
ErrNoTxOutputs = fmt.Errorf("transaction has no outputs")
ErrDuplicateTxInputs = fmt.Errorf("transaction contains duplicate inputs")
ErrDuplicateTxNullifiers = fmt.Errorf("transaction contains duplicate nullifiers")
ErrPrevOutIsNull = fmt.Errorf("transaction input refers to null previous output")
ErrCoinBaseTxHasJoinSplits = fmt.Errorf("coinbase transaction has joinsplits")
ErrCoinBaseTxHasOutputs = fmt.Errorf("coinbase transaction has outputs")
zeroHash chainhash.Hash
)
const (
MaxBlockBaseSize = 2000000
NumJoinSplitInputs = 2
NumJoinSplitOutputs = 2
SproutVersionGroupID uint32 = 0
OverwinterFlagMask uint32 = 0x80000000
OverwinterVersionGroupID = 0x03C48270
TxExpiryHeightThreshold uint32 = 500000000
SproutMinCurrentVersion uint32 = 1
SproutMaxCurrentVersion = 2
OverwinterMinCurrentVersion = 3
OverwinterMaxCurrentVersion = 3
)
type Transaction struct {
IsOverwinter bool
Version uint32
VersionGroupID uint32
Inputs []Input
Outputs []Output
LockTime uint32
ExpiryHeight uint32
ValueBalance int64
TemporaryUnknownValue uint16
JoinSplits []JoinSplit
JoinSplitPubKey [32]byte
JoinSplitSignature [64]byte
}
// TxHash generates the Hash for the transaction.
func (t *Transaction) TxHash() chainhash.Hash {
// Encode the transaction and calculate double sha256 on the result.
// Ignore the error returns since the only way the encode could fail
// is being out of memory or due to nil pointers, both of which would
// cause a run-time panic.
b, _ := t.MarshalBinary()
return chainhash.DoubleHashH(b)
}
func (t *Transaction) IsEqual(other *Transaction) bool {
switch {
case t == nil && other == nil:
return true
case t == nil || other == nil:
return false
case t.IsOverwinter != other.IsOverwinter:
return false
case t.Version != other.Version:
return false
case t.VersionGroupID != other.VersionGroupID:
return false
case t.LockTime != other.LockTime:
return false
case t.ExpiryHeight != other.ExpiryHeight:
return false
case string(t.JoinSplitPubKey[:]) != string(other.JoinSplitPubKey[:]):
return false
case string(t.JoinSplitSignature[:]) != string(other.JoinSplitSignature[:]):
return false
case len(t.Inputs) != len(other.Inputs):
return false
case len(t.Outputs) != len(other.Outputs):
return false
case len(t.JoinSplits) != len(other.JoinSplits):
return false
}
for i := range t.Inputs {
if !t.Inputs[i].IsEqual(other.Inputs[i]) {
return false
}
}
for i := range t.Outputs {
if !t.Outputs[i].IsEqual(other.Outputs[i]) {
return false
}
}
for i := range t.JoinSplits {
if !t.JoinSplits[i].IsEqual(other.JoinSplits[i]) {
return false
}
}
return true
}
func (t *Transaction) UnmarshalBinary(data []byte) error {
_, err := t.ReadFrom(bytes.NewReader(data))
return err
}
func (t *Transaction) ReadFrom(r io.Reader) (n int64, err error) {
counter := &countingReader{Reader: r}
for _, segment := range []func(io.Reader) error{
t.readVersion,
t.readVersionGroupID,
t.readInputs,
t.readOutputs,
readField(&t.LockTime),
t.readExpiryHeight,
t.readJoinSplits,
t.readJoinSplitPubKey,
t.readJoinSplitSignature,
} {
if err := segment(counter); err != nil {
return counter.N, err
}
}
return counter.N, nil
}
func (t *Transaction) readVersion(r io.Reader) error {
// Check the version
err := binary.Read(r, binary.LittleEndian, &t.Version)
if err != nil {
return err
}
t.IsOverwinter = (t.Version & OverwinterFlagMask) > 0
if t.IsOverwinter {
t.Version = t.Version &^ OverwinterFlagMask
}
return err
}
func (t *Transaction) readVersionGroupID(r io.Reader) error {
if !t.IsOverwinter {
return nil
}
return binary.Read(r, binary.LittleEndian, &t.VersionGroupID)
}
func (t *Transaction) readInputs(r io.Reader) error {
count, err := wire.ReadVarInt(r, 0)
if err != nil {
return err
}
if t.Version == 1 && count <= 0 {
return fmt.Errorf("txn must have transparent inputs")
}
for i := uint64(0); i < count; i++ {
var input Input
if _, err := input.ReadFrom(r); err != nil {
return err
}
t.Inputs = append(t.Inputs, input)
}
return nil
}
func (t *Transaction) readOutputs(r io.Reader) error {
count, err := wire.ReadVarInt(r, 0)
if err != nil {
return err
}
for i := uint64(0); i < count; i++ {
var output Output
if _, err := output.ReadFrom(r); err != nil {
return err
}
t.Outputs = append(t.Outputs, output)
}
return nil
}
// readScript reads a variable length byte array that represents a transaction
// script. It is encoded as a varInt containing the length of the array
// followed by the bytes themselves. An error is returned if the length is
// greater than the passed maxAllowed parameter which helps protect against
// memory exhuastion attacks and forced panics thorugh malformed messages. The
// fieldName parameter is only used for the error message so it provides more
// context in the error.
func readScript(r io.Reader, fieldName string) ([]byte, error) {
count, err := wire.ReadVarInt(r, 0)
if err != nil {
return nil, err
}
// Prevent byte array larger than the max message size. It would
// be possible to cause memory exhaustion and panics without a sane
// upper bound on this count.
if count > uint64(wire.MaxMessagePayload) {
return nil, fmt.Errorf(
"readScript: %s is larger than the max allowed size [count %d, max %d]",
fieldName, count, wire.MaxMessagePayload,
)
}
b := make([]byte, count)
if _, err := io.ReadFull(r, b); err != nil {
return nil, err
}
return b, nil
}
func (t *Transaction) readExpiryHeight(r io.Reader) error {
if !t.IsOverwinter {
return nil
}
return binary.Read(r, binary.LittleEndian, &t.ExpiryHeight)
}
func (t *Transaction) readJoinSplits(r io.Reader) error {
if t.Version <= 1 {
return nil
}
count, err := wire.ReadVarInt(r, 0)
if err != nil {
return err
}
for i := uint64(0); i < count; i++ {
var js JoinSplit
if _, err := js.ReadFrom(r); err != nil {
return err
}
t.JoinSplits = append(t.JoinSplits, js)
}
return nil
}
func (t *Transaction) readJoinSplitPubKey(r io.Reader) error {
if t.Version <= 1 || len(t.JoinSplits) <= 0 {
return nil
}
_, err := io.ReadFull(r, t.JoinSplitPubKey[:])
return err
}
func (t *Transaction) readJoinSplitSignature(r io.Reader) error {
if t.Version <= 1 || len(t.JoinSplits) <= 0 {
return nil
}
_, err := io.ReadFull(r, t.JoinSplitSignature[:])
return err
}
func (t *Transaction) MarshalBinary() ([]byte, error) {
buf := &bytes.Buffer{}
if _, err := t.WriteTo(buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (t *Transaction) WriteTo(w io.Writer) (n int64, err error) {
counter := &countingWriter{Writer: w}
for _, segment := range []func(io.Writer) error{
writeField(t.GetHeader()),
writeIf(t.IsOverwinter, writeField(t.VersionGroupID)),
t.writeInputs,
t.writeOutputs,
writeField(t.LockTime),
writeIf(t.IsOverwinter, writeField(t.ExpiryHeight)),
writeIf(t.Version >= 4, writeField(t.ValueBalance)),
writeIf(t.Version >= 4, writeField(t.TemporaryUnknownValue)),
writeIf(t.Version >= 2, t.writeJoinSplits),
writeIf(t.Version >= 2 && len(t.JoinSplits) > 0, writeBytes(t.JoinSplitPubKey[:])),
writeIf(t.Version >= 2 && len(t.JoinSplits) > 0, writeBytes(t.JoinSplitSignature[:])),
} {
if err := segment(counter); err != nil {
return counter.N, err
}
}
return counter.N, nil
}
func (t *Transaction) GetHeader() uint32 {
if t.IsOverwinter {
return t.Version | OverwinterFlagMask
}
return t.Version
}
func (t *Transaction) writeInputs(w io.Writer) error {
if err := wire.WriteVarInt(w, 0, uint64(len(t.Inputs))); err != nil {
return err
}
for _, input := range t.Inputs {
if _, err := input.WriteTo(w); err != nil {
return err
}
}
return nil
}
func (t *Transaction) writeOutputs(w io.Writer) error {
if err := wire.WriteVarInt(w, 0, uint64(len(t.Outputs))); err != nil {
return err
}
for _, output := range t.Outputs {
if _, err := output.WriteTo(w); err != nil {
return err
}
}
return nil
}
func (t *Transaction) writeJoinSplits(w io.Writer) error {
if err := wire.WriteVarInt(w, 0, uint64(len(t.JoinSplits))); err != nil {
return err
}
for _, js := range t.JoinSplits {
if _, err := js.WriteTo(w); err != nil {
return err
}
}
return nil
}
func (tx *Transaction) Validate(params *chaincfg.Params) error {
if !tx.IsOverwinter && tx.Version < SproutMinCurrentVersion {
return ErrTxVersionTooLow
} else if tx.IsOverwinter {
if tx.Version < OverwinterMinCurrentVersion {
return ErrOverwinterTxVersionTooLow
}
if tx.VersionGroupID != OverwinterVersionGroupID {
return ErrUnknownTxVersionGroupID
}
if tx.ExpiryHeight >= TxExpiryHeightThreshold {
return ErrTxExpiryHeightIsTooHigh
}
}
// Transactions can contain empty `vin` and `vout` so long as
// `vjoinsplit` is non-empty.
if len(tx.Inputs) == 0 && len(tx.JoinSplits) == 0 {
return ErrNoTxInputs
}
if len(tx.Outputs) == 0 && len(tx.JoinSplits) == 0 {
return ErrNoTxOutputs
}
serialized, err := tx.MarshalBinary()
if err != nil {
return err
}
serializedTxSize := len(serialized)
// TODO: Figure out the max zcash block base size
if serializedTxSize > MaxBlockBaseSize {
return fmt.Errorf("serialized transaction is too big - got %d, max %d", serializedTxSize, MaxBlockBaseSize)
}
// Ensure the transaction amounts are in range. Each transaction
// output must not be negative or more than the max allowed per
// transaction. Also, the total of all outputs must abide by the same
// restrictions. All amounts in a transaction are in a unit value known
// as a satoshi. One bitcoin is a quantity of satoshi as defined by the
// SatoshiPerBitcoin constant.
var totalSatoshi int64
for _, txOut := range tx.Outputs {
if txOut.Value < 0 {
return fmt.Errorf("transaction output has negative value of %v", txOut.Value)
}
if txOut.Value > btcutil.MaxSatoshi {
return fmt.Errorf("transaction output value of %v is higher than max allowed value of %v", txOut.Value, btcutil.MaxSatoshi)
}
totalSatoshi += txOut.Value
if !MoneyRange(totalSatoshi) {
return fmt.Errorf("txout total out of range")
}
}
// Ensure that joinsplit values are well-formed
for _, joinSplit := range tx.JoinSplits {
if joinSplit.VPubOld < 0 {
return fmt.Errorf("joinsplit.VPubOld negative")
}
if joinSplit.VPubNew < 0 {
return fmt.Errorf("joinsplit.VPubNew negative")
}
if joinSplit.VPubOld > btcutil.MaxSatoshi {
return fmt.Errorf("joinsplit.VPubOld too high")
}
if joinSplit.VPubNew > btcutil.MaxSatoshi {
return fmt.Errorf("joinsplit.VPubNew too high")
}
if joinSplit.VPubNew != 0 && joinSplit.VPubOld != 0 {
return fmt.Errorf("joinsplit.VPubNew and joinsplit.VPubOld both nonzero")
}
totalSatoshi += int64(joinSplit.VPubOld)
if !MoneyRange(totalSatoshi) {
return fmt.Errorf("txout total out of range")
}
}
// Ensure input values do not exceed btcutil.MaxSatoshi
// We have not resolved the txin values at this stage,
// but we do know what the joinsplits claim to add
// to the value pool.
{
var nValueIn int64 = 0
for _, joinSplit := range tx.JoinSplits {
nValueIn += int64(joinSplit.VPubNew)
if !MoneyRange(int64(joinSplit.VPubNew)) || !MoneyRange(nValueIn) {
return fmt.Errorf("txin total out of range")
}
}
}
// Check for duplicate transaction inputs.
existingTxOut := make(map[wire.OutPoint]struct{})
for _, txIn := range tx.Inputs {
if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists {
return ErrDuplicateTxInputs
}
existingTxOut[txIn.PreviousOutPoint] = struct{}{}
}
// Check for duplicate joinsplit nullifiers in this transaction
existingNullifiers := make(map[string]struct{})
for _, joinSplit := range tx.JoinSplits {
for _, nf := range joinSplit.Nullifiers {
key := string(nf[:])
if _, exists := existingNullifiers[key]; exists {
return ErrDuplicateTxNullifiers
}
existingNullifiers[key] = struct{}{}
}
}
if tx.IsCoinBase() {
// There should be no joinsplits in a coinbase transaction
if len(tx.JoinSplits) > 0 {
return ErrCoinBaseTxHasJoinSplits
}
// Coinbase script length must be between min and max length.
slen := len(tx.Inputs[0].SignatureScript)
if slen < blockchain.MinCoinbaseScriptLen || slen > blockchain.MaxCoinbaseScriptLen {
return fmt.Errorf("coinbase transaction script length of %d is out of range (min: %d, max: %d)", slen, blockchain.MinCoinbaseScriptLen, blockchain.MaxCoinbaseScriptLen)
}
// Coinbase txns must have only founders' reward outputs
for _, output := range tx.Outputs {
if !output.IsFoundersReward(params) {
return ErrCoinBaseTxHasOutputs
}
}
} else {
// Previous transaction outputs referenced by the inputs to this
// transaction must not be null.
for _, txIn := range tx.Inputs {
prevOut := &txIn.PreviousOutPoint
if isNullOutpoint(prevOut) {
return ErrPrevOutIsNull
}
}
}
return nil
}
func MoneyRange(v int64) bool {
return 0 <= v && v < btcutil.MaxSatoshi
}
// isNullOutpoint determines whether or not a previous transaction output point
// is set.
func isNullOutpoint(outpoint *wire.OutPoint) bool {
if outpoint.Index == math.MaxUint32 && outpoint.Hash == zeroHash {
return true
}
return false
}
// IsCoinBase determines whether or not a transaction is a coinbase. A
// coinbase is a special transaction created by miners that has no inputs.
// This is represented in the block chain by a transaction with a single input
// that has a previous output transaction index set to the maximum value along
// with a zero hash.
func (t *Transaction) IsCoinBase() bool {
// A coin base must only have one transaction input.
if len(t.Inputs) != 1 {
return false
}
// The previous output of a coin base must have a max value index and
// a zero hash.
prevOut := &t.Inputs[0].PreviousOutPoint
if prevOut.Index != math.MaxUint32 || prevOut.Hash != zeroHash {
return false
}
return true
}
type countingReader struct {
io.Reader
N int64
}
func (c *countingReader) Read(p []byte) (n int, err error) {
n, err = c.Reader.Read(p)
c.N += int64(n)
return n, err
}
type countingWriter struct {
io.Writer
N int64
}
func (c *countingWriter) Write(p []byte) (n int, err error) {
n, err = c.Writer.Write(p)
c.N += int64(n)
return n, err
}
type Input struct {
PreviousOutPoint wire.OutPoint
SignatureScript []byte
Sequence uint32
}
func (i Input) IsEqual(other Input) bool {
if !OutpointsEqual(i.PreviousOutPoint, other.PreviousOutPoint) {
return false
}
if string(i.SignatureScript) != string(other.SignatureScript) {
return false
}
if i.Sequence != other.Sequence {
return false
}
return true
}
func (i *Input) ReadFrom(r io.Reader) (int64, error) {
counter := &countingReader{Reader: r}
if err := i.readOutPoint(counter); err != nil {
return counter.N, err
}
var err error
i.SignatureScript, err = readScript(counter, "transaction input signature script")
if err != nil {
return counter.N, err
}
if err := binary.Read(counter, binary.LittleEndian, &i.Sequence); err != nil {
return counter.N, err
}
return counter.N, nil
}
// readOutPoint reads the next sequence of bytes from r as an OutPoint.
func (i *Input) readOutPoint(r io.Reader) error {
if _, err := io.ReadFull(r, i.PreviousOutPoint.Hash[:]); err != nil {
return err
}
if err := binary.Read(r, binary.LittleEndian, &i.PreviousOutPoint.Index); err != nil {
return err
}
return nil
}
func (i *Input) WriteTo(w io.Writer) (int64, error) {
counter := &countingWriter{Writer: w}
if err := i.writeOutPoint(counter); err != nil {
return counter.N, err
}
if err := writeScript(counter, i.SignatureScript); err != nil {
return counter.N, err
}
if err := writeField(i.Sequence)(counter); err != nil {
return counter.N, err
}
return counter.N, nil
}
func writeScript(w io.Writer, script []byte) error {
return wire.WriteVarBytes(w, 0, script)
}
// writeOutPoint encodes op to the bitcoin/zcash protocol encoding for an OutPoint
// to w.
func (i *Input) writeOutPoint(w io.Writer) error {
if _, err := w.Write(i.PreviousOutPoint.Hash[:]); err != nil {
return err
}
return binary.Write(w, binary.LittleEndian, i.PreviousOutPoint.Index)
}
type Output struct {
Value int64
ScriptPubKey []byte
}
func (o Output) IsEqual(other Output) bool {
if o.Value != other.Value {
return false
}
if string(o.ScriptPubKey) != string(other.ScriptPubKey) {
return false
}
return true
}
func (o *Output) ReadFrom(r io.Reader) (int64, error) {
counter := &countingReader{Reader: r}
if err := binary.Read(counter, binary.LittleEndian, &o.Value); err != nil {
return counter.N, err
}
var err error
o.ScriptPubKey, err = readScript(counter, "transaction output public key script")
return counter.N, err
}
func (o *Output) WriteTo(w io.Writer) (int64, error) {
counter := &countingWriter{Writer: w}
if err := writeField(o.Value)(counter); err != nil {
return counter.N, err
}
err := writeScript(counter, o.ScriptPubKey)
return counter.N, err
}
// SerializeSize returns the number of bytes it would take to serialize the
// the transaction output.
func (o *Output) SerializeSize() int {
return 8 + wire.VarIntSerializeSize(uint64(len(o.ScriptPubKey))) + len(o.ScriptPubKey)
}
func (o *Output) IsFoundersReward(params *chaincfg.Params) bool {
// If we knew the block height, and chain params, we could check exactly
// which founders reward address and the amount it should be.
for _, template := range founderRewardScripts[params.Name] {
if string(o.ScriptPubKey) == string(template) {
return true
}
}
return false
}
type JoinSplit struct {
// A value v_{pub}^{old} that the JoinSplit transfer removes from the
// transparent value pool.
VPubOld uint64
// A value v_{pub}^{new} that the JoinSplit transfer inserts into the
// transparent value pool.
VPubNew uint64
// A merkle root of the note commitment tree at some block height in the
// past, or the merkle root produced by a previous JoinSplit transfer in this
// transaction.
//
// JoinSplits are always anchored to a root in the note commitment tree at
// some point in the blockchain history or in the history of the current
// transaction.
Anchor [32]byte
// A sequence of nullifiers of the input notes $nf$_{1..N^{old}}^{old}
//
// Nullifiers are used to prevent double-spends. They are derived from the
// secrets placed in the note and the secret spend-authority key known by the
// spender.
Nullifiers [NumJoinSplitInputs][32]byte
// A sequence of note commitments for the output notes $cm$_{1..N^{new}}^{new}
//
// Note commitments are introduced into the commitment tree, blinding the
// public about the values and destinations involved in the JoinSplit. The
// presence of a commitment in the note commitment tree is required to spend
// it.
Commitments [NumJoinSplitOutputs][32]byte
// A Curve25519 public key epk.
EphemeralKey [32]byte
// A 256-bit seed that must be chosen independently at random for each
// JoinSplit description.
RandomSeed [32]byte
// A sequence of message authentication tags h_{1..N^{old}} that bind h^{Sig}
// to each a_{sk} of the JoinSplit description.
//
// The verification of the JoinSplit requires these MACs to be provided as an
// input.
Macs [NumJoinSplitInputs][32]byte
// An encoding of the zero-knowledge proof \pi_{ZKJoinSplit}
//
// This is a zk-SNARK which ensures that this JoinSplit is valid.
Proof [296]byte
// A sequence of ciphertext components for the encrypted output notes,
// C_{1..N^{new}}^{enc}
//
// These contain trapdoors, values and other information that the recipient
// needs, including a memo field. It is encrypted using the scheme
// implemented in crypto/NoteEncryption.cpp
Ciphertexts [NumJoinSplitOutputs][601]byte
}
func (js JoinSplit) IsEqual(other JoinSplit) bool {
return reflect.DeepEqual(js, other)
}
func (js *JoinSplit) ReadFrom(r io.Reader) (int64, error) {
counter := &countingReader{Reader: r}
for _, segment := range []func(io.Reader) error{
readField(&js.VPubOld),
readField(&js.VPubNew),
readBytes(js.Anchor[:]),
readByteArray32(js.Nullifiers[:]),
readByteArray32(js.Commitments[:]),
readBytes(js.EphemeralKey[:]),
readBytes(js.RandomSeed[:]),
readByteArray32(js.Macs[:]),
readBytes(js.Proof[:]),
js.readCiphertexts,
} {
if err := segment(counter); err != nil {
return counter.N, err
}
}
return counter.N, nil
}
// readCiphertexts is needed because ciphertexts is an odd size (not 32 bytes).
// We could probably eliminate this with some type inference magic, but...
func (js *JoinSplit) readCiphertexts(r io.Reader) error {
for _, x := range js.Ciphertexts {
if _, err := io.ReadFull(r, x[:]); err != nil {
return err
}
}
return nil
}
func readField(v interface{}) func(r io.Reader) error {
return func(r io.Reader) error { return binary.Read(r, binary.LittleEndian, v) }
}
func readBytes(b []byte) func(r io.Reader) error {
return func(r io.Reader) error {
_, err := io.ReadFull(r, b)
return err
}
}
func readByteArray32(a [][32]byte) func(r io.Reader) error {
return func(r io.Reader) error {
for i, x := range a {
if _, err := io.ReadFull(r, x[:]); err != nil {
return err
}
a[i] = x // x is a copy, so we have to set it back
}
return nil
}
}
func (js *JoinSplit) WriteTo(w io.Writer) (n int64, err error) {
counter := &countingWriter{Writer: w}
for _, segment := range []func(io.Writer) error{
writeField(js.VPubOld),
writeField(js.VPubNew),
writeBytes(js.Anchor[:]),
writeByteArray32(js.Nullifiers[:]),
writeByteArray32(js.Commitments[:]),
writeBytes(js.EphemeralKey[:]),
writeBytes(js.RandomSeed[:]),
writeByteArray32(js.Macs[:]),
writeBytes(js.Proof[:]),
js.writeCiphertexts,
} {
if err := segment(counter); err != nil {
return counter.N, err
}
}
return counter.N, nil
}
// writeCiphertexts is needed because ciphertexts is an odd size (not 32
// bytes). We could probably eliminate this with some type inference magic,
// but...
func (js *JoinSplit) writeCiphertexts(w io.Writer) error {
for _, x := range js.Ciphertexts {
if _, err := w.Write(x[:]); err != nil {
return err
}
}
return nil
}
func writeIf(pred bool, f func(w io.Writer) error) func(w io.Writer) error {
if pred {
return f
}
return func(w io.Writer) error { return nil }
}
func writeField(v interface{}) func(w io.Writer) error {
return func(w io.Writer) error {
return binary.Write(w, binary.LittleEndian, v)
}
}
func writeBytes(v []byte) func(w io.Writer) error {
return func(w io.Writer) error {
_, err := w.Write(v)
return err
}
}
func writeByteArray32(a [][32]byte) func(w io.Writer) error {
return func(w io.Writer) error {
for _, x := range a {
if _, err := w.Write(x[:]); err != nil {
return err
}
}
return nil
}
}
func writeAll(w io.Writer, items ...interface{}) error {
for _, item := range items {
if b, ok := item.([]byte); ok {
if err := writeBytes(b)(w); err != nil {
return err
}
} else {
if err := writeField(item)(w); err != nil {
return err
}
}
}
return nil
}