/
transactions.go
1827 lines (1646 loc) · 66.3 KB
/
transactions.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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package types
import (
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"github.com/threefoldtech/rivine/crypto"
"github.com/threefoldtech/rivine/pkg/encoding/rivbin"
"github.com/threefoldtech/rivine/types"
)
const (
// TransactionVersionBotRegistration defines the Transaction version
// for a BotRegistration Transaction, used to register a new 3bot,
// where new means that the used public key cannot yet exist.
TransactionVersionBotRegistration types.TransactionVersion = iota + 144
// TransactionVersionBotRecordUpdate defines the Transaction version
// for a Tx used to update a 3bot Record by the owner. where owner
// means the 3bot that created the record to be updated initially using the BotRegistration Tx.
TransactionVersionBotRecordUpdate
// TransactionVersionBotNameTransfer defines the Transaction version
// for a Tx used to transfer one or multiple names from the active
// 3bot that up to the point of that Tx to another 3bot.
TransactionVersionBotNameTransfer
)
// 3bot Multiplier fees that have to be multiplied with the OneCoin definition,
// in order to know the amount in the used chain currency (TFT).
const (
BotFeePerAdditionalNameMultiplier = 50
BotFeeForNetworkAddressInfoChangeMultiplier = 20
BotRegistrationFeeMultiplier = 90
BotMonthlyFeeMultiplier = 10
)
var (
SpecifierBotRegistrationTransaction = types.Specifier{'b', 'o', 't', ' ', 'r', 'e', 'g', 'i', 's', 't', 'e', 'r', ' ', 't', 'x'}
SpecifierBotRecordUpdateTransaction = types.Specifier{'b', 'o', 't', ' ', 'r', 'e', 'c', 'u', 'p', 'd', 'a', 't', 'e', ' ', 't', 'x'}
SpecifierBotNameTransferTransaction = types.Specifier{'b', 'o', 't', ' ', 'n', 'a', 'm', 'e', 't', 'r', 'a', 'n', 's', ' ', 't', 'x'}
)
// Bot validation errors
var (
ErrBotKeyAlreadyRegistered = errors.New("bot key is already registered")
ErrBotNameAlreadyRegistered = errors.New("bot name is already registered")
)
type (
// BotRegistrationTransaction defines the Transaction (with version 0x90)
// used to register a new 3bot, where new means that the used public key
// (identification) cannot yet exist.
BotRegistrationTransaction struct {
// Addresses contains the optional network addresses used to reach the 3bot.
// Normally at least one is given, none are required however.
// All addresses (max 10) can be of any of the following types: IPv4, IPv6, hostname
Addresses []NetworkAddress `json:"addresses,omitempty"`
// Names contains the optional names (max 5) that can be used to reach the bot,
// using a name, instead of one of its network addresses, comparable to how DNS works.
Names []BotName `json:"names,omitempty"`
// NrOfMonths defines the amount of months that
// is desired to be paid upfront. Note that the amount of
// months defined here indicates how much additional fees are to be paid.
// The NrOfMonths has to be within this inclusive range [1,24].
NrOfMonths uint8 `json:"nrofmonths"`
// TransactionFee defines the regular Tx fee.
TransactionFee types.Currency `json:"txfee"`
// CoinInputs are only used for the required fees,
// which contains the regular Tx fee as well as the additional fees,
// to be paid for a 3bot registration. At least one CoinInput is required.
CoinInputs []types.CoinInput `json:"coininputs"`
// RefundCoinOutput is an optional coin output that can be used
// to refund coins paid as inputs for the required fees.
RefundCoinOutput *types.CoinOutput `json:"refundcoinoutput,omitempty"`
// Identification is used to identify the 3bot and verify its identity.
// The identification is only given at registration, for all other
// 3bot Tx types it is identified by a combination of its unique ID and signature.
Identification PublicKeySignaturePair `json:"identification"`
}
// BotRegistrationTransactionExtension defines the BotRegistrationTransaction Extension Data
BotRegistrationTransactionExtension struct {
Addresses []NetworkAddress
Names []BotName
NrOfMonths uint8
Identification PublicKeySignaturePair
}
)
// RequiredBotFee computes the required Bot Fee, that is to be applied as a required
// additional fee on top of the regular required (minimum) Tx fee.
func (brtxe *BotRegistrationTransactionExtension) RequiredBotFee(oneCoin types.Currency) types.Currency {
// a static registration fee has to be paid
fee := oneCoin.Mul64(BotRegistrationFeeMultiplier)
// the amount of desired months also has to be paid
fee = fee.Add(ComputeMonthlyBotFees(brtxe.NrOfMonths, oneCoin))
// if more than one name is defined it also has to be paid
if n := len(brtxe.Names); n > 1 {
fee = fee.Add(oneCoin.Mul64(uint64(n-1) * BotFeePerAdditionalNameMultiplier))
}
// no fee has to be paid for the used network addresses during registration
// return the total fees
return fee
}
// BotRegistrationTransactionFromTransaction creates a BotRegistrationTransaction,
// using a regular in-memory tfchain transaction.
//
// Past the (tx) Version validation it piggy-backs onto the
// `BotRegistrationTransactionFromTransactionData` constructor.
func BotRegistrationTransactionFromTransaction(tx types.Transaction) (BotRegistrationTransaction, error) {
if tx.Version != TransactionVersionBotRegistration {
return BotRegistrationTransaction{}, fmt.Errorf(
"a bot registration transaction requires tx version %d",
TransactionVersionBotRegistration)
}
return BotRegistrationTransactionFromTransactionData(types.TransactionData{
CoinInputs: tx.CoinInputs,
CoinOutputs: tx.CoinOutputs,
BlockStakeInputs: tx.BlockStakeInputs,
BlockStakeOutputs: tx.BlockStakeOutputs,
MinerFees: tx.MinerFees,
ArbitraryData: tx.ArbitraryData,
Extension: tx.Extension,
})
}
// BotRegistrationTransactionFromTransactionData creates a BotRegistrationTransaction,
// using the TransactionData from a regular in-memory tfchain transaction.
func BotRegistrationTransactionFromTransactionData(txData types.TransactionData) (BotRegistrationTransaction, error) {
// validate the Transaction Data
err := validateBotInMemoryTransactionDataRequirements(txData)
if err != nil {
return BotRegistrationTransaction{}, fmt.Errorf("BotRegistrationTransaction: %v", err)
}
// (tx) extension (data) is expected to be a pointer to a valid BotRegistrationTransaction,
// which contains all the properties unique to a 3bot (registration) Tx
extensionData, ok := txData.Extension.(*BotRegistrationTransactionExtension)
if !ok {
return BotRegistrationTransaction{}, errors.New("invalid extension data for a BotRegistrationTransaction")
}
// create the BotRegistrationTransaction and return it,
// all should be good (at least the common requirements, it might still be invalid for version-specific reasons)
tx := BotRegistrationTransaction{
Addresses: extensionData.Addresses,
Names: extensionData.Names,
NrOfMonths: extensionData.NrOfMonths,
TransactionFee: txData.MinerFees[0],
CoinInputs: txData.CoinInputs,
Identification: extensionData.Identification,
}
if len(txData.CoinOutputs) == 1 {
// take refund coin output
tx.RefundCoinOutput = &txData.CoinOutputs[0]
}
return tx, nil
}
// TransactionData returns this BotRegistrationTransaction
// as regular tfchain transaction data.
func (brtx *BotRegistrationTransaction) TransactionData(oneCoin types.Currency) types.TransactionData {
txData := types.TransactionData{
CoinInputs: brtx.CoinInputs,
MinerFees: []types.Currency{brtx.TransactionFee},
Extension: &BotRegistrationTransactionExtension{
Addresses: brtx.Addresses,
Names: brtx.Names,
NrOfMonths: brtx.NrOfMonths,
Identification: brtx.Identification,
},
}
if brtx.RefundCoinOutput != nil {
txData.CoinOutputs = append(txData.CoinOutputs, *brtx.RefundCoinOutput)
}
return txData
}
// Transaction returns this BotRegistrationTransaction
// as regular tfchain transaction, using TransactionVersionBotRegistration as the type.
func (brtx *BotRegistrationTransaction) Transaction(oneCoin types.Currency) types.Transaction {
tx := types.Transaction{
Version: TransactionVersionBotRegistration,
CoinInputs: brtx.CoinInputs,
MinerFees: []types.Currency{brtx.TransactionFee},
Extension: &BotRegistrationTransactionExtension{
Addresses: brtx.Addresses,
Names: brtx.Names,
NrOfMonths: brtx.NrOfMonths,
Identification: brtx.Identification,
},
}
if brtx.RefundCoinOutput != nil {
tx.CoinOutputs = append(tx.CoinOutputs, *brtx.RefundCoinOutput)
}
return tx
}
// RequiredBotFee computes the required Bot Fee, that is to be applied as a required
// additional fee on top of the regular required (minimum) Tx fee.
func (brtx *BotRegistrationTransaction) RequiredBotFee(oneCoin types.Currency) types.Currency {
return (&BotRegistrationTransactionExtension{
Addresses: brtx.Addresses,
Names: brtx.Names,
NrOfMonths: brtx.NrOfMonths,
Identification: brtx.Identification,
}).RequiredBotFee(oneCoin)
}
// MarshalSia implements SiaMarshaler.MarshalSia,
// alias of MarshalRivine for backwards-compatibility reasons.
func (brtx BotRegistrationTransaction) MarshalSia(w io.Writer) error {
return brtx.MarshalRivine(w)
}
// UnmarshalSia implements SiaUnmarshaler.UnmarshalSia,
// alias of UnmarshalRivine for backwards-compatibility reasons.
func (brtx *BotRegistrationTransaction) UnmarshalSia(r io.Reader) error {
return brtx.UnmarshalRivine(r)
}
// MarshalRivine implements RivineMarshaler.MarshalRivine
func (brtx BotRegistrationTransaction) MarshalRivine(w io.Writer) error {
// the tfchain binary encoder used for this implementation
enc := rivbin.NewEncoder(w)
// encode the nr of months, flags and paired lenghts
addrLen := len(brtx.Addresses)
nameLen := len(brtx.Names)
maf := &BotMonthsAndFlagsData{
NrOfMonths: brtx.NrOfMonths,
HasAddresses: addrLen != 0,
HasNames: nameLen != 0,
HasRefund: brtx.RefundCoinOutput != nil,
}
err := enc.EncodeAll(maf, (uint8(addrLen) | (uint8(nameLen) << 4)))
if err != nil {
return err
}
// encode all addresses
for _, addr := range brtx.Addresses {
err = enc.Encode(addr)
if err != nil {
return err
}
}
// encode all names
for _, name := range brtx.Names {
err = enc.Encode(name)
if err != nil {
return err
}
}
// encode TxFee and CoinInputs
err = enc.EncodeAll(brtx.TransactionFee, brtx.CoinInputs)
if err != nil {
return err
}
// encode refund coin output, if given
if maf.HasRefund {
// deref to ensure we do not also encode one byte
// for the pointer indication
err = enc.Encode(*brtx.RefundCoinOutput)
if err != nil {
return err
}
}
// encode the identification at the end
return enc.Encode(brtx.Identification)
}
// UnmarshalRivine implements RivineUnmarshaler.UnmarshalRivine
func (brtx *BotRegistrationTransaction) UnmarshalRivine(r io.Reader) error {
dec := rivbin.NewDecoder(r)
var maf BotMonthsAndFlagsData
err := dec.Decode(&maf)
if err != nil {
return err
}
// assign number of months
brtx.NrOfMonths = maf.NrOfMonths
// decode the pair length (length of both names and addresses in one byte)
var pairLength uint8
err = dec.Decode(&pairLength)
if err != nil {
return err
}
addrLen, nameLen := pairLength&15, pairLength>>4
// decode all addresses and all names and store them in this Tx
if addrLen > 0 {
brtx.Addresses = make([]NetworkAddress, addrLen)
for i := range brtx.Addresses {
err = dec.Decode(&brtx.Addresses[i])
if err != nil {
return err
}
}
} else {
brtx.Addresses = nil
}
if nameLen > 0 {
brtx.Names = make([]BotName, nameLen)
for i := range brtx.Names {
err = dec.Decode(&brtx.Names[i])
if err != nil {
return err
}
}
} else {
brtx.Names = nil
}
// decode tx fee and coin inputs
err = dec.DecodeAll(&brtx.TransactionFee, &brtx.CoinInputs)
if err != nil {
return err
}
// decode the refund coin output, only if its flag is defined
if maf.HasRefund {
brtx.RefundCoinOutput = new(types.CoinOutput)
err = dec.Decode(brtx.RefundCoinOutput)
if err != nil {
return err
}
} else {
brtx.RefundCoinOutput = nil // explicitly set it nil
}
// decode identification as the last step
return dec.Decode(&brtx.Identification)
}
type (
// BotRecordUpdateTransaction defines the Transaction (with version 0x91)
// used to update a 3bot Record by the owner. where owner
// means the 3bot that created the record to be updated initially using the BotRegistration Tx.
BotRecordUpdateTransaction struct {
// Identifier of the 3bot, used to find the 3bot record to be updated,
// and verify that the Tx is authorized to do so.
Identifier BotID `json:"id"`
// Addresses can be used to add and/or remove network addresses
// to/from the existing 3bot record. Note that after each Tx,
// no more than 10 addresses can be linked to a single 3bot record.
Addresses BotRecordAddressUpdate `json:"addresses,omitempty"`
// Names can be used to add and/or remove names
// to/from the existing 3bot record. Note that after each Tx,
// no more than 5 names can be linked to a single 3bot record.
Names BotRecordNameUpdate `json:"names,omitempty"`
// NrOfMonths defines the optional amount of months that
// is desired to be paid upfront in this update. Note that the amount of
// months defined here defines how much additional fees are to be paid.
// The NrOfMonths has to be within this inclusive range [0,24].
NrOfMonths uint8 `json:"nrofmonths"`
// TransactionFee defines the regular Tx fee.
TransactionFee types.Currency `json:"txfee"`
// CoinInputs are only used for the required fees,
// which contains the regular Tx fee as well as the additional fees,
// to be paid for a 3bot record update. At least one CoinInput is required.
// If this 3bot record update is only to pay for extending the 3bot activity,
// than no fees are required other than the monthly fees as defined by this bots usage.
CoinInputs []types.CoinInput `json:"coininputs"`
// RefundCoinOutput is an optional coin output that can be used
// to refund coins paid as inputs for the required fees.
RefundCoinOutput *types.CoinOutput `json:"refundcoinoutput,omitempty"`
// Signature is used to proof the ownership of the 3bot record to be updated,
// and is verified using the public key defined in the 3bot linked
// to the given (3bot) identifier.
Signature types.ByteSlice `json:"signature"`
}
// BotRecordAddressUpdate contains all information required for an update
// to the addresses of a bot's record.
BotRecordAddressUpdate struct {
Add []NetworkAddress `json:"add,omitempty"`
Remove []NetworkAddress `json:"remove,omitempty"`
}
// BotRecordNameUpdate contains all information required for an update
// to the names of a bot's record.
BotRecordNameUpdate struct {
Add []BotName `json:"add,omitempty"`
Remove []BotName `json:"remove,omitempty"`
}
// BotRecordUpdateTransactionExtension defines the BotRecordUpdateTransaction Extension Data
BotRecordUpdateTransactionExtension struct {
Identifier BotID
Signature types.ByteSlice
AddressUpdate BotRecordAddressUpdate
NameUpdate BotRecordNameUpdate
NrOfMonths uint8
}
)
// RequiredBotFee computes the required Bot Fee, that is to be applied as a required
// additional fee on top of the regular required (minimum) Tx fee.
func (brutxe *BotRecordUpdateTransactionExtension) RequiredBotFee(oneCoin types.Currency) (fee types.Currency) {
// all additional months have to be paid
if brutxe.NrOfMonths > 0 {
fee = fee.Add(ComputeMonthlyBotFees(brutxe.NrOfMonths, oneCoin))
}
// a Tx that modifies the network address info of a 3bot record also has to be paid
if len(brutxe.AddressUpdate.Add) > 0 || len(brutxe.AddressUpdate.Remove) > 0 {
fee = fee.Add(oneCoin.Mul64(BotFeeForNetworkAddressInfoChangeMultiplier))
}
// each additional name has to be paid as well
// (regardless of the fact that the 3bot has a name or not)
if n := len(brutxe.NameUpdate.Add); n > 0 {
fee = fee.Add(oneCoin.Mul64(BotFeePerAdditionalNameMultiplier * uint64(n)))
}
// return the total fees
return fee
}
// BotRecordUpdateTransactionFromTransaction creates a BotRecordUpdateTransaction,
// using a regular in-memory tfchain transaction.
//
// Past the (tx) Version validation it piggy-backs onto the
// `BotRecordUpdateTransactionFromTransactionData` constructor.
func BotRecordUpdateTransactionFromTransaction(tx types.Transaction) (BotRecordUpdateTransaction, error) {
if tx.Version != TransactionVersionBotRecordUpdate {
return BotRecordUpdateTransaction{}, fmt.Errorf(
"a bot record update transaction requires tx version %d",
TransactionVersionBotRecordUpdate)
}
return BotRecordUpdateTransactionFromTransactionData(types.TransactionData{
CoinInputs: tx.CoinInputs,
CoinOutputs: tx.CoinOutputs,
BlockStakeInputs: tx.BlockStakeInputs,
BlockStakeOutputs: tx.BlockStakeOutputs,
MinerFees: tx.MinerFees,
ArbitraryData: tx.ArbitraryData,
Extension: tx.Extension,
})
}
// BotRecordUpdateTransactionFromTransactionData creates a BotRecordUpdateTransaction,
// using the TransactionData from a regular in-memory tfchain transaction.
func BotRecordUpdateTransactionFromTransactionData(txData types.TransactionData) (BotRecordUpdateTransaction, error) {
// validate the Transaction Data
err := validateBotInMemoryTransactionDataRequirements(txData)
if err != nil {
return BotRecordUpdateTransaction{}, fmt.Errorf("BotRecordUpdateTransaction: %v", err)
}
// (tx) extension (data) is expected to be a pointer to a valid BotRecordUpdateTransaction,
// which contains all the properties unique to a 3bot (record update) Tx
extensionData, ok := txData.Extension.(*BotRecordUpdateTransactionExtension)
if !ok {
return BotRecordUpdateTransaction{}, errors.New("invalid extension data for a BotRecordUpdateTransaction")
}
// create the BotRecordUpdateTransaction and return it,
// all should be good (at least the common requirements, it might still be invalid for version-specific reasons)
tx := BotRecordUpdateTransaction{
Identifier: extensionData.Identifier,
Addresses: extensionData.AddressUpdate,
Names: extensionData.NameUpdate,
NrOfMonths: extensionData.NrOfMonths,
TransactionFee: txData.MinerFees[0],
CoinInputs: txData.CoinInputs,
Signature: extensionData.Signature,
}
if len(txData.CoinOutputs) == 1 {
// take refund coin output
tx.RefundCoinOutput = &txData.CoinOutputs[0]
}
return tx, nil
}
// TransactionData returns this BotRecordUpdateTransaction
// as regular tfchain transaction data.
func (brutx *BotRecordUpdateTransaction) TransactionData(oneCoin types.Currency) types.TransactionData {
txData := types.TransactionData{
CoinInputs: brutx.CoinInputs,
MinerFees: []types.Currency{brutx.TransactionFee},
Extension: &BotRecordUpdateTransactionExtension{
Identifier: brutx.Identifier,
Signature: brutx.Signature,
AddressUpdate: brutx.Addresses,
NameUpdate: brutx.Names,
NrOfMonths: brutx.NrOfMonths,
},
}
if brutx.RefundCoinOutput != nil {
txData.CoinOutputs = append(txData.CoinOutputs, *brutx.RefundCoinOutput)
}
return txData
}
// Transaction returns this BotRecordUpdateTransaction
// as regular tfchain transaction, using TransactionVersionBotRecordUpdate as the type.
func (brutx *BotRecordUpdateTransaction) Transaction(oneCoin types.Currency) types.Transaction {
tx := types.Transaction{
Version: TransactionVersionBotRecordUpdate,
CoinInputs: brutx.CoinInputs,
MinerFees: []types.Currency{brutx.TransactionFee},
Extension: &BotRecordUpdateTransactionExtension{
Identifier: brutx.Identifier,
Signature: brutx.Signature,
AddressUpdate: brutx.Addresses,
NameUpdate: brutx.Names,
NrOfMonths: brutx.NrOfMonths,
},
}
if brutx.RefundCoinOutput != nil {
tx.CoinOutputs = append(tx.CoinOutputs, *brutx.RefundCoinOutput)
}
return tx
}
// RequiredBotFee computes the required Bot Fee, that is to be applied as a required
// additional fee on top of the regular required (minimum) Tx fee.
func (brutx *BotRecordUpdateTransaction) RequiredBotFee(oneCoin types.Currency) (fee types.Currency) {
return (&BotRecordUpdateTransactionExtension{
Identifier: brutx.Identifier,
Signature: brutx.Signature,
AddressUpdate: brutx.Addresses,
NameUpdate: brutx.Names,
NrOfMonths: brutx.NrOfMonths,
}).RequiredBotFee(oneCoin)
}
// UpdateBotRecord updates the given record, within the context of the given blockTime,
// using the information of this BotRecordUpdateTransaction.
//
// This method should only be called once for the given record,
// as it has no way of checking whether or not it already updated the given record.
func (brutx *BotRecordUpdateTransaction) UpdateBotRecord(blockTime types.Timestamp, record *BotRecord) error {
var err error
// if the record indicate the bot is expired, we ensure to reset the names,
// and also make sure the NrOfMonths is greater than 0
if record.IsExpired(blockTime) {
if brutx.NrOfMonths == 0 {
return errors.New("record update Tx does not make bot active, while bot is already expired")
}
record.ResetNames()
}
// update the expiration time
if brutx.NrOfMonths != 0 {
err = record.ExtendExpirationDate(blockTime, brutx.NrOfMonths)
if err != nil {
return err
}
}
// remove all addresses first, afterwards add the new addresses.
// By removing first we ensure that we can add addresses that were removed by this Tx,
// but more importantly it ensures that we don't invalidly report that an overflow has happened.
err = record.RemoveNetworkAddresses(brutx.Addresses.Remove...) // passing a nil slice is valid
if err != nil {
return err
}
err = record.AddNetworkAddresses(brutx.Addresses.Add...) // passing a nil slice is valid
if err != nil {
return err
}
// remove all names first, afterwards add the new names.
// By removing first we ensure that we can add names that were removed by this Tx,
// but more importantly it ensures that we don't invalidly report that an overflow has happened.
err = record.RemoveNames(brutx.Names.Remove...) // passing a nil slice is valid
if err != nil {
// an error will also occur here, in case names are removed from a bot that was previously inactive,
// as our earlier logic has already reset the names of the revord, making this step implicitly invalid,
// which is what we want, as an inative revord no longer owns any names, no matter what was last known about the record.
return err
}
err = record.AddNames(brutx.Names.Add...) // passing a nil slice is valid
if err != nil {
return err
}
// all good
return nil
}
// RevertBotRecordUpdate reverts the given record update, within the context of the given blockTime,
// using the information of this BotRecordUpdateTransaction.
//
// This method should only be called once for the given record,
// as it has no way of checking whether or not it already reverted the update of the given record.
//
// NOTE: implicit updates such as time jumps in expiration time (due to an inactive bot that became active again)
// and names that were implicitly removed because the bot was inactive, are not reverted by this method,
// and have to be added manually reverted.
func (brutx *BotRecordUpdateTransaction) RevertBotRecordUpdate(record *BotRecord) error {
// update the record expiration time in the most simple way possible,
// should there have been a time jump, the caller might have to correct expiration time
record.Expiration -= BotMonth * CompactTimestamp(brutx.NrOfMonths)
// remove all addresses that were added
err := record.RemoveNetworkAddresses(brutx.Addresses.Add...) // passing a nil slice is valid
if err != nil {
return err
}
// add all adderesses that were removed
err = record.AddNetworkAddresses(brutx.Addresses.Remove...) // passing a nil slice is valid
if err != nil {
return err
}
// remove all names that were added
err = record.RemoveNames(brutx.Names.Add...) // passing a nil slice is valid
if err != nil {
return err
}
// add all names that were removed
err = record.AddNames(brutx.Names.Remove...) // passing a nil slice is valid
if err != nil {
return err
}
// all good
return nil
}
// MarshalSia implements SiaMarshaler.MarshalSia,
// alias of MarshalRivine for backwards-compatibility reasons.
func (brutx BotRecordUpdateTransaction) MarshalSia(w io.Writer) error {
return brutx.MarshalRivine(w)
}
// UnmarshalSia implements SiaUnmarshaler.UnmarshalSia,
// alias of UnmarshalRivine for backwards-compatibility reasons.
func (brutx *BotRecordUpdateTransaction) UnmarshalSia(r io.Reader) error {
return brutx.UnmarshalRivine(r)
}
// MarshalRivine implements RivineMarshaler.MarshalRivine
func (brutx BotRecordUpdateTransaction) MarshalRivine(w io.Writer) error {
// collect length of all the name/addr slices
addrAddLen, addrRemoveLen := len(brutx.Addresses.Add), len(brutx.Addresses.Remove)
nameAddLen, nameRemoveLen := len(brutx.Names.Add), len(brutx.Names.Remove)
// the tfchain binary encoder used for this implementation
enc := rivbin.NewEncoder(w)
// encode the identifier, nr of months, flags and paired lenghts
maf := BotMonthsAndFlagsData{
NrOfMonths: brutx.NrOfMonths,
HasAddresses: addrAddLen > 0 || addrRemoveLen > 0,
HasNames: nameAddLen > 0 || nameRemoveLen > 0,
HasRefund: brutx.RefundCoinOutput != nil,
}
err := enc.EncodeAll(brutx.Identifier, maf)
if err != nil {
return err
}
// encode addressed added and removed, if defined
if maf.HasAddresses {
err = enc.Encode(uint8(addrAddLen) | (uint8(addrRemoveLen) << 4))
if err != nil {
return err
}
for _, addr := range brutx.Addresses.Add {
err = enc.Encode(addr)
if err != nil {
return err
}
}
for _, addr := range brutx.Addresses.Remove {
err = enc.Encode(addr)
if err != nil {
return err
}
}
}
// encode names added and removed, if defined
if maf.HasNames {
err = enc.Encode(uint8(nameAddLen) | (uint8(nameRemoveLen) << 4))
if err != nil {
return err
}
for _, name := range brutx.Names.Add {
err = enc.Encode(name)
if err != nil {
return err
}
}
for _, name := range brutx.Names.Remove {
err = enc.Encode(name)
if err != nil {
return err
}
}
}
// encode TxFee and CoinInputs
err = enc.EncodeAll(brutx.TransactionFee, brutx.CoinInputs)
if err != nil {
return err
}
// encode refund coin output, if given
if maf.HasRefund {
// deref to ensure we do not also encode one byte
// for the pointer indication
err = enc.Encode(*brutx.RefundCoinOutput)
if err != nil {
return err
}
}
// encode the signature at the end
return enc.Encode(brutx.Signature)
}
// UnmarshalRivine implements RivineUnmarshaler.UnmarshalRivine
func (brutx *BotRecordUpdateTransaction) UnmarshalRivine(r io.Reader) error {
dec := rivbin.NewDecoder(r)
// unmarshal identifier, NrOfMonths and flags
var maf BotMonthsAndFlagsData
err := dec.DecodeAll(&brutx.Identifier, &maf)
if err != nil {
return err
}
// assign number of months
brutx.NrOfMonths = maf.NrOfMonths
// decode addressed added and removed, if defined
if maf.HasAddresses {
var pairLength uint8
err = dec.Decode(&pairLength)
if err != nil {
return err
}
addrAddLen, addrRemoveLen := pairLength&15, pairLength>>4
if addrAddLen > 0 {
brutx.Addresses.Add = make([]NetworkAddress, addrAddLen)
for i := range brutx.Addresses.Add {
err = dec.Decode(&brutx.Addresses.Add[i])
if err != nil {
return err
}
}
} else {
brutx.Addresses.Add = nil
}
if addrRemoveLen > 0 {
brutx.Addresses.Remove = make([]NetworkAddress, addrRemoveLen)
for i := range brutx.Addresses.Remove {
err = dec.Decode(&brutx.Addresses.Remove[i])
if err != nil {
return err
}
}
} else {
brutx.Addresses.Remove = nil
}
} else {
// explicitly set added/removed address to nil
brutx.Addresses.Add, brutx.Addresses.Remove = nil, nil
}
if maf.HasNames {
var pairLength uint8
err = dec.Decode(&pairLength)
if err != nil {
return err
}
nameAddLen, nameRemoveLen := pairLength&15, pairLength>>4
if nameAddLen > 0 {
brutx.Names.Add = make([]BotName, nameAddLen)
for i := range brutx.Names.Add {
err = dec.Decode(&brutx.Names.Add[i])
if err != nil {
return err
}
}
} else {
brutx.Names.Add = nil
}
if nameRemoveLen > 0 {
brutx.Names.Remove = make([]BotName, nameRemoveLen)
for i := range brutx.Names.Remove {
err = dec.Decode(&brutx.Names.Remove[i])
if err != nil {
return err
}
}
} else {
brutx.Names.Remove = nil
}
} else {
// explicitly set added/removed address to nil
brutx.Names.Add, brutx.Names.Remove = nil, nil
}
// encode TxFee and CoinInputs
err = dec.DecodeAll(&brutx.TransactionFee, &brutx.CoinInputs)
if err != nil {
return err
}
// decode refund coin output, if defined
if maf.HasRefund {
brutx.RefundCoinOutput = new(types.CoinOutput)
err = dec.Decode(brutx.RefundCoinOutput)
if err != nil {
return err
}
} else {
brutx.RefundCoinOutput = nil
}
// decode the signature at the end
return dec.Decode(&brutx.Signature)
}
type (
// BotNameTransferTransaction defines the Transaction (with version 0x92)
// used to transfer one or multiple names from the active
// 3bot that up to the point of the Tx to another 3bot.
BotNameTransferTransaction struct {
// Sender is in this context the 3bot that owns and transfers the names
// defined in this Tx to the 3bot defined in this Tx as the Receiver.
// The Sender has to be different from the Receiver.
Sender BotIdentifierSignaturePair `json:"sender"`
// Receiver is in this context the 3bot that receives the names
// defined in this Tx from the 3bot defined in this Tx as the Sender.
// The Receiver has to be different from the Sender.
Receiver BotIdentifierSignaturePair `json:"receiver"`
// Names to be transferred from sender to receiver. Note that after each Tx,
// no more than 5 names can be linked to a single 3bot record.
Names []BotName `json:"names"`
// TransactionFee defines the regular Tx fee.
TransactionFee types.Currency `json:"txfee"`
// CoinInputs are only used for the required fees,
// which contains the regular Tx fee as well as the additional fees,
// to be paid for a 3bot record update. At least one CoinInput is required.
// If this 3bot record update is only to pay for extending the 3bot activity,
// than no fees are required other than the monthly fees as defined by this bots usage.
CoinInputs []types.CoinInput `json:"coininputs"`
// RefundCoinOutput is an optional coin output that can be used
// to refund coins paid as inputs for the required fees.
RefundCoinOutput *types.CoinOutput `json:"refundcoinoutput,omitempty"`
}
// BotIdentifierSignaturePair pairs a bot identifier and a signature assumed
// to be created by the bot linked to that ID.
BotIdentifierSignaturePair struct {
Identifier BotID `json:"id"`
Signature types.ByteSlice `json:"signature"`
}
// BotNameTransferTransactionExtension defines the BotNameTransferTransaction Extension Data
BotNameTransferTransactionExtension struct {
Sender BotIdentifierSignaturePair
Receiver BotIdentifierSignaturePair
Names []BotName
}
)
// RequiredBotFee computes the required Bot Fee, that is to be applied as a required
// additional fee on top of the regular required (minimum) Tx fee.
func (bnttxe *BotNameTransferTransactionExtension) RequiredBotFee(oneCoin types.Currency) types.Currency {
return oneCoin.Mul64(BotFeePerAdditionalNameMultiplier * uint64(len(bnttxe.Names)))
}
// BotNameTransferTransactionFromTransaction creates a BotNameTransferTransaction,
// using a regular in-memory tfchain transaction.
//
// Past the (tx) Version validation it piggy-backs onto the
// `BotNameTransferTransactionFromTransactionData` constructor.
func BotNameTransferTransactionFromTransaction(tx types.Transaction) (BotNameTransferTransaction, error) {
if tx.Version != TransactionVersionBotNameTransfer {
return BotNameTransferTransaction{}, fmt.Errorf(
"a bot name transfer transaction requires tx version %d",
TransactionVersionBotNameTransfer)
}
return BotNameTransferTransactionFromTransactionData(types.TransactionData{
CoinInputs: tx.CoinInputs,
CoinOutputs: tx.CoinOutputs,
BlockStakeInputs: tx.BlockStakeInputs,
BlockStakeOutputs: tx.BlockStakeOutputs,
MinerFees: tx.MinerFees,
ArbitraryData: tx.ArbitraryData,
Extension: tx.Extension,
})
}
// BotNameTransferTransactionFromTransactionData creates a BotNameTransferTransaction,
// using the TransactionData from a regular in-memory tfchain transaction.
func BotNameTransferTransactionFromTransactionData(txData types.TransactionData) (BotNameTransferTransaction, error) {
// validate the Transaction Data
err := validateBotInMemoryTransactionDataRequirements(txData)
if err != nil {
return BotNameTransferTransaction{}, fmt.Errorf("BotNameTransferTransaction: %v", err)
}
// (tx) extension (data) is expected to be a pointer to a valid BotNameTransferTransaction,
// which contains all the properties unique to a 3bot (name transfer) Tx
extensionData, ok := txData.Extension.(*BotNameTransferTransactionExtension)
if !ok {
return BotNameTransferTransaction{}, errors.New("invalid extension data for a BotNameTransferTransaction")
}
// create the BotNameTransferTransaction and return it,
// all should be good (at least the common requirements, it might still be invalid for version-specific reasons)
tx := BotNameTransferTransaction{
Sender: extensionData.Sender,
Receiver: extensionData.Receiver,
Names: extensionData.Names,
TransactionFee: txData.MinerFees[0],
CoinInputs: txData.CoinInputs,
}
if len(txData.CoinOutputs) == 1 {
// take refund coin output
tx.RefundCoinOutput = &txData.CoinOutputs[0]
}
return tx, nil
}
// TransactionData returns this BotNameTransferTransaction
// as regular tfchain transaction data.
func (bnttx *BotNameTransferTransaction) TransactionData(oneCoin types.Currency) types.TransactionData {
txData := types.TransactionData{
CoinInputs: bnttx.CoinInputs,
MinerFees: []types.Currency{bnttx.TransactionFee},
Extension: &BotNameTransferTransactionExtension{
Sender: bnttx.Sender,
Receiver: bnttx.Receiver,
Names: bnttx.Names,
},
}
if bnttx.RefundCoinOutput != nil {
txData.CoinOutputs = append(txData.CoinOutputs, *bnttx.RefundCoinOutput)
}
return txData
}
// Transaction returns this BotNameTransferTransaction
// as regular tfchain transaction, using TransactionVersionBotNameTransfer as the type.
func (bnttx *BotNameTransferTransaction) Transaction(oneCoin types.Currency) types.Transaction {
tx := types.Transaction{
Version: TransactionVersionBotNameTransfer,
CoinInputs: bnttx.CoinInputs,
MinerFees: []types.Currency{bnttx.TransactionFee},
Extension: &BotNameTransferTransactionExtension{
Sender: bnttx.Sender,
Receiver: bnttx.Receiver,
Names: bnttx.Names,
},
}
if bnttx.RefundCoinOutput != nil {
tx.CoinOutputs = append(tx.CoinOutputs, *bnttx.RefundCoinOutput)
}
return tx
}
// RequiredBotFee computes the required Bot Fee, that is to be applied as a required
// additional fee on top of the regular required (minimum) Tx fee.
func (bnttx *BotNameTransferTransaction) RequiredBotFee(oneCoin types.Currency) types.Currency {
return (&BotNameTransferTransactionExtension{
Sender: bnttx.Sender,
Receiver: bnttx.Receiver,
Names: bnttx.Names,
}).RequiredBotFee(oneCoin)
}
// UpdateReceiverBotRecord updates the given (receiver bot) record, within the context of the given blockTime,
// using the information of this BotNameTransferTransaction.
//
// This method should only be called once for the given (receiver bot) record,
// as it has no way of checking whether or not it already updated the given record.
func (bnttx *BotNameTransferTransaction) UpdateReceiverBotRecord(blockTime types.Timestamp, record *BotRecord) error {
if record.IsExpired(blockTime) {
return errors.New("receiver bot is inactive while a name transfer requires the bot to be active")
}
err := record.AddNames(bnttx.Names...)
if err != nil {
return fmt.Errorf("error while adding transferred names to receiver bot: %v", err)
}
return nil
}
// RevertReceiverBotRecordUpdate reverts the given record update, within the context of the given blockTime,
// using the information of this BotRecordUpdateTransaction.