-
Notifications
You must be signed in to change notification settings - Fork 13
/
get.go
63 lines (55 loc) · 1.71 KB
/
get.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright (c) 2014-2017 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package block
import (
"encoding/binary"
"github.com/bitmark-inc/bitmarkd/blockdigest"
"github.com/bitmark-inc/bitmarkd/blockrecord"
"github.com/bitmark-inc/bitmarkd/blockring"
"github.com/bitmark-inc/bitmarkd/fault"
"github.com/bitmark-inc/bitmarkd/genesis"
"github.com/bitmark-inc/bitmarkd/mode"
"github.com/bitmark-inc/bitmarkd/storage"
)
// get block data for initialising a new block
// returns: previous block digest and the number for the new block
func Get() (blockdigest.Digest, uint64) {
globalData.Lock()
defer globalData.Unlock()
nextBlockNumber := globalData.height + 1
return globalData.previousBlock, nextBlockNumber
}
// get the current height
func GetHeight() uint64 {
globalData.Lock()
height := globalData.height
globalData.Unlock()
return height
}
func DigestForBlock(number uint64) (blockdigest.Digest, error) {
globalData.Lock()
defer globalData.Unlock()
// valid block number
if number <= genesis.BlockNumber {
if mode.IsTesting() {
return genesis.TestGenesisDigest, nil
}
return genesis.LiveGenesisDigest, nil
}
// check if in the cache
if number > genesis.BlockNumber && number <= globalData.height {
d := blockring.DigestForBlock(number)
if nil != d {
return *d, nil
}
}
// no cache, fetch block and compute digest
n := make([]byte, 8)
binary.BigEndian.PutUint64(n, number)
packed := storage.Pool.Blocks.Get(n) // ***** FIX THIS: possible optimisation is to store the block hashes in a separate index
if nil == packed {
return blockdigest.Digest{}, fault.ErrBlockNotFound
}
return blockrecord.PackedHeader(packed).Digest(), nil
}