Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tmp/
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Golang Blockchain

### In this tutorial, we add a Wallet Module to our Blockchain app.

## Run `go run main.go` to run the app, run `go build main.go` to build an executable file.

### Check out the Youtube Tutorial for this [Go Program](https://youtu.be/O9rDas-0s2c). Here is our [Youtube Channel](https://www.youtube.com/channel/UCYqCZOwHbnPwyjawKfE21wg) Subscribe for more content.

### Check out our blog at [tensor-programming.com](http://tensor-programming.com/).

### Our [Twitter](https://twitter.com/TensorProgram), our [facebook](https://www.facebook.com/Tensor-Programming-1197847143611799/) and our [Steemit](https://steemit.com/@tensor).
72 changes: 72 additions & 0 deletions blockchain/block.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package blockchain

import (
"bytes"
"encoding/gob"
"log"
"time"
)

type Block struct {
Timestamp int64
Hash []byte
Transactions []*Transaction
PrevHash []byte
Nonce int
Height int
}

func (b *Block) HashTransactions() []byte {
var txHashes [][]byte

for _, tx := range b.Transactions {
txHashes = append(txHashes, tx.Serialize())
}
tree := NewMerkleTree(txHashes)

return tree.RootNode.Data
}

func CreateBlock(txs []*Transaction, prevHash []byte, height int) *Block {
block := &Block{time.Now().Unix(), []byte{}, txs, prevHash, 0, height}
pow := NewProof(block)
nonce, hash := pow.Run()

block.Hash = hash[:]
block.Nonce = nonce

return block
}

func Genesis(coinbase *Transaction) *Block {
return CreateBlock([]*Transaction{coinbase}, []byte{}, 0)
}

func (b *Block) Serialize() []byte {
var res bytes.Buffer
encoder := gob.NewEncoder(&res)

err := encoder.Encode(b)

Handle(err)

return res.Bytes()
}

func Deserialize(data []byte) *Block {
var block Block

decoder := gob.NewDecoder(bytes.NewReader(data))

err := decoder.Decode(&block)

Handle(err)

return &block
}

func Handle(err error) {
if err != nil {
log.Panic(err)
}
}
Loading