-
Notifications
You must be signed in to change notification settings - Fork 34
/
block.go
169 lines (152 loc) · 5.73 KB
/
block.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
package protocol
import (
"context"
"encoding/hex"
"sync/atomic"
"time"
"github.com/chain/txvm/crypto/ed25519"
"github.com/chain/txvm/errors"
"github.com/chain/txvm/log"
"github.com/chain/txvm/protocol/bc"
"github.com/chain/txvm/protocol/patricia"
"github.com/chain/txvm/protocol/state"
)
var (
// ErrBadContractsRoot is returned when the computed contracts merkle root
// disagrees with the one declared in a block header.
ErrBadContractsRoot = errors.New("invalid contracts merkle root")
// ErrBadNoncesRoot is returned when the computed nonces merkle root
// disagrees with the one declared in a block header.
ErrBadNoncesRoot = errors.New("invalid nonces merkle root")
)
// GetBlock returns the block at the given height, if there is one,
// otherwise it returns an error.
func (c *Chain) GetBlock(ctx context.Context, height uint64) (*bc.Block, error) {
return c.store.GetBlock(ctx, height)
}
// GenerateBlock generates a valid, but unsigned, candidate block from
// the current pending transaction pool. It returns the new block and
// a snapshot of what the state snapshot is if the block is applied.
//
// After generating the block, the pending transaction pool will be
// empty.
func (c *Chain) GenerateBlock(ctx context.Context, timestampMS uint64, txs []*bc.CommitmentsTx) (*bc.UnsignedBlock, *state.Snapshot, error) {
err := c.bb.Start(c.State(), timestampMS)
if err != nil {
return nil, nil, err
}
for _, tx := range txs {
err := c.bb.AddTx(tx)
if err != nil {
log.Printkv(ctx, "event", "invalid tx", "error", err, "tx", hex.EncodeToString(tx.Tx.Program))
}
}
return c.bb.Build()
}
// CommitAppliedBlock takes a block, commits it to persistent storage and
// sets c's state. Unlike CommitBlock, it accepts an already applied
// snapshot. CommitAppliedBlock is idempotent.
func (c *Chain) CommitAppliedBlock(ctx context.Context, block *bc.Block, snapshot *state.Snapshot) error {
err := c.store.SaveBlock(ctx, block)
if err != nil {
return errors.Wrap(err, "storing block")
}
curState := c.State()
// CommitAppliedBlock needs to be idempotent. If block's height is less than or
// equal to c's current block, then it was already applied. Because
// SaveBlock didn't error with a conflict, we know it's not a different
// block at the same height.
if block.Height <= curState.Height() {
return nil
}
return c.finalizeCommitState(ctx, snapshot)
}
// CommitBlock takes a block, commits it to persistent storage and applies
// it to c. CommitBlock is idempotent. A duplicate call with a previously
// committed block will succeed.
func (c *Chain) CommitBlock(ctx context.Context, block *bc.Block) error {
err := c.store.SaveBlock(ctx, block)
if err != nil {
return errors.Wrap(err, "storing block")
}
curSnapshot := c.State()
// CommitBlock needs to be idempotent. If block's height is less than or
// equal to c's current block, then it was already applied. Because
// SaveBlock didn't error with a conflict, we know it's not a different
// block at the same height.
if block.Height <= curSnapshot.Height() {
return nil
}
snapshot := state.Copy(curSnapshot)
err = snapshot.ApplyBlock(block.UnsignedBlock)
if err != nil {
return err
}
if block.ContractsRoot.Byte32() != snapshot.ContractsTree.RootHash() {
return ErrBadContractsRoot
}
if block.NoncesRoot.Byte32() != snapshot.NonceTree.RootHash() {
return ErrBadNoncesRoot
}
return c.finalizeCommitState(ctx, snapshot)
}
func (c *Chain) finalizeCommitState(ctx context.Context, snapshot *state.Snapshot) error {
// Save the blockchain state tree snapshot to persistent storage
// if we haven't done it recently.
lastQueuedHeight := atomic.LoadUint64(&c.lastQueuedSnapshotHeight)
if lastQueuedHeight+c.blocksPerSnapshot <= snapshot.Height() {
c.queueSnapshot(ctx, snapshot)
}
// setState will update c's current block and snapshot, or no-op
// if another goroutine has already updated the state.
c.setState(snapshot)
// The below FinalizeHeight will notify other cored processes that
// the a new block has been committed. It may result in a duplicate
// attempt to update c's height but setState and setHeight safely
// ignore duplicate heights.
err := c.store.FinalizeHeight(ctx, snapshot.Height())
return errors.Wrap(err, "finalizing block")
}
func (c *Chain) queueSnapshot(ctx context.Context, s *state.Snapshot) {
// Non-blockingly queue the snapshot for storage.
select {
case c.pendingSnapshots <- s:
atomic.StoreUint64(&c.lastQueuedSnapshotHeight, s.Height())
default:
// Skip it; saving snapshots is taking longer than the snapshotting period.
lastQueuedHeight := atomic.LoadUint64(&c.lastQueuedSnapshotHeight)
log.Printf(ctx, "snapshot storage is taking too long; %d blocks since last snapshot queued",
s.Height()-lastQueuedHeight)
}
}
// NewInitialBlock produces the first block for a new blockchain,
// using the given pubkeys and quorum for its NextPredicate.
func NewInitialBlock(pubkeys []ed25519.PublicKey, quorum int, timestamp time.Time) (*bc.Block, error) {
// TODO(kr): move this into a lower-level package (e.g. chain/protocol/bc)
// so that other packages (e.g. chain/protocol/validation) unit tests can
// call this function.
root := bc.TxMerkleRoot(nil) // calculate the zero value of the tx merkle root
patRoot := bc.NewHash(new(patricia.Tree).RootHash())
var pkBytes [][]byte
for _, pk := range pubkeys {
pkBytes = append(pkBytes, pk)
}
b := &bc.Block{
UnsignedBlock: &bc.UnsignedBlock{
BlockHeader: &bc.BlockHeader{
Version: 3,
Height: 1,
TimestampMs: bc.Millis(timestamp),
TransactionsRoot: &root,
ContractsRoot: &patRoot,
NoncesRoot: &patRoot,
NextPredicate: &bc.Predicate{
Version: 1,
Quorum: int32(quorum),
Pubkeys: pkBytes,
},
},
},
}
return b, nil
}