/
blockchain.go
executable file
·357 lines (313 loc) · 10.6 KB
/
blockchain.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
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
/*
Copyright IBM Corp. 2016 All Rights Reserved.
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 ledger
import (
"bytes"
"encoding/binary"
"strconv"
"fmt"
"github.com/TarantulaTechnology/fabric/core/db"
"github.com/TarantulaTechnology/fabric/core/util"
"github.com/TarantulaTechnology/fabric/protos"
"github.com/tecbot/gorocksdb"
"golang.org/x/net/context"
)
// Blockchain holds basic information in memory. Operations on Blockchain are not thread-safe
// TODO synchronize access to in-memory variables
type blockchain struct {
size uint64
previousBlockHash []byte
indexer blockchainIndexer
lastProcessedBlock *lastProcessedBlock
}
type lastProcessedBlock struct {
block *protos.Block
blockNumber uint64
blockHash []byte
}
var indexBlockDataSynchronously = true
func newBlockchain() (*blockchain, error) {
size, err := fetchBlockchainSizeFromDB()
if err != nil {
return nil, err
}
blockchain := &blockchain{0, nil, nil, nil}
blockchain.size = size
if size > 0 {
previousBlock, err := fetchBlockFromDB(size - 1)
if err != nil {
return nil, err
}
previousBlockHash, err := previousBlock.GetHash()
if err != nil {
return nil, err
}
blockchain.previousBlockHash = previousBlockHash
}
err = blockchain.startIndexer()
if err != nil {
return nil, err
}
return blockchain, nil
}
func (blockchain *blockchain) startIndexer() (err error) {
if indexBlockDataSynchronously {
blockchain.indexer = newBlockchainIndexerSync()
} else {
blockchain.indexer = newBlockchainIndexerAsync()
}
err = blockchain.indexer.start(blockchain)
return
}
// getLastBlock get last block in blockchain
func (blockchain *blockchain) getLastBlock() (*protos.Block, error) {
if blockchain.size == 0 {
return nil, nil
}
return blockchain.getBlock(blockchain.size - 1)
}
// getSize number of blocks in blockchain
func (blockchain *blockchain) getSize() uint64 {
return blockchain.size
}
// getBlock get block at arbitrary height in block chain
func (blockchain *blockchain) getBlock(blockNumber uint64) (*protos.Block, error) {
return fetchBlockFromDB(blockNumber)
}
// getBlockByHash get block by block hash
func (blockchain *blockchain) getBlockByHash(blockHash []byte) (*protos.Block, error) {
blockNumber, err := blockchain.indexer.fetchBlockNumberByBlockHash(blockHash)
if err != nil {
return nil, err
}
return blockchain.getBlock(blockNumber)
}
func (blockchain *blockchain) getTransactionByUUID(txUUID string) (*protos.Transaction, error) {
blockNumber, txIndex, err := blockchain.indexer.fetchTransactionIndexByUUID(txUUID)
if err != nil {
return nil, err
}
block, err := blockchain.getBlock(blockNumber)
if err != nil {
return nil, err
}
transaction := block.GetTransactions()[txIndex]
return transaction, nil
}
func (blockchain *blockchain) getTransactionResultByUUID(txUUID string) (*protos.TransactionResult, error) {
blockNumber, txIndex, err := blockchain.indexer.fetchTransactionIndexByUUID(txUUID)
if err != nil {
return nil, err
}
block, err := blockchain.getBlock(blockNumber)
if err != nil {
return nil, err
}
nonHashData := block.GetNonHashData()
if nonHashData == nil {
return nil, fmt.Errorf("Error getting TransactionResult for txUUID = %s, nonHashData was nil", txUUID)
}
transactionResults := nonHashData.GetTransactionResults()
if transactionResults == nil {
return nil, fmt.Errorf("Error getting TransactionResult for txUUID = %s, GetTransactionResults returned nil", txUUID)
}
if txIndex > uint64(len(transactionResults))-1 {
return nil, fmt.Errorf("Error getting TransactionResult for txUUID = %s, txIndex (%d) out of range in TransactionResults with length = %d", txUUID, txIndex, len(transactionResults))
}
txResult := transactionResults[txIndex]
return txResult, nil
}
// getTransactions get all transactions in a block identified by block number
func (blockchain *blockchain) getTransactions(blockNumber uint64) ([]*protos.Transaction, error) {
block, err := blockchain.getBlock(blockNumber)
if err != nil {
return nil, err
}
return block.GetTransactions(), nil
}
// getTransactionsByBlockHash get all transactions in a block identified by block hash
func (blockchain *blockchain) getTransactionsByBlockHash(blockHash []byte) ([]*protos.Transaction, error) {
block, err := blockchain.getBlockByHash(blockHash)
if err != nil {
return nil, err
}
return block.GetTransactions(), nil
}
// getTransaction get a transaction identified by blocknumber and index within the block
func (blockchain *blockchain) getTransaction(blockNumber uint64, txIndex uint64) (*protos.Transaction, error) {
block, err := blockchain.getBlock(blockNumber)
if err != nil {
return nil, err
}
return block.GetTransactions()[txIndex], nil
}
// getTransactionByBlockHash get a transaction identified by blockhash and index within the block
func (blockchain *blockchain) getTransactionByBlockHash(blockHash []byte, txIndex uint64) (*protos.Transaction, error) {
block, err := blockchain.getBlockByHash(blockHash)
if err != nil {
return nil, err
}
return block.GetTransactions()[txIndex], nil
}
func (blockchain *blockchain) getBlockchainInfo() (*protos.BlockchainInfo, error) {
if blockchain.getSize() == 0 {
return &protos.BlockchainInfo{Height: 0}, nil
}
lastBlock, err := blockchain.getLastBlock()
if err != nil {
return nil, err
}
info := blockchain.getBlockchainInfoForBlock(blockchain.getSize(), lastBlock)
return info, nil
}
func (blockchain *blockchain) getBlockchainInfoForBlock(height uint64, block *protos.Block) *protos.BlockchainInfo {
hash, _ := block.GetHash()
info := &protos.BlockchainInfo{
Height: height,
CurrentBlockHash: hash,
PreviousBlockHash: block.PreviousBlockHash}
return info
}
func (blockchain *blockchain) buildBlock(block *protos.Block, stateHash []byte) *protos.Block {
block.SetPreviousBlockHash(blockchain.previousBlockHash)
block.StateHash = stateHash
return block
}
func (blockchain *blockchain) addPersistenceChangesForNewBlock(ctx context.Context,
block *protos.Block, stateHash []byte, writeBatch *gorocksdb.WriteBatch) (uint64, error) {
block = blockchain.buildBlock(block, stateHash)
if block.NonHashData == nil {
block.NonHashData = &protos.NonHashData{LocalLedgerCommitTimestamp: util.CreateUtcTimestamp()}
} else {
block.NonHashData.LocalLedgerCommitTimestamp = util.CreateUtcTimestamp()
}
blockNumber := blockchain.size
blockHash, err := block.GetHash()
if err != nil {
return 0, err
}
blockBytes, blockBytesErr := block.Bytes()
if blockBytesErr != nil {
return 0, blockBytesErr
}
writeBatch.PutCF(db.GetDBHandle().BlockchainCF, encodeBlockNumberDBKey(blockNumber), blockBytes)
writeBatch.PutCF(db.GetDBHandle().BlockchainCF, blockCountKey, encodeUint64(blockNumber+1))
if blockchain.indexer.isSynchronous() {
blockchain.indexer.createIndexesSync(block, blockNumber, blockHash, writeBatch)
}
blockchain.lastProcessedBlock = &lastProcessedBlock{block, blockNumber, blockHash}
return blockNumber, nil
}
func (blockchain *blockchain) blockPersistenceStatus(success bool) {
if success {
blockchain.size++
blockchain.previousBlockHash = blockchain.lastProcessedBlock.blockHash
if !blockchain.indexer.isSynchronous() {
blockchain.indexer.createIndexesAsync(blockchain.lastProcessedBlock.block,
blockchain.lastProcessedBlock.blockNumber, blockchain.lastProcessedBlock.blockHash)
}
}
blockchain.lastProcessedBlock = nil
}
func (blockchain *blockchain) persistRawBlock(block *protos.Block, blockNumber uint64) error {
blockBytes, blockBytesErr := block.Bytes()
if blockBytesErr != nil {
return blockBytesErr
}
writeBatch := gorocksdb.NewWriteBatch()
defer writeBatch.Destroy()
writeBatch.PutCF(db.GetDBHandle().BlockchainCF, encodeBlockNumberDBKey(blockNumber), blockBytes)
blockHash, err := block.GetHash()
if err != nil {
return err
}
// Need to check as we suport out of order blocks in cases such as block/state synchronization. This is
// really blockchain height, not size.
if blockchain.getSize() < blockNumber+1 {
sizeBytes := encodeUint64(blockNumber + 1)
writeBatch.PutCF(db.GetDBHandle().BlockchainCF, blockCountKey, sizeBytes)
blockchain.size = blockNumber + 1
blockchain.previousBlockHash = blockHash
}
if blockchain.indexer.isSynchronous() {
blockchain.indexer.createIndexesSync(block, blockNumber, blockHash, writeBatch)
}
opt := gorocksdb.NewDefaultWriteOptions()
defer opt.Destroy()
err = db.GetDBHandle().DB.Write(opt, writeBatch)
if err != nil {
return err
}
return nil
}
func fetchBlockFromDB(blockNumber uint64) (*protos.Block, error) {
blockBytes, err := db.GetDBHandle().GetFromBlockchainCF(encodeBlockNumberDBKey(blockNumber))
if err != nil {
return nil, err
}
if blockBytes == nil {
return nil, nil
}
return protos.UnmarshallBlock(blockBytes)
}
func fetchBlockchainSizeFromDB() (uint64, error) {
bytes, err := db.GetDBHandle().GetFromBlockchainCF(blockCountKey)
if err != nil {
return 0, err
}
if bytes == nil {
return 0, nil
}
return decodeToUint64(bytes), nil
}
func fetchBlockchainSizeFromSnapshot(snapshot *gorocksdb.Snapshot) (uint64, error) {
blockNumberBytes, err := db.GetDBHandle().GetFromBlockchainCFSnapshot(snapshot, blockCountKey)
if err != nil {
return 0, err
}
var blockNumber uint64
if blockNumberBytes != nil {
blockNumber = decodeToUint64(blockNumberBytes)
}
return blockNumber, nil
}
var blockCountKey = []byte("blockCount")
func encodeBlockNumberDBKey(blockNumber uint64) []byte {
return encodeUint64(blockNumber)
}
func encodeUint64(number uint64) []byte {
bytes := make([]byte, 8)
binary.BigEndian.PutUint64(bytes, number)
return bytes
}
func decodeToUint64(bytes []byte) uint64 {
return binary.BigEndian.Uint64(bytes)
}
func (blockchain *blockchain) String() string {
var buffer bytes.Buffer
size := blockchain.getSize()
for i := uint64(0); i < size; i++ {
block, blockErr := blockchain.getBlock(i)
if blockErr != nil {
return ""
}
buffer.WriteString("\n----------<block #")
buffer.WriteString(strconv.FormatUint(i, 10))
buffer.WriteString(">----------\n")
buffer.WriteString(block.String())
buffer.WriteString("\n----------<\\block #")
buffer.WriteString(strconv.FormatUint(i, 10))
buffer.WriteString(">----------\n")
}
return buffer.String()
}