This repository was archived by the owner on Jul 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdatabase.go
More file actions
1434 lines (1318 loc) · 52.5 KB
/
database.go
File metadata and controls
1434 lines (1318 loc) · 52.5 KB
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 main
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"github.com/threefoldfoundation/rexplorer/pkg/database"
dtypes "github.com/threefoldfoundation/rexplorer/pkg/database/types"
"github.com/threefoldfoundation/rexplorer/pkg/encoding"
"github.com/threefoldfoundation/rexplorer/pkg/types"
"github.com/threefoldtech/rivine/crypto"
"github.com/threefoldtech/rivine/pkg/encoding/siabin"
rivinetypes "github.com/threefoldtech/rivine/types"
"github.com/gomodule/redigo/redis"
)
// Database represents the interface of a Database (client) as used by the Explorer module of this binary.
type Database interface {
GetExplorerState() (dtypes.ExplorerState, error)
SetExplorerState(state dtypes.ExplorerState) error
GetNetworkStats() (types.NetworkStats, error)
SetNetworkStats(stats types.NetworkStats) error
AddCoinOutput(id types.CoinOutputID, co CoinOutput) error
AddLockedCoinOutput(id types.CoinOutputID, co CoinOutput, lt dtypes.LockType, lockValue types.LockValue) error
SpendCoinOutput(id types.CoinOutputID) error
RevertCoinInput(id types.CoinOutputID) error
RevertCoinOutput(id types.CoinOutputID) (oldState dtypes.CoinOutputState, err error)
ApplyCoinOutputLocks(height types.BlockHeight, time types.Timestamp) (n uint64, coins types.Currency, err error)
RevertCoinOutputLocks(height types.BlockHeight, time types.Timestamp) (n uint64, coins types.Currency, err error)
SetMultisigAddresses(address types.UnlockHash, owners []types.UnlockHash, signaturesRequired uint64) error
SetCoinCreators(creators []types.UnlockHash) error
CreateBotRecord(record types.BotRecord) error
UpdateBotRecord(id types.BotID, fn func(*types.BotRecord) error) error
DeleteBotRecord(id types.BotID) error
AddERC20AddressRegistration(erc20Address types.ERC20Address, tftAddress types.UnlockHash) error
DeleteERC20AddressRegistration(erc20Address types.ERC20Address) error
Close() error
}
// public function parameter data structures
type (
// CoinOutput redefines a regular Rivine CoinOutput, adding a description field to it.
// The description field is usually taken directly from the ArbitraryData field,
// it is however hardcoded for tx fees and block creator rewards.
CoinOutput struct {
Value types.Currency
Condition rivinetypes.UnlockConditionProxy
Description string
}
)
type (
// RedisDatabase is a Database (client) implementation for Redis, using github.com/gomodule/redigo.
//
// Note that the state as stored in this redis database will be corrupt when an error (due to a code bug) occurs.
// This is however not a problem, as that bug should be fixed, and the redis database can be repopulated aftwards.
// Because of this it is probably wise to reserve a Redis database (slot), used only by this explorer.
//
// Note as well that this implementation will break as soon as you have multiple clients writing to the database.
// Many clients are allowed to read from the redis database, only this explorer module (and only as one instance) should write to
// the redis database (slot) used. Multiple writers are NOT supported! You've been warned.
//
// Following key (templates) are reserved by this Redis database implementation:
//
// internal keys:
// internal (Redis Hashmap) used for internal state of this explorer
// c:<4_random_hex_chars> (custom) all coin outputs
// lcos.height:<height> (custom) all locked coin outputs on a given height
// lcos.time:<timestamp-(timestamp%7200)> (custom) all locked coin outputs for a given timestamp range
//
// public keys:
// stats (JSON/MsgPack/Proto) used for global network statistics
// coincreators (SET) set of unique wallet addresses of the coin creator(s)
// addresses (SET) set of unique wallet addresses used (even if reverted) in the network
// a:<01|02|03><4_random_hex_chars> (JSON/MsgPack/Proto) used by all contract and wallet addresses, storing all content of the wallet/contract
// e:<6_random_hex_chars> (JSON/MsgPack/Proto) used by all ERC20 Address, storing the mapping to a TFT address
//
// Rivine Value Encodings:
// + addresses are Hex-encoded and the exact format (and how it is created) is described in:
// https://github.com/threefoldtech/rivine/blob/master/doc/transactions/unlockhash.md#textstring-encoding
// + currencies are encoded as described in https://godoc.org/math/big#Int.Text
// using base 10, and using the smallest coin unit as value (e.g. 10^-9 TFT)
// + coin outputs are stored in the Rivine-defined JSON format, described in:
// https://github.com/threefoldtech/rivine/blob/master/doc/transactions/transaction.md#json-encoding-of-outputs-in-v0-transactions (v0 tx) and
// https://github.com/threefoldtech/rivine/blob/master/doc/transactions/transaction.md#json-encoding-of-outputs-in-v1-transactions (v1 tx)
//
// JSON formats of value types defined by this module:
//
// example of global stats (stored under <chainName>:<networkName>:stats):
// {
// "timestamp": 1535661244,
// "blockHeight": 103481,
// "txCount": 103830,
// "coinCreationTxCount": 2,
// "coinCreatorDefinitionTxCount": 1,
// "coinBurnTxCount": 1,
// "botRegistrationTxCount": 3402,
// "botUpdateTxCount": 100,
// "valueTxCount": 348,
// "coinOutputCount": 104414,
// "lockedCoinOutputCount": 736,
// "coinInputCount": 1884,
// "minerPayoutCount": 103481,
// "txFeeCount": 306,
// "foundationFeeCount": 10,
// "minerPayouts": "1034810000000000",
// "txFees": "36100000071",
// "foundationFees": "410003200",
// "coins": "101054810300000000",
// "lockedCoins": "8045200000000"
// }
//
// example of a wallet (stored under a:01<4_random_hex_chars>)
// {
// "balance": {
// "unlocked": "10000000",
// "locked": {
// "total": "5000",
// "outputs": [
// {
// "amount": "2000",
// "lockedUntil": 1534105468
// },
// {
// "amount": "100",
// "lockedUntil": 1534105468,
// "description": "SGVsbG8=",
// }
// ]
// }
// },
// "multisignaddresses": [
// "0359aaaa311a10efd7762953418b828bfe2d4e2111dfe6aaf82d4adf6f2fb385688d7f86510d37"
// ]
// }
//
// example of a multisig wallet (stored under a:03<4_random_hex_chars>)
// {
// "balance": {
// "unlocked": "10000000"
// },
// "multisign": {
// "owners": [
// "01b650391f06c6292ecf892419dd059c6407bf8bb7220ac2e2a2df92e948fae9980a451ac0a6aa",
// "0114df42a3bb8303a745d23c47062a1333246b3adac446e6d62f4de74f5223faf4c2da465e76af"
// ],
// "signaturesRequired": 1
// }
// }
//
// example of a 3Bot record (stored under b:<1+_random_digits> <1_or_2_random_digits>)
// {
// "id": 1,
// "addresses":["example.com","91.198.174.192"],
// "names": ["thisis.mybot", "voicebot.example", "voicebot.example.myorg"],
// "publickey": "ed25519:00bde9571b30e1742c41fcca8c730183402d967df5b17b5f4ced22c677806614",
// "expiration": 1542815220
// }
//
RedisDatabase struct {
// The redis connection, no time out
conn redis.Conn
// used for the encoding/decoding of structured data
encoder encoding.Encoder
// cached chain constants
blockFrequency types.LockValue
// optional description filter set
// which is used to know which unlocked outputs to store in a wallet,
// as only outputs which have descriptions (that also match any of the filters in the filter set)
// will be stored as part of a structured wallet value
filters types.DescriptionFilterSet
// cached version of the chain stats
networkBlockHeight types.BlockHeight
networkTime types.Timestamp
// All Lua scripts used by this redis client implementation, for advanced features.
// Loaded when creating the client, and using the script's SHA1 (EVALSHA) afterwards.
coinOutputDropScript *redis.Script
lockByTimeScript, unlockByTimeScript *redis.Script
lockByHeightScript, unlockByHeightScript *redis.Script
spendCoinOutputScript, unspendCoinOutputScript *redis.Script
}
)
var (
_ Database = (*RedisDatabase)(nil)
)
type (
// DatabaseCoinOutputResult is returned by a Lua scripts which updates/marks a CoinOutput.
DatabaseCoinOutputResult struct {
CoinOutputID types.CoinOutputID
UnlockHash types.UnlockHash
CoinValue types.Currency
LockType dtypes.LockType
LockValue types.LockValue
Description string
}
)
// LoadBytes implements BytesLoader.LoadBytes
func (cor *DatabaseCoinOutputResult) LoadBytes(b []byte) error {
// load prefixed coin output ID
const coinOutputIDStringSize = crypto.HashSize * 2
if len(b) < coinOutputIDStringSize+1 {
return fmt.Errorf("failed to load Prefixed CoinOutputID in DatabaseCoinOutputResult from given byte slice: %v", io.EOF)
}
err := cor.CoinOutputID.LoadString(string(b[:coinOutputIDStringSize]))
if err != nil {
return fmt.Errorf("failed to load Prefixed CoinOutputID in DatabaseCoinOutputResult from given byte slice: %v", err)
}
// load returned CoinOutput values
decoder := siabin.NewDecoder(bytes.NewReader(b[coinOutputIDStringSize:]))
err = decoder.DecodeAll(
&cor.UnlockHash,
&cor.CoinValue,
&cor.LockType,
&cor.LockValue,
&cor.Description,
)
if err != nil {
return fmt.Errorf("failed to decode CoinOutput: %v", err)
}
return nil
}
const (
internalKey = "internal"
internalFieldState = "state"
internalFieldNetwork = "network"
internalFieldEncoding = "encoding"
internalFieldDescriptionFilters = "desc.filters"
lockedByHeightOutputsKeyPrefix = "lcos.height:"
lockedByTimestampOutputsKeyPrefix = "lcos.time:"
)
// NewRedisDatabase creates a new Redis Database client, used by the internal explorer module,
// see RedisDatabase for more information.
func NewRedisDatabase(address string, db int, encodingType encoding.Type, bcInfo rivinetypes.BlockchainInfo, chainCts rivinetypes.ChainConstants, filters types.DescriptionFilterSet, yesToAll bool) (*RedisDatabase, error) {
// dial a TCP connection
conn, err := redis.Dial("tcp", address, redis.DialDatabase(db))
if err != nil {
return nil, fmt.Errorf(
"failed to dial a Redis connection to tcp://%s@%d: %v", address, db, err)
}
// compute all keys and return the RedisDatabase instance
rdb := RedisDatabase{
conn: conn,
blockFrequency: types.LockValue(chainCts.BlockFrequency),
}
// ensure the encoding type is as expected (or register if this is a fresh db)
err = rdb.registerOrValidateEncodingType(encodingType)
if err != nil {
return nil, err
}
// create our encoder, now that we know our encoding type is OK, as we'll need it from here on out
rdb.encoder, err = encoding.NewEncoder(encodingType)
if err != nil {
return nil, err
}
// ensure the network info is as expected (or register if this is a fresh db)
err = rdb.registerOrValidateNetworkInfo(bcInfo)
if err != nil {
return nil, err
}
// set the description filter set (an empty set is fine too)
err = rdb.registerFilterSet(filters, yesToAll)
if err != nil {
return nil, err
}
// create and load scripts
err = rdb.createAndLoadScripts()
if err != nil {
return nil, fmt.Errorf("failed to create/load a lua script(s): %v", err)
}
return &rdb, nil
}
// Close implements Database.Close
//
// closes the internal redis db client connection
func (rdb *RedisDatabase) Close() error {
err := rdb.conn.Close()
if err != nil {
return fmt.Errorf("failed to close redis db client connection: %v", err)
}
return nil
}
// internal logic to create and load scripts usd for advanced lua-script-driven logic
func (rdb *RedisDatabase) createAndLoadScripts() (err error) {
rdb.coinOutputDropScript, err = rdb.createAndLoadScript(hashDropScriptSource)
if err != nil {
return
}
rdb.unlockByTimeScript, err = rdb.createAndLoadScript(
updateTimeLocksScriptSource,
dtypes.CoinOutputStateLocked.String(), dtypes.CoinOutputStateLiquid.String(), ">=")
if err != nil {
return
}
rdb.lockByTimeScript, err = rdb.createAndLoadScript(
updateTimeLocksScriptSource,
dtypes.CoinOutputStateLiquid.String(), dtypes.CoinOutputStateLocked.String(), "<")
if err != nil {
return
}
rdb.unlockByHeightScript, err = rdb.createAndLoadScript(
updateHeightLocksScriptSource,
dtypes.CoinOutputStateLocked.Byte(), dtypes.CoinOutputStateLiquid.Byte())
if err != nil {
return
}
rdb.lockByHeightScript, err = rdb.createAndLoadScript(
updateHeightLocksScriptSource,
dtypes.CoinOutputStateLiquid.Byte(), dtypes.CoinOutputStateLocked.Byte())
if err != nil {
return
}
rdb.spendCoinOutputScript, err = rdb.createAndLoadScript(
updateCoinOutputScriptSource,
dtypes.CoinOutputStateLiquid.Byte(), dtypes.CoinOutputStateSpent.Byte())
if err != nil {
return
}
rdb.unspendCoinOutputScript, err = rdb.createAndLoadScript(
updateCoinOutputScriptSource,
dtypes.CoinOutputStateSpent.Byte(), dtypes.CoinOutputStateLiquid.Byte())
if err != nil {
return
}
// all scripts loaded successfully
return nil
}
func (rdb *RedisDatabase) createAndLoadScript(src string, argv ...interface{}) (*redis.Script, error) {
src = fmt.Sprintf(src, argv...)
script := redis.NewScript(0, src)
err := script.Load(rdb.conn)
if err != nil {
return nil, fmt.Errorf("failed to load Lua-Script: %v", err)
}
return script, nil
}
const (
hashDropScriptSource = `
local coinOutputID = ARGV[1]
local key = 'c:' .. coinOutputID:sub(1,4)
local field = coinOutputID:sub(5)
local value = redis.call("HGET", key, field)
redis.call("HDEL", key, field)
return value
`
updateCoinOutputsSnippetSource = `
local results = {}
for i = 1 , #outputsToUpdate do
local outputID = outputsToUpdate[i]
local key = 'c:' .. outputID:sub(1,4)
local field = outputID:sub(5)
local output = redis.call("HGET", key, field)
if output:byte(1) == %[1]v then
output = string.char(%[2]v) .. output:sub(2)
redis.call("HSET", key, field, output)
results[#results+1] = outputID .. output:sub(2)
end
end
return results
`
updateTimeLocksScriptSource = `
local bucketKey = ARGV[1]
local timenow = tonumber(ARGV[2])
local outputsToUpdate = {}
local bucketLength = tonumber(redis.call('LLEN', bucketKey))
for i = 1 , bucketLength do
local str = redis.call('LINDEX', bucketKey, i-1)
local timelock = tonumber(str:sub(66))
if timenow %[3]s timelock then
outputsToUpdate[#outputsToUpdate+1] = str:sub(1,64)
end
end
` + updateCoinOutputsSnippetSource
updateHeightLocksScriptSource = `
local bucketKey = ARGV[1]
local outputsToUpdate = {}
local bucketLength = tonumber(redis.call('LLEN', bucketKey))
for i = 1 , bucketLength do
outputsToUpdate[#outputsToUpdate+1] = redis.call('LINDEX', bucketKey, i-1)
end
` + updateCoinOutputsSnippetSource
updateCoinOutputScriptSource = `
local coinOutputID = ARGV[1]
local key = 'c:' .. coinOutputID:sub(1,4)
local field = coinOutputID:sub(5)
local output = redis.call("HGET", key, field)
if output:byte(1) ~= %[1]v then
return nil
end
output = string.char(%[2]v) .. output:sub(2)
redis.call("HSET", key, field, output)
return coinOutputID .. output:sub(2)
`
)
// registerFilterSet registers the filter set if it doesn't exist yet,
// otherwise it ensures that the returned filter set matches the expected filter set.
func (rdb *RedisDatabase) registerFilterSet(filters types.DescriptionFilterSet, overwriteFilters bool) error {
// load previous stored, as to be able to delete out references and add new references
var receivedFilters types.DescriptionFilterSet
err := RedisStringLoader(&receivedFilters)(rdb.conn.Do("HGET", internalKey, internalFieldDescriptionFilters))
if err != nil {
if err == redis.ErrNil {
// assume a new database, simply register description filter set
err = RedisError(rdb.conn.Do("HSET", internalKey, internalFieldDescriptionFilters, filters.String()))
if err != nil {
return fmt.Errorf("failed to register/validate description filter set: %v", err)
}
return nil
}
return fmt.Errorf("failed to register/validate description filter set: %v", err)
}
// validate returned filter set
removedFilters := receivedFilters.Difference(filters)
addedFilters := filters.Difference(receivedFilters)
filtersChanged := false
if removedFilters.Len() > 0 || addedFilters.Len() > 0 {
filtersChanged = true
if !overwriteFilters {
var question string
if removedFilters.Len() > 0 {
question += "{" + removedFilters.String() + "} will be removed."
}
if addedFilters.Len() > 0 {
if question != "" {
question += " "
}
question += "{" + addedFilters.String() + "} will be added."
}
question += " Are you sure that you want to change the description filters to apply " +
"and modify the stored wallet values as a consequence?"
overwriteFilters, err = askYesNoQuestion(question)
if err != nil {
return fmt.Errorf("failed to register/validate description filter set: %v", err)
}
if !overwriteFilters {
return errors.New("failed to register/validate description filter set: user denied to modify existing filters")
}
}
// apply new filter set
err = rdb.applyNewFilterSet(addedFilters, removedFilters)
if err != nil {
return fmt.Errorf("failed to register/validate description filter set: "+
"an error occurred while applying new filter set: %v", err)
}
}
rdb.filters = filters
if filtersChanged {
// store filters
err = RedisError(rdb.conn.Do("HSET", internalKey, internalFieldDescriptionFilters, filters.String()))
if err != nil {
return fmt.Errorf("failed to register/validate description filter set: %v", err)
}
}
// return successfully
return nil
}
// for all outputs, check if it has a description that matches an added/removed filter,
// if so, the wallet has to be fetched and updated IFF the output is in the unlocked state.
func (rdb *RedisDatabase) applyNewFilterSet(addedFilters, removedFilters types.DescriptionFilterSet) error {
// needed to know the total coin outputs, as to be able to report progress within a useful context
stats, err := rdb.GetNetworkStats()
if err != nil {
return fmt.Errorf("failed to applyNewFilters: could not fetch network stats: %v", err)
}
// cache wallets, so we do not constantly need to serialize and deserialize
wallets := make(map[types.UnlockHash]*types.Wallet)
// used to keep track of output conter, and report progress
var outputCounter int
// scan through all outputs (scanning through all outputs of all buckets)
cursor := "0"
for {
results, err := redis.Values(rdb.conn.Do("SCAN", cursor, "MATCH", "c:*"))
if err != nil {
return fmt.Errorf("unexpected error while scanning through unique outputs with cursor %q: %v", cursor, err.Error())
}
if n := len(results); n != 2 {
return fmt.Errorf("expected to receive 2 results from a SCAN call, but received %d result(s)", n)
}
cursor, err = redis.String(results[0], nil)
if err != nil {
return fmt.Errorf("failed to interpret cursor received from last SCAN call: %v", err)
}
buckets, err := redis.Strings(results[1], nil)
if err == redis.ErrNil || len(buckets) == 0 {
// MATCH is applied only at the end, therefore it is possible
// that an iteration returns no elements
if cursor == "0" {
break
}
continue
}
if err != nil {
return fmt.Errorf("unexpected error while scanning through unique outputs with cursor %q: invalid addresses: %v", cursor, err.Error())
}
for _, bucket := range buckets {
bucketCursor := "0"
for {
bucketResults, err := redis.Values(rdb.conn.Do("HSCAN", bucket, bucketCursor))
if err != nil {
return fmt.Errorf("unexpected error while scanning through outputs bucket with cursor %q: %v", bucketCursor, err.Error())
}
if n := len(bucketResults); n != 2 {
return fmt.Errorf("unexpected to receive 2 results from a HSCAN call, but received %d result(s)", n)
}
outputs, err := redis.StringMap(bucketResults[1], nil)
if err != nil {
return fmt.Errorf("error while scanning through output buckets with cursor %q: invalid outputs: %v", bucketCursor, err.Error())
}
for key, value := range outputs {
outputIDStr := bucket[2:] + key
var outputID types.CoinOutputID
err := outputID.LoadString(outputIDStr)
if err != nil {
return fmt.Errorf("unexpected error while decoding coin output ID %s: %v", outputIDStr, err)
}
var output dtypes.CoinOutput
err = output.LoadBytes([]byte(value))
if err != nil {
return fmt.Errorf("unexpected error while decoding coin output %s: %v", outputIDStr, err)
}
// print progress
outputCounter++
if outputCounter%5000 == 0 {
log.Printf("[filter update] coin output scanner is now at coin output %d/%d...\n",
outputCounter, stats.CoinOutputCount)
}
// check state, we only care about the ones which are in state Liquid,
// reason being that only those are expected to be in the unlocked list of a wallet,
// which is the list populated after using the description filters
if output.State != dtypes.CoinOutputStateLiquid {
continue
}
// if the description is empty we also do not care
if output.Description == "" {
continue
}
var added, removed bool
added = addedFilters.Match(output.Description)
if !added {
removed = removedFilters.Match(output.Description)
if !removed {
// if not affected by a removed/added filter we can stop as well,
// as the output will not be affected either
continue
}
}
// get wallet for given unlock hash
wallet, ok := wallets[output.UnlockHash]
if !ok {
addressKey, addressField := database.GetAddressKeyAndField(output.UnlockHash)
b, err := redis.Bytes(rdb.conn.Do("HGET", addressKey, addressField))
if err != nil {
// not even redis.ErrNil is expected at this point
return fmt.Errorf("failed to get wallet (uh: %s) for output %s: %v", output.UnlockHash, outputIDStr, err)
}
if len(b) > 0 {
wallet = new(types.Wallet)
err = rdb.encoder.Unmarshal(b, wallet)
if err != nil {
return errors.New("failed to unmarshal wallet: " + err.Error())
}
}
wallets[output.UnlockHash] = wallet
}
// add or remove the output
if added {
// add the unlocked output
err = wallet.Balance.Unlocked.AddUnlockedCoinOutput(outputID, types.WalletUnlockedOutput{
Amount: output.CoinValue,
Description: output.Description,
}, false)
if err != nil {
return fmt.Errorf("failed to add unlocked coin output %s to wallet %s: %v",
outputIDStr, output.UnlockHash.String(), err)
}
} else {
// remove the unlocked output
err = wallet.Balance.Unlocked.SubUnlockedCoinOutput(outputID, output.CoinValue, false)
if err != nil {
return fmt.Errorf("failed to remove unlocked coin output %s from wallet %s: %v",
outputIDStr, output.UnlockHash.String(), err)
}
}
}
bucketCursor, err = redis.String(bucketResults[0], nil)
if err != nil {
return fmt.Errorf("failed to interpret cursor received from last HSCAN call: %v", err)
}
if bucketCursor == "0" {
break
}
}
}
if cursor == "0" {
break
}
}
// store all updated wallets
for uh, wallet := range wallets {
rdb.planWalletStorageOrDeletion(*wallet, uh)
}
err = RedisError(RedisFlushAndReceive(rdb.conn, len(wallets)))
if err != nil {
return fmt.Errorf("failed to update wallets with modifed filterset: %v", err)
}
return nil
}
// registerOrValidateEncodingType registers the encoding type if it doesn't exist yet,
// otherwise it ensures that the returned encoding type matches the expected encoding type.
func (rdb *RedisDatabase) registerOrValidateEncodingType(encodingType encoding.Type) error {
rdb.conn.Send("HSETNX", internalKey, internalFieldEncoding, encodingType.String())
rdb.conn.Send("HGET", internalKey, internalFieldEncoding)
replies, err := redis.Values(RedisFlushAndReceive(rdb.conn, 2))
if err != nil {
return fmt.Errorf("failed to register/validate encoding type: %v", err)
}
if len(replies) != 2 {
return errors.New("failed to register/validate encoding type: unexpected amount of replies received")
}
var receivedEncodingType encoding.Type
err = RedisStringLoader(&receivedEncodingType)(replies[1], err)
if err != nil {
return fmt.Errorf("failed to validate encoding type: %v", err)
}
if receivedEncodingType != encodingType {
return fmt.Errorf("cannot encode data using encoding type %s: db already uses encoding type %s",
encodingType.String(), receivedEncodingType.String())
}
return nil
}
// registerOrValidateNetworkInfo registers the network name and chain name if it doesn't exist yet,
// otherwise it ensures that the returned network info matches the expected network info.
func (rdb *RedisDatabase) registerOrValidateNetworkInfo(bcInfo rivinetypes.BlockchainInfo) error {
networkInfo := dtypes.NetworkInfo{
ChainName: bcInfo.Name,
NetworkName: bcInfo.NetworkName,
}
rdb.conn.Send("HSETNX", internalKey, internalFieldNetwork, rdb.marshalData(&networkInfo))
rdb.conn.Send("HGET", internalKey, internalFieldNetwork)
replies, err := redis.Values(RedisFlushAndReceive(rdb.conn, 2))
if err != nil {
return fmt.Errorf("failed to register/validate network info: %v", err)
}
if len(replies) != 2 {
return errors.New("failed to register/validate network info: unexpected amount of replies received")
}
var receivedNetworkInfo dtypes.NetworkInfo
err = rdb.redisStructuredValue(&receivedNetworkInfo)(replies[1], err)
if err != nil {
return fmt.Errorf("failed to validate network info: %v", err)
}
if receivedNetworkInfo != networkInfo {
return fmt.Errorf("cannot store data for chain %s/%s: db has already data for chain %s/%s stored",
networkInfo.ChainName, networkInfo.NetworkName,
receivedNetworkInfo.ChainName, receivedNetworkInfo.NetworkName)
}
return nil
}
// GetExplorerState implements Database.GetExplorerState
func (rdb *RedisDatabase) GetExplorerState() (dtypes.ExplorerState, error) {
var state dtypes.ExplorerState
switch err := rdb.redisStructuredValue(&state)(rdb.conn.Do("HGET", internalKey, internalFieldState)); err {
case nil:
return state, nil
case redis.ErrNil:
// default to fresh explorer state if not stored yet
return dtypes.NewExplorerState(), nil
default:
return dtypes.ExplorerState{}, err
}
}
// SetExplorerState implements Database.SetExplorerState
func (rdb *RedisDatabase) SetExplorerState(state dtypes.ExplorerState) error {
return RedisError(rdb.conn.Do("HSET", internalKey, internalFieldState, rdb.marshalData(&state)))
}
// GetNetworkStats implements Database.GetNetworkStats
func (rdb *RedisDatabase) GetNetworkStats() (types.NetworkStats, error) {
var stats types.NetworkStats
switch err := rdb.redisStructuredValue(&stats)(rdb.conn.Do("GET", database.StatsKey)); err {
case nil:
rdb.networkTime, rdb.networkBlockHeight = stats.Timestamp, stats.BlockHeight
return stats, nil
case redis.ErrNil:
// default to fresh network stats if not stored yet
stats = types.NewNetworkStats()
rdb.networkTime, rdb.networkBlockHeight = stats.Timestamp, stats.BlockHeight
return stats, nil
default:
return types.NetworkStats{}, err
}
}
// SetNetworkStats implements Database.SetNetworkStats
func (rdb *RedisDatabase) SetNetworkStats(stats types.NetworkStats) error {
err := RedisError(rdb.conn.Do("SET", database.StatsKey, rdb.marshalData(&stats)))
if err != nil {
return err
}
rdb.networkTime, rdb.networkBlockHeight = stats.Timestamp, stats.BlockHeight
return nil
}
// AddCoinOutput implements Database.AddCoinOutput
func (rdb *RedisDatabase) AddCoinOutput(id types.CoinOutputID, co CoinOutput) error {
uh := types.AsUnlockHash(co.Condition.UnlockHash())
addressKey, addressField := database.GetAddressKeyAndField(uh)
// get initial values
wallet, err := rdb.redisWallet(rdb.conn.Do("HGET", addressKey, addressField))
if err != nil {
return fmt.Errorf(
"redis: failed to get wallet for %s at %s#%s: %v", uh.String(), addressKey, addressField, err)
}
// increase coin count and optionally add output
if rdb.filters.Match(co.Description) {
err = wallet.Balance.Unlocked.AddUnlockedCoinOutput(id, types.WalletUnlockedOutput{
Amount: co.Value,
Description: co.Description,
}, true)
if err != nil {
return fmt.Errorf(
"redis: failed to add unlocked coinoutput %s to wallet for %s: %v",
id.String(), uh.String(), err)
}
} else {
wallet.Balance.Unlocked.Total = wallet.Balance.Unlocked.Total.Add(co.Value)
}
coinOutputKey, coinOutputField := database.GetCoinOutputKeyAndField(id)
// set all values pipelined
// store address, an address never gets deleted
rdb.conn.Send("SADD", database.AddressesKey, uh.String())
// store output
rdb.conn.Send("HSET", coinOutputKey, coinOutputField, dtypes.CoinOutput{
UnlockHash: uh,
CoinValue: co.Value,
State: dtypes.CoinOutputStateLiquid,
LockType: dtypes.LockTypeNone,
LockValue: 0,
Description: co.Description,
}.Bytes())
// store or delete the updated wallet (for now sending it only)
rdb.planWalletStorageOrDeletion(wallet, uh)
// submit all changes
err = RedisError(RedisFlushAndReceive(rdb.conn, 3))
if err != nil {
return fmt.Errorf("redis: failed to add coinoutput %s: %v", id.String(), err)
}
return nil
}
// AddLockedCoinOutput implements Database.AddLockedCoinOutput
func (rdb *RedisDatabase) AddLockedCoinOutput(id types.CoinOutputID, co CoinOutput, lt dtypes.LockType, lockValue types.LockValue) error {
uh := types.AsUnlockHash(co.Condition.UnlockHash())
addressKey, addressField := database.GetAddressKeyAndField(uh)
// get initial values
wallet, err := rdb.redisWallet(rdb.conn.Do("HGET", addressKey, addressField))
if err != nil {
return fmt.Errorf(
"redis: failed to get wallet for %s at %s#%s: %v", uh.String(), addressKey, addressField, err)
}
err = wallet.Balance.Locked.AddLockedCoinOutput(id, types.WalletLockedOutput{
Amount: co.Value,
LockedUntil: rdb.lockValueAsLockTime(lt, lockValue),
Description: co.Description,
})
if err != nil {
return fmt.Errorf(
"redis: failed to add locked coinoutput %s to wallet for %s: %v",
id.String(), uh.String(), err)
}
// set all values pipeline
// store address, an address never gets deleted
rdb.conn.Send("SADD", database.AddressesKey, uh.String())
// store coinoutput in list of locked coins for wallet
// keep track of locked output
switch lt {
case dtypes.LockTypeHeight:
rdb.conn.Send("RPUSH", getLockHeightBucketKey(lockValue), id.String())
case dtypes.LockTypeTime:
rdb.conn.Send("RPUSH", getLockTimeBucketKey(lockValue), dtypes.CoinOutputLock{
CoinOutputID: id,
LockValue: lockValue,
}.String())
}
// store output
coinOutputKey, coinOutputField := database.GetCoinOutputKeyAndField(id)
rdb.conn.Send("HSET", coinOutputKey, coinOutputField, dtypes.CoinOutput{
UnlockHash: uh,
CoinValue: co.Value,
State: dtypes.CoinOutputStateLocked,
LockType: lt,
LockValue: lockValue,
Description: co.Description,
}.Bytes())
// store or delete the updated wallet (for now sending it only)
rdb.planWalletStorageOrDeletion(wallet, uh)
// submit all changes
err = RedisError(RedisFlushAndReceive(rdb.conn, 4))
if err != nil {
return fmt.Errorf("redis: failed to add coinoutput %s: %v", id.String(), err)
}
return nil
}
// SpendCoinOutput implements Database.SpendCoinOutput
func (rdb *RedisDatabase) SpendCoinOutput(id types.CoinOutputID) error {
var result DatabaseCoinOutputResult
err := RedisBytesLoader(&result)(rdb.spendCoinOutputScript.Do(rdb.conn, id.String()))
if err != nil {
return fmt.Errorf(
"redis: failed to spend coin output: cannot update coin output %s: %v",
id.String(), err)
}
// get wallet, so its balance can be updated
addressKey, addressField := database.GetAddressKeyAndField(result.UnlockHash)
wallet, err := rdb.redisWallet(rdb.conn.Do("HGET", addressKey, addressField))
if err != nil {
return fmt.Errorf(
"redis: failed to get wallet for %s at %s#%s: %v", result.UnlockHash.String(), addressKey, addressField, err)
}
// update unlocked coins (and optionally mapped outputs)
wallet.Balance.Unlocked.SubUnlockedCoinOutput(id, result.CoinValue, true)
// store or delete the updated wallet
err = rdb.storeOrDeleteWallet(wallet, result.UnlockHash)
if err != nil {
return fmt.Errorf(
"redis: failed to spend coin output: failed to store/delete wallet %s as part of coinoutput %s: %v",
result.UnlockHash.String(), id.String(), err)
}
return nil
}
// RevertCoinInput implements Database.RevertCoinInput
// more or less a reverse process of SpendCoinOutput
func (rdb *RedisDatabase) RevertCoinInput(id types.CoinOutputID) error {
var result DatabaseCoinOutputResult
err := RedisBytesLoader(&result)(rdb.unspendCoinOutputScript.Do(rdb.conn, id.String()))
if err != nil {
return fmt.Errorf(
"redis: failed to revert coin input: cannot update coin output %s: %v",
id.String(), err)
}
// get wallet, so its balance can be updated
addressKey, addressField := database.GetAddressKeyAndField(result.UnlockHash)
wallet, err := rdb.redisWallet(rdb.conn.Do("HGET", addressKey, addressField))
if err != nil {
return fmt.Errorf(
"redis: failed to get wallet for %s at %s#%s: %v", result.UnlockHash.String(), addressKey, addressField, err)
}
// increase coin count and optionally add output
if rdb.filters.Match(result.Description) {
err = wallet.Balance.Unlocked.AddUnlockedCoinOutput(id, types.WalletUnlockedOutput{
Amount: result.CoinValue,
Description: result.Description,
}, true)
if err != nil {
return fmt.Errorf(
"redis: failed to add unlocked coinoutput %s to wallet for %s: %v",
id.String(), result.UnlockHash.String(), err)
}
} else {
wallet.Balance.Unlocked.Total = wallet.Balance.Unlocked.Total.Add(result.CoinValue)
}
// store or delete the updated wallet
err = rdb.storeOrDeleteWallet(wallet, result.UnlockHash)
if err != nil {
return fmt.Errorf(
"redis: failed to revert coin input: failed to store/delete wallet %s as part of coinoutput %s: %v",
result.UnlockHash.String(), id.String(), err)
}
return nil
}
// RevertCoinOutput implements Database.RevertCoinOutput
func (rdb *RedisDatabase) RevertCoinOutput(id types.CoinOutputID) (dtypes.CoinOutputState, error) {
var co dtypes.CoinOutput
err := RedisBytesLoader(&co)(rdb.coinOutputDropScript.Do(rdb.conn, id.String()))
if err != nil {
return dtypes.CoinOutputStateNil, fmt.Errorf(
"redis: failed to revert coin output: cannot drop coin output %s: %v",
id.String(), err)
}
if co.State == dtypes.CoinOutputStateNil {
return dtypes.CoinOutputStateNil, fmt.Errorf(
"redis: failed to revert coin output: nil coin output state %s",
id.String())
}
var sendCount int
if co.State != dtypes.CoinOutputStateSpent {
// update all data for this unspent coin output
sendCount++
// get wallet, so its balance can be updated
addressKey, addressField := database.GetAddressKeyAndField(co.UnlockHash)
wallet, err := rdb.redisWallet(rdb.conn.Do("HGET", addressKey, addressField))
if err != nil {
return dtypes.CoinOutputStateNil, fmt.Errorf(
"redis: failed to get wallet for %s at %s#%s: %v", co.UnlockHash.String(), addressKey, addressField, err)
}
// update correct balanace
switch co.State {
case dtypes.CoinOutputStateLiquid:
// update unlocked balance of address wallet (and optionally mapped outputs)
wallet.Balance.Unlocked.SubUnlockedCoinOutput(id, co.CoinValue, true)
case dtypes.CoinOutputStateLocked:
// update locked output map and balance of address wallet
err = wallet.Balance.Locked.SubLockedCoinOutput(id)
if err != nil {
return dtypes.CoinOutputStateNil, fmt.Errorf(
"redis: failed to revert coin output %s: %v",
id.String(), err)
}
}
// store or delete the updated wallet (just sending it for now)
rdb.planWalletStorageOrDeletion(wallet, co.UnlockHash)
}
// always remove lock properties if a lock is used, no matter the state
if co.LockType != dtypes.LockTypeNone {
sendCount++
// remove locked coin output lock
switch co.LockType {
case dtypes.LockTypeHeight:
rdb.conn.Send("LREM", getLockHeightBucketKey(co.LockValue), 1, id.String())
case dtypes.LockTypeTime: