0% found this document useful (0 votes)
3 views37 pages

Lecture 6 - Block

SpartanGold is a simplified blockchain implementation inspired by Bitcoin, designed for educational purposes and rapid prototyping, featuring both single-threaded and multi-process modes. It utilizes an account-based model instead of Bitcoin's UTXO model, and supports proof-of-work mining with unique transaction and block structures. The document outlines key concepts, differences from Bitcoin, and provides guidance on installation and experimentation with SpartanGold.

Uploaded by

sohailyasserr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Lecture 6 - Block

SpartanGold is a simplified blockchain implementation inspired by Bitcoin, designed for educational purposes and rapid prototyping, featuring both single-threaded and multi-process modes. It utilizes an account-based model instead of Bitcoin's UTXO model, and supports proof-of-work mining with unique transaction and block structures. The document outlines key concepts, differences from Bitcoin, and provides guidance on installation and experimentation with SpartanGold.

Uploaded by

sohailyasserr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Blockchain and Cryptocurrencies

Introduction to SpartanGold

Prepared by:
Dr. Hossam Mahmoud Moftah
Faculty of Computers and Artificial Intelligence
Beni-Suef University
What is SpartanGold?
• It is a blockchain implementation written in JavaScript
patterned after Bitcoin.
• Several features of Bitcoin’s design are simplified or
eliminated, though those features may be added in easily.
• SpartanGold supports a single-threaded mode where
miners communicate via JavaScript events, and a multi-
process mode where miners and clients send messages
over TCP/IP.
• While the former mode (single-threaded) simplifies testing
and can provide cleaner demonstrations, the latter mode
(multi-process) provides a more realistic experience.
Prof. Tom Austin (Thomas H. Austin) , San José State University
SpartanGold: A Blockchain for Education, Experimentation, and Rapid Prototyping
April 2021: Communications in Computer and Information Science
DOI: 10.1007/978-3-030-72725-3_9
SpartanGold npm module

• Simplified Bitcoin-like blockchain


• Designed for rapid prototyping
• Currency is called "gold"
• Created by Prof. Tom Austin
• https://github.com/taustin/spartan-gold/

Source: Prof. Tom Austin, San José State University


Node Package Manager (npm)

• npm is the standard package manager for Node.js.


• NPM creates a folder named "node_modules", where
the package will be placed. All packages you install in
the future will be placed in this folder.

https://nodejs.org/
https://www.w3schools.com/
Similarities to Bitcoin

• Proof-of-work (PoW) blockchain


– Miners validate blocks by finding a valid PoW
• Blocks collect transactions
• Mining rewards:
– Coinbase reward: newly minted gold
– Transaction fees

Source: Prof. Tom Austin, San José State University


Key differences from Bitcoin

Bitcoin: SpartanGold:
• Transactions stored in a • Transactions stored in a
Merkle tree map
• Bitcoin script • No scripting language
• UTXO-based model • Account-based model
• Proof-of-work target • Proof-of-work target
adjusts over time fixed
• Fixed block size • No block size limit

Source: Prof. Tom Austin, San José State University


UTXO vs. Account-Based Blockchains

• The UTXO and account-based models represent the


two most popular bookkeeping methods in the
blockchain space.
• The two models represent two fundamentally different
ways on how blockchains process and record
transactions.
• The UTXO model works similarly to cash
transactions, while the account-based model works
similarly to how bank accounts work.

https://www.nervos.org/
How Does the UTXO Model Work?

• UTXOs work similarly to cash, where each UTXO is like a unique fiat paper
bill that users can spend. Each user in UTXO-based blockchains can keep
track of its balance by adding up the cryptocurrencies in their possession.

• For example, assume a guy named Bob goes to a fast-food restaurant


looking to buy a burger that costs $10. However, Bob only has a $20 bill,
meaning that when he pays for the burger, the restaurant must give him a
$10 bill as a change.

• In UTXO-based blockchains, the $20 bill and the $10 change would be
represented as two separate UTXOs. So, in Bob’s case, his cryptocurrency
account balance is just a sum of his UTXOs, just like his physical wallet is
just a sum of all the different bills that he puts into his wallet.

https://www.nervos.org/
How Does the Account-Based Model Work?

• The account-based model is the more popular blockchain bookkeeping


method between the two. Initially popularized by Ethereum, the account
model is used by many, if not most, blockchains today to record both
transactions and state changes.

• The bookkeeping in the account model works just like bank accounts, where
money transfers are recorded as debits and credits on different users'
accounts on the bank's ledger. For example, when Dave wants to send $10 to
Bob, the bank credits or deducts $10 from Dave's account and debits or adds
$10 to Bob's name in its ledger.

https://www.nervos.org/
Running insingle-threaded mode
$ node driver.js
Starting simulation. This may take a moment...
Initial balances:
Alice has 233 gold.
Bob has 99 gold.
Charlie has 67 gold.
Minnie has 400 gold.
Mickey has 300 gold.
Donald has 0 gold.
Alice is transfering 40 gold to zy2sIPBlf9PeM36D/
j0SyTznb8c3ESsDekNlZtSi06s=
Minnie: found proof for block 1: 5660
Minnie: cutting over to new chain.
Mickey: cutting over to new chain.

Source: Prof. Tom Austin, San José State University


Running in multi- process mode
Balances:
hDDXlpBFlnKViXVhbpJbf+tua7F8yMPIYtjJ+8KbWbk=:
675
Funds: 675
Address: hDDXlpBFlnKViXVhbpJbf+tua7F8yMPIYtjJ+8KbWbk=
Pending transactions:

What would you like to do?


*(c)onnect to miner?
*(t)ransfer funds?
*(r)esend pending transactions?
*show (b)alances?
*show blocks for (d)ebugging and exit?
*(s)ave your state?
*e(x)it without saving?

Your choice:
Source: Prof. Tom Austin, San José State University
Lab, part 1:
Experiment with SpartanGold
• Install with:
npm install spartan-gold
• Download singleThreadedExample.js, tcpMiner.js,
minnie.json, and mickey.json from the website.
• Experiment with single-threaded and multi-process mode.

Source: Prof. Tom Austin, San José State University


SpartanGold Design

Source: Prof. Tom Austin, San José State University


Key concepts

• All classes can be extended


• Override methods if you want to change
behavior

Source: Prof. Tom Austin, San José State University


Transaction class fields

• from: Address of the payer


– derived from public key
• nonce: orders transactions from payer
• pubKey
• sig: Signature for the transaction
• fee: Transaction fee paid to miner
• data: Generic JSON object (for extensibility)
• outputs: Discussed next slide…

Source: Prof. Tom Austin, San José State University


Transaction outputs

• One transaction may pay multiple recipients


• The outputs field: array of JSON
objects
– Object keys: { address, amount }
– Address: The recipient
– Amount: Gold given to recipient

Source: Prof. Tom Austin, San José State University


JSON for sample transaction
(parts elided with "…")
{ from:'4HWTOR8cgvejeMd…',
nonce: 0,
pubKey: '-----BEGIN
PUBLIC KEY-----\n' …,
sig:
'83adb439…', fee:
1,
outputs: [
{ amount: 25,
address:
'vAy8w7bavN9…'
}
],
data: {}
} Source: Prof. Tom Austin, San José State University
Transaction methods

• sign(privKey)
• validSignature()
• sufficientFunds(block)
– Pass in most recently confirmed block
– Returns true if client has enough gold for
transaction
• totalOutput()
– Sum of all outputs plus the transaction
fee

Source: Prof. Tom Austin, San José State University


Determining transaction validity

• The from field matches pubKey


• Signature is valid
• The nonce is valid
– Greater than last received nonce
• Payer has enough gold for the transaction

Source: Prof. Tom Austin, San José State University


Block class
• Stores transactions
• Tracks balances

• Contains rules for validating transactions and blocks

Source: Prof. Tom Austin, San José State University


Block class fields
• rewardAddr
– Address of miner for coinbase reward
• prevBlockHash
– First block (genesis) does not have previous block
• target: Maximum accepted PoW value
• proof
• coinbaseReward
• chainLength
• timestamp
• transactions: transaction ID -> transaction
• balances

Source: Prof. Tom Austin, San José State University


Block methods

• isGenesisBlock()
– Genesis block has special rules.
• hasValidProof()
• balanceOf(addr): Gold available for specified client
• totalRewards(): Transaction fees + coinbase reward
• contains(tx): True if transaction is in current block
• addTransaction(tx)
– Overridden in BuggyClient for lab
• serialize(): Converts block to string form
– some fields are omitted
• rerun(prevBlock): Described next slide…

Source: Prof. Tom Austin, San José State University


rerun method

• Clients and miners do not trust other's blocks.


– Exception: The genesis block is trusted.
• The rerun method:
– Resets balances and nonces to match previous
block
– Replays all transactions contained in the
block
• Returns true if all transactions are re-added
successfully

Source: Prof. Tom Austin, San José State University


Client class

• Posts transactions
• Stores public/private keys
• Tracks blocks
– Listens for new blocks
– Verifies block validity
– Requests missing blocks
– Tracks last confirmed block

Source: Prof. Tom Austin, San José State University


When is a block "confirmed"

• In Bitcoin, a block is confirmed:


– After a chain of 6 blocks has been produced
building on this block.
– Takes about an hour in Bitcoin.
• SpartanGold uses the same approach.
• Probabilistic
– could still roll back (though unlikely)

Source: Prof. Tom Austin, San José State University


Client methods

• availableGold: getter for the amount of gold the client


can currently spend
• postTransaction(outputs, fee)
• showAllBalances()
• showBlockchain()
• log(msg)
• receiveBlock(block)
– Invoked on Blockchain.PROOF_FOUND message
– Verifies block's validity
– Stores block
– If better than current block, updates current block

Source: Prof. Tom Austin, San José State University


Miner class

• Extends Client class


• Collects transactions into a block
• Finds proof for a block

Source: Prof. Tom Austin, San José State University


Miner methods

• initialize():
– set up listeners and begin mining
• findProof():
– searches for a valid PoW
• addTransaction(tx):
– Invoked on
Blockchain.POST_TRANSACTION
message

Source: Prof. Tom Austin, San José State University


Blockchain class

• Contains settings for blockchain


• Stores constants
• Makes new blocks or transactions as
appropriate for current blockchain
– Might be Transaction or Block
subclasses
– Helps with SpartanGold's extensibility

Source: Prof. Tom Austin, San José State University


Blockchain static methods

• deserializeBlock(s):
– converts string to instance of Block class
• makeBlock(…):
– Equivalent to new Block(…),
except that appropriate
subclass is above.
• makeTransaction(…):
– Equivalent to new
Transaction(…), except …
• makeGenesis(cfg): next slide…
Source: Prof. Tom Austin, San José State University
makeGenesis

• Configures settings for blockchain


• Takes in JSON configuration
• Mandatory parameters:
– transactionClass: Transaction (sub)class
– blockClass: Block (sub)class

Source: Prof. Tom Austin, San José State University


makeGenesis optional parameters

• Blockchain configuration details:


– powLeadingZeroes
– coinbaseAmount
• Genesis block balances (choose at most one):
– clientBalanceMap: client -> amount Map
– startingBalances: address -> amount JS object
• Client configuration details:
– defaultTxFee
– confirmedDepth

Source: Prof. Tom Austin, San José State University


FakeNet class

• Simulates network connection


• Override to:
– provide more realistic connection
• See this approach in tcpMiner.js
– Simulate different types of behaviors
• Delayed messages
• Dropped messages

Source: Prof. Tom Austin, San José State University


FakeNet methods

• register(…clientList)
– Adds clients to list of known clients
• recognizes(client)
• sendMessage(address, msg,
o)
– address: client to send message to
– msg: name of the event
– o: payload of the message
• broadcast(msg, o)
– Calls sendMessage to all known
clients
Source: Prof. Tom Austin, San José State University
Lab, part 2: Replay attack

Download replayAttack.js and


buggyBlock.js from the website.
Lab, part 3: Explain replay attack

Contrast buggyBlock.js with the overridden methods from


block.js in
https://github.com/taustin/spartan-gold/.

What differences do you notice? Why

did this attack work?


Thank you

You might also like