github.com/turingchain2020/turingchain@v1.1.21/blockchain/chain_test.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package blockchain_test 6 7 import ( 8 "bytes" 9 "encoding/hex" 10 "errors" 11 "fmt" 12 "testing" 13 "time" 14 15 "github.com/turingchain2020/turingchain/blockchain" 16 "github.com/turingchain2020/turingchain/client" 17 "github.com/turingchain2020/turingchain/common" 18 "github.com/turingchain2020/turingchain/common/crypto" 19 20 // "github.com/turingchain2020/turingchain/common/log" 21 "github.com/turingchain2020/turingchain/common/log/log15" 22 "github.com/turingchain2020/turingchain/common/merkle" 23 "github.com/turingchain2020/turingchain/queue" 24 _ "github.com/turingchain2020/turingchain/system" 25 "github.com/turingchain2020/turingchain/types" 26 "github.com/turingchain2020/turingchain/util" 27 "github.com/turingchain2020/turingchain/util/testnode" 28 "github.com/stretchr/testify/assert" 29 "github.com/stretchr/testify/require" 30 ) 31 32 var sendTxWait = time.Millisecond * 5 33 var chainlog = log15.New("module", "chain_test") 34 35 func addTx(cfg *types.TuringchainConfig, priv crypto.PrivKey, api client.QueueProtocolAPI) ([]*types.Transaction, string, error) { 36 txs := util.GenCoinsTxs(cfg, priv, 1) 37 hash := common.ToHex(txs[0].Hash()) 38 reply, err := api.SendTx(txs[0]) 39 if err != nil { 40 return nil, hash, err 41 } 42 if !reply.GetIsOk() { 43 return nil, hash, errors.New("sendtx unknow error") 44 } 45 return txs, hash, nil 46 } 47 48 func addTxTxHeight(cfg *types.TuringchainConfig, priv crypto.PrivKey, api client.QueueProtocolAPI, height int64) ([]*types.Transaction, string, error) { 49 txs := util.GenTxsTxHeight(cfg, priv, 1, height) 50 hash := common.ToHex(txs[0].Hash()) 51 reply, err := api.SendTx(txs[0]) 52 if err != nil { 53 return txs, hash, err 54 } 55 if !reply.GetIsOk() { 56 return nil, hash, errors.New("sendtx unknow error") 57 } 58 return txs, hash, nil 59 } 60 61 func TestBlockChain(t *testing.T) { 62 //log.SetLogLevel("crit") 63 mock33 := testnode.New("", nil) 64 defer mock33.Close() 65 cfg := mock33.GetClient().GetConfig() 66 blockchain := mock33.GetBlockChain() 67 //等待共识模块增长10个区块 68 testProcAddBlockMsg(t, mock33, blockchain) 69 70 testGetTx(t, blockchain) 71 72 testGetTxHashList(t, blockchain) 73 74 testProcQueryTxMsg(cfg, t, blockchain) 75 76 testGetBlocksMsg(t, blockchain) 77 78 testProcGetHeadersMsg(t, blockchain) 79 80 testProcGetLastHeaderMsg(t, blockchain) 81 82 testGetBlockByHash(t, cfg, blockchain) 83 84 testProcGetLastSequence(t, blockchain) 85 86 testGetBlockSequences(t, blockchain) 87 88 testGetBlockByHashes(t, cfg, blockchain) 89 testGetSeqByHash(t, blockchain) 90 testPrefixCount(t, mock33, blockchain) 91 testAddrTxCount(t, mock33, blockchain) 92 93 // QM add 94 testGetBlockHerderByHash(t, cfg, blockchain) 95 96 testProcGetTransactionByHashes(t, blockchain) 97 98 textProcGetBlockOverview(t, cfg, blockchain) 99 100 testProcGetAddrOverview(t, cfg, blockchain) 101 102 testProcGetBlockHash(t, cfg, blockchain) 103 104 // testSendDelBlockEvent(t, blockchain) 105 106 testGetOrphanRoot(t, cfg, blockchain) 107 108 testRemoveOrphanBlock(t, cfg, blockchain) 109 110 testLoadBlockBySequence(t, blockchain) 111 testProcDelParaChainBlockMsg(t, mock33, blockchain) 112 113 testProcAddParaChainBlockMsg(t, mock33, blockchain) 114 testProcGetBlockBySeqMsg(t, mock33, blockchain) 115 testProcBlockChainFork(t, blockchain) 116 testDelBlock(t, blockchain) 117 testIsRecordFaultErr(t) 118 119 testGetsynBlkHeight(t, blockchain) 120 testProcDelChainBlockMsg(t, mock33, blockchain) 121 testFaultPeer(t, cfg, blockchain) 122 testCheckBlock(t, blockchain) 123 testWriteBlockToDbTemp(t, blockchain) 124 testReadBlockToExec(t, blockchain) 125 testReExecBlock(t, blockchain) 126 testUpgradeStore(t, blockchain) 127 128 testProcMainSeqMsg(t, blockchain) 129 testAddOrphanBlock(t, blockchain) 130 testCheckBestChainProc(t, cfg, blockchain) 131 132 // chunk 133 testGetChunkRecordMsg(t, mock33, blockchain) 134 testAddChunkRecordMsg(t, mock33, blockchain) 135 testGetChunkBlockBodyMsg(t, mock33, blockchain) 136 testAddChunkBlockMsg(t, mock33, blockchain) 137 } 138 139 func testGetChunkRecordMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 140 chainlog.Debug("testGetChunkRecordMsg begin --------------------") 141 142 records := &types.ReqChunkRecords{ 143 Start: 1, 144 End: 1, 145 IsDetail: false, 146 } 147 148 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventGetChunkRecord, records) 149 err := mock33.GetClient().Send(msgGen, false) 150 assert.NoError(t, err) 151 chainlog.Debug("testGetChunkRecordMsg end --------------------") 152 } 153 154 func testAddChunkRecordMsg(t *testing.T, mock33 *testnode.TuringchainMock, chain *blockchain.BlockChain) { 155 chainlog.Debug("testAddChunkRecordMsg begin --------------------") 156 157 records := &types.ChunkRecords{ 158 Infos: []*types.ChunkInfo{{ChunkNum: 1, ChunkHash: []byte("11111111111")}}, 159 } 160 161 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventAddChunkRecord, records) 162 err := mock33.GetClient().Send(msgGen, false) 163 assert.Nil(t, err) 164 chainlog.Debug("testAddChunkRecordMsg end --------------------") 165 } 166 167 func testGetChunkBlockBodyMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 168 chainlog.Debug("testGetChunkBlockBodyMsg begin --------------------") 169 170 curheight := blockchain.GetBlockHeight() 171 block, err := blockchain.GetBlock(curheight - 1) 172 require.NoError(t, err) 173 174 end := block.Block.Height 175 start := block.Block.Height - 2 176 if start < 0 { 177 start = 0 178 } 179 180 blocks := &types.ChunkInfoMsg{ 181 ChunkHash: []byte{}, 182 Start: start, 183 End: end, 184 } 185 186 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventGetChunkBlockBody, blocks) 187 mock33.GetClient().Send(msgGen, true) 188 resp, _ := mock33.GetClient().Wait(msgGen) 189 if resp.GetData() != nil { 190 bds := resp.Data.(*types.BlockBodys) 191 assert.Equal(t, len(bds.Items), int(end-start+1)) 192 } 193 chainlog.Debug("testGetChunkBlockBodyMsg end --------------------") 194 } 195 196 func testAddChunkBlockMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 197 chainlog.Debug("testAddChunkBlockMsg begin --------------------") 198 199 curheight := blockchain.GetBlockHeight() 200 block1, err := blockchain.GetBlock(curheight - 1) 201 require.NoError(t, err) 202 block2, err := blockchain.GetBlock(curheight - 2) 203 require.NoError(t, err) 204 205 blocks := &types.Blocks{ 206 Items: []*types.Block{block1.Block, block2.Block}, 207 } 208 209 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventAddChunkBlock, blocks) 210 mock33.GetClient().Send(msgGen, false) 211 chainlog.Debug("testAddChunkBlockMsg end --------------------") 212 } 213 214 func testProcAddBlockMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 215 chainlog.Debug("testProcAddBlockMsg begin --------------------") 216 217 curheight := blockchain.GetBlockHeight() 218 addblockheight := curheight + 10 219 220 _, err := blockchain.GetBlock(curheight) 221 if err != nil { 222 require.NoError(t, err) 223 } 224 cfg := mock33.GetClient().GetConfig() 225 for { 226 _, _, err = addTx(cfg, mock33.GetGenesisKey(), mock33.GetAPI()) 227 require.NoError(t, err) 228 curheight = blockchain.GetBlockHeight() 229 chainlog.Debug("testProcAddBlockMsg ", "curheight", curheight) 230 _, err = blockchain.GetBlock(curheight) 231 require.NoError(t, err) 232 if curheight >= addblockheight { 233 break 234 } 235 time.Sleep(sendTxWait) 236 } 237 chainlog.Debug("testProcAddBlockMsg end --------------------") 238 } 239 240 func testGetTx(t *testing.T, blockchain *blockchain.BlockChain) { 241 chainlog.Debug("TestGetTx begin --------------------") 242 //构建txhash 243 curheight := blockchain.GetBlockHeight() 244 block, err := blockchain.GetBlock(curheight) 245 require.NoError(t, err) 246 247 chainlog.Debug("testGetTx :", "curheight", curheight) 248 txResult, err := blockchain.GetTxResultFromDb(block.Block.Txs[0].Hash()) 249 require.NoError(t, err) 250 251 if err == nil && txResult != nil { 252 Execer := string(txResult.GetTx().Execer) 253 if "coins" != Execer { 254 t.Error("ExecerName error") 255 } 256 } 257 chainlog.Debug("TestGetTx end --------------------") 258 } 259 260 func testGetTxHashList(t *testing.T, blockchain *blockchain.BlockChain) { 261 chainlog.Debug("TestGetTxHashList begin --------------------") 262 var txhashlist types.TxHashList 263 total := 10 264 Txs := make([]*types.Transaction, total) 265 266 // 构建当前高度的tx信息 267 i := blockchain.GetBlockHeight() 268 for j := 0; j < total; j++ { 269 var transaction types.Transaction 270 payload := fmt.Sprintf("Payload :%d:%d!", i, j) 271 signature := fmt.Sprintf("Signature :%d:%d!", i, j) 272 273 transaction.Payload = []byte(payload) 274 var signature1 types.Signature 275 signature1.Signature = []byte(signature) 276 transaction.Signature = &signature1 277 278 Txs[j] = &transaction 279 txhash := Txs[j].Hash() 280 //chainlog.Debug("testGetTxHashList", "height", i, "count", j, "txhash", txhash) 281 txhashlist.Hashes = append(txhashlist.Hashes, txhash[:]) 282 } 283 duptxhashlist, err := blockchain.GetDuplicateTxHashList(&txhashlist) 284 if err != nil { 285 t.Error(err) 286 return 287 } 288 if duptxhashlist != nil { 289 for _, duptxhash := range duptxhashlist.Hashes { 290 if duptxhash != nil { 291 chainlog.Debug("testGetTxHashList", "duptxhash", duptxhash) 292 } 293 } 294 } 295 chainlog.Debug("TestGetTxHashList end --------------------") 296 } 297 298 func checkDupTx(cacheTxs []*types.Transaction, blockchain *blockchain.BlockChain) (*types.TxHashList, error) { 299 var txhashlist types.TxHashList 300 i := blockchain.GetBlockHeight() 301 for j, tx := range cacheTxs { 302 txhash := tx.Hash() 303 chainlog.Debug("checkDupTx", "height", i, "count", j, "txhash", txhash) 304 txhashlist.Hashes = append(txhashlist.Hashes, txhash[:]) 305 } 306 //count 现在是高度,当前的高度 307 txhashlist.Count = i 308 duptxhashlist, err := blockchain.GetDuplicateTxHashList(&txhashlist) 309 if err != nil { 310 return nil, err 311 } 312 313 return duptxhashlist, nil 314 } 315 316 func checkDupTxHeight(cacheTxsTxHeigt []*types.Transaction, blockchain *blockchain.BlockChain) (*types.TxHashList, error) { 317 var txhashlist types.TxHashList 318 i := blockchain.GetBlockHeight() 319 for j, tx := range cacheTxsTxHeigt { 320 txhash := tx.Hash() 321 chainlog.Debug("checkDupTxHeight", "height", i, "count", j, "txhash", common.ToHex(txhash)) 322 txhashlist.Hashes = append(txhashlist.Hashes, txhash[:]) 323 txhashlist.Expire = append(txhashlist.Expire, tx.Expire) 324 } 325 txhashlist.Count = i 326 duptxhashlist, err := blockchain.GetDuplicateTxHashList(&txhashlist) 327 if err != nil { 328 return nil, err 329 } 330 return duptxhashlist, nil 331 } 332 333 func testProcQueryTxMsg(cfg *types.TuringchainConfig, t *testing.T, blockchain *blockchain.BlockChain) { 334 chainlog.Debug("TestProcQueryTxMsg begin --------------------") 335 curheight := blockchain.GetBlockHeight() 336 var merkleroothash []byte 337 var txhash []byte 338 var txindex int 339 340 //获取当前高度的block信息 341 block, err := blockchain.GetBlock(curheight) 342 343 if err == nil { 344 merkleroothash = block.Block.TxHash 345 for index, transaction := range block.Block.Txs { 346 txhash = transaction.Hash() 347 txindex = index 348 } 349 } 350 txProof, err := blockchain.ProcQueryTxMsg(txhash) 351 require.NoError(t, err) 352 if len(block.Block.Txs) <= 1 { 353 assert.Nil(t, txProof.GetProofs()) 354 assert.Nil(t, txProof.GetTxProofs()[0].GetProofs()) 355 } 356 357 blockheight := block.Block.GetHeight() 358 if cfg.IsPara() { 359 blockheight = block.Block.GetMainHeight() 360 } 361 if cfg.IsFork(blockheight, "ForkRootHash") { 362 txhash = block.Block.Txs[txindex].FullHash() 363 } 364 //证明txproof的正确性, 365 if txProof.GetProofs() != nil { //ForkRootHash 之前的proof证明 366 brroothash := merkle.GetMerkleRootFromBranch(txProof.GetProofs(), txhash, uint32(txindex)) 367 assert.Equal(t, merkleroothash, brroothash) 368 } else if txProof.GetTxProofs() != nil { //ForkRootHash 之后的proof证明 369 var childhash []byte 370 for i, txproof := range txProof.GetTxProofs() { 371 if i == 0 { 372 childhash = merkle.GetMerkleRootFromBranch(txproof.GetProofs(), txhash, txproof.GetIndex()) 373 if txproof.GetRootHash() != nil { 374 assert.Equal(t, txproof.GetRootHash(), childhash) 375 } else { 376 assert.Equal(t, txproof.GetIndex(), uint32(txindex)) 377 assert.Equal(t, merkleroothash, childhash) 378 } 379 } else { 380 brroothash := merkle.GetMerkleRootFromBranch(txproof.GetProofs(), childhash, txproof.GetIndex()) 381 assert.Equal(t, merkleroothash, brroothash) 382 } 383 } 384 } 385 chainlog.Debug("TestProcQueryTxMsg end --------------------") 386 } 387 388 func testGetBlocksMsg(t *testing.T, blockchain *blockchain.BlockChain) { 389 chainlog.Debug("TestGetBlocksMsg begin --------------------") 390 curheight := blockchain.GetBlockHeight() 391 var reqBlock types.ReqBlocks 392 if curheight >= 5 { 393 reqBlock.Start = curheight - 5 394 } 395 reqBlock.End = curheight 396 reqBlock.IsDetail = true 397 checkheight := reqBlock.Start 398 blocks, err := blockchain.ProcGetBlockDetailsMsg(&reqBlock) 399 if err == nil && blocks != nil { 400 for _, block := range blocks.Items { 401 if checkheight != block.Block.Height { 402 t.Error("TestGetBlocksMsg", "checkheight", checkheight, "block", block) 403 } 404 checkheight++ 405 } 406 } 407 reqBlock.Start = 0 408 reqBlock.End = 1000 409 _, err = blockchain.ProcGetBlockDetailsMsg(&reqBlock) 410 assert.Equal(t, err, types.ErrMaxCountPerTime) 411 412 chainlog.Debug("TestGetBlocksMsg end --------------------") 413 } 414 415 func testProcGetHeadersMsg(t *testing.T, blockchain *blockchain.BlockChain) { 416 chainlog.Debug("TestProcGetHeadersMsg begin --------------------") 417 418 curheight := blockchain.GetBlockHeight() 419 var reqBlock types.ReqBlocks 420 if curheight >= 5 { 421 reqBlock.Start = curheight - 5 422 } 423 reqBlock.End = curheight 424 checkheight := reqBlock.Start 425 blockheaders, err := blockchain.ProcGetHeadersMsg(&reqBlock) 426 if err == nil && blockheaders != nil { 427 for _, head := range blockheaders.Items { 428 if checkheight != head.Height { 429 t.Error("testProcGetHeadersMsg Block header check error") 430 } 431 checkheight++ 432 } 433 } 434 reqBlock.Start = 0 435 reqBlock.End = 100000 436 _, err = blockchain.ProcGetHeadersMsg(&reqBlock) 437 assert.Equal(t, err, types.ErrMaxCountPerTime) 438 439 chainlog.Debug("TestProcGetHeadersMsg end --------------------") 440 } 441 442 //新增区块时代码中是先更新UpdateHeight2,然后再更新UpdateLastBlock2 443 // 可能存在调用GetBlockHeight时已经更新,但UpdateLastBlock2还没有来得及更新最新区块 444 // GetBlockHeight()获取的最新高度 >= ProcGetLastHeaderMsg()获取的区块高度 445 func testProcGetLastHeaderMsg(t *testing.T, blockchain *blockchain.BlockChain) { 446 chainlog.Debug("TestProcGetLastHeaderMsg begin --------------------") 447 curheight := blockchain.GetBlockHeight() 448 blockheader, err := blockchain.ProcGetLastHeaderMsg() 449 if err == nil && blockheader != nil { 450 if curheight < blockheader.Height { 451 chainlog.Debug("TestProcGetLastHeaderMsg", "curheight", curheight, "blockheader.Height", blockheader.Height) 452 t.Error("testProcGetLastHeaderMsg Last Header check error") 453 } 454 } 455 chainlog.Debug("TestProcGetLastHeaderMsg end --------------------") 456 } 457 458 func testGetBlockByHash(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 459 chainlog.Debug("TestGetBlockByHash begin --------------------") 460 curheight := blockchain.GetBlockHeight() 461 block1, err := blockchain.GetBlock(curheight - 5) 462 require.NoError(t, err) 463 464 blockhash1 := block1.Block.Hash(cfg) 465 block2, err := blockchain.GetBlock(curheight - 4) 466 require.NoError(t, err) 467 468 if !bytes.Equal(blockhash1, block2.Block.ParentHash) { 469 fmt.Println("block.ParentHash != prehash: nextParentHash", blockhash1, block2.Block.ParentHash) 470 } 471 block3, err := blockchain.ProcGetBlockByHashMsg(block2.Block.Hash(cfg)) 472 require.NoError(t, err) 473 if !bytes.Equal(block2.Block.Hash(cfg), block3.Block.Hash(cfg)) { 474 t.Error("testGetBlockByHash Block Hash check error") 475 } 476 chainlog.Debug("TestGetBlockByHash end --------------------") 477 } 478 479 func testProcGetLastSequence(t *testing.T, blockchain *blockchain.BlockChain) { 480 chainlog.Debug("testProcGetLastSequence begin --------------------") 481 482 curheight := blockchain.GetBlockHeight() 483 484 lastSequence, err := blockchain.GetStore().LoadBlockLastSequence() 485 require.NoError(t, err) 486 if curheight != lastSequence { 487 t.Error("testProcGetLastSequence Last Sequence check error") 488 } 489 chainlog.Debug("testProcGetLastSequence end --------------------") 490 } 491 492 func testGetBlockSequences(t *testing.T, chain *blockchain.BlockChain) { 493 chainlog.Debug("testGetBlockSequences begin --------------------") 494 lastSequence, _ := chain.GetStore().LoadBlockLastSequence() 495 var reqBlock types.ReqBlocks 496 if lastSequence >= 5 { 497 reqBlock.Start = lastSequence - 5 498 } 499 reqBlock.End = lastSequence 500 reqBlock.IsDetail = true 501 Sequences, err := chain.GetBlockSequences(&reqBlock) 502 if err == nil && Sequences != nil { 503 for _, sequence := range Sequences.Items { 504 if sequence.Type != types.AddBlock { 505 t.Error("testGetBlockSequences sequence type check error") 506 } 507 } 508 } 509 reqBlock.Start = 0 510 reqBlock.End = 1000 511 _, err = chain.GetBlockSequences(&reqBlock) 512 assert.Equal(t, err, types.ErrMaxCountPerTime) 513 514 chainlog.Debug("testGetBlockSequences end --------------------") 515 } 516 517 func testGetBlockByHashes(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 518 chainlog.Debug("testGetBlockByHashes begin --------------------") 519 lastSequence, _ := blockchain.GetStore().LoadBlockLastSequence() 520 var reqBlock types.ReqBlocks 521 if lastSequence >= 5 { 522 reqBlock.Start = lastSequence - 5 523 } 524 reqBlock.End = lastSequence 525 reqBlock.IsDetail = true 526 hashes := make([][]byte, 6) 527 Sequences, err := blockchain.GetBlockSequences(&reqBlock) 528 if err == nil && Sequences != nil { 529 for index, sequence := range Sequences.Items { 530 hashes[index] = sequence.Hash 531 } 532 } 533 534 blocks, err := blockchain.GetBlockByHashes(hashes) 535 if err == nil && blocks != nil { 536 for index, block := range blocks.Items { 537 if !bytes.Equal(hashes[index], block.Block.Hash(cfg)) { 538 t.Error("testGetBlockByHashes block hash check error") 539 } 540 } 541 } 542 chainlog.Debug("testGetBlockByHashes end --------------------") 543 } 544 545 func testGetSeqByHash(t *testing.T, blockchain *blockchain.BlockChain) { 546 chainlog.Debug("testGetSeqByHash begin --------------------") 547 lastSequence, _ := blockchain.GetStore().LoadBlockLastSequence() 548 var reqBlock types.ReqBlocks 549 550 reqBlock.Start = lastSequence 551 reqBlock.End = lastSequence 552 reqBlock.IsDetail = true 553 hashes := make([][]byte, 1) 554 Sequences, err := blockchain.GetBlockSequences(&reqBlock) 555 556 if err == nil && Sequences != nil { 557 for index, sequence := range Sequences.Items { 558 hashes[index] = sequence.Hash 559 } 560 } 561 562 seq, _ := blockchain.ProcGetSeqByHash(hashes[0]) 563 if seq == -1 { 564 t.Error(" GetSeqByHash err") 565 } 566 567 chainlog.Debug("testGetSeqByHash end --------------------") 568 } 569 570 func testPrefixCount(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 571 chainlog.Debug("testPrefixCount begin --------------------") 572 573 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventLocalPrefixCount, &types.ReqKey{Key: []byte("TxAddrHash:14KEKbYtKKQm4wMthSK9J4La4nAiidGozt:")}) 574 mock33.GetClient().Send(msgGen, true) 575 Res, _ := mock33.GetClient().Wait(msgGen) 576 count := Res.GetData().(*types.Int64).Data 577 if count == 0 { 578 t.Error("testPrefixCount count check error ") 579 } 580 chainlog.Debug("testPrefixCount end --------------------") 581 } 582 583 func testAddrTxCount(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 584 chainlog.Debug("testAddrTxCount begin --------------------") 585 cfg := mock33.GetClient().GetConfig() 586 var reqkey types.ReqKey 587 reqkey.Key = []byte(fmt.Sprintf("AddrTxsCount:%s", "14KEKbYtKKQm4wMthSK9J4La4nAiidGozt")) 588 count, err := mock33.GetAPI().Query(cfg.ExecName("coins"), "GetAddrTxsCount", &reqkey) 589 if err != nil { 590 t.Error(err) 591 return 592 } 593 if count.(*types.Int64).GetData() == 0 { 594 t.Error("testAddrTxCount count check error ") 595 } 596 chainlog.Debug("testAddrTxCount end --------------------") 597 } 598 599 func testGetBlockHerderByHash(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 600 chainlog.Debug("testGetBlockHerderByHash begin --------------------") 601 curheight := blockchain.GetBlockHeight() 602 block, err := blockchain.GetBlock(curheight - 5) 603 require.NoError(t, err) 604 605 blockhash := block.Block.Hash(cfg) 606 block, err = blockchain.GetBlock(curheight - 4) 607 require.NoError(t, err) 608 609 if !bytes.Equal(blockhash, block.Block.ParentHash) { 610 fmt.Println("block.ParentHash != prehash: nextParentHash", blockhash, block.Block.ParentHash) 611 } 612 header, err := blockchain.GetStore().GetBlockHeaderByHash(block.Block.Hash(cfg)) 613 require.NoError(t, err) 614 if !bytes.Equal(header.Hash, block.Block.Hash(cfg)) { 615 t.Error("testGetBlockHerderByHash block header hash check error") 616 } 617 chainlog.Debug("testGetBlockHerderByHash end --------------------") 618 } 619 620 func testProcGetTransactionByHashes(t *testing.T, blockchain *blockchain.BlockChain) { 621 chainlog.Debug("textProcGetTransactionByHashes begin --------------------") 622 parm := &types.ReqAddr{ 623 Addr: "14KEKbYtKKQm4wMthSK9J4La4nAiidGozt", 624 Height: -1, 625 } 626 txinfos, err := blockchain.ProcGetTransactionByAddr(parm) 627 require.NoError(t, err) 628 629 var Hashes [][]byte 630 if txinfos != nil { 631 for _, receipt := range txinfos.TxInfos { 632 Hashes = append(Hashes, receipt.Hash) 633 } 634 } 635 636 TxDetails, err := blockchain.ProcGetTransactionByHashes(Hashes) 637 require.NoError(t, err) 638 639 if TxDetails != nil { 640 for index, tx := range TxDetails.Txs { 641 if tx.Tx != nil { 642 if !bytes.Equal(Hashes[index], tx.Tx.Hash()) { 643 t.Error("testProcGetTransactionByHashes hash check error") 644 } 645 } 646 } 647 } 648 649 parm.Count = 1001 650 _, err = blockchain.ProcGetTransactionByAddr(parm) 651 assert.Equal(t, err, types.ErrMaxCountPerTime) 652 653 chainlog.Debug("textProcGetTransactionByHashes end --------------------") 654 } 655 656 func textProcGetBlockOverview(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 657 chainlog.Debug("textProcGetBlockOverview begin --------------------") 658 curheight := blockchain.GetBlockHeight() 659 block, err := blockchain.GetBlock(curheight - 5) 660 require.NoError(t, err) 661 662 parm := &types.ReqHash{ 663 Hash: block.Block.Hash(cfg), 664 } 665 blockOverview, err := blockchain.ProcGetBlockOverview(parm) 666 require.NoError(t, err) 667 668 if blockOverview != nil { 669 if !bytes.Equal(block.Block.Hash(cfg), blockOverview.Head.Hash) { 670 t.Error("textProcGetBlockOverview block hash check error") 671 } 672 673 } 674 chainlog.Debug("textProcGetBlockOverview end --------------------") 675 } 676 677 func testProcGetAddrOverview(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 678 chainlog.Debug("testProcGetAddrOverview begin --------------------") 679 curheight := blockchain.GetBlockHeight() 680 block, err := blockchain.GetBlock(curheight - 5) 681 require.NoError(t, err) 682 683 blockhash := block.Block.Hash(cfg) 684 block, err = blockchain.GetBlock(curheight - 4) 685 require.NoError(t, err) 686 687 if !bytes.Equal(blockhash, block.Block.ParentHash) { 688 fmt.Println("block.ParentHash != prehash: nextParentHash", blockhash, block.Block.ParentHash) 689 } 690 691 parm := &types.ReqAddr{ 692 Addr: "14KEKbYtKKQm4wMthSK9J4La4nAiidGozt", 693 } 694 addrOverview, err := blockchain.ProcGetAddrOverview(parm) 695 require.NoError(t, err) 696 697 if addrOverview != nil { 698 if addrOverview.TxCount == 0 { 699 t.Error("testProcGetAddrOverview TxCount check error") 700 } 701 } 702 chainlog.Debug("testProcGetAddrOverview end --------------------") 703 } 704 705 func testProcGetBlockHash(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 706 chainlog.Debug("testProcGetBlockHash begin --------------------") 707 curheight := blockchain.GetBlockHeight() 708 block, err := blockchain.GetBlock(curheight - 5) 709 require.NoError(t, err) 710 height := &types.ReqInt{Height: curheight - 5} 711 hash, err := blockchain.ProcGetBlockHash(height) 712 require.NoError(t, err) 713 714 if !bytes.Equal(block.Block.Hash(cfg), hash.Hash) { 715 t.Error("testProcGetBlockHash block hash check error") 716 } 717 718 chainlog.Debug("testProcGetBlockHash end --------------------") 719 } 720 721 func testGetOrphanRoot(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 722 chainlog.Debug("testGetOrphanRoot begin --------------------") 723 curheight := blockchain.GetBlockHeight() 724 block, err := blockchain.GetBlock(curheight - 5) 725 require.NoError(t, err) 726 727 hash := blockchain.GetOrphanPool().GetOrphanRoot(block.Block.Hash(cfg)) 728 if !bytes.Equal(block.Block.Hash(cfg), hash) { 729 t.Error("testGetOrphanRoot Orphan Root hash check error") 730 } 731 chainlog.Debug("testGetOrphanRoot end --------------------") 732 } 733 734 func testRemoveOrphanBlock(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 735 chainlog.Debug("testRemoveOrphanBlock begin --------------------") 736 curheight := blockchain.GetBlockHeight() 737 block, err := blockchain.GetBlock(curheight - 5) 738 require.NoError(t, err) 739 740 ParentHashNotexist, _ := hex.DecodeString("8bd1f23741c90e9db4edd663acc0328a49f7c92d9974f83e2d5b57b25f3f059b") 741 block.Block.ParentHash = ParentHashNotexist 742 743 blockchain.GetOrphanPool().RemoveOrphanBlock2(block.Block, time.Time{}, false, "123", 0) 744 blockchain.GetOrphanPool().RemoveOrphanBlockByHash(block.Block.Hash(cfg)) 745 746 chainlog.Debug("testRemoveOrphanBlock end --------------------") 747 } 748 749 func testDelBlock(t *testing.T, blockchain *blockchain.BlockChain) { 750 chainlog.Debug("testDelBlock begin --------------------") 751 curheight := blockchain.GetBlockHeight() 752 block, err := blockchain.GetBlock(curheight) 753 require.NoError(t, err) 754 755 newblock := types.BlockDetail{} 756 newblock.Block = types.Clone(block.Block).(*types.Block) 757 newblock.Block.Difficulty = block.Block.Difficulty - 100 758 759 blockchain.ProcessBlock(true, &newblock, "1", true, 0) 760 chainlog.Debug("testDelBlock end --------------------") 761 } 762 763 func testLoadBlockBySequence(t *testing.T, blockchain *blockchain.BlockChain) { 764 chainlog.Debug("testLoadBlockBySequence begin ---------------------") 765 766 curheight := blockchain.GetBlockHeight() 767 lastseq, _ := blockchain.GetStore().LoadBlockLastSequence() 768 sequence, err := blockchain.GetStore().GetBlockSequence(lastseq) 769 require.NoError(t, err) 770 block, _, err := blockchain.GetStore().LoadBlockBySequence(lastseq) 771 require.NoError(t, err) 772 773 if block.Block.Height != curheight && types.DelBlock != sequence.GetType() { 774 t.Error("testLoadBlockBySequence", "curheight", curheight, "lastseq", lastseq, "Block.Height", block.Block.Height) 775 } 776 chainlog.Debug("testLoadBlockBySequence end -------------------------") 777 } 778 779 func testProcDelParaChainBlockMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 780 chainlog.Debug("testProcDelParaChainBlockMsg begin --------------------") 781 782 curheight := blockchain.GetBlockHeight() 783 block, err := blockchain.GetBlock(curheight - 1) 784 require.NoError(t, err) 785 786 var parablockDetail types.ParaChainBlockDetail 787 parablockDetail.Blockdetail = block 788 parablockDetail.Sequence = 1 789 790 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventDelParaChainBlockDetail, ¶blockDetail) 791 mock33.GetClient().Send(msgGen, true) 792 resp, _ := mock33.GetClient().Wait(msgGen) 793 if resp.GetData().(*types.Reply).IsOk { 794 t.Error("testProcDelParaChainBlockMsg only in parachain ") 795 } 796 chainlog.Debug("testProcDelParaChainBlockMsg end --------------------") 797 } 798 799 func testProcAddParaChainBlockMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 800 chainlog.Debug("testProcAddParaChainBlockMsg begin --------------------") 801 802 curheight := blockchain.GetBlockHeight() 803 block, err := blockchain.GetBlock(curheight) 804 require.NoError(t, err) 805 806 var parablockDetail types.ParaChainBlockDetail 807 parablockDetail.Blockdetail = block 808 parablockDetail.Sequence = 1 809 810 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventAddParaChainBlockDetail, ¶blockDetail) 811 812 mock33.GetClient().Send(msgGen, true) 813 _, err = mock33.GetClient().Wait(msgGen) 814 if err != nil { 815 t.Log(err) 816 //t.Error("testProcAddParaChainBlockMsg only in parachain ") 817 } 818 chainlog.Debug("testProcAddParaChainBlockMsg end --------------------") 819 } 820 821 func testProcGetBlockBySeqMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 822 chainlog.Debug("testProcGetBlockBySeqMsg begin --------------------") 823 824 seq, err := blockchain.GetStore().LoadBlockLastSequence() 825 assert.Nil(t, err) 826 827 //block, err := blockchain.GetBlock(curheight) 828 //require.NoError(t, err) 829 830 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventGetBlockBySeq, &types.Int64{Data: seq}) 831 832 mock33.GetClient().Send(msgGen, true) 833 msg, err := mock33.GetClient().Wait(msgGen) 834 if err != nil { 835 t.Log(err) 836 //t.Error("testProcAddParaChainBlockMsg only in parachain ") 837 } 838 blockseq := msg.Data.(*types.BlockSeq) 839 assert.Equal(t, seq, blockseq.Num) 840 chainlog.Debug("testProcGetBlockBySeqMsg end --------------------") 841 } 842 843 func testProcBlockChainFork(t *testing.T, blockchain *blockchain.BlockChain) { 844 chainlog.Debug("testProcBlockChainFork begin --------------------") 845 846 curheight := blockchain.GetBlockHeight() 847 blockchain.ProcDownLoadBlocks(curheight-1, curheight+256, false, []string{"self"}) 848 chainlog.Debug("testProcBlockChainFork end --------------------") 849 } 850 851 func testIsRecordFaultErr(t *testing.T) { 852 chainlog.Debug("testIsRecordFaultErr begin ---------------------") 853 isok := blockchain.IsRecordFaultErr(types.ErrFutureBlock) 854 if isok { 855 t.Error("testIsRecordFaultErr IsRecordFaultErr", "isok", isok) 856 } 857 chainlog.Debug("testIsRecordFaultErr end ---------------------") 858 } 859 860 func testProcDelChainBlockMsg(t *testing.T, mock33 *testnode.TuringchainMock, blockchain *blockchain.BlockChain) { 861 chainlog.Debug("testProcDelChainBlockMsg begin --------------------") 862 863 curheight := blockchain.GetBlockHeight() 864 block, err := blockchain.GetBlock(curheight) 865 require.NoError(t, err) 866 867 var parablockDetail types.ParaChainBlockDetail 868 parablockDetail.Blockdetail = block 869 parablockDetail.Sequence = curheight 870 871 msgGen := mock33.GetClient().NewMessage("blockchain", types.EventDelParaChainBlockDetail, ¶blockDetail) 872 mock33.GetClient().Send(msgGen, true) 873 mock33.GetClient().Wait(msgGen) 874 875 chainlog.Debug("testProcDelChainBlockMsg end --------------------") 876 } 877 func testGetsynBlkHeight(t *testing.T, chain *blockchain.BlockChain) { 878 chainlog.Debug("testGetsynBlkHeight begin --------------------") 879 curheight := chain.GetBlockHeight() 880 chain.UpdatesynBlkHeight(curheight) 881 882 height := chain.GetsynBlkHeight() 883 if height != curheight { 884 chainlog.Error("testGetsynBlkHeight", "curheight", curheight, "height", height) 885 } 886 //get peerinfo 887 peerinfo := chain.GetPeerInfo("self") 888 if peerinfo != nil { 889 chainlog.Error("testGetsynBlkHeight:GetPeerInfo", "peerinfo", peerinfo) 890 } 891 maxpeer := chain.GetMaxPeerInfo() 892 if maxpeer != nil { 893 chainlog.Error("testGetsynBlkHeight:GetMaxPeerInfo", "maxpeer", maxpeer) 894 } 895 896 chainlog.Debug("testGetsynBlkHeight end --------------------") 897 } 898 899 func testFaultPeer(t *testing.T, cfg *types.TuringchainConfig, chain *blockchain.BlockChain) { 900 chainlog.Debug("testFaultPeer begin ---------------------") 901 curheight := chain.GetBlockHeight() 902 block, err := chain.GetBlock(curheight) 903 require.NoError(t, err) 904 isok := chain.IsFaultPeer("self") 905 if isok { 906 t.Error("testFaultPeer:IsFaultPeer") 907 } 908 //记录故障peer信息 909 chain.RecordFaultPeer("self", curheight+1, block.Block.Hash(cfg), types.ErrSign) 910 911 var faultnode blockchain.FaultPeerInfo 912 var peerinfo blockchain.PeerInfo 913 peerinfo.Name = "self" 914 faultnode.Peer = &peerinfo 915 faultnode.FaultHeight = curheight + 1 916 faultnode.FaultHash = block.Block.Hash(cfg) 917 faultnode.ErrInfo = types.ErrSign 918 faultnode.ReqFlag = false 919 chain.AddFaultPeer(&faultnode) 920 921 peer := chain.GetFaultPeer("self") 922 if peer == nil { 923 t.Error("testFaultPeer:GetFaultPeer is nil") 924 } 925 926 chain.UpdateFaultPeer("self", true) 927 928 chain.RemoveFaultPeer("self") 929 chainlog.Debug("testFaultPeer end ---------------------") 930 } 931 func testCheckBlock(t *testing.T, chain *blockchain.BlockChain) { 932 curheight := chain.GetBlockHeight() 933 //chain.CheckHeightNoIncrease() 934 chain.FetchBlockHeaders(0, curheight, "self") 935 header, err := chain.ProcGetLastHeaderMsg() 936 937 var blockheader types.Header 938 if header != nil && err == nil { 939 blockheader.Version = header.Version 940 blockheader.ParentHash = header.ParentHash 941 blockheader.TxHash = header.TxHash 942 blockheader.StateHash = header.StateHash 943 blockheader.Height = header.Height 944 blockheader.BlockTime = header.BlockTime 945 946 blockheader.TxCount = header.TxCount 947 blockheader.Hash = header.Hash 948 blockheader.Difficulty = header.Difficulty 949 blockheader.Signature = header.Signature 950 } 951 var blockheaders types.Headers 952 blockheaders.Items = append(blockheaders.Items, &blockheader) 953 chain.ProcAddBlockHeadersMsg(&blockheaders, "self") 954 chain.ProcBlockHeaders(&blockheaders, "self") 955 } 956 func testReadBlockToExec(t *testing.T, chain *blockchain.BlockChain) { 957 chainlog.Debug("testReadBlockToExec begin ---------------------") 958 curheight := chain.GetBlockHeight() 959 chain.ReadBlockToExec(curheight+1, false) 960 chain.DownLoadTimeOutProc(curheight - 1) 961 chainlog.Debug("testReadBlockToExec end ---------------------") 962 } 963 func testWriteBlockToDbTemp(t *testing.T, chain *blockchain.BlockChain) { 964 chainlog.Debug("WriteBlockToDbTemp begin ---------------------") 965 curheight := chain.GetBlockHeight() 966 block, err := chain.GetBlock(curheight) 967 if err != nil { 968 t.Error("testWriteBlockToDbTemp", "err", err) 969 } 970 var rawblock types.Block 971 rawblock.Version = block.Block.Version 972 rawblock.ParentHash = block.Block.ParentHash 973 rawblock.TxHash = block.Block.TxHash 974 rawblock.StateHash = block.Block.StateHash 975 rawblock.BlockTime = block.Block.BlockTime 976 rawblock.Difficulty = block.Block.Difficulty 977 rawblock.MainHash = block.Block.MainHash 978 rawblock.MainHeight = block.Block.MainHeight 979 980 rawblock.Height = block.Block.Height + 1 981 err = chain.WriteBlockToDbTemp(&rawblock, true) 982 if err != nil { 983 t.Error("testWriteBlockToDbTemp", "err", err) 984 } 985 chain.UpdateDownLoadPids() 986 chainlog.Debug("WriteBlockToDbTemp end ---------------------") 987 } 988 989 func testReExecBlock(t *testing.T, chain *blockchain.BlockChain) { 990 chainlog.Debug("ReExecBlock begin ---------------------") 991 curheight := chain.GetBlockHeight() 992 chain.ReExecBlock(0, curheight) 993 chainlog.Debug("ReExecBlock end ---------------------") 994 } 995 996 func testUpgradeStore(t *testing.T, chain *blockchain.BlockChain) { 997 chainlog.Debug("UpgradeStore begin ---------------------") 998 chain.UpgradeStore() 999 chainlog.Debug("UpgradeStore end ---------------------") 1000 } 1001 1002 func testProcMainSeqMsg(t *testing.T, blockchain *blockchain.BlockChain) { 1003 chainlog.Debug("testProcMainSeqMsg begin -------------------") 1004 1005 msg := queue.NewMessage(1, "blockchain", types.EventGetLastBlockMainSequence, nil) 1006 blockchain.GetLastBlockMainSequence(msg) 1007 assert.Equal(t, int64(types.EventGetLastBlockMainSequence), msg.Ty) 1008 1009 msg = queue.NewMessage(1, "blockchain", types.EventGetMainSeqByHash, &types.ReqHash{Hash: []byte("hash")}) 1010 blockchain.GetMainSeqByHash(msg) 1011 assert.Equal(t, int64(types.EventGetMainSeqByHash), msg.Ty) 1012 1013 chainlog.Debug("testProcMainSeqMsg end --------------------") 1014 } 1015 1016 func testAddOrphanBlock(t *testing.T, blockchain *blockchain.BlockChain) { 1017 1018 chainlog.Debug("testAddOrphanBlock begin --------------------") 1019 curheight := blockchain.GetBlockHeight() 1020 block, err := blockchain.GetBlock(curheight) 1021 require.NoError(t, err) 1022 block.Block.ParentHash = block.Block.GetTxHash() 1023 newblock := types.BlockDetail{} 1024 newblock.Block = block.Block 1025 1026 blockchain.ProcessBlock(true, &newblock, "1", true, 0) 1027 chainlog.Debug("testAddOrphanBlock end --------------------") 1028 } 1029 func testCheckBestChainProc(t *testing.T, cfg *types.TuringchainConfig, blockchain *blockchain.BlockChain) { 1030 chainlog.Debug("testCheckBestChainProc begin --------------------") 1031 curheight := blockchain.GetBlockHeight() 1032 block, err := blockchain.GetBlock(curheight) 1033 require.NoError(t, err) 1034 header := block.Block.GetHeader(cfg) 1035 1036 var headers types.Headers 1037 headers.Items = append(headers.Items, header) 1038 blockchain.CheckBestChainProc(&headers, "test") 1039 1040 blockchain.CheckBestChain(true) 1041 blockchain.GetNtpClockSyncStatus() 1042 blockchain.UpdateNtpClockSyncStatus(true) 1043 blockchain.IsErrExecBlock(curheight, block.Block.Hash(cfg)) 1044 chainlog.Debug("testCheckBestChainProc end --------------------") 1045 } 1046 1047 //测试kv对的读写 1048 func TestSetValueByKey(t *testing.T) { 1049 mock33 := testnode.New("", nil) 1050 defer func() { 1051 defer mock33.Close() 1052 }() 1053 chainlog.Debug("TestSetValueByKey begin --------------------") 1054 blockchain := mock33.GetBlockChain() 1055 1056 //设置kv对到数据库,key的前缀错误 1057 var kvs types.LocalDBSet 1058 var kv types.KeyValue 1059 //ConsensusParaTxsPrefix = []byte("LODB:Consensus:Para:") 1060 key_1 := []byte("LODBP:Consensus:Parakey-1") 1061 value_1 := []byte("value-1") 1062 kv.Key = key_1 1063 kv.Value = value_1 1064 kvs.KV = append(kvs.KV, &kv) 1065 1066 err := blockchain.SetValueByKey(&kvs) 1067 if err != nil { 1068 t.Error("TestSetValueByKey:SetValueByKey1", "err", err) 1069 } 1070 //读取数据为空 1071 var keys types.LocalDBGet 1072 key := []byte("LODBP:Consensus:Parakey-1") 1073 keys.Keys = append(keys.Keys, key) 1074 values := blockchain.GetValueByKey(&keys) 1075 for _, value := range values.Values { 1076 if bytes.Equal(value, value_1) { 1077 t.Error("TestSetValueByKey:GetValueByKey1", "value", string(value)) 1078 } 1079 } 1080 //设置kv对到数据库 1081 var kvs2 types.LocalDBSet 1082 var kv2 types.KeyValue 1083 key_1 = types.CalcConsensusParaTxsKey([]byte("key-1")) 1084 kv2.Key = key_1 1085 kv2.Value = value_1 1086 kvs2.KV = append(kvs2.KV, &kv2) 1087 1088 err = blockchain.SetValueByKey(&kvs2) 1089 if err != nil { 1090 t.Error("TestSetValueByKey:SetValueByKey2", "err", err) 1091 } 1092 //读取数据ok 1093 var keys2 types.LocalDBGet 1094 var key_1_exist bool 1095 keys2.Keys = append(keys2.Keys, key_1) 1096 values = blockchain.GetValueByKey(&keys2) 1097 for _, value := range values.Values { 1098 if bytes.Equal(value, value_1) { 1099 key_1_exist = true 1100 } else { 1101 t.Error("TestSetValueByKey:GetValueByKey", "value", string(value)) 1102 } 1103 } 1104 if !key_1_exist { 1105 t.Error("TestSetValueByKey:GetValueByKey:key_1", "key_1", string(key_1)) 1106 } 1107 1108 //删除key_1对应的数据,set时设置key_1对应的value为nil 1109 for _, kv := range kvs2.KV { 1110 if bytes.Equal(kv.GetKey(), key_1) { 1111 kv.Value = nil 1112 } 1113 } 1114 err = blockchain.SetValueByKey(&kvs2) 1115 if err != nil { 1116 t.Error("TestSetValueByKey:SetValueByKey3", "err", err) 1117 } 1118 values = blockchain.GetValueByKey(&keys2) 1119 for _, value := range values.Values { 1120 if bytes.Equal(value, value_1) { 1121 t.Error("TestSetValueByKey:GetValueByKey4", "value", string(value)) 1122 } 1123 } 1124 1125 //插入多个kv对到数据库并获取 1126 var kvs3 types.LocalDBSet 1127 var kv3 types.KeyValue 1128 key_1 = types.CalcConsensusParaTxsKey([]byte("key-1")) 1129 value_1 = []byte("test-1") 1130 key_2 := types.CalcConsensusParaTxsKey([]byte("key-2")) 1131 value_2 := []byte("test-2") 1132 key_3 := types.CalcConsensusParaTxsKey([]byte("key-3")) 1133 value_3 := []byte("test-3") 1134 1135 kv.Key = key_1 1136 kv.Value = value_1 1137 kv2.Key = key_2 1138 kv2.Value = value_2 1139 kv3.Key = key_3 1140 kv3.Value = value_3 1141 1142 kvs3.KV = append(kvs2.KV, &kv, &kv2, &kv3) 1143 1144 err = blockchain.SetValueByKey(&kvs3) 1145 if err != nil { 1146 t.Error("TestSetValueByKey:SetValueByKey4", "err", err) 1147 } 1148 //读取数据ok 1149 var keys3 types.LocalDBGet 1150 count := 0 1151 for _, kv := range kvs3.GetKV() { 1152 keys3.Keys = append(keys3.Keys, kv.GetKey()) 1153 } 1154 values = blockchain.GetValueByKey(&keys3) 1155 for i, value := range values.Values { 1156 if bytes.Equal(value, kvs3.GetKV()[i].GetValue()) { 1157 count++ 1158 } else { 1159 t.Error("TestSetValueByKey:GetValueByKey", "value", string(value)) 1160 } 1161 } 1162 if count < 3 { 1163 t.Error("TestSetValueByKey:GetValueByKey:fail") 1164 } 1165 chainlog.Debug("TestSetValueByKey end --------------------") 1166 } 1167 1168 func TestOnChainTimeout(t *testing.T) { 1169 chainlog.Debug("TestOnChainTimeout begin --------------------") 1170 1171 cfg := testnode.GetDefaultConfig() 1172 mcfg := cfg.GetModuleConfig() 1173 mcfg.BlockChain.OnChainTimeout = 1 1174 mock33 := testnode.NewWithConfig(cfg, nil) 1175 1176 defer mock33.Close() 1177 blockchain := mock33.GetBlockChain() 1178 1179 //等待共识模块增长10个区块 1180 testProcAddBlockMsg(t, mock33, blockchain) 1181 1182 curheight := blockchain.GetBlockHeight() 1183 1184 //没有超时 1185 isTimeOut := blockchain.OnChainTimeout(curheight) 1186 assert.Equal(t, isTimeOut, false) 1187 1188 //2秒后超时 1189 time.Sleep(2 * time.Second) 1190 lastheight := blockchain.GetBlockHeight() 1191 blockchain.OnChainTimeout(lastheight) 1192 println("curheight:", curheight) 1193 println("lastheight:", lastheight) 1194 if lastheight == curheight { 1195 isTimeOut = blockchain.OnChainTimeout(lastheight) 1196 assert.Equal(t, isTimeOut, true) 1197 } else { 1198 time.Sleep(2 * time.Second) 1199 isTimeOut = blockchain.OnChainTimeout(lastheight) 1200 assert.Equal(t, isTimeOut, true) 1201 } 1202 1203 chainlog.Debug("TestOnChainTimeout end --------------------") 1204 } 1205 1206 func TestProcessDelBlock(t *testing.T) { 1207 chainlog.Debug("TestProcessDelBlock begin --------------------") 1208 mock33 := testnode.New("", nil) 1209 defer mock33.Close() 1210 blockchain := mock33.GetBlockChain() 1211 1212 //构造十个区块 1213 curheight := blockchain.GetBlockHeight() 1214 addblockheight := curheight + 10 1215 1216 _, err := blockchain.GetBlock(curheight) 1217 if err != nil { 1218 require.NoError(t, err) 1219 } 1220 cfg := mock33.GetClient().GetConfig() 1221 1222 // 确保只出指定数量的区块 1223 isFirst := true 1224 prevheight := curheight 1225 for { 1226 if isFirst || curheight > prevheight { 1227 _, err = addSingleParaTx(cfg, mock33.GetGenesisKey(), mock33.GetAPI(), "user.p.hyb.none") 1228 require.NoError(t, err) 1229 if curheight > prevheight { 1230 prevheight = curheight 1231 } 1232 isFirst = false 1233 } 1234 curheight = blockchain.GetBlockHeight() 1235 _, err = blockchain.GetBlock(curheight) 1236 require.NoError(t, err) 1237 if curheight >= addblockheight { 1238 break 1239 } 1240 time.Sleep(sendTxWait) 1241 } 1242 1243 curheight = blockchain.GetBlockHeight() 1244 block, err := blockchain.GetBlock(curheight) 1245 require.NoError(t, err) 1246 1247 //删除最新的区块:可能存在GetBlockHeight()获取的是最新区块, 1248 //但是在删除时b.bestChain.Tip()中还没有更新成最新的区块,此时会返回ErrBlockHashNoMatch错误信息 1249 1250 isok := false 1251 count := 0 1252 for { 1253 _, ok, _, err := blockchain.ProcessDelParaChainBlock(true, block, "self", curheight) 1254 if err != nil { 1255 time.Sleep(sendTxWait) 1256 count++ 1257 } else if true == ok && err == nil { 1258 isok = true 1259 break 1260 } else if count == 10 { 1261 isok = false 1262 chainlog.Error("TestProcessDelBlock 50ms timeout --------------------") 1263 break 1264 } 1265 } 1266 if !isok { 1267 chainlog.Error("TestProcessDelBlock:ProcessDelParaChainBlock:fail!") 1268 return 1269 } 1270 1271 //获取已经删除的区块上的title 1272 var req types.ReqParaTxByTitle 1273 req.Start = curheight + 1 1274 req.End = curheight + 1 1275 req.Title = "user.p.para." 1276 req.IsSeq = true 1277 1278 paratxs, err := blockchain.GetParaTxByTitle(&req) 1279 require.NoError(t, err) 1280 assert.NotNil(t, paratxs) 1281 for _, paratx := range paratxs.Items { 1282 assert.Equal(t, types.DelBlock, paratx.Type) 1283 assert.Nil(t, paratx.TxDetails) 1284 assert.Nil(t, paratx.ChildHash) 1285 assert.Nil(t, paratx.Proofs) 1286 assert.Equal(t, uint32(0), paratx.Index) 1287 } 1288 1289 req.Title = "user.p.hyb." 1290 maintxs, err := blockchain.GetParaTxByTitle(&req) 1291 require.NoError(t, err) 1292 assert.NotNil(t, maintxs) 1293 for _, maintx := range maintxs.Items { 1294 assert.Equal(t, types.DelBlock, maintx.Type) 1295 roothash := merkle.GetMerkleRootFromBranch(maintx.Proofs, maintx.ChildHash, maintx.Index) 1296 var txs []*types.Transaction 1297 for _, tx := range maintx.TxDetails { 1298 txs = append(txs, tx.Tx) 1299 } 1300 hash := merkle.CalcMerkleRoot(cfg, maintx.GetHeader().GetHeight(), txs) 1301 assert.Equal(t, hash, roothash) 1302 } 1303 chainlog.Debug("TestProcessDelBlock end --------------------") 1304 } 1305 1306 func TestEnableCmpBestBlock(t *testing.T) { 1307 chainlog.Debug("TestEnableCmpBestBlock begin --------------------") 1308 defaultCfg := testnode.GetDefaultConfig() 1309 mcfg := defaultCfg.GetModuleConfig() 1310 mcfg.Consensus.EnableBestBlockCmp = true 1311 mock33 := testnode.NewWithConfig(defaultCfg, nil) 1312 1313 defer mock33.Close() 1314 blockchain := mock33.GetBlockChain() 1315 1316 //构造十个区块 1317 curheight := blockchain.GetBlockHeight() 1318 addblockheight := curheight + 10 1319 1320 _, err := blockchain.GetBlock(curheight) 1321 if err != nil { 1322 require.NoError(t, err) 1323 } 1324 cfg := mock33.GetClient().GetConfig() 1325 1326 // 确保只出指定数量的区块 1327 isFirst := true 1328 prevheight := curheight 1329 for { 1330 if isFirst || curheight > prevheight { 1331 _, err = addSingleParaTx(cfg, mock33.GetGenesisKey(), mock33.GetAPI(), "user.p.hyb.none") 1332 require.NoError(t, err) 1333 if curheight > prevheight { 1334 prevheight = curheight 1335 } 1336 isFirst = false 1337 } 1338 curheight = blockchain.GetBlockHeight() 1339 _, err = blockchain.GetBlock(curheight) 1340 require.NoError(t, err) 1341 if curheight >= addblockheight { 1342 break 1343 } 1344 time.Sleep(sendTxWait) 1345 } 1346 1347 curheight = blockchain.GetBlockHeight() 1348 block, err := blockchain.GetBlock(curheight) 1349 require.NoError(t, err) 1350 1351 temblock := types.Clone(block.Block) 1352 newblock := temblock.(*types.Block) 1353 newblock.GetTxs()[0].Nonce = newblock.GetTxs()[0].Nonce + 1 1354 newblock.TxHash = merkle.CalcMerkleRoot(cfg, newblock.GetHeight(), newblock.GetTxs()) 1355 blockDetail := types.BlockDetail{Block: newblock} 1356 _, err = blockchain.ProcAddBlockMsg(true, &blockDetail, "peer") 1357 1358 //直接修改了交易的Nonce,执行时会报ErrSign错误 1359 if err != nil { 1360 assert.Equal(t, types.ErrSign, err) 1361 } else { 1362 require.NoError(t, err) 1363 } 1364 1365 //当前节点做对比 1366 curheight = blockchain.GetBlockHeight() 1367 curblock, err := blockchain.GetBlock(curheight) 1368 require.NoError(t, err) 1369 1370 testCmpBestBlock(t, mock33.GetClient(), curblock.Block, cfg) 1371 1372 //非当前节点做对比 1373 curheight = blockchain.GetBlockHeight() 1374 oldblock, err := blockchain.GetBlock(curheight - 1) 1375 require.NoError(t, err) 1376 1377 testCmpBestBlock(t, mock33.GetClient(), oldblock.Block, cfg) 1378 1379 chainlog.Debug("TestEnableCmpBestBlock end --------------------") 1380 } 1381 1382 func TestDisableCmpBestBlock(t *testing.T) { 1383 chainlog.Debug("TestDisableCmpBestBlock begin --------------------") 1384 defaultCfg := testnode.GetDefaultConfig() 1385 mock33 := testnode.NewWithConfig(defaultCfg, nil) 1386 1387 defer mock33.Close() 1388 blockchain := mock33.GetBlockChain() 1389 1390 //构造十个区块 1391 curheight := blockchain.GetBlockHeight() 1392 addblockheight := curheight + 10 1393 1394 _, err := blockchain.GetBlock(curheight) 1395 if err != nil { 1396 require.NoError(t, err) 1397 } 1398 cfg := mock33.GetClient().GetConfig() 1399 1400 // 确保只出指定数量的区块 1401 isFirst := true 1402 prevheight := curheight 1403 for { 1404 if isFirst || curheight > prevheight { 1405 _, err = addSingleParaTx(cfg, mock33.GetGenesisKey(), mock33.GetAPI(), "user.p.hyb.none") 1406 require.NoError(t, err) 1407 if curheight > prevheight { 1408 prevheight = curheight 1409 } 1410 isFirst = false 1411 } 1412 curheight = blockchain.GetBlockHeight() 1413 _, err = blockchain.GetBlock(curheight) 1414 require.NoError(t, err) 1415 if curheight >= addblockheight { 1416 break 1417 } 1418 time.Sleep(sendTxWait) 1419 } 1420 1421 curheight = blockchain.GetBlockHeight() 1422 block, err := blockchain.GetBlock(curheight) 1423 require.NoError(t, err) 1424 1425 temblock := types.Clone(block.Block) 1426 newblock := temblock.(*types.Block) 1427 newblock.GetTxs()[0].Nonce = newblock.GetTxs()[0].Nonce + 1 1428 newblock.TxHash = merkle.CalcMerkleRoot(cfg, newblock.GetHeight(), newblock.GetTxs()) 1429 blockDetail := types.BlockDetail{Block: newblock} 1430 _, err = blockchain.ProcAddBlockMsg(true, &blockDetail, "peer") 1431 1432 //直接修改了交易的Nonce,执行时会报ErrSign错误 1433 if err != nil { 1434 assert.Equal(t, types.ErrSign, err) 1435 } else { 1436 require.NoError(t, err) 1437 } 1438 chainlog.Debug("TestDisableCmpBestBlock end --------------------") 1439 } 1440 1441 func testCmpBestBlock(t *testing.T, client queue.Client, block *types.Block, cfg *types.TuringchainConfig) { 1442 temblock := types.Clone(block) 1443 newblock := temblock.(*types.Block) 1444 newblock.GetTxs()[0].Nonce = newblock.GetTxs()[0].Nonce + 1 1445 newblock.TxHash = merkle.CalcMerkleRoot(cfg, newblock.GetHeight(), newblock.GetTxs()) 1446 1447 isbestBlock := util.CmpBestBlock(client, newblock, block.Hash(cfg)) 1448 assert.Equal(t, isbestBlock, false) 1449 }