This repository has been archived by the owner on Nov 10, 2022. It is now read-only.
/
blockchain.go
58 lines (50 loc) · 1.59 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
package lazyledger
import (
"bytes"
)
// Blockchain is a chain of blocks.
// This is a prototype for testing purposes and thus does not support re-orgs, and there is no network stack.
type Blockchain struct {
blockStore BlockStore
headBlock Block
applications []*Application
}
// NewBlockchain returns a new blockchain.
func NewBlockchain(blockStore BlockStore) *Blockchain {
return &Blockchain{
blockStore: blockStore,
}
}
// ProcessBlock processes a new block.
func (b *Blockchain) ProcessBlock(block Block) {
b.blockStore.Put(block.Digest(), block)
if b.headBlock == nil || bytes.Compare(block.PrevHash(), b.headBlock.Digest()) == 0 {
b.headBlock = block
b.processCallbacks(block, true)
} else {
b.processCallbacks(block, false)
}
}
func (b *Blockchain) Block(digest []byte) (Block, error) {
block, err := b.blockStore.Get(digest)
if err != nil {
return nil, err
}
return block, nil
}
// RegisterApplication registers an application instance to call when new relevant messages arrive.
func (b *Blockchain) RegisterApplication(application *Application) {
b.applications = append(b.applications, application)
}
func (b *Blockchain) processCallbacks(block Block, isHead bool) {
for _, application := range b.applications {
if isHead {
(*application).SetBlockHead(block.Digest())
}
for _, message := range block.Messages() {
if message.Namespace() == (*application).Namespace() {
(*application).ProcessMessage(message)
}
}
}
}