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.

83 lines
1.6 KiB

  1. package core
  2. import (
  3. "errors"
  4. "time"
  5. "github.com/arnaucube/slowlorisdb/db"
  6. )
  7. type Blockchain struct {
  8. Id []byte // Id allows to have multiple blockchains
  9. Difficulty uint64
  10. Genesis Hash
  11. LastBlock *Block
  12. db *db.Db
  13. }
  14. func NewBlockchain(database *db.Db, dif uint64) *Blockchain {
  15. blockchain := &Blockchain{
  16. Id: []byte{},
  17. Difficulty: dif,
  18. Genesis: HashBytes([]byte("genesis")),
  19. LastBlock: &Block{},
  20. db: database,
  21. }
  22. return blockchain
  23. }
  24. func (bc *Blockchain) NewBlock(txs []Tx) *Block {
  25. block := &Block{
  26. Height: bc.GetHeight() + 1,
  27. PrevHash: bc.LastBlock.Hash,
  28. Txs: txs,
  29. Miner: Address{}, // TODO put the node address
  30. Timestamp: time.Now(),
  31. Nonce: 0,
  32. Hash: Hash{},
  33. Signature: []byte{},
  34. }
  35. return block
  36. }
  37. func (bc *Blockchain) GetHeight() uint64 {
  38. return bc.LastBlock.Height
  39. }
  40. func (bc *Blockchain) GetLastBlock() *Block {
  41. return bc.LastBlock
  42. }
  43. func (bc *Blockchain) AddBlock(block *Block) error {
  44. bc.LastBlock = block
  45. err := bc.db.Put(block.Hash[:], block.Bytes())
  46. return err
  47. }
  48. func (bc *Blockchain) GetBlock(hash Hash) (*Block, error) {
  49. v, err := bc.db.Get(hash[:])
  50. if err != nil {
  51. return nil, err
  52. }
  53. block, err := BlockFromBytes(v)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return block, nil
  58. }
  59. func (bc *Blockchain) GetPrevBlock(hash Hash) (*Block, error) {
  60. currentBlock, err := bc.GetBlock(hash)
  61. if err != nil {
  62. return nil, err
  63. }
  64. if currentBlock.PrevHash.IsZero() {
  65. return nil, errors.New("This was the oldest block")
  66. }
  67. prevBlock, err := bc.GetBlock(currentBlock.PrevHash)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return prevBlock, nil
  72. }