You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.1 KiB

  1. package core
  2. import (
  3. "io/ioutil"
  4. "testing"
  5. "github.com/arnaucube/slowlorisdb/db"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestBlockchainDataStructure(t *testing.T) {
  9. dir, err := ioutil.TempDir("", "db")
  10. assert.Nil(t, err)
  11. db, err := db.New(dir)
  12. assert.Nil(t, err)
  13. bc := NewBlockchain(db, uint64(1))
  14. block := bc.NewBlock([]Tx{})
  15. block2, err := BlockFromBytes(block.Bytes())
  16. assert.Nil(t, err)
  17. assert.Equal(t, block2.Bytes(), block.Bytes())
  18. }
  19. func TestGetBlock(t *testing.T) {
  20. dir, err := ioutil.TempDir("", "db")
  21. assert.Nil(t, err)
  22. db, err := db.New(dir)
  23. assert.Nil(t, err)
  24. bc := NewBlockchain(db, uint64(1))
  25. block := bc.NewBlock([]Tx{})
  26. assert.Equal(t, block.Height, uint64(1))
  27. err = bc.AddBlock(block)
  28. assert.Nil(t, err)
  29. block2, err := bc.GetBlock(block.Hash)
  30. assert.Nil(t, err)
  31. assert.Equal(t, block.Bytes(), block2.Bytes())
  32. }
  33. func TestGetPrevBlock(t *testing.T) {
  34. dir, err := ioutil.TempDir("", "db")
  35. assert.Nil(t, err)
  36. db, err := db.New(dir)
  37. assert.Nil(t, err)
  38. bc := NewBlockchain(db, uint64(1))
  39. for i := 0; i < 10; i++ {
  40. block := bc.NewBlock([]Tx{})
  41. block.CalculatePoW(bc.Difficulty)
  42. assert.Equal(t, block.Height, uint64(i+1))
  43. err = bc.AddBlock(block)
  44. assert.Nil(t, err)
  45. assert.Equal(t, bc.LastBlock.Height, block.Height)
  46. }
  47. block9, err := bc.GetPrevBlock(bc.LastBlock.Hash)
  48. assert.Nil(t, err)
  49. assert.Equal(t, block9.Height, uint64(9))
  50. block8, err := bc.GetPrevBlock(block9.Hash)
  51. assert.Nil(t, err)
  52. assert.Equal(t, block8.Height, uint64(8))
  53. currentBlock := bc.LastBlock
  54. for err == nil {
  55. currentBlock, err = bc.GetPrevBlock(currentBlock.Hash)
  56. }
  57. assert.Equal(t, err.Error(), "This was the oldest block")
  58. }
  59. func TestAddBlockWithTx(t *testing.T) {
  60. addr0 := Address(HashBytes([]byte("addr0")))
  61. addr1 := Address(HashBytes([]byte("addr1")))
  62. dir, err := ioutil.TempDir("", "db")
  63. assert.Nil(t, err)
  64. db, err := db.New(dir)
  65. assert.Nil(t, err)
  66. bc := NewBlockchain(db, uint64(1))
  67. var txs []Tx
  68. tx := NewTx(addr0, addr1, []Input{}, []Output{})
  69. txs = append(txs, *tx)
  70. block := bc.NewBlock(txs)
  71. block2, err := BlockFromBytes(block.Bytes())
  72. assert.Nil(t, err)
  73. assert.Equal(t, block2.Bytes(), block.Bytes())
  74. }