Created
April 5, 2021 21:11
-
-
Save Israel-Miles/c03c1ea45467853fbf980ee0a14540a1 to your computer and use it in GitHub Desktop.
full blockchain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/sha256" | |
"fmt" | |
"time" | |
) | |
type Block struct { | |
timestamp time.Time | |
transactions []string | |
prevHash []byte | |
Hash []byte | |
} | |
func main() { | |
genesisTransactions := []string{"Izzy sent Will 50 bitcoin", "Will sent Izzy 30 bitcoin"} | |
genesisBlock := NewBlock(genesisTransactions, []byte{}) | |
fmt.Println("--- First Block ---") | |
printBlockInformation(genesisBlock) | |
block2Transactions := []string{"John sent Izzy 30 bitcoin"} | |
block2 := NewBlock(block2Transactions, genesisBlock.Hash) | |
fmt.Println("--- Second Block ---") | |
printBlockInformation(block2) | |
block3Transactions := []string{"Will sent Izzy 45 bitcoin", "Izzy sent Will 10 bitcoin"} | |
block3 := NewBlock(block3Transactions, block2.Hash) | |
fmt.Println("--- Third Block ---") | |
printBlockInformation(block3) | |
} | |
func NewBlock(transactions []string, prevHash []byte) *Block { | |
currentTime := time.Now() | |
return &Block { | |
timestamp: currentTime, | |
transactions: transactions, | |
prevHash: prevHash, | |
Hash: NewHash(currentTime, transactions, prevHash), | |
} | |
} | |
func NewHash(time time.Time, transactions []string, prevHash []byte) []byte { | |
input := append(prevHash, time.String()...) | |
for transaction := range transactions { | |
input = append(input, string(rune(transaction))...) | |
} | |
hash := sha256.Sum256(input) | |
return hash[:] | |
} | |
func printBlockInformation(block *Block) { | |
fmt.Printf("\ttime: %s\n", block.timestamp.String()) | |
fmt.Printf("\tprevHash: %x\n", block.prevHash) | |
fmt.Printf("\tHash: %x\n", block.Hash) | |
printTransactions(block) | |
} | |
func printTransactions(block *Block) { | |
fmt.Println("\tTransactions:") | |
for i, transaction := range block.transactions { | |
fmt.Printf("\t\t%v: %q\n", i, transaction) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment