-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathchain.go
More file actions
1276 lines (1153 loc) · 34.7 KB
/
chain.go
File metadata and controls
1276 lines (1153 loc) · 34.7 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
/*
* Copyright 2018 The CovenantSQL Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sqlchain
import (
"bytes"
"context"
"database/sql"
"encoding/binary"
"fmt"
"os"
rt "runtime"
"sync"
"sync/atomic"
"time"
"github.com/pkg/errors"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util"
"github.com/CovenantSQL/CovenantSQL/crypto"
"github.com/CovenantSQL/CovenantSQL/crypto/asymmetric"
"github.com/CovenantSQL/CovenantSQL/crypto/kms"
"github.com/CovenantSQL/CovenantSQL/proto"
"github.com/CovenantSQL/CovenantSQL/route"
"github.com/CovenantSQL/CovenantSQL/rpc"
"github.com/CovenantSQL/CovenantSQL/types"
"github.com/CovenantSQL/CovenantSQL/utils"
"github.com/CovenantSQL/CovenantSQL/utils/log"
x "github.com/CovenantSQL/CovenantSQL/xenomint"
xi "github.com/CovenantSQL/CovenantSQL/xenomint/interfaces"
xs "github.com/CovenantSQL/CovenantSQL/xenomint/sqlite"
)
const (
minBlockCacheTTL = int32(30)
)
var (
metaState = [4]byte{'S', 'T', 'A', 'T'}
metaBlockIndex = [4]byte{'B', 'L', 'C', 'K'}
metaResponseIndex = [4]byte{'R', 'E', 'S', 'P'}
metaAckIndex = [4]byte{'Q', 'A', 'C', 'K'}
leveldbConf = opt.Options{}
// Atomic counters for stats
cachedBlockCount int32
)
func init() {
leveldbConf.Compression = opt.SnappyCompression
}
func statBlock(b *types.Block) {
atomic.AddInt32(&cachedBlockCount, 1)
rt.SetFinalizer(b, func(_ *types.Block) {
atomic.AddInt32(&cachedBlockCount, -1)
})
}
// heightToKey converts a height in int32 to a key in bytes.
func heightToKey(h int32) (key []byte) {
key = make([]byte, 4)
binary.BigEndian.PutUint32(key, uint32(h))
return
}
// keyWithSymbolToHeight converts a height back from a key(ack/resp/req/block) in bytes.
// ack key:
// ['Q', 'A', 'C', 'K', height, hash]
// resp key:
// ['R', 'E', 'S', 'P', height, hash]
// req key:
// ['R', 'E', 'Q', 'U', height, hash]
// block key:
// ['B', 'L', 'C', 'K', height, hash].
func keyWithSymbolToHeight(k []byte) int32 {
if len(k) < 8 {
return -1
}
return int32(binary.BigEndian.Uint32(k[4:]))
}
// Chain represents a sql-chain.
type Chain struct {
// bdb stores state, profile and block
bdb *leveldb.DB
// tdb stores ack/request/response
tdb *leveldb.DB
bi *blockIndex
ai *ackIndex
st *x.State
cl *rpc.Caller
rt *runtime
ctx context.Context // ctx is the root context of Chain
blocks chan *types.Block
heights chan int32
responses chan *types.ResponseHeader
acks chan *types.AckHeader
// DBAccount info
databaseID proto.DatabaseID
tokenType types.TokenType
gasPrice uint64
updatePeriod uint64
// Cached fileds, may need to renew some of this fields later.
//
// pk is the private key of the local miner.
pk *asymmetric.PrivateKey
// addr is the AccountAddress generate from public key.
addr *proto.AccountAddress
}
// NewChain creates a new sql-chain struct.
func NewChain(c *Config) (chain *Chain, err error) {
return NewChainWithContext(context.Background(), c)
}
// NewChainWithContext creates a new sql-chain struct with context.
func NewChainWithContext(ctx context.Context, c *Config) (chain *Chain, err error) {
// TODO(leventeliu): this is a rough solution, you may also want to clean database file and
// force rebuilding.
var fi os.FileInfo
if fi, err = os.Stat(c.ChainFilePrefix + "-block-state.ldb"); err == nil && fi.Mode().IsDir() {
return LoadChain(c)
}
err = c.Genesis.VerifyAsGenesis()
if err != nil {
return
}
// Open LevelDB for block and state
bdbFile := c.ChainFilePrefix + "-block-state.ldb"
bdb, err := leveldb.OpenFile(bdbFile, &leveldbConf)
if err != nil {
err = errors.Wrapf(err, "open leveldb %s", bdbFile)
return
}
log.WithField("db", c.DatabaseID).Debugf("create new chain bdb %s", bdbFile)
// Open LevelDB for ack/request/response
tdbFile := c.ChainFilePrefix + "-ack-req-resp.ldb"
tdb, err := leveldb.OpenFile(tdbFile, &leveldbConf)
if err != nil {
err = errors.Wrapf(err, "open leveldb %s", tdbFile)
return
}
log.WithField("db", c.DatabaseID).Debugf("create new chain tdb %s", tdbFile)
// Open storage
var strg xi.Storage
if strg, err = xs.NewSqlite(c.DataFile); err != nil {
return
}
// Cache local private key
var (
pk *asymmetric.PrivateKey
addr proto.AccountAddress
)
if pk, err = kms.GetLocalPrivateKey(); err != nil {
err = errors.Wrap(err, "failed to cache private key")
return
}
addr, err = crypto.PubKeyHash(pk.PubKey())
if err != nil {
log.WithError(err).WithField("db", c.DatabaseID).Warning("failed to generate addr in NewChain")
return
}
// Create chain state
chain = &Chain{
bdb: bdb,
tdb: tdb,
bi: newBlockIndex(),
ai: newAckIndex(),
st: x.NewState(sql.IsolationLevel(c.IsolationLevel), c.Server, strg),
cl: rpc.NewCaller(),
rt: newRunTime(ctx, c),
ctx: ctx,
blocks: make(chan *types.Block),
heights: make(chan int32, 1),
responses: make(chan *types.ResponseHeader),
acks: make(chan *types.AckHeader),
tokenType: c.TokenType,
gasPrice: c.GasPrice,
updatePeriod: c.UpdatePeriod,
databaseID: c.DatabaseID,
pk: pk,
addr: &addr,
}
if err = chain.pushBlock(c.Genesis); err != nil {
return nil, err
}
return
}
// LoadChain loads the chain state from the specified database and rebuilds a memory index.
func LoadChain(c *Config) (chain *Chain, err error) {
return LoadChainWithContext(context.Background(), c)
}
// LoadChainWithContext loads the chain state from the specified database and rebuilds
// a memory index with context.
func LoadChainWithContext(ctx context.Context, c *Config) (chain *Chain, err error) {
// Open LevelDB for block and state
bdbFile := c.ChainFilePrefix + "-block-state.ldb"
bdb, err := leveldb.OpenFile(bdbFile, &leveldbConf)
if err != nil {
err = errors.Wrapf(err, "open leveldb %s", bdbFile)
return
}
// Open LevelDB for ack/request/response
tdbFile := c.ChainFilePrefix + "-ack-req-resp.ldb"
tdb, err := leveldb.OpenFile(tdbFile, &leveldbConf)
if err != nil {
err = errors.Wrapf(err, "open leveldb %s", tdbFile)
return
}
// Open x.State
var strg xi.Storage
if strg, err = xs.NewSqlite(c.DataFile); err != nil {
return
}
// Cache local private key
var (
pk *asymmetric.PrivateKey
addr proto.AccountAddress
)
if pk, err = kms.GetLocalPrivateKey(); err != nil {
err = errors.Wrap(err, "failed to cache private key")
return
}
addr, err = crypto.PubKeyHash(pk.PubKey())
if err != nil {
log.WithError(err).WithField("db", c.DatabaseID).Warning("failed to generate addr in LoadChain")
return
}
// Create chain state
chain = &Chain{
bdb: bdb,
tdb: tdb,
bi: newBlockIndex(),
ai: newAckIndex(),
st: x.NewState(sql.IsolationLevel(c.IsolationLevel), c.Server, strg),
cl: rpc.NewCaller(),
rt: newRunTime(ctx, c),
ctx: ctx,
blocks: make(chan *types.Block),
heights: make(chan int32, 1),
responses: make(chan *types.ResponseHeader),
acks: make(chan *types.AckHeader),
tokenType: c.TokenType,
gasPrice: c.GasPrice,
updatePeriod: c.UpdatePeriod,
databaseID: c.DatabaseID,
pk: pk,
addr: &addr,
}
// Read state struct
stateEnc, err := chain.bdb.Get(metaState[:], nil)
if err != nil {
return nil, err
}
st := &state{}
if err = utils.DecodeMsgPack(stateEnc, st); err != nil {
return nil, err
}
log.WithFields(log.Fields{
"peer": chain.rt.getPeerInfoString(),
"state": st,
"db": c.DatabaseID,
}).Debug("loading state from database")
// Read blocks and rebuild memory index
var (
id uint64
index int32
last *blockNode
blockIter = chain.bdb.NewIterator(util.BytesPrefix(metaBlockIndex[:]), nil)
)
defer blockIter.Release()
for index = 0; blockIter.Next(); index++ {
var (
k = blockIter.Key()
v = blockIter.Value()
block = &types.Block{}
current, parent *blockNode
)
if err = utils.DecodeMsgPack(v, block); err != nil {
err = errors.Wrapf(err, "decoding failed at height %d with key %s",
keyWithSymbolToHeight(k), string(k))
return
}
log.WithFields(log.Fields{
"peer": chain.rt.getPeerInfoString(),
"block": block.BlockHash().String(),
"db": c.DatabaseID,
}).Debug("loading block from database")
if last == nil {
if err = block.VerifyAsGenesis(); err != nil {
err = errors.Wrap(err, "genesis verification failed")
return
}
// Set constant fields from genesis block
chain.rt.setGenesis(block)
} else if block.ParentHash().IsEqual(&last.hash) {
if err = block.Verify(); err != nil {
err = errors.Wrapf(err, "block verification failed at height %d with key %s",
keyWithSymbolToHeight(k), string(k))
return
}
parent = last
} else {
if parent = chain.bi.lookupNode(block.ParentHash()); parent == nil {
return nil, ErrParentNotFound
}
}
// Update id
if nid, ok := block.CalcNextID(); ok && nid > id {
id = nid
}
current = &blockNode{}
current.initBlockNode(chain.rt.getHeightFromTime(block.Timestamp()), block, parent)
chain.bi.addBlock(current)
last = current
}
if err = blockIter.Error(); err != nil {
err = errors.Wrap(err, "load block")
return
}
// Set chain state
st.node = last
chain.rt.setHead(st)
chain.st.SetSeq(id)
chain.pruneBlockCache()
// Read queries and rebuild memory index
respIter := chain.tdb.NewIterator(util.BytesPrefix(metaResponseIndex[:]), nil)
defer respIter.Release()
for respIter.Next() {
k := respIter.Key()
v := respIter.Value()
h := keyWithSymbolToHeight(k)
var resp = &types.SignedResponseHeader{}
if err = utils.DecodeMsgPack(v, resp); err != nil {
err = errors.Wrapf(err, "load resp, height %d, index %s", h, string(k))
return
}
log.WithFields(log.Fields{
"height": h,
"header": resp.Hash().String(),
"db": c.DatabaseID,
}).Debug("loaded new resp header")
}
if err = respIter.Error(); err != nil {
err = errors.Wrap(err, "load resp")
return
}
ackIter := chain.tdb.NewIterator(util.BytesPrefix(metaAckIndex[:]), nil)
defer ackIter.Release()
for ackIter.Next() {
k := ackIter.Key()
v := ackIter.Value()
h := keyWithSymbolToHeight(k)
var ack = &types.SignedAckHeader{}
if err = utils.DecodeMsgPack(v, ack); err != nil {
err = errors.Wrapf(err, "load ack, height %d, index %s", h, string(k))
return
}
log.WithFields(log.Fields{
"height": h,
"header": ack.Hash().String(),
"db": c.DatabaseID,
}).Debug("loaded new ack header")
}
if err = respIter.Error(); err != nil {
err = errors.Wrap(err, "load ack")
return
}
return
}
// pushBlock pushes the signed block header to extend the current main chain.
func (c *Chain) pushBlock(b *types.Block) (err error) {
// Prepare and encode
h := c.rt.getHeightFromTime(b.Timestamp())
node := newBlockNode(h, b, c.rt.getHead().node)
st := &state{
node: node,
Head: node.hash,
Height: node.height,
}
var encBlock, encState *bytes.Buffer
if encBlock, err = utils.EncodeMsgPack(b); err != nil {
return
}
if encState, err = utils.EncodeMsgPack(st); err != nil {
return
}
// Update in transaction
t, err := c.bdb.OpenTransaction()
if err = t.Put(metaState[:], encState.Bytes(), nil); err != nil {
err = errors.Wrapf(err, "put %s", string(metaState[:]))
t.Discard()
return
}
blockKey := utils.ConcatAll(metaBlockIndex[:], node.indexKey())
if err = t.Put(blockKey, encBlock.Bytes(), nil); err != nil {
err = errors.Wrapf(err, "put %s", string(node.indexKey()))
t.Discard()
return
}
if err = t.Commit(); err != nil {
err = errors.Wrapf(err, "commit error")
t.Discard()
return
}
c.rt.setHead(st)
c.bi.addBlock(node)
// Keep track of the queries from the new block
var ierr error
for i, v := range b.QueryTxs {
if ierr = c.AddResponse(v.Response); ierr != nil {
log.WithFields(log.Fields{
"index": i,
"producer": b.Producer(),
"block_hash": b.BlockHash(),
"db": c.databaseID,
}).WithError(ierr).Warn("failed to add response to ackIndex")
}
}
for i, v := range b.Acks {
if ierr = c.remove(v); ierr != nil {
log.WithFields(log.Fields{
"index": i,
"producer": b.Producer(),
"block_hash": b.BlockHash(),
"db": c.databaseID,
}).WithError(ierr).Warn("failed to remove Ack from ackIndex")
}
}
if err == nil {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString()[:14],
"time": c.rt.getChainTimeString(),
"block": b.BlockHash().String()[:8],
"producer": b.Producer()[:8],
"queryCount": len(b.QueryTxs),
"ackCount": len(b.Acks),
"blockTime": b.Timestamp().Format(time.RFC3339Nano),
"height": c.rt.getHeightFromTime(b.Timestamp()),
"head": fmt.Sprintf("%s <- %s",
func() string {
if st.node.parent != nil {
return st.node.parent.hash.String()[:8]
}
return "|"
}(), st.Head.String()[:8]),
"headHeight": c.rt.getHead().Height,
"db": c.databaseID,
}).Info("pushed new block")
}
return
}
// pushAckedQuery pushes a acknowledged, signed and verified query into the chain.
func (c *Chain) pushAckedQuery(ack *types.SignedAckHeader) (err error) {
log.WithField("db", c.databaseID).Debugf("push ack %s", ack.Hash().String())
h := c.rt.getHeightFromTime(ack.GetResponseTimestamp())
k := heightToKey(h)
var enc *bytes.Buffer
if enc, err = utils.EncodeMsgPack(ack); err != nil {
return
}
tdbKey := utils.ConcatAll(metaAckIndex[:], k, ack.Hash().AsBytes())
if err = c.register(ack); err != nil {
err = errors.Wrapf(err, "register ack %v at height %d", ack.Hash(), h)
return
}
if err = c.tdb.Put(tdbKey, enc.Bytes(), nil); err != nil {
err = errors.Wrapf(err, "put ack %d %s", h, ack.Hash().String())
return
}
return
}
// produceBlock prepares, signs and advises the pending block to the other peers.
func (c *Chain) produceBlock(now time.Time) (err error) {
var (
frs []*types.Request
qts []*x.QueryTracker
)
if frs, qts, err = c.st.CommitEx(); err != nil {
return
}
var block = &types.Block{
SignedHeader: types.SignedHeader{
Header: types.Header{
Version: 0x01000000,
Producer: c.rt.getServer(),
GenesisHash: c.rt.genesisHash,
ParentHash: c.rt.getHead().Head,
// MerkleRoot: will be set by BPBlock.PackAndSignBlock(PrivateKey)
Timestamp: now,
},
},
FailedReqs: frs,
QueryTxs: make([]*types.QueryAsTx, len(qts)),
Acks: c.ai.acks(c.rt.getHeightFromTime(now)),
}
statBlock(block)
for i, v := range qts {
// TODO(leventeliu): maybe block waiting at a ready channel instead?
for !v.Ready() {
time.Sleep(1 * time.Millisecond)
if c.rt.ctx.Err() != nil {
err = c.rt.ctx.Err()
return
}
}
block.QueryTxs[i] = &types.QueryAsTx{
// TODO(leventeliu): add acks for billing.
Request: v.Req,
Response: &v.Resp.Header,
}
}
// Sign block
if err = block.PackAndSignBlock(c.pk); err != nil {
return
}
// Send to pending list
select {
case c.blocks <- block:
case <-c.rt.ctx.Done():
err = c.rt.ctx.Err()
return
}
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"using_timestamp": now.Format(time.RFC3339Nano),
"block_hash": block.BlockHash().String(),
"db": c.databaseID,
}).Debug("produced new block")
// Advise new block to the other peers
var (
req = &MuxAdviseNewBlockReq{
Envelope: proto.Envelope{
// TODO(leventeliu): Add fields.
},
DatabaseID: c.databaseID,
AdviseNewBlockReq: AdviseNewBlockReq{
Block: block,
Count: func() int32 {
if nd := c.bi.lookupNode(block.BlockHash()); nd != nil {
return nd.count
}
if pn := c.bi.lookupNode(block.ParentHash()); pn != nil {
return pn.count + 1
}
return -1
}(),
},
}
peers = c.rt.getPeers()
wg = &sync.WaitGroup{}
)
for _, s := range peers.Servers {
if s != c.rt.getServer() {
wg.Add(1)
go func(id proto.NodeID) {
defer wg.Done()
resp := &MuxAdviseNewBlockResp{}
if err := c.cl.CallNodeWithContext(
c.rt.ctx, id, route.SQLCAdviseNewBlock.String(), req, resp,
); err != nil {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"using_timestamp": now.Format(time.RFC3339Nano),
"block_hash": block.BlockHash().String(),
"db": c.databaseID,
}).WithError(err).Error("failed to advise new block")
}
}(s)
}
}
wg.Wait()
return
}
func (c *Chain) syncHead() {
// Try to fetch if the block of the current turn is not advised yet
if h := c.rt.getNextTurn() - 1; c.rt.getHead().Height < h {
var err error
req := &MuxFetchBlockReq{
Envelope: proto.Envelope{
// TODO(leventeliu): Add fields.
},
DatabaseID: c.databaseID,
FetchBlockReq: FetchBlockReq{
Height: h,
},
}
resp := &MuxFetchBlockResp{}
peers := c.rt.getPeers()
succ := false
for i, s := range peers.Servers {
if s != c.rt.getServer() {
if err = c.cl.CallNode(
s, route.SQLCFetchBlock.String(), req, resp,
); err != nil || resp.Block == nil {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"remote": fmt.Sprintf("[%d/%d] %s", i, len(peers.Servers), s),
"curr_turn": c.rt.getNextTurn(),
"head_height": c.rt.getHead().Height,
"head_block": c.rt.getHead().Head.String(),
"db": c.databaseID,
}).WithError(err).Debug(
"Failed to fetch block from peer")
} else {
statBlock(resp.Block)
select {
case c.blocks <- resp.Block:
case <-c.rt.ctx.Done():
err = c.rt.ctx.Err()
return
}
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"remote": fmt.Sprintf("[%d/%d] %s", i, len(peers.Servers), s),
"curr_turn": c.rt.getNextTurn(),
"head_height": c.rt.getHead().Height,
"head_block": c.rt.getHead().Head.String(),
"db": c.databaseID,
}).Debug(
"Fetch block from remote peer successfully")
succ = true
break
}
}
}
if !succ {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"head_height": c.rt.getHead().Height,
"head_block": c.rt.getHead().Head.String(),
"db": c.databaseID,
}).Debug(
"Cannot get block from any peer")
}
}
}
// runCurrentTurn does the check and runs block producing if its my turn.
func (c *Chain) runCurrentTurn(now time.Time) {
defer func() {
c.stat()
c.pruneBlockCache()
c.rt.setNextTurn()
c.ai.advance(c.rt.getMinValidHeight())
// Info the block processing goroutine that the chain height has grown, so please return
// any stashed blocks for further check.
c.heights <- c.rt.getHead().Height
}()
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"head_height": c.rt.getHead().Height,
"head_block": c.rt.getHead().Head.String(),
"using_timestamp": now.Format(time.RFC3339Nano),
"db": c.databaseID,
}).Debug("run current turn")
if c.rt.getHead().Height < c.rt.getNextTurn()-1 {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"head_height": c.rt.getHead().Height,
"head_block": c.rt.getHead().Head.String(),
"using_timestamp": now.Format(time.RFC3339Nano),
"db": c.databaseID,
}).Error("A block will be skipped")
}
if !c.rt.isMyTurn() {
return
}
if err := c.produceBlock(now); err != nil {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"using_timestamp": now.Format(time.RFC3339Nano),
"db": c.databaseID,
}).WithError(err).Error(
"Failed to produce block")
}
}
// mainCycle runs main cycle of the sql-chain.
func (c *Chain) mainCycle(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
c.syncHead()
if t, d := c.rt.nextTick(); d > 0 {
//log.WithFields(log.Fields{
// "peer": c.rt.getPeerInfoString(),
// "time": c.rt.getChainTimeString(),
// "next_turn": c.rt.getNextTurn(),
// "head_height": c.rt.getHead().Height,
// "head_block": c.rt.getHead().Head.String(),
// "using_timestamp": t.Format(time.RFC3339Nano),
// "duration": d,
// "db": c.databaseID,
//}).Debug("main cycle")
time.Sleep(d)
} else {
c.runCurrentTurn(t)
}
}
}
}
// sync synchronizes blocks and queries from the other peers.
func (c *Chain) sync() (err error) {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"db": c.databaseID,
}).Debug("synchronizing chain state")
for {
now := c.rt.now()
height := c.rt.getHeightFromTime(now)
if c.rt.getNextTurn() >= height {
break
}
for c.rt.getNextTurn() <= height {
// TODO(leventeliu): fetch blocks and queries.
c.rt.setNextTurn()
}
}
return
}
func (c *Chain) processBlocks(ctx context.Context) {
var (
cld, ccl = context.WithCancel(ctx)
wg = &sync.WaitGroup{}
)
returnStash := func(stash []*types.Block) {
defer wg.Done()
for _, block := range stash {
select {
case c.blocks <- block:
case <-cld.Done():
return
}
}
}
defer func() {
ccl()
wg.Wait()
}()
var (
stash []*types.Block
)
for {
select {
case h := <-c.heights:
// Return all stashed blocks to pending channel
log.WithFields(log.Fields{
"height": h,
"stashs": len(stash),
"db": c.databaseID,
}).Debug("read new height from channel")
if stash != nil {
wg.Add(1)
go returnStash(stash)
stash = nil
}
case block := <-c.blocks:
height := c.rt.getHeightFromTime(block.Timestamp())
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"head_height": c.rt.getHead().Height,
"head_block": c.rt.getHead().Head.String(),
"block_height": height,
"block_hash": block.BlockHash().String(),
"db": c.databaseID,
}).Debug("processing new block")
if height > c.rt.getNextTurn()-1 {
// Stash newer blocks for later check
stash = append(stash, block)
} else {
// Process block
if height < c.rt.getNextTurn()-1 {
// TODO(leventeliu): check and add to fork list.
} else {
if err := c.CheckAndPushNewBlock(block); err != nil {
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"curr_turn": c.rt.getNextTurn(),
"head_height": c.rt.getHead().Height,
"head_block": c.rt.getHead().Head.String(),
"block_height": height,
"block_hash": block.BlockHash().String(),
"db": c.databaseID,
}).WithError(err).Error("Failed to check and push new block")
} else {
head := c.rt.getHead()
currentCount := uint64(head.node.count)
if currentCount%c.updatePeriod == 0 {
ub, err := c.billing(head.node)
if err != nil {
log.WithError(err).WithField("db", c.databaseID).Error("billing failed")
}
// allocate nonce
nonceReq := &types.NextAccountNonceReq{}
nonceResp := &types.NextAccountNonceResp{}
nonceReq.Addr = *c.addr
if err = rpc.RequestBP(route.MCCNextAccountNonce.String(), nonceReq, nonceResp); err != nil {
// allocate nonce failed
log.WithError(err).WithField("db", c.databaseID).Warning("allocate nonce for transaction failed")
}
ub.Nonce = nonceResp.Nonce
if err = ub.Sign(c.pk); err != nil {
log.WithError(err).WithField("db", c.databaseID).Warning("sign tx failed")
}
addTxReq := &types.AddTxReq{TTL: 1}
addTxResp := &types.AddTxResp{}
addTxReq.Tx = ub
log.WithField("db", c.databaseID).Debugf("nonce in processBlocks: %d, addr: %s",
addTxReq.Tx.GetAccountNonce(), addTxReq.Tx.GetAccountAddress())
if err = rpc.RequestBP(route.MCCAddTx.String(), addTxReq, addTxResp); err != nil {
log.WithError(err).WithField("db", c.databaseID).Warning("send tx failed")
}
}
}
}
}
case <-ctx.Done():
return
}
}
}
// Start starts the main process of the sql-chain.
func (c *Chain) Start() (err error) {
if err = c.sync(); err != nil {
return
}
c.rt.goFunc(c.processBlocks)
c.rt.goFunc(c.mainCycle)
c.rt.startService(c)
return
}
// Stop stops the main process of the sql-chain.
func (c *Chain) Stop() (err error) {
// Stop main process
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"db": c.databaseID,
}).Debug("stopping chain")
c.rt.stop(c.databaseID)
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"db": c.databaseID,
}).Debug("chain service and workers stopped")
// Close LevelDB file
var ierr error
if ierr = c.bdb.Close(); ierr != nil && err == nil {
err = ierr
}
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"db": c.databaseID,
}).WithError(ierr).Debug("chain database closed")
if ierr = c.tdb.Close(); ierr != nil && err == nil {
err = ierr
}
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"db": c.databaseID,
}).WithError(ierr).Debug("chain database closed")
// Close state
if ierr = c.st.Close(false); ierr != nil && err == nil {
err = ierr
}
log.WithFields(log.Fields{
"peer": c.rt.getPeerInfoString(),
"time": c.rt.getChainTimeString(),
"db": c.databaseID,
}).WithError(ierr).Debug("chain state storage closed")
return
}
// FetchBlock fetches the block at specified height from local cache.
func (c *Chain) FetchBlock(height int32) (b *types.Block, err error) {
if n := c.rt.getHead().node.ancestor(height); n != nil {
b, err = c.fetchBlockByIndexKey(n.indexKey())
if err != nil {
return
}
}
return
}
// FetchBlockByCount fetches the block at specified count from local cache.
func (c *Chain) FetchBlockByCount(count int32) (b *types.Block, realCount int32, height int32, err error) {
var n *blockNode
if count < 0 {