8 "github.com/golang/protobuf/proto"
9 "github.com/vapor/blockchain/txbuilder"
10 "github.com/vapor/consensus"
11 "github.com/vapor/database"
12 dbm "github.com/vapor/database/leveldb"
13 "github.com/vapor/database/storage"
14 "github.com/vapor/protocol"
15 "github.com/vapor/protocol/bc"
16 "github.com/vapor/protocol/bc/types"
17 "github.com/vapor/protocol/vm"
20 const utxoPrefix = "UT:"
22 type chainTestContext struct {
28 func (ctx *chainTestContext) validateStatus(block *types.Block) error {
29 // validate in mainchain
30 if !ctx.Chain.InMainChain(block.Hash()) {
31 return fmt.Errorf("block %d is not in mainchain", block.Height)
34 // validate chain status and saved block
35 bestBlockHeader := ctx.Chain.BestBlockHeader()
36 chainBlock, err := ctx.Chain.GetBlockByHeight(block.Height)
41 blockHash := block.Hash()
42 if bestBlockHeader.Hash() != blockHash || chainBlock.Hash() != blockHash {
43 return fmt.Errorf("chain status error")
47 txStatus, err := ctx.Chain.GetTransactionStatus(&blockHash)
52 txStatusMerkleRoot, err := types.TxStatusMerkleRoot(txStatus.VerifyStatus)
57 if txStatusMerkleRoot != block.TransactionStatusHash {
58 return fmt.Errorf("tx status error")
63 func (ctx *chainTestContext) validateExecution(block *types.Block) error {
64 for _, tx := range block.Transactions {
65 for _, spentOutputID := range tx.SpentOutputIDs {
66 utxoEntry, _ := ctx.Store.GetUtxo(&spentOutputID)
70 if !utxoEntry.IsCoinBase {
71 return fmt.Errorf("found non-coinbase spent utxo entry")
74 return fmt.Errorf("utxo entry status should be spent")
78 for _, outputID := range tx.ResultIds {
79 utxoEntry, _ := ctx.Store.GetUtxo(outputID)
80 if utxoEntry == nil && isSpent(outputID, block) {
83 if utxoEntry.BlockHeight != block.Height {
84 return fmt.Errorf("block height error, expected: %d, have: %d", block.Height, utxoEntry.BlockHeight)
87 return fmt.Errorf("utxo entry status should not be spent")
94 func (ctx *chainTestContext) getUtxoEntries() map[string]*storage.UtxoEntry {
95 utxoEntries := make(map[string]*storage.UtxoEntry)
96 iter := ctx.DB.IteratorPrefix([]byte(utxoPrefix))
100 utxoEntry := storage.UtxoEntry{}
101 if err := proto.Unmarshal(iter.Value(), &utxoEntry); err != nil {
104 key := string(iter.Key())
105 utxoEntries[key] = &utxoEntry
110 func (ctx *chainTestContext) validateRollback(utxoEntries map[string]*storage.UtxoEntry) error {
111 newUtxoEntries := ctx.getUtxoEntries()
112 for key := range utxoEntries {
113 entry, ok := newUtxoEntries[key]
115 return fmt.Errorf("can't find utxo after rollback")
117 if entry.Spent != utxoEntries[key].Spent {
118 return fmt.Errorf("utxo status dismatch after rollback")
124 type chainTestConfig struct {
125 RollbackTo uint64 `json:"rollback_to"`
126 Blocks []*ctBlock `json:"blocks"`
129 type ctBlock struct {
130 Transactions []*ctTransaction `json:"transactions"`
131 Append uint64 `json:"append"`
132 Invalid bool `json:"invalid"`
135 func (b *ctBlock) createBlock(ctx *chainTestContext) (*types.Block, error) {
136 txs := make([]*types.Tx, 0, len(b.Transactions))
137 for _, t := range b.Transactions {
138 tx, err := t.createTransaction(ctx, txs)
142 txs = append(txs, tx)
144 return NewBlock(ctx.Chain, txs, []byte{byte(vm.OP_TRUE)})
147 type ctTransaction struct {
148 Inputs []*ctInput `json:"inputs"`
149 Outputs []uint64 `json:"outputs"`
152 type ctInput struct {
153 Height uint64 `json:"height"`
154 TxIndex uint64 `json:"tx_index"`
155 OutputIndex uint64 `json:"output_index"`
158 func (input *ctInput) createTxInput(ctx *chainTestContext) (*types.TxInput, error) {
159 block, err := ctx.Chain.GetBlockByHeight(input.Height)
164 spendInput, err := CreateSpendInput(block.Transactions[input.TxIndex], input.OutputIndex)
169 return &types.TxInput{
170 AssetVersion: assetVersion,
171 TypedInput: spendInput,
175 // create tx input spent previous tx output in the same block
176 func (input *ctInput) createDependencyTxInput(txs []*types.Tx) (*types.TxInput, error) {
177 // sub 1 because of coinbase tx is not included in txs
178 spendInput, err := CreateSpendInput(txs[input.TxIndex-1], input.OutputIndex)
183 return &types.TxInput{
184 AssetVersion: assetVersion,
185 TypedInput: spendInput,
189 func (t *ctTransaction) createTransaction(ctx *chainTestContext, txs []*types.Tx) (*types.Tx, error) {
190 builder := txbuilder.NewBuilder(time.Now())
191 sigInst := &txbuilder.SigningInstruction{}
192 currentHeight := ctx.Chain.BestBlockHeight()
193 for _, input := range t.Inputs {
194 var txInput *types.TxInput
196 if input.Height == currentHeight+1 {
197 txInput, err = input.createDependencyTxInput(txs)
199 txInput, err = input.createTxInput(ctx)
204 err = builder.AddInput(txInput, sigInst)
210 for _, amount := range t.Outputs {
211 output := types.NewIntraChainOutput(*consensus.BTMAssetID, amount, []byte{byte(vm.OP_TRUE)})
212 if err := builder.AddOutput(output); err != nil {
217 tpl, _, err := builder.Build()
222 txSerialized, err := tpl.Transaction.MarshalText()
227 tpl.Transaction.Tx.SerializedSize = uint64(len(txSerialized))
228 tpl.Transaction.TxData.SerializedSize = uint64(len(txSerialized))
229 return tpl.Transaction, err
232 func (cfg *chainTestConfig) Run() error {
233 db := dbm.NewDB("chain_test_db", "leveldb", "chain_test_db")
234 defer os.RemoveAll("chain_test_db")
235 chain, store, _, err := MockChain(db)
239 ctx := &chainTestContext{
245 var utxoEntries map[string]*storage.UtxoEntry
246 var rollbackBlock *types.Block
247 for _, blk := range cfg.Blocks {
248 block, err := blk.createBlock(ctx)
252 _, err = ctx.Chain.ProcessBlock(block)
253 if err != nil && blk.Invalid {
259 if err := ctx.validateStatus(block); err != nil {
262 if err := ctx.validateExecution(block); err != nil {
265 if block.Height <= cfg.RollbackTo && cfg.RollbackTo <= block.Height+blk.Append {
266 utxoEntries = ctx.getUtxoEntries()
267 rollbackBlock = block
269 if err := AppendBlocks(ctx.Chain, blk.Append); err != nil {
274 if rollbackBlock == nil {
278 // rollback and validate
279 forkedChain, err := declChain("forked_chain", ctx.Chain, rollbackBlock.Height, ctx.Chain.BestBlockHeight()+1)
280 defer os.RemoveAll("forked_chain")
285 if err := merge(forkedChain, ctx.Chain); err != nil {
288 return ctx.validateRollback(utxoEntries)
291 // if the output(hash) was spent in block
292 func isSpent(hash *bc.Hash, block *types.Block) bool {
293 for _, tx := range block.Transactions {
294 for _, spendOutputID := range tx.SpentOutputIDs {
295 if spendOutputID == *hash {