Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Blockchain implementation

notebooks/exercises.livemd

Blockchain implementation

Aliases

alias Blockchain.{
  Block,
  Hash,
  Transaction,
  TransactionIO,
  Utilities,
  Wallet
}

Notes

Note all exercises are currently implemented in this notebook, although all required modules and functions for the initial blockchain are implemented.

Section 3.1: Wallet

Exercise 3-1
wallet = Wallet.new()
Exercise 3-2
IO.inspect(wallet.private_key, label: "private key")
IO.inspect(wallet.public_key, label: "public_key")
Exercise 3-3

Documentation links for the ExCrypto package:

Section 3.2: Block

mined_block =
  Block.make_and_mine_block(
    Hash.new("234"),
    DateTime.utc_now(),
    Transaction.new(Wallet.new(), Wallet.new(), 123, []),
    1
  )
Hash.new("test")

#####

Exercise 3-4
transaction = Transaction.new(Wallet.new(), Wallet.new(), 123, [])

block = %Block{
  current_hash: Hash.new(""),
  previous_hash: Hash.new(""),
  data: transaction,
  timestamp: DateTime.utc_now(),
  nonce: 1
}

Block.calculate_hash(block)
Exercise 3-5
mined_block = Block.make_and_mine_block(block)
Exercise 3-6
IO.inspect(Block.valid?(mined_block), label: "Mined block valid?")

IO.inspect(Block.valid?(%{mined_block | nonce: 1}), label: "Block with nonce=1 valid?")

:ok

Section 3.4: Transactions

IO.inspect(
  TransactionIO.valid?(TransactionIO.new(123, Wallet.new())),
  label: "Valid TransactionIO?"
)

IO.inspect(
  TransactionIO.valid?(%TransactionIO{
    transaction_hash: Hash.new("badhash"),
    value: 123,
    owner: Wallet.new(),
    timestamp: DateTime.utc_now()
  }),
  label: "Valid TransactionIO?"
)

:ok
wallet = Wallet.new()
ExPublicKey.encrypt_private(ExCrypto.Hash.sha256!(["test", "asdf"]), wallet.private_key)
Exercise 3-13
Transaction.new(Wallet.new(), Wallet.new(), 500, [])
|> Transaction.format()