/
plugin.go
1611 lines (1475 loc) · 54.7 KB
/
plugin.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 threebot
import (
"encoding/binary"
"errors"
"fmt"
"io"
"github.com/threefoldtech/rivine/modules"
"github.com/threefoldtech/rivine/persist"
"github.com/threefoldtech/rivine/pkg/encoding/rivbin"
"github.com/threefoldtech/rivine/types"
tbtypes "github.com/threefoldfoundation/tfchain/extensions/threebot/types"
bolt "github.com/rivine/bbolt"
)
const (
pluginDBVersion = "1.0.0.0"
pluginDBHeader = "threebotPlugin"
)
var (
bucketBotRecords = []byte("botrecords") // ID => name
bucketBotKeyToIDMapping = []byte("botkeys") // Key => ID
bucketBotNameToIDMapping = []byte("botnames") // Name => ID
bucketBotRecordImplicitUpdates = []byte("botimplupdates") // txID => implicitBotRecordUpdate
bucketBotTransactions = []byte("bottransactions") // ID => []txID
bucketBlockTime = []byte("blockTimes") // block times
bucketSlice = [][]byte{
bucketBotRecords,
bucketBotKeyToIDMapping,
bucketBotNameToIDMapping,
bucketBotRecordImplicitUpdates,
bucketBotTransactions,
bucketBlockTime,
}
)
type (
// Plugin is a struct defines the 3bot plugin
Plugin struct {
storage modules.PluginViewStorage
unregisterCallback modules.PluginUnregisterCallback
hackMinimumBlockHeightSinceDoubleRegistrationsAreForbidden types.BlockHeight
}
// opt-in features for the plugin
PluginOptions struct {
HackMinimumBlockHeightSinceDoubleRegistrationsAreForbidden types.BlockHeight
}
)
// NewPlugin creates a new 3bot Plugin.
func NewPlugin(registryPool types.UnlockHash, oneCoin types.Currency, opts *PluginOptions) *Plugin {
p := new(Plugin)
if opts != nil {
p.hackMinimumBlockHeightSinceDoubleRegistrationsAreForbidden = opts.HackMinimumBlockHeightSinceDoubleRegistrationsAreForbidden
}
types.RegisterTransactionVersion(tbtypes.TransactionVersionBotRegistration, tbtypes.BotRegistrationTransactionController{
Registry: p,
RegistryPoolAddress: registryPool,
OneCoin: oneCoin,
})
types.RegisterTransactionVersion(tbtypes.TransactionVersionBotRecordUpdate, tbtypes.BotUpdateRecordTransactionController{
Registry: p,
RegistryPoolAddress: registryPool,
OneCoin: oneCoin,
})
types.RegisterTransactionVersion(tbtypes.TransactionVersionBotNameTransfer, tbtypes.BotNameTransferTransactionController{
Registry: p,
RegistryPoolAddress: registryPool,
OneCoin: oneCoin,
})
return p
}
// GetRecordForID returns the record mapped to the given BotID.
func (p *Plugin) GetRecordForID(id tbtypes.BotID) (record *tbtypes.BotRecord, err error) {
err = p.storage.View(func(bucket *bolt.Bucket) (err error) {
record, err = getRecordForID(bucket, id)
return
})
return
}
// internal function to get a record from the TxDB
func getRecordForID(bucket *bolt.Bucket, id tbtypes.BotID) (*tbtypes.BotRecord, error) {
recordBucket := bucket.Bucket(bucketBotRecords)
if recordBucket == nil {
return nil, errors.New("corrupt 3bot Plugin DB: bot record bucket does not exist")
}
bid, err := rivbin.Marshal(id)
if err != nil {
return nil, err
}
b := recordBucket.Get(bid)
if len(b) == 0 {
return nil, tbtypes.ErrBotNotFound
}
record := new(tbtypes.BotRecord)
err = rivbin.Unmarshal(b, record)
if err != nil {
return nil, err
}
return record, nil
}
// GetRecordForKey returns the record mapped to the given Key.
func (p *Plugin) GetRecordForKey(key types.PublicKey) (record *tbtypes.BotRecord, err error) {
err = p.storage.View(func(bucket *bolt.Bucket) error {
id, err := getBotIDForPublicKey(bucket, key)
if err != nil {
return err
}
record, err = getRecordForID(bucket, id)
return err
})
return
}
func getBotIDForPublicKey(bucket *bolt.Bucket, key types.PublicKey) (tbtypes.BotID, error) {
keyBucket := bucket.Bucket(bucketBotKeyToIDMapping)
if keyBucket == nil {
return 0, errors.New("corrupt 3bot plugin DB: bot key bucket does not exist")
}
bkey, err := rivbin.Marshal(key)
if err != nil {
return 0, err
}
b := keyBucket.Get(bkey)
if len(b) == 0 {
return 0, tbtypes.ErrBotKeyNotFound
}
var id tbtypes.BotID
err = rivbin.Unmarshal(b, &id)
return id, err
}
// GetRecordForName returns the record mapped to the given Name.
func (p *Plugin) GetRecordForName(name tbtypes.BotName) (record *tbtypes.BotRecord, err error) {
err = p.storage.View(func(bucket *bolt.Bucket) error {
blockTimeBucket := bucket.Bucket(bucketBlockTime)
if blockTimeBucket == nil {
return fmt.Errorf("corrupt 3bot plugin DB: bucket %s not foumd", string(bucketBlockTime))
}
_, chainTime, err := getCurrentBlockHeightAndTime(blockTimeBucket)
if err != nil {
return err
}
record, err = getRecordForName(bucket, name, chainTime)
return err
})
return
}
func getRecordForName(bucket *bolt.Bucket, name tbtypes.BotName, chainTime types.Timestamp) (*tbtypes.BotRecord, error) {
nameBucket := bucket.Bucket(bucketBotNameToIDMapping)
if nameBucket == nil {
return nil, errors.New("corrupt 3bot plugin DB: bot name bucket does not exist")
}
bname, err := rivbin.Marshal(name)
if err != nil {
return nil, err
}
b := nameBucket.Get(bname)
if len(b) == 0 {
return nil, tbtypes.ErrBotNameNotFound
}
var id tbtypes.BotID
err = rivbin.Unmarshal(b, &id)
if err != nil {
return nil, err
}
record, err := getRecordForID(bucket, id)
if err != nil {
return nil, err
}
if record.Expiration.SiaTimestamp() <= chainTime {
// a botname automatically expires as soon as the last 3bot that owned it expired as well
return nil, tbtypes.ErrBotNameExpired
}
return record, nil
}
// GetBotTransactionIdentifiers returns the identifiers of all transactions that created and updated the given bot's record.
//
// The transaction identifiers are returned in the (stable) order as defined by the blockchain.
func (p *Plugin) GetBotTransactionIdentifiers(id tbtypes.BotID) (ids []types.TransactionID, err error) {
err = p.storage.View(func(bucket *bolt.Bucket) (err error) {
ids, err = getBotTransactions(bucket, id)
return
})
return
}
// InitPlugin initializes the Bucket for the first time
func (p *Plugin) InitPlugin(metadata *persist.Metadata, bucket *bolt.Bucket, storage modules.PluginViewStorage, unregisterCallback modules.PluginUnregisterCallback) (persist.Metadata, error) {
p.storage = storage
p.unregisterCallback = unregisterCallback
if metadata == nil {
for _, bucketName := range bucketSlice {
b := bucket.Bucket([]byte(bucketName))
if b == nil {
var err error
_, err = bucket.CreateBucket([]byte(bucketName))
if err != nil {
return persist.Metadata{}, fmt.Errorf("failed to create bucket %s: %v", string(bucketName), err)
}
}
}
metadata = &persist.Metadata{
Version: pluginDBVersion,
Header: pluginDBHeader,
}
} else if metadata.Version != pluginDBVersion {
return persist.Metadata{}, errors.New("There is only 1 version of this plugin, version mismatch")
}
return *metadata, nil
}
// ApplyBlock applies a block's 3bot transactions to the 3Bot bucket.
func (p *Plugin) ApplyBlock(block modules.ConsensusBlock, bucket *persist.LazyBoltBucket) error {
if bucket == nil {
return errors.New("3Bot bucket does not exist")
}
var err error
for idx, txn := range block.Transactions {
cTxn := modules.ConsensusTransaction{
Transaction: txn,
BlockHeight: block.Height,
BlockTime: block.Timestamp,
SequenceID: uint16(idx),
SpentCoinOutputs: block.SpentCoinOutputs,
SpentBlockStakeOutputs: block.SpentBlockStakeOutputs,
}
err = p.ApplyTransaction(cTxn, bucket)
if err != nil {
return err
}
}
blockTimeBucket, err := bucket.Bucket(bucketBlockTime)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: %v", err)
}
return setStatsBlockTime(blockTimeBucket, block.Height, block.Timestamp)
}
// ApplyBlockHeader applies a block's header data to the 3Bot bucket.
func (p *Plugin) ApplyBlockHeader(header modules.ConsensusBlockHeader, bucket *persist.LazyBoltBucket) error {
if bucket == nil {
return errors.New("3Bot bucket does not exist")
}
blockTimeBucket, err := bucket.Bucket(bucketBlockTime)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: %v", err)
}
return setStatsBlockTime(blockTimeBucket, header.Height, header.Timestamp)
}
// ApplyTransaction applies a 3Bot transactions to the 3Bot bucket.
func (p *Plugin) ApplyTransaction(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
if bucket == nil {
return errors.New("3Bot bucket does not exist")
}
// check the version and handle the ones we care about
var err error
switch txn.Version {
case tbtypes.TransactionVersionBotRegistration:
err = p.applyBotRegistrationTx(txn, bucket)
case tbtypes.TransactionVersionBotRecordUpdate:
err = p.applyRecordUpdateTx(txn, bucket)
case tbtypes.TransactionVersionBotNameTransfer:
err = p.applyBotNameTransferTx(txn, bucket)
}
return err
}
func (p *Plugin) applyBotRegistrationTx(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
recordBucket, err := bucket.Bucket(bucketBotRecords)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: bot record bucket error: %v", err)
}
brtx, err := tbtypes.BotRegistrationTransactionFromTransaction(txn.Transaction)
if err != nil {
return fmt.Errorf("unexpected error while unpacking the bot registration tx type: %v", err)
}
// get the unique ID for the 3bot, using bolt's auto incrementing feature
sequenceIndex, err := recordBucket.NextSequence()
if err != nil {
return fmt.Errorf("error while getting auto incrementing sequence bot ID: %v", err)
}
if sequenceIndex > tbtypes.MaxBotID {
return errors.New("error while getting auto incrementing sequence bot ID: value exceeds 32 bit")
}
id := tbtypes.BotID(sequenceIndex)
// create the record
record := tbtypes.BotRecord{
ID: id,
PublicKey: brtx.Identification.PublicKey,
Expiration: tbtypes.SiaTimestampAsCompactTimestamp(txn.BlockTime) + tbtypes.CompactTimestamp(brtx.NrOfMonths)*tbtypes.BotMonth,
}
err = record.AddNetworkAddresses(brtx.Addresses...)
if err != nil {
return fmt.Errorf("error while adding network addresses to bot (%v): %v", brtx.Identification.PublicKey, err)
}
err = record.AddNames(brtx.Names...)
if err != nil {
return fmt.Errorf("error while adding bot names to bot (%v): %v", brtx.Identification.PublicKey, err)
}
// store the record, and the other mappings, assuming the consensus validated that
// the registration Tx is completely valid
bid, err := rivbin.Marshal(id)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
brecord, err := rivbin.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal bot Record: %v", err)
}
err = recordBucket.Put(bid, brecord)
if err != nil {
return fmt.Errorf("error while storing record for bot %d with public key %v: %v", id, brtx.Identification.PublicKey, err)
}
// store pubkey to ID mapping
err = applyKeyToIDMapping(bucket, brtx.Identification.PublicKey, id)
if err != nil {
return fmt.Errorf("error while storing pubKey %s to bot id %d mapping: %v", brtx.Identification.PublicKey, id, err)
}
// store all name mappings
for _, name := range brtx.Names {
err = applyNameToIDMapping(bucket, name, id)
if err != nil {
return fmt.Errorf("error while storing name %s to bot id %d mapping: %v", name.String(), id, err)
}
}
// apply the transactionID to the list of transactionIDs for the given bot
err = applyBotTransaction(bucket, id, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID), txn.ID())
if err != nil {
return fmt.Errorf("error while applying transaction for bot %d: %v", id, err)
}
// all information is applied
return nil
}
func (p *Plugin) applyRecordUpdateTx(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
recordBucket, err := bucket.Bucket(bucketBotRecords)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: bot record bucket error: %v", err)
}
brutx, err := tbtypes.BotRecordUpdateTransactionFromTransaction(txn.Transaction)
if err != nil {
return fmt.Errorf("unexpected error while unpacking the bot record update tx type: %v", err)
}
// get the bot record
bid, err := rivbin.Marshal(brutx.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal 3bot ID: %v", err)
}
b := recordBucket.Get(bid)
if len(b) == 0 {
return errors.New("no bot record found for the specified identifier")
}
var record tbtypes.BotRecord
err = rivbin.Unmarshal(b, &record)
if err != nil {
return fmt.Errorf("failed to unmarshal found bot record: %v", err)
}
// check if bot is still active,
// if the bot is still active we expect that the Tx defines the names to remove
// otherwise we require that all names should be removed
var namesInRecordRemovedImplicitly []tbtypes.BotName
if record.IsExpired(txn.BlockTime) {
namesInRecordRemovedImplicitly = record.Names.Difference(tbtypes.BotNameSortedSet{}) // A \ {} = A
// store the implicit update that will happen due to the invalid period prior to this Tx,
// this will help is in reverting the record back to its original state,
// as such implicit updates cannot be easily reverted otherwise
err = applyImplicitBotRecordUpdate(bucket, txn.ID(), implicitBotRecordUpdate{
PreviousExpirationTime: record.Expiration,
InactiveNamesRemoved: namesInRecordRemovedImplicitly,
})
if err != nil {
return fmt.Errorf("failed to apply implicit record update: %v", err)
}
}
// update it (will also reset names of an inactive bot)
err = brutx.UpdateBotRecord(txn.BlockTime, &record)
if err != nil {
return fmt.Errorf("failed to update bot record: %v", err)
}
// save it
bid, err = rivbin.Marshal(brutx.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal 3bot ID: %v", err)
}
brecord, err := rivbin.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal 3bot Record: %v", err)
}
err = recordBucket.Put(bid, brecord)
if err != nil {
return fmt.Errorf("error while updating record for bot %d: %v", brutx.Identifier, err)
}
if len(namesInRecordRemovedImplicitly) > 0 {
// otherwise remove all names that previously active,
// as we can assume that an update of a record update HAS to make it active again
for _, name := range namesInRecordRemovedImplicitly {
err = revertNameToIDMappingIfOwnedByBot(bucket, name, record.ID)
if err != nil {
return fmt.Errorf("failed to update bot record: error while tx-removing mapping of name %v: %v", name, err)
}
}
} else {
// if the bot was active, we apply the removals as defined by the Tx
for _, name := range brutx.Names.Remove {
err = revertNameToIDMapping(bucket, name)
if err != nil {
return fmt.Errorf("failed to update bot record: error while record-removing mapping of name %v: %v", name, err)
}
}
}
// add mapping for all the added names
for _, name := range brutx.Names.Add {
err = applyNameToIDMapping(bucket, name, record.ID)
if err != nil {
return fmt.Errorf("failed to update bot record: error while name %v to ID %v: %v", name, record.ID, err)
}
}
// apply the transactionID to the list of transactionIDs for the given bot
err = applyBotTransaction(bucket, record.ID, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID), txn.ID())
if err != nil {
return fmt.Errorf("error while applying transaction for bot %d: %v", record.ID, err)
}
// all information is applied
return nil
}
func (p *Plugin) applyBotNameTransferTx(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
recordBucket, err := bucket.Bucket(bucketBotRecords)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: bot record bucket error: %v", err)
}
bnttx, err := tbtypes.BotNameTransferTransactionFromTransaction(txn.Transaction)
if err != nil {
return fmt.Errorf("unexpected error while unpacking the bot name transfer tx type: %v", err)
}
// get the sender bot record
bid, err := rivbin.Marshal(bnttx.Sender.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal 3bot ID: %v", err)
}
b := recordBucket.Get(bid)
if len(b) == 0 {
return errors.New("no bot record found for the specified sender bot identifier")
}
var record tbtypes.BotRecord
err = rivbin.Unmarshal(b, &record)
if err != nil {
return fmt.Errorf("failed to unmarshal found record of sender bot %d: %v", bnttx.Sender.Identifier, err)
}
// update sender bot (this also ensures the sender bot isn't expired)
err = bnttx.UpdateSenderBotRecord(txn.BlockTime, &record)
if err != nil { // automatically checks also if at least one name is transferred, returning an error if not
return fmt.Errorf("failed to update record of sender bot %d: %v", record.ID, err)
}
// save the record of the sender bot
bid, err = rivbin.Marshal(record.ID)
if err != nil {
return fmt.Errorf("failed to marshal 3bot ID: %v", err)
}
brecord, err := rivbin.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal 3bot Record: %v", err)
}
err = recordBucket.Put(bid, brecord)
if err != nil {
return fmt.Errorf("error while saving the updated record for sender bot %d: %v", record.ID, err)
}
// apply the transactionID to the list of transactionIDs for the sender bot
err = applyBotTransaction(bucket, record.ID, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID), txn.ID())
if err != nil {
return fmt.Errorf("error while applying transaction for sender bot %d: %v", record.ID, err)
}
// get the receiver bot record
bid, err = rivbin.Marshal(bnttx.Receiver.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal 3bot ID: %v", err)
}
b = recordBucket.Get(bid)
if len(b) == 0 {
return errors.New("no bot record found for the specified receiver bot identifier")
}
err = rivbin.Unmarshal(b, &record)
if err != nil {
return fmt.Errorf("failed to unmarshal found record of receiver bot %d: %v", bnttx.Receiver.Identifier, err)
}
// update receiver bot (this also ensures the receiver bot isn't expired)
err = bnttx.UpdateReceiverBotRecord(txn.BlockTime, &record)
if err != nil { // automatically checks also if at least one name is transferred, returning an error if not
return fmt.Errorf("failed to update record of receiver bot %d: %v", record.ID, err)
}
// save the record of the receiver bot
bid, err = rivbin.Marshal(record.ID)
if err != nil {
return fmt.Errorf("failed to marshal 3bot ID: %v", err)
}
brecord, err = rivbin.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal 3bot Record: %v", err)
}
err = recordBucket.Put(bid, brecord)
if err != nil {
return fmt.Errorf("error while saving the updated record for receiver bot %d: %v", record.ID, err)
}
// update mapping for all the transferred names
for _, name := range bnttx.Names {
err = applyNameToIDMapping(bucket, name, record.ID)
if err != nil {
return fmt.Errorf("failed to update bot record: error while mapping name %v to ID %v: %v", name, record.ID, err)
}
}
// apply the transactionID to the list of transactionIDs for the receiver bot
err = applyBotTransaction(bucket, record.ID, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID), txn.ID())
if err != nil {
return fmt.Errorf("error while applying transaction for receiver bot %d: %v", record.ID, err)
}
// update went fine
return nil
}
// RevertBlock reverts a block's 3Bot transaction from the 3Bot bucket
func (p *Plugin) RevertBlock(block modules.ConsensusBlock, bucket *persist.LazyBoltBucket) error {
if bucket == nil {
return errors.New("mint conditions bucket does not exist")
}
// collect all one-per-block mint conditions
var err error
for idx, txn := range block.Transactions {
cTxn := modules.ConsensusTransaction{
Transaction: txn,
BlockHeight: block.Height,
BlockTime: block.Timestamp,
SequenceID: uint16(idx),
SpentCoinOutputs: block.SpentCoinOutputs,
SpentBlockStakeOutputs: block.SpentBlockStakeOutputs,
}
err = p.RevertTransaction(cTxn, bucket)
if err != nil {
return err
}
}
blockTimeBucket, err := bucket.Bucket(bucketBlockTime)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: %v", err)
}
return deleteStatsBlockTime(blockTimeBucket, block.Height)
}
// RevertBlockHeader applies a block's header data to the 3Bot bucket.
func (p *Plugin) RevertBlockHeader(header modules.ConsensusBlockHeader, bucket *persist.LazyBoltBucket) error {
if bucket == nil {
return errors.New("3Bot bucket does not exist")
}
blockTimeBucket, err := bucket.Bucket(bucketBlockTime)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: %v", err)
}
return deleteStatsBlockTime(blockTimeBucket, header.Height)
}
// RevertTransaction reverts a 3Bot transactions to the 3Bot bucket.
func (p *Plugin) RevertTransaction(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
if bucket == nil {
return errors.New("3Bot bucket does not exist")
}
var err error
switch txn.Version {
case tbtypes.TransactionVersionBotRegistration:
err = p.revertBotRegistrationTx(txn, bucket)
case tbtypes.TransactionVersionBotRecordUpdate:
err = p.revertRecordUpdateTx(txn, bucket)
case tbtypes.TransactionVersionBotNameTransfer:
err = p.revertBotNameTransferTx(txn, bucket)
}
return err
}
func (p *Plugin) revertBotRegistrationTx(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
recordBucket, err := bucket.Bucket(bucketBotRecords)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: %v", err)
}
brtx, err := tbtypes.BotRegistrationTransactionFromTransaction(txn.Transaction)
if err != nil {
return fmt.Errorf("unexpected error while unpacking the bot registration tx type: %v", err)
}
// the ID should be equal to the current bucket sequence, given it was incremented by the registration process
rbSequence := recordBucket.Sequence()
id := tbtypes.BotID(rbSequence)
// delete the record
bid, err := rivbin.Marshal(id)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
err = recordBucket.Delete(bid)
if err != nil {
return fmt.Errorf("error while deleting record for bot %d with public key %v: %v",
id, brtx.Identification.PublicKey, err)
}
// delete the name->ID mappings
for _, name := range brtx.Names {
err = revertNameToIDMapping(bucket, name)
if err != nil {
return fmt.Errorf("error while deleting name %s to bot id %d mapping: %v", name.String(), id, err)
}
}
// delete the publicKey->ID mapping,
// doing it last as this is the initial check that happens when registering a bot,
// as to ensure we only have one bot per public key
err = revertKeyToIDMapping(bucket, brtx.Identification.PublicKey)
if err != nil {
return fmt.Errorf("error while deleting pubKey %s to bot id %d mapping: %v", brtx.Identification.PublicKey, id, err)
}
// revert the transactionID from the list of transactionIDs for the given bot
err = revertBotTransaction(bucket, id, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID))
if err != nil {
return fmt.Errorf("error while reverting transaction for bot %d: %v", id, err)
}
// decrease the sequence counter of the bucket
err = recordBucket.SetSequence(rbSequence - 1)
if err != nil {
return fmt.Errorf("error while decrementing the sequence counter of bot record bucket: %v", err)
}
// all information is reverted
return nil
}
func (p *Plugin) revertRecordUpdateTx(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
recordBucket, err := bucket.Bucket(bucketBotRecords)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: %v", err)
}
brutx, err := tbtypes.BotRecordUpdateTransactionFromTransaction(txn.Transaction)
if err != nil {
return fmt.Errorf("unexpected error while unpacking the bot record update tx type: %v", err)
}
// get the bot record
bid, err := rivbin.Marshal(brutx.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
b := recordBucket.Get(bid)
if len(b) == 0 {
return errors.New("no bot record found for the specified identifier")
}
var record tbtypes.BotRecord
err = rivbin.Unmarshal(b, &record)
if err != nil {
return fmt.Errorf("failed to unmarshal found bot record: %v", err)
}
// first revert the Tx
err = brutx.RevertBotRecordUpdate(&record)
if err != nil {
return fmt.Errorf("failed to revert bot record: %v", err)
}
// now check if we're expired, if so,
// we might need to revert an implicit update that happened during the apply phase of this Tx
if record.IsExpired(txn.BlockTime) {
txID := txn.ID()
// if the record is expired, there is a big chance that
// there was an implicit update, as such let's try to get it,
// if an implicit update did indeed take place, let's restore that info
update, err := getImplicitBotRecordUpdate(bucket, txID)
if err != nil {
return fmt.Errorf("failed to revert bot record: failed to fetch implicit record update: %v", err)
}
if update.PreviousExpirationTime != 0 {
// only if the previous expiration time was set,
// could there have been an update (in the current setup)
record.Expiration = update.PreviousExpirationTime
// add all names to the record again (they were removed as well, so no error is expected)
err = record.AddNames(update.InactiveNamesRemoved...)
if err != nil {
return fmt.Errorf("failed to revert bot record: unexpected error while adding implicitly removed names back to record: %v", err)
}
// apply all removed names again in the mapping bucket as well (for all those names that aren't taken in the meanwhile)
for _, name := range update.InactiveNamesRemoved {
err = applyNameToIDMappingIfAvailable(bucket, name, record.ID)
if err != nil {
return fmt.Errorf("failed to revert bot record: :"+
"failed to add back mapping of expired bot's name %v to its ID %d: %v", name, record.ID, err)
}
}
// delete the implicit record update, it is no longer required
err = revertImplicitBotRecordUpdate(bucket, txID)
if err != nil {
return fmt.Errorf("failed to revert bot record: failed to revert implicit bot record update content:%v", err)
}
}
}
// save it
bid, err = rivbin.Marshal(brutx.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
brecord, err := rivbin.Marshal(brutx.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal bot Record: %v", err)
}
err = recordBucket.Put(bid, brecord)
if err != nil {
return fmt.Errorf("error while updating record for bot %d: %v", brutx.Identifier, err)
}
// revert all names that were added
for _, name := range brutx.Names.Add {
err = revertNameToIDMapping(bucket, name)
if err != nil {
return fmt.Errorf("failed to update bot record: error while name %v to ID %v: %v", name, record.ID, err)
}
}
// apply all names again that were removed,
// which can only be in case the bot was active
for _, name := range brutx.Names.Remove {
err = applyNameToIDMapping(bucket, name, record.ID)
if err != nil {
return fmt.Errorf("failed to revert update bot record: error while revert mapping of name %v that was removed: %v", name, err)
}
}
// revert the transactionID from the list of transactionIDs for the given bot
err = revertBotTransaction(bucket, record.ID, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID))
if err != nil {
return fmt.Errorf("error while reverting transaction for bot %d: %v", record.ID, err)
}
// all information is applied
return nil
}
func (p *Plugin) revertBotNameTransferTx(txn modules.ConsensusTransaction, bucket *persist.LazyBoltBucket) error {
recordBucket, err := bucket.Bucket(bucketBotRecords)
if err != nil {
return fmt.Errorf("corrupt 3bot plugin DB: %v", err)
}
bnttx, err := tbtypes.BotNameTransferTransactionFromTransaction(txn.Transaction)
if err != nil {
return fmt.Errorf("unexpected error while unpacking the bot name transfer tx type: %v", err)
}
// get the receiver bot record
bid, err := rivbin.Marshal(bnttx.Receiver.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
b := recordBucket.Get(bid)
if len(b) == 0 {
return errors.New("no bot record found for the specified receiver bot identifier")
}
var record tbtypes.BotRecord
err = rivbin.Unmarshal(b, &record)
if err != nil {
return fmt.Errorf("failed to unmarshal found record of receiver bot %d: %v", bnttx.Receiver.Identifier, err)
}
// revert receiver bot
err = bnttx.RevertReceiverBotRecordUpdate(&record)
if err != nil {
return fmt.Errorf("failed to update record of receiver bot %d: %v", record.ID, err)
}
// save the record of the receiver bot
bid, err = rivbin.Marshal(record.ID)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
brecord, err := rivbin.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal bot Record: %v", err)
}
err = recordBucket.Put(bid, brecord)
if err != nil {
return fmt.Errorf("error while saving the reverted (update of the) receiver bot %d: %v", record.ID, err)
}
// revert the transactionID from the list of transactionIDs for the receiver bot
err = revertBotTransaction(bucket, record.ID, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID))
if err != nil {
return fmt.Errorf("error while reverting transaction for receiver bot %d: %v", record.ID, err)
}
// get the sender bot record
bid, err = rivbin.Marshal(bnttx.Sender.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
b = recordBucket.Get(bid)
if len(b) == 0 {
return errors.New("no bot record found for the specified sender bot identifier")
}
err = rivbin.Unmarshal(b, &record)
if err != nil {
return fmt.Errorf("failed to unmarshal found record of sender bot %d: %v", bnttx.Sender.Identifier, err)
}
// revert sender bot
err = bnttx.RevertSenderBotRecordUpdate(&record)
if err != nil {
return fmt.Errorf("failed to revert record of sender bot %d: %v", record.ID, err)
}
// save the record of the sender bot
bid, err = rivbin.Marshal(bnttx.Receiver.Identifier)
if err != nil {
return fmt.Errorf("failed to marshal bot ID: %v", err)
}
brecord, err = rivbin.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal bot Record: %v", err)
}
err = recordBucket.Put(bid, brecord)
if err != nil {
return fmt.Errorf("error while saving the reverted record for sender bot %d: %v", record.ID, err)
}
// update mapping for all the transferred names, reverting them back to the sender
for _, name := range bnttx.Names {
err = applyNameToIDMapping(bucket, name, record.ID)
if err != nil {
return fmt.Errorf("failed to update bot record: error while mapping name %v to ID %v: %v", name, record.ID, err)
}
}
// revert the transactionID from the list of transactionIDs for the sender bot
err = revertBotTransaction(bucket, record.ID, newSortableTransactionShortID(txn.BlockHeight, txn.SequenceID))
if err != nil {
return fmt.Errorf("error while reverting transaction for sender bot %d: %v", record.ID, err)
}
// revert went fine
return nil
}
// TransactionValidators returns all tx validators linked to this plugin
func (p *Plugin) TransactionValidators() []modules.PluginTransactionValidationFunction {
return nil
}
// TransactionValidatorVersionFunctionMapping returns all tx validators linked to this plugin
func (p *Plugin) TransactionValidatorVersionFunctionMapping() map[types.TransactionVersion][]modules.PluginTransactionValidationFunction {
return map[types.TransactionVersion][]modules.PluginTransactionValidationFunction{
tbtypes.TransactionVersionBotRegistration: {
p.validateBotRegistrationTx,
},
tbtypes.TransactionVersionBotRecordUpdate: {
p.validateBotUpdateTx,
},
tbtypes.TransactionVersionBotNameTransfer: {
p.validateBotNameTransferTx,
},
}
}
func (p *Plugin) validateBotRegistrationTx(txn modules.ConsensusTransaction, ctx types.TransactionValidationContext, bucket *persist.LazyBoltBucket) error {
// get BotRegistrationTx
brtx, err := tbtypes.BotRegistrationTransactionFromTransaction(txn.Transaction)
if err != nil {
return fmt.Errorf("failed to use tx as a bot registration tx: %v", err)
}
rootBucket, err := bucket.AsBoltBucket()
if err != nil {
return fmt.Errorf("failed to cast passed bucket as a bolt bucket: %v", err)
}
// look up the public key, to ensure it is not registered yet
err = func() error {
id, err := getBotIDForPublicKey(rootBucket, brtx.Identification.PublicKey)
if err != nil {
return err
}
_, err = getRecordForID(rootBucket, id)
return err
}()
// TODO: remove this sad hack, required due to mistakes in testnet 3Bot inner block validation
if ctx.BlockHeight < p.hackMinimumBlockHeightSinceDoubleRegistrationsAreForbidden {
if err != nil && err != tbtypes.ErrBotKeyNotFound && err != tbtypes.ErrBotKeyAlreadyRegistered {
return fmt.Errorf("unexpected error while validating non-existence of bot's public key: %v", err)
}
} else {
if err == nil {
return tbtypes.ErrBotKeyAlreadyRegistered
}
if err != tbtypes.ErrBotKeyNotFound {
return fmt.Errorf("unexpected error while validating non-existence of bot's public key: %v", err)
}
}
// validate the signature of the to-be-registered bot
err = validateBotSignature(txn.Transaction, brtx.Identification.PublicKey, brtx.Identification.Signature, ctx, tbtypes.BotSignatureSpecifierSender)
if err != nil {
return fmt.Errorf("failed to fulfill bot registration condition: %v", err)
}
// ensure the NrOfMonths is in the inclusive range of [1, 24]
if brtx.NrOfMonths == 0 {
return errors.New("bot registration requires at least one month to be paid already")
}
if brtx.NrOfMonths > tbtypes.MaxBotPrepaidMonths {
return tbtypes.ErrBotExpirationExtendOverflow
}
// validate the lengths,
// and ensure that at least one name or one addr is registered
addrLen := len(brtx.Addresses)
if addrLen > tbtypes.MaxAddressesPerBot {
return tbtypes.ErrTooManyBotAddresses
}
nameLen := len(brtx.Names)
if nameLen > tbtypes.MaxNamesPerBot {
return tbtypes.ErrTooManyBotNames
}
if addrLen == 0 && nameLen == 0 {
return errors.New("bot registration requires a name or address to be defined")
}
// validate that all network addresses are unique
err = validateUniquenessOfNetworkAddresses(brtx.Addresses)
if err != nil {
return fmt.Errorf("invalid bot registration Tx: validateUniquenessOfNetworkAddresses: %v", err)
}
// validate that all names are unique
err = validateUniquenessOfBotNames(brtx.Names)
if err != nil {
return fmt.Errorf("invalid bot registration Tx: validateUniquenessOfBotNames: %v", err)
}
// validate that the names are not registered yet
for _, name := range brtx.Names {
_, err = getRecordForName(rootBucket, name, ctx.BlockTime)
// TODO: remove this sad hack, required due to mistakes in testnet 3Bot inner block validation
if ctx.BlockHeight < p.hackMinimumBlockHeightSinceDoubleRegistrationsAreForbidden {
if err != nil && err != tbtypes.ErrBotNameNotFound && err != tbtypes.ErrBotNameAlreadyRegistered {
return fmt.Errorf(
"unexpected error while validating non-existence of bot's name %v: %v",
name, err)
}
} else {
if err == nil {
return tbtypes.ErrBotNameAlreadyRegistered
}
if err != tbtypes.ErrBotNameNotFound {
return fmt.Errorf(
"unexpected error while validating non-existence of bot's name %v: %v",
name, err)
}
}
}
// validate the miner fee
if brtx.TransactionFee.Cmp(ctx.MinimumMinerFee) == -1 {
return types.ErrTooSmallMinerFee
}