Browse Source

docs(blockchain): add blockchain branch subjects to public

pull/1649/head
jrosendo 1 year ago committed by José Rosendo
parent
commit
7a960f7d00
  1. 17
      subjects/blockchain/README.md
  2. 13
      subjects/blockchain/artists-do-work/README.md
  3. 20
      subjects/blockchain/basic-swap/README.md
  4. 37
      subjects/blockchain/basic-wallet/README.md
  5. 15
      subjects/blockchain/buy-tickets/README.md
  6. 31
      subjects/blockchain/check-document/README.md
  7. 28
      subjects/blockchain/connect-to-metamask/README.md
  8. 111
      subjects/blockchain/decentralised-finance/README.md
  9. 99
      subjects/blockchain/decentralised-finance/audit/README.md
  10. 29
      subjects/blockchain/donation/README.md
  11. 15
      subjects/blockchain/eventful-token/README.md
  12. 116
      subjects/blockchain/exploring-blockchains/README.md
  13. 63
      subjects/blockchain/exploring-blockchains/audit/README.md
  14. 16
      subjects/blockchain/fun-and-profit/README.md
  15. 41
      subjects/blockchain/generate-address/README.md
  16. 25
      subjects/blockchain/get-account/README.md
  17. 23
      subjects/blockchain/hash-160/README.md
  18. 25
      subjects/blockchain/hash-file/README.md
  19. 21
      subjects/blockchain/increment/README.md
  20. 17
      subjects/blockchain/lineup/README.md
  21. 39
      subjects/blockchain/local-node-info/README.md
  22. BIN
      subjects/blockchain/local-node-info/networkInfo.png
  23. 37
      subjects/blockchain/local-node/README.md
  24. 26
      subjects/blockchain/minimal-token/README.md
  25. 46
      subjects/blockchain/named-festival/README.md
  26. 94
      subjects/blockchain/nft-marketplace/README.md
  27. 59
      subjects/blockchain/nft-marketplace/audit/README.md
  28. 132
      subjects/blockchain/non-fungible-cats/README.md
  29. 143
      subjects/blockchain/non-fungible-cats/audit/README.md
  30. 19
      subjects/blockchain/organized-festival/README.md
  31. 144
      subjects/blockchain/payment-channel/README.md
  32. 71
      subjects/blockchain/payment-channel/audit/README.md
  33. 22
      subjects/blockchain/random-wallet/README.md
  34. BIN
      subjects/blockchain/random-wallet/baseWallet.png
  35. 24
      subjects/blockchain/read-secret/README.md
  36. 16
      subjects/blockchain/register-with-events/README.md
  37. 28
      subjects/blockchain/register/README.md
  38. 19
      subjects/blockchain/retrieve-block-date/README.md
  39. 47
      subjects/blockchain/retrieve-transaction-in-out/README.md
  40. 33
      subjects/blockchain/retrieve-transaction-value/README.md
  41. 25
      subjects/blockchain/semi-brute/README.md
  42. 26
      subjects/blockchain/send-eth-transaction/README.md
  43. 25
      subjects/blockchain/send-hash/README.md
  44. 40
      subjects/blockchain/send-transaction-to-peer/README.md
  45. 38
      subjects/blockchain/send-transaction/README.md
  46. 21
      subjects/blockchain/sent-ether/README.md
  47. 85
      subjects/blockchain/sign-service/README.md
  48. 35
      subjects/blockchain/sign-service/audit/README.md
  49. 27
      subjects/blockchain/signer/README.md
  50. 17
      subjects/blockchain/time-and-place/README.md
  51. 19
      subjects/blockchain/time-is-money/README.md
  52. 17
      subjects/blockchain/tip/README.md
  53. 21
      subjects/blockchain/token-sale/README.md
  54. 34
      subjects/blockchain/tracking-network/README.md
  55. 23
      subjects/blockchain/tracking-network/audit/README.md
  56. 36
      subjects/blockchain/transfers-history/README.md
  57. 15
      subjects/blockchain/usable-token/README.md

17
subjects/blockchain/README.md

@ -0,0 +1,17 @@
# Blockchain
### **Content**
Those subjects are progressive in difficulty, designed to learn the fundamental of blockchains as well as the main technologies and tools used in the industry.
- Quest 1: Experiment basic Bitcoin transactions
- Quest 2: Learn fundamental cryptography
- Quest 3: Create a complete Smart Contract
- Quest 4: Scripted interactions with the Ethereum blockchain
- Quest 5: Create a complete decentralised application
- Raid 1: Create a signing service
- Quest 6: Create a first token
- Quest 7: An NFT based DApp
- Quest 8: Learn the basics of DeFi and security
- Quest 9: Explore other blockchains
- Raid 2: Create a tracking service

13
subjects/blockchain/artists-do-work/README.md

@ -0,0 +1,13 @@
# Artists Do Work
Artists deserve to be payed too! Along the way, we will learn payments and divisions in Solidity
### Instructions
- Create a Smart Contract `ArtistsDoWork` with a function `buyTicket()` that takes no parameters and allows a user to buy a ticket paying 0.1 ether or more.
- Add the `addRemuneratedArtist()` function that takes as parameters an `address` to register an artist in the festival. Only the organizer that deployed the Smart Contract can trigger that function
- Add a function `getPayed()` that takes no parameters and that allows an artist, registered with the function above, to receive 1 Ether **once**, providing that there are enough funds in the Smart Contract!
### Notions
- [solidity docs](https://docs.soliditylang.org/)

20
subjects/blockchain/basic-swap/README.md

@ -0,0 +1,20 @@
# Basic Swap
We will create a basic swap smart contract that will allow two users, Alice and Bob, to exchange two minimal tokens safely. The contracts will be specific to the two users and unidirectional.
### Instructions
- Create a `usableToken` contract as defined before
- Create a Smart Contract `BasicSwap` with a constructor that takes the address of two Externally Owned Accounts.
- Create a function `swap(tokenA, AmountA, TokenB, AmountB)` that takes as parameters, two `MinimalTokenAllowance`contracts and amounts
- The function checks that users gave the corresponding allowances to the smart contract
- The function proceed to transfert the first amount in TokenA from Alice to Bob and the second amount from Bob to Alice
To test your smart contract, you will need to deploy two instances of `MinimalTokenAllowance`
### Resources
- [solidity docs](https://docs.soliditylang.org/)
- [learn X in Y](https://learnxinyminutes.com/docs/solidity/)
- [Remix IDE](https://remix.ethereum.org)
- [hardhat](https://hardhat.org)

37
subjects/blockchain/basic-wallet/README.md

@ -0,0 +1,37 @@
# Basic Wallet
_- Do you always look at it encoded ?_
_- Well you have to, the image translators work for the construct program, but there is way too much information to decode the Matrix_
### Instructions
- Create a function `generateAddress()` that generates a cryptographic key pair on any elliptic curve and stores locally the private key in a `wallet.pem` file and returns the hash of the public key (`spki/der`) prepended with '01'
- Create a function `createTransaction(amount, recipient)` that takes as arguments an integer and a string. It returns a string with the following format:
`sender + recipient + hexAmount + signature`
- `sender` is the hash of the public key (`spki/der`) of the current user prepended with '01'
- `recipient` is the recipient taken as parameter
- `amount` is the amount taken as parameter in hexadecimal form
- `signature` is a digital signature of the first three fields, using the private key stored in `wallet.pem`
### Usage
```js
let address = generateAddress();
console.log(address);
// 01ae9596973b45d10e6a65c7fdcc593f63283bd405539c77e83938750d29729fac
let transaction = createTransaction(
200,
"01ffa17f4e0bbb2f049f5d1f9d4ab9fad967e6b0ed9a8fc94563d0b4e47b62e169"
);
console.log(transaction);
// 01ae9596973b45d10e6a65c7fdcc593f63283bd405539c77e83938750d29729fac01ffa17f4e0bbb2f049f5d1f9d4ab9fad967e6b0ed9a8fc94563d0b4e47b62e1692003045022017cdeb0e982e0705044caeb73db8d86992282f466c8b124cff0bfef64ae8be72022100ec4c6025d83a726bb483ebd05e53da37de28eaeb5db85068e355974c3caffaa4
```
### Notions
- [Node.js _crypto_ sign](https://nodejs.org/docs/latest-v14.x/api/crypto.html#crypto_class_sign)
- [Node.js _fs_ writeFileSync](https://nodejs.org/docs/latest-v14.x/api/fs.html#fs_fs_writefilesync_file_data_options)
- [Node.js _fs_ readFileSync](https://nodejs.org/docs/latest-v14.x/api/fs.html#fs_fs_readfilesync_path_options)

15
subjects/blockchain/buy-tickets/README.md

@ -0,0 +1,15 @@
# Festival Buy Ticket
A core functionality of your smart contract is the ability to sell tickets. You will sell them for 0.1 Ethers. An Ethereum address could own several tickets.
You learn to take into account the value field of a transaction.
### Instructions
- Create a new Smart Contract `BuyTickets`.
- Add a function `buyTicket()` that takes no parameters and that allows a user to buy one ticket for 0.1 Ethers. If a user pays more than 0.1 the excess is kept.
- Add a function `ticketsOf()` that takes as parameter an ethereum address and returns the number of tickets that this address owns.
### Notions
- [solidity docs](https://docs.soliditylang.org/)

31
subjects/blockchain/check-document/README.md

@ -0,0 +1,31 @@
# Check Document
### Instructions
Write a node script that exports the function `checkDocument()` that :
- takes as parameter a transaction id and a string
- connects to a local node (`http://localhost:8545`)
- returns the date, as a unix timestamp, that the document was added to the blockchain if the transaction id and the string match and returns 0 otherwise
```js
function checkDocument(text, txID) {
//...
}
module.exports = checkDocument;
```
### Usage
```js
checkDocument(
"Hello world!",
"0x49c8803ea126179502d59707dbcd9e9de15f5d441920936e9ec6fd78dd6468d8"
);
// Expected :
//1611104541
```
### Notions
- [ethers provider](https://docs.ethers.io/v5/api/providers/provider/#Provider--transaction-methods)

28
subjects/blockchain/connect-to-metamask/README.md

@ -0,0 +1,28 @@
# Connect To MetaMask
### Instructions
Create a web page, `connectToMetaMask.html` that :
- Loads an ethereum JavaScript Library. It should be the only JavaScript library.
- Contains a `Connect` button that triggers metamask to ask the user to connect an account.
- Once connected, the page displays :
- the address of the account
- the balance of this account
- Contains a button `Refresh balance` that refreshes the balance.
**Note on vocabulary** :
A **wallet** is an object or a software that contains private keys and allows the user to sign them.
An **account** is, on Ethereum, a particular address with an associated private key.
Most **wallets**, like MetaMask, can manage several **accounts**, often stemming from the same cryptographic **seed**. However, please be aware that some software use interchangeably accounts and wallets.
### Notions
- [ethers : connecting to MetaMask](https://docs.ethers.io/v5/getting-started/#getting-started--connecting)
- [MetaMask : getting started ](https://docs.metamask.io/guide/getting-started.html)
### Relevance
We use a common wallet.

111
subjects/blockchain/decentralised-finance/README.md

@ -0,0 +1,111 @@
# Decentralised Finance
_I accidentally killed it - devops199_
It is time for us to advance beyond basic contracts for integrate with actual DeFi smart contrat. For this we will need to use current standards and implementations.
First, we will create a simple stablecoin, following the ERC20 standart and an oracle. We will then create a decentralised exchange that will allow us to exchange our stablecoin. Finally, we will create the tests for this project.
### **Content**
1. `Stablecoin`
2. `Lending Platform`
3. `Test and Coverage`
### Integration
-> Audited
---
---
# Exercise 1: Stablecoin
The purpose of this exercise is to create a fully collateralised stablecoin. We will use an oracle smart contract to get the current value of any volatile token
### Instructions
First, we need a very basic oracle smart contract.
- Create a smart contract `oracle`
- Add a function getEthPrice() that gives the current value of Ether
- Add a function setEthPrice() that allows the owner of the contract to set the value of Ether
Then, we will create a stablecoin smart contract. It will allow user to mint and burn the stablecoin providing they have the correct amount of collateral.
- Create a `stablecoin` smart contract that inherit from the ERC20 standard
- Add a function `registerOracle` that identifies the oracle smart contract
- Add a payable function `deposit()` that allow the user to deposit Ether to the contract
- Add a `withdraw(amount)` function that allows any user to receive the corresponding value in Ether providing the user has a sufficient position.
- Add a function `mint(amount)` that allow the user to mint the stablecoin for up to half the value deposited in Ether
- add a `burn(amount)` function that allows any user to burn the corresponding value in stablecoin providing the user has a sufficient position.
And, the keystone, we allow any user to punish users that issued more tokens than they should.
- Add a `liquidate(user)` function that allows any user to liquidate the position of any user which current position is below this 1:2 ratio. The liquidator must provide the corresponding value in stablecoin and receives 80% of the outstanding deposit in Ether.
### Resources
- [ERC20 token standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/)
- For inspiration, [MakerDao documentation](https://docs.makerdao.com/)
---
---
# Exercise 2: Lending Platform
We will create a platforms that allow borrowers tokens from lenders in a decentralized manner around a volatile and a stable token. Lenders will earn a fixed yield of 5% per year.
### Instructions
- Create or import an implementation of the ERC20 standard mandatory functions with additionally the `name()` optional function. (you can add other optional functions).
- Create a script and the documentation to deploy instances of this ERC20 implementation:
- `Volatile`
- `Stable`
- `lStable`
- `lVolatile`
- Expand the `oracle` smart contract from the prior exercise:
- Add a function `getPrice()` that gives the current value of `Volatile` in `Stable`
- Add a function `setPrice(uint)` that allow to set the value of `Volatile` in `Stable`
- Create a `LendingPlatform` smart contract with :
- A constructor that takes in parameters the addresses the tokens mentioned above
- A function `registerOracle(address)` that identifies the oracle used
- A function `depositStable(amount)` that allows a lender to deposit the amount in the Stable token. In exchange, the lender will receive the corresponding amount in lStable.
- A function `depositVolatile(amount)` that allows an user to deposit the amount in the Volatile . In exchange, the lender will receive the corresponding amount in lVolatile.
- A function `borrowStable(amount)` that allows a borrower to borrow the amount in the Stable token. It will be required to have more at 150% of its value in volatile token.
- Add a `liquidate(address)` function that allows any user to liquidate the full position of any user which current position is below the 150% threshold. The liquidator needs to provide 110% of the value of the position in the Stable token and will receive the reminder of the value
_Optional provide a web interface for the lending platform_
### Resources
- [ERC20 token standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/)
- For inspiration, [AAVE documentation](https://docs.aave.com/hub/)
---
---
# Exercise 3: Tests and Coverage
To produce adequate tests is the first obvious step to start applying good security measures. We will create the tests for the stablecoin smart contract.
### Instructions
- For each function of the `stablecoin` smart contract, create two tests, one that handles the failure of the function and one that handles the success of the function. You can use any testing framework.
- Provide the documentation to run your tests. Once a testing framework is available, the user should be able to launch the tests with one command line.
### Resources
- [Hardhat testing](https://hardhat.org/tutorial/testing-contracts)
- [Foundry test suit](https://book.getfoundry.sh/forge/tests)
---
---

99
subjects/blockchain/decentralised-finance/audit/README.md

@ -0,0 +1,99 @@
#### Exercise 1: Stablecoin
##### Deploy the oracle smart contract
##### Call the setEthPrice() function with value 1000 (1 Eth = $ 1000)
###### Can you trigger the oracle smart contract to set the current price of Ether?
##### Call the getEthPrice() function
###### Do you get the provided value as a return from the getEthPrice() function?
##### Compile and deploy the stablecoin smart contract
###### Does the smart contract compile and deploy?
##### Call the registerOracle() function with the address of the oracle smart contract
##### Call the deposit() function with 1 Ether (in wei)
##### Call the mint() function with 200 and verify your balance in stablecoin
###### Have you received the 200 stablecoins?
##### Call the mint() function with 3000
###### Does the transaction fail?
##### Call the withdraw() function with 1 Ether (in wei)
###### Does the transaction fail?
##### Call the burn() function with 200
###### Does you have now 0 stablecoins again?
##### Mint 500 stablecoins again,
##### Change the value of ETH in the oracle smart contract to 1
##### From a second account, deposit 1 Ether, mint 500 stablecoins, and liquidate the position of the first account
###### Does the liquidation succeed?
---
---
#### Exercise 2: Lending Platform
##### Deploy the oracle smart contract
##### Call the setPrice() function with value 1000 and call the getPrice() function
###### Can you trigger the oracle smart contract to set the price and retrieve the value correctly?
##### Compile and deploy the tokens smart contract following the script provided.
###### Does the smart contracts compile and deploy?
##### Call the registerOracle() function with the address of the oracle smart contract
##### Call the depositStable() function with 200 Stable and verify your balance in lStable
###### Have you received the 200 lStable?
##### With a second user, call depositVolatile with 2'000
###### Have you received the 2'000 lVolatile?
##### Call the borrowStable() function with 200
###### Does the transaction fail?
##### Call the borrowStable() function with 20
###### Did you receive the corresponding Stable amount?
##### Change the value of Volatile in the oracle smart contract to 10
##### From a second account and liquidate the position of the first account
###### Does the liquidation succeed?
---
---
#### Exercise 3: Tests and Coverage
##### Install the test tooling recommended in the documentation
##### run the command provided in the documentation
###### Does the tests execute correctly?
###### Does the tests cover all functions?
###### For each function, are there two tests, one positive and one negative?

29
subjects/blockchain/donation/README.md

@ -0,0 +1,29 @@
# Donation
We will use a new wallet to send t donation
### Instructions
Create a web page, `donation.html` that loads an ethereum library and connects to a local `http://localhost:8545`.
When loaded, the page generates a random wallet. The page should display the address of the wallet inside an element with id `address` and the balance of this address inside an element with id `balance`.
Additionally, the page contains:
- an input field (id:`amount`)
- a button (id:`donate`)
Pressing this button should send the amount inputted to the address `0x837F324FF70AD9AE4B71084c941c23dDF8371d60`.
```html
<input type="number" id="amount" /> <button id="donate">Donate</button>
```
### Hint
You will need to send ETH from the default accounts of the node to your random wallet.
### Notions
- [ethers : wallet](https://docs.ethers.io/v5/api/signer/#Wallet)
- [web3 : accounts](https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html)

15
subjects/blockchain/eventful-token/README.md

@ -0,0 +1,15 @@
# Eventful Token
### Instructions
- Create a Smart Conctract named `eventfulToken`
- Like MinimalToken, its constructor takes as parameter an amount that is given initially to the deployer.
- Create an event `Transfer(address, address, uint)` that returns the address from which the funds where transferred (the variable should be called `sender`), the address of the `recipient` and the `amount` of the transfer. Trigger the event within the transfer function
- Create an event `Minting(address, amount)` that returns the `address` `recipient` to which token were minted and the `amount` of tokens created. Trigger the event when appropriate.
### Notions
- [solidity docs](https://docs.soliditylang.org/)
- [learn X in Y](https://learnxinyminutes.com/docs/solidity/)
- [Remix IDE](https://remix.ethereum.org)
- [hardhat](https://hardhat.org)

116
subjects/blockchain/exploring-blockchains/README.md

@ -0,0 +1,116 @@
# Exploring Blockchains
_If you don't believe it or don't get it, I don't have the time to try to convince you, sorry. — Satoshi Nakamoto_
While we have focused on fundamentals and the two main public blockchains, other alternatives and projects have been build over the years. I can only recommend you to try and test various alternatives. Most reuse the same principles that we have seen in the previous quests.
In this course, we will focus on two solutions provided by the Hyperledger project. The Hyperledger project is an umbrella that regroup vastly different technical solution. The solutions we will explore are both lego sets that allow you to create varied projects
### **Content**
1. `Private Network`
2. `Command Line Wallet`
### Integration
-> Audited
---
---
# Exercise 1: Private Network
Besu in an alternative Ethereum client that is compatible with Ethereum mainnet. It facilitates the deployment of private networks. Will we use the QBFT consensus algorithm, a Proof of Authority Byzantine Fault Tolerant algorithm
### Instructions
- It must be a private network of 4 nodes
- It must use the QBFT consensus algorithm
- Chain id must be set to 2222
- blocktime must be set to 2 seconds
- the napping cats platform must be deployed on the network
- The keys to the owner(s) of the napping cats Platform must be stored in a file called `keys.json`
- A script must be provided to launch the network using the data in the node folders and deploy napping cats
- Documentation must explain how to launch the network and the showcase web interface.
The final project should have the following structure
```console
Network/
├── NodeA
│ └── data
├── NodeB
│ └──data
├── NodeC
│ └── data
├── NodeD
| └──data
├── Contracts
├── Web
├ genesis.json
├ launch.sh
├ README.md
├ keys.json
```
## Ressources
- [Private network explanation](https://ethereum.org/wiki/private-networks)
- [Launch a private network with Besu tutorial](https://besu.hyperledger.org/en/stable/Tutorials/Private-Network/Create-QBFT-Network/)
- [Overview on industrial usage of private network](https://www.sciencedirect.com/science/article/pii/S209672092200029X)
---
---
# Exercise 2: Clillet
The goal of this raid is to create a fully functional command line wallet for a blockchain of your choice. You can choose any of the major alternative blockchains: Solana, Tezos, Poladot, Cosmos... The executable `clillet` must follow and implement the help description below. Our wallet consists of the following subcommands
- `generate` to generate a new wallet
- `import <file>` to import a wallet from a file
- `connect <endpoint>` to connect to an existing blockchain node
- `balance` to list in the main currency and common tokens of the platform
- `send <destination> <amount>` a high level command to send assets over the network.
The documentation must provide an endpoint to connect to a blockchain node of the testnet network with necessary information to create an account to access this endpoint if needed and to retrieve tokens from a faucet.
## Output and functionalities
```console
$ clillet --help
NAME:
clillet - the multicurrency wallet
Copyright 2022-today The authors of clillet
USAGE:
clillet [options] [command] [<arguments>...]
VERSION:
0.0.1
FLAGS:
-h, --help
Prints help information
-V, --version
Prints version information
COMMANDS:
generate Generates a new wallet and prints the mnemonic
import <file> Imports a wallet from a file
export <file> Export the wallet to a file
connect <endpoint> Connect to a blockchain node
balance Get the balance for the current loaded wallet
send <destination> <amount> sends assets to a destination
## Deliverable
The project must provide an executable file that complies with the specifications
```
---
---

63
subjects/blockchain/exploring-blockchains/audit/README.md

@ -0,0 +1,63 @@
#### Exercise 1: Private Network
###### Is a documentation provided?
##### Follow the documentation to launch the script
###### Is the network running?
###### Are there 4 nodes running?
###### Is the network using the QBFT consensus algorithm?
###### Is the napping Platform deployed?
###### Is the napping cat showcase accessible from a web browser
###### Does your wallet connect properly?
##### Buy cat 0 using the buy button
###### Does the buy function work?
---
---
#### Exercise 2: Clillet
### Preliminary
###### Does the readme file contains a description of the project ?
###### Does the readme file contains information on the endpoint that can be used?
###### Does the readme file contains information to retrieve tokens from a faucet?
##### launch the command with --help
###### Does the display describes the command and 6 subcommands (at least)?
### Functionalities
##### Use the generate subcommand to create a wallet
###### does it display its address and mnemonic phrase?
##### Use the export subcommand to export the current wallet
###### Does it create the appropriate file?
##### Use the connect subcommand, following the instructions in the documentation.
###### Does it connects to a blockchain node?
##### retrieve token from a faucet as instructed in the documentation
##### Launch the balance subcommand
###### Does it display the appropriate balance?
##### Send tokens to a random address using the send function
###### Is the balance appropriately updated?

16
subjects/blockchain/fun-and-profit/README.md

@ -0,0 +1,16 @@
# Fun and Profit
The Festival is going well. Attendees are entering by redeeming tickets and enjoying it. It is now time for the organizer to cash out the benefits.
You will use a Smart Contract to send the benefits in ETH to the organizer.
### Instructions
- Create a new Smart Contract `FunAndProfit` that implements the functions `buyTicket()` and `ticketsOf()` from the prior exercise.
- Add a function `redeemTicket()` that allows an attendee to give return one ticket. The function should fail (revert) if the attendee does not own any ticket.
- Add a function `getBenefits()` that sends all the benefits from the Festival to the organizer.
### Notions
- [unix time](https://en.wikipedia.org/wiki/Unix_time)
- [solidity docs](https://docs.soliditylang.org/)

41
subjects/blockchain/generate-address/README.md

@ -0,0 +1,41 @@
# Generate Address
### Instructions
Create a function `generateAddress()` that generates a pair of cryptographic keys using the elliptic curve `secp256k1`. The return value is an object with members:
- `privateKey`, a private key as a string (`pkcs8/pem` format)
- `publicKey`, the corresponding public key as a string (`spki/pem`)
- `address`, an address to identify this account. The address is the hash `sha256` of the publicKey (in format `spki/der`) prepended with '01'
### Usage
```js
console.log(generateAddress())
// expected result :
{
privateKey: '-----BEGIN PRIVATE KEY-----\n' +
'MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQg6wEoiAc7tEeOfh1HPVMw\n' +
'z/eNG/D30JziVWjq8bW35MChRANCAAQP0WsGc3VmBsXO6Iz+LKxPPWNRb2DqUJKY\n' +
'8Qh7qVvB4rExjUR0DhgUJrTC9tCPy3aiYGbXYLzuXTuOBcPbUiJq\n' +
'-----END PRIVATE KEY-----\n',
publicKey: '-----BEGIN PUBLIC KEY-----\n' +
'MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAED9FrBnN1ZgbFzuiM/iysTz1jUW9g6lCS\n' +
'mPEIe6lbweKxMY1EdA4YFCa0wvbQj8t2omBm12C87l07jgXD21Iiag==\n' +
'-----END PUBLIC KEY-----\n',
address: '01598fbb0e68eaa369d361f7b59157d80a91b2b78de74bc2ff71f6a44b272af368'
}
```
### Relevance
- The `secp256k1` curve is used several blockchains to generate keys.
- An user account is identified using an `address`. The address is computed from the public key using hash functions, splits and concatenations.
- In Bitcoin `hash160` is used in the process and the address starts with '1', '3' or 'bc1'.
- In Ethereum `keccak-256` is used and addresses are appended with 'Ox' that denotes an hexadecimal number.
### Notions
- [Node.js _crypto_ generateKeyPairSync](https://nodejs.org/docs/latest-v14.x/api/crypto.html#crypto_crypto_generatekeypairsync_type_options)
- [Bitcoin invoice address](https://en.bitcoin.it/wiki/Invoice_address)

25
subjects/blockchain/get-account/README.md

@ -0,0 +1,25 @@
# Get Account
Now you will interact with the node's API
### Instructions
For this exercise you will have to create a node script that :
- Loads an ethereum javascript library. I recommend `ethers.js`, `Web3.js` is a common alternative.
- create a function `getAccount()` that connects to a local node (`http://localhost:8545`) and returns the address of the first account available.
- export the function
```js
function getAccount() {
//...
}
module.exports = getAccount;
```
### Notions
- [hardhat](https://hardhat.org)
- [ganache](https://www.trufflesuite.com/ganache)
- [ethers](https://docs.ethers.io/)
- [web3](https://web3js.readthedocs.io/)

23
subjects/blockchain/hash-160/README.md

@ -0,0 +1,23 @@
# Hash160
### Instructions
Create a function `hash160` that takes one argument, expected to be a string, and returns the hash `sha256` of this argument hashed again with the `ripemd160` algorithm. The return value must be in a binary form.
Formally, it could be described as:
```
hash160 = sha256(ripemd160(input))
```
### Usage
```js
let hash = hash160("Ducks");
console.log(hash); // expected result : <Buffer de 5b 73 aa 85 84 02 d8 8c 36 d4 ff 85 29 65 d3 76 ac 6d 19>
```
### Notions
- [Node.js _crypto_](ttps://nodejs.org/docs/latest-v14.x/api/crypto.html)
- [Wikipedia: Hash_function](https://en.wikipedia.org/wiki/Hash_function)

25
subjects/blockchain/hash-file/README.md

@ -0,0 +1,25 @@
# Hash File
### Instructions
Create a function `hashFile(file)` that given the name of a file in the current folder, expected to be a string, returns the hash `sha256` of the content of this file as a string.
### Usage
_textfile.txt_
```
Sometimes science is more art than science.
```
```js
let hash = hashFile("textfile.txt")
console.log(hash)
// expected result : 575e6ccc6aa3882344d97a8ebae4b7fc4852f9149ad14007d11164450f751eb1
```
### Notions
- [Node.js _crypto_ hash](https://nodejs.org/docs/latest-v14.x/api/crypto.html#crypto_class_hash)
- [Node.js _fs_ readFileSync](https://nodejs.org/docs/latest-v14.x/api/fs.html#fs_fs_readfilesync_path_options)
- [Wikipedia: Hash_function](https://en.wikipedia.org/wiki/Hash_function)

21
subjects/blockchain/increment/README.md

@ -0,0 +1,21 @@
# Increment
Cryptographic algorithms use a `binary` representation of variables internally (`Buffer` in nodejs). `Hexadecimal` representation is used to facilitate human reading. To get more familiar with the hexadecimal form, we will do a simple operation.
### Instructions
Create a function `increment` that takes as argument a number written in hexadecimal form and returns the same number incremented by one.
### Usage
```js
increment("03"); // expected : <Buffer 04>
increment("a0"); // expected : <Buffer a1>
increment("ff"); // expected : <Buffer 01 00>
increment("d537"); // expected : <Buffer d5 38>
```
### Notions
- [Node.js buffer](https://nodejs.org/api/buffer.html)
- [Wikipedia: Hexadecimal number](https://en.wikipedia.org/wiki/Hexadecimal)

17
subjects/blockchain/lineup/README.md

@ -0,0 +1,17 @@
# Lineup
For this to be a good festival, you need to register artists. Hip hip hip, arrays!
### Instructions
- Create a new Smart Contract `Lineup`.
- Create a function `addArtist(string)` that takes as parameter a string. Artists are added in their order of registration.
- Create a function`lineup(uint)` that given an index returns the name of corresponding artist.
### Hint
Public variables offer an implicit getter function
### Notions
- [solidity docs: arrays](https://docs.soliditylang.org/en/v0.8.4/types.html#arrays)

39
subjects/blockchain/local-node-info/README.md

@ -0,0 +1,39 @@
# Local Node Info
To start, we will create a simple page that displays basic information from our local node.
### Instructions
Create a web page, `localNodeInfo.html` that loads an ethereum library, connects to a local node at `http://localhost:8545` and displays basic information :
- In an element with (`id`=`chainId`), the number ID of the current network
- In an element with `blockNumber` as `id` the number of blocks in the chain
![image](networkInfo.png)
### Hint
You can use any library such as `ethers.js` or `web3.js` to connect to your local node.
Automated tests check for elements with specific IDs, the design is up to you.
Minimal structure:
```HTML
<!DOCTYPE html>
<body>
<span id="chainId"></span>
<span id="blockNumber"></span>
<script src="XXX"></script>
<script type="module">
// Your code
</script>
</body>
</html>
```
### Notions
- [ethers Provider transaction-methods](https://docs.ethers.io/v5/api/providers/provider/#Provider--network-methods)
- [web3](https://web3js.readthedocs.io/en/v1.3.4/web3-eth.html)

BIN
subjects/blockchain/local-node-info/networkInfo.png

diff.bin_not_shown

After

Width:  |  Height:  |  Size: 9.0 KiB

37
subjects/blockchain/local-node/README.md

@ -0,0 +1,37 @@
# Local Node
An Ethereum node provides different functionalities :
1. To be connected to other nodes and exchange blocks and transactions
2. To verify each transaction by running the Ethereum Virtual Machine
3. To provide an API to interact with the node
4. To provide a basic wallet to sign transactions and collect fees when mining
For now you will simply learn to launch a local node.
### Instructions
Launch a local test node. You can use any client (geth, openEthereum...), but I recommend javascript test nodes `hardhat` and `ganache-cli`.
**hardhat node**
```sh
npm i hardhat
npx hardhat node
```
**ganache**
```
npm i ganache-cli
npx ganache-cli
```
*You can also use ganache ("non cli") that provides a nice graphical interface. For compatibility, change the listening port to 8545 in the settings*
Noticeably, local javascript nodes are not connected to any network and provide already 10 account populated with test ether.
### Notions
- [hardhat](https://hardhat.org)
- [ganache](https://www.trufflesuite.com/ganache)

26
subjects/blockchain/minimal-token/README.md

@ -0,0 +1,26 @@
# Minimal Token
It is now time to create our first token. We will start with a minmal implementation of a token.
### Instructions
- Create a Smart Contract `MinimalToken`
- Create a `constructor` function that takes a positive number as parameter and give an initial balance of tokens to the contract deployer.
- Create a public function `balanceOf(address)` to retrieve the balance of each user given an address
_Hint: You can declare a variable public to have an implicit public getter function of the same name._
- Create a function `transfer(address,uint)` that takes as parameters an address and a positive integer and, providing the sender has sufficient funds, moves the token to the provided address.
### Resources
- [solidity docs](https://docs.soliditylang.org/)
- [learn X in Y](https://learnxinyminutes.com/docs/solidity/)
- [Remix IDE](https://remix.ethereum.org)
- [hardhat](https://hardhat.org)
### Relevance
This is a minimal functionning token.

46
subjects/blockchain/named-festival/README.md

@ -0,0 +1,46 @@
# Named Festival
In this exercise you will create your first smart contract! For a beginner friendly environment, I recommend [remix](https://remix.ethereum.org). It is an online IDE that provides many useful functionalities.
If you want a more complete local dev environment, you can have a look at [hardhat](https://hardhat.org).
### Instructions
- First, you need to specify the licence and the solidity version you will be using. If you have not thought about it, you can use UNLICENSED.
```js
// SPDX-License-Identifier: UNLICENSED
```
- Pragma specifies the version of solidity you will use. The tests are designed to work with version 0.8.4 of solidity.
```js
pragma solidity ^0.8.4;
```
- Then create a Smart Contract named `NamedFestival`.
- Create a public function `setName()` that takes a string as parameter and sets the name of the festival
- Finally a function `getName()` takes no parameters and retrieves the name
#### Expected Functions
```js
contract NamedFestival {
//...
}
function setName(string memory input) public {
//...
}
function getName() public view returns (string memory) {
//...
}
```
### Notions
- [solidity docs](https://docs.soliditylang.org/)
- [learn X in Y](https://learnxinyminutes.com/docs/solidity/)
- [Remix IDE](https://remix.ethereum.org)
- [hardhat](https://hardhat.org)

94
subjects/blockchain/nft-marketplace/README.md

@ -0,0 +1,94 @@
# NFT Marketplace
In this project, we will create a thematic NFT platform that references a genre of NFTs, displays them and allows NFTs trades. By genre of NFT, it can be a visual or thematic category, for instance all NFTs about mediaeval characters, a subcategory of NFTs, for example Profile Pictures (PFP), or more interestingly NFTs used for a particular usage, for instance software licences.
In terms of underlying technology, you will create a website using any web technologies you are familiar with. It will include a server with a database the served webpages and connection to a wallet. We will use NFTs following the ERC721 standard on Ethereum or equivalent.
It is strongly recommended to select a non EVM blockchain and its equivalent standards for this project as long as the same functionalities are offered to the user and a clear guidance is provided on how to launch or connect the blockchain. Potential options include Tezos, Solana, Avalanche…
### Display pages
The following pages display NFTs and information referenced manually by a user of the website.
### Welcome
The NFT marketplace opens with a welcome page that includes a title, a description and visual theme to express the type of NFTs available.
Additionally, the welcome page includes the following elements.
- It features at least two NFTs. One is the NFT sold at the highest price on the platform during the last 24 hours and a second one is available to buy. If no NFT qualify it displays two random NFTs
- A link to the “Explore” web page allows the user to see all the NFTs listed on the platform.
- The “Connect” button that allows more advanced functionalities by connecting a wallet.
### Explore
This page lists all the NFTs available on the platform and can be scrolled by the user. This page must include:
- For each NFT, its image, name and token ID
- Pagination, to load NFT pictures only as the list is scrolled by the user
- A button to the “Submit an NFT” page
- _Bonus : Offer filters of the NFTs available for the convenience of the user_
### Submit an NFT
This simple page allows the user to submit an NFT to add it to the platform. The user must give the address of an ERC721 contract and a token ID. The NFT is now available in the explore page to all users visiting the page. This page also offers the possibility to add several tokens from the same smart contract at the same time by specifying the range of token IDs available.
_Hint. You may use a light database to list all referenced NFTs. For simplicity you can also use an object_
### NFT page
When clicking on an NFT on the _Welcome \_or the \_Explore_ page, a page dedicated to this NFT should be displayed.
This page displays the image, the name of this particular NFT, the token ID, its description, and the current owner. It displays the list of transfers of the NFT
### Functionalities
The connect button allows two categories of functionalities. First it updates the interface to add information to the user about its options. Second, associated with a dedicated smart contract, it allows the user to list and sell the NFT
### Connect
The interfaces should offer to connect a wallet via a button and when interacting with an element that requires an account (such as buying a token).
The connection to a browser extension wallet and to a mobile wallet should be offered.
### Portfolio page
Once connected, a button should be available for the user to display his own portfolio page. The page, reading from listed NFTs and the address of the connected wallet displays all the NFTs owned by the user.
### List & Buy
When the users are on the page of an NFT that they own, or from their portfolio page, they should be able to list the token for sale. Tokens can be sold at a fixed price. They decide an amount of ETH for which the token can be sold. When a token is listed for sale, its potential transfer must be approved by the user to the marketplace’s Smart Contract.
_Bonus: Auction NFTs. Users decide an initial amount and a period of time. At the end of the period, the NFT will be sold to the highest bidder._
A token available for sale exposes a Buy button everywhere the NFT appears on the website. This button requires that a user connects a wallet and allows him to pay the proposed amount. Once the transaction is completed, the token is transferred to the buyer.
### Notions
[https://eips.ethereum.org/EIPS/eip-721](https://eips.ethereum.org/EIPS/eip-721) The NFT base standart
[https://walletconnect.com/](https://walletconnect.com/) The most common library to connect a wallet to a website
[https://tofunft.com/](https://tofunft.com/) an example of marketplace
### Documentation
The project must contain a README file that introduces the project and instructs how to:
- **Compile and deploy the smart contract** on a local blockchain and on a testnet. The instructions must be step by step assuming that no prior tooling is available. E.g.
- **Deploys at least three sample NFTs** and adds two of them to the website’s database. One of the NFTs must be available for sale. Their images might be existing pictures on the internet (wikidata for instance). If you use a testnet, the script can only reference existing NFTs (two directly and one should remain available for the auditor). In any case, the documentation must present the available NFT.
- How to launch the server. It must serves the page on localhost:8080
Ideally, an user would have to do :
- _npm install_
- _npx hardhat node_ (or the equivalent of the blockchain used)
- _npm run deploy_
- _npm run samples_
- _npm run serve_
### _Additional bonuses_
- _Use the graph to find NFTs_
- _Allow to mint directly on the platform_
- _Provide an API_

59
subjects/blockchain/nft-marketplace/audit/README.md

@ -0,0 +1,59 @@
#### NFT Marketplace
### Read the documentation
#### Does the README file contains the instructions to deploy and launch the project
#### Does the smart contract compile correctly following the instructions?
#### Does the documentation explains how to deploy sample NFTs
#### Does the documentation informs you of the remaining available NFT
#### Is the website available at localhost:8080 following the instructions?
### Serve the interface
#### Does the website include a title and a theme?
#### Does the frontpage display two NFTs?
#### Does the frontpage offer a connect wallet button
#### Does the frontpage offers a explore page
#### Does the explore page reference several NFTs?
#### Does the explore page offer a submit an NFT page?
### Submit an NFT using the submit and NFT
#### Does the interface page allow you to submit and NFT (using from the documentation)
#### Is the NFT displayed in the explore page?
### Connect a wallet
#### Does the button connect a wallet allow to connect a browser wallet (e.g. MetaMask)?
#### Once connected, does the interface offer a portfolio page?
### Buy an NFT
#### Does the interface allow you to buy an NFT?
#### Does the portfolio reflect the new NFT ?
### Try to sell the NFT
#### Can you list the NFT for sale?
#### Using another account, can you buy the NFT?
### Bonus
#### Does the explore page offer filters of the NFTs available for the convenience of the user
#### Can you put an NFT for auction by deciding an initial amount and a period of time?
#### Is the NFT attributed at the end of the period?

132
subjects/blockchain/non-fungible-cats/README.md

@ -0,0 +1,132 @@
# Non Fungible Cats
Today's quest objective is to master Non Fungible Tokens, NFTs.
To represent a simple token, we used a smart contract with with each blockchain address amount of tokens. We talk about fungible token because each token has the same value. A Non-Fungible Token is a token with a unique identifier, usually part of a collection. NFTs are used to represent playing cards, works of art, financial securities and even physical objects.
Internally fungible token that we have seen in the prior quest are represented with a mapping from addresses to an amount:
Address ---> Amount
0x2FE34 20
Non-Fungible Tokens are represented with a mapping of unique identifiers to an owner
Identifier ---> Address
123455 0x2FE34
In addition, each token is linked to an Uniform Resource Identifier (URI) where additional information about the NFT can be found, such as metadata, an image...
Identifier ---> Address
123455 0x2FE34
---> URI
bafkreiajlq3
### **Content**
### Mandatory
1. `Napping Cats `
2. `Showcase`
### Optional
3. `Automated Reveal`
---
---
# Exercise 1: Napping Cats
In this exercise we will create a basic NFT smart contract, and use it to instantiate an NFT collection with some custom functions
### Instructions
#### Basic NFT
- Create a smart contract `basicNFT`
- Create a `constructor` function that takes a string that will be used as a name for the NFT.
- Create a public function `ownerOf()` that associate a token to the address of its owner
- Create a public function `TokenURI()` that associate a token to a resource
- Create a function `transfer(uint, address)` that takes as parameters an identifier (a positive integer) and an address to allow the owner of a NFT to transfer it.
_Optionally you can implement or reuse the full ERC721 standard_
#### Napping cats
- Create a smart contract `Napping Cats` that inherits from basicNFT
- Its constructor function takes a new parameter, initial price, that fixes the initial sale price of the NFT collection
- Instantiate the first three cats inside the smart contract with for each a json file (0.json, 1.json, 2.json) that contain a field name and a field image that points to a local or online image. NFTs initially don't have an owner
#### Trading functions
- Add to `Napping Cats` a function `listToken(uint256 id, uint256 price)` that lists the token for sale at the proposed price
- Add to `Napping Cats` a function `buyToken(uint256 id)`, payable, that allows an user to buy a token
- For the initial sale price defined by the constructor for new tokens
- For the listed price by the function listToken
_Optionally, the price for new tokens is an auction. It starts at 100x of the initial sale price or the last paid price for a new token and decreases over time to reach 0 after 24 hours._
### Resources
- [ERC721 standart](https://eips.ethereum.org/EIPS/eip-721)
- [Uniform Ressource Identifier Definition](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier)
---
---
# Exercise 2: Showcase
We will now be able to display our NFT collection on a website and allow user to use the interface to buy and sell tokens.
### Instructions
- Reuse the `Napping Cats` smart contract from the previous exercise
- Create a webpage index.html that connects to the napping Cats smart contract and displays the corresponding URIs as a table
- Add a button to connect a wallet.
- Offer a buy button connected to the buyToken
- _optionally : the buy button display the current price of this specific token_
- Once the wallet is connected, offer a sell token under the tokens owned by the user
- The button should open a modal or include an input field to give a listing price.
- provide a script and a guide to deploy the smart contract and serve the webpage
### Resources
- [ERC721 Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-721/)
- [solidity docs](https://docs.soliditylang.org/)
- [learn X in Y](https://learnxinyminutes.com/docs/solidity/)
- [Remix IDE](https://remix.ethereum.org)
- [hardhat](https://hardhat.org)
---
---
# Exercise 3: Automated Reveal (Optional)
In some auctions, NFT images are only revealed once purchased.
For this we will create a node server that will serve the images only once they are purchased.
### Instructions
- Create a node server file index.js
- Listen on port 3030 and connect to a local node 8545
- Add the nappingCats exercise, modifying tokenURI to match the local node server
- The server is launched with a smart contract address as parameter
- For each request for an image X.jpg, only return it if the token has an owner.
- Optionnally, using IPFS
- The Json file contain the futur hash of tokens on IPFS
- The server periodically monitor the smart contract for new owners
- Once a new owner is found, the image is published on a local or remote IPFS server
### Resources
- [Express documentation](https://expressjs.com/en/4x/api.html)
- [IPFS documentation](https://docs.ipfs.tech/reference/)
- [Pinata documentation (commercial pining serivce)](https://docs.pinata.cloud/pinata-api/pinning-services-api)
---
---

143
subjects/blockchain/non-fungible-cats/audit/README.md

@ -0,0 +1,143 @@
#### Exercise 1: Napping Cats
##### Try to compile the two contracts
###### The contracts compile properly
##### Deploy NappingCats with 10 as its initial price
###### The contract deploys properly
###### TokenURI(0) returns the location of a json file
###### The json files contains the name and the image of the cat
##### buy cat 1 at the listed price (10wei)
###### The buy function functions properly
##### transfer cat 1 to a secondary user
###### The transfer function properly works
##### buy cat 2 at the listed price (10wei)
---
---
#### Exercise 2: Showcase
###### Is there a documentation on how to deploy and serve this project?
##### Use the script and instruction to deploy the smart contract
###### Does the smart contract deploy?
###### Can the webpage be accessed?
###### Does the page display the napping cats ?
###### Does the page offer a button to buy each napping cat?
###### Does the page offer a connect button?
##### Click on the connect button and connect to the wallet
###### Does your wallet connect properly?
##### Buy cat 0 using the buy button
###### Does the buy function work?
###### Does the cat 0 now show the listing button?
##### Try to list cat 0 for 10 wei
###### Did the student explicit the price of each token?
###### Are prices accurate (listed price or moving current price.)
---
---
#### Exercise 3: Automated Reveal (Optional)
##### Try to create a new user and login.
###### +Can you confirm that the user was created?
##### Navigate to the homepage using the user you created. Try to erase products that were not created by the user.
###### +Is it impossible to edit and delete products that were not created by your user?
##### Try to sell a product by creating an add with the user created.
###### +Is it possible to create adds and sell a product using your user?
##### Navigate to the homepage and try to edit the add that you have created.
###### +Is it possible for you to edit your own add?
##### Try to create another new user, login and create at least two new adds.
###### +Can you confirm that the new user and the adds were created?
##### Login in with the first user and check if the adds created by the second user are there.
###### +Can you confirm that the adds created by the second user are present?
##### Navigate to the homepage with a user of your choice and try to delete an add that you have created.
###### +Is it possible for you to delete your own add?
##### Navigate to the homepage with any user and try to check who is selling each product.
###### +Is it possible for you to see who is selling the products without opening the add?
##### Navigate to the homepage and try to find the cart icon.
###### +Can you confirm that the cart icon is present in the homepage?
##### Try to add one item to the cart using the first user.
###### +Can you confirm that the item was added to the cart of the first user?
###### +Did the message "Added to your cart" appear on the screen when you added something to the cart?
###### +Can you confirm that the cart icon in the homepage shows the number "1", meaning that you have one product in the cart?
##### Try to add four more items to the cart.
###### +Can you confirm that all the added items are present in the cart?
###### +Can you confirm that the cart icon in the homepage shows the number "5", meaning that you have five products in the cart?
##### Try to open your cart and check if you can see how much you have to pay for all the products in your cart.
###### +Can you confirm that the cart displays the total of all the products in your cart?
##### Try to open your cart and remove one item from it.
###### +Can you confirm that the product was removed from the cart and the message "Removed from your cart" appeared on the screen?
##### Try to go to the cart and check the total.
###### +Can you confirm that the total was updated accordingly when you removed the item?
###### +Can you confirm that the cart item in the homepage was updated an shows the number "4", meaning that you have four products in the cart?
##### Try to login with the second user and check if the cart is empty.
###### +Can you confirm that the cart is empty, and the cart from the first user was not carried to the second user?
##### Try to logout and add items in the cart without any user. Now after you add items to the cart, login to one user of your choice.
###### +Can you confirm that the items that you added to the cart are present in the user cart?
##### Try to add some items to the cart and then push the button `Empty cart`. After the message appears, confirm that you want to empty the cart.
###### +Did the message "Are you sure?" appeared on the screen for you to confirm the action?
###### +After the confirmation were you redirected to the homepage?

19
subjects/blockchain/organized-festival/README.md

@ -0,0 +1,19 @@
# Organised Festival
In order for your festival to be properly managed, you need to define an organizer. The organizer will be the only user to have the right to modify certain properties. By default, you will define the organizer as the contract's deployer.
### Instructions
- Create a new Smart contract `OrganizedFestival`.
- Add a `constructor` function that takes as parameter a `uint` to represent the date of the festival and a `string` to register its place (Like in `TimeAndPlace`).
- Add functions `getStartTime` and `getPlace` that retrieve the starting time and place.
- Add functions `updateStartTime` and `updatePlace` that update the corresponding value only if the caller of the function is the organizer (which should be the original deployer of the Smart Contract).
### Hint
The constructor function might save the address of the deployer of the contract in an internal variable
### Notions
- [solidity docs: control structures](https://docs.soliditylang.org/en/v0.8.4/control-structures.html)
- [solidity docs: Transaction properties](https://docs.soliditylang.org/en/v0.8.4/units-and-global-variables.html)

144
subjects/blockchain/payment-channel/README.md

@ -0,0 +1,144 @@
# Payment Channel
To overcome the scalability problem, two types of solutions have been devised. On the one hand the state and payment channels (_payment channels _and state channels_) and on the other hand the secondary chains (_sidechains)_ whose units of value are guaranteed by the main network.
Bitcoin offers a network of payment channels, the _lightning network_. On Ethereum there is Raiden, a network of payment channels, µRaiden a micropayments solution, and Counterfactual, a network of state channels. A state channel allows any state to be exchanged, while a payment channel allows only tokens to be exchanged.
The objective of this project is to implement a tool, \_Thunder, \_allowing the creation, usage and monitoring of payment channels. We expect the project to run using a local Ethereum testnet. You can use any other technology providing the same functionalities and extra care in the script and documentation for an easy deployment by the auditor.
### Overall Functionalities
At the high level, this project consists of two executables.
- **thunderd** is the node that will run and communicate with other nodes and the blockchain
- **thunder-cli **is a command line interface that will instruct the node to open channels, pay, and close channels. It provides wallet functionalities.
Once a node is launched, thunder-cli will allow the user:
- First to load a wallet that will be use to move funds and sign transactions
- Connect to another node to exchange information at the network level
- Open a channel with this node
- Pay the other user using the payment channel
- Close the channel and retrieve the funds
As a first stage, we expect the project to work only for one channel between two nodes, each used by a different user. You can expand and give it more flexibility as a bonus. All operations are done one a dedicated ERC20, THD.
+---------------------+
| Blockchain node |
+---------------------+
/ \
/ \ RPC connection
/ \
+------------+ +------------+
| Thunderd A |--connect--| Thunderd B |
+------------+ +------------+
### Smart contract
The **PaymentChannel** contract for a channel between two parts A and B contains:
- An enumeration “StateChannel” of the possible states of the channel: EMPTY, ACTIVE, CLOSING, CLOSED
- The following variables
```solidity
address partA;
address partB;
uint amount;
StateChannel state;
uint closingBlock;
uint Nonce ;
uint balanceA;
uint balanceB;
```
The constructor function that takes the payment channel amount and two payment addresses as parameters and updates the smart contract information.
The fund() function which allows parties A and B to finance the contract up to the amount of the channel. The function updates the status of the channel according to the situation.
The pure function message()returns the message that will be transmitted between the parties and signed . This is the hash of the parameters: nonce, balanceA, balanceB.
The closing function(uint \_nonce, uint \_equilibreA, uint \_equilibreB bytes \_signature) closes the payment channel. It updates the status and value of blocClose. The message must have been signed by the other party to the channel.
The withdraw() function allows funds to be withdrawn for A or B once a period of 24 blocks has passed (about six minutes) after closing of the channel.
The challenge() functions allows the user to challenge a closing by providing a message with a more recent nonce, signed by the other party. It then receives the full amount initially locked in the channel.
### Commands
Here is the help menu and the functionalities that should be expected from the command lines. You may slightly augment his menu with functionalities.
```
$ thunderd --help
Thunder version v0..0.1
Usage: thunderd [options] Start Thunder
Options:
-- help
Print this help message and exit
-- RPC <IP:Port>
Specify the RPC entry point at which a compatible blockchain is available. Otherwise, default is localhost:8545
-- port <port>
Specify the port at which this node is available. Default is 2001
```
```
$ thunder-cli --help
Thunder cli version v0.0.1
Usage: thunder-cli [options] <command> Interact with a thunder node and manage a channel
Options:
-- help
Print this help message and exit
-- port <port>
Specify the port at which a thunder node is available (if not default is used)
Commands
infos: display information about the node (available port, connected node, and the state of the channel)
importwallet <"seedphrase">: Import a wallet using a seed phrase
balance: Shows the balance in your main wallet in THD and the amount available in the channel
connect <ip:port>: connect to another thunder node.
openchannel : create a channel to another connected node.
pay <amount> : pay someone using the open channel
closechannel: Request the closing of the channel. It sends to the smart contract the last receipt
withdraw: retrieve the THD locked in a closed channel after the challenge period
```
### Notions
[https://blog.ethereum.org/2014/07/11/toward-a-12-second-block-time/](https://blog.ethereum.org/2014/07/11/toward-a-12-second-block-time/)
[https://www.jeffcoleman.ca/state-channels/](https://www.jeffcoleman.ca/state-channels/)
[https://github.com/vercel/pkg](https://github.com/vercel/pkg)
### Packaging and documentation
The project must include a base documentation to
- install and launch the executables.
- Launch a local ethereum testnet
- Deploy the THD smart contract and attribute 100 THD tokens to an address specified
The executables can be available by any means (docker, npm, executables…) and must be available for the following platforms:
- A Linux AMD64
- A MacOSX ARM64 and AMD64
- A Windows AMD64
### Bonus
- Import wallets using a keyfile
- Provide the command line interface for the challenge function

71
subjects/blockchain/payment-channel/audit/README.md

@ -0,0 +1,71 @@
#### Payment Channel
### Read the documentation
#### Does the README file contains the instructions to install the project
#### Is the executable available for various platforms?
#### Does the documentation provide explanations on how to
#### Does thunder-cli --help provide informations on the command and its options
#### Does thunder --help provide information on the command and its captions
### Launch a local blockchain testnet , deploy a THD smart contract as specified in the documentation (using for instance a prepopulated address of the local testnet)
#### Is the token deployed on the testnet?
#### Is the address provided correctly credited in THD?
### Launch thunderd on the default port using `thunderd`
#### Is the server launched ?
#### Does `thunder-cli infos` display information about the node?
#### Is thunderd connected to the local testnet?
### import a wallet using `thunder-cli importwallet “seed seed seed…” (using a prepopulated seed phrase from the local testnet for instance).
#### Does the command execute without error?`
#### Does `thunder-cli balance` displays the correct balance ?
### In another terminal, launch another node `thunderd --port 2oo2`
#### Does `thunder-cli --port 2002` display information about this new node?
### Import a second wallet to this secondary node
#### Does the command execute without error?`
#### Does `thunder-cli balance` display the correct balance ?
### Connect the first node to the second one using the `connect` command
#### Does the command execute without error?
#### Does `thunder-cli infos` applied to the first node reflect the connection ?
#### Does `thunder-cli infos` applied to the second node reflect the connection ?
### Open a channel from the first node to the second one with 10 THD
#### Is the channel smart contract deployed on the blockchain?
#### Does `thunder-cli balance` display that 100 THD are available, 10 of which are locked in the channel?
### Pay 5 THD from the first node the user of the second node with `thunder-cli pay 5`
#### Does `thunder-cli balance`on the first node still display that 95 THD are still available, 5 of which are locked in the channel.
#### Does `thunder-cli balance`on the second node reflect that 5THD are now available in this channel?
### As the user of the second channel, close the channel using the `closechannel` command, and wait for the challenge period (potentially creating empty blocks)
#### Can the second user withdraw the funds?
#### Is the balance of the first user correctly updated?
#### Is the balance of the second user correctly updated?

22
subjects/blockchain/random-wallet/README.md

@ -0,0 +1,22 @@
# Random Wallet
You will have to create a simple web-based wallet.
### Instructions
- Create a web page, `randomWallet.html` that loads an ethereum library and connects to a local node `http://localhost:8545`.
- When loaded the page generates a new wallet.
- The address of the wallet is displayed in an HTML element with id `address`.
- The balance of this address is displayed in an HTML element with id `balance`.
- A button, with id `refreshBalance` refreshes the balance.
![image](baseWallet.png)
### Hint
You might need to send Ether from one of the default accounts of your local node to test the wallet. You could use the `send ether` exercise from the prior quest.
### Notions
- [ethers : wallet](https://docs.ethers.io/v5/api/signer/#Wallet)
- [web3 : accounts](https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html)

BIN
subjects/blockchain/random-wallet/baseWallet.png

diff.bin_not_shown

After

Width:  |  Height:  |  Size: 15 KiB

24
subjects/blockchain/read-secret/README.md

@ -0,0 +1,24 @@
# Read a Secret (Optional)
### Instructions
Create a web page, `readSecret.html` that loads an ethereum library, connects to ethereum testnet `kovan` and displays a secret contained in a smart contract.
The smart contract is available at the address `0x27c8dda37a22a29cb78320bf5e1c81ca087b2f8e` on Kovan testnet. It contains one function `getSecret()` that returns a string.
You might use the following interface :
```js
const abi = ["function getSecret() view returns (string)"];
```
### Notions
- [ethers contract](https://docs.ethers.io/v5/api/contract/contract/)
- [Infura](https://infura.io/)
- [Alchemy](https://www.alchemy.com/supernode)
- [web3](https://web3js.readthedocs.io/en/v1.3.4/web3-eth.html)
### Relevance
Reading your first smart contract.

16
subjects/blockchain/register-with-events/README.md

@ -0,0 +1,16 @@
# Register With Events
In order to facilitate the use of your Smart Contract, you will add events.
Events in solidity are used to facilitate the retrieval of information.
### Instructions
Write solidity smart contract `RegisterWithEvents` that provides:
- The functions `addDocument()` and `getDate()` as specified in the prior exercise.
- An event `event DocumentAdded(bytes32, uint)` that triggers when a new document is added to the register
### Notions
- [Events](https://docs.soliditylang.org/en/v0.8.4/contracts.html#events)

28
subjects/blockchain/register/README.md

@ -0,0 +1,28 @@
# Register
To conveniently check for a given string or document, you will create a register smart contract.
### Instructions
Write a solidity smart contract `Register` that provides the following :
- a function `addDocument()` that takes as parameter a hash (bytes32 in solidity)
- a function `getDate()` that takes as parameter a hash and returns the corresponding unix timestamp of the document
```js
contract Register {
function getDate(bytes32 documentHash) public view returns (uint) {
}
function addDocument(bytes32 documentHash) public {
}
}
```
### Hint
You may use block.timestamp to retrieve the current block date and a mapping (see Notions).
### Notions
- [Block information](https://docs.soliditylang.org/en/v0.4.21/units-and-global-variables.html#block-and-transaction-properties)
- [mapping](https://docs.soliditylang.org/en/v0.8.4/types.html#mapping-types)

19
subjects/blockchain/retrieve-block-date/README.md

@ -0,0 +1,19 @@
# Retrieve Block Date
### Instructions
Using Node.js, create and exports a function `retrieveBlockDate()` that takes as input the height of a block and returns the date of this block. The date must be a `date` javascript object. The script must connect to a local node available on `localhost:18443`, with the user `leeloo` and the password `multipass`.
### Usage
```js
retrieveBlockDate(1881467); // Expected : 2020-11-05T20:18:48.000Z
```
### Notions
- [Node.js https module](https://nodejs.org/api/https.html)
- [Async function in Javascript](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Statements/async_function)
- [Exports module](https://nodejs.org/api/modules.html#exports-shortcut)
- [bitcoin core rpc](https://bitcoin.org/en/developer-reference#remote-procedure-calls-rpcs)
- [bitcoin-core js](https://www.npmjs.com/package/bitcoin-core)

47
subjects/blockchain/retrieve-transaction-in-out/README.md

@ -0,0 +1,47 @@
# Retrieve Transaction In and Out
A Bitcoin transaction consists of one or several inputs and one or several outputs. The sum of the inputs is slightly superior to the sum of the output to take into account the fee. One transaction per block, called "coinbase", pays miners and does not have a valid input. For some transactions, outputs might be null too.
This model is referred to as `UTXO` for "Unspent Transaction Outputs", as there is a ongoing list of unspent outputs.
#### A simple transaction
| -> In | Out -> |
| ----- | ------ |
| 0.50 | 0.30 |
| | 0.19 |
_+ 0.01 fee_
### Instructions
Using a local Bitcoin node RPC API, create a function `retrieveTxValue()` that takes as input a hash of a simple transaction, and returns an object with an array of inputs values and an array outputs values in this transaction.
The Bitcoin node RPC interface is expected to be running with the following parameters:
```bash
rpcallowip=127.0.0.1
rpcport=18443
rpcuser=leeloo
rpcpassword=multipass
```
### Usage
```js
txHash = "d030023d96b9170af9ec2fe5d9b62a5eacbcbf144c68f3f45d68bca72d1d3649";
retrieveTxData(txHash);
/* Expected :
{
in: [ 0.18075094 ],
out: [ 0.001, 0.1797493 ]
}
*/
```
### Notions
- [blockcypher API](https://www.blockcypher.com/dev/bitcoin/#blockchain-api)
- [Node.js https module](https://nodejs.org/api/https.html)
- [Node.js axios module](https://github.com/axios/axios)
- [Async function in Javascript](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Statements/async_function)

33
subjects/blockchain/retrieve-transaction-value/README.md

@ -0,0 +1,33 @@
# Retrieve transaction value
### Instructions
Targeting a local bitcoin node, create a function `retrieveTransactionValue()` that takes as input a hash of a simple transaction, and returns the total value transferred in this transaction in bitcoins. If several outputs are sent, the value should be summed up.
The Bitcoin node RPC interface is expected to be running with the following parameters:
```bash
rpcallowip=127.0.0.1
rpcport=18443
rpcuser=leeloo
rpcpassword=multipass
```
### Usage
```js
const { retrieveTxValue } = require("./retrieveTransactionValue.js");
retrieveTxValue(
"d030023d96b9170af9ec2fe5d9b62a5eacbcbf144c68f3f45d68bca72d1d3649"
); // Expected : 50
```
### Hint
Internally, Bitcoin uses satoshis, 1 satoshi = 10^-8 bitcoin
### Notions
- [Node.js https module](https://nodejs.org/api/https.html)
- [Async function in Javascript](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Statements/async_function)
- [satoshi](<https://en.bitcoin.it/wiki/Satoshi_(unit)>)

25
subjects/blockchain/semi-brute/README.md

@ -0,0 +1,25 @@
# Semi Brute
Hash functions are used to secure information. A piece of data, for instance a password, is hashed and only its hash is stored. While there is no way to compute on the original information, one can try every possible value. This is called a brute force attack.
Proof of Work algorithms work in a similar manner. Miners hash a block and modify it continuously to obtain a certain value.
We will create an example of this with a function that finds a string which hash starts with a given value.
### Instructions
Create a function `semiBrute()` that takes as argument a target, which is a two characters hexadecimal number, and returns a string which hash `sha256` starts with the target.
### Usage
```js
solution = semiBrute("e2");
console.log(solution);
// One valid result : 'abcdefghijklmnopqrs'
// You might find other valid solutions as we only check the first two characters
```
### Notions
- [Module crypto: hash](https://nodejs.org/docs/latest-v14.x/api/crypto.html#crypto_class_hash)
- [Password cracking (video)](https://www.youtube.com/watch?v=7U-RbOKanYs)

26
subjects/blockchain/send-eth-transaction/README.md

@ -0,0 +1,26 @@
# Send Eth Transaction
You will create your first transaction on Ethereum using one of its testnets. We recommend Goerli as it is the most commonly used testnet, but you can use any other testnet.
### Instructions
- Create manually a wallet on any **Ethereum testnet**
- Get testnet Ether on a faucet (You might have to try several)
- Send a transaction of 0.000000000000001337 Ethers to the address '0x7A7a4EdC679bC4E29F74E32E9eEDd256cd435FBb'
- Create a js file and store the hash of your transaction in a variable `txid`
### Usage
```js
exports.txid =
"0xf02c4a1487aa2e45fc2c77cb5a28713a1474d86d5f4292b264875ccc5da82b67";
```
### Notions
- A full list of Ethereum compatible wallets [ethereum wallets](https://ethereum.org/en/wallets/find-wallet/)
- The commonly used wallet for development [MetaMask](https://metamask.io/)
- Find a [goerli faucet](https://letmegooglethat.com/?q=goerli+faucet)

25
subjects/blockchain/send-hash/README.md

@ -0,0 +1,25 @@
# Send Hash
In this exercise, you will register the hash of a document on the blockchain.
### Instructions
Write a node script that provides a function `sendHash()` that:
- creates a hash `sha256` of a string provided as parameter
- connects to a local node (`http://localhost:8545`)
- sends a transaction to an address with the hash of the document in the `data` field
```js
function sendHash(text) {
//...
}
module.exports = sendHash;
```
### Notions
- [hardhat](https://hardhat.org)
- [ganache](https://www.trufflesuite.com/ganache)
- [ethers](https://docs.ethers.io/)
- [web3](https://web3js.readthedocs.io/)

40
subjects/blockchain/send-transaction-to-peer/README.md

@ -0,0 +1,40 @@
# Send Transaction to Peer
You will send your first peer-to-peer transaction between two students.
### Instructions
- Create manually an address on **Bitcoin testnet**. You can use bitcoin-cli configured on testnet or any other wallet.
- Get testnet Bitcoin from a faucet (see below).
- Send a transaction of 0.00001337 bitcoins to another student.
- Retrieve the main information from the transaction from a public API or a node (using for instance `bitcoin-cli gettransaction`). You might need to convert some fields depending on the API used. - Transaction hash "txid - Transaction fee "fee" (in Bitcoins, negative integer) - Transaction amount "amount" (in Bitcoins, negative integer) - Transaction date "time"
- Store the
### Expected file
sendTransactionToPeer.js
```js
exports.tx = {
amount: -0.00001337,
fee: -0.00000003,
txid: "95952d9bf7542dfa0c98486495f1ae432a8738bbd7da051915d0aca1bec1f9",
time: 1789670282,
};
```
Congrats for your first real peer to peer Bitcoin transaction!
### Utilities
- A fully open source Bitcoin wallet software [electrum](https://electrum.org/)
In order to use it on the testnet you will need to launch it from the command line with the `--testnet` option
- A full list of Bitcoin compatible wallets [bitcoin wallets](https://bitcoin.org/en/choose-your-wallet)
- A Bitcoin explorer [bitcoin testnet explorer](https://blockstream.info/testnet/)
- A Bitcoin public API documentation [esplora](https://github.com/Blockstream/esplora/blob/master/API.md)
- [faucet 1](https://kuttler.eu/en/bitcoin/btc/faucet/)
- [faucet 2](https://bitcoinfaucet.uo1.net/)
- [faucet 3](https://testnet-faucet.com/btc-testnet/)

38
subjects/blockchain/send-transaction/README.md

@ -0,0 +1,38 @@
# Send Transaction
The purpose of this exercise is to create a simple Bitcoin transaction locally using the command line. As we use new tools this exercise is guided.
### Instructions
- Install a Bitcoin node. There are two solutions :
- Use a preconfigured image for a virtual machine such as [cryptotux](https://cryptotux.org/)
- Install manually by downloading and installing the Bitcoin Core software from [github](https://github.com/bitcoin/bitcoin/releases).
- Launch Bitcoin core daemon on _regtest_ network. You can do so with `bitcoind -regtest -fallbackfee=0.00000003` assuming the executable is in your shell's path.
- Create manually a wallet and two addresses on _Bitcoin regtest_. You may do this by running the following commands
```bash
bitcoin-cli createwallet "testwallet"
bitcoin-cli getnewaddress
bitcoin-cli getnewaddress
```
- Generate 101 blocks to get fresh bitcoins. You need 101 blocks as the Bitcoin you receive from mining are locked for 100 blocks.
You may use the following command `bitcoin-cli -regtest generatetoaddress 101 <your address>`
- Send a transaction of 2 bitcoins to the second address.
- List the last transactions `bitcoin-cli listtransactions`
- Create a js file and exports the hash of your transaction in a variable `txid`.
### Usage
```js
exports.txid =
"be3d0d245e7dce50964ac9157aee7e18a3828e11d89f72ee0bc3f76b526e5bb";
```
Congrats for your first Bitcoin transaction!
### Notions
- A linux image with developer tools [cryptotux.org](https://cryptotux.org/)
- Bitcoin core node [bitcoin.org](https://bitcoin.org/)
- Send to address [reference](https://wbnns.github.io/bitcoin-dev-docs/reference/rpc/sendtoaddress.html)

21
subjects/blockchain/sent-ether/README.md

@ -0,0 +1,21 @@
# Send Ether
In this exercise, you will send ETH using a script.
### Instructions
Write a node script that provides a function `sendEther(amount, address)` which connects to a local node (`http://localhost:8545`) and sends an amount in Ether to the specified address.
```js
function sendEther(amount, address) {
//...
}
module.exports = sendEther
```
### Notions
- [hardhat](https://hardhat.org)
- [ganache](https://www.trufflesuite.com/ganache)
- [ethers](https://docs.ethers.io/)
- [web3](https://web3js.readthedocs.io/)

85
subjects/blockchain/sign-service/README.md

@ -0,0 +1,85 @@
# Sign Service
The goal of this raid is to create a web service that allows users to upload, sign and store the hash of documents on the blockchain and to
### Functionalities
Our signing service consist of three sections.
- Title and short presentation of the service
- Upload a document and connect a wallet
- Actions : sign, publish and verify
**Presentation**
This section introduces the service and redirects to the two other pages
**Connection**
- a button to upload a document to the webpage
- a button `Connect Wallet` to connect an Ethereum wallet. It should handle MetaMask. Optionnaly you could use wallet connet
**Action**
- a button `sign offline` to sign the document offline
- The resulting signature is displayed on the page or in a modal
- a button `publish` to store hash of the transaction on the blockchain
- The transaction is created to add the hash to a smart contract.
- The transaction is signed by the wallet and send
- _Optionally : The document can be stored in the database of your choice_
- a button `verify` to check if a document has been stored previously. - It hashes the document, reads if the smart contract contains it, and displays the data at which the document was added
**Optionally**
- A retrieve section allows to recover a document from its hash. The document must have been stored
### Result
The overall appearance can be basic but it should be clear and easy to use.
Example of interface
```console
==== Introduction ====
This is a signing service
==== Upload and connection ====
[connect wallet]
<Current document> [upload document]
==== Actions ====
[sign] | [publish] | [verify]
<Signature> | <Confirmation> | <Result>
```
<> are displays
[] are buttons
### Structure
The structure of the project is
```console
project
│ README.md
│ package.json
└── server
│ │ index.js
└── interface
│ │ index.html
│ │ style.css
│ └── js
│ | main.js
| | blockchain.js
└── Contracts
│ storage.sol
```
### Scripts and documentation
Package.json must contain following scripts:
- **deploy** that compile and deploy the smart contract with the tooling of your choice on a local blockchain (that must be launched too)
- If the tooling is not available it should instruct the user how to install it
- **serve** that launches the server that serves the page on localhost:3000
- **start** that does all of the above
The project must contain a readme file that introduces the project and instructs how to use i

35
subjects/blockchain/sign-service/audit/README.md

@ -0,0 +1,35 @@
#### Sign Service
### Preliminary
###### Does the package.json contain the scripts to deploy and serve the project
###### Does the readme file contain a description of the project and explains how to run the code from an empty environment?
#### Compile and deploy
##### Does the smart contracts compile properly?
### Interfaces
##### Serve the interface
###### Does the interface include a title, a connect & upload and an action section?
###### Does the interface allows to upload a document?
###### Does the interface allows to connect a wallet
###### Does the action section include a sign, publish and verify button?
### Functionalities
###### Does the sign button trigger the wallet and display a signature of the document
###### Does the publish button trigger the wallet and display a confirmation?
###### Does the verify button display the date of the use of the publish function?
### Bonus
###### +Does the page include a retrieve section that allows to download the document uploaded previously?

27
subjects/blockchain/signer/README.md

@ -0,0 +1,27 @@
# Signer
Elliptic curve cryptography is used in most blockchain projects to sign transactions. Using Node.js base library we will practise simple signatures.
### Instructions
- Create a function `init()` that generates a cryptographic key pair on any elliptic curve and returns the public key in any format.
- Create a function `signer(message)` that takes as arguments a message and returns the signature of the message (using the `sha256` algorithm and the keys generated with init).
- create a function `verifier(message, pubKey, signature)` that takes as arguments a message, a public key and a signature and returns a boolean if the signature is valid.
### Usage
```js
const message = "This is a message to sign";
const pubKey = init();
const signature = signer(message);
console.log(verifier(message, pubKey, signature));
// expected result :
// true
```
### Notions
- [Module crypto, sign](https://nodejs.org/docs/latest-v14.x/api/crypto.html#crypto_class_sign)
- [ECDSA](https://cryptobook.nakov.com/digital-signatures/ecdsa-sign-verify-messages)

17
subjects/blockchain/time-and-place/README.md

@ -0,0 +1,17 @@
# Time and Place
To be considered a festival, you need to initially specify a time and a place. Everything else can be organized later.
You will use a constructor function to set the time and place when the Smart Contract is deployed.
### Instructions
- Create a new Smart Contract `TimeAndPlace`.
- The Smart Contract contains a special `constructor()` function that takes as parameter a `uint`, that is a Unix timestamp representation of the date of the beginning of the festival, and a `string` that is the address of the festival.
- Create a function `getStartTime()` that returns the starting time and date of the festival as a Unix timestamp.
- Create a function `getPlace()` that returns the place of the festival.
### Notions
- [unix time](https://en.wikipedia.org/wiki/Unix_time)
- [solidity docs: constructor](https://docs.soliditylang.org/en/v0.8.4/contracts.html)

19
subjects/blockchain/time-is-money/README.md

@ -0,0 +1,19 @@
# Time is Money
We organize a bit of yield management. Tickets are now 0.01 ether if they are bought up to 10 days before the start of the festival and 0.1 afterward.
Also, in order for payments to go orderly, we decide that artists can get payed only 3 days after the festival. Also, 10 days after the end of the festival, the organizer can get the reminder of the benefits.
### Instructions
- Create a Smart Contract `TimeIsMoney` that takes a uint as a parameter for its `constructor()` function that represents the date of the festival.
- Add a function `buyTicket()` that allows to buy one ticket for a minimum price of 0.01 ethers 10 days before its start, and 0.1 afterward.
- A function `ticketsOf()` that returns the number of tickets owned by that particular address.
- Add a function `addPayedArtist()` that takes as parameters a string and an address to register an artist to the festival.
- Add a function `getPayed()` that allows an artist registered with the function above to receive 1 Ether, three days after the start of the festival.
- Add a function `getBenefits()` that can be triggered only by the organizer 10 days after the start of the festival. It receives the remainder of money from the festival.
### Notions
- [unix time](https://en.wikipedia.org/wiki/Unix_time)
- [solidity docs](https://docs.soliditylang.org/)

17
subjects/blockchain/tip/README.md

@ -0,0 +1,17 @@
# Tip
### Instructions
Create a web page, `tip.html` that contains a `Connect` button that triggers a MetaMask window that asks the user to connect an account. Once connected, it displays the address of the wallet.
Additionally, the page contains:
- an input field (id:`address`)
- a button (id:`tip`)
Pressing on the button send the amount of 0.001701 ETH to the address in the input field.
### Notions
- [ethers : connecting to MetaMask](https://docs.ethers.io/v5/getting-started/#getting-started--connecting)
- [MetaMask : getting started ](https://docs.metamask.io/guide/getting-started.html)

21
subjects/blockchain/token-sale/README.md

@ -0,0 +1,21 @@
# Token Sale
One way to distribute our token is to sell it. We will set a fixed price for each token. The tokens will have to be send to the Smart Contract by their owner initally.
### Instructions
- Create a Smart Contract `TokenSale`
- The contract imports MinimalToken
- Create a `constructor` function that takes as parameter the address of a deployed `MinimalToken` and the price of a token (in wei).
- Create a public payable function `buy()` that sends to the buyer token proportionally to the value send.
- Create a public function `getPrice()` that returns the price of the token.
- Create a public function `collect()` that allows the initial deployer of the contract to collect the proceedings from the sale
### Resources
- [solidity : import"](https://docs.soliditylang.org/en/v0.8.4/layout-of-source-files.html)

34
subjects/blockchain/tracking-network/README.md

@ -0,0 +1,34 @@
# Tracking Network
We will create a network to track postal parcels using Hyperledger Fabric. Hyperledger Fabric is a modular blockchain framework. It revolves around a few key concepts. First, the notion of channel, which represents a network with a set of transactions and participants dedicated to the same business objective. Within a channel a transaction is validated by a set of designated peers. On this channel, Smart Contracts can be deployed as "chaincode" to define business logic that will control validation within this network.
### Instruction
Network:
- Deploy a Hyperledger Fabric networks with one channel "PostalServices", two peers representing different cities ("Nairobi" and "Atlanta") belonging to the same organization and a third node "Singapore" belonging to another organization, an ordering node and two certificate authorities.
Objects:
- Define the following element of our postal network:
- 'Parcels', of type assets, which include a destination (a string), a current address (a string) and a status
- 'Transport' a transaction which allows the address of the parcel to be changed a package
Functionalities:
- Allow the creation of users, postal employees, that can create and modify parcels.
- Enable tracking of the status of the parcel: Good, Damaged or Destroyed. The state is saved in the package and a transaction allows this state to be modified. The transaction verifies that changes are consistent (state can go only one way... )
- Distribution, travel from the sorting center to the final address emits an event “Distribution”
Interface and deliverable
- Provide a README file and necessary script to allow the deployment of the network.
- Provide a command line interface with
- `create-user`, a command to create a user
- `create-parcel` a command to create a parcel
- `transport` a command to modify the address of a parcel
- `change status`that can potentially change its status.
### Resources
-[Hyperledger Fabric documentation](https://hyperledger-fabric.readthedocs.io/) -[Chain code tutorials](https://hyperledger-fabric.readthedocs.io/en/release-2.0/chaincode4ade.html)

23
subjects/blockchain/tracking-network/audit/README.md

@ -0,0 +1,23 @@
#### Tracking Network
###### Is there a documentation provided to launch the network?
##### Try to launch the network
###### Can you confirm that the network was created?
##### Try to create a user
###### Can you confirm that the user was created?
##### create a parcel with a random address
###### Do you have a feedback that the parcel was created?
##### Modify the address of the parcel with the transport command to another random address
###### Was the address of the parcel modified?
##### Modify the status of the package
###### Is the status of the package modified?

36
subjects/blockchain/transfers-history/README.md

@ -0,0 +1,36 @@
# Transfers History
### Instructions
- Create a JavaScript file `transfersHistory.js`that exports the function `transfersHistory(address, address)` that takes as parameters the address of a MinimalTokenEvent Smart Contract instance and the address of an user.
It returns an array with all the transfers from that account, starting from the most recent, positive if it is toward the user, and negative if it is outside.
#### Structure
```js
const { ethers } = require("ethers");
async function transfersHistory(contractAddress, userAddress) {}
exports.transfersHistory = transfersHistory;
```
#### Usage
```js
const { transfersHistory } = require("./transfersHistory.sl.js");
transfersHistory(
"0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc",
"0x70997970c51812dc3a010c7d01b50e0d17dc79c8"
);
/* expected:
[50, -25, 200, 30, -230]
*/
```
### Resources
- [solidity docs](https://docs.soliditylang.org/)
- [ethers](https://learnxinyminutes.com/docs/solidity/)
- [web3 : contracts events](https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#contract-events)

15
subjects/blockchain/usable-token/README.md

@ -0,0 +1,15 @@
# Usable Token
### Instructions
- Create a Smart Contract named `UsableToken`
- Like MinimalToken, its constructor takes as parameter an amount that is given initially to the deployer.
- Create a function `approve(address,uint)` that allows the owner of the token to approve a spender to spend a certain amount of tokens.
- Create a function `allowance(address,uint)` that returns the amount of tokens that a spender can spend on behalf of the owner.
### Notions
- [solidity docs](https://docs.soliditylang.org/)
- [learn X in Y](https://learnxinyminutes.com/docs/solidity/)
- [Remix IDE](https://remix.ethereum.org)
- [hardhat](https://hardhat.org)
Loading…
Cancel
Save