Sådan opbygges en Blockchain fra Scratch with Go

Introduktion

Da Web 3.0 og blockchain bliver mere mainstream hver dag, ved du hvad blockchain er? Kender du dens tekniske fordele og brugssager?

Målet med denne vejledning er at introducere blockchain-teknologi fra et teknisk perspektiv ved at opbygge en fra bunden.

Glem alt, hvad du har hørt om blockchain fra sociale medier. Nu vil du opbygge et blockchain-system fra grunden nul for virkelig at forstå ind og ud af denne peer-to-peer, distribuerede teknologi.

Bagefter skal du tænke dig selv om dens fremtid og fordele. Spoiler-alarm: du bliver forelsket i programmering af blockchain-software.

Hvordan?

Du vil følge historien om en softwareudvikler, der ønsker at revolutionere sin lokale bar ved at implementere blockchain-teknologi til sit betalingssystem.

Selvom blockchain har flere ubestridelige brugssager, er applikationen nummer et i øjeblikket betalinger. Dette skyldes, at banker stadig kører på en ineffektiv, 40 år gammel infrastruktur, der drives af CSV-filer og FTP.

Historien kommer med en masse sjove og spændende fakta om det overordnede blockchain-økosystem og forskellige protokoller som Bitcoin, Ethereum og XRP.

Hvad vil du opbygge, lære og gøre i denne vejledning?

  • Du konfigurerer et Go-projekt på din lokale maskine uden nogen tidligere GoLang-oplevelse
  • Du genererer og distribuerer dine første blockchain-tokens
  • Du udvikler en CLI-styret database i Go fra bunden
  • Du finder ud af, hvor få rettigheder brugere har i deres foretrukne apps
  • Du opdager blockchains vigtigste værdiforslag
  • Du gør din DB uforanderlig ved hjælp af en sikker kryptografisk hash-funktion

Så lad os komme i gang og springe ind i vores historie.

⭐ Mød hovedpersonen, Andrej.

Andrej er barejer om natten og softwareudvikler om dagen i en lille slovakisk by ved navn Bardejov.

Andrej er træt af:

  • Programmering af solide, gammeldags PHP / Java / Javascript-applikationer
  • Glemmer hvor mange penge hans venner og kunder skylder ham for alle de ubetalte vodka-skud fredag ​​aften
  • Brug tid på at indsamle og tælle mønter, returnere forandring og generelt røre ved COVID-19-eksponerede bankregninger
  • Vedligeholdelse af forskellige plastchips til bordfodbold, dart, billard og poker

Andrej vil meget gerne:

  • Har en perfekt revideret historie af barens aktiviteter og salg for at gøre sin bar i overensstemmelse med skattereglerne
  • Omdan sin bar til et autonomt, betalingseffektivt, decentralt og sikkert miljø, som hans kunder kan stole på og drage fordel af

Hans mål er at skrive et simpelt program og holde alle sine kunders saldi i virtuel form.

Andrej deler sine tanker her:

"Hver ny kunde vil give mig kontanter, og jeg krediterer dem et tilsvarende beløb af mine digitale tokens (mønter / kryptokurrency). Tokenerne repræsenterer en monetær enhed inden for og uden for linjen.

Brugerne bruger tokens til alle barfunktioner fra at betale for drinks, låne og låne dem til deres venner og spille bordtennis, poker og kicker.

At have en bar drevet af blockchain-tokens vil generere masser af værdi for mine kunder. I modsætning til min konkurrence og andre barer på denne gade, hvor kunderne kun bruger penge og får tømmermænd til gengæld, vil mine barkunder, der holder barens tokens, have aktionærrettigheder.

På samme måde som at eje en stor del af aktier i et firma som Apple eller Microsoft, vil de kunder, der har disse stregtegn, være i stand til at beslutte, hvordan stangen skal fungere ved at stemme og beslutte:

  • priser på drikkevarer
  • åbningstider
  • nye funktioner (TV, Jukebox ...)
  • indvendigt og udvendigt design
  • fordeling af overskud
  • etc.

Åh, dette bliver en programmeringsdrøm!

Jeg kalder tokens: Blockchain Bar-tokens, TBB! "

Nu da Andrej har delt sin drøm, kommer vi i gang.

Indholdsfortegnelse

  • Krav
  • Opsæt projektet
  • 01 | MVP-databasen
  • 02 | Muterende global DB-stat
  • 03 | Monolitisk begivenhed vs transaktion
  • 04 | Mennesker er grådige
  • 05 | Hvorfor vi har brug for Blockchain
  • 06 | L'Hash de Immutable
  • Næste skridt

Krav

Lad os dykke ned i vores tutorial. Jeg anbefaler 2+ års erfaring med programmering i Java / PHP / Javascript eller et andet sprog, der ligner Go.

Hvis du ønsker at få en god hurtig introduktion til at gå, her er et gratis kursus, der får dig i gang.

Du kan også gennemføre de officielle 17 forelæsninger af A Tour Of Go for at blive fortrolig med sprogsyntaks og grundlæggende begreber (~ 20 minutter).

Hvorfor gå?

For ligesom blockchain er det en fantastisk teknologi til din samlede programmeringskarriere. Go er et trendy sprog, og Go devs er bedre betalt end de gennemsnitlige Java / PHP / Javascript-positioner.

Go is optimized for multi-core CPU architecture. You can spawn thousands of light-weight threads (Go-routines) without problems. It's extremely practical for highly parallel and concurrent software such as blockchain networks.

By writing your software in Go, you achieve nearly C++ level of performance out of the box without killing yourself for that one time you forgot to free up memory.

Go also compiles to binary which makes it very portable.

Setup the project

This article has a dedicated open-sourced Github repository with full source code so you can compile the code and run the program on your own local machine.

If you get stuck at any chapter or a particular line of code, create a Github Issue in this repository describing your problem and I will help you out ASAP!

↓ Visit the Github repository and follow the installation instructions ↓

web3coach / the-blockchain-bar-newsletter-edition Kildekoden til de første 7 kapitler i: "The Blockchain Way of Programming" e-bog. - web3coach / the-blockchain-bar-newsletter-edition web3coach GitHub

01 | MVP-databasen

git checkout c1_genesis_json

Andrej mestrer relationelle SQL-databaser i 90'erne. Han ved, hvordan man laver avancerede datamodeller, og hvordan man optimerer SQL-forespørgsler.

Det er tid for Andrej at indhente innovation og begynde at opbygge Web 3.0-software.

Efter at have læst "The Lean Startup" -bogen i sidste uge, føler Andrej heldigvis, at han ikke skulle over-engineer løsningen endnu. Derfor vælger han en enkel, men effektiv JSON-fil til barens MVP-database.

I starten var der en primitiv centraliseret database.

? Resumé

Blockchain er en database.

Bruger 1, Andrej

Mandag den 18. marts.

Andrej genererer 1M hjælpeprogrammer.

In the blockchain world, tokens are units inside the blockchain database. Their real value in dollars or euro fluctuates based on their demand and popularity.

Every blockchain has a "Genesis" file. The Genesis file is used to distribute the first tokens to early blockchain participants.

It all starts with a simple, dummy genesis.json.

Andrej creates the file ./database/genesis.json where he defines that The Blockchain Bar's database will have 1M tokens and all of them will belong to Andrej:

{ "genesis_time": "2019-03-18T00:00:00.000000000Z", "chain_id": "the-blockchain-bar-ledger", "balances": { "andrej": 1000000 } } 

The tokens need to have a real "utility", that is a use case. Users should be able to pay with them from day 1!

Andrej must comply with law regulators (the SEC). It is illegal to issue unregistered security. On the other hand, utility tokens are fine, so right away he prints and sticks a new pricing white p̶a̶p̶e̶r̶ poster on the bar's door.

Andrej assigns a starting monetary value to his tokens so he can exchange them for euro, dollars, or other fiat currency.

1 TBB token = 1€ | Item | Price | | ------------------------- | ------- | | Vodka shot | 1 TBB | | Orange juice | 5 TBB | | Burger | 2 TBB | | Crystal Head Vodka Bottle | 950 TBB | 

Andrej also decides he should be getting 100 tokens per day for maintaining the database and having such a brilliant disruptive idea.

?Fun Facts

Den første genese Ether (ETH) på Ethereum blockchain blev oprettet og distribueret til tidlige investorer og udviklere på samme måde som Andrejs utility token. I 2017 under en ICO (første møntudbydelse) boom på Ethereum blockchain-netværket skrev projektstifterne og præsenterede hvidbøger for investorer. En hvidbog er et teknisk dokument, der skitserer et komplekst spørgsmål og en mulig løsning, der er beregnet til at uddanne og belyse en bestemt sag. I en verden af ​​blockchains tjener en hvidbog til at skitsere specifikationerne for, hvordan den pågældende blockchain vil se ud og opføre sig, når den er udviklet. Blockchain-projekter hævet mellem € 10 mio. Til € 300 mio. Per hvidbogidé. i bytte for penge (ICO "finansiering") ville investornavne være inkluderet i de oprindelige "genesis saldi", svarende til hvordan Andrej gjorde det. Investorers håb gennem en ICO er, at oprindelsesmønterne stiger i værdi, og at holdene leverer den skitserede blockchain. Naturligvis kommer ikke alle hvidbogsidéer til at virke. Massive investeringer tabt på grund af uklare eller ufuldstændige ideer er, hvorfor blockchain modtog negativ dækning i medierne gennem disse ICO'er, og hvorfor nogle stadig betragtede det som en hype. Men den underliggende blockchain-teknologi er fantastisk og nyttig, som du vil lære mere om i denne bog. Det er bare blevet misbrugt af nogle dårlige skuespillere.

? Resumé

Blockchain er en database.

Tokenforsyningen, indledende brugerbalancer og globale blockchain-indstillinger, du definerer i en Genesis-fil.

02 | Muterende global DB-stat

git checkout c2_db_changes_txt

Dead Party

Monday, March 25.

After a week of work, the bar facilities are ready to accept tokens. Unfortunately, no one shows up, so Andrej orders three shots of vodka for himself and writes the database changes on a piece of paper:

andrej-3; // 3 shots of vodka andrej+3; // technically purchasing from his own bar andrej+700; // Reward for a week of work (7x100 per day) 

To avoid recalculating the latest state of each customer's balance, Andrej creates a ./database/state.json file storing the balances in an aggregated format.

New DB state:

{ "balances": { "andrej": 1000700 } } 

Bonus for BabaYaga

Tuesday, March 26.

To bring traffic to his bar, Andrej announces an exclusive 100% bonus for everyone who purchases the TBB tokens in the next 24 hours.

Bing! He gets his first customer called BabaYaga. BabaYaga pre-purchases 1000€ worth of tokens, and to celebrate, she immediately spends 1 TBB for a vodka shot. She has a drinking problem.

DB transactions written on a piece of paper:

andrej-2000; // transfer to BabaYaga babayaga+2000; // pre-purchase with 100% bonus babayaga-1; andrej+1; andrej+100; // 1 day of sun coming up 

New DB state:

{ "balances": { "andrej": 998801, "babayaga": 1999 } } 

?Fun Facts

Blockchain ICO-projekter (indledende mønttilbud baseret på whitepapers) distribuerer ofte genesis-tokens med forskellige bonusser, afhængigt af hvor mange af dem du køber, og hvor tidligt du gør det. Hold tilbyder i gennemsnit 10-40% bonusser til tidlige "deltagere". Ordet "investor" undgås, så lovgivere vil ikke betragte tokens som en sikkerhed. Projekter ville begrunde deres hovedprodukt, blockchain-tokens, fungere som "flyvende loyalitetspoint." "Deltagerne" tjente senere endda 1000% på, at deres investering solgte til offentligheden gennem en udveksling flere måneder senere.

?Resumé

Blockchain er en database.

Tokenforsyningen, indledende brugerbalancer og globale blockchain-indstillinger, du definerer i en Genesis-fil.

Genesis-saldoserne angiver, hvad der var den oprindelige blockchain-tilstand, og opdateres aldrig bagefter.

The database state changes are called Transactions (TX).

03 | Monolithic Event vs Transaction

git checkout c3_state_blockchain_component

Developers used to event-sourcing architecture must have immediately recognized the familiar principles behind transactions. They are correct.

Blockchain transactions represent a series of events, and the database is a final aggregated, calculated state after replaying all the transactions in a specific sequence.

Andrej Programming

Tuesday evening, March 26.

It's a relaxing Tuesday evening for Andrej. Celebrating his first client, he decides to play some Starcraft and clean up his local development machine by removing some old pictures.

Unfortunately, he prematurely pressed enter when typing a removal command path in terminal sudo rm -rf /. Oops.

All his files, including the bar's genesis.json and state.json are gone.

Andrej, being a senior developer, repeatedly shouted some f* words very loudly for a few seconds, but he didn't panic!

While he didn't have a backup, he had something better — a piece of paper with all the database transactions. The only thing he needs to do is replay all the transactions one by one, and his database state will get recovered.

Impressed by the advantages of event-based architecture, he decides to extend his MVP database solution. Every bar's activity, such as individual drink purchases, MUST be recorded inside the blockchain database.

Each customer will be represented in DB using an Account Struct:

type Account string 

Each Transaction (TX - a database change) will have the following four attributes: from, to, value and data.

The data attribute with one possible value (reward) captures Andrej's bonus for inventing the blockchain and increases the initial TBB tokens total supply artificially (inflation).

type Tx struct { From Account `json:"from"` To Account `json:"to"` Value uint `json:"value"` Data string `json:"data"` } func (t Tx) IsReward() bool { return t.Data == "reward" } 

The Genesis DB will remain a JSON file:

{ "genesis_time": "2019-03-18T00:00:00.000000000Z", "chain_id": "the-blockchain-bar-ledger", "balances": { "andrej": 1000000 } } 

All the transactions, previously written on a piece of paper, will be stored in a local text-file database called tx.db, serialized in JSON format and separated by line-break character:

{"from":"andrej","to":"andrej","value":3,"data":""} {"from":"andrej","to":"andrej","value":700,"data":"reward"} {"from":"andrej","to":"babayaga","value":2000,"data":""} {"from":"andrej","to":"andrej","value":100,"data":"reward"} {"from":"babayaga","to":"andrej","value":1,"data":""} 

The most crucial database component encapsulating all the business logic will be State:

type State struct { Balances map[Account]uint txMempool []Tx dbFile *os.File } 

The State struct will know about all user balances and who transferred TBB tokens to whom, and how many were transferred.

It's constructed by reading the initial user balances from genesis.json file:

func NewStateFromDisk() (*State, error) { // get current working directory cwd, err := os.Getwd() if err != nil { return nil, err } genFilePath := filepath.Join(cwd, "database", "genesis.json") gen, err := loadGenesis(genFilePath) if err != nil { return nil, err } balances := make(map[Account]uint) for account, balance := range gen.Balances { balances[account] = balance } 

Afterwards, the genesis State balances are updated by sequentially replaying all the database events from tx.db:

 txDbFilePath := filepath.Join(cwd, "database", "tx.db") f, err := os.OpenFile(txDbFilePath, os.O_APPEND|os.O_RDWR, 0600) if err != nil { return nil, err } scanner := bufio.NewScanner(f) state := &State{balances, make([]Tx, 0), f} // Iterate over each the tx.db file's line for scanner.Scan() { if err := scanner.Err(); err != nil { return nil, err } // Convert JSON encoded TX into an object (struct) var tx Tx json.Unmarshal(scanner.Bytes(), &tx) // Rebuild the state (user balances), // as a series of events if err := state.apply(tx); err != nil { return nil, err } } return state, nil } 

The State component is responsible for:

  • Adding new transactions to Mempool
  • Validating transactions against the current State (sufficient sender balance)
  • Changing the state
  • Persisting transactions to disk
  • Calculating accounts balances by replaying all transactions since Genesis in a sequence

Adding new transactions to Mempool:

func (s *State) Add(tx Tx) error { if err := s.apply(tx); err != nil { return err } s.txMempool = append(s.txMempool, tx) return nil } 

Persisting the transactions to disk:

func (s *State) Persist() error { // Make a copy of mempool because the s.txMempool will be modified // in the loop below mempool := make([]Tx, len(s.txMempool)) copy(mempool, s.txMempool) for i := 0; i < len(mempool); i++ { txJson, err := json.Marshal(s.txMempool[i]) if err != nil { return err } if _, err = s.dbFile.Write(append(txJson, '\n')); err != nil { return err } // Remove the TX written to a file from the mempool // Yes... this particular Go syntax is a bit weird s.txMempool = append(s.txMempool[:i], s.txMempool[i+1:]...) } return nil }

Changing, Validating the state:

func (s *State) apply(tx Tx) error { if tx.IsReward() { s.Balances[tx.To] += tx.Value return nil } if tx.Value > s.Balances[tx.From] { return fmt.Errorf("insufficient balance") } s.Balances[tx.From] -= tx.Value s.Balances[tx.To] += tx.Value return nil } 

Building a Command-Line-Interface (CLI)

Tuesday evening, March 26.

Andrej wants to have a convenient way to add new transactions to his DB and list the latest balances of his customers. Because Go programs compile to binary, he builds a CLI for his program.

The easiest way to develop CLI based programs in Go is by using the third party github.com/spf13/cobra library.

Andrej initializes Go's built-in dependency manager for his project, called go modules:

cd $GOPATH/src/github.com/web3coach/the-blockchain-way-of-programming-newsletter-edition

go mod init github.com/web3coach/the-blockchain-way-of-programming-newsletter-edition

The Go modules command will automatically fetch any library you reference within your Go files.

Andrej creates a new directory called: cmd with a subdirectory tbb:

mkdir -p ./cmd/tbb

Inside he creates a main.go file, serving as the program's CLI entry point:

package main import ( "github.com/spf13/cobra" "os" "fmt" ) func main() { var tbbCmd = &cobra.Command{ Use: "tbb", Short: "The Blockchain Bar CLI", Run: func(cmd *cobra.Command, args []string) { }, } err := tbbCmd.Execute() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } 

The Go programs are compiled using the install cmd:

go install ./cmd/tbb/...

go: finding github.com/spf13/cobra v1.0.0 go: downloading github.com/spf13/cobra v1.0.0 go: extracting github.com/spf13/cobra v1.0.0

Go will detect missing libraries and automatically fetch them before compiling the program. Depending on your $GOPATH the resulting program will be saved in the $GOPATH/bin folder.

echo $GOPATH

/home/web3coach/go

which tbb

/home/web3coach/go/bin/tbb

You can run tbb from your terminal now, but it will not do anything because the Run function inside the main.go file is empty.

The first thing Andrej needs is versioning support for his tbb CLI program.

Next to the main.go file, he creates a version.go command:

package main import ( "fmt" "github.com/spf13/cobra" ) const Major = "0" const Minor = "1" const Fix = "0" const Verbal = "TX Add && Balances List" var versionCmd = &cobra.Command{ Use: "version", Short: "Describes version.", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Version: %s.%s.%s-beta %s", Major, Minor, Fix, Verbal) }, } 

Compiles and runs it:

go install ./cmd/tbb/...

tbb version

Version: 0.1.0-beta TX Add && Balances List

Perfect.

Identically to the version.go file, he creates a balances.go file:

func balancesCmd() *cobra.Command { var balancesCmd = &cobra.Command{ Use: "balances", Short: "Interact with balances (list...).", PreRunE: func(cmd *cobra.Command, args []string) error { return incorrectUsageErr() }, Run: func(cmd *cobra.Command, args []string) { }, } balancesCmd.AddCommand(balancesListCmd) return balancesCmd } 

The balances command will be responsible for loading the latest DB State and printing it to the standard output:

var balancesListCmd = &cobra.Command{ Use: "list", Short: "Lists all balances.", Run: func(cmd *cobra.Command, args []string) { state, err := database.NewStateFromDisk() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer state.Close() fmt.Println("Accounts balances:") fmt.Println("__________________") fmt.Println("") for account, balance := range state.Balances { fmt.Println(fmt.Sprintf("%s: %d", account, balance)) } }, } 

Andrej verifies if the cmd works as expected. It should print the exact balances defined in the Genesis file because the tx.db file is still empty.

go install ./cmd/tbb/...

tbb balances list

Accounts balances: __________________ andrej: 1000000 

Works well! Now he only needs a cmd for recording the bar's activity.

Andrej creates ./cmd/tbb/tx.go cmd:

func txCmd() *cobra.Command { var txsCmd = &cobra.Command{ Use: "tx", Short: "Interact with txs (add...).", PreRunE: func(cmd *cobra.Command, args []string) error { return incorrectUsageErr() }, Run: func(cmd *cobra.Command, args []string) { }, } txsCmd.AddCommand(txAddCmd()) return txsCmd } 

The tbb tx add cmd uses State.Add(tx) function for persisting the bar's events into the file system:

func txAddCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "add", Short: "Adds new TX to database.", Run: func(cmd *cobra.Command, args []string) { from, _ := cmd.Flags().GetString(flagFrom) to, _ := cmd.Flags().GetString(flagTo) value, _ := cmd.Flags().GetUint(flagValue) fromAcc := database.NewAccount(from) toAcc := database.NewAccount(to) tx := database.NewTx(fromAcc, toAcc, value, "") state, err := database.NewStateFromDisk() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } // defer means, at the end of this function execution, // execute the following statement (close DB file with all TXs) defer state.Close() // Add the TX to an in-memory array (pool) err = state.Add(tx) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } // Flush the mempool TXs to disk err = state.Persist() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Println("TX successfully added to the ledger.") }, } 

The tbb tx add cmd has 3 mandatory flags: --from, --to and --value.

cmd.Flags().String(flagFrom, "", "From what account to send tokens") cmd.MarkFlagRequired(flagFrom) cmd.Flags().String(flagTo, "", "To what account to send tokens") cmd.MarkFlagRequired(flagTo) cmd.Flags().Uint(flagValue, 0, "How many tokens to send") cmd.MarkFlagRequired(flagValue) return cmd 

The CLI is done!

Andrej migrates all transactions from paper to his new DB:

tbb tx add --from=andrej --to=andrej --value=3

tbb tx add --from=andrej --to=andrej --value=700

tbb tx add --from=babayaga --to=andrej --value=2000

tbb tx add --from=andrej --to=andrej --value=100 --data=reward

tbb tx add --from=babayaga --to=andrej --value=1

Read all TXs from disk and calculate the latest state:

tbb balances list

Accounts balances: __________________ andrej: 998801 babayaga: 1999 

Bar data successfully restored! Phew, what a night!

About the Cobra CLI library

The good thing about the Cobra lib for CLI programming is the additional features it comes with. For example, you can now run: tbb help cmd and it will print out all TBB registered sub-commands with instructions on how to use them.

 tbb help The Blockchain Bar CLI Usage: tbb [flags] tbb [command] Available Commands: balances Interact with balances (list...). help Help about any command tx Interact with txs (add...). version Describes version. Flags: -h, --help help for tbb Use "tbb [command] --help" for more information about a command. 

?Fun Facts

At miste kunders data ved et uheld er en standardlørdag i erhvervslivet i disse dage. Blockchain løser dette ved at decentralisere datalagringen. Tricket, som Andrej bakte ind i programmet, ved at springe over balancebekræftelse for TX'er markeret som belønninger. Bitcoin og Ethereum fungerer på samme måde. Saldoen på kontoen, der minede en blok, stiger ud af det blå som et emne for den samlede tokensforsyningsinflation, der påvirker hele kæden. Den samlede levering af bitcoins er begrænset til 21M BTC. Du lærer mere om "minedrift" og "blokke" i kapitel 7 og 10. Komponenterne State og Mempooler ikke unikke for dette program. Andrej valgte navnene og designene til at matche en forenklet go-Ethereum-model, så du får et kig ind i kernen i Ethereum-kildekoden.

? Resumé

Blockchain er en database.

Tokenforsyningen, indledende brugerbalancer og globale blockchain-indstillinger er defineret i en Genesis-fil.

Genesis-saldoserne angiver, hvad den oprindelige blockchain-tilstand var, og opdateres aldrig bagefter.

Databasestatusændringerne kaldes Transaktioner (TX).

Transaktioner er gammeldags begivenheder, der repræsenterer handlinger inden for systemet.

⚒ Studiekode

Forpligtelse: 5d4b0b

Lad os tale om grådighed.

04 | Mennesker er grådige

git checkout c4_caesar_transfer

Typisk forretningsgrådighed

Onsdag den 27. marts.

BabaYaga investerede lidt for meget. Hun glemte, at hendes faste leje var lige rundt om hjørnet, og hun har ikke pengene. BabaYaga kalder sin lejlighedsejer, Caesar.

BabaYaga: Hey Caesar, I am sorry, but I don't have the cash to pay you the rent this month…

Caesar: Why not?

BabaYaga: The Blockchain Bar ICO offered a massive bonus, and I purchased 2000€ worth of tokens for just 1000€. It was a great deal!

Caesar: What the heck are you talking about? What is an ICO? What on earth are tokens? Can you pay me in some other way?

BabaYaga: Oh, not again. I can give you 1000 TBB tokens worth 1000€, and you can use them in the bar to pay for your drinks! Let me call the bar owner, Andrej, and make the transfer!

Caesar: All right... I will take it.

Andrej performs the transfer, but decides to charge an extra 50 TBB tokens for his troubles. He doesn't want to, BUT the bar shareholders who invested in him a few years ago are forcing him to generate profit as soon as possible.

BabaYaga won't notice this relatively small fee most likely anyway, Andrej tells himself. In the end, only he has the DB access.

// Rent payment

tbb tx add --from=babayaga --to=caesar --value=1000

// hidden fee charge

tbb tx add --from=babayaga --to=andrej --value=50

// new reward for another day of maintaining the DB

tbb tx add --from=andrej --to=andrej --value=100 --data=reward

?Fun Facts

Den mest anvendte case-blockchain er bankvirksomhed. Mange blockchain-projekter sigter mod at optimere den indenlandske og internationale udveksling af penge på tværs af forskellige valutakorridorer (XRP). Andre projekter fokuserer på frihed og selvsuveræn identitet (SSI) - en digital bevægelse, der anerkender et individ, skal eje og kontrollere deres identitet og penge uden de intervenerende administrative myndigheder eller andre centraliserede formidlere. SSI giver folk mulighed for at interagere i den digitale verden med samme frihed og kapacitet til tillid som de gør i offlineverdenen. (Bitcoin / Ethereum) Her er nogle sjove fakta, hvorfor blockchain passer perfekt til at erstatte din banks nuværende bankinfrastruktur. Den gode ting ved virtuelle tokens er deres svaghed - dvs. deres evne til at blive handlet, hvor hver enhed er lige så anvendelig som Næste.Udførelse af en overførsel fra konto til konto kan ske ved blot at ændre databasetilstanden. Cryptovalutaer kan handles døgnet rundt. Du kan ikke handle aktier direkte. Du skal gennem en mægler, der deltager i en procentdel af den samlede transaktion som et gebyr (1-3% til 7% gennemsnitlig årlig fortjeneste). En international bankoverførsel tager mellem 3-10 hverdage og kan koste så meget 5% af den overførte værdi! Hvis du sender $ 10.000, skal du muligvis betale op til $ 500. Teknologien bag de sidste 40 år? FTP + CSV-filer. Tror du, at aktiemarkedet er retfærdigt? Banker, indekser og aktier er stærkt centraliseret og kontrolleret af regeringer og private Wall Street-grupper. Frit marked? Wall Street styrer, hvor meget priser kan hoppe / falde på en enkelt dag. Som et eksempel stoppede Wall Street handlen med "S&P 500 Index"efter et fald på 7% for at beskytte deres investorer og hedgefonde mod at miste penge fra folk, der sælger deres aktier i marts 2020 efter COVID-nyheder. Derefter trykte FED billioner dollars for sig selv for at understøtte aktiekursen. Hvis du er en udvikler, der kan lide at spare penge og undgå gæld, har dine besparelser bare mistet værdien natten over med en endnu ukendt procentdel. Mange lande går ind i negative udbytter, et uudforsket område med ukendte konsekvenser. Hvad betyder det? Snart bliver du nødt til at betale banken for at beholde dine opsparinger. Inflation på sit bedste. Du bliver tvunget til at bruge dine penge til at understøtte et system, du ikke kontrollerer.FED trykte billioner af dollars til sig selv for at understøtte aktiekursen. Hvis du er en udvikler, der kan lide at spare penge og undgå gæld, har dine besparelser bare mistet værdien natten over med en endnu ukendt procentdel. Mange lande går ind i negative udbytter, et uudforsket område med ukendte konsekvenser. Hvad betyder det? Snart bliver du nødt til at betale banken for at beholde dine opsparinger. Inflation på sit bedste. Du bliver tvunget til at bruge dine penge til at understøtte et system, du ikke kontrollerer.FED trykte billioner af dollars til sig selv for at understøtte aktiekursen. Hvis du er en udvikler, der kan lide at spare penge og undgå gæld, har dine besparelser bare mistet værdien natten over med en endnu ukendt procentdel. Mange lande går ind i negative udbytter, et uudforsket område med ukendte konsekvenser. Hvad betyder det? Snart bliver du nødt til at betale banken for at beholde dine opsparinger. Inflation på sit bedste. Du bliver tvunget til at bruge dine penge til at understøtte et system, du ikke kontrollerer.Du bliver tvunget til at bruge dine penge til at understøtte et system, du ikke kontrollerer.Du bliver tvunget til at bruge dine penge til at understøtte et system, du ikke kontrollerer.

⚒ Study Code

Commit: 00d6ed

05 | Why We Need Blockchain

git checkout c5_broken_trust

BabaYaga Seeks Justice

Thursday, March 28.

BabaYaga enters the bar for her birthday.

BabaYaga: Hey, Andrej! Today is my birthday! Get me your most expensive bottle!

Andrej: Happy birthday! Here you go: Crystal Head Vodka. But you need to purchase one additional TBB token. The bottle costs 950 tokens, and your balance is 949.

BabaYaga: What?! My balance is supposed to be 999 TBB!

Andrej: The funds transfer to Caesar you requested last week cost you 50 tokens.

BabaYaga: This is unacceptable! I would never agree to such a high fee. You can't do this, Andrej. I trusted your system, but you are as unreliable as every other business owner. Things must change!

Andrej: All right, look. You are my most loyal customer, and I didn't want to charge you, but my shareholders forced me.

Let me re-program my system and make it completely transparent and decentralized. After all, if everyone were able to interact with the bar without going through me, it would significantly improve the bar's efficiency and balance the level of trust!

  • Ordering drinks would take seconds instead of minutes
  • The customers who forgot their wallets at home could borrow or lend tokens to each other
  • I wouldn't have to worry about losing the clients data (again) as everyone would have a copy of it
  • The database would be immutable, so once everyone would agree on a specific state, no one else can change it or maliciously modify the history. Immutability would help with yearly tax audits as well!
  • If shareholders wanted to introduce new fees or raise the current ones, everyone involved in the blockchain system would notice and have to agree with it. The users and business owners would even have to engage in some decentralized governance system together, based on voting, probably. In case of a disagreement, the users walk away with all their data!

BabaYaga: Well, it certainly sounds good, but is this even possible?

Andrej: Yes, I think so. With a bit of hashing, linked lists, immutable data structure, distributed replication, and asymmetric cryptography!

BabaYaga: Jeg aner ikke hvad du lige har sagt, men gå og gør din nørdede ting, Andrej!

?Sjove fakta

Bitcoin- og Ethereum-minearbejdere modtager også belønninger hvert ~ 15. minut for at køre blockchain-serverne (noder) og validere transaktioner. Hvert 15. minut modtager en Bitcoin-minearbejder 12,5 BTC ($ 100k i øjeblikket for at skrive denne side) for at dække sine serveromkostninger + tjene noget overskud. Bitcoin-netværket bruger lige så meget elektricitet som hele Østrigs land. Det tegner sig for 0,29% af verdens årlige elforbrug og forbruger hvert år 76,84 TWh og producerer 36,50 Mt CO2-kulstofaftryk (New Zealand). Kilde. Hvorfor? Du lærer mere senere (i kapitel 11), hvor du programmerer en Bitcoin-minealgoritme fra bunden! PS: Vores algoritme bruger lidt mindre elektricitet :)

? Resumé

Closed software with centralized access to private data allows for just a handful of people to have a lot of power. Users don’t have a choice, and shareholders are in business to make money.

Blockchain developers aim to develop protocols where applications' entrepreneurs and users synergize in a transparent, auditable relationship. Specifications of the blockchain system should be well-defined from the beginning and only change if its users support it.

Blockchain is a database. The token supply, initial user balances, and global blockchain settings are defined in a Genesis file. The Genesis balances indicate what was the original blockchain state and are never updated afterwards.

The database state changes are called Transactions (TX). Transactions are old fashion Events representing actions within the system.

⚒ Study Code

Commit: 642045

06 | L'Hash de Immutable

git checkout c6_immutable_hash

The technical difficulty starts with this section! The concepts will only get more challenging but at the same time, very exciting. Buckle up :)

How to Program an Immutable Database?

Friday, March 29.

If Andrej wants to figure out how to program an immutable DB, he has to realize why other database systems are mutable by design.

He decides to analyze an all-mighty MySQL DB Table:

| id | name | balance | | -- | -------- | ------- | | 1 | Andrej | 998951 | | 2 | BabaYaga | 949 | | 3 | Caesar | 1000 |

In MySQL DB, anyone with access and a good enough reason can perform a table update such as:

UPDATE user_balance SET balance = balance + 100 WHERE id > 1 

Updating values across different rows is possible because the table rows are independent, mutable, and the latest state is not apparent.

Hvad er den seneste DB-ændring? Sidste kolonne ændret? Sidste række indsat? Hvis ja, hvordan kan Andrej vide, hvilken række der blev slettet for nylig? Hvis rækkerne og tabeltilstanden var tæt koblet, afhængig, alias opdatering af række 1 ville generere en helt ny, anden tabel, ville Andrej opnå sin uforanderlighed.

Hvordan kan du se, om nogen byte i en database er ændret?

Uforanderlighed via Hash-funktioner

Hashing er processen med at tage en strenginput med vilkårlig længde og producere en hash-streng med fast længde. Enhver ændring i input vil resultere i en ny, anden hash.

package main import ( "crypto/sha256" "fmt" ) func main()  99896  

Prøv det: //play.golang.org/p/FTPUa7IhOCE

Andrej kræver også et vist sikkerhedsniveau for sin database, så han beslutter sig for en kryptografisk hash-funktion med følgende egenskaber:

  • det er deterministisk - den samme besked resulterer altid i den samme hash
  • it is quick to compute the hash value for any given message
  • it is infeasible to generate a message from its hash value except by trying all possible messages
  • a small change to a message should change the hash value so extensively that the new hash value appears uncorrelated with the old hash value
  • it is infeasible to find two different messages with the same hash value

Implementing the DB Content Hashing

Saturday Evening, March 30.

Andrej modifies the Persist() function to return a new content hash, Snapshot, every time a new transaction is persisted.

type Snapshot [32]byte 

The Snapshot is produced by this new sha256 secure hashing function:

func (s *State) doSnapshot() error { // Re-read the whole file from the first byte _, err := s.dbFile.Seek(0, 0) if err != nil { return err } txsData, err := ioutil.ReadAll(s.dbFile) if err != nil { return err } s.snapshot = sha256.Sum256(txsData) return nil } 

The doSnapshot() is called by the modified Persist() function. When a new transaction is written into the tx.db file, the Persist() hashes the entire file content and returns its 32 bytes "fingerprint" hash.

From this moment, everyone can 100% confidently and securely refer to any particular database state (set of data) with a specific snapshot hash.

⚓Practice time

1/4 Run the tbb balances list cmd and check the balances are matching.

tbb balances list

Account balances at 7d4a360f465d... | id | name | balance | | -- | -------- | ------- | | 1 | Andrej | 999251 | | 2 | BabaYaga | 949 | | 3 | Caesar | 1000 |

2/4 Remove the last 2 rows from ./database/tx.db and check the balances again.

tbb balances list

Account balances at 841770dcd3... | id | name | balance | | -- | -------- | ------- | | 1 | Andrej | 999051 | | 2 | BabaYaga | 949 | | 3 | Caesar | 1000 | 

3/4 Reward Andrej for the last 2 days (from 28th to 30th of March):

Reward Transaction 1:

tbb tx add --from=andrej --to=andrej --value=100 --data=reward

Persisting new TX to disk: {"from":"andrej","to":"andrej","value":100,"data":"reward"} New DB Snapshot: ff2470c7043f5a34169b5dd38921ba6825b03b3facb83e426 TX successfully persisted to the ledger. 

Reward Transaction 2:

tbb tx add --from=andrej --to=andrej --value=100 --data=reward

Persisting new TX to disk: {"from":"andrej","to":"andrej","value":100,"data":"reward"} New DB Snapshot: 7d4a360f468b837b662816bcdc52c1869f99327d53ab4a9ca TX successfully persisted to the ledger. 

4/4 Run the tbb balances list cmd and ensure the balances and the snapshot hash is the same as at the beginning.

tbb balances list

Account balances at 7d4a360f465d... | id | name | balance | | -- | -------- | ------- | | 1 | Andrej | 999251 | | 2 | BabaYaga | 949 | | 3 | Caesar | 1000 | 

Done!

Because the cryptographic hash function sha256 produces the same output (given the same inputs (current tx.db and 2x tbb tx add)), if you follow the exact steps on your own computer, you will generate the exact same database state and hashes!

? Summary

Closed software with centralized access to private data puts only a few people to the position of power. Users don’t have a choice, and shareholders are in business to make money.

Blockchain developers aim to develop protocols where applications' entrepreneurs and users synergize in a transparent, auditable relation. Specifications of the blockchain system should be well defined from the beginning and only change if its users support it.

Blockchain is an immutable database. The token supply, initial user balances, and global blockchain settings you define in a Genesis file. The Genesis balances indicate what was the original blockchain state and are never updated afterwards.

The database state changes are called Transactions (TX). Transactions are old fashion Events representing actions within the system.

The database content is hashed by a secure cryptographic hash function. The blockchain participants use the resulted hash to reference a specific database state.

⚒ Study Code

Commit: b99e51

Next steps

You finished the first few chapters! Congratulations!

█▒▒▒▒▒▒▒▒▒ 10%

Men dette var bare en hurtig opvarmning. Blockchain er en meget udfordrende og omfattende teknologi, og du har brug for en hel bog, der forklarer, hvordan man bygger hele systemet og alle dets komponenter fra bunden - så jeg skrev en.

Du kan fortsætte med at læse i det næste gratis kapitel i min nyhedsbrevsversion af "The Blockchain Way of Programming" e-bog.

07 | Blockchain-programmeringsmodellen

  • Forbedring af ydeevnen for en uforanderlig DB
  • Batch + Hash + sammenkædet liste ⇒ Blokke
  • Migrering fra TX.db til BLOCKS.db

Læring: Du redesigner og omformler din MVP-database til en blockchain-arkitektur.

Fortsæt i vejledningen: //web3.coach#book

Tak for læsningen!