aboutsummaryrefslogtreecommitdiffstats
path: root/core/headerchain.go
blob: 4eff41b26f98e0e257df28d3fa06c61a98ec2597 (plain) (blame)
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
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package core

import (
    crand "crypto/rand"
    "errors"
    "fmt"
    "math"
    "math/big"
    mrand "math/rand"
    "reflect"
    "sync/atomic"
    "time"

    dexCore "github.com/dexon-foundation/dexon-consensus/core"
    coreCrypto "github.com/dexon-foundation/dexon-consensus/core/crypto"
    coreTypes "github.com/dexon-foundation/dexon-consensus/core/types"

    "github.com/dexon-foundation/dexon/common"
    "github.com/dexon-foundation/dexon/consensus"
    "github.com/dexon-foundation/dexon/consensus/dexcon"
    "github.com/dexon-foundation/dexon/core/rawdb"
    "github.com/dexon-foundation/dexon/core/types"
    "github.com/dexon-foundation/dexon/core/vm"
    "github.com/dexon-foundation/dexon/crypto"
    "github.com/dexon-foundation/dexon/ethdb"
    "github.com/dexon-foundation/dexon/log"
    "github.com/dexon-foundation/dexon/params"
    "github.com/dexon-foundation/dexon/rlp"
    "github.com/dexon-foundation/dexon/trie"
    "github.com/hashicorp/golang-lru"
)

const (
    headerCacheLimit = 512
    tdCacheLimit     = 1024
    numberCacheLimit = 2048
)

// HeaderChain implements the basic block header chain logic that is shared by
// core.BlockChain and light.LightChain. It is not usable in itself, only as
// a part of either structure.
// It is not thread safe either, the encapsulating chain structures should do
// the necessary mutex locking/unlocking.
type HeaderChain struct {
    config *params.ChainConfig

    chainDb       ethdb.Database
    genesisHeader *types.Header

    currentHeader     atomic.Value // Current head of the header chain (may be above the block chain!)
    currentHeaderHash common.Hash  // Hash of the current head of the header chain (prevent recomputing all the time)

    headerCache *lru.Cache // Cache for the most recent block headers
    tdCache     *lru.Cache // Cache for the most recent block total difficulties
    numberCache *lru.Cache // Cache for the most recent block numbers

    procInterrupt func() bool

    rand   *mrand.Rand
    engine consensus.Engine
}

// NewHeaderChain creates a new HeaderChain structure.
//  getValidator should return the parent's validator
//  procInterrupt points to the parent's interrupt semaphore
//  wg points to the parent's shutdown wait group
func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
    headerCache, _ := lru.New(headerCacheLimit)
    tdCache, _ := lru.New(tdCacheLimit)
    numberCache, _ := lru.New(numberCacheLimit)

    // Seed a fast but crypto originating random generator
    seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    if err != nil {
        return nil, err
    }

    hc := &HeaderChain{
        config:        config,
        chainDb:       chainDb,
        headerCache:   headerCache,
        tdCache:       tdCache,
        numberCache:   numberCache,
        procInterrupt: procInterrupt,
        rand:          mrand.New(mrand.NewSource(seed.Int64())),
        engine:        engine,
    }

    hc.genesisHeader = hc.GetHeaderByNumber(0)
    if hc.genesisHeader == nil {
        return nil, ErrNoGenesis
    }

    hc.currentHeader.Store(hc.genesisHeader)
    if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
        if chead := hc.GetHeaderByHash(head); chead != nil {
            hc.currentHeader.Store(chead)
        }
    }
    hc.currentHeaderHash = hc.CurrentHeader().Hash()

    return hc, nil
}

// GetBlockNumber retrieves the block number belonging to the given hash
// from the cache or database
func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 {
    if cached, ok := hc.numberCache.Get(hash); ok {
        number := cached.(uint64)
        return &number
    }
    number := rawdb.ReadHeaderNumber(hc.chainDb, hash)
    if number != nil {
        hc.numberCache.Add(hash, *number)
    }
    return number
}

// WriteHeader writes a header into the local chain, given that its parent is
// already known. If the total difficulty of the newly inserted header becomes
// greater than the current known TD, the canonical chain is re-routed.
//
// Note: This method is not concurrent-safe with inserting blocks simultaneously
// into the chain, as side effects caused by reorganisations cannot be emulated
// without the real blocks. Hence, writing headers directly should only be done
// in two scenarios: pure-header mode of operation (light clients), or properly
// separated header/block phases (non-archive clients).
func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
    // Cache some values to prevent constant recalculation
    var (
        hash   = header.Hash()
        number = header.Number.Uint64()
    )
    // Calculate the total difficulty of the header
    ptd := hc.GetTd(header.ParentHash, number-1)
    if ptd == nil {
        return NonStatTy, consensus.ErrUnknownAncestor
    }
    localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
    externTd := new(big.Int).Add(header.Difficulty, ptd)

    // Irrelevant of the canonical status, write the td and header to the database
    if err := hc.WriteTd(hash, number, externTd); err != nil {
        log.Crit("Failed to write header total difficulty", "err", err)
    }
    rawdb.WriteHeader(hc.chainDb, header)

    // If the total difficulty is higher than our known, add it to the canonical chain
    // Second clause in the if statement reduces the vulnerability to selfish mining.
    // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
    if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
        // Delete any canonical number assignments above the new head
        batch := hc.chainDb.NewBatch()
        for i := number + 1; ; i++ {
            hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
            if hash == (common.Hash{}) {
                break
            }
            rawdb.DeleteCanonicalHash(batch, i)
        }
        batch.Write()

        // Overwrite any stale canonical number assignments
        var (
            headHash   = header.ParentHash
            headNumber = header.Number.Uint64() - 1
            headHeader = hc.GetHeader(headHash, headNumber)
        )
        for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
            rawdb.WriteCanonicalHash(hc.chainDb, headHash, headNumber)

            headHash = headHeader.ParentHash
            headNumber = headHeader.Number.Uint64() - 1
            headHeader = hc.GetHeader(headHash, headNumber)
        }
        // Extend the canonical chain with the new header
        rawdb.WriteCanonicalHash(hc.chainDb, hash, number)
        rawdb.WriteHeadHeaderHash(hc.chainDb, hash)

        hc.currentHeaderHash = hash
        hc.currentHeader.Store(types.CopyHeader(header))

        status = CanonStatTy
    } else {
        status = SideStatTy
    }

    hc.headerCache.Add(hash, header)
    hc.numberCache.Add(hash, number)

    return
}

// WhCallback is a callback function for inserting individual headers.
// A callback is used for two reasons: first, in a LightChain, status should be
// processed and light chain events sent, while in a BlockChain this is not
// necessary since chain events are sent after inserting blocks. Second, the
// header writes should be protected by the parent chain mutex individually.
type WhCallback func(*types.Header) error

func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
    // Do a sanity check that the provided chain is actually ordered and linked
    for i := 1; i < len(chain); i++ {
        if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
            // Chain broke ancestry, log a message (programming error) and skip insertion
            log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
                "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())

            return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].Number,
                chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
        }
    }

    // Generate the list of seal verification requests, and start the parallel verifier
    seals := make([]bool, len(chain))
    for i := 0; i < len(seals)/checkFreq; i++ {
        index := i*checkFreq + hc.rand.Intn(checkFreq)
        if index >= len(seals) {
            index = len(seals) - 1
        }
        seals[index] = true
    }
    seals[len(seals)-1] = true // Last should always be verified to avoid junk

    abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
    defer close(abort)

    // Iterate over the headers and ensure they all check out
    for i, header := range chain {
        // If the chain is terminating, stop processing blocks
        if hc.procInterrupt() {
            log.Debug("Premature abort during headers verification")
            return 0, errors.New("aborted")
        }
        // If the header is a banned one, straight out abort
        if BadHashes[header.Hash()] {
            return i, ErrBlacklistedHash
        }
        // Otherwise wait for headers checks and ensure they pass
        if err := <-results; err != nil {
            return i, err
        }
    }

    return 0, nil
}

// InsertHeaderChain attempts to insert the given header chain in to the local
// chain, possibly creating a reorg. If an error is returned, it will return the
// index number of the failing header as well an error describing what went wrong.
//
// The verify parameter can be used to fine tune whether nonce verification
// should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verfy nonces, as well as
// because nonces can be verified sparsely, not needing to check each.
func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
    // Collect some import statistics to report on
    stats := struct{ processed, ignored int }{}
    // All headers passed verification, import them into the database
    for i, header := range chain {
        // Short circuit insertion if shutting down
        if hc.procInterrupt() {
            log.Debug("Premature abort during headers import")
            return i, errors.New("aborted")
        }
        // If the header's already known, skip it, otherwise store
        if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
            stats.ignored++
            continue
        }
        if err := writeHeader(header); err != nil {
            return i, err
        }
        stats.processed++
    }
    // Report some public statistics so the user has a clue what's going on
    last := chain[len(chain)-1]

    context := []interface{}{
        "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
        "number", last.Number, "hash", last.Hash(),
    }
    if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute {
        context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
    }
    if stats.ignored > 0 {
        context = append(context, []interface{}{"ignored", stats.ignored}...)
    }
    log.Info("Imported new block headers", context...)

    return 0, nil
}

func (hc *HeaderChain) WriteDexonHeader(header *types.HeaderWithGovState) (status WriteStatus, err error) {
    // Cache some values to prevent constant recalculation
    var (
        hash   = header.Hash()
        number = header.Number.Uint64()
    )
    // Calculate the total difficulty of the header
    ptd := hc.GetTd(header.ParentHash, number-1)
    if ptd == nil {
        return NonStatTy, consensus.ErrUnknownAncestor
    }
    localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
    externTd := new(big.Int).Add(header.Difficulty, ptd)

    // Irrelevant of the canonical status, write the td and header to the database
    if err := hc.WriteTd(hash, number, externTd); err != nil {
        log.Crit("Failed to write header total difficulty", "err", err)
    }
    rawdb.WriteHeader(hc.chainDb, header.Header)

    // If the total difficulty is higher than our known, add it to the canonical chain
    // Second clause in the if statement reduces the vulnerability to selfish mining.
    // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
    if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
        // Delete any canonical number assignments above the new head
        batch := hc.chainDb.NewBatch()
        for i := number + 1; ; i++ {
            hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
            if hash == (common.Hash{}) {
                break
            }
            rawdb.DeleteCanonicalHash(batch, i)
        }
        batch.Write()

        // Overwrite any stale canonical number assignments
        var (
            headHash   = header.ParentHash
            headNumber = header.Number.Uint64() - 1
            headHeader = hc.GetHeader(headHash, headNumber)
        )
        for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
            rawdb.WriteCanonicalHash(hc.chainDb, headHash, headNumber)

            headHash = headHeader.ParentHash
            headNumber = headHeader.Number.Uint64() - 1
            headHeader = hc.GetHeader(headHash, headNumber)
        }
        // Extend the canonical chain with the new header
        rawdb.WriteCanonicalHash(hc.chainDb, hash, number)
        rawdb.WriteHeadHeaderHash(hc.chainDb, hash)

        hc.currentHeaderHash = hash
        hc.currentHeader.Store(types.CopyHeader(header.Header))

        status = CanonStatTy
    } else {
        status = SideStatTy
    }

    hc.headerCache.Add(hash, header.Header)
    hc.numberCache.Add(hash, number)

    // Store the govState
    if govState := header.GovState; govState != nil {
        batch := hc.chainDb.NewBatch()
        for _, node := range govState.Proof {
            batch.Put(crypto.Keccak256(node), node)
        }
        if err := batch.Write(); err != nil {
            panic(fmt.Errorf("DB write error: %v", err))
        }

        triedb := trie.NewDatabase(hc.chainDb)
        t, err := trie.New(common.Hash{}, triedb)
        if err != nil {
            panic(err)
        }

        for _, kv := range govState.Storage {
            t.TryUpdate(kv[0], kv[1])
        }
        t.Commit(nil)
        triedb.Commit(t.Hash(), false)
    }
    return
}

type Wh2Callback func(*types.HeaderWithGovState) error

type headerVerifierCache struct {
    verifierCache  *dexCore.TSigVerifierCache
    gov            dexcon.GovernanceStateFetcher
    stateCache     *lru.Cache
    nodeOwnerCache *lru.Cache
    configCache    *lru.Cache
}

func newHeaderVerifierCache(
    verifierCache *dexCore.TSigVerifierCache,
    gov dexcon.GovernanceStateFetcher) *headerVerifierCache {
    stateCache, _ := lru.New(5)
    nodeOwnerCache, _ := lru.New(5)
    configCache, _ := lru.New(5)
    return &headerVerifierCache{
        verifierCache:  verifierCache,
        gov:            gov,
        stateCache:     stateCache,
        nodeOwnerCache: nodeOwnerCache,
        configCache:    configCache,
    }
}

func (c *headerVerifierCache) state(round uint64) *vm.GovernanceState {
    if state, exist := c.stateCache.Get(round); exist {
        return state.(*vm.GovernanceState)
    }
    state := c.gov.GetStateForConfigAtRound(round)
    c.stateCache.Add(round, state)
    return state
}

func (c *headerVerifierCache) getNodeOwnerByID(round uint64, ID coreTypes.NodeID) (
    common.Address, error) {
    nodeOwner, exist := c.nodeOwnerCache.Get(round)
    if !exist {
        nodeOwner = make(map[coreTypes.NodeID]interface{})
        c.nodeOwnerCache.Add(round, nodeOwner)
    }
    nodeOwnerMap := nodeOwner.(map[coreTypes.NodeID]interface{})
    if owner, exist := nodeOwnerMap[ID]; exist {
        if addr, ok := owner.(common.Address); ok {
            return addr, nil
        }
        return common.Address{}, owner.(error)
    }
    node, err := c.state(round).GetNodeByID(ID)
    if err != nil {
        nodeOwnerMap[ID] = err
        return common.Address{}, err
    }
    nodeOwnerMap[ID] = node.Owner
    return node.Owner, nil

}

func (c *headerVerifierCache) configuration(round uint64) *params.DexconConfig {
    if cfg, exist := c.configCache.Get(round); exist {
        return cfg.(*params.DexconConfig)
    }
    cfg := c.state(round).Configuration()
    c.configCache.Add(round, cfg)
    return cfg
}

func (hc *HeaderChain) ValidateDexonHeaderChain(chain []*types.HeaderWithGovState,
    gov dexcon.GovernanceStateFetcher,
    verifierCache *dexCore.TSigVerifierCache, validator Validator) (int, error) {
    // Do a sanity check that the provided chain is actually ordered and linked
    for i := 1; i < len(chain); i++ {
        if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
            // Chain broke ancestry, log a message (programming error) and skip insertion
            log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
                "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())

            return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].Number,
                chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
        }
    }

    // If the last TSig pass the verification, we don't need to verify others.
    cache := newHeaderVerifierCache(verifierCache, gov)
    verifyTSig := false
    if err := hc.verifyDexonHeader(chain[len(chain)-1].Header, gov, cache, true); err != nil {
        verifyTSig = true
    }
    // Iterate over the headers and ensure they all check out
    for i, header := range chain {
        // If the chain is terminating, stop processing blocks
        if hc.procInterrupt() {
            log.Debug("Premature abort during headers verification")
            return 0, errors.New("aborted")
        }

        if i == 0 {
            log.Debug("validate header chain", "parent", header.ParentHash.String(), "number", header.Number.Uint64()-1)
            if parent := hc.GetHeader(header.ParentHash, header.Number.Uint64()-1); parent == nil {
                return 0, consensus.ErrUnknownAncestor
            }
        }

        if err := hc.verifyDexonHeader(header.Header, gov, cache, verifyTSig); err != nil {
            return i, err
        }

        // Verify witness
        var coreBlock coreTypes.Block
        if err := rlp.DecodeBytes(header.DexconMeta, &coreBlock); err != nil {
            return i, err
        }

        if !coreBlock.IsEmpty() {
            var witnessBlockHash common.Hash
            if err := rlp.DecodeBytes(coreBlock.Witness.Data, &witnessBlockHash); err != nil {
                log.Error("decode witness data fail", "err", err)
                return i, err
            }

            index := int64(coreBlock.Witness.Height) - int64(chain[0].Number.Uint64())
            if index < 0 {
                if err := validator.ValidateWitnessData(
                    coreBlock.Witness.Height, witnessBlockHash); err != nil {
                    return i, err
                }
            } else {
                if witnessBlockHash != chain[index].Hash() {
                    return i, consensus.ErrWitnessMismatch
                }
            }
        }
    }
    return 0, nil
}

func (hc *HeaderChain) VerifyDexonHeader(header *types.Header,
    gov dexcon.GovernanceStateFetcher,
    verifierCache *dexCore.TSigVerifierCache, validator Validator) error {

    if parent := hc.GetHeader(header.ParentHash, header.Number.Uint64()-1); parent == nil {
        return consensus.ErrUnknownAncestor
    }
    cache := newHeaderVerifierCache(verifierCache, gov)
    if err := hc.verifyDexonHeader(header, gov, cache, true); err != nil {
        return err
    }

    // Verify witness
    var coreBlock coreTypes.Block
    if err := rlp.DecodeBytes(header.DexconMeta, &coreBlock); err != nil {
        return err
    }

    if !coreBlock.IsEmpty() {
        var witnessBlockHash common.Hash
        if err := rlp.DecodeBytes(coreBlock.Witness.Data, &witnessBlockHash); err != nil {
            log.Error("decode witness data fail", "err", err)
            return err
        }

        if err := validator.ValidateWitnessData(
            coreBlock.Witness.Height, witnessBlockHash); err != nil {
            return err
        }
    }
    return nil
}

func (hc *HeaderChain) verifyDexonHeader(header *types.Header,
    gov dexcon.GovernanceStateFetcher,
    cache *headerVerifierCache, verifyTSig bool) error {

    // If the header is a banned one, straight out abort
    if BadHashes[header.Hash()] {
        return ErrBlacklistedHash
    }

    // Difficulty should always be 1.
    if header.Difficulty.Cmp(big.NewInt(1)) != 0 {
        return fmt.Errorf("difficulty should be 1")
    }

    // Verify fields that should be same as dexcon meta.
    var coreBlock coreTypes.Block
    if err := rlp.DecodeBytes(header.DexconMeta, &coreBlock); err != nil {
        return fmt.Errorf("decode dexcon meta fail, number=%d, err=%v",
            header.Number.Uint64(), err)
    }

    if verifyTSig {
        if err := hc.verifyTSig(&coreBlock, cache.verifierCache); err != nil {
            log.Debug("verify header sig fail, number=%d, err=%v",
                header.Number.Uint64(), err)
        }
    }

    if coreBlock.IsEmpty() {
        if header.Coinbase != (common.Address{}) {
            return fmt.Errorf("coinbase should be nil for empty block")
        }
    } else {
        owner, err := cache.getNodeOwnerByID(header.Round, coreBlock.ProposerID)
        if err != nil {
            return err
        }

        if header.Coinbase != owner {
            return fmt.Errorf("coinbase mismatch")
        }
    }

    if header.Time != uint64(coreBlock.Timestamp.UnixNano()/1000000) {
        return fmt.Errorf("timestamp mismatch")
    }

    if header.Number.Uint64() != coreBlock.Position.Height {
        return fmt.Errorf("height mismatch")
    }

    if !reflect.DeepEqual(header.Randomness, coreBlock.Randomness) {
        return fmt.Errorf("randomness mismatch")
    }

    if header.Round != coreBlock.Position.Round {
        return fmt.Errorf("round mismatch")
    }

    config := cache.configuration(header.Round)
    if header.GasLimit != config.BlockGasLimit {
        return fmt.Errorf("block gas limit mismatch")
    }
    return nil
}

func (hc *HeaderChain) verifyTSig(coreBlock *coreTypes.Block,
    verifierCache *dexCore.TSigVerifierCache) error {

    round := coreBlock.Position.Round
    randomness := coreBlock.Randomness

    if round == 0 {
        return nil
    }

    // Verify threshold signature
    v, ok, err := verifierCache.UpdateAndGet(round)
    if err != nil {
        panic(err)
    }

    if !ok {
        panic(fmt.Errorf("DKG of round %d is not finished", round))
    }

    if !v.VerifySignature(coreBlock.Hash, coreCrypto.Signature{
        Type:      "bls",
        Signature: randomness}) {
        return fmt.Errorf("signature invalid")
    }
    return nil
}

// InsertDexonHeaderChain attempts to insert the given header chain in to the local
// chain, possibly creating a reorg. If an error is returned, it will return the
// index number of the failing header as well an error describing what went wrong.
//
// The verify parameter can be used to fine tune whether nonce verification
// should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verfy nonces, as well as
// because nonces can be verified sparsely, not needing to check each.
func (hc *HeaderChain) InsertDexonHeaderChain(chain []*types.HeaderWithGovState, writeHeader Wh2Callback, start time.Time) (int, error) {
    // Collect some import statistics to report on
    stats := struct{ processed, ignored int }{}
    // All headers passed verification, import them into the database
    for i, header := range chain {
        // Short circuit insertion if shutting down
        if hc.procInterrupt() {
            log.Debug("Premature abort during headers import")
            return i, errors.New("aborted")
        }
        // If the header's already known, skip it, otherwise store
        if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
            stats.ignored++
            continue
        }
        if err := writeHeader(header); err != nil {
            return i, err
        }
        stats.processed++
    }
    // Report some public statistics so the user has a clue what's going on
    last := chain[len(chain)-1]
    log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
        "number", last.Number, "hash", last.Hash(), "ignored", stats.ignored)

    return 0, nil
}

// GetBlockHashesFromHash retrieves a number of block hashes starting at a given
// hash, fetching towards the genesis block.
func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
    // Get the origin header from which to fetch
    header := hc.GetHeaderByHash(hash)
    if header == nil {
        return nil
    }
    // Iterate the headers until enough is collected or the genesis reached
    chain := make([]common.Hash, 0, max)
    for i := uint64(0); i < max; i++ {
        next := header.ParentHash
        if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
            break
        }
        chain = append(chain, next)
        if header.Number.Sign() == 0 {
            break
        }
    }
    return chain
}

// GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
// a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
// number of blocks to be individually checked before we reach the canonical chain.
//
// Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
    if ancestor > number {
        return common.Hash{}, 0
    }
    if ancestor == 1 {
        // in this case it is cheaper to just read the header
        if header := hc.GetHeader(hash, number); header != nil {
            return header.ParentHash, number - 1
        } else {
            return common.Hash{}, 0
        }
    }
    for ancestor != 0 {
        if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
            number -= ancestor
            return rawdb.ReadCanonicalHash(hc.chainDb, number), number
        }
        if *maxNonCanonical == 0 {
            return common.Hash{}, 0
        }
        *maxNonCanonical--
        ancestor--
        header := hc.GetHeader(hash, number)
        if header == nil {
            return common.Hash{}, 0
        }
        hash = header.ParentHash
        number--
    }
    return hash, number
}

// GetTd retrieves a block's total difficulty in the canonical chain from the
// database by hash and number, caching it if found.
func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
    // Short circuit if the td's already in the cache, retrieve otherwise
    if cached, ok := hc.tdCache.Get(hash); ok {
        return cached.(*big.Int)
    }
    td := rawdb.ReadTd(hc.chainDb, hash, number)
    if td == nil {
        return nil
    }
    // Cache the found body for next time and return
    hc.tdCache.Add(hash, td)
    return td
}

// GetTdByHash retrieves a block's total difficulty in the canonical chain from the
// database by hash, caching it if found.
func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
    number := hc.GetBlockNumber(hash)
    if number == nil {
        return nil
    }
    return hc.GetTd(hash, *number)
}

// WriteTd stores a block's total difficulty into the database, also caching it
// along the way.
func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
    rawdb.WriteTd(hc.chainDb, hash, number, td)
    hc.tdCache.Add(hash, new(big.Int).Set(td))
    return nil
}

// GetHeader retrieves a block header from the database by hash and number,
// caching it if found.
func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
    // Short circuit if the header's already in the cache, retrieve otherwise
    if header, ok := hc.headerCache.Get(hash); ok {
        return header.(*types.Header)
    }
    header := rawdb.ReadHeader(hc.chainDb, hash, number)
    if header == nil {
        return nil
    }
    // Cache the found header for next time and return
    hc.headerCache.Add(hash, header)
    return header
}

// GetHeaderByHash retrieves a block header from the database by hash, caching it if
// found.
func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
    number := hc.GetBlockNumber(hash)
    if number == nil {
        return nil
    }
    return hc.GetHeader(hash, *number)
}

// HasHeader checks if a block header is present in the database or not.
func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
    if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
        return true
    }
    return rawdb.HasHeader(hc.chainDb, hash, number)
}

// GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found.
func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
    hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
    if hash == (common.Hash{}) {
        return nil
    }
    return hc.GetHeader(hash, number)
}

// CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache.
func (hc *HeaderChain) CurrentHeader() *types.Header {
    return hc.currentHeader.Load().(*types.Header)
}

// SetCurrentHeader sets the current head header of the canonical chain.
func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
    rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())

    hc.currentHeader.Store(head)
    hc.currentHeaderHash = head.Hash()
}

// DeleteCallback is a callback function that is called by SetHead before
// each header is deleted.
type DeleteCallback func(rawdb.DatabaseDeleter, common.Hash, uint64)

// SetHead rewinds the local chain to a new head. Everything above the new head
// will be deleted and the new one set.
func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
    height := uint64(0)

    if hdr := hc.CurrentHeader(); hdr != nil {
        height = hdr.Number.Uint64()
    }
    batch := hc.chainDb.NewBatch()
    for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
        hash := hdr.Hash()
        num := hdr.Number.Uint64()
        if delFn != nil {
            delFn(batch, hash, num)
        }
        rawdb.DeleteHeader(batch, hash, num)
        rawdb.DeleteTd(batch, hash, num)

        hc.currentHeader.Store(hc.GetHeader(hdr.ParentHash, hdr.Number.Uint64()-1))
    }
    // Roll back the canonical chain numbering
    for i := height; i > head; i-- {
        rawdb.DeleteCanonicalHash(batch, i)
    }
    batch.Write()

    // Clear out any stale content from the caches
    hc.headerCache.Purge()
    hc.tdCache.Purge()
    hc.numberCache.Purge()

    if hc.CurrentHeader() == nil {
        hc.currentHeader.Store(hc.genesisHeader)
    }
    hc.currentHeaderHash = hc.CurrentHeader().Hash()

    rawdb.WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash)
}

// SetGenesis sets a new genesis block header for the chain
func (hc *HeaderChain) SetGenesis(head *types.Header) {
    hc.genesisHeader = head
}

// Config retrieves the header chain's chain configuration.
func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }

// Engine retrieves the header chain's consensus engine.
func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }

// GetBlock implements consensus.ChainReader, and returns nil for every input as
// a header chain does not have blocks available for retrieval.
func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
    return nil
}