Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "log"
- "net/http"
- "net"
- "time"
- "math/rand"
- )
- type Block struct{
- Hash string
- PrevHash string
- Id uint64
- Timestamp uint64
- Data interface{}
- }
- func (block *Block) GetHash() string{
- hash := sha256.Sum256([]byte(block.ToString()))
- return hex.Decode(sha25)
- }
- func (block *Block) ToString() string{
- data, _ := json.MarshalIndent(block.Data, '\n', '\t')
- return fmt.Sprintf(`
- {
- "id": %d,
- "prevHash":"%s",
- "timestamp":%d,
- "data":%v,
- }
- `, block.Id, block.PrevHash, block.Timestamp, data)
- }
- type BlockChain struct{
- Blocks []*Block
- LastID uint64
- }
- func New () *BlockChain{
- chain := new(BlockChain)
- chain.LastID = 0
- chain.Blocks = make([]*Block, 0)
- return chain
- }
- func (BlockChain *ch) NewBlock(data interface{}) string{
- ch.LastID++
- block := new (Block)
- block.Data = data
- block.Id = ch.LastID
- if ch.Length() == 0{
- block.PrevHash = ToSha256(rand.Uint64())
- }else{
- block.PrevHash = ch.LastBlock.GetHash()
- }
- ch.Blocks = append(ch.Blocks, block)
- return block.GetHash()
- }
- func (BlockChain *ch) Length() int{
- return len(ch.Blocks)
- }
- func (BlockChain *ch) LastBlock() *Block{
- return ch.Blocks[len(ch.Blocks) - 1]
- }
- func (BlockChain *ch) GetBlock(hash string) *Block{
- for _, block := range ch.Blocks{
- if block.Hash == hash{
- return block
- }
- }
- return nil
- }
- func ToSha256(data interface{}) string{
- hash := sha256.Sum256([]byte(data))
- return hex.Decode(hash)
- }
- func Exists(r http.Request, form string){
- _, ok := r.Form[form]
- return ok
- }
- func main() {
- http.HandleFunc("/block/new", func (w *http.Writer, r http.Request){
- if r.ParseForm() != nil{
- log.Fataln("Cannot Parse Form")
- }
- if Exists(r, "data"){
- }
- })
- http.HandleFunc("/block/list", func(w *http.Writer, r http.Request){
- if r.ParseForm() != nil{
- log.Fataln("Cannot Parse Form")
- }
- if Exists(r, "hash"){
- hash := r.FormValue("hash")
- }else{
- }
- })
- log.Println("Starting on :80")
- log.Println(http.ServeAndListen(":80", nil))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement