-
Notifications
You must be signed in to change notification settings - Fork 13
/
setup.go
227 lines (184 loc) · 5.64 KB
/
setup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// 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"
"encoding/json"
"fmt"
"github.com/bitmark-inc/bitmarkd/background"
"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"
"github.com/bitmark-inc/bitmarkd/transactionrecord"
"github.com/bitmark-inc/logger"
"sync"
)
// globals for background proccess
type blockData struct {
sync.RWMutex // to allow locking
log *logger.L
height uint64 // this is the current block Height
previousBlock blockdigest.Digest // and its digest
blk blockstore // for sequencing block storage
// for background
background *background.T
// set once during initialise
initialised bool
}
// global data
var globalData blockData
// setup the current block data
func Initialise() error {
globalData.Lock()
defer globalData.Unlock()
// no need to start if already started
if globalData.initialised {
return fault.ErrAlreadyInitialised
}
log := logger.New("block")
if nil == log {
return fault.ErrInvalidLoggerChannel
}
globalData.log = log
log.Info("starting…")
// check storage is initialised
if nil == storage.Pool.Blocks {
log.Critical("storage pool is not initialise")
return fault.ErrNotInitialised
}
// initialise block height and initial previous block digest
globalData.height = genesis.BlockNumber
globalData.previousBlock = genesis.LiveGenesisDigest
if mode.IsTesting() {
globalData.previousBlock = genesis.TestGenesisDigest
}
log.Infof("block height: %d", globalData.height)
log.Infof("previous block: %v", globalData.previousBlock)
// fill ring with default values
if err := fillRingBuffer(log); nil != err {
return err
}
// initialise background tasks
if err := globalData.blk.initialise(); nil != err {
return err
}
// all data initialised
globalData.initialised = true
// start background processes
log.Info("start background…")
processes := background.Processes{
&globalData.blk,
}
globalData.background = background.Start(processes, log)
return nil
}
// shudown the block system
func Finalise() error {
globalData.Lock()
defer globalData.Unlock()
if !globalData.initialised {
return fault.ErrNotInitialised
}
globalData.log.Info("shutting down…")
globalData.log.Flush()
// finally...
globalData.initialised = false
globalData.log.Info("finished")
globalData.log.Flush()
return nil
}
// must hold lock to call this
func fillRingBuffer(log *logger.L) error {
// reset ring to default
blockring.Clear(log)
// detect if any blocks on file
if last, ok := storage.Pool.Blocks.LastElement(); ok {
// get highest block
packedHeader := blockrecord.PackedHeader(last.Value[:blockrecord.TotalBlockSize])
header, err := packedHeader.Unpack()
if nil != err {
log.Criticalf("failed to unpack block: %d from storage error: %v", binary.BigEndian.Uint64(last.Key), err)
return err
}
globalData.previousBlock = packedHeader.Digest()
globalData.height = header.Number // highest block number in database
log.Infof("highest block from storage: %d", globalData.height)
// determine the start point for fetching last few blocks
n := genesis.BlockNumber + 1 // first real block (genesis block is not in db)
if globalData.height > blockring.Size+1 {
n = globalData.height - blockring.Size + 1
}
if n <= genesis.BlockNumber { // check just in case above calculation is wrong
log.Criticalf("value of n < 2: %d", n)
return fault.ErrInitialisationFailed
}
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, n)
c := storage.Pool.Blocks.NewFetchCursor()
c.Seek(key)
items, err := c.Fetch(blockring.Size)
if nil != err {
return err
}
log.Infof("populate ring buffer staring from block: %d", n)
log.Tracef("items: %x", items)
for i, item := range items {
packedHeader := blockrecord.PackedHeader(item.Value[:blockrecord.TotalBlockSize])
digest := packedHeader.Digest()
header, err := packedHeader.Unpack()
if nil != err {
log.Criticalf("failed to unpack block: %d from storage error: %v", binary.BigEndian.Uint64(last.Key), err)
return err
}
log.Infof("ring[%d] from block: %d", i, header.Number)
// consistency check
if n != header.Number {
log.Criticalf("number mismatch actual: %d expected: %d", header.Number, n)
return fault.ErrInitialisationFailed
}
n += 1
blockring.Put(header.Number, digest, item.Value)
log.Tracec(func() string {
// + begin debugging
//log.Infof("header: %#v", header)
data := item.Value[blockrecord.TotalBlockSize:]
txs := make([]interface{}, header.TransactionCount)
loop:
for i := 1; true; i += 1 {
transaction, n, err := transactionrecord.Packed(data).Unpack()
if nil != err {
//log.Errorf("tx[%d]: error: %v", i, err)
//return err
return fmt.Sprintf("tx[%d]: error: %v", i, err)
}
txs[i-1] = transaction
data = data[n:]
if 0 == len(data) {
break loop
}
}
s := struct {
Header *blockrecord.Header
Transactions []interface{}
}{
Header: header,
Transactions: txs,
}
jsonData, err := json.MarshalIndent(s, "", " ")
if nil != err {
//return err
return fmt.Sprintf("JSON marshal error: %v", err)
}
//log.Infof("block: %s", jsonData)
return fmt.Sprintf("block: %s", jsonData)
// - end debugging
})
}
}
return nil
}